updateCheck.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. var AvailableVersion = "none"
  22. var CurrentVersion = "?"
  23. func machineID() string {
  24. v, err := machineid.ProtectedID("OliveTin")
  25. if err != nil {
  26. log.Warnf("Error getting machine ID: %v", err)
  27. return "?"
  28. }
  29. return v
  30. }
  31. // StartUpdateChecker will start a job that runs periodically, checking
  32. // for updates.
  33. func StartUpdateChecker(currentVersion string, currentCommit string, cfg *config.Config) {
  34. if !cfg.CheckForUpdates {
  35. log.Warn("Update checking is disabled")
  36. return
  37. }
  38. CurrentVersion = currentVersion
  39. payload := updateRequest{
  40. CurrentVersion: currentVersion,
  41. CurrentCommit: currentCommit,
  42. OS: runtime.GOOS,
  43. Arch: runtime.GOARCH,
  44. MachineID: machineID(),
  45. }
  46. s := gocron.NewScheduler(time.UTC)
  47. s.Every(7).Days().Do(func() {
  48. actualCheckForUpdate(payload)
  49. })
  50. s.StartAsync()
  51. }
  52. func doRequest(jsonUpdateRequest []byte) string {
  53. req, err := http.NewRequest("POST", "http://update-check.olivetin.app", bytes.NewBuffer(jsonUpdateRequest))
  54. if err != nil {
  55. log.Errorf("Update check failed %v", err)
  56. return ""
  57. }
  58. req.Header.Set("Content-Type", "application/json")
  59. resp, err := http.DefaultClient.Do(req)
  60. if err != nil {
  61. log.Errorf("Update check failed %v", err)
  62. return ""
  63. }
  64. newVersion, _ := ioutil.ReadAll(resp.Body)
  65. defer resp.Body.Close()
  66. return string(newVersion)
  67. }
  68. func actualCheckForUpdate(payload updateRequest) {
  69. jsonUpdateRequest, err := json.Marshal(payload)
  70. if err != nil {
  71. log.Errorf("Update check failed %v", err)
  72. return
  73. }
  74. AvailableVersion = doRequest(jsonUpdateRequest)
  75. log.WithFields(log.Fields{
  76. "NewVersion": AvailableVersion,
  77. }).Infof("Update check complete")
  78. }