Skip to content

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

feat(parser):

XiaoYouChR4724c1fa60dd
diff --git a/app/models/__init__.py b/app/models/__init__.py
index f7d2e3e1..764510b1 100644
--- a/app/models/__init__.py
+++ b/app/models/__init__.py
@@ -6,6 +6,7 @@ from app.models.task import (
TaskFile,
TaskOptions,
ResourceTaskOptions,
+ FetchedTaskOptions,
PageTaskOptions,
MergeTaskOptions,
)
diff --git a/app/models/task.py b/app/models/task.py
index 04df616c..cdbc8d66 100644
--- a/app/models/task.py
+++ b/app/models/task.py
@@ -70,6 +70,13 @@ 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/platform/filesystem.py b/app/platform/filesystem.py
index f2cb4e0d..51e962f4 100644
--- a/app/platform/filesystem.py
+++ b/app/platform/filesystem.py
@@ -60,11 +60,26 @@ def toPosixPath(path) -> str:
def localFilePath(url: str, validSuffixes: set[str] | None = None) -> Path | None:
- from urllib.parse import urlparse, unquote
+ from urllib.parse import urlparse
+ from urllib.request import url2pathname
parsed = urlparse(url)
if parsed.scheme != "file":
return None
- path = Path(unquote(parsed.path))
+
+ rawPath = parsed.path
+ if parsed.netloc:
+ host = parsed.netloc.lower()
+ if host == "localhost":
+ rawPath = parsed.path
+ elif sys.platform == "win32":
+ if re.fullmatch(r"[a-zA-Z]:", parsed.netloc):
+ rawPath = f"{parsed.netloc}{parsed.path}"
+ else:
+ rawPath = f"//{parsed.netloc}{parsed.path}"
+ else:
+ return None
+
+ path = Path(url2pathname(rawPath))
if not path.is_file():
return None
if validSuffixes is not None and path.suffix.lower() not in validSuffixes:
diff --git a/app/services/feature_service.py b/app/services/feature_service.py
index b393f9f0..b4582330 100644
--- a/app/services/feature_service.py
+++ b/app/services/feature_service.py
@@ -54,6 +54,9 @@ class FeatureService(QObject):
return task
raise 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 TaskOptions
options = TaskOptions(url=url)
diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.py
index 75a5d10a..7c80b403 100644
--- a/features/bittorrent_pack/pack.py
+++ b/features/bittorrent_pack/pack.py
@@ -8,10 +8,8 @@ from urllib.parse import urlparse
import libtorrent as lt
from loguru import logger
-from app.client import buildClient, toEmulation
-from app.config.cfg import cfg
from app.models.pack import FeaturePack, TaskParser, FileType
-from app.models.task import Task, TaskOptions
+from app.models.task import FetchedTaskOptions, Task, TaskOptions
from app.platform.filesystem import localFilePath, toSafeFilename
from .config import bittorrentConfig
@@ -20,14 +18,31 @@ from .task import BTFile, BTTask, BTTaskStep
from .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 = 85
def match(self, options: TaskOptions) -> bool:
+ if isinstance(options, FetchedTaskOptions):
+ return isFetchedTorrent(options)
url = options.url.strip()
if urlparse(url).scheme.lower() == "magnet":
return True
- return localFilePath(url, {".torrent"}) is not None or url.lower().endswith(".torrent")
+ return localFilePath(url, {".torrent"}) is not None
async def parse(self, options: TaskOptions) -> Task:
url = options.url.strip()
@@ -44,7 +59,11 @@ class TorrentParser(TaskParser):
webTrackers = []
localPath = localFilePath(url, {".torrent"})
- if localPath is not None:
+ if isinstance(options, FetchedTaskOptions):
+ torrentBytes = options.body
+ sourceType, sourceUrl = "torrent", url
+
+ elif localPath is not None:
torrentBytes = await asyncio.to_thread(localPath.resolve().read_bytes)
sourceType, sourceUrl = "torrent", str(localPath.resolve())
@@ -55,20 +74,16 @@ class TorrentParser(TaskParser):
sourceType, sourceUrl = "magnet", url
else:
- emulation = toEmulation(
- options.clientProfile or cfg.clientProfile.value,
- options.sourceUserAgent,
- )
- client = buildClient(emulation=emulation, headers=dict(options.headers))
- try:
- response = await client.get(url)
- response.raise_for_status()
- torrentBytes = response.content
- finally:
- client.close()
- sourceType, sourceUrl = "torrent", url
+ raise ValueError("无法解析 BitTorrent 来源")
+
+ if not torrentBytes:
+ raise ValueError("种子文件为空")
+
+ try:
+ ti = lt.torrent_info(torrentBytes)
+ except Exception as e:
+ raise ValueError(f"无效的 BitTorrent 种子文件:{e}") from e
- ti = lt.torrent_info(torrentBytes)
torrentTrackers = [str(t.url).strip() for t in ti.trackers()]
allSources = (magnetTrackers, torrentTrackers, webTrackers) if sourceType == "magnet" else (torrentTrackers, webTrackers)
trackers = list(dict.fromkeys(t for g in allSources for t in g if t))
diff --git a/features/http_pack/pack.py b/features/http_pack/pack.py
index cc0f9cbf..b520c4d3 100644
--- a/features/http_pack/pack.py
+++ b/features/http_pack/pack.py
@@ -13,7 +13,7 @@ from app.client import buildClient, toEmulation
from app.config.cfg import cfg
from app.models.pack import FeaturePack, TaskParser
from app.models.task import (
- Task, TaskOptions, ResourceTaskOptions, SpecialFileSize,
+ FetchedTaskOptions, Task, TaskOptions, ResourceTaskOptions, SpecialFileSize,
)
from app.platform.filesystem import toSafeFilename
from .task import HttpTask, HttpTaskStep
@@ -28,12 +28,15 @@ DOWNLOADABLE_EXTENSIONS = frozenset({
".pdf", ".epub",
".apk", ".ipa",
})
+FETCHED_TASK_MAX_BYTES = 50 * 1024 * 1024
class HttpParser(TaskParser):
priority = 100
def match(self, options: TaskOptions) -> bool:
+ if isinstance(options, FetchedTaskOptions):
+ return False
return urlparse(options.url).scheme.lower() in {"http", "https"}
def matchPassive(self, options: TaskOptions) -> bool:
@@ -55,10 +58,61 @@ class HttpParser(TaskParser):
canUseRangeRequests = False
lastModified = ""
+ 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.UNKNOWN
canUseRangeRequests = 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,
@@ -170,6 +224,10 @@ 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 ""