updateCheck.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package updatecheck
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/denisbrodbeck/machineid"
  6. "github.com/go-co-op/gocron"
  7. config "github.com/jamesread/OliveTin/internal/config"
  8. log "github.com/sirupsen/logrus"
  9. "io/ioutil"
  10. "net/http"
  11. "runtime"
  12. "time"
  13. )
  14. type updateRequest struct {
  15. CurrentVersion string
  16. CurrentCommit string
  17. OS string
  18. Arch string
  19. MachineID string
  20. }
  21. // AvailableVersion is updated when checking with the update service.
  22. var AvailableVersion = "none"
  23. // CurrentVersion is set by the main cmd (which is in tern set as a compile constant)
  24. var CurrentVersion = "?"
  25. func machineID() string {
  26. v, err := machineid.ProtectedID("OliveTin")
  27. if err != nil {
  28. log.Warnf("Error getting machine ID: %v", err)
  29. return "?"
  30. }
  31. return v
  32. }
  33. // StartUpdateChecker will start a job that runs periodically, checking
  34. // for updates.
  35. func StartUpdateChecker(currentVersion string, currentCommit string, cfg *config.Config) {
  36. if !cfg.CheckForUpdates {
  37. log.Warn("Update checking is disabled")
  38. return
  39. }
  40. CurrentVersion = currentVersion
  41. payload := updateRequest{
  42. CurrentVersion: currentVersion,
  43. CurrentCommit: currentCommit,
  44. OS: runtime.GOOS,
  45. Arch: runtime.GOARCH,
  46. MachineID: machineID(),
  47. }
  48. s := gocron.NewScheduler(time.UTC)
  49. s.Every(7).Days().Do(func() {
  50. actualCheckForUpdate(payload)
  51. })
  52. s.StartAsync()
  53. }
  54. func doRequest(jsonUpdateRequest []byte) string {
  55. req, err := http.NewRequest("POST", "http://update-check.olivetin.app", bytes.NewBuffer(jsonUpdateRequest))
  56. if err != nil {
  57. log.Errorf("Update check failed %v", err)
  58. return ""
  59. }
  60. req.Header.Set("Content-Type", "application/json")
  61. resp, err := http.DefaultClient.Do(req)
  62. if err != nil {
  63. log.Errorf("Update check failed %v", err)
  64. return ""
  65. }
  66. newVersion, _ := ioutil.ReadAll(resp.Body)
  67. defer resp.Body.Close()
  68. return string(newVersion)
  69. }
  70. func actualCheckForUpdate(payload updateRequest) {
  71. jsonUpdateRequest, err := json.Marshal(payload)
  72. if err != nil {
  73. log.Errorf("Update check failed %v", err)
  74. return
  75. }
  76. AvailableVersion = doRequest(jsonUpdateRequest)
  77. log.WithFields(log.Fields{
  78. "NewVersion": AvailableVersion,
  79. }).Infof("Update check complete")
  80. }