From 03e0b11e4e45919cc4194b3ae600a68b5e43b559 Mon Sep 17 00:00:00 2001 From: Adhityaa Chandrasekar Date: Thu, 16 Aug 2018 23:45:59 +0530 Subject: [PATCH] api: add version checking --- api/constants.go | 4 +++ api/main.go | 1 + api/version.go | 78 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 api/constants.go create mode 100644 api/version.go diff --git a/api/constants.go b/api/constants.go new file mode 100644 index 0000000..79052bf --- /dev/null +++ b/api/constants.go @@ -0,0 +1,4 @@ +package main + +var edition = "ce" +var version = "v1.0.0" diff --git a/api/main.go b/api/main.go index 59c814a..7d309d2 100644 --- a/api/main.go +++ b/api/main.go @@ -10,6 +10,7 @@ func main() { exitIfError(oauthConfigure()) exitIfError(markdownRendererCreate()) exitIfError(sigintCleanupSetup()) + exitIfError(versionCheckStart()) exitIfError(routesServe()) } diff --git a/api/version.go b/api/version.go new file mode 100644 index 0000000..216c63b --- /dev/null +++ b/api/version.go @@ -0,0 +1,78 @@ +package main + +import ( + "bytes" + "encoding/json" + "io/ioutil" + "net/http" + "net/url" + "os" + "time" +) + +func versionCheckStart() error { + go func() { + printedError := false + errorCount := 0 + + for { + time.Sleep(5 * time.Minute) + + data := url.Values{ + "origin": {os.Getenv("ORIGIN")}, + "edition": {edition}, + "version": {version}, + } + + resp, err := http.Post("https://version.commento.io/api/check", "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode())) + if err != nil { + errorCount++ + // print the error only once; we don't want to spam the logs with this + // every five minutes + if !printedError && errorCount > 5 { + logger.Errorf("error checking version: %v", err) + printedError = true + } + continue + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + errorCount++ + if !printedError && errorCount > 5 { + logger.Errorf("error reading body: %s", err) + printedError = true + } + continue + } + + type response struct { + Success bool `json:"success"` + Message string `json:"message"` + Latest string `json:"latest"` + NewUpdate bool `json:"newUpdate"` + } + + r := response{} + json.Unmarshal(body, &r) + if r.Success == false { + errorCount++ + if !printedError && errorCount > 5 { + logger.Errorf("error checking version: %s", r.Message) + printedError = true + } + continue + } + + if r.NewUpdate { + logger.Infof("New update available! Latest version: %s", r.Latest) + } + + errorCount = 0 + printedError = false + } + }() + + return nil +}