The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
fix(parser): 删除 FetchedTaskOptions,修复浏览器下载 torrent 时文件被错误命名
XiaoYouChR8ef240212c6a
diff --git a/CONTEXT.md b/CONTEXT.mdindex 0891e4bf..8db2d82e 100644--- a/CONTEXT.md+++ b/CONTEXT.md@@ -77,15 +77,9 @@ The full path of a Task's finished file; equals `outputFolder / name`.**Task Options**:The app-owned options used to parse, create, or edit a Task. Frozen dataclasswith subtypes: ResourceTaskOptions, PageTaskOptions, MergeTaskOptions,-FetchedTaskOptions, BinaryInstallOptions.+BinaryInstallOptions._Avoid_: payload (keep only at raw transport seams)-**Fetched Task Options**:-A second-pass parse input for small response bodies already fetched by a-parser. Used when the HTTP fallback discovers that a URL returned a descriptor-format owned by a more specific parser, such as BitTorrent metadata.-_Avoid_: using it for large user files.-**Task Parser**:A FeaturePack-provided capability that turns Task Options into a Task.Declares a `priority` and a `match(options)` predicate.@@ -280,7 +274,7 @@ and are checked first; HttpParser (100) is the fallback, checked last.| MergeParser | 60 | `isinstance(options, MergeTaskOptions)` || YouTubeParser | 70 | YouTube domain || M3U8Parser | 80 | `.m3u8`/`.mpd` in URL or local manifest |-| TorrentParser | 85 | `magnet:` scheme, `.torrent`, or fetched BitTorrent metadata |+| TorrentParser | 85 | `magnet:` scheme or `.torrent` local file || HuggingFaceParser | 85 | HuggingFace domain || GitHubParser | 90 | GitHub file URL + proxy configured || FtpParser | 95 | `ftp`/`ftps` scheme |@@ -295,11 +289,6 @@ Delegation patterns:through the priority chain.- **InstallParser** delegates the download through`featureService.parse(TaskOptions(url=...))` so GitHubParser mirrors it.-- **HttpParser** may fetch a small response body and call- `featureService.parse(FetchedTaskOptions(...))` when- `featureService.matchFetched(...)` says a more specific parser matches the- fetched response metadata. HttpParser does not match Fetched Task Options, so- second-pass routing cannot fall back to itself.## Ownership rulesdiff --git a/app/models/__init__.py b/app/models/__init__.pyindex 764510b1..f7d2e3e1 100644--- a/app/models/__init__.py+++ b/app/models/__init__.py@@ -6,7 +6,6 @@ from app.models.task import (TaskFile,TaskOptions,ResourceTaskOptions,- FetchedTaskOptions,PageTaskOptions,MergeTaskOptions,)diff --git a/app/models/task.py b/app/models/task.pyindex cdbc8d66..04df616c 100644--- a/app/models/task.py+++ b/app/models/task.py@@ -70,13 +70,6 @@ class ResourceTaskOptions(TaskOptions):canUseRangeRequests: bool = False-@dataclass(frozen=True)-class FetchedTaskOptions(TaskOptions):- name: str = ""- contentType: str = ""- body: bytes = b""--@dataclass(frozen=True)class PageTaskOptions(TaskOptions):pageUrl: str = ""diff --git a/app/services/feature_service.py b/app/services/feature_service.pyindex b4582330..b393f9f0 100644--- a/app/services/feature_service.py+++ b/app/services/feature_service.py@@ -54,9 +54,6 @@ class FeatureService(QObject):return taskraise ValueError(f"No parser matched: {options.url}")- def matchFetched(self, options: TaskOptions) -> bool:- return any(parser.match(options) for parser in self._parsers)-def matchPassive(self, url: str) -> bool:from app.models.task import TaskOptionsoptions = TaskOptions(url=url)diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.pyindex 7c80b403..f18cefbf 100644--- a/features/bittorrent_pack/pack.py+++ b/features/bittorrent_pack/pack.py@@ -9,7 +9,7 @@ import libtorrent as ltfrom loguru import loggerfrom app.models.pack import FeaturePack, TaskParser, FileType-from app.models.task import FetchedTaskOptions, Task, TaskOptions+from app.models.task import Task, TaskOptionsfrom app.platform.filesystem import localFilePath, toSafeFilenamefrom .config import bittorrentConfig@@ -18,27 +18,10 @@ from .task import BTFile, BTTask, BTTaskStepfrom .web_tracker.service import trackerService-TORRENT_CONTENT_TYPES = frozenset({- "application/x-bittorrent",- "application/x-torrent",-})---def isFetchedTorrent(options: FetchedTaskOptions) -> bool:- contentType = options.contentType.split(";", 1)[0].strip().lower()- if contentType in TORRENT_CONTENT_TYPES or "bittorrent" in contentType:- return True- if Path(options.name).suffix.lower() == ".torrent":- return True- return PurePosixPath(urlparse(options.url).path).suffix.lower() == ".torrent"--class TorrentParser(TaskParser):priority = 85def match(self, options: TaskOptions) -> bool:- if isinstance(options, FetchedTaskOptions):- return isFetchedTorrent(options)url = options.url.strip()if urlparse(url).scheme.lower() == "magnet":return True@@ -59,11 +42,7 @@ class TorrentParser(TaskParser):webTrackers = []localPath = localFilePath(url, {".torrent"})- if isinstance(options, FetchedTaskOptions):- torrentBytes = options.body- sourceType, sourceUrl = "torrent", url-- elif localPath is not None:+ if localPath is not None:torrentBytes = await asyncio.to_thread(localPath.resolve().read_bytes)sourceType, sourceUrl = "torrent", str(localPath.resolve())diff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex b520c4d3..cc0f9cbf 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -13,7 +13,7 @@ from app.client import buildClient, toEmulationfrom app.config.cfg import cfgfrom app.models.pack import FeaturePack, TaskParserfrom app.models.task import (- FetchedTaskOptions, Task, TaskOptions, ResourceTaskOptions, SpecialFileSize,+ Task, TaskOptions, ResourceTaskOptions, SpecialFileSize,)from app.platform.filesystem import toSafeFilenamefrom .task import HttpTask, HttpTaskStep@@ -28,15 +28,12 @@ DOWNLOADABLE_EXTENSIONS = frozenset({".pdf", ".epub",".apk", ".ipa",})-FETCHED_TASK_MAX_BYTES = 50 * 1024 * 1024class HttpParser(TaskParser):priority = 100def match(self, options: TaskOptions) -> bool:- if isinstance(options, FetchedTaskOptions):- return Falsereturn urlparse(options.url).scheme.lower() in {"http", "https"}def matchPassive(self, options: TaskOptions) -> bool:@@ -58,61 +55,10 @@ class HttpParser(TaskParser):canUseRangeRequests = FalselastModified = ""- def fetchedOptions(name: str, contentType: str, body: bytes = b"") -> FetchedTaskOptions:- return FetchedTaskOptions(- url=url,- outputFolder=outputFolder,- headers=headers,- clientProfile=clientProfile,- sourceUserAgent=options.sourceUserAgent,- subworkerCount=subworkerCount,- name=name,- contentType=contentType,- body=body,- )-- async def parseFetchedTask(client, name: str, contentType: str, contentLength: int) -> Task | None:- from app.services.feature_service import featureService- probe = fetchedOptions(name, contentType)- if not featureService.matchFetched(probe):- return None- if contentLength > FETCHED_TASK_MAX_BYTES:- raise ValueError("响应体过大,无法在解析阶段读取")- body = await fetchSmallBody(client)- return await featureService.parse(fetchedOptions(name, contentType, body))-- async def fetchSmallBody(client) -> bytes:- response = await client.get(url, headers={**headers, "accept-encoding": "identity"})- try:- response.raise_for_status()- chunks = []- size = 0- async for chunk in response.stream():- if not chunk:- continue- size += len(chunk)- if size > FETCHED_TASK_MAX_BYTES:- raise ValueError("响应体过大,无法在解析阶段读取")- chunks.append(chunk)- return b"".join(chunks)- finally:- response.close()-if isinstance(options, ResourceTaskOptions) and options.name:name = toSafeFilename(options.name, fallback=f"file_{time_ns()}")fileSize = options.size if options.size > 0 else SpecialFileSize.UNKNOWNcanUseRangeRequests = options.canUseRangeRequests- emulation = toEmulation(- options.clientProfile or cfg.clientProfile.value,- options.sourceUserAgent,- )- client = buildClient(emulation=emulation, headers=headers)- try:- task = await parseFetchedTask(client, name, "", fileSize)- if task is not None:- return task- finally:- client.close()else:emulation = toEmulation(options.clientProfile or cfg.clientProfile.value,@@ -224,10 +170,6 @@ class HttpParser(TaskParser):name = unquote(cleanPath.split("/")[-1])contentType = responseHeaders.get("content-type", "").split(";", 1)[0].lower().strip()- task = await parseFetchedTask(client, name, contentType, fileSize)- if task is not None:- return task-standardExt = guess_extension(contentType) if contentType else ""standardExt = standardExt or ""