2026-07-20 22:21:29 +08:00
|
|
|
|
"""MoviePilot media and resource operations."""
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
from collections.abc import Mapping
|
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
2026-07-20 22:54:31 +08:00
|
|
|
|
try:
|
|
|
|
|
|
from .moviepilot_client import MoviePilotClient
|
|
|
|
|
|
from .session_context import SessionContextStore
|
|
|
|
|
|
except ImportError:
|
|
|
|
|
|
from moviepilot_client import MoviePilotClient
|
|
|
|
|
|
from session_context import SessionContextStore
|
2026-07-20 22:21:29 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class MediaService:
|
|
|
|
|
|
"""Coordinate MoviePilot media APIs with per-session result caching."""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
|
self,
|
|
|
|
|
|
config: Mapping[str, Any],
|
|
|
|
|
|
session_store: SessionContextStore,
|
|
|
|
|
|
) -> None:
|
|
|
|
|
|
self._config = config
|
|
|
|
|
|
self._session_store = session_store
|
|
|
|
|
|
self._client: MoviePilotClient | None = None
|
|
|
|
|
|
|
|
|
|
|
|
def _get_client(self) -> MoviePilotClient:
|
|
|
|
|
|
if self._client is None:
|
|
|
|
|
|
self._client = MoviePilotClient(
|
|
|
|
|
|
str(self._config.get("moviepilot_url", "")),
|
|
|
|
|
|
str(self._config.get("moviepilot_api_token", "")),
|
2026-07-22 23:25:14 +08:00
|
|
|
|
timeout=float(self._config.get("moviepilot_timeout", 20)),
|
|
|
|
|
|
retries=int(self._config.get("moviepilot_retries", 2)),
|
|
|
|
|
|
retry_backoff=float(self._config.get("moviepilot_retry_backoff", 0.5)),
|
2026-07-20 22:21:29 +08:00
|
|
|
|
)
|
|
|
|
|
|
return self._client
|
|
|
|
|
|
|
|
|
|
|
|
async def close(self) -> None:
|
|
|
|
|
|
if self._client is not None:
|
|
|
|
|
|
await self._client.close()
|
|
|
|
|
|
self._client = None
|
|
|
|
|
|
|
|
|
|
|
|
async def search_media(
|
|
|
|
|
|
self,
|
|
|
|
|
|
origin: str,
|
|
|
|
|
|
title: str,
|
|
|
|
|
|
*,
|
|
|
|
|
|
media_type: str | None = None,
|
|
|
|
|
|
page: int = 1,
|
|
|
|
|
|
count: int | None = None,
|
|
|
|
|
|
) -> list[dict[str, Any]]:
|
|
|
|
|
|
params: dict[str, Any] = {"title": title, "page": page}
|
|
|
|
|
|
if media_type:
|
|
|
|
|
|
params["type"] = media_type
|
|
|
|
|
|
params["count"] = count or int(self._config.get("search_result_count", 5))
|
|
|
|
|
|
response = await self._get_client().get("/api/v1/media/search", params=params)
|
|
|
|
|
|
results = self._as_dict_list(response.data)
|
|
|
|
|
|
self._session_store.set_media_results(origin, results)
|
|
|
|
|
|
return results
|
|
|
|
|
|
|
|
|
|
|
|
async def media_detail(self, media_id: str) -> dict[str, Any]:
|
|
|
|
|
|
response = await self._get_client().get(f"/api/v1/media/{media_id}")
|
|
|
|
|
|
return response.data if isinstance(response.data, dict) else {}
|
|
|
|
|
|
|
|
|
|
|
|
async def media_seasons(
|
|
|
|
|
|
self,
|
|
|
|
|
|
*,
|
|
|
|
|
|
media_id: str | None = None,
|
|
|
|
|
|
title: str | None = None,
|
|
|
|
|
|
year: str | None = None,
|
|
|
|
|
|
season: int | None = None,
|
|
|
|
|
|
) -> list[dict[str, Any]]:
|
|
|
|
|
|
params: dict[str, Any] = {}
|
|
|
|
|
|
if media_id:
|
|
|
|
|
|
params["mediaid"] = media_id
|
|
|
|
|
|
if title:
|
|
|
|
|
|
params["title"] = title
|
|
|
|
|
|
if year:
|
|
|
|
|
|
params["year"] = year
|
|
|
|
|
|
if season is not None:
|
|
|
|
|
|
params["season"] = season
|
|
|
|
|
|
response = await self._get_client().get("/api/v1/media/seasons", params=params)
|
|
|
|
|
|
return self._as_dict_list(response.data)
|
|
|
|
|
|
|
|
|
|
|
|
async def search_resources(
|
|
|
|
|
|
self,
|
|
|
|
|
|
origin: str,
|
|
|
|
|
|
media: dict[str, Any],
|
|
|
|
|
|
*,
|
|
|
|
|
|
page: int = 1,
|
|
|
|
|
|
count: int | None = None,
|
|
|
|
|
|
) -> list[dict[str, Any]]:
|
|
|
|
|
|
media_id = self._media_id(media)
|
|
|
|
|
|
if not media_id:
|
|
|
|
|
|
raise ValueError("媒体结果缺少可用的媒体 ID")
|
|
|
|
|
|
response = await self._get_client().get(
|
|
|
|
|
|
f"/api/v1/search/media/{media_id}",
|
|
|
|
|
|
params={
|
|
|
|
|
|
"page": page,
|
|
|
|
|
|
"count": count or int(self._config.get("search_result_count", 5)),
|
|
|
|
|
|
},
|
|
|
|
|
|
)
|
|
|
|
|
|
results = self._as_dict_list(response.data)
|
|
|
|
|
|
self._session_store.set_resource_results(origin, media, results)
|
|
|
|
|
|
return results
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _media_id(media: Mapping[str, Any]) -> str:
|
2026-07-20 23:44:07 +08:00
|
|
|
|
for key in ("mediaid", "media_id", "id", "mediaId"):
|
2026-07-20 22:21:29 +08:00
|
|
|
|
value = media.get(key)
|
|
|
|
|
|
if value:
|
|
|
|
|
|
return str(value)
|
2026-07-20 23:44:07 +08:00
|
|
|
|
tmdb_id = media.get("tmdb_id") or media.get("tmdbid") or media.get("tmdbId")
|
|
|
|
|
|
if tmdb_id:
|
|
|
|
|
|
return f"tmdb:{tmdb_id}"
|
2026-07-20 22:21:29 +08:00
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _as_dict_list(value: Any) -> list[dict[str, Any]]:
|
|
|
|
|
|
if isinstance(value, list):
|
|
|
|
|
|
return [item for item in value if isinstance(item, dict)]
|
|
|
|
|
|
if isinstance(value, dict):
|
|
|
|
|
|
for key in ("results", "items", "medias", "torrents"):
|
|
|
|
|
|
nested = value.get(key)
|
|
|
|
|
|
if isinstance(nested, list):
|
|
|
|
|
|
return [item for item in nested if isinstance(item, dict)]
|
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-20 23:32:48 +08:00
|
|
|
|
def _first_value(item: Mapping[str, Any], *keys: str) -> Any:
|
|
|
|
|
|
for key in keys:
|
|
|
|
|
|
value = item.get(key)
|
|
|
|
|
|
if value not in (None, "", [], {}):
|
|
|
|
|
|
return value
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _format_release_month(item: Mapping[str, Any]) -> str:
|
|
|
|
|
|
value = _first_value(item, "release_date", "first_air_date", "year")
|
|
|
|
|
|
if value is None:
|
|
|
|
|
|
return "未公布"
|
|
|
|
|
|
text = str(value)
|
|
|
|
|
|
if len(text) >= 7 and text[4] == "-":
|
|
|
|
|
|
return text[:7]
|
|
|
|
|
|
return text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def media_poster_url(item: Mapping[str, Any]) -> str | None:
|
|
|
|
|
|
value = _first_value(item, "poster_path", "poster", "cover_url", "cover", "image")
|
|
|
|
|
|
if isinstance(value, str) and value.startswith(("http://", "https://")):
|
|
|
|
|
|
return value
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def format_media_result_item(index: int, item: Mapping[str, Any]) -> str:
|
|
|
|
|
|
title = _first_value(item, "title", "name", "original_title") or "未命名"
|
|
|
|
|
|
tmdb_id = _first_value(item, "tmdb_id", "tmdbid", "tmdbId")
|
|
|
|
|
|
if tmdb_id is None:
|
|
|
|
|
|
raw_id = _first_value(item, "id")
|
|
|
|
|
|
if isinstance(raw_id, str) and raw_id.lower().startswith("tmdb:"):
|
|
|
|
|
|
tmdb_id = raw_id.split(":", 1)[1]
|
|
|
|
|
|
episodes = _first_value(
|
|
|
|
|
|
item,
|
|
|
|
|
|
"number_of_episodes",
|
|
|
|
|
|
"episode_count",
|
|
|
|
|
|
"episodes",
|
|
|
|
|
|
"total_episode",
|
|
|
|
|
|
)
|
|
|
|
|
|
rating = _first_value(item, "vote_average", "rating", "vote")
|
|
|
|
|
|
media_type = _first_value(item, "type_name", "type")
|
|
|
|
|
|
lines = [
|
|
|
|
|
|
f"{index}. {title}",
|
|
|
|
|
|
f"TMDB编号:{tmdb_id if tmdb_id is not None else '未提供'}",
|
|
|
|
|
|
f"上映年月:{_format_release_month(item)}",
|
|
|
|
|
|
f"集数:{episodes if episodes is not None else '未公布'}",
|
|
|
|
|
|
f"评分:{rating if rating is not None else '暂无'}",
|
|
|
|
|
|
]
|
|
|
|
|
|
if media_type:
|
|
|
|
|
|
lines.append(f"类型:{media_type}")
|
|
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-20 22:21:29 +08:00
|
|
|
|
def format_media_results(results: list[dict[str, Any]]) -> str:
|
|
|
|
|
|
if not results:
|
|
|
|
|
|
return "没有找到匹配的影视信息。"
|
|
|
|
|
|
lines = ["影视搜索结果:"]
|
|
|
|
|
|
for index, item in enumerate(results, start=1):
|
2026-07-20 23:32:48 +08:00
|
|
|
|
lines.append(format_media_result_item(index, item))
|
2026-07-20 22:21:29 +08:00
|
|
|
|
lines.append("可继续使用:/mp resources <编号> 或 /mp subscribe <编号>")
|
2026-07-20 23:32:48 +08:00
|
|
|
|
return "\n\n".join(lines)
|
2026-07-20 22:21:29 +08:00
|
|
|
|
|
2026-07-22 23:12:18 +08:00
|
|
|
|
def _format_resource_size(value: Any) -> str:
|
|
|
|
|
|
if value in (None, "", 0, 0.0):
|
|
|
|
|
|
return "\u672a\u77e5"
|
|
|
|
|
|
if isinstance(value, (int, float)):
|
|
|
|
|
|
size = float(value)
|
|
|
|
|
|
if size >= 1024:
|
|
|
|
|
|
return f"{size / 1024:.2f} GB"
|
|
|
|
|
|
return f"{size:.2f} MB"
|
|
|
|
|
|
return str(value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def format_resource_result_item(index: int, item: Mapping[str, Any]) -> str:
|
|
|
|
|
|
title = _first_value(item, "title", "name") or "\u672a\u547d\u540d\u8d44\u6e90"
|
|
|
|
|
|
site = _first_value(item, "site_name", "site") or "\u672a\u77e5\u7ad9\u70b9"
|
|
|
|
|
|
quality = _first_value(item, "quality", "resolution", "category") or "\u672a\u77e5\u8d28\u91cf"
|
|
|
|
|
|
size = _format_resource_size(_first_value(item, "size", "length"))
|
|
|
|
|
|
seeders = _first_value(item, "seeders", "seed", "seeds")
|
|
|
|
|
|
peers = _first_value(item, "peers", "leechers", "leeches")
|
|
|
|
|
|
seed_text = seeders if seeders is not None else "\u672a\u77e5"
|
|
|
|
|
|
peer_text = peers if peers is not None else "\u672a\u77e5"
|
|
|
|
|
|
pubdate = _first_value(item, "pubdate", "publish_time", "published_at") or "\u672a\u77e5"
|
|
|
|
|
|
free = _first_value(item, "freedate", "free", "is_free", "volume_factor")
|
|
|
|
|
|
free_text = "\u662f" if free is True or (isinstance(free, str) and free.lower() in {"free", "yes", "true"}) else "\u5426"
|
|
|
|
|
|
colon = "\uFF1A"
|
|
|
|
|
|
lines = [
|
|
|
|
|
|
f"\u8d44\u6e90 {index}",
|
|
|
|
|
|
f"\u540d\u79f0{colon}{title}",
|
|
|
|
|
|
f"\u7ad9\u70b9{colon}{site}",
|
|
|
|
|
|
f"\u8d28\u91cf{colon}{quality}",
|
|
|
|
|
|
f"\u5927\u5c0f{colon}{size}",
|
|
|
|
|
|
f"\u505a\u79cd{colon}{seed_text} / \u4e0b\u8f7d{colon}{peer_text}",
|
|
|
|
|
|
f"\u53d1\u5e03\u65f6\u95f4{colon}{pubdate}",
|
|
|
|
|
|
f"\u514d\u8d39{colon}{free_text}",
|
|
|
|
|
|
]
|
|
|
|
|
|
if not _first_value(item, "enclosure", "page_url", "download_url", "url"):
|
|
|
|
|
|
lines.append(f"\u63d0\u793a{colon}\u8be5\u8d44\u6e90\u7f3a\u5c11\u53ef\u63d0\u4ea4\u7684\u4e0b\u8f7d\u94fe\u63a5\uFF0C\u53ef\u80fd\u65e0\u6cd5\u76f4\u63a5\u4e0b\u8f7d")
|
|
|
|
|
|
return chr(10).join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-20 22:21:29 +08:00
|
|
|
|
def format_resource_results(results: list[dict[str, Any]]) -> str:
|
|
|
|
|
|
if not results:
|
2026-07-22 23:12:18 +08:00
|
|
|
|
return "\u6682\u672a\u627e\u5230\u8d44\u6e90\u3002\u53ef\u4ee5\u4f7f\u7528 /mp subscribe <\u5a92\u4f53\u7f16\u53f7> \u8ba2\u9605\u8be5\u5a92\u4f53\u3002"
|
|
|
|
|
|
lines = ["\u8d44\u6e90\u641c\u7d22\u7ed3\u679c\uFF1A"]
|
2026-07-20 22:21:29 +08:00
|
|
|
|
for index, item in enumerate(results, start=1):
|
2026-07-22 23:12:18 +08:00
|
|
|
|
lines.append(format_resource_result_item(index, item))
|
|
|
|
|
|
lines.append("\u53ef\u4f7f\u7528 /mp download <\u7f16\u53f7> \u9009\u62e9\u8d44\u6e90\u4e0b\u8f7d\u3002")
|
|
|
|
|
|
return (chr(10) + chr(10)).join(lines)
|