Skip to content

Commit

Permalink
Merge pull request #127 from ShellUnease/gh-118
Browse files Browse the repository at this point in the history
Fixes #118 - Display user info straightaway if there's no active mach…
  • Loading branch information
qu35t-code authored Apr 23, 2024
2 parents b86b8c9 + 3e5c06a commit df4ffae
Show file tree
Hide file tree
Showing 2 changed files with 124 additions and 113 deletions.
204 changes: 99 additions & 105 deletions cmd/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,144 +223,138 @@ func displayActiveMachine(header string) error {
if err != nil {
return err
}
if machineID == "" {
fmt.Println("No machine is running")
return nil
}
machineType, err := utils.GetMachineType(machineID)
if err != nil {
return err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType))

var expiresTime string
switch {
case machineType == "release":
expiresTime, err = utils.GetReleaseArenaExpiredTime()
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Expires Time: %s", expiresTime))
if err != nil {
return err
}
default:
expiresTime, err = utils.GetActiveExpiredTime()
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Expires Time:: %s", expiresTime))
if err != nil {
return err
}
expiresTime, err := utils.GetExpiredTime(machineType)
if err != nil {
return err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Expires Time: %s", expiresTime))

if machineID != "" {
config.GlobalConfig.Logger.Info("Active machine found !")
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %s", machineID))
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Expires At: %v", expiresTime))
config.GlobalConfig.Logger.Info("Active machine found !")
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %s", machineID))

layout := "2006-01-02 15:04:05"

date, err := time.Parse(layout, expiresTime)
if expiresTime != "Undefined" {
err = checkIfExpiringSoon(expiresTime, machineID)
if err != nil {
return fmt.Errorf("date conversion error: %v", err)
return err
}
}

now := time.Now()
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Actual date: %v", now))

timeLeft := date.Sub(now)
limit := 2 * time.Hour
if timeLeft > 0 && timeLeft <= limit {
var remainingTime string
if date.After(now) {
duration := date.Sub(now)
hours := int(duration.Hours())
minutes := int(duration.Minutes()) % 60
seconds := int(duration.Seconds()) % 60

remainingTime = fmt.Sprintf("%dh %dm %ds", hours, minutes, seconds)

}
// Extend time
isConfirmed := utils.AskConfirmation(fmt.Sprintf("Would you like to extend the active machine time ? Remaining: %s", remainingTime))
if isConfirmed {
jsonData := []byte("{\"machine_id\":" + machineID + "}")
resp, err := utils.HtbRequest(http.MethodPost, config.BaseHackTheBoxAPIURL+"/vm/extend", jsonData)
if err != nil {
return err
}
var response Response
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return fmt.Errorf("error decoding JSON response: %v", err)
}

inputLayout := time.RFC3339Nano

date, err := time.Parse(inputLayout, response.ExpiresAt)
if err != nil {
return fmt.Errorf("error decoding JSON response: %v", err)
}

outputLayout := "2006-01-02 -> 15h 04m 05s"
tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.Debug)
w := utils.SetTabWriterHeader(header)

formattedDate := date.Format(outputLayout)
url := fmt.Sprintf("%s/machine/profile/%s", config.BaseHackTheBoxAPIURL, machineID)
resp, err := utils.HtbRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
info := utils.ParseJsonMessage(resp, "info")
// info := utils.ParseJsonMessage(resp, "data")

fmt.Println(response.Message)
fmt.Printf("Expires Date: %s\n", formattedDate)
data := info.(map[string]interface{})
status := utils.SetStatus(data)
retiredStatus := getMachineStatus(data)

}
}
datetime, err := utils.ParseAndFormatDate(data["release"].(string))
if err != nil {
return err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType))

tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.Debug)
w := utils.SetTabWriterHeader(header)
userSubscription, err := utils.GetUserSubscription()
if err != nil {
return err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("User subscription: %s", userSubscription))

url := fmt.Sprintf("%s/machine/profile/%s", config.BaseHackTheBoxAPIURL, machineID)
resp, err := utils.HtbRequest(http.MethodGet, url, nil)
ip := "Undefined"
_ = ip
switch {
case machineType == "release":
ip, err = utils.GetActiveReleaseArenaMachineIP()
if err != nil {
return err
}
info := utils.ParseJsonMessage(resp, "info")
// info := utils.ParseJsonMessage(resp, "data")

data := info.(map[string]interface{})
status := utils.SetStatus(data)
retiredStatus := getMachineStatus(data)

datetime, err := utils.ParseAndFormatDate(data["release"].(string))
case userSubscription == "vip+":
ip, err = utils.GetActiveMachineIP()
if err != nil {
return err
}
default:
ip = getIPStatus(data).(string)
}

machineType, err := utils.GetMachineType(machineID)
if err != nil {
return err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType))
bodyData := fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n",
data["name"], data["os"], retiredStatus,
data["difficultyText"], data["stars"],
ip, status, data["last_reset_time"], datetime)

userSubscription, err := utils.GetUserSubscription()
if err != nil {
return err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("User subscription: %s", userSubscription))
utils.SetTabWriterData(w, bodyData)
w.Flush()
return nil
}

func checkIfExpiringSoon(expiresTime string, machineID string) error {
layout := "2006-01-02 15:04:05"

ip := "Undefined"
_ = ip
switch {
case machineType == "release":
ip, err = utils.GetActiveReleaseArenaMachineIP()
date, err := time.Parse(layout, expiresTime)
if err != nil {
return fmt.Errorf("date conversion error: %v", err)
}

now := time.Now()
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Actual date: %v", now))

timeLeft := date.Sub(now)
limit := 2 * time.Hour
if timeLeft > 0 && timeLeft <= limit {
var remainingTime string
if date.After(now) {
duration := date.Sub(now)
hours := int(duration.Hours())
minutes := int(duration.Minutes()) % 60
seconds := int(duration.Seconds()) % 60

remainingTime = fmt.Sprintf("%dh %dm %ds", hours, minutes, seconds)

}
// Extend time
isConfirmed := utils.AskConfirmation(fmt.Sprintf("Would you like to extend the active machine time ? Remaining: %s", remainingTime))
if isConfirmed {
jsonData := []byte("{\"machine_id\":" + machineID + "}")
resp, err := utils.HtbRequest(http.MethodPost, config.BaseHackTheBoxAPIURL+"/vm/extend", jsonData)
if err != nil {
return err
}
case userSubscription == "vip+":
ip, err = utils.GetActiveMachineIP()
var response Response
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return fmt.Errorf("error decoding JSON response: %v", err)
}

inputLayout := time.RFC3339Nano

date, err := time.Parse(inputLayout, response.ExpiresAt)
if err != nil {
return err
return fmt.Errorf("error decoding JSON response: %v", err)
}
default:
ip = getIPStatus(data).(string)
}

bodyData := fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n",
data["name"], data["os"], retiredStatus,
data["difficultyText"], data["stars"],
ip, status, data["last_reset_time"], datetime)
outputLayout := "2006-01-02 -> 15h 04m 05s"

utils.SetTabWriterData(w, bodyData)
w.Flush()
} else {
fmt.Println("No machine is running")
formattedDate := date.Format(outputLayout)

fmt.Println(response.Message)
fmt.Printf("Expires Date: %s\n", formattedDate)

}
}
return nil
}
Expand Down
33 changes: 25 additions & 8 deletions lib/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,34 +299,51 @@ func GetActiveMachineID() (string, error) {
return fmt.Sprintf("%.0f", info.(map[string]interface{})["id"].(float64)), nil
}

// GetActiveExpiredTime returns the expired date of the active machine
func GetActiveExpiredTime() (string, error) {
// GetExpiredTime returns the expired date of the machine
func GetExpiredTime(machineType string) (string, error) {
if machineType == "release" {
return getReleaseArenaExpiredTime()
}
return getActiveExpiredTime()
}

// getActiveExpiredTime returns the expired date of the active machine
func getActiveExpiredTime() (string, error) {
url := fmt.Sprintf("%s/machine/active", config.BaseHackTheBoxAPIURL)
resp, err := HtbRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
info := ParseJsonMessage(resp, "info")
if info == nil {
return "", nil
return "Undefined", nil
}
return fmt.Sprintf("%s", info.(map[string]interface{})["expires_at"]), nil
data := info.(map[string]interface{})
expiresAt := data["expires_at"]
if expiresAt == nil {
return "Undefined", nil
}
return expiresAt.(string), nil
}

func GetReleaseArenaExpiredTime() (string, error) {
// getReleaseArenaExpiredTime returns the expired date of the release arena machine
func getReleaseArenaExpiredTime() (string, error) {
url := fmt.Sprintf("%s/season/machine/active", config.BaseHackTheBoxAPIURL)
resp, err := HtbRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
info := ParseJsonMessage(resp, "data")
if info == nil {
return "", nil
return "Undefined", nil
}
data := info.(map[string]interface{})
playInfo := data["play_info"].(map[string]interface{})
expiresAt := playInfo["expires_at"].(string)
return expiresAt, nil
expiresAt := playInfo["expires_at"]
if expiresAt == nil {
return "Undefined", nil
}
return expiresAt.(string), nil
}

// GetActiveMachineIP returns the ip of the active machine
Expand Down

0 comments on commit df4ffae

Please sign in to comment.