From f21ed9229695ed1cbcc86d65b52d98cfc9116f5a Mon Sep 17 00:00:00 2001 From: "Farhad H. P. Shirvan" <9374298+farhadh@users.noreply.github.com> Date: Tue, 28 Apr 2026 18:46:55 +0200 Subject: [PATCH] feat: add panel update functionality via web GUI (#4117) * feat: add panel update functionality via web GUI * feat: enhance panel update notifications in web GUI * feat: implement panel update modal and enhance translation strings * fix design --- web/controller/server.go | 19 +++ web/html/index.html | 113 +++++++++++++++-- web/service/panel.go | 174 +++++++++++++++++++++++++++ web/service/panel_other.go | 7 ++ web/service/panel_test.go | 41 +++++++ web/service/panel_unix.go | 12 ++ web/translation/translate.en_US.toml | 11 ++ 7 files changed, 367 insertions(+), 10 deletions(-) create mode 100644 web/service/panel_other.go create mode 100644 web/service/panel_test.go create mode 100644 web/service/panel_unix.go diff --git a/web/controller/server.go b/web/controller/server.go index d32209e1..188e987a 100644 --- a/web/controller/server.go +++ b/web/controller/server.go @@ -22,6 +22,7 @@ type ServerController struct { serverService service.ServerService settingService service.SettingService + panelService service.PanelService lastStatus *service.Status @@ -43,6 +44,7 @@ func (a *ServerController) initRouter(g *gin.RouterGroup) { g.GET("/status", a.status) g.GET("/cpuHistory/:bucket", a.getCpuHistoryBucket) g.GET("/getXrayVersion", a.getXrayVersion) + g.GET("/getPanelUpdateInfo", a.getPanelUpdateInfo) g.GET("/getConfigJson", a.getConfigJson) g.GET("/getDb", a.getDb) g.GET("/getNewUUID", a.getNewUUID) @@ -54,6 +56,7 @@ func (a *ServerController) initRouter(g *gin.RouterGroup) { g.POST("/stopXrayService", a.stopXrayService) g.POST("/restartXrayService", a.restartXrayService) g.POST("/installXray/:version", a.installXray) + g.POST("/updatePanel", a.updatePanel) g.POST("/updateGeofile", a.updateGeofile) g.POST("/updateGeofile/:fileName", a.updateGeofile) g.POST("/logs/:count", a.getLogs) @@ -131,6 +134,16 @@ func (a *ServerController) getXrayVersion(c *gin.Context) { jsonObj(c, versions, nil) } +// getPanelUpdateInfo retrieves the current and latest panel version. +func (a *ServerController) getPanelUpdateInfo(c *gin.Context) { + info, err := a.panelService.GetUpdateInfo() + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateCheckPopover"), err) + return + } + jsonObj(c, info, nil) +} + // installXray installs or updates Xray to the specified version. func (a *ServerController) installXray(c *gin.Context) { version := c.Param("version") @@ -138,6 +151,12 @@ func (a *ServerController) installXray(c *gin.Context) { jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err) } +// updatePanel starts a panel self-update to the latest release. +func (a *ServerController) updatePanel(c *gin.Context) { + err := a.panelService.StartUpdate() + jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateStartedPopover"), err) +} + // updateGeofile updates the specified geo file for Xray. func (a *ServerController) updateGeofile(c *gin.Context) { fileName := c.Param("fileName") diff --git a/web/html/index.html b/web/html/index.html index 0a36b9cb..62e9453b 100644 --- a/web/html/index.html +++ b/web/html/index.html @@ -139,7 +139,7 @@ {{ i18n "pages.index.restartXray" }} - + [[ status.xray.version != 'Unknown' ? `v${status.xray.version}` : '{{ i18n @@ -169,6 +169,14 @@ + v{{ .cur_ver }} @@ -317,9 +325,36 @@ - + + + + {{ i18n "pages.index.currentPanelVersion" }} + v[[ panelUpdateModal.info.currentVersion || '{{ .cur_ver }}' ]] + + + {{ i18n "pages.index.latestPanelVersion" }} + + [[ panelUpdateModal.info.latestVersion || '-' ]] + + + + {{ i18n "pages.index.panelUpToDate" }} + {{ i18n "pages.index.upToDate" }} + + +
+ + {{ i18n "pages.index.updatePanel" }} + +
+
+ - + @@ -799,9 +834,11 @@ const versionModal = { visible: false, + activeKey: '1', versions: [], - show(versions) { + show(versions, activeKey = '1') { this.visible = true; + this.activeKey = activeKey; this.versions = versions; }, hide() { @@ -809,6 +846,24 @@ }, }; + const panelUpdateModal = { + visible: false, + info: { + currentVersion: '{{ .cur_ver }}', + latestVersion: '', + updateAvailable: false, + }, + show(info) { + this.visible = true; + if (info) { + this.info = info; + } + }, + hide() { + this.visible = false; + }, + }; + const logModal = { visible: false, logs: [], @@ -958,11 +1013,12 @@ spinning: false }, status: new Status(), - cpuHistory: [], // small live widget history - cpuHistoryLong: [], // aggregated points from backend - cpuHistoryLabels: [], - cpuHistoryModal: { visible: false, bucket: 2 }, + cpuHistory: [], // small live widget history + cpuHistoryLong: [], // aggregated points from backend + cpuHistoryLabels: [], + cpuHistoryModal: { visible: false, bucket: 2 }, versionModal, + panelUpdateModal, logModal, xraylogModal, backupModal, @@ -1049,16 +1105,25 @@ console.error('Failed to fetch bucketed cpu history', e) } }, - async openSelectV2rayVersion() { + async openSelectV2rayVersion(activeKey = '1') { this.loading(true); const msg = await HttpUtil.get('/panel/api/server/getXrayVersion'); this.loading(false); if (!msg.success) { return; } - versionModal.show(msg.obj); + versionModal.show(msg.obj, activeKey); this.loadCustomGeo(); }, + async openPanelUpdate() { + this.loading(true); + const msg = await HttpUtil.get('/panel/api/server/getPanelUpdateInfo'); + this.loading(false); + if (!msg.success) { + return; + } + panelUpdateModal.show(msg.obj); + }, customGeoFormatTime(ts) { if (!ts) return ''; return typeof moment !== 'undefined' ? moment(ts * 1000).format('YYYY-MM-DD HH:mm') : String(ts); @@ -1195,6 +1260,27 @@ }, }); }, + updatePanel() { + this.$confirm({ + title: '{{ i18n "pages.index.panelUpdateDialog" }}', + content: '{{ i18n "pages.index.panelUpdateDialogDesc" }}' + .replace('#version#', panelUpdateModal.info.latestVersion || ''), + okText: '{{ i18n "confirm"}}', + class: themeSwitcher.currentTheme, + cancelText: '{{ i18n "cancel"}}', + onOk: async () => { + panelUpdateModal.hide(); + this.loading(true, '{{ i18n "pages.index.dontRefresh"}}'); + const msg = await HttpUtil.post('/panel/api/server/updatePanel'); + if (!msg.success) { + this.loading(false); + return; + } + await PromiseUtil.sleep(15000); + window.location.reload(); + }, + }); + }, updateGeofile(fileName) { const isSingleFile = !!fileName; this.$confirm({ @@ -1346,6 +1432,13 @@ // Initial status fetch await this.getStatus(); + // Silently check for panel updates so the indicator shows on load + HttpUtil.get('/panel/api/server/getPanelUpdateInfo').then(msg => { + if (msg && msg.success && msg.obj) { + panelUpdateModal.info = msg.obj; + } + }); + // Setup WebSocket for real-time updates if (window.wsClient) { window.wsClient.connect(); diff --git a/web/service/panel.go b/web/service/panel.go index e4fb0c68..75f2f155 100644 --- a/web/service/panel.go +++ b/web/service/panel.go @@ -1,10 +1,19 @@ package service import ( + "encoding/json" + "fmt" + "net/http" "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" "syscall" "time" + "github.com/mhsanaei/3x-ui/v2/config" "github.com/mhsanaei/3x-ui/v2/logger" ) @@ -12,6 +21,13 @@ import ( // It handles panel restart, updates, and system-level panel controls. type PanelService struct{} +// PanelUpdateInfo contains the current and latest available panel versions. +type PanelUpdateInfo struct { + CurrentVersion string `json:"currentVersion"` + LatestVersion string `json:"latestVersion"` + UpdateAvailable bool `json:"updateAvailable"` +} + func (s *PanelService) RestartPanel(delay time.Duration) error { p, err := os.FindProcess(syscall.Getpid()) if err != nil { @@ -26,3 +42,161 @@ func (s *PanelService) RestartPanel(delay time.Duration) error { }() return nil } + +// GetUpdateInfo checks GitHub for the latest 3x-ui release. +func (s *PanelService) GetUpdateInfo() (*PanelUpdateInfo, error) { + latest, err := fetchLatestPanelVersion() + if err != nil { + return nil, err + } + current := config.GetVersion() + return &PanelUpdateInfo{ + CurrentVersion: current, + LatestVersion: latest, + UpdateAvailable: isNewerVersion(latest, current), + }, nil +} + +// StartUpdate starts the official updater outside of the current web request. +func (s *PanelService) StartUpdate() error { + if runtime.GOOS != "linux" { + return fmt.Errorf("panel web update is supported only on Linux installations") + } + + bash, err := exec.LookPath("bash") + if err != nil { + return fmt.Errorf("bash is required to run the panel updater: %w", err) + } + curl, err := exec.LookPath("curl") + if err != nil { + return fmt.Errorf("curl is required to download the panel updater: %w", err) + } + + mainFolder, serviceFolder := resolveUpdateFolders() + updateScript := fmt.Sprintf("set -o pipefail; %s -fLs https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh | %s", shellQuote(curl), shellQuote(bash)) + + if systemdRun, err := exec.LookPath("systemd-run"); err == nil { + unitName := fmt.Sprintf("x-ui-web-update-%d", time.Now().Unix()) + cmd := exec.Command(systemdRun, + "--unit", unitName, + "--setenv", "XUI_MAIN_FOLDER="+mainFolder, + "--setenv", "XUI_SERVICE="+serviceFolder, + bash, "-lc", updateScript, + ) + out, err := cmd.CombinedOutput() + if err != nil { + output := strings.TrimSpace(string(out)) + if !strings.Contains(output, "System has not been booted with systemd") && + !strings.Contains(output, "Failed to connect to bus") { + return fmt.Errorf("failed to start panel update job: %w: %s", err, output) + } + logger.Warning("systemd-run is unavailable, falling back to detached update process:", output) + } else { + logger.Infof("started panel update job via systemd-run unit %s", unitName) + return nil + } + } + + cmd := exec.Command(bash, "-lc", updateScript) + cmd.Env = append(os.Environ(), + "XUI_MAIN_FOLDER="+mainFolder, + "XUI_SERVICE="+serviceFolder, + ) + setDetachedProcess(cmd) + if err := cmd.Start(); err != nil { + return fmt.Errorf("failed to start panel update job: %w", err) + } + if err := cmd.Process.Release(); err != nil { + logger.Warning("failed to release panel update process:", err) + } + logger.Infof("started panel update job with pid %d", cmd.Process.Pid) + return nil +} + +func fetchLatestPanelVersion() (string, error) { + client := &http.Client{Timeout: 10 * time.Second} + resp, err := client.Get("https://api.github.com/repos/MHSanaei/3x-ui/releases/latest") + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status) + } + + var release Release + if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { + return "", err + } + if release.TagName == "" { + return "", fmt.Errorf("latest panel release tag is empty") + } + return release.TagName, nil +} + +func resolveUpdateFolders() (string, string) { + mainFolder := os.Getenv("XUI_MAIN_FOLDER") + if mainFolder == "" { + if exePath, err := os.Executable(); err == nil { + mainFolder = filepath.Dir(exePath) + } + } + if mainFolder == "" { + mainFolder = "/usr/local/x-ui" + } + + serviceFolder := os.Getenv("XUI_SERVICE") + if serviceFolder == "" { + serviceFolder = "/etc/systemd/system" + } + return mainFolder, serviceFolder +} + +func isNewerVersion(latest string, current string) bool { + cmp, ok := compareVersionStrings(latest, current) + if !ok { + return normalizeVersionTag(latest) != normalizeVersionTag(current) + } + return cmp > 0 +} + +func compareVersionStrings(a string, b string) (int, bool) { + aParts, okA := parseVersionParts(a) + bParts, okB := parseVersionParts(b) + if !okA || !okB { + return 0, false + } + for i := 0; i < len(aParts); i++ { + if aParts[i] > bParts[i] { + return 1, true + } + if aParts[i] < bParts[i] { + return -1, true + } + } + return 0, true +} + +func parseVersionParts(version string) ([3]int, bool) { + var result [3]int + parts := strings.Split(normalizeVersionTag(version), ".") + if len(parts) != 3 { + return result, false + } + for i, part := range parts { + n, err := strconv.Atoi(part) + if err != nil { + return result, false + } + result[i] = n + } + return result, true +} + +func normalizeVersionTag(version string) string { + return strings.TrimPrefix(strings.TrimSpace(version), "v") +} + +func shellQuote(value string) string { + return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" +} diff --git a/web/service/panel_other.go b/web/service/panel_other.go new file mode 100644 index 00000000..53295c10 --- /dev/null +++ b/web/service/panel_other.go @@ -0,0 +1,7 @@ +//go:build !linux + +package service + +import "os/exec" + +func setDetachedProcess(cmd *exec.Cmd) {} diff --git a/web/service/panel_test.go b/web/service/panel_test.go new file mode 100644 index 00000000..44e9ba34 --- /dev/null +++ b/web/service/panel_test.go @@ -0,0 +1,41 @@ +package service + +import "testing" + +func TestIsNewerVersion(t *testing.T) { + cases := []struct { + latest string + current string + want bool + }{ + {"v2.9.4", "2.9.3", true}, + {"v2.10.0", "2.9.9", true}, + {"v2.9.3", "2.9.3", false}, + {"v2.9.2", "2.9.3", false}, + {"v3.0.0", "2.9.3", true}, + } + + for _, tc := range cases { + if got := isNewerVersion(tc.latest, tc.current); got != tc.want { + t.Fatalf("isNewerVersion(%q, %q) = %v, want %v", tc.latest, tc.current, got, tc.want) + } + } +} + +func TestCompareVersionStringsRejectsUnexpectedFormats(t *testing.T) { + if _, ok := compareVersionStrings("latest", "2.9.3"); ok { + t.Fatal("expected non-semver latest tag to be rejected") + } + if _, ok := compareVersionStrings("v2.9", "2.9.3"); ok { + t.Fatal("expected short version to be rejected") + } +} + +func TestShellQuote(t *testing.T) { + if got := shellQuote("/usr/bin/curl"); got != "'/usr/bin/curl'" { + t.Fatalf("unexpected quote result: %s", got) + } + if got := shellQuote("/tmp/a'b"); got != "'/tmp/a'\\''b'" { + t.Fatalf("unexpected quote result with single quote: %s", got) + } +} diff --git a/web/service/panel_unix.go b/web/service/panel_unix.go new file mode 100644 index 00000000..13d2237c --- /dev/null +++ b/web/service/panel_unix.go @@ -0,0 +1,12 @@ +//go:build linux + +package service + +import ( + "os/exec" + "syscall" +) + +func setDetachedProcess(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} +} diff --git a/web/translation/translate.en_US.toml b/web/translation/translate.en_US.toml index 45186187..49c9f952 100644 --- a/web/translation/translate.en_US.toml +++ b/web/translation/translate.en_US.toml @@ -124,8 +124,15 @@ "stopXray" = "Stop" "restartXray" = "Restart" "xraySwitch" = "Version" +"xrayUpdates" = "Xray Updates" "xraySwitchClick" = "Choose the version you want to switch to." "xraySwitchClickDesk" = "Choose carefully, as older versions may not be compatible with current configurations." +"updatePanel" = "Update Panel" +"panelUpdateDesc" = "This will update 3X-UI itself to the latest release and restart the panel service." +"currentPanelVersion" = "Current panel version" +"latestPanelVersion" = "Latest panel version" +"panelUpToDate" = "Panel is up to date" +"upToDate" = "Up to date" "xrayStatusUnknown" = "Unknown" "xrayStatusRunning" = "Running" "xrayStatusStop" = "Stop" @@ -147,6 +154,10 @@ "xraySwitchVersionDialog" = "Do you really want to change the Xray version?" "xraySwitchVersionDialogDesc" = "This will change the Xray version to #version#." "xraySwitchVersionPopover" = "Xray updated successfully" +"panelUpdateDialog" = "Do you really want to update the panel?" +"panelUpdateDialogDesc" = "This will update 3X-UI to #version# and restart the panel service." +"panelUpdateCheckPopover" = "Panel update check failed" +"panelUpdateStartedPopover" = "Panel update started" "geofileUpdateDialog" = "Do you really want to update the geofile?" "geofileUpdateDialogDesc" = "This will update the #filename# file." "geofilesUpdateDialogDesc" = "This will update all geofiles."