Skip to content

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

refactor(http): 按内容解析失败时统一由来源 parser 回落为普通文件

XiaoYouChR9eeccc37d88e
diff --git a/app/services/feature_service.py b/app/services/feature_service.py
index e9792b19..286d62ba 100644
--- a/app/services/feature_service.py
+++ b/app/services/feature_service.py
@@ -8,7 +8,7 @@ from urllib.parse import urlparse
from app.config.cfg import cfg
from app.config.paths import FEATURES_DIR
-from app.models.task import TaskOptions
+from app.models.task import TaskError, TaskOptions
from app.platform import file_association
from app.loader import loadPacks
@@ -101,6 +101,15 @@ class FeatureService:
raise ValueError(f"No parser matched: {options.url}")
return await parser.probe(options)
+ async def probeRelink(self, task: Task, options: TaskOptions) -> TaskOptions:
+ try:
+ probed = await self.probe(options)
+ except NotImplementedError:
+ raise TaskError("该链接不能用于更换") from None
+ if not task.canReuseProgress(probed) and not task.canRelinkToOtherContent:
+ raise TaskError("新链接的内容与原任务不同,请重新添加任务")
+ return probed
+
def match(self, url: str) -> bool:
options = TaskOptions(url=url)
return any(parser.match(options) for parser in self._parsers)
diff --git a/app/view/dialogs/edit_task.py b/app/view/dialogs/edit_task.py
index 7eefc26f..f7304ba5 100644
--- a/app/view/dialogs/edit_task.py
+++ b/app/view/dialogs/edit_task.py
@@ -12,7 +12,7 @@ from app.format import toReadableSize
from app.view.components.card_groups import OptionCardGroup
from app.view.components.editors import addRecentFolder
from app.i18n import toLocalizedError
-from app.models.task import TaskError, toTaskError
+from app.models.task import toTaskError
if TYPE_CHECKING:
from app.models.task import Task, TaskOptions
@@ -73,7 +73,7 @@ class LiveEditDialog(EditTaskDialog):
self._setInteractive(False)
taskOptions = TaskOptions.fromOptions({**options, "url": newUrl})
self._pendingParseId = self._coroutineRunner.submit(
- self._featureService.probe(taskOptions),
+ self._featureService.probeRelink(self._task, taskOptions),
done=self._onReparsed,
failed=self._onReparseFailed,
options=options,
@@ -102,10 +102,6 @@ class LiveEditDialog(EditTaskDialog):
super().accept()
return
- if not self._task.canRelinkToOtherContent:
- self._onReparseFailed(TaskError("新链接的内容与原任务不同,请重新添加任务"))
- return
-
receivedBytes = self._task.currentSnapshot()[2]
if receivedBytes > 0:
confirm = MessageBox(
@@ -125,8 +121,6 @@ class LiveEditDialog(EditTaskDialog):
def _onReparseFailed(self, error, **_) -> None:
self._pendingParseId = ""
self._setInteractive(True)
- if isinstance(error, NotImplementedError):
- error = TaskError("该链接不能用于更换")
InfoBar.error(
title=self.tr("链接解析失败"),
content=toLocalizedError(toTaskError(error)),
diff --git a/docs/adr/0025-probe-then-dispatch-by-content.md b/docs/adr/0025-probe-then-dispatch-by-content.md
index 44c66f68..bb403e5c 100644
--- a/docs/adr/0025-probe-then-dispatch-by-content.md
+++ b/docs/adr/0025-probe-then-dispatch-by-content.md
@@ -1,13 +1,13 @@
# probe 之后按内容重新分派;Relink 只走 probe
压缩包、种子、流媒体清单要按链接背后文件的内容认领,而文件是什么只有 probe 之后才知道(如 `download.aspx?file=x` 返回的 zip)。
-我们让来源 parser(HttpParser、GitHubParser)probe 后把 `file` 和 `template` 填进 Task Options,经已有的 `delegate` 再分派一次;格式 parser 按 `file` 的名字和类型认领,无人认领时回落为普通文件。
+我们让来源 parser(HttpParser、GitHubParser)probe 后把 `file` 和 `template` 填进 Task Options,经 `pack.parse` 再分派一次;格式 parser 按 `file` 的名字和类型认领,无人认领或认领后解析失败时,来源 parser 回落为普通文件。
Relink 是"同一个文件换一个新地址",只需 probe 的结果,不再创建 Task,因而不会因按内容识别而改变 Task 的种类(#1015)。
## Considered Options
- **Route:把 Proxy Site 下沉到请求层,格式 parser 按 URL 后缀抢先认领**:无后缀的链接认不出来;还要改 10 个 pack 的 `run` 签名、迁移 GitHub 旧记录。
-- **FileParser:来源 parser probe 后把文件交给格式 pack**:每个来源 parser 都要记得转交,m3u8 需要原链接、被动识别要伪造文件对象,seam 位置不对。复用 `delegate` 后只剩 HttpParser 与 GitHubParser 两处,且无需新接口。
+- **FileParser:来源 parser probe 后把文件交给格式 pack**:每个来源 parser 都要记得转交,m3u8 需要原链接、被动识别要伪造文件对象,seam 位置不对。复用 `pack.parse` 后只剩 HttpParser 与 GitHubParser 两处,且无需新接口。
- **Relink 仍然重新解析,用标志关掉按内容分派**:Task 与 Task Options 各多一个字段,还要检查种类是否改变;Relink 本来就不需要回答"这是什么"。
## Consequences
diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.py
index 430ad11e..528e0111 100644
--- a/features/bittorrent_pack/pack.py
+++ b/features/bittorrent_pack/pack.py
@@ -7,14 +7,13 @@ from pathlib import Path, PurePosixPath
from urllib.parse import urlparse
import libtorrent as lt
-from loguru import logger
from app.i18n import N
from app.models.pack import FeaturePack, TaskParser, FileType, UriScheme
from app.models.task import Task, TaskOptions
from app.platform.filesystem import localFilePath, toSafeFilename
-from http_pack.pack import buildTask, fetchContent
+from http_pack.pack import fetchContent
from .config import bittorrentConfig
from .session import PROXY_SCHEMES, btSession
@@ -53,12 +52,7 @@ class TorrentParser(TaskParser):
localPath = localFilePath(url, {".torrent"})
if options.isProbed:
- try:
- torrentBytes = await fetchContent(options.template)
- lt.torrent_info(torrentBytes)
- except Exception as e:
- logger.opt(exception=e).warning("不是有效的种子,按普通文件下载 {}", url)
- return buildTask(options)
+ torrentBytes = await fetchContent(options.template)
sourceType, sourceUrl = "torrent", url
elif localPath is not None:
diff --git a/features/github_pack/pack.py b/features/github_pack/pack.py
index 3ead61ce..4e3749c8 100644
--- a/features/github_pack/pack.py
+++ b/features/github_pack/pack.py
@@ -7,7 +7,7 @@ from loguru import logger
from app.i18n import N
from app.models.pack import FeaturePack, TaskParser
from app.models.task import Task, TaskOptions
-from http_pack.pack import buildStep
+from http_pack.pack import buildStep, parseProbed
from http_pack.task import HttpTask, HttpTaskStep
from .config import githubConfig, selectedProxySite, GITHUB_PROXY_SITES
from .probe import probeUrls, toProxyHeaders
@@ -89,7 +89,7 @@ class GitHubParser(TaskParser):
return githubConfig.enabled.value and isGitHubFileUrl(options.url) and not options.isProbed
async def parse(self, options: TaskOptions) -> Task:
- task = await self.pack.parse(await self.probe(options))
+ task = await parseProbed(self.pack.parse, await self.probe(options))
if type(task) is HttpTask:
task.packId = "github"
return task
diff --git a/features/http_pack/pack.py b/features/http_pack/pack.py
index 43333b2d..9abd3cd8 100644
--- a/features/http_pack/pack.py
+++ b/features/http_pack/pack.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import re
+from collections.abc import Awaitable, Callable
from dataclasses import replace
from email.message import Message
from email.utils import collapse_rfc2231_value
@@ -186,6 +187,10 @@ def buildStep(stepType: type[HttpTaskStep], stepIndex: int, url: str, options: T
return stepType(**{**fields, **kwargs})
+def toProbed(options: TaskOptions, file: RemoteFile) -> TaskOptions:
+ return replace(options, file=file, template=buildStep(HttpTaskStep, 1, options.url, options, file))
+
+
def buildTask(options: TaskOptions) -> HttpTask:
name = options.file.name
if isinstance(options, ResourceTaskOptions) and options.name:
@@ -200,6 +205,14 @@ def buildTask(options: TaskOptions) -> HttpTask:
return task
+async def parseProbed(parse: Callable[[TaskOptions], Awaitable[Task]], probed: TaskOptions) -> Task:
+ try:
+ return await parse(probed)
+ except Exception as e:
+ logger.opt(exception=e).warning("无法按内容解析,按普通文件下载 {}", probed.url)
+ return buildTask(probed)
+
+
async def fetchRange(step: HttpTaskStep, offset: int, length: int) -> bytes:
emulation = toEmulation(step.clientProfile or cfg.clientProfile.value, "")
client = buildClient(emulation=emulation, userAgent=step.userAgent or None, timeout=30)
@@ -250,16 +263,15 @@ class HttpParser(TaskParser):
return any(path.endswith(ext) for ext in DOWNLOADABLE_EXTENSIONS)
async def probe(self, options: TaskOptions) -> TaskOptions:
- file = await probe(options)
- return replace(options, file=file, template=buildStep(HttpTaskStep, 1, options.url, options, file))
+ return toProbed(options, await probe(options))
async def parse(self, options: TaskOptions) -> Task:
if options.isProbed:
return buildTask(options)
if isinstance(options, ResourceTaskOptions) and options.name and options.size > 0:
file = RemoteFile(name=options.name, fileSize=options.size, canUseRangeRequests=options.canUseRangeRequests)
- return buildTask(replace(options, file=file, template=buildStep(HttpTaskStep, 1, options.url, options, file)))
- return await self.pack.parse(await self.probe(options))
+ return buildTask(toProbed(options, file))
+ return await parseProbed(self.pack.parse, await self.probe(options))
class HttpPack(FeaturePack):
diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.py
index cda68870..7a6e166b 100644
--- a/features/m3u8_pack/pack.py
+++ b/features/m3u8_pack/pack.py
@@ -20,7 +20,6 @@ from app.models.task import PageTaskOptions, Task, TaskOptions
from app.platform.filesystem import localFilePath, toSafeFilename
from .config import m3u8Config, m3u8Runtime
from .task import M3U8Task, M3U8TaskStep
-from http_pack.pack import buildTask
MEDIA_SUFFIXES = {
@@ -44,15 +43,6 @@ class M3U8Parser(TaskParser):
return options.isProbed and options.file.matchType(MANIFEST_SUFFIXES, MANIFEST_CONTENT_TYPES)
async def parse(self, options: TaskOptions) -> Task:
- try:
- return await self.parseManifest(options)
- except Exception as e:
- if not options.isProbed:
- raise
- logger.opt(exception=e).warning("不是有效的流媒体清单,按普通文件下载 {}", options.url)
- return buildTask(options)
-
- async def parseManifest(self, options: TaskOptions) -> Task:
if options.isProbed:
options = replace(options, url=options.template.url, headers=options.template.headers)
url = options.url.strip()
diff --git a/features/zip_pack/pack.py b/features/zip_pack/pack.py
index 389192bb..e6b19051 100644
--- a/features/zip_pack/pack.py
+++ b/features/zip_pack/pack.py
@@ -4,12 +4,10 @@ import asyncio
import zipfile
from bisect import bisect_right
-from loguru import logger
-
from app.models.pack import FeaturePack, TaskParser
from app.models.task import ResourceTaskOptions, Task, TaskOptions
from app.platform.filesystem import toSafeFilename
-from http_pack.pack import buildTask, fetchRange
+from http_pack.pack import fetchRange
from .sparse import SparseView
from .task import ZipEntry, ZipExtractStep, ZipTask
@@ -64,7 +62,7 @@ def buildEntries(infos: list[zipfile.ZipInfo], centralOffset: int) -> list[ZipEn
index=len(entries),
relativePath=relativePath,
size=info.file_size,
- name=info.filename,
+ innerPath=info.filename,
localHeaderOffset=info.header_offset,
windowEnd=starts[bisect_right(starts, info.header_offset)],
))
@@ -96,23 +94,19 @@ class ZipParser(TaskParser):
async def parse(self, options: TaskOptions) -> Task:
size = options.file.fileSize
- try:
- tailOffset = max(0, size - TAIL_SIZE)
- tail = await fetchRange(options.template, tailOffset, size - tailOffset)
- centralOffset = parseCentralOffset(tail, tailOffset)
- if size - centralOffset > MAX_CENTRAL_SIZE:
- raise zipfile.BadZipFile("中央目录过大")
- if centralOffset < tailOffset:
- tail = await fetchRange(options.template, centralOffset, tailOffset - centralOffset) + tail
- tailOffset = centralOffset
- view = SparseView(size)
- view.addSegment(tailOffset, tail)
- metadataEncoding, infos = await asyncio.to_thread(parseInfos, view)
- entries = await asyncio.to_thread(buildEntries, infos, centralOffset)
- return buildZipTask(options, entries, tailOffset, metadataEncoding)
- except Exception as e:
- logger.opt(exception=e).warning("无法预览压缩包,按普通文件下载 {}", options.url)
- return buildTask(options)
+ tailOffset = max(0, size - TAIL_SIZE)
+ tail = await fetchRange(options.template, tailOffset, size - tailOffset)
+ centralOffset = parseCentralOffset(tail, tailOffset)
+ if size - centralOffset > MAX_CENTRAL_SIZE:
+ raise zipfile.BadZipFile("中央目录过大")
+ if centralOffset < tailOffset:
+ tail = await fetchRange(options.template, centralOffset, tailOffset - centralOffset) + tail
+ tailOffset = centralOffset
+ view = SparseView(size)
+ view.addSegment(tailOffset, tail)
+ metadataEncoding, infos = await asyncio.to_thread(parseInfos, view)
+ entries = await asyncio.to_thread(buildEntries, infos, centralOffset)
+ return buildZipTask(options, entries, tailOffset, metadataEncoding)
class ZipPack(FeaturePack):
diff --git a/features/zip_pack/task.py b/features/zip_pack/task.py
index e6c00bb5..23d0b852 100644
--- a/features/zip_pack/task.py
+++ b/features/zip_pack/task.py
@@ -18,7 +18,7 @@ from .sparse import SparseView
@dataclass(kw_only=True)
class ZipEntry(TaskFile):
- name: str = ""
+ innerPath: str = ""
localHeaderOffset: int = 0
windowEnd: int = 0
@@ -118,8 +118,8 @@ def toSpans(files: list[ZipEntry]) -> list[list[ZipEntry]]:
return spans
-def extractFile(archive: zipfile.ZipFile, name: str, path: Path) -> None:
- info = archive.getinfo(name)
+def extractFile(archive: zipfile.ZipFile, innerPath: str, path: Path) -> None:
+ info = archive.getinfo(innerPath)
with archive.open(info) as source, open(path, "wb") as target:
shutil.copyfileobj(source, target, 1 << 20)
with suppress(ValueError):
@@ -176,7 +176,7 @@ class ZipExtractStep(TaskStep):
continue
target = task.toFilePath(file.index)
temporary = Path(f"{path}.out")
- await asyncio.to_thread(extractFile, archive, file.name, temporary)
+ await asyncio.to_thread(extractFile, archive, file.innerPath, temporary)
target.parent.mkdir(parents=True, exist_ok=True)
os.replace(temporary, target)
file.downloadedBytes, file.completed = file.size, True
diff --git a/tests/bittorrent_pack/test_task_parser.py b/tests/bittorrent_pack/test_task_parser.py
index f2a574f1..fdbc2e03 100644
--- a/tests/bittorrent_pack/test_task_parser.py
+++ b/tests/bittorrent_pack/test_task_parser.py
@@ -5,7 +5,7 @@ import pytest
from aiohttp import web
from app.models.pack import PackServices
-from app.models.task import TaskOptions
+from app.models.task import TaskError, TaskOptions
from bittorrent_pack.config import bittorrentConfig
from bittorrent_pack.pack import BitTorrentPack
from bittorrent_pack.session import btSession
@@ -66,9 +66,11 @@ async def test_parse_invalid_online_torrent_adds_plain_file(features, startServe
assert task.name == "movie.torrent"
-async def test_probe_magnet_link_is_unsupported(features):
- with pytest.raises(NotImplementedError):
- await features.probe(TaskOptions(url=f"magnet:?xt=urn:btih:{'0' * 40}"))
+async def test_probe_relink_magnet_link_rejects(features, startServer):
+ task = await features.parse(TaskOptions(url=await startServer(buildRangeHandler(b"x" * 100))))
+
+ with pytest.raises(TaskError):
+ await features.probeRelink(task, TaskOptions(url=f"magnet:?xt=urn:btih:{'0' * 40}"))
@pytest.mark.parametrize("infoHash", ["ab" * 20, "AB" * 20, "abcdefgh234567ab" * 2, "ABCDEFGH234567AB" * 2])
diff --git a/tests/zip_pack/test_task.py b/tests/zip_pack/test_task.py
index e9453ec7..dea3ae65 100644
--- a/tests/zip_pack/test_task.py
+++ b/tests/zip_pack/test_task.py
@@ -8,7 +8,7 @@ import pytest
from aiohttp import web
from app.models.pack import PackServices
-from app.models.task import TaskOptions, TaskStatus
+from app.models.task import TaskError, TaskOptions, TaskStatus
from http_pack.pack import HttpPack
from http_pack.task import HttpTask
from tests.helpers import buildFileContent, buildRangeHandler, waitUntil
@@ -248,8 +248,7 @@ async def test_relink_same_archive_keeps_selection(engine, features, startServer
engine.taskService.add(task, autoStart=False)
newUrl = await startArchive(startServer, archive)
- probed = await features.probe(TaskOptions(url=newUrl))
- assert task.canReuseProgress(probed)
+ probed = await features.probeRelink(task, TaskOptions(url=newUrl))
engine.taskService.edit(task, {}, probed)
engine.taskService.start(task)
await runToCompletion(engine, task)
@@ -258,10 +257,9 @@ async def test_relink_same_archive_keeps_selection(engine, features, startServer
assert listFolder(downloadFolder) == ["a", "a/readme.txt"]
-async def test_probe_other_archive_cannot_relink(features, startServer):
+async def test_probe_relink_other_archive_rejects(features, startServer):
task = await features.parse(TaskOptions(url=await startArchive(startServer, buildArchive())))
+ otherUrl = await startArchive(startServer, buildArchive({"b.txt": b"b"}))
- probed = await features.probe(TaskOptions(url=await startArchive(startServer, buildArchive({"b.txt": b"b"}))))
-
- assert not task.canReuseProgress(probed)
- assert not task.canRelinkToOtherContent
+ with pytest.raises(TaskError):
+ await features.probeRelink(task, TaskOptions(url=otherUrl))