hishtory/clients/remote/client.go

98 lines
2.2 KiB
Go
Raw Normal View History

package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/ddworken/hishtory/shared"
)
func main() {
2022-01-10 00:48:20 +01:00
if len(os.Args) == 1 {
fmt.Println("Must specify a command! Do you mean `hishtory query`?")
return
}
switch os.Args[1] {
case "saveHistoryEntry":
saveHistoryEntry()
case "query":
2022-01-10 00:48:20 +01:00
query(strings.Join(os.Args[2:], " "))
case "init":
2022-01-10 00:48:20 +01:00
shared.CheckFatalError(shared.Setup(os.Args))
case "install":
shared.CheckFatalError(shared.Install())
2022-01-09 20:00:53 +01:00
case "enable":
shared.CheckFatalError(shared.Enable())
case "disable":
shared.CheckFatalError(shared.Disable())
2022-01-09 23:34:59 +01:00
default:
shared.CheckFatalError(fmt.Errorf("unknown command: %s", os.Args[1]))
}
}
func getServerHostname() string {
if server := os.Getenv("HISHTORY_SERVER"); server != "" {
return server
}
return "http://localhost:8080"
}
2022-01-10 00:48:20 +01:00
func query(query string) {
userSecret, err := shared.GetUserSecret()
2022-01-09 20:00:53 +01:00
shared.CheckFatalError(err)
req, err := http.NewRequest("GET", getServerHostname()+"/api/v1/search", nil)
2022-01-09 20:00:53 +01:00
shared.CheckFatalError(err)
q := req.URL.Query()
2022-01-10 00:48:20 +01:00
q.Add("query", query)
q.Add("user_secret", userSecret)
q.Add("limit", "25")
req.URL.RawQuery = q.Encode()
client := &http.Client{}
resp, err := client.Do(req)
2022-01-09 20:00:53 +01:00
shared.CheckFatalError(err)
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
2022-01-09 20:00:53 +01:00
shared.CheckFatalError(err)
if resp.Status != "200 OK" {
2022-01-09 20:00:53 +01:00
shared.CheckFatalError(fmt.Errorf("search API returned invalid result. status=" + resp.Status))
}
var data []*shared.HistoryEntry
err = json.Unmarshal(resp_body, &data)
2022-01-09 20:00:53 +01:00
shared.CheckFatalError(err)
2022-01-09 23:34:59 +01:00
shared.DisplayResults(data, true)
}
func saveHistoryEntry() {
2022-01-09 20:00:53 +01:00
isEnabled, err := shared.IsEnabled()
shared.CheckFatalError(err)
if !isEnabled {
return
}
2022-01-09 20:00:53 +01:00
entry, err := shared.BuildHistoryEntry(os.Args)
shared.CheckFatalError(err)
err = send(*entry)
2022-01-09 20:00:53 +01:00
shared.CheckFatalError(err)
}
func send(entry shared.HistoryEntry) error {
jsonValue, err := json.Marshal(entry)
if err != nil {
return fmt.Errorf("failed to marshal HistoryEntry as json: %v", err)
}
_, err = http.Post(getServerHostname()+"/api/v1/submit", "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
return fmt.Errorf("failed to send HistoryEntry to api: %v", err)
}
return nil
}