diff --git a/app/chain/download/history.py b/app/chain/download/history.py index 61b2c94f1..970b7cf0a 100644 --- a/app/chain/download/history.py +++ b/app/chain/download/history.py @@ -140,6 +140,7 @@ class DownloadHistoryOwner(_DownloadOwnerBase): torrentname=meta.org_string, ) ) + media_file_count = len(files_to_add) if already_exists: retained_files = self._filter_unrecorded_download_files(files_to_add, download_hash) if files_to_add and not retained_files: @@ -153,11 +154,19 @@ 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_meta.begin_episode and file_meta.begin_episode in 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 frozen_files = tuple(files_to_add) event_payload = { diff --git a/app/modules/qbittorrent/__init__.py b/app/modules/qbittorrent/__init__.py index 264648081..edd42304b 100644 --- a/app/modules/qbittorrent/__init__.py +++ b/app/modules/qbittorrent/__init__.py @@ -246,6 +246,9 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): ) -> Tuple[bool, str]: """ 验证全部目标集数及优先级后启动;失败不确认成功,并明确暂停或未知状态。 + + 本次只请求一集且种子只有一个视频文件时,即使文件名保留累计集号,也按 + 唯一视频文件兜底选中,避免识别后的季集与物理文件集号不一致导致误报缺集。 """ failure = f"选集失败,任务 {torrent_hash} 保持暂停,请在下载器检查" torrent_files = server.get_files( @@ -256,18 +259,36 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): 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: - meta = MetaInfo(Path(item.get("name")).name, - custom_words=custom_words.splitlines() if custom_words else []) + 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(item.get("id")) + wanted.append(file_id) matched.update(file_episodes) else: - unwanted.append(item.get("id")) + unwanted.append(file_id) 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): return False, f"{failure}:未找到目标集数 {sorted(set(episodes) - matched)}" if unwanted and not server.set_files(torrent_hash=torrent_hash, file_ids=unwanted, priority=0): diff --git a/app/modules/transmission/__init__.py b/app/modules/transmission/__init__.py index d4363b060..0c23b1508 100644 --- a/app/modules/transmission/__init__.py +++ b/app/modules/transmission/__init__.py @@ -256,6 +256,9 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): """ 先确认任务暂停再按来源集数映射选集,确认启动状态后才返回成功。 + 本次只请求一集且种子只有一个视频文件时,即使文件名保留累计集号,也按 + 唯一视频文件兜底选中,避免识别后的季集与物理文件集号不一致导致误报缺集。 + :param server: 已配置的 Transmission 客户端 :param torrent_hash: 需要暂停、选集并恢复的任务哈希 :param episodes: 需要完整匹配的目标集数;空集合不启动任务 @@ -271,17 +274,36 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): 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: - meta = MetaInfo(Path(item.name).name, custom_words=custom_words.splitlines() if custom_words else []) + 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(item.id) + wanted.append(file_id) matched.update(file_episodes) else: - unwanted.append(item.id) + unwanted.append(file_id) 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): return False, f"{failure}:未找到目标集数 {sorted(set(episodes) - matched)}" if not server.set_files(torrent_hash, wanted) or not server.set_unwanted_files(torrent_hash, unwanted): diff --git a/tests/test_download_history_episode_mapping.py b/tests/test_download_history_episode_mapping.py index 300194938..e0a0d6d48 100644 --- a/tests/test_download_history_episode_mapping.py +++ b/tests/test_download_history_episode_mapping.py @@ -73,3 +73,36 @@ def test_selected_episode_file_resolves_its_own_hash(db, offset, durable): ) assert resolved.download_hash == "episode-10-hash" assert resolved.downloader == "qb" + + +@pytest.mark.parametrize("durable", [False, True]) +def test_single_raw_episode_file_is_recorded_for_selected_episode(durable): + """ + 唯一视频文件的原始累计集号与目标季集不一致时,成功结算仍须写入文件明细。 + """ + selected_file = "Show.S03E54.mp4" + meta = MetaInfo("Show.S03E06.mp4") + media = MediaInfo(type=MediaType.TV, title="示例剧", tmdb_id=107371) + torrent = TorrentInfo(title="Show.S03E54") + 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=[selected_file], + download_dir=Path("/downloads"), layout="Original", downloader="qb", + download_hash="episode-6-hash", download_episodes="E06", + episodes={6}, 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] == [selected_file] diff --git a/tests/test_downloader_submission.py b/tests/test_downloader_submission.py index f4f6c713c..a141967e3 100644 --- a/tests/test_downloader_submission.py +++ b/tests/test_downloader_submission.py @@ -121,6 +121,39 @@ def test_subscription_mapping_reaches_real_downloader_selection(downloader): chain._record_rejected_download.assert_not_called() +def test_single_video_file_selection_accepts_episode_label_mismatch(downloader): + """ + 单集种子只有一个视频文件时,累计集号与目标季集不一致也应选中该文件。 + """ + module, server, _content, torrent_hash = downloader + server.get_files.side_effect = None + if isinstance(module, QbittorrentModule): + server.get_files.return_value = [ + {"id": 0, "name": "Show.S03E54.mp4"}, + {"id": 1, "name": "Show.S03E54.ass"}, + ] + else: + server.get_files.return_value = [ + SimpleNamespace(id=0, name="Show.S03E54.mp4"), + SimpleNamespace(id=1, name="Show.S03E54.ass"), + ] + + selected, message = module._select_download_files(server, torrent_hash, {6}, None) + + assert selected is True + assert "未找到目标集数" not in message + if isinstance(module, QbittorrentModule): + assert server.set_files.call_args_list[0].kwargs == { + "torrent_hash": torrent_hash, "file_ids": [1], "priority": 0, + } + assert server.set_files.call_args_list[1].kwargs == { + "torrent_hash": torrent_hash, "file_ids": [0], "priority": 1, + } + else: + server.set_files.assert_called_once_with(torrent_hash, [0]) + server.set_unwanted_files.assert_called_once_with(torrent_hash, [1]) + + @pytest.mark.parametrize("file_count", [1, 2]) def test_transmission_all_files_wanted_starts_without_unwanted_rpc(downloader, file_count) -> None: """