834 lines
32 KiB
Python
834 lines
32 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, replace
|
|
from datetime import datetime, timezone
|
|
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 = (
|
|
"/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
|
|
allow_delta: 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]
|
|
ProgressCallback = Callable[[dict[str, Any]], 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:
|
|
manifest_url = DEFAULT_UPDATE_MANIFEST_URL
|
|
using_default_manifest = True
|
|
enabled_default = _to_bool(section.get("enabled"), True)
|
|
enabled = _to_bool(env_enabled, default=enabled_default)
|
|
if os.environ.get("DOUYIN_DISABLE_AUTO_UPDATE", "").strip() == "1":
|
|
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),
|
|
allow_delta=_to_bool(
|
|
os.environ.get("DOUYIN_UPDATE_ALLOW_DELTA", section.get("allow_delta")),
|
|
False,
|
|
),
|
|
)
|
|
|
|
|
|
def load_manual_update_settings() -> UpdateSettings:
|
|
"""Load settings for an explicit user-triggered update check.
|
|
|
|
The manual button should report errors in the UI instead of exiting the
|
|
process through the startup fail-closed path.
|
|
"""
|
|
settings = load_update_settings()
|
|
return replace(settings, enabled=True, fail_closed=False)
|
|
|
|
|
|
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,
|
|
progress_callback: Callable[[int, int], None] | None = None,
|
|
) -> 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:
|
|
total = 0
|
|
try:
|
|
total = int(resp.headers.get("Content-Length") or 0)
|
|
except Exception:
|
|
total = 0
|
|
done = 0
|
|
while True:
|
|
chunk = resp.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
f.write(chunk)
|
|
done += len(chunk)
|
|
if progress_callback:
|
|
try:
|
|
progress_callback(done, total)
|
|
except Exception:
|
|
pass
|
|
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 _delta_attempt_state_path(settings: UpdateSettings) -> Path:
|
|
return settings.download_dir / "delta_attempt_state.json"
|
|
|
|
|
|
def _delta_attempt_key(delta: dict[str, Any], current_version: str, latest_version: str) -> str:
|
|
filename = str(delta.get("filename") or delta.get("url") or "").strip()
|
|
sha = str(delta.get("sha256") or "").strip().lower()
|
|
return "|".join([str(current_version), str(latest_version), filename, sha])
|
|
|
|
|
|
def _read_delta_attempt_state(settings: UpdateSettings) -> dict[str, Any]:
|
|
path = _delta_attempt_state_path(settings)
|
|
try:
|
|
obj = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
return obj if isinstance(obj, dict) else {}
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def _write_delta_attempt_state(settings: UpdateSettings, payload: dict[str, Any]) -> None:
|
|
path = _delta_attempt_state_path(settings)
|
|
try:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _clear_delta_attempt_state(settings: UpdateSettings) -> None:
|
|
try:
|
|
_delta_attempt_state_path(settings).unlink(missing_ok=True)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _should_skip_delta_after_previous_attempt(
|
|
settings: UpdateSettings,
|
|
delta: dict[str, Any],
|
|
current_version: str,
|
|
latest_version: str,
|
|
) -> bool:
|
|
state = _read_delta_attempt_state(settings)
|
|
if state.get("status") != "started":
|
|
return False
|
|
if state.get("key") != _delta_attempt_key(delta, current_version, latest_version):
|
|
return False
|
|
return compare_versions(current_version, latest_version) < 0
|
|
|
|
|
|
def _mark_delta_attempt_started(
|
|
settings: UpdateSettings,
|
|
delta: dict[str, Any],
|
|
current_version: str,
|
|
latest_version: str,
|
|
delta_path: Path,
|
|
) -> None:
|
|
_write_delta_attempt_state(
|
|
settings,
|
|
{
|
|
"status": "started",
|
|
"key": _delta_attempt_key(delta, current_version, latest_version),
|
|
"from_version": current_version,
|
|
"to_version": latest_version,
|
|
"filename": delta_path.name,
|
|
},
|
|
)
|
|
|
|
|
|
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 _update_client_log_path() -> Path:
|
|
log_dir = Path(path_config.get_logs_dir()) / "updates"
|
|
log_dir.mkdir(parents=True, exist_ok=True)
|
|
return log_dir / "update-client.log"
|
|
|
|
|
|
def _append_update_log(event: str, **fields: Any) -> None:
|
|
try:
|
|
payload = {
|
|
"time": datetime.now(timezone.utc).isoformat(),
|
|
"event": event,
|
|
**fields,
|
|
}
|
|
with _update_client_log_path().open("a", encoding="utf-8") as f:
|
|
f.write(json.dumps(payload, ensure_ascii=False, default=str) + "\n")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
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; "
|
|
"try { "
|
|
" ('delta update started ' + (Get-Date -Format o) + ' zip=' + $zip + ' root=' + $root) | Out-File -LiteralPath $log -Encoding utf8 -Append; "
|
|
" 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; "
|
|
" exit 0 "
|
|
"} catch { "
|
|
" ('delta update failed ' + (Get-Date -Format o) + ' error=' + $_.Exception.Message) | Out-File -LiteralPath $log -Encoding utf8 -Append; "
|
|
" if ($_.ScriptStackTrace) { $_.ScriptStackTrace | Out-File -LiteralPath $log -Encoding utf8 -Append }; "
|
|
" exit 1 "
|
|
"}"
|
|
)
|
|
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,
|
|
progress_callback: ProgressCallback | None = None,
|
|
) -> UpdateResult:
|
|
def emit_progress(stage: str, **fields: Any) -> None:
|
|
if progress_callback:
|
|
try:
|
|
progress_callback({"stage": stage, **fields})
|
|
except Exception:
|
|
pass
|
|
|
|
def call_download_file(
|
|
url: str,
|
|
dest: Path,
|
|
timeout: float,
|
|
*,
|
|
kind: str,
|
|
) -> None:
|
|
def on_bytes(done: int, total: int) -> None:
|
|
emit_progress("download_progress", kind=kind, done=done, total=total, path=str(dest), url=url)
|
|
|
|
try:
|
|
download_file(url, dest, timeout, on_bytes) # type: ignore[misc]
|
|
except TypeError:
|
|
download_file(url, dest, timeout)
|
|
|
|
if not settings.enabled:
|
|
return UpdateResult("disabled", "未配置更新服务器")
|
|
|
|
_validate_manifest_url(settings)
|
|
emit_progress("manifest_fetch", message="正在连接更新服务器")
|
|
manifest = fetch_manifest(settings.manifest_url, settings.timeout_seconds)
|
|
if settings.require_signed_manifest:
|
|
emit_progress("manifest_verify", message="正在校验更新签名")
|
|
_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:
|
|
_clear_delta_attempt_state(settings)
|
|
return UpdateResult("up_to_date", "已是最新版本", version=latest_version)
|
|
|
|
def launch_full_installer() -> UpdateResult:
|
|
emit_progress("full_prepare", message="准备下载完整安装包")
|
|
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)
|
|
emit_progress("full_download_start", kind="full", message=f"正在下载完整安装包 {installer_name}", path=str(installer_path), url=download_url)
|
|
call_download_file(download_url, installer_path, settings.timeout_seconds, kind="full")
|
|
|
|
if expected_sha:
|
|
emit_progress("full_verify", message="正在校验完整安装包")
|
|
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)
|
|
emit_progress("full_launch", message="正在启动安装器")
|
|
launch_installer(cmd)
|
|
_clear_delta_attempt_state(settings)
|
|
return UpdateResult(
|
|
"update_started",
|
|
f"发现新版本 {latest_version},已启动安装器",
|
|
exit_required=True,
|
|
version=latest_version,
|
|
installer_path=installer_path,
|
|
)
|
|
|
|
delta = _matching_delta(manifest, current_version, latest_version) if settings.allow_delta else None
|
|
if not delta:
|
|
unavailable_message = (
|
|
"未找到当前版本可用的差量包,准备下载完整安装包"
|
|
if settings.allow_delta
|
|
else "准备下载完整安装包"
|
|
)
|
|
emit_progress(
|
|
"delta_unavailable",
|
|
message=unavailable_message,
|
|
current_version=current_version,
|
|
latest_version=latest_version,
|
|
)
|
|
skip_delta = bool(delta and _should_skip_delta_after_previous_attempt(settings, delta, current_version, latest_version))
|
|
if delta and skip_delta:
|
|
emit_progress(
|
|
"delta_skipped",
|
|
message="上次差量更新未完成,准备回退完整安装包",
|
|
current_version=current_version,
|
|
latest_version=latest_version,
|
|
)
|
|
_append_update_log(
|
|
"delta_skip_after_previous_started_attempt",
|
|
current_version=current_version,
|
|
latest_version=latest_version,
|
|
delta_filename=delta.get("filename") or delta.get("url"),
|
|
)
|
|
if delta and not skip_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)):
|
|
try:
|
|
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)
|
|
emit_progress("delta_download_start", kind="delta", message=f"正在下载差量包 {delta_name}", path=str(delta_path), url=delta_url)
|
|
_append_update_log(
|
|
"delta_download_start",
|
|
current_version=current_version,
|
|
latest_version=latest_version,
|
|
url=delta_url,
|
|
path=str(delta_path),
|
|
)
|
|
call_download_file(delta_url, delta_path, settings.timeout_seconds, kind="delta")
|
|
if delta_sha:
|
|
emit_progress("delta_verify", message="正在校验差量包")
|
|
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}")
|
|
emit_progress("delta_validate", message="正在检查差量包内容")
|
|
validate_delta_package(delta_path, current_version=current_version, latest_version=latest_version)
|
|
_mark_delta_attempt_started(settings, delta, current_version, latest_version, delta_path)
|
|
_append_update_log(
|
|
"delta_launch_start",
|
|
current_version=current_version,
|
|
latest_version=latest_version,
|
|
path=str(delta_path),
|
|
sha256=delta_sha,
|
|
)
|
|
emit_progress("delta_launch", message="正在应用差量更新")
|
|
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,
|
|
)
|
|
except Exception as exc:
|
|
emit_progress("delta_failed", message="差量更新失败,准备回退完整安装包", error=f"{type(exc).__name__}: {exc}")
|
|
_append_update_log(
|
|
"delta_failed_fallback_full",
|
|
current_version=current_version,
|
|
latest_version=latest_version,
|
|
delta_filename=delta.get("filename") or delta.get("url"),
|
|
error=f"{type(exc).__name__}: {exc}",
|
|
)
|
|
_write_delta_attempt_state(
|
|
settings,
|
|
{
|
|
"status": "failed",
|
|
"key": _delta_attempt_key(delta, current_version, latest_version),
|
|
"from_version": current_version,
|
|
"to_version": latest_version,
|
|
"error": f"{type(exc).__name__}: {exc}",
|
|
},
|
|
)
|
|
|
|
return launch_full_installer()
|
|
|
|
|
|
def run_startup_update_check(
|
|
*,
|
|
app_name: str,
|
|
current_version: str = VERSION,
|
|
perform_update: Callable[..., UpdateResult] = perform_forced_update,
|
|
progress_callback: ProgressCallback | None = None,
|
|
) -> UpdateResult:
|
|
settings = load_update_settings()
|
|
try:
|
|
if progress_callback is None:
|
|
result = perform_update(settings=settings, current_version=current_version)
|
|
else:
|
|
result = perform_update(
|
|
settings=settings,
|
|
current_version=current_version,
|
|
progress_callback=progress_callback,
|
|
)
|
|
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
|