From 20787793974b14d8e002dd38f30329819f35cd65 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Fri, 13 Nov 2026 22:26:21 +0800 Subject: [PATCH] fix(download): preserve tasks and align episode file selection (#7405) Keep existing downloads untouched, retain unnumbered attachments and select intersecting episode videos consistently across downloaders. Refs #7362 --- app/chain/download/history.py | 4 +- app/domain/torrent.py | 41 +++- app/modules/qbittorrent/__init__.py | 56 ++---- app/modules/rtorrent/__init__.py | 34 ++-- app/modules/transmission/__init__.py | 53 ++--- app/modules/transmission/transmission.py | 49 +++++ docs/rules/05-architecture.md | 2 +- docs/testing.md | 8 +- .../architecture/complexity-baseline.json | 4 +- .../architecture/dependency-baseline.json | 5 +- .../architecture/dependency-policy.json | 2 +- tests/test_architecture_egress.py | 3 +- .../test_download_history_episode_mapping.py | 12 +- tests/test_downloader_add_failure_message.py | 1 + tests/test_downloader_submission.py | 79 ++++---- tests/test_episode_file_selection.py | 185 ++++++++++++++++++ tests/test_qbittorrent_compat.py | 45 ++++- .../test_review_download_site_regressions.py | 5 +- tests/test_transmission_add_status.py | 140 +++++++++++++ 19 files changed, 577 insertions(+), 151 deletions(-) create mode 100644 tests/test_episode_file_selection.py create mode 100644 tests/test_transmission_add_status.py diff --git a/app/chain/download/history.py b/app/chain/download/history.py index 970b7cf0a..b2d2203d6 100644 --- a/app/chain/download/history.py +++ b/app/chain/download/history.py @@ -82,6 +82,8 @@ class DownloadHistoryOwner(_DownloadOwnerBase): """ 提交下载历史、文件明细和 durable 下载事件。 + 选集文件按集号交集保留,确保跨目标边界的多集视频也有文件明细。 + :param already_exists: 下载器中已存在同一任务时为 True,仅补记历史,不再重复通知与文件明细; 若整包全部媒体文件已记录过,同时为这个资源登记提交退避 """ @@ -159,7 +161,7 @@ class DownloadHistoryOwner(_DownloadOwnerBase): # 与订阅选集使用相同识别词,避免偏移前的文件集数被目标集数过滤。 file_meta = MetaInfo(Path(cast(str, item.filepath)).stem, custom_words=custom_word_list) file_episodes = set(file_meta.episode_list) - if file_meta.begin_episode and file_meta.begin_episode in episodes: + if file_episodes.intersection(episodes): selected_files.append(item) elif len(file_episodes) <= 1: unmatched_single_files.append(item) diff --git a/app/domain/torrent.py b/app/domain/torrent.py index 682743ff6..51dcfc4a4 100644 --- a/app/domain/torrent.py +++ b/app/domain/torrent.py @@ -1,11 +1,12 @@ """ -种子身份与下载链接的纯领域判断规则。 +种子身份、下载链接与剧集文件选择的纯领域判断规则。 """ import base64 import binascii import hashlib import re +from collections.abc import Iterable from typing import TYPE_CHECKING, Optional, Union from urllib.parse import parse_qs, urlsplit @@ -13,6 +14,44 @@ if TYPE_CHECKING: from app.domain.context import TorrentInfo +def select_episode_files( + files: Iterable[tuple[int, set[int], bool]], episodes: set[int], +) -> tuple[list[int], list[int], set[int]]: + """ + 按视频覆盖集数选择文件,保留无集号的非视频附属文件。 + + 多集文件与目标集有交集即选中,允许一并下载同文件中的其它集。仅请求一集且 + 只有一个单集或无集号视频时,沿用识别修正后的唯一视频兜底;附属文件不证明视频覆盖。 + + :param files: 文件索引、已按来源识别词解析的集数、是否为视频组成的条目 + :param episodes: 本次需要完整覆盖的目标集数 + :return: 需要下载的索引、不下载的索引、已选视频覆盖的集数;输入条目不会被修改 + """ + wanted: list[int] = [] + unwanted: list[int] = [] + matched: set[int] = set() + media_files: list[tuple[int, set[int]]] = [] + for file_id, file_episodes, is_video in files: + if is_video: + media_files.append((file_id, file_episodes)) + if file_episodes.intersection(episodes): + wanted.append(file_id) + if is_video: + matched.update(file_episodes) + elif not file_episodes and not is_video: + wanted.append(file_id) + else: + unwanted.append(file_id) + if not episodes.issubset(matched) and len(episodes) == 1 and len(media_files) == 1: + file_id, file_episodes = media_files[0] + # 无交集的多集视频不能用唯一视频规则冒充目标单集。 + if len(file_episodes) <= 1: + unwanted.remove(file_id) + wanted.append(file_id) + matched.update(episodes) + return wanted, unwanted, matched + + def is_magnet_link(content: Union[str, bytes]) -> bool: """ 判断字符串或字节内容是否为磁力链接。 diff --git a/app/modules/qbittorrent/__init__.py b/app/modules/qbittorrent/__init__.py index dd1f0e53a..49fa79064 100644 --- a/app/modules/qbittorrent/__init__.py +++ b/app/modules/qbittorrent/__init__.py @@ -115,7 +115,8 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): """ 读取种子内容并添加下载任务,按需选择剧集文件。 - 无论添加或后续处理是否成功,都会尝试清理随机临时标签。 + 已有任务直接返回存在标志,不暂停或重选文件。无论添加或后续处理是否成功, + 都会尝试清理随机临时标签。 :param content: 本地种子路径、磁力链接或种子文件字节内容;普通 URL 不会由本方法下载 :param download_dir: MoviePilot 侧的下载目录,会映射为下载器路径 @@ -193,11 +194,6 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): server.set_torrents_tag(ids=torrent_hash, tags=[get_runtime_setting('TORRENT_TAG')]) # 获取种子内容布局: `Original: 原始, Subfolder: 创建子文件夹, NoSubfolder: 不创建子文件夹` torrent_layout = server.get_content_layout() - if is_paused: - return self._finish_selected_download( - server, torrent_hash, episodes or set(), custom_words, downloader, torrent_layout, - already_exists=True, - ) return downloader or self.get_default_config_name(), torrent_hash, torrent_layout, DOWNLOAD_TASK_ALREADY_EXISTS finally: torrents.clear() @@ -230,18 +226,14 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): def _finish_selected_download( self, server: Qbittorrent, torrent_hash: str, episodes: Set[int], custom_words: Optional[str], - downloader: Optional[str], torrent_layout: Optional[str], already_exists: bool = False, + downloader: Optional[str], torrent_layout: Optional[str], ) -> Tuple[Optional[str], Optional[str], Optional[str], str]: """ - 统一选集任务结果;已有任务先确认暂停,失败不向下载链返回成功 hash。 + 完成新任务选集,失败不向下载链返回成功 hash。 """ - if already_exists and not server.stop_torrents(torrent_hash): - return None, None, None, "已有下载任务无法暂停,未执行选集" selected, message = self._select_download_files(server, torrent_hash, episodes, custom_words) if not selected: return None, None, None, message - if already_exists: - message = DOWNLOAD_TASK_ALREADY_EXISTS return downloader or self.get_default_config_name(), torrent_hash, torrent_layout, message @staticmethod @@ -285,8 +277,7 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): """ 验证全部目标集数及优先级后启动;失败不确认成功,并明确暂停或未知状态。 - 本次只请求一集且种子只有一个视频文件时,即使文件名保留累计集号,也按 - 唯一视频文件兜底选中,避免识别后的季集与物理文件集号不一致导致误报缺集。 + 视频按目标集交集选择,保留无集号非视频附件;单集请求保留唯一视频兜底。 """ failure = f"选集失败,任务 {torrent_hash} 保持暂停,请在下载器检查" paused = True @@ -303,40 +294,23 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): state_failure = failure if paused else ( f"选集失败,任务 {torrent_hash} 启动任务未确认,请在下载器核实,未记录成功" ) - wanted: list[int] = [] - unwanted: list[int] = [] - matched: set[int] = set() media_extensions = { str(extension).lower() for extension in get_runtime_setting("RMT_MEDIAEXT", []) } - media_files: list[tuple[int, set[int]]] = [] try: - for item in torrent_files: - file_id = item.get("id") - file_name = Path(item.get("name")).name - file_path = Path(file_name) - meta = MetaInfo(file_name, custom_words=custom_words.splitlines() if custom_words else []) - file_episodes = set(meta.episode_list) - if file_path.suffix.lower() in media_extensions: - media_files.append((file_id, file_episodes)) - if file_episodes and file_episodes.issubset(episodes): - wanted.append(file_id) - matched.update(file_episodes) - else: - unwanted.append(file_id) + wanted, unwanted, matched = torrent_rules.select_episode_files( + ( + (item.get("id"), set(MetaInfo( + Path(item.get("name")).name, + custom_words=custom_words.splitlines() if custom_words else [], + ).episode_list), Path(item.get("name")).suffix.lower() in media_extensions) + for item in torrent_files + ), episodes, + ) finally: torrent_files.clear() - if not set(episodes).issubset(matched) and len(episodes) == 1 and len(media_files) == 1: - file_id, file_episodes = media_files[0] - # 多集视频不能当作单集兜底,否则会把合集误选为目标单集。 - if len(file_episodes) <= 1: - if file_id in unwanted: - unwanted.remove(file_id) - if file_id not in wanted: - wanted.append(file_id) - matched.update(episodes) - if not set(episodes).issubset(matched): + if not episodes or not episodes.issubset(matched): return False, f"{state_failure}:未找到目标集数 {sorted(set(episodes) - matched)}" if unwanted and not server.set_files(torrent_hash=torrent_hash, file_ids=unwanted, priority=0): return False, f"{state_failure}:文件优先级设置未确认" diff --git a/app/modules/rtorrent/__init__.py b/app/modules/rtorrent/__init__.py index 6c11ff8aa..7a603a134 100644 --- a/app/modules/rtorrent/__init__.py +++ b/app/modules/rtorrent/__init__.py @@ -88,6 +88,7 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): category: Optional[str] = None, label: Optional[str] = None, downloader: Optional[str] = None, + custom_words: Optional[str] = None, ) -> Optional[Tuple[Optional[str], Optional[str], Optional[str], str]]: """ 读取种子内容并添加下载任务,按需选择剧集文件。 @@ -99,6 +100,7 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): :param category: 下载器任务分类,当前下载器不使用 :param label: 逗号分隔的任务标签;省略时使用系统种子标签 :param downloader: 下载器配置名称,省略时使用默认实例 + :param custom_words: 来源识别词,按行参与文件名识别,使选集结果与订阅一致 :return: 下载器名称、任务哈希、内容布局和结果说明;无适用实例时返回 None, 添加失败时前三项为空,说明包含失败原因 """ @@ -206,7 +208,7 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): else: torrent_hash = added_torrent_hash if episodes: - selected, message = self._select_episode_files(server, torrent_hash, episodes) + selected, message = self._select_episode_files(server, torrent_hash, episodes, custom_words) if not selected: return None, None, None, message return ( @@ -224,28 +226,36 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): ) @staticmethod - def _select_episode_files(server: Rtorrent, torrent_hash: str, episodes: Set[int]) -> Tuple[bool, str]: + def _select_episode_files( + server: Rtorrent, torrent_hash: str, episodes: Set[int], custom_words: Optional[str] = None, + ) -> Tuple[bool, str]: """ 对暂停添加的任务完成选集,所有RPC均成功才允许下载链确认任务。 :param server: 当前下载器客户端 :param torrent_hash: 已暂停添加的任务Hash - :param episodes: 本次允许下载的目标集数 + :param episodes: 本次需要完整覆盖的目标集数,多集文件按交集选择 + :param custom_words: 来源识别词,按行参与物理文件名识别 :return: 是否确认选集启动成功及结果说明 """ torrent_files = server.get_files(torrent_hash) if not torrent_files: return False, "获取种子文件失败,下载任务保留暂停状态,请检查下载器" - file_ids, selected_episodes = [], set() - for torrent_file in torrent_files: - meta = MetaInfo(torrent_file["name"]) - if meta.episode_list and set(meta.episode_list).issubset(episodes): - selected_episodes.update(meta.episode_list) - else: - file_ids.append(torrent_file["id"]) - if not selected_episodes: + media_extensions = {str(extension).lower() for extension in get_runtime_setting("RMT_MEDIAEXT", [])} + wanted, unwanted, selected_episodes = torrent_rules.select_episode_files( + ( + (item["id"], set(MetaInfo( + Path(item["name"]).name, + custom_words=custom_words.splitlines() if custom_words else [], + ).episode_list), Path(item["name"]).suffix.lower() in media_extensions) + for item in torrent_files + ), episodes, + ) + if not episodes or not episodes.issubset(selected_episodes): return False, "未匹配到目标集数,下载任务保留暂停状态" - if file_ids and not server.set_files(torrent_hash=torrent_hash, file_ids=file_ids, priority=0): + if unwanted and not server.set_files(torrent_hash=torrent_hash, file_ids=unwanted, priority=0): + return False, "设置选集优先级失败,下载任务保留暂停状态" + if not server.set_files(torrent_hash=torrent_hash, file_ids=wanted, priority=1): return False, "设置选集优先级失败,下载任务保留暂停状态" if not server.start_torrents(torrent_hash): stopped = server.stop_torrents(torrent_hash) diff --git a/app/modules/transmission/__init__.py b/app/modules/transmission/__init__.py index 3be771716..b82fa0a49 100644 --- a/app/modules/transmission/__init__.py +++ b/app/modules/transmission/__init__.py @@ -156,6 +156,8 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): """ 读取种子内容并添加下载任务,按需选择剧集文件。 + 已有任务直接返回存在标志,不暂停或重选文件,包括 RPC 返回的重复添加结果。 + :param content: 本地种子路径、磁力链接或种子文件字节内容;普通 URL 不会由本方法下载 :param download_dir: MoviePilot 侧的下载目录,会映射为下载器路径 :param cookie: 传给下载器的站点 Cookie @@ -195,7 +197,7 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): labels = get_runtime_setting('TORRENT_TAG').split(',') else: labels = None - added_torrent = server.add_torrent( + added_torrent, already_exists = server.add_torrent_with_status( content=torrent_content, download_dir=self.normalize_path(download_dir, downloader), is_paused=is_paused, @@ -205,6 +207,9 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): # TR 始终使用原始种子布局, 返回"Original" torrent_layout = "Original" + if added_torrent and already_exists: + return downloader or self.get_default_config_name(), added_torrent.hashString, torrent_layout, DOWNLOAD_TASK_ALREADY_EXISTS + if not added_torrent: # 查询所有下载器的种子 torrents, error = server.get_torrents() @@ -230,12 +235,6 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): if get_runtime_setting('TORRENT_TAG') and get_runtime_setting('TORRENT_TAG') not in labels: labels.append(get_runtime_setting('TORRENT_TAG')) server.set_torrent_tag(ids=torrent_hash, tags=labels) - if is_paused: - selected, message = self._select_download_files( - server, torrent_hash, episodes or set(), custom_words, - ) - if not selected: - return None, None, None, message return downloader or self.get_default_config_name(), torrent_hash, torrent_layout, DOWNLOAD_TASK_ALREADY_EXISTS finally: torrents.clear() @@ -292,8 +291,7 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): """ 先确认任务暂停再按来源集数映射选集,确认启动状态后才返回成功。 - 本次只请求一集且种子只有一个视频文件时,即使文件名保留累计集号,也按 - 唯一视频文件兜底选中,避免识别后的季集与物理文件集号不一致导致误报缺集。 + 视频按目标集交集选择,保留无集号非视频附件;单集请求保留唯一视频兜底。 :param server: 已配置的 Transmission 客户端 :param torrent_hash: 需要暂停、选集并恢复的任务哈希 @@ -316,40 +314,23 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): state_failure = failure if paused else ( f"选集失败,任务 {torrent_hash} 启动任务未确认,请在下载器核实,未记录成功" ) - wanted: list[int] = [] - unwanted: list[int] = [] - matched: set[int] = set() media_extensions = { str(extension).lower() for extension in get_runtime_setting("RMT_MEDIAEXT", []) } - media_files: list[tuple[int, set[int]]] = [] try: - for item in torrent_files: - file_id = item.id - file_name = Path(item.name).name - file_path = Path(file_name) - meta = MetaInfo(file_name, custom_words=custom_words.splitlines() if custom_words else []) - file_episodes = set(meta.episode_list) - if file_path.suffix.lower() in media_extensions: - media_files.append((file_id, file_episodes)) - if file_episodes and file_episodes.issubset(episodes): - wanted.append(file_id) - matched.update(file_episodes) - else: - unwanted.append(file_id) + wanted, unwanted, matched = torrent_rules.select_episode_files( + ( + (item.id, set(MetaInfo( + Path(item.name).name, + custom_words=custom_words.splitlines() if custom_words else [], + ).episode_list), Path(item.name).suffix.lower() in media_extensions) + for item in torrent_files + ), episodes, + ) finally: torrent_files.clear() - if not set(episodes).issubset(matched) and len(episodes) == 1 and len(media_files) == 1: - file_id, file_episodes = media_files[0] - # 多集视频不能当作单集兜底,否则会把合集误选为目标单集。 - if len(file_episodes) <= 1: - if file_id in unwanted: - unwanted.remove(file_id) - if file_id not in wanted: - wanted.append(file_id) - matched.update(episodes) - if not wanted or not set(episodes).issubset(matched): + if not episodes or not episodes.issubset(matched): return False, f"{state_failure}:未找到目标集数 {sorted(set(episodes) - matched)}" if not server.set_files(torrent_hash, wanted) or not server.set_unwanted_files(torrent_hash, unwanted): return False, f"{state_failure}:文件选择设置未确认" diff --git a/app/modules/transmission/transmission.py b/app/modules/transmission/transmission.py index 3d31a72b1..6b9212824 100755 --- a/app/modules/transmission/transmission.py +++ b/app/modules/transmission/transmission.py @@ -2,6 +2,8 @@ Transmission 客户端连接与下载任务操作封装。 """ +import base64 +import json import time from typing import List, Optional, Sequence, Tuple, Union from urllib.parse import urlsplit @@ -295,6 +297,53 @@ class Transmission: return None return None + def add_torrent_with_status( + self, content: Union[str, bytes], is_paused: Optional[bool] = False, + download_dir: Optional[str] = None, labels: Optional[list[str]] = None, + cookie: Optional[str] = None, + ) -> Tuple[Optional[Torrent], bool]: + """ + 添加任务并保留 RPC 的重复标志,供宿主决定是否可以选集。 + + SDK 的 add_torrent 会合并 torrent-added 与 torrent-duplicate,无法证明任务 + 是本次创建。此处复用 SDK 传输以保留认证、超时和 409 会话重试,只单独解释添加响应。 + 不依靠添加前查询,避免另一个调用方同时添加相同种子的竞争窗口。 + + :param content: 种子 URL、磁力链接或文件字节内容 + :param is_paused: 新任务是否以暂停状态添加 + :param download_dir: 下载器保存目录,省略时使用默认目录 + :param labels: 新任务的标签列表 + :param cookie: 下载种子 URL 使用的站点 Cookie + :return: 种子对象与是否已存在;未连接、请求失败或响应无效时返回 (None, False) + """ + arguments = { + key: value for key, value in { + "download-dir": download_dir, "paused": is_paused, "labels": labels, "cookies": cookie, + }.items() if value is not None + } + if isinstance(content, bytes) and not content.startswith(b"magnet:"): + arguments["metainfo"] = base64.b64encode(content).decode("ascii") + else: + arguments["filename"] = content.decode("utf-8") if isinstance(content, bytes) else content + if not self.trc and getattr(self, "_host", None) and getattr(self, "_port", None): + self.reconnect() + for attempt in range(2): + if not self.trc: + return None, False + try: + response = json.loads(self.trc._http_query({"method": "torrent-add", "arguments": arguments})) + if response.get("result") != "success": + raise ValueError(f"添加种子失败:{response.get('result')}") + for key, already_exists in (("torrent-added", False), ("torrent-duplicate", True)): + if fields := response.get("arguments", {}).get(key): + return Torrent(fields=fields), already_exists + raise ValueError("添加种子响应缺少任务信息") + except Exception as err: + logger.error(f"添加种子出错:{str(err)}") + if attempt == 0: + self.reconnect() + return None, False + def start_torrents(self, ids: TorrentIds) -> bool: """ 启动指定种子任务。 diff --git a/docs/rules/05-architecture.md b/docs/rules/05-architecture.md index 6fb5d7421..434d5a24e 100644 --- a/docs/rules/05-architecture.md +++ b/docs/rules/05-architecture.md @@ -45,7 +45,7 @@ Entrypoints (app/api, app/command, app/monitor, app/scheduler, app/agent, app/wo | Package | Responsibility and Ownership Boundary | | --- | --- | | `app/foundation/` | Generic reflection, collection/text/time utilities and pure helpers independent of MoviePilot state | -| `app/domain/` | Pure business rules — `meta/` and `metainfo.py` (title/release recognition), `projection/` (immutable TMDB/Douban/Bangumi/AniList to `MediaInfo` mappers imported directly by host callers instead of legacy `MediaInfo` setters), media identity source policy (`media.py`), music release/disc/cover rules (`music.py`), torrent identity (`torrent.py`), search collection rules (`search.py`), `classification/`, `plugin.py` and `chat.py` | +| `app/domain/` | Pure business rules — `meta/` and `metainfo.py` (title/release recognition), `projection/` (immutable TMDB/Douban/Bangumi/AniList to `MediaInfo` mappers imported directly by host callers instead of legacy `MediaInfo` setters), media identity source policy (`media.py`), music release/disc/cover rules (`music.py`), torrent identity and episode file selection (`torrent.py`), search collection rules (`search.py`), `classification/`, `plugin.py` and `chat.py` | | `app/application/` | Typed use-case services, deeply frozen snapshots and port `Protocol` definitions (`subscription/`, `history/`, `transfer/`, `download/`, `search/`, `site/`, `plugin/`, `security/`, `server/`, `chain/`, `outbox.py`, `agent.py`, `workflow.py`, `scheduling.py`, `commands.py`, `system.py`, `network.py`, `notification.py`, `mediaserver.py`, `rss.py`, `rules.py`) | | `app/chain/` | Shared workflow orchestrators (`subscribe/`, `download/`, `transfer/`, `search/`, `media/` same-named packages plus focused chains and `_recognition.py`, `_messaging.py`, `_interaction.py`, `_music.py` mixins) | | `app/modules/` | Pluggable downloaders, media servers, metadata/lyrics sources, indexers, notifications and `filemanager` storages (shared boilerplate templates live in `app/modules/_base/`) | diff --git a/docs/testing.md b/docs/testing.md index fcbd43e08..e1c9d15cb 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -205,10 +205,16 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)): ## 种子下载重试回归 -下载选集回归使用真实 qBittorrent/Transmission Module 与离线下载器端口,验证自定义识别词 +下载选集回归使用真实 qBittorrent/Transmission/rTorrent Module 与离线下载器端口,验证自定义识别词 从订阅计划一直传到下载器文件选择;目标集数不匹配或优先级未确认时不启动任务,不能写成功历史。 启动结果未知时尝试确认暂停;无法确认则明确要求检查下载器,不能宣称任务已停止。 已有下载任务只按原始种子 info 字节或磁力中的 v1/v2 哈希确认,名称与大小相同不能接管任务。 +已有任务返回存在标志,保留启停状态和文件选择,包括之前暂停的任务;不再通过重复提交自动恢复选集。 +新任务的视频文件按目标集交集选择,允许多集文件连带下载相邻集;无集号的非视频附属文件保留, +无集号视频不随整包附件自动选中。只有视频可证明目标集完整覆盖,单集请求仍允许唯一视频兜底。 +`tests/test_episode_file_selection.py` 覆盖三种下载器的一致规则,历史明细也按交集保留多集视频。 +`tests/test_transmission_add_status.py` 在 SDK HTTP 边界回放新增、重复和 409 会话握手,验证 +重复添加及响应丢失后的重试不会被宿主误当作可以暂停重选的新任务。 `tests/test_download_category.py` 从真实下载链经过 qBittorrent 模块和客户端,在 SDK 边界检查 音乐缺分类时使用“音乐”、已有分类优先,以及自动管理开关和指定路径的传递。 diff --git a/tests/fixtures/architecture/complexity-baseline.json b/tests/fixtures/architecture/complexity-baseline.json index 0fb886aa0..7a095686a 100644 --- a/tests/fixtures/architecture/complexity-baseline.json +++ b/tests/fixtures/architecture/complexity-baseline.json @@ -94,14 +94,14 @@ "app/modules/imdb/__init__.py:ImdbModule._to_media_info": 17, "app/modules/indexer/spider/__init__.py:SiteSpider.__get_search_url": 24, "app/modules/jellyfin/jellyfin.py:Jellyfin.get_tv_episodes": 18, - "app/modules/qbittorrent/__init__.py:QbittorrentModule.download": 20, + "app/modules/qbittorrent/__init__.py:QbittorrentModule.download": 19, "app/modules/qbittorrent/__init__.py:QbittorrentModule.list_torrents": 20, "app/modules/qqbot/gateway.py:run_gateway": 42, "app/modules/rtorrent/__init__.py:RtorrentModule.download": 16, "app/modules/rtorrent/__init__.py:RtorrentModule.list_torrents": 20, "app/modules/slack/__init__.py:SlackModule.message_parser": 16, "app/modules/slack/slack.py:Slack.send_medias_msg": 18, - "app/modules/transmission/__init__.py:TransmissionModule.download": 18, + "app/modules/transmission/__init__.py:TransmissionModule.download": 17, "app/modules/transmission/__init__.py:TransmissionModule.list_torrents": 22, "app/modules/trimemedia/api.py:Api.request": 16, "app/modules/ugreen/ugreen.py:Ugreen.get_tv_episodes": 21, diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index bc780fb73..b74390674 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -836,14 +836,15 @@ "from:transmission_rpc.session.SessionStats as SessionStats", "import:transmission_rpc as transmission_rpc" ], - "fingerprint": "1652e661cb17dbadb039fdc4ab73d6d06e47eb118292ba3693313e45834959cf", + "fingerprint": "43c697821ba063624f01a2c75f77f0ec9fe08a8e72a7ec991845c83c805bbc2b", "kind": "network_sdk", "source": "app.modules.transmission.transmission", "target": "transmission_rpc", "uses": [ "Transmission.__login_transmission|call:Client", "Transmission.__sync_incomplete_file_suffix|call:get_session", - "Transmission.__sync_incomplete_file_suffix|call:set_session" + "Transmission.__sync_incomplete_file_suffix|call:set_session", + "Transmission.add_torrent_with_status|call:Torrent" ] }, { diff --git a/tests/fixtures/architecture/dependency-policy.json b/tests/fixtures/architecture/dependency-policy.json index f94ba5c57..1b4a09590 100644 --- a/tests/fixtures/architecture/dependency-policy.json +++ b/tests/fixtures/architecture/dependency-policy.json @@ -145,7 +145,7 @@ {"source": "app.modules.qbittorrent.qbittorrent", "target": "qbittorrentapi", "kind": "network_sdk", "fingerprint": "b2f5a27f0c54cf95ed42fe99848fd6c9c0641caca8bc4ff8006a411cb427066d"}, {"source": "app.modules.slack.slack", "target": "slack_bolt", "kind": "network_sdk", "fingerprint": "d970999c7c77ca5e93ec8a2773fa0b3db10df63ecce780b5fd52ca038734666a"}, {"source": "app.modules.slack.slack", "target": "slack_sdk", "kind": "network_sdk", "fingerprint": "7559f31e4172ad3bbbaf161e1164ea48b997c56d05c77b49b82626298c39aa14"}, - {"source": "app.modules.transmission.transmission", "target": "transmission_rpc", "kind": "network_sdk", "fingerprint": "1652e661cb17dbadb039fdc4ab73d6d06e47eb118292ba3693313e45834959cf"} + {"source": "app.modules.transmission.transmission", "target": "transmission_rpc", "kind": "network_sdk", "fingerprint": "43c697821ba063624f01a2c75f77f0ec9fe08a8e72a7ec991845c83c805bbc2b"} ] }, { diff --git a/tests/test_architecture_egress.py b/tests/test_architecture_egress.py index 4dc721264..e6df792c3 100644 --- a/tests/test_architecture_egress.py +++ b/tests/test_architecture_egress.py @@ -143,7 +143,8 @@ FROZEN_EGRESS_FINGERPRINT_BY_EDGE = { ("app.modules.slack.slack", "slack_sdk"): "7559f31e4172ad3bbbaf161e1164ea48b997c56d05c77b49b82626298c39aa14", # Session 类型使扫描器识别原有的两处 close;未新增发送或会话关闭路径。 ("app.modules.themoviedb.tmdbv3api.tmdb", "requests"): "6c4ea48dd83616375a48785f9de9f477268f9236029e57b17ca1d2bde538fd4c", - ("app.modules.transmission.transmission", "transmission_rpc"): "1652e661cb17dbadb039fdc4ab73d6d06e47eb118292ba3693313e45834959cf", + # 区分添加与重复响应时只新增 Torrent 值对象构造,仍复用原 SDK 传输与会话握手。 + ("app.modules.transmission.transmission", "transmission_rpc"): "43c697821ba063624f01a2c75f77f0ec9fe08a8e72a7ec991845c83c805bbc2b", ("app.modules.wechat.wechatbot", "websocket"): "1bae78270eadce0571e2caaa111a5c0a9065ba2da97ebb26b8a5b76d3ed5eef6", ("app.startup.composition.network", "websocket"): "09e1909ac750fe40b145dde8fee52eedf84aaf2123f6a1bc38109252c89d6000", ("app.modules.zspace.zspace", "requests"): "9df3fd27b9696d45a72e7c8f67b5a9ad79a7371d1fe690bbaa17485bd1960d51", diff --git a/tests/test_download_history_episode_mapping.py b/tests/test_download_history_episode_mapping.py index e0a0d6d48..2f9af3a04 100644 --- a/tests/test_download_history_episode_mapping.py +++ b/tests/test_download_history_episode_mapping.py @@ -76,11 +76,15 @@ def test_selected_episode_file_resolves_its_own_hash(db, offset, durable): @pytest.mark.parametrize("durable", [False, True]) -def test_single_raw_episode_file_is_recorded_for_selected_episode(durable): +@pytest.mark.parametrize("file_list", [ + ["Show.S03E54.mp4"], + ["Show.S03E05E06.mp4", "Show.S03E07.mp4"], +], ids=["unique-video", "cross-boundary-video"]) +def test_selected_video_file_is_recorded_for_selected_episode(durable, file_list): """ - 唯一视频文件的原始累计集号与目标季集不一致时,成功结算仍须写入文件明细。 + 唯一视频兜底或跨集视频命中非起始集时,成功结算仍须写入对应文件明细。 """ - selected_file = "Show.S03E54.mp4" + selected_file = file_list[0] meta = MetaInfo("Show.S03E06.mp4") media = MediaInfo(type=MediaType.TV, title="示例剧", tmdb_id=107371) torrent = TorrentInfo(title="Show.S03E54") @@ -94,7 +98,7 @@ def test_single_raw_episode_file_is_recorded_for_selected_episode(durable): chain._settle_download_success( context=context, media=media, meta=meta, torrent=torrent, - folder_name="show", file_list=[selected_file], + folder_name="show", file_list=file_list, download_dir=Path("/downloads"), layout="Original", downloader="qb", download_hash="episode-6-hash", download_episodes="E06", episodes={6}, channel=None, source="subscribe", userid=None, diff --git a/tests/test_downloader_add_failure_message.py b/tests/test_downloader_add_failure_message.py index b18db1d8a..fb393afff 100644 --- a/tests/test_downloader_add_failure_message.py +++ b/tests/test_downloader_add_failure_message.py @@ -41,6 +41,7 @@ def _rejecting_server(module_cls): server.add_torrent.return_value = (False, []) elif module_cls is TransmissionModule: server.add_torrent.return_value = None + server.add_torrent_with_status.return_value = (None, False) else: server.add_torrent.return_value = False server.get_torrents.return_value = ([], False) diff --git a/tests/test_downloader_submission.py b/tests/test_downloader_submission.py index 94f2884c1..296b28294 100644 --- a/tests/test_downloader_submission.py +++ b/tests/test_downloader_submission.py @@ -56,10 +56,8 @@ def downloader(request): """ content, hashes = _torrent() server = Mock() - server.add_torrent.return_value = ( - (True, [hashes[0]]) if request.param is QbittorrentModule - else SimpleNamespace(hashString=hashes[0]) - ) + server.add_torrent.return_value = (True, [hashes[0]]) + server.add_torrent_with_status.return_value = (SimpleNamespace(hashString=hashes[0]), False) server.get_content_layout.return_value = "Original" server.is_force_resume.return_value = False server.get_files.side_effect = lambda *_args, **_kwargs: ( @@ -347,9 +345,9 @@ def _single_video_after_start(server, module, torrent_hash): return read_files -def test_existing_paused_magnet_recovers_on_retry(downloader): +def test_existing_paused_magnet_preserves_state_on_retry(downloader): """ - 重试遇到已存在的暂停磁力时,取到元数据后应完成选集自愈,而不是重复报 Conflict 分支失败。 + 重试不接管已存在的暂停磁力;返回存在标志并由用户决定如何恢复任务。 """ module, server, content, torrent_hash = downloader server.get_files.side_effect = _files_after_start(server, module, torrent_hash) @@ -362,6 +360,10 @@ def test_existing_paused_magnet_recovers_on_retry(downloader): assert result[1] == torrent_hash assert result[3] == DOWNLOAD_TASK_ALREADY_EXISTS + server.get_files.assert_not_called() + server.start_torrents.assert_not_called() + server.stop_torrents.assert_not_called() + server.set_files.assert_not_called() @pytest.mark.parametrize("file_count", [1, 2]) @@ -405,7 +407,7 @@ def _use_transmission_rpc(module, server) -> Transmission: """ client = Transmission.__new__(Transmission) client.trc = Mock() - client.add_torrent = server.add_torrent + client.add_torrent_with_status = server.add_torrent_with_status client.get_files = server.get_files module.get_instance.return_value = client return client @@ -443,7 +445,7 @@ def test_transmission_new_paused_task_starts_without_stop_rpc(downloader) -> Non result = module.download(content, Path("/downloads"), "", episodes={170}, custom_words=_CUSTOM_WORDS) assert result[1] == torrent_hash - assert client.add_torrent.call_args.kwargs["is_paused"] is True + assert client.add_torrent_with_status.call_args.kwargs["is_paused"] is True client.trc.stop_torrent.assert_not_called() client.trc.start_torrent.assert_called_once_with(ids=torrent_hash) @@ -472,9 +474,9 @@ def test_transmission_stopped_after_accepted_start_never_settles_success(downloa @pytest.mark.parametrize("pause_completes", [True, False]) -def test_transmission_async_pause_guards_file_selection(downloader, transmission_clock, pause_completes) -> None: +def test_transmission_new_task_async_pause_guards_file_selection(downloader, transmission_clock, pause_completes) -> None: """ - 重复任务异步暂停前不得选集;暂停超时也不能启动或记录订阅成功。 + 新任务异步暂停前不得选集;暂停超时也不能启动或记录订阅成功。 """ module, server, content, torrent_hash = downloader if not isinstance(module, TransmissionModule): @@ -595,6 +597,7 @@ def test_existing_task_requires_actual_info_hash(downloader, version, matching): content, hashes = _torrent(version) existing_hash = hashes[-1] if matching else "a" * 40 server.add_torrent.return_value = (False, []) if isinstance(module, QbittorrentModule) else None + server.add_torrent_with_status.return_value = (None, False) existing = {"name": "Same.Show.S01", "total_size": 42, "hash": existing_hash, "tags": "已整理"} server.get_torrents.return_value = ( [existing] if isinstance(module, QbittorrentModule) else @@ -611,12 +614,13 @@ def test_existing_task_requires_actual_info_hash(downloader, version, matching): server.set_torrent_tag.assert_not_called() -def test_existing_paused_task_cannot_bypass_failed_selection(downloader): +def test_existing_paused_task_is_returned_without_reselection(downloader): """ - 重试遇到相同 hash 时仍须核验选集,不能把此前暂停的失败任务结算为成功。 + 重试遇到相同 hash 时返回存在标志,不读取文件或改变原有暂停任务。 """ module, server, content, torrent_hash = downloader server.add_torrent.return_value = (False, []) if isinstance(module, QbittorrentModule) else None + server.add_torrent_with_status.return_value = (None, False) server.get_torrents.return_value = ( [{"hash": torrent_hash, "name": "Same.Show.S01", "total_size": 42, "tags": ""}] if isinstance(module, QbittorrentModule) else @@ -624,59 +628,45 @@ def test_existing_paused_task_cannot_bypass_failed_selection(downloader): None, ) result = module.download(content, Path("/downloads"), "", episodes={170}, downloader="test-downloader") - assert result[1] is None - assert "保持暂停" in result[3] + assert result[1] == torrent_hash + assert result[3] == DOWNLOAD_TASK_ALREADY_EXISTS + server.get_files.assert_not_called() + server.stop_torrents.assert_not_called() + server.set_files.assert_not_called() server.start_torrents.assert_not_called() @pytest.mark.parametrize("matching", [True, False]) -def test_transmission_duplicate_rpc_task_is_paused_before_selection(downloader, matching): +def test_transmission_duplicate_rpc_task_preserves_selection(downloader, matching): """ - RPC 把重复任务返回为非空 Torrent 时,先暂停正在运行的旧任务再选集。 + RPC 返回重复任务的非空 Torrent 时,识别词是否匹配都不暂停或重选原任务。 """ module, server, content, torrent_hash = downloader if not isinstance(module, TransmissionModule): pytest.skip("Transmission RPC 重复添加返回非空 Torrent") - task_state = {"running": True} - list_files = server.get_files.side_effect - - def stop_task(_torrent_hash): - """ - 模拟重复添加不会修改状态、显式暂停才能停止的原任务。 - """ - task_state["running"] = False - return True - - def get_paused_files(*args, **kwargs): - """ - 在真正读取和选择文件前验证旧任务已经暂停。 - """ - assert not task_state["running"] - return list_files(*args, **kwargs) - - server.stop_torrents.side_effect = stop_task - server.get_files.side_effect = get_paused_files + server.add_torrent_with_status.return_value = (SimpleNamespace(hashString=torrent_hash), True) result = module.download( content, Path("/downloads"), "", episodes={170}, custom_words=_CUSTOM_WORDS if matching else None, ) - server.stop_torrents.assert_called_once_with(torrent_hash) - assert result[1] == (torrent_hash if matching else None) - if not matching: - server.start_torrents.assert_not_called() - assert not task_state["running"] - assert "保持暂停" in result[3] + assert result[1] == torrent_hash + assert result[3] == DOWNLOAD_TASK_ALREADY_EXISTS + server.stop_torrents.assert_not_called() + server.start_torrents.assert_not_called() + server.get_files.assert_not_called() + server.set_files.assert_not_called() + server.set_unwanted_files.assert_not_called() @pytest.mark.parametrize("pause_result", [False, None]) -def test_transmission_duplicate_rpc_task_requires_confirmed_pause(downloader, pause_result): +def test_transmission_new_task_requires_confirmed_pause(downloader, pause_result): """ - 重复任务的暂停失败或状态未知时,不查询、重选或启动任何文件。 + 新任务的暂停失败或状态未知时,不查询、重选或启动任何文件。 """ module, server, content, torrent_hash = downloader if not isinstance(module, TransmissionModule): - pytest.skip("Transmission RPC 重复添加返回非空 Torrent") + pytest.skip("Transmission 新任务的暂停确认") server.stop_torrents.return_value = pause_result result = module.download(content, Path("/downloads"), "", episodes={170}, custom_words=_CUSTOM_WORDS) @@ -734,6 +724,7 @@ def _report_existing_task(server, module, torrent_hash) -> None: server.add_torrent.return_value = ( (False, []) if isinstance(module, QbittorrentModule) else None ) + server.add_torrent_with_status.return_value = (None, False) server.get_torrents.return_value = ( [{"hash": torrent_hash, "name": "Same.Show.S01", "total_size": 42, "tags": ""}] if isinstance(module, QbittorrentModule) else diff --git a/tests/test_episode_file_selection.py b/tests/test_episode_file_selection.py new file mode 100644 index 000000000..78abf6e8c --- /dev/null +++ b/tests/test_episode_file_selection.py @@ -0,0 +1,185 @@ +""" +三个下载器在选集、附属文件保留和已有任务保护上的一致性回归。 +""" + +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from torrentool.bencode import Bencode + +from app.chain.download.facade import DownloadChain +from app.domain import torrent as torrent_rules +from app.domain.context import Context +from app.modules.qbittorrent import QbittorrentModule +from app.modules.rtorrent import RtorrentModule +from app.modules.transmission import TransmissionModule +from app.schemas.download import DOWNLOAD_TASK_ALREADY_EXISTS + + +@pytest.fixture(params=[QbittorrentModule, TransmissionModule, RtorrentModule]) +def selected_downloader(request): + """ + 构造真实模块和离线下载器边界,保留下载链的识别词传递。 + """ + module = request.param.__new__(request.param) + content = Bencode.encode({"info": { + "name": "Show.S01", "piece length": 16384, "pieces": b"x" * 20, + "files": [{"length": 42, "path": ["Show.S01E05.mkv"]}], + }}) + torrent_hash = next(iter(torrent_rules.download_hashes(content))) + server = Mock() + server.add_torrent.return_value = (True, [torrent_hash]) if request.param is QbittorrentModule else True + server.add_torrent_with_status.return_value = (SimpleNamespace(hashString=torrent_hash), False) + server.get_torrent_id_by_tag.return_value = torrent_hash + server.get_content_layout.return_value = "Original" + server.is_force_resume.return_value = False + server.ensure_torrent_state.side_effect = ( + lambda torrent_hash, *, paused: + server.stop_torrents(torrent_hash) if paused else server.start_torrents(torrent_hash) + ) + module.get_instance = Mock(return_value=server) + module.normalize_path = Mock(return_value="/downloads") + module.get_default_config_name = Mock(return_value="test-downloader") + return module, server, content, torrent_hash + + +def _set_files(module, server, names: list[str]) -> None: + """ + 按各客户端的文件对象协议构造列表,目录集号不参与匹配。 + """ + files = [{"id": index, "name": f"Folder.S09E99/{name}"} for index, name in enumerate(names)] + server.get_files.side_effect = lambda *_args, **_kwargs: ( + [SimpleNamespace(**item) for item in files] + if isinstance(module, TransmissionModule) else list(files) + ) + + +def _assert_selected_files(module, server, torrent_hash, wanted, unwanted) -> None: + """ + 验证真实模块发送的文件选择 RPC,防止附属文件落入不下载列表。 + """ + if isinstance(module, TransmissionModule): + server.set_files.assert_called_once_with(torrent_hash, wanted) + server.set_unwanted_files.assert_called_once_with(torrent_hash, unwanted) + else: + priorities = {call.kwargs["priority"]: call.kwargs["file_ids"] for call in server.set_files.call_args_list} + assert priorities == {1: wanted, **({0: unwanted} if unwanted else {})} + server.start_torrents.assert_called_once_with(torrent_hash) + + +def test_cross_boundary_video_keeps_unnumbered_attachments(selected_downloader) -> None: + """ + 目标 E05 应选中 E05E06,并保留跨目录的字体、字幕和 NFO,排除其它视频。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, [ + "Show.S01E05E06.MKV", "Show.S01E07.mkv", "Fonts/Fonts.7z", + "Subtitles/Show.S01.ass", "Show.nfo", "Extras/Behind the Scenes.mp4", + "Show.S01E07.srt", "Show.S01E05.srt", + ]) + + result = module.download(content, Path("/downloads"), "", episodes={5}) + + assert result[1] == torrent_hash + _assert_selected_files(module, server, torrent_hash, [0, 2, 3, 4, 7], [1, 5, 6]) + + +@pytest.mark.parametrize("names,episodes", [ + (["Show.S01E05E06.mkv", "Show.nfo"], {5, 9}), + (["Show.S01E05E06.mkv", "Show.nfo"], {9}), + (["Show.S01E05.ass", "Fonts.7z"], {5}), + (["Show.S01E05.mkv", "Fonts.7z"], set()), +]) +def test_incomplete_video_coverage_never_starts(selected_downloader, names, episodes) -> None: + """ + 附属文件不能代替视频证明覆盖,缺集和空目标均不得执行文件设置或启动。 + """ + module, server, _content, torrent_hash = selected_downloader + _set_files(module, server, names) + if isinstance(module, RtorrentModule): + selected, _message = module._select_episode_files(server, torrent_hash, episodes) + else: + selected, _message = module._select_download_files(server, torrent_hash, episodes, None) + + assert selected is False + server.set_files.assert_not_called() + server.set_unwanted_files.assert_not_called() + server.start_torrents.assert_not_called() + + +@pytest.mark.parametrize("video", ["Show.S01E54.mkv", "Show.mkv"]) +def test_unique_video_fallback_keeps_unnumbered_attachments(selected_downloader, video) -> None: + """ + 唯一视频兜底在三个下载器上一致,并保留字体及无集号字幕。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, [video, "Fonts.7z", "Show.ass"]) + + result = module.download(content, Path("/downloads"), "", episodes={6}) + + assert result[1] == torrent_hash + _assert_selected_files(module, server, torrent_hash, [1, 2, 0], []) + + +def test_subscription_words_reach_all_downloader_modules(selected_downloader) -> None: + """ + 从下载链传入识别词,让多视频种子的修正集号在三个下载器上均能选中。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, ["Show.S01E54.mkv", "Show.S01E55.mkv", "Fonts.7z"]) + chain = DownloadChain.__new__(DownloadChain) + chain.run_module = lambda method, **kwargs: getattr(module, method)(**kwargs) + chain._settle_accepted_download = Mock() + chain._record_rejected_download = Mock() + prepared = SimpleNamespace( + torrent_content=content, torrent=SimpleNamespace(site_cookie=""), + download_dir=Path("/downloads"), media=SimpleNamespace(category="TV"), site_downloader=None, + ) + + result, _message = chain._submit_prepared_download( + prepared=prepared, context=Context(), episodes={6}, channel=None, source="subscribe", + downloader="test-downloader", userid=None, username=None, label=None, + custom_words="S01E54 => S01E06", governance=None, + ) + + assert result == torrent_hash + _assert_selected_files(module, server, torrent_hash, [0, 2], [1]) + chain._settle_accepted_download.assert_called_once() + chain._record_rejected_download.assert_not_called() + + +@pytest.mark.parametrize("status", ["downloading", "seeding", "stopped"]) +def test_existing_task_preserves_state_and_files(selected_downloader, status) -> None: + """ + 相同种子的下载、做种和暂停任务均只返回存在标志,不取文件、重选或启停。 + """ + module, server, content, torrent_hash = selected_downloader + server.add_torrent.return_value = (False, []) if isinstance(module, QbittorrentModule) else False + server.add_torrent_with_status.return_value = (None, False) + server.get_torrents.return_value = ( + [SimpleNamespace(hashString=torrent_hash, name="Show", labels=[], status=status)] + if isinstance(module, TransmissionModule) else + [{"hash": torrent_hash, "name": "Show", "tags": "", "state": status}], False, + ) + + result = module.download(content, Path("/downloads"), "", episodes={5}, custom_words="E05 => E99") + + assert result[1] == torrent_hash + assert result[3] == DOWNLOAD_TASK_ALREADY_EXISTS + for method in ("get_files", "set_files", "set_unwanted_files", "start_torrents", "stop_torrents", + "ensure_torrent_state", "torrents_set_force_start"): + getattr(server, method).assert_not_called() + + +def test_episode_selection_preserves_input_sets() -> None: + """ + 共享纯规则不改写文件识别结果或调用方的目标集合。 + """ + file_episodes = {5, 6} + episodes = {5} + + assert torrent_rules.select_episode_files([(0, file_episodes, True)], episodes) == ([0], [], {5, 6}) + assert file_episodes == {5, 6} + assert episodes == {5} diff --git a/tests/test_qbittorrent_compat.py b/tests/test_qbittorrent_compat.py index 89363369c..601b5a2d0 100644 --- a/tests/test_qbittorrent_compat.py +++ b/tests/test_qbittorrent_compat.py @@ -9,7 +9,7 @@ from enum import Enum from pathlib import Path from unittest.mock import MagicMock, call, patch -from app.domain.torrent import download_hashes +from app.domain.torrent import download_hashes, select_episode_files def _load_qbittorrent_modules(): @@ -55,6 +55,10 @@ def _load_qbittorrent_modules(): qbittorrentapi_transfer_module = types.ModuleType("qbittorrentapi.transfer") class _Logger: + """ + 接收兼容测试日志,隔离真实日志设施。 + """ + def info(self, *_args, **_kwargs): """ 吞掉普通日志,避免兼容性测试依赖真实日志系统。 @@ -112,6 +116,10 @@ def _load_qbittorrent_modules(): return str(value) class _FileCache: + """ + 仅模拟未命中结果,不访问真实缓存文件。 + """ + def get(self, *_args, **_kwargs): """ 固定模拟缓存未命中,避免测试读取真实文件缓存。 @@ -134,14 +142,29 @@ def _load_qbittorrent_modules(): self.episode_list = [] class _ModuleBase: + """ + 隔离下载器模块的宿主基类依赖。 + """ + pass class _DownloaderBase: + """ + 接受客户端类型参数的最小下载器基类。 + """ + def __class_getitem__(cls, _item): + """ + 忽略泛型参数并返回当前测试基类。 + """ return cls # 隔离环境下的下载器业务样板基类,镜像 app.modules._base.downloader 的行为 class _DownloaderModuleBase(_ModuleBase, _DownloaderBase): + """ + 镜像下载器通用入口,不注册真实实例或后台任务。 + """ + def test(self): """ 固定返回下载器连通成功,供模块兼容入口测试使用。 @@ -165,6 +188,9 @@ def _load_qbittorrent_modules(): return [item_factory(item) for item in source] def _get_torrent_info(self, content): + """ + 从测试路径或内存内容构造种子信息,磁力链接不解析为文件。 + """ torrent_info, torrent_content = None, None if isinstance(content, Path): torrent_content = content.read_bytes() if content.exists() else None @@ -178,6 +204,9 @@ def _load_qbittorrent_modules(): @staticmethod def _normalize_query_status(status): + """ + 将兼容状态别名归一为模块使用的查询枚举。 + """ status_value = getattr(status, "value", status) status_text = str(status_value or "").strip().lower() if status_text in {"transfer", TorrentStatus.TRANSFER.value}: @@ -191,6 +220,10 @@ def _load_qbittorrent_modules(): return TorrentQueryStatus.ALL class _Torrent: + """ + 为模块添加入口提供不访问网络的种子解析边界。 + """ + @staticmethod def from_string(content): """ @@ -199,7 +232,14 @@ def _load_qbittorrent_modules(): return types.SimpleNamespace(name="test", total_size=len(content)) class _DownloaderTorrent: + """ + 保存任务投影字段,便于验证客户端字段兼容。 + """ + def __init__(self, **kwargs): + """ + 保留模块传入的原始任务字段。 + """ self.__dict__.update(kwargs) class _DownloaderFile: @@ -273,7 +313,7 @@ def _load_qbittorrent_modules(): log_module.logger = _Logger() cache_module.FileCache = _FileCache - config_module.settings = types.SimpleNamespace(TORRENT_TAG="moviepilot-tag") + config_module.settings = types.SimpleNamespace(TORRENT_TAG="moviepilot-tag", RMT_MEDIAEXT=[".mkv"]) runtime_settings_module.get_runtime_setting = lambda key, default=None: getattr( config_module.settings, key, default ) @@ -290,6 +330,7 @@ def _load_qbittorrent_modules(): schema_types_module.DownloaderType = DownloaderType torrent_rules_module.is_magnet_link = _is_magnet_link torrent_rules_module.download_hashes = download_hashes + torrent_rules_module.select_episode_files = select_episode_files url_tools_module.parse_address = _parse_address text_tools_module.random_string = _random_string size_tools_module.format_compact_size = _format_size diff --git a/tests/test_review_download_site_regressions.py b/tests/test_review_download_site_regressions.py index 6a4d8c4a2..75b9595d2 100644 --- a/tests/test_review_download_site_regressions.py +++ b/tests/test_review_download_site_regressions.py @@ -78,7 +78,7 @@ def test_f036_transmission_requests_limit_fields(): @pytest.mark.parametrize('files,set_ok,start_ok', [ (None, True, True), - ([{'id': 0, 'name': 'Demo.S01E01.mkv'}], True, True), + ([{'id': 0, 'name': 'Demo.S01E03E04.mkv'}], True, True), ([{'id': 0, 'name': 'Demo.S01E01.mkv'}, {'id': 1, 'name': 'Demo.S01E02.mkv'}], False, True), ([{'id': 0, 'name': 'Demo.S01E02.mkv'}], True, False), ]) @@ -94,7 +94,8 @@ def test_f037_rtorrent_selection_failure_never_reports_hash(monkeypatch, files, module = object.__new__(RtorrentModule) monkeypatch.setattr(module, 'get_instance', lambda name: server) monkeypatch.setattr(module, 'normalize_path', lambda path, name: str(path)) - monkeypatch.setattr('app.modules.rtorrent.get_runtime_setting', lambda key: '') + monkeypatch.setattr('app.modules.rtorrent.get_runtime_setting', + lambda key, default=None: ['.mkv'] if key == 'RMT_MEDIAEXT' else '') can_start = bool(files and set_ok and any('E02' in f['name'] for f in files)) result = module.download(content, Path('/downloads'), '', episodes={2}, downloader='rt') assert result[1] is None diff --git a/tests/test_transmission_add_status.py b/tests/test_transmission_add_status.py new file mode 100644 index 000000000..22683173d --- /dev/null +++ b/tests/test_transmission_add_status.py @@ -0,0 +1,140 @@ +""" +Transmission 添加响应的新增与重复任务区分,以及 SDK 传输复用回归。 +""" + +import base64 +import json +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from transmission_rpc import Client + +from app.modules.transmission.transmission import Transmission + +_HASH = "0123456789abcdef0123456789abcdef01234567" +_MAGNET = f"magnet:?xt=urn:btih:{_HASH}" + + +def _response(result="success", arguments=None, status=200, headers=None): + """ + 构造原始 HTTP 响应,保留 SDK 会话握手及原始 RPC 参数解释。 + """ + return SimpleNamespace( + status_code=status, headers=headers or {}, + text=json.dumps({"result": result, "arguments": arguments or {}}), + ) + + +@pytest.fixture +def client(monkeypatch): + """ + 仅替换 HTTP 发送边界,SDK 仍执行认证地址、超时和 409 会话重试逻辑。 + """ + monkeypatch.setattr(Client, "get_session", Mock()) + sdk = Client(host="transmission.invalid", path="/proxy/transmission/rpc", username="user", password="pass") + sdk._http_session.post = Mock() + server = Transmission.__new__(Transmission) + server.trc = sdk + server.reconnect = Mock() + yield server + sdk._http_session.close() + + +@pytest.mark.parametrize("key,duplicate", [("torrent-added", False), ("torrent-duplicate", True)]) +@pytest.mark.parametrize("content", [b"torrent bytes", _MAGNET, _MAGNET.encode(), "https://tracker.invalid/file.torrent"]) +def test_add_status_preserves_raw_duplicate_and_parameters(client, key, duplicate, content) -> None: + """ + 两种成功结果均返回原始身份,重复标志独立保留且添加参数完整传到 SDK 传输。 + """ + client.trc._http_session.post.return_value = _response(arguments={ + key: {"id": 1, "name": "Show", "hashString": _HASH}, + }) + + torrent, already_exists = client.add_torrent_with_status( + content, is_paused=True, download_dir="/downloads", labels=["MP"], cookie="session=value", + ) + + assert torrent.hashString == _HASH + assert already_exists is duplicate + request = client.trc._http_session.post.call_args + assert request.args == ("http://user:pass@transmission.invalid:9091/proxy/transmission/rpc",) + assert request.kwargs["timeout"] == client.trc.timeout + arguments = request.kwargs["json"]["arguments"] + assert {key: arguments[key] for key in ("paused", "download-dir", "labels", "cookies")} == { + "paused": True, "download-dir": "/downloads", "labels": ["MP"], "cookies": "session=value", + } + if content == b"torrent bytes": + assert base64.b64decode(arguments["metainfo"]) == content + assert "filename" not in arguments + else: + assert arguments["filename"] == (content.decode() if isinstance(content, bytes) else content) + assert "metainfo" not in arguments + client.reconnect.assert_not_called() + + +def test_add_status_keeps_sdk_session_handshake(client) -> None: + """ + 409 响应仍由 SDK 更新会话并重试,新增任务标志在握手后保持准确。 + """ + client.trc._http_session.post.side_effect = [ + _response(status=409, headers={"x-transmission-session-id": "new-session"}), + _response(arguments={"torrent-added": {"id": 1, "name": "Show", "hashString": _HASH}}), + ] + + torrent, duplicate = client.add_torrent_with_status(_MAGNET) + + assert torrent.hashString == _HASH and duplicate is False + calls = client.trc._http_session.post.call_args_list + assert calls[0].kwargs["headers"] == {"x-transmission-session-id": "0"} + assert calls[1].kwargs["headers"] == {"x-transmission-session-id": "new-session"} + assert calls[1].kwargs["json"]["arguments"] == {"filename": _MAGNET, "paused": False} + client.reconnect.assert_not_called() + + +@pytest.mark.parametrize("response", [ + _response(result="invalid torrent"), _response(), + SimpleNamespace(status_code=200, headers={}, text="not json"), + SimpleNamespace(status_code=200, headers={}, text='{"result":"success","arguments":null}'), +]) +def test_add_status_rejects_invalid_responses(client, response) -> None: + """ + 无效、失败或缺任务字段的 RPC 响应只重连一次,不能被误报成新增成功。 + """ + client.trc._http_session.post.return_value = response + + assert client.add_torrent_with_status(_MAGNET) == (None, False) + assert client.trc._http_session.post.call_count == 2 + client.reconnect.assert_called_once_with() + + +def test_add_status_reconnects_without_losing_duplicate_result(client) -> None: + """ + 添加响应丢失后重试得到重复结果,也只能作为已有任务交还宿主。 + """ + first_sdk = client.trc + first_sdk._http_session.post.side_effect = ConnectionError("response lost") + second_sdk = Mock() + second_sdk._http_query.return_value = json.dumps({ + "result": "success", "arguments": {"torrent-duplicate": {"id": 1, "name": "Show", "hashString": _HASH}}, + }) + client.reconnect.side_effect = lambda: setattr(client, "trc", second_sdk) + + torrent, duplicate = client.add_torrent_with_status(_MAGNET) + + assert torrent.hashString == _HASH and duplicate is True + assert first_sdk._http_session.post.call_count == 1 + second_sdk._http_query.assert_called_once() + client.reconnect.assert_called_once_with() + + +def test_add_status_without_connection_does_not_claim_success() -> None: + """ + 未连接且没有地址时不发起添加或重连,缺少的任务对象不能当作新增成功。 + """ + server = Transmission.__new__(Transmission) + server.trc = None + server.reconnect = Mock() + + assert server.add_torrent_with_status(_MAGNET) == (None, False) + server.reconnect.assert_not_called()