mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-02 00:46:27 +08:00
fix(subscribe): 手工末集号按实际集号裁剪缺集,整季记账只移除已下载的季
上一提交只在本季从第 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 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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` 验证下载一季后,其他季的显式缺集仍可在本轮提交。
|
||||
|
||||
整包优先也约束候选分批:已收集的整包即使排序低于分集、检查点恢复后缺少临时下载地址,
|
||||
也须先恢复地址并共同进入下载选择;多个整包不完整、下载失败或恢复后已不可用时才回退分集。
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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):
|
||||
"""
|
||||
整季下载失败后,即使剧集元数据变化也继续受到失败冷却约束。
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user