updateCheck.go 1.9 KB

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