From 81223374279e0a33e80b707b86c08bd270c226ff Mon Sep 17 00:00:00 2001 From: jxxghp Date: Sat, 14 Nov 2026 23:35:29 +0800 Subject: [PATCH] fix(download): preserve recognized season and episode mapping --- app/application/torrent/download.py | 13 +- app/chain/base.py | 4 + app/chain/download/batch.py | 2 + app/chain/download/history.py | 25 +-- app/chain/download/submission.py | 1 + app/domain/torrent.py | 117 ++++++++++++- app/modules/_base/downloader.py | 21 +++ app/modules/qbittorrent/__init__.py | 26 +-- app/modules/rtorrent/__init__.py | 21 ++- app/modules/transmission/__init__.py | 23 +-- app/runtime/extensions/module/contracts.py | 2 +- docs/architecture-overview.md | 2 +- docs/testing.md | 10 ++ .../architecture/dependency-baseline.json | 9 +- .../runtime-contract-baseline.json | 3 +- tests/test_download_batch_phases.py | 29 ++++ tests/test_download_chain.py | 6 +- .../test_download_history_episode_mapping.py | 33 +++- tests/test_downloader_submission.py | 7 +- tests/test_episode_file_selection.py | 159 +++++++++++++++++- tests/test_module_invocation_dispatcher.py | 47 ++++++ tests/test_qbittorrent_compat.py | 7 +- .../test_review_download_site_regressions.py | 4 +- 23 files changed, 493 insertions(+), 78 deletions(-) diff --git a/app/application/torrent/download.py b/app/application/torrent/download.py index 6a7943015..849f8899e 100644 --- a/app/application/torrent/download.py +++ b/app/application/torrent/download.py @@ -731,12 +731,16 @@ class TorrentHelper: return result @staticmethod - def get_torrent_episodes(files: list[str], custom_words: Optional[List[str]] = None) -> list[int]: + def get_torrent_episodes( + files: list[str], custom_words: Optional[List[str]] = None, + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, + ) -> list[int]: """ 从种子的文件清单中获取所有集数 :param files: 种子文件清单 :param custom_words: 当前下载来源的临时自定义识别词 + :param episode_selection: 目标季和已经确认的季集对应关系,冲突文件不贡献集数 :return: 识别到的全部集数 """ episodes: list[int] = [] @@ -748,10 +752,9 @@ class TorrentHelper: if not file_path.suffix or file_path.suffix.lower() not in config.video_extensions: continue # 只使用文件名识别 - meta = MetaInfo(file_path.name, custom_words=custom_words) - if not meta.begin_episode: - continue - episodes = list(set(episodes).union(set(meta.episode_list))) + episodes = list(set(episodes).union(torrent_rules.torrent_file_episodes( + file_path.name, custom_words=custom_words, episode_selection=episode_selection, + ))) return episodes def is_invalid(self, url: Optional[str]) -> bool: diff --git a/app/chain/base.py b/app/chain/base.py index 3b3a5c9ac..0678d7265 100644 --- a/app/chain/base.py +++ b/app/chain/base.py @@ -39,6 +39,7 @@ from app.schemas.types import ( if TYPE_CHECKING: from app.application.transfer.workflow import TransferPlanCheckpoint, TransferPlanningInput + from app.domain import torrent as torrent_rules class ChainBase(RecognitionMixin, MessageProcessingMixin, NotificationMixin, metaclass=ABCMeta): @@ -857,6 +858,7 @@ class ChainBase(RecognitionMixin, MessageProcessingMixin, NotificationMixin, met label: Optional[str] = None, downloader: Optional[str] = None, custom_words: Optional[str] = None, + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, ) -> Optional[Tuple[Optional[str], Optional[str], Optional[str], str]]: """ 根据种子文件,选择并添加下载任务 @@ -869,6 +871,7 @@ class ChainBase(RecognitionMixin, MessageProcessingMixin, NotificationMixin, met :param label: 标签 :param downloader: 下载器 :param custom_words: 来源识别词,选集须与订阅解析采用相同规则 + :param episode_selection: 目标季与已确认的原始集号对应关系,旧模块可不接收 :return: 下载器名称、种子Hash、种子文件布局、错误原因 """ return cast(Optional[Tuple[Optional[str], Optional[str], Optional[str], str]], self.run_module( @@ -881,6 +884,7 @@ class ChainBase(RecognitionMixin, MessageProcessingMixin, NotificationMixin, met label=label, downloader=downloader, custom_words=custom_words, + episode_selection=episode_selection, )) def download_added( diff --git a/app/chain/download/batch.py b/app/chain/download/batch.py index 85365ece0..916c39b9d 100644 --- a/app/chain/download/batch.py +++ b/app/chain/download/batch.py @@ -10,6 +10,7 @@ from app.application.download.admission import SubscriptionDownloadGovernance from app.application.torrent.download import TorrentHelper from app.chain.download.contract import _DownloadOwnerBase from app.domain import episode as episode_rules +from app.domain import torrent as torrent_rules from app.domain.context import ( Context, ) @@ -238,6 +239,7 @@ class _BatchDownloadRun: return None episodes = _new_torrent_helper().get_torrent_episodes( files, custom_words=self.custom_words, + episode_selection=torrent_rules.episode_selection_for_context(context), ) if partial: logger.info(f"{torrent.site_name} - {meta.org_string} 解析种子文件集数:{episodes}") diff --git a/app/chain/download/history.py b/app/chain/download/history.py index b2d2203d6..9447521f0 100644 --- a/app/chain/download/history.py +++ b/app/chain/download/history.py @@ -13,6 +13,7 @@ from app.application.chain.events import ( from app.application.classification.reference import effective_classification_snapshot from app.application.history import DownloadFileWrite, DownloadHistoryWrite from app.chain.download.contract import _DownloadOwnerBase +from app.domain import torrent as torrent_rules from app.domain.context import ( Context, MediaInfo, @@ -20,7 +21,6 @@ from app.domain.context import ( TorrentInfo, ) from app.domain.meta.metabase import MetaBase -from app.domain.metainfo import MetaInfo from app.runtime.log import logger from app.schemas.media import resolve_media_identity from app.schemas.types import ( @@ -128,7 +128,6 @@ class DownloadHistoryOwner(_DownloadOwnerBase): custom_words=custom_words, ) files_to_add: list[DownloadFileWrite] = [] - custom_word_list = custom_words.splitlines() if custom_words else [] for file in file_list: if not Path(file).suffix or Path(file).suffix.lower() not in self.runtime_config.media_extensions: continue @@ -155,21 +154,13 @@ class DownloadHistoryOwner(_DownloadOwnerBase): ) files_to_add = retained_files if episodes: - selected_files = [] - unmatched_single_files = [] - for item in files_to_add: - # 与订阅选集使用相同识别词,避免偏移前的文件集数被目标集数过滤。 - file_meta = MetaInfo(Path(cast(str, item.filepath)).stem, custom_words=custom_word_list) - file_episodes = set(file_meta.episode_list) - if file_episodes.intersection(episodes): - selected_files.append(item) - elif len(file_episodes) <= 1: - unmatched_single_files.append(item) - if (not selected_files and len(episodes) == 1 and media_file_count == 1 - and len(unmatched_single_files) == 1): - # 下载器已按唯一视频文件兜底选集,历史也要保留该文件,避免留下空记录。 - selected_files = unmatched_single_files - files_to_add = selected_files + wanted, _unwanted, _matched = torrent_rules.select_torrent_files( + ((index, cast(str, item.filepath)) for index, item in enumerate(files_to_add)), + episodes, self.runtime_config.media_extensions, custom_words, + torrent_rules.episode_selection_for_context(context), + allow_single_fallback=media_file_count == 1, + ) + files_to_add = [files_to_add[index] for index in wanted] frozen_files = tuple(files_to_add) event_payload = { "hash": download_hash, "context": context, "username": username, diff --git a/app/chain/download/submission.py b/app/chain/download/submission.py index 2d35e8c91..b781f9309 100644 --- a/app/chain/download/submission.py +++ b/app/chain/download/submission.py @@ -865,6 +865,7 @@ class DownloadSubmissionOwner(_DownloadResourceOwner): label=label, downloader=downloader or prepared.site_downloader, custom_words=custom_words, + episode_selection=torrent_rules.episode_selection_for_context(context) if episodes else None, ) actual_downloader, download_hash, layout, error_msg = ( result if result else (None, None, None, "未找到下载器") diff --git a/app/domain/torrent.py b/app/domain/torrent.py index 51dcfc4a4..ee25ad9ac 100644 --- a/app/domain/torrent.py +++ b/app/domain/torrent.py @@ -7,15 +7,120 @@ import binascii import hashlib import re from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path from typing import TYPE_CHECKING, Optional, Union from urllib.parse import parse_qs, urlsplit +from app.domain.metainfo import MetaInfo + if TYPE_CHECKING: - from app.domain.context import TorrentInfo + from app.domain.context import Context, TorrentInfo + + +@dataclass(frozen=True) +class EpisodeSelection: + """ + 下载目标季与识别阶段已经确认的季集对应关系,不推算未确认的集数。 + + :param season: 目标季号,0 表示特别篇 + :param source_season: 种子标题识别修正前的季号;None 表示未标季 + :param episode_map: 标题原集号与目标集号的对应项;空元组表示没有额外换算依据 + """ + + season: int + source_season: Optional[int] = None + episode_map: tuple[tuple[int, int], ...] = () + + +def episode_selection_for_context(context: "Context") -> Optional[EpisodeSelection]: + """ + 从单季候选冻结季集依据,只有等长的明确集号列表才建立逐集对应关系。 + + 不根据目标季号或单个差值外推整包偏移。来源识别词由文件解析自行应用, + 此处保留应用来源临时词之前的标题坐标,避免标题专用词无法命中文件名。 + """ + meta, torrent = context.meta_info, context.torrent_info + if meta is None or len(meta.season_list) != 1: + return None + season = meta.season_list[0] + original = MetaInfo(torrent.title or "", torrent.description) if torrent else None + source_season = original.begin_season if original else None + source_episodes = original.episode_list if original else [] + target_episodes = meta.episode_list + mapping: tuple[tuple[int, int], ...] = () + if original and len(original.season_list) == 1 and source_episodes and len(source_episodes) == len(target_episodes) and ( + source_season != season or source_episodes != target_episodes + ): + mapping = tuple(zip(source_episodes, target_episodes)) + return EpisodeSelection(season, source_season, mapping) + + +def _file_episode_coordinates( + name: str, custom_words: Optional[list[str]], selection: Optional[EpisodeSelection], +) -> tuple[Optional[set[int]], bool]: + """ + 解析文件并应用明确映射;None 表示季集冲突,布尔值区分无集号附件。 + """ + original = MetaInfo(Path(name).name) + meta = MetaInfo(Path(name).name, custom_words=custom_words) if custom_words else original + episodes = set(meta.episode_list) + numbered = bool(episodes) + if selection is None: + return episodes, numbered + corrected = (meta.begin_season, meta.episode_list) != (original.begin_season, original.episode_list) + if not corrected and selection.episode_map and original.begin_season in (None, selection.source_season): + mapping = dict(selection.episode_map) + mapped = {mapping[episode] for episode in episodes if episode in mapping} + return mapped or None, numbered + if meta.begin_season is not None and meta.season_list != [selection.season]: + return None, numbered + return episodes, numbered + + +def torrent_file_episodes( + name: str, custom_words: Optional[list[str]] = None, + episode_selection: Optional[EpisodeSelection] = None, +) -> set[int]: + """ + 返回文件在目标季中的已确认集号,供下载候选检查复用;冲突不贡献集数。 + """ + episodes, _numbered = _file_episode_coordinates(name, custom_words, episode_selection) + return episodes or set() + + +def select_torrent_files( + files: Iterable[tuple[int, str]], episodes: set[int], media_extensions: Iterable[str], + custom_words: Optional[str] = None, episode_selection: Optional[EpisodeSelection] = None, + *, allow_single_fallback: bool = True, +) -> tuple[list[int], list[int], set[int]]: + """ + 按目标季和已确认映射选择真实文件,下载器与历史结算共用相同规则。 + + :param files: 下载器文件索引和路径;仅解析文件名,父目录不作为季集依据 + :param episodes: 必须由视频完整覆盖的目标集号 + :param media_extensions: 视频后缀;历史调用方可传入其媒体后缀集合 + :param custom_words: 来源临时识别词,先于明确映射应用,避免重复换算 + :param episode_selection: 冻结的目标季与映射;None 保留旧调用方的集号选集行为 + :param allow_single_fallback: 历史去重后不能用剩余唯一文件冒充原始单文件种子 + :return: 需要下载的索引、不下载的索引和已选视频覆盖的目标集号 + """ + extensions = {extension.lower() for extension in media_extensions} + words = custom_words.splitlines() if custom_words else None + entries: list[tuple[int, set[int], bool]] = [] + excluded: set[int] = set() + for file_id, name in files: + is_video = Path(name).suffix.lower() in extensions + mapped, numbered = _file_episode_coordinates(name, words, episode_selection) + if mapped is None and (is_video or numbered): + excluded.add(file_id) + entries.append((file_id, mapped or set(), is_video)) + return select_episode_files(entries, episodes, excluded=excluded, allow_single_fallback=allow_single_fallback) def select_episode_files( files: Iterable[tuple[int, set[int], bool]], episodes: set[int], + *, excluded: Optional[set[int]] = None, allow_single_fallback: bool = True, ) -> tuple[list[int], list[int], set[int]]: """ 按视频覆盖集数选择文件,保留无集号的非视频附属文件。 @@ -25,6 +130,8 @@ def select_episode_files( :param files: 文件索引、已按来源识别词解析的集数、是否为视频组成的条目 :param episodes: 本次需要完整覆盖的目标集数 + :param excluded: 季集依据冲突的文件,不能参与匹配或唯一视频兜底 + :param allow_single_fallback: 是否允许唯一视频兜底 :return: 需要下载的索引、不下载的索引、已选视频覆盖的集数;输入条目不会被修改 """ wanted: list[int] = [] @@ -34,7 +141,9 @@ def select_episode_files( for file_id, file_episodes, is_video in files: if is_video: media_files.append((file_id, file_episodes)) - if file_episodes.intersection(episodes): + if excluded and file_id in excluded: + unwanted.append(file_id) + elif file_episodes.intersection(episodes): wanted.append(file_id) if is_video: matched.update(file_episodes) @@ -42,10 +151,10 @@ def select_episode_files( wanted.append(file_id) else: unwanted.append(file_id) - if not episodes.issubset(matched) and len(episodes) == 1 and len(media_files) == 1: + if allow_single_fallback and 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: + if len(file_episodes) <= 1 and (not excluded or file_id not in excluded): unwanted.remove(file_id) wanted.append(file_id) matched.update(episodes) diff --git a/app/modules/_base/downloader.py b/app/modules/_base/downloader.py index 96fc108be..d9d82bf18 100644 --- a/app/modules/_base/downloader.py +++ b/app/modules/_base/downloader.py @@ -47,6 +47,16 @@ class _DownloaderClient(Protocol): """ ... + def delete_torrents(self, delete_file: bool, ids: str) -> bool: + """ + 请求移除指定任务,选集失败清理必须保留已存在的文件。 + + :param delete_file: 是否删除文件;选集清理始终传 False + :param ids: 本次新增任务的哈希,不能传入已有任务 + :return: 下载器是否接受移除请求;False 时由上层通知人工核查 + """ + ... + DownloaderServiceT = TypeVar("DownloaderServiceT", bound=_DownloaderClient) TFile = TypeVar("TFile") @@ -57,6 +67,17 @@ class _DownloaderModuleBase(_ModuleBase, _DownloaderBase[DownloaderServiceT]): 下载器模块业务样板基类。 """ + @staticmethod + def _discard_failed_selection(server: _DownloaderClient, torrent_hash: str, message: str) -> str: + """ + 清理本次新增但选集失败的任务,保留文件并交回下载链通知、退避和换源。 + + 只由新增任务分支调用;已有任务不暂停、不重选也不删除。 + """ + if server.delete_torrents(delete_file=False, ids=torrent_hash): + return f"{message};已请求移除本次新增任务(保留文件),等待后续重试或换源" + return f"{message};移除本次新增任务失败,请在下载器核实(保留文件)" + def test(self) -> Optional[Tuple[bool, str]]: """ 检查全部已启用下载器的连接状态,必要时先尝试重连。 diff --git a/app/modules/qbittorrent/__init__.py b/app/modules/qbittorrent/__init__.py index 49fa79064..d991f50ac 100644 --- a/app/modules/qbittorrent/__init__.py +++ b/app/modules/qbittorrent/__init__.py @@ -111,7 +111,9 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): def download(self, content: Union[Path, str, bytes], download_dir: Path, cookie: str, episodes: Optional[Set[int]] = None, 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]]: + custom_words: Optional[str] = None, + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, + ) -> Optional[Tuple[Optional[str], Optional[str], Optional[str], str]]: """ 读取种子内容并添加下载任务,按需选择剧集文件。 @@ -126,6 +128,7 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): :param label: 逗号分隔的任务标签;省略时使用系统种子标签 :param downloader: 下载器配置名称,省略时使用默认实例 :param custom_words: 来源识别词,按行参与文件名识别,使选集结果与订阅一致 + :param episode_selection: 目标季与已确认的季集对应关系;选集失败清理本次新增任务并保留文件 :return: 下载器名称、任务哈希、内容布局和结果说明;无适用实例时返回 None, 添加失败时前三项为空,说明包含失败原因 """ @@ -213,6 +216,7 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): if is_paused: return self._finish_selected_download( server, torrent_hash, episodes or set(), custom_words, downloader, torrent_layout, + episode_selection, ) else: if server.is_force_resume(): @@ -227,13 +231,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], + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, ) -> Tuple[Optional[str], Optional[str], Optional[str], str]: """ 完成新任务选集,失败不向下载链返回成功 hash。 """ - selected, message = self._select_download_files(server, torrent_hash, episodes, custom_words) + selected, message = self._select_download_files(server, torrent_hash, episodes, custom_words, episode_selection) if not selected: - return None, None, None, message + return None, None, None, self._discard_failed_selection(server, torrent_hash, message) return downloader or self.get_default_config_name(), torrent_hash, torrent_layout, message @staticmethod @@ -273,11 +278,13 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): @staticmethod def _select_download_files( server: Qbittorrent, torrent_hash: str, episodes: Set[int], custom_words: Optional[str], + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, ) -> Tuple[bool, str]: """ 验证全部目标集数及优先级后启动;失败不确认成功,并明确暂停或未知状态。 视频按目标集交集选择,保留无集号非视频附件;单集请求保留唯一视频兜底。 + 有目标季时先核对季集依据,跨季冲突不参与兜底。 """ failure = f"选集失败,任务 {torrent_hash} 保持暂停,请在下载器检查" paused = True @@ -299,19 +306,14 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): for extension in get_runtime_setting("RMT_MEDIAEXT", []) } try: - 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, + wanted, unwanted, matched = torrent_rules.select_torrent_files( + ((item.get("id"), item.get("name")) for item in torrent_files), + episodes, media_extensions, custom_words, episode_selection, ) finally: torrent_files.clear() if not episodes or not episodes.issubset(matched): - return False, f"{state_failure}:未找到目标集数 {sorted(set(episodes) - 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}:文件优先级设置未确认" if not server.set_files(torrent_hash=torrent_hash, file_ids=wanted, priority=1): diff --git a/app/modules/rtorrent/__init__.py b/app/modules/rtorrent/__init__.py index 7a603a134..312fd8d30 100644 --- a/app/modules/rtorrent/__init__.py +++ b/app/modules/rtorrent/__init__.py @@ -89,6 +89,7 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): label: Optional[str] = None, downloader: Optional[str] = None, custom_words: Optional[str] = None, + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, ) -> Optional[Tuple[Optional[str], Optional[str], Optional[str], str]]: """ 读取种子内容并添加下载任务,按需选择剧集文件。 @@ -101,6 +102,7 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): :param label: 逗号分隔的任务标签;省略时使用系统种子标签 :param downloader: 下载器配置名称,省略时使用默认实例 :param custom_words: 来源识别词,按行参与文件名识别,使选集结果与订阅一致 + :param episode_selection: 目标季与已确认的季集对应关系;选集失败清理本次新增任务并保留文件 :return: 下载器名称、任务哈希、内容布局和结果说明;无适用实例时返回 None, 添加失败时前三项为空,说明包含失败原因 """ @@ -208,9 +210,9 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): else: torrent_hash = added_torrent_hash if episodes: - selected, message = self._select_episode_files(server, torrent_hash, episodes, custom_words) + selected, message = self._select_episode_files(server, torrent_hash, episodes, custom_words, episode_selection) if not selected: - return None, None, None, message + return None, None, None, self._discard_failed_selection(server, torrent_hash, message) return ( downloader or self.get_default_config_name(), torrent_hash, @@ -228,6 +230,7 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): @staticmethod def _select_episode_files( server: Rtorrent, torrent_hash: str, episodes: Set[int], custom_words: Optional[str] = None, + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, ) -> Tuple[bool, str]: """ 对暂停添加的任务完成选集,所有RPC均成功才允许下载链确认任务。 @@ -236,23 +239,19 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]): :param torrent_hash: 已暂停添加的任务Hash :param episodes: 本次需要完整覆盖的目标集数,多集文件按交集选择 :param custom_words: 来源识别词,按行参与物理文件名识别 + :param episode_selection: 目标季与已确认的季集对应关系,跨季冲突不参与唯一视频兜底 :return: 是否确认选集启动成功及结果说明 """ torrent_files = server.get_files(torrent_hash) if not torrent_files: return False, "获取种子文件失败,下载任务保留暂停状态,请检查下载器" 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, + wanted, unwanted, selected_episodes = torrent_rules.select_torrent_files( + ((item["id"], item["name"]) for item in torrent_files), + episodes, media_extensions, custom_words, episode_selection, ) if not episodes or not episodes.issubset(selected_episodes): - return False, "未匹配到目标集数,下载任务保留暂停状态" + return False, "未匹配到目标集数,请检查季集映射,下载任务保留暂停状态" 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): diff --git a/app/modules/transmission/__init__.py b/app/modules/transmission/__init__.py index b82fa0a49..108ef3d81 100644 --- a/app/modules/transmission/__init__.py +++ b/app/modules/transmission/__init__.py @@ -152,7 +152,9 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): def download(self, content: Union[Path, str, bytes], download_dir: Path, cookie: str, episodes: Optional[Set[int]] = None, 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]]: + custom_words: Optional[str] = None, + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, + ) -> Optional[Tuple[Optional[str], Optional[str], Optional[str], str]]: """ 读取种子内容并添加下载任务,按需选择剧集文件。 @@ -166,6 +168,7 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): :param label: 逗号分隔的任务标签;省略时使用系统种子标签 :param downloader: 下载器配置名称,省略时使用默认实例 :param custom_words: 来源识别词,按行参与文件名识别,使选集结果与订阅一致 + :param episode_selection: 目标季与已确认的季集对应关系;选集失败清理本次新增任务并保留文件 :return: 下载器名称、任务哈希、内容布局和结果说明;无适用实例时返回 None, 添加失败时前三项为空,说明包含失败原因 """ @@ -245,9 +248,10 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): if is_paused: selected, message = self._select_download_files( server, torrent_hash, episodes or set(), custom_words, + episode_selection, ) if not selected: - return None, None, None, message + return None, None, None, self._discard_failed_selection(server, torrent_hash, message) return downloader or self.get_default_config_name(), torrent_hash, torrent_layout, "添加下载任务成功" else: return downloader or self.get_default_config_name(), torrent_hash, torrent_layout, "添加下载任务成功" @@ -287,6 +291,7 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): @staticmethod def _select_download_files( server: Transmission, torrent_hash: str, episodes: Set[int], custom_words: Optional[str], + episode_selection: Optional[torrent_rules.EpisodeSelection] = None, ) -> Tuple[bool, str]: """ 先确认任务暂停再按来源集数映射选集,确认启动状态后才返回成功。 @@ -297,6 +302,7 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): :param torrent_hash: 需要暂停、选集并恢复的任务哈希 :param episodes: 需要完整匹配的目标集数;空集合不启动任务 :param custom_words: 来源识别词,按行参与物理文件名识别 + :param episode_selection: 目标季与已确认的季集对应关系,跨季冲突不参与唯一视频兜底 :return: 是否确认选集及启动成功,以及失败时的下载器核查说明 """ if not server.ensure_torrent_state(torrent_hash, paused=True): @@ -319,19 +325,14 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): for extension in get_runtime_setting("RMT_MEDIAEXT", []) } try: - 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, + wanted, unwanted, matched = torrent_rules.select_torrent_files( + ((item.id, item.name) for item in torrent_files), + episodes, media_extensions, custom_words, episode_selection, ) finally: torrent_files.clear() if not episodes or not episodes.issubset(matched): - return False, f"{state_failure}:未找到目标集数 {sorted(set(episodes) - 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}:文件选择设置未确认" if not server.ensure_torrent_state(torrent_hash, paused=False): diff --git a/app/runtime/extensions/module/contracts.py b/app/runtime/extensions/module/contracts.py index b2cff5d04..de7f1c569 100644 --- a/app/runtime/extensions/module/contracts.py +++ b/app/runtime/extensions/module/contracts.py @@ -1440,7 +1440,7 @@ _METHOD_CONTRACTS = { result_contract="DownloadTaskResult | None", aggregation=ModuleResultAggregation.FIRST_NON_EMPTY, required_parameters=("content", "download_dir", "cookie", "episodes", "category", "label", "downloader"), - optional_parameters=("custom_words",), + optional_parameters=("custom_words", "episode_selection"), ), "download_added": ModuleMethodContract( family="downloader", diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index 4f8bf56e8..70edaf1eb 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -851,7 +851,7 @@ flowchart LR | 指标 | 当前值 | |---|---:| | Python 模块 | 1166 | -| 内部导入边 | 10,165 | +| 内部导入边 | 10,168 | | 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) | diff --git a/docs/testing.md b/docs/testing.md index a154e2dee..6d688d781 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -113,6 +113,16 @@ AppPush 的所有用户范围由 `tests/test_notification_routing_parity.py` 验 ## 外部依赖:一律 mock,零真实网络 +季集选集由 `tests/test_episode_file_selection.py`、`tests/test_download_batch_phases.py` 和 +`tests/test_download_history_episode_mapping.py` 验证:S01E20 已识别为 S02E08 时,整包选中 +真实第 20 集,候选集数检查与历史文件明细采用相同对应关系。仅使用标题与识别结果中明确、 +等长的集号对应项,不根据季号猜测整包偏移;无对应依据时拒绝跨季同号文件,特别篇 S00 +独立匹配。来源识别词已经修正的文件不重复换算,无集号附件继续保留。 +选集失败只请求移除本次新增任务并保留文件,再由现有下载链记录退避、通知和尝试其它候选; +下载器拒绝清理时明确提示人工核查。已有任务不启停、不重选也不删除。 +`tests/test_module_invocation_dispatcher.py` 同时验证旧插件下载器不接收新增可选的 +`episode_selection` 时继续兼容。这些测试使用离线下载器替身,不代表真实 Docker 实例验收。 + AniList 直接访问官方 GraphQL 接口,不再探测 `trace.moe/anilist/`。中文数据集保存在 `/cache/anilist/anilist-chinese.json`,有效期 24 小时,同步、异步查询和重建客户端 共用快照;配置 `GITHUB_PROXY` 时先直连镜像,失败再按 `PROXY` 访问原始 GitHub 地址。 diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 83813a47c..34a4e2cd0 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -963,8 +963,8 @@ "runtime_only": true } }, - "edge_count": 10165, - "edge_sha256": "3256a88ae8af9a22db4a253019e9cd28ba510edce839b09886aacb0011e31389", + "edge_count": 10168, + "edge_sha256": "0d18e0059a0e92f3505b0fe57704f69f4c67a2571b70e64ed36ab89840dd386e", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -4764,6 +4764,7 @@ "app.chain.download.batch -> app.domain", "app.chain.download.batch -> app.domain.context", "app.chain.download.batch -> app.domain.episode", + "app.chain.download.batch -> app.domain.torrent", "app.chain.download.batch -> app.runtime", "app.chain.download.batch -> app.runtime.log", "app.chain.download.batch -> app.runtime.stop", @@ -4832,7 +4833,7 @@ "app.chain.download.history -> app.domain.context", "app.chain.download.history -> app.domain.meta", "app.chain.download.history -> app.domain.meta.metabase", - "app.chain.download.history -> app.domain.metainfo", + "app.chain.download.history -> app.domain.torrent", "app.chain.download.history -> app.runtime", "app.chain.download.history -> app.runtime.log", "app.chain.download.history -> app.schemas", @@ -7249,6 +7250,8 @@ "app.domain.title -> app.foundation.text", "app.domain.title -> app.schemas", "app.domain.title -> app.schemas.types", + "app.domain.torrent -> app.domain", + "app.domain.torrent -> app.domain.metainfo", "app.factory -> app.adapters", "app.factory -> app.adapters.observability", "app.factory -> app.adapters.observability.otel", diff --git a/tests/fixtures/architecture/runtime-contract-baseline.json b/tests/fixtures/architecture/runtime-contract-baseline.json index a11444f27..8e0e7b166 100644 --- a/tests/fixtures/architecture/runtime-contract-baseline.json +++ b/tests/fixtures/architecture/runtime-contract-baseline.json @@ -5687,7 +5687,8 @@ "family": "downloader", "input_contract": "DownloadTaskRequest", "optional_parameters": [ - "custom_words" + "custom_words", + "episode_selection" ], "plugin_short_circuit": true, "public_to_plugins": true, diff --git a/tests/test_download_batch_phases.py b/tests/test_download_batch_phases.py index 77c900e8d..010911d45 100644 --- a/tests/test_download_batch_phases.py +++ b/tests/test_download_batch_phases.py @@ -9,6 +9,7 @@ import pytest import app.chain.download.batch as download_batch import app.chain.download.selection as download_selection +from app.application.torrent.download import TorrentHelper from app.chain.download import DownloadChain from app.domain.context import Context, MediaInfo, TorrentInfo from app.domain.metainfo import MetaInfo @@ -23,6 +24,9 @@ def _context( season: int = 1, media_type: MediaType = MediaType.TV, ) -> Context: + """ + 构造指定媒体身份、季和集号的批量下载候选。 + """ meta = MetaInfo(f"{name} S{season:02d}") if episodes: meta.set_episode_list(list(episodes)) @@ -41,6 +45,9 @@ def _missing( season: int = 1, complete: bool = False, ) -> NotExistMediaInfo: + """ + 构造单季缺集或完整覆盖要求。 + """ return NotExistMediaInfo( season=season, episodes=list(episodes), total_episode=total, start_episode=1, require_complete_coverage=complete, @@ -72,12 +79,34 @@ def batch(monkeypatch): def _submitted(chain) -> list[Context]: + """ + 按调用顺序提取批量下载提交的候选。 + """ return [ call.args[0] if call.args else call.kwargs["context"] for call in chain.download_single.call_args_list ] +def test_partial_pack_maps_file_episodes_before_missing_intersection(batch): + """ + 拆包候选检查也须先映射,避免目标 E05 在累计编号包中被提前丢弃。 + """ + context = _context("Show", episodes=tuple(range(1, 13)), season=2) + context.torrent_info.title = "Show.S01E13-E24" + batch.chain.download_torrent.return_value = ( + b"torrent", None, [f"Show.S01E{episode:02}.mkv" for episode in range(13, 25)], + ) + batch.helper.get_torrent_episodes = TorrentHelper.get_torrent_episodes + missing = {"tmdb:1": {2: _missing((5,), total=12, season=2)}} + + downloaded, remaining = batch.chain.batch_download([context], missing) + + assert downloaded == [context] + assert remaining == {} + assert batch.chain.download_single.call_args.kwargs["episodes"] == {5} + + def test_batch_preserves_phase_order_and_submission_options(batch): """ 批量下载保持各媒体阶段顺序,并完整传递提交选项。 diff --git a/tests/test_download_chain.py b/tests/test_download_chain.py index 3779d6e96..b28ccc59a 100644 --- a/tests/test_download_chain.py +++ b/tests/test_download_chain.py @@ -954,9 +954,9 @@ class _FakeBatchTorrentHelper: results.append(context) return results - def get_torrent_episodes(self, _files, custom_words=None): + def get_torrent_episodes(self, _files, custom_words=None, episode_selection=None): """ - 记录自定义识别词配置,并返回预设剧集编号的副本。 + 记录自定义识别词配置,接受冻结的季集依据并返回预设剧集编号的副本。 """ type(self).received_custom_words = custom_words return list(self.episodes) @@ -998,7 +998,7 @@ def _build_tv_context(episode_list=None): anilist_id=None, ), meta_info=meta, - torrent_info=SimpleNamespace(title="Test Show S01 2160p", site_name="TestSite"), + torrent_info=SimpleNamespace(title="Test Show S01 2160p", description=None, site_name="TestSite"), allowed_episodes=None, confirmed_full_coverage=False, ) diff --git a/tests/test_download_history_episode_mapping.py b/tests/test_download_history_episode_mapping.py index 2f9af3a04..8171137df 100644 --- a/tests/test_download_history_episode_mapping.py +++ b/tests/test_download_history_episode_mapping.py @@ -87,7 +87,7 @@ def test_selected_video_file_is_recorded_for_selected_episode(durable, file_list selected_file = file_list[0] meta = MetaInfo("Show.S03E06.mp4") media = MediaInfo(type=MediaType.TV, title="示例剧", tmdb_id=107371) - torrent = TorrentInfo(title="Show.S03E54") + torrent = TorrentInfo(title="Show.S03E54" if len(file_list) == 1 else "Show.S03E05E06") context = Context(meta_info=meta, media_info=media, torrent_info=torrent) chain = DownloadChain.__new__(DownloadChain) chain.download_history_repository = MagicMock() @@ -110,3 +110,34 @@ def test_selected_video_file_is_recorded_for_selected_episode(durable, file_list else: files = chain.download_history_repository.add.call_args.args[1] assert [file.filepath for file in files] == [selected_file] + + +@pytest.mark.parametrize("durable", [False, True]) +def test_cross_season_mapping_records_only_the_physical_target(durable): + """ + 累计第 20 集映射为 S02E08 后,只记录真正选中的第 20 集,排除同号的第 8 集。 + """ + meta = MetaInfo("Show.S02E08") + torrent = TorrentInfo(title="Show.S01E20") + media = MediaInfo(type=MediaType.TV, title="示例剧", tmdb_id=107371) + context = Context(meta_info=meta, media_info=media, torrent_info=torrent) + chain = DownloadChain.__new__(DownloadChain) + chain.download_history_repository = MagicMock() + chain.durable_event_writer = MagicMock() if durable else None + chain._build_download_notification = MagicMock(return_value=None) + chain._submit_download_added_task = MagicMock() + chain.eventmanager = MagicMock() + + chain._settle_download_success( + context=context, media=media, meta=meta, torrent=torrent, + folder_name="show", file_list=["Show.S01E08.mkv", "Show.S01E20.mkv"], + download_dir=Path("/downloads"), layout="Original", downloader="qb", + download_hash="mapped-hash", download_episodes="E08", episodes={8}, channel=None, + source="subscribe", userid=None, username=None, torrent_content=b"torrent", custom_words=None, + ) + + if durable: + files = chain.durable_event_writer.download_added.call_args.kwargs["files"] + else: + files = chain.download_history_repository.add.call_args.args[1] + assert [file.filepath for file in files] == ["Show.S01E20.mkv"] diff --git a/tests/test_downloader_submission.py b/tests/test_downloader_submission.py index 296b28294..6e8018f10 100644 --- a/tests/test_downloader_submission.py +++ b/tests/test_downloader_submission.py @@ -547,12 +547,12 @@ def test_transmission_empty_episode_selection_never_starts_task() -> None: @pytest.mark.parametrize("failure", ["unmatched", "missing_files", "priority", "start"]) -def test_selection_failure_keeps_paused_task_and_never_settles_success(downloader, failure): +def test_selection_failure_releases_new_task_and_never_settles_success(downloader, failure): """ - 零匹配或下载器未确认选集时,不启动整包或把非空 hash 当成功。 + 零匹配或下载器未确认选集时,清理新增任务并保留文件,不能把非空 hash 当成功。 文件列表为空时允许一次有界启动取元数据(#7347:暂停磁力无元数据时文件列表恒为空), - 超时后仍恢复暂停、不记录成功。 + 超时后先请求暂停再清理任务,不记录成功。 """ module, server, content, torrent_hash = downloader words = None if failure == "unmatched" else _CUSTOM_WORDS @@ -585,6 +585,7 @@ def test_selection_failure_keeps_paused_task_and_never_settles_success(downloade assert "保持暂停" in message chain._settle_accepted_download.assert_not_called() chain._record_rejected_download.assert_called_once() + server.delete_torrents.assert_called_once_with(delete_file=False, ids=torrent_hash) @pytest.mark.parametrize("version", ["v1", "v2", "hybrid"]) diff --git a/tests/test_episode_file_selection.py b/tests/test_episode_file_selection.py index 78abf6e8c..e7f448bca 100644 --- a/tests/test_episode_file_selection.py +++ b/tests/test_episode_file_selection.py @@ -11,11 +11,13 @@ 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.domain.context import Context, MediaInfo, TorrentInfo +from app.domain.metainfo import MetaInfo 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 +from app.schemas.types import MediaType @pytest.fixture(params=[QbittorrentModule, TransmissionModule, RtorrentModule]) @@ -169,7 +171,7 @@ def test_existing_task_preserves_state_and_files(selected_downloader, status) -> 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"): + "ensure_torrent_state", "torrents_set_force_start", "delete_torrents"): getattr(server, method).assert_not_called() @@ -183,3 +185,156 @@ def test_episode_selection_preserves_input_sets() -> None: assert torrent_rules.select_episode_files([(0, file_episodes, True)], episodes) == ([0], [], {5, 6}) assert file_episodes == {5, 6} assert episodes == {5} + + +@pytest.mark.parametrize("source,target,requested,wanted", [ + ("Show.S01E20", "Show.S02E08", {8}, [19]), + ("Show.S01E13-E24", "Show.S02E01-E12", {5}, [16]), + ("Show.S01E20", "Show.S01E08", {8}, [19]), +]) +def test_recognized_season_episode_mapping_reaches_selection( + selected_downloader, source, target, requested, wanted, +) -> None: + """ + 真实下载链须按已识别的对应关系选择累计集号,不能误选同号的早期剧集。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, [f"Show.S01E{episode:02}.mkv" for episode in range(1, 25)]) + context = Context(meta_info=MetaInfo(target), torrent_info=TorrentInfo(title=source), + media_info=MediaInfo(type=MediaType.TV)) + prepared = SimpleNamespace( + torrent_content=content, torrent=context.torrent_info, + download_dir=Path("/downloads"), media=context.media_info, site_downloader=None, + ) + chain = DownloadChain.__new__(DownloadChain) + chain.run_module = lambda method, **kwargs: getattr(module, method)(**kwargs) + chain._settle_accepted_download = Mock() + chain._record_rejected_download = Mock() + + result, _message = chain._submit_prepared_download( + prepared=prepared, context=context, episodes=requested, channel=None, source="subscribe", + downloader="test-downloader", userid=None, username=None, label=None, + custom_words=None, governance=None, + ) + + assert result == torrent_hash + _assert_selected_files(module, server, torrent_hash, wanted, [i for i in range(24) if i not in wanted]) + chain._settle_accepted_download.assert_called_once() + + +@pytest.mark.parametrize("names", [ + ["Show.S01E08.mkv"], + ["Show.S01E08.mkv", "Show.S01E20.mkv"], +]) +def test_unmapped_season_mismatch_rejects_and_releases_new_task(selected_downloader, names) -> None: + """ + 无对应关系时拒绝跨季同号文件,清理本次新增任务并将失败交回通知与退避流程。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, names) + selection = torrent_rules.episode_selection_for_context(Context( + meta_info=MetaInfo("Show.S02"), torrent_info=TorrentInfo(title="Show.S01"), + )) + + result = module.download(content, Path("/downloads"), "", episodes={8}, episode_selection=selection) + + assert result[1] is None + assert "季集" in result[3] + assert "已请求移除" in result[3] + server.delete_torrents.assert_called_once_with(delete_file=False, ids=torrent_hash) + server.set_files.assert_not_called() + server.start_torrents.assert_not_called() + + +def test_season_mapping_does_not_double_apply_custom_words(selected_downloader) -> None: + """ + 文件本身已被来源识别词修正时,不能再次应用种子标题的集数映射。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, ["Show.S01E20.mkv", "Show.S01E08.mkv"]) + selection = torrent_rules.episode_selection_for_context(Context( + meta_info=MetaInfo("Show.S02E08"), torrent_info=TorrentInfo(title="Show.S01E20"), + )) + + result = module.download(content, Path("/downloads"), "", episodes={8}, episode_selection=selection, + custom_words="S01E20 => S02E08") + + assert result[1] == torrent_hash + _assert_selected_files(module, server, torrent_hash, [0], [1]) + + +@pytest.mark.parametrize("names,selection,wanted", [ + (["Show.S01E08.mkv", "Show.S02E08.mkv", "Show.S02.ass"], torrent_rules.EpisodeSelection(2), [1, 2]), + (["Show.S01E08.mkv", "Show.S00E08.mkv"], torrent_rules.EpisodeSelection(0), [1]), + (["Show.E20.mkv", "Show.E08.mkv"], torrent_rules.EpisodeSelection(2, None, ((20, 8),)), [0]), + (["Show.S01E08.mkv", "Show.S01E20.mkv", "Show.S01E20.srt", "Show.S01E08.srt", "Fonts.7z"], + torrent_rules.EpisodeSelection(2, 1, ((20, 8),)), [1, 2, 4]), +]) +def test_season_selection_preserves_attachments_and_specials(selected_downloader, names, selection, wanted) -> None: + """ + 季号、特别篇、无季累计编号和带集号字幕使用同一映射,未编号附件继续保留。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, names) + + result = module.download(content, Path("/downloads"), "", episodes={8}, episode_selection=selection) + + assert result[1] == torrent_hash + _assert_selected_files(module, server, torrent_hash, wanted, [i for i in range(len(names)) if i not in wanted]) + + +def test_selection_failure_cleanup_failure_is_reported(selected_downloader) -> None: + """ + 下载器拒绝清理时保留真实状态说明,不能声称任务已移除或提交成功。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, ["Show.S01E08.mkv"]) + server.delete_torrents.return_value = False + + result = module.download(content, Path("/downloads"), "", episodes={8}, + episode_selection=torrent_rules.EpisodeSelection(2)) + + assert result[1] is None + assert "移除本次新增任务失败" in result[3] + assert "已请求移除" not in result[3] + server.delete_torrents.assert_called_once_with(delete_file=False, ids=torrent_hash) + + +def test_missing_mapping_notifies_and_records_download_backoff(selected_downloader) -> None: + """ + 跨季拒绝清理新任务后,真实下载链保留具体原因并触发失败通知和退避记账。 + """ + module, server, content, torrent_hash = selected_downloader + _set_files(module, server, ["Show.S01E08.mkv", "Show.S01E20.mkv"]) + context = Context(meta_info=MetaInfo("Show.S02E08"), torrent_info=TorrentInfo(title="Show.S01"), + media_info=MediaInfo(type=MediaType.TV, title="Show")) + prepared = SimpleNamespace(torrent_content=content, torrent=context.torrent_info, + meta=context.meta_info, media=context.media_info, + download_dir=Path("/downloads"), site_downloader=None) + chain = DownloadChain.__new__(DownloadChain) + chain.run_module = lambda method, **kwargs: getattr(module, method)(**kwargs) + chain._settle_accepted_download = Mock() + chain._record_download_failure = Mock() + chain.post_message = Mock() + + result, message = chain._submit_prepared_download( + prepared=prepared, context=context, episodes={8}, channel=None, source="subscribe", + downloader="test-downloader", userid=None, username=None, label=None, + custom_words=None, governance=None, + ) + + assert result is None + assert "季集映射" in message + assert chain._record_download_failure.call_args.kwargs["error_msg"] == message + assert message in chain.post_message.call_args.args[0].text + chain._settle_accepted_download.assert_not_called() + server.delete_torrents.assert_called_once_with(delete_file=False, ids=torrent_hash) + + +@pytest.mark.parametrize("title", [None, "Show.S01-S02"]) +def test_unknown_or_multiseason_context_does_not_invent_mapping(title) -> None: + """ + 缺少元数据或包含多个目标季时,不能从集号数字推算单季映射。 + """ + context = Context(meta_info=MetaInfo(title) if title else None) + assert torrent_rules.episode_selection_for_context(context) is None diff --git a/tests/test_module_invocation_dispatcher.py b/tests/test_module_invocation_dispatcher.py index aaceb34e1..a77db81fb 100644 --- a/tests/test_module_invocation_dispatcher.py +++ b/tests/test_module_invocation_dispatcher.py @@ -9,6 +9,7 @@ from unittest.mock import Mock import pytest +from app.domain.torrent import EpisodeSelection from app.runtime.extensions.module.dispatcher import ( FrozenModuleProviderMissingError, FrozenPluginProviderRef, @@ -63,6 +64,52 @@ async def test_download_optional_mapping_keeps_legacy_provider_signatures( system_error.assert_not_called() +@pytest.mark.parametrize("provider_type", ["plugin", "system"]) +@pytest.mark.parametrize("async_dispatch", [False, True]) +@pytest.mark.parametrize("accepts_selection", [False, True]) +@pytest.mark.asyncio +async def test_download_season_mapping_preserves_custom_words_provider( + provider_type, async_dispatch, accepts_selection, +): + """ + 只支持识别词的旧签名继续可用,支持季集依据的模块收到同一个冻结对象。 + """ + selection = EpisodeSelection(2, 1, ((20, 8),)) + calls = [] + + def previous(content, download_dir, cookie, episodes, category, label, downloader, custom_words=None): + """ + 模拟支持识别词、尚未支持季集依据的插件下载器。 + """ + calls.append(custom_words) + return "previous" + + def current(**kwargs): + """ + 保存新下载器收到的季集依据和来源识别词。 + """ + calls.append((kwargs["custom_words"], kwargs["episode_selection"])) + return "current" + + callback = current if accepts_selection else previous + module = _Module("下载器", 10, callback) + module.download = callback + dispatcher, plugin_error, system_error, _ = _dispatcher( + plugins={("legacy", "旧插件"): {"download": callback}} if provider_type == "plugin" else None, + modules=[module] if provider_type == "system" else None, + ) + kwargs = { + "content": b"torrent", "download_dir": "/downloads", "cookie": "", "episodes": {8}, + "category": None, "label": None, "downloader": "test", "custom_words": "words", + "episode_selection": selection, + } + result = await dispatcher.async_dispatch("download", **kwargs) if async_dispatch else dispatcher.dispatch("download", **kwargs) + assert result == ("current" if accepts_selection else "previous") + assert calls == ([("words", selection)] if accepts_selection else ["words"]) + plugin_error.assert_not_called() + system_error.assert_not_called() + + class _PluginCatalog: """ 提供固定插件方法表的内存目录。 diff --git a/tests/test_qbittorrent_compat.py b/tests/test_qbittorrent_compat.py index 601b5a2d0..f46412cca 100644 --- a/tests/test_qbittorrent_compat.py +++ b/tests/test_qbittorrent_compat.py @@ -9,7 +9,8 @@ from enum import Enum from pathlib import Path from unittest.mock import MagicMock, call, patch -from app.domain.torrent import download_hashes, select_episode_files +from app.domain.torrent import download_hashes, select_torrent_files +from app.modules._base.downloader import _DownloaderModuleBase as ProductionDownloaderBase def _load_qbittorrent_modules(): @@ -165,6 +166,8 @@ def _load_qbittorrent_modules(): 镜像下载器通用入口,不注册真实实例或后台任务。 """ + _discard_failed_selection = staticmethod(ProductionDownloaderBase._discard_failed_selection) + def test(self): """ 固定返回下载器连通成功,供模块兼容入口测试使用。 @@ -330,7 +333,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 + torrent_rules_module.select_torrent_files = select_torrent_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 75b9595d2..709b8d3bc 100644 --- a/tests/test_review_download_site_regressions.py +++ b/tests/test_review_download_site_regressions.py @@ -90,7 +90,8 @@ def test_f037_rtorrent_selection_failure_never_reports_hash(monkeypatch, files, server = SimpleNamespace(add_torrent=Mock(return_value=True), get_torrent_id_by_tag=Mock(return_value=Torrent.from_string(content).info_hash), get_files=Mock(return_value=files), set_files=Mock(return_value=set_ok), - start_torrents=Mock(return_value=start_ok), stop_torrents=Mock(return_value=True)) + start_torrents=Mock(return_value=start_ok), stop_torrents=Mock(return_value=True), + delete_torrents=Mock(return_value=True)) module = object.__new__(RtorrentModule) monkeypatch.setattr(module, 'get_instance', lambda name: server) monkeypatch.setattr(module, 'normalize_path', lambda path, name: str(path)) @@ -99,6 +100,7 @@ def test_f037_rtorrent_selection_failure_never_reports_hash(monkeypatch, files, 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 + server.delete_torrents.assert_called_once_with(delete_file=False, ids=Torrent.from_string(content).info_hash) if not can_start: server.start_torrents.assert_not_called()