The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(runtime): 安装改为覆盖解压,yt-dlp 改走 PyPI
XiaoYouChR598b54a9779d
diff --git a/CONTEXT.md b/CONTEXT.mdindex 430588e4..d9bd1a8c 100644--- a/CONTEXT.md+++ b/CONTEXT.md@@ -125,7 +125,12 @@ _Avoid_: 直接操作 Task 的状态转换_Avoid_: module、extension**Binary Runtime**:-FeaturePack 可探测或提供安装任务的外部可执行文件家族。+FeaturePack 可探测、安装和卸载的外部可执行文件家族。安装由 Binary Runtime 自己完成,不是 Task。+_Avoid_: 安装任务++**Install Folder**:+用户为一个 Binary Runtime 选定的文件夹。应用不独占它:安装只覆盖该 Runtime 自己的文件,卸载只删除这些文件,其他内容不动。+_Avoid_: 运行时目录、安装路径**Browser Service**:浏览器扩展的协议适配器:接收扩展消息,翻译为 Task Service 动词,返回结果。diff --git a/app/client.py b/app/client.pyindex ae80e2f2..f31ab1cc 100644--- a/app/client.py+++ b/app/client.py@@ -19,6 +19,7 @@ if TYPE_CHECKING:from wreq import ClientConfigFALLBACK_PROFILE = "chrome"+FETCH_READ_TIMEOUT = 30FAMILY_BY_PREFIX = {"Chrome": "chrome", "Edge": "edge", "Firefox": "firefox", "Opera": "opera",@@ -163,7 +164,7 @@ async def fetchFile(outputPath: Path,onProgress: Callable[[float], None] | None = None,) -> None:- client = buildClient()+ client = buildClient(readTimeout=FETCH_READ_TIMEOUT)try:outputPath.parent.mkdir(parents=True, exist_ok=True)response = await client.get(url)diff --git a/app/install.py b/app/install.pyindex aa8ae602..ce5ad69f 100644--- a/app/install.py+++ b/app/install.py@@ -3,314 +3,61 @@ from __future__ import annotationsimport asyncioimport hashlibimport shutil-import sysimport tarfileimport zipfile-from dataclasses import dataclass, field-from pathlib import Path, PurePosixPath-from time import perf_counter-from urllib.parse import urlparse--from app.models.task import Task, TaskError, TaskStep-from app.platform.filesystem import deletePath, toPosixPath--CHUNK_SIZE = 1 << 20-ARCHIVE_SUFFIXES = (".zip", ".tar.gz")---def isArchive(name: str) -> bool:- lower = name.lower()- return any(lower.endswith(suffix) for suffix in ARCHIVE_SUFFIXES)---@dataclass(kw_only=True, eq=False)-class InstallTask(Task):- hasOutputFile = False- installFolder: str = ""-- @property- def canPause(self) -> bool:- return False-- def deleteFiles(self):- if self.installFolder:- deletePath(Path(self.installFolder))- return- super().deleteFiles()---@dataclass(kw_only=True)-class ExtractStep(TaskStep):- canPause = False-- archivePath: str- outputFolder: str- archiveSize: int = 0- root: str = ""- subtree: str = ""-- async def _extractZip(self, archive: Path, outputFolder: Path):- with zipfile.ZipFile(archive) as zf:- members = []- for info in zf.infolist():- if info.is_dir():- continue- name = info.filename- if self.root:- if not name.startswith(self.root):+from pathlib import Path++from app.models.task import TaskError+from app.platform.filesystem import deletePath+++async def installArchive(archive: Path, folder: Path, root: str = "", subtree: str = "") -> None:+ safeRoot = folder.resolve()++ def toMemberPath(name: str) -> Path | None:+ relativeName = name+ if root:+ if not relativeName.startswith(root):+ return None+ relativeName = relativeName[len(root):]+ if subtree and not relativeName.startswith(subtree):+ return None+ path = (folder / relativeName).resolve()+ if safeRoot not in path.parents:+ raise TaskError("压缩包包含不安全路径:{path}", path=name)+ path.parent.mkdir(parents=True, exist_ok=True)+ return path++ def install() -> None:+ lowered = archive.name.lower()+ if lowered.endswith((".zip", ".whl")):+ with zipfile.ZipFile(archive) as zf:+ for info in zf.infolist():+ if info.is_dir() or (path := toMemberPath(info.filename)) is None:continue- name = name[len(self.root):]- if self.subtree and not name.startswith(self.subtree):- continue- members.append((info, name))-- totalSize = sum(info.file_size for info, _ in members)- self.task.fileSize = max(self.archiveSize + totalSize, self.archiveSize)-- safeRoot = outputFolder.resolve()- extractedBytes = speedBytes = 0- speedTime = perf_counter()- for info, name in members:- memberPath = (outputFolder / name).resolve()- if safeRoot not in {memberPath, *memberPath.parents}:- raise TaskError("压缩包包含不安全路径:{path}", path=info.filename)- memberPath.parent.mkdir(parents=True, exist_ok=True)- with zf.open(info, "r") as source, open(memberPath, "wb") as target:- while chunk := source.read(CHUNK_SIZE):- target.write(chunk)- extractedBytes += len(chunk)- self.receivedBytes = extractedBytes- if totalSize > 0:- self.progress = min(99.5, extractedBytes / totalSize * 100)- now = perf_counter()- if now - speedTime >= 0.5:- self.speed = int((extractedBytes - speedBytes) / (now - speedTime))- speedBytes, speedTime = extractedBytes, now- await asyncio.sleep(0)-- async def _extractTar(self, archive: Path, outputFolder: Path):- with tarfile.open(archive, "r:*") as tf:- members = []- for m in tf.getmembers():- if not m.isfile():- continue- name = m.name- if self.root:- if not name.startswith(self.root):+ with zf.open(info) as source, open(path, "wb") as target:+ shutil.copyfileobj(source, target)+ elif lowered.endswith(".tar.gz"):+ with tarfile.open(archive, "r:gz") as tf:+ for member in tf.getmembers():+ if not member.isfile() or (path := toMemberPath(member.name)) is None:continue- name = name[len(self.root):]- if self.subtree and not name.startswith(self.subtree):- continue- members.append((m, name))-- totalSize = sum(m.size for m, _ in members)- self.task.fileSize = max(self.archiveSize + totalSize, self.archiveSize)-- safeRoot = outputFolder.resolve()- extractedBytes = speedBytes = 0- speedTime = perf_counter()- for member, name in members:- memberPath = (outputFolder / name).resolve()- if safeRoot not in {memberPath, *memberPath.parents}:- raise TaskError("压缩包包含不安全路径:{path}", path=member.name)- memberPath.parent.mkdir(parents=True, exist_ok=True)- source = tf.extractfile(member)- if source is None:- continue- with source, open(memberPath, "wb") as target:- while chunk := source.read(CHUNK_SIZE):- target.write(chunk)- extractedBytes += len(chunk)- self.receivedBytes = extractedBytes- if totalSize > 0:- self.progress = min(99.5, extractedBytes / totalSize * 100)- now = perf_counter()- if now - speedTime >= 0.5:- self.speed = int((extractedBytes - speedBytes) / (now - speedTime))- speedBytes, speedTime = extractedBytes, now- await asyncio.sleep(0)-- async def run(self, reportSpeed, waitForSpeedLimit) -> None:- archive = Path(self.archivePath)- if not archive.is_file():- raise TaskError("压缩包未找到:{path}", path=str(archive))-- outputFolder = Path(self.outputFolder)- self.progress = 0- self.speed = 0- self.receivedBytes = 0- outputFolder.mkdir(parents=True, exist_ok=True)-- lowered = archive.name.lower()- if lowered.endswith(".tar.gz"):- await self._extractTar(archive, outputFolder)- elif lowered.endswith(".zip"):- await self._extractZip(archive, outputFolder)+ with tf.extractfile(member) as source, open(path, "wb") as target:+ shutil.copyfileobj(source, target)+ path.chmod(member.mode & 0o777)else:raise TaskError("不支持的压缩格式:{name}", name=archive.name)+ try:+ folder.mkdir(parents=True, exist_ok=True)+ await asyncio.to_thread(install)+ finally:+ deletePath(archive)-@dataclass(kw_only=True)-class InstallStep(TaskStep):- canPause = False-- sourceFolder: str- installFolder: str- archivePath: str = ""- shouldDeleteSource: bool = True- executableNames: list[str] = field(default_factory=list)-- async def run(self, reportSpeed, waitForSpeedLimit) -> None:- sourceFolder = Path(self.sourceFolder)- installFolder = Path(self.installFolder)- archive = Path(self.archivePath) if self.archivePath else None-- try:- preserve = {sourceFolder.name}- if archive is not None and archive.parent == installFolder:- preserve.add(archive.name)- for child in installFolder.iterdir():- if child.name in preserve:- continue- if child.is_dir() and not child.is_symlink():- shutil.rmtree(child, ignore_errors=True)- else:- child.unlink(missing_ok=True)-- children = list(sourceFolder.iterdir())- contentRoot = children[0] if len(children) == 1 and children[0].is_dir() else sourceFolder-- for child in list(contentRoot.iterdir()):- shutil.move(str(child), str(installFolder / child.name))-- for name in self.executableNames:- executable = None- for candidate in (installFolder / "bin" / name, installFolder / name):- if candidate.is_file():- executable = candidate- break- if executable is None:- executable = next((c for c in installFolder.rglob(name) if c.is_file()), None)- if executable is None:- raise TaskError("解压后未找到可执行文件:{name}", name=name)- if sys.platform != "win32":- executable.chmod(executable.stat().st_mode | 0o755)-- if self.shouldDeleteSource and archive is not None and archive.exists():- archive.unlink()- finally:- if self.shouldDeleteSource and sourceFolder.exists():- shutil.rmtree(sourceFolder, ignore_errors=True)---@dataclass(kw_only=True)-class ChecksumStep(TaskStep):- canPause = False-- targetFile: str- sha256File: str-- async def run(self, reportSpeed, waitForSpeedLimit) -> None:- text = Path(self.sha256File).read_text(encoding="utf-8", errors="ignore").strip()- expected = text.split()[0].lower() if text else ""- if not expected:- raise TaskError("无法读取校验文件:{path}", path=self.sha256File)- actual = await asyncio.to_thread(self._sha256, Path(self.targetFile))- if expected != actual:- raise TaskError("SHA256 校验失败:期望 {expected},实际 {actual}", expected=expected, actual=actual)- deletePath(Path(self.sha256File))-- def _sha256(self, path: Path) -> str:- digest = hashlib.sha256()- with path.open("rb") as file:- for chunk in iter(lambda: file.read(CHUNK_SIZE), b""):- digest.update(chunk)- return digest.hexdigest().lower()---@dataclass(kw_only=True)-class BinaryInstallStep(TaskStep):- canPause = False-- binaryPath: str-- async def run(self, reportSpeed, waitForSpeedLimit) -> None:- path = Path(self.binaryPath)- if not path.is_file():- raise TaskError("下载的文件未找到:{path}", path=str(path))- if sys.platform != "win32":- path.chmod(path.stat().st_mode | 0o755)---@dataclass(kw_only=True)-class FetchStep(TaskStep):- canPause = False- url: str- outputFile: str = ""-- async def run(self, reportSpeed, waitForSpeedLimit) -> None:- from app.client import fetchFile-- def onProgress(p):- self.progress = p- reportSpeed()-- await fetchFile(self.url, Path(self.outputFile), onProgress=onProgress)---def createInstallTask(- url: str,- outputFolder: Path,- name: str = "",- executableNames: tuple[str, ...] = (),- sha256Url: str = "",-) -> InstallTask:- assetName = PurePosixPath(urlparse(url).path).name-- archive = isArchive(assetName)- if archive:- targetPath = toPosixPath(outputFolder / assetName)- else:- binaryName = executableNames[0] if executableNames else assetName- targetPath = toPosixPath(outputFolder / binaryName)-- task = InstallTask(- name=name or assetName,- url=url,- packId="install",- fileSize=0,- outputFolder=outputFolder,- installFolder=str(outputFolder),- )- stepIndex = 1- task.addStep(FetchStep(stepIndex=stepIndex, url=url, outputFile=targetPath))- stepIndex += 1-- if sha256Url:- sha256Path = toPosixPath(outputFolder / PurePosixPath(urlparse(sha256Url).path).name)- task.addStep(FetchStep(stepIndex=stepIndex, url=sha256Url, outputFile=sha256Path))- stepIndex += 1- task.addStep(ChecksumStep(- stepIndex=stepIndex, targetFile=targetPath, sha256File=sha256Path,- ))- stepIndex += 1-- if archive:- extractFolder = toPosixPath(outputFolder / ".extracting")- task.addStep(ExtractStep(- stepIndex=stepIndex,- archivePath=targetPath,- outputFolder=extractFolder,- ))- stepIndex += 1- task.addStep(InstallStep(- stepIndex=stepIndex,- sourceFolder=extractFolder,- installFolder=toPosixPath(outputFolder),- archivePath=targetPath,- executableNames=list(executableNames),- ))- else:- task.addStep(BinaryInstallStep(stepIndex=stepIndex, binaryPath=targetPath))- return task+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/models/pack.py b/app/models/pack.pyindex 49fd63f1..d69bfac4 100644--- a/app/models/pack.py+++ b/app/models/pack.py@@ -170,14 +170,19 @@ class BinaryRuntime:# ── Lifecycle ──- def delete(self) -> None:- folder = self.installFolder()- if folder.exists():- shutil.rmtree(folder)+ def installedPaths(self) -> list[Path]:+ raise NotImplementedError- async def createInstallTask(self, version: str = "") -> Task:+ async def install(self, version: str, onProgress: Callable[[float], None]) -> None:raise NotImplementedError+ def delete(self) -> None:+ for path in self.installedPaths():+ if path.is_dir() and not path.is_symlink():+ shutil.rmtree(path)+ else:+ path.unlink(missing_ok=True)+class PackPage:icon: ...diff --git a/app/platform/filesystem.py b/app/platform/filesystem.pyindex 65a04fcd..5ed725b7 100644--- a/app/platform/filesystem.py+++ b/app/platform/filesystem.py@@ -98,12 +98,8 @@ def localFilePath(url: str, validSuffixes: set[str] | None = None) -> Path | Nonreturn path-def findExecutable(installFolder: Path, name: str, *subdirs: str) -> str:+def findExecutable(installFolder: Path, name: str) -> str:exe = f"{name}.exe" if sys.platform == "win32" else name- for sub in subdirs:- candidate = installFolder / sub / exe- if candidate.is_file():- return toPosixPath(candidate)candidate = installFolder / exeif candidate.is_file():return toPosixPath(candidate)diff --git a/app/services/runtime_status.py b/app/services/runtime_status.pyindex 5c59781c..08ba5363 100644--- a/app/services/runtime_status.py+++ b/app/services/runtime_status.py@@ -1,6 +1,5 @@from __future__ import annotations-import asynciofrom dataclasses import dataclass, replacefrom typing import TYPE_CHECKING@@ -23,7 +22,7 @@ class RuntimeStatus:error: TaskError | None = NoneisBusy: bool = FalseisInstalling: bool = False- progress: float = 0+ progress: int = 0class RuntimeStatusService:@@ -99,22 +98,19 @@ class RuntimeStatusService:self.statusChanged.emit(status)async def _runInstall(self, runtime: BinaryRuntime, version: str = "") -> None:- from app.models.task import TaskStatus-- task = await runtime.createInstallTask(version)- task.setStatus(TaskStatus.RUNNING)-- def reportProgress(*_args):- step = next((s for s in task.steps if s.progress > 0), None)- if step:- runtimeId = runtime.runtimeId- current = self._statuses.get(runtimeId)- if current and current.isInstalling and current.progress != step.progress:- status = replace(current, progress=step.progress)- self._statuses[runtimeId] = status- self._coroutineRunner.post(self.statusChanged.emit, status)-- await task.run(reportProgress, lambda: asyncio.sleep(0))+ runtimeId = runtime.runtimeId++ def reportProgress(percent: float) -> None:+ progress = int(percent)+ current = self._statuses.get(runtimeId)+ if current and current.isInstalling and current.progress != progress:+ status = replace(current, progress=progress)+ self._statuses[runtimeId] = status+ self._coroutineRunner.post(self.statusChanged.emit, status)++ await runtime.install(version, reportProgress)+ if not runtime.isAppManaged():+ raise TaskError("安装后未找到 {name}", name=runtime.name)def _onInstallFinished(self, _, runtimeId: str) -> None:self._installingIds.discard(runtimeId)diff --git a/app/sources.py b/app/sources.pyindex 6507c955..50aed5df 100644--- a/app/sources.py+++ b/app/sources.py@@ -227,6 +227,8 @@ PYPI_MIRRORS = {"gitcode": "https://mirrors.bfsu.edu.cn/pypi/web/json","github": "https://pypi.org/pypi",}+PYPI_FILES = "https://files.pythonhosted.org/packages/"+PYPI_FILES_MIRROR = "https://mirrors.bfsu.edu.cn/pypi/web/packages/"def buildPypiUrl(package: str, *, source: str) -> str:@@ -236,25 +238,51 @@ def buildPypiUrl(package: str, *, source: str) -> str:return f"{base}/{package}/json"-async def fetchPypiJson(package: str) -> dict:+async def fetchPypiReleases(package: str) -> dict[str, list[dict]]:async def attempt(source):url = buildPypiUrl(package, source=source)client = buildClient(timeout=15)try:resp = await client.get(url)resp.raise_for_status()- return await resp.json()+ return (await resp.json())["releases"]except Exception as e:logger.debug("从 {} 获取 PyPI {} 失败: {}", source, package, repr(e))raisefinally:client.close()- result, index, _ = await staggered_race(- [lambda s=s: attempt(s) for s in SOURCE_ORDER], STAGGER_DELAY)- if index is not None:- return result- raise TaskError("无法获取 PyPI 包信息: {package}", package=package)+ results = await asyncio.gather(*[attempt(s) for s in SOURCE_ORDER], return_exceptions=True)+ succeeded = [r for r in results if not isinstance(r, BaseException)]+ if not succeeded:+ raise TaskError("无法获取 PyPI 包信息: {package}", package=package)+ releases: dict[str, list[dict]] = {}+ for result in reversed(succeeded):+ releases |= result+ return releases+++async def fetchPypiFile(url: str, outputPath: Path, onProgress: Callable[[float], None] | None = None) -> None:+ async def probe(candidate):+ client = buildClient(headers={"Range": "bytes=0-0"}, timeout=10)+ try:+ resp = await client.get(candidate)+ try:+ resp.raise_for_status()+ return candidate+ finally:+ resp.close()+ except Exception as e:+ logger.debug("下载 {} 失败: {}", candidate, repr(e))+ raise+ finally:+ client.close()++ candidates = [url, url.replace(PYPI_FILES, PYPI_FILES_MIRROR, 1)] if url.startswith(PYPI_FILES) else [url]+ result, index, _ = await staggered_race([lambda c=c: probe(c) for c in candidates], STAGGER_DELAY)+ if index is None:+ raise TaskError("无法下载 {url}", url=url)+ await fetchFile(result, outputPath, onProgress=onProgress)def buildDownloadUrl(repo: Repo, tag: str, asset: str, *, source: str) -> str:diff --git a/app/view/components/setting_cards.py b/app/view/components/setting_cards.pyindex 62be3814..977b55c4 100644--- a/app/view/components/setting_cards.py+++ b/app/view/components/setting_cards.py@@ -865,8 +865,10 @@ class RuntimeCard(SettingCard):)if status.isInstalling:- if status.progress > 0:- self.setContent(self.tr("正在安装... {0}%").format(f"{status.progress:.0f}"))+ if status.progress <= 0:+ self.setContent(self.tr("正在准备..."))+ elif status.progress < 100:+ self.setContent(self.tr("正在下载... {0}%").format(status.progress))else:self.setContent(self.tr("正在安装..."))self.installButton.hide()diff --git a/docs/adr/0017-runtime-install-is-not-a-task.md b/docs/adr/0017-runtime-install-is-not-a-task.mdnew file mode 100644index 00000000..a60956f5--- /dev/null+++ b/docs/adr/0017-runtime-install-is-not-a-task.md@@ -0,0 +1,18 @@+# Binary Runtime 安装不是 Task,只覆盖、只删自己的文件++Binary Runtime 的安装是 `BinaryRuntime.install(version, onProgress)` 里的一段直线代码:`fetchFile` 下载、`matchSha256` 校验、`installArchive` 覆盖解压。+不套 Task,也不复用 http_pack 的 `HttpTaskStep`。安装从不进 TaskService、不持久化、不可暂停、对用户不可见,不符合 Task 的定义;+为套用 Task 而付出的必填字段、手写 `stepIndex`、手动 `setStatus(RUNNING)`、速度与 fileSize 维护,全部换不来能力。+Install Folder 由用户选定、可能是共用目录,所以安装只覆盖、卸载只删除 `installedPaths()` 声明的路径,从不清空文件夹。++## Considered Options++- **InstallTask + Step**(37b3b75 至本 ADR 前):37b3b75 拆掉了 parse 路由,留下了 Task 外壳;通用 `InstallStep` 的清空文件夹、拆外层目录、rglob 找可执行文件,四个 Runtime 都用不上。+- **安装下载复用 `HttpTaskStep`**:多连接、断点续传可加速国内直连,但它依赖 Task 外壳(`outputPath`、`.ghd`、Placeholder)并让引擎层依赖 http_pack。安装包只有 4~13 MB,超时由 `fetchFile` 自己补齐。+- **清空 Install Folder 时移到回收站**:保住了误放的用户文件,但回收站里零散 N 项、移不了时状态说不清;各 Runtime 包都是平铺的固定文件,覆盖解压即完整替换,不需要清空。++## Consequences++- 安装不受 Download Speed Limit 约束,也不进 Speed Meter。+- `RuntimeStatus.progress` 只表示主安装包的下载百分比:0 为准备、1~99 为下载、100 为安装。+- 第三方包布局变了(例如多出外层目录)时,安装后 `isAppManaged()` 为假,安装以「安装后未找到」失败,需要在 pack 里改 `root`。diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.pyindex bf667ed5..b8c5abe8 100644--- a/features/ed2k_pack/config.py+++ b/features/ed2k_pack/config.py@@ -8,12 +8,10 @@ from app.config.cfg import BoolValidator, ConfigItem, RangeConfigItem, RangeValifrom app.i18n import Nfrom app.config.paths import APP_DATA_DIR-from app.install import FetchStep, InstallTaskfrom app.models.pack import BinaryRuntime, PackConfigfrom app.platform.android import IS_ANDROID, nativeLibraryDir-from app.platform.filesystem import findExecutable, toPosixPath-from app.sources import Repo, fetchLatestRelease, probeDownloadUrl-from .task import ED2kInstallStep+from app.platform.filesystem import findExecutable+from app.sources import Repo, fetchLatestRelease, fetchReleaseAssetED2K_REPO = Repo("XiaoYouChR/Python-eD2k", mirrors={"gitcode": "XiaoYouChR/Python-eD2k"})@@ -107,25 +105,15 @@ class ED2kRuntime(BinaryRuntime):async def fetchLatestVersion(self) -> str:return (await fetchLatestRelease(ED2K_REPO)).version- async def createInstallTask(self, version: str = ""):+ def installedPaths(self) -> list[Path]:+ return [self.installFolder() / ("goed2kd.exe" if sys.platform == "win32" else "goed2kd")]++ async def install(self, version: str, onProgress) -> None:tag = version or (await fetchLatestRelease(ED2K_REPO)).version- assetName = _assetName()- url = await probeDownloadUrl(ED2K_REPO, tag, assetName)- folder = self.installFolder()- binaryName = "goed2kd.exe" if sys.platform == "win32" else "goed2kd"- binaryPath = toPosixPath(folder / binaryName)-- task = InstallTask(- name=f"goed2kd 安装 ({assetName})",- url=url,- packId="ed2k",- fileSize=0,- outputFolder=folder,- installFolder=str(folder),- )- task.addStep(FetchStep(stepIndex=1, url=url, outputFile=binaryPath))- task.addStep(ED2kInstallStep(stepIndex=2, binaryPath=binaryPath))- return task+ binaryPath = self.installedPaths()[0]+ await fetchReleaseAsset(ED2K_REPO, tag, _assetName(), binaryPath, onProgress)+ if sys.platform != "win32":+ binaryPath.chmod(binaryPath.stat().st_mode | 0o755)def _assetName() -> str:diff --git a/features/ed2k_pack/task.py b/features/ed2k_pack/task.pyindex ca1bf9ee..520bf05c 100644--- a/features/ed2k_pack/task.py+++ b/features/ed2k_pack/task.py@@ -1,8 +1,6 @@from __future__ import annotations-import sysfrom dataclasses import dataclass-from pathlib import Pathfrom app.models.task import Task, TaskError, TaskStep, TaskStatusfrom .python_ed2k import Transfer@@ -78,16 +76,3 @@ class ED2kTaskStep(TaskStep):onStarted=onStarted,onProgress=onProgress,)---@dataclass(kw_only=True)-class ED2kInstallStep(TaskStep):- canPause = False- binaryPath: str = ""-- async def run(self, reportSpeed, waitForSpeedLimit) -> None:- path = Path(self.binaryPath)- if not path.is_file():- raise TaskError("{name} 未安装,请在设置中安装", name="goed2kd")- if sys.platform != "win32":- path.chmod(path.stat().st_mode | 0o755)diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex 117038a5..85a82f81 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -11,10 +11,10 @@ from app.config.cfg import ConfigItemfrom app.config.paths import APP_DATA_DIRfrom app.models.pack import BinaryRuntime, PackConfig, VersionInfofrom app.platform.android import IS_ANDROID, nativeLibraryDir-from app.platform.filesystem import findExecutable+from app.platform.filesystem import deletePath, findExecutablefrom app.models.task import TaskError-from app.sources import Repo, fetchLatestRelease, probeDownloadUrl-from app.install import createInstallTask+from app.sources import Repo, fetchLatestRelease, fetchReleaseAsset+from app.install import installArchive, matchSha256FFMPEG_REPO = Repo("XiaoYouChR/Ghost-Downloader-FFmpeg", mirrors={"gitcode": "XiaoYouChR/Ghost-Downloader-FFmpeg"})@@ -74,7 +74,7 @@ class FFmpegRuntime(BinaryRuntime):return ""binary = Path(nativeDir) / "libffmpeg.so"return str(binary) if binary.exists() else ""- return findExecutable(self.installFolder(), "ffmpeg", "bin")+ return findExecutable(self.installFolder(), "ffmpeg")def ffprobePath(self) -> str:if IS_ANDROID:@@ -83,7 +83,7 @@ class FFmpegRuntime(BinaryRuntime):return ""binary = Path(nativeDir) / "libffprobe.so"return str(binary) if binary.exists() else ""- return findExecutable(self.installFolder(), "ffprobe", "bin")+ return findExecutable(self.installFolder(), "ffprobe")async def probeVersion(self) -> VersionInfo:path = self.path()@@ -110,23 +110,26 @@ class FFmpegRuntime(BinaryRuntime):async def fetchLatestVersion(self) -> str:return (await fetchLatestRelease(FFMPEG_REPO)).version- async def createInstallTask(self, version: str = ""):+ def installedPaths(self) -> list[Path]:+ folder = self.installFolder()+ suffix = ".exe" if sys.platform == "win32" else ""+ return [folder / f"ffmpeg{suffix}", folder / f"ffprobe{suffix}", folder / "VERSION"]++ async def install(self, version: str, onProgress) -> None:tag = version or (await fetchLatestRelease(FFMPEG_REPO)).version- target = ffmpegAssetTarget()extension = "zip" if sys.platform == "win32" else "tar.gz"- asset = f"ffmpeg-{target}.{extension}"- url = await probeDownloadUrl(FFMPEG_REPO, tag, asset)- executableNames = (- ("ffmpeg.exe", "ffprobe.exe") if sys.platform == "win32"- else ("ffmpeg", "ffprobe")- )- return createInstallTask(- url=url,- outputFolder=self.installFolder(),- name=f"FFmpeg 安装 ({target})",- executableNames=executableNames,- sha256Url=await probeDownloadUrl(FFMPEG_REPO, tag, f"{asset}.sha256"),- )+ asset = f"ffmpeg-{ffmpegAssetTarget()}.{extension}"+ folder = self.installFolder()+ archive = folder / asset+ 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)+ deletePath(sha256File)+ if not isMatched:+ deletePath(archive)+ raise TaskError("安装包校验失败,可能已损坏,请重试")+ await installArchive(archive, folder)ffmpegRuntime = FFmpegRuntime()diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex d356a0fc..bb1a69d1 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -16,12 +16,12 @@ from app.config.cfg import (from app.i18n import Nfrom app.config.paths import APP_DATA_DIR-from app.install import createInstallTask+from app.install import installArchivefrom app.models.pack import BinaryRuntime, PackConfigfrom app.platform.android import IS_ANDROID, nativeLibraryDirfrom app.platform.filesystem import findExecutablefrom app.models.task import TaskError-from app.sources import Repo, fetchLatestRelease, probeDownloadUrl+from app.sources import Repo, fetchLatestRelease, fetchReleaseAssetM3U8_REPO = Repo("nilaoda/N_m3u8DL-RE", mirrors={"gitcode": "XiaoYouChR/N_m3u8DL-RE-mirror"})@@ -162,11 +162,13 @@ class M3U8Runtime(BinaryRuntime):return findExecutable(self.installFolder(), "N_m3u8DL-RE")async def fetchLatestVersion(self) -> str:- release = await fetchLatestRelease(M3U8_REPO)- self.release = release- return release.version+ return (await fetchLatestRelease(M3U8_REPO)).version++ def installedPaths(self) -> list[Path]:+ suffix = ".exe" if sys.platform == "win32" else ""+ return [self.installFolder() / f"N_m3u8DL-RE{suffix}"]- async def createInstallTask(self, version: str = ""):+ async def install(self, version: str, onProgress) -> None:machine = platform.machine().lower()if sys.platform == "win32":if machine in {"amd64", "x86_64"}:@@ -182,10 +184,7 @@ class M3U8Runtime(BinaryRuntime):else:raise TaskError("当前平台暂不支持一键安装 N_m3u8DL-RE: {platform}", platform=sys.platform)- release = getattr(self, "release", None)- if release is None or (version and release.version != version):- release = await fetchLatestRelease(M3U8_REPO)- self.release = release+ release = await fetchLatestRelease(M3U8_REPO)extension = ".zip" if sys.platform == "win32" else ".tar.gz"assetName = ""for asset in release.assets:@@ -195,13 +194,9 @@ class M3U8Runtime(BinaryRuntime):if not assetName:raise TaskError("未找到适配 {target} 的 N_m3u8DL-RE 安装包", target=target)- binaryName = "N_m3u8DL-RE.exe" if sys.platform == "win32" else "N_m3u8DL-RE"- return createInstallTask(- url=await probeDownloadUrl(M3U8_REPO, release.version, assetName),- outputFolder=self.installFolder(),- name=f"N_m3u8DL-RE {release.version} ({target})",- executableNames=(binaryName,),- )+ archive = self.installFolder() / assetName+ await fetchReleaseAsset(M3U8_REPO, release.version, assetName, archive, onProgress)+ await installArchive(archive, self.installFolder())m3u8Runtime = M3U8Runtime()diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.pyindex 8e3a8da9..a01af245 100644--- a/features/yt_dlp_pack/config.py+++ b/features/yt_dlp_pack/config.py@@ -13,10 +13,11 @@ from app.models.pack import BinaryRuntime, PackConfig, VersionInfofrom app.platform.android import IS_ANDROIDfrom app.platform.filesystem import findExecutablefrom app.models.task import TaskError-from app.sources import Repo, fetchLatestRelease, probeDownloadUrl+from app.install import installArchive+from app.sources import Repo, fetchLatestRelease, fetchPypiFile, fetchPypiReleases, fetchReleaseAsset+from app.update import parseVersionQJS_REPO = Repo("quickjs-ng/quickjs", mirrors={"gitcode": "XiaoYouChR/quickjs-mirror"})-YTDLP_NIGHTLY_REPO = Repo("yt-dlp/yt-dlp-nightly-builds")COOKIE_DOMAIN = ".youtube.com"AUTH_COOKIE_NAMES = ("LOGIN_INFO", "SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID")@@ -197,85 +198,44 @@ class YouTubeRuntime(BinaryRuntime):)async def fetchLatestVersion(self) -> str:- release = await fetchLatestRelease(YTDLP_NIGHTLY_REPO)- self._latestRelease = release- return release.version+ version, _ = await fetchNightlyWheel()+ return version- async def createInstallTask(self, version: str = ""):- from app.install import BinaryInstallStep, ExtractStep, FetchStep, InstallTask-- tarballUrl, tarballSize = await self._fetchTarballAsset()+ def installedPaths(self) -> list[Path]:+ folder = self.installFolder()+ if IS_ANDROID:+ return [folder / "yt_dlp"]+ return [folder / "yt_dlp", folder / ("qjs.exe" if sys.platform == "win32" else "qjs")]+ async def install(self, version: str, onProgress) -> None:folder = self.installFolder()- folder.mkdir(parents=True, exist_ok=True)- archiveName = "yt_dlp.tar.gz"+ if not IS_ANDROID:+ qjsTag = (await fetchLatestRelease(QJS_REPO)).version+ qjsPath = folder / ("qjs.exe" if sys.platform == "win32" else "qjs")+ await fetchReleaseAsset(QJS_REPO, qjsTag, _qjsAssetName(), qjsPath)+ if sys.platform != "win32":+ qjsPath.chmod(qjsPath.stat().st_mode | 0o755)++ _, wheelUrl = await fetchNightlyWheel()+ archive = folder / "yt_dlp.whl"+ await fetchPypiFile(wheelUrl, archive, onProgress)+ await installArchive(archive, folder, subtree="yt_dlp/")+++async def fetchNightlyWheel() -> tuple[str, str]:+ nightlies = {}+ for version, files in (await fetchPypiReleases("yt-dlp")).items():+ if "dev" not in version:+ continue+ wheel = next((f for f in files if f["filename"].endswith("-py3-none-any.whl") and not f.get("yanked")), None)+ if wheel:+ nightlies[parseVersion(version)] = wheel["url"]+ if not nightlies:+ raise TaskError("未找到 yt-dlp nightly")+ latest = max(nightlies)+ year, month, day, time = latest[:4]+ return f"{year}.{month:02d}.{day:02d}.{time:06d}", nightlies[latest]- if IS_ANDROID:- task = InstallTask(- name="yt-dlp 安装",- url=tarballUrl,- packId="disk",- fileSize=tarballSize,- outputFolder=folder,- installFolder=str(folder),- )- task.addStep(FetchStep(- stepIndex=1, url=tarballUrl,- outputFile=str(folder / archiveName),- ))- task.addStep(ExtractStep(- stepIndex=2,- archivePath=str(folder / archiveName),- outputFolder=str(folder),- archiveSize=tarballSize,- root="yt-dlp/",- subtree="yt_dlp/",- ))- return task-- qjsBinaryName = "qjs.exe" if sys.platform == "win32" else "qjs"- qjsTag = (await fetchLatestRelease(QJS_REPO)).version- qjsUrl = await probeDownloadUrl(QJS_REPO, qjsTag, _qjsAssetName())-- task = InstallTask(- name="YouTube 运行环境安装",- url=tarballUrl,- packId="disk",- fileSize=0,- outputFolder=folder,- installFolder=str(folder),- )- task.addStep(FetchStep(- stepIndex=1, url=tarballUrl,- outputFile=str(folder / archiveName),- ))- task.addStep(FetchStep(- stepIndex=2, url=qjsUrl,- outputFile=str(folder / qjsBinaryName),- ))- task.addStep(ExtractStep(- stepIndex=3,- archivePath=str(folder / archiveName),- outputFolder=str(folder),- archiveSize=tarballSize,- root="yt-dlp/",- subtree="yt_dlp/",- ))- task.addStep(BinaryInstallStep(- stepIndex=4,- binaryPath=str(folder / qjsBinaryName),- ))- return task-- async def _fetchTarballAsset(self) -> tuple[str, int]:- release = getattr(self, "_latestRelease", None)- if release is None:- release = await fetchLatestRelease(YTDLP_NIGHTLY_REPO)- self._latestRelease = release- for asset in release.assets:- if asset.name == "yt-dlp.tar.gz":- return asset.downloadUrl, asset.size- raise TaskError("未找到 yt-dlp nightly tarball")def _qjsAssetName() -> str:machine = platform.machine().lower()diff --git a/tests/test_runtime_install.py b/tests/test_runtime_install.pynew file mode 100644index 00000000..050851c6--- /dev/null+++ b/tests/test_runtime_install.py@@ -0,0 +1,220 @@+from __future__ import annotations++import asyncio+import hashlib+import io+import sys+import tarfile+import zipfile+from pathlib import Path++import pytest++from app.install import installArchive, matchSha256+from app.models.pack import BinaryRuntime, VersionInfo+from app.models.task import TaskError+from app.services.coroutine_runner import CoroutineRunner+from app.services.runtime_status import RuntimeStatusService+++def writeTar(path: Path, members: dict[str, bytes], mode: int = 0o755) -> Path:+ with tarfile.open(path, "w:gz") as tf:+ for name, data in members.items():+ info = tarfile.TarInfo(name)+ info.size = len(data)+ info.mode = mode+ tf.addfile(info, io.BytesIO(data))+ return path+++def writeZip(path: Path, members: dict[str, bytes]) -> Path:+ with zipfile.ZipFile(path, "w") as zf:+ for name, data in members.items():+ zf.writestr(name, data)+ return path+++async def test_tar_overwrites_old_version_and_keeps_user_files(tmp_path):+ folder = tmp_path / "FFmpeg"+ folder.mkdir()+ (folder / "ffmpeg").write_bytes(b"old")+ (folder / "notes.txt").write_bytes(b"user")+ archive = writeTar(folder / "ffmpeg.tar.gz", {"ffmpeg": b"new", "VERSION": b"8.1"})++ await installArchive(archive, folder)++ assert (folder / "ffmpeg").read_bytes() == b"new"+ assert (folder / "ffmpeg").stat().st_mode & 0o777 == 0o755+ assert (folder / "VERSION").read_bytes() == b"8.1"+ assert (folder / "notes.txt").read_bytes() == b"user"+ assert not archive.exists()+++async def test_tar_keeps_only_subtree_under_root(tmp_path):+ archive = writeTar(tmp_path / "yt_dlp.tar.gz", {+ "yt-dlp/yt_dlp/__init__.py": b"init",+ "yt-dlp/README.md": b"readme",+ "other/yt_dlp/x.py": b"x",+ }, mode=0o644)++ await installArchive(archive, tmp_path / "out", root="yt-dlp/", subtree="yt_dlp/")++ assert sorted(p.relative_to(tmp_path / "out").as_posix()+ for p in (tmp_path / "out").rglob("*") if p.is_file()) == ["yt_dlp/__init__.py"]+++async def test_zip_overwrites_and_deletes_archive(tmp_path):+ (tmp_path / "ffmpeg.exe").write_bytes(b"old")+ archive = writeZip(tmp_path / "ffmpeg.zip", {"ffmpeg.exe": b"new"})++ await installArchive(archive, tmp_path)++ assert (tmp_path / "ffmpeg.exe").read_bytes() == b"new"+ assert not archive.exists()+++async def test_unsafe_member_is_rejected_and_archive_deleted(tmp_path):+ folder = tmp_path / "folder"+ folder.mkdir()+ archive = writeTar(folder / "evil.tar.gz", {"../escaped": b"x"})++ with pytest.raises(TaskError):+ await installArchive(archive, folder)++ assert not (tmp_path / "escaped").exists()+ assert not archive.exists()++[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"++ def __init__(self, folder: Path, progresses: list[float] = (), error: Exception | None = None,+ isMissingAfterInstall: bool = False):+ self.folder = folder+ self.progresses = progresses+ self.error = error+ self.isMissingAfterInstall = isMissingAfterInstall++ def installFolder(self) -> Path:+ return self.folder++ def path(self) -> str:+ binary = self.folder / "fake"+ return str(binary) if binary.is_file() else ""++ async def probeVersion(self) -> VersionInfo:+ return VersionInfo("")++ def installedPaths(self) -> list[Path]:+ return [self.folder / "fake", self.folder / "lib"]++ async def install(self, version: str, onProgress) -> None:+ for progress in self.progresses:+ onProgress(progress)+ await asyncio.sleep(0)+ if self.error:+ raise self.error+ if not self.isMissingAfterInstall:+ (self.folder / "fake").write_bytes(b"bin")+++def test_delete_removes_only_installed_paths(tmp_path):+ (tmp_path / "fake").write_bytes(b"bin")+ (tmp_path / "lib").mkdir()+ (tmp_path / "lib" / "a.so").write_bytes(b"so")+ (tmp_path / "notes.txt").write_bytes(b"user")++ FakeRuntime(tmp_path).delete()++ assert [p.name for p in tmp_path.iterdir()] == ["notes.txt"]++[email protected](sys.platform == "win32", reason="POSIX 目录权限")+def test_delete_raises_when_a_path_cannot_be_deleted(tmp_path):+ (tmp_path / "fake").write_bytes(b"bin")+ tmp_path.chmod(0o555)+ try:+ with pytest.raises(PermissionError):+ FakeRuntime(tmp_path).delete()+ finally:+ tmp_path.chmod(0o755)+++async def runInstall(runtime: FakeRuntime) -> list:+ loop = asyncio.get_running_loop()+ service = RuntimeStatusService(CoroutineRunner(loop.call_soon, loop=loop))+ statuses = []+ service.statusChanged.connect(statuses.append)+ service.install(runtime)+ await asyncio.sleep(0.05)+ return statuses+++async def test_install_reports_each_whole_percent_once(tmp_path):+ statuses = await runInstall(FakeRuntime(tmp_path, [0.2, 0.9, 1.1, 1.8, 45.5, 100.0]))++ assert [s.progress for s in statuses if s.isInstalling] == [0, 1, 45, 100]+++async def test_install_failure_ends_installing_with_error(tmp_path):+ statuses = await runInstall(FakeRuntime(tmp_path, [50.0], TaskError("安装包校验失败,可能已损坏,请重试")))++ assert not statuses[-1].isInstalling+ assert statuses[-1].error.message == "安装包校验失败,可能已损坏,请重试"+++async def test_install_without_the_executable_fails(tmp_path):+ statuses = await runInstall(FakeRuntime(tmp_path, [100.0], isMissingAfterInstall=True))++ assert not statuses[-1].isInstalling+ assert statuses[-1].error.message == "安装后未找到 {name}"+++async def test_install_success_reports_installed_path(tmp_path):+ statuses = await runInstall(FakeRuntime(tmp_path, [100.0]))++ assert statuses[-1].error is None+ assert statuses[-1].path == str(tmp_path / "fake")+++async def test_wheel_installs_package_only(tmp_path):+ archive = writeZip(tmp_path / "yt_dlp.whl", {+ "yt_dlp/__init__.py": b"init",+ "yt_dlp-2026.9.27.232945.dev0.dist-info/METADATA": b"meta",+ })++ await installArchive(archive, tmp_path / "out", subtree="yt_dlp/")++ assert [p.relative_to(tmp_path / "out").as_posix()+ for p in (tmp_path / "out").rglob("*") if p.is_file()] == ["yt_dlp/__init__.py"]+ assert not archive.exists()+++async def test_nightly_wheel_is_latest_dev_in_tag_format(monkeypatch):+ import features.yt_dlp_pack.config as ytDlpConfig++ def wheel(version, yanked=False):+ return {"filename": f"yt_dlp-{version}-py3-none-any.whl", "url": version, "yanked": yanked}++ async def fetchPypiReleases(package):+ return {+ "2026.8.27.3630.dev0": [wheel("2026.8.27.3630.dev0")],+ "2026.8.20.234504.dev0": [wheel("2026.8.20.234504.dev0")],+ "2026.8.28.100.dev0": [wheel("2026.8.28.100.dev0", yanked=True)],+ "2026.8.29.1.dev0": [{"filename": "yt_dlp-2026.8.29.1.dev0.tar.gz", "url": "", "yanked": False}],+ "2026.9.1": [wheel("2026.9.1")],+ }++ monkeypatch.setattr(ytDlpConfig, "fetchPypiReleases", fetchPypiReleases)++ assert await ytDlpConfig.fetchNightlyWheel() == ("2026.08.27.003630", "2026.8.27.3630.dev0")