Add forced startup updater
This commit is contained in:
1 parent
9ffbe47bdb
commit
d48fa4eec3
9 files changed
+493
No files matched your search
@@ -99,6 +99,7 @@ os.environ.setdefault("OMP_NUM_THREADS", "1")
|
||||
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
from douyin.license.license_manager import require_license_or_exit
|
||||
from douyin.updater.force_update import run_startup_update_check
|
||||
|
||||
|
||||
def ensure_adb_in_path() -> None:
|
||||
@@ -340,6 +341,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
run_startup_update_check(app_name="run_cli")
|
||||
require_license_or_exit()
|
||||
ensure_adb_in_path()
|
||||
args = parse_args(argv)
|
||||
|
||||
@@ -2,6 +2,19 @@
|
||||
"needswitch": true,
|
||||
"infinite_loop_enabled": true,
|
||||
"wait_minutes": 5,
|
||||
"auto_update": {
|
||||
"enabled": false,
|
||||
"manifest_url": "",
|
||||
"fail_closed": true,
|
||||
"require_sha256": true,
|
||||
"timeout_seconds": 20,
|
||||
"installer_args": [
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER"
|
||||
]
|
||||
},
|
||||
"min_prize_value_yuan": 300.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""客户端更新检查模块。"""
|
||||
@@ -0,0 +1,284 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urljoin, urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.core.version import VERSION
|
||||
|
||||
|
||||
DEFAULT_INSTALLER_ARGS = (
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER",
|
||||
)
|
||||
|
||||
|
||||
class UpdateError(RuntimeError):
|
||||
"""强制更新失败。"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UpdateSettings:
|
||||
enabled: bool
|
||||
manifest_url: str
|
||||
download_dir: Path
|
||||
installer_args: tuple[str, ...] = DEFAULT_INSTALLER_ARGS
|
||||
timeout_seconds: float = 20.0
|
||||
fail_closed: bool = True
|
||||
require_sha256: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UpdateResult:
|
||||
status: str
|
||||
message: str = ""
|
||||
exit_required: bool = False
|
||||
version: str = ""
|
||||
installer_path: Path | None = None
|
||||
|
||||
|
||||
FetchManifest = Callable[[str, float], dict[str, Any]]
|
||||
DownloadFile = Callable[[str, Path, float], None]
|
||||
LaunchInstaller = Callable[[list[str]], None]
|
||||
|
||||
|
||||
def _to_bool(value: Any, default: bool = False) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if value is None:
|
||||
return default
|
||||
text = str(value).strip().lower()
|
||||
if text in {"1", "true", "yes", "y", "on", "启用", "是"}:
|
||||
return True
|
||||
if text in {"0", "false", "no", "n", "off", "禁用", "否"}:
|
||||
return False
|
||||
return default
|
||||
|
||||
|
||||
def _version_parts(value: str) -> list[int]:
|
||||
text = str(value or "").strip().lstrip("Vv")
|
||||
parts = re.split(r"[^0-9]+", text)
|
||||
nums = [int(p) for p in parts if p != ""]
|
||||
return nums or [0]
|
||||
|
||||
|
||||
def compare_versions(left: str, right: str) -> int:
|
||||
"""比较语义化版本号,支持 V 前缀。"""
|
||||
a = _version_parts(left)
|
||||
b = _version_parts(right)
|
||||
size = max(len(a), len(b))
|
||||
a.extend([0] * (size - len(a)))
|
||||
b.extend([0] * (size - len(b)))
|
||||
if a > b:
|
||||
return 1
|
||||
if a < b:
|
||||
return -1
|
||||
return 0
|
||||
|
||||
|
||||
def _read_config() -> dict[str, Any]:
|
||||
try:
|
||||
cfg_path = path_config.get_config_path()
|
||||
if not os.path.exists(cfg_path):
|
||||
return {}
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
obj = json.load(f)
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _as_path(value: Any, default: Path) -> Path:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return default
|
||||
path = Path(text)
|
||||
if not path.is_absolute():
|
||||
path = Path(path_config.get_project_root()) / path
|
||||
return path
|
||||
|
||||
|
||||
def _as_installer_args(value: Any) -> tuple[str, ...]:
|
||||
if isinstance(value, list):
|
||||
items = tuple(str(x).strip() for x in value if str(x).strip())
|
||||
return items or DEFAULT_INSTALLER_ARGS
|
||||
if isinstance(value, str) and value.strip():
|
||||
return tuple(x for x in value.split() if x) or DEFAULT_INSTALLER_ARGS
|
||||
return DEFAULT_INSTALLER_ARGS
|
||||
|
||||
|
||||
def load_update_settings() -> UpdateSettings:
|
||||
cfg = _read_config()
|
||||
section = cfg.get("auto_update") if isinstance(cfg.get("auto_update"), dict) else {}
|
||||
manifest_url = (
|
||||
os.environ.get("DOUYIN_UPDATE_MANIFEST_URL", "")
|
||||
or str(section.get("manifest_url", "") or "")
|
||||
or str(cfg.get("update_manifest_url", "") or "")
|
||||
).strip()
|
||||
env_enabled = os.environ.get("DOUYIN_AUTO_UPDATE_ENABLED")
|
||||
enabled = _to_bool(env_enabled, default=_to_bool(section.get("enabled"), False))
|
||||
if os.environ.get("DOUYIN_DISABLE_AUTO_UPDATE", "").strip() == "1":
|
||||
enabled = False
|
||||
if not manifest_url:
|
||||
enabled = False
|
||||
|
||||
default_download_dir = Path(path_config.get_state_dir()) / "updates"
|
||||
timeout_raw = section.get("timeout_seconds", 20.0)
|
||||
try:
|
||||
timeout_seconds = max(3.0, float(timeout_raw))
|
||||
except Exception:
|
||||
timeout_seconds = 20.0
|
||||
|
||||
return UpdateSettings(
|
||||
enabled=enabled,
|
||||
manifest_url=manifest_url,
|
||||
download_dir=_as_path(section.get("download_dir"), default_download_dir),
|
||||
installer_args=_as_installer_args(section.get("installer_args")),
|
||||
timeout_seconds=timeout_seconds,
|
||||
fail_closed=_to_bool(section.get("fail_closed"), True),
|
||||
require_sha256=_to_bool(section.get("require_sha256"), True),
|
||||
)
|
||||
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict[str, Any]:
|
||||
req = Request(url, headers={"User-Agent": f"douyin-guaji-updater/{VERSION}"})
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read()
|
||||
obj = json.loads(raw.decode("utf-8-sig"))
|
||||
if not isinstance(obj, dict):
|
||||
raise UpdateError("manifest 不是 JSON 对象")
|
||||
return obj
|
||||
|
||||
|
||||
def download_file(url: str, dest: Path, timeout: float) -> None:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = dest.with_name(dest.name + ".download")
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
req = Request(url, headers={"User-Agent": f"douyin-guaji-updater/{VERSION}"})
|
||||
with urlopen(req, timeout=timeout) as resp, tmp.open("wb") as f:
|
||||
while True:
|
||||
chunk = resp.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
if dest.exists():
|
||||
dest.unlink()
|
||||
tmp.replace(dest)
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _safe_installer_name(manifest: dict[str, Any], download_url: str, version: str) -> str:
|
||||
raw = str(manifest.get("filename") or Path(urlparse(download_url).path).name or "").strip()
|
||||
if not raw.lower().endswith(".exe"):
|
||||
raw = f"DouyinGuaji-{version}-Setup.exe"
|
||||
return re.sub(r'[<>:"/\\|?*]+', "_", raw)
|
||||
|
||||
|
||||
def launch_installer(cmd: list[str]) -> None:
|
||||
creationflags = 0
|
||||
if sys.platform.startswith("win"):
|
||||
creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
||||
subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(Path(cmd[0]).parent),
|
||||
close_fds=True,
|
||||
creationflags=creationflags,
|
||||
)
|
||||
|
||||
|
||||
def perform_forced_update(
|
||||
settings: UpdateSettings,
|
||||
*,
|
||||
current_version: str = VERSION,
|
||||
fetch_manifest: FetchManifest = fetch_manifest,
|
||||
download_file: DownloadFile = download_file,
|
||||
launch_installer: LaunchInstaller = launch_installer,
|
||||
) -> UpdateResult:
|
||||
if not settings.enabled:
|
||||
return UpdateResult("disabled", "未配置更新服务器")
|
||||
|
||||
manifest = fetch_manifest(settings.manifest_url, settings.timeout_seconds)
|
||||
latest_version = str(manifest.get("version", "") or "").strip()
|
||||
if not latest_version:
|
||||
raise UpdateError("manifest 缺少 version")
|
||||
if compare_versions(latest_version, current_version) <= 0:
|
||||
return UpdateResult("up_to_date", "已是最新版本", version=latest_version)
|
||||
|
||||
raw_url = str(manifest.get("url") or manifest.get("installer_url") or "").strip()
|
||||
if not raw_url:
|
||||
raise UpdateError("manifest 缺少 url")
|
||||
download_url = urljoin(settings.manifest_url, raw_url)
|
||||
expected_sha = str(manifest.get("sha256") or "").strip().lower()
|
||||
if settings.require_sha256 and not re.fullmatch(r"[0-9a-fA-F]{64}", expected_sha):
|
||||
raise UpdateError("manifest 缺少有效 sha256")
|
||||
|
||||
installer_name = _safe_installer_name(manifest, download_url, latest_version)
|
||||
installer_path = settings.download_dir / installer_name
|
||||
installer_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
download_file(download_url, installer_path, settings.timeout_seconds)
|
||||
|
||||
if expected_sha:
|
||||
actual_sha = _sha256(installer_path)
|
||||
if actual_sha.lower() != expected_sha.lower():
|
||||
try:
|
||||
installer_path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise UpdateError(f"sha256 校验失败: expected={expected_sha} actual={actual_sha}")
|
||||
|
||||
cmd = [str(installer_path), *settings.installer_args]
|
||||
launch_installer(cmd)
|
||||
return UpdateResult(
|
||||
"update_started",
|
||||
f"发现新版本 {latest_version},已启动安装器",
|
||||
exit_required=True,
|
||||
version=latest_version,
|
||||
installer_path=installer_path,
|
||||
)
|
||||
|
||||
|
||||
def run_startup_update_check(
|
||||
*,
|
||||
app_name: str,
|
||||
current_version: str = VERSION,
|
||||
perform_update: Callable[..., UpdateResult] = perform_forced_update,
|
||||
) -> UpdateResult:
|
||||
settings = load_update_settings()
|
||||
try:
|
||||
result = perform_update(settings=settings, current_version=current_version)
|
||||
except UpdateError as exc:
|
||||
message = f"[更新] {app_name} 强制更新失败:{exc}"
|
||||
print(message, file=sys.stderr)
|
||||
if settings.enabled and settings.fail_closed:
|
||||
raise SystemExit(3)
|
||||
return UpdateResult("error", message)
|
||||
except Exception as exc:
|
||||
message = f"[更新] {app_name} 强制更新检查异常:{exc}"
|
||||
print(message, file=sys.stderr)
|
||||
if settings.enabled and settings.fail_closed:
|
||||
raise SystemExit(3)
|
||||
return UpdateResult("error", message)
|
||||
|
||||
if result.exit_required:
|
||||
print(f"[更新] {app_name}: {result.message}")
|
||||
raise SystemExit(0)
|
||||
return result
|
||||
@@ -16,6 +16,7 @@ from gui.gui_core import (
|
||||
)
|
||||
from douyin.core.path_config import get_logs_dir
|
||||
from douyin.license.license_manager import require_license_or_exit
|
||||
from douyin.updater.force_update import run_startup_update_check
|
||||
from gui.components.wifi_adb_scan_dialog import open_scan_dialog # noqa: F401 re-export
|
||||
from gui.components.preview_view import (
|
||||
async_refresh_preview as _async_refresh_preview_impl,
|
||||
@@ -54,6 +55,7 @@ def format_gui_log_line(line: str) -> str: # noqa: F401 re-export for backward
|
||||
|
||||
|
||||
def main():
|
||||
run_startup_update_check(app_name="gui_app")
|
||||
require_license_or_exit()
|
||||
_bundle = setup_root_window(read_config=read_config)
|
||||
root = _bundle.root
|
||||
|
||||
@@ -20,6 +20,7 @@ if project_root not in sys.path:
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import require_license_or_exit
|
||||
from douyin.updater.force_update import run_startup_update_check
|
||||
|
||||
# 从子包 re-export 顶层 helper(保持兼容)
|
||||
from gui.web_gui_pkg import (
|
||||
@@ -841,6 +842,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
|
||||
def main() -> int:
|
||||
run_startup_update_check(app_name="web_gui")
|
||||
require_license_or_exit()
|
||||
host = get_web_gui_host()
|
||||
# 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.com/downloads/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": "替换为安装包的 SHA256",
|
||||
"force": true,
|
||||
"notes": "强制更新说明"
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_compare_versions_handles_v_prefix_and_patch_order():
|
||||
from douyin.updater.force_update import compare_versions
|
||||
|
||||
assert compare_versions("V3.3.10", "3.3.9") > 0
|
||||
assert compare_versions("3.3.3", "V3.3.3") == 0
|
||||
assert compare_versions("3.3.2", "3.3.3") < 0
|
||||
|
||||
|
||||
def test_load_settings_is_disabled_without_manifest_url(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater.force_update import load_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({"auto_update": {"enabled": True}}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
|
||||
settings = load_update_settings()
|
||||
|
||||
assert settings.enabled is False
|
||||
assert settings.manifest_url == ""
|
||||
|
||||
|
||||
def test_forced_update_downloads_verifies_and_launches_installer(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
payload = b"fake installer bytes"
|
||||
expected_sha = hashlib.sha256(payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
installer_args=("/VERYSILENT", "/CURRENTUSER"),
|
||||
)
|
||||
downloaded: list[str] = []
|
||||
launched: list[list[str]] = []
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
assert url == settings.manifest_url
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": expected_sha,
|
||||
"force": True,
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
assert dest.parent.exists()
|
||||
dest.write_bytes(payload)
|
||||
|
||||
def launch(cmd: list[str]) -> None:
|
||||
launched.append(cmd)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=launch,
|
||||
)
|
||||
|
||||
assert result.status == "update_started"
|
||||
assert result.exit_required is True
|
||||
assert downloaded == ["https://example.test/DouyinGuaji-3.3.4-Setup.exe"]
|
||||
assert launched == [
|
||||
[str(tmp_path / "DouyinGuaji-3.3.4-Setup.exe"), "/VERYSILENT", "/CURRENTUSER"]
|
||||
]
|
||||
|
||||
|
||||
def test_forced_update_rejects_hash_mismatch(tmp_path):
|
||||
from douyin.updater.force_update import (
|
||||
UpdateError,
|
||||
UpdateSettings,
|
||||
perform_forced_update,
|
||||
)
|
||||
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
)
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": "0" * 64,
|
||||
"force": True,
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
dest.write_bytes(b"tampered")
|
||||
|
||||
with pytest.raises(UpdateError, match="sha256"):
|
||||
perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: None,
|
||||
)
|
||||
|
||||
|
||||
def test_forced_update_ignores_manifest_force_false_for_newer_version(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
payload = b"forced installer"
|
||||
expected_sha = hashlib.sha256(payload).hexdigest()
|
||||
launched: list[list[str]] = []
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": expected_sha,
|
||||
"force": False,
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
dest.write_bytes(payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
UpdateSettings(enabled=True, manifest_url="https://example.test/update.json", download_dir=tmp_path),
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: launched.append(cmd),
|
||||
)
|
||||
|
||||
assert result.status == "update_started"
|
||||
assert launched
|
||||
|
||||
|
||||
def test_startup_update_raises_system_exit_after_launch(tmp_path):
|
||||
from douyin.updater.force_update import UpdateResult, run_startup_update_check
|
||||
|
||||
called: list[str] = []
|
||||
|
||||
def perform(*, settings, current_version):
|
||||
called.append(current_version)
|
||||
return UpdateResult("update_started", "started", exit_required=True)
|
||||
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
run_startup_update_check(
|
||||
app_name="test_app",
|
||||
current_version="3.3.3",
|
||||
perform_update=perform,
|
||||
)
|
||||
|
||||
assert exc.value.code == 0
|
||||
assert called == ["3.3.3"]
|
||||
|
||||
|
||||
def test_startup_update_fail_closed_blocks_old_client(tmp_path, monkeypatch):
|
||||
from douyin.updater.force_update import UpdateError, run_startup_update_check
|
||||
|
||||
monkeypatch.setenv("DOUYIN_AUTO_UPDATE_ENABLED", "1")
|
||||
monkeypatch.setenv("DOUYIN_UPDATE_MANIFEST_URL", "https://example.test/update.json")
|
||||
|
||||
def perform(*, settings, current_version):
|
||||
raise UpdateError("network down")
|
||||
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
run_startup_update_check(
|
||||
app_name="test_app",
|
||||
current_version="3.3.3",
|
||||
perform_update=perform,
|
||||
)
|
||||
|
||||
assert exc.value.code == 3
|
||||
@@ -14,6 +14,8 @@ def _write(path: Path, text: str = "x = 1\n") -> None:
|
||||
def _make_minimal_project(root: Path) -> None:
|
||||
_write(root / "douyin" / "__init__.py")
|
||||
_write(root / "douyin" / "core" / "version.py")
|
||||
_write(root / "douyin" / "updater" / "__init__.py")
|
||||
_write(root / "douyin" / "updater" / "force_update.py")
|
||||
_write(root / "gui" / "gui_app.py")
|
||||
_write(root / "gui" / "web_gui.py")
|
||||
_write(root / "gui" / "components" / "left_config_area.py")
|
||||
|
||||
Reference in new issue
Block a user