Skip to content

The only downloader you need. 下载器的集大成者。

feat(update): Pack 独立分发

XiaoYouChRa67f0c58d8f6
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 4628016f..4735438d 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -599,12 +599,17 @@ jobs:
if: ${{ github.event.inputs.create_release == 'true' }}
runs-on: ubuntu-latest
steps:
+ - uses: actions/checkout@v7
+
- name: Set up uv
uses: astral-sh/setup-uv@v7
- name: Install Python
run: uv python install 3.11
+ - name: Build pack zips
+ run: uv run --no-project python3 scripts/build_pack.py --all
+
- name: Generate versions.json
env:
GH_TOKEN: ${{ github.token }}
@@ -647,14 +652,25 @@ jobs:
if os.path.isfile(full_path):
full[p] = {"file": full_name, "sha256": sha256of(full_path), "size": os.path.getsize(full_path)}
- data = {"app": {"version": version, "patches": patches, "full": full}, "packs": {}}
+ with open("versions.json") as f:
+ data = json.load(f)
+
+ data["app"] = {"version": version, "patches": patches, "full": full}
with open("versions.json", "w") as f:
json.dump(data, f, indent=2)
print(json.dumps(data, indent=2))
PYEOF
- gh release upload "v${VERSION}" versions.json --repo ${{ github.repository }} --clobber
+ - name: Commit versions.json
+ env:
+ VERSION: ${{ needs.prepare.outputs.version }}
+ run: |
+ git config user.name "github-actions[bot]"
+ git config user.email "github-actions[bot]@users.noreply.github.com"
+ git add versions.json dist/packs/
+ git diff --staged --quiet || git commit -m "chore: update versions.json for v${VERSION} [skip ci]"
+ git push
- name: Mirror to GitCode
env:
@@ -700,8 +716,6 @@ jobs:
echo "uploaded: $name"
}
- upload_file versions.json
-
for f in assets/patch-*.hdiff; do
[ -f "$f" ] && upload_file "$f"
done
diff --git a/.gitignore b/.gitignore
index 7a6d8854..fa834d6a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -22,7 +22,8 @@ log/
# 忽略构建文件
build/
-dist/
+dist/*
+!dist/packs/
output/
*.spec
diff --git a/app/services/update_service.py b/app/services/update_service.py
index ecb71d74..9668ea30 100644
--- a/app/services/update_service.py
+++ b/app/services/update_service.py
@@ -29,12 +29,14 @@ STAGING_DIR = Path(APP_DATA_DIR) / "update_staging"
SOURCES = {
"github": {
- "api": "https://api.github.com/repos/XiaoYouChR/Ghost-Downloader-3/releases/latest",
- "headers": {"accept": "application/vnd.github+json"},
+ "versions": "https://raw.githubusercontent.com/XiaoYouChR/Ghost-Downloader-3/main/versions.json",
+ "raw": "https://raw.githubusercontent.com/XiaoYouChR/Ghost-Downloader-3/main",
+ "release": "https://github.com/XiaoYouChR/Ghost-Downloader-3/releases/download",
},
"gitcode": {
- "api": "https://gitcode.com/api/v5/repos/XiaoYouChR/Ghost-Downloader-3/releases/latest",
- "headers": {},
+ "versions": "https://raw.gitcode.com/XiaoYouChR/Ghost-Downloader-3/raw/main/versions.json",
+ "raw": "https://raw.gitcode.com/XiaoYouChR/Ghost-Downloader-3/raw/main",
+ "release": "https://gitcode.com/XiaoYouChR/Ghost-Downloader-3/releases/download",
},
}
@@ -53,9 +55,7 @@ def isNewer(current: str, latest: str) -> bool:
def buildAssetUrl(source: str, version: str, assetName: str) -> str:
- if source == "gitcode":
- return f"https://gitcode.com/XiaoYouChR/Ghost-Downloader-3/releases/download/v{version}/{assetName}"
- return f"https://github.com/XiaoYouChR/Ghost-Downloader-3/releases/download/v{version}/{assetName}"
+ return f"{SOURCES[source]['release']}/v{version}/{assetName}"
def extractZip(archivePath: Path, targetDir: Path) -> None:
@@ -197,22 +197,13 @@ class UpdateService(QObject):
sources = [self._source] if self._source else list(SOURCES)
for sourceName in sources:
try:
- source = SOURCES[sourceName]
- client = buildClient(headers=source["headers"] or None, timeout=15)
+ client = buildClient(timeout=15)
try:
- resp = await client.get(source["api"])
+ resp = await client.get(SOURCES[sourceName]["versions"])
resp.raise_for_status()
- data = await resp.json()
- for asset in data.get("assets", []):
- if asset.get("name") == "versions.json":
- url = asset.get("browser_download_url", "")
- if not url:
- continue
- response = await client.get(url)
- response.raise_for_status()
- result = await response.json()
- self._source = sourceName
- return result
+ result = await resp.json()
+ self._source = sourceName
+ return result
finally:
client.close()
except Exception as e:
@@ -294,9 +285,9 @@ class UpdateService(QObject):
self._emit("app", UpdateState.READY)
async def _downloadPack(self, packId: str, info: UpdateInfo) -> None:
- appVersion = self._versionsData.get("app", {}).get("version", "")
packData = self._versionsData.get("packs", {}).get(packId, {})
- url = buildAssetUrl(self._source, appVersion, packData.get("file", f"{packId}-{info.latestVersion}.zip"))
+ filename = packData.get("file", f"{packId}.zip")
+ url = f"{SOURCES[self._source]['raw']}/dist/packs/{filename}"
outputPath = STAGING_DIR / f"{packId}.zip"
await fetchFile(url, outputPath, onProgress=lambda p: self._emit(packId, UpdateState.DOWNLOADING, progress=p))
diff --git a/app/view/windows/main_window.py b/app/view/windows/main_window.py
index f779c741..5f3b6701 100644
--- a/app/view/windows/main_window.py
+++ b/app/view/windows/main_window.py
@@ -5,7 +5,7 @@ from functools import cached_property
from typing import TYPE_CHECKING
from PySide6.QtCore import QEvent, QRect, QUrl, QTimer, Qt
-from PySide6.QtGui import QColor, QIcon, QDesktopServices, QPainter, QPalette
+from PySide6.QtGui import QColor, QIcon, QDesktopServices, QKeySequence, QPainter, QPalette, QShortcut
from PySide6.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QWidget
from qfluentwidgets import (
MSFluentWindow, FluentIcon, NavigationItemPosition, MessageBox, Theme, InfoBar, InfoBarPosition,
@@ -227,7 +227,6 @@ class MainWindow(MSFluentWindow):
self.titleBar.closeBtn.clicked.connect(self._onCloseClicked)
self.searchEdit.textChanged.connect(self._onSearchTextChanged)
- from PySide6.QtGui import QKeySequence, QShortcut
QShortcut(QKeySequence.StandardKey.Find, self).activated.connect(self._onSearchShortcut)
if self._updateService is not None:
diff --git a/dist/packs/.gitkeep b/dist/packs/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/scripts/build_pack.py b/scripts/build_pack.py
new file mode 100644
index 00000000..3486c463
--- /dev/null
+++ b/scripts/build_pack.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""Build pack zips and update versions.json.
+
+Usage:
+ python scripts/build_pack.py http_pack [bili_pack ...]
+ python scripts/build_pack.py --all
+"""
+import argparse
+import hashlib
+import json
+import sys
+import tomllib
+import zipfile
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parent.parent
+FEATURES_DIR = REPO / "features"
+DIST_PACKS = REPO / "dist" / "packs"
+VERSIONS_FILE = REPO / "versions.json"
+EXCLUDED_PACKS = {"jack_yao"}
+IGNORE_SUFFIXES = {".svg", ".qrc", ".pyc"}
+
+
+def buildPackZip(packId: str) -> Path:
+ packDir = FEATURES_DIR / packId
+ if not packDir.is_dir():
+ raise FileNotFoundError(f"Pack not found: {packDir}")
+ if not (packDir / "manifest.toml").is_file():
+ raise FileNotFoundError(f"No manifest.toml in {packDir}")
+
+ DIST_PACKS.mkdir(parents=True, exist_ok=True)
+ zipPath = DIST_PACKS / f"{packId}.zip"
+
+ with zipfile.ZipFile(zipPath, "w", zipfile.ZIP_DEFLATED) as zf:
+ for file in sorted(packDir.rglob("*")):
+ if not file.is_file():
+ continue
+ if file.suffix in IGNORE_SUFFIXES:
+ continue
+ if any(p.name == "__pycache__" for p in file.relative_to(packDir).parents):
+ continue
+ zf.write(file, file.relative_to(packDir))
+
+ return zipPath
+
+
+def sha256(path: Path) -> str:
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(8192), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def readManifest(packId: str) -> dict:
+ with open(FEATURES_DIR / packId / "manifest.toml", "rb") as f:
+ return tomllib.load(f).get("pack", {})
+
+
+def allPackIds() -> list[str]:
+ return [
+ d.name for d in sorted(FEATURES_DIR.iterdir())
+ if d.is_dir() and d.name not in EXCLUDED_PACKS and (d / "manifest.toml").is_file()
+ ]
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Build pack zips and update versions.json")
+ parser.add_argument("packs", nargs="*", help="Pack IDs to build")
+ parser.add_argument("--all", action="store_true", help="Build all packs")
+ args = parser.parse_args()
+
+ if args.all:
+ packIds = allPackIds()
+ elif args.packs:
+ packIds = args.packs
+ else:
+ parser.error("Specify pack IDs or --all")
+ return
+
+ versions = json.loads(VERSIONS_FILE.read_text()) if VERSIONS_FILE.is_file() else {"app": {}, "packs": {}}
+ packs = versions.setdefault("packs", {})
+
+ for packId in packIds:
+ print(f"Building {packId}...")
+ zipPath = buildPackZip(packId)
+ manifest = readManifest(packId)
+
+ entry = {
+ "version": manifest.get("version", ""),
+ "file": f"{packId}.zip",
+ "sha256": sha256(zipPath),
+ }
+ gdMin = manifest.get("gdMinVersion", "")
+ if gdMin:
+ entry["gdMinVersion"] = gdMin
+ packs[packId] = entry
+
+ print(f" {zipPath.name} {zipPath.stat().st_size} bytes sha256={entry['sha256'][:12]}...")
+
+ VERSIONS_FILE.write_text(json.dumps(versions, indent=2, ensure_ascii=False) + "\n")
+ print(f"\nUpdated {VERSIONS_FILE}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/test_update_flow.py b/tools/test_update_flow.py
new file mode 100644
index 00000000..e295db29
--- /dev/null
+++ b/tools/test_update_flow.py
@@ -0,0 +1,247 @@
+"""End-to-end test for the update flow with a local HTTP server.
+
+Exercises: _fetchVersions (raw URL) → _check → _downloadPack (raw URL) →
+_applyPack → installPendingPacks. Also verifies buildAssetUrl.
+
+Usage:
+ .venv/bin/python3 tools/test_update_flow.py
+"""
+import asyncio
+import hashlib
+import json
+import shutil
+import sys
+import threading
+import zipfile
+from http.server import HTTPServer, SimpleHTTPRequestHandler
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+WORK_DIR = Path(__file__).resolve().parent / "_test_update"
+SERVE_DIR = WORK_DIR / "serve"
+FAKE_EXEC_DIR = WORK_DIR / "exec"
+FAKE_STAGING = WORK_DIR / "staging"
+
+
+def sha256(path: Path) -> str:
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(8192), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def setup_server_content() -> str:
+ SERVE_DIR.mkdir(parents=True, exist_ok=True)
+
+ pack_dir = SERVE_DIR / "dist" / "packs"
+ pack_dir.mkdir(parents=True, exist_ok=True)
+ pack_zip = pack_dir / "test_pack.zip"
+ with zipfile.ZipFile(pack_zip, "w") as zf:
+ zf.writestr("manifest.toml", '[pack]\nentry = "pack.py"\nclass = "TestPack"\nversion = "2.0.0"\ngdMinVersion = "4.2.0"\n')
+ zf.writestr("pack.py", "class TestPack: pass\n")
+
+ pack_sha = sha256(pack_zip)
+ versions = {
+ "app": {
+ "version": "99.0.0",
+ "patches": {},
+ "full": {},
+ },
+ "packs": {
+ "test_pack": {
+ "version": "2.0.0",
+ "file": "test_pack.zip",
+ "sha256": pack_sha,
+ "gdMinVersion": "4.2.0",
+ }
+ },
+ }
+ (SERVE_DIR / "versions.json").write_text(json.dumps(versions, indent=2))
+ return pack_sha
+
+
+def setup_local_pack():
+ features = FAKE_EXEC_DIR / "features"
+ pack_dir = features / "test_pack"
+ pack_dir.mkdir(parents=True, exist_ok=True)
+ (pack_dir / "manifest.toml").write_text(
+ '[pack]\nentry = "pack.py"\nclass = "TestPack"\nversion = "1.0.0"\ngdMinVersion = "4.2.0"\n'
+ )
+ (pack_dir / "pack.py").write_text("class TestPack: pass\n")
+
+
+def start_server() -> tuple[HTTPServer, int]:
+ import os
+ os.chdir(SERVE_DIR)
+
+ class QuietHandler(SimpleHTTPRequestHandler):
+ def log_message(self, format, *args):
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), QuietHandler)
+ port = server.server_address[1]
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ return server, port
+
+
+def cleanup():
+ if WORK_DIR.exists():
+ shutil.rmtree(WORK_DIR)
+
+
+def main():
+ from PySide6.QtWidgets import QApplication
+ app = QApplication.instance() or QApplication(sys.argv)
+
+ cleanup()
+ expected_sha = setup_server_content()
+ setup_local_pack()
+ server, port = start_server()
+ base = f"http://127.0.0.1:{port}"
+ print(f"Local server: {base}")
+
+ import app.services.update_service as us
+
+ original_sources = us.SOURCES.copy()
+ original_staging = us.STAGING_DIR
+ original_exec_dir = us.executableDir
+
+ us.SOURCES["github"] = {
+ "versions": f"{base}/versions.json",
+ "raw": base,
+ "release": f"{base}/releases",
+ }
+ us.STAGING_DIR = FAKE_STAGING
+ us.executableDir = FAKE_EXEC_DIR
+
+ original_fetchFile = us.fetchFile
+ async def mock_fetchFile(url, outputPath, onProgress=None):
+ import urllib.request
+ urllib.request.urlretrieve(url, str(outputPath))
+ if onProgress:
+ onProgress(100)
+ us.fetchFile = mock_fetchFile
+
+ passed = 0
+ failed = 0
+
+ def check(name, condition):
+ nonlocal passed, failed
+ if condition:
+ print(f" ✓ {name}")
+ passed += 1
+ else:
+ print(f" ✗ {name}")
+ failed += 1
+
+ signals: list = []
+
+ from app.services.update_service import UpdateService, UpdateState, installPendingPacks, buildAssetUrl
+
+ class FakeCoroutineRunner:
+ def submit(self, coro, **kwargs):
+ loop = asyncio.new_event_loop()
+ try:
+ loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+ try:
+ svc = UpdateService(FakeCoroutineRunner())
+ svc.changed.connect(lambda info: signals.append(info))
+
+ # ── Test 1: _fetchVersions ──
+ print("\n[Test 1] _fetchVersions via raw URL")
+ loop = asyncio.new_event_loop()
+ data = loop.run_until_complete(svc._fetchVersions())
+ loop.close()
+ check("returns dict", isinstance(data, dict))
+ check("app.version = 99.0.0", data.get("app", {}).get("version") == "99.0.0")
+ check("packs.test_pack exists", "test_pack" in data.get("packs", {}))
+ check("source set to github", svc._source == "github")
+
+ # ── Test 2: _check ──
+ print("\n[Test 2] _check detects app + pack updates")
+ signals.clear()
+ svc._source = ""
+ loop = asyncio.new_event_loop()
+ loop.run_until_complete(svc._check())
+ loop.close()
+
+ states = [(s.targetId, s.state) for s in signals]
+ check("app CHECKING emitted", ("app", UpdateState.CHECKING) in states)
+ check("app AVAILABLE emitted", ("app", UpdateState.AVAILABLE) in states)
+ check("test_pack AVAILABLE emitted", ("test_pack", UpdateState.AVAILABLE) in states)
+
+ app_info = next((s for s in signals if s.targetId == "app" and s.state == UpdateState.AVAILABLE), None)
+ check("app latestVersion=99.0.0", app_info and app_info.latestVersion == "99.0.0")
+
+ pack_info = next((s for s in signals if s.targetId == "test_pack" and s.state == UpdateState.AVAILABLE), None)
+ check("pack latestVersion=2.0.0", pack_info and pack_info.latestVersion == "2.0.0")
+ check("pack currentVersion=1.0.0", pack_info and pack_info.currentVersion == "1.0.0")
+
+ # ── Test 3: _downloadPack ──
+ print("\n[Test 3] _downloadPack via raw URL")
+ signals.clear()
+ loop = asyncio.new_event_loop()
+ loop.run_until_complete(svc._download("test_pack"))
+ loop.close()
+
+ dl_states = [(s.targetId, s.state) for s in signals]
+ check("DOWNLOADING emitted", ("test_pack", UpdateState.DOWNLOADING) in dl_states)
+ check("READY emitted", ("test_pack", UpdateState.READY) in dl_states)
+ check("FAILED not emitted", ("test_pack", UpdateState.FAILED) not in dl_states)
+
+ zip_path = FAKE_STAGING / "test_pack.zip"
+ check("zip downloaded", zip_path.is_file())
+ if zip_path.is_file():
+ check("sha256 matches", sha256(zip_path) == expected_sha)
+
+ # ── Test 4: _applyPack ──
+ print("\n[Test 4] _applyPack stages to _pending")
+ svc._applyPack("test_pack")
+ pending = FAKE_EXEC_DIR / "features" / "test_pack_pending"
+ check("pending dir created", pending.is_dir())
+ check("manifest.toml in pending", (pending / "manifest.toml").is_file())
+ check("zip removed after apply", not zip_path.is_file())
+
+ # ── Test 5: installPendingPacks ──
+ print("\n[Test 5] installPendingPacks swaps pending → final")
+ features_dir = FAKE_EXEC_DIR / "features"
+ installPendingPacks(features_dir)
+ check("pending dir gone", not pending.exists())
+ check("test_pack dir exists", (features_dir / "test_pack").is_dir())
+
+ import tomllib
+ with open(features_dir / "test_pack" / "manifest.toml", "rb") as f:
+ manifest = tomllib.load(f)
+ check("version updated to 2.0.0", manifest.get("pack", {}).get("version") == "2.0.0")
+
+ # ── Test 6: buildAssetUrl ──
+ print("\n[Test 6] buildAssetUrl uses SOURCES table")
+ url = buildAssetUrl("github", "4.3.0", "Ghost-Downloader-v4.3.0-Windows-x86_64.zip")
+ check("URL correct", url == f"{base}/releases/v4.3.0/Ghost-Downloader-v4.3.0-Windows-x86_64.zip")
+
+ # ── Summary ──
+ print(f"\n{'='*40}")
+ print(f"Passed: {passed} Failed: {failed}")
+ if failed:
+ print("SOME TESTS FAILED")
+ sys.exit(1)
+ else:
+ print("ALL TESTS PASSED")
+
+ finally:
+ us.SOURCES = original_sources
+ us.STAGING_DIR = original_staging
+ us.executableDir = original_exec_dir
+ us.fetchFile = original_fetchFile
+ server.shutdown()
+ cleanup()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/versions.json b/versions.json
new file mode 100644
index 00000000..3f093525
--- /dev/null
+++ b/versions.json
@@ -0,0 +1,11 @@
+{
+ "app": {},
+ "packs": {
+ "http_pack": {
+ "version": "1.0.0",
+ "file": "http_pack.zip",
+ "sha256": "e79d7004982deab4341890f1e46e4e36204ca7ce2ba9aca4aa2d6e5922055a4a",
+ "gdMinVersion": "4.2.0"
+ }
+ }
+}