Files
douyi_guaji_main/douyin/updater/force_update.py
T

417 lines
14 KiB
Python

from __future__ import annotations
import base64
import hashlib
import json
import os
import re
import shlex
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 cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from douyin.core import path_config
from douyin.core.version import VERSION
from douyin.license.public_key import PUBLIC_KEY_PEM
DEFAULT_INSTALLER_ARGS = (
"/VERYSILENT",
"/SUPPRESSMSGBOXES",
"/NORESTART",
"/CURRENTUSER",
)
DEFAULT_UPDATE_MANIFEST_URL = "http://dy.absfan.cn:18100/api/v1/update/manifest"
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
require_https: bool = True
allow_cross_origin: bool = False
require_signed_manifest: bool = False
@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 _canonical_payload_bytes(payload: dict[str, Any]) -> bytes:
return json.dumps(
payload,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
def _verify_manifest_signature(manifest: dict[str, Any]) -> None:
signature_raw = manifest.get("signature")
if not isinstance(signature_raw, str) or not signature_raw.strip():
raise UpdateError("manifest 缺少签名")
payload = dict(manifest)
payload.pop("signature", None)
try:
signature = base64.b64decode(signature_raw.encode("ascii"), validate=True)
public_key = serialization.load_pem_public_key(PUBLIC_KEY_PEM)
public_key.verify(signature, _canonical_payload_bytes(payload))
except InvalidSignature as exc:
raise UpdateError("manifest 签名校验失败") from exc
except UpdateError:
raise
except Exception as exc:
raise UpdateError(f"manifest 签名校验异常:{exc}") from exc
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")
using_default_manifest = False
if not manifest_url and getattr(sys, "frozen", False):
manifest_url = DEFAULT_UPDATE_MANIFEST_URL
using_default_manifest = True
enabled_default = True if using_default_manifest else _to_bool(section.get("enabled"), False)
enabled = _to_bool(env_enabled, default=enabled_default)
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),
require_https=_to_bool(section.get("require_https"), not using_default_manifest),
allow_cross_origin=_to_bool(section.get("allow_cross_origin"), False),
require_signed_manifest=_to_bool(section.get("require_signed_manifest"), using_default_manifest),
)
def _origin(value: str) -> tuple[str, str, int]:
parsed = urlparse(value)
scheme = (parsed.scheme or "").lower()
host = (parsed.hostname or "").lower()
port = parsed.port
if port is None:
port = 443 if scheme == "https" else 80 if scheme == "http" else -1
return scheme, host, port
def _validate_manifest_url(settings: UpdateSettings) -> None:
parsed = urlparse(settings.manifest_url)
if settings.require_https and parsed.scheme.lower() != "https":
raise UpdateError("manifest_url 必须使用 HTTPS")
if not parsed.scheme or not parsed.netloc:
raise UpdateError("manifest_url 必须是完整 URL")
def _validate_installer_url(settings: UpdateSettings, download_url: str) -> None:
parsed = urlparse(download_url)
if settings.require_https and parsed.scheme.lower() != "https":
raise UpdateError("安装包 URL 必须使用 HTTPS")
if not parsed.scheme or not parsed.netloc:
raise UpdateError("安装包 URL 必须是完整 URL")
if not settings.allow_cross_origin and _origin(download_url) != _origin(settings.manifest_url):
raise UpdateError("安装包 URL 必须与 manifest 同源")
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 _installer_log_arg(version: str) -> str:
safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "unknown"))
log_dir = Path(path_config.get_logs_dir()) / "updates"
log_dir.mkdir(parents=True, exist_ok=True)
return f"/LOG={log_dir / f'installer-{safe_version}.log'}"
def _build_installer_cmd(
installer_path: Path,
installer_args: tuple[str, ...],
version: str,
) -> list[str]:
args = [str(x) for x in installer_args]
if not any(arg.upper().startswith("/LOG") for arg in args):
args.append(_installer_log_arg(version))
return [str(installer_path), *args]
def launch_installer(cmd: list[str]) -> None:
cwd = str(Path(cmd[0]).parent)
if sys.platform.startswith("win"):
parent_pid = os.getpid()
quoted_args = ", ".join(_ps_quote(arg) for arg in cmd[1:])
script = (
f"Wait-Process -Id {parent_pid} -ErrorAction SilentlyContinue; "
"$p = Start-Process "
f"-FilePath {_ps_quote(cmd[0])} "
f"-ArgumentList @({quoted_args}) "
"-Wait -PassThru; "
"exit $p.ExitCode"
)
subprocess.Popen(
[
"powershell",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-WindowStyle",
"Hidden",
"-Command",
script,
],
cwd=cwd,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
close_fds=True,
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
)
return
creationflags = 0
subprocess.Popen(
cmd,
cwd=cwd,
close_fds=True,
creationflags=creationflags,
)
def _ps_quote(value: str) -> str:
text = str(value)
if sys.platform.startswith("win"):
return "'" + text.replace("'", "''") + "'"
return shlex.quote(text)
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", "未配置更新服务器")
_validate_manifest_url(settings)
manifest = fetch_manifest(settings.manifest_url, settings.timeout_seconds)
if settings.require_signed_manifest:
_verify_manifest_signature(manifest)
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)
_validate_installer_url(settings, download_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 = _build_installer_cmd(installer_path, settings.installer_args, latest_version)
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