mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-02 00:46:27 +08:00
fix(subscribe): deduplicate subscriptions across media sources
This commit is contained in:
@@ -13737,6 +13737,18 @@
|
||||
"additionalProperties": false,
|
||||
"description": "subscription.find 的筛选和控制参数。按规范媒体身份和可选季查找一个可访问订阅。仅使用下列已声明字段。",
|
||||
"properties": {
|
||||
"episode_group": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "用于其他剧集排序方式的 TMDB 剧集组标识。",
|
||||
"title": "Episode Group"
|
||||
},
|
||||
"media_source": {
|
||||
"$ref": "#/$defs/MediaSource",
|
||||
"description": "元数据来源标识,保留与 media_id 一同返回的精确值。"
|
||||
|
||||
@@ -43,6 +43,7 @@ from app.application.subscription.execution import SubscriptionSearchRepository
|
||||
from app.application.subscription.identity import (
|
||||
DeleteSubscriptionsByIdentityCommand,
|
||||
)
|
||||
from app.application.subscription.lookup import SubscriptionIdentityLookup
|
||||
from app.application.subscription.mutation import (
|
||||
SubscriptionMutationService,
|
||||
)
|
||||
@@ -58,6 +59,7 @@ from app.application.subscription.status import (
|
||||
from app.application.subscription.write import (
|
||||
SubscriptionBatchWritePort,
|
||||
)
|
||||
from app.chain.media import MediaChain
|
||||
from app.runtime.events import eventmanager
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.tasks import TaskRegistry
|
||||
@@ -211,6 +213,10 @@ def get_subscription_query_service(
|
||||
repository=runtime.subscription.repository(db),
|
||||
async_repository=runtime.subscription.repository(db),
|
||||
history_repository=runtime.subscription.history_repository(db),
|
||||
identity_lookup=SubscriptionIdentityLookup(
|
||||
MediaChain().convert_media_identity,
|
||||
MediaChain().async_convert_media_identity,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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.subscription.contract import SubscriptionIdentity
|
||||
from app.application.subscription.query import SubscriptionQueryService
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.scraping import ScrapingChain
|
||||
@@ -106,7 +107,20 @@ async def _query_media_status(
|
||||
record for record in candidates
|
||||
if current_user.is_superuser or (bool(record.username) and record.username == current_user.name)
|
||||
]
|
||||
if item.mtype is not None:
|
||||
accessible = [record for record in accessible if record.type == item.mtype.value]
|
||||
matched = [record for record in accessible if season is None or record.season == season]
|
||||
if (not matched and item.media_source and item.media_id
|
||||
and item.mtype is not None and item.mtype in (MediaType.MOVIE, MediaType.TV)):
|
||||
projected = await subscriptions.list_by_projected_identity(
|
||||
SubscriptionIdentity(
|
||||
media_source=item.media_source, media_id=item.media_id, type=item.mtype.value,
|
||||
season=season,
|
||||
),
|
||||
username=None if current_user.is_superuser else current_user.name,
|
||||
)
|
||||
accessible.extend(projected)
|
||||
matched = [record for record in accessible if season is None or record.season == season]
|
||||
if not matched and title and item.mtype in (MediaType.MOVIE, MediaType.TV):
|
||||
fallback = await subscriptions.list_by_video_metadata(
|
||||
title=title, year=item.year, media_type=item.mtype, season=season,
|
||||
|
||||
@@ -54,7 +54,11 @@ from app.application.configuration import (
|
||||
get_api_runtime_config_snapshot,
|
||||
get_configured_system_config,
|
||||
)
|
||||
from app.application.subscription.contract import SubscriptionIdentityConflictError, SubscriptionQueryPort
|
||||
from app.application.subscription.contract import (
|
||||
SubscriptionIdentity,
|
||||
SubscriptionIdentityConflictError,
|
||||
SubscriptionQueryPort,
|
||||
)
|
||||
from app.application.subscription.delete import (
|
||||
DeleteSubscribeCommand,
|
||||
SubscribeDeletionActor,
|
||||
@@ -465,20 +469,34 @@ async def subscribe_media_identity(
|
||||
year: Optional[str] = None,
|
||||
mtype: Optional[MediaType] = None,
|
||||
music_type: Optional[str] = None,
|
||||
episode_group: Optional[str] = None,
|
||||
query: SubscriptionQueryService = Depends(get_subscription_query_service),
|
||||
current_user: ApiPrincipal = Depends(get_current_active_user_async),
|
||||
) -> Any:
|
||||
"""
|
||||
根据媒体身份查询订阅,影视身份未命中时按类型、标题和可用年份跨源回退。
|
||||
按原生身份、共同 TMDB 身份依次查询,最后保留类型、标题和年份的提示回退。
|
||||
"""
|
||||
metadata = MetaInfo(title) if title else None
|
||||
normalized_title = metadata.name if metadata else None
|
||||
if season is None and metadata:
|
||||
season = metadata.begin_season
|
||||
subscribes = await query.list_by_media_identity(media_source, media_id, music_type)
|
||||
if mtype is not None:
|
||||
subscribes = [subscribe for subscribe in subscribes if subscribe.type == mtype.value]
|
||||
if season is not None:
|
||||
subscribes = [subscribe for subscribe in subscribes if subscribe.season == season]
|
||||
if episode_group is not None:
|
||||
subscribes = [subscribe for subscribe in subscribes if subscribe.episode_group == episode_group]
|
||||
result = select_accessible_subscribe(subscribes, current_user)
|
||||
if not result and mtype is not None and mtype in (MediaType.MOVIE, MediaType.TV):
|
||||
subscribes = await query.list_by_projected_identity(
|
||||
SubscriptionIdentity(
|
||||
media_source=media_source, media_id=media_id, type=mtype.value,
|
||||
season=season, episode_group=episode_group,
|
||||
),
|
||||
username=None if current_user.is_superuser else current_user.name,
|
||||
)
|
||||
result = select_accessible_subscribe(subscribes, current_user)
|
||||
if (
|
||||
not result
|
||||
and mtype in (MediaType.MOVIE, MediaType.TV)
|
||||
@@ -490,6 +508,8 @@ async def subscribe_media_identity(
|
||||
media_type=mtype,
|
||||
season=season,
|
||||
)
|
||||
if episode_group is not None:
|
||||
subscribes = [subscribe for subscribe in subscribes if subscribe.episode_group == episode_group]
|
||||
result = select_accessible_subscribe(subscribes, current_user)
|
||||
return result if result else _SchemaSubscribe()
|
||||
|
||||
|
||||
181
app/application/subscription/lookup.py
Normal file
181
app/application/subscription/lookup.py
Normal file
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
以共同的 TMDB 身份确认跨来源订阅,保留类型、季、剧集组和用户边界。
|
||||
|
||||
只读取快照和注入的身份转换能力,不修改旧订阅,也不把标题相似视为身份等价。
|
||||
"""
|
||||
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from dataclasses import replace
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.application.subscription.contract import SubscriptionIdentity, SubscriptionSnapshot
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
Projection = Callable[..., Optional[dict[str, Any]]]
|
||||
AsyncProjection = Callable[..., Awaitable[Optional[dict[str, Any]]]]
|
||||
|
||||
|
||||
def subscription_identity(record: SubscriptionSnapshot) -> SubscriptionIdentity:
|
||||
"""
|
||||
从已持久化的订阅构造包含类型及季集边界的完整身份。
|
||||
|
||||
:param record: 已脱离数据库会话的订阅快照
|
||||
:return: 保留来源、类型、季、剧集组及音乐实体的身份
|
||||
:raises ValueError: 快照缺少成对的来源和媒体标识
|
||||
"""
|
||||
source, media_id = resolve_media_identity(media=record)
|
||||
if source is None or media_id is None:
|
||||
raise ValueError("订阅缺少完整媒体身份")
|
||||
return SubscriptionIdentity(
|
||||
media_source=source,
|
||||
media_id=media_id,
|
||||
type=record.type,
|
||||
season=record.season,
|
||||
episode_group=record.episode_group,
|
||||
music_type=record.music_type,
|
||||
)
|
||||
|
||||
|
||||
class SubscriptionIdentityLookup:
|
||||
"""
|
||||
在一次操作内缓存身份投影,避免同作品多季或批量状态查询重复转换。
|
||||
"""
|
||||
|
||||
def __init__(self, project: Projection, async_project: AsyncProjection) -> None:
|
||||
"""
|
||||
注入同步、异步转换入口;缓存仅属于本实例,不跨请求保留失败结果。
|
||||
|
||||
:param project: 接收来源、媒体标识、类型和季号的同步媒体转换入口
|
||||
:param async_project: 与同步入口保持相同输入和结果语义的异步转换入口
|
||||
"""
|
||||
self._project = project
|
||||
self._async_project = async_project
|
||||
self._cache: dict[SubscriptionIdentity, Optional[SubscriptionIdentity]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _candidates(
|
||||
identity: SubscriptionIdentity,
|
||||
records: Sequence[SubscriptionSnapshot],
|
||||
username: Optional[str],
|
||||
) -> list[SubscriptionSnapshot]:
|
||||
"""
|
||||
在外部查询前限定用户、影视类型及剧集组;空用户名保留跳过查重的兼容语义。
|
||||
"""
|
||||
if username == "" or identity.type not in (MediaType.MOVIE.value, MediaType.TV.value):
|
||||
return []
|
||||
return [record for record in records
|
||||
if record.type == identity.type
|
||||
and record.episode_group == identity.episode_group
|
||||
and (identity.season is None or record.season == identity.season)
|
||||
and (username is None or record.username == username)
|
||||
and record.media_source and record.media_id]
|
||||
|
||||
@staticmethod
|
||||
def _converted(
|
||||
identity: SubscriptionIdentity,
|
||||
payload: Optional[dict[str, Any]],
|
||||
) -> Optional[SubscriptionIdentity]:
|
||||
"""
|
||||
只接纳有效 TMDB 标识;显式季优先,未指定季时采用来源投影确定的季号。
|
||||
"""
|
||||
source, media_id = resolve_media_identity(
|
||||
media_source=MediaSource.TMDB,
|
||||
media_id=str(payload.get("id") or "") if payload else None,
|
||||
)
|
||||
if source is None or media_id is None:
|
||||
return None
|
||||
projected_season = payload.get("season") if payload else None
|
||||
season = identity.season
|
||||
if season is None and isinstance(projected_season, int):
|
||||
season = projected_season
|
||||
return replace(identity, media_source=source, media_id=media_id, season=season)
|
||||
|
||||
def _resolve(self, identity: SubscriptionIdentity) -> Optional[SubscriptionIdentity]:
|
||||
"""
|
||||
同步取得共同身份,转换故障只影响跨源确认,不阻断原来源订阅。
|
||||
"""
|
||||
if identity.media_source == MediaSource.TMDB:
|
||||
return identity
|
||||
if identity not in self._cache:
|
||||
try:
|
||||
payload = self._project(
|
||||
target_source=MediaSource.TMDB, media_source=identity.media_source,
|
||||
media_id=identity.media_id, mtype=MediaType(identity.type), season=identity.season,
|
||||
)
|
||||
self._cache[identity] = self._converted(identity, payload)
|
||||
except Exception:
|
||||
logger.warning(f"订阅跨源身份查询失败,沿用原身份:{identity.media_source}:{identity.media_id}")
|
||||
self._cache[identity] = None
|
||||
return self._cache[identity]
|
||||
|
||||
async def _async_resolve(self, identity: SubscriptionIdentity) -> Optional[SubscriptionIdentity]:
|
||||
"""
|
||||
异步取得共同身份,与同步入口共享转换结果和失败回退规则。
|
||||
"""
|
||||
if identity.media_source == MediaSource.TMDB:
|
||||
return identity
|
||||
if identity not in self._cache:
|
||||
try:
|
||||
payload = await self._async_project(
|
||||
target_source=MediaSource.TMDB, media_source=identity.media_source,
|
||||
media_id=identity.media_id, mtype=MediaType(identity.type), season=identity.season,
|
||||
)
|
||||
self._cache[identity] = self._converted(identity, payload)
|
||||
except Exception:
|
||||
logger.warning(f"订阅跨源身份查询失败,沿用原身份:{identity.media_source}:{identity.media_id}")
|
||||
self._cache[identity] = None
|
||||
return self._cache[identity]
|
||||
|
||||
@staticmethod
|
||||
def _matches(target: SubscriptionIdentity, candidate: Optional[SubscriptionIdentity]) -> bool:
|
||||
"""
|
||||
在共同媒体身份下比较季,未指定目标季时允许返回该作品的各季订阅。
|
||||
"""
|
||||
return bool(candidate and target.media_id == candidate.media_id
|
||||
and (target.season is None or target.season == candidate.season))
|
||||
|
||||
def find(
|
||||
self, identity: SubscriptionIdentity, records: Sequence[SubscriptionSnapshot],
|
||||
username: Optional[str] = None,
|
||||
) -> list[SubscriptionSnapshot]:
|
||||
"""
|
||||
同步查找其它来源中身份已确认等价的订阅,不凭名称或数字 ID 跨源查重。
|
||||
|
||||
:param identity: 创建或查询使用的完整影视身份
|
||||
:param records: 从持久化端口读取的候选订阅快照
|
||||
:param username: 指定时仅匹配该用户;None 不限制,空字符串显式跳过查重
|
||||
:return: 共同 TMDB 身份及季集边界匹配的订阅,保持输入顺序
|
||||
"""
|
||||
candidates = [record for record in self._candidates(identity, records, username)
|
||||
if record.media_source != identity.media_source]
|
||||
if not candidates:
|
||||
return []
|
||||
target = self._resolve(identity)
|
||||
if target is None:
|
||||
return []
|
||||
return [record for record in candidates
|
||||
if self._matches(target, self._resolve(subscription_identity(record)))]
|
||||
|
||||
async def async_find(
|
||||
self, identity: SubscriptionIdentity, records: Sequence[SubscriptionSnapshot],
|
||||
username: Optional[str] = None,
|
||||
) -> list[SubscriptionSnapshot]:
|
||||
"""
|
||||
异步确认跨源订阅;顺序执行转换,避免并发复用请求数据库会话。
|
||||
|
||||
:param identity: 创建或查询使用的完整影视身份
|
||||
:param records: 从持久化端口读取的候选订阅快照
|
||||
:param username: 指定时仅匹配该用户;None 不限制,空字符串显式跳过查重
|
||||
:return: 已确认等价的订阅;转换失败的条目不参与匹配
|
||||
"""
|
||||
candidates = [record for record in self._candidates(identity, records, username)
|
||||
if record.media_source != identity.media_source]
|
||||
if not candidates:
|
||||
return []
|
||||
target = await self._async_resolve(identity)
|
||||
if target is None:
|
||||
return []
|
||||
return [record for record in candidates
|
||||
if self._matches(target, await self._async_resolve(subscription_identity(record)))]
|
||||
@@ -14,6 +14,7 @@ from app.application.subscription.contract import (
|
||||
SubscriptionQueryPort,
|
||||
SubscriptionSnapshot,
|
||||
)
|
||||
from app.application.subscription.lookup import SubscriptionIdentityLookup
|
||||
from app.domain.context import MediaInfo
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.schemas.common import JsonData
|
||||
@@ -25,7 +26,9 @@ from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
class SubscriptionQueryService:
|
||||
"""
|
||||
封装不修改订阅状态的三个公开查询用例。
|
||||
封装订阅列表、存在性和跨源身份查询,不修改订阅记录。
|
||||
|
||||
身份投影和候选快照缓存仅在配置了跨源查询能力的请求级实例内复用。
|
||||
"""
|
||||
|
||||
_SOURCE_FIELDS = {
|
||||
@@ -51,6 +54,7 @@ class SubscriptionQueryService:
|
||||
*,
|
||||
async_repository: Optional[SubscriptionQueryPort] = None,
|
||||
history_repository: Optional[SubscriptionHistoryQueryPort] = None,
|
||||
identity_lookup: Optional[SubscriptionIdentityLookup] = None,
|
||||
) -> None:
|
||||
"""
|
||||
保存订阅查询仓储端口。
|
||||
@@ -58,6 +62,8 @@ class SubscriptionQueryService:
|
||||
self._repository = repository
|
||||
self._async_repository = async_repository
|
||||
self._history_repository = history_repository
|
||||
self._identity_lookup = identity_lookup
|
||||
self._projection_records: Optional[list[SubscriptionSnapshot]] = None
|
||||
|
||||
@staticmethod
|
||||
def _to_public_view(record: Any) -> SubscribeView:
|
||||
@@ -140,6 +146,25 @@ class SubscriptionQueryService:
|
||||
if self._matches_music_type(record, music_type)
|
||||
]
|
||||
|
||||
async def list_by_projected_identity(
|
||||
self,
|
||||
identity: SubscriptionIdentity,
|
||||
username: Optional[str] = None,
|
||||
) -> list[SubscribeView]:
|
||||
"""
|
||||
通过共同 TMDB 身份读取跨源订阅,转换前先限制用户可见范围。
|
||||
|
||||
:param identity: 请求媒体的类型、来源及季集身份
|
||||
:param username: 普通用户的 owner 限定;管理员传 None
|
||||
:return: 身份转换确认等价的订阅;没有转换能力或转换失败时为空列表
|
||||
"""
|
||||
if self._async_repository is None or self._identity_lookup is None:
|
||||
return []
|
||||
if self._projection_records is None:
|
||||
self._projection_records = await self._async_repository.async_list()
|
||||
matches = await self._identity_lookup.async_find(identity, self._projection_records, username)
|
||||
return [self._to_public_view(record) for record in matches]
|
||||
|
||||
async def list_by_video_metadata(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -10,6 +10,7 @@ from enum import Enum, auto
|
||||
from typing import Any, Final, Optional, cast
|
||||
|
||||
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,
|
||||
@@ -30,6 +31,8 @@ class _ProjectionRule(Enum):
|
||||
DOUBAN_TO_TMDB = auto()
|
||||
# 根据 Bangumi 详情匹配 TMDB 身份。
|
||||
BANGUMI_TO_TMDB = auto()
|
||||
# 根据 AniList 的多语言标题、年份和季信息匹配 TMDB 身份。
|
||||
ANILIST_TO_TMDB = auto()
|
||||
# 根据 TMDB 详情匹配豆瓣身份。
|
||||
TMDB_TO_DOUBAN = auto()
|
||||
# 根据 Bangumi 详情匹配豆瓣身份。
|
||||
@@ -41,11 +44,13 @@ class _ProjectionRule(Enum):
|
||||
_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.TMDB, MediaSource.Douban): _ProjectionRule.TMDB_TO_DOUBAN,
|
||||
(MediaSource.Bangumi, MediaSource.Douban): _ProjectionRule.BANGUMI_TO_DOUBAN,
|
||||
}
|
||||
_NUMERIC_SOURCE_RULES: Final = {
|
||||
_ProjectionRule.BANGUMI_TO_TMDB,
|
||||
_ProjectionRule.ANILIST_TO_TMDB,
|
||||
_ProjectionRule.TMDB_TO_DOUBAN,
|
||||
_ProjectionRule.BANGUMI_TO_DOUBAN,
|
||||
}
|
||||
@@ -223,6 +228,27 @@ def _build_bangumi_tmdb_match(
|
||||
)
|
||||
|
||||
|
||||
def _build_anilist_tmdb_match(
|
||||
plan: _ProjectionPlan,
|
||||
source_info: _ProjectionSource,
|
||||
) -> Optional[_TmdbMatch]:
|
||||
"""
|
||||
复用 AniList 详情投影的多语言别名及续季解析,避免用季标题建立独立剧集身份。
|
||||
"""
|
||||
media = MediaInfo(anilist_info=dict(source_info))
|
||||
raw_names = _unique_names(tuple(media.names or []) + (media.title, media.original_title))
|
||||
names = _unique_names(tuple(MetaInfo(name).name for name in raw_names) + raw_names)
|
||||
if not names:
|
||||
return None
|
||||
return _TmdbMatch(
|
||||
names=names,
|
||||
year=_optional_text(media.year),
|
||||
media_type=plan.media_type or media.type or MediaType.TV,
|
||||
season=plan.season if plan.season is not None else media.season,
|
||||
include_season=True,
|
||||
)
|
||||
|
||||
|
||||
def _build_tmdb_douban_match(
|
||||
plan: _ProjectionPlan,
|
||||
source_info: _ProjectionSource,
|
||||
@@ -279,6 +305,7 @@ def _build_projection_match(
|
||||
builders = {
|
||||
_ProjectionRule.DOUBAN_TO_TMDB: _build_douban_tmdb_match,
|
||||
_ProjectionRule.BANGUMI_TO_TMDB: _build_bangumi_tmdb_match,
|
||||
_ProjectionRule.ANILIST_TO_TMDB: _build_anilist_tmdb_match,
|
||||
_ProjectionRule.TMDB_TO_DOUBAN: _build_tmdb_douban_match,
|
||||
_ProjectionRule.BANGUMI_TO_DOUBAN: _build_bangumi_douban_match,
|
||||
}
|
||||
@@ -295,6 +322,8 @@ def _load_projection_source(
|
||||
"""
|
||||
if plan.rule == _ProjectionRule.DOUBAN_TO_TMDB:
|
||||
return owner.douban_info(doubanid=plan.media_id, mtype=plan.media_type)
|
||||
if plan.rule == _ProjectionRule.ANILIST_TO_TMDB:
|
||||
return cast(Optional[_ProjectionPayload], owner.run_module("anilist_info", anilist_id=int(plan.media_id)))
|
||||
if plan.rule in {
|
||||
_ProjectionRule.BANGUMI_TO_TMDB,
|
||||
_ProjectionRule.BANGUMI_TO_DOUBAN,
|
||||
@@ -319,6 +348,8 @@ async def _async_load_projection_source(
|
||||
doubanid=plan.media_id,
|
||||
mtype=plan.media_type,
|
||||
)
|
||||
elif plan.rule == _ProjectionRule.ANILIST_TO_TMDB:
|
||||
source_info = await owner.async_run_module("async_anilist_info", anilist_id=int(plan.media_id))
|
||||
elif plan.rule in {
|
||||
_ProjectionRule.BANGUMI_TO_TMDB,
|
||||
_ProjectionRule.BANGUMI_TO_DOUBAN,
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
"""
|
||||
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from dataclasses import replace
|
||||
from typing import Any, Dict, Optional, Tuple, cast
|
||||
|
||||
from app.application.subscription.lookup import subscription_identity
|
||||
from app.application.subscription.write import (
|
||||
SubscriptionBatchWritePort,
|
||||
SubscriptionCreateRequest,
|
||||
@@ -15,7 +17,11 @@ from app.application.subscription.write import (
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.subscribe.context import _SubscribeCreateContext, _SubscribePostCommitContext
|
||||
from app.chain.subscribe.contract import _SubscribeOwnerBase
|
||||
from app.chain.subscribe.identity import media_recognize_kwargs
|
||||
from app.chain.subscribe.identity import (
|
||||
async_find_existing_subscription,
|
||||
find_existing_subscription,
|
||||
media_recognize_kwargs,
|
||||
)
|
||||
from app.domain.context import MediaInfo
|
||||
from app.domain.meta.metamusic import MetaMusic
|
||||
from app.domain.metainfo import MetaInfo
|
||||
@@ -612,6 +618,9 @@ class SubscribeCreateOwner(_SubscribeOwnerBase):
|
||||
"""
|
||||
if context.mediainfo is None:
|
||||
return None, "未识别到媒体信息"
|
||||
existing = find_existing_subscription(context, self.subscription_repository)
|
||||
if existing:
|
||||
return existing.id, "订阅已存在"
|
||||
mediainfo = context.mediainfo
|
||||
post_commit_context = self._SubscribeChain__subscribe_post_commit_context(
|
||||
context,
|
||||
@@ -647,6 +656,9 @@ class SubscribeCreateOwner(_SubscribeOwnerBase):
|
||||
"""
|
||||
if context.mediainfo is None:
|
||||
return None, "未识别到媒体信息"
|
||||
existing = await async_find_existing_subscription(context, self.subscription_repository)
|
||||
if existing:
|
||||
return existing.id, "订阅已存在"
|
||||
mediainfo = context.mediainfo
|
||||
post_commit_context = self._SubscribeChain__subscribe_post_commit_context(
|
||||
context,
|
||||
@@ -874,6 +886,9 @@ class SubscribeCreateOwner(_SubscribeOwnerBase):
|
||||
)
|
||||
if request is None:
|
||||
return None, "媒体身份不完整"
|
||||
existing = await async_find_existing_subscription(context, self.subscription_repository)
|
||||
if existing:
|
||||
request = replace(request, identity=subscription_identity(existing))
|
||||
requests.append(request)
|
||||
|
||||
results = await batch_writer.async_add(requests)
|
||||
|
||||
@@ -4,9 +4,55 @@
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.application.subscription.contract import SubscriptionSnapshot
|
||||
from app.application.subscription.contract import SubscriptionIdentity, SubscriptionQueryPort, SubscriptionSnapshot
|
||||
from app.application.subscription.lookup import SubscriptionIdentityLookup
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.subscribe.context import _SubscribeCreateContext
|
||||
from app.domain.context import MediaInfo
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.schemas.types import MediaType
|
||||
|
||||
|
||||
def create_subscription_identity(context: _SubscribeCreateContext) -> SubscriptionIdentity:
|
||||
"""
|
||||
从最终识别结果提取创建查重身份,保持用户选择的季和剧集组。
|
||||
"""
|
||||
source, media_id = resolve_media_identity(media=context.mediainfo)
|
||||
if source is None or media_id is None or context.mediainfo is None:
|
||||
raise ValueError("订阅创建缺少完整媒体身份")
|
||||
return SubscriptionIdentity(
|
||||
media_source=source, media_id=media_id,
|
||||
type=context.mediainfo.type.value if context.mediainfo.type else None,
|
||||
season=context.season, episode_group=context.mediainfo.episode_group,
|
||||
)
|
||||
|
||||
|
||||
def find_existing_subscription(
|
||||
context: _SubscribeCreateContext, repository: SubscriptionQueryPort,
|
||||
) -> SubscriptionSnapshot | None:
|
||||
"""
|
||||
在持久化前同步确认同用户的跨来源订阅,音乐和显式空用户沿用原查重规则。
|
||||
"""
|
||||
if context.mediainfo is None or context.mediainfo.type == MediaType.MUSIC or context.username == "":
|
||||
return None
|
||||
media = MediaChain()
|
||||
lookup = SubscriptionIdentityLookup(media.convert_media_identity, media.async_convert_media_identity)
|
||||
matches = lookup.find(create_subscription_identity(context), repository.list(), context.username)
|
||||
return matches[0] if matches else None
|
||||
|
||||
|
||||
async def async_find_existing_subscription(
|
||||
context: _SubscribeCreateContext, repository: SubscriptionQueryPort,
|
||||
) -> SubscriptionSnapshot | None:
|
||||
"""
|
||||
在异步和批量创建入口复用完整身份查重,不改写旧订阅的配置与进度。
|
||||
"""
|
||||
if context.mediainfo is None or context.mediainfo.type == MediaType.MUSIC or context.username == "":
|
||||
return None
|
||||
media = MediaChain()
|
||||
lookup = SubscriptionIdentityLookup(media.convert_media_identity, media.async_convert_media_identity)
|
||||
matches = await lookup.async_find(create_subscription_identity(context), await repository.async_list(), context.username)
|
||||
return matches[0] if matches else None
|
||||
|
||||
|
||||
def media_recognize_kwargs(mediainfo: MediaInfo) -> dict[str, Any]:
|
||||
|
||||
@@ -113,7 +113,7 @@ class SubscribeMetadataOwner(_SubscribeOwnerBase):
|
||||
media_chain_factory: Callable[[], Any],
|
||||
) -> Optional[SubscriptionSnapshot]:
|
||||
"""
|
||||
在元数据巡检中重试豆瓣或 Bangumi 到 TMDB 的订阅身份转换。
|
||||
在元数据巡检中重试豆瓣、Bangumi 或 AniList 到 TMDB 的订阅身份转换。
|
||||
|
||||
该补偿复用既有的 TMDB 元数据巡检周期。没有匹配结果、外部识别失败或目标身份
|
||||
已被其他订阅占用时保留原订阅,避免转换失败影响当前订阅的后续搜索。
|
||||
@@ -129,7 +129,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) or not media_id:
|
||||
if source not in (MediaSource.Douban, MediaSource.Bangumi, MediaSource.AniList) or not media_id:
|
||||
return None
|
||||
|
||||
media_chain = media_chain_factory()
|
||||
|
||||
@@ -850,8 +850,8 @@ flowchart LR
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1166 |
|
||||
| 内部导入边 | 10,185 |
|
||||
| Python 模块 | 1168 |
|
||||
| 内部导入边 | 10,206 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) |
|
||||
|
||||
@@ -207,9 +207,16 @@ Web 影视精确与标题 SSE 的 `manual_paging=true` 模式在最终 `done`
|
||||
### 大集合查询窗口
|
||||
|
||||
`POST /api/v1/media/status` 接受 1 至 50 个媒体身份/标题/年份/季号查询,按输入顺序返回
|
||||
`item_id`、`subscribed` 与同来源剧集的各季订阅模式 `seasons`。查询仅访问本地媒体库和
|
||||
当前用户可见订阅,不调用外部媒体服务器,不返回完整订阅表。普通用户仍受 owner 限制,
|
||||
影视保留标题、年份回退,音乐按实体类型隔离。该界面专用批量端点不新增 Agent 操作。
|
||||
`item_id`、`subscribed` 与已确认身份的各季订阅模式 `seasons`。查询使用本地媒体库和
|
||||
当前用户可见订阅,不调用外部媒体服务器,不返回完整订阅表。影视原生身份未命中时,
|
||||
复用媒体身份转换查询共同 TMDB 身份;同一请求内复用订阅快照和转换结果。
|
||||
转换可能读取外部元数据,失败后仍保留标题、年份提示回退。普通用户仍受 owner 限制,
|
||||
音乐按实体类型隔离。该界面专用批量端点不新增 Agent 操作。
|
||||
|
||||
`subscription.find` 也先按原生身份、再按共同 TMDB 身份查找;可通过 `episode_group`
|
||||
限定剧集组。创建影视订阅时,同用户、同类型、同季和同剧集组的跨源身份若已确认等价,
|
||||
返回已有订阅 ID,不覆盖旧配置、进度或重复发出新增通知。标题、年份相似只用于展示回退,
|
||||
不据此合并或删除订阅。TMDB、豆瓣、Bangumi 和 AniList 使用同一确认规则;音乐保持原规则。
|
||||
|
||||
`search.recommend` 的 `check_only=true` 只读当前状态,不读取全量搜索结果缓存;
|
||||
推荐禁用时也直接返回 `disabled`。`force=true` 保留优先级,确实启动任务时才读取候选。
|
||||
|
||||
@@ -19,7 +19,7 @@ _QUERY_FIELDS = {
|
||||
"search.results": frozenset(),
|
||||
"subscription.list": _PAGINATION,
|
||||
"subscription.find": frozenset(
|
||||
{"media_source", "season", "title", "music_type", "mtype", "year"}
|
||||
{"media_source", "season", "title", "music_type", "mtype", "year", "episode_group"}
|
||||
),
|
||||
"subscription.get": frozenset(),
|
||||
"subscription.add": frozenset(),
|
||||
@@ -366,7 +366,7 @@ class EvaluationWorld:
|
||||
value = query.get(field)
|
||||
if value is not None and (type(value) is not int or value < 1 or (field == "count" and value > 200)):
|
||||
return "分页参数必须为有效正整数,count 不得超过 200"
|
||||
for field in ("name", "title", "music_type", "media_id", "media_source", "mtype", "year"):
|
||||
for field in ("name", "title", "music_type", "media_id", "media_source", "mtype", "year", "episode_group"):
|
||||
if query.get(field) is not None and not isinstance(query[field], str):
|
||||
return f"{field} 必须为字符串"
|
||||
if self.scenario.scenario_id in _LONG_CONTEXT_SCENARIOS:
|
||||
@@ -454,6 +454,8 @@ class EvaluationWorld:
|
||||
matched = row["media_source"] == query["media_source"] and row["media_id"] == path_params["media_id"]
|
||||
matched = matched and (query.get("season") is None or row.get("season") == query["season"])
|
||||
matched = matched and (query.get("music_type") is None or row.get("music_type") == query["music_type"])
|
||||
matched = matched and (query.get("mtype") is None or row.get("type") == query["mtype"])
|
||||
matched = matched and (query.get("episode_group") is None or row.get("episode_group") == query["episode_group"])
|
||||
if matched:
|
||||
event["observations"].append({"kind": "subscription", "record": deepcopy(row)})
|
||||
return _result("succeeded", "查询成功", row)
|
||||
|
||||
@@ -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 = "74"
|
||||
MOVIEPILOT_API_SKILL_VERSION = "75"
|
||||
DATABASE_OPERATION_SKILL_VERSION = "19"
|
||||
|
||||
|
||||
@@ -389,8 +389,10 @@ _OPERATION_NOTES: dict[str, list[str]] = {
|
||||
# 在生成的 Schema 字段旁保留经过维护的操作指引。
|
||||
_OPERATION_PURPOSE_NOTES: dict[str, str] = {
|
||||
"subscription.find": (
|
||||
"For movies and TV, if exact identity misses and mtype/title are supplied, match across "
|
||||
"sources by type, normalized title, optional season, and year. An exact year ranks first; "
|
||||
"For movies and TV, if exact identity misses and mtype is supplied, first confirm "
|
||||
"cross-source subscriptions through a shared TMDB identity, preserving season, episode "
|
||||
"group and owner boundaries. If projection fails and title is supplied, retain the "
|
||||
"type/title/year fallback as a display hint. An exact year ranks first; "
|
||||
"a subscription with no year may match when the card has a year, while a card with no "
|
||||
"year only matches a subscription with no year. Music uses exact identity only."
|
||||
),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: moviepilot-api
|
||||
version: 74
|
||||
version: 75
|
||||
description: >-
|
||||
Use this skill for MoviePilot product operations such as media search, torrent
|
||||
search, downloads, subscriptions, library checks, sites, storage, workflows,
|
||||
|
||||
@@ -63,10 +63,10 @@ Identity scope: `bound_user`; required role: `user`.
|
||||
|
||||
### `subscription.find`
|
||||
`GET /api/v1/subscribe/media/{media_id}`; policy effect: `safe_read`.
|
||||
Purpose: 按规范媒体身份和可选季查找一个可访问订阅。 For movies and TV, if exact identity misses and mtype/title are supplied, match across sources by type, normalized title, optional season, and year. An exact year ranks first; a subscription with no year may match when the card has a year, while a card with no year only matches a subscription with no year. Music uses exact identity only.
|
||||
Purpose: 按规范媒体身份和可选季查找一个可访问订阅。 For movies and TV, if exact identity misses and mtype is supplied, first confirm cross-source subscriptions through a shared TMDB identity, preserving season, episode group and owner boundaries. If projection fails and title is supplied, retain the type/title/year fallback as a display hint. An exact year ranks first; a subscription with no year may match when the card has a year, while a card with no year only matches a subscription with no year. Music uses exact identity only.
|
||||
Identity scope: `bound_user`; required role: `user`.
|
||||
- `path_params`: `media_id*` (string): 来源原生媒体标识,始终与搜索返回的精确 media_source 配对。
|
||||
- `query`: `media_source*` (MediaSource): 元数据来源标识,保留与 media_id 一同返回的精确值。; `mtype` (MediaType|null): 操作要求的媒体类型或订阅历史分类。; `music_type` (string|null): 音乐身份层级:按操作支持范围选择 recording、album 或 artist。; `season` (integer|null): 媒体、搜索、订阅或整理操作使用的季号。; `title` (string|null): 操作使用的媒体、种子、订阅或历史标题。; `year` (string|null): 用于区分同名媒体的发行或首映年份。
|
||||
- `query`: `episode_group` (string|null): 用于其他剧集排序方式的 TMDB 剧集组标识。; `media_source*` (MediaSource): 元数据来源标识,保留与 media_id 一同返回的精确值。; `mtype` (MediaType|null): 操作要求的媒体类型或订阅历史分类。; `music_type` (string|null): 音乐身份层级:按操作支持范围选择 recording、album 或 artist。; `season` (integer|null): 媒体、搜索、订阅或整理操作使用的季号。; `title` (string|null): 操作使用的媒体、种子、订阅或历史标题。; `year` (string|null): 用于区分同名媒体的发行或首映年份。
|
||||
- `body`: none
|
||||
|
||||
### `subscription.follow.add`
|
||||
|
||||
@@ -977,8 +977,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10185,
|
||||
"edge_sha256": "7f38852ed55a0002549c7dbe94b8810841659290fce66ed8721376f3a518dc14",
|
||||
"edge_count": 10206,
|
||||
"edge_sha256": "87ecd2cdf5db4efafc8ef84af564b7ffcfe5dd30298fdeefbbb004a2a5b60a10",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -2333,11 +2333,14 @@
|
||||
"app.api.dependencies.subscription -> app.application.subscription.delete",
|
||||
"app.api.dependencies.subscription -> app.application.subscription.execution",
|
||||
"app.api.dependencies.subscription -> app.application.subscription.identity",
|
||||
"app.api.dependencies.subscription -> app.application.subscription.lookup",
|
||||
"app.api.dependencies.subscription -> app.application.subscription.mutation",
|
||||
"app.api.dependencies.subscription -> app.application.subscription.query",
|
||||
"app.api.dependencies.subscription -> app.application.subscription.search",
|
||||
"app.api.dependencies.subscription -> app.application.subscription.status",
|
||||
"app.api.dependencies.subscription -> app.application.subscription.write",
|
||||
"app.api.dependencies.subscription -> app.chain",
|
||||
"app.api.dependencies.subscription -> app.chain.media",
|
||||
"app.api.dependencies.subscription -> app.runtime",
|
||||
"app.api.dependencies.subscription -> app.runtime.events",
|
||||
"app.api.dependencies.subscription -> app.runtime.log",
|
||||
@@ -2735,6 +2738,7 @@
|
||||
"app.api.endpoints.media -> app.application.plugin",
|
||||
"app.api.endpoints.media -> app.application.plugin.runtime",
|
||||
"app.api.endpoints.media -> app.application.subscription",
|
||||
"app.api.endpoints.media -> app.application.subscription.contract",
|
||||
"app.api.endpoints.media -> app.application.subscription.query",
|
||||
"app.api.endpoints.media -> app.chain",
|
||||
"app.api.endpoints.media -> app.chain.media",
|
||||
@@ -4412,6 +4416,14 @@
|
||||
"app.application.subscription.identity -> app.schemas",
|
||||
"app.application.subscription.identity -> app.schemas.common",
|
||||
"app.application.subscription.identity -> app.schemas.types",
|
||||
"app.application.subscription.lookup -> app.application",
|
||||
"app.application.subscription.lookup -> app.application.subscription",
|
||||
"app.application.subscription.lookup -> app.application.subscription.contract",
|
||||
"app.application.subscription.lookup -> app.runtime",
|
||||
"app.application.subscription.lookup -> app.runtime.log",
|
||||
"app.application.subscription.lookup -> app.schemas",
|
||||
"app.application.subscription.lookup -> app.schemas.media",
|
||||
"app.application.subscription.lookup -> app.schemas.types",
|
||||
"app.application.subscription.mutation -> app.application",
|
||||
"app.application.subscription.mutation -> app.application.classification",
|
||||
"app.application.subscription.mutation -> app.application.classification.reference",
|
||||
@@ -4446,6 +4458,7 @@
|
||||
"app.application.subscription.query -> app.application",
|
||||
"app.application.subscription.query -> app.application.subscription",
|
||||
"app.application.subscription.query -> app.application.subscription.contract",
|
||||
"app.application.subscription.query -> app.application.subscription.lookup",
|
||||
"app.application.subscription.query -> app.domain",
|
||||
"app.application.subscription.query -> app.domain.context",
|
||||
"app.application.subscription.query -> app.domain.meta",
|
||||
@@ -5163,6 +5176,7 @@
|
||||
"app.chain.media.projection -> app.chain.media",
|
||||
"app.chain.media.projection -> app.chain.media.contract",
|
||||
"app.chain.media.projection -> app.domain",
|
||||
"app.chain.media.projection -> app.domain.context",
|
||||
"app.chain.media.projection -> app.domain.metainfo",
|
||||
"app.chain.media.projection -> app.domain.projection",
|
||||
"app.chain.media.projection -> app.domain.projection.bangumi",
|
||||
@@ -5665,6 +5679,7 @@
|
||||
"app.chain.subscribe.context -> app.schemas.types",
|
||||
"app.chain.subscribe.create -> app.application",
|
||||
"app.chain.subscribe.create -> app.application.subscription",
|
||||
"app.chain.subscribe.create -> app.application.subscription.lookup",
|
||||
"app.chain.subscribe.create -> app.application.subscription.write",
|
||||
"app.chain.subscribe.create -> app.chain",
|
||||
"app.chain.subscribe.create -> app.chain.media",
|
||||
@@ -5719,10 +5734,16 @@
|
||||
"app.chain.subscribe.identity -> app.application",
|
||||
"app.chain.subscribe.identity -> app.application.subscription",
|
||||
"app.chain.subscribe.identity -> app.application.subscription.contract",
|
||||
"app.chain.subscribe.identity -> app.application.subscription.lookup",
|
||||
"app.chain.subscribe.identity -> app.chain",
|
||||
"app.chain.subscribe.identity -> app.chain.media",
|
||||
"app.chain.subscribe.identity -> app.chain.subscribe",
|
||||
"app.chain.subscribe.identity -> app.chain.subscribe.context",
|
||||
"app.chain.subscribe.identity -> app.domain",
|
||||
"app.chain.subscribe.identity -> app.domain.context",
|
||||
"app.chain.subscribe.identity -> app.schemas",
|
||||
"app.chain.subscribe.identity -> app.schemas.media",
|
||||
"app.chain.subscribe.identity -> app.schemas.types",
|
||||
"app.chain.subscribe.interaction -> app.application",
|
||||
"app.chain.subscribe.interaction -> app.application.messaging",
|
||||
"app.chain.subscribe.interaction -> app.application.messaging.subscribe",
|
||||
@@ -11166,7 +11187,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1167,
|
||||
"module_count": 1168,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -11591,6 +11612,7 @@
|
||||
"app.application.subscription.execution",
|
||||
"app.application.subscription.facts",
|
||||
"app.application.subscription.identity",
|
||||
"app.application.subscription.lookup",
|
||||
"app.application.subscription.mutation",
|
||||
"app.application.subscription.observability",
|
||||
"app.application.subscription.priority",
|
||||
|
||||
@@ -8623,7 +8623,7 @@
|
||||
}
|
||||
},
|
||||
"run_module": {
|
||||
"call_count": 276,
|
||||
"call_count": 278,
|
||||
"dynamic_call_count": 0,
|
||||
"dynamic_calls": [],
|
||||
"method_count": 224,
|
||||
@@ -8647,6 +8647,11 @@
|
||||
"caller": "app.chain.anilist",
|
||||
"count": 1,
|
||||
"mode": "sync"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.media.projection",
|
||||
"count": 1,
|
||||
"mode": "sync"
|
||||
}
|
||||
],
|
||||
"anilist_person_credits": [
|
||||
@@ -8710,6 +8715,11 @@
|
||||
"caller": "app.chain.anilist",
|
||||
"count": 1,
|
||||
"mode": "async"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.media.projection",
|
||||
"count": 1,
|
||||
"mode": "async"
|
||||
}
|
||||
],
|
||||
"async_anilist_person_credits": [
|
||||
|
||||
@@ -131,6 +131,20 @@ def test_existing_identity_is_found_under_old_title_without_writing() -> None:
|
||||
assert world.ledger[0]["observations"] == [{"kind": "subscription", "record": subscription["data"]}]
|
||||
|
||||
|
||||
def test_subscription_lookup_filters_episode_group_without_writing() -> None:
|
||||
"""
|
||||
独立评测世界接受剧集组筛选,错误类型不产生证据,未命中的组不返回其它组订阅。
|
||||
"""
|
||||
world = EvaluationWorld("dedup_existing")
|
||||
query = {"media_source": world.scenario.media_source, "episode_group": "alternate"}
|
||||
result = world.execute("subscription.find", path_params={"media_id": world.scenario.media_id}, query=query)
|
||||
assert result["outcome"] == "succeeded" and result["data"] == {}
|
||||
query["episode_group"] = 1
|
||||
result = world.execute("subscription.find", path_params={"media_id": world.scenario.media_id}, query=query)
|
||||
assert result["outcome"] == "failed"
|
||||
assert world.snapshot() == world.initial_snapshot()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation,arguments", [
|
||||
("download.list", {}),
|
||||
("download.tasks.active", {"query": {"infohash": "a1" * 20}}),
|
||||
|
||||
@@ -130,7 +130,7 @@ def test_modified_builtin_skills_have_incremented_versions() -> None:
|
||||
"database-operation": "19",
|
||||
"feedback-issue": "12",
|
||||
"anysearch": "3",
|
||||
"moviepilot-api": "74",
|
||||
"moviepilot-api": "75",
|
||||
"moviepilot-update": "7",
|
||||
"organize-files": "6",
|
||||
"transfer-failed-retry": "7",
|
||||
|
||||
@@ -27,6 +27,7 @@ def services():
|
||||
SimpleNamespace(
|
||||
list_by_media_identity=AsyncMock(return_value=[]),
|
||||
list_by_video_metadata=AsyncMock(return_value=[]),
|
||||
list_by_projected_identity=AsyncMock(return_value=[]),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -49,7 +49,11 @@ def _load_subscribe_chain_class():
|
||||
chain_module.__path__ = []
|
||||
|
||||
class _ChainBase:
|
||||
subscription_repository = SimpleNamespace()
|
||||
"""
|
||||
为隔离链测试提供空订阅仓储及动态修改事务接缝。
|
||||
"""
|
||||
|
||||
subscription_repository = SimpleNamespace(list=lambda: [], async_list=AsyncMock(return_value=[]))
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
@@ -638,7 +642,7 @@ def _load_subscribe_chain_class():
|
||||
保留存量单元测试按调用时替换 repository 的隔离接缝。
|
||||
"""
|
||||
|
||||
subscription_repository = SimpleNamespace()
|
||||
subscription_repository = SimpleNamespace(list=lambda: [], async_list=AsyncMock(return_value=[]))
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
@@ -3542,6 +3546,7 @@ class TestSubscribeProgressConsolidation:
|
||||
year="2026",
|
||||
media_source="themoviedb",
|
||||
media_id="31000",
|
||||
episode_group=None,
|
||||
vote_average=9.5,
|
||||
overview="overview",
|
||||
imdb_id="tt1234567",
|
||||
|
||||
338
tests/test_subscription_cross_source.py
Normal file
338
tests/test_subscription_cross_source.py
Normal file
@@ -0,0 +1,338 @@
|
||||
"""
|
||||
跨来源订阅的身份确认、创建幂等和页面状态回归,全程隔离外部媒体查询。
|
||||
"""
|
||||
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.endpoints.media import media_status
|
||||
from app.api.endpoints.subscribe import subscribe_media_identity
|
||||
from app.application.subscription.contract import SubscriptionIdentity, SubscriptionSnapshot
|
||||
from app.application.subscription.lookup import SubscriptionIdentityLookup
|
||||
from app.application.subscription.query import SubscriptionQueryService
|
||||
from app.application.subscription.write import AsyncCreateSubscriptionBatchCommand
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.subscribe import identity as identity_owner
|
||||
from app.chain.subscribe.context import _SubscribeCreateContext
|
||||
from app.chain.subscribe.create import SubscribeCreateOwner
|
||||
from app.chain.subscribe.metadata import SubscribeMetadataOwner
|
||||
from app.db.adapters.subscription import SessionSubscriptionRepository, TransactionalSubscriptionRepository
|
||||
from app.db.models.subscribe import Subscribe
|
||||
from app.db.session import SessionFactory, async_session_scope
|
||||
from app.db.uow import SqlAlchemyAsyncUnitOfWork
|
||||
from app.domain.context import MediaInfo
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.schemas.media import MediaStatusQuery
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def projection():
|
||||
"""
|
||||
注入可观察的同步、异步投影,两个原生 ID 默认指向同一 TMDB 作品。
|
||||
"""
|
||||
sync = Mock(return_value={"id": 259140})
|
||||
asynchronous = AsyncMock(return_value={"id": 259140})
|
||||
return sync, asynchronous, SubscriptionIdentityLookup(sync, asynchronous)
|
||||
|
||||
|
||||
def _record(source=MediaSource.Bangumi, **changes):
|
||||
"""
|
||||
构造带真实进度及保存配置的不可变订阅快照。
|
||||
"""
|
||||
return replace(SubscriptionSnapshot(
|
||||
id=73, name="舊來源的標題", year="2026", type=MediaType.TV.value,
|
||||
media_source=source, media_id="637802", season=2, episode_group=None,
|
||||
username="alice", lack_episode=3, total_episode=12, save_path="/library/anime",
|
||||
), **changes)
|
||||
|
||||
|
||||
def _identity(source=MediaSource.TMDB, **changes):
|
||||
"""
|
||||
构造完整查重身份,辅助 ID 数字相同不代表来源相同。
|
||||
"""
|
||||
return replace(SubscriptionIdentity(
|
||||
media_source=source, media_id="259140", type=MediaType.TV.value, season=2,
|
||||
), **changes)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("source", [MediaSource.Douban, MediaSource.Bangumi, MediaSource.AniList])
|
||||
@pytest.mark.parametrize("reverse", [False, True])
|
||||
async def test_lookup_confirms_identity_in_both_creation_orders(projection, source, reverse):
|
||||
"""
|
||||
新旧条目的名称、年份不同仍按投影身份查重,覆盖各来源先后创建的两个方向。
|
||||
"""
|
||||
sync, asynchronous, lookup = projection
|
||||
target = _identity(source if reverse else MediaSource.TMDB)
|
||||
record = _record(MediaSource.TMDB if reverse else source,
|
||||
media_id="259140" if reverse else "637802", year="2024")
|
||||
assert lookup.find(target, [record], "alice") == [record]
|
||||
async_lookup = SubscriptionIdentityLookup(sync, asynchronous)
|
||||
assert await async_lookup.async_find(target, [record], "alice") == [record]
|
||||
assert record.lack_episode == 3 and record.save_path == "/library/anime"
|
||||
assert sync.call_count == asynchronous.await_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("changes,username", [
|
||||
({"type": MediaType.MOVIE.value}, "alice"),
|
||||
({"season": 1}, "alice"),
|
||||
({"episode_group": "alternate"}, "alice"),
|
||||
({"username": "bob"}, "alice"),
|
||||
({}, ""),
|
||||
({"media_source": MediaSource.TMDB, "media_id": "637802"}, "alice"),
|
||||
])
|
||||
async def test_lookup_keeps_type_season_group_and_owner_boundaries(projection, changes, username):
|
||||
"""
|
||||
不同季、类型、剧集组、用户和同来源不同作品不能通过跨源查重合并,且不发起投影。
|
||||
"""
|
||||
sync, asynchronous, lookup = projection
|
||||
record = _record(**changes)
|
||||
assert lookup.find(_identity(), [record], username) == []
|
||||
assert await lookup.async_find(_identity(), [record], username) == []
|
||||
sync.assert_not_called()
|
||||
asynchronous.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("result", [None, {}, {"id": 0}, {"id": 999}])
|
||||
@pytest.mark.parametrize("reverse", [False, True])
|
||||
async def test_lookup_does_not_deduplicate_unconfirmed_or_conflicting_ids(projection, result, reverse):
|
||||
"""
|
||||
相同数字原生 ID 或相同标题不能替代有效的共同身份,投影失败和冲突均保留独立订阅。
|
||||
"""
|
||||
sync, asynchronous, lookup = projection
|
||||
sync.return_value = asynchronous.return_value = result
|
||||
record = _record(MediaSource.TMDB if reverse else MediaSource.Bangumi, media_id="259140")
|
||||
target = _identity(MediaSource.Bangumi if reverse else MediaSource.TMDB)
|
||||
assert lookup.find(target, [record], "alice") == []
|
||||
assert await SubscriptionIdentityLookup(sync, asynchronous).async_find(target, [record], "alice") == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lookup_projection_errors_are_cached_only_within_operation(projection):
|
||||
"""
|
||||
外部转换故障保留原身份,同一次查询不反复请求,下一次操作允许重试。
|
||||
"""
|
||||
sync, asynchronous, lookup = projection
|
||||
sync.side_effect = RuntimeError("offline")
|
||||
asynchronous.side_effect = RuntimeError("offline")
|
||||
assert lookup.find(_identity(), [_record()]) == []
|
||||
assert lookup.find(_identity(), [_record()]) == []
|
||||
assert sync.call_count == 1
|
||||
assert await SubscriptionIdentityLookup(sync, asynchronous).async_find(_identity(), [_record()]) == []
|
||||
asynchronous.side_effect = None
|
||||
assert await SubscriptionIdentityLookup(sync, asynchronous).async_find(_identity(), [_record()]) == [_record()]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lookup_retains_projected_season_zero_and_reuses_batch_projection(projection):
|
||||
"""
|
||||
来源投影得到的第零季不能退回第一季,批量重复查询共享当前操作缓存。
|
||||
"""
|
||||
sync, asynchronous, lookup = projection
|
||||
asynchronous.return_value = {"id": 259140, "season": 0}
|
||||
target = _identity(MediaSource.AniList, season=None)
|
||||
record = _record(MediaSource.TMDB, media_id="259140", season=0)
|
||||
for _ in range(2):
|
||||
assert await lookup.async_find(target, [record, replace(record, id=74, season=1)]) == [record]
|
||||
asynchronous.assert_awaited_once()
|
||||
sync.assert_not_called()
|
||||
|
||||
|
||||
def _context(source=MediaSource.TMDB):
|
||||
"""
|
||||
构造已经完成识别与季集准备的真实创建上下文。
|
||||
"""
|
||||
media = MediaInfo(media_source=source, media_id="259140", type=MediaType.TV, title="新來源標題")
|
||||
return _SubscribeCreateContext(
|
||||
title=media.title, year="2026", mtype=MediaType.TV, episode_group=None, season=2,
|
||||
channel=None, source=None, userid=None, username="alice", message=False, exist_ok=False,
|
||||
options={}, explicit_identity=True, media_source=source, media_id=media.media_id,
|
||||
requested_music_type=None, metainfo=MetaInfo(media.title), mediainfo=media,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("skip_reason", ["music", "empty_user"])
|
||||
async def test_creation_lookup_keeps_music_and_explicit_empty_user_contract(skip_reason):
|
||||
"""
|
||||
音乐及显式跳过查重的空用户不读取影视候选,也不触发任何跨源转换。
|
||||
"""
|
||||
context = _context()
|
||||
if skip_reason == "music":
|
||||
context.mediainfo.type = MediaType.MUSIC
|
||||
else:
|
||||
context.username = ""
|
||||
repository = Mock()
|
||||
assert identity_owner.find_existing_subscription(context, repository) is None
|
||||
assert await identity_owner.async_find_existing_subscription(context, repository) is None
|
||||
repository.list.assert_not_called()
|
||||
repository.async_list.assert_not_called()
|
||||
|
||||
|
||||
def test_anilist_metadata_retry_uses_the_existing_refresh_cycle():
|
||||
"""
|
||||
AniList 存量订阅也使用既有元数据巡检转换身份,成功时原位保留其订阅与进度。
|
||||
"""
|
||||
record = _record(MediaSource.AniList)
|
||||
converted = MediaInfo(media_source=MediaSource.TMDB, media_id="259140", type=MediaType.TV,
|
||||
title="统一后的作品", year="2024", seasons={2: [1, 2, 3]})
|
||||
media = SimpleNamespace(convert_media_identity=Mock(return_value={"id": 259140}),
|
||||
recognize_media=Mock(return_value=converted))
|
||||
updated = replace(record, media_source=MediaSource.TMDB, media_id="259140")
|
||||
owner = SimpleNamespace(_SubscribeChain__is_tmdb_recognize_source=lambda: True,
|
||||
_SubscribeChain__apply_subscribe_update=Mock(return_value=updated))
|
||||
result = SubscribeMetadataOwner._retry_subscribe_media_identity(owner, record, MetaInfo("作品 S02"), lambda: media)
|
||||
assert result is updated
|
||||
assert result.id == record.id and result.lack_episode == record.lack_episode
|
||||
assert owner._SubscribeChain__apply_subscribe_update.call_args.args[1]["media_source"] == MediaSource.TMDB
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_creation_returns_existing_id_without_write_or_post_commit(projection, monkeypatch):
|
||||
"""
|
||||
同步、异步创建确认重复后直接返回旧 ID,不重写进度,也不重发新增通知或下载副作用。
|
||||
"""
|
||||
sync, asynchronous, _ = projection
|
||||
media = SimpleNamespace(convert_media_identity=sync, async_convert_media_identity=asynchronous)
|
||||
monkeypatch.setattr(identity_owner, "MediaChain", lambda: media)
|
||||
record = _record()
|
||||
repository = SimpleNamespace(list=Mock(return_value=[record]), async_list=AsyncMock(return_value=[record]))
|
||||
owner = SimpleNamespace(subscription_repository=repository)
|
||||
assert SubscribeCreateOwner._SubscribeChain__persist_subscribe_create(owner, _context()) == (73, "订阅已存在")
|
||||
assert await SubscribeCreateOwner._SubscribeChain__async_persist_subscribe_create(owner, _context()) == (73, "订阅已存在")
|
||||
assert record.lack_episode == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_mode", [False, True])
|
||||
async def test_creation_reuses_database_subscription_and_preserves_progress(db, projection, monkeypatch, async_mode):
|
||||
"""
|
||||
真实数据库中旧来源订阅保持单行,名称、下载缺口和目标路径不会被新的来源覆写。
|
||||
"""
|
||||
db.watermark(Subscribe)
|
||||
with SessionFactory() as session:
|
||||
record = Subscribe(**{key: value for key, value in _record().to_dict().items()
|
||||
if key not in {"id", "activity_key"}})
|
||||
session.add(record)
|
||||
session.commit()
|
||||
subscribe_id = record.id
|
||||
sync, asynchronous, _ = projection
|
||||
monkeypatch.setattr(identity_owner, "MediaChain", lambda: SimpleNamespace(
|
||||
convert_media_identity=sync, async_convert_media_identity=asynchronous,
|
||||
))
|
||||
repository = TransactionalSubscriptionRepository(sync_session=SessionFactory, async_session=async_session_scope)
|
||||
owner = SimpleNamespace(subscription_repository=repository)
|
||||
if async_mode:
|
||||
result = await SubscribeCreateOwner._SubscribeChain__async_persist_subscribe_create(owner, _context())
|
||||
else:
|
||||
result = SubscribeCreateOwner._SubscribeChain__persist_subscribe_create(owner, _context())
|
||||
assert result == (subscribe_id, "订阅已存在")
|
||||
actual = repository.get(subscribe_id)
|
||||
assert actual.name == "舊來源的標題" and actual.media_source == MediaSource.Bangumi
|
||||
assert actual.lack_episode == 3 and actual.save_path == "/library/anime"
|
||||
assert not [record for record in repository.list() if record.media_source == MediaSource.TMDB
|
||||
and record.media_id == "259140" and record.username == "alice"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_skips_duplicate_season_and_creates_remaining_season(db, projection, monkeypatch):
|
||||
"""
|
||||
批量跨源订阅复用旧季 ID,同时正常提交其它季,重复季不产生新的持久副作用。
|
||||
"""
|
||||
db.watermark(Subscribe)
|
||||
async with async_session_scope() as session:
|
||||
record = Subscribe(name="舊來源的標題", type=MediaType.TV.value, media_source=MediaSource.Bangumi,
|
||||
media_id="637802", season=2, username="alice", lack_episode=3)
|
||||
session.add(record)
|
||||
await session.commit()
|
||||
subscribe_id = record.id
|
||||
sync, asynchronous, _ = projection
|
||||
monkeypatch.setattr(identity_owner, "MediaChain", lambda: SimpleNamespace(
|
||||
convert_media_identity=sync, async_convert_media_identity=asynchronous,
|
||||
))
|
||||
contexts = [(_context(), None), (replace(_context(), season=3), None)]
|
||||
prepare = AsyncMock(side_effect=contexts)
|
||||
repository = SessionSubscriptionRepository(session)
|
||||
outbox = SimpleNamespace(stage=AsyncMock())
|
||||
command = AsyncCreateSubscriptionBatchCommand(repository, SqlAlchemyAsyncUnitOfWork(session), outbox)
|
||||
captured = []
|
||||
|
||||
async def persist(requests):
|
||||
"""
|
||||
保留真实批量事务,收集每季的新增或复用结果。
|
||||
"""
|
||||
results = await command.execute(requests)
|
||||
captured.extend(results)
|
||||
return results
|
||||
|
||||
owner = SimpleNamespace(
|
||||
subscription_repository=repository,
|
||||
_SubscribeChain__async_prepare_subscribe_create=prepare,
|
||||
_SubscribeChain__build_subscribe_notification=Mock(return_value=None),
|
||||
_SubscribeChain__subscribe_post_commit_context=SubscribeCreateOwner._SubscribeChain__subscribe_post_commit_context,
|
||||
)
|
||||
result = await SubscribeCreateOwner.async_add_batch(
|
||||
owner, title="新來源標題", year="2026", seasons=[2, 3],
|
||||
batch_writer=SimpleNamespace(async_add=persist), username="alice",
|
||||
)
|
||||
assert captured[0].subscribe_id == subscribe_id and not captured[0].created
|
||||
assert captured[1].created and result[0] == captured[1].subscribe_id
|
||||
assert outbox.stage.await_count == 2
|
||||
assert (await repository.async_get(subscribe_id)).lack_episode == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_detail_and_card_status_use_projection_before_title_fallback(projection):
|
||||
"""
|
||||
详情与卡片在标题不同、未提供年份时也能显示已订阅,并保留当前用户及季模式。
|
||||
"""
|
||||
_, _, lookup = projection
|
||||
record = _record()
|
||||
repository = SimpleNamespace(async_list_by_media_identity=AsyncMock(return_value=[]),
|
||||
async_list=AsyncMock(return_value=[record, replace(record, id=74, username="bob")]),
|
||||
async_list_by_title=AsyncMock(return_value=[]))
|
||||
query = SubscriptionQueryService(repository, async_repository=repository, identity_lookup=lookup)
|
||||
actor = SimpleNamespace(name="alice", is_superuser=False)
|
||||
result = await subscribe_media_identity("259140", MediaSource.TMDB, season=2, title="新來源標題",
|
||||
mtype=MediaType.TV, query=query, current_user=actor)
|
||||
assert result.id == 73
|
||||
statuses = await media_status([
|
||||
MediaStatusQuery(media_source=MediaSource.TMDB, media_id="259140", season=2, mtype=MediaType.TV),
|
||||
], SimpleNamespace(find_item_id=AsyncMock(return_value=None)), query, actor)
|
||||
assert statuses[0].subscribed is True and statuses[0].seasons == {2: "normal"}
|
||||
repository.async_list_by_title.assert_not_awaited()
|
||||
repository.async_list.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_mode", [False, True])
|
||||
async def test_anilist_projection_uses_native_dispatch_and_season_aliases(async_mode):
|
||||
"""
|
||||
AniList 内置转换通过模块分发读取多语言条目,保留续季和年份,并隔离对目标详情的修改。
|
||||
"""
|
||||
source = {"id": 187999, "title": {"chinese": "青之蘆葦 第二季", "native": "アオアシ"},
|
||||
"format": "TV", "startDate": {"year": 2026}, "episodes": 12}
|
||||
target = {"id": 259140, "name": "青之芦苇"}
|
||||
owner = SimpleNamespace(run_module=Mock(return_value=source),
|
||||
async_run_module=AsyncMock(return_value=source),
|
||||
_match_tmdb_with_names=Mock(return_value=target),
|
||||
_async_match_tmdb_with_names=AsyncMock(return_value=target))
|
||||
kwargs = dict(target_source=MediaSource.TMDB, media_source=MediaSource.AniList, media_id="187999")
|
||||
if async_mode:
|
||||
result = await MediaChain.async_convert_media_identity(owner, **kwargs)
|
||||
owner.async_run_module.assert_awaited_once_with("async_anilist_info", anilist_id=187999)
|
||||
matched = owner._async_match_tmdb_with_names.await_args.kwargs
|
||||
else:
|
||||
result = MediaChain.convert_media_identity(owner, **kwargs)
|
||||
owner.run_module.assert_called_once_with("anilist_info", anilist_id=187999)
|
||||
matched = owner._match_tmdb_with_names.call_args.kwargs
|
||||
assert result == {**target, "season": 2}
|
||||
assert "青之蘆葦" in matched["meta_names"]
|
||||
assert matched["year"] == "2026" and matched["season"] == 2
|
||||
assert "season" not in target
|
||||
Reference in New Issue
Block a user