mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-02 00:46:27 +08:00
feat(download): convert manual downloads to TMDB primary identity (#7566)
Reuse cross-source TMDB projection and full recognition across manual download API and interactive messaging paths when RECOGNIZE_SOURCE=themoviedb, preserving TV season/episode/episode_group checks, external ID and origin_media traceability, warning fallback on mismatch, and post-ResourceDownload context sync.
This commit is contained in:
@@ -2,7 +2,6 @@
|
||||
提供下载任务查询、控制和手动添加接口,保留当前用户与媒体身份。
|
||||
"""
|
||||
|
||||
from copy import deepcopy
|
||||
from typing import Annotated, Any, List, Optional, Union
|
||||
|
||||
import anyio
|
||||
@@ -34,6 +33,7 @@ from app.application.site.query import (
|
||||
get_configured_site_query_service,
|
||||
)
|
||||
from app.chain.download import DownloadChain
|
||||
from app.chain.download.submission import convert_download_identity_to_tmdb
|
||||
from app.chain.media import MediaChain
|
||||
from app.domain.authorization import has_web_permission
|
||||
from app.domain.context import Context, MediaInfo, MusicInfo, SubtitleInfo, TorrentInfo
|
||||
@@ -41,6 +41,7 @@ from app.domain.media import is_music_media_source, normalize_music_type
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.schemas.common import JsonData
|
||||
from app.schemas.common import ServiceClientInfo as _SchemaServiceClientInfo
|
||||
from app.schemas.context import MediaInfo as _SchemaMediaInfo
|
||||
from app.schemas.context import SubtitleInfo as _SchemaSubtitleInfo
|
||||
@@ -173,58 +174,88 @@ def _resolve_converted_tmdb_media(
|
||||
metainfo: MetaBase,
|
||||
media_source: MediaSource,
|
||||
media_id: str,
|
||||
) -> tuple[MetaBase, MediaInfo] | None:
|
||||
*,
|
||||
source_media: Optional[MediaInfo] = None,
|
||||
) -> tuple[MetaBase, MediaInfo, dict[str, JsonData]] | None:
|
||||
"""
|
||||
尝试将非 TMDB 影视身份投影为 TMDB 主身份并识别,失败时不污染原元数据。
|
||||
复用统一下载身份转换规则,将非 TMDB 影视身份投影并核验为完整 TMDB 媒体信息。
|
||||
"""
|
||||
convert_identity = getattr(media_chain, "convert_media_identity", None)
|
||||
if not callable(convert_identity):
|
||||
return None
|
||||
# IMDb 外部标识可由 TMDB /find 直接区分电影与剧集,避免种子分类或电影标题误解析干扰;
|
||||
# 仅在剧集已解析出季号,或处理豆瓣等季级来源时传递季号。
|
||||
projected_season = (
|
||||
metainfo.begin_season
|
||||
if media_source != MediaSource.IMDb or metainfo.type == MediaType.TV
|
||||
else None
|
||||
return convert_download_identity_to_tmdb(
|
||||
media_chain,
|
||||
metainfo,
|
||||
media_source,
|
||||
media_id,
|
||||
source_media=source_media,
|
||||
)
|
||||
tmdbinfo = convert_identity(
|
||||
target_source=MediaSource.TMDB,
|
||||
|
||||
|
||||
def _convert_manual_download_media(
|
||||
metainfo: MetaBase,
|
||||
mediainfo: MediaInfo | MusicInfo,
|
||||
) -> tuple[MetaBase, MediaInfo | MusicInfo, Optional[dict[str, JsonData]]]:
|
||||
"""
|
||||
在全局识别源为 TMDB 时,将手动下载携带的非 TMDB 影视媒体对象转换为 TMDB 主身份。
|
||||
|
||||
仅对电影和电视剧生效;已有 TMDB 身份、音乐、非 TMDB 识别源以及无法可靠转换或核验的目标
|
||||
均保持原媒体与元数据对象不变。
|
||||
|
||||
:param metainfo: 种子标题解析出的元数据
|
||||
:param mediainfo: 请求传入的影视或音乐媒体对象
|
||||
:return: ``(最终元数据, 最终媒体对象, 原来源追溯字典)``;未转换时追溯字典为 None
|
||||
"""
|
||||
if (
|
||||
not isinstance(mediainfo, MediaInfo)
|
||||
or mediainfo.type not in (MediaType.MOVIE, MediaType.TV)
|
||||
or not _is_tmdb_recognize_source()
|
||||
):
|
||||
return metainfo, mediainfo, None
|
||||
source, media_id = resolve_media_identity(media=mediainfo)
|
||||
if not source or not media_id or source == MediaSource.TMDB:
|
||||
return metainfo, mediainfo, None
|
||||
converted = _resolve_converted_tmdb_media(
|
||||
MediaChain(),
|
||||
metainfo,
|
||||
source,
|
||||
media_id,
|
||||
source_media=mediainfo,
|
||||
)
|
||||
if converted is None:
|
||||
return metainfo, mediainfo, None
|
||||
return converted
|
||||
|
||||
|
||||
def _origin_media_for_converted_add(
|
||||
media_source: MediaSource | None,
|
||||
media_id: str | None,
|
||||
mediainfo: MediaInfo | MusicInfo,
|
||||
) -> Optional[dict[str, JsonData]]:
|
||||
"""
|
||||
判断无媒体信息下载是否发生了非 TMDB 到 TMDB 的主身份转换,并返回原来源追溯记录。
|
||||
|
||||
:param media_source: 请求提交的原媒体来源
|
||||
:param media_id: 请求提交的原来源原生标识
|
||||
:param mediainfo: 最终用于提交下载的媒体对象
|
||||
:return: 发生跨来源转换时返回 ``{"media_source": ..., "media_id": ...}``,否则返回 None
|
||||
"""
|
||||
if not isinstance(mediainfo, MediaInfo) or media_source is None or media_id is None:
|
||||
return None
|
||||
origin_source, origin_id = resolve_media_identity(
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
season=projected_season,
|
||||
)
|
||||
if not isinstance(tmdbinfo, dict):
|
||||
return None
|
||||
tmdb_id = tmdbinfo.get("id")
|
||||
if not tmdb_id or isinstance(tmdb_id, bool):
|
||||
return None
|
||||
raw_type = tmdbinfo.get("media_type")
|
||||
tmdb_mtype = (
|
||||
raw_type
|
||||
if isinstance(raw_type, MediaType)
|
||||
else MediaType.from_agent(str(raw_type or ""))
|
||||
)
|
||||
if tmdb_mtype not in (MediaType.MOVIE, MediaType.TV):
|
||||
tmdb_mtype = None
|
||||
candidate_meta = deepcopy(metainfo)
|
||||
projected_tv_season = tmdbinfo.get("season")
|
||||
final_source, final_id = resolve_media_identity(media=mediainfo)
|
||||
if (
|
||||
tmdb_mtype == MediaType.TV
|
||||
and candidate_meta.begin_season is None
|
||||
and isinstance(projected_tv_season, int)
|
||||
and not isinstance(projected_tv_season, bool)
|
||||
and projected_tv_season >= 0
|
||||
origin_source
|
||||
and origin_id
|
||||
and origin_source != MediaSource.TMDB
|
||||
and final_source == MediaSource.TMDB
|
||||
and final_id
|
||||
):
|
||||
candidate_meta.begin_season = projected_tv_season
|
||||
converted = media_chain.recognize_media(
|
||||
meta=candidate_meta,
|
||||
mtype=tmdb_mtype,
|
||||
media_source=MediaSource.TMDB,
|
||||
media_id=str(tmdb_id),
|
||||
)
|
||||
if not isinstance(converted, MediaInfo):
|
||||
return None
|
||||
return candidate_meta, converted
|
||||
return {
|
||||
"media_source": origin_source.value,
|
||||
"media_id": origin_id,
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_explicit_download_media(
|
||||
@@ -261,7 +292,8 @@ def _resolve_explicit_download_media(
|
||||
normalized_id,
|
||||
)
|
||||
if converted is not None:
|
||||
return converted
|
||||
converted_meta, converted_media, _origin_media = converted
|
||||
return converted_meta, converted_media
|
||||
mediainfo = media_chain.recognize_media(
|
||||
meta=metainfo,
|
||||
media_source=media_source,
|
||||
@@ -401,13 +433,19 @@ def download(
|
||||
mediainfo = MediaInfo()
|
||||
mediainfo.from_dict(media_in.model_dump())
|
||||
metainfo = MetaInfo(title=torrent_in.title or "", subtitle=torrent_in.description, mtype=mediainfo.type)
|
||||
metainfo, mediainfo, origin_media = _convert_manual_download_media(metainfo, mediainfo)
|
||||
# 种子信息
|
||||
torrentinfo = TorrentInfo()
|
||||
torrentinfo.from_dict(torrent_in.model_dump())
|
||||
# 手动下载始终使用选择的下载器
|
||||
torrentinfo.site_downloader = downloader
|
||||
# 上下文
|
||||
context = Context(meta_info=metainfo, media_info=mediainfo, torrent_info=torrentinfo)
|
||||
context = Context(
|
||||
meta_info=metainfo,
|
||||
media_info=mediainfo,
|
||||
torrent_info=torrentinfo,
|
||||
origin_media=origin_media,
|
||||
)
|
||||
did = DownloadChain().download_single(
|
||||
context=context,
|
||||
username=current_user.name,
|
||||
@@ -520,7 +558,12 @@ def add(
|
||||
torrentinfo = TorrentInfo()
|
||||
torrentinfo.from_dict(torrent_in.model_dump())
|
||||
# 上下文
|
||||
context = Context(meta_info=metainfo, media_info=mediainfo, torrent_info=torrentinfo)
|
||||
context = Context(
|
||||
meta_info=metainfo,
|
||||
media_info=mediainfo,
|
||||
torrent_info=torrentinfo,
|
||||
origin_media=_origin_media_for_converted_add(media_source, media_id, mediainfo),
|
||||
)
|
||||
|
||||
did = DownloadChain().download_single(
|
||||
context=context,
|
||||
|
||||
@@ -386,6 +386,7 @@ def _restore_context(payload: dict[str, Any]) -> Context:
|
||||
payload.get("media_recognize_fail_count") or 0
|
||||
),
|
||||
subscription_download=payload.get("subscription_download"),
|
||||
origin_media=payload.get("origin_media"),
|
||||
selected_episodes=payload.get("selected_episodes"),
|
||||
resource_source=str(payload.get("resource_source") or "unknown"),
|
||||
match_source=str(payload.get("match_source") or "unknown"),
|
||||
|
||||
@@ -139,6 +139,7 @@ class DownloadHistoryOwner(_DownloadOwnerBase):
|
||||
episode_group=media.episode_group,
|
||||
note={**self._build_download_note(source, media, meta),
|
||||
**({"subscription_download": context.subscription_download} if context.subscription_download else {}),
|
||||
**({"origin_media": context.origin_media} if getattr(context, "origin_media", None) else {}),
|
||||
torrent_rules.CONFIRMED_SELECTION_NOTE_KEY: self._confirmed_task_selection(
|
||||
previous_selection, downloader=downloader, accepted_files=accepted_files, episodes=episodes,
|
||||
custom_words=custom_words, context=context, task_action=task_action,
|
||||
|
||||
@@ -411,6 +411,7 @@ class DownloadPendingOwner(_DownloadOwnerBase):
|
||||
"userid": userid,
|
||||
"channel": channel.value if channel else None,
|
||||
"subscription_download": context.subscription_download,
|
||||
"origin_media": context.origin_media,
|
||||
"downloader_scope": self._download_scope(downloader, torrent),
|
||||
"user_specified": user_specified,
|
||||
"confirmed_full_coverage": bool(getattr(context, "confirmed_full_coverage", False)),
|
||||
@@ -865,6 +866,9 @@ class DownloadPendingOwner(_DownloadOwnerBase):
|
||||
raw_sub_download = payload.get("subscription_download")
|
||||
if isinstance(raw_sub_download, Mapping):
|
||||
context.subscription_download = _thaw_dict(raw_sub_download)
|
||||
raw_origin_media = payload.get("origin_media")
|
||||
if isinstance(raw_origin_media, Mapping):
|
||||
context.origin_media = _thaw_dict(raw_origin_media)
|
||||
raw_selected = payload.get("selected_episodes")
|
||||
if isinstance(raw_selected, (list, tuple)):
|
||||
context.selected_episodes = [
|
||||
|
||||
@@ -6,13 +6,17 @@ import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from copy import copy
|
||||
from collections.abc import Mapping, Sequence
|
||||
from copy import copy, deepcopy
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, Optional, Set, Tuple, Union, cast
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app.application.configuration import get_chain_runtime_config_snapshot
|
||||
from app.application.configuration import (
|
||||
get_chain_runtime_config_snapshot,
|
||||
get_runtime_settings,
|
||||
)
|
||||
from app.application.directory import (
|
||||
specified_download_save_path,
|
||||
validate_download_save_path,
|
||||
@@ -40,11 +44,13 @@ from app.domain.context import (
|
||||
TorrentInfo,
|
||||
)
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.foundation.url import UrlUtils, url_origin_for_log
|
||||
from app.runtime.cache import FileCache
|
||||
from app.runtime.events import eventmanager
|
||||
from app.runtime.locks import downloader_task_locks
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.common import JsonData
|
||||
from app.schemas.download import (
|
||||
DownloadTaskAction,
|
||||
ExistingTaskRejection,
|
||||
@@ -53,15 +59,428 @@ from app.schemas.download import (
|
||||
from app.schemas.event import ResourceDownloadEventData
|
||||
from app.schemas.exception import RateLimitExceededException
|
||||
from app.schemas.file import FileURI
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.schemas.media import normalize_media_source, resolve_media_identity
|
||||
from app.schemas.message import Message
|
||||
from app.schemas.types import (
|
||||
ChainEventType,
|
||||
MediaSource,
|
||||
MediaType,
|
||||
MessageType,
|
||||
NotificationChannel,
|
||||
)
|
||||
|
||||
# 转换后可无损回填到 TMDB 媒体对象的非主来源外链字段,保持主身份不变。
|
||||
_AUXILIARY_EXTERNAL_ID_FIELDS = (
|
||||
"douban_id",
|
||||
"bangumi_id",
|
||||
"anilist_id",
|
||||
"imdb_id",
|
||||
"tvdb_id",
|
||||
"tvdb_slug",
|
||||
)
|
||||
|
||||
|
||||
def is_tmdb_recognize_source() -> bool:
|
||||
"""
|
||||
判断当前系统影视识别源配置是否为 TMDB。
|
||||
|
||||
:return: 全局 RECOGNIZE_SOURCE 规范化为 TMDB 时返回 True,否则返回 False
|
||||
"""
|
||||
return normalize_media_source(get_runtime_settings().get("RECOGNIZE_SOURCE")) == MediaSource.TMDB
|
||||
|
||||
|
||||
def _valid_season_number(value: object) -> Optional[int]:
|
||||
"""
|
||||
提取有效的非负整数季号,排除布尔值和负数。
|
||||
|
||||
:param value: 来源或投影返回的原始季号字段
|
||||
:return: 合法季号(含第 0 季特别篇);无效时返回 None
|
||||
"""
|
||||
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def explicit_meta_seasons(meta: MetaBase) -> list[int]:
|
||||
"""
|
||||
从元数据提取显式解析出的季号列表,不把缺失季号的电视剧默认当成第 1 季。
|
||||
|
||||
``MetaVideo`` 在标题仅含集号(如 ``E01-E05``)且未标季时会回填 ``begin_season=1``
|
||||
但保持 ``total_season=0``;此类默认补齐不算显式季号,以便豆瓣或 Bangumi 季级条目
|
||||
能正确带入真实季号。
|
||||
|
||||
:param meta: 种子标题解析出的元数据
|
||||
:return: 按升序排列的显式季号列表;未解析出季号时返回空列表
|
||||
"""
|
||||
begin = _valid_season_number(meta.begin_season)
|
||||
if begin is None:
|
||||
return []
|
||||
end = _valid_season_number(meta.end_season)
|
||||
if end is not None and end >= begin:
|
||||
return list(range(begin, end + 1))
|
||||
if begin == 1 and getattr(meta, "total_season", 0) == 0:
|
||||
return []
|
||||
return [begin]
|
||||
|
||||
|
||||
def _extract_source_media_season(source_media: Optional[MediaInfo]) -> Optional[int]:
|
||||
"""
|
||||
从非 TMDB 媒体对象本身提取季号,兼容豆瓣和 Bangumi 等季级条目标题。
|
||||
|
||||
:param source_media: 转换前的原媒体对象
|
||||
:return: 提取到的季号;无法确定时返回 None
|
||||
"""
|
||||
if source_media is None:
|
||||
return None
|
||||
direct_season = _valid_season_number(source_media.season)
|
||||
if direct_season is not None:
|
||||
return direct_season
|
||||
if not source_media.title:
|
||||
return None
|
||||
return _valid_season_number(MetaInfo(source_media.title).begin_season)
|
||||
|
||||
|
||||
def _resolve_conversion_query_season(
|
||||
metainfo: MetaBase,
|
||||
media_source: MediaSource,
|
||||
source_media: Optional[MediaInfo],
|
||||
expected_mtype: Optional[MediaType],
|
||||
) -> Optional[int]:
|
||||
"""
|
||||
决定传给跨来源身份投影的查询季号,避免把电影或多季包误压成单季。
|
||||
|
||||
:param metainfo: 种子标题解析元数据
|
||||
:param media_source: 待转换的非 TMDB 媒体来源
|
||||
:param source_media: 已知的原媒体对象;无媒体上下文下载时为 None
|
||||
:param expected_mtype: 已确认的影视类型;未确定时为 None
|
||||
:return: 传给 ``convert_media_identity`` 的季号,未限定时返回 None
|
||||
"""
|
||||
if expected_mtype == MediaType.MOVIE:
|
||||
return None
|
||||
explicit_seasons = explicit_meta_seasons(metainfo)
|
||||
single_meta_season = explicit_seasons[0] if len(explicit_seasons) == 1 else None
|
||||
if source_media is not None:
|
||||
if single_meta_season is not None:
|
||||
return single_meta_season
|
||||
if not explicit_seasons:
|
||||
return _extract_source_media_season(source_media)
|
||||
return _valid_season_number(source_media.season)
|
||||
if media_source == MediaSource.IMDb:
|
||||
return single_meta_season if metainfo.type == MediaType.TV else None
|
||||
return single_meta_season
|
||||
|
||||
|
||||
def _parse_tmdb_media_type(raw_type: object) -> Optional[MediaType]:
|
||||
"""
|
||||
把投影返回的影视类型字段规范为电影或电视剧枚举。
|
||||
|
||||
:param raw_type: 投影结果中的 ``media_type`` 原始值
|
||||
:return: 电影或电视剧枚举;无法识别或非影视类型时返回 None
|
||||
"""
|
||||
parsed = (
|
||||
raw_type
|
||||
if isinstance(raw_type, MediaType)
|
||||
else MediaType.from_agent(str(raw_type or ""))
|
||||
)
|
||||
return parsed if parsed in (MediaType.MOVIE, MediaType.TV) else None
|
||||
|
||||
|
||||
def available_tmdb_seasons(
|
||||
converted: MediaInfo,
|
||||
tmdbinfo: Optional[Mapping[str, Any]] = None,
|
||||
) -> set[int]:
|
||||
"""
|
||||
收集 TMDB 识别结果中已列出的合法季号集合,用于校验目标季是否存在。
|
||||
|
||||
:param converted: TMDB 完整识别得到的媒体对象
|
||||
:param tmdbinfo: 投影步骤返回的原始 TMDB 字典,可为 None
|
||||
:return: 已确认存在的季号集合;结果未提供季清单时返回空集合
|
||||
"""
|
||||
seasons: set[int] = {
|
||||
season for season in (converted.seasons or {})
|
||||
if _valid_season_number(season) is not None
|
||||
}
|
||||
for item in converted.season_info or ():
|
||||
if isinstance(item, Mapping):
|
||||
season_num = _valid_season_number(item.get("season_number"))
|
||||
if season_num is not None:
|
||||
seasons.add(season_num)
|
||||
if seasons or not tmdbinfo:
|
||||
return seasons
|
||||
raw_seasons = tmdbinfo.get("seasons")
|
||||
if not isinstance(raw_seasons, Sequence) or isinstance(raw_seasons, (str, bytes)):
|
||||
return set()
|
||||
for item in raw_seasons:
|
||||
if isinstance(item, Mapping):
|
||||
season_num = _valid_season_number(item.get("season_number"))
|
||||
if season_num is not None:
|
||||
seasons.add(season_num)
|
||||
return seasons
|
||||
|
||||
|
||||
def _preserve_origin_media_fields(
|
||||
converted: MediaInfo,
|
||||
origin_source: MediaSource,
|
||||
origin_id: str,
|
||||
source_media: Optional[MediaInfo],
|
||||
) -> None:
|
||||
"""
|
||||
在转换后的 TMDB 媒体对象上回填缺失的原来源外链标识,保持 TMDB 主身份不变。
|
||||
|
||||
:param converted: 转换并识别完成的 TMDB 媒体对象
|
||||
:param origin_source: 转换前的原媒体来源
|
||||
:param origin_id: 转换前的原来源原生标识
|
||||
:param source_media: 转换前的原媒体对象,可为空
|
||||
"""
|
||||
source_field_map: dict[MediaSource, tuple[str, bool]] = {
|
||||
MediaSource.Douban: ("douban_id", False),
|
||||
MediaSource.Bangumi: ("bangumi_id", True),
|
||||
MediaSource.AniList: ("anilist_id", True),
|
||||
MediaSource.IMDb: ("imdb_id", False),
|
||||
MediaSource.TVDB: ("tvdb_id", True),
|
||||
}
|
||||
target = source_field_map.get(origin_source)
|
||||
if target is not None:
|
||||
field_name, is_numeric = target
|
||||
if not getattr(converted, field_name, None):
|
||||
if is_numeric:
|
||||
if origin_id.isdigit():
|
||||
setattr(converted, field_name, int(origin_id))
|
||||
else:
|
||||
setattr(converted, field_name, origin_id)
|
||||
if source_media is None:
|
||||
return
|
||||
for field_name in _AUXILIARY_EXTERNAL_ID_FIELDS:
|
||||
if not getattr(converted, field_name, None):
|
||||
value = getattr(source_media, field_name, None)
|
||||
if value:
|
||||
setattr(converted, field_name, value)
|
||||
|
||||
|
||||
def _validate_converted_tmdb_media(
|
||||
converted: object,
|
||||
*,
|
||||
expected_tmdb_id: str,
|
||||
expected_mtype: Optional[MediaType],
|
||||
episode_group: Optional[str],
|
||||
candidate_meta: MetaBase,
|
||||
tmdbinfo: Mapping[str, Any],
|
||||
origin_source: MediaSource,
|
||||
origin_id: str,
|
||||
) -> Optional[MediaInfo]:
|
||||
"""
|
||||
核验转换后的 TMDB 媒体对象与原目标在身份、类型、剧集组和电视剧季号上是否可靠一致。
|
||||
|
||||
:param converted: TMDB 完整识别返回的对象
|
||||
:param expected_tmdb_id: 投影给出的目标 TMDB ID
|
||||
:param expected_mtype: 原媒体确定的影视类型;未限定时为 None
|
||||
:param episode_group: 请求保留的剧集组标识;未指定时为 None
|
||||
:param candidate_meta: 已补齐缺失季号的候选元数据
|
||||
:param tmdbinfo: 投影步骤返回的原始 TMDB 字典
|
||||
:param origin_source: 原媒体来源,用于告警日志定位
|
||||
:param origin_id: 原来源原生标识,用于告警日志定位
|
||||
:return: 通过可靠性校验的 TMDB 媒体对象;任一条件不满足时返回 None
|
||||
"""
|
||||
if not isinstance(converted, MediaInfo):
|
||||
logger.warning(
|
||||
f"手动下载未能识别转换后的 TMDB {expected_tmdb_id},保留原身份 {origin_source.value}:{origin_id}"
|
||||
)
|
||||
return None
|
||||
converted_source, converted_id = resolve_media_identity(media=converted)
|
||||
if converted_source != MediaSource.TMDB or converted_id != expected_tmdb_id:
|
||||
logger.warning(
|
||||
f"手动下载识别结果与目标 TMDB {expected_tmdb_id} 不一致,保留原身份 {origin_source.value}:{origin_id}"
|
||||
)
|
||||
return None
|
||||
if expected_mtype is not None and converted.type != expected_mtype:
|
||||
logger.warning(
|
||||
f"手动下载转换后的 TMDB {expected_tmdb_id} 类型({converted.type})与原目标({expected_mtype})冲突,"
|
||||
f"保留原身份 {origin_source.value}:{origin_id}"
|
||||
)
|
||||
return None
|
||||
if converted.type == MediaType.TV:
|
||||
if episode_group and converted.episode_group != episode_group:
|
||||
logger.warning(
|
||||
f"手动下载转换后的 TMDB {expected_tmdb_id} 未能应用剧集组 {episode_group},"
|
||||
f"保留原身份 {origin_source.value}:{origin_id}"
|
||||
)
|
||||
return None
|
||||
requested_seasons = explicit_meta_seasons(candidate_meta)
|
||||
available_seasons = available_tmdb_seasons(converted, tmdbinfo)
|
||||
if available_seasons and requested_seasons:
|
||||
missing_seasons = [season for season in requested_seasons if season not in available_seasons]
|
||||
if missing_seasons:
|
||||
logger.warning(
|
||||
f"手动下载转换后的 TMDB {expected_tmdb_id} 季列表未包含目标季 {missing_seasons},"
|
||||
f"保留原身份 {origin_source.value}:{origin_id}"
|
||||
)
|
||||
return None
|
||||
return converted
|
||||
|
||||
|
||||
def _project_tmdb_payload(
|
||||
media_chain: Any,
|
||||
*,
|
||||
media_source: MediaSource,
|
||||
media_id: str,
|
||||
expected_mtype: Optional[MediaType],
|
||||
query_season: Optional[int],
|
||||
) -> Optional[tuple[Mapping[str, Any], str, Optional[MediaType]]]:
|
||||
"""
|
||||
调用共享跨来源投影获取 TMDB 标识与类型,失败或类型冲突时记录告警并返回 None。
|
||||
|
||||
:param media_chain: 提供 ``convert_media_identity`` 的媒体链对象
|
||||
:param media_source: 已规范化的非 TMDB 媒体来源
|
||||
:param media_id: 已规范化的来源原生标识
|
||||
:param expected_mtype: 已确认的影视类型;未限定时为 None
|
||||
:param query_season: 传给投影接口的电视剧季号;电影或未指定时为 None
|
||||
:return: ``(原始投影字典, TMDB ID, 最终识别类型)``;无法可靠投影时返回 None
|
||||
"""
|
||||
convert_identity = getattr(media_chain, "convert_media_identity", None)
|
||||
if not callable(convert_identity):
|
||||
return None
|
||||
convert_kwargs: dict[str, Any] = {
|
||||
"target_source": MediaSource.TMDB,
|
||||
"media_source": media_source,
|
||||
"media_id": media_id,
|
||||
"season": query_season,
|
||||
}
|
||||
if expected_mtype is not None:
|
||||
convert_kwargs["mtype"] = expected_mtype
|
||||
try:
|
||||
tmdbinfo = convert_identity(**convert_kwargs)
|
||||
except Exception as err:
|
||||
logger.warning(
|
||||
f"手动下载将 {media_source.value}:{media_id} 转换为 TMDB 主身份失败,保留原身份:{err}"
|
||||
)
|
||||
return None
|
||||
if not isinstance(tmdbinfo, dict):
|
||||
logger.warning(
|
||||
f"手动下载未能将 {media_source.value}:{media_id} 映射到 TMDB 主身份,保留原身份"
|
||||
)
|
||||
return None
|
||||
tmdb_id = tmdbinfo.get("id")
|
||||
if not tmdb_id or isinstance(tmdb_id, bool):
|
||||
logger.warning(
|
||||
f"手动下载转换 {media_source.value}:{media_id} 未返回有效 TMDB ID,保留原身份"
|
||||
)
|
||||
return None
|
||||
tmdb_mtype = _parse_tmdb_media_type(tmdbinfo.get("media_type"))
|
||||
if expected_mtype is not None and tmdb_mtype is not None and tmdb_mtype != expected_mtype:
|
||||
logger.warning(
|
||||
f"手动下载转换 {media_source.value}:{media_id} 类型冲突(原:{expected_mtype.value},"
|
||||
f"映射:{tmdb_mtype.value}),保留原身份"
|
||||
)
|
||||
return None
|
||||
return tmdbinfo, str(tmdb_id), expected_mtype or tmdb_mtype
|
||||
|
||||
|
||||
def convert_download_identity_to_tmdb(
|
||||
media_chain: Any,
|
||||
metainfo: MetaBase,
|
||||
media_source: MediaSource,
|
||||
media_id: str,
|
||||
*,
|
||||
source_media: Optional[MediaInfo] = None,
|
||||
mtype: Optional[MediaType] = None,
|
||||
episode_group: Optional[str] = None,
|
||||
) -> Optional[tuple[MetaBase, MediaInfo, dict[str, JsonData]]]:
|
||||
"""
|
||||
复用订阅同款跨来源映射将非 TMDB 影视下载目标转换为完整 TMDB 主身份。
|
||||
|
||||
转换仅在命中有效 TMDB 映射、二次完整识别成功且通过类型、电视剧季号与剧集组核验时生效;
|
||||
任一步骤失败均保持传入的 ``metainfo`` 与 ``source_media`` 不受污染并返回 None。
|
||||
成功时会保留种子自身解析的季号与选集,并在返回对象与来源追溯字典中保留原来源信息。
|
||||
|
||||
:param media_chain: 媒体链实例,需提供 ``convert_media_identity`` 与 ``recognize_media``
|
||||
:param metainfo: 种子标题解析出的元数据,转换失败时不会被修改
|
||||
:param media_source: 原媒体来源
|
||||
:param media_id: 原来源原生标识
|
||||
:param source_media: 已知的原媒体对象;无媒体上下文入口为 None
|
||||
:param mtype: 显式影视类型约束;省略时优先读取 ``source_media.type``
|
||||
:param episode_group: 显式剧集组标识;省略时回退到原媒体或元数据中的剧集组
|
||||
:return: ``(候选元数据, 完整 TMDB 媒体对象, 原来源追溯字典)``;不适用或不可靠时返回 None
|
||||
"""
|
||||
normalized_source, normalized_id = resolve_media_identity(
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
)
|
||||
if not normalized_source or not normalized_id or normalized_source == MediaSource.TMDB:
|
||||
return None
|
||||
expected_mtype = mtype or (
|
||||
source_media.type
|
||||
if source_media is not None and source_media.type in (MediaType.MOVIE, MediaType.TV)
|
||||
else None
|
||||
)
|
||||
if source_media is not None and expected_mtype not in (MediaType.MOVIE, MediaType.TV):
|
||||
return None
|
||||
effective_episode_group = (
|
||||
episode_group
|
||||
or (source_media.episode_group if source_media is not None else None)
|
||||
or getattr(metainfo, "episode_group", None)
|
||||
)
|
||||
query_season = _resolve_conversion_query_season(
|
||||
metainfo, normalized_source, source_media, expected_mtype,
|
||||
)
|
||||
projected = _project_tmdb_payload(
|
||||
media_chain,
|
||||
media_source=normalized_source,
|
||||
media_id=normalized_id,
|
||||
expected_mtype=expected_mtype,
|
||||
query_season=query_season,
|
||||
)
|
||||
if projected is None:
|
||||
return None
|
||||
tmdbinfo, tmdb_id, target_mtype = projected
|
||||
candidate_meta = deepcopy(metainfo)
|
||||
if target_mtype == MediaType.TV and not explicit_meta_seasons(candidate_meta):
|
||||
projected_season = _valid_season_number(tmdbinfo.get("season"))
|
||||
fallback_season = (
|
||||
projected_season
|
||||
if projected_season is not None
|
||||
else _extract_source_media_season(source_media)
|
||||
)
|
||||
if fallback_season is not None:
|
||||
candidate_meta.begin_season = fallback_season
|
||||
if getattr(candidate_meta, "total_season", 0) == 0:
|
||||
candidate_meta.total_season = 1
|
||||
recognize_kwargs: dict[str, Any] = {
|
||||
"meta": candidate_meta,
|
||||
"mtype": target_mtype,
|
||||
"media_source": MediaSource.TMDB,
|
||||
"media_id": tmdb_id,
|
||||
}
|
||||
if effective_episode_group:
|
||||
recognize_kwargs["episode_group"] = effective_episode_group
|
||||
try:
|
||||
raw_converted = media_chain.recognize_media(**recognize_kwargs)
|
||||
except Exception as err:
|
||||
logger.warning(
|
||||
f"手动下载识别转换后的 TMDB {tmdb_id} 失败,保留原身份 {normalized_source.value}:{normalized_id}:{err}"
|
||||
)
|
||||
return None
|
||||
converted = _validate_converted_tmdb_media(
|
||||
raw_converted,
|
||||
expected_tmdb_id=tmdb_id,
|
||||
expected_mtype=expected_mtype,
|
||||
episode_group=effective_episode_group,
|
||||
candidate_meta=candidate_meta,
|
||||
tmdbinfo=tmdbinfo,
|
||||
origin_source=normalized_source,
|
||||
origin_id=normalized_id,
|
||||
)
|
||||
if converted is None:
|
||||
return None
|
||||
_preserve_origin_media_fields(converted, normalized_source, normalized_id, source_media)
|
||||
origin_media: dict[str, JsonData] = {
|
||||
"media_source": normalized_source.value,
|
||||
"media_id": normalized_id,
|
||||
}
|
||||
logger.info(
|
||||
f"手动下载主身份已由 {normalized_source.value}:{normalized_id} 转换为 TMDB {tmdb_id}:{converted.title_year}"
|
||||
)
|
||||
return candidate_meta, converted, origin_media
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PreparedDownload:
|
||||
@@ -746,6 +1165,24 @@ class DownloadSubmissionOwner(_DownloadResourceOwner):
|
||||
delivered[key] = delivered.get(key, False) or Path(item.dest).is_file()
|
||||
return delivered
|
||||
|
||||
@staticmethod
|
||||
def _sync_context_after_download_event(
|
||||
context: Context,
|
||||
torrent: TorrentInfo,
|
||||
) -> Optional[tuple[TorrentInfo, Union[MediaInfo, MusicInfo], MetaBase]]:
|
||||
"""
|
||||
在 ``ResourceDownload`` 事件返回后重新读取上下文,保证插件替换后的媒体与元数据生效。
|
||||
|
||||
:param context: 已派发过 ``ResourceDownload`` 事件的下载上下文
|
||||
:param torrent: 事件派发前的种子对象,用作 ``context.torrent_info`` 未修改时的回退
|
||||
:return: 同步后的 ``(种子, 媒体, 元数据)``;上下文缺失有效媒体或元数据时返回 None
|
||||
"""
|
||||
media, meta = context.media_info, context.meta_info
|
||||
if not isinstance(media, (MediaInfo, MusicInfo)) or meta is None:
|
||||
return None
|
||||
updated_torrent = context.torrent_info if context.torrent_info is not None else torrent
|
||||
return updated_torrent, media, meta
|
||||
|
||||
def _prepare_download_single(
|
||||
self,
|
||||
*,
|
||||
@@ -766,7 +1203,6 @@ class DownloadSubmissionOwner(_DownloadResourceOwner):
|
||||
torrent, media, meta = context.torrent_info, context.media_info, context.meta_info
|
||||
if torrent is None or media is None or meta is None:
|
||||
return None, "下载上下文缺少媒体、元数据或种子信息"
|
||||
site_downloader = torrent.site_downloader
|
||||
supplemented_media = MediaChain().supplement_tmdb_info(media, meta)
|
||||
if not isinstance(supplemented_media, (MediaInfo, MusicInfo)):
|
||||
return None, "媒体信息补全失败"
|
||||
@@ -777,6 +1213,11 @@ class DownloadSubmissionOwner(_DownloadResourceOwner):
|
||||
)
|
||||
if event_error:
|
||||
return None, event_error
|
||||
synced = self._sync_context_after_download_event(context, torrent)
|
||||
if synced is None:
|
||||
return None, "下载上下文缺少媒体或元数据信息"
|
||||
torrent, media, meta = synced
|
||||
site_downloader = torrent.site_downloader
|
||||
download_episodes = episode_rules.format_ranges(list(episodes)) if episodes else None
|
||||
if episodes is not None:
|
||||
context.selected_episodes = sorted(set(episodes))
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from copy import copy, deepcopy
|
||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
||||
|
||||
from app.application.directory import DirectoryHelper
|
||||
@@ -15,6 +16,12 @@ from app.application.messaging.media import (
|
||||
from app.application.torrent.download import TorrentHelper
|
||||
from app.chain.base import ChainBase
|
||||
from app.chain.download import DownloadChain
|
||||
from app.chain.download.submission import (
|
||||
available_tmdb_seasons,
|
||||
convert_download_identity_to_tmdb,
|
||||
explicit_meta_seasons,
|
||||
is_tmdb_recognize_source,
|
||||
)
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.music_interaction.music import (
|
||||
format_music_candidate,
|
||||
@@ -39,7 +46,7 @@ from app.schemas.mediaserver import NotExistMediaInfo
|
||||
from app.schemas.message import Message
|
||||
from app.schemas.notification import ChannelCapabilityManager
|
||||
from app.schemas.system import TransferDirectoryConf
|
||||
from app.schemas.types import MediaType, NotificationChannel
|
||||
from app.schemas.types import MediaSource, MediaType, NotificationChannel
|
||||
|
||||
|
||||
class MediaInteractionChain(ChainBase):
|
||||
@@ -871,7 +878,7 @@ class MediaInteractionChain(ChainBase):
|
||||
)
|
||||
return
|
||||
|
||||
context: Context = page_items[page_index - 1]
|
||||
context: Context = self._prepare_manual_download_context(page_items[page_index - 1])
|
||||
if self._prompt_download_dir_selection(
|
||||
request=request,
|
||||
download_mode="single",
|
||||
@@ -892,6 +899,43 @@ class MediaInteractionChain(ChainBase):
|
||||
user_specified=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _prepare_manual_download_context(context: Context) -> Context:
|
||||
"""
|
||||
在全局识别源为 TMDB 时,把交互选中的非 TMDB 影视下载上下文转换为 TMDB 主身份。
|
||||
|
||||
未触发转换或转换不可靠时直接返回原上下文对象,不修改搜索缓存列表中的原项。
|
||||
|
||||
:param context: 用户在消息交互中选中的单个资源上下文
|
||||
:return: 转换后的浅拷贝上下文,或无需转换时的原上下文
|
||||
"""
|
||||
media, meta = context.media_info, context.meta_info
|
||||
if (
|
||||
not isinstance(media, MediaInfo)
|
||||
or meta is None
|
||||
or media.type not in (MediaType.MOVIE, MediaType.TV)
|
||||
or not is_tmdb_recognize_source()
|
||||
):
|
||||
return context
|
||||
source, media_id = resolve_media_identity(media=media)
|
||||
if not source or not media_id or source == MediaSource.TMDB:
|
||||
return context
|
||||
converted = convert_download_identity_to_tmdb(
|
||||
MediaChain(),
|
||||
meta,
|
||||
source,
|
||||
media_id,
|
||||
source_media=media,
|
||||
)
|
||||
if converted is None:
|
||||
return context
|
||||
converted_meta, converted_media, origin_media = converted
|
||||
updated = copy(context)
|
||||
updated.meta_info = converted_meta
|
||||
updated.media_info = converted_media
|
||||
updated.origin_media = origin_media
|
||||
return updated
|
||||
|
||||
def _prompt_download_dir_selection(
|
||||
self,
|
||||
request: PendingMediaInteraction,
|
||||
@@ -1083,6 +1127,123 @@ class MediaInteractionChain(ChainBase):
|
||||
request.pending_no_exists = None
|
||||
request.pending_torrent_page = 0
|
||||
|
||||
@staticmethod
|
||||
def _batch_seasons_supported(
|
||||
converted_media: MediaInfo,
|
||||
matching_contexts: List[Context],
|
||||
no_exists: Optional[Dict[Union[int, str], Dict[int, NotExistMediaInfo]]],
|
||||
old_key: str,
|
||||
) -> bool:
|
||||
"""
|
||||
核验批量自动下载涉及的缺集季号和候选显式季号是否均存在于转换后的 TMDB 剧集中。
|
||||
|
||||
:param converted_media: 转换得到的 TMDB 媒体对象
|
||||
:param matching_contexts: 绑定了原非 TMDB 身份的候选上下文
|
||||
:param no_exists: 调用方已计算的缺集映射,可为空
|
||||
:param old_key: 原非 TMDB 身份对应的媒体键
|
||||
:return: 所有目标季均受支持或无需校验时返回 True,存在缺失季时返回 False
|
||||
"""
|
||||
if converted_media.type != MediaType.TV:
|
||||
return True
|
||||
available = available_tmdb_seasons(converted_media)
|
||||
if not available:
|
||||
return True
|
||||
if no_exists and old_key in no_exists:
|
||||
if any(season not in available for season in no_exists[old_key]):
|
||||
return False
|
||||
for item in matching_contexts:
|
||||
item_meta = item.meta_info
|
||||
if item_meta is None:
|
||||
continue
|
||||
if any(season not in available for season in explicit_meta_seasons(item_meta)):
|
||||
return False
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def _prepare_auto_download_batch(
|
||||
cls,
|
||||
current_media: MediaInfo | MusicInfo,
|
||||
meta: MetaBase,
|
||||
cache_list: List[Context],
|
||||
no_exists: Optional[Dict[Union[int, str], Dict[int, NotExistMediaInfo]]],
|
||||
) -> Tuple[
|
||||
MediaInfo | MusicInfo,
|
||||
MetaBase,
|
||||
List[Context],
|
||||
Optional[Dict[Union[int, str], Dict[int, NotExistMediaInfo]]],
|
||||
]:
|
||||
"""
|
||||
在自动择优下载前同步转换目标媒体、候选列表和缺集映射的 TMDB 主身份。
|
||||
|
||||
批内目标键、待确认防重键和补建订阅共享同一身份;任一季号核验失败时整批回退原身份。
|
||||
|
||||
:param current_media: 当前交互选中的媒体目标
|
||||
:param meta: 本次搜索请求元数据
|
||||
:param cache_list: 待提交的候选资源上下文列表
|
||||
:param no_exists: 已计算的缺集映射,可为 None
|
||||
:return: 转换或回退后的 ``(目标媒体, 元数据, 候选列表, 缺集映射)``
|
||||
"""
|
||||
if (
|
||||
not isinstance(current_media, MediaInfo)
|
||||
or current_media.type not in (MediaType.MOVIE, MediaType.TV)
|
||||
or not is_tmdb_recognize_source()
|
||||
):
|
||||
return current_media, meta, cache_list, no_exists
|
||||
source, media_id = resolve_media_identity(media=current_media)
|
||||
if not source or not media_id or source == MediaSource.TMDB:
|
||||
return current_media, meta, cache_list, no_exists
|
||||
converted = convert_download_identity_to_tmdb(
|
||||
MediaChain(),
|
||||
meta,
|
||||
source,
|
||||
media_id,
|
||||
source_media=current_media,
|
||||
)
|
||||
if converted is None:
|
||||
return current_media, meta, cache_list, no_exists
|
||||
converted_meta, converted_media, origin_media = converted
|
||||
old_key = build_media_key(source, media_id)
|
||||
new_key = build_media_key(MediaSource.TMDB, converted_media.media_id)
|
||||
matching_contexts = [
|
||||
item for item in cache_list
|
||||
if resolve_media_identity(media=item.media_info) == (source, media_id)
|
||||
]
|
||||
if not new_key or not cls._batch_seasons_supported(converted_media, matching_contexts, no_exists, old_key):
|
||||
logger.warning(
|
||||
f"交互自动下载转换后的 TMDB {converted_media.media_id} 季信息与候选或缺集不兼容,"
|
||||
f"保留原身份 {source.value}:{media_id}"
|
||||
)
|
||||
return current_media, meta, cache_list, no_exists
|
||||
converted_seasons = explicit_meta_seasons(converted_meta)
|
||||
fill_season = converted_seasons[0] if len(converted_seasons) == 1 else None
|
||||
remapped_contexts: List[Context] = []
|
||||
for item in cache_list:
|
||||
if resolve_media_identity(media=item.media_info) != (source, media_id):
|
||||
remapped_contexts.append(item)
|
||||
continue
|
||||
updated_item = copy(item)
|
||||
updated_item.media_info = converted_media
|
||||
updated_item.origin_media = origin_media
|
||||
if (
|
||||
converted_media.type == MediaType.TV
|
||||
and updated_item.meta_info is not None
|
||||
and fill_season is not None
|
||||
and not explicit_meta_seasons(updated_item.meta_info)
|
||||
):
|
||||
updated_meta = deepcopy(updated_item.meta_info)
|
||||
updated_meta.begin_season = fill_season
|
||||
if getattr(updated_meta, "total_season", 0) == 0:
|
||||
updated_meta.total_season = 1
|
||||
updated_item.meta_info = updated_meta
|
||||
remapped_contexts.append(updated_item)
|
||||
remapped_no_exists = no_exists
|
||||
if no_exists is not None and old_key in no_exists:
|
||||
remapped_no_exists = {
|
||||
(new_key if key == old_key else key): value
|
||||
for key, value in no_exists.items()
|
||||
}
|
||||
return converted_media, converted_meta, remapped_contexts, remapped_no_exists
|
||||
|
||||
def _auto_download(
|
||||
self,
|
||||
request: PendingMediaInteraction,
|
||||
@@ -1110,6 +1271,12 @@ class MediaInteractionChain(ChainBase):
|
||||
title="下载交互信息已失效,请重新搜索媒体",
|
||||
)
|
||||
return
|
||||
current_media, meta, cache_list, no_exists = self._prepare_auto_download_batch(
|
||||
current_media,
|
||||
meta,
|
||||
cache_list,
|
||||
no_exists,
|
||||
)
|
||||
downloadchain = DownloadChain()
|
||||
if no_exists is None:
|
||||
exist_flag, no_exists = downloadchain.get_no_exists_info(
|
||||
|
||||
@@ -2420,6 +2420,7 @@ class Context:
|
||||
:param confirmed_full_coverage: 下载层确认候选资源覆盖完整目标范围,供订阅事实写入判断整包资源
|
||||
:param subscription_download: 本次订阅提交的类型、全集洗版模式及新增和升级集数;非订阅下载为 None
|
||||
:param music_track_keys: 下载层从种子文件清单提取的稳定音轨键,供专辑订阅跨轮次累计下载进度
|
||||
:param origin_media: 主身份转换为 TMDB 前保留的原媒体来源与原生标识,用于下载历史追溯;未转换时为 None
|
||||
"""
|
||||
|
||||
meta_info: Optional[MetaBase] = None
|
||||
@@ -2437,6 +2438,7 @@ class Context:
|
||||
confirmed_full_coverage: bool = False
|
||||
music_track_keys: Optional[List[str]] = None
|
||||
subscription_download: Optional[Dict[str, JsonData]] = None
|
||||
origin_media: Optional[Dict[str, JsonData]] = None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -2459,4 +2461,5 @@ class Context:
|
||||
"confirmed_full_coverage": self.confirmed_full_coverage,
|
||||
"music_track_keys": self.music_track_keys,
|
||||
"subscription_download": self.subscription_download,
|
||||
"origin_media": self.origin_media,
|
||||
}
|
||||
|
||||
@@ -458,6 +458,7 @@ class Context(BaseModel):
|
||||
match_reason: Optional[str] = Field(default=None, description="资源匹配或未匹配的原因")
|
||||
confirmed_full_coverage: Optional[bool] = Field(default=False, description="下载层确认候选资源覆盖完整目标范围,供订阅事实写入判断整包资源")
|
||||
subscription_download: Optional[Dict[str, JsonData]] = Field(default=None, description="本次订阅提交类型、全集洗版模式及新增和升级集数;旧记录或非订阅下载为空")
|
||||
origin_media: Optional[Dict[str, JsonData]] = Field(default=None, description="主身份转换为 TMDB 前保留的原媒体来源与原生标识;未转换时为空")
|
||||
music_track_keys: Optional[List[str]] = Field(default=None, description="下载层从种子文件清单提取的稳定音轨键,供专辑订阅跨轮次累计下载进度")
|
||||
|
||||
|
||||
|
||||
@@ -851,7 +851,7 @@ flowchart LR
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1199 |
|
||||
| 内部导入边 | 10,594 |
|
||||
| 内部导入边 | 10,598 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) |
|
||||
|
||||
@@ -978,8 +978,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10594,
|
||||
"edge_sha256": "b2ea0244a1a2d0a0e8aeb1aee7a143d5cb54f4ea0e234e49a4fb431acab4a807",
|
||||
"edge_count": 10598,
|
||||
"edge_sha256": "993e3c59261342f22092792ee5c363c7f76552106841d3f3b26ce2f9239e4ad0",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -2693,6 +2693,7 @@
|
||||
"app.api.endpoints.download -> app.application.site.query",
|
||||
"app.api.endpoints.download -> app.chain",
|
||||
"app.api.endpoints.download -> app.chain.download",
|
||||
"app.api.endpoints.download -> app.chain.download.submission",
|
||||
"app.api.endpoints.download -> app.chain.media",
|
||||
"app.api.endpoints.download -> app.domain",
|
||||
"app.api.endpoints.download -> app.domain.authorization",
|
||||
@@ -5137,6 +5138,7 @@
|
||||
"app.chain.download.submission -> app.domain.episode",
|
||||
"app.chain.download.submission -> app.domain.meta",
|
||||
"app.chain.download.submission -> app.domain.meta.metabase",
|
||||
"app.chain.download.submission -> app.domain.metainfo",
|
||||
"app.chain.download.submission -> app.domain.torrent",
|
||||
"app.chain.download.submission -> app.foundation",
|
||||
"app.chain.download.submission -> app.foundation.url",
|
||||
@@ -5146,6 +5148,7 @@
|
||||
"app.chain.download.submission -> app.runtime.locks",
|
||||
"app.chain.download.submission -> app.runtime.log",
|
||||
"app.chain.download.submission -> app.schemas",
|
||||
"app.chain.download.submission -> app.schemas.common",
|
||||
"app.chain.download.submission -> app.schemas.download",
|
||||
"app.chain.download.submission -> app.schemas.event",
|
||||
"app.chain.download.submission -> app.schemas.exception",
|
||||
@@ -5201,6 +5204,7 @@
|
||||
"app.chain.interaction -> app.chain",
|
||||
"app.chain.interaction -> app.chain.base",
|
||||
"app.chain.interaction -> app.chain.download",
|
||||
"app.chain.interaction -> app.chain.download.submission",
|
||||
"app.chain.interaction -> app.chain.media",
|
||||
"app.chain.interaction -> app.chain.music_interaction",
|
||||
"app.chain.interaction -> app.chain.music_interaction.music",
|
||||
|
||||
@@ -2107,3 +2107,146 @@ def test_settle_accepted_download_records_actual_path_for_existing_torrent():
|
||||
assert history.path == "/volume4/flow/The.Ordinary.Jackpot.S01E01.1080p.mkv"
|
||||
assert files[0].fullpath == "/volume4/flow/The.Ordinary.Jackpot.S01E01.1080p.mkv"
|
||||
assert files[0].savepath == "/volume4/flow"
|
||||
|
||||
|
||||
def test_prepare_download_single_syncs_context_media_and_meta_after_resource_download_event(
|
||||
monkeypatch,
|
||||
):
|
||||
"""
|
||||
ResourceDownload 事件处理器替换 context.media_info 和 context.meta_info 后,下载目录与准备事实应同步生效。
|
||||
"""
|
||||
chain = DownloadChain.__new__(DownloadChain)
|
||||
resolved_dir_medias = []
|
||||
converted_media = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 1483525,
|
||||
"media_type": MediaType.MOVIE,
|
||||
"title": "可能的爱",
|
||||
"release_date": "2026-01-01",
|
||||
}
|
||||
)
|
||||
converted_media.set_library_category("外语电影")
|
||||
updated_meta = MetaInfo("Possible.Love.2026.S01E02.1080p")
|
||||
|
||||
def replace_context_media(_event_type, event_data):
|
||||
"""
|
||||
模拟插件在 ResourceDownload 同步事件中替换上下文媒体与元数据对象。
|
||||
"""
|
||||
event_data.context.media_info = converted_media
|
||||
event_data.context.meta_info = updated_meta
|
||||
return SimpleNamespace(event_data=event_data)
|
||||
|
||||
def resolve_dir(media_info, save_path=None):
|
||||
"""
|
||||
记录目录解析实际使用的媒体对象并返回固定下载目录。
|
||||
"""
|
||||
resolved_dir_medias.append((media_info, save_path))
|
||||
return "local", Path("/downloads/movies"), None
|
||||
|
||||
monkeypatch.setattr(eventmanager, "send_event", replace_context_media)
|
||||
monkeypatch.setattr(download_submission, "TorrentHelper", _FakeTorrentHelper)
|
||||
monkeypatch.setattr(chain, "_resolve_media_download_dir", resolve_dir)
|
||||
|
||||
context = Context(
|
||||
meta_info=MetaInfo("Possible.Love.2026.1080p"),
|
||||
media_info=MediaInfo(
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="36847425",
|
||||
type=MediaType.MOVIE,
|
||||
title="可能的爱",
|
||||
),
|
||||
torrent_info=TorrentInfo(title="Possible.Love.2026.1080p"),
|
||||
)
|
||||
|
||||
prepared, error_msg = chain._prepare_download_single(
|
||||
context=context,
|
||||
torrent_file=None,
|
||||
torrent_content="magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567",
|
||||
episodes=None,
|
||||
channel=None,
|
||||
source="Manual",
|
||||
downloader=None,
|
||||
save_path=None,
|
||||
userid=None,
|
||||
username="tester",
|
||||
)
|
||||
|
||||
assert error_msg is None
|
||||
assert prepared is not None
|
||||
assert resolved_dir_medias == [(converted_media, None)]
|
||||
assert prepared.media is converted_media
|
||||
assert prepared.meta is updated_meta
|
||||
assert context.selected_episodes == [2]
|
||||
|
||||
|
||||
def test_settle_download_success_persists_origin_media_trace_and_snapshot_roundtrip():
|
||||
"""
|
||||
发生跨来源主身份转换的下载应在 DownloadHistory.note 和持久处理快照中保留 origin_media。
|
||||
"""
|
||||
from app.application.chain.events import (
|
||||
restore_download_processing,
|
||||
snapshot_download_processing,
|
||||
)
|
||||
|
||||
chain = DownloadChain.__new__(DownloadChain)
|
||||
chain.runtime_config = SimpleNamespace(media_extensions=(".mkv",), video_extensions=(".mkv",))
|
||||
chain.durable_event_writer = None
|
||||
chain.download_history_repository = MagicMock()
|
||||
chain._build_download_notification = MagicMock(return_value=None)
|
||||
chain._submit_download_added_task = MagicMock()
|
||||
chain.eventmanager = MagicMock()
|
||||
|
||||
media = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 1483525,
|
||||
"media_type": MediaType.MOVIE,
|
||||
"title": "可能的爱",
|
||||
"release_date": "2026-01-01",
|
||||
}
|
||||
)
|
||||
media.douban_id = "36847425"
|
||||
meta = MetaInfo("Possible.Love.2026.1080p")
|
||||
torrent = TorrentInfo(title="Possible.Love.2026.1080p")
|
||||
origin_media = {"media_source": "douban", "media_id": "36847425"}
|
||||
context = Context(
|
||||
meta_info=meta,
|
||||
media_info=media,
|
||||
torrent_info=torrent,
|
||||
origin_media=origin_media,
|
||||
)
|
||||
|
||||
chain._settle_download_success(
|
||||
context=context,
|
||||
media=media,
|
||||
meta=meta,
|
||||
torrent=torrent,
|
||||
folder_name="Possible.Love.2026",
|
||||
file_list=["Possible.Love.2026.mkv"],
|
||||
download_dir=Path("/downloads/movies"),
|
||||
layout="Original",
|
||||
downloader="qb",
|
||||
download_hash="hash-origin-1",
|
||||
download_episodes=None,
|
||||
episodes=None,
|
||||
channel=None,
|
||||
source="Manual",
|
||||
userid=None,
|
||||
username="tester",
|
||||
torrent_content=b"torrent",
|
||||
custom_words=None,
|
||||
)
|
||||
|
||||
history, _files = chain.download_history_repository.add.call_args.args
|
||||
assert history.media_source == MediaSource.TMDB
|
||||
assert history.media_id == "1483525"
|
||||
assert history.note["origin_media"] == origin_media
|
||||
|
||||
payload = snapshot_download_processing(
|
||||
context=context,
|
||||
download_dir=Path("/downloads/movies"),
|
||||
torrent_content=b"torrent",
|
||||
download_hash="hash-origin-1",
|
||||
downloader="qb",
|
||||
)
|
||||
restored = restore_download_processing(payload)
|
||||
assert restored.context.origin_media == origin_media
|
||||
|
||||
@@ -550,3 +550,341 @@ def test_download_add_skips_conversion_when_source_is_already_tmdb(monkeypatch)
|
||||
media_chain.convert_media_identity.assert_not_called()
|
||||
assert media_chain.recognize_media.call_args.kwargs["media_source"] == MediaSource.TMDB
|
||||
assert media_chain.recognize_media.call_args.kwargs["media_id"] == "1101383"
|
||||
assert download_chain.download_single.call_args.kwargs["context"].origin_media is None
|
||||
|
||||
|
||||
def test_download_with_douban_movie_media_converts_to_tmdb_and_keeps_origin_trace(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""
|
||||
RECOGNIZE_SOURCE=themoviedb 时,从豆瓣电影详情页发起的手动下载应转为 TMDB 主身份并保留原来源追溯。
|
||||
"""
|
||||
_patch_recognize_source(monkeypatch, "themoviedb")
|
||||
tmdb_media = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 1483525,
|
||||
"media_type": MediaType.MOVIE,
|
||||
"title": "可能的爱",
|
||||
"release_date": "2026-01-01",
|
||||
}
|
||||
)
|
||||
media_chain = Mock()
|
||||
media_chain.convert_media_identity.return_value = {
|
||||
"id": 1483525,
|
||||
"media_type": MediaType.MOVIE,
|
||||
"title": "可能的爱",
|
||||
}
|
||||
media_chain.recognize_media.return_value = tmdb_media
|
||||
download_chain = Mock()
|
||||
download_chain.download_single.return_value = "download-douban-movie"
|
||||
monkeypatch.setattr(download_endpoint, "MediaChain", lambda: media_chain)
|
||||
monkeypatch.setattr(download_endpoint, "DownloadChain", lambda: download_chain)
|
||||
|
||||
response = download_endpoint.download(
|
||||
media_in=schemas.MediaInfo(
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="36847425",
|
||||
douban_id="36847425",
|
||||
type=MediaType.MOVIE.value,
|
||||
title="可能的爱",
|
||||
year="2026",
|
||||
),
|
||||
torrent_in=schemas.TorrentInfo(title="Possible.Love.2026.1080p.WEB-DL"),
|
||||
current_user=SimpleNamespace(name="tester"),
|
||||
)
|
||||
|
||||
assert response.success is True
|
||||
media_chain.convert_media_identity.assert_called_once_with(
|
||||
target_source=MediaSource.TMDB,
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="36847425",
|
||||
mtype=MediaType.MOVIE,
|
||||
season=None,
|
||||
)
|
||||
assert media_chain.recognize_media.call_args.kwargs["media_source"] == MediaSource.TMDB
|
||||
assert media_chain.recognize_media.call_args.kwargs["media_id"] == "1483525"
|
||||
assert media_chain.recognize_media.call_args.kwargs["mtype"] == MediaType.MOVIE
|
||||
context = download_chain.download_single.call_args.kwargs["context"]
|
||||
assert context.media_info is tmdb_media
|
||||
assert context.media_info.media_source == MediaSource.TMDB
|
||||
assert context.media_info.media_id == "1483525"
|
||||
assert context.media_info.douban_id == "36847425"
|
||||
assert context.origin_media == {
|
||||
"media_source": "douban",
|
||||
"media_id": "36847425",
|
||||
}
|
||||
|
||||
|
||||
def test_download_with_douban_tv_media_fills_missing_season_and_preserves_episodes(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""
|
||||
从豆瓣季条目发起手动下载且种子标题缺季号时,应补齐季号、保留选集并核验 TMDB 季列表。
|
||||
"""
|
||||
_patch_recognize_source(monkeypatch, "themoviedb")
|
||||
tmdb_media = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 124101,
|
||||
"media_type": MediaType.TV,
|
||||
"name": "绝望写手",
|
||||
"first_air_date": "2021-05-13",
|
||||
"seasons": [
|
||||
{"season_number": 1, "episode_count": 10},
|
||||
{"season_number": 2, "episode_count": 8},
|
||||
{"season_number": 3, "episode_count": 9},
|
||||
],
|
||||
}
|
||||
)
|
||||
media_chain = Mock()
|
||||
media_chain.convert_media_identity.return_value = {
|
||||
"id": 124101,
|
||||
"media_type": MediaType.TV,
|
||||
"season": 3,
|
||||
}
|
||||
media_chain.recognize_media.return_value = tmdb_media
|
||||
download_chain = Mock()
|
||||
download_chain.download_single.return_value = "download-douban-tv"
|
||||
monkeypatch.setattr(download_endpoint, "MediaChain", lambda: media_chain)
|
||||
monkeypatch.setattr(download_endpoint, "DownloadChain", lambda: download_chain)
|
||||
|
||||
response = download_endpoint.download(
|
||||
media_in=schemas.MediaInfo(
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="35932853",
|
||||
type=MediaType.TV.value,
|
||||
title="绝望写手 第三季",
|
||||
year="2024",
|
||||
),
|
||||
torrent_in=schemas.TorrentInfo(title="Hacks.E01-E05.1080p.WEB-DL"),
|
||||
current_user=SimpleNamespace(name="tester"),
|
||||
)
|
||||
|
||||
assert response.success is True
|
||||
media_chain.convert_media_identity.assert_called_once_with(
|
||||
target_source=MediaSource.TMDB,
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="35932853",
|
||||
mtype=MediaType.TV,
|
||||
season=3,
|
||||
)
|
||||
context = download_chain.download_single.call_args.kwargs["context"]
|
||||
assert context.media_info is tmdb_media
|
||||
assert context.meta_info.begin_season == 3
|
||||
assert context.meta_info.episode_list == [1, 2, 3, 4, 5]
|
||||
assert context.media_info.douban_id == "35932853"
|
||||
assert context.origin_media == {
|
||||
"media_source": "douban",
|
||||
"media_id": "35932853",
|
||||
}
|
||||
|
||||
|
||||
def test_download_with_bangumi_tv_rejects_unlisted_tmdb_season_and_keeps_origin(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""
|
||||
TMDB 季列表未包含目标季时视为不可靠转换,应保留原 Bangumi 身份且不污染原元数据。
|
||||
"""
|
||||
_patch_recognize_source(monkeypatch, "themoviedb")
|
||||
tmdb_media = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 99901,
|
||||
"media_type": MediaType.TV,
|
||||
"name": "测试分季动画",
|
||||
"seasons": [{"season_number": 1, "episode_count": 24}],
|
||||
}
|
||||
)
|
||||
media_chain = Mock()
|
||||
media_chain.convert_media_identity.return_value = {
|
||||
"id": 99901,
|
||||
"media_type": MediaType.TV,
|
||||
"season": 2,
|
||||
}
|
||||
media_chain.recognize_media.return_value = tmdb_media
|
||||
download_chain = Mock()
|
||||
download_chain.download_single.return_value = "download-keep-bangumi"
|
||||
monkeypatch.setattr(download_endpoint, "MediaChain", lambda: media_chain)
|
||||
monkeypatch.setattr(download_endpoint, "DownloadChain", lambda: download_chain)
|
||||
|
||||
response = download_endpoint.download(
|
||||
media_in=schemas.MediaInfo(
|
||||
media_source=MediaSource.Bangumi,
|
||||
media_id="40000",
|
||||
bangumi_id=40000,
|
||||
type=MediaType.TV.value,
|
||||
title="测试分季动画 第二季",
|
||||
year="2025",
|
||||
),
|
||||
torrent_in=schemas.TorrentInfo(title="Test.Anime.S02E01-E03.1080p.WEB-DL"),
|
||||
current_user=SimpleNamespace(name="tester"),
|
||||
)
|
||||
|
||||
assert response.success is True
|
||||
context = download_chain.download_single.call_args.kwargs["context"]
|
||||
assert context.media_info.media_source == MediaSource.Bangumi
|
||||
assert context.media_info.media_id == "40000"
|
||||
assert context.meta_info.media_source is None
|
||||
assert context.meta_info.media_id is None
|
||||
assert context.meta_info.begin_season == 2
|
||||
assert context.meta_info.episode_list == [1, 2, 3]
|
||||
assert context.origin_media is None
|
||||
|
||||
|
||||
def test_download_with_episode_group_preserves_on_match_and_falls_back_on_mismatch(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""
|
||||
剧集组在 TMDB 识别成功应用时应完整保留,未能应用时应回退原身份避免静默丢失。
|
||||
"""
|
||||
_patch_recognize_source(monkeypatch, "themoviedb")
|
||||
|
||||
def run_case(applied_group: str | None):
|
||||
"""
|
||||
构造不同剧集组返回结果并执行一次带剧集组的手动下载。
|
||||
"""
|
||||
tmdb_media = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 88801,
|
||||
"media_type": MediaType.TV,
|
||||
"name": "剧集组测试剧",
|
||||
}
|
||||
)
|
||||
tmdb_media.seasons = {1: [1, 2, 3], 2: [1, 2, 3]}
|
||||
tmdb_media.episode_group = applied_group
|
||||
media_chain = Mock()
|
||||
media_chain.convert_media_identity.return_value = {
|
||||
"id": 88801,
|
||||
"media_type": MediaType.TV,
|
||||
"season": 2,
|
||||
}
|
||||
media_chain.recognize_media.return_value = tmdb_media
|
||||
download_chain = Mock()
|
||||
download_chain.download_single.return_value = "download-eg"
|
||||
monkeypatch.setattr(download_endpoint, "MediaChain", lambda: media_chain)
|
||||
monkeypatch.setattr(download_endpoint, "DownloadChain", lambda: download_chain)
|
||||
response = download_endpoint.download(
|
||||
media_in=schemas.MediaInfo(
|
||||
media_source=MediaSource.Bangumi,
|
||||
media_id="50001",
|
||||
type=MediaType.TV.value,
|
||||
title="剧集组测试剧",
|
||||
episode_group="eg-custom-1",
|
||||
),
|
||||
torrent_in=schemas.TorrentInfo(title="Group.Show.S02E01.1080p"),
|
||||
current_user=SimpleNamespace(name="tester"),
|
||||
)
|
||||
assert response.success is True
|
||||
return media_chain, download_chain.download_single.call_args.kwargs["context"]
|
||||
|
||||
ok_media_chain, ok_context = run_case("eg-custom-1")
|
||||
assert ok_media_chain.recognize_media.call_args.kwargs["episode_group"] == "eg-custom-1"
|
||||
assert ok_context.media_info.media_source == MediaSource.TMDB
|
||||
assert ok_context.media_info.media_id == "88801"
|
||||
assert ok_context.media_info.episode_group == "eg-custom-1"
|
||||
assert ok_context.media_info.bangumi_id == 50001
|
||||
assert ok_context.origin_media == {"media_source": "bangumi", "media_id": "50001"}
|
||||
|
||||
fallback_media_chain, fallback_context = run_case(None)
|
||||
assert fallback_media_chain.recognize_media.call_args.kwargs["episode_group"] == "eg-custom-1"
|
||||
assert fallback_context.media_info.media_source == MediaSource.Bangumi
|
||||
assert fallback_context.media_info.media_id == "50001"
|
||||
assert fallback_context.media_info.episode_group == "eg-custom-1"
|
||||
assert fallback_context.origin_media is None
|
||||
|
||||
|
||||
def test_download_rejects_media_type_conflict_and_skips_when_recognize_source_not_tmdb(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""
|
||||
影视类型冲突或全局识别源非 TMDB 时,手动下载均应保留原来源身份。
|
||||
"""
|
||||
_patch_recognize_source(monkeypatch, "themoviedb")
|
||||
media_chain = Mock()
|
||||
media_chain.convert_media_identity.return_value = {
|
||||
"id": 77701,
|
||||
"media_type": MediaType.MOVIE,
|
||||
}
|
||||
download_chain = Mock()
|
||||
download_chain.download_single.return_value = "download-conflict"
|
||||
monkeypatch.setattr(download_endpoint, "MediaChain", lambda: media_chain)
|
||||
monkeypatch.setattr(download_endpoint, "DownloadChain", lambda: download_chain)
|
||||
|
||||
conflict_resp = download_endpoint.download(
|
||||
media_in=schemas.MediaInfo(
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="36000001",
|
||||
type=MediaType.TV.value,
|
||||
title="类型冲突剧",
|
||||
),
|
||||
torrent_in=schemas.TorrentInfo(title="Conflict.Show.S01E01.1080p"),
|
||||
current_user=SimpleNamespace(name="tester"),
|
||||
)
|
||||
assert conflict_resp.success is True
|
||||
media_chain.recognize_media.assert_not_called()
|
||||
conflict_ctx = download_chain.download_single.call_args.kwargs["context"]
|
||||
assert conflict_ctx.media_info.media_source == MediaSource.Douban
|
||||
assert conflict_ctx.media_info.media_id == "36000001"
|
||||
assert conflict_ctx.origin_media is None
|
||||
|
||||
_patch_recognize_source(monkeypatch, "douban")
|
||||
media_chain.reset_mock()
|
||||
non_tmdb_resp = download_endpoint.download(
|
||||
media_in=schemas.MediaInfo(
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="36847425",
|
||||
type=MediaType.MOVIE.value,
|
||||
title="可能的爱",
|
||||
),
|
||||
torrent_in=schemas.TorrentInfo(title="Possible.Love.2026.1080p"),
|
||||
current_user=SimpleNamespace(name="tester"),
|
||||
)
|
||||
assert non_tmdb_resp.success is True
|
||||
media_chain.convert_media_identity.assert_not_called()
|
||||
kept_ctx = download_chain.download_single.call_args.kwargs["context"]
|
||||
assert kept_ctx.media_info.media_source == MediaSource.Douban
|
||||
assert kept_ctx.media_info.media_id == "36847425"
|
||||
assert kept_ctx.origin_media is None
|
||||
|
||||
|
||||
def test_download_add_records_origin_media_and_preserves_imdb_field_on_conversion(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""
|
||||
无媒体信息下载发生 IMDb 到 TMDB 转换时,应在上下文与媒体对象中保留原来源追溯信息。
|
||||
"""
|
||||
_patch_recognize_source(monkeypatch, "themoviedb")
|
||||
tmdb_media = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 1101383,
|
||||
"media_type": MediaType.MOVIE,
|
||||
"title": "逃出绝命街",
|
||||
}
|
||||
)
|
||||
media_chain = Mock()
|
||||
media_chain.convert_media_identity.return_value = {
|
||||
"id": 1101383,
|
||||
"media_type": MediaType.MOVIE,
|
||||
}
|
||||
media_chain.recognize_media.return_value = tmdb_media
|
||||
download_chain = Mock()
|
||||
download_chain.download_single.return_value = "download-origin"
|
||||
monkeypatch.setattr(download_endpoint, "MediaChain", lambda: media_chain)
|
||||
monkeypatch.setattr(download_endpoint, "DownloadChain", lambda: download_chain)
|
||||
|
||||
response = download_endpoint.add(
|
||||
torrent_in=schemas.TorrentInfo(
|
||||
title="The.End.of.Oak.Street.2026.1080p.WEB-DL",
|
||||
media_source=MediaSource.IMDb,
|
||||
media_id="tt27165187",
|
||||
),
|
||||
media_source=MediaSource.IMDb,
|
||||
media_id="tt27165187",
|
||||
current_user=SimpleNamespace(name="tester"),
|
||||
)
|
||||
|
||||
assert response.success is True
|
||||
context = download_chain.download_single.call_args.kwargs["context"]
|
||||
assert context.media_info.imdb_id == "tt27165187"
|
||||
assert context.origin_media == {
|
||||
"media_source": "imdb",
|
||||
"media_id": "tt27165187",
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -19,10 +19,12 @@ from app.chain.message import MessageChain
|
||||
from app.domain.context import Context, MediaInfo, MusicInfo, TorrentInfo
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.domain.meta.metamusic import MetaMusic
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.runtime.events import EventManager
|
||||
|
||||
# 此用例覆盖运行时惰性导出,静态检查无法解析该公开入口。
|
||||
from app.schemas import IncomingMessage, TransferDirectoryConf # pylint: disable=no-name-in-module
|
||||
from app.schemas.mediaserver import NotExistMediaInfo
|
||||
from app.schemas.types import (
|
||||
MUSIC_ENTITY_ALBUM,
|
||||
MUSIC_ENTITY_RECORDING,
|
||||
@@ -2408,3 +2410,239 @@ def test_get_download_dirs_keeps_matching_tv_category_dir():
|
||||
"动画下载",
|
||||
]
|
||||
assert download_dirs[0].save_path == "rclone:/media/anime"
|
||||
|
||||
|
||||
def test_torrent_selection_converts_douban_context_to_tmdb_when_recognize_source_is_tmdb():
|
||||
"""
|
||||
消息交互选中豆瓣来源资源且全局识别源为 TMDB 时,应转换为 TMDB 主身份并保留原搜索项。
|
||||
"""
|
||||
chain = MediaInteractionChain()
|
||||
douban_media = MediaInfo(
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="36847425",
|
||||
douban_id="36847425",
|
||||
type=MediaType.MOVIE,
|
||||
title="可能的爱",
|
||||
year="2026",
|
||||
)
|
||||
tmdb_media = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 1483525,
|
||||
"media_type": MediaType.MOVIE,
|
||||
"title": "可能的爱",
|
||||
"release_date": "2026-01-01",
|
||||
}
|
||||
)
|
||||
context = Context(
|
||||
meta_info=MetaInfo("Possible.Love.2026.1080p"),
|
||||
media_info=douban_media,
|
||||
torrent_info=TorrentInfo(title="Possible.Love.2026.1080p"),
|
||||
)
|
||||
request = media_interaction_manager.create_or_replace(
|
||||
user_id="10099",
|
||||
channel=NotificationChannel.Telegram,
|
||||
source="telegram-test",
|
||||
username="tester",
|
||||
action="Search",
|
||||
keyword="可能的爱",
|
||||
title="可能的爱",
|
||||
meta=_build_meta("可能的爱"),
|
||||
items=[context],
|
||||
)
|
||||
request.phase = "torrent"
|
||||
|
||||
fake_media_chain = MagicMock()
|
||||
fake_media_chain.convert_media_identity.return_value = {
|
||||
"id": 1483525,
|
||||
"media_type": MediaType.MOVIE,
|
||||
}
|
||||
fake_media_chain.recognize_media.return_value = tmdb_media
|
||||
|
||||
with (
|
||||
patch("app.chain.interaction.is_tmdb_recognize_source", return_value=True),
|
||||
patch("app.chain.interaction.MediaChain", return_value=fake_media_chain),
|
||||
patch("app.chain.interaction.DirectoryHelper.get_download_dirs", return_value=[]),
|
||||
patch(
|
||||
"app.chain.interaction.DownloadChain.download_single",
|
||||
return_value="hash-tmdb",
|
||||
) as download_single,
|
||||
):
|
||||
handled = chain.handle_text_interaction(
|
||||
channel=NotificationChannel.Telegram,
|
||||
source="telegram-test",
|
||||
userid="10099",
|
||||
username="tester",
|
||||
text="1",
|
||||
)
|
||||
|
||||
assert handled
|
||||
submitted = download_single.call_args.args[0]
|
||||
assert submitted is not context
|
||||
assert submitted.media_info is tmdb_media
|
||||
assert submitted.media_info.media_source == MediaSource.TMDB
|
||||
assert submitted.media_info.media_id == "1483525"
|
||||
assert submitted.media_info.douban_id == "36847425"
|
||||
assert submitted.origin_media == {"media_source": "douban", "media_id": "36847425"}
|
||||
# 原搜索列表中的条目保持原身份不被原地篡改。
|
||||
assert context.media_info is douban_media
|
||||
|
||||
|
||||
def test_auto_download_converts_douban_tv_batch_and_remaps_no_exists_key():
|
||||
"""
|
||||
交互自动择优下载豆瓣剧集时,应同步转换批量上下文和缺集键,避免下载与补订身份不一致。
|
||||
"""
|
||||
chain = MediaInteractionChain()
|
||||
douban_tv = MediaInfo(
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="35932853",
|
||||
type=MediaType.TV,
|
||||
title="绝望写手 第三季",
|
||||
year="2024",
|
||||
)
|
||||
tmdb_tv = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 124101,
|
||||
"media_type": MediaType.TV,
|
||||
"name": "绝望写手",
|
||||
"seasons": [
|
||||
{"season_number": 1, "episode_count": 10},
|
||||
{"season_number": 2, "episode_count": 8},
|
||||
{"season_number": 3, "episode_count": 9},
|
||||
],
|
||||
}
|
||||
)
|
||||
candidate = Context(
|
||||
meta_info=MetaInfo("Hacks.E01-E09.1080p", mtype=MediaType.TV),
|
||||
media_info=douban_tv,
|
||||
torrent_info=TorrentInfo(title="Hacks.E01-E09.1080p"),
|
||||
)
|
||||
request = media_interaction_manager.create_or_replace(
|
||||
user_id="10100",
|
||||
channel=NotificationChannel.Telegram,
|
||||
source="telegram-test",
|
||||
username="tester",
|
||||
action="Search",
|
||||
keyword="绝望写手",
|
||||
title="绝望写手 第三季",
|
||||
meta=MetaInfo("绝望写手", mtype=MediaType.TV),
|
||||
items=[candidate],
|
||||
)
|
||||
request.current_media = douban_tv
|
||||
no_exists = {
|
||||
"douban:35932853": {
|
||||
3: NotExistMediaInfo(season=3, episodes=[], total_episode=9, start_episode=1),
|
||||
}
|
||||
}
|
||||
fake_media_chain = MagicMock()
|
||||
fake_media_chain.convert_media_identity.return_value = {
|
||||
"id": 124101,
|
||||
"media_type": MediaType.TV,
|
||||
"season": 3,
|
||||
}
|
||||
fake_media_chain.recognize_media.return_value = tmdb_tv
|
||||
|
||||
with (
|
||||
patch("app.chain.interaction.is_tmdb_recognize_source", return_value=True),
|
||||
patch("app.chain.interaction.MediaChain", return_value=fake_media_chain),
|
||||
patch(
|
||||
"app.chain.interaction.DownloadChain.batch_download",
|
||||
return_value=([candidate], {}),
|
||||
) as batch_download,
|
||||
):
|
||||
chain._auto_download(
|
||||
request=request,
|
||||
cache_list=[candidate],
|
||||
channel=NotificationChannel.Telegram,
|
||||
source="telegram-test",
|
||||
userid="10100",
|
||||
username="tester",
|
||||
no_exists=no_exists,
|
||||
)
|
||||
|
||||
batch_download.assert_called_once()
|
||||
kwargs = batch_download.call_args.kwargs
|
||||
assert list(kwargs["no_exists"].keys()) == ["tmdb:124101"]
|
||||
assert 3 in kwargs["no_exists"]["tmdb:124101"]
|
||||
remapped = kwargs["contexts"][0]
|
||||
assert remapped.media_info is tmdb_tv
|
||||
assert remapped.meta_info.begin_season == 3
|
||||
assert remapped.origin_media == {"media_source": "douban", "media_id": "35932853"}
|
||||
assert candidate.media_info is douban_tv
|
||||
|
||||
|
||||
def test_auto_download_keeps_origin_identity_when_tmdb_seasons_incompatible():
|
||||
"""
|
||||
交互自动择优下载的目标缺集季号不在转换后的 TMDB 季清单内时,应整批保留原身份不改写缺集键。
|
||||
"""
|
||||
chain = MediaInteractionChain()
|
||||
douban_tv = MediaInfo(
|
||||
media_source=MediaSource.Douban,
|
||||
media_id="35932853",
|
||||
type=MediaType.TV,
|
||||
title="绝望写手",
|
||||
year="2024",
|
||||
)
|
||||
tmdb_tv = MediaInfo(
|
||||
tmdb_info={
|
||||
"id": 124101,
|
||||
"media_type": MediaType.TV,
|
||||
"name": "绝望写手",
|
||||
"seasons": [
|
||||
{"season_number": 1, "episode_count": 10},
|
||||
{"season_number": 2, "episode_count": 8},
|
||||
],
|
||||
}
|
||||
)
|
||||
candidate = Context(
|
||||
meta_info=MetaInfo("Hacks.S03E01-E09.1080p", mtype=MediaType.TV),
|
||||
media_info=douban_tv,
|
||||
torrent_info=TorrentInfo(title="Hacks.S03E01-E09.1080p"),
|
||||
)
|
||||
request = media_interaction_manager.create_or_replace(
|
||||
user_id="10101",
|
||||
channel=NotificationChannel.Telegram,
|
||||
source="telegram-test",
|
||||
username="tester",
|
||||
action="Search",
|
||||
keyword="绝望写手",
|
||||
title="绝望写手",
|
||||
meta=MetaInfo("绝望写手", mtype=MediaType.TV),
|
||||
items=[candidate],
|
||||
)
|
||||
request.current_media = douban_tv
|
||||
no_exists = {
|
||||
"douban:35932853": {
|
||||
3: NotExistMediaInfo(season=3, episodes=[], total_episode=9, start_episode=1),
|
||||
}
|
||||
}
|
||||
fake_media_chain = MagicMock()
|
||||
fake_media_chain.convert_media_identity.return_value = {
|
||||
"id": 124101,
|
||||
"media_type": MediaType.TV,
|
||||
}
|
||||
fake_media_chain.recognize_media.return_value = tmdb_tv
|
||||
|
||||
with (
|
||||
patch("app.chain.interaction.is_tmdb_recognize_source", return_value=True),
|
||||
patch("app.chain.interaction.MediaChain", return_value=fake_media_chain),
|
||||
patch(
|
||||
"app.chain.interaction.DownloadChain.batch_download",
|
||||
return_value=([candidate], {}),
|
||||
) as batch_download,
|
||||
):
|
||||
chain._auto_download(
|
||||
request=request,
|
||||
cache_list=[candidate],
|
||||
channel=NotificationChannel.Telegram,
|
||||
source="telegram-test",
|
||||
userid="10101",
|
||||
username="tester",
|
||||
no_exists=no_exists,
|
||||
)
|
||||
|
||||
batch_download.assert_called_once()
|
||||
kwargs = batch_download.call_args.kwargs
|
||||
assert list(kwargs["no_exists"].keys()) == ["douban:35932853"]
|
||||
assert kwargs["contexts"][0] is candidate
|
||||
assert kwargs["contexts"][0].media_info is douban_tv
|
||||
assert kwargs["contexts"][0].origin_media is None
|
||||
|
||||
Reference in New Issue
Block a user