The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(bittorrent, m3u8): 按 probe 结果识别在线种子与流媒体清单
XiaoYouChR7fc18bd4f1da
diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.pyindex 1ca644ea..ee5df5aa 100644--- a/features/bittorrent_pack/config.py+++ b/features/bittorrent_pack/config.py@@ -82,7 +82,7 @@ class BitTorrentConfig(PackConfig):self.tr("稀疏分配更省磁盘写入,预分配更容易提前暴露空间不足"),texts=[self.tr("稀疏分配"), self.tr("预分配")], parent=btGroup),SwitchSettingCard(FluentIcon.SAVE, self.tr("保存 Magnet 种子文件"),- self.tr("下载 magnet 链接时额外保存 .torrent 文件"), self.saveMagnetFile, btGroup),+ self.tr("下载 magnet 链接或在线种子时额外保存 .torrent 文件"), self.saveMagnetFile, btGroup),SwitchSettingCard(FluentIcon.LIBRARY, self.tr("顺序下载"),self.tr("按文件顺序下载,适合边下边看但通常会影响整体效率"),self.enableSequentialDownload, btGroup),diff --git a/features/bittorrent_pack/manifest.toml b/features/bittorrent_pack/manifest.tomlindex 52d1a52c..70e417cf 100644--- a/features/bittorrent_pack/manifest.toml+++ b/features/bittorrent_pack/manifest.toml@@ -1,6 +1,6 @@[pack]entry = "pack.py"class = "BitTorrentPack"-dependencies = []-version = "1.1.2"-gdMinVersion = "4.4.4"+dependencies = ["http_pack"]+version = "1.1.3"+gdMinVersion = "4.4.7"diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.pyindex 1da16ff1..993ac432 100644--- a/features/bittorrent_pack/pack.py+++ b/features/bittorrent_pack/pack.py@@ -6,12 +6,14 @@ from pathlib import Path, PurePosixPathfrom urllib.parse import urlparseimport libtorrent as lt+from loguru import loggerfrom app.i18n import Nfrom app.models.pack import FeaturePack, TaskParser, FileType, UriSchemefrom app.models.task import Task, TaskOptionsfrom app.platform.filesystem import localFilePath, toSafeFilename+from http_pack.pack import buildTask, fetchContentfrom .config import bittorrentConfigfrom .session import PROXY_SCHEMES, btSession@@ -28,6 +30,8 @@ class TorrentParser(TaskParser):priority = 85def match(self, options: TaskOptions) -> bool:+ if options.isProbed:+ return options.file.name.lower().endswith(".torrent") or options.file.contentType == "application/x-bittorrent"url = options.url.strip()if urlparse(url).scheme.lower() == "magnet":return True@@ -41,7 +45,16 @@ class TorrentParser(TaskParser):webTrackers = mergedTrackers() if bittorrentConfig.enableWebTrackers.value else []localPath = localFilePath(url, {".torrent"})- if localPath is not None:+ 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)+ sourceType, sourceUrl = "torrent", url++ elif localPath is not None:torrentBytes = await asyncio.to_thread(localPath.resolve().read_bytes)sourceType, sourceUrl = "torrent", str(localPath.resolve())@@ -83,7 +96,7 @@ class TorrentParser(TaskParser):name = toSafeFilename(Path(entries[0].relativePath).name, fallback="torrent") if len(entries) == 1 else rootNamesteps = [BTTaskStep(stepIndex=1)]- if sourceType == "magnet" and bittorrentConfig.saveMagnetFile.value:+ if (sourceType == "magnet" or options.isProbed) and bittorrentConfig.saveMagnetFile.value:steps.append(BTTorrentFileStep(stepIndex=0))task = BTTask(name=name,diff --git a/features/m3u8_pack/manifest.toml b/features/m3u8_pack/manifest.tomlindex 6e3b216d..d2b2fc4d 100644--- a/features/m3u8_pack/manifest.toml+++ b/features/m3u8_pack/manifest.toml@@ -2,5 +2,5 @@entry = "pack.py"class = "M3U8Pack"dependencies = ["http_pack", "ffmpeg_pack"]-version = "1.1.3"-gdMinVersion = "4.4.5"+version = "1.1.4"+gdMinVersion = "4.4.7"diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex 80c36303..379225d6 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -19,6 +19,7 @@ from app.models.task import PageTaskOptions, Task, TaskOptionsfrom app.platform.filesystem import localFilePath, toSafeFilenamefrom .config import m3u8Config, m3u8Runtimefrom .task import M3U8Task, M3U8TaskStep+from http_pack.pack import buildTaskMEDIA_SUFFIXES = {@@ -35,11 +36,27 @@ class M3U8Parser(TaskParser):if localFilePath(options.url, MANIFEST_SUFFIXES) is not None:return Truelowered = options.url.lower()- return ".m3u" in lowered or ".mpd" in lowered+ if ".m3u" in lowered or ".mpd" in lowered:+ return True+ if not options.isProbed:+ return False+ contentType = options.file.contentType+ return (Path(options.file.name).suffix.lower() in MANIFEST_SUFFIXES+ or "mpegurl" in contentType or "dash+xml" in contentType)async def parse(self, options: TaskOptions) -> Task:- url = options.url.strip()- headers = dict(options.headers)+ 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:+ source = options.template if options.isProbed else options+ url = source.url.strip()+ headers = dict(source.headers)outputFolder = options.outputFolderlocalPath = localFilePath(url, MANIFEST_SUFFIXES)@@ -70,6 +87,8 @@ class M3U8Parser(TaskParser):loweredUrl = manifestUrl.lower()contentType = responseHeaders.get("content-type", "").lower()sample = body.lstrip()[:256].lower()+ if options.isProbed and not (sample.startswith("#extm3u") or "<mpd" in sample):+ raise ValueError("不是流媒体清单")if ".mpd" in loweredUrl or "dash+xml" in contentType or sample.startswith("<mpd"):manifestType = "mpd"else:diff --git a/tests/bittorrent_pack/test_task_parser.py b/tests/bittorrent_pack/test_task_parser.pynew file mode 100644index 00000000..a4c188bc--- /dev/null+++ b/tests/bittorrent_pack/test_task_parser.py@@ -0,0 +1,65 @@+from __future__ import annotations++import libtorrent as lt+import pytest+from aiohttp import web++from app.models.pack import PackServices+from app.models.task import TaskOptions+from bittorrent_pack.config import bittorrentConfig+from bittorrent_pack.pack import BitTorrentPack+from bittorrent_pack.task import BTTask+from http_pack.pack import HttpPack+from http_pack.task import HttpTask+from tests.helpers import buildRangeHandler++[email protected](params=["desktop", "android"])+def engine(startEngine, request):+ return startEngine(request.param)+++def features(engine, monkeypatch):+ monkeypatch.setattr(bittorrentConfig.autoRefreshWebTrackers, "value", False)+ services = PackServices(coroutineRunner=engine.coroutineRunner, speedMeter=engine.speedMeter)+ for pack in (HttpPack(services), BitTorrentPack(services)):+ engine.featureService.register(pack)+ return engine.featureService+++def buildTorrent(folder) -> bytes:+ (folder / "movie.mkv").write_bytes(b"x" * 40_000)+ torrent = lt.create_torrent(lt.list_files(str(folder / "movie.mkv")), piece_size=16384)+ lt.set_piece_hashes(torrent, str(folder))+ return lt.bencode(torrent.generate())+++def buildNamedHandler(content: bytes, name: str):+ rangeHandler = buildRangeHandler(content)++ async def handler(request: web.Request) -> web.Response:+ response = await rangeHandler(request)+ response.headers["Content-Disposition"] = f'attachment; filename="{name}"'+ return response+ return handler++[email protected]("ignore::DeprecationWarning:bittorrent_pack.pack")+async def test_parse_online_torrent_adds_its_files(features, startServer, tmp_path):+ url = await startServer(buildNamedHandler(buildTorrent(tmp_path), "movie.torrent"))++ task = await features.parse(TaskOptions(url=f"{url}?id=1"))++ assert isinstance(task, BTTask)+ assert task.name == "movie.mkv"+ assert task.url == f"{url}?id=1"+++async def test_parse_invalid_online_torrent_adds_plain_file(features, startServer):+ url = await startServer(buildNamedHandler(b"not a torrent" * 10, "movie.torrent"))++ task = await features.parse(TaskOptions(url=url))++ assert isinstance(task, HttpTask)+ assert task.name == "movie.torrent"diff --git a/tests/m3u8_pack/test_task_parser.py b/tests/m3u8_pack/test_task_parser.pynew file mode 100644index 00000000..cb7e7c9a--- /dev/null+++ b/tests/m3u8_pack/test_task_parser.py@@ -0,0 +1,55 @@+from __future__ import annotations++import pytest+from aiohttp import web++from app.models.pack import PackServices+from app.models.task import TaskOptions+from ffmpeg_pack.pack import FFmpegPack+from http_pack.pack import HttpPack+from http_pack.task import HttpTask+from m3u8_pack.pack import M3U8Pack+from m3u8_pack.task import M3U8Task+from tests.helpers import buildRangeHandler++PLAYLIST = b"#EXTM3U\n#EXT-X-TARGETDURATION:10\n#EXTINF:10,\nseg0.ts\n#EXT-X-ENDLIST\n"++[email protected](params=["desktop", "android"])+def engine(startEngine, request):+ return startEngine(request.param)+++def features(engine):+ services = PackServices(coroutineRunner=engine.coroutineRunner, speedMeter=engine.speedMeter)+ for pack in (HttpPack(services), FFmpegPack(services), M3U8Pack(services)):+ engine.featureService.register(pack)+ return engine.featureService+++def buildTypedHandler(content: bytes, contentType: str):+ rangeHandler = buildRangeHandler(content)++ async def handler(request: web.Request) -> web.Response:+ response = await rangeHandler(request)+ response.content_type = contentType+ return response+ return handler+++async def test_parse_playlist_without_suffix_adds_stream(features, startServer):+ url = await startServer(buildTypedHandler(PLAYLIST, "application/vnd.apple.mpegurl"))++ task = await features.parse(TaskOptions(url=f"{url}?id=1"))++ assert isinstance(task, M3U8Task)+ assert not task.isLive+++async def test_parse_broken_playlist_without_suffix_adds_plain_file(features, startServer):+ url = await startServer(buildTypedHandler(b"<html>expired</html>", "application/vnd.apple.mpegurl"))++ task = await features.parse(TaskOptions(url=url))++ assert isinstance(task, HttpTask)