From 39e09a2da1ae79b2b80e7efc1c3fc03bbff2d580 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 20 Jul 2026 22:28:19 +0800 Subject: [PATCH] feat: add notification polling and push targets --- _conf_schema.json | 6 ++ main.py | 15 +++ notification_service.py | 154 +++++++++++++++++++++++++++++ tests/test_notification_service.py | 77 +++++++++++++++ 4 files changed, 252 insertions(+) create mode 100644 notification_service.py create mode 100644 tests/test_notification_service.py diff --git a/_conf_schema.json b/_conf_schema.json index a8acfb3..fcf4d70 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -58,6 +58,12 @@ "hint": "留空表示不推送到固定群聊", "default": "" }, + "push_platform_id": { + "description": "推送目标平台实例标识", + "type": "string", + "hint": "默认使用 aiocqhttp;需要发送到其他平台时填写对应 AstrBot 平台 ID", + "default": "aiocqhttp" + }, "push_private_user_id": { "description": "通知推送个人账号", "type": "string", diff --git a/main.py b/main.py index fdb4a66..3251be1 100644 --- a/main.py +++ b/main.py @@ -9,6 +9,8 @@ from session_context import SessionContextStore from confirmation import ConfirmationStore from subscription_service import SubscriptionService, format_subscriptions from download_service import DownloadService, format_download_tasks +from notification_service import NotificationPoller +from astrbot.api.event import MessageChain @star.register( @@ -31,6 +33,15 @@ class MoviePilotPlugin(star.Star): self.media_service = MediaService(config, self.session_store) self.subscription_service = SubscriptionService(config) self.download_service = DownloadService(config) + self.notification_poller = NotificationPoller( + config, + star.StarTools.get_data_dir() / "notification_cursor.json", + self._send_notification, + ) + if config.get("enable_notification_polling", True) and config.get( + "moviepilot_url" + ) and config.get("moviepilot_api_token"): + self.notification_poller.start() self.confirmations = ConfirmationStore() logger.info("MoviePilot 插件已加载") @@ -271,9 +282,13 @@ class MoviePilotPlugin(star.Star): self.confirmations.cancel(item["code"]) yield event.plain_result("已取消待确认操作。" if pending else "当前没有待确认操作。") + async def _send_notification(self, target: str, text: str) -> None: + await self.context.send_message(target, MessageChain().message(text)) + async def terminate(self) -> None: """释放插件资源。""" await self.media_service.close() await self.subscription_service.close() await self.download_service.close() + await self.notification_poller.close() logger.info("MoviePilot 插件已停止") diff --git a/notification_service.py b/notification_service.py new file mode 100644 index 0000000..6271069 --- /dev/null +++ b/notification_service.py @@ -0,0 +1,154 @@ +"""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) diff --git a/tests/test_notification_service.py b/tests/test_notification_service.py new file mode 100644 index 0000000..cdc37dd --- /dev/null +++ b/tests/test_notification_service.py @@ -0,0 +1,77 @@ +from pathlib import Path + +import pytest + +from notification_service import ( + NotificationPoller, + fixed_notification_targets, + format_notification, +) + + +class FakeResponse: + def __init__(self, data): + self.data = data + + +class FakeClient: + def __init__(self, data): + self.data = data + + async def get(self, path, *, params=None): + return FakeResponse(self.data) + + +@pytest.mark.asyncio +async def test_first_poll_seeds_cursor_without_replaying_history(tmp_path: Path) -> None: + sent = [] + poller = NotificationPoller( + {"push_group_id": "200", "push_platform_id": "aiocqhttp"}, + tmp_path / "cursor.json", + lambda target, text: _append(sent, target, text), + ) + poller._client = FakeClient([{"id": 1, "title": "旧通知", "text": "old"}]) + + assert await poller.poll_once() == [] + assert sent == [] + assert (tmp_path / "cursor.json").exists() + + +@pytest.mark.asyncio +async def test_new_notifications_are_sent_once(tmp_path: Path) -> None: + sent = [] + poller = NotificationPoller( + {"push_group_id": "200", "push_platform_id": "aiocqhttp"}, + tmp_path / "cursor.json", + lambda target, text: _append(sent, target, text), + ) + poller._client = FakeClient([{"id": 1, "title": "旧", "text": "old"}]) + await poller.poll_once() + poller._client.data = [ + {"id": 1, "title": "旧", "text": "old"}, + {"id": 2, "title": "新", "text": "done"}, + ] + + assert len(await poller.poll_once()) == 1 + assert len(await poller.poll_once()) == 0 + assert len(sent) == 1 + assert "新" in sent[0][1] + + +def test_targets_and_formatting() -> None: + targets = fixed_notification_targets( + { + "push_platform_id": "aiocqhttp", + "push_group_id": "200", + "push_private_user_id": "100", + } + ) + text = format_notification({"id": 2, "title": "下载完成", "text": "沙丘"}) + + assert targets == ["aiocqhttp:GroupMessage:200", "aiocqhttp:FriendMessage:100"] + assert "下载完成" in text + assert "通知 ID:2" in text + + +async def _append(items, target, text): + items.append((target, text))