The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(sources): add fetchRawFile/fetchReleaseAsset with multi-source fallback
XiaoYouChR2d8fc2b33883
diff --git a/app/services/update_service.py b/app/services/update_service.pyindex f990c74f..048da6db 100644--- a/app/services/update_service.py+++ b/app/services/update_service.py@@ -16,12 +16,11 @@ from typing import TYPE_CHECKINGfrom PySide6.QtCore import QObject, Signalfrom loguru import logger-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.sources import buildDownloadUrl, buildRawUrl, fetchJson+from app.sources import fetchJson, fetchRawFile, fetchReleaseAssetfrom app.update import APP_REPO, isNewerif TYPE_CHECKING:@@ -113,7 +112,6 @@ class UpdateService(QObject):super().__init__(parent)self._coroutineRunner = coroutineRunnerself._infos: dict[str, UpdateInfo] = {}- self._source = ""self._versionsData: dict = {}def check(self) -> None:@@ -174,7 +172,7 @@ class UpdateService(QObject):async def _fetchVersions(self) -> dict | None:try:- data, self._source = await fetchJson(APP_REPO, "main", "versions.json")+ data, _ = await fetchJson(APP_REPO, "main", "versions.json")return dataexcept RuntimeError:return None@@ -199,24 +197,23 @@ class UpdateService(QObject):async def _downloadApp(self, info: UpdateInfo) -> None:appData = self._versionsData.get("app", {})version = appData.get("version", "")+ tag = f"v{version}"platformKey = buildPlatformKey()patches = appData.get("patches", {})patch = patches.get(platformKey)if patch and patch.get("from") == VERSION:- url = buildDownloadUrl(APP_REPO, f"v{version}", patch["file"], source=self._source)sha = patch.get("sha256", "")outputPath = STAGING_DIR / "patch.hdiff"- await fetchFile(url, outputPath,- onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))+ await fetchReleaseAsset(APP_REPO, tag, patch["file"], outputPath,+ onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))- if sha:- if not matchChecksum(outputPath, sha):- outputPath.unlink(missing_ok=True)- self._emit("app", UpdateState.FAILED, error="校验失败")- return+ if sha and not matchChecksum(outputPath, sha):+ outputPath.unlink(missing_ok=True)+ self._emit("app", UpdateState.FAILED, error="校验失败")+ returnself._emit("app", UpdateState.READY)return@@ -229,8 +226,8 @@ class UpdateService(QObject):archivePath = STAGING_DIR / full["file"]sha = full.get("sha256", "")- await fetchFile(buildDownloadUrl(APP_REPO, f"v{version}", full["file"], source=self._source), archivePath,- onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))+ await fetchReleaseAsset(APP_REPO, tag, full["file"], archivePath,+ onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))if sha and not matchChecksum(archivePath, sha):archivePath.unlink(missing_ok=True)@@ -255,10 +252,10 @@ 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 = 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))+ await fetchRawFile(APP_REPO, "main", f"dist/packs/{filename}", outputPath,+ onProgress=lambda p: self._emit(packId, UpdateState.DOWNLOADING, progress=p))expectedSha = packData.get("sha256", "")if expectedSha and not matchChecksum(outputPath, expectedSha):diff --git a/app/sources.py b/app/sources.pyindex fb50378e..4f8e567a 100644--- a/app/sources.py+++ b/app/sources.py@@ -1,11 +1,12 @@from __future__ import annotationsfrom dataclasses import dataclass-from typing import Any+from pathlib import Path+from typing import Any, Callablefrom loguru import logger-from app.client import buildClient+from app.client import buildClient, fetchFile@dataclass(frozen=True)@@ -129,6 +130,40 @@ async def fetchJson(repo: str, branch: str, path: str) -> tuple[dict, str]:raise RuntimeError(f"无法获取 {repo}/{branch}/{path}")+async def fetchRawFile(+ repo: str, 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 repo+ endpoints = SOURCES[source]+ url = f"{endpoints.raw}/{mapped}{endpoints.rawInfix}{branch}/{path}"+ try:+ await fetchFile(url, outputPath, onProgress=onProgress)+ return source+ except Exception as e:+ logger.debug("从 {} 下载 {}/{} 失败: {}", source, repo, path, repr(e))+ continue+ raise RuntimeError(f"无法下载 {repo}/{branch}/{path}")+++async def fetchReleaseAsset(+ repo: str, 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 repo+ endpoints = SOURCES[source]+ url = f"{endpoints.download}/{mapped}/releases/download/{tag}/{asset}"+ try:+ await fetchFile(url, outputPath, onProgress=onProgress)+ return source+ except Exception as e:+ logger.debug("从 {} 下载 {}/{} 失败: {}", source, repo, asset, repr(e))+ continue+ raise RuntimeError(f"无法下载 {repo}/{tag}/{asset}")++PYPI_MIRRORS = {"gitcode": "https://mirrors.bfsu.edu.cn/pypi/web/json","github": "https://pypi.org/pypi",