The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor(checksum): 校验值模块平铺到 app/,统一哈希实现
XiaoYouChR80c52e6d6201
diff --git a/app/models/checksum.py b/app/checksum.pysimilarity index 69%rename from app/models/checksum.pyrename to app/checksum.pyindex ec280cb1..64d3a4be 100644--- a/app/models/checksum.py+++ b/app/checksum.py@@ -5,15 +5,12 @@ import hashlibfrom collections.abc import Callablefrom pathlib import Path+ALGORITHMS = sorted(hashlib.algorithms_available)COMMON_ALGORITHMS = ("md5", "sha1", "sha256", "sha512")SHAKE_LENGTHS = {"shake_128": 32, "shake_256": 64}CHUNK_SIZE = 4 * 1024 * 1024-def toAlgorithms() -> list[str]:- return sorted(hashlib.algorithms_available)--async def toChecksum(path: Path, algorithm: str, onProgress: Callable[[int], None]) -> str:hasher = hashlib.new(algorithm)size = path.stat().st_size@@ -25,3 +22,12 @@ async def toChecksum(path: Path, algorithm: str, onProgress: Callable[[int], NononProgress(done * 100 // size)length = SHAKE_LENGTHS.get(algorithm)return hasher.hexdigest(length) if length else hasher.hexdigest()+++def parseChecksum(text: str) -> str:+ return (text.split() or [""])[0].lower()+++def matchChecksum(checksums: dict[str, str], expected: str) -> str | None:+ expected = expected.strip().lower()+ return next((algorithm for algorithm, value in checksums.items() if value == expected), None)diff --git a/app/install.py b/app/install.pyindex 3188c803..f72a67c9 100644--- a/app/install.py+++ b/app/install.py@@ -1,7 +1,6 @@from __future__ import annotationsimport asyncio-import hashlibimport globimport shutilimport tarfile@@ -78,11 +77,3 @@ async def installArchive(archive: Path, folder: Path, root: str = "", subtree: sawait asyncio.to_thread(install)finally:deletePath(archive)---async def matchSha256(file: Path, sha256File: Path) -> bool:- text = sha256File.read_text(encoding="utf-8", errors="ignore").strip()- expected = text.split()[0].lower() if text else ""- with file.open("rb") as source:- actual = (await asyncio.to_thread(hashlib.file_digest, source, "sha256")).hexdigest()- return expected == actualdiff --git a/app/platform/filesystem.py b/app/platform/filesystem.pyindex 5ed725b7..83fe6b43 100644--- a/app/platform/filesystem.py+++ b/app/platform/filesystem.py@@ -1,6 +1,5 @@from __future__ import annotations-import hashlibimport reimport shutilimport sys@@ -107,14 +106,6 @@ def findExecutable(installFolder: Path, name: str) -> str:return toPosixPath(found) if found else ""-def matchChecksum(filePath: Path, expectedHex: str) -> bool:- digest = hashlib.sha256()- with filePath.open("rb") as f:- for chunk in iter(lambda: f.read(1 << 20), b""):- digest.update(chunk)- return digest.hexdigest().lower() == expectedHex.lower()--def deletePath(path: Path) -> None:if path.is_dir() and not path.is_symlink():shutil.rmtree(path, ignore_errors=True)diff --git a/app/services/task_service.py b/app/services/task_service.pyindex c9b911cd..07d43307 100644--- a/app/services/task_service.py+++ b/app/services/task_service.py@@ -390,7 +390,7 @@ class TaskService:return work.progress if work else Nonedef startChecksum(self, task: Task, algorithm: str) -> None:- from app.models.checksum import toChecksum+ from app.checksum import toChecksumwork = ChecksumWork()self._checksums[task.taskId] = workwork.workId = self._coroutineRunner.submit(diff --git a/app/services/update_service.py b/app/services/update_service.pyindex 50883fb1..666d847f 100644--- a/app/services/update_service.py+++ b/app/services/update_service.py@@ -16,10 +16,10 @@ from typing import TYPE_CHECKINGfrom app.signal import Signalfrom loguru import logger+from app.checksum import parseChecksum, toChecksumfrom app.config.constants import VERSIONfrom app.config.paths import APP_DATA_DIR, FEATURES_DIR, EXECUTABLE_DIRfrom app.platform.android import IS_ANDROID-from app.platform.filesystem import matchChecksumfrom app.models.pack import PackManifestfrom app.models.task import TaskError, toTaskErrorfrom app.sources import fetchJson, fetchRawFile, fetchReleaseAsset@@ -219,7 +219,7 @@ class UpdateService:await fetchReleaseAsset(APP_REPO, tag, patch["file"], outputPath,onProgress=lambda p: self._emit("app", UpdateState.DOWNLOADING, progress=p))- if sha and not matchChecksum(outputPath, sha):+ if sha and await toChecksum(outputPath, "sha256", lambda _: None) != parseChecksum(sha):outputPath.unlink(missing_ok=True)self._emit("app", UpdateState.FAILED, error=TaskError("校验失败"))return@@ -238,7 +238,7 @@ class UpdateService: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):+ if sha and await toChecksum(archivePath, "sha256", lambda _: None) != parseChecksum(sha):archivePath.unlink(missing_ok=True)self._emit("app", UpdateState.FAILED, error=TaskError("校验失败"))return@@ -266,7 +266,7 @@ class UpdateService:onProgress=lambda p: self._emit(packId, UpdateState.DOWNLOADING, progress=p))expectedSha = packData.get("sha256", "")- if expectedSha and not matchChecksum(outputPath, expectedSha):+ if expectedSha and await toChecksum(outputPath, "sha256", lambda _: None) != parseChecksum(expectedSha):outputPath.unlink(missing_ok=True)self._emit(packId, UpdateState.FAILED, error=TaskError("校验失败"))returndiff --git a/app/view/cards/task_cards.py b/app/view/cards/task_cards.pyindex f44d15ee..6798cd3e 100644--- a/app/view/cards/task_cards.py+++ b/app/view/cards/task_cards.py@@ -17,7 +17,7 @@ from qfluentwidgets import (from app.config.cfg import cfgfrom app.format import toReadableSize, toReadableTime-from app.models.checksum import COMMON_ALGORITHMS, toAlgorithms+from app.checksum import ALGORITHMS, COMMON_ALGORITHMSfrom app.models.task import TaskStatus, SpecialFileSizefrom app.platform.desktop import openFile, revealInFolderfrom app.platform.filesystem import isExisting, isFolder@@ -391,10 +391,9 @@ class TaskCard(CardWidget):if isFolder(self._task.outputPath) or not isExisting(self._task.outputPath):self._setStatus(self.tr("文件不存在,无法校验"))return- algorithms = toAlgorithms()menu = RoundMenu(parent=self)moreMenu = RoundMenu(self.tr("更多"), self)- for algorithm in algorithms:+ for algorithm in ALGORITHMS:action = Action(algorithm.upper(), self)action.setCheckable(True)action.setChecked(algorithm in self._task.checksums)diff --git a/app/view/dialogs/task_drawer.py b/app/view/dialogs/task_drawer.pyindex 153b18f9..6822ea7a 100644--- a/app/view/dialogs/task_drawer.py+++ b/app/view/dialogs/task_drawer.py@@ -19,6 +19,7 @@ from qfluentwidgets import (from qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBasefrom qfluentwidgets.components.widgets.menu import TextEditMenu+from app.checksum import matchChecksumfrom app.config.cfg import cfgfrom app.format import toReadableSize, toReadableTimefrom app.i18n import toLocalizedError@@ -46,11 +47,6 @@ def toTimeText(timestamp: int) -> str:return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")-def matchChecksum(task: Task, expected: str) -> str | None:- expected = expected.strip().lower()- return next((algorithm for algorithm, value in task.checksums.items() if value == expected), None)--def toCaptionStyle(label: CaptionLabel) -> None:label.setFixedWidth(CAPTION_WIDTH)label.setTextColor(QColor(96, 96, 96), QColor(206, 206, 206))@@ -296,7 +292,7 @@ class ChecksumCard(DetailCard):def _refreshMatch(self) -> None:expected = self.expectedEdit.text()- algorithm = matchChecksum(self._task, expected)+ algorithm = matchChecksum(self._task.checksums, expected)self.expectedEdit.setError(bool(expected.strip()) and algorithm is None)if algorithm:self.expectedEdit.setCustomFocusedBorderColor(*MATCH_COLORS)diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex 85a82f81..64b3b199 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -14,7 +14,8 @@ from app.platform.android import IS_ANDROID, nativeLibraryDirfrom app.platform.filesystem import deletePath, findExecutablefrom app.models.task import TaskErrorfrom app.sources import Repo, fetchLatestRelease, fetchReleaseAsset-from app.install import installArchive, matchSha256+from app.checksum import parseChecksum, toChecksum+from app.install import installArchiveFFMPEG_REPO = Repo("XiaoYouChR/Ghost-Downloader-FFmpeg", mirrors={"gitcode": "XiaoYouChR/Ghost-Downloader-FFmpeg"})@@ -124,7 +125,8 @@ class FFmpegRuntime(BinaryRuntime):sha256File = folder / f"{asset}.sha256"await fetchReleaseAsset(FFMPEG_REPO, tag, asset, archive, onProgress)await fetchReleaseAsset(FFMPEG_REPO, tag, sha256File.name, sha256File)- isMatched = await matchSha256(archive, sha256File)+ isMatched = (parseChecksum(sha256File.read_text(encoding="utf-8", errors="ignore"))+ == await toChecksum(archive, "sha256", lambda _: None))deletePath(sha256File)if not isMatched:deletePath(archive)diff --git a/tests/test_checksum.py b/tests/test_checksum.pyindex 6ded2fb3..287cf167 100644--- a/tests/test_checksum.py+++ b/tests/test_checksum.py@@ -1,6 +1,6 @@"""Checksum 的计算与 TaskService 生命周期。-Seam: toChecksum(真实临时文件);TaskService.startChecksum/cancelChecksum(S7 stub runner)+Seam: toChecksum(真实临时文件);parseChecksum/matchChecksum(纯函数);TaskService.startChecksum/cancelChecksum(S7 stub runner)"""from __future__ import annotations@@ -9,12 +9,12 @@ import hashlibimport pytest-from app.models.checksum import toAlgorithms, toChecksum+from app.checksum import ALGORITHMS, matchChecksum, parseChecksum, toChecksumfrom app.models.task import Task, TaskStatusfrom tests.test_task_service import makeTask, service, platform, speedMeter # noqa: F401[email protected]("algorithm", toAlgorithms())[email protected]("algorithm", ALGORITHMS)def test_every_listed_algorithm_matches_hashlib(tmp_path, algorithm):path = tmp_path / "blob.bin"path.write_bytes(bytes(range(256)) * 64)@@ -26,7 +26,7 @@ def test_every_listed_algorithm_matches_hashlib(tmp_path, algorithm):def test_progress_reaches_100_for_multi_chunk_file(tmp_path, monkeypatch):- monkeypatch.setattr("app.models.checksum.CHUNK_SIZE", 1000)+ monkeypatch.setattr("app.checksum.CHUNK_SIZE", 1000)path = tmp_path / "blob.bin"path.write_bytes(b"x" * 2500)progress: list[int] = []@@ -116,16 +116,17 @@ class TestChecksumLifecycle:class TestMatchChecksum:- def test_match_ignores_case_and_surrounding_spaces(self, qapp):- from app.view.dialogs.task_drawer import matchChecksum- task = makeTask()- task.checksums = {"md5": "aa11", "sha256": "bb22"}+ def test_match_ignores_case_and_surrounding_spaces(self):+ assert matchChecksum({"md5": "aa11", "sha256": "bb22"}, " BB22\n") == "sha256"- assert matchChecksum(task, " BB22\n") == "sha256"+ def test_mismatch_gives_none(self):+ assert matchChecksum({"md5": "aa11"}, "cc33") is None- def test_mismatch_gives_none(self, qapp):- from app.view.dialogs.task_drawer import matchChecksum- task = makeTask()- task.checksums = {"md5": "aa11"}- assert matchChecksum(task, "cc33") is None+class TestParseChecksum:++ def test_sha256sum_line_gives_lowercase_hex(self):+ assert parseChecksum("AB12 ffmpeg.tar.gz\n") == "ab12"++ def test_blank_text_gives_empty(self):+ assert parseChecksum(" \n") == ""diff --git a/tests/test_runtime_install.py b/tests/test_runtime_install.pyindex 50ca22c7..b095925e 100644--- a/tests/test_runtime_install.py+++ b/tests/test_runtime_install.py@@ -1,7 +1,6 @@from __future__ import annotationsimport asyncio-import hashlibimport ioimport shutilimport sys@@ -11,7 +10,7 @@ from pathlib import Pathimport pytest-from app.install import deleteInstalled, installArchive, installFile, matchSha256+from app.install import deleteInstalled, installArchive, installFilefrom app.models.pack import BinaryRuntime, VersionInfofrom app.models.task import TaskErrorfrom app.services.coroutine_runner import CoroutineRunner@@ -181,16 +180,6 @@ async def test_tar_replaces_a_locked_file_and_keeps_its_mode(tmp_path, lockRunniassert sorted(p.name for p in tmp_path.iterdir() if not p.name.endswith(".old")) == ["ffmpeg"][email protected]("digestOf, expected", [(b"payload", True), (b"other", False)])-async def test_match_sha256(tmp_path, digestOf, expected):- file = tmp_path / "ffmpeg.tar.gz"- file.write_bytes(b"payload")- sha256File = tmp_path / "ffmpeg.tar.gz.sha256"- sha256File.write_text(f"{hashlib.sha256(digestOf).hexdigest().upper()} ffmpeg.tar.gz\n")-- assert await matchSha256(file, sha256File) is expected--class FakeRuntime(BinaryRuntime):name = "fake"