The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor(sources): Repo 类型替代 GITCODE_REPOS,镜像知识归属 pack
XiaoYouChRb375609d8a21
diff --git a/app/sources.py b/app/sources.pyindex 193cfba4..e3c60fb1 100644--- a/app/sources.py+++ b/app/sources.py@@ -1,6 +1,6 @@from __future__ import annotations-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable@@ -9,6 +9,15 @@ from loguru import loggerfrom app.client import buildClient, fetchFile+@dataclass(frozen=True)+class Repo:+ name: str+ mirrors: dict[str, str] = field(default_factory=dict)++ def forSource(self, source: str) -> str:+ return self.mirrors.get(source, self.name)++@dataclass(frozen=True)class SourceEndpoints:api: str@@ -34,11 +43,6 @@ SOURCES = {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:@@ -86,11 +90,10 @@ class Release:)-async def fetchLatestRelease(repo: str) -> tuple[Release, str]:+async def fetchLatestRelease(repo: Repo) -> tuple[Release, str]:for source in SOURCE_ORDER:- mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repoendpoints = SOURCES[source]- url = f"{endpoints.api}/{mapped}/releases/latest"+ url = f"{endpoints.api}/{repo.forSource(source)}/releases/latest"headers = {"accept": "application/vnd.github+json"} if source == "github" else {}client = buildClient(headers=headers, timeout=15)try:@@ -99,23 +102,22 @@ async def fetchLatestRelease(repo: str) -> tuple[Release, str]:data = await resp.json()return Release.fromResponse(data), sourceexcept Exception as e:- logger.debug("从 {} 获取 {} release 失败: {}", source, repo, repr(e))+ logger.debug("从 {} 获取 {} release 失败: {}", source, repo.name, repr(e))continuefinally:client.close()- raise RuntimeError(f"无法获取 {repo} 的最新 release")+ raise RuntimeError(f"无法获取 {repo.name} 的最新 release")-async def fetchLatestTag(repo: str) -> tuple[str, str]:+async def fetchLatestTag(repo: Repo) -> tuple[str, str]:release, source = await fetchLatestRelease(repo)return release.version, source-async def fetchJson(repo: str, branch: str, path: str) -> tuple[dict, str]:+async def fetchJson(repo: Repo, branch: str, path: str) -> tuple[dict, str]:for source in SOURCE_ORDER:- mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repoendpoints = SOURCES[source]- url = f"{endpoints.raw}/{mapped}{endpoints.rawInfix}{branch}/{path}"+ url = f"{endpoints.raw}/{repo.forSource(source)}{endpoints.rawInfix}{branch}/{path}"client = buildClient(timeout=15)try:resp = await client.get(url)@@ -123,45 +125,43 @@ async def fetchJson(repo: str, branch: str, path: str) -> tuple[dict, str]:result = await resp.json()return result, sourceexcept Exception as e:- logger.debug("从 {} 获取 {}/{} 失败: {}", source, repo, path, repr(e))+ logger.debug("从 {} 获取 {}/{} 失败: {}", source, repo.name, path, repr(e))continuefinally:client.close()- raise RuntimeError(f"无法获取 {repo}/{branch}/{path}")+ raise RuntimeError(f"无法获取 {repo.name}/{branch}/{path}")async def fetchRawFile(- repo: str, branch: str, path: str, outputPath: Path,+ repo: Repo, branch: str, path: str, outputPath: Path,onProgress: Callable[[float], None] | None = None,) -> str:for source in SOURCE_ORDER:- mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repoendpoints = SOURCES[source]- url = f"{endpoints.raw}/{mapped}{endpoints.rawInfix}{branch}/{path}"+ url = f"{endpoints.raw}/{repo.forSource(source)}{endpoints.rawInfix}{branch}/{path}"try:await fetchFile(url, outputPath, onProgress=onProgress)return sourceexcept Exception as e:- logger.debug("从 {} 下载 {}/{} 失败: {}", source, repo, path, repr(e))+ logger.debug("从 {} 下载 {}/{} 失败: {}", source, repo.name, path, repr(e))continue- raise RuntimeError(f"无法下载 {repo}/{branch}/{path}")+ raise RuntimeError(f"无法下载 {repo.name}/{branch}/{path}")async def fetchReleaseAsset(- repo: str, tag: str, asset: str, outputPath: Path,+ repo: Repo, tag: str, asset: str, outputPath: Path,onProgress: Callable[[float], None] | None = None,) -> str:for source in SOURCE_ORDER:- mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repoendpoints = SOURCES[source]- url = f"{endpoints.download}/{mapped}/releases/download/{tag}/{asset}"+ url = f"{endpoints.download}/{repo.forSource(source)}/releases/download/{tag}/{asset}"try:await fetchFile(url, outputPath, onProgress=onProgress)return sourceexcept Exception as e:- logger.debug("从 {} 下载 {}/{} 失败: {}", source, repo, asset, repr(e))+ logger.debug("从 {} 下载 {}/{} 失败: {}", source, repo.name, asset, repr(e))continue- raise RuntimeError(f"无法下载 {repo}/{tag}/{asset}")+ raise RuntimeError(f"无法下载 {repo.name}/{tag}/{asset}")PYPI_MIRRORS = {@@ -193,13 +193,11 @@ async def fetchPypiJson(package: str) -> dict:raise RuntimeError(f"无法获取 PyPI 包信息: {package}")-def buildDownloadUrl(repo: str, tag: str, asset: str, *, source: str) -> str:- mapped = GITCODE_REPOS.get(repo, repo) if source == "gitcode" else repo+def buildDownloadUrl(repo: Repo, tag: str, asset: str, *, source: str) -> str:endpoints = SOURCES[source]- return f"{endpoints.download}/{mapped}/releases/download/{tag}/{asset}"+ return f"{endpoints.download}/{repo.forSource(source)}/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+def buildRawUrl(repo: Repo, branch: str, path: str, *, source: str) -> str:endpoints = SOURCES[source]- return f"{endpoints.raw}/{mapped}{endpoints.rawInfix}{branch}/{path}"+ return f"{endpoints.raw}/{repo.forSource(source)}{endpoints.rawInfix}{branch}/{path}"diff --git a/app/update.py b/app/update.pyindex c0dbccbb..6c84dcfe 100644--- a/app/update.py+++ b/app/update.py@@ -5,9 +5,9 @@ import sysfrom PySide6.QtCore import QVersionNumber-from app.sources import Release, ReleaseAsset, fetchLatestRelease+from app.sources import Release, ReleaseAsset, Repo, fetchLatestRelease-APP_REPO = "XiaoYouChR/Ghost-Downloader-3"+APP_REPO = Repo("XiaoYouChR/Ghost-Downloader-3")def isNewer(current: str, latest: str) -> bool:diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.pyindex f67db08e..dd76649b 100644--- a/features/ed2k_pack/config.py+++ b/features/ed2k_pack/config.py@@ -7,10 +7,11 @@ from pathlib import Pathfrom app.config.paths import APP_DATA_DIRfrom app.models.pack import BinaryRuntime, PackConfigfrom app.platform.filesystem import toPosixPath+from app.sources import Repofrom PySide6.QtCore import QT_TRANSLATE_NOOP as Nfrom qfluentwidgets import ConfigItem, BoolValidator, FluentIcon, RangeConfigItem, RangeValidator-ED2K_REPO = "XiaoYouChR/Python-eD2k"+ED2K_REPO = Repo("XiaoYouChR/Python-eD2k")class ED2kConfig(PackConfig):diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex 8b86f740..fb1cf140 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -13,9 +13,10 @@ from app.config.paths import APP_DATA_DIRfrom app.models.pack import BinaryRuntime, PackConfig, VersionInfofrom app.platform.android import IS_ANDROID, nativeLibraryDirfrom app.platform.filesystem import findExecutable+from app.sources import Repo-FFMPEG_REPO = "XiaoYouChR/Ghost-Downloader-FFmpeg"+FFMPEG_REPO = Repo("XiaoYouChR/Ghost-Downloader-FFmpeg")def ffmpegAssetTarget() -> str:diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex 3df8efa5..4f20f3a4 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -20,8 +20,9 @@ from app.config.paths import APP_DATA_DIRfrom app.models.pack import BinaryRuntime, PackConfigfrom app.platform.android import IS_ANDROID, nativeLibraryDirfrom app.platform.filesystem import findExecutable+from app.sources import Repo-M3U8_REPO = "nilaoda/N_m3u8DL-RE"+M3U8_REPO = Repo("nilaoda/N_m3u8DL-RE", mirrors={"gitcode": "XiaoYouChR/N_m3u8DL-RE-mirror"})class M3U8Config(PackConfig):diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.pyindex aed8b982..191bbfb6 100644--- a/features/yt_dlp_pack/config.py+++ b/features/yt_dlp_pack/config.py@@ -16,8 +16,9 @@ from app.config.paths import APP_DATA_DIRfrom app.models.pack import BinaryRuntime, PackConfig, VersionInfofrom app.platform.android import IS_ANDROIDfrom app.platform.filesystem import findExecutable+from app.sources import Repo-QJS_REPO = "quickjs-ng/quickjs"+QJS_REPO = Repo("quickjs-ng/quickjs", mirrors={"gitcode": "XiaoYouChR/quickjs-mirror"})COOKIE_DOMAIN = ".youtube.com"AUTH_COOKIE_NAMES = ("LOGIN_INFO", "SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID")diff --git a/tools/test_update_flow.py b/tools/test_update_flow.pyindex e5bbe08e..a24666ec 100644--- a/tools/test_update_flow.py+++ b/tools/test_update_flow.py@@ -312,7 +312,7 @@ def main():# ── 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)+ check("URL contains repo and version", f"{APP_REPO.name}/releases/download/v4.3.0/" in url)# ── Test 7: _downloadApp full release ──print("\n[Test 7] _downloadApp full release")