Merge pull request #7420 from CHANTXU64/ai/subscribe-trimmed-total-scope

This commit is contained in:
jxxghp
2026-11-15 07:04:29 +08:00
committed by GitHub
7 changed files with 232 additions and 60 deletions

View File

@@ -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

View File

@@ -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,52 +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, [],
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, [],
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,
@@ -188,6 +169,33 @@ 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, episode_end: int) -> list[int]:
"""
计算一季完全未入库时的缺集列表。
手工订阅末集号裁短本季,或恰好覆盖累计编号的整季时,写出目标范围。
范围内尚未确认的集号继续等待补集;超过本季已知末集号时沿用整季标记。
仅提供集数的调用继续在季初连续且两种口径一致时写出显式目标集。
:param episodes: 本季全部集号
: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]
if target[-1] != total:
return []
return target
@staticmethod
def _append_no_exists(
no_exists: Dict[str, Dict[int, NotExistMediaInfo]],

View File

@@ -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:

View File

@@ -246,6 +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`
覆盖媒体库无此剧和只有其他季两种情况,并验证单集、累计编号和断号资源只提交范围内可用的集。
断号缺失集继续等待补集。早于季首的历史集数设置保留原缺集语义,历史负数按未设置处理。
`tests/test_download_batch_phases.py` 验证下载一季后,其他季的显式缺集仍可在本轮提交。
整包优先也约束候选分批:已收集的整包即使排序低于分集、检查点恢复后缺少临时下载地址,
也须先恢复地址并共同进入下载选择;多个整包不完整、下载失败或恢复后已不可用时才回退分集。

View File

@@ -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,

View File

@@ -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):
"""
整季下载失败后,即使剧集元数据变化也继续受到失败冷却约束。

View File

@@ -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
@@ -124,6 +125,89 @@ 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(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_resolves_manual_total_with_irregular_episode_numbers(
scope, season_episodes, start, total, expected,
):
"""
手工末集号覆盖累计编号和断号;早于季首的历史集数配置不能被误判为已完成。
"""
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
@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):
"""
下载历史已覆盖目标范围时,应清空裁剪结果而不是返回更早的库内缺集。
@@ -232,3 +316,64 @@ 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(("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, episode_label, season_episodes, start, total, remaining_episodes,
):
"""
整季包优先与普通回退均只提交订阅范围内的文件,仍缺的集继续等待补集。
"""
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(f"Renegade Immortal {episode_label} 2023 2160p WEB-DL H265 AAC-UBWEB")
context = Context(
meta_info=meta,
media_info=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, season_episodes))
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=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]
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"] == set(season_episodes).intersection(
range(start, total + 1),
)