"""MoviePilot notification polling and fixed AstrBot targets.""" from __future__ import annotations import asyncio import hashlib import json import time from collections.abc import Awaitable, Callable, Mapping from pathlib import Path from typing import Any from moviepilot_client import MoviePilotClient NotificationSender = Callable[[str, str], Awaitable[None]] class NotificationPoller: """Poll MoviePilot notification history with a persistent cursor.""" def __init__( self, config: Mapping[str, Any], state_path: str | Path, sender: NotificationSender, *, clock: Callable[[], float] = time.time, ) -> None: self._config = config self._state_path = Path(state_path) self._sender = sender self._clock = clock self._client: MoviePilotClient | None = None self._task: asyncio.Task | None = None self._cursor: int | None = self._load_cursor() self._initialized = self._cursor is not 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 def _load_cursor(self) -> int | None: try: payload = json.loads(self._state_path.read_text(encoding="utf-8")) except (OSError, ValueError): return None value = payload.get("cursor") if isinstance(payload, dict) else None try: return int(value) if value is not None else None except (TypeError, ValueError): return None def _save_cursor(self) -> None: self._state_path.parent.mkdir(parents=True, exist_ok=True) self._state_path.write_text( json.dumps({"cursor": self._cursor}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) async def poll_once(self) -> list[dict[str, Any]]: response = await self._get_client().get( "/api/v1/message/notification", params={"page": 1, "count": 50} ) notifications = [ item for item in response.data if isinstance(item, dict) ] if isinstance(response.data, list) else [] identified = [(self._notification_id(item), item) for item in notifications] identified = [(item_id, item) for item_id, item in identified if item_id is not None] identified.sort(key=lambda pair: pair[0]) if not identified: return [] newest = identified[-1][0] if not self._initialized: self._cursor = newest self._initialized = True self._save_cursor() return [] pending = [item for item_id, item in identified if item_id > (self._cursor or 0)] self._cursor = newest self._save_cursor() targets = fixed_notification_targets(self._config) for item in pending: text = format_notification(item) for target in targets: await self._sender(target, text) return pending def start(self) -> None: if self._task is None or self._task.done(): self._task = asyncio.create_task(self._run()) async def _run(self) -> None: interval = max(int(self._config.get("notification_poll_interval", 60)), 15) while True: try: await self.poll_once() except asyncio.CancelledError: raise except Exception: await asyncio.sleep(min(interval * 2, 300)) else: await asyncio.sleep(interval) async def close(self) -> None: if self._task is not None: self._task.cancel() try: await self._task except asyncio.CancelledError: pass self._task = None if self._client is not None: await self._client.close() self._client = None @staticmethod def _notification_id(item: Mapping[str, Any]) -> int | None: value = item.get("id") try: return int(value) if value is not None else None except (TypeError, ValueError): return None def fixed_notification_targets(config: Mapping[str, Any]) -> list[str]: """Build configured AstrBot unified message origins.""" platform_id = str(config.get("push_platform_id", "aiocqhttp")).strip() targets: list[str] = [] group_id = str(config.get("push_group_id", "")).strip() private_user_id = str(config.get("push_private_user_id", "")).strip() if platform_id and group_id: targets.append(f"{platform_id}:GroupMessage:{group_id}") if platform_id and private_user_id: targets.append(f"{platform_id}:FriendMessage:{private_user_id}") return targets def format_notification(item: Mapping[str, Any]) -> str: title = item.get("title") or "MoviePilot 通知" text = item.get("text") or item.get("message") or "" link = item.get("link") digest_source = json.dumps(dict(item), ensure_ascii=False, sort_keys=True) digest = hashlib.sha1(digest_source.encode("utf-8")).hexdigest()[:8] lines = [f"【{title}】", str(text) if text else ""] if link: lines.append(f"详情:{link}") lines.append(f"通知 ID:{item.get('id', digest)}") return "\n".join(line for line in lines if line)