# -*- coding: utf-8 -*- """执行机壳子(主程序)自动更新:自动下载新版安装包,由用户点击触发静默升级重启。 流程(对应前端交互): 1. 检查+下载:启动时后台检查控制面 /api/shell/version,版本落后则自动把新版安装包 下载到 %LOCALAPPDATA%\\37duAutomation\\shell\\(本地缓存,不打断用户)。 2. 应用:前端提示"发现新版本"后用户点击 → apply_update() 运行安装包 /VERYSILENT 静默覆盖安装,随后本进程退出,Inno CloseApplications 收尾, 安装完成由 [Run] 自动重启新版本主程序。 3. 离线/控制面不可达/校验失败:静默跳过,不影响使用。 """ from __future__ import annotations import hashlib import logging import os import subprocess import sys import time from pathlib import Path from webhost.backend import config _LOGGER = logging.getLogger(__name__) # 下载缓存的安装包目录:独立于程序目录(升级时不被覆盖/清理) _SHELL_CACHE = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "shell" # 已下载待应用的新版本(模块内状态,供 update-status 查询) _PENDING: dict = {} def local_shell_version() -> str: """本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。""" if not getattr(sys, "frozen", False): return "" vf = Path(sys.executable).resolve().parent / "shell.version" try: return vf.read_text(encoding="utf-8").strip() if vf.is_file() else "" except OSError: return "" def _headers() -> dict: h = {} if config.CONTROLPLANE_TOKEN: h["X-API-Token"] = config.CONTROLPLANE_TOKEN return h def _version_lt(a: str, b: str) -> bool: def _key(v: str): return [int(x) if x.isdigit() else x for x in str(v).split(".")] try: return _key(a) < _key(b) except Exception: # noqa: BLE001 return a != b and a < b def check_and_download() -> dict | None: """检查壳子更新并自动下载安装包到本地缓存。有可用更新返回 {version, notes};否则 None。""" cur = local_shell_version() if not cur or not config.CONTROLPLANE_URL: return None import requests try: r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/version", headers=_headers(), timeout=5) r.raise_for_status() info = r.json() except Exception as _exc: # noqa: BLE001 离线/不可达 _LOGGER.info("检查壳子更新失败(离线跳过):%s", _exc) return None if not info.get("available") or not info.get("version"): return None cloud = str(info["version"]) if not _version_lt(cur, cloud): return None try: r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/pkg", headers=_headers(), timeout=300) r.raise_for_status() data = r.content except Exception as _exc: # noqa: BLE001 _LOGGER.warning("下载壳子安装包失败:%s", _exc) return None expect = (info.get("sha256") or "").lower() if expect and hashlib.sha256(data).hexdigest() != expect: _LOGGER.error("壳子安装包 sha256 校验失败,放弃更新") return None try: _SHELL_CACHE.mkdir(parents=True, exist_ok=True) pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe" pkg.write_bytes(data) except OSError as _exc: # noqa: BLE001 _LOGGER.warning("壳子安装包落盘失败:%s", _exc) return None _PENDING["version"] = cloud _PENDING["notes"] = info.get("notes", "") _LOGGER.info("壳子新版本已下载待应用:%s → %s(%d 字节)", cur, cloud, len(data)) return {"version": cloud, "notes": _PENDING["notes"]} def cached_pkg(version: str) -> Path | None: """本地缓存的指定版本安装包路径;不存在返回 None。""" p = _SHELL_CACHE / f"setup-37du-host-{version}.exe" return p if p.is_file() else None def pending_status() -> dict: """当前更新状态(供前端提示):当前版本 / 待应用新版本 / 是否已下载。""" return { "current": local_shell_version(), "new": _PENDING.get("version", ""), "notes": _PENDING.get("notes", ""), "downloaded": bool(_PENDING.get("version")) and cached_pkg(_PENDING.get("version", "")) is not None, } def apply_update() -> None: """运行新版安装包静默覆盖安装并退出本进程(升级完成后由 Inno 重启新版本)。 注意:本函数在返回前 os._exit(0) 退出整个进程,调用方无需继续处理。 """ version = _PENDING.get("version", "") pkg = cached_pkg(version) if not pkg: raise FileNotFoundError(f"未找到已下载的安装包:setup-37du-host-{version}.exe") _LOGGER.info("开始静默升级到 %s:%s", version, pkg) subprocess.Popen( [str(pkg), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"], cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) time.sleep(1) # 给安装器接管进程,随后退出让 Inno CloseApplications 收尾 os._exit(0)