upgrade.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package route
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "github.com/metacubex/mihomo/component/updater"
  8. "github.com/metacubex/mihomo/log"
  9. "github.com/go-chi/chi/v5"
  10. "github.com/go-chi/render"
  11. )
  12. func upgradeRouter() http.Handler {
  13. r := chi.NewRouter()
  14. r.Post("/", upgradeCore)
  15. r.Post("/ui", updateUI)
  16. r.Post("/geo", updateGeoDatabases)
  17. return r
  18. }
  19. func upgradeCore(w http.ResponseWriter, r *http.Request) {
  20. // modify from https://github.com/AdguardTeam/AdGuardHome/blob/595484e0b3fb4c457f9bb727a6b94faa78a66c5f/internal/home/controlupdate.go#L108
  21. log.Infoln("start update")
  22. execPath, err := os.Executable()
  23. if err != nil {
  24. render.Status(r, http.StatusInternalServerError)
  25. render.JSON(w, r, newError(fmt.Sprintf("getting path: %s", err)))
  26. return
  27. }
  28. err = updater.UpdateCore(execPath)
  29. if err != nil {
  30. log.Warnln("%s", err)
  31. render.Status(r, http.StatusInternalServerError)
  32. render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
  33. return
  34. }
  35. render.JSON(w, r, render.M{"status": "ok"})
  36. if f, ok := w.(http.Flusher); ok {
  37. f.Flush()
  38. }
  39. go restartExecutable(execPath)
  40. }
  41. func updateUI(w http.ResponseWriter, r *http.Request) {
  42. err := updater.UpdateUI()
  43. if err != nil {
  44. if errors.Is(err, updater.ErrIncompleteConf) {
  45. log.Warnln("%s", err)
  46. render.Status(r, http.StatusNotImplemented)
  47. render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
  48. } else {
  49. log.Warnln("%s", err)
  50. render.Status(r, http.StatusInternalServerError)
  51. render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
  52. }
  53. return
  54. }
  55. render.JSON(w, r, render.M{"status": "ok"})
  56. if f, ok := w.(http.Flusher); ok {
  57. f.Flush()
  58. }
  59. }