add the CLI function implementations

This commit is contained in:
Keiran 2025-08-06 06:32:00 +01:00
parent 227df20bf2
commit 424fae88c9

View File

@ -149,6 +149,166 @@ func saveConfig(config *Config) error {
return os.WriteFile(configPath, data, 0600)
}
func makeAuthenticatedRequest(method, endpoint string, body []byte) (*http.Response, error) {
config, err := loadConfig()
if err != nil {
return nil, fmt.Errorf("failed to load config: %v", err)
}
if config.Token == "" {
return nil, fmt.Errorf("not logged in. Please run 'termbox auth login' first")
}
req, err := http.NewRequest(method, apiURL+endpoint, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+config.Token)
return http.DefaultClient.Do(req)
}
func runInbox(cmd *cobra.Command, args []string) {
search, _ := cmd.Flags().GetString("search")
limit, _ := cmd.Flags().GetInt("limit")
offset, _ := cmd.Flags().GetInt("offset")
unread, _ := cmd.Flags().GetBool("unread")
endpoint := fmt.Sprintf("/termail/inbox?limit=%d&offset=%d", limit, offset)
if search != "" {
endpoint += "&search=" + search
}
if unread {
endpoint += "&unread=true"
}
resp, err := makeAuthenticatedRequest("GET", endpoint, nil)
if err != nil {
fmt.Printf("Error fetching inbox: %v\n", err)
return
}
defer resp.Body.Close()
var response map[string]interface{}
json.NewDecoder(resp.Body).Decode(&response)
if resp.StatusCode == http.StatusOK {
termails := response["termails"].([]interface{})
if len(termails) == 0 {
fmt.Println("No termails found.")
return
}
for _, t := range termails {
termail := t.(map[string]interface{})
status := "READ"
if !termail["is_read"].(bool) {
status = "UNREAD"
}
fmt.Printf("[%s] ID: %.0f | From: %s | Subject: %s | Sent: %s\n",
status,
termail["id"].(float64),
termail["sender"].(string),
termail["subject"].(string),
termail["sent_at"].(string),
)
}
} else {
fmt.Printf("Error: %s\n", response["error"])
}
}
func runInboxRead(cmd *cobra.Command, args []string) {
termailID, err := strconv.Atoi(args[0])
if err != nil {
fmt.Printf("Invalid termail ID: %s\n", args[0])
return
}
endpoint := fmt.Sprintf("/termail/%d/read", termailID)
resp, err := makeAuthenticatedRequest("POST", endpoint, nil)
if err != nil {
fmt.Printf("Error marking termail as read: %v\n", err)
return
}
defer resp.Body.Close()
var response map[string]interface{}
json.NewDecoder(resp.Body).Decode(&response)
if resp.StatusCode == http.StatusOK {
fmt.Println("Termail marked as read.")
} else {
fmt.Printf("Error: %s\n", response["error"])
}
}
func runInboxDelete(cmd *cobra.Command, args []string) {
termailID, err := strconv.Atoi(args[0])
if err != nil {
fmt.Printf("Invalid termail ID: %s\n", args[0])
return
}
endpoint := fmt.Sprintf("/termail/%d", termailID)
resp, err := makeAuthenticatedRequest("DELETE", endpoint, nil)
if err != nil {
fmt.Printf("Error deleting termail: %v\n", err)
return
}
defer resp.Body.Close()
var response map[string]interface{}
json.NewDecoder(resp.Body).Decode(&response)
if resp.StatusCode == http.StatusOK {
fmt.Println("Termail deleted.")
} else {
fmt.Printf("Error: %s\n", response["error"])
}
}
func runSend(cmd *cobra.Command, args []string) {
receiverUsername := args[0]
fmt.Print("Subject: ")
reader := bufio.NewReader(os.Stdin)
subject, _ := reader.ReadString('\n')
subject = strings.TrimSpace(subject)
fmt.Println("Content (press Ctrl+D when finished):")
var contentLines []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
contentLines = append(contentLines, scanner.Text())
}
content := strings.Join(contentLines, "\n")
requestBody, _ := json.Marshal(map[string]string{
"receiver_username": receiverUsername,
"subject": subject,
"content": content,
})
resp, err := makeAuthenticatedRequest("POST", "/termail/send", requestBody)
if err != nil {
fmt.Printf("Error sending termail: %v\n", err)
return
}
defer resp.Body.Close()
var response map[string]interface{}
json.NewDecoder(resp.Body).Decode(&response)
if resp.StatusCode == http.StatusCreated {
fmt.Printf("Termail sent successfully to %s!\n", receiverUsername)
} else {
fmt.Printf("Error: %s\n", response["error"])
}
}
func runRegister(cmd *cobra.Command, args []string) {
fmt.Print("Username: ")
reader := bufio.NewReader(os.Stdin)