The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor(sources): 统一 GitHub/GitCode 源路由
XiaoYouChR23da0d73cd9b
diff --git a/app/services/update_service.py b/app/services/update_service.pyindex 69523ee9..f990c74f 100644--- a/app/services/update_service.py+++ b/app/services/update_service.py@@ -16,31 +16,19 @@ from typing import TYPE_CHECKINGfrom PySide6.QtCore import QObject, Signalfrom loguru import logger-from app.client import buildClient, fetchFile+from app.client import fetchFilefrom app.config.constants import VERSIONfrom app.config.paths import APP_DATA_DIR, executableDirfrom app.platform.filesystem import matchChecksumfrom app.models.pack import PackManifest-from app.update import isNewer+from app.sources import buildDownloadUrl, buildRawUrl, fetchJson+from app.update import APP_REPO, isNewerif TYPE_CHECKING:from app.services.coroutine_runner import CoroutineRunnerSTAGING_DIR = Path(APP_DATA_DIR) / "update_staging"-SOURCES = {- "github": {- "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": {- "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",- },-}-OS_MAP = {"win32": "Windows", "darwin": "macOS", "linux": "Linux"}MACHINE_MAP = {"AMD64": "x86_64", "x86_64": "x86_64", "aarch64": "arm64", "arm64": "arm64"}@@ -49,10 +37,6 @@ def buildPlatformKey() -> str:return f"{OS_MAP[sys.platform]}-{MACHINE_MAP[platform.machine()]}"-def buildAssetUrl(source: str, version: str, assetName: str) -> str:- return f"{SOURCES[source]['release']}/v{version}/{assetName}"--def extractZip(archivePath: Path, targetDir: Path) -> None:with zipfile.ZipFile(archivePath) as zf:zf.extractall(targetDir)@@ -189,22 +173,11 @@ class UpdateService(QObject):latestVersion=remoteVersion)async def _fetchVersions(self) -> dict | None:- sources = [self._source] if self._source else list(SOURCES)- for sourceName in sources:- try:- client = buildClient(timeout=15)- try:- resp = await client.get(SOURCES[sourceName]["versions"])- resp.raise_for_status()- result = await resp.json()- self._source = sourceName- return result- finally:- client.close()- except Exception as e:- logger.debug("从 {} 获取版本信息失败: {}", sourceName, repr(e))- continue- return None+ try:+ data, self._source = await fetchJson(APP_REPO, "main", "versions.json")+ return data+ except RuntimeError:+ return Noneasync def _download(self, targetId: str) -> None:info = self._infos.get(targetId)@@ -232,7 +205,7 @@ class UpdateService(QObject):patch = patches.get(platformKey)if patch and patch.get("from") == VERSION:- url = buildAssetUrl(self._source, version, patch["file"])+ url = buildDownloadUrl(APP_REPO, f"v{version}", patch["file"], source=self._source)sha = patch.get("sha256", "")outputPath = STAGING_DIR / "patch.hdiff"@@ -256,7 +229,7 @@ class UpdateService(QObject):archivePath = STAGING_DIR / full["file"]sha = full.get("sha256", "")- await fetchFile(buildAssetUrl(self._source, version, full["file"]), archivePath,+ await fetchFile(buildDownloadUrl(APP_REPO, f"v{version}", full["file"], source=self._source), archivePath,onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))if sha and not matchChecksum(archivePath, sha):@@ -282,7 +255,7 @@ class UpdateService(QObject):async def _downloadPack(self, packId: str, info: UpdateInfo) -> None:packData = self._versionsData.get("packs", {}).get(packId, {})filename = packData.get("file", f"{packId}.zip")- url = f"{SOURCES[self._source]['raw']}/dist/packs/{filename}"+ url = buildRawUrl(APP_REPO, "main", f"dist/packs/{filename}", source=self._source)outputPath = STAGING_DIR / f"{packId}.zip"await fetchFile(url, outputPath, onProgress=lambda p: self._emit(packId, UpdateState.DOWNLOADING, progress=p))diff --git a/app/sources.py b/app/sources.pynew file mode 100644index 00000000..3e247989--- /dev/null+++ b/app/sources.py@@ -0,0 +1,141 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from loguru import logger++from app.client import buildClient+++@dataclass(frozen=True)+class SourceEndpoints:+ api: str+ download: str+ raw: str+ rawInfix: str+++SOURCES = {+ "gitcode": SourceEndpoints(+ api="https://api.gitcode.com/api/v5/repos",+ download="https://gitcode.com",+ raw="https://raw.gitcode.com",+ rawInfix="/raw/",+ ),+ "github": SourceEndpoints(+ api="https://api.github.com/repos",+ download="https://github.com",+ raw="https://raw.githubusercontent.com",+ rawInfix="/",+ ),+}++SOURCE_ORDER = ("gitcode", "github")++GITCODE_REPOS = {+ "nilaoda/N_m3u8DL-RE": "XiaoYouChR/N_m3u8DL-RE-mirror",+ "quickjs-ng/quickjs": "XiaoYouChR/quickjs-mirror",+}+++@dataclass(frozen=True)+class ReleaseAsset:+ name: str+ size: int+ downloadCount: int+ downloadUrl: str+++@dataclass(frozen=True)+class Release:+ version: str+ publishedAt: str+ body: str+ pageUrl: str+ prerelease: bool+ assets: list[ReleaseAsset]++ @classmethod+ def fromResponse(cls, data: dict[str, Any]) -> Release:+ version = ""+ for key in ("tag_name", "name"):+ value = str(data.get(key) or "").strip()+ if value:+ version = value+ break++ assets = [+ ReleaseAsset(+ name=a.get("name", ""),+ size=a.get("size", 0),+ downloadCount=a.get("download_count", 0),+ downloadUrl=a.get("browser_download_url", ""),+ )+ for a in data.get("assets", [])+ ]++ return cls(+ version=version or "Unknown",+ publishedAt=data.get("published_at", "") or data.get("created_at", ""),+ body=data.get("body", "") or "",+ pageUrl=data.get("html_url", ""),+ prerelease=data.get("prerelease", False),+ assets=assets,+ )+++async def fetchLatestRelease(repo: str) -> tuple[Release, str]:+ for source in SOURCE_ORDER:+ mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repo+ endpoints = SOURCES[source]+ url = f"{endpoints.api}/{mapped}/releases/latest"+ headers = {"accept": "application/vnd.github+json"} if source == "github" else {}+ client = buildClient(headers=headers, timeout=15)+ try:+ resp = await client.get(url)+ resp.raise_for_status()+ data = await resp.json()+ return Release.fromResponse(data), source+ except Exception as e:+ logger.debug("从 {} 获取 {} release 失败: {}", source, repo, repr(e))+ continue+ finally:+ client.close()+ raise RuntimeError(f"无法获取 {repo} 的最新 release")+++async def fetchLatestTag(repo: str) -> tuple[str, str]:+ release, source = await fetchLatestRelease(repo)+ return release.version, source+++async def fetchJson(repo: str, branch: str, path: str) -> tuple[dict, str]:+ for source in SOURCE_ORDER:+ mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repo+ endpoints = SOURCES[source]+ url = f"{endpoints.raw}/{mapped}{endpoints.rawInfix}{branch}/{path}"+ client = buildClient(timeout=15)+ try:+ resp = await client.get(url)+ resp.raise_for_status()+ result = await resp.json()+ return result, source+ except Exception as e:+ logger.debug("从 {} 获取 {}/{} 失败: {}", source, repo, path, repr(e))+ continue+ finally:+ client.close()+ raise RuntimeError(f"无法获取 {repo}/{branch}/{path}")+++def buildDownloadUrl(repo: str, tag: str, asset: str, *, source: str) -> str:+ mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repo+ endpoints = SOURCES[source]+ return f"{endpoints.download}/{mapped}/releases/download/{tag}/{asset}"+++def buildRawUrl(repo: str, branch: str, path: str, *, source: str) -> str:+ mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repo+ endpoints = SOURCES[source]+ return f"{endpoints.raw}/{mapped}{endpoints.rawInfix}{branch}/{path}"diff --git a/app/update.py b/app/update.pyindex 3ef9e47b..c0dbccbb 100644--- a/app/update.py+++ b/app/update.py@@ -2,12 +2,12 @@ from __future__ import annotationsimport platformimport sys-from dataclasses import dataclass-from typing import Anyfrom PySide6.QtCore import QVersionNumber-from app.client import buildClient+from app.sources import Release, ReleaseAsset, fetchLatestRelease++APP_REPO = "XiaoYouChR/Ghost-Downloader-3"def isNewer(current: str, latest: str) -> bool:@@ -15,75 +15,10 @@ def isNewer(current: str, latest: str) -> bool:v2 = QVersionNumber.fromString(latest.lstrip("vV"))return v2 > v1-RELEASE_API = "https://api.github.com/repos/XiaoYouChR/Ghost-Downloader-3/releases/latest"---@dataclass(frozen=True)-class ReleaseAsset:- name: str- size: int- downloadCount: int- downloadUrl: str---@dataclass(frozen=True)-class Release:- version: str- publishedAt: str- body: str- pageUrl: str- prerelease: bool- assets: list[ReleaseAsset]-- @classmethod- def fromResponse(cls, data: dict[str, Any]) -> Release:- version = ""- for key in ("tag_name", "name"):- value = str(data.get(key) or "").strip()- if value:- version = value- break-- assets = [- ReleaseAsset(- name=a.get("name", ""),- size=a.get("size", 0),- downloadCount=a.get("download_count", 0),- downloadUrl=a.get("browser_download_url", ""),- )- for a in data.get("assets", [])- ]-- return cls(- version=version or "Unknown",- publishedAt=data.get("published_at", ""),- body=data.get("body", ""),- pageUrl=data.get("html_url", ""),- prerelease=data.get("prerelease", False),- assets=assets,- )-async def fetchRelease() -> Release:- client = buildClient(headers={"accept": "application/vnd.github+json"})- try:- response = await client.get(RELEASE_API)- response.raise_for_status()- data = await response.json()- return Release.fromResponse(data)- finally:- client.close()---async def fetchGitHubLatestTag(repo: str) -> str:- client = buildClient(headers={"accept": "application/vnd.github+json"}, timeout=15)- try:- resp = await client.get(f"https://api.github.com/repos/{repo}/releases/latest")- resp.raise_for_status()- data = await resp.json()- return data.get("tag_name", "")- finally:- client.close()+ release, _ = await fetchLatestRelease(APP_REPO)+ return releasedef bestAsset(release: Release) -> ReleaseAsset | None:diff --git a/app/view/dialogs/release_info.py b/app/view/dialogs/release_info.pyindex 39eb1865..94e63f12 100644--- a/app/view/dialogs/release_info.py+++ b/app/view/dialogs/release_info.py@@ -16,7 +16,7 @@ from app.view.components.markdown_viewer import MarkdownViewerfrom app.view.components.tree_view import AutoSizingTreeViewif TYPE_CHECKING:- from app.update import Release, ReleaseAsset+ from app.sources import Release, ReleaseAssetclass ReleaseInfoDialog(MessageBoxBase):diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.pyindex 822402fc..f67db08e 100644--- a/features/ed2k_pack/config.py+++ b/features/ed2k_pack/config.py@@ -10,7 +10,7 @@ from app.platform.filesystem import toPosixPathfrom PySide6.QtCore import QT_TRANSLATE_NOOP as Nfrom qfluentwidgets import ConfigItem, BoolValidator, FluentIcon, RangeConfigItem, RangeValidator-RELEASE_BASE = "https://github.com/XiaoYouChR/Python-eD2k/releases/latest/download"+ED2K_REPO = "XiaoYouChR/Python-eD2k"class ED2kConfig(PackConfig):@@ -85,15 +85,18 @@ class ED2kRuntime(BinaryRuntime):return Path(ed2kConfig.installFolder.value)async def fetchLatestVersion(self) -> str:- from app.update import fetchGitHubLatestTag- return await fetchGitHubLatestTag("XiaoYouChR/Python-eD2k")+ from app.sources import fetchLatestTag+ tag, _ = await fetchLatestTag(ED2K_REPO)+ return tagasync def createInstallTask(self):from app.install import FetchStep, InstallTask+ from app.sources import buildDownloadUrl, fetchLatestTagfrom .task import ED2kInstallStep+ tag, source = await fetchLatestTag(ED2K_REPO)assetName = _assetName()- url = f"{RELEASE_BASE}/{assetName}"+ url = buildDownloadUrl(ED2K_REPO, tag, assetName, source=source)folder = self.installFolder()binaryName = "goed2kd.exe" if sys.platform == "win32" else "goed2kd"binaryPath = toPosixPath(folder / binaryName)diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex 6b3de454..8b86f740 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -15,7 +15,7 @@ from app.platform.android import IS_ANDROID, nativeLibraryDirfrom app.platform.filesystem import findExecutable-RELEASE_BASE = "https://github.com/XiaoYouChR/Ghost-Downloader-FFmpeg"+FFMPEG_REPO = "XiaoYouChR/Ghost-Downloader-FFmpeg"def ffmpegAssetTarget() -> str:@@ -106,15 +106,19 @@ class FFmpegRuntime(BinaryRuntime):return VersionInfo(version)async def fetchLatestVersion(self) -> str:- from app.update import fetchGitHubLatestTag- return await fetchGitHubLatestTag("XiaoYouChR/Ghost-Downloader-FFmpeg")+ from app.sources import fetchLatestTag+ tag, _ = await fetchLatestTag(FFMPEG_REPO)+ return tagasync def createInstallTask(self):from app.install import createInstallTask+ from app.sources import buildDownloadUrl, fetchLatestTag+ tag, source = await fetchLatestTag(FFMPEG_REPO)target = ffmpegAssetTarget()extension = "zip" if sys.platform == "win32" else "tar.gz"- url = f"{RELEASE_BASE}/releases/latest/download/ffmpeg-{target}.{extension}"+ asset = f"ffmpeg-{target}.{extension}"+ url = buildDownloadUrl(FFMPEG_REPO, tag, asset, source=source)executableNames = (("ffmpeg.exe", "ffprobe.exe") if sys.platform == "win32"else ("ffmpeg", "ffprobe")@@ -124,7 +128,7 @@ class FFmpegRuntime(BinaryRuntime):outputFolder=self.installFolder(),name=f"FFmpeg 安装 ({target})",executableNames=executableNames,- sha256Url=f"{url}.sha256",+ sha256Url=buildDownloadUrl(FFMPEG_REPO, tag, f"{asset}.sha256", source=source),)diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex 5cb7e81a..3df8efa5 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -160,10 +160,13 @@ class M3U8Runtime(BinaryRuntime):return findExecutable(self.installFolder(), "N_m3u8DL-RE")async def fetchLatestVersion(self) -> str:- from app.update import fetchGitHubLatestTag- return await fetchGitHubLatestTag(M3U8_REPO)+ from app.sources import fetchLatestTag+ tag, _ = await fetchLatestTag(M3U8_REPO)+ return tagasync def createInstallTask(self):+ from app.sources import fetchLatestRelease+machine = platform.machine().lower()if sys.platform == "win32":if machine in {"amd64", "x86_64"}:@@ -179,35 +182,24 @@ class M3U8Runtime(BinaryRuntime):else:raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")- url, tag = await self._fetchAssetUrl(target)+ release, _ = await fetchLatestRelease(M3U8_REPO)+ extension = ".zip" if sys.platform == "win32" else ".tar.gz"+ url = ""+ for asset in release.assets:+ if target in asset.name and asset.name.endswith(extension):+ url = asset.downloadUrl+ break+ if not url:+ raise RuntimeError(f"未找到适配 {target} 的 N_m3u8DL-RE 安装包")from app.install import createInstallTaskbinaryName = "N_m3u8DL-RE.exe" if sys.platform == "win32" else "N_m3u8DL-RE"return createInstallTask(url=url,outputFolder=self.installFolder(),- name=f"N_m3u8DL-RE {tag} ({target})",+ name=f"N_m3u8DL-RE {release.version} ({target})",executableNames=(binaryName,),)- async def _fetchAssetUrl(self, target: str) -> tuple[str, str]:- from app.client import buildClient- url = f"https://api.github.com/repos/{M3U8_REPO}/releases/latest"- client = buildClient(headers={"accept": "application/vnd.github+json"}, timeout=15)- try:- resp = await client.get(url)- resp.raise_for_status()- data = await resp.json()- finally:- client.close()-- tag = data.get("tag_name", "")- extension = ".zip" if sys.platform == "win32" else ".tar.gz"- for asset in data.get("assets", []):- name = asset.get("name", "")- if target in name and name.endswith(extension):- return asset["browser_download_url"], tag- raise RuntimeError(f"未找到适配 {target} 的 N_m3u8DL-RE 安装包")-m3u8Runtime = M3U8Runtime()diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.pyindex 58e8fb1a..2004daa8 100644--- a/features/yt_dlp_pack/config.py+++ b/features/yt_dlp_pack/config.py@@ -18,7 +18,7 @@ from app.platform.android import IS_ANDROIDfrom app.platform.filesystem import findExecutablePYPI_API = "https://pypi.org/pypi/yt-dlp/json"-QJS_RELEASE_BASE = "https://github.com/quickjs-ng/quickjs/releases/latest/download"+QJS_REPO = "quickjs-ng/quickjs"COOKIE_DOMAIN = ".youtube.com"AUTH_COOKIE_NAMES = ("LOGIN_INFO", "SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID")@@ -238,8 +238,11 @@ class YouTubeRuntime(BinaryRuntime):))return task+ from app.sources import buildDownloadUrl, fetchLatestTag+qjsBinaryName = "qjs.exe" if sys.platform == "win32" else "qjs"- qjsUrl = f"{QJS_RELEASE_BASE}/{_qjsAssetName()}"+ qjsTag, qjsSource = await fetchLatestTag(QJS_REPO)+ qjsUrl = buildDownloadUrl(QJS_REPO, qjsTag, _qjsAssetName(), source=qjsSource)task = InstallTask(name="YouTube 运行环境安装",diff --git a/tools/test_update_flow.py b/tools/test_update_flow.pyindex ff6b0634..e5bbe08e 100644--- a/tools/test_update_flow.py+++ b/tools/test_update_flow.py@@ -163,8 +163,10 @@ def main():print(f"Local server: {base}")import app.services.update_service as us+ import app.sources as sources- original_sources = us.SOURCES.copy()+ original_sources = sources.SOURCES.copy()+ original_order = sources.SOURCE_ORDERoriginal_staging = us.STAGING_DIRoriginal_exec_dir = us.executableDiroriginal_fetchFile = us.fetchFile@@ -172,11 +174,13 @@ def main():original_extractDmg = us.extractDmgoriginal_extractTarXz = us.extractTarXz- us.SOURCES["github"] = {- "versions": f"{base}/versions.json",- "raw": base,- "release": f"{base}/releases",- }+ sources.SOURCES["github"] = sources.SourceEndpoints(+ api=f"http://127.0.0.1:{port}/api",+ download=f"http://127.0.0.1:{port}",+ raw=f"http://127.0.0.1:{port}",+ rawInfix="/",+ )+ sources.SOURCE_ORDER = ("github",)us.STAGING_DIR = FAKE_STAGINGus.executableDir = FAKE_EXEC_DIR@@ -221,8 +225,10 @@ def main():from app.services.update_service import (UpdateService, UpdateState, installPendingPacks,- buildAssetUrl, buildPlatformKey,+ buildPlatformKey,)+ from app.sources import buildDownloadUrl+ from app.update import APP_REPOclass FakeCoroutineRunner:def submit(self, coro, **kwargs):@@ -303,10 +309,10 @@ def main():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")+ # ── Test 6: buildDownloadUrl ──+ print("\n[Test 6] buildDownloadUrl uses sources module")+ url = buildDownloadUrl(APP_REPO, "v4.3.0", "Ghost-Downloader-v4.3.0-Windows-x86_64.zip", source="github")+ check("URL contains repo and version", f"{APP_REPO}/releases/download/v4.3.0/" in url)# ── Test 7: _downloadApp full release ──print("\n[Test 7] _downloadApp full release")@@ -418,7 +424,8 @@ def main():print("ALL TESTS PASSED")finally:- us.SOURCES = original_sources+ sources.SOURCES.update(original_sources)+ sources.SOURCE_ORDER = original_orderus.STAGING_DIR = original_stagingus.executableDir = original_exec_dirus.fetchFile = original_fetchFile