From e2ab505b47ef53d2a534c5c9a81abfadb1aba5e0 Mon Sep 17 00:00:00 2001 From: sneak Date: Tue, 22 Sep 2020 07:27:14 -0700 Subject: [PATCH] almost posts now --- hp/detector.go | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/hp/detector.go b/hp/detector.go index 937b2fb..342b3ac 100644 --- a/hp/detector.go +++ b/hp/detector.go @@ -9,12 +9,15 @@ import ( "time" "git.eeqj.de/sneak/goutil" + "git.eeqj.de/sneak/mothership/apitypes" // db driver: _ "github.com/mattn/go-sqlite3" "github.com/rs/zerolog/log" ) +const jsonContentType = "application/json; charset=utf-8" + func (hp *HistoryPoster) postURLs(ctx context.Context, cancel context.CancelFunc) { log.Info().Msg("finding history files") files, err := findHistoryFiles() @@ -57,8 +60,48 @@ func (hp *HistoryPoster) processURLFromHistory(hi historyItem) { } func (hp *HistoryPoster) postURL(hi historyItem) error { - // FIXME - // panic("unimplemented") + + req := &apitypes.MothershipHistoryRequest{ + PSK: viper.GetString("PSK"), + Visit: &apitypes.MothershipHistoryItem{ + LastVisitTime: hi.LastVisitTime.Format(time.RFC3339Nano), + URL: hi.URL, + } + } + + url := viper.GetString("APIURL") + + reqBody := new(bytes.Buffer) + + json.NewEncoder(reqBody).Encode(req) + + res, err := http.Post(url, jsonContentType, reqBody) + if err != nil { + log.Error().Err(err).Msg("unable to POST url to mothership") + return err + } + + if res.StatusCode != http.StatusOK { + log.Error(). + Int("statuscode", res.StatusCode). + Msg("unable to POST url to mothership") + return err + } + + var apiresp apitypes.MothershipHistoryResponse + err = json.NewDecoder(res.Body).Decode(&apiresp) + + if err != nil { + log.Error().Err(err).Msg("unable to decode mothership response") + return err + } + + if apiresp.Result != "ok" { + log.Error().Msg("mothership response non-ok") + return errors.New("mothership response non-ok") + } + + log.Info().Str("url",hi.URL).Msg("url sent to mothership") return nil }