Skip to content

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

feat(sources): add fetchRawFile/fetchReleaseAsset with multi-source fallback

XiaoYouChR2d8fc2b33883
diff --git a/app/services/update_service.py b/app/services/update_service.py
index f990c74f..048da6db 100644
--- a/app/services/update_service.py
+++ b/app/services/update_service.py
@@ -16,12 +16,11 @@ from typing import TYPE_CHECKING
from PySide6.QtCore import QObject, Signal
from loguru import logger
-from app.client import fetchFile
from app.config.constants import VERSION
from app.config.paths import APP_DATA_DIR, executableDir
from app.platform.filesystem import matchChecksum
from app.models.pack import PackManifest
-from app.sources import buildDownloadUrl, buildRawUrl, fetchJson
+from app.sources import fetchJson, fetchRawFile, fetchReleaseAsset
from app.update import APP_REPO, isNewer
if TYPE_CHECKING:
@@ -113,7 +112,6 @@ class UpdateService(QObject):
super().__init__(parent)
self._coroutineRunner = coroutineRunner
self._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 data
except 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="校验失败")
+ return
self._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.py
index fb50378e..4f8e567a 100644
--- a/app/sources.py
+++ b/app/sources.py
@@ -1,11 +1,12 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any
+from pathlib import Path
+from typing import Any, Callable
from 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",