mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-29 23:45:03 +08:00
fix(subscribe): retry identity conversion during metadata checks
This commit is contained in:
@@ -55,6 +55,7 @@ if TYPE_CHECKING:
|
||||
_SubscribeChain__get_episode_priority: Callable[..., Any]
|
||||
_SubscribeChain__get_subscribe_no_exits: Callable[..., Any]
|
||||
_SubscribeChain__is_best_version_complete: Callable[..., Any]
|
||||
_SubscribeChain__is_tmdb_recognize_source: Callable[[], bool]
|
||||
_SubscribeChain__is_full_best_version_enabled: Callable[..., Any]
|
||||
_SubscribeChain__is_full_season_best_version_resource: Callable[..., Any]
|
||||
_SubscribeChain__notify_subscribe_create_failure: Callable[..., Any]
|
||||
|
||||
@@ -225,10 +225,19 @@ class SubscribeCreateOwner(_SubscribeOwnerBase):
|
||||
source, media_id = resolve_media_identity(media=mediainfo)
|
||||
if not source or not media_id or source == MediaSource.TMDB:
|
||||
return None
|
||||
if normalize_media_source(get_runtime_setting("RECOGNIZE_SOURCE", None)) != MediaSource.TMDB:
|
||||
if not SubscribeCreateOwner._SubscribeChain__is_tmdb_recognize_source():
|
||||
return None
|
||||
return source, media_id
|
||||
|
||||
@staticmethod
|
||||
def _SubscribeChain__is_tmdb_recognize_source() -> bool:
|
||||
"""
|
||||
判断当前影视识别源是否为 TMDB,供订阅创建和定期巡检共用。
|
||||
|
||||
:return: 当前识别源规范化后为 TMDB 时返回 True,否则返回 False
|
||||
"""
|
||||
return normalize_media_source(get_runtime_setting("RECOGNIZE_SOURCE", None)) == MediaSource.TMDB
|
||||
|
||||
@staticmethod
|
||||
def _SubscribeChain__apply_converted_subscribe_media(
|
||||
context: _SubscribeCreateContext,
|
||||
|
||||
@@ -23,7 +23,7 @@ from app.domain.meta.metabase import MetaBase
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.schemas.mediaserver import NotExistMediaInfo
|
||||
from app.schemas.types import MUSIC_ENTITY_ALBUM, MediaType
|
||||
from app.schemas.types import MUSIC_ENTITY_ALBUM, MediaSource, MediaType
|
||||
|
||||
SubscriptionMediaT = TypeVar("SubscriptionMediaT", MediaInfo, MusicInfo)
|
||||
|
||||
@@ -106,6 +106,108 @@ class SubscribeMetadataOwner(_SubscribeOwnerBase):
|
||||
刷新一条订阅的新鲜媒体事实、持久字段与可选完成状态。
|
||||
"""
|
||||
|
||||
def _retry_subscribe_media_identity(
|
||||
self,
|
||||
subscribe: SubscriptionSnapshot,
|
||||
meta: MetaBase,
|
||||
media_chain_factory: Callable[[], Any],
|
||||
) -> Optional[SubscriptionSnapshot]:
|
||||
"""
|
||||
在元数据巡检中重试豆瓣或 Bangumi 到 TMDB 的订阅身份转换。
|
||||
|
||||
该补偿复用既有的 TMDB 元数据巡检周期。没有匹配结果、外部识别失败或目标身份
|
||||
已被其他订阅占用时保留原订阅,避免转换失败影响当前订阅的后续搜索。
|
||||
|
||||
:param subscribe: 当前订阅快照
|
||||
:param meta: 当前订阅的媒体类型和标题元数据
|
||||
:param media_chain_factory: 媒体链构造入口
|
||||
:return: 转换成功并完成持久化后的订阅快照;不适用或失败时返回 None
|
||||
"""
|
||||
if meta.type not in (MediaType.MOVIE, MediaType.TV):
|
||||
return None
|
||||
is_tmdb_recognize_source = getattr(self, "_SubscribeChain__is_tmdb_recognize_source", None)
|
||||
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:
|
||||
return None
|
||||
|
||||
media_chain = media_chain_factory()
|
||||
try:
|
||||
tmdb_info = media_chain.convert_media_identity(
|
||||
target_source=MediaSource.TMDB,
|
||||
media_source=source,
|
||||
media_id=media_id,
|
||||
mtype=meta.type,
|
||||
season=subscribe.season,
|
||||
)
|
||||
tmdb_id = tmdb_info.get("id") if isinstance(tmdb_info, dict) else None
|
||||
if not tmdb_id:
|
||||
logger.info(
|
||||
f"订阅身份巡检未找到 TMDB 对应条目:{source}:{media_id},"
|
||||
f"暂时沿用原身份:{subscribe.name}"
|
||||
)
|
||||
return None
|
||||
converted = media_chain.recognize_media(
|
||||
meta=meta,
|
||||
mtype=meta.type,
|
||||
media_source=MediaSource.TMDB,
|
||||
media_id=str(tmdb_id),
|
||||
episode_group=subscribe.episode_group,
|
||||
cache=False,
|
||||
)
|
||||
except Exception as err:
|
||||
logger.warning(
|
||||
f"订阅身份巡检将 {source}:{media_id} 转换为 TMDB 失败,"
|
||||
f"暂时沿用原身份:{subscribe.name},原因:{err}"
|
||||
)
|
||||
return None
|
||||
|
||||
if not converted:
|
||||
logger.info(
|
||||
f"订阅身份巡检未识别到 TMDB 媒体:{source}:{media_id},"
|
||||
f"暂时沿用原身份:{subscribe.name}"
|
||||
)
|
||||
return None
|
||||
|
||||
target_season = subscribe.season
|
||||
projected_season = tmdb_info.get("season") if isinstance(tmdb_info, dict) else None
|
||||
if target_season is None and isinstance(projected_season, int) and projected_season > 0:
|
||||
target_season = projected_season
|
||||
update_data: dict[str, Any] = {
|
||||
"name": converted.title,
|
||||
"year": str(converted.year) if converted.year is not None else None,
|
||||
"vote": converted.vote_average,
|
||||
"poster": converted.get_poster_image(),
|
||||
"backdrop": converted.get_backdrop_image(),
|
||||
"description": converted.overview,
|
||||
"media_source": MediaSource.TMDB,
|
||||
"media_id": str(tmdb_id),
|
||||
}
|
||||
if target_season != subscribe.season:
|
||||
update_data["season"] = target_season
|
||||
if meta.type == MediaType.TV and target_season is not None:
|
||||
episodes = (converted.seasons or {}).get(target_season) or []
|
||||
if episodes:
|
||||
update_data["total_episode"] = len(episodes)
|
||||
|
||||
try:
|
||||
updated = self._SubscribeChain__apply_subscribe_update(
|
||||
subscribe,
|
||||
update_data,
|
||||
scene="identity_refresh",
|
||||
)
|
||||
except Exception as err:
|
||||
logger.warning(
|
||||
f"订阅身份巡检写入 TMDB 身份失败:{subscribe.name},"
|
||||
f"暂时沿用原身份,原因:{err}"
|
||||
)
|
||||
return None
|
||||
logger.info(
|
||||
f"订阅身份巡检已将 {source}:{media_id} 转换为 TMDB {tmdb_id}:{converted.title_year}"
|
||||
)
|
||||
return cast(SubscriptionSnapshot, updated)
|
||||
|
||||
def _check_subscription(
|
||||
self,
|
||||
subscribe: SubscriptionSnapshot,
|
||||
@@ -122,6 +224,18 @@ class SubscribeMetadataOwner(_SubscribeOwnerBase):
|
||||
except ValueError:
|
||||
logger.error(f"订阅 {subscribe.name} 类型错误:{subscribe.type}")
|
||||
return None
|
||||
converted_subscribe = self._retry_subscribe_media_identity(
|
||||
subscribe,
|
||||
meta,
|
||||
media_chain_factory,
|
||||
)
|
||||
if converted_subscribe is not None:
|
||||
subscribe = converted_subscribe
|
||||
try:
|
||||
meta = build_subscribe_meta(subscribe)
|
||||
except ValueError:
|
||||
logger.error(f"订阅 {subscribe.name} 类型错误:{subscribe.type}")
|
||||
return None
|
||||
if meta.type == MediaType.MUSIC:
|
||||
mediainfo = self._recognize_music_subscribe(subscribe)
|
||||
else:
|
||||
|
||||
@@ -621,6 +621,7 @@ def _load_subscribe_chain_class():
|
||||
import app.chain.subscribe.completion as completion_owner
|
||||
import app.chain.subscribe.create as create_owner
|
||||
import app.chain.subscribe.match as match_owner
|
||||
import app.chain.subscribe.metadata as metadata_owner
|
||||
import app.chain.subscribe.notify as notification_owner
|
||||
import app.chain.subscribe.policy as policy_owner
|
||||
import app.chain.subscribe.query as query_owner
|
||||
@@ -699,6 +700,7 @@ def _load_subscribe_chain_class():
|
||||
create_owner,
|
||||
completion_owner,
|
||||
match_owner,
|
||||
metadata_owner,
|
||||
query_owner,
|
||||
refresh_owner,
|
||||
search_owner,
|
||||
@@ -4526,11 +4528,23 @@ class TestSubscribeProgressConsolidation:
|
||||
mediainfo.seasons = {number: [object() for _ in range(total_episode)] for number in seasons}
|
||||
return mediainfo
|
||||
|
||||
def _conversion_media_chain(self, module, tmdbinfo, *, allow_convert=True, tmdb_available=True):
|
||||
def _conversion_media_chain(
|
||||
self,
|
||||
module,
|
||||
tmdbinfo,
|
||||
*,
|
||||
allow_convert=True,
|
||||
tmdb_available=True,
|
||||
source_id="35932853",
|
||||
source_title="绝望写手 第三季",
|
||||
source_year="2024",
|
||||
):
|
||||
"""
|
||||
按请求来源分发识别结果,并记录身份转换调用,供订阅创建的转换用例复用。
|
||||
"""
|
||||
douban = self._identity_mediainfo("douban", "35932853", "绝望写手 第三季", "2024", seasons=(1,))
|
||||
douban = self._identity_mediainfo(
|
||||
"douban", source_id, source_title, source_year, seasons=(1,)
|
||||
)
|
||||
tmdb = self._identity_mediainfo("themoviedb", "124101", "绝望写手", "2021", seasons=(1, 2, 3, 4, 5))
|
||||
calls = {"convert": [], "recognize": []}
|
||||
|
||||
@@ -4773,6 +4787,142 @@ class TestSubscribeProgressConsolidation:
|
||||
assert context.season == 3
|
||||
assert calls["convert"][0]["season"] is None
|
||||
|
||||
def test_check_retries_failed_creation_conversion_and_persists_tmdb_identity(self):
|
||||
"""
|
||||
元数据巡检重试创建时失败的豆瓣身份,并将成功结果写回 TMDB 身份。
|
||||
"""
|
||||
module, SubscribeChain = _load_subscribe_chain_class()
|
||||
subscribe = module.SubscriptionSnapshot(
|
||||
id=71,
|
||||
name="绝望写手 第三季",
|
||||
year="2024",
|
||||
type=MediaType.TV.value,
|
||||
season=3,
|
||||
total_episode=9,
|
||||
start_episode=1,
|
||||
lack_episode=9,
|
||||
state="R",
|
||||
best_version=0,
|
||||
best_version_full=0,
|
||||
note=[],
|
||||
manual_total_episode=0,
|
||||
media_source="douban",
|
||||
media_id="35932853",
|
||||
)
|
||||
current = subscribe
|
||||
updates = []
|
||||
|
||||
class _SubscribeOper:
|
||||
def list(self):
|
||||
"""
|
||||
返回待巡检的豆瓣订阅。
|
||||
"""
|
||||
return [current]
|
||||
|
||||
def update(self, subscribe_id, payload):
|
||||
"""
|
||||
记录巡检写入并返回合并后的订阅快照。
|
||||
|
||||
:param subscribe_id: 被更新的订阅标识
|
||||
:param payload: 待写入的订阅字段
|
||||
:return: 合并后的订阅快照
|
||||
"""
|
||||
nonlocal current
|
||||
assert subscribe_id == subscribe.id
|
||||
updates.append(payload.to_payload())
|
||||
current = replace(current, **payload.to_payload())
|
||||
return current
|
||||
|
||||
media_patch, calls = self._conversion_media_chain(
|
||||
module,
|
||||
{"id": 124101, "season": 3},
|
||||
)
|
||||
chain = SubscribeChain()
|
||||
chain.subscription_repository = _SubscribeOper()
|
||||
with (
|
||||
media_patch,
|
||||
patch.object(module, "get_runtime_setting", lambda _key, _default=None: "themoviedb"),
|
||||
):
|
||||
chain.check()
|
||||
|
||||
assert calls["convert"] == [
|
||||
{
|
||||
"target_source": MediaSource.TMDB,
|
||||
"media_source": MediaSource.Douban,
|
||||
"media_id": "35932853",
|
||||
"mtype": MediaType.TV,
|
||||
"season": 3,
|
||||
}
|
||||
]
|
||||
assert updates[0]["media_source"] == MediaSource.TMDB
|
||||
assert updates[0]["media_id"] == "124101"
|
||||
assert current.media_source == MediaSource.TMDB
|
||||
assert current.media_id == "124101"
|
||||
|
||||
def test_check_keeps_original_identity_when_conversion_still_fails(self):
|
||||
"""
|
||||
元数据巡检暂时找不到 TMDB 条目时保留原豆瓣身份并继续刷新。
|
||||
"""
|
||||
module, SubscribeChain = _load_subscribe_chain_class()
|
||||
subscribe = module.SubscriptionSnapshot(
|
||||
id=72,
|
||||
name="洛水知何年",
|
||||
year="2028",
|
||||
type=MediaType.TV.value,
|
||||
season=1,
|
||||
total_episode=12,
|
||||
start_episode=1,
|
||||
lack_episode=12,
|
||||
state="R",
|
||||
best_version=0,
|
||||
best_version_full=0,
|
||||
note=[],
|
||||
manual_total_episode=0,
|
||||
media_source="douban",
|
||||
media_id="37333131",
|
||||
)
|
||||
updates = []
|
||||
|
||||
class _SubscribeOper:
|
||||
def list(self):
|
||||
"""
|
||||
返回待巡检的豆瓣订阅。
|
||||
"""
|
||||
return [subscribe]
|
||||
|
||||
def update(self, subscribe_id, payload):
|
||||
"""
|
||||
记录元数据刷新写入并保留原媒体身份。
|
||||
|
||||
:param subscribe_id: 被更新的订阅标识
|
||||
:param payload: 待写入的订阅字段
|
||||
:return: 合并后的订阅快照
|
||||
"""
|
||||
assert subscribe_id == subscribe.id
|
||||
updates.append(payload.to_payload())
|
||||
return replace(subscribe, **payload.to_payload())
|
||||
|
||||
media_patch, calls = self._conversion_media_chain(
|
||||
module,
|
||||
None,
|
||||
source_id="37333131",
|
||||
source_title="洛水知何年",
|
||||
source_year="2028",
|
||||
)
|
||||
chain = SubscribeChain()
|
||||
chain.subscription_repository = _SubscribeOper()
|
||||
with (
|
||||
media_patch,
|
||||
patch.object(module, "get_runtime_setting", lambda _key, _default=None: "themoviedb"),
|
||||
):
|
||||
chain.check()
|
||||
|
||||
assert len(calls["convert"]) == 1
|
||||
assert all(call.get("media_source") != MediaSource.TMDB for call in calls["recognize"])
|
||||
assert updates
|
||||
assert updates[-1]["media_source"] == MediaSource.Douban
|
||||
assert updates[-1]["media_id"] == "37333131"
|
||||
|
||||
def test_completed_episode_uses_schema_function_directly_for_best_version(self):
|
||||
"""
|
||||
洗版完成集数直接复用模型层计算入口,避免链层维护重复算法。
|
||||
|
||||
Reference in New Issue
Block a user