This commit is contained in:
1 parent
16019ee649
commit
329b7756f4
17 files changed
+754
-85
No files matched your search
@@ -71,6 +71,7 @@ def run_startup_update_check_early(
|
||||
app_name: str,
|
||||
*,
|
||||
update_check: Callable[..., object] | None = None,
|
||||
progress_callback: Callable[[dict[str, object]], None] | None = None,
|
||||
) -> None:
|
||||
"""Run the updater before importing the heavier app modules."""
|
||||
try:
|
||||
@@ -80,7 +81,10 @@ def run_startup_update_check_early(
|
||||
check = run_startup_update_check
|
||||
else:
|
||||
check = update_check
|
||||
check(app_name=app_name)
|
||||
if progress_callback is None:
|
||||
check(app_name=app_name)
|
||||
else:
|
||||
check(app_name=app_name, progress_callback=progress_callback)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as exc:
|
||||
|
||||
@@ -65,6 +65,7 @@ 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:
|
||||
@@ -256,18 +257,35 @@ def fetch_manifest(url: str, timeout: float) -> dict[str, Any]:
|
||||
return obj
|
||||
|
||||
|
||||
def download_file(url: str, dest: Path, timeout: float) -> None:
|
||||
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)
|
||||
@@ -600,13 +618,38 @@ def perform_forced_update(
|
||||
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:
|
||||
@@ -616,6 +659,7 @@ def perform_forced_update(
|
||||
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")
|
||||
@@ -628,9 +672,11 @@ def perform_forced_update(
|
||||
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)
|
||||
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:
|
||||
@@ -640,6 +686,7 @@ def perform_forced_update(
|
||||
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(
|
||||
@@ -651,8 +698,21 @@ def perform_forced_update(
|
||||
)
|
||||
|
||||
delta = _matching_delta(manifest, current_version, latest_version)
|
||||
if not delta:
|
||||
emit_progress(
|
||||
"delta_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,
|
||||
@@ -669,6 +729,7 @@ def perform_forced_update(
|
||||
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,
|
||||
@@ -676,8 +737,9 @@ def perform_forced_update(
|
||||
url=delta_url,
|
||||
path=str(delta_path),
|
||||
)
|
||||
download_file(delta_url, delta_path, settings.timeout_seconds)
|
||||
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:
|
||||
@@ -685,6 +747,7 @@ def perform_forced_update(
|
||||
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(
|
||||
@@ -694,6 +757,7 @@ def perform_forced_update(
|
||||
path=str(delta_path),
|
||||
sha256=delta_sha,
|
||||
)
|
||||
emit_progress("delta_launch", message="正在应用差量更新")
|
||||
launch_delta_update(delta_path, latest_version)
|
||||
return UpdateResult(
|
||||
"delta_update_started",
|
||||
@@ -703,6 +767,7 @@ def perform_forced_update(
|
||||
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,
|
||||
@@ -729,10 +794,18 @@ 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:
|
||||
result = perform_update(settings=settings, current_version=current_version)
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Any, Callable
|
||||
|
||||
from douyin.updater.bootstrap import load_update_settings, run_startup_update_check_early
|
||||
from gui.dashboard_app import theme
|
||||
from gui.dashboard_app.widgets import rounded_surface
|
||||
|
||||
|
||||
class UpdateProgressWindow:
|
||||
"""Small standalone update progress window used before the main GUI exists."""
|
||||
|
||||
def __init__(self, title: str = "软件更新") -> None:
|
||||
self.root = tk.Tk()
|
||||
self.root.title(title)
|
||||
self.root.resizable(False, False)
|
||||
self.root.configure(bg=theme.BG)
|
||||
theme.setup_styles(self.root)
|
||||
self.root.protocol("WM_DELETE_WINDOW", lambda: None)
|
||||
|
||||
frame = tk.Frame(self.root, bg=theme.BG, padx=28, pady=26)
|
||||
frame.pack(fill="both", expand=True)
|
||||
card = rounded_surface(frame, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
card.pack(fill="both", expand=True)
|
||||
inner = tk.Frame(card, bg=theme.SURFACE, padx=26, pady=24)
|
||||
inner.pack(fill="both", expand=True)
|
||||
|
||||
top = tk.Frame(inner, bg=theme.SURFACE)
|
||||
top.pack(fill="x")
|
||||
tk.Label(
|
||||
top,
|
||||
text="正在更新",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 19, "bold"),
|
||||
).pack(side="left")
|
||||
self.mode = tk.Label(
|
||||
top,
|
||||
text="检查中",
|
||||
bg=theme.BLUE_SOFT,
|
||||
fg=theme.BLUE,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
padx=12,
|
||||
pady=5,
|
||||
)
|
||||
self.mode.pack(side="right")
|
||||
|
||||
self.stage = tk.Label(
|
||||
inner,
|
||||
text="正在连接更新服务器",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 14, "bold"),
|
||||
)
|
||||
self.stage.pack(anchor="w", pady=(20, 5))
|
||||
self.detail = tk.Label(
|
||||
inner,
|
||||
text="优先尝试差量更新,失败后才回退完整安装包",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=theme.FONT_SMALL,
|
||||
)
|
||||
self.detail.pack(anchor="w", pady=(0, 14))
|
||||
self.percent = tk.Label(
|
||||
inner,
|
||||
text="0%",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 24, "bold"),
|
||||
)
|
||||
self.percent.pack(anchor="e")
|
||||
self.bar = ttk.Progressbar(inner, mode="determinate", length=460, maximum=100)
|
||||
self.bar.pack(fill="x", pady=(3, 10), ipady=4)
|
||||
self.sub = tk.Label(
|
||||
inner,
|
||||
text="准备中",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.SUBTLE,
|
||||
font=("Microsoft YaHei UI", 11),
|
||||
)
|
||||
self.sub.pack(anchor="w")
|
||||
|
||||
self.root.update_idletasks()
|
||||
w, h = self.root.winfo_width(), self.root.winfo_height()
|
||||
sw, sh = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
|
||||
self.root.geometry(f"+{max(0, (sw - w) // 2)}+{max(0, (sh - h) // 2)}")
|
||||
|
||||
def callback(self) -> Callable[[dict[str, Any]], None]:
|
||||
return lambda event: self.root.after(0, lambda event=event: self.update(event))
|
||||
|
||||
def update(self, event: dict[str, Any]) -> None:
|
||||
apply_update_progress_event(
|
||||
event,
|
||||
mode_label=self.mode,
|
||||
stage_label=self.stage,
|
||||
detail_label=self.detail,
|
||||
percent_label=self.percent,
|
||||
bar=self.bar,
|
||||
sub_label=self.sub,
|
||||
)
|
||||
self.root.update_idletasks()
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
self.root.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run_gui_startup_update_check_early(app_name: str) -> None:
|
||||
"""Run startup updater with a visible GUI progress window when enabled."""
|
||||
try:
|
||||
settings = load_update_settings()
|
||||
except Exception:
|
||||
settings = None
|
||||
if settings is None or not settings.enabled:
|
||||
run_startup_update_check_early(app_name=app_name)
|
||||
return
|
||||
|
||||
progress = UpdateProgressWindow()
|
||||
try:
|
||||
run_startup_update_check_early(
|
||||
app_name=app_name,
|
||||
progress_callback=progress.callback(),
|
||||
)
|
||||
finally:
|
||||
progress.close()
|
||||
|
||||
|
||||
def apply_update_progress_event(
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
mode_label: tk.Label,
|
||||
stage_label: tk.Label,
|
||||
detail_label: tk.Label,
|
||||
percent_label: tk.Label,
|
||||
bar: ttk.Progressbar,
|
||||
sub_label: tk.Label,
|
||||
) -> None:
|
||||
stage = str(event.get("stage") or "")
|
||||
message = str(event.get("message") or "")
|
||||
kind = str(event.get("kind") or "")
|
||||
stage_text = message or {
|
||||
"manifest_fetch": "正在连接更新服务器",
|
||||
"manifest_verify": "正在校验更新签名",
|
||||
"delta_download_start": "正在下载差量包",
|
||||
"delta_verify": "正在校验差量包",
|
||||
"delta_validate": "正在检查差量包内容",
|
||||
"delta_launch": "正在应用差量更新",
|
||||
"delta_failed": "差量更新失败,准备回退完整安装包",
|
||||
"delta_unavailable": "未找到当前版本可用的差量包",
|
||||
"delta_skipped": "上次差量更新未完成",
|
||||
"full_prepare": "准备下载完整安装包",
|
||||
"full_download_start": "正在下载完整安装包",
|
||||
"full_verify": "正在校验完整安装包",
|
||||
"full_launch": "正在启动安装器",
|
||||
}.get(stage, "正在处理更新")
|
||||
|
||||
if kind == "delta" or stage.startswith("delta_"):
|
||||
mode_text = "差量更新"
|
||||
mode_bg, mode_fg = theme.TEAL_SOFT, theme.TEAL_DARK
|
||||
elif kind == "full" or stage.startswith("full_"):
|
||||
mode_text = "完整安装包"
|
||||
mode_bg, mode_fg = theme.AMBER_SOFT, theme.AMBER
|
||||
else:
|
||||
mode_text = "检查中"
|
||||
mode_bg, mode_fg = theme.BLUE_SOFT, theme.BLUE
|
||||
|
||||
mode_label.config(text=mode_text, bg=mode_bg, fg=mode_fg)
|
||||
stage_label.config(text=stage_text)
|
||||
|
||||
done = int(event.get("done") or 0)
|
||||
total = int(event.get("total") or 0)
|
||||
if stage == "download_progress" and total > 0:
|
||||
percent = max(0, min(100, round(done * 100 / total)))
|
||||
bar.config(value=percent)
|
||||
percent_label.config(text=f"{percent}%")
|
||||
detail_label.config(text=f"已下载 {done // (1024 * 1024)} MB / {max(1, total // (1024 * 1024))} MB")
|
||||
elif stage.endswith("_start"):
|
||||
bar.config(value=5)
|
||||
percent_label.config(text="0%")
|
||||
detail_label.config(text="正在建立下载任务")
|
||||
elif stage in {"delta_verify", "delta_validate", "full_verify"}:
|
||||
bar.config(value=92)
|
||||
percent_label.config(text="92%")
|
||||
detail_label.config(text="下载完成,正在校验完整性")
|
||||
elif stage in {"delta_launch", "full_launch"}:
|
||||
bar.config(value=100)
|
||||
percent_label.config(text="100%")
|
||||
detail_label.config(text="校验完成,正在启动更新器")
|
||||
elif stage in {"delta_failed", "delta_unavailable", "delta_skipped"}:
|
||||
bar.config(value=0)
|
||||
percent_label.config(text="回退")
|
||||
detail_label.config(text=str(event.get("error") or "将下载完整安装包"))
|
||||
else:
|
||||
bar.config(value=max(8, int(float(bar["value"] or 0))))
|
||||
percent_label.config(text="")
|
||||
|
||||
sub_label.config(text=str(event.get("path") or event.get("url") or ""))
|
||||
+89
-14
@@ -24,6 +24,7 @@ from gui.components.config_vars import build_config_vars
|
||||
from gui.components.mousewheel_guard import disable_spinbox_mousewheel
|
||||
from gui.components.run_params_builder import get_params as build_run_params
|
||||
from gui.components.screenshot_action import do_screenshot
|
||||
from gui.components.update_progress import apply_update_progress_event
|
||||
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog
|
||||
from gui.components.wifi_adb_one_click_scan import on_scan_one_click
|
||||
from gui.components.wifi_adb_pick_dialog import open_scan_pick_dialog
|
||||
@@ -541,7 +542,13 @@ class DashboardApp:
|
||||
|
||||
def worker() -> None:
|
||||
try:
|
||||
result = perform_forced_update(settings=load_manual_update_settings())
|
||||
result = perform_forced_update(
|
||||
settings=load_manual_update_settings(),
|
||||
progress_callback=lambda event: self.root.after(
|
||||
0,
|
||||
lambda event=event: self._update_progress_window(progress, event),
|
||||
),
|
||||
)
|
||||
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_result(result)))
|
||||
except UpdateError as exc:
|
||||
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_error(str(exc))))
|
||||
@@ -555,27 +562,81 @@ class DashboardApp:
|
||||
win.title("检查更新")
|
||||
win.transient(self.root)
|
||||
win.resizable(False, False)
|
||||
win.configure(bg=theme.SURFACE)
|
||||
win.configure(bg=theme.BG)
|
||||
win.protocol("WM_DELETE_WINDOW", lambda: None)
|
||||
frame = tk.Frame(win, bg=theme.SURFACE, padx=24, pady=22)
|
||||
frame = tk.Frame(win, bg=theme.BG, padx=26, pady=24)
|
||||
frame.pack(fill="both", expand=True)
|
||||
|
||||
card = rounded_surface(frame, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
card.pack(fill="both", expand=True)
|
||||
inner = tk.Frame(card, bg=theme.SURFACE, padx=24, pady=22)
|
||||
inner.pack(fill="both", expand=True)
|
||||
|
||||
top = tk.Frame(inner, bg=theme.SURFACE)
|
||||
top.pack(fill="x")
|
||||
tk.Label(
|
||||
frame,
|
||||
text="正在检查更新",
|
||||
top,
|
||||
text="软件更新",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 16, "bold"),
|
||||
).pack(anchor="w")
|
||||
tk.Label(
|
||||
frame,
|
||||
font=("Microsoft YaHei UI", 18, "bold"),
|
||||
).pack(side="left")
|
||||
mode = tk.Label(
|
||||
top,
|
||||
text="检查中",
|
||||
bg=theme.TEAL_SOFT,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
padx=12,
|
||||
pady=5,
|
||||
)
|
||||
mode.pack(side="right")
|
||||
|
||||
stage = tk.Label(
|
||||
inner,
|
||||
text=message,
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 14, "bold"),
|
||||
)
|
||||
stage.pack(anchor="w", pady=(18, 4))
|
||||
detail = tk.Label(
|
||||
inner,
|
||||
text="优先尝试差量更新,失败后才回退完整安装包",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=theme.FONT_UI,
|
||||
).pack(anchor="w", pady=(8, 14))
|
||||
bar = ttk.Progressbar(frame, mode="indeterminate", length=340)
|
||||
bar.pack(fill="x")
|
||||
bar.start(12)
|
||||
font=theme.FONT_SMALL,
|
||||
)
|
||||
detail.pack(anchor="w", pady=(0, 14))
|
||||
pct = tk.Label(
|
||||
inner,
|
||||
text="0%",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 22, "bold"),
|
||||
)
|
||||
pct.pack(anchor="e")
|
||||
bar = ttk.Progressbar(inner, mode="determinate", length=420, maximum=100)
|
||||
bar.pack(fill="x", pady=(3, 10), ipady=3)
|
||||
sub = tk.Label(
|
||||
inner,
|
||||
text="准备中",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.SUBTLE,
|
||||
font=("Microsoft YaHei UI", 11),
|
||||
)
|
||||
sub.pack(anchor="w")
|
||||
|
||||
win._update_labels = { # type: ignore[attr-defined]
|
||||
"mode": mode,
|
||||
"stage": stage,
|
||||
"detail": detail,
|
||||
"pct": pct,
|
||||
"bar": bar,
|
||||
"sub": sub,
|
||||
}
|
||||
self._update_progress_window(win, {"stage": "manifest_fetch", "message": message})
|
||||
|
||||
try:
|
||||
win.update_idletasks()
|
||||
x = self.root.winfo_rootx() + (self.root.winfo_width() - win.winfo_width()) // 2
|
||||
@@ -586,6 +647,20 @@ class DashboardApp:
|
||||
pass
|
||||
return win
|
||||
|
||||
def _update_progress_window(self, progress: tk.Toplevel, event: dict) -> None:
|
||||
labels = getattr(progress, "_update_labels", None)
|
||||
if not labels:
|
||||
return
|
||||
apply_update_progress_event(
|
||||
event,
|
||||
mode_label=labels["mode"],
|
||||
stage_label=labels["stage"],
|
||||
detail_label=labels["detail"],
|
||||
percent_label=labels["pct"],
|
||||
bar=labels["bar"],
|
||||
sub_label=labels["sub"],
|
||||
)
|
||||
|
||||
def _finish_update_progress(self, progress: tk.Toplevel, callback) -> None:
|
||||
try:
|
||||
progress.grab_release()
|
||||
|
||||
@@ -8,10 +8,10 @@ _BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(_BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_BASE_DIR))
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
from gui.components.update_progress import run_gui_startup_update_check_early
|
||||
|
||||
|
||||
run_startup_update_check_early(app_name="gui_app")
|
||||
run_gui_startup_update_check_early(app_name="gui_app")
|
||||
|
||||
from douyin.core.version import print_version_banner # noqa: E402
|
||||
from gui.gui_app import main # noqa: E402
|
||||
|
||||
+50
-2
@@ -7,6 +7,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
@@ -132,15 +133,62 @@ def list_adb_devices(adb_exe: str) -> list[str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
env=_adb_env(),
|
||||
timeout=5,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
return []
|
||||
devices: list[str] = []
|
||||
for line in (proc.stdout or "").splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[1] == "device":
|
||||
devices.append(parts[0])
|
||||
return devices
|
||||
return _normalize_mdns_device_serials(adb_exe, devices)
|
||||
|
||||
|
||||
def _normalize_mdns_device_serials(adb_exe: str, devices: list[str]) -> list[str]:
|
||||
"""Convert Android wireless-debug mDNS serials to stable ip:port targets."""
|
||||
mdns_serials = [d for d in devices if "._adb" in d or d.startswith("adb-")]
|
||||
if not mdns_serials:
|
||||
return devices
|
||||
mdns_targets: list[str] = []
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[adb_exe, "mdns", "services"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
env=_adb_env(),
|
||||
timeout=2,
|
||||
)
|
||||
if proc.returncode == 0:
|
||||
for line in (proc.stdout or "").splitlines():
|
||||
if "_adb-tls-pairing" in line or "_adb" not in line:
|
||||
continue
|
||||
m = re.search(r"(\d{1,3}(?:\.\d{1,3}){3}):(\d{1,5})", line)
|
||||
if m:
|
||||
mdns_targets.append(f"{m.group(1)}:{m.group(2)}")
|
||||
except Exception:
|
||||
mdns_targets = []
|
||||
|
||||
out: list[str] = []
|
||||
has_ip_target = any(_is_ip_port_device(d) for d in devices) or bool(mdns_targets)
|
||||
for device in devices:
|
||||
if device in mdns_serials and mdns_targets:
|
||||
for target in mdns_targets:
|
||||
if target not in out:
|
||||
out.append(target)
|
||||
continue
|
||||
if device in mdns_serials and has_ip_target:
|
||||
continue
|
||||
if device not in out:
|
||||
out.append(device)
|
||||
return out
|
||||
|
||||
|
||||
def _is_ip_port_device(device: str) -> bool:
|
||||
return bool(re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}:\d{1,5}", str(device or "").strip()))
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Iterable, Optional
|
||||
|
||||
from .adb import _adb_env
|
||||
from .adb import _adb_env, list_adb_devices
|
||||
|
||||
|
||||
DEFAULT_ADB_PORT = 5555
|
||||
@@ -728,6 +728,21 @@ def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
return targets
|
||||
|
||||
|
||||
def discover_connected_wifi_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
"""Return already-connected WiFi ADB targets from adb devices as scan fallback."""
|
||||
targets: list[tuple[str, int]] = []
|
||||
seen: set[tuple[str, int]] = set()
|
||||
for device in list_adb_devices(adb_exe):
|
||||
parsed = _parse_target_ip_port(device)
|
||||
if not parsed:
|
||||
continue
|
||||
if parsed in seen:
|
||||
continue
|
||||
seen.add(parsed)
|
||||
targets.append(parsed)
|
||||
return targets
|
||||
|
||||
|
||||
def verify_adb_target(adb_exe: str, target: str, timeout: float = 5.0) -> tuple[str, str]:
|
||||
"""对一个 ip:port 调 `adb connect <target>`,解析输出。
|
||||
|
||||
@@ -886,11 +901,17 @@ def discover_adb_devices(
|
||||
|
||||
# 2) mDNS 发现(Android 11+ 无线调试常见随机端口)
|
||||
mdns_targets = discover_mdns_targets(adb_exe)
|
||||
connected_wifi_targets = discover_connected_wifi_targets(adb_exe)
|
||||
if on_phase and mdns_targets:
|
||||
try:
|
||||
on_phase(f"mDNS 发现 {len(mdns_targets)} 个 ADB 候选目标")
|
||||
except Exception:
|
||||
pass
|
||||
if on_phase and connected_wifi_targets:
|
||||
try:
|
||||
on_phase(f"已连接设备兜底发现 {len(connected_wifi_targets)} 个 WiFi ADB 目标")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
quick_open_targets: list[tuple[str, int]] = []
|
||||
quick_hosts: list[str] = []
|
||||
@@ -954,7 +975,8 @@ def discover_adb_devices(
|
||||
all_open_targets.extend(open_targets)
|
||||
|
||||
# 合并 mDNS + 网段扫描,并去重
|
||||
all_targets = list(mdns_targets)
|
||||
all_targets = list(connected_wifi_targets)
|
||||
all_targets.extend(mdns_targets)
|
||||
all_targets.extend(quick_open_targets)
|
||||
all_targets.extend(all_open_targets)
|
||||
uniq_open: list[tuple[str, int]] = []
|
||||
|
||||
@@ -8,10 +8,10 @@ _BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(_BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_BASE_DIR))
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
from gui.components.update_progress import run_gui_startup_update_check_early
|
||||
|
||||
|
||||
run_startup_update_check_early(app_name="gui_dashboard_app")
|
||||
run_gui_startup_update_check_early(app_name="gui_dashboard_app")
|
||||
|
||||
from gui.dashboard_app.app import main # noqa: E402
|
||||
|
||||
|
||||
+32
-12
@@ -357,12 +357,18 @@ def _signed_update_manifest(service: LicenseService, request: Request) -> dict[s
|
||||
"published_at": manifest.published_at,
|
||||
}
|
||||
if manifest.delta:
|
||||
delta = dict(manifest.delta)
|
||||
delta_filename = str(delta.get("filename") or "")
|
||||
if delta_filename:
|
||||
delta_path = f"/api/v1/update/download/{delta_filename}"
|
||||
delta["url"] = urljoin(_public_base_url(request) + "/", delta_path.lstrip("/"))
|
||||
payload["delta"] = delta
|
||||
raw_deltas = manifest.delta if isinstance(manifest.delta, list) else [manifest.delta]
|
||||
deltas: list[dict[str, Any]] = []
|
||||
for raw_delta in raw_deltas:
|
||||
if not isinstance(raw_delta, dict):
|
||||
continue
|
||||
delta = dict(raw_delta)
|
||||
delta_filename = str(delta.get("filename") or "")
|
||||
if delta_filename:
|
||||
delta_path = f"/api/v1/update/download/{delta_filename}"
|
||||
delta["url"] = urljoin(_public_base_url(request) + "/", delta_path.lstrip("/"))
|
||||
deltas.append(delta)
|
||||
payload["delta"] = deltas[0] if len(deltas) == 1 else deltas
|
||||
payload["signature"] = service.sign_payload(payload)
|
||||
return payload
|
||||
|
||||
@@ -372,13 +378,16 @@ def _update_summary_html(manifest: UpdateManifest) -> str:
|
||||
sha = manifest.sha256[:12] + "..." if manifest.sha256 else "-"
|
||||
file_name = manifest.filename or "-"
|
||||
published = manifest.published_at or "-"
|
||||
delta = manifest.delta or {}
|
||||
raw_delta = manifest.delta or {}
|
||||
delta_text = "-"
|
||||
if delta:
|
||||
delta_text = (
|
||||
if raw_delta:
|
||||
deltas = raw_delta if isinstance(raw_delta, list) else [raw_delta]
|
||||
delta_text = "<br>".join(
|
||||
f"{escape(str(delta.get('from_version') or ''))}"
|
||||
f" -> {escape(str(delta.get('to_version') or ''))} / "
|
||||
f"<code>{escape(str(delta.get('filename') or '-'))}</code>"
|
||||
for delta in deltas
|
||||
if isinstance(delta, dict)
|
||||
)
|
||||
return (
|
||||
"<div class='update-state'>"
|
||||
@@ -863,8 +872,10 @@ document.getElementById("claim").addEventListener("click", async () => {{
|
||||
manifest = service.load_update_manifest()
|
||||
safe_name = Path(str(filename or "")).name
|
||||
allowed_names = {manifest.filename}
|
||||
if manifest.delta and manifest.delta.get("filename"):
|
||||
allowed_names.add(str(manifest.delta.get("filename")))
|
||||
if manifest.delta:
|
||||
for delta in manifest.delta if isinstance(manifest.delta, list) else [manifest.delta]:
|
||||
if isinstance(delta, dict) and delta.get("filename"):
|
||||
allowed_names.add(str(delta.get("filename")))
|
||||
if not manifest.enabled or safe_name not in allowed_names:
|
||||
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
|
||||
target = service.update_dir / safe_name
|
||||
@@ -1078,7 +1089,16 @@ document.getElementById("claim").addEventListener("click", async () => {{
|
||||
filename=delta_file.filename or "",
|
||||
file_path=tmp_path,
|
||||
)
|
||||
delta = manifest.delta or {}
|
||||
raw_delta = manifest.delta or {}
|
||||
deltas = raw_delta if isinstance(raw_delta, list) else [raw_delta]
|
||||
delta = next(
|
||||
(
|
||||
item for item in deltas
|
||||
if isinstance(item, dict)
|
||||
and str(item.get("from_version") or "") == str(from_version).strip().lstrip("Vv")
|
||||
),
|
||||
deltas[-1] if deltas else {},
|
||||
)
|
||||
msg = f"已发布差量更新 {delta.get('from_version')} -> {delta.get('to_version')},文件={delta.get('filename')}"
|
||||
except Exception as exc:
|
||||
msg = f"发布差量更新失败:{exc}"
|
||||
|
||||
+57
-42
@@ -117,7 +117,7 @@ class UpdateManifest:
|
||||
force: bool
|
||||
notes: str
|
||||
published_at: str
|
||||
delta: dict[str, Any] | None = None
|
||||
delta: dict[str, Any] | list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
@@ -564,17 +564,7 @@ class LicenseService:
|
||||
if not isinstance(raw, dict):
|
||||
return UpdateManifest(False, "0.0.0", "", "", False, "manifest 格式错误", "")
|
||||
raw_filename = str(raw.get("filename") or "").strip()
|
||||
raw_delta = raw.get("delta")
|
||||
delta = raw_delta if isinstance(raw_delta, dict) else None
|
||||
if delta:
|
||||
delta = dict(delta)
|
||||
delta_filename = str(delta.get("filename") or "").strip()
|
||||
if delta_filename:
|
||||
delta["filename"] = sanitize_delta_filename(
|
||||
delta_filename,
|
||||
from_version=str(delta.get("from_version") or ""),
|
||||
to_version=str(delta.get("to_version") or raw.get("version") or ""),
|
||||
)
|
||||
delta = self._normalize_manifest_delta(raw.get("delta"), to_version=str(raw.get("version") or ""))
|
||||
return UpdateManifest(
|
||||
enabled=bool(raw.get("enabled")),
|
||||
version=str(raw.get("version") or "0.0.0").strip() or "0.0.0",
|
||||
@@ -586,6 +576,59 @@ class LicenseService:
|
||||
delta=delta,
|
||||
)
|
||||
|
||||
def _normalize_manifest_delta(
|
||||
self,
|
||||
raw_delta: Any,
|
||||
*,
|
||||
to_version: str,
|
||||
) -> dict[str, Any] | list[dict[str, Any]] | None:
|
||||
candidates = raw_delta if isinstance(raw_delta, list) else [raw_delta] if isinstance(raw_delta, dict) else []
|
||||
out: list[dict[str, Any]] = []
|
||||
for item in candidates:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
delta = dict(item)
|
||||
delta_filename = str(delta.get("filename") or "").strip()
|
||||
if delta_filename:
|
||||
delta["filename"] = sanitize_delta_filename(
|
||||
delta_filename,
|
||||
from_version=str(delta.get("from_version") or ""),
|
||||
to_version=str(delta.get("to_version") or to_version),
|
||||
)
|
||||
out.append(delta)
|
||||
if not out:
|
||||
return None
|
||||
return out[0] if len(out) == 1 else out
|
||||
|
||||
def _append_delta_to_manifest(
|
||||
self,
|
||||
existing: UpdateManifest,
|
||||
delta: dict[str, Any],
|
||||
) -> UpdateManifest:
|
||||
raw_existing = existing.delta
|
||||
deltas = list(raw_existing) if isinstance(raw_existing, list) else [raw_existing] if isinstance(raw_existing, dict) else []
|
||||
next_deltas = [
|
||||
item for item in deltas
|
||||
if str(item.get("from_version") or "") != str(delta.get("from_version") or "")
|
||||
]
|
||||
next_deltas.append(delta)
|
||||
next_deltas.sort(key=lambda item: str(item.get("from_version") or ""))
|
||||
manifest = UpdateManifest(
|
||||
enabled=existing.enabled,
|
||||
version=existing.version,
|
||||
filename=existing.filename,
|
||||
sha256=existing.sha256,
|
||||
force=existing.force,
|
||||
notes=existing.notes,
|
||||
published_at=existing.published_at,
|
||||
delta=next_deltas[0] if len(next_deltas) == 1 else next_deltas,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def publish_update(
|
||||
self,
|
||||
*,
|
||||
@@ -689,21 +732,7 @@ class LicenseService:
|
||||
"sha256": sha256_bytes(content),
|
||||
"size": len(content),
|
||||
}
|
||||
manifest = UpdateManifest(
|
||||
enabled=existing.enabled,
|
||||
version=existing.version,
|
||||
filename=existing.filename,
|
||||
sha256=existing.sha256,
|
||||
force=existing.force,
|
||||
notes=existing.notes,
|
||||
published_at=existing.published_at,
|
||||
delta=delta,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
return self._append_delta_to_manifest(existing, delta)
|
||||
|
||||
def publish_delta_update_file(
|
||||
self,
|
||||
@@ -738,21 +767,7 @@ class LicenseService:
|
||||
"sha256": sha256_file(target),
|
||||
"size": target.stat().st_size,
|
||||
}
|
||||
manifest = UpdateManifest(
|
||||
enabled=existing.enabled,
|
||||
version=existing.version,
|
||||
filename=existing.filename,
|
||||
sha256=existing.sha256,
|
||||
force=existing.force,
|
||||
notes=existing.notes,
|
||||
published_at=existing.published_at,
|
||||
delta=delta,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
return self._append_delta_to_manifest(existing, delta)
|
||||
|
||||
def save_diagnostic_log_file(
|
||||
self,
|
||||
|
||||
@@ -205,6 +205,71 @@ def test_forced_update_prefers_matching_delta_package(tmp_path):
|
||||
assert result.delta_path == launched[0]
|
||||
|
||||
|
||||
def test_forced_update_picks_matching_delta_from_list(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
import zipfile
|
||||
|
||||
file_payload = b"latest bytes"
|
||||
file_sha = hashlib.sha256(file_payload).hexdigest()
|
||||
delta_zip = tmp_path / "delta-source.zip"
|
||||
with zipfile.ZipFile(delta_zip, "w") as zf:
|
||||
zf.writestr(
|
||||
"manifest.json",
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"from_version": "3.3.7",
|
||||
"to_version": "3.3.9",
|
||||
"files": [{"path": "DouyinGuajiGUI.exe", "sha256": file_sha, "size": len(file_payload)}],
|
||||
"delete": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
zf.writestr("files/DouyinGuajiGUI.exe", file_payload)
|
||||
delta_payload = delta_zip.read_bytes()
|
||||
delta_sha = hashlib.sha256(delta_payload).hexdigest()
|
||||
settings = UpdateSettings(enabled=True, manifest_url="https://example.test/update.json", download_dir=tmp_path)
|
||||
downloaded: list[str] = []
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
dest.write_bytes(delta_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.7",
|
||||
fetch_manifest=lambda url, timeout: {
|
||||
"version": "3.3.9",
|
||||
"url": "https://example.test/full.exe",
|
||||
"sha256": "0" * 64,
|
||||
"delta": [
|
||||
{
|
||||
"from_version": "3.3.8",
|
||||
"to_version": "3.3.9",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.8_to_3.3.9_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.8_to_3.3.9_delta.zip",
|
||||
"sha256": "1" * 64,
|
||||
},
|
||||
{
|
||||
"from_version": "3.3.7",
|
||||
"to_version": "3.3.9",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.7_to_3.3.9_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.7_to_3.3.9_delta.zip",
|
||||
"sha256": delta_sha,
|
||||
},
|
||||
],
|
||||
},
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: pytest.fail("should not launch full installer"),
|
||||
launch_delta_update=lambda path, version: None,
|
||||
)
|
||||
|
||||
assert result.status == "delta_update_started"
|
||||
assert downloaded == ["https://example.test/DouyinGuaji-3.3.7_to_3.3.9_delta.zip"]
|
||||
|
||||
|
||||
def test_forced_update_falls_back_to_full_installer_when_delta_download_fails(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
|
||||
@@ -276,6 +276,38 @@ class TestAdbFunctions:
|
||||
result = list_adb_devices("/nonexistent/path/to/adb")
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_list_adb_devices_normalizes_mdns_serial_to_ip_port(self, monkeypatch):
|
||||
from gui.gui_core_pkg import adb as adb_mod
|
||||
|
||||
calls = []
|
||||
|
||||
class _Proc:
|
||||
returncode = 0
|
||||
|
||||
def __init__(self, stdout: str):
|
||||
self.stdout = stdout
|
||||
self.stderr = ""
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
calls.append(cmd)
|
||||
if cmd[1:3] == ["devices", "-l"]:
|
||||
return _Proc(
|
||||
"List of devices attached\n"
|
||||
"adb-ABC._adb-tls-connect._tcp device product:x model:x\n"
|
||||
)
|
||||
if cmd[1:3] == ["mdns", "services"]:
|
||||
return _Proc(
|
||||
"List of discovered mdns services\n"
|
||||
"adb-ABC _adb-tls-connect._tcp 192.168.10.105:46107\n"
|
||||
)
|
||||
return _Proc("")
|
||||
|
||||
monkeypatch.setattr(adb_mod.subprocess, "run", fake_run)
|
||||
|
||||
assert adb_mod.list_adb_devices("/adb") == ["192.168.10.105:46107"]
|
||||
assert calls[0][1:3] == ["devices", "-l"]
|
||||
assert calls[1][1:3] == ["mdns", "services"]
|
||||
|
||||
def test_resolve_adb_device_with_invalid_id_raises(self):
|
||||
# 指定了不存在的 device_id 应抛 RuntimeError
|
||||
with pytest.raises(RuntimeError):
|
||||
|
||||
@@ -260,6 +260,43 @@ def test_admin_can_publish_delta_update_and_download_zip(tmp_path):
|
||||
assert download.content == delta_payload
|
||||
|
||||
|
||||
def test_admin_can_publish_multiple_cumulative_delta_updates(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(api.create_app(service=service, admin_token="secret"))
|
||||
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
|
||||
|
||||
client.post(
|
||||
"/admin/update/publish",
|
||||
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
|
||||
data={"csrf_token": "csrf-token", "version": "3.3.9", "notes": "", "force": "1"},
|
||||
files={"installer": ("DouyinGuaji-3.3.9-Setup.exe", b"installer", "application/octet-stream")},
|
||||
)
|
||||
for from_version, payload in [("3.3.7", b"delta37"), ("3.3.8", b"delta38")]:
|
||||
resp = client.post(
|
||||
"/admin/update/publish-delta",
|
||||
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
|
||||
data={"csrf_token": "csrf-token", "from_version": from_version, "to_version": "3.3.9"},
|
||||
files={"delta_file": (f"DouyinGuaji-{from_version}_to_3.3.9_delta.zip", payload, "application/zip")},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
manifest = client.get("/api/v1/update/manifest").json()
|
||||
deltas = manifest["delta"]
|
||||
|
||||
assert isinstance(deltas, list)
|
||||
assert [item["from_version"] for item in deltas] == ["3.3.7", "3.3.8"]
|
||||
assert deltas[0]["url"].endswith("/api/v1/update/download/DouyinGuaji-3.3.7_to_3.3.9_delta.zip")
|
||||
download = client.get("/api/v1/update/download/DouyinGuaji-3.3.7_to_3.3.9_delta.zip")
|
||||
assert download.status_code == 200
|
||||
assert download.content == b"delta37"
|
||||
|
||||
|
||||
def test_license_server_rejects_untrusted_host(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@@ -8,8 +8,12 @@ from pathlib import Path
|
||||
|
||||
def _assert_bootstrap_before(path: str, *late_markers: str) -> None:
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
import_marker = "from douyin.updater.bootstrap import run_startup_update_check_early"
|
||||
call_marker = "run_startup_update_check_early("
|
||||
import_marker = (
|
||||
"from douyin.updater.bootstrap import run_startup_update_check_early"
|
||||
if "run_startup_update_check_early(" in text
|
||||
else "from gui.components.update_progress import run_gui_startup_update_check_early"
|
||||
)
|
||||
call_marker = "run_startup_update_check_early(" if "run_startup_update_check_early(" in text else "run_gui_startup_update_check_early("
|
||||
assert import_marker in text
|
||||
assert call_marker in text
|
||||
call_index = text.index(call_marker)
|
||||
@@ -26,9 +30,10 @@ def _assert_packaging_uses_wrapper(wrapper_path: str, target_script: str) -> Non
|
||||
|
||||
def _assert_wrapper_imports_target_after_bootstrap(path: str, target_import: str) -> None:
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
assert "run_startup_update_check_early(" in text
|
||||
call_marker = "run_startup_update_check_early(" if "run_startup_update_check_early(" in text else "run_gui_startup_update_check_early("
|
||||
assert call_marker in text
|
||||
assert target_import in text
|
||||
assert text.index("run_startup_update_check_early(") < text.index(target_import)
|
||||
assert text.index(call_marker) < text.index(target_import)
|
||||
|
||||
|
||||
def _assert_source_entry_bootstraps_under_main_guard(path: str, late_marker: str) -> None:
|
||||
|
||||
@@ -47,3 +47,21 @@ def test_update_delta_build_and_apply_round_trip(tmp_path):
|
||||
with zipfile.ZipFile(delta) as zf:
|
||||
package_manifest = json.loads(zf.read("manifest.json").decode("utf-8"))
|
||||
assert package_manifest["files"] == manifest["files"]
|
||||
|
||||
|
||||
def test_update_delta_build_many_creates_cumulative_delta_packages(tmp_path):
|
||||
from tools.update_delta import create_delta_zips
|
||||
|
||||
old37 = tmp_path / "DouyinGuaji-3.3.7"
|
||||
old38 = tmp_path / "DouyinGuaji-3.3.8"
|
||||
new = tmp_path / "DouyinGuaji-3.3.9"
|
||||
out = tmp_path / "delta"
|
||||
for root, text in [(old37, "37"), (old38, "38"), (new, "39")]:
|
||||
root.mkdir()
|
||||
(root / "app.txt").write_text(text, encoding="utf-8")
|
||||
|
||||
manifests = create_delta_zips([old37, old38], new, out, to_version="3.3.9")
|
||||
|
||||
assert [item["from_version"] for item in manifests] == ["3.3.7", "3.3.8"]
|
||||
assert (out / "DouyinGuaji-3.3.7_to_3.3.9_delta.zip").exists()
|
||||
assert (out / "DouyinGuaji-3.3.8_to_3.3.9_delta.zip").exists()
|
||||
@@ -441,6 +441,18 @@ class TestDiscoverAdbDevices:
|
||||
assert len(devs) == 1
|
||||
assert devs[0].target == "192.168.10.66:40075"
|
||||
|
||||
def test_connected_wifi_devices_are_scan_fallback(self):
|
||||
with patch.object(scan, "discover_mdns_targets", return_value=[]), \
|
||||
patch.object(scan, "discover_connected_wifi_targets", return_value=[("192.168.10.105", 46107)]), \
|
||||
patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30"]), \
|
||||
patch.object(scan, "scan_open_ports", return_value=[]), \
|
||||
patch.object(scan, "verify_adb_target", return_value=("connected", "already connected")), \
|
||||
patch.object(scan, "query_device_model", return_value="PEPM00"):
|
||||
devs = scan.discover_adb_devices("/adb")
|
||||
|
||||
assert len(devs) == 1
|
||||
assert devs[0].target == "192.168.10.105:46107"
|
||||
|
||||
def test_returns_devs_with_correct_ports(self):
|
||||
"""两个 (ip, port) 分别返回各自端口的 DiscoveredDevice。"""
|
||||
with patch.object(
|
||||
|
||||
@@ -80,6 +80,39 @@ def create_delta_zip(old_root: Path, new_root: Path, out_path: Path, from_versio
|
||||
return manifest
|
||||
|
||||
|
||||
def create_delta_zips(
|
||||
old_roots: list[Path],
|
||||
new_root: Path,
|
||||
out_dir: Path,
|
||||
*,
|
||||
to_version: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
manifests: list[dict[str, Any]] = []
|
||||
for old_root in old_roots:
|
||||
from_version = infer_dist_version(old_root)
|
||||
out_path = out_dir / f"DouyinGuaji-{from_version}_to_{to_version.strip().lstrip('Vv')}_delta.zip"
|
||||
manifests.append(
|
||||
create_delta_zip(
|
||||
old_root,
|
||||
new_root,
|
||||
out_path,
|
||||
from_version,
|
||||
to_version,
|
||||
)
|
||||
)
|
||||
return manifests
|
||||
|
||||
|
||||
def infer_dist_version(path: Path) -> str:
|
||||
name = path.name
|
||||
for prefix in ("DouyinGuaji-", "douyin-guaji-", "douyin_guaji-"):
|
||||
if name.startswith(prefix):
|
||||
candidate = name[len(prefix):].strip().lstrip("Vv")
|
||||
if candidate:
|
||||
return candidate
|
||||
raise ValueError(f"cannot infer version from directory name: {path}")
|
||||
|
||||
|
||||
def apply_delta_zip(delta_path: Path, target_root: Path) -> dict[str, Any]:
|
||||
target_root = target_root.resolve()
|
||||
with zipfile.ZipFile(delta_path) as zf:
|
||||
@@ -116,6 +149,11 @@ def main(argv: list[str] | None = None) -> int:
|
||||
build.add_argument("--out", required=True, type=Path)
|
||||
build.add_argument("--from-version", required=True)
|
||||
build.add_argument("--to-version", required=True)
|
||||
build_many = sub.add_parser("build-many", help="Create cumulative delta zips from multiple old distributions to one new distribution.")
|
||||
build_many.add_argument("--old", required=True, type=Path, nargs="+")
|
||||
build_many.add_argument("--new", required=True, type=Path)
|
||||
build_many.add_argument("--out-dir", required=True, type=Path)
|
||||
build_many.add_argument("--to-version", required=True)
|
||||
apply = sub.add_parser("apply", help="Apply a delta zip to a target directory for local verification.")
|
||||
apply.add_argument("--delta", required=True, type=Path)
|
||||
apply.add_argument("--target", required=True, type=Path)
|
||||
@@ -124,6 +162,10 @@ def main(argv: list[str] | None = None) -> int:
|
||||
manifest = create_delta_zip(args.old, args.new, args.out, args.from_version, args.to_version)
|
||||
print(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
if args.cmd == "build-many":
|
||||
manifests = create_delta_zips(args.old, args.new, args.out_dir, to_version=args.to_version)
|
||||
print(json.dumps({"deltas": manifests}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
manifest = apply_delta_zip(args.delta, args.target)
|
||||
print(json.dumps({"ok": True, "from_version": manifest.get("from_version"), "to_version": manifest.get("to_version")}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
Reference in new issue
Block a user