astrbot_plugin_moviepilot/moviepilot_client.py
2026-07-20 22:15:26 +08:00

205 行
6.2 KiB
Python

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

"""Asynchronous MoviePilot REST client."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
import httpx
class MoviePilotError(Exception):
"""Base exception for MoviePilot integration failures."""
class MoviePilotConfigError(MoviePilotError):
"""Raised when the client configuration is incomplete or invalid."""
class MoviePilotConnectionError(MoviePilotError):
"""Raised when MoviePilot cannot be reached."""
class MoviePilotAuthenticationError(MoviePilotError):
"""Raised when MoviePilot rejects the API token."""
class MoviePilotAPIError(MoviePilotError):
"""Raised when MoviePilot returns an unsuccessful API response."""
def __init__(self, status_code: int, message: str, data: Any = None) -> None:
super().__init__(message)
self.status_code = status_code
self.message = message
self.data = data
class MoviePilotResponseError(MoviePilotError):
"""Raised when a response cannot be decoded as JSON."""
@dataclass(frozen=True, slots=True)
class MoviePilotResponse:
"""Normalized response returned by MoviePilot."""
status_code: int
data: Any
success: bool | None = None
message: str | None = None
def _response_message(payload: Any) -> str | None:
if not isinstance(payload, Mapping):
return None
message = payload.get("message")
return message if isinstance(message, str) else None
def _response_success(payload: Any) -> bool | None:
if not isinstance(payload, Mapping):
return None
success = payload.get("success")
return success if isinstance(success, bool) else None
class MoviePilotClient:
"""Small async client for MoviePilot's external API."""
def __init__(
self,
base_url: str,
api_token: str,
*,
timeout: float = 20.0,
transport: httpx.AsyncBaseTransport | None = None,
) -> None:
normalized_url = (base_url or "").strip().rstrip("/")
normalized_token = (api_token or "").strip()
if not normalized_url:
raise MoviePilotConfigError("MoviePilot 地址未配置")
if not normalized_token:
raise MoviePilotConfigError("MoviePilot API Token 未配置")
if not normalized_url.startswith(("http://", "https://")):
raise MoviePilotConfigError("MoviePilot 地址必须以 http:// 或 https:// 开头")
self.base_url = normalized_url
self._api_token = normalized_token
self._timeout = httpx.Timeout(timeout)
self._transport = transport
self._client: httpx.AsyncClient | None = None
async def __aenter__(self) -> "MoviePilotClient":
await self.start()
return self
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
await self.close()
async def start(self) -> None:
if self._client is None:
self._client = httpx.AsyncClient(
base_url=self.base_url,
headers={"X-API-KEY": self._api_token},
timeout=self._timeout,
transport=self._transport,
)
async def close(self) -> None:
if self._client is not None:
await self._client.aclose()
self._client = None
async def request(
self,
method: str,
path: str,
*,
params: Mapping[str, Any] | None = None,
json: Any = None,
) -> MoviePilotResponse:
await self.start()
assert self._client is not None
request_path = path if path.startswith("/") else f"/{path}"
try:
response = await self._client.request(
method,
request_path,
params=params,
json=json,
)
except httpx.TimeoutException as exc:
raise MoviePilotConnectionError("连接 MoviePilot 超时") from exc
except httpx.HTTPError as exc:
raise MoviePilotConnectionError("连接 MoviePilot 失败") from exc
if response.status_code in (401, 403):
raise MoviePilotAuthenticationError("MoviePilot API Token 无效")
try:
payload = response.json()
except ValueError as exc:
raise MoviePilotResponseError(
f"MoviePilot 返回了无法解析的 JSON(HTTP {response.status_code})"
) from exc
message = _response_message(payload)
success = _response_success(payload)
if response.status_code >= 400:
raise MoviePilotAPIError(
response.status_code,
message or f"MoviePilot 请求失败(HTTP {response.status_code})",
payload,
)
if success is False:
raise MoviePilotAPIError(
response.status_code,
message or "MoviePilot 操作失败",
payload,
)
data = payload.get("data") if isinstance(payload, Mapping) else payload
return MoviePilotResponse(
status_code=response.status_code,
data=data,
success=success,
message=message,
)
async def get(
self,
path: str,
*,
params: Mapping[str, Any] | None = None,
) -> MoviePilotResponse:
return await self.request("GET", path, params=params)
async def post(
self,
path: str,
*,
params: Mapping[str, Any] | None = None,
json: Any = None,
) -> MoviePilotResponse:
return await self.request("POST", path, params=params, json=json)
async def put(
self,
path: str,
*,
params: Mapping[str, Any] | None = None,
json: Any = None,
) -> MoviePilotResponse:
return await self.request("PUT", path, params=params, json=json)
async def delete(
self,
path: str,
*,
params: Mapping[str, Any] | None = None,
) -> MoviePilotResponse:
return await self.request("DELETE", path, params=params)
async def test_connection(self) -> MoviePilotResponse:
"""Call a low-cost endpoint to validate URL and token."""
return await self.get("/api/v1/subscribe/list")