Clash.Meta/hub/route/upgrade.go

70 lines
1.6 KiB
Go
Raw Normal View History

package route
import (
"errors"
2023-04-02 15:16:42 +08:00
"fmt"
"net/http"
2023-04-02 15:16:42 +08:00
"os"
"github.com/Dreamacro/clash/config"
"github.com/Dreamacro/clash/hub/updater"
"github.com/Dreamacro/clash/log"
"github.com/go-chi/chi/v5"
2023-04-02 15:16:42 +08:00
"github.com/go-chi/render"
)
func upgradeRouter() http.Handler {
r := chi.NewRouter()
r.Post("/", upgradeCore)
2023-09-18 19:21:30 +08:00
r.Post("/ui", updateUI)
return r
}
func upgradeCore(w http.ResponseWriter, r *http.Request) {
// modify from https://github.com/AdguardTeam/AdGuardHome/blob/595484e0b3fb4c457f9bb727a6b94faa78a66c5f/internal/home/controlupdate.go#L108
log.Infoln("start update")
2023-04-02 15:16:42 +08:00
execPath, err := os.Executable()
if err != nil {
2023-04-02 15:16:42 +08:00
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, newError(fmt.Sprintf("getting path: %s", err)))
2023-03-27 00:49:32 +08:00
return
}
2023-04-02 15:16:42 +08:00
err = updater.Update(execPath)
if err != nil {
2023-05-17 00:17:23 +08:00
log.Warnln("%s", err)
2023-04-02 15:16:42 +08:00
render.Status(r, http.StatusInternalServerError)
2023-05-17 00:17:23 +08:00
render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
2023-04-02 15:16:42 +08:00
return
}
render.JSON(w, r, render.M{"status": "ok"})
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
2023-08-30 15:52:41 +08:00
go restartExecutable(execPath)
}
2023-09-18 19:21:30 +08:00
func updateUI(w http.ResponseWriter, r *http.Request) {
err := config.UpdateUI()
if err != nil {
2023-09-24 19:00:51 +08:00
if errors.Is(err, config.ErrIncompleteConf) {
log.Warnln("%s", err)
render.Status(r, http.StatusNotImplemented)
render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
} else {
log.Warnln("%s", err)
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, newError(fmt.Sprintf("%s", err)))
}
return
}
render.JSON(w, r, render.M{"status": "ok"})
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}