Files
douyi_guaji_main/douyin/updater/force_update.py
T

602 lines
22 KiB
Python

from __future__ import annotations
import base64
import hashlib
import json
import os
import re
import shlex
import subprocess
import sys
import zipfile
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 = "https://dy.absfan.cn/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
delta_path: Path | None = None
FetchManifest = Callable[[str, float], dict[str, Any]]
DownloadFile = Callable[[str, Path, float], None]
LaunchInstaller = Callable[[list[str]], None]
LaunchDeltaUpdate = Callable[[Path, 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 _validate_download_url(settings: UpdateSettings, download_url: str, label: str) -> None:
parsed = urlparse(download_url)
if settings.require_https and parsed.scheme.lower() != "https":
raise UpdateError(f"{label} URL 必须使用 HTTPS")
if not parsed.scheme or not parsed.netloc:
raise UpdateError(f"{label} URL 必须是完整 URL")
if not settings.allow_cross_origin and _origin(download_url) != _origin(settings.manifest_url):
raise UpdateError(f"{label} 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 _safe_delta_name(delta: dict[str, Any], download_url: str, version: str) -> str:
raw = str(delta.get("filename") or Path(urlparse(download_url).path).name or "").strip()
if not raw.lower().endswith(".zip"):
raw = f"DouyinGuaji-delta-{version}.zip"
return re.sub(r'[<>:"/\\|?*]+', "_", raw)
def _safe_delta_path(raw_path: Any) -> str:
rel = str(raw_path or "").replace("\\", "/").strip("/")
parts = [part for part in rel.split("/") if part]
if not parts or any(part in {".", ".."} for part in parts):
raise UpdateError(f"差量包包含非法路径:{raw_path}")
if Path(rel).is_absolute() or ":" in parts[0]:
raise UpdateError(f"差量包包含非法路径:{raw_path}")
return "/".join(parts)
def _matching_delta(manifest: dict[str, Any], current_version: str, latest_version: str) -> dict[str, Any] | None:
raw = manifest.get("delta")
candidates: list[Any]
if isinstance(raw, list):
candidates = raw
elif isinstance(raw, dict):
candidates = [raw]
else:
return None
for item in candidates:
if not isinstance(item, dict):
continue
from_version = str(item.get("from_version") or "").strip().lstrip("Vv")
to_version = str(item.get("to_version") or latest_version).strip().lstrip("Vv")
if compare_versions(from_version, current_version) == 0 and compare_versions(to_version, latest_version) == 0:
return dict(item)
return None
def validate_delta_package(delta_path: Path, *, current_version: str, latest_version: str) -> dict[str, Any]:
try:
with zipfile.ZipFile(delta_path) as zf:
for info in zf.infolist():
name = info.filename.replace("\\", "/")
if name.endswith("/"):
continue
if name != "manifest.json" and not name.startswith("files/"):
raise UpdateError(f"差量包包含未知条目:{info.filename}")
if name.startswith("files/"):
_safe_delta_path(name[len("files/"):])
try:
manifest = json.loads(zf.read("manifest.json").decode("utf-8-sig"))
except KeyError as exc:
raise UpdateError("差量包缺少 manifest.json") from exc
except Exception as exc:
raise UpdateError(f"差量包 manifest 读取失败:{exc}") from exc
if not isinstance(manifest, dict):
raise UpdateError("差量包 manifest 格式错误")
if compare_versions(str(manifest.get("from_version") or ""), current_version) != 0:
raise UpdateError("差量包来源版本不匹配")
if compare_versions(str(manifest.get("to_version") or ""), latest_version) != 0:
raise UpdateError("差量包目标版本不匹配")
for item in manifest.get("files") or []:
if not isinstance(item, dict):
raise UpdateError("差量包文件列表格式错误")
rel = _safe_delta_path(item.get("path"))
zip_name = f"files/{rel}"
if zip_name not in zf.namelist():
raise UpdateError(f"差量包缺少文件:{rel}")
expected = str(item.get("sha256") or "").strip().lower()
if not re.fullmatch(r"[0-9a-fA-F]{64}", expected):
raise UpdateError(f"差量包文件缺少有效 sha256:{rel}")
actual = hashlib.sha256(zf.read(zip_name)).hexdigest()
if actual.lower() != expected:
raise UpdateError(f"差量包文件校验失败:{rel}")
for rel in manifest.get("delete") or []:
_safe_delta_path(rel)
return manifest
except zipfile.BadZipFile as exc:
raise UpdateError("差量包不是有效 zip") from exc
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 _install_root() -> Path:
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(path_config.get_project_root()).resolve()
def _delta_log_path(version: str) -> Path:
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 log_dir / f"delta-{safe_version}.log"
def launch_delta_update(delta_path: Path, version: str) -> None:
install_root = _install_root()
work_dir = delta_path.parent / f"{delta_path.stem}.apply"
log_path = _delta_log_path(version)
parent_pid = os.getpid()
script = (
"$ErrorActionPreference = 'Stop'; "
f"Wait-Process -Id {parent_pid} -ErrorAction SilentlyContinue; "
f"$zip = {_ps_quote(str(delta_path))}; "
f"$root = {_ps_quote(str(install_root))}; "
f"$work = {_ps_quote(str(work_dir))}; "
f"$log = {_ps_quote(str(log_path))}; "
"New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null; "
"if (Test-Path $work) { Remove-Item -LiteralPath $work -Recurse -Force }; "
"New-Item -ItemType Directory -Force -Path $work | Out-Null; "
"Expand-Archive -LiteralPath $zip -DestinationPath $work -Force; "
"$manifest = Get-Content -LiteralPath (Join-Path $work 'manifest.json') -Raw | ConvertFrom-Json; "
"foreach ($rel in $manifest.delete) { "
" $target = Join-Path $root $rel; "
" if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } "
"}; "
"foreach ($file in $manifest.files) { "
" $src = Join-Path (Join-Path $work 'files') $file.path; "
" $dst = Join-Path $root $file.path; "
" New-Item -ItemType Directory -Force -Path (Split-Path $dst) | Out-Null; "
" Copy-Item -LiteralPath $src -Destination $dst -Force "
"}; "
"'delta update applied' | Out-File -LiteralPath $log -Encoding utf8 -Append; "
"Remove-Item -LiteralPath $work -Recurse -Force"
)
subprocess.Popen(
[
"powershell",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-WindowStyle",
"Hidden",
"-Command",
script,
],
cwd=str(install_root),
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
close_fds=True,
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
)
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,
launch_delta_update: LaunchDeltaUpdate = launch_delta_update,
) -> 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)
delta = _matching_delta(manifest, current_version, latest_version)
if delta:
raw_delta_url = str(delta.get("url") or "").strip()
delta_sha = str(delta.get("sha256") or "").strip().lower()
if raw_delta_url and (not settings.require_sha256 or re.fullmatch(r"[0-9a-fA-F]{64}", delta_sha)):
delta_url = urljoin(settings.manifest_url, raw_delta_url)
_validate_download_url(settings, delta_url, "差量包")
delta_name = _safe_delta_name(delta, delta_url, latest_version)
delta_path = settings.download_dir / delta_name
delta_path.parent.mkdir(parents=True, exist_ok=True)
download_file(delta_url, delta_path, settings.timeout_seconds)
if delta_sha:
actual_sha = _sha256(delta_path)
if actual_sha.lower() != delta_sha:
try:
delta_path.unlink()
except Exception:
pass
raise UpdateError(f"差量包 sha256 校验失败: expected={delta_sha} actual={actual_sha}")
validate_delta_package(delta_path, current_version=current_version, latest_version=latest_version)
launch_delta_update(delta_path, latest_version)
return UpdateResult(
"delta_update_started",
f"发现新版本 {latest_version},已启动差量更新",
exit_required=True,
version=latest_version,
delta_path=delta_path,
)
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