2023-03-23 20:42:01 +08:00
|
|
|
package route
|
|
|
|
|
|
|
|
import (
|
2023-09-23 17:59:59 +08:00
|
|
|
"errors"
|
2023-04-02 15:16:42 +08:00
|
|
|
"fmt"
|
2023-03-23 20:42:01 +08:00
|
|
|
"net/http"
|
2023-04-02 15:16:42 +08:00
|
|
|
"os"
|
2023-03-23 20:42:01 +08:00
|
|
|
|
2023-09-15 23:25:56 +08:00
|
|
|
"github.com/Dreamacro/clash/config"
|
2023-03-23 20:42:01 +08:00
|
|
|
"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"
|
2023-03-23 20:42:01 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func upgradeRouter() http.Handler {
|
|
|
|
r := chi.NewRouter()
|
2023-09-23 17:59:59 +08:00
|
|
|
r.Post("/", upgradeCore)
|
2023-09-18 19:21:30 +08:00
|
|
|
r.Post("/ui", updateUI)
|
2023-03-23 20:42:01 +08:00
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
2023-09-23 17:59:59 +08:00
|
|
|
func upgradeCore(w http.ResponseWriter, r *http.Request) {
|
2023-03-23 20:42:01 +08:00
|
|
|
// 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()
|
2023-03-23 20:42:01 +08:00
|
|
|
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-03-23 20:42:01 +08:00
|
|
|
}
|
|
|
|
|
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-03-23 20:42:01 +08:00
|
|
|
}
|
2023-09-15 23:25:56 +08:00
|
|
|
|
2023-09-18 19:21:30 +08:00
|
|
|
func updateUI(w http.ResponseWriter, r *http.Request) {
|
|
|
|
err := config.UpdateUI()
|
2023-09-15 23:25:56 +08:00
|
|
|
if err != nil {
|
2023-09-24 19:00:51 +08:00
|
|
|
if errors.Is(err, config.ErrIncompleteConf) {
|
2023-09-23 17:59:59 +08:00
|
|
|
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)))
|
|
|
|
}
|
2023-09-15 23:25:56 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
render.JSON(w, r, render.M{"status": "ok"})
|
|
|
|
if f, ok := w.(http.Flusher); ok {
|
|
|
|
f.Flush()
|
|
|
|
}
|
|
|
|
}
|