diff --git a/app/modules/qbittorrent/__init__.py b/app/modules/qbittorrent/__init__.py index edd42304b..dd1f0e53a 100644 --- a/app/modules/qbittorrent/__init__.py +++ b/app/modules/qbittorrent/__init__.py @@ -5,7 +5,7 @@ Qbittorrent 下载模块,负责实例路由、任务投影与下载文件选 from __future__ import annotations from pathlib import Path -from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Tuple, Union +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, Union from app.domain import torrent as torrent_rules from app.domain.metainfo import MetaInfo @@ -50,6 +50,10 @@ _QBITTORRENT_PAUSED_STATES = { _TORRENT_FILES_RETRY_TIMES = 5 # 文件索引查询之间的等待秒数。 _TORRENT_FILES_RETRY_INTERVAL = 1 +# 暂停磁力取元数据时最多等待 10 秒(每秒查询一次),仍无文件列表则恢复暂停并报错。 +_TORRENT_METADATA_RETRY_TIMES = 10 +# 取元数据时文件索引查询之间的等待秒数。 +_TORRENT_METADATA_RETRY_INTERVAL = 1 class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): @@ -240,6 +244,40 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): message = DOWNLOAD_TASK_ALREADY_EXISTS return downloader or self.get_default_config_name(), torrent_hash, torrent_layout, message + @staticmethod + def _fetch_files_with_metadata( + server: Qbittorrent, torrent_hash: str, failure: str, + ) -> Tuple[List[Any], bool, Optional[str]]: + """ + 暂停磁力取元数据:先启动任务再轮询文件列表,拿到后重新暂停。 + + 暂停的磁力不建立 peer/DHT 连接,文件列表恒为空;先启动取元数据, + 拿到后再重新暂停选集,超时仍恢复暂停,避免任务永久留在暂停状态。 + + :param server: 已配置的 qBittorrent 客户端 + :param torrent_hash: 需要取元数据的任务哈希 + :param failure: 任务保持暂停时的失败前缀 + :return: 文件列表、取元数据后是否确认暂停、失败说明;失败说明非空时 + 文件列表为空列表,暂停状态无效 + """ + if not server.start_torrents(torrent_hash): + return [], True, f"{failure}:获取种子文件失败" + torrent_files = server.get_files( + torrent_hash, + retry=_TORRENT_METADATA_RETRY_TIMES, + interval=_TORRENT_METADATA_RETRY_INTERVAL, + ) + if not torrent_files: + if not server.stop_torrents(torrent_hash): + return [], False, ( + f"选集失败,任务 {torrent_hash} 启动任务未确认,请在下载器核实,未记录成功" + ) + return [], True, f"{failure}:获取种子文件失败" + paused = server.stop_torrents(torrent_hash) + if not paused: + logger.warning(f"种子 {torrent_hash} 获取元数据后无法重新暂停,继续选集") + return torrent_files, paused, None + @staticmethod def _select_download_files( server: Qbittorrent, torrent_hash: str, episodes: Set[int], custom_words: Optional[str], @@ -251,11 +289,20 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): 唯一视频文件兜底选中,避免识别后的季集与物理文件集号不一致导致误报缺集。 """ failure = f"选集失败,任务 {torrent_hash} 保持暂停,请在下载器检查" + paused = True torrent_files = server.get_files( torrent_hash, retry=_TORRENT_FILES_RETRY_TIMES, interval=_TORRENT_FILES_RETRY_INTERVAL, ) if not torrent_files: - return False, f"{failure}:获取种子文件失败" + torrent_files, paused, error = QbittorrentModule._fetch_files_with_metadata( + server, torrent_hash, failure, + ) + if error: + return False, error + # 取元数据后无法重新暂停时任务仍在运行,后续失败不得再称“保持暂停”。 + state_failure = failure if paused else ( + f"选集失败,任务 {torrent_hash} 启动任务未确认,请在下载器核实,未记录成功" + ) wanted: list[int] = [] unwanted: list[int] = [] matched: set[int] = set() @@ -290,11 +337,11 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]): wanted.append(file_id) matched.update(episodes) if not set(episodes).issubset(matched): - return False, f"{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"{failure}:文件优先级设置未确认" + return False, f"{state_failure}:文件优先级设置未确认" if not server.set_files(torrent_hash=torrent_hash, file_ids=wanted, priority=1): - return False, f"{failure}:目标文件优先级设置未确认" + return False, f"{state_failure}:目标文件优先级设置未确认" started = ( server.torrents_set_force_start(torrent_hash) if server.is_force_resume() else server.start_torrents(torrent_hash) diff --git a/app/modules/transmission/__init__.py b/app/modules/transmission/__init__.py index 0c23b1508..3be771716 100644 --- a/app/modules/transmission/__init__.py +++ b/app/modules/transmission/__init__.py @@ -5,7 +5,7 @@ Transmission 下载模块,负责实例路由、任务投影与下载文件选 from __future__ import annotations from pathlib import Path -from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Literal, Optional, Set, Tuple, Union, overload +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Optional, Set, Tuple, Union, overload from app.domain import torrent as torrent_rules from app.domain.metainfo import MetaInfo @@ -44,6 +44,10 @@ _TRANSMISSION_DOWNLOADING_STATES = { _TRANSMISSION_PAUSED_STATES = { "stopped", } +# 暂停磁力取元数据时最多等待 10 秒(每秒查询一次),仍无文件列表则恢复暂停并报错。 +_TORRENT_METADATA_RETRY_TIMES = 10 +# 取元数据时文件索引查询之间的等待秒数。 +_TORRENT_METADATA_RETRY_INTERVAL = 1 @overload @@ -249,6 +253,38 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): else: return downloader or self.get_default_config_name(), torrent_hash, torrent_layout, "添加下载任务成功" + @staticmethod + def _fetch_files_with_metadata( + server: Transmission, torrent_hash: str, failure: str, + ) -> Tuple[List[Any], bool, Optional[str]]: + """ + 暂停磁力取元数据:先启动任务再轮询文件列表,拿到后重新暂停。 + + 暂停的磁力不建立 peer/DHT 连接,文件列表恒为空;先启动取元数据, + 拿到后再重新暂停选集,超时仍恢复暂停,避免任务永久留在暂停状态。 + + :param server: 已配置的 Transmission 客户端 + :param torrent_hash: 需要取元数据的任务哈希 + :param failure: 任务保持暂停时的失败前缀 + :return: 文件列表、取元数据后是否确认暂停、失败说明;失败说明非空时 + 文件列表为空列表,暂停状态无效 + """ + if not server.ensure_torrent_state(torrent_hash, paused=False): + return [], True, f"选集失败,任务 {torrent_hash} 启动任务未确认,请在下载器核实,未记录成功" + torrent_files = server.get_files( + torrent_hash, + retry=_TORRENT_METADATA_RETRY_TIMES, + interval=_TORRENT_METADATA_RETRY_INTERVAL, + ) + if not torrent_files: + if not server.ensure_torrent_state(torrent_hash, paused=True): + return [], False, f"选集失败,任务 {torrent_hash} 启动任务未确认,请在下载器核实,未记录成功" + return [], True, f"{failure}:获取种子文件失败" + paused = server.ensure_torrent_state(torrent_hash, paused=True) + if not paused: + logger.warning(f"种子 {torrent_hash} 获取元数据后无法确认暂停,继续选集") + return torrent_files, paused, None + @staticmethod def _select_download_files( server: Transmission, torrent_hash: str, episodes: Set[int], custom_words: Optional[str], @@ -268,9 +304,18 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): if not server.ensure_torrent_state(torrent_hash, paused=True): return False, f"选集失败,任务 {torrent_hash} 无法确认暂停,未执行选集,请在下载器核实" failure = f"选集失败,任务 {torrent_hash} 保持暂停,请在下载器检查" + paused = True torrent_files = server.get_files(torrent_hash) if not torrent_files: - return False, f"{failure}:获取种子文件失败" + torrent_files, paused, error = TransmissionModule._fetch_files_with_metadata( + server, torrent_hash, failure, + ) + if error: + return False, error + # 取元数据后无法确认暂停时任务仍在运行,后续失败不得再称“保持暂停”。 + state_failure = failure if paused else ( + f"选集失败,任务 {torrent_hash} 启动任务未确认,请在下载器核实,未记录成功" + ) wanted: list[int] = [] unwanted: list[int] = [] matched: set[int] = set() @@ -305,9 +350,9 @@ class TransmissionModule(_DownloaderModuleBase[Transmission]): wanted.append(file_id) matched.update(episodes) if not wanted or not set(episodes).issubset(matched): - return False, f"{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"{failure}:文件选择设置未确认" + return False, f"{state_failure}:文件选择设置未确认" if not server.ensure_torrent_state(torrent_hash, paused=False): if server.ensure_torrent_state(torrent_hash, paused=True): return False, f"{failure}:启动任务未确认,未记录成功" diff --git a/app/modules/transmission/transmission.py b/app/modules/transmission/transmission.py index 302e0bf8b..3d31a72b1 100755 --- a/app/modules/transmission/transmission.py +++ b/app/modules/transmission/transmission.py @@ -383,34 +383,48 @@ class Transmission: logger.error(f"删除种子出错:{str(err)}") return False - def get_files(self, tid: str) -> Optional[List[File]]: + def get_files(self, tid: str, retry: int = 1, interval: float = 0) -> Optional[List[File]]: """ 读取种子文件列表,兼容新旧 transmission-rpc 文件接口。 + 暂停的磁力在取到元数据前文件列表为空,调用方可多查几次等待元数据到达; + 默认只查一次,与旧行为一致。 + :param tid: 种子哈希 - :return: 文件列表;哈希为空、任务不存在、未连接或查询失败时返回 None + :param retry: 最多查询次数,最少执行 1 次 + :param interval: 查询间隔,单位秒;0 表示立即重试 + :return: 文件列表;哈希为空、任务不存在、未连接、查询失败或始终无文件时返回 None """ if not self.trc: return None if not tid: return None - try: - torrent = self.trc.get_torrent(tid) - except Exception as err: - logger.error(f"获取种子文件列表出错:{str(err)}") - return None - if not torrent: - return None - try: - get_files = getattr(torrent, "get_files", None) - if callable(get_files): - files: List[File] = get_files() - return files - legacy_files: List[File] = torrent.files() - return legacy_files - except Exception as err: - logger.error(f"获取种子文件列表出错:{str(err)}") - return None + retry_times = max(retry, 1) + last_error: Optional[Exception] = None + for index in range(retry_times): + try: + torrent = self.trc.get_torrent(tid) + except Exception as err: + last_error = err + torrent = None + if torrent: + try: + get_files = getattr(torrent, "get_files", None) + if callable(get_files): + files: List[File] = get_files() + if files: + return files + else: + legacy_files: List[File] = torrent.files() + if legacy_files: + return legacy_files + except Exception as err: + last_error = err + if index < retry_times - 1 and interval: + time.sleep(interval) + if last_error: + logger.error(f"获取种子文件列表出错:{str(last_error)}") + return None def set_files(self, tid: str, file_ids: list[int]) -> bool: """ diff --git a/tests/test_downloader_submission.py b/tests/test_downloader_submission.py index a141967e3..94f2884c1 100644 --- a/tests/test_downloader_submission.py +++ b/tests/test_downloader_submission.py @@ -154,6 +154,216 @@ def test_single_video_file_selection_accepts_episode_label_mismatch(downloader): server.set_unwanted_files.assert_called_once_with(torrent_hash, [1]) +def test_paused_magnet_without_metadata_resumes_to_fetch_then_repauses(downloader): + """ + 暂停的磁力无元数据时,先启动取元数据、再暂停选集,而不是直接报获取种子文件失败。 + + 复现 #7347:暂停任务不建立 peer/DHT 连接,第一次读文件为空;启动后元数据 + 到达,重新暂停后再按优先级选集、启动。 + """ + module, server, _content, torrent_hash = downloader + server.get_files.side_effect = _files_after_start(server, module, torrent_hash) + + selected, message = module._select_download_files(server, torrent_hash, {170}, _CUSTOM_WORDS) + + assert selected is True + assert "已选择集数" in message or message == "添加下载任务成功" + # 取元数据启动一次,选集完成后再启动一次;重新暂停发生在两次启动之间、设优先级之前。 + assert server.start_torrents.call_count == 2 + if isinstance(module, QbittorrentModule): + assert server.stop_torrents.call_count == 1 + 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: + assert server.stop_torrents.call_count == 2 + server.set_files.assert_called_once_with(torrent_hash, [0]) + server.set_unwanted_files.assert_called_once_with(torrent_hash, [1]) + calls = [str(call) for call in server.mock_calls] + resume = next(index for index, call in enumerate(calls) if "start_torrents" in call) + repause = next(index for index, call in enumerate(calls) if index > resume and "stop_torrents" in call) + set_files = next(index for index, call in enumerate(calls) if "set_files" in call) + final_start = max(index for index, call in enumerate(calls) if "start_torrents" in call) + assert resume < repause < set_files < final_start + + +def _files_after_start(server, module, torrent_hash): + """ + 模拟暂停磁力在启动前无元数据、启动后才有文件列表。 + + :param server: 被替换的外部下载器客户端 + :param module: 当前参数化的下载器模块 + :param torrent_hash: 本次选集的任务哈希 + """ + if isinstance(module, QbittorrentModule): + files = [{"id": index, "name": f"Folder.S09E99/{name}"} for index, name in enumerate(_FILES)] + else: + files = [SimpleNamespace(id=index, name=f"Folder.S09E99/{name}") for index, name in enumerate(_FILES)] + + def read_files(*_args, **_kwargs): + """ + 启动前返回空列表模拟无元数据,启动后返回真实文件列表。 + """ + return list(files) if server.start_torrents.called else [] + + return read_files + + +def test_metadata_wait_failure_restores_paused_state(downloader): + """ + 启动后仍无元数据时,任务应恢复暂停并报获取种子文件失败,不能留在运行状态。 + """ + module, server, _content, torrent_hash = downloader + server.get_files.side_effect = None + server.get_files.return_value = [] + + selected, message = module._select_download_files(server, torrent_hash, {170}, _CUSTOM_WORDS) + + assert selected is False + assert "获取种子文件失败" in message and "保持暂停" in message + server.start_torrents.assert_called_once_with(torrent_hash) + if isinstance(module, QbittorrentModule): + server.stop_torrents.assert_called_once_with(torrent_hash) + else: + assert server.stop_torrents.call_count == 2 + server.set_files.assert_not_called() + server.set_unwanted_files.assert_not_called() + # 取元数据等待次数有界:第一次 5×1s,取元数据时 10×1s。 + assert server.get_files.call_count == 2 + assert server.get_files.call_args_list[1].kwargs == {"retry": 10, "interval": 1} + if isinstance(module, QbittorrentModule): + assert server.get_files.call_args_list[0].kwargs == {"retry": 5, "interval": 1} + else: + assert server.get_files.call_args_list[0].kwargs == {} + + +def test_repause_failure_reports_unconfirmed_state(downloader): + """ + 取元数据后无法重新暂停时,后续失败不得再称“保持暂停”,必须报状态未确认。 + """ + module, server, _content, torrent_hash = downloader + server.get_files.side_effect = _files_after_start(server, module, torrent_hash) + if isinstance(module, QbittorrentModule): + server.stop_torrents.return_value = False + else: + server.stop_torrents.side_effect = [True, False] + + selected, message = module._select_download_files(server, torrent_hash, {999}, _CUSTOM_WORDS) + + assert selected is False + assert "未找到目标集数" in message + assert "核实" in message + assert "保持暂停" not in message + + +def test_metadata_timeout_repause_failure_reports_unconfirmed_state(downloader): + """ + 超时仍无元数据且恢复暂停失败时,不得报“保持暂停”,必须报状态未确认。 + """ + module, server, _content, torrent_hash = downloader + server.get_files.side_effect = None + server.get_files.return_value = [] + if isinstance(module, QbittorrentModule): + server.stop_torrents.return_value = False + else: + server.stop_torrents.side_effect = [True, False] + + selected, message = module._select_download_files(server, torrent_hash, {170}, _CUSTOM_WORDS) + + assert selected is False + assert "核实" in message + assert "保持暂停" not in message + assert "获取种子文件失败" not in message + + +def test_metadata_resume_uses_plain_start_under_force_resume(downloader): + """ + 开启强制恢复时,取元数据仍用普通启动,最终启动才用强制恢复;取元数据不等同于下载。 + """ + module, server, _content, torrent_hash = downloader + if not isinstance(module, QbittorrentModule): + pytest.skip("qBittorrent 强制恢复") + server.is_force_resume.return_value = True + server.get_files.side_effect = _files_after_start(server, module, torrent_hash) + + selected, _message = module._select_download_files(server, torrent_hash, {170}, _CUSTOM_WORDS) + + assert selected is True + server.start_torrents.assert_called_once_with(torrent_hash) + server.torrents_set_force_start.assert_called_once_with(torrent_hash) + + +def test_metadata_resume_composes_with_single_video_fallback(downloader): + """ + 取元数据成功后,#7345 的单视频兜底仍生效:单集种子只有一个视频文件时选中它。 + """ + module, server, _content, torrent_hash = downloader + server.get_files.side_effect = _single_video_after_start(server, module, torrent_hash) + + 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]) + + +def _single_video_after_start(server, module, torrent_hash): + """ + 模拟单视频种子在启动前无元数据、启动后才有文件列表。 + + :param server: 被替换的外部下载器客户端 + :param module: 当前参数化的下载器模块 + :param torrent_hash: 本次选集的任务哈希 + """ + if isinstance(module, QbittorrentModule): + files = [ + {"id": 0, "name": "Show.S03E54.mp4"}, + {"id": 1, "name": "Show.S03E54.ass"}, + ] + else: + files = [ + SimpleNamespace(id=0, name="Show.S03E54.mp4"), + SimpleNamespace(id=1, name="Show.S03E54.ass"), + ] + + def read_files(*_args, **_kwargs): + """ + 启动前返回空列表模拟无元数据,启动后返回真实文件列表。 + """ + return list(files) if server.start_torrents.called else [] + + return read_files + + +def test_existing_paused_magnet_recovers_on_retry(downloader): + """ + 重试遇到已存在的暂停磁力时,取到元数据后应完成选集自愈,而不是重复报 Conflict 分支失败。 + """ + module, server, content, torrent_hash = downloader + server.get_files.side_effect = _files_after_start(server, module, torrent_hash) + _report_existing_task(server, module, torrent_hash) + + result = module.download( + content, Path("/downloads"), "", episodes={170}, + custom_words=_CUSTOM_WORDS, downloader="test-downloader", + ) + + assert result[1] == torrent_hash + assert result[3] == DOWNLOAD_TASK_ALREADY_EXISTS + + @pytest.mark.parametrize("file_count", [1, 2]) def test_transmission_all_files_wanted_starts_without_unwanted_rpc(downloader, file_count) -> None: """ @@ -338,6 +548,9 @@ def test_transmission_empty_episode_selection_never_starts_task() -> None: def test_selection_failure_keeps_paused_task_and_never_settles_success(downloader, failure): """ 零匹配或下载器未确认选集时,不启动整包或把非空 hash 当成功。 + + 文件列表为空时允许一次有界启动取元数据(#7347:暂停磁力无元数据时文件列表恒为空), + 超时后仍恢复暂停、不记录成功。 """ module, server, content, torrent_hash = downloader words = None if failure == "unmatched" else _CUSTOM_WORDS @@ -358,7 +571,11 @@ def test_selection_failure_keeps_paused_task_and_never_settles_success(downloade assert result is None assert torrent_hash in message assert ("启动任务未确认" if failure == "start" else "保持暂停") in message - if failure != "start": + if failure == "missing_files": + # 暂停磁力无元数据时先启动一次取元数据;超时后恢复暂停,仍不记录成功。 + server.start_torrents.assert_called_once_with(torrent_hash) + assert server.stop_torrents.call_count == (2 if isinstance(module, TransmissionModule) else 1) + elif failure != "start": server.start_torrents.assert_not_called() else: assert server.stop_torrents.call_count == (2 if isinstance(module, TransmissionModule) else 1)