From b56af20366dd75a75df7649ed1a97a4ff22339c1 Mon Sep 17 00:00:00 2001 From: CHANTXU64 Date: Sat, 14 Nov 2026 23:26:55 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(subscribe):=20=E6=80=BB=E9=9B=86?= =?UTF-8?q?=E6=95=B0=E8=A3=81=E7=9F=AD=E6=97=B6=E6=95=B4=E5=AD=A3=E5=8C=85?= =?UTF-8?q?=E5=8F=AA=E4=B8=8B=E8=BD=BD=E8=AE=A2=E9=98=85=E8=8C=83=E5=9B=B4?= =?UTF-8?q?=E5=86=85=E7=9A=84=E5=89=A7=E9=9B=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 订阅只要本季前几集(如单集试看 start=1、total=1)且本季完全未入库时, 缺集仍用空列表表示缺整季。首次下载的整包优先因候选优先级为 0 被拒、 回退普通下载后,整季包不选集整包提交,例如只订第 1 集却下载 E01-E21。 - get_no_exists_info 在传入的总集数少于本季集数时写出显式目标集, 下载链据此走拆包选集;媒体库无此剧和只有其他季两条分支一致 - 总集数存在集数与末集号两种口径,仅在两者一致(本季从第 1 集起、 前段不断号)时写出目标集,否则保留整季标记,避免订阅被裁成空集而误判完成 - 总集数覆盖整季或大于本季集数时行为不变;插件传入较小 totals 时 返回值由空列表变为显式集数 - 补充缺集计算与从订阅下载入口到下载器选集的回归用例 Co-Authored-By: Claude Opus 5.5 --- app/chain/download/existence.py | 29 +++++++- docs/testing.md | 5 ++ tests/test_subscribe_missing_scope.py | 102 ++++++++++++++++++++++++++ 3 files changed, 134 insertions(+), 2 deletions(-) diff --git a/app/chain/download/existence.py b/app/chain/download/existence.py index bffb6e5c1..adc9e0488 100644 --- a/app/chain/download/existence.py +++ b/app/chain/download/existence.py @@ -118,7 +118,8 @@ class DownloadExistenceOwner(_DownloadOwnerBase): continue total_ep = totals.get(season) or len(episodes) self._append_no_exists( - no_exists, media_source, media_id, season, [], + no_exists, media_source, media_id, season, + self._whole_season_missing(episodes, total_ep), total_ep, min(episodes) ) return False, no_exists @@ -148,7 +149,8 @@ class DownloadExistenceOwner(_DownloadOwnerBase): ) else: self._append_no_exists( - no_exists, media_source, media_id, season, [], + no_exists, media_source, media_id, season, + self._whole_season_missing(episodes, season_total), season_total, min(episodes) ) if no_exists: @@ -188,6 +190,29 @@ class DownloadExistenceOwner(_DownloadOwnerBase): "seasons": {season: sorted(episodes) for season, episodes in seasons.items()}, }) if combined else None + @staticmethod + def _whole_season_missing(episodes: list[int], total: int) -> list[int]: + """ + 计算一季完全未入库时的缺集列表。 + + 下载链把空列表当作缺整季,整季包会不选集整包提交;传入的总集数少于本季集数时 + (如订阅只要第 1 集),必须写出目标集,下载链才会只选范围内的集。 + + 部分入库分支把总集数当作从本季最小集号起数的集数,订阅缺集裁剪却把它当作末集号。 + 只有按两种口径得到的目标集相同(本季从第 1 集起且前段不断号)时才写出目标集; + 口径不一致时保留空列表,避免订阅裁剪把显式集全部裁掉、误判为已完成。 + + :param episodes: 本季全部集号 + :param total: 本季有效总集数 + :return: 范围覆盖整季或口径不一致时为空列表,否则为显式目标集 + """ + if total >= len(episodes): + return [] + target = sorted(episodes)[:total] + if target[-1] != total: + return [] + return target + @staticmethod def _append_no_exists( no_exists: Dict[str, Dict[int, NotExistMediaInfo]], diff --git a/docs/testing.md b/docs/testing.md index 6d688d781..38f5c5b38 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -246,6 +246,11 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)): 或写入洗版优先级。测试覆盖显式缺集列表、后页整包、不完整包和搜索期间进度变化,均隔离外部服务。 完整覆盖目标来自订阅起止集;整包含范围外剧集时只选目标集提交,例如只订阅第 5 集时整季包也只下载 第 5 集,种子集数与目标一致时仍整包提交。下载层用例见 `tests/test_download_batch_phases.py`。 +整包未通过优先级门槛而回退普通下载时,同样不能下载订阅范围外的剧集:本季完全未入库、订阅总集数 +少于本季集数时,缺集计算写出显式目标集,不再用空列表表示缺整季。`tests/test_subscribe_missing_scope.py` +覆盖媒体库无此剧和只有其他季两种情况,并从订阅下载入口验证只订阅第 1 集时整季包只提交第 1 集。 +季内集号不从 1 开始或前段断号时,总集数按集数和按末集号理解会得到不同目标,此时保留整季标记, +用例断言订阅不会被裁成空集而误判完成。 整包优先也约束候选分批:已收集的整包即使排序低于分集、检查点恢复后缺少临时下载地址, 也须先恢复地址并共同进入下载选择;多个整包不完整、下载失败或恢复后已不可用时才回退分集。 diff --git a/tests/test_subscribe_missing_scope.py b/tests/test_subscribe_missing_scope.py index 965c7ec64..828da3818 100644 --- a/tests/test_subscribe_missing_scope.py +++ b/tests/test_subscribe_missing_scope.py @@ -124,6 +124,55 @@ def test_missing_scope_materializes_full_season_after_start_episode(scope): assert missing["tmdb:223911"][1].start_episode == 159 +@pytest.mark.parametrize("library", [None, ExistMediaInfo(seasons={2: [1]})]) +@pytest.mark.parametrize(("total", "expected"), [(1, [1]), (5, [1, 2, 3, 4, 5]), (200, [])]) +def test_missing_scope_materializes_full_season_before_total_episode(scope, library, total, expected): + """ + 整季未入库且总集数裁掉季末时,同样转成显式集数;总集数覆盖整季才保留整季标记。 + + 媒体库完全没有该剧,或只有其他季时,两条缺集分支口径一致。 + """ + scope.download._media_exists_with_server_cache.return_value = library + subscribe = replace(scope.subscribe, start_episode=1, total_episode=total, note=[]) + + satisfied, missing = scope.chain.resolve_subscribe_missing( + subscribe=subscribe, meta=MetaInfo("Renegade Immortal 2023"), mediainfo=scope.media, + ) + + assert not satisfied + info = missing["tmdb:223911"][1] + assert info.episodes == expected + assert info.start_episode == 1 + assert info.total_episode == total + + +@pytest.mark.parametrize(("season_episodes", "start", "total", "expected"), [ + (list(range(13, 25)), 13, 6, []), + (list(range(13, 25)), None, 6, []), + (list(range(13, 25)), 13, 18, []), + (list(range(1, 11)) + [12], 1, 11, []), + (list(range(1, 11)) + [12], 1, 8, list(range(1, 9))), +]) +def test_missing_scope_keeps_whole_season_when_total_semantics_disagree( + scope, season_episodes, start, total, expected, +): + """ + 总集数按集数和按末集号理解得到不同目标集时,保留整季标记,不能裁成空集而误判订阅已完成。 + + 季内集号不从 1 开始或前段断号时两种口径不一致;从第 1 集起且前段连续时仍写出目标集。 + """ + scope.download._media_exists_with_server_cache.return_value = None + media = replace(scope.media, seasons={1: season_episodes}) + subscribe = replace(scope.subscribe, start_episode=start, total_episode=total, note=[]) + + satisfied, missing = scope.chain.resolve_subscribe_missing( + subscribe=subscribe, meta=MetaInfo("Renegade Immortal 2023"), mediainfo=media, + ) + + assert not satisfied + assert missing["tmdb:223911"][1].episodes == expected + + def test_missing_scope_finishes_only_when_subscription_range_is_satisfied(scope): """ 下载历史已覆盖目标范围时,应清空裁剪结果而不是返回更早的库内缺集。 @@ -232,3 +281,56 @@ def test_policy_recheck_keeps_scope_through_batch_file_selection(scope, monkeypa download.download_single.assert_called_once() assert download.download_single.call_args.kwargs["episodes"] == set(range(161, 166)) assert set(remaining["tmdb:223911"][1].episodes) == set(range(166, 201)) + + +@pytest.mark.parametrize("title", [ + "Renegade Immortal S01 2023 2160p WEB-DL H265 AAC-UBWEB", + "Renegade Immortal E01-E200 2023 1080p HDTV x265 AC3", +]) +@pytest.mark.parametrize("pri_order", [0, 90]) +def test_trimmed_total_subscription_only_selects_target_from_season_pack(scope, monkeypatch, pri_order, title): + """ + 只订阅第 1 集时,整季包无论走首次整包优先还是回退的普通下载,都只向下载器提交第 1 集。 + + 优先级为 0 时整包优先被拒、回退普通下载;此前缺集仍是空列表,被当成缺整季而整包提交。 + 标题无集号和标注全季集号的整包都要覆盖。 + """ + subscribe = replace(scope.subscribe, start_episode=1, total_episode=1, note=[]) + scope.chain.subscription_repository.get.return_value = subscribe + meta = MetaInfo(title) + context = Context( + meta_info=meta, + media_info=scope.media, + torrent_info=TorrentInfo( + title=meta.org_string, site=1, site_name="TestSite", pri_order=pri_order, + ), + ) + download = scope.download + download._media_exists_with_server_cache.return_value = None + download.eventmanager = SimpleNamespace(send_event=Mock(return_value=None)) + download._active_download_failure_fingerprints = Mock(return_value={}) + download.download_torrent = Mock(return_value=(b"torrent", None, list(range(1, 201)))) + download.download_single = Mock(return_value="download-id") + helper = SimpleNamespace( + sort_torrents=lambda contexts: contexts, + get_torrent_episodes=lambda files, **_kwargs: files, + ) + stop = SimpleNamespace(is_system_stopped=False) + monkeypatch.setattr(download_batch, "_new_torrent_helper", lambda: helper) + monkeypatch.setattr(download_selection, "_new_torrent_helper", lambda: helper) + monkeypatch.setattr(download_batch, "runtime_stop_state", stop) + monkeypatch.setattr(download_selection, "runtime_stop_state", stop) + satisfied, prepared_missing = scope.chain.resolve_subscribe_missing( + subscribe=subscribe, meta=build_subscribe_meta(subscribe), mediainfo=scope.media, + ) + assert not satisfied + + downloads, remaining = scope.chain._SubscribeChain__download_best_version_with_full_pack_first( + contexts=[context], no_exists=prepared_missing, + subscribe=subscribe, mediakey="tmdb:223911", + ) + + assert downloads == [context] + assert remaining == {} + download.download_single.assert_called_once() + assert download.download_single.call_args.kwargs["episodes"] == {1} From 6f8a04abeb693ad3b74c4d1714d409876ef23c24 Mon Sep 17 00:00:00 2001 From: CHANTXU64 Date: Sun, 15 Nov 2026 00:36:50 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(subscribe):=20=E6=89=8B=E5=B7=A5?= =?UTF-8?q?=E6=9C=AB=E9=9B=86=E5=8F=B7=E6=8C=89=E5=AE=9E=E9=99=85=E9=9B=86?= =?UTF-8?q?=E5=8F=B7=E8=A3=81=E5=89=AA=E7=BC=BA=E9=9B=86=EF=BC=8C=E6=95=B4?= =?UTF-8?q?=E5=AD=A3=E8=AE=B0=E8=B4=A6=E5=8F=AA=E7=A7=BB=E9=99=A4=E5=B7=B2?= =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E7=9A=84=E5=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一提交只在本季从第 1 集起且前段不断号时写出目标集;断号季和累计编号季 仍按缺整季处理,例如订阅 E01–E11 时整包连范围外的 E12 一起提交, 订阅 E13–E18 时含 E13–E24 的整包又因文件数少于末集号被拒。 - 订阅总集数为手工指定时,get_no_exists_info 按季内末集号计算目标范围 (新增仅限关键字参数 totals_are_episode_numbers,默认行为不变), 覆盖累计编号与断号;范围内 TMDB 尚未列出的集继续等待补集 - update_no_exists_seasons 只移除本次成功下载的季,不再连带清掉 其他季的显式缺集 - 非正数总集数按未设置处理,避免空目标切片导致缺集查询中断 - 合并缺集计算的两条分支,get_no_exists_info 复杂度由 23 降到 17, 同步下调复杂度基线 Co-Authored-By: Claude Opus 5.5 --- app/application/download/selection.py | 17 ++-- app/chain/download/existence.py | 97 ++++++++----------- app/chain/subscribe/refresh.py | 9 +- docs/testing.md | 9 +- .../architecture/complexity-baseline.json | 2 +- tests/test_download_batch_phases.py | 15 +++ tests/test_subscribe_missing_scope.py | 85 ++++++++++++---- 7 files changed, 137 insertions(+), 97 deletions(-) diff --git a/app/application/download/selection.py b/app/application/download/selection.py index 6fdfc916a..b94ffb4c8 100644 --- a/app/application/download/selection.py +++ b/app/application/download/selection.py @@ -6,7 +6,6 @@ 规则只操作传入数据,不做网络/下载器 I/O;下载执行顺序编排仍属于链层。 """ -from copy import deepcopy from typing import Dict, List, Optional, Set from app.domain.context import Context @@ -23,17 +22,15 @@ def update_no_exists_seasons( """ 更新缺失字典中的季数记账,返回剩余需要下载的季数。 - 就地维护传入的 no_exists:已满足的季从记账中移除,媒体条目清空后整体删除。 + 就地移除本次成功下载的季,保留其他季的显式缺集;媒体条目清空后整体删除。 """ need = list(set(needed_seasons).difference(set(current_seasons))) - seas = deepcopy(no_exists.get(media_key)) - if seas: - for season in list(seas): - if season not in need: - no_exists[media_key].pop(season) - if not no_exists.get(media_key) and no_exists.get(media_key) is not None: - no_exists.pop(media_key) - break + seasons = no_exists.get(media_key) + if seasons: + for season in current_seasons: + seasons.pop(season, None) + if not seasons: + no_exists.pop(media_key) return need diff --git a/app/chain/download/existence.py b/app/chain/download/existence.py index adc9e0488..8002c277c 100644 --- a/app/chain/download/existence.py +++ b/app/chain/download/existence.py @@ -29,7 +29,9 @@ class DownloadExistenceOwner(_DownloadOwnerBase): def get_no_exists_info(self, meta: MetaBase, mediainfo: MediaInfo | MusicInfo, no_exists: Optional[Dict[str, Dict[int, NotExistMediaInfo]]] = None, - totals: Optional[Dict[int, int]] = None + totals: Optional[Dict[int, int]] = None, + *, + totals_are_episode_numbers: bool = False, ) -> Tuple[bool, Dict[str, Dict[int, NotExistMediaInfo]]]: """ 检查媒体库,查询电影或音乐是否存在;对于剧集同时返回不存在的季集信息 @@ -37,7 +39,8 @@ class DownloadExistenceOwner(_DownloadOwnerBase): :param meta: 元数据 :param mediainfo: 已识别的媒体信息,指定剧集组时重新识别对应的季集结构 :param no_exists: 在调用该方法前已经存储的不存在的季集信息,有传入时该函数搜索的内容将会叠加后输出 - :param totals: 电视剧每季的总集数 + :param totals: 电视剧每季的总集数;非正数视为未指定 + :param totals_are_episode_numbers: 指定的总集数为季内末集号;早于季首时沿用原有集数口径 :return: 当前媒体是否缺失,各标题总的季集和缺失的季集 """ media_source, media_id = resolve_media_identity(media=mediainfo) @@ -109,54 +112,30 @@ class DownloadExistenceOwner(_DownloadOwnerBase): "season": mediainfo.season, }, ) - if not exists_tvs: - for season, episodes in mediainfo.seasons.items(): - if not episodes: + existing_seasons = (exists_tvs.seasons or {}) if exists_tvs else {} + for season, episodes in mediainfo.seasons.items(): + if not episodes or (meta.sea and season not in meta.season_list): + continue + first = min(episodes) + total_override = max(totals.get(season) or 0, 0) + season_total = total_override or len(episodes) + episode_end = total_override if totals_are_episode_numbers and total_override >= first else 0 + exist_episodes = existing_seasons.get(season) + if exist_episodes: + episode_range = range(first, (episode_end or first + season_total - 1) + 1) + target_episodes = episode_range if total_override else episodes + lack_episodes = sorted(set(target_episodes).difference(exist_episodes)) + if not lack_episodes: continue - if meta.sea \ - and season not in meta.season_list: - continue - total_ep = totals.get(season) or len(episodes) - self._append_no_exists( - no_exists, media_source, media_id, season, - self._whole_season_missing(episodes, total_ep), - total_ep, min(episodes) - ) - return False, no_exists - else: - for season, episodes in mediainfo.seasons.items(): - if meta.sea \ - and season not in meta.season_list: - continue - if not episodes: - continue - season_total = totals.get(season) or len(episodes) - exist_episodes = (exists_tvs.seasons or {}).get(season) - if exist_episodes: - if totals.get(season): - # 按总集数计算缺失集(开始集为TMDB中的最小集) - lack_episodes = list(set(range(min(episodes), - season_total + min(episodes)) - ).difference(set(exist_episodes))) - else: - # 按TMDB集数计算缺失集 - lack_episodes = list(set(episodes).difference(set(exist_episodes))) - if not lack_episodes: - continue - self._append_no_exists( - no_exists, media_source, media_id, season, - lack_episodes, season_total, min(lack_episodes) - ) - else: - self._append_no_exists( - no_exists, media_source, media_id, season, - self._whole_season_missing(episodes, season_total), - season_total, min(episodes) - ) - if no_exists: + first = lack_episodes[0] + else: + lack_episodes = self._whole_season_missing(episodes, season_total, episode_end) + self._append_no_exists( + no_exists, media_source, media_id, season, lack_episodes, season_total, first, + ) + if exists_tvs and no_exists: logger.debug(f"媒体库中已存在部分剧集,缺失:{no_exists}") - return False, no_exists - return True, no_exists + return bool(exists_tvs) and not no_exists, no_exists def _media_exists_with_server_cache( self, @@ -191,21 +170,25 @@ class DownloadExistenceOwner(_DownloadOwnerBase): }) if combined else None @staticmethod - def _whole_season_missing(episodes: list[int], total: int) -> list[int]: + def _whole_season_missing(episodes: list[int], total: int, episode_end: int) -> list[int]: """ 计算一季完全未入库时的缺集列表。 - 下载链把空列表当作缺整季,整季包会不选集整包提交;传入的总集数少于本季集数时 - (如订阅只要第 1 集),必须写出目标集,下载链才会只选范围内的集。 - - 部分入库分支把总集数当作从本季最小集号起数的集数,订阅缺集裁剪却把它当作末集号。 - 只有按两种口径得到的目标集相同(本季从第 1 集起且前段不断号)时才写出目标集; - 口径不一致时保留空列表,避免订阅裁剪把显式集全部裁掉、误判为已完成。 + 手工订阅末集号裁短本季,或恰好覆盖累计编号的整季时,写出目标范围。 + 范围内尚未确认的集号继续等待补集;超过本季已知末集号时沿用整季标记。 + 仅提供集数的调用继续在季初连续且两种口径一致时写出显式目标集。 :param episodes: 本季全部集号 - :param total: 本季有效总集数 - :return: 范围覆盖整季或口径不一致时为空列表,否则为显式目标集 + :param total: 本季有效总集数,调用方已保证为正 + :param episode_end: 显式末集号;未指定或早于季首时为 0 + :return: 显式目标集;空列表表示按整季处理 """ + if episode_end: + first = min(episodes) + last = max(episodes) + if episode_end < last or (first != 1 and episode_end == last): + return list(range(first, episode_end + 1)) + return [] if total >= len(episodes): return [] target = sorted(episodes)[:total] diff --git a/app/chain/subscribe/refresh.py b/app/chain/subscribe/refresh.py index 21aa47055..c2058a049 100644 --- a/app/chain/subscribe/refresh.py +++ b/app/chain/subscribe/refresh.py @@ -355,7 +355,10 @@ class SubscribeRefreshOwner(SubscribeMetadataOwner): totals = {} if subscribe.season is not None and effective_total_episode: totals = {subscribe.season: effective_total_episode} - exist_flag, no_exists = DownloadChain().get_no_exists_info(meta=meta, mediainfo=mediainfo, totals=totals) + exist_flag, no_exists = DownloadChain().get_no_exists_info( + meta=meta, mediainfo=mediainfo, totals=totals, + totals_are_episode_numbers=bool(subscribe.manual_total_episode), + ) elif meta.type != MediaType.TV and self._SubscribeChain__is_best_version_complete(subscribe): return True, {} else: @@ -507,9 +510,9 @@ class SubscribeRefreshOwner(SubscribeMetadataOwner): 主流程会通过 ``__refresh_total_episode_before_completion`` 持久化增长后的总集数; 该查询接口只需要同样避免旧 total 造成误判,因此仅使用当前 mediainfo 中更大的 - 季集数作为临时目标范围。 + 季集数作为临时目标范围。历史负数总集数按未设置处理。 """ - current_total = subscribe.total_episode or 0 + current_total = max(subscribe.total_episode or 0, 0) if subscribe.type != MediaType.TV.value: return current_total if subscribe.manual_total_episode: diff --git a/docs/testing.md b/docs/testing.md index 38f5c5b38..467e8bb1f 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -246,11 +246,10 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)): 或写入洗版优先级。测试覆盖显式缺集列表、后页整包、不完整包和搜索期间进度变化,均隔离外部服务。 完整覆盖目标来自订阅起止集;整包含范围外剧集时只选目标集提交,例如只订阅第 5 集时整季包也只下载 第 5 集,种子集数与目标一致时仍整包提交。下载层用例见 `tests/test_download_batch_phases.py`。 -整包未通过优先级门槛而回退普通下载时,同样不能下载订阅范围外的剧集:本季完全未入库、订阅总集数 -少于本季集数时,缺集计算写出显式目标集,不再用空列表表示缺整季。`tests/test_subscribe_missing_scope.py` -覆盖媒体库无此剧和只有其他季两种情况,并从订阅下载入口验证只订阅第 1 集时整季包只提交第 1 集。 -季内集号不从 1 开始或前段断号时,总集数按集数和按末集号理解会得到不同目标,此时保留整季标记, -用例断言订阅不会被裁成空集而误判完成。 +整包未通过优先级门槛而回退普通下载时,按订阅范围拆包。`tests/test_subscribe_missing_scope.py` +覆盖媒体库无此剧和只有其他季两种情况,并验证单集、累计编号和断号资源只提交范围内可用的集。 +断号缺失集继续等待补集。早于季首的历史集数设置保留原缺集语义,历史负数按未设置处理。 +`tests/test_download_batch_phases.py` 验证下载一季后,其他季的显式缺集仍可在本轮提交。 整包优先也约束候选分批:已收集的整包即使排序低于分集、检查点恢复后缺少临时下载地址, 也须先恢复地址并共同进入下载选择;多个整包不完整、下载失败或恢复后已不可用时才回退分集。 diff --git a/tests/fixtures/architecture/complexity-baseline.json b/tests/fixtures/architecture/complexity-baseline.json index c6ce4a464..2d4160d69 100644 --- a/tests/fixtures/architecture/complexity-baseline.json +++ b/tests/fixtures/architecture/complexity-baseline.json @@ -40,7 +40,7 @@ "app/application/torrent/download.py:TorrentHelper.download_torrent": 22, "app/application/torrent/download.py:TorrentHelper.match_torrent": 16, "app/application/transfer/models.py:TransferPlanCheckpoint.__post_init__": 18, - "app/chain/download/existence.py:DownloadExistenceOwner.get_no_exists_info": 23, + "app/chain/download/existence.py:DownloadExistenceOwner.get_no_exists_info": 17, "app/chain/download/subtitle.py:DownloadSubtitleOwner._save_subtitle_response": 16, "app/chain/media/album.py:_album_context_with_resource": 20, "app/chain/message.py:MessageChain._download_attachments_to_data_urls": 18, diff --git a/tests/test_download_batch_phases.py b/tests/test_download_batch_phases.py index 010911d45..9d9ce26f6 100644 --- a/tests/test_download_batch_phases.py +++ b/tests/test_download_batch_phases.py @@ -175,6 +175,21 @@ def test_incomplete_season_becomes_labelled_candidate_after_file_inspection(batc batch.chain._record_download_failure.assert_not_called() +def test_whole_season_download_preserves_other_seasons_with_explicit_missing_episodes(batch): + """ + 整季下载成功只清除该季,其他季的缺集仍能在本轮获得提交。 + """ + whole = _context("show", season=2) + partial = _context("show", season=1, episodes=(1,)) + missing = {"tmdb:1": {1: _missing((1, 2)), 2: _missing(season=2)}} + + result, remaining = batch.chain.batch_download([whole, partial], missing) + + assert result == [whole, partial] + assert set(remaining["tmdb:1"]) == {1} + assert remaining["tmdb:1"][1].episodes == [2] + + def test_failed_season_submission_stays_in_cooldown_after_metadata_changes(batch): """ 整季下载失败后,即使剧集元数据变化也继续受到失败冷却约束。 diff --git a/tests/test_subscribe_missing_scope.py b/tests/test_subscribe_missing_scope.py index 828da3818..9efffdb30 100644 --- a/tests/test_subscribe_missing_scope.py +++ b/tests/test_subscribe_missing_scope.py @@ -14,6 +14,7 @@ import app.chain.subscribe.policy as subscribe_policy import app.chain.subscribe.refresh as subscribe_refresh from app.application.subscription.contract import SubscriptionSnapshot, build_subscribe_meta from app.chain.download import DownloadChain +from app.chain.search.scan import search_targets from app.chain.subscribe.facade import SubscribeChain from app.domain.context import Context, MediaInfo, TorrentInfo from app.domain.metainfo import MetaInfo @@ -149,17 +150,17 @@ def test_missing_scope_materializes_full_season_before_total_episode(scope, libr @pytest.mark.parametrize(("season_episodes", "start", "total", "expected"), [ (list(range(13, 25)), 13, 6, []), (list(range(13, 25)), None, 6, []), - (list(range(13, 25)), 13, 18, []), - (list(range(1, 11)) + [12], 1, 11, []), + (list(range(13, 25)), 13, 18, list(range(13, 19))), + (list(range(13, 25)), 13, 24, list(range(13, 25))), + (list(range(13, 25)), 13, 10000, []), + (list(range(1, 11)) + [12], 1, 11, list(range(1, 12))), (list(range(1, 11)) + [12], 1, 8, list(range(1, 9))), ]) -def test_missing_scope_keeps_whole_season_when_total_semantics_disagree( +def test_missing_scope_resolves_manual_total_with_irregular_episode_numbers( scope, season_episodes, start, total, expected, ): """ - 总集数按集数和按末集号理解得到不同目标集时,保留整季标记,不能裁成空集而误判订阅已完成。 - - 季内集号不从 1 开始或前段断号时两种口径不一致;从第 1 集起且前段连续时仍写出目标集。 + 手工末集号覆盖累计编号和断号;早于季首的历史集数配置不能被误判为已完成。 """ scope.download._media_exists_with_server_cache.return_value = None media = replace(scope.media, seasons={1: season_episodes}) @@ -173,6 +174,40 @@ def test_missing_scope_keeps_whole_season_when_total_semantics_disagree( assert missing["tmdb:223911"][1].episodes == expected +@pytest.mark.parametrize("library", [None, ExistMediaInfo(seasons={1: [1]})]) +def test_missing_scope_treats_legacy_negative_total_as_unset(scope, library): + """ + 历史负数总集数按未设置处理,一季无入库或部分入库时均保留实际缺集。 + """ + scope.download._media_exists_with_server_cache.return_value = library + media = replace(scope.media, seasons={1: [1, 2, 3]}) + subscribe = replace(scope.subscribe, start_episode=1, total_episode=-200, note=[]) + + satisfied, missing = scope.chain.resolve_subscribe_missing( + subscribe=subscribe, meta=build_subscribe_meta(subscribe), mediainfo=media, + ) + + assert not satisfied + info = missing["tmdb:223911"][1] + assert info.total_episode == 3 + assert info.episodes == ([2, 3] if library else []) + + +def test_missing_scope_applies_manual_end_to_partially_existing_cumulative_season(scope): + """ + 累计编号部分已入库时,E13 至 E18 全部存在即可满足订阅。 + """ + scope.download._media_exists_with_server_cache.return_value = ExistMediaInfo( + seasons={1: list(range(13, 19))}, + ) + media = replace(scope.media, seasons={1: list(range(13, 25))}) + subscribe = replace(scope.subscribe, start_episode=13, total_episode=18, note=[]) + + assert scope.chain.resolve_subscribe_missing( + subscribe=subscribe, meta=build_subscribe_meta(subscribe), mediainfo=media, + ) == (True, {}) + + def test_missing_scope_finishes_only_when_subscription_range_is_satisfied(scope): """ 下载历史已覆盖目标范围时,应清空裁剪结果而不是返回更早的库内缺集。 @@ -283,24 +318,26 @@ def test_policy_recheck_keeps_scope_through_batch_file_selection(scope, monkeypa assert set(remaining["tmdb:223911"][1].episodes) == set(range(166, 201)) -@pytest.mark.parametrize("title", [ - "Renegade Immortal S01 2023 2160p WEB-DL H265 AAC-UBWEB", - "Renegade Immortal E01-E200 2023 1080p HDTV x265 AC3", +@pytest.mark.parametrize(("episode_label", "season_episodes", "start", "total", "remaining_episodes"), [ + ("S01", list(range(1, 201)), 1, 1, []), + ("E01-E200", list(range(1, 201)), 1, 1, []), + ("S01", list(range(1, 11)) + [12], 1, 11, [11]), + ("S01", list(range(13, 25)), 13, 18, []), ]) @pytest.mark.parametrize("pri_order", [0, 90]) -def test_trimmed_total_subscription_only_selects_target_from_season_pack(scope, monkeypatch, pri_order, title): +def test_trimmed_total_subscription_only_selects_target_from_season_pack( + scope, monkeypatch, pri_order, episode_label, season_episodes, start, total, remaining_episodes, +): """ - 只订阅第 1 集时,整季包无论走首次整包优先还是回退的普通下载,都只向下载器提交第 1 集。 - - 优先级为 0 时整包优先被拒、回退普通下载;此前缺集仍是空列表,被当成缺整季而整包提交。 - 标题无集号和标注全季集号的整包都要覆盖。 + 整季包优先与普通回退均只提交订阅范围内的文件,仍缺的集继续等待补集。 """ - subscribe = replace(scope.subscribe, start_episode=1, total_episode=1, note=[]) + subscribe = replace(scope.subscribe, start_episode=start, total_episode=total, note=[]) + media = replace(scope.media, seasons={1: season_episodes}) scope.chain.subscription_repository.get.return_value = subscribe - meta = MetaInfo(title) + meta = MetaInfo(f"Renegade Immortal {episode_label} 2023 2160p WEB-DL H265 AAC-UBWEB") context = Context( meta_info=meta, - media_info=scope.media, + media_info=media, torrent_info=TorrentInfo( title=meta.org_string, site=1, site_name="TestSite", pri_order=pri_order, ), @@ -309,7 +346,7 @@ def test_trimmed_total_subscription_only_selects_target_from_season_pack(scope, download._media_exists_with_server_cache.return_value = None download.eventmanager = SimpleNamespace(send_event=Mock(return_value=None)) download._active_download_failure_fingerprints = Mock(return_value={}) - download.download_torrent = Mock(return_value=(b"torrent", None, list(range(1, 201)))) + download.download_torrent = Mock(return_value=(b"torrent", None, season_episodes)) download.download_single = Mock(return_value="download-id") helper = SimpleNamespace( sort_torrents=lambda contexts: contexts, @@ -321,16 +358,22 @@ def test_trimmed_total_subscription_only_selects_target_from_season_pack(scope, monkeypatch.setattr(download_batch, "runtime_stop_state", stop) monkeypatch.setattr(download_selection, "runtime_stop_state", stop) satisfied, prepared_missing = scope.chain.resolve_subscribe_missing( - subscribe=subscribe, meta=build_subscribe_meta(subscribe), mediainfo=scope.media, + subscribe=subscribe, meta=build_subscribe_meta(subscribe), mediainfo=media, ) assert not satisfied downloads, remaining = scope.chain._SubscribeChain__download_best_version_with_full_pack_first( contexts=[context], no_exists=prepared_missing, subscribe=subscribe, mediakey="tmdb:223911", + eligible_targets=search_targets(SimpleNamespace(mediainfo=media, no_exists=prepared_missing)), ) assert downloads == [context] - assert remaining == {} + if remaining_episodes: + assert remaining["tmdb:223911"][1].episodes == remaining_episodes + else: + assert remaining == {} download.download_single.assert_called_once() - assert download.download_single.call_args.kwargs["episodes"] == {1} + assert download.download_single.call_args.kwargs["episodes"] == set(season_episodes).intersection( + range(start, total + 1), + )