From d3d0327eaa0aa3d54c7c22c2cc9514d94dc98574 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 20 Jul 2026 22:15:26 +0800 Subject: [PATCH] feat: add async MoviePilot REST client --- moviepilot_client.py | 205 ++++++++++++++++++++++++++++++++ tests/test_moviepilot_client.py | 99 +++++++++++++++ 2 files changed, 304 insertions(+) create mode 100644 moviepilot_client.py create mode 100644 tests/test_moviepilot_client.py diff --git a/moviepilot_client.py b/moviepilot_client.py new file mode 100644 index 0000000..05a6c30 --- /dev/null +++ b/moviepilot_client.py @@ -0,0 +1,205 @@ +"""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") diff --git a/tests/test_moviepilot_client.py b/tests/test_moviepilot_client.py new file mode 100644 index 0000000..d29b740 --- /dev/null +++ b/tests/test_moviepilot_client.py @@ -0,0 +1,99 @@ +import httpx +import pytest + +from moviepilot_client import ( + MoviePilotAPIError, + MoviePilotAuthenticationError, + MoviePilotClient, + MoviePilotConfigError, + MoviePilotConnectionError, + MoviePilotResponseError, +) + + +def make_transport(handler): + return httpx.MockTransport(handler) + + +@pytest.mark.asyncio +async def test_request_adds_api_header_and_unwraps_data() -> None: + async def handler(request: httpx.Request) -> httpx.Response: + assert request.headers["X-API-KEY"] == "secret" + assert request.url.path == "/api/v1/media/search" + assert request.url.params["title"] == "沙丘" + return httpx.Response(200, json={"success": True, "data": [{"id": 1}]}) + + async with MoviePilotClient( + "http://moviepilot:3000/", "secret", transport=make_transport(handler) + ) as client: + response = await client.get( + "/api/v1/media/search", params={"title": "沙丘"} + ) + + assert response.data == [{"id": 1}] + assert response.success is True + + +@pytest.mark.asyncio +async def test_list_response_is_preserved() -> None: + async def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json=[{"id": 1}]) + + async with MoviePilotClient( + "http://moviepilot:3000", "secret", transport=make_transport(handler) + ) as client: + response = await client.get("/api/v1/subscribe/list") + + assert response.data == [{"id": 1}] + assert response.success is None + + +@pytest.mark.asyncio +async def test_api_failure_and_auth_failure_are_normalized() -> None: + async def api_error(request: httpx.Request) -> httpx.Response: + return httpx.Response(400, json={"success": False, "message": "参数错误"}) + + async with MoviePilotClient( + "http://moviepilot:3000", "secret", transport=make_transport(api_error) + ) as client: + with pytest.raises(MoviePilotAPIError, match="参数错误"): + await client.get("/api/v1/media/search") + + async def auth_error(request: httpx.Request) -> httpx.Response: + return httpx.Response(401, json={"detail": "Unauthorized"}) + + async with MoviePilotClient( + "http://moviepilot:3000", "secret", transport=make_transport(auth_error) + ) as client: + with pytest.raises(MoviePilotAuthenticationError): + await client.get("/api/v1/media/search") + + +@pytest.mark.asyncio +async def test_connection_and_json_errors_are_normalized() -> None: + async def invalid_json(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, content=b"not-json") + + async with MoviePilotClient( + "http://moviepilot:3000", "secret", transport=make_transport(invalid_json) + ) as client: + with pytest.raises(MoviePilotResponseError): + await client.get("/api/v1/media/search") + + async def network_error(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("offline", request=request) + + async with MoviePilotClient( + "http://moviepilot:3000", "secret", transport=make_transport(network_error) + ) as client: + with pytest.raises(MoviePilotConnectionError): + await client.get("/api/v1/media/search") + + +def test_invalid_configuration_is_rejected() -> None: + with pytest.raises(MoviePilotConfigError): + MoviePilotClient("", "secret") + with pytest.raises(MoviePilotConfigError): + MoviePilotClient("http://moviepilot:3000", "") + with pytest.raises(MoviePilotConfigError): + MoviePilotClient("moviepilot:3000", "secret")