astrbot_plugin_moviepilot/subscription_service.py

165 行
5.4 KiB
Python

"""MoviePilot subscription and immediate download operations."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from media_service import MediaService
from moviepilot_client import MoviePilotClient
class SubscriptionService:
"""Coordinate MoviePilot subscription and download APIs."""
def __init__(self, config: Mapping[str, Any]) -> None:
self._config = config
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", "")),
)
return self._client
async def close(self) -> None:
if self._client is not None:
await self._client.close()
self._client = None
async def create_subscription(
self,
media: Mapping[str, Any],
*,
season: int | None = None,
) -> dict[str, Any]:
payload = build_subscription_payload(media, season=season)
response = await self._get_client().post(
"/api/v1/subscribe/", json=payload
)
return response.data if isinstance(response.data, dict) else {}
async def trigger_subscription_search(self, subscribe_id: int) -> dict[str, Any]:
response = await self._get_client().get(
f"/api/v1/subscribe/search/{subscribe_id}"
)
return response.data if isinstance(response.data, dict) else {}
async def list_subscriptions(self) -> list[dict[str, Any]]:
response = await self._get_client().get("/api/v1/subscribe/list")
return MediaService._as_dict_list(response.data)
async def delete_subscription(
self, media_id: str, *, season: int | None = None
) -> dict[str, Any]:
params = {"season": season} if season is not None else None
response = await self._get_client().delete(
f"/api/v1/subscribe/media/{media_id}", params=params
)
return response.data if isinstance(response.data, dict) else {}
async def download_resource(
self,
resource: Mapping[str, Any],
media: Mapping[str, Any],
) -> dict[str, Any]:
torrent = build_torrent_payload(resource)
body: dict[str, Any] = {"torrent_in": torrent}
tmdbid = _tmdb_id(media)
if tmdbid is not None:
body["tmdbid"] = tmdbid
response = await self._get_client().post(
"/api/v1/download/add", json=body
)
return response.data if isinstance(response.data, dict) else {}
def _value(media: Mapping[str, Any], *keys: str) -> Any:
for key in keys:
value = media.get(key)
if value not in (None, ""):
return value
return None
def _tmdb_id(media: Mapping[str, Any]) -> int | None:
value = _value(media, "tmdbid", "tmdb_id")
if value is None:
media_id = _value(media, "mediaid", "media_id", "id")
if isinstance(media_id, str) and media_id.startswith("tmdb:"):
value = media_id[5:]
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
return None
def build_subscription_payload(
media: Mapping[str, Any], *, season: int | None = None
) -> dict[str, Any]:
"""Build only public-write fields accepted by MoviePilot."""
media_id = _value(media, "mediaid", "media_id", "id")
payload: dict[str, Any] = {
"name": _value(media, "title", "name") or "",
"year": _value(media, "year", "release_date", "first_air_date"),
"type": _normalize_media_type(_value(media, "type", "type_name")),
}
tmdbid = _tmdb_id(media)
if tmdbid is not None:
payload["tmdbid"] = tmdbid
elif media_id:
payload["mediaid"] = str(media_id)
if season is not None:
payload["season"] = season
elif _value(media, "season") is not None:
payload["season"] = _value(media, "season")
return {key: value for key, value in payload.items() if value not in (None, "")}
def build_torrent_payload(resource: Mapping[str, Any]) -> dict[str, Any]:
"""Copy only download-relevant TorrentInfo-compatible fields."""
fields = (
"site",
"site_name",
"title",
"description",
"imdbid",
"enclosure",
"page_url",
"size",
"seeders",
"peers",
"grabs",
"pubdate",
"freedate",
"labels",
"category",
)
return {key: resource[key] for key in fields if key in resource}
def _normalize_media_type(value: Any) -> str | None:
if not value:
return None
normalized = str(value).strip().lower()
if normalized in {"movie", "电影"}:
return "movie"
if normalized in {"tv", "电视剧", "series"}:
return "tv"
return str(value)
def format_subscriptions(subscriptions: list[dict[str, Any]]) -> str:
if not subscriptions:
return "当前没有订阅。"
lines = ["订阅列表:"]
for item in subscriptions:
sid = item.get("id", "?")
title = item.get("name") or "未命名"
state = item.get("state") or ""
season = item.get("season")
suffix = f" / 第 {season} 季" if season is not None else ""
lines.append(f"{sid}. {title}{suffix} {state}".strip())
return "\n".join(lines)