From a6cf75466f6650d32f43d310f3307a2fd55cf042 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Mon, 23 Nov 2026 14:45:40 +0800 Subject: [PATCH] fix(download): project IMDb identity to TMDB when adding downloads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充 IMDb -> TMDB 身份投影(经 TMDB /find/{imdb_id} 精确查找并补全本地化详情),并在 RECOGNIZE_SOURCE=themoviedb 时于 /api/v1/download/add 将 IMDb 及站点资源自带的非 TMDB 线索优先转换为 TMDB 主身份,转换或识别失败时无污染回退原来源;同步扩展订阅元数据巡检对 IMDb 身份的重试转换。 Refs #7550 --- app/api/endpoints/download.py | 148 +++++++- app/chain/base.py | 36 +- app/chain/media/contract.py | 6 +- app/chain/media/projection.py | 28 +- app/chain/subscribe/metadata.py | 4 +- app/modules/themoviedb/__init__.py | 38 +- app/modules/themoviedb/tmdbapi.py | 217 +++++++++++- app/modules/themoviedb/tmdbv3api/tmdb.py | 26 +- app/runtime/extensions/module/contracts.py | 1 + docs/architecture-overview.md | 2 +- .../architecture/dependency-baseline.json | 5 +- .../runtime-contract-baseline.json | 8 +- tests/test_download_media_source.py | 330 ++++++++++++++++++ tests/test_media_identity_projection.py | 326 +++++++++++++++++ tests/test_tmdb_empty_result_cache.py | 22 ++ tests/test_tmdb_sync_async_parity.py | 30 ++ tests/test_tmdbapi_sync_async_parity.py | 146 ++++++++ 17 files changed, 1340 insertions(+), 33 deletions(-) diff --git a/app/api/endpoints/download.py b/app/api/endpoints/download.py index 7563314ed..dccde7793 100644 --- a/app/api/endpoints/download.py +++ b/app/api/endpoints/download.py @@ -2,6 +2,7 @@ 提供下载任务查询、控制和手动添加接口,保留当前用户与媒体身份。 """ +from copy import deepcopy from typing import Annotated, Any, List, Optional, Union import anyio @@ -20,7 +21,10 @@ from app.api.response import ( CompatiblePageParam, ResponseAPIRouter, ) -from app.application.configuration import get_configured_system_config +from app.application.configuration import ( + get_configured_system_config, + get_runtime_settings, +) from app.application.directory import DirectoryHelper from app.application.download.organization import organize_existing_source from app.application.download.tasks import DownloadTaskMutationService @@ -49,6 +53,7 @@ from app.schemas.download import DownloadTaskUpdateData as _SchemaDownloadTaskUp from app.schemas.download import DownloadTaskUpdateRequest as _SchemaDownloadTaskUpdateRequest from app.schemas.download import SubtitleDownloadData as _SchemaSubtitleDownloadData from app.schemas.file import FileURI as _SchemaFileURI +from app.schemas.media import normalize_media_source, resolve_media_identity from app.schemas.music import MusicInfo as _SchemaMusicInfo from app.schemas.response import Response as _SchemaResponse from app.schemas.token import TokenPayload as _SchemaTokenPayload @@ -137,6 +142,136 @@ def _build_unrecognized_media_info( ) +def _is_tmdb_recognize_source() -> bool: + """ + 判断当前系统影视识别源配置是否为 TMDB。 + """ + return normalize_media_source(get_runtime_settings().get("RECOGNIZE_SOURCE")) == MediaSource.TMDB + + +def _should_convert_download_identity_to_tmdb( + torrent_in: _SchemaTorrentInfo, + media_source: MediaSource, + media_id: str, +) -> bool: + """ + 判断下载请求携带的非 TMDB 影视身份是否应转换为 TMDB 主身份。 + + 当系统识别源为 TMDB 时,IMDb 标识以及种子自身携带的非 TMDB 线索(如站点资源附带的 + IMDb 或豆瓣 ID)优先投影为 TMDB 身份,以避免后续下载记录和整理锁死为外部来源标题或季级身份; + 用户在高级选项中主动切换的其他非 TMDB 来源则保持原来源。 + """ + if media_source == MediaSource.TMDB or not _is_tmdb_recognize_source(): + return False + if media_source == MediaSource.IMDb: + return True + return resolve_media_identity(media=torrent_in) == (media_source, media_id) + + +def _resolve_converted_tmdb_media( + media_chain: MediaChain, + metainfo: MetaBase, + media_source: MediaSource, + media_id: str, +) -> tuple[MetaBase, MediaInfo] | None: + """ + 尝试将非 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 + ) + tmdbinfo = convert_identity( + target_source=MediaSource.TMDB, + 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") + 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 + ): + 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 + + +def _resolve_explicit_download_media( + torrent_in: _SchemaTorrentInfo, + metainfo: MetaBase, + media_source: MediaSource, + media_id: str, + *, + is_music: bool, + music_type: Optional[str], +) -> tuple[MetaBase, MediaInfo | MusicInfo | None]: + """ + 使用显式来源身份识别下载媒体,适用时优先按 TMDB 识别源转换主身份并保留失败回退。 + """ + media_chain = MediaChain() + normalized_source, normalized_id = resolve_media_identity( + media_source=media_source, + media_id=media_id, + ) + if ( + not is_music + and normalized_source + and normalized_id + and _should_convert_download_identity_to_tmdb( + torrent_in, + normalized_source, + normalized_id, + ) + ): + converted = _resolve_converted_tmdb_media( + media_chain, + metainfo, + normalized_source, + normalized_id, + ) + if converted is not None: + return converted + mediainfo = media_chain.recognize_media( + meta=metainfo, + media_source=media_source, + media_id=media_id, + mtype=MediaType.MUSIC if is_music else None, + music_type=music_type, + ) + return metainfo, mediainfo + + def _resolve_add_media( torrent_in: _SchemaTorrentInfo, media_source: MediaSource | None, @@ -186,11 +321,12 @@ def _resolve_add_media( metainfo = MetaInfo(title=torrent_in.title or "", subtitle=torrent_in.description, mtype=MediaType.MUSIC if is_music else None) if media_source and media_id: - mediainfo = MediaChain().recognize_media( - meta=metainfo, - media_source=media_source, - media_id=media_id, - mtype=MediaType.MUSIC if is_music else None, + metainfo, mediainfo = _resolve_explicit_download_media( + torrent_in, + metainfo, + media_source, + media_id, + is_music=is_music, music_type=normalized_music_type, ) else: diff --git a/app/chain/base.py b/app/chain/base.py index 046af10a4..a764a3728 100644 --- a/app/chain/base.py +++ b/app/chain/base.py @@ -362,37 +362,61 @@ class ChainBase(RecognitionMixin, MessageProcessingMixin, NotificationMixin, met def match_tmdbinfo( self, - name: str, + name: str = "", mtype: Optional[MediaType] = None, year: Optional[str] = None, season: Optional[int] = None, + imdbid: Optional[str] = None, ) -> Optional[dict[str, Any]]: """ 搜索和匹配TMDB信息 - :param name: 标题 + :param name: 标题,仅按 IMDb 标识精确匹配时可为空字符串 :param mtype: 类型 :param year: 年份 :param season: 季 + :param imdbid: IMDb 媒体标识,旧模块可不接收 """ - return cast(Optional[dict[str, Any]], self.run_module("match_tmdbinfo", name=name, mtype=mtype, year=year, season=season)) + return cast( + Optional[dict[str, Any]], + self.run_module( + "match_tmdbinfo", + name=name, + mtype=mtype, + year=year, + season=season, + imdbid=imdbid, + ), + ) async def async_match_tmdbinfo( self, - name: str, + name: str = "", mtype: Optional[MediaType] = None, year: Optional[str] = None, season: Optional[int] = None, + imdbid: Optional[str] = None, ) -> Optional[dict[str, Any]]: """ 搜索和匹配TMDB信息(异步版本) - :param name: 标题 + :param name: 标题,仅按 IMDb 标识精确匹配时可为空字符串 :param mtype: 类型 :param year: 年份 :param season: 季 + :param imdbid: IMDb 媒体标识,旧模块可不接收 """ - return cast(Optional[dict[str, Any]], await self.async_run_module("async_match_tmdbinfo", name=name, mtype=mtype, year=year, season=season)) + return cast( + Optional[dict[str, Any]], + await self.async_run_module( + "async_match_tmdbinfo", + name=name, + mtype=mtype, + year=year, + season=season, + imdbid=imdbid, + ), + ) def obtain_images(self, mediainfo: MediaInfo) -> Optional[MediaInfo]: """ diff --git a/app/chain/media/contract.py b/app/chain/media/contract.py index 087ec62fb..842ccdba6 100644 --- a/app/chain/media/contract.py +++ b/app/chain/media/contract.py @@ -500,10 +500,11 @@ if TYPE_CHECKING: def match_tmdbinfo( self, - name: str, + name: str = "", mtype: Optional[MediaType] = None, year: Optional[str] = None, season: Optional[int] = None, + imdbid: Optional[str] = None, ) -> Optional[_MediaPayload]: """ 同步匹配 TMDB 详情。 @@ -512,10 +513,11 @@ if TYPE_CHECKING: async def async_match_tmdbinfo( self, - name: str, + name: str = "", mtype: Optional[MediaType] = None, year: Optional[str] = None, season: Optional[int] = None, + imdbid: Optional[str] = None, ) -> Optional[_MediaPayload]: """ 异步匹配 TMDB 详情。 diff --git a/app/chain/media/projection.py b/app/chain/media/projection.py index 7f37ae06c..38099a5b8 100644 --- a/app/chain/media/projection.py +++ b/app/chain/media/projection.py @@ -4,6 +4,7 @@ from __future__ import annotations +import re from collections.abc import Mapping, Sequence from dataclasses import dataclass from enum import Enum, auto @@ -37,6 +38,8 @@ class _ProjectionRule(Enum): BANGUMI_TO_TMDB = auto() # 根据 AniList 的多语言标题、年份和季信息匹配 TMDB 身份。 ANILIST_TO_TMDB = auto() + # 根据 IMDb 标识直接通过 TMDB 外部标识接口精确匹配 TMDB 身份。 + IMDB_TO_TMDB = auto() # 根据 TMDB 详情匹配豆瓣身份。 TMDB_TO_DOUBAN = auto() # 根据 Bangumi 详情匹配豆瓣身份。 @@ -49,6 +52,7 @@ _PROJECTION_RULES: Final = { (MediaSource.Douban, MediaSource.TMDB): _ProjectionRule.DOUBAN_TO_TMDB, (MediaSource.Bangumi, MediaSource.TMDB): _ProjectionRule.BANGUMI_TO_TMDB, (MediaSource.AniList, MediaSource.TMDB): _ProjectionRule.ANILIST_TO_TMDB, + (MediaSource.IMDb, MediaSource.TMDB): _ProjectionRule.IMDB_TO_TMDB, (MediaSource.TMDB, MediaSource.Douban): _ProjectionRule.TMDB_TO_DOUBAN, (MediaSource.Bangumi, MediaSource.Douban): _ProjectionRule.BANGUMI_TO_DOUBAN, } @@ -58,6 +62,8 @@ _NUMERIC_SOURCE_RULES: Final = { _ProjectionRule.TMDB_TO_DOUBAN, _ProjectionRule.BANGUMI_TO_DOUBAN, } +# IMDb 原生条目标识必须为 tt 加数字,统一转小写后再用于查询与共享缓存键。 +_IMDB_ID_PATTERN: Final = re.compile(r"^tt\d+$", re.IGNORECASE) @dataclass(frozen=True) @@ -167,6 +173,10 @@ def _build_projection_plan( rule = _PROJECTION_RULES.get((source, target), _ProjectionRule.EVENT) if rule in _NUMERIC_SOURCE_RULES and not normalized_id.isdigit(): return None + if rule == _ProjectionRule.IMDB_TO_TMDB: + if not _IMDB_ID_PATTERN.fullmatch(normalized_id): + return None + normalized_id = normalized_id.lower() return _ProjectionPlan( rule=rule, source=source, @@ -425,8 +435,15 @@ def _convert_builtin_projection( plan: _ProjectionPlan, ) -> Optional[_ProjectionPayload]: """ - 同步执行来源读取、纯投影和目标匹配三阶段流程。 + 同步执行来源读取、纯投影和目标匹配流程;IMDb 直连 TMDB 外部标识匹配。 """ + if plan.rule == _ProjectionRule.IMDB_TO_TMDB: + return owner.match_tmdbinfo( + name="", + mtype=plan.media_type, + season=plan.season, + imdbid=plan.media_id, + ) source_info = _load_projection_source(owner, plan) match = _build_projection_match(plan, source_info) if source_info else None return _apply_projection_match(owner, match) if match else None @@ -437,8 +454,15 @@ async def _async_convert_builtin_projection( plan: _ProjectionPlan, ) -> Optional[_ProjectionPayload]: """ - 异步执行来源读取、纯投影和目标匹配三阶段流程。 + 异步执行来源读取、纯投影和目标匹配流程;IMDb 直连 TMDB 外部标识匹配。 """ + if plan.rule == _ProjectionRule.IMDB_TO_TMDB: + return await owner.async_match_tmdbinfo( + name="", + mtype=plan.media_type, + season=plan.season, + imdbid=plan.media_id, + ) source_info = await _async_load_projection_source(owner, plan) match = _build_projection_match(plan, source_info) if source_info else None return await _async_apply_projection_match(owner, match) if match else None diff --git a/app/chain/subscribe/metadata.py b/app/chain/subscribe/metadata.py index 9eff0a84b..c883ef81b 100644 --- a/app/chain/subscribe/metadata.py +++ b/app/chain/subscribe/metadata.py @@ -119,7 +119,7 @@ class SubscribeMetadataOwner(_SubscribeOwnerBase): media_chain_factory: Callable[[], Any], ) -> Optional[SubscriptionSnapshot]: """ - 在元数据巡检中重试豆瓣、Bangumi 或 AniList 到 TMDB 的订阅身份转换。 + 在元数据巡检中重试豆瓣、Bangumi、AniList 或 IMDb 到 TMDB 的订阅身份转换。 该补偿复用既有的 TMDB 元数据巡检周期。没有匹配结果、外部识别失败或目标身份 已被其他订阅占用时保留原订阅,避免转换失败影响当前订阅的后续搜索。 @@ -135,7 +135,7 @@ class SubscribeMetadataOwner(_SubscribeOwnerBase): if is_tmdb_recognize_source is None or not is_tmdb_recognize_source(): return None source, media_id = resolve_media_identity(media=subscribe) - if source not in (MediaSource.Douban, MediaSource.Bangumi, MediaSource.AniList) or not media_id: + if source not in (MediaSource.Douban, MediaSource.Bangumi, MediaSource.AniList, MediaSource.IMDb) or not media_id: return None media_chain = media_chain_factory() diff --git a/app/modules/themoviedb/__init__.py b/app/modules/themoviedb/__init__.py index f3000dd00..7723133a9 100644 --- a/app/modules/themoviedb/__init__.py +++ b/app/modules/themoviedb/__init__.py @@ -1189,17 +1189,32 @@ class TheMovieDbModule(MediaAuxiliaryProviderMixin, _ModuleBase): return await self._async_run_recognize_steps(plan) def match_tmdbinfo( - self, name: str, mtype: Optional[MediaType] = None, year: Optional[str] = None, season: Optional[int] = None + self, + name: str = "", + mtype: Optional[MediaType] = None, + year: Optional[str] = None, + season: Optional[int] = None, + imdbid: Optional[str] = None, ) -> Optional[_TmdbData]: """ 搜索和匹配TMDB信息。 - :param name: 待搜索或匹配的名称 + 提供 IMDb 标识时优先按外部标识精确查询;未命中且提供名称时回退名称搜索。 + + :param name: 待搜索或匹配的名称;仅按 IMDb 标识查询时可为空字符串 :param mtype: 电影或电视剧类型;可选入口使用 None 表示未限定 :param year: 作品上映或整剧首播年份,未指定时不按年份限制 :param season: 目标季号,0 表示特别篇,None 在可选入口表示整剧 + :param imdbid: 可选 IMDb 标识,提供时优先用于 TMDB 外部标识精确查找 :return: 补齐 media_type 等字段的 TMDB 字典;无匹配、失败或无法消歧时返回空值 """ + if imdbid: + logger.info(f"开始使用 IMDBID:{imdbid} 匹配TMDB信息 ...") + info = self.tmdb.match_by_imdb_id(imdb_id=imdbid, mtype=mtype, season_number=season) + if info or not name: + return info + if not name: + return None logger.info(f"开始使用 名称:{name} 年份:{year} 匹配TMDB信息 ...") info = self.tmdb.match(name=name, year=year, mtype=mtype or MediaType.MOVIE, season_year=year, season_number=season) if info and not info.get("genres"): @@ -1210,17 +1225,32 @@ class TheMovieDbModule(MediaAuxiliaryProviderMixin, _ModuleBase): return info async def async_match_tmdbinfo( - self, name: str, mtype: Optional[MediaType] = None, year: Optional[str] = None, season: Optional[int] = None + self, + name: str = "", + mtype: Optional[MediaType] = None, + year: Optional[str] = None, + season: Optional[int] = None, + imdbid: Optional[str] = None, ) -> Optional[_TmdbData]: """ 异步搜索和匹配TMDB信息。 - :param name: 待搜索或匹配的名称 + 提供 IMDb 标识时优先按外部标识精确查询;未命中且提供名称时回退名称搜索。 + + :param name: 待搜索或匹配的名称;仅按 IMDb 标识查询时可为空字符串 :param mtype: 电影或电视剧类型;可选入口使用 None 表示未限定 :param year: 作品上映或整剧首播年份,未指定时不按年份限制 :param season: 目标季号,0 表示特别篇,None 在可选入口表示整剧 + :param imdbid: 可选 IMDb 标识,提供时优先用于 TMDB 外部标识精确查找 :return: 补齐 media_type 等字段的 TMDB 字典;无匹配、失败或无法消歧时返回空值 """ + if imdbid: + logger.info(f"开始使用 IMDBID:{imdbid} 匹配TMDB信息 ...") + info = await self.tmdb.async_match_by_imdb_id(imdb_id=imdbid, mtype=mtype, season_number=season) + if info or not name: + return info + if not name: + return None logger.info(f"开始使用 名称:{name} 年份:{year} 匹配TMDB信息 ...") info = await self.tmdb.async_match(name=name, year=year, mtype=mtype or MediaType.MOVIE, season_year=year, season_number=season) if info and not info.get("genres"): diff --git a/app/modules/themoviedb/tmdbapi.py b/app/modules/themoviedb/tmdbapi.py index 1f4513b58..e58ca88a9 100644 --- a/app/modules/themoviedb/tmdbapi.py +++ b/app/modules/themoviedb/tmdbapi.py @@ -14,11 +14,13 @@ from app.runtime.log import logger from app.runtime.settings import get_runtime_setting from app.schemas.types import MediaType -from .tmdbv3api import TV, Collection, Discover, Episode, Movie, Person, Search, Season, TMDb, Trending +from .tmdbv3api import TV, Collection, Discover, Episode, Find, Movie, Person, Search, Season, TMDb, Trending from .tmdbv3api.exceptions import TMDbConnectionError, TMDbException _MediaRecord = dict[str, Any] _DATE_PATTERN = re.compile(r"^\d{4}-\d{2}-\d{2}$") +# IMDb 条目标识固定为 tt 加数字,用于拦截无效外部标识避免无意义请求。 +_IMDB_ID_PATTERN = re.compile(r"^tt\d+$", re.IGNORECASE) class _MatchTarget(Enum): @@ -76,6 +78,21 @@ class _DetailRequest: tmdbid: int +@dataclass(frozen=True) +class _ImdbFindTarget: + """ + 保存由 TMDB 外部标识查询确定的目标媒体身份。 + + :param mtype: 解析出的电影或电视剧类型 + :param tmdbid: 对应的 TMDB 电影或剧集数字标识 + :param season: 由季、单集结果或调用方提供的剧集季号,电影及未指定时为 None + """ + + mtype: MediaType + tmdbid: int + season: Optional[int] = None + + class TmdbApi: """ 统一 TMDB 名称匹配、媒体详情投影和辅助信息查询。 @@ -91,6 +108,7 @@ class TmdbApi: """ self.tmdb = TMDb(language=language) self.search = Search(language=language) + self.find = Find(language=language) self.movie = Movie(language=language) self.tv = TV(language=language) self.season_obj = Season(language=language) @@ -687,6 +705,169 @@ class TmdbApi: ret_names.append(name) return ret_names + @staticmethod + def _normalize_imdb_id(imdb_id: Optional[str]) -> Optional[str]: + """ + 规范化并校验 IMDb 条目标识。 + + :param imdb_id: 原始 IMDb 标识,允许首尾空白和大小写差异 + :return: 小写 ``tt`` 数字标识;空值或格式无效时返回 None + """ + value = str(imdb_id or "").strip().lower() + return value if _IMDB_ID_PATTERN.fullmatch(value) else None + + @staticmethod + def _positive_int(value: object) -> Optional[int]: + """ + 校验 TMDB 媒体数字标识,拒绝布尔值与非正整数。 + """ + if isinstance(value, int) and not isinstance(value, bool) and value > 0: + return value + return None + + @staticmethod + def _non_negative_int(value: object) -> Optional[int]: + """ + 校验剧集季号,允许 0 表示特别篇并拒绝布尔值与负数。 + """ + if isinstance(value, int) and not isinstance(value, bool) and value >= 0: + return value + return None + + @classmethod + def _extract_find_target( + cls, + items: object, + *, + mtype: MediaType, + id_key: str, + explicit_season: Optional[int], + read_item_season: bool = False, + ) -> Optional[_ImdbFindTarget]: + """ + 从 /find 单个结果分组中提取首条具备有效 TMDB 标识的目标。 + """ + if not isinstance(items, list): + return None + for item in items: + if not isinstance(item, dict): + continue + tmdb_id = cls._positive_int(item.get(id_key)) + if tmdb_id is None: + continue + if mtype != MediaType.TV: + return _ImdbFindTarget(mtype=mtype, tmdbid=tmdb_id) + season = explicit_season + if season is None and read_item_season: + season = cls._non_negative_int(item.get("season_number")) + return _ImdbFindTarget(mtype=MediaType.TV, tmdbid=tmdb_id, season=season) + return None + + @classmethod + def _select_imdb_find_target( + cls, + imdb_id: str, + found: object, + mtype: Optional[MediaType], + season_number: Optional[int], + ) -> Optional[_ImdbFindTarget]: + """ + 结合媒体类型与季号从 /find 响应中确定唯一 TMDB 目标。 + + 同步与异步入口共享此规则:限定电影时只采信 movie_results,限定剧集时依次回退 + tv_results、tv_season_results 与 tv_episode_results;未限定类型且电影与剧集同时 + 命中时,仅在提供季号时偏向剧集,否则按歧义放弃匹配。 + """ + if not isinstance(found, dict): + return None + movie_target = cls._extract_find_target( + found.get("movie_results"), + mtype=MediaType.MOVIE, + id_key="id", + explicit_season=None, + ) + if mtype == MediaType.MOVIE: + return movie_target + tv_target = ( + cls._extract_find_target( + found.get("tv_results"), + mtype=MediaType.TV, + id_key="id", + explicit_season=season_number, + ) + or cls._extract_find_target( + found.get("tv_season_results"), + mtype=MediaType.TV, + id_key="show_id", + explicit_season=season_number, + read_item_season=True, + ) + or cls._extract_find_target( + found.get("tv_episode_results"), + mtype=MediaType.TV, + id_key="show_id", + explicit_season=season_number, + read_item_season=True, + ) + ) + if mtype == MediaType.TV: + return tv_target + if mtype not in (None, MediaType.UNKNOWN): + return None + if movie_target and tv_target: + if season_number is not None: + return tv_target + logger.warning(f"无法判断imdb_id:{imdb_id} 是电影还是电视剧") + return None + return tv_target or movie_target + + @staticmethod + def _attach_imdb_find_season( + info: Optional[_MediaRecord], + target: _ImdbFindTarget, + ) -> Optional[_MediaRecord]: + """ + 为剧集详情附加非空季号,不原地修改详情字典。 + """ + if not info: + return None + if target.mtype == MediaType.TV and target.season is not None: + return {**info, "season": target.season} + return info + + def match_by_imdb_id( + self, + imdb_id: str, + mtype: Optional[MediaType] = None, + season_number: Optional[int] = None, + ) -> Optional[_MediaRecord]: + """ + 按 IMDb 标识经 TMDB /find 接口精确查找并补全本地化媒体详情。 + + :param imdb_id: IMDb 条目标识,如 tt27165187 + :param mtype: 限定的电影或电视剧类型;None 或 UNKNOWN 表示由结果判定 + :param season_number: 目标剧集季号,0 表示特别篇,None 表示未指定 + :return: 补齐 media_type、本地化译名与可选季号的 TMDB 详情;未命中或失败时返回 None + """ + normalized_id = self._normalize_imdb_id(imdb_id) + if not normalized_id or not self.find: + return None + if mtype not in (None, MediaType.UNKNOWN, MediaType.MOVIE, MediaType.TV): + return None + try: + found = self.find.find_by_imdb_id(normalized_id) + except TMDbException as err: + logger.error(f"连接TMDB出错:{str(err)}") + return None + except Exception as err: + logger.error(f"连接TMDB出错:{str(err)} - {traceback.format_exc()}") + return None + target = self._select_imdb_find_target(normalized_id, found, mtype, season_number) + if not target: + return None + info = self.get_info(mtype=target.mtype, tmdbid=target.tmdbid) + return self._attach_imdb_find_season(info, target) + def match( self, name: str, @@ -2049,6 +2230,39 @@ class TmdbApi: resolved = await self._resolve_details_async(self._multi_resolution(name, plan)) return self._convert_media_type(resolved) + async def async_match_by_imdb_id( + self, + imdb_id: str, + mtype: Optional[MediaType] = None, + season_number: Optional[int] = None, + ) -> Optional[_MediaRecord]: + """ + 异步按 IMDb 标识经 TMDB /find 接口精确查找并补全本地化媒体详情。 + + :param imdb_id: IMDb 条目标识,如 tt27165187 + :param mtype: 限定的电影或电视剧类型;None 或 UNKNOWN 表示由结果判定 + :param season_number: 目标剧集季号,0 表示特别篇,None 表示未指定 + :return: 补齐 media_type、本地化译名与可选季号的 TMDB 详情;未命中或失败时返回 None + """ + normalized_id = self._normalize_imdb_id(imdb_id) + if not normalized_id or not self.find: + return None + if mtype not in (None, MediaType.UNKNOWN, MediaType.MOVIE, MediaType.TV): + return None + try: + found = await self.find.async_find_by_imdb_id(normalized_id) + except TMDbException as err: + logger.error(f"连接TMDB出错:{str(err)}") + return None + except Exception as err: + logger.error(f"连接TMDB出错:{str(err)} - {traceback.format_exc()}") + return None + target = self._select_imdb_find_target(normalized_id, found, mtype, season_number) + if not target: + return None + info = await self.async_get_info(mtype=target.mtype, tmdbid=target.tmdbid) + return self._attach_imdb_find_season(info, target) + async def async_get_info( self, mtype: Optional[MediaType], tmdbid: int, raise_on_connection_error: bool = False ) -> Optional[_MediaRecord]: @@ -2387,6 +2601,7 @@ class TmdbApi: for client in ( self.tmdb, self.search, + self.find, self.movie, self.tv, self.season_obj, diff --git a/app/modules/themoviedb/tmdbv3api/tmdb.py b/app/modules/themoviedb/tmdbv3api/tmdb.py index 64a67b3f8..0bbf766b6 100644 --- a/app/modules/themoviedb/tmdbv3api/tmdb.py +++ b/app/modules/themoviedb/tmdbv3api/tmdb.py @@ -97,13 +97,24 @@ def _is_business_failure_snapshot(snapshot: object) -> bool: return isinstance(json_data, dict) and json_data.get("success") is False +# /find 外部标识查询接口返回的结果分组字段,全空时与空搜索结果同样走短 TTL 缓存。 +_FIND_RESULT_KEYS = ( + "movie_results", + "person_results", + "tv_results", + "tv_episode_results", + "tv_season_results", +) + + def _is_empty_result_snapshot(snapshot: object) -> bool: """ - 判断响应快照是否为空结果(列表/搜索类接口的 results 为空列表)。 + 判断响应快照是否为空结果(列表/搜索类接口的 results 或 /find 各结果列表均为空)。 - 这类快照结构合法但无业务内容,常由代理瞬时故障产生;不能靠 skip_none/skip_empty - 识别(快照本身是非空字典),需单独谓词判定后按 get_runtime_setting('EMPTY_RESULT_CACHE_TTL') - 短 TTL 缓存。详情类接口无 results 字段,不属于空结果。 + 这类快照结构合法但无业务内容,常由代理瞬时故障或上游尚未补录关联引起;不能靠 + skip_none/skip_empty 识别(快照本身是非空字典),需单独谓词判定后按 + get_runtime_setting('EMPTY_RESULT_CACHE_TTL') 短 TTL 缓存。详情类接口无这类字段, + 不属于空结果。 """ if not isinstance(snapshot, dict): return False @@ -111,7 +122,12 @@ def _is_empty_result_snapshot(snapshot: object) -> bool: if not isinstance(json_data, dict): return False results = json_data.get("results") - return isinstance(results, list) and not results + if isinstance(results, list): + return not results + if "movie_results" in json_data and "tv_results" in json_data: + present_keys = [key for key in _FIND_RESULT_KEYS if key in json_data] + return all(isinstance(json_data[key], list) and not json_data[key] for key in present_keys) + return False def _cache_request(function: _RequestFunction) -> _RequestFunction: diff --git a/app/runtime/extensions/module/contracts.py b/app/runtime/extensions/module/contracts.py index a79227ee9..9e45ada5c 100644 --- a/app/runtime/extensions/module/contracts.py +++ b/app/runtime/extensions/module/contracts.py @@ -153,6 +153,7 @@ _METHOD_CONTRACTS = { result_shape=ModuleResultShape.MAPPING, aggregation=ModuleResultAggregation.FIRST_NON_EMPTY, required_parameters=("name", "mtype", "year", "season"), + optional_parameters=("imdbid",), ), "update_recognize_cache": ModuleMethodContract( family="media-recognition", diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index 415d6ef04..3e21e8dd6 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -851,7 +851,7 @@ flowchart LR | 指标 | 当前值 | |---|---:| | Python 模块 | 1194 | -| 内部导入边 | 10,524 | +| 内部导入边 | 10,525 | | 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) | diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 934a89090..7bdef45fe 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -978,8 +978,8 @@ "runtime_only": true } }, - "edge_count": 10524, - "edge_sha256": "51067d3a051ddd91b2c89819b815f71a4e9dbeb95e2572a3fa6315263ca2e39e", + "edge_count": 10525, + "edge_sha256": "013377dfdc2a13d76045e0d071283ecd4e3225fa7c1e3a609ee573e6bb44bdb4", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -2697,6 +2697,7 @@ "app.api.endpoints.download -> app.schemas.context", "app.api.endpoints.download -> app.schemas.download", "app.api.endpoints.download -> app.schemas.file", + "app.api.endpoints.download -> app.schemas.media", "app.api.endpoints.download -> app.schemas.music", "app.api.endpoints.download -> app.schemas.response", "app.api.endpoints.download -> app.schemas.token", diff --git a/tests/fixtures/architecture/runtime-contract-baseline.json b/tests/fixtures/architecture/runtime-contract-baseline.json index 759fd728e..83fd4b7b0 100644 --- a/tests/fixtures/architecture/runtime-contract-baseline.json +++ b/tests/fixtures/architecture/runtime-contract-baseline.json @@ -4564,7 +4564,9 @@ "execution": "sync_or_async", "family": "media-recognition", "input_contract": "TmdbMatchRequest", - "optional_parameters": [], + "optional_parameters": [ + "imdbid" + ], "plugin_short_circuit": true, "public_to_plugins": true, "required_parameters": [ @@ -6592,7 +6594,9 @@ "execution": "sync_or_async", "family": "media-recognition", "input_contract": "TmdbMatchRequest", - "optional_parameters": [], + "optional_parameters": [ + "imdbid" + ], "plugin_short_circuit": true, "public_to_plugins": true, "required_parameters": [ diff --git a/tests/test_download_media_source.py b/tests/test_download_media_source.py index 6d12758cb..ee458ad40 100644 --- a/tests/test_download_media_source.py +++ b/tests/test_download_media_source.py @@ -220,3 +220,333 @@ def test_subtitle_download_passes_generic_media_source(monkeypatch) -> None: assert response.success is True assert captured["media_source"] == "anilist" assert captured["media_id"] == "154587" + + +def _patch_recognize_source(monkeypatch, source: str) -> None: + """ + 在当前用例中隔离替换 RECOGNIZE_SOURCE 配置值。 + """ + monkeypatch.setattr( + download_endpoint, + "get_runtime_settings", + lambda: SimpleNamespace(get=lambda key, default=None: source if key == "RECOGNIZE_SOURCE" else default), + ) + + +def test_download_add_converts_imdb_site_resource_to_tmdb_when_recognize_source_is_tmdb( + monkeypatch, +) -> None: + """ + RECOGNIZE_SOURCE=themoviedb 时,站点资源携带的 IMDb 身份应转为 TMDB 主身份并保留中文标题。 + """ + _patch_recognize_source(monkeypatch, "themoviedb") + captured: dict = {"recognize": []} + tmdb_media = MediaInfo( + tmdb_info={ + "id": 1101383, + "media_type": MediaType.MOVIE, + "title": "逃出绝命街", + "original_title": "The End of Oak Street", + "release_date": "2026-01-01", + } + ) + + class FakeMediaChain: + """ + 模拟 IMDb 到 TMDB 的身份投影和本地化识别。 + """ + + def convert_media_identity(self, **kwargs): + """ + 记录投影调用并返回对应的 TMDB 电影详情。 + """ + captured["convert"] = kwargs + return {"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + + def recognize_media(self, **kwargs): + """ + 记录每次识别参数并按 TMDB 身份返回中文电影信息。 + """ + captured["recognize"].append(kwargs) + assert kwargs["media_source"] == MediaSource.TMDB + assert kwargs["media_id"] == "1101383" + return tmdb_media + + class FakeDownloadChain: + """ + 记录最终提交到下载链的上下文。 + """ + + def download_single(self, **kwargs): + """ + 保存下载上下文并返回任务 ID。 + """ + captured["download"] = kwargs + return "download-tmdb" + + monkeypatch.setattr(download_endpoint, "MediaChain", FakeMediaChain) + monkeypatch.setattr(download_endpoint, "DownloadChain", FakeDownloadChain) + + response = download_endpoint.add( + torrent_in=schemas.TorrentInfo( + title="The.End.of.Oak.Street.2026.1080p.WEB-DL", + category=MediaType.MOVIE.value, + media_source=MediaSource.IMDb, + media_id="tt27165187", + ), + media_source=MediaSource.IMDb, + media_id="tt27165187", + current_user=SimpleNamespace(name="tester"), + ) + + assert response.success is True + assert captured["convert"] == { + "target_source": MediaSource.TMDB, + "media_source": MediaSource.IMDb, + "media_id": "tt27165187", + "season": None, + } + assert len(captured["recognize"]) == 1 + assert captured["recognize"][0]["mtype"] == MediaType.MOVIE + context = captured["download"]["context"] + assert context.media_info is tmdb_media + assert context.media_info.media_source == MediaSource.TMDB + assert context.media_info.media_id == "1101383" + assert context.media_info.title == "逃出绝命街" + + +def test_download_add_converts_manual_imdb_id_and_fills_projected_tv_season(monkeypatch) -> None: + """ + 手动提交 IMDb 剧集/单集标识时,应转为 TMDB 剧集身份并在标题缺季号时补齐投影季号。 + """ + _patch_recognize_source(monkeypatch, "tmdb") + captured: dict = {} + tmdb_media = MediaInfo( + tmdb_info={ + "id": 209867, + "media_type": MediaType.TV, + "name": "葬送的芙莉莲", + "first_air_date": "2023-09-29", + } + ) + + class FakeMediaChain: + """ + 模拟返回带季号的 TMDB 剧集投影与识别。 + """ + + def convert_media_identity(self, **kwargs): + """ + 返回带第二季信息的剧集投影结果。 + """ + captured["convert"] = kwargs + return {"id": 209867, "media_type": MediaType.TV, "season": 2} + + def recognize_media(self, **kwargs): + """ + 保存传给 TMDB 识别的元数据与参数。 + """ + captured["recognize"] = kwargs + return tmdb_media + + download_chain = Mock() + download_chain.download_single.return_value = "download-tv" + monkeypatch.setattr(download_endpoint, "MediaChain", FakeMediaChain) + monkeypatch.setattr(download_endpoint, "DownloadChain", lambda: download_chain) + + response = download_endpoint.add( + torrent_in=schemas.TorrentInfo(title="Frieren Special"), + media_source="imdb", + media_id="tt29000001", + current_user=SimpleNamespace(name="tester"), + ) + + assert response.success is True + assert captured["recognize"]["media_source"] == MediaSource.TMDB + assert captured["recognize"]["media_id"] == "209867" + assert captured["recognize"]["mtype"] == MediaType.TV + context = download_chain.download_single.call_args.kwargs["context"] + assert context.meta_info.begin_season == 2 + assert context.media_info is tmdb_media + + +def test_download_add_converts_torrent_embedded_douban_identity_to_tmdb(monkeypatch) -> None: + """ + 站点资源自带豆瓣身份且默认识别源为 TMDB 时,同样优先转换为 TMDB 整剧身份。 + """ + _patch_recognize_source(monkeypatch, "themoviedb") + tmdb_media = MediaInfo( + tmdb_info={ + "id": 124101, + "media_type": MediaType.TV, + "name": "绝望写手", + "first_air_date": "2021-05-13", + } + ) + 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-to-tmdb" + 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="Hacks.S03E01.1080p.WEB-DL", + media_source=MediaSource.Douban, + media_id="35932853", + ), + media_source=MediaSource.Douban, + media_id="35932853", + 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", + season=3, + ) + assert media_chain.recognize_media.call_args.kwargs["media_source"] == MediaSource.TMDB + assert media_chain.recognize_media.call_args.kwargs["media_id"] == "124101" + context = download_chain.download_single.call_args.kwargs["context"] + assert context.media_info is tmdb_media + + +def test_download_add_falls_back_to_imdb_without_polluting_meta_when_tmdb_fails(monkeypatch) -> None: + """ + TMDB 投影失败或 TMDB 识别失败时,应保留未污染的原元数据并回退 IMDb 识别结果。 + """ + _patch_recognize_source(monkeypatch, "themoviedb") + imdb_media = MediaInfo( + media_source=MediaSource.IMDb, + media_id="tt27165187", + type=MediaType.MOVIE, + title="The End of Oak Street", + ) + recognize_calls: list[dict] = [] + + class FakeMediaChain: + """ + 模拟 TMDB 识别先修改元数据后失败,再回退 IMDb 识别成功。 + """ + + @staticmethod + def convert_media_identity(**_kwargs): + """ + 返回 TMDB 候选以触发 TMDB 识别路径。 + """ + return {"id": 1101383, "media_type": MediaType.MOVIE} + + @staticmethod + def recognize_media(**kwargs): + """ + TMDB 识别模拟写入元数据后失败,IMDb 识别返回英文媒体信息。 + """ + recognize_calls.append(kwargs) + if kwargs["media_source"] == MediaSource.TMDB: + kwargs["meta"].media_source = MediaSource.TMDB + kwargs["meta"].media_id = "1101383" + return None + return imdb_media + + download_chain = Mock() + download_chain.download_single.return_value = "download-fallback" + monkeypatch.setattr(download_endpoint, "MediaChain", FakeMediaChain) + 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 + assert [call["media_source"] for call in recognize_calls] == [ + MediaSource.TMDB, + MediaSource.IMDb, + ] + fallback_meta = recognize_calls[1]["meta"] + assert fallback_meta.media_source is None + assert fallback_meta.media_id is None + context = download_chain.download_single.call_args.kwargs["context"] + assert context.media_info is imdb_media + + +def test_download_add_keeps_imdb_when_recognize_source_is_not_tmdb(monkeypatch) -> None: + """ + 当系统 RECOGNIZE_SOURCE 不是 TMDB 时,下载接口不应强制转换 IMDb 身份。 + """ + _patch_recognize_source(monkeypatch, "imdb") + imdb_media = MediaInfo( + media_source=MediaSource.IMDb, + media_id="tt27165187", + type=MediaType.MOVIE, + title="The End of Oak Street", + ) + media_chain = Mock() + media_chain.recognize_media.return_value = imdb_media + download_chain = Mock() + download_chain.download_single.return_value = "download-imdb" + 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 + media_chain.convert_media_identity.assert_not_called() + assert media_chain.recognize_media.call_args.kwargs["media_source"] == MediaSource.IMDb + assert media_chain.recognize_media.call_args.kwargs["media_id"] == "tt27165187" + assert download_chain.download_single.call_args.kwargs["context"].media_info is imdb_media + + +def test_download_add_skips_conversion_when_source_is_already_tmdb(monkeypatch) -> None: + """ + 已是 TMDB 身份的下载请求直接识别,不重复触发跨来源投影。 + """ + _patch_recognize_source(monkeypatch, "themoviedb") + tmdb_media = MediaInfo( + tmdb_info={"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + ) + media_chain = Mock() + media_chain.recognize_media.return_value = tmdb_media + download_chain = Mock() + download_chain.download_single.return_value = "download-already-tmdb" + 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.TMDB, + media_id="1101383", + ), + media_source=MediaSource.TMDB, + media_id="1101383", + current_user=SimpleNamespace(name="tester"), + ) + + assert response.success is True + 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" diff --git a/tests/test_media_identity_projection.py b/tests/test_media_identity_projection.py index ebce2db50..4ef9cdc0a 100644 --- a/tests/test_media_identity_projection.py +++ b/tests/test_media_identity_projection.py @@ -3,9 +3,21 @@ MediaChain 跨来源身份投影的同步、异步对称性测试。 """ import asyncio +from types import SimpleNamespace from typing import Any, Optional +from unittest.mock import AsyncMock, Mock +from app.application.server.mapping import ( + configure_media_mapping_port, + get_media_mapping_port, +) +from app.application.subscription.contract import SubscriptionSnapshot from app.chain.media import MediaChain +from app.chain.subscribe.metadata import SubscribeMetadataOwner +from app.domain.context import MediaInfo +from app.domain.metainfo import MetaInfo +from app.runtime.extensions.module.dispatcher import ModuleInvocationDispatcher +from app.schemas.mapping import MediaMapping, MediaMappingQuery from app.schemas.types import MediaSource, MediaType @@ -19,8 +31,17 @@ class _SyncProjectionChain: 初始化固定来源详情和调用记录。 """ self.tmdb_match: dict[str, Any] = {} + self.imdb_tmdb_match: dict[str, Any] = {} self.douban_match: dict[str, Any] = {} self.tmdb_result = {"id": 550, "media_type": "tv"} + self.imdb_tmdb_result = {"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + + def match_tmdbinfo(self, **kwargs: Any) -> dict[str, Any]: + """ + 记录直接 TMDB 匹配参数并返回模拟电影详情。 + """ + self.imdb_tmdb_match = kwargs + return self.imdb_tmdb_result @staticmethod def douban_info( @@ -85,8 +106,17 @@ class _AsyncProjectionChain: 初始化固定来源详情和调用记录。 """ self.tmdb_match: dict[str, Any] = {} + self.imdb_tmdb_match: dict[str, Any] = {} self.douban_match: dict[str, Any] = {} self.tmdb_result = {"id": 550, "media_type": "tv"} + self.imdb_tmdb_result = {"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + + async def async_match_tmdbinfo(self, **kwargs: Any) -> dict[str, Any]: + """ + 异步记录直接 TMDB 匹配参数并返回模拟电影详情。 + """ + self.imdb_tmdb_match = kwargs + return self.imdb_tmdb_result async def async_douban_info( self, @@ -217,3 +247,299 @@ def test_async_tmdb_to_douban_matches_sync_projection() -> None: assert result == {"id": "1295644", "media_type": "tv"} assert chain.douban_match["year"] == "2025" assert chain.douban_match["imdbid"] == "tt0000550" + + +def test_imdb_to_tmdb_sync_and_async_normalize_id_and_share_mapping() -> None: + """ + IMDb 转 TMDB 应规范化标识、直连 match_tmdbinfo 并在同步与异步入口共享映射上报。 + """ + previous_port = get_media_mapping_port() + port = SimpleNamespace( + query=Mock(return_value=None), + async_query=AsyncMock(return_value=None), + share=Mock(), + ) + configure_media_mapping_port(port) + try: + sync_chain = _SyncProjectionChain() + sync_result = MediaChain.convert_media_identity( + sync_chain, + target_source=MediaSource.TMDB, + media_source=MediaSource.IMDb, + media_id=" TT27165187 ", + mtype=MediaType.MOVIE, + ) + assert sync_result == {"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + assert sync_chain.imdb_tmdb_match == { + "name": "", + "mtype": MediaType.MOVIE, + "season": None, + "imdbid": "tt27165187", + } + + async_chain = _AsyncProjectionChain() + async_result = asyncio.run( + MediaChain.async_convert_media_identity( + async_chain, + target_source=MediaSource.TMDB, + media_source=MediaSource.IMDb, + media_id="TT27165187", + mtype=MediaType.MOVIE, + ) + ) + assert async_result == sync_result + assert async_chain.imdb_tmdb_match == sync_chain.imdb_tmdb_match + assert port.query.call_args.args[0] == MediaMappingQuery( + media_source=MediaSource.IMDb, + media_id="tt27165187", + type="movie", + ) + assert port.share.call_count == 2 + assert port.share.call_args.args[0] == MediaMapping( + media_source=MediaSource.IMDb, + media_id="tt27165187", + type="movie", + tmdb_id=1101383, + tmdb_type="movie", + tmdb_season=None, + ) + finally: + configure_media_mapping_port(previous_port) + + +def test_imdb_to_tmdb_rejects_invalid_id_without_calling_tmdb() -> None: + """ + 非 tt 数字格式的 IMDb 标识在投影规划阶段直接拒绝,不发起模块查询。 + """ + sync_chain = _SyncProjectionChain() + async_chain = _AsyncProjectionChain() + + assert ( + MediaChain.convert_media_identity( + sync_chain, + target_source=MediaSource.TMDB, + media_source=MediaSource.IMDb, + media_id="27165187", + ) + is None + ) + assert ( + asyncio.run( + MediaChain.async_convert_media_identity( + async_chain, + target_source=MediaSource.TMDB, + media_source=MediaSource.IMDb, + media_id="invalid", + ) + ) + is None + ) + assert sync_chain.imdb_tmdb_match == {} + assert async_chain.imdb_tmdb_match == {} + + +def test_match_tmdbinfo_dispatcher_keeps_legacy_provider_compatible() -> None: + """ + 不接受可选 imdbid 的旧 provider 应被安全过滤参数并继续回退到支持 imdbid 的模块。 + """ + legacy_calls: list[dict[str, Any]] = [] + modern_calls: list[dict[str, Any]] = [] + + class _LegacyProvider: + """ + 模拟仅声明原有四参数的旧 match_tmdbinfo 插件。 + """ + + @staticmethod + def get_name() -> str: + """ + 返回旧插件名称。 + """ + return "LegacyProvider" + + @staticmethod + def get_priority() -> int: + """ + 设置较高优先级以确保先于默认模块执行。 + """ + return 0 + + @staticmethod + def match_tmdbinfo(name: str, mtype=None, year=None, season=None): + """ + 仅接受旧四参数,空名称时返回空以交由后续模块处理。 + """ + legacy_calls.append({"name": name, "mtype": mtype, "year": year, "season": season}) + return None + + @staticmethod + async def async_match_tmdbinfo(name: str, mtype=None, year=None, season=None): + """ + 异步仅接受旧四参数,空名称时返回空以交由后续模块处理。 + """ + legacy_calls.append({"name": name, "mtype": mtype, "year": year, "season": season}) + return None + + class _ModernProvider: + """ + 模拟支持 imdbid 的 TMDB 宿主模块。 + """ + + @staticmethod + def get_name() -> str: + """ + 返回宿主模块名称。 + """ + return "ModernProvider" + + @staticmethod + def get_priority() -> int: + """ + 设置低于旧插件的优先级以验证回退。 + """ + return 1 + + @staticmethod + def match_tmdbinfo(name: str = "", mtype=None, year=None, season=None, imdbid=None): + """ + 记录收到的完整参数并返回匹配的 TMDB 详情。 + """ + modern_calls.append( + {"name": name, "mtype": mtype, "year": year, "season": season, "imdbid": imdbid} + ) + return {"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + + @staticmethod + async def async_match_tmdbinfo( + name: str = "", mtype=None, year=None, season=None, imdbid=None + ): + """ + 异步记录收到的完整参数并返回匹配的 TMDB 详情。 + """ + modern_calls.append( + {"name": name, "mtype": mtype, "year": year, "season": season, "imdbid": imdbid} + ) + return {"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + + module_manager = Mock() + module_manager.get_running_modules.return_value = [_LegacyProvider(), _ModernProvider()] + plugin_manager = Mock() + plugin_manager.get_plugin_modules.return_value = {} + chain = object.__new__(MediaChain) + chain._module_dispatcher = ModuleInvocationDispatcher( + module_catalog=module_manager, + plugin_catalog=plugin_manager, + plugin_error_handler=lambda *args, **kwargs: None, + system_error_handler=lambda *args, **kwargs: None, + rate_limit_handler=lambda *args, **kwargs: None, + ) + + result = chain.match_tmdbinfo( + name="", + mtype=None, + year=None, + season=None, + imdbid="tt27165187", + ) + async_result = asyncio.run( + chain.async_match_tmdbinfo( + name="", + mtype=None, + year=None, + season=None, + imdbid="tt27165187", + ) + ) + + expected = {"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + assert result == expected + assert async_result == expected + assert legacy_calls == [ + {"name": "", "mtype": None, "year": None, "season": None}, + {"name": "", "mtype": None, "year": None, "season": None}, + ] + assert modern_calls == [ + {"name": "", "mtype": None, "year": None, "season": None, "imdbid": "tt27165187"}, + {"name": "", "mtype": None, "year": None, "season": None, "imdbid": "tt27165187"}, + ] + + +def test_subscribe_metadata_retry_converts_imdb_subscription_to_tmdb() -> None: + """ + 订阅元数据巡检应对保留 IMDb 身份的订阅重试 TMDB 身份转换。 + """ + subscribe = SubscriptionSnapshot( + id=88, + name="The End of Oak Street", + year="2026", + type=MediaType.MOVIE.value, + media_source=MediaSource.IMDb.value, + media_id="tt27165187", + ) + meta = MetaInfo("The End of Oak Street 2026") + meta.type = MediaType.MOVIE + tmdb_media = MediaInfo( + tmdb_info={ + "id": 1101383, + "media_type": MediaType.MOVIE, + "title": "逃出绝命街", + "release_date": "2026-01-01", + "vote_average": 7.5, + } + ) + media_chain = SimpleNamespace( + convert_media_identity=Mock( + return_value={"id": 1101383, "media_type": MediaType.MOVIE, "title": "逃出绝命街"} + ), + recognize_media=Mock(return_value=tmdb_media), + ) + updates: list[dict[str, Any]] = [] + + class _Owner(SubscribeMetadataOwner): + """ + 隔离订阅持久化写入的最小元数据巡检测试替身。 + """ + + @staticmethod + def _SubscribeChain__is_tmdb_recognize_source() -> bool: + """ + 固定模拟当前识别源为 TMDB。 + """ + return True + + @staticmethod + def _SubscribeChain__apply_subscribe_update( + current: SubscriptionSnapshot, + update_data: dict[str, Any], + *, + scene: str, + ) -> SubscriptionSnapshot: + """ + 记录更新字段并返回模拟更新后的快照。 + """ + assert scene == "identity_refresh" + updates.append(update_data) + return SubscriptionSnapshot( + id=current.id, + name=update_data["name"], + year=update_data["year"], + type=current.type, + media_source=MediaSource.TMDB.value, + media_id=update_data["media_id"], + ) + + updated = _Owner()._retry_subscribe_media_identity(subscribe, meta, lambda: media_chain) + + assert updated is not None + assert updated.media_source == MediaSource.TMDB.value + assert updated.media_id == "1101383" + assert updated.name == "逃出绝命街" + assert updates[0]["media_source"] == MediaSource.TMDB + assert updates[0]["media_id"] == "1101383" + media_chain.convert_media_identity.assert_called_once_with( + target_source=MediaSource.TMDB, + media_source=MediaSource.IMDb, + media_id="tt27165187", + mtype=MediaType.MOVIE, + season=None, + ) diff --git a/tests/test_tmdb_empty_result_cache.py b/tests/test_tmdb_empty_result_cache.py index cb70b0cc1..11c1edffb 100644 --- a/tests/test_tmdb_empty_result_cache.py +++ b/tests/test_tmdb_empty_result_cache.py @@ -57,6 +57,28 @@ def test_empty_result_snapshot_predicate(): """ assert _is_empty_result_snapshot(_snapshot(EMPTY_PAYLOAD)) assert not _is_empty_result_snapshot(_snapshot(NOT_EMPTY_PAYLOAD)) + assert _is_empty_result_snapshot( + _snapshot( + { + "movie_results": [], + "person_results": [], + "tv_results": [], + "tv_episode_results": [], + "tv_season_results": [], + } + ) + ) + assert not _is_empty_result_snapshot( + _snapshot( + { + "movie_results": [{"id": 1101383}], + "person_results": [], + "tv_results": [], + "tv_episode_results": [], + "tv_season_results": [], + } + ) + ) assert not _is_empty_result_snapshot(_snapshot({"id": 98865, "title": "Test"})) # json 非字典或无 results 字段时不能误判为空结果 assert not _is_empty_result_snapshot(_snapshot("upstream error")) diff --git a/tests/test_tmdb_sync_async_parity.py b/tests/test_tmdb_sync_async_parity.py index 45c44c3e0..9ec1c615b 100644 --- a/tests/test_tmdb_sync_async_parity.py +++ b/tests/test_tmdb_sync_async_parity.py @@ -491,3 +491,33 @@ def test_obtain_images_sync_async_skip_ineligible_media( assert asyncio.run(module.async_obtain_images(media)) is media assert media.to_dict() == original assert module.tmdb.mock_calls == [] + + +def test_match_tmdbinfo_sync_async_prefer_imdb_and_fallback_only_with_name() -> None: + """ + 提供 IMDb 标识时优先精确查找;未命中仅在有名称时回退名称匹配。 + """ + module = _module_with_clients() + imdb_hit = _movie_info(1101383) + module.tmdb.match_by_imdb_id.return_value = imdb_hit + module.tmdb.async_match_by_imdb_id = AsyncMock(return_value=imdb_hit) + + assert module.match_tmdbinfo(imdbid="tt27165187") == imdb_hit + assert asyncio.run(module.async_match_tmdbinfo(imdbid="tt27165187")) == imdb_hit + module.tmdb.match.assert_not_called() + module.tmdb.async_match.assert_not_called() + + module.tmdb.match_by_imdb_id.return_value = None + module.tmdb.async_match_by_imdb_id = AsyncMock(return_value=None) + assert module.match_tmdbinfo(imdbid="tt27165187") is None + assert asyncio.run(module.async_match_tmdbinfo(imdbid="tt27165187")) is None + module.tmdb.match.assert_not_called() + module.tmdb.async_match.assert_not_called() + + name_hit = _movie_info(42) + module.tmdb.match.return_value = name_hit + module.tmdb.async_match = AsyncMock(return_value=name_hit) + assert module.match_tmdbinfo(name="逃出绝命街", imdbid="tt27165187") == name_hit + assert asyncio.run(module.async_match_tmdbinfo(name="逃出绝命街", imdbid="tt27165187")) == name_hit + module.tmdb.match.assert_called_once() + module.tmdb.async_match.assert_awaited_once() diff --git a/tests/test_tmdbapi_sync_async_parity.py b/tests/test_tmdbapi_sync_async_parity.py index 81bf48ee8..e0cec20d4 100644 --- a/tests/test_tmdbapi_sync_async_parity.py +++ b/tests/test_tmdbapi_sync_async_parity.py @@ -35,6 +35,7 @@ def _api() -> TmdbApi: collections=Mock(), async_collections=AsyncMock(), ) + api.find = SimpleNamespace(find_by_imdb_id=Mock(), async_find_by_imdb_id=AsyncMock()) api.movie = SimpleNamespace(details=Mock(), async_details=AsyncMock()) api.tv = SimpleNamespace(details=Mock(), async_details=AsyncMock()) return api @@ -395,3 +396,148 @@ def test_get_info_sync_async_propagate_connection_error_at_same_boundary() -> No api.get_info(MediaType.MOVIE, 50, raise_on_connection_error=True) with pytest.raises(TMDbConnectionError): asyncio.run(api.async_get_info(MediaType.MOVIE, 50, raise_on_connection_error=True)) + + +@pytest.mark.parametrize( + ("found", "mtype", "season", "expected_type", "expected_id", "expected_season"), + [ + ( + {"movie_results": [{"id": 1101383}], "tv_results": []}, + None, + None, + MediaType.MOVIE, + 1101383, + None, + ), + ( + {"movie_results": [{"id": 1101383}], "tv_results": []}, + None, + 1, + MediaType.MOVIE, + 1101383, + None, + ), + ( + {"movie_results": [], "tv_results": [{"id": 209867}]}, + None, + 0, + MediaType.TV, + 209867, + 0, + ), + ( + {"movie_results": [], "tv_results": [], "tv_season_results": [{"show_id": 209867, "season_number": 2}]}, + None, + None, + MediaType.TV, + 209867, + 2, + ), + ( + {"movie_results": [], "tv_results": [], "tv_episode_results": [{"show_id": 209867, "season_number": 3}]}, + MediaType.TV, + None, + MediaType.TV, + 209867, + 3, + ), + ( + {"movie_results": [], "tv_results": [], "tv_episode_results": [{"show_id": 209867, "season_number": 3}]}, + MediaType.TV, + 1, + MediaType.TV, + 209867, + 1, + ), + ( + {"movie_results": [{"id": 1101383}], "tv_results": [{"id": 209867}]}, + MediaType.MOVIE, + None, + MediaType.MOVIE, + 1101383, + None, + ), + ( + {"movie_results": [{"id": 1101383}], "tv_results": [{"id": 209867}]}, + None, + 2, + MediaType.TV, + 209867, + 2, + ), + ], +) +def test_match_by_imdb_id_sync_async_resolve_target_and_details( + found: dict, + mtype: Optional[MediaType], + season: Optional[int], + expected_type: MediaType, + expected_id: int, + expected_season: Optional[int], +) -> None: + """ + IMDb 外部标识查找在同步与异步入口应共享目标选取、完整详情补全和季号语义。 + """ + api = _api() + api.find.find_by_imdb_id.return_value = found + api.find.async_find_by_imdb_id.return_value = found + api.movie.details.return_value = _movie_detail(expected_id, "逃出绝命街") + api.movie.async_details.return_value = _movie_detail(expected_id, "逃出绝命街") + api.tv.details.return_value = _tv_detail(expected_id, "示例剧") + api.tv.async_details.return_value = _tv_detail(expected_id, "示例剧") + + sync_result = api.match_by_imdb_id(" TT27165187 ", mtype=mtype, season_number=season) + async_result = asyncio.run(api.async_match_by_imdb_id(" TT27165187 ", mtype=mtype, season_number=season)) + + assert sync_result == async_result + assert sync_result is not None + assert sync_result["id"] == expected_id + assert sync_result["media_type"] == expected_type + if expected_season is None: + assert "season" not in sync_result + else: + assert sync_result["season"] == expected_season + api.find.find_by_imdb_id.assert_called_once_with("tt27165187") + api.find.async_find_by_imdb_id.assert_awaited_once_with("tt27165187") + + +@pytest.mark.parametrize( + ("imdb_id", "found", "mtype"), + [ + ("12345", {"movie_results": [{"id": 1}]}, None), + ("tt", {"movie_results": [{"id": 1}]}, None), + ("tt27165187", {"movie_results": [{"id": 1}]}, MediaType.MUSIC), + ("tt27165187", {"movie_results": [{"id": 1}], "tv_results": [{"id": 2}]}, None), + ("tt27165187", {"movie_results": [], "tv_results": [{"id": 2}]}, MediaType.MOVIE), + ("tt27165187", {"movie_results": [{"id": 1}], "tv_results": []}, MediaType.TV), + ("tt27165187", None, None), + ], +) +def test_match_by_imdb_id_sync_async_reject_invalid_mismatched_and_ambiguous_results( + imdb_id: str, + found: Optional[dict], + mtype: Optional[MediaType], +) -> None: + """ + 无效 IMDb 标识、类型冲突及无季号歧义在同步与异步入口均应返回空值。 + """ + api = _api() + api.find.find_by_imdb_id.return_value = found + api.find.async_find_by_imdb_id.return_value = found + + assert api.match_by_imdb_id(imdb_id, mtype=mtype) is None + assert asyncio.run(api.async_match_by_imdb_id(imdb_id, mtype=mtype)) is None + api.movie.details.assert_not_called() + api.tv.details.assert_not_called() + + +def test_match_by_imdb_id_sync_async_handle_client_errors() -> None: + """ + TMDB /find 接口异常时双入口均安全返回空值。 + """ + api = _api() + api.find.find_by_imdb_id.side_effect = TMDbException("boom") + api.find.async_find_by_imdb_id.side_effect = RuntimeError("network") + + assert api.match_by_imdb_id("tt27165187") is None + assert asyncio.run(api.async_match_by_imdb_id("tt27165187")) is None