mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-02 00:46:27 +08:00
feat(media): 共享并缓存非 TMDB 到 TMDB 的转换关系 (#7440)
* feat(media): reuse shared source to TMDB mappings * test(media): cover shared target fallback and invalid reports
This commit is contained in:
236
app/adapters/external/mapping.py
vendored
Normal file
236
app/adapters/external/mapping.py
vendored
Normal file
@@ -0,0 +1,236 @@
|
||||
"""
|
||||
带有界本地缓存、故障冷却和总超时的中心媒体关系客户端。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import concurrent.futures
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from typing import Any, cast
|
||||
|
||||
from app.adapters.network.http import AsyncHttpRequestError, AsyncRequestUtils
|
||||
from app.runtime.loop import main_loop_registry
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.runtime.tasks import get_task_registry
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingQuery
|
||||
|
||||
# 查询总预算包含 DNS、重定向、连接、读取和传输层重试。
|
||||
QUERY_TIMEOUT = 0.8
|
||||
REPORT_TIMEOUT = 0.5
|
||||
POSITIVE_TTL = 3600
|
||||
NEGATIVE_TTL = 600
|
||||
FAILURE_TTL = 30
|
||||
CACHE_LIMIT = 4096
|
||||
INFLIGHT_LIMIT = 8
|
||||
|
||||
|
||||
class MediaMappingClient:
|
||||
"""
|
||||
同异步调用共用进程缓存,中心故障不会阻塞正常转换和详情加载。
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
建立有界缓存、在途集合与跨线程保护锁。
|
||||
"""
|
||||
self._cache: OrderedDict[str, tuple[float, MediaMapping | None]] = OrderedDict()
|
||||
self._inflight: set[str] = set()
|
||||
self._queries: dict[str, concurrent.futures.Future[MediaMapping | None]] = {}
|
||||
self._lock = threading.Lock()
|
||||
self._retry_at = 0.0
|
||||
|
||||
@staticmethod
|
||||
def _url() -> str | None:
|
||||
"""
|
||||
沿用共享识别开关,始终向配置的 Server 查询持久关系。
|
||||
|
||||
:return: 中心关系接口,未启用时为 None
|
||||
"""
|
||||
host = (get_runtime_setting("MP_SERVER_HOST") or "").strip().rstrip("/")
|
||||
return f"{host}/recognize/mapping" if host and get_runtime_setting("MEDIA_RECOGNIZE_SHARE") else None
|
||||
|
||||
@staticmethod
|
||||
def _key(url: str, query: MediaMappingQuery) -> str:
|
||||
"""
|
||||
隔离 Server 地址、来源、ID、类型和季号不同的缓存。
|
||||
|
||||
:param url: 当前中心接口地址
|
||||
:param query: 关系查询
|
||||
:return: 无分隔符碰撞的规范 JSON 键
|
||||
"""
|
||||
return url + ":" + query.model_dump_json()
|
||||
|
||||
def _remember(self, key: str, value: MediaMapping | None, ttl: int) -> None:
|
||||
"""
|
||||
记录命中或未命中并淘汰最久未访问条目,调用方持有锁。
|
||||
|
||||
:param key: 查询键
|
||||
:param value: 已验证关系或负缓存
|
||||
:param ttl: 有效秒数
|
||||
"""
|
||||
self._cache[key] = (time.monotonic() + ttl, value)
|
||||
self._cache.move_to_end(key)
|
||||
while len(self._cache) > CACHE_LIMIT:
|
||||
self._cache.popitem(last=False)
|
||||
|
||||
async def _request(self, url: str, payload: dict[str, Any], *, report: bool = False) -> MediaMapping | None:
|
||||
"""
|
||||
在总时间预算内完成一次请求并验证外部响应,失败进入全局短冷却。
|
||||
|
||||
:param url: 中心接口地址
|
||||
:param payload: 来源查询或共享关系
|
||||
:param report: 是否发送共享写入
|
||||
:return: 中心确认的关系或未命中
|
||||
"""
|
||||
try:
|
||||
async with asyncio.timeout(REPORT_TIMEOUT if report else QUERY_TIMEOUT):
|
||||
client = AsyncRequestUtils(http2=False, timeout=REPORT_TIMEOUT if report else QUERY_TIMEOUT,
|
||||
proxies=get_runtime_setting("PROXY"), verify=True, follow_redirects=False)
|
||||
if report:
|
||||
response = await client.post(url, json=payload)
|
||||
else:
|
||||
response = await client.get_res(url, params=payload)
|
||||
if response is None or response.status_code != 200:
|
||||
raise ValueError("中心关系服务不可用")
|
||||
data = response.json()
|
||||
if not isinstance(data, dict) or data.get("code") != 0 or not isinstance(data.get("data"), dict):
|
||||
raise ValueError("中心关系响应无效")
|
||||
item = data["data"].get("item")
|
||||
return MediaMapping.model_validate(item) if item is not None else None
|
||||
except (TimeoutError, ValueError, TypeError, OSError, AsyncHttpRequestError):
|
||||
with self._lock:
|
||||
self._retry_at = time.monotonic() + FAILURE_TTL
|
||||
return None
|
||||
|
||||
async def async_query(self, query: MediaMappingQuery) -> MediaMapping | None:
|
||||
"""
|
||||
优先复用本地正负缓存,合并在途键并在故障冷却期间跳过请求。
|
||||
|
||||
:param query: 原来源身份与上下文
|
||||
:return: 匹配当前请求的共享关系,未命中或故障为 None
|
||||
"""
|
||||
url = self._url()
|
||||
if not url:
|
||||
return None
|
||||
key = self._key(url, query)
|
||||
with self._lock:
|
||||
cached = self._cache.get(key)
|
||||
if cached and cached[0] > time.monotonic():
|
||||
self._cache.move_to_end(key)
|
||||
return cached[1].model_copy(deep=True) if cached[1] else None
|
||||
pending = self._queries.get(key)
|
||||
if pending is None and (time.monotonic() < self._retry_at or key in self._inflight
|
||||
or len(self._inflight) >= INFLIGHT_LIMIT):
|
||||
return None
|
||||
if pending is None:
|
||||
self._inflight.add(key)
|
||||
completion: concurrent.futures.Future[MediaMapping | None] = concurrent.futures.Future()
|
||||
self._queries[key] = completion
|
||||
if pending is not None:
|
||||
try:
|
||||
# 不让一个请求的取消传递给其他调用方正在使用的中心查询。
|
||||
result = await asyncio.wait_for(asyncio.shield(asyncio.wrap_future(pending)), timeout=QUERY_TIMEOUT)
|
||||
return result.model_copy(deep=True) if result else None
|
||||
except TimeoutError:
|
||||
return None
|
||||
result = None
|
||||
try:
|
||||
result = await self._request(url, query.model_dump(mode="json", exclude_none=True))
|
||||
if result and (result.media_source != query.media_source or result.media_id != query.media_id
|
||||
or (query.type and result.type != query.type)
|
||||
or (query.season is not None and result.season not in (None, query.season))):
|
||||
result = None
|
||||
with self._lock:
|
||||
ttl = FAILURE_TTL if time.monotonic() < self._retry_at else POSITIVE_TTL if result else NEGATIVE_TTL
|
||||
self._remember(key, result, ttl)
|
||||
return result.model_copy(deep=True) if result else None
|
||||
finally:
|
||||
with self._lock:
|
||||
self._inflight.discard(key)
|
||||
self._queries.pop(key, None)
|
||||
completion.set_result(result)
|
||||
|
||||
def query(self, query: MediaMappingQuery) -> MediaMapping | None:
|
||||
"""
|
||||
在宿主循环执行有总超时的查询,同步等待也有独立上限。
|
||||
|
||||
:param query: 原来源身份与上下文
|
||||
:return: 已知关系;不可执行或超时为 None
|
||||
"""
|
||||
url = self._url()
|
||||
if not url:
|
||||
return None
|
||||
with self._lock:
|
||||
cached = self._cache.get(self._key(url, query))
|
||||
if cached and cached[0] > time.monotonic():
|
||||
return cached[1].model_copy(deep=True) if cached[1] else None
|
||||
try:
|
||||
asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
pass
|
||||
else:
|
||||
# 同步兼容调用落在事件循环线程时不能阻塞宿主。
|
||||
return None
|
||||
loop = main_loop_registry.current
|
||||
if loop is None or not loop.is_running() or loop.is_closed():
|
||||
return asyncio.run(self.async_query(query))
|
||||
try:
|
||||
future = get_task_registry().submit_threadsafe(self.async_query(query), loop=loop, owner="media-mapping.query")
|
||||
return cast(MediaMapping | None, future.result(timeout=QUERY_TIMEOUT + 0.1))
|
||||
except concurrent.futures.TimeoutError:
|
||||
future.cancel()
|
||||
return None
|
||||
except (RuntimeError, concurrent.futures.CancelledError):
|
||||
return None
|
||||
|
||||
def share(self, mapping: MediaMapping) -> None:
|
||||
"""
|
||||
立即缓存成功转换,并有界投递后台共享;公共写入不阻塞业务结果。
|
||||
|
||||
:param mapping: 转换成功后的原身份与 TMDB 目标
|
||||
"""
|
||||
url = self._url()
|
||||
if not url:
|
||||
return
|
||||
query = MediaMappingQuery(**mapping.model_dump(include={"media_source", "media_id", "type", "season"}))
|
||||
key = self._key(url, query)
|
||||
with self._lock:
|
||||
self._remember(key, mapping.model_copy(deep=True), POSITIVE_TTL)
|
||||
if time.monotonic() < self._retry_at or key in self._inflight or len(self._inflight) >= INFLIGHT_LIMIT:
|
||||
return
|
||||
self._inflight.add(key)
|
||||
coroutine = self._report(url, key, mapping)
|
||||
try:
|
||||
try:
|
||||
asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
loop = main_loop_registry.current
|
||||
if loop is not None and loop.is_running() and not loop.is_closed():
|
||||
get_task_registry().submit_threadsafe(coroutine, loop=loop, owner="media-mapping.share")
|
||||
else:
|
||||
# 独立同步命令没有宿主循环,上报仍受 500 毫秒总预算保护。
|
||||
asyncio.run(coroutine)
|
||||
else:
|
||||
get_task_registry().create(coroutine, owner="media-mapping.share")
|
||||
except RuntimeError:
|
||||
coroutine.close()
|
||||
with self._lock:
|
||||
self._inflight.discard(key)
|
||||
|
||||
async def _report(self, url: str, key: str, mapping: MediaMapping) -> None:
|
||||
"""
|
||||
消费短时上报并按服务器的既有关系修正缓存,结束后释放并发名额。
|
||||
|
||||
:param url: 中心地址
|
||||
:param key: 共享查询键
|
||||
:param mapping: 本地新转换的关系
|
||||
"""
|
||||
try:
|
||||
confirmed = await self._request(url, mapping.model_dump(mode="json"), report=True)
|
||||
with self._lock:
|
||||
if time.monotonic() >= self._retry_at:
|
||||
self._remember(key, confirmed, POSITIVE_TTL if confirmed else NEGATIVE_TTL)
|
||||
finally:
|
||||
with self._lock:
|
||||
self._inflight.discard(key)
|
||||
@@ -28,6 +28,7 @@ from app.application.classification.runtime import ClassificationRuntime
|
||||
from app.application.configuration import get_api_runtime_config_snapshot
|
||||
from app.application.mediaserver import MediaServerQueryService
|
||||
from app.application.module import get_module_manager
|
||||
from app.application.server.mapping import get_media_mapping_port
|
||||
from app.application.subscription.contract import SubscriptionIdentity
|
||||
from app.application.subscription.query import SubscriptionQueryService
|
||||
from app.chain.media import MediaChain
|
||||
@@ -49,6 +50,7 @@ from app.schemas.context import MediaSearchResults as _SchemaMediaSearchResults
|
||||
from app.schemas.context import MediaSeason as _SchemaMediaSeason
|
||||
from app.schemas.event import MediaSourceInfo as _SchemaMediaSourceInfo
|
||||
from app.schemas.file import FileItem as _SchemaFileItem
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingQuery
|
||||
from app.schemas.media import MediaStatusQuery, MediaStatusResult, normalize_media_source, resolve_media_identity
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.token import TokenPayload as _SchemaTokenPayload
|
||||
@@ -57,6 +59,22 @@ from app.schemas.types import MUSIC_ENTITY_ALBUM, MUSIC_ENTITY_RECORDING, MediaS
|
||||
router = ResponseAPIRouter()
|
||||
|
||||
|
||||
@router.get("/mapping", summary="查询已有的 TMDB 共享关系", response_model=MediaMapping | None)
|
||||
async def media_mapping(
|
||||
query: Annotated[MediaMappingQuery, Query()],
|
||||
_: ApiPrincipal = Depends(get_current_active_user_async),
|
||||
) -> MediaMapping | None:
|
||||
"""
|
||||
只查询缓存或中心已有关系,不进行名称匹配,不阻塞媒体详情请求。
|
||||
|
||||
:param query: 非 TMDB 原来源身份和可选影视类型、季号
|
||||
:param _: 已认证的当前用户
|
||||
:return: 已知的 TMDB 关系;未命中、未启用或服务故障时为 None
|
||||
"""
|
||||
port = get_media_mapping_port()
|
||||
return await port.async_query(query) if port is not None else None
|
||||
|
||||
|
||||
@router.post("/status", summary="批量查询本地入库与订阅状态", response_model=list[MediaStatusResult])
|
||||
async def media_status(
|
||||
items: Annotated[list[MediaStatusQuery], Body(min_length=1, max_length=50, description="按展示顺序提交的媒体,最多 50 项")],
|
||||
|
||||
61
app/application/server/mapping.py
Normal file
61
app/application/server/mapping.py
Normal file
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
媒体转换和详情浏览共享的 TMDB 关系查询端口。
|
||||
"""
|
||||
|
||||
from typing import Protocol
|
||||
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingQuery
|
||||
|
||||
|
||||
class MediaMappingPort(Protocol):
|
||||
"""
|
||||
中心服务的可降级查询与共享能力,不向调用方暴露传输实现。
|
||||
"""
|
||||
|
||||
def query(self, query: MediaMappingQuery) -> MediaMapping | None:
|
||||
"""
|
||||
同步查询本地缓存或中心服务。
|
||||
|
||||
:param query: 原来源媒体身份与类型、季号上下文
|
||||
:return: 已知对应关系;未命中或服务不可用时为 None
|
||||
"""
|
||||
...
|
||||
|
||||
async def async_query(self, query: MediaMappingQuery) -> MediaMapping | None:
|
||||
"""
|
||||
异步查询缓存或中心服务。
|
||||
|
||||
:param query: 原来源媒体身份与类型、季号上下文
|
||||
:return: 已知对应关系;未命中或服务不可用时为 None
|
||||
"""
|
||||
...
|
||||
|
||||
def share(self, mapping: MediaMapping) -> None:
|
||||
"""
|
||||
缓存转换结果并尝试后台上报,不改变转换结果。
|
||||
|
||||
:param mapping: 本次成功转换的单向关系
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
_port: MediaMappingPort | None = None
|
||||
|
||||
|
||||
def configure_media_mapping_port(port: MediaMappingPort | None) -> None:
|
||||
"""
|
||||
由宿主组合根装配或释放关系端口。
|
||||
|
||||
:param port: 有界缓存和超时的实现;None 表示未装配
|
||||
"""
|
||||
global _port
|
||||
_port = port
|
||||
|
||||
|
||||
def get_media_mapping_port() -> MediaMappingPort | None:
|
||||
"""
|
||||
返回可选关系端口,未装配的测试或插件上下文保持原转换行为。
|
||||
|
||||
:return: 已装配的中心关系端口,或 None
|
||||
"""
|
||||
return _port
|
||||
@@ -7,14 +7,18 @@ from __future__ import annotations
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum, auto
|
||||
from typing import Any, Final, Optional, cast
|
||||
from typing import Any, Final, Literal, Optional, cast
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.application.server.mapping import get_media_mapping_port
|
||||
from app.chain.media.contract import _MediaOwnerBase
|
||||
from app.domain.context import MediaInfo
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.schemas.event import (
|
||||
MediaRecognizeConvertEventData as _SchemaMediaRecognizeConvertEventData,
|
||||
)
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingQuery
|
||||
from app.schemas.media import normalize_media_source, resolve_media_identity
|
||||
from app.schemas.types import ChainEventType, MediaSource, MediaType
|
||||
|
||||
@@ -225,6 +229,7 @@ def _build_bangumi_tmdb_match(
|
||||
year=MediaProjectionOwner._extract_year_from_bangumi(source_info),
|
||||
media_type=plan.media_type or resolve_media_type(source_info),
|
||||
season=selected_season,
|
||||
include_season=(plan.media_type or resolve_media_type(source_info)) == MediaType.TV,
|
||||
)
|
||||
|
||||
|
||||
@@ -439,6 +444,53 @@ async def _async_convert_builtin_projection(
|
||||
return await _async_apply_projection_match(owner, match) if match else None
|
||||
|
||||
|
||||
def _mapping_query(plan: _ProjectionPlan) -> MediaMappingQuery | None:
|
||||
"""
|
||||
仅为非 TMDB 到 TMDB 的影视转换构造共享查询。
|
||||
|
||||
:param plan: 已标准化的转换输入
|
||||
:return: 单向关系查询,其他转换返回 None
|
||||
"""
|
||||
if plan.target != MediaSource.TMDB or plan.source == MediaSource.TMDB or plan.media_type == MediaType.MUSIC:
|
||||
return None
|
||||
try:
|
||||
return MediaMappingQuery(
|
||||
media_source=plan.source, media_id=plan.media_id,
|
||||
type="movie" if plan.media_type == MediaType.MOVIE else "tv" if plan.media_type == MediaType.TV else None,
|
||||
season=plan.season if plan.media_type != MediaType.MOVIE else None,
|
||||
)
|
||||
except ValidationError:
|
||||
return None
|
||||
|
||||
|
||||
def _share_mapping(plan: _ProjectionPlan, result: _ProjectionPayload | None) -> None:
|
||||
"""
|
||||
从成功的 TMDB 原始详情提取关系;不影响原转换结果与插件兼容合同。
|
||||
|
||||
:param plan: 原来源身份及转换上下文
|
||||
:param result: 成功转换的完整 TMDB 详情,失败为 None
|
||||
"""
|
||||
port = get_media_mapping_port()
|
||||
query = _mapping_query(plan)
|
||||
if port is None or query is None or not result:
|
||||
return
|
||||
try:
|
||||
raw_type = result.get("media_type")
|
||||
media_type = raw_type if isinstance(raw_type, MediaType) else MediaType.from_agent(str(raw_type or ""))
|
||||
media_type = media_type or plan.media_type
|
||||
if media_type not in (MediaType.MOVIE, MediaType.TV):
|
||||
return
|
||||
target_type: Literal["movie", "tv"] = "movie" if media_type == MediaType.MOVIE else "tv"
|
||||
port.share(MediaMapping.model_validate({
|
||||
**query.model_dump(), "type": query.type or target_type,
|
||||
"tmdb_id": result.get("id"), "tmdb_type": target_type,
|
||||
"tmdb_season": result.get("season") if target_type == "tv" else None,
|
||||
}))
|
||||
except (ValidationError, TypeError, ValueError):
|
||||
# 未提供有效 TMDB 身份的旧插件结果继续返回业务调用方,但不能污染公共关系表。
|
||||
return
|
||||
|
||||
|
||||
class MediaProjectionOwner(_MediaOwnerBase):
|
||||
"""
|
||||
不同媒体来源之间的身份匹配与转换。
|
||||
@@ -504,9 +556,19 @@ class MediaProjectionOwner(_MediaOwnerBase):
|
||||
)
|
||||
if not plan:
|
||||
return None
|
||||
query = _mapping_query(plan)
|
||||
port = get_media_mapping_port()
|
||||
shared = port.query(query) if port is not None and query is not None else None
|
||||
if shared:
|
||||
result = self.tmdb_info(tmdbid=shared.tmdb_id, mtype=MediaType.MOVIE if shared.tmdb_type == "movie" else MediaType.TV)
|
||||
if result:
|
||||
return {**result, "season": shared.tmdb_season} if shared.tmdb_season is not None else result
|
||||
if plan.rule == _ProjectionRule.EVENT:
|
||||
return MediaProjectionOwner._dispatch_projection_event(self, plan)
|
||||
return _convert_builtin_projection(self, plan)
|
||||
result = MediaProjectionOwner._dispatch_projection_event(self, plan)
|
||||
else:
|
||||
result = _convert_builtin_projection(self, plan)
|
||||
_share_mapping(plan, result)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _extract_year_from_bangumi(
|
||||
@@ -600,8 +662,18 @@ class MediaProjectionOwner(_MediaOwnerBase):
|
||||
)
|
||||
if not plan:
|
||||
return None
|
||||
query = _mapping_query(plan)
|
||||
port = get_media_mapping_port()
|
||||
shared = await port.async_query(query) if port is not None and query is not None else None
|
||||
if shared:
|
||||
result = await self.async_tmdb_info(tmdbid=shared.tmdb_id, mtype=MediaType.MOVIE if shared.tmdb_type == "movie" else MediaType.TV)
|
||||
if result:
|
||||
return {**result, "season": shared.tmdb_season} if shared.tmdb_season is not None else result
|
||||
if plan.rule == _ProjectionRule.EVENT:
|
||||
return await MediaProjectionOwner._async_dispatch_projection_event(
|
||||
result = await MediaProjectionOwner._async_dispatch_projection_event(
|
||||
self, plan
|
||||
)
|
||||
return await _async_convert_builtin_projection(self, plan)
|
||||
else:
|
||||
result = await _async_convert_builtin_projection(self, plan)
|
||||
_share_mapping(plan, result)
|
||||
return result
|
||||
|
||||
74
app/schemas/mapping.py
Normal file
74
app/schemas/mapping.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
非 TMDB 来源到 TMDB 的共享关系协议,不包含完整媒体详情。
|
||||
"""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from app.schemas.media import normalize_media_source
|
||||
from app.schemas.types import MediaSource
|
||||
|
||||
|
||||
class MediaMappingQuery(BaseModel):
|
||||
"""
|
||||
用原来源身份、可选类型与季号定位已有关系。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
media_source: MediaSource = Field(description="非 TMDB 的影视来源")
|
||||
media_id: str = Field(min_length=1, max_length=256, description="来源原生媒体 ID")
|
||||
type: Literal["movie", "tv"] | None = Field(default=None, description="原来源影视类型")
|
||||
season: int | None = Field(default=None, ge=0, le=10000, description="原来源季号;未指定为 null")
|
||||
|
||||
@field_validator("media_source", mode="before")
|
||||
@classmethod
|
||||
def normalize_source(cls, value: object) -> MediaSource:
|
||||
"""
|
||||
规范来源别名,并拒绝反向 TMDB 转换。
|
||||
|
||||
:param value: 内置来源或插件来源标识
|
||||
:return: 非 TMDB 的有效来源
|
||||
"""
|
||||
source = normalize_media_source(value) if isinstance(value, (str, MediaSource)) else None
|
||||
if source is None or source == MediaSource.TMDB:
|
||||
raise ValueError("仅支持非 TMDB 来源到 TMDB 的关系")
|
||||
return source
|
||||
|
||||
@field_validator("media_id")
|
||||
@classmethod
|
||||
def validate_id(cls, value: str) -> str:
|
||||
"""
|
||||
拒绝零哨兵并保留原生 ID 大小写。
|
||||
|
||||
:param value: 去除首尾空白后的媒体标识
|
||||
:return: 有效的原生标识
|
||||
"""
|
||||
if value == "0":
|
||||
raise ValueError("媒体 ID 无效")
|
||||
return value
|
||||
|
||||
|
||||
class MediaMapping(MediaMappingQuery):
|
||||
"""
|
||||
记录单向转换的原身份及对应的 TMDB 类型、ID、季号。
|
||||
"""
|
||||
|
||||
type: Literal["movie", "tv"] = Field(description="原来源影视类型")
|
||||
tmdb_id: int = Field(gt=0, le=2147483647, description="TMDB 原生 ID")
|
||||
tmdb_type: Literal["movie", "tv"] = Field(description="TMDB 电影或剧集类型")
|
||||
tmdb_season: int | None = Field(default=None, ge=0, le=10000, description="TMDB 季号,电影或未知为 null")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_seasons(self) -> "MediaMapping":
|
||||
"""
|
||||
拒绝电影携带季号的无效共享结果。
|
||||
|
||||
:return: 类型与季号相容的关系
|
||||
"""
|
||||
if self.type == "movie" and self.season is not None:
|
||||
raise ValueError("电影来源不能指定季号")
|
||||
if self.tmdb_type == "movie" and self.tmdb_season is not None:
|
||||
raise ValueError("TMDB 电影不能指定季号")
|
||||
return self
|
||||
@@ -7,6 +7,7 @@ from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Optional, cast
|
||||
|
||||
from app.adapters.external.mapping import MediaMappingClient
|
||||
from app.adapters.external.server import MoviePilotServerHelper
|
||||
from app.adapters.system.host import SystemUtils
|
||||
from app.application.chain.context import (
|
||||
@@ -26,6 +27,7 @@ from app.application.image import (
|
||||
reset_wallpaper_providers,
|
||||
)
|
||||
from app.application.module import ModuleRuntime, configure_module_runtime
|
||||
from app.application.server.mapping import configure_media_mapping_port
|
||||
from app.application.subscription.activity import SubscriptionActivityService
|
||||
from app.application.system import SystemService
|
||||
from app.chain._recognition import (
|
||||
@@ -341,6 +343,7 @@ def configure_chain_port_composition() -> None:
|
||||
"""
|
||||
reset_chain_port_composition()
|
||||
try:
|
||||
configure_media_mapping_port(MediaMappingClient())
|
||||
configure_recognition_share_port(
|
||||
cast(RecognitionSharePort, _RecognitionShareAdapter())
|
||||
)
|
||||
@@ -359,6 +362,7 @@ def reset_chain_port_composition() -> None:
|
||||
"""
|
||||
释放 Chain 技术端口,支持重复 lifespan 与启动失败回滚。
|
||||
"""
|
||||
configure_media_mapping_port(None)
|
||||
reset_network_filesystem_port()
|
||||
reset_subscription_share_port()
|
||||
reset_recognition_share_port()
|
||||
|
||||
@@ -851,7 +851,7 @@ flowchart LR
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1168 |
|
||||
| 内部导入边 | 10,206 |
|
||||
| 内部导入边 | 10,230 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) |
|
||||
|
||||
@@ -2,6 +2,22 @@
|
||||
|
||||
本文面向通过 MCP 调用 MoviePilot 的外部 Agent 和工具开发者。接入后,客户端通过工具目录发现能力,按 JSON Schema 构造参数,并根据业务结果判断操作是否完成。
|
||||
|
||||
### 已有的跨来源 TMDB 对应关系
|
||||
|
||||
登录用户可通过 `GET /api/v1/media/mapping` 查询非 TMDB 影视来源已有的对应关系,
|
||||
参数为 `media_source`、`media_id` 和可选的 `type=movie|tv`、`season`。接口返回统一响应,
|
||||
`data` 为关系或 `null`;只查本地缓存及 Server,不现场按名称匹配,也不增加 Agent operation。
|
||||
关系包含 `tmdb_id`、`tmdb_type` 和 `tmdb_season`,剧集外链使用 TMDB 季号而非原来源季号。
|
||||
|
||||
转换流程仅对“非 TMDB → TMDB”接入此查询;未命中时沿用原转换,成功后向 Server 后台共享。
|
||||
沿用 `MEDIA_RECOGNIZE_SHARE` 开关,服务地址为 `MP_SERVER_HOST + /recognize/mapping`,
|
||||
独立于种子名识别接口 `MEDIA_RECOGNIZE_SHARE_API`。中心查询总时限 800 毫秒,上报 500 毫秒;
|
||||
成功关系缓存一小时、未命中十分钟,故障冷却三十秒,并合并并发查询、限制在途请求数。
|
||||
详情页独立异步补充 TheMovieDb 外链,查询失败时保留原详情及操作。
|
||||
|
||||
Server 使用独立 SQL 表长期保存关系,不属于识别缓存清理范围。公共上报只补缺,
|
||||
管理后台可纠正目标或撤销错误关系;撤销保留记录,防止旧实例覆盖。实例正缓存最多一小时后更新。
|
||||
|
||||
### 外部整理历史登记
|
||||
|
||||
管理员可通过 `transfer.history.register`(`POST /api/v1/history/transfer`)登记已经完成的
|
||||
|
||||
@@ -18,7 +18,7 @@ if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
# 与对应 SKILL.md 同步维护,重新生成不能回退用户同步所需的版本。
|
||||
MOVIEPILOT_API_SKILL_VERSION = "75"
|
||||
MOVIEPILOT_API_SKILL_VERSION = "76"
|
||||
DATABASE_OPERATION_SKILL_VERSION = "19"
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: moviepilot-api
|
||||
version: 75
|
||||
version: 76
|
||||
description: >-
|
||||
Use this skill for MoviePilot product operations such as media search, torrent
|
||||
search, downloads, subscriptions, library checks, sites, storage, workflows,
|
||||
@@ -163,6 +163,12 @@ downloader mappings when switching path modes.
|
||||
|
||||
## Overall Workflow
|
||||
|
||||
Conversions from other video sources to TMDB reuse cached community mappings
|
||||
before matching names and share successful results. Browsing only looks up known
|
||||
mappings to add a TheMovieDb link and preserves the original source identity.
|
||||
`GET /api/v1/media/mapping` is a frontend helper, without an Agent operation;
|
||||
continue using `media.detail` and do not construct extra HTTP requests.
|
||||
|
||||
1. Select the exact `operation_id` from the category index below.
|
||||
2. Call `read_skill` again with `name="moviepilot-api"` and
|
||||
`file="api/<category>.md"` to load the complete standalone category
|
||||
|
||||
@@ -553,6 +553,9 @@ def configure_plugin_system_services():
|
||||
)
|
||||
|
||||
init_chain_ports()
|
||||
# 共享关系是新增的外部端口;普通单元测试保持未装配,由专项测试注入受控实现。
|
||||
from app.application.server.mapping import configure_media_mapping_port
|
||||
configure_media_mapping_port(None)
|
||||
init_chain_network_ports()
|
||||
configure_site_query_service(SiteQueryService(repository=site_repository()))
|
||||
configure_site_health_service(SiteHealthService(repository=site_repository()))
|
||||
|
||||
@@ -977,8 +977,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10206,
|
||||
"edge_sha256": "87ecd2cdf5db4efafc8ef84af564b7ffcfe5dd30298fdeefbbb004a2a5b60a10",
|
||||
"edge_count": 10230,
|
||||
"edge_sha256": "8493fad27c51627bec333bc13383600490d123e01c3d7977dd8a710e3356688b",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -1022,6 +1022,15 @@
|
||||
"app.adapters.external.location -> app.adapters.network.http",
|
||||
"app.adapters.external.location -> app.schemas",
|
||||
"app.adapters.external.location -> app.schemas.common",
|
||||
"app.adapters.external.mapping -> app.adapters",
|
||||
"app.adapters.external.mapping -> app.adapters.network",
|
||||
"app.adapters.external.mapping -> app.adapters.network.http",
|
||||
"app.adapters.external.mapping -> app.runtime",
|
||||
"app.adapters.external.mapping -> app.runtime.loop",
|
||||
"app.adapters.external.mapping -> app.runtime.settings",
|
||||
"app.adapters.external.mapping -> app.runtime.tasks",
|
||||
"app.adapters.external.mapping -> app.schemas",
|
||||
"app.adapters.external.mapping -> app.schemas.mapping",
|
||||
"app.adapters.external.market -> app.adapters",
|
||||
"app.adapters.external.market -> app.adapters.external",
|
||||
"app.adapters.external.market -> app.adapters.external.plugin",
|
||||
@@ -2737,6 +2746,8 @@
|
||||
"app.api.endpoints.media -> app.application.module",
|
||||
"app.api.endpoints.media -> app.application.plugin",
|
||||
"app.api.endpoints.media -> app.application.plugin.runtime",
|
||||
"app.api.endpoints.media -> app.application.server",
|
||||
"app.api.endpoints.media -> app.application.server.mapping",
|
||||
"app.api.endpoints.media -> app.application.subscription",
|
||||
"app.api.endpoints.media -> app.application.subscription.contract",
|
||||
"app.api.endpoints.media -> app.application.subscription.query",
|
||||
@@ -2756,6 +2767,7 @@
|
||||
"app.api.endpoints.media -> app.schemas.context",
|
||||
"app.api.endpoints.media -> app.schemas.event",
|
||||
"app.api.endpoints.media -> app.schemas.file",
|
||||
"app.api.endpoints.media -> app.schemas.mapping",
|
||||
"app.api.endpoints.media -> app.schemas.media",
|
||||
"app.api.endpoints.media -> app.schemas.response",
|
||||
"app.api.endpoints.media -> app.schemas.token",
|
||||
@@ -4268,6 +4280,8 @@
|
||||
"app.application.security.widget -> app.schemas.widget",
|
||||
"app.application.servarr -> app.schemas",
|
||||
"app.application.servarr -> app.schemas.types",
|
||||
"app.application.server.mapping -> app.schemas",
|
||||
"app.application.server.mapping -> app.schemas.mapping",
|
||||
"app.application.server.payload -> app.schemas",
|
||||
"app.application.server.payload -> app.schemas.media",
|
||||
"app.application.server.report -> app.application",
|
||||
@@ -5172,6 +5186,9 @@
|
||||
"app.chain.media.plugin -> app.runtime.log",
|
||||
"app.chain.media.plugin -> app.schemas",
|
||||
"app.chain.media.plugin -> app.schemas.types",
|
||||
"app.chain.media.projection -> app.application",
|
||||
"app.chain.media.projection -> app.application.server",
|
||||
"app.chain.media.projection -> app.application.server.mapping",
|
||||
"app.chain.media.projection -> app.chain",
|
||||
"app.chain.media.projection -> app.chain.media",
|
||||
"app.chain.media.projection -> app.chain.media.contract",
|
||||
@@ -5182,6 +5199,7 @@
|
||||
"app.chain.media.projection -> app.domain.projection.bangumi",
|
||||
"app.chain.media.projection -> app.schemas",
|
||||
"app.chain.media.projection -> app.schemas.event",
|
||||
"app.chain.media.projection -> app.schemas.mapping",
|
||||
"app.chain.media.projection -> app.schemas.media",
|
||||
"app.chain.media.projection -> app.schemas.types",
|
||||
"app.chain.media.recognition -> app.application",
|
||||
@@ -9856,6 +9874,9 @@
|
||||
"app.schemas.history -> app.schemas.common",
|
||||
"app.schemas.history -> app.schemas.media",
|
||||
"app.schemas.history -> app.schemas.types",
|
||||
"app.schemas.mapping -> app.schemas",
|
||||
"app.schemas.mapping -> app.schemas.media",
|
||||
"app.schemas.mapping -> app.schemas.types",
|
||||
"app.schemas.mcp -> app.schemas",
|
||||
"app.schemas.mcp -> app.schemas.common",
|
||||
"app.schemas.media -> app.schemas",
|
||||
@@ -10178,6 +10199,7 @@
|
||||
"app.startup.composition.cache -> app.runtime.settings",
|
||||
"app.startup.composition.chain -> app.adapters",
|
||||
"app.startup.composition.chain -> app.adapters.external",
|
||||
"app.startup.composition.chain -> app.adapters.external.mapping",
|
||||
"app.startup.composition.chain -> app.adapters.external.server",
|
||||
"app.startup.composition.chain -> app.adapters.system",
|
||||
"app.startup.composition.chain -> app.adapters.system.host",
|
||||
@@ -10192,6 +10214,8 @@
|
||||
"app.startup.composition.chain -> app.application.directory",
|
||||
"app.startup.composition.chain -> app.application.image",
|
||||
"app.startup.composition.chain -> app.application.module",
|
||||
"app.startup.composition.chain -> app.application.server",
|
||||
"app.startup.composition.chain -> app.application.server.mapping",
|
||||
"app.startup.composition.chain -> app.application.subscription",
|
||||
"app.startup.composition.chain -> app.application.subscription.activity",
|
||||
"app.startup.composition.chain -> app.application.system",
|
||||
@@ -11187,7 +11211,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1168,
|
||||
"module_count": 1171,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -11198,6 +11222,7 @@
|
||||
"app.adapters.external.cookiecloud",
|
||||
"app.adapters.external.github",
|
||||
"app.adapters.external.location",
|
||||
"app.adapters.external.mapping",
|
||||
"app.adapters.external.market",
|
||||
"app.adapters.external.ocr",
|
||||
"app.adapters.external.plugin",
|
||||
@@ -11586,6 +11611,7 @@
|
||||
"app.application.security.widget",
|
||||
"app.application.servarr",
|
||||
"app.application.server",
|
||||
"app.application.server.mapping",
|
||||
"app.application.server.payload",
|
||||
"app.application.server.report",
|
||||
"app.application.server.share",
|
||||
@@ -12235,6 +12261,7 @@
|
||||
"app.schemas.history",
|
||||
"app.schemas.initialization",
|
||||
"app.schemas.llm",
|
||||
"app.schemas.mapping",
|
||||
"app.schemas.mcp",
|
||||
"app.schemas.media",
|
||||
"app.schemas.mediaserver",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"repeat": 3,
|
||||
"targets": {
|
||||
"app.startup.lifecycle": {
|
||||
"loaded_app_module_count": 605,
|
||||
"loaded_app_module_count": 608,
|
||||
"max_ms": 1293.338,
|
||||
"median_ms": 1156.239,
|
||||
"min_ms": 1102.806,
|
||||
@@ -17,7 +17,7 @@
|
||||
]
|
||||
},
|
||||
"app.factory": {
|
||||
"loaded_app_module_count": 619,
|
||||
"loaded_app_module_count": 622,
|
||||
"max_ms": 1127.911,
|
||||
"median_ms": 1122.382,
|
||||
"min_ms": 1119.221,
|
||||
@@ -28,7 +28,7 @@
|
||||
]
|
||||
},
|
||||
"app.main": {
|
||||
"loaded_app_module_count": 621,
|
||||
"loaded_app_module_count": 624,
|
||||
"max_ms": 1188.652,
|
||||
"median_ms": 1183.509,
|
||||
"min_ms": 1174.522,
|
||||
|
||||
@@ -130,7 +130,7 @@ def test_modified_builtin_skills_have_incremented_versions() -> None:
|
||||
"database-operation": "19",
|
||||
"feedback-issue": "12",
|
||||
"anysearch": "3",
|
||||
"moviepilot-api": "75",
|
||||
"moviepilot-api": "76",
|
||||
"moviepilot-update": "7",
|
||||
"organize-files": "6",
|
||||
"transfer-failed-retry": "7",
|
||||
|
||||
241
tests/test_media_mapping.py
Normal file
241
tests/test_media_mapping.py
Normal file
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
共享 TMDB 关系的转换顺序、缓存、故障降级和接口回归。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.adapters.external import mapping as transport
|
||||
from app.api.endpoints import media as endpoint
|
||||
from app.application.server.mapping import configure_media_mapping_port
|
||||
from app.chain.media import MediaChain
|
||||
from app.runtime.loop import main_loop_registry
|
||||
from app.schemas.mapping import MediaMapping, MediaMappingQuery
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
|
||||
def query(**overrides):
|
||||
"""
|
||||
提供来源季号与 TMDB 季号不同的动画查询上下文。
|
||||
"""
|
||||
return MediaMappingQuery(media_source=MediaSource.AniList, media_id="123", type="tv", **overrides)
|
||||
|
||||
|
||||
def relation(**overrides):
|
||||
"""
|
||||
构造共享剧集第零季关系,确认不能把 0 当作空值。
|
||||
"""
|
||||
return MediaMapping(**{**query().model_dump(), "tmdb_id": 456, "tmdb_type": "tv", "tmdb_season": 0, **overrides})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
"""
|
||||
用受控传输隔离实际 Server,并允许检验请求次数。
|
||||
"""
|
||||
config = {"MP_SERVER_HOST": "https://center.example", "MEDIA_RECOGNIZE_SHARE": True, "PROXY": None}
|
||||
monkeypatch.setattr(transport, "get_runtime_setting", config.get)
|
||||
return transport.MediaMappingClient()
|
||||
|
||||
|
||||
def test_client_positive_negative_cache_expiry_and_configuration(client, monkeypatch):
|
||||
"""
|
||||
正负缓存、类型季号和中心地址隔离,并在有效期后重新请求。
|
||||
"""
|
||||
clock = [100.0]
|
||||
monkeypatch.setattr(transport.time, "monotonic", lambda: clock[0])
|
||||
request = AsyncMock(side_effect=[relation(), None, relation(), None])
|
||||
monkeypatch.setattr(client, "_request", request)
|
||||
|
||||
async def run():
|
||||
"""
|
||||
反复读取和过期读取应产生精确的中心请求次数。
|
||||
"""
|
||||
first = await client.async_query(query())
|
||||
first.tmdb_id = 999
|
||||
assert (await client.async_query(query())).tmdb_id == 456
|
||||
assert await client.async_query(query(season=2)) is None
|
||||
assert await client.async_query(query(season=2)) is None
|
||||
assert request.await_count == 2
|
||||
clock[0] += transport.POSITIVE_TTL + 1
|
||||
assert (await client.async_query(query())).tmdb_id == 456
|
||||
monkeypatch.setattr(client, "_url", lambda: "https://other.example/recognize/mapping")
|
||||
assert await client.async_query(query()) is None
|
||||
assert request.await_count == 4
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("response", [None, {"code": 1}, {"code": 0, "data": {"item": {"tmdb_id": 0}}}])
|
||||
def test_bad_response_enters_global_cooldown(client, monkeypatch, response):
|
||||
"""
|
||||
非法或不可用响应只触发一次请求,后续不同身份在冷却中快速返回。
|
||||
"""
|
||||
get = AsyncMock(return_value=None if response is None else Mock(status_code=200, json=Mock(return_value=response)))
|
||||
monkeypatch.setattr(transport, "AsyncRequestUtils", Mock(return_value=SimpleNamespace(get_res=get)))
|
||||
|
||||
async def run():
|
||||
"""
|
||||
不同媒体连续失败也不会持续请求故障中心。
|
||||
"""
|
||||
assert await client.async_query(query()) is None
|
||||
assert await client.async_query(query(season=2)) is None
|
||||
assert get.await_count == 1
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_request_total_timeout_and_concurrent_bound(client, monkeypatch):
|
||||
"""
|
||||
故障总超时覆盖传输重试,重复在途查询不重复请求。
|
||||
"""
|
||||
async def blocked(*_args, **_kwargs):
|
||||
"""
|
||||
模拟不会主动返回的中心请求,依靠总预算中断。
|
||||
"""
|
||||
await asyncio.Event().wait()
|
||||
get = AsyncMock(side_effect=blocked)
|
||||
monkeypatch.setattr(transport, "QUERY_TIMEOUT", 0.03)
|
||||
monkeypatch.setattr(transport, "AsyncRequestUtils", Mock(return_value=SimpleNamespace(get_res=get)))
|
||||
|
||||
async def run():
|
||||
"""
|
||||
两个相同查询只发一次请求且均在短预算内结束。
|
||||
"""
|
||||
started = time.monotonic()
|
||||
assert await asyncio.gather(client.async_query(query()), client.async_query(query())) == [None, None]
|
||||
assert time.monotonic() - started < 0.3
|
||||
assert get.await_count == 1
|
||||
assert not client._inflight
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_query_validates_response_identity_and_disabled_service(client, monkeypatch):
|
||||
"""
|
||||
即使中心响应格式有效,也不能使用其他来源或原生 ID 的关系。
|
||||
"""
|
||||
monkeypatch.setattr(client, "_request", AsyncMock(return_value=relation(media_id="other")))
|
||||
assert client.query(query()) is None
|
||||
monkeypatch.setattr(client, "_url", lambda: None)
|
||||
assert client.query(query()) is None
|
||||
client.share(relation())
|
||||
|
||||
|
||||
def test_share_runs_in_owned_background_and_honors_revocation(client, monkeypatch):
|
||||
"""
|
||||
共享立即写入本地缓存,后台根据中心撤销结果清除该命中。
|
||||
"""
|
||||
complete = asyncio.Event()
|
||||
|
||||
async def request(*_args, **_kwargs):
|
||||
"""
|
||||
中心确认撤销时返回空关系,不允许长期保留本地错误目标。
|
||||
"""
|
||||
complete.set()
|
||||
return None
|
||||
monkeypatch.setattr(client, "_request", request)
|
||||
|
||||
async def run():
|
||||
"""
|
||||
使用真实宿主循环登记,等待已归属后台任务完成。
|
||||
"""
|
||||
owner = main_loop_registry.register(asyncio.get_running_loop())
|
||||
try:
|
||||
client.share(relation())
|
||||
assert (await client.async_query(query())).tmdb_id == 456
|
||||
await asyncio.wait_for(complete.wait(), 0.5)
|
||||
assert await client.async_query(query()) is None
|
||||
assert client.query(query()) is None
|
||||
finally:
|
||||
main_loop_registry.release(owner)
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
def test_conversion_uses_shared_identity_before_source_or_name_matching(asynchronous):
|
||||
"""
|
||||
同异步转换均直接按共享 TMDB ID 取详情,并保留共享季号。
|
||||
"""
|
||||
port = SimpleNamespace(query=Mock(return_value=relation()), async_query=AsyncMock(return_value=relation()), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
owner = SimpleNamespace(tmdb_info=Mock(return_value={"id": 456, "media_type": "tv"}),
|
||||
async_tmdb_info=AsyncMock(return_value={"id": 456, "media_type": "tv"}))
|
||||
args = dict(target_source=MediaSource.TMDB, media_source=MediaSource.AniList, media_id="123", mtype=MediaType.TV)
|
||||
result = asyncio.run(MediaChain.async_convert_media_identity(owner, **args)) if asynchronous else MediaChain.convert_media_identity(owner, **args)
|
||||
assert result == {"id": 456, "media_type": "tv", "season": 0}
|
||||
port.share.assert_not_called()
|
||||
|
||||
|
||||
def test_miss_keeps_existing_conversion_and_shares_success(monkeypatch):
|
||||
"""
|
||||
缺少关系时仍执行原匹配,成功关系以原来源身份上报。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
port = SimpleNamespace(query=Mock(return_value=None), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
monkeypatch.setattr(projection, "_convert_builtin_projection", Mock(return_value={"id": 456, "media_type": "tv", "season": 2}))
|
||||
result = MediaChain.convert_media_identity(SimpleNamespace(), target_source=MediaSource.TMDB,
|
||||
media_source=MediaSource.AniList, media_id="123", mtype=MediaType.TV, season=1)
|
||||
assert result["season"] == 2
|
||||
assert port.share.call_args.args[0] == relation(season=1, tmdb_season=2)
|
||||
|
||||
|
||||
def test_reverse_conversion_never_queries_or_shares(monkeypatch):
|
||||
"""
|
||||
原有 TMDB 到其他来源转换保持原行为,不接入关系共享。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
port = SimpleNamespace(query=Mock(), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
monkeypatch.setattr(projection, "_convert_builtin_projection", Mock(return_value={"id": "db-1"}))
|
||||
MediaChain.convert_media_identity(SimpleNamespace(), target_source=MediaSource.Douban,
|
||||
media_source=MediaSource.TMDB, media_id="456", mtype=MediaType.TV)
|
||||
port.query.assert_not_called()
|
||||
port.share.assert_not_called()
|
||||
|
||||
|
||||
def test_browsing_endpoint_only_reads_existing_mapping():
|
||||
"""
|
||||
详情辅助入口只读已有关系,不触发转换或共享。
|
||||
"""
|
||||
port = SimpleNamespace(async_query=AsyncMock(return_value=relation()), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
assert asyncio.run(endpoint.media_mapping(query())) == relation()
|
||||
port.share.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
def test_unavailable_shared_tmdb_detail_falls_back_to_original_conversion(monkeypatch, asynchronous):
|
||||
"""
|
||||
共享目标无法读取时仍执行原转换,并共享本次有效匹配,避免旧关系阻断订阅。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
|
||||
port = SimpleNamespace(query=Mock(return_value=relation()), async_query=AsyncMock(return_value=relation()), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
fresh = {"id": 789, "media_type": "tv", "season": 2}
|
||||
match = AsyncMock(return_value=fresh) if asynchronous else Mock(return_value=fresh)
|
||||
monkeypatch.setattr(projection, "_async_convert_builtin_projection" if asynchronous else "_convert_builtin_projection", match)
|
||||
owner = SimpleNamespace(tmdb_info=Mock(return_value=None), async_tmdb_info=AsyncMock(return_value=None))
|
||||
args = dict(target_source=MediaSource.TMDB, media_source=MediaSource.AniList, media_id="123", mtype=MediaType.TV)
|
||||
result = asyncio.run(MediaChain.async_convert_media_identity(owner, **args)) if asynchronous else MediaChain.convert_media_identity(owner, **args)
|
||||
assert result == fresh
|
||||
assert port.share.call_args.args[0] == relation(tmdb_id=789, tmdb_season=2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("result", [{"id": 0, "media_type": "tv"}, {"id": 789, "media_type": "music"}, {"id": 789}])
|
||||
def test_incomplete_plugin_result_is_returned_without_polluting_shared_relations(monkeypatch, result):
|
||||
"""
|
||||
旧插件不提供完整 TMDB 类型或有效 ID 时保持兼容结果,但禁止写入公共关系。
|
||||
"""
|
||||
from app.chain.media import projection
|
||||
|
||||
port = SimpleNamespace(query=Mock(return_value=None), share=Mock())
|
||||
configure_media_mapping_port(port)
|
||||
monkeypatch.setattr(projection, "_convert_builtin_projection", Mock(return_value=result))
|
||||
actual = MediaChain.convert_media_identity(SimpleNamespace(), target_source=MediaSource.TMDB,
|
||||
media_source=MediaSource.AniList, media_id="123")
|
||||
assert actual == result
|
||||
port.share.assert_not_called()
|
||||
Reference in New Issue
Block a user