比较提交

...

10 提交

作者 SHA1 备注 提交日期
Codex
5f9a5ae35a docs: finalize integration and test report 2026-07-20 22:34:05 +08:00
Codex
e48e325cfc feat: add MoviePilot LLM tools 2026-07-20 22:31:36 +08:00
Codex
08bb9cb7da feat: add cross-platform target abstraction 2026-07-20 22:29:17 +08:00
Codex
39e09a2da1 feat: add notification polling and push targets 2026-07-20 22:28:19 +08:00
Codex
cc9ae09a08 feat: add download task controls 2026-07-20 22:25:50 +08:00
Codex
5e804e08d1 feat: add subscription and download flow 2026-07-20 22:24:07 +08:00
Codex
cfb37396a6 feat: add media and resource search flow 2026-07-20 22:21:29 +08:00
Codex
4faaa1180c feat: add session context and confirmations 2026-07-20 22:19:04 +08:00
Codex
d60788d6c9 feat: add platform access policy 2026-07-20 22:17:04 +08:00
Codex
d3d0327eaa feat: add async MoviePilot REST client 2026-07-20 22:15:26 +08:00
共有 28 个文件被更改,包括 2357 次插入 和 17 次删除

查看文件

@ -4,7 +4,7 @@
## 当前状态 ## 当前状态
当前完成插件骨架和配置 schema。后续按 `docs/development-queue.md` 逐阶段实现。 核心功能已按开发队列完成到 `v0.11.0`,包括媒体/资源搜索、订阅、立即下载、下载任务控制、固定目标通知和 LLM Tool。
## 安装开发版本 ## 安装开发版本
@ -21,3 +21,63 @@
- 通知轮询间隔。 - 通知轮询间隔。
API Token 仅用于访问 MoviePilot,不要粘贴到聊天消息或提交到日志中。 API Token 仅用于访问 MoviePilot,不要粘贴到聊天消息或提交到日志中。
## 命令
```text
/mp help
/mp search <关键词>
/mp detail <媒体编号或媒体ID>
/mp seasons <媒体编号或媒体ID>
/mp resources <媒体编号>
/mp subscribe <媒体编号>
/mp download <资源编号>
/mp downloads
/mp download start <任务ID>
/mp download stop <任务ID>
/mp download delete <任务ID>
/mp subscriptions
/mp confirm <确认码>
/mp cancel
```
推荐使用链路:
```text
/mp search 沙丘
/mp resources 2
/mp download 1
/mp confirm abc123
```
如果没有资源,可以直接:
```text
/mp subscribe 2
```
订阅创建后插件会自动触发一次 MoviePilot 订阅搜索。
## 推送
通知轮询读取 MoviePilot 的 `/api/v1/message/notification`,默认首次启动不重放历史通知,后续按通知 ID 去重。推送目标由配置决定:
- `push_group_id`:固定群聊。
- `push_private_user_id`:固定个人账号。
- `push_platform_id`:目标平台实例,默认 `aiocqhttp`,Telegram 可填写 `telegram`。
## 安全
- 所有命令和 LLM Tool 都先经过平台、私聊用户、群聊和群内用户白名单检查。
- 下载、删除订阅、删除下载任务等副作用操作需要确认。
- 资源下载链接只传给 MoviePilot,默认不直接发送到聊天窗口。
- Token 保存在 AstrBot 配置中,不应写入日志、截图或聊天记录。
## 开发与测试
```bash
python -m pytest tests -q
python -m py_compile main.py access_policy.py confirmation.py download_service.py media_service.py moviepilot_client.py notification_service.py platform_compat.py session_context.py subscription_service.py
```
完整设计和分阶段任务见 `docs/research-2026-07-20.md` 与 `docs/development-queue.md`。

查看文件

@ -13,6 +13,15 @@
"obvious_hint": true, "obvious_hint": true,
"default": "" "default": ""
}, },
"allowed_platforms": {
"description": "允许使用插件的平台",
"type": "list",
"hint": "默认支持 aiocqhttp 和 telegram",
"default": [
"aiocqhttp",
"telegram"
]
},
"private_user_ids": { "private_user_ids": {
"description": "允许操作的私聊用户", "description": "允许操作的私聊用户",
"type": "list", "type": "list",
@ -49,6 +58,12 @@
"hint": "留空表示不推送到固定群聊", "hint": "留空表示不推送到固定群聊",
"default": "" "default": ""
}, },
"push_platform_id": {
"description": "推送目标平台实例标识",
"type": "string",
"hint": "默认使用 aiocqhttp;需要发送到其他平台时填写对应 AstrBot 平台 ID",
"default": "aiocqhttp"
},
"push_private_user_id": { "push_private_user_id": {
"description": "通知推送个人账号", "description": "通知推送个人账号",
"type": "string", "type": "string",
@ -67,6 +82,11 @@
"hint": "超过有效期后,搜索结果编号不能继续用于订阅或下载", "hint": "超过有效期后,搜索结果编号不能继续用于订阅或下载",
"default": 600 "default": 600
}, },
"search_result_count": {
"description": "每次搜索返回的结果数量",
"type": "int",
"default": 5
},
"enable_notification_polling": { "enable_notification_polling": {
"description": "启用 MoviePilot 通知轮询", "description": "启用 MoviePilot 通知轮询",
"type": "bool", "type": "bool",

100
access_policy.py 普通文件
查看文件

@ -0,0 +1,100 @@
"""Platform-aware access policy for MoviePilot commands."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Mapping
@dataclass(frozen=True, slots=True)
class PlatformIdentity:
"""Normalized identity extracted from an AstrBot message event."""
platform_name: str
platform_id: str
user_id: str
group_id: str
session_origin: str
@property
def is_private(self) -> bool:
return not self.group_id
def _string(value: Any) -> str:
return str(value).strip() if value is not None else ""
def identity_from_event(event: Any) -> PlatformIdentity:
"""Extract a platform-neutral identity from an AstrMessageEvent-like object."""
return PlatformIdentity(
platform_name=_string(event.get_platform_name()),
platform_id=_string(event.get_platform_id()),
user_id=_string(event.get_sender_id()),
group_id=_string(event.get_group_id()),
session_origin=_string(event.unified_msg_origin),
)
def _normalized_ids(values: Any) -> set[str]:
if not isinstance(values, (list, tuple, set)):
return set()
return {_string(value) for value in values if _string(value)}
class AccessPolicy:
"""Whitelist policy for private and group MoviePilot operations."""
def __init__(self, config: Mapping[str, Any]) -> None:
self._allowed_platforms = _normalized_ids(
config.get("allowed_platforms", ["aiocqhttp", "telegram"])
)
self._private_user_ids = _normalized_ids(config.get("private_user_ids", []))
self._group_permissions = self._parse_group_permissions(
config.get("group_permissions", [])
)
@staticmethod
def _parse_group_permissions(value: Any) -> dict[str, set[str]]:
permissions: dict[str, set[str]] = {}
if isinstance(value, Mapping):
for group_id, user_ids in value.items():
normalized_group = _string(group_id)
if normalized_group:
permissions[normalized_group] = _normalized_ids(user_ids)
return permissions
if not isinstance(value, (list, tuple)):
return permissions
for item in value:
if not isinstance(item, Mapping):
continue
group_id = _string(item.get("group_id"))
if group_id:
permissions[group_id] = _normalized_ids(item.get("user_ids", []))
return permissions
def is_allowed(self, event: Any) -> bool:
"""Return whether an event may operate MoviePilot."""
identity = identity_from_event(event)
if (
not identity.platform_name
or identity.platform_name not in self._allowed_platforms
):
return False
if not identity.user_id:
return False
if identity.is_private:
return identity.user_id in self._private_user_ids
return (
identity.group_id in self._group_permissions
and identity.user_id in self._group_permissions[identity.group_id]
)
def is_allowed_identity(self, identity: PlatformIdentity) -> bool:
"""Return whether a normalized identity may operate MoviePilot."""
if identity.platform_name not in self._allowed_platforms or not identity.user_id:
return False
if identity.is_private:
return identity.user_id in self._private_user_ids
return identity.user_id in self._group_permissions.get(identity.group_id, set())

104
confirmation.py 普通文件
查看文件

@ -0,0 +1,104 @@
"""Short-lived confirmation requests for side-effecting operations."""
from __future__ import annotations
import secrets
import time
from dataclasses import asdict, dataclass
from typing import Any, Callable
@dataclass(frozen=True, slots=True)
class ConfirmationRequest:
code: str
session_origin: str
user_id: str
operation: str
target: dict[str, Any]
created_at: float
expires_at: float
class ConfirmationStore:
"""In-memory confirmation store bound to the originating session and user."""
def __init__(
self,
*,
ttl: int = 120,
clock: Callable[[], float] = time.time,
) -> None:
self.ttl = max(int(ttl), 1)
self._clock = clock
self._requests: dict[str, ConfirmationRequest] = {}
def _purge_expired(self) -> None:
now = self._clock()
expired = [
code
for code, request in self._requests.items()
if request.expires_at <= now
]
for code in expired:
self._requests.pop(code, None)
def create(
self,
*,
session_origin: str,
user_id: str,
operation: str,
target: dict[str, Any],
) -> ConfirmationRequest:
self._purge_expired()
now = self._clock()
code = secrets.token_hex(3)
while code in self._requests:
code = secrets.token_hex(3)
request = ConfirmationRequest(
code=code,
session_origin=session_origin,
user_id=user_id,
operation=operation,
target=target,
created_at=now,
expires_at=now + self.ttl,
)
self._requests[code] = request
return request
def get(
self,
code: str,
*,
session_origin: str,
user_id: str,
) -> ConfirmationRequest | None:
self._purge_expired()
request = self._requests.get(code.strip().lower())
if request is None:
return None
if request.session_origin != session_origin or request.user_id != user_id:
return None
return request
def consume(
self,
code: str,
*,
session_origin: str,
user_id: str,
) -> ConfirmationRequest | None:
request = self.get(code, session_origin=session_origin, user_id=user_id)
if request is None:
return None
self._requests.pop(request.code, None)
return request
def cancel(self, code: str) -> bool:
self._purge_expired()
return self._requests.pop(code.strip().lower(), None) is not None
def snapshot(self) -> list[dict[str, Any]]:
self._purge_expired()
return [asdict(request) for request in self._requests.values()]

查看文件

@ -4,6 +4,24 @@
> >
> 目标:在 AstrBot 内提供 MoviePilot 的命令控制、LLM 调用和固定目标通知能力。 > 目标:在 AstrBot 内提供 MoviePilot 的命令控制、LLM 调用和固定目标通知能力。
## 执行映射
本文件的详细内容按实现依赖分组;实际版本推送按以下 11 项执行,每项对应一个版本标签:
| 项目 | 实现内容 | 版本 |
|---|---|---|
| 1 | 插件骨架与 WebUI 配置 | `v0.1.0` |
| 2 | MoviePilot REST Client | `v0.2.0` |
| 3 | 平台白名单权限服务 | `v0.3.0` |
| 4 | 会话缓存和确认机制 | `v0.4.0` |
| 5 | 媒体与资源搜索 | `v0.5.0` |
| 6 | 订阅与立即下载 | `v0.6.0` |
| 7 | 下载任务控制 | `v0.7.0` |
| 8 | 固定目标通知推送 | `v0.8.0` |
| 9 | QQ / Telegram 平台兼容 | `v0.9.0` |
| 10 | LLM Tool 和确认工作流 | `v0.10.0` |
| 11 | 测试、联调和文档 | `v0.11.0` |
## 总体原则 ## 总体原则
- 先做确定性的 REST API 桥接,再做 LLM Tool。 - 先做确定性的 REST API 桥接,再做 LLM Tool。
@ -13,7 +31,7 @@
- 命令和 LLM 共用同一套 MoviePilot Client、权限校验、会话缓存和确认服务。 - 命令和 LLM 共用同一套 MoviePilot Client、权限校验、会话缓存和确认服务。
- 破坏性或有副作用的操作必须经过确认。 - 破坏性或有副作用的操作必须经过确认。
## 阶段 0:插件骨架与配置 ## 阶段 1:插件骨架与配置
### 任务 0.1 创建插件目录结构 ### 任务 0.1 创建插件目录结构
@ -41,7 +59,7 @@
**验收:** 配置可以通过 AstrBot WebUI 修改;Token 字段敏感显示;配置修改后不会要求手工编辑文件。 **验收:** 配置可以通过 AstrBot WebUI 修改;Token 字段敏感显示;配置修改后不会要求手工编辑文件。
## 阶段 1:公共基础层 ## 阶段 2:公共基础层
### 任务 1.1 实现 MoviePilot REST Client ### 任务 1.1 实现 MoviePilot REST Client
@ -94,7 +112,7 @@
**验收:** 确认码无法跨群或跨用户使用;过期后不执行副作用操作。 **验收:** 确认码无法跨群或跨用户使用;过期后不执行副作用操作。
## 阶段 2:媒体查询主链路 ## 阶段 3:媒体查询主链路
### 任务 2.1 实现 `/mp search` ### 任务 2.1 实现 `/mp search`
@ -148,7 +166,7 @@ GET /api/v1/search/media/{mediaid}
**验收:** 资源编号可以安全映射到后续下载操作;不存在资源时不误报为网络错误。 **验收:** 资源编号可以安全映射到后续下载操作;不存在资源时不误报为网络错误。
## 阶段 3:订阅和立即下载 ## 阶段 4:订阅和立即下载
### 任务 3.1 实现 `/mp subscribe` ### 任务 3.1 实现 `/mp subscribe`
@ -232,7 +250,7 @@ POST /api/v1/download/add
删除下载任务必须二次确认。 删除下载任务必须二次确认。
## 阶段 4:固定目标通知推送 ## 阶段 5:固定目标通知推送
### 任务 4.1 实现通知轮询器 ### 任务 4.1 实现通知轮询器
@ -272,7 +290,7 @@ GET /api/v1/message/notification
通知格式应包含:标题、媒体类型、资源摘要、状态、时间和必要的 MoviePilot 跳转地址(如果返回)。Token、完整站点凭据和不必要的下载链接不得发送。 通知格式应包含:标题、媒体类型、资源摘要、状态、时间和必要的 MoviePilot 跳转地址(如果返回)。Token、完整站点凭据和不必要的下载链接不得发送。
## 阶段 5:命令组织和平台兼容 ## 阶段 6:命令组织和平台兼容
### 任务 5.1 完善命令树 ### 任务 5.1 完善命令树
@ -305,7 +323,7 @@ GET /api/v1/message/notification
- 统一纯文本和图片回复。 - 统一纯文本和图片回复。
- QQ 先行测试,Telegram 后续验证命令格式和目标消息发送能力。 - QQ 先行测试,Telegram 后续验证命令格式和目标消息发送能力。
## 阶段 6:LLM Tool 和确认工作流 ## 阶段 7:LLM Tool 和确认工作流
### 任务 6.1 添加只读 LLM Tools ### 任务 6.1 添加只读 LLM Tools
@ -341,7 +359,7 @@ GET /api/v1/message/notification
LLM 必须在执行前明确展示媒体、资源、站点、大小和操作类型。 LLM 必须在执行前明确展示媒体、资源、站点、大小和操作类型。
## 阶段 7:测试、联调和文档 ## 阶段 8:测试、联调和文档
### 任务 7.1 单元测试 ### 任务 7.1 单元测试

82
docs/integration.md 普通文件
查看文件

@ -0,0 +1,82 @@
# 安装与联调说明
## 安装
将插件目录放到 AstrBot:
```text
AstrBot/data/plugins/astrbot_plugin_moviepilot/
```
目录至少需要包含:
```text
metadata.yaml
_conf_schema.json
main.py
moviepilot_client.py
```
启动 AstrBot 后,在插件管理页面重载插件,并在插件配置页面填写 MoviePilot 地址和 API Token。
## 配置建议
### MoviePilot
- 地址填写 MoviePilot 的服务根地址,例如 `http://192.168.1.20:3000`。
- 不要把 `/api/v1` 拼到配置地址末尾。
- 使用 MoviePilot 的 API Token。
- AstrBot 和 MoviePilot 在同一局域网时,填写 AstrBot 容器能够访问的地址;不能只填写 MoviePilot 容器内部的 `localhost`。
### OneBot 11 / QQ
- `allowed_platforms` 保留 `aiocqhttp`。
- `private_user_ids` 填允许操作的用户标识。
- `group_permissions` 中填写群标识和群内用户标识。
- 群聊操作必须同时匹配群和用户。
- `push_platform_id` 使用发送通知的 AstrBot 平台实例 ID。
### Telegram
- `allowed_platforms` 增加 `telegram`。
- 根据 AstrBot 实际事件使用的用户/会话标识填写白名单。
- `push_platform_id` 设置为 `telegram`。
- Telegram 的群聊/私聊主动发送能力需要由当前 AstrBot 适配器和 Bot 权限支持。
## 实机联调顺序
1. 先在 AstrBot WebUI 保存配置并重载插件。
2. 使用白名单私聊执行 `/mp test`,验证插件加载、MoviePilot 地址和 API Token。
3. 执行 `/mp search 测试影片`,确认返回媒体编号。
4. 执行 `/mp resources 1`,确认返回资源编号和摘要。
5. 先用测试资源执行 `/mp download 1`,确认收到确认码;再执行 `/mp cancel` 验证取消流程。
6. 再次执行下载并使用 `/mp confirm <确认码>`,确认 MoviePilot 出现下载任务。
7. 执行 `/mp subscribe 1`,确认订阅创建并触发一次搜索。
8. 验证 `/mp downloads`、`/mp subscriptions` 和任务控制命令。
9. 配置固定群聊/个人账号,等待一个轮询周期验证通知推送和去重。
10. 最后测试 LLM 的搜索、资源查询、订阅确认和下载确认链路。
## 常见问题
### 401/403
检查 MoviePilot API Token,以及请求是否确实到达目标 MoviePilot 实例。
### 连接超时
检查容器网络、局域网防火墙、反向代理和 MoviePilot 监听地址;AstrBot 容器内的 `localhost` 指向 AstrBot 容器自身。
### 编号无效或过期
搜索结果按会话保存并受 TTL 限制。重新执行对应的 `/mp search` 或 `/mp resources` 即可。
### 没有推送
检查轮询是否启用、推送平台 ID 是否正确、目标群/用户是否可由 AstrBot 主动发送,以及 MoviePilot 通知历史中是否出现了新记录。
## 尚需实机确认
- 当前 MoviePilot 版本返回的资源字段是否都能被 `/api/v1/download/add` 接受。
- 不同下载器、站点和保存策略下的订阅 Body 行为。
- OneBot 11 和 Telegram 部署中的实际平台实例 ID。
- MoviePilot 通知历史 ID 的稳定性和轮询分页行为。

32
docs/test-report.md 普通文件
查看文件

@ -0,0 +1,32 @@
# 阶段 11 测试报告
## 已通过
- `python -m pytest tests -q`
- 34 个测试通过。
- 所有插件业务模块通过 `python -m py_compile`。
- metadata 和 `_conf_schema.json` 可解析。
- MoviePilot REST Client、白名单、缓存、确认、媒体搜索、订阅、下载、通知、平台目标和 LLM 注册均有测试覆盖。
## 当前环境限制
尝试将本插件放到本地 AstrBot 参考源码路径进行导入检查时,环境缺少 AstrBot 运行依赖:
```text
ModuleNotFoundError: No module named 'deprecated'
```
这属于本机 AstrBot 参考环境未安装完整依赖,不能替代真实 AstrBot 实例联调。应在实际 AstrBot 虚拟环境或容器中安装 AstrBot requirements 后再执行:
```bash
python -c "import main; print('astrbot_import: PASS')"
```
## 实机联调剩余项
- 使用真实 MoviePilot API Token 验证 `/mp test`。
- 验证媒体搜索结果字段和资源下载 Body。
- 验证订阅策略继承和自动搜索。
- 验证 QQ 固定群聊/私聊主动推送。
- 验证 Telegram 平台实例 ID 和主动推送权限。
- 验证 MoviePilot 通知历史 ID、分页和轮询去重。

15
docs/version-history.md 普通文件
查看文件

@ -0,0 +1,15 @@
# 版本记录
| 版本 | 阶段 | 内容 |
|---|---|---|
| `v0.1.0` | 1 | 插件骨架、元数据、WebUI 配置 schema |
| `v0.2.0` | 2 | 异步 MoviePilot REST Client |
| `v0.3.0` | 3 | QQ/Telegram 白名单权限服务 |
| `v0.4.0` | 4 | 会话缓存、TTL 和二次确认 |
| `v0.5.0` | 5 | 媒体、详情、季信息和资源搜索 |
| `v0.6.0` | 6 | 订阅、自动触发搜索和立即下载 |
| `v0.7.0` | 7 | 下载任务列表、开始、暂停、删除 |
| `v0.8.0` | 8 | 通知轮询、游标去重和固定目标推送 |
| `v0.9.0` | 9 | QQ/Telegram 平台目标抽象 |
| `v0.10.0` | 10 | LLM 查询工具和确认型写操作工具 |
| `v0.11.0` | 11 | 测试、联调说明和使用文档 |

61
download_service.py 普通文件
查看文件

@ -0,0 +1,61 @@
"""MoviePilot download task 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 DownloadService:
"""Coordinate download task 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 list_tasks(self, name: str | None = None) -> list[dict[str, Any]]:
params = {"name": name} if name else None
response = await self._get_client().get("/api/v1/download/", params=params)
return MediaService._as_dict_list(response.data)
async def start(self, task_id: str) -> dict[str, Any]:
response = await self._get_client().get(f"/api/v1/download/start/{task_id}")
return response.data if isinstance(response.data, dict) else {}
async def stop(self, task_id: str) -> dict[str, Any]:
response = await self._get_client().get(f"/api/v1/download/stop/{task_id}")
return response.data if isinstance(response.data, dict) else {}
async def delete(self, task_id: str) -> dict[str, Any]:
response = await self._get_client().delete(f"/api/v1/download/{task_id}")
return response.data if isinstance(response.data, dict) else {}
def format_download_tasks(tasks: list[dict[str, Any]]) -> str:
if not tasks:
return "当前没有下载任务。"
lines = ["下载任务:"]
for item in tasks:
task_id = item.get("download_id") or item.get("hash") or item.get("id") or "?"
title = item.get("name") or item.get("title") or "未命名任务"
state = item.get("state") or item.get("status") or ""
progress = item.get("progress") or item.get("percent") or ""
suffix = " / ".join(str(value) for value in (state, progress) if value)
lines.append(f"{task_id}: {title}" + (f"({suffix})" if suffix else ""))
return "\n".join(lines)

426
main.py
查看文件

@ -1,15 +1,23 @@
"""AstrBot MoviePilot integration plugin.""" """AstrBot MoviePilot integration plugin."""
from astrbot.api import logger, star from astrbot.api import AstrBotConfig, logger, star
from astrbot.api.event import AstrMessageEvent, filter from astrbot.api.event import AstrMessageEvent, filter
from astrbot.api.star import AstrBotConfig
from access_policy import AccessPolicy
from media_service import MediaService, format_media_results, format_resource_results
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( @star.register(
"astrbot_plugin_moviepilot", "astrbot_plugin_moviepilot",
"AstrBot MoviePilot Contributors", "AstrBot MoviePilot Contributors",
"在 AstrBot 中通过命令和 LLM 控制 MoviePilot。", "在 AstrBot 中通过命令和 LLM 控制 MoviePilot。",
"0.1.0", "0.11.0",
) )
class MoviePilotPlugin(star.Star): class MoviePilotPlugin(star.Star):
"""MoviePilot integration entrypoint.""" """MoviePilot integration entrypoint."""
@ -17,16 +25,422 @@ class MoviePilotPlugin(star.Star):
def __init__(self, context: star.Context, config: AstrBotConfig) -> None: def __init__(self, context: star.Context, config: AstrBotConfig) -> None:
super().__init__(context) super().__init__(context)
self.config = config self.config = config
self.access_policy = AccessPolicy(config)
self.session_store = SessionContextStore(
star.StarTools.get_data_dir() / "sessions.json",
ttl=int(config.get("search_cache_ttl", 600)),
)
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 插件已加载") logger.info("MoviePilot 插件已加载")
@filter.command("mp") @filter.command_group("mp")
def moviepilot(self) -> None:
"""MoviePilot 命令组。"""
@moviepilot.command("help", alias={"帮助"})
async def moviepilot_help(self, event: AstrMessageEvent) -> None: async def moviepilot_help(self, event: AstrMessageEvent) -> None:
"""显示 MoviePilot 插件命令入口。""" """显示 MoviePilot 插件命令入口。"""
if not self.access_policy.is_allowed(event):
return
yield event.plain_result( yield event.plain_result(
"MoviePilot 插件已加载。当前开发中,后续将支持 /mp search、/mp resources、" "MoviePilot 命令:/mp search、/mp detail、/mp seasons、/mp resources、"
"/mp subscribe 和 /mp download。" "/mp subscribe、/mp download。"
) )
@moviepilot.command("test", alias={"测试"})
async def test_connection(self, event: AstrMessageEvent) -> None:
"""测试 MoviePilot 连接和 API Token。"""
if not self.access_policy.is_allowed(event):
return
try:
await self.media_service._get_client().test_connection()
yield event.plain_result("MoviePilot 连接成功,API Token 有效。")
except Exception as exc:
yield event.plain_result(f"MoviePilot 连接失败:{exc}")
@moviepilot.command("search", alias={"搜索"})
async def search_media(self, event: AstrMessageEvent, title: str) -> None:
"""搜索影视信息。"""
if not self.access_policy.is_allowed(event):
return
try:
results = await self.media_service.search_media(event.unified_msg_origin, title)
yield event.plain_result(format_media_results(results))
except Exception as exc:
logger.warning(f"MoviePilot 媒体搜索失败: {exc}")
yield event.plain_result(f"媒体搜索失败:{exc}")
@moviepilot.command("detail", alias={"详情"})
async def media_detail(self, event: AstrMessageEvent, media_id: str) -> None:
"""查询媒体详情。"""
if not self.access_policy.is_allowed(event):
return
try:
media = self.session_store.get_media_result(event.unified_msg_origin, int(media_id))
detail = await self.media_service.media_detail(
media_id if media is None else MediaService._media_id(media)
)
title = detail.get("title") or detail.get("name") or "未命名"
overview = detail.get("description") or detail.get("overview") or "暂无简介"
yield event.plain_result(f"{title}\n{overview}")
except Exception as exc:
logger.warning(f"MoviePilot 媒体详情查询失败: {exc}")
yield event.plain_result(f"媒体详情查询失败:{exc}")
@moviepilot.command("resources", alias={"资源"})
async def search_resources(self, event: AstrMessageEvent, media_index: int) -> None:
"""搜索指定媒体的资源。"""
if not self.access_policy.is_allowed(event):
return
media = self.session_store.get_media_result(event.unified_msg_origin, media_index)
if media is None:
yield event.plain_result("媒体编号无效或已过期,请重新使用 /mp search。")
return
try:
results = await self.media_service.search_resources(
event.unified_msg_origin, media
)
yield event.plain_result(format_resource_results(results))
except Exception as exc:
logger.warning(f"MoviePilot 资源搜索失败: {exc}")
yield event.plain_result(f"资源搜索失败:{exc}")
@moviepilot.command("seasons", alias={"季"})
async def media_seasons(self, event: AstrMessageEvent, media_id: str) -> None:
"""查询媒体季信息。"""
if not self.access_policy.is_allowed(event):
return
media = self.session_store.get_media_result(event.unified_msg_origin, int(media_id))
target_id = media_id if media is None else MediaService._media_id(media)
try:
seasons = await self.media_service.media_seasons(media_id=target_id)
if not seasons:
yield event.plain_result("没有找到季信息。")
return
lines = ["季信息:"]
for item in seasons:
number = item.get("season_number") or item.get("season") or "?"
name = item.get("name") or item.get("title") or ""
lines.append(f"第 {number} 季 {name}".strip())
yield event.plain_result("\n".join(lines))
except Exception as exc:
logger.warning(f"MoviePilot 季信息查询失败: {exc}")
yield event.plain_result(f"季信息查询失败:{exc}")
@moviepilot.command("subscribe", alias={"订阅"})
async def subscribe_media(self, event: AstrMessageEvent, media_index: int) -> None:
"""创建订阅并自动触发一次搜索。"""
if not self.access_policy.is_allowed(event):
return
media = self.session_store.get_media_result(event.unified_msg_origin, media_index)
if media is None:
yield event.plain_result("媒体编号无效或已过期,请重新使用 /mp search。")
return
try:
result = await self.subscription_service.create_subscription(media)
subscribe_id = result.get("id")
if not subscribe_id:
yield event.plain_result("订阅创建失败,MoviePilot 没有返回订阅编号。")
return
message = f"已创建订阅:{media.get('title') or media.get('name') or '未命名'}(ID: {subscribe_id})"
try:
await self.subscription_service.trigger_subscription_search(int(subscribe_id))
message += "\n已自动触发一次资源搜索。"
except Exception as exc:
logger.warning(f"订阅创建成功但触发搜索失败: {exc}")
message += f"\n订阅已保留,但自动搜索失败:{exc}"
yield event.plain_result(message)
except Exception as exc:
logger.warning(f"MoviePilot 创建订阅失败: {exc}")
yield event.plain_result(f"订阅创建失败:{exc}")
@moviepilot.command("subscriptions", alias={"订阅列表"})
async def list_subscriptions(self, event: AstrMessageEvent) -> None:
"""查询订阅列表。"""
if not self.access_policy.is_allowed(event):
return
try:
subscriptions = await self.subscription_service.list_subscriptions()
yield event.plain_result(format_subscriptions(subscriptions))
except Exception as exc:
logger.warning(f"MoviePilot 查询订阅失败: {exc}")
yield event.plain_result(f"查询订阅失败:{exc}")
@moviepilot.command("download", alias={"下载"})
async def download_resource(self, event: AstrMessageEvent, target: str) -> None:
"""创建立即下载确认请求或控制已有下载任务。"""
if not self.access_policy.is_allowed(event):
return
parts = target.split(maxsplit=1)
if parts and parts[0] in {"start", "开始", "stop", "暂停", "delete", "删除"}:
if len(parts) != 2 or not parts[1].strip():
yield event.plain_result("用法:/mp download start|stop|delete <任务ID>")
return
action, task_id = parts[0], parts[1].strip()
if action in {"delete", "删除"}:
request = self.confirmations.create(
session_origin=event.unified_msg_origin,
user_id=event.get_sender_id(),
operation="delete_download",
target={"task_id": task_id},
)
yield event.plain_result(
f"准备删除下载任务 {task_id}。请回复:/mp confirm {request.code}"
)
return
try:
result = (
await self.download_service.start(task_id)
if action in {"start", "开始"}
else await self.download_service.stop(task_id)
)
state = "开始" if action in {"start", "开始"} else "暂停"
yield event.plain_result(f"已发送{state}任务请求:{task_id}\n{result or '操作成功'}")
except Exception as exc:
logger.warning(f"MoviePilot 下载任务控制失败: {exc}")
yield event.plain_result(f"下载任务操作失败:{exc}")
return
try:
resource_index = int(target)
except ValueError:
yield event.plain_result("用法:/mp download <资源编号>,或 /mp download start|stop|delete <任务ID>")
return
origin = event.unified_msg_origin
resource = self.session_store.get_resource_result(origin, resource_index)
media = self.session_store.get_resource_media(origin)
if resource is None or media is None:
yield event.plain_result("资源编号无效或已过期,请重新使用 /mp resources。")
return
request = self.confirmations.create(
session_origin=origin,
user_id=event.get_sender_id(),
operation="download",
target={"resource": resource, "media": media},
)
title = resource.get("title") or resource.get("name") or "未命名资源"
yield event.plain_result(
f"准备下载:{title}\n请在 {self.confirmations.ttl} 秒内回复:/mp confirm {request.code}"
)
@moviepilot.command("confirm", alias={"确认"})
async def confirm_operation(self, event: AstrMessageEvent, code: str) -> None:
"""确认并执行副作用操作。"""
if not self.access_policy.is_allowed(event):
return
request = self.confirmations.consume(
code,
session_origin=event.unified_msg_origin,
user_id=event.get_sender_id(),
)
if request is None:
yield event.plain_result("确认码无效、已过期,或不属于当前会话。")
return
try:
if request.operation == "download":
result = await self.subscription_service.download_resource(
request.target["resource"], request.target["media"]
)
download_id = result.get("download_id") or result.get("id") or "未知"
yield event.plain_result(f"下载任务已提交,任务 ID:{download_id}")
return
if request.operation == "subscribe":
media = request.target["media"]
result = await self.subscription_service.create_subscription(
media, season=request.target.get("season")
)
subscribe_id = result.get("id")
if not subscribe_id:
yield event.plain_result("订阅创建失败,MoviePilot 没有返回订阅编号。")
return
message = f"订阅已创建,ID:{subscribe_id}"
try:
await self.subscription_service.trigger_subscription_search(
int(subscribe_id)
)
message += ";已自动触发一次资源搜索。"
except Exception as exc:
message += f";自动搜索失败:{exc}"
yield event.plain_result(message)
return
if request.operation == "delete_download":
task_id = str(request.target["task_id"])
await self.download_service.delete(task_id)
yield event.plain_result(f"已删除下载任务:{task_id}")
return
yield event.plain_result("不支持的确认操作。")
except Exception as exc:
logger.warning(f"MoviePilot 确认操作失败: {exc}")
yield event.plain_result(f"操作失败:{exc}")
@moviepilot.command("downloads", alias={"下载列表"})
async def list_downloads(self, event: AstrMessageEvent) -> None:
"""查询当前下载任务。"""
if not self.access_policy.is_allowed(event):
return
try:
tasks = await self.download_service.list_tasks()
yield event.plain_result(format_download_tasks(tasks))
except Exception as exc:
logger.warning(f"MoviePilot 查询下载任务失败: {exc}")
yield event.plain_result(f"查询下载任务失败:{exc}")
@moviepilot.command("cancel", alias={"取消"})
async def cancel_confirmation(self, event: AstrMessageEvent) -> None:
"""取消当前会话的待确认操作。"""
if not self.access_policy.is_allowed(event):
return
pending = [
item
for item in self.confirmations.snapshot()
if item["session_origin"] == event.unified_msg_origin
and item["user_id"] == event.get_sender_id()
]
for item in pending:
self.confirmations.cancel(item["code"])
yield event.plain_result("已取消待确认操作。" if pending else "当前没有待确认操作。")
@filter.llm_tool(name="moviepilot_search_media")
async def llm_search_media(
self, event: AstrMessageEvent, title: str, media_type: str = ""
) -> None:
"""搜索 MoviePilot 中的影视信息。
Args:
title(string): 要搜索的影视标题。
media_type(string): 可选媒体类型,填写 movie 或 tv。
"""
if not self.access_policy.is_allowed(event):
return
try:
results = await self.media_service.search_media(
event.unified_msg_origin,
title,
media_type=media_type or None,
)
yield event.plain_result(format_media_results(results))
except Exception as exc:
yield event.plain_result(f"媒体搜索失败:{exc}")
@filter.llm_tool(name="moviepilot_search_resources")
async def llm_search_resources(
self, event: AstrMessageEvent, media_index: int
) -> None:
"""搜索指定影视的下载资源。
Args:
media_index(number): 当前会话最近一次媒体搜索结果的编号。
"""
if not self.access_policy.is_allowed(event):
return
media = self.session_store.get_media_result(event.unified_msg_origin, media_index)
if media is None:
yield event.plain_result("媒体编号无效或已过期,请先重新搜索影视。")
return
try:
results = await self.media_service.search_resources(
event.unified_msg_origin, media
)
yield event.plain_result(format_resource_results(results))
except Exception as exc:
yield event.plain_result(f"资源搜索失败:{exc}")
@filter.llm_tool(name="moviepilot_list_subscriptions")
async def llm_list_subscriptions(self, event: AstrMessageEvent) -> None:
"""查询 MoviePilot 当前订阅列表。"""
if not self.access_policy.is_allowed(event):
return
try:
subscriptions = await self.subscription_service.list_subscriptions()
yield event.plain_result(format_subscriptions(subscriptions))
except Exception as exc:
yield event.plain_result(f"查询订阅失败:{exc}")
@filter.llm_tool(name="moviepilot_list_downloads")
async def llm_list_downloads(self, event: AstrMessageEvent) -> None:
"""查询 MoviePilot 当前下载任务。"""
if not self.access_policy.is_allowed(event):
return
try:
tasks = await self.download_service.list_tasks()
yield event.plain_result(format_download_tasks(tasks))
except Exception as exc:
yield event.plain_result(f"查询下载任务失败:{exc}")
@filter.llm_tool(name="moviepilot_request_subscribe")
async def llm_request_subscribe(
self, event: AstrMessageEvent, media_index: int, season: int = 0
) -> None:
"""请求订阅影视,并等待用户确认。
Args:
media_index(number): 当前会话最近一次媒体搜索结果的编号。
season(number): 可选电视剧季号,电影填写 0。
"""
if not self.access_policy.is_allowed(event):
return
media = self.session_store.get_media_result(event.unified_msg_origin, media_index)
if media is None:
yield event.plain_result("媒体编号无效或已过期,请先重新搜索影视。")
return
request = self.confirmations.create(
session_origin=event.unified_msg_origin,
user_id=event.get_sender_id(),
operation="subscribe",
target={"media": media, "season": season or None},
)
title = media.get("title") or media.get("name") or "未命名"
yield event.plain_result(
f"准备订阅《{title}》。请回复 /mp confirm {request.code} 确认。"
)
@filter.llm_tool(name="moviepilot_request_download")
async def llm_request_download(
self, event: AstrMessageEvent, resource_index: int
) -> None:
"""请求下载资源,并等待用户确认。
Args:
resource_index(number): 当前会话最近一次资源搜索结果的编号。
"""
if not self.access_policy.is_allowed(event):
return
origin = event.unified_msg_origin
resource = self.session_store.get_resource_result(origin, resource_index)
media = self.session_store.get_resource_media(origin)
if resource is None or media is None:
yield event.plain_result("资源编号无效或已过期,请先重新搜索资源。")
return
request = self.confirmations.create(
session_origin=origin,
user_id=event.get_sender_id(),
operation="download",
target={"resource": resource, "media": media},
)
title = resource.get("title") or resource.get("name") or "未命名资源"
yield event.plain_result(
f"准备下载《{title}》。请回复 /mp confirm {request.code} 确认。"
)
async def _send_notification(self, target: str, text: str) -> None:
await self.context.send_message(target, MessageChain().message(text))
async def terminate(self) -> None: 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 插件已停止") logger.info("MoviePilot 插件已停止")

150
media_service.py 普通文件
查看文件

@ -0,0 +1,150 @@
"""MoviePilot media and resource operations."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from moviepilot_client import MoviePilotClient
from session_context import SessionContextStore
class MediaService:
"""Coordinate MoviePilot media APIs with per-session result caching."""
def __init__(
self,
config: Mapping[str, Any],
session_store: SessionContextStore,
) -> None:
self._config = config
self._session_store = session_store
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 search_media(
self,
origin: str,
title: str,
*,
media_type: str | None = None,
page: int = 1,
count: int | None = None,
) -> list[dict[str, Any]]:
params: dict[str, Any] = {"title": title, "page": page}
if media_type:
params["type"] = media_type
params["count"] = count or int(self._config.get("search_result_count", 5))
response = await self._get_client().get("/api/v1/media/search", params=params)
results = self._as_dict_list(response.data)
self._session_store.set_media_results(origin, results)
return results
async def media_detail(self, media_id: str) -> dict[str, Any]:
response = await self._get_client().get(f"/api/v1/media/{media_id}")
return response.data if isinstance(response.data, dict) else {}
async def media_seasons(
self,
*,
media_id: str | None = None,
title: str | None = None,
year: str | None = None,
season: int | None = None,
) -> list[dict[str, Any]]:
params: dict[str, Any] = {}
if media_id:
params["mediaid"] = media_id
if title:
params["title"] = title
if year:
params["year"] = year
if season is not None:
params["season"] = season
response = await self._get_client().get("/api/v1/media/seasons", params=params)
return self._as_dict_list(response.data)
async def search_resources(
self,
origin: str,
media: dict[str, Any],
*,
page: int = 1,
count: int | None = None,
) -> list[dict[str, Any]]:
media_id = self._media_id(media)
if not media_id:
raise ValueError("媒体结果缺少可用的媒体 ID")
response = await self._get_client().get(
f"/api/v1/search/media/{media_id}",
params={
"page": page,
"count": count or int(self._config.get("search_result_count", 5)),
},
)
results = self._as_dict_list(response.data)
self._session_store.set_resource_results(origin, media, results)
return results
@staticmethod
def _media_id(media: Mapping[str, Any]) -> str:
for key in ("mediaid", "media_id", "id", "mediaId"):
value = media.get(key)
if value:
return str(value)
return ""
@staticmethod
def _as_dict_list(value: Any) -> list[dict[str, Any]]:
if isinstance(value, list):
return [item for item in value if isinstance(item, dict)]
if isinstance(value, dict):
for key in ("results", "items", "medias", "torrents"):
nested = value.get(key)
if isinstance(nested, list):
return [item for item in nested if isinstance(item, dict)]
return []
def format_media_results(results: list[dict[str, Any]]) -> str:
if not results:
return "没有找到匹配的影视信息。"
lines = ["影视搜索结果:"]
for index, item in enumerate(results, start=1):
title = item.get("title") or item.get("name") or "未命名"
year = item.get("year") or item.get("release_date") or ""
media_type = item.get("type_name") or item.get("type") or ""
media_id = MediaService._media_id(item)
vote = item.get("vote") or item.get("rating") or ""
details = " / ".join(str(value) for value in (year, media_type, vote) if value)
suffix = f"({details})" if details else ""
lines.append(f"{index}. {title}{suffix} [{media_id}]")
lines.append("可继续使用:/mp resources <编号> 或 /mp subscribe <编号>")
return "\n".join(lines)
def format_resource_results(results: list[dict[str, Any]]) -> str:
if not results:
return "暂未找到资源。可以使用 /mp subscribe <媒体编号> 订阅该媒体。"
lines = ["资源搜索结果:"]
for index, item in enumerate(results, start=1):
title = item.get("title") or item.get("name") or "未命名资源"
site = item.get("site_name") or item.get("site") or "未知站点"
size = item.get("size") or item.get("length") or ""
quality = item.get("quality") or item.get("resolution") or ""
details = " / ".join(str(value) for value in (site, size, quality) if value)
lines.append(f"{index}. {title}({details})")
lines.append("可使用 /mp download <编号> 选择资源下载。")
return "\n".join(lines)

查看文件

@ -2,7 +2,7 @@ name: astrbot_plugin_moviepilot
display_name: MoviePilot 控制 display_name: MoviePilot 控制
description: 在 AstrBot 中通过命令和 LLM 控制 MoviePilot。 description: 在 AstrBot 中通过命令和 LLM 控制 MoviePilot。
short_desc: 搜索影视、订阅、下载和接收 MoviePilot 通知。 short_desc: 搜索影视、订阅、下载和接收 MoviePilot 通知。
version: 0.1.0 version: 0.11.0
author: AstrBot MoviePilot Contributors author: AstrBot MoviePilot Contributors
repo: https://github.com/jxxghp/MoviePilot repo: https://github.com/jxxghp/MoviePilot
astrbot_version: ">=4.16,<5" astrbot_version: ">=4.16,<5"

205
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")

157
notification_service.py 普通文件
查看文件

@ -0,0 +1,157 @@
"""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
from platform_compat import target_from_config
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()
group_target = target_from_config(platform_id, group_id=group_id)
private_target = target_from_config(platform_id, user_id=private_user_id)
if group_target:
targets.append(group_target.unified_msg_origin)
if private_target:
targets.append(private_target.unified_msg_origin)
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)

52
platform_compat.py 普通文件
查看文件

@ -0,0 +1,52 @@
"""Platform-neutral identities and fixed notification targets."""
from __future__ import annotations
from dataclasses import dataclass
from access_policy import PlatformIdentity
@dataclass(frozen=True, slots=True)
class PlatformTarget:
"""A target address that AstrBot can use for proactive messages."""
platform_id: str
message_type: str
session_id: str
@property
def unified_msg_origin(self) -> str:
return f"{self.platform_id}:{self.message_type}:{self.session_id}"
def target_from_config(
platform_id: str,
*,
group_id: str = "",
user_id: str = "",
) -> PlatformTarget | None:
"""Build a fixed group or private target from configured identifiers."""
normalized_platform = str(platform_id or "").strip()
normalized_group = str(group_id or "").strip()
normalized_user = str(user_id or "").strip()
if not normalized_platform:
return None
if normalized_group:
return PlatformTarget(normalized_platform, "GroupMessage", normalized_group)
if normalized_user:
return PlatformTarget(normalized_platform, "FriendMessage", normalized_user)
return None
def parse_unified_msg_origin(value: str) -> PlatformTarget | None:
"""Parse AstrBot's platform/type/session address."""
parts = str(value or "").split(":", 2)
if len(parts) != 3 or not all(parts):
return None
return PlatformTarget(parts[0], parts[1], parts[2])
def is_supported_platform(identity: PlatformIdentity) -> bool:
"""Return whether the normalized identity is a supported target platform."""
return identity.platform_name in {"aiocqhttp", "telegram"}

122
session_context.py 普通文件
查看文件

@ -0,0 +1,122 @@
"""Persistent per-conversation search context."""
from __future__ import annotations
import json
import os
import tempfile
import time
from pathlib import Path
from typing import Any, Callable
class SessionContextStore:
"""Store recent media/resource results without mixing conversations."""
def __init__(
self,
path: str | Path,
*,
ttl: int = 600,
clock: Callable[[], float] = time.time,
) -> None:
self.path = Path(path)
self.ttl = max(int(ttl), 1)
self._clock = clock
self._sessions: dict[str, dict[str, Any]] = {}
self._load()
def _load(self) -> None:
if not self.path.exists():
return
try:
payload = json.loads(self.path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return
if isinstance(payload, dict):
self._sessions = {
str(key): value
for key, value in payload.items()
if isinstance(value, dict)
}
self._purge_expired(save=False)
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_name = tempfile.mkstemp(
prefix=f"{self.path.name}.", suffix=".tmp", dir=self.path.parent
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as output:
json.dump(self._sessions, output, ensure_ascii=False, indent=2)
output.write("\n")
os.replace(temp_name, self.path)
finally:
if os.path.exists(temp_name):
os.remove(temp_name)
def _purge_expired(self, *, save: bool = True) -> None:
now = self._clock()
expired = [
origin
for origin, session in self._sessions.items()
if float(session.get("updated_at", 0)) + self.ttl <= now
]
for origin in expired:
self._sessions.pop(origin, None)
if expired and save:
self._save()
def _session(self, origin: str) -> dict[str, Any]:
self._purge_expired()
return self._sessions.setdefault(origin, {})
def _touch(self, origin: str) -> dict[str, Any]:
session = self._session(origin)
session["updated_at"] = self._clock()
return session
def set_media_results(self, origin: str, results: list[dict[str, Any]]) -> None:
session = self._touch(origin)
session["media_results"] = results
session.pop("resource_results", None)
self._save()
def get_media_results(self, origin: str) -> list[dict[str, Any]]:
results = self._session(origin).get("media_results", [])
return results if isinstance(results, list) else []
def get_media_result(self, origin: str, index: int) -> dict[str, Any] | None:
results = self.get_media_results(origin)
if index < 1 or index > len(results):
return None
item = results[index - 1]
return item if isinstance(item, dict) else None
def set_resource_results(
self, origin: str, media: dict[str, Any], results: list[dict[str, Any]]
) -> None:
session = self._touch(origin)
session["resource_media"] = media
session["resource_results"] = results
self._save()
def get_resource_results(self, origin: str) -> list[dict[str, Any]]:
results = self._session(origin).get("resource_results", [])
return results if isinstance(results, list) else []
def get_resource_result(self, origin: str, index: int) -> dict[str, Any] | None:
results = self.get_resource_results(origin)
if index < 1 or index > len(results):
return None
item = results[index - 1]
return item if isinstance(item, dict) else None
def get_resource_media(self, origin: str) -> dict[str, Any] | None:
media = self._session(origin).get("resource_media")
return media if isinstance(media, dict) else None
def clear(self, origin: str) -> None:
if origin in self._sessions:
self._sessions.pop(origin, None)
self._save()

165
subscription_service.py 普通文件
查看文件

@ -0,0 +1,165 @@
"""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)

77
tests/test_access_policy.py 普通文件
查看文件

@ -0,0 +1,77 @@
from dataclasses import dataclass
from access_policy import AccessPolicy, PlatformIdentity, identity_from_event
@dataclass
class FakeEvent:
platform_name: str = "aiocqhttp"
platform_id: str = "bot-1"
user_id: str = "100"
group_id: str = ""
unified_msg_origin: str = "aiocqhttp:friend:100"
def get_platform_name(self) -> str:
return self.platform_name
def get_platform_id(self) -> str:
return self.platform_id
def get_sender_id(self) -> str:
return self.user_id
def get_group_id(self) -> str:
return self.group_id
def policy() -> AccessPolicy:
return AccessPolicy(
{
"allowed_platforms": ["aiocqhttp", "telegram"],
"private_user_ids": ["100"],
"group_permissions": [
{"group_id": "200", "user_ids": ["100", "101"]}
],
}
)
def test_identity_uses_astrbot_event_fields() -> None:
identity = identity_from_event(FakeEvent())
assert identity == PlatformIdentity(
platform_name="aiocqhttp",
platform_id="bot-1",
user_id="100",
group_id="",
session_origin="aiocqhttp:friend:100",
)
assert identity.is_private
def test_private_user_whitelist() -> None:
access_policy = policy()
assert access_policy.is_allowed(FakeEvent(user_id="100"))
assert not access_policy.is_allowed(FakeEvent(user_id="999"))
def test_group_requires_group_and_user_whitelist() -> None:
access_policy = policy()
assert access_policy.is_allowed(FakeEvent(user_id="100", group_id="200"))
assert access_policy.is_allowed(FakeEvent(user_id="101", group_id="200"))
assert not access_policy.is_allowed(FakeEvent(user_id="999", group_id="200"))
assert not access_policy.is_allowed(FakeEvent(user_id="100", group_id="999"))
def test_platform_and_missing_identity_are_rejected() -> None:
access_policy = policy()
assert not access_policy.is_allowed(FakeEvent(platform_name="discord"))
assert not access_policy.is_allowed(FakeEvent(user_id=""))
def test_mapping_group_config_is_supported() -> None:
access_policy = AccessPolicy(
{"private_user_ids": [], "group_permissions": {"200": ["100"]}}
)
assert access_policy.is_allowed(FakeEvent(user_id="100", group_id="200"))

48
tests/test_confirmation.py 普通文件
查看文件

@ -0,0 +1,48 @@
from confirmation import ConfirmationStore
def test_confirmation_is_bound_to_session_and_user() -> None:
store = ConfirmationStore(ttl=30, clock=lambda: 100)
request = store.create(
session_origin="qq:group:1",
user_id="100",
operation="download",
target={"resource_id": 1},
)
assert store.get(
request.code, session_origin="qq:group:1", user_id="100"
) == request
assert store.get(
request.code, session_origin="qq:group:2", user_id="100"
) is None
assert store.get(
request.code, session_origin="qq:group:1", user_id="999"
) is None
def test_confirmation_is_consumed_once() -> None:
store = ConfirmationStore(ttl=30, clock=lambda: 100)
request = store.create(
session_origin="session",
user_id="100",
operation="delete",
target={"id": 1},
)
assert store.consume(request.code, session_origin="session", user_id="100")
assert store.consume(request.code, session_origin="session", user_id="100") is None
def test_expired_confirmation_cannot_be_consumed() -> None:
now = [100.0]
store = ConfirmationStore(ttl=30, clock=lambda: now[0])
request = store.create(
session_origin="session",
user_id="100",
operation="delete",
target={"id": 1},
)
now[0] = 131.0
assert store.consume(request.code, session_origin="session", user_id="100") is None

查看文件

@ -0,0 +1,55 @@
import pytest
from download_service import DownloadService, format_download_tasks
class FakeResponse:
def __init__(self, data):
self.data = data
class FakeClient:
def __init__(self):
self.calls = []
async def get(self, path, *, params=None):
self.calls.append(("GET", path, params))
if path != "/api/v1/download/":
return FakeResponse({"ok": True})
return FakeResponse([{"download_id": "abc", "name": "沙丘", "state": "下载中"}])
async def delete(self, path, *, params=None):
self.calls.append(("DELETE", path, params))
return FakeResponse({"ok": True})
@pytest.fixture
def service():
service = DownloadService({})
service._client = FakeClient()
return service
@pytest.mark.asyncio
async def test_download_task_operations(service) -> None:
assert (await service.list_tasks())[0]["download_id"] == "abc"
assert (await service.start("abc"))["ok"]
assert (await service.stop("abc"))["ok"]
assert (await service.delete("abc"))["ok"]
assert service._client.calls == [
("GET", "/api/v1/download/", None),
("GET", "/api/v1/download/start/abc", None),
("GET", "/api/v1/download/stop/abc", None),
("DELETE", "/api/v1/download/abc", None),
]
def test_format_download_tasks() -> None:
text = format_download_tasks(
[{"download_id": "abc", "name": "沙丘", "state": "下载中"}]
)
assert "abc" in text
assert "沙丘" in text
assert "下载中" in text
assert "当前没有下载任务" in format_download_tasks([])

25
tests/test_llm_tools.py 普通文件
查看文件

@ -0,0 +1,25 @@
from pathlib import Path
MAIN_SOURCE = (Path(__file__).parents[1] / "main.py").read_text(encoding="utf-8")
def test_llm_tools_are_registered_with_argument_documentation() -> None:
expected_tools = (
"moviepilot_search_media",
"moviepilot_search_resources",
"moviepilot_list_subscriptions",
"moviepilot_list_downloads",
"moviepilot_request_subscribe",
"moviepilot_request_download",
)
for tool_name in expected_tools:
assert f'name="{tool_name}"' in MAIN_SOURCE
assert MAIN_SOURCE.count("Args:") >= 4
def test_llm_write_operations_use_confirmation_store() -> None:
assert 'operation="subscribe"' in MAIN_SOURCE
assert 'operation="download"' in MAIN_SOURCE
assert "/mp confirm" in MAIN_SOURCE

58
tests/test_media_service.py 普通文件
查看文件

@ -0,0 +1,58 @@
import pytest
from media_service import MediaService, format_media_results, format_resource_results
from session_context import SessionContextStore
class FakeResponse:
def __init__(self, data):
self.data = data
class FakeClient:
async def get(self, path, *, params=None):
if path == "/api/v1/media/search":
return FakeResponse([{"id": "tmdb:1", "title": "沙丘", "year": "2021"}])
if path == "/api/v1/media/tmdb:1":
return FakeResponse({"title": "沙丘", "overview": "简介"})
if path == "/api/v1/media/seasons":
return FakeResponse([{"season_number": 1, "name": "第一季"}])
if path == "/api/v1/search/media/tmdb:1":
return FakeResponse([{"title": "Dune", "site": "site-a", "size": "10G"}])
raise AssertionError(path)
@pytest.fixture
def service(tmp_path):
service = MediaService(
{"search_result_count": 5},
SessionContextStore(tmp_path / "sessions.json", ttl=600),
)
service._client = FakeClient()
return service
@pytest.mark.asyncio
async def test_media_and_resource_results_are_cached(service) -> None:
media = await service.search_media("session", "沙丘")
resources = await service.search_resources("session", media[0])
assert media[0]["id"] == "tmdb:1"
assert resources[0]["site"] == "site-a"
assert service._session_store.get_resource_result("session", 1) == resources[0]
@pytest.mark.asyncio
async def test_detail_and_seasons(service) -> None:
assert (await service.media_detail("tmdb:1"))["title"] == "沙丘"
assert (await service.media_seasons(media_id="tmdb:1"))[0]["season_number"] == 1
def test_formatters_include_next_commands() -> None:
media_text = format_media_results([{"id": "tmdb:1", "title": "沙丘"}])
resource_text = format_resource_results([{"title": "Dune", "site": "site-a"}])
assert "/mp resources <编号>" in media_text
assert "/mp download <编号>" in resource_text
assert "没有找到" in format_media_results([])
assert "/mp subscribe <媒体编号>" in format_resource_results([])

查看文件

@ -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")

查看文件

@ -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))

查看文件

@ -0,0 +1,37 @@
from access_policy import PlatformIdentity
from platform_compat import (
is_supported_platform,
parse_unified_msg_origin,
target_from_config,
)
def test_targets_support_qq_and_telegram_without_platform_specific_logic() -> None:
qq_group = target_from_config("aiocqhttp", group_id="200")
telegram_user = target_from_config("telegram", user_id="chat-100")
assert qq_group is not None
assert qq_group.unified_msg_origin == "aiocqhttp:GroupMessage:200"
assert telegram_user is not None
assert telegram_user.unified_msg_origin == "telegram:FriendMessage:chat-100"
def test_target_parser_and_invalid_inputs() -> None:
parsed = parse_unified_msg_origin("aiocqhttp:GroupMessage:200")
assert parsed is not None
assert parsed.session_id == "200"
assert target_from_config("", group_id="200") is None
assert parse_unified_msg_origin("invalid") is None
def test_supported_platforms() -> None:
assert is_supported_platform(
PlatformIdentity("aiocqhttp", "bot", "100", "", "origin")
)
assert is_supported_platform(
PlatformIdentity("telegram", "bot", "100", "", "origin")
)
assert not is_supported_platform(
PlatformIdentity("discord", "bot", "100", "", "origin")
)

查看文件

@ -13,7 +13,7 @@ def test_metadata_contains_required_plugin_fields() -> None:
) )
assert metadata["name"] == "astrbot_plugin_moviepilot" assert metadata["name"] == "astrbot_plugin_moviepilot"
assert metadata["version"] == "0.1.0" assert metadata["version"] == "0.11.0"
assert metadata["astrbot_version"] == ">=4.16,<5" assert metadata["astrbot_version"] == ">=4.16,<5"
assert "aiocqhttp" in metadata["support_platforms"] assert "aiocqhttp" in metadata["support_platforms"]
assert "telegram" in metadata["support_platforms"] assert "telegram" in metadata["support_platforms"]

查看文件

@ -0,0 +1,35 @@
from pathlib import Path
from session_context import SessionContextStore
def test_session_results_are_isolated_and_persisted(tmp_path: Path) -> None:
now = [100.0]
path = tmp_path / "sessions.json"
store = SessionContextStore(path, ttl=10, clock=lambda: now[0])
store.set_media_results("qq:group:1", [{"id": "tmdb:1"}])
store.set_resource_results(
"qq:group:1", {"id": "tmdb:1"}, [{"download": "one"}]
)
restored = SessionContextStore(path, ttl=10, clock=lambda: now[0])
assert restored.get_media_result("qq:group:1", 1) == {"id": "tmdb:1"}
assert restored.get_resource_result("qq:group:1", 1) == {"download": "one"}
assert restored.get_media_result("qq:group:2", 1) is None
def test_new_media_search_clears_previous_resources(tmp_path: Path) -> None:
store = SessionContextStore(tmp_path / "sessions.json", ttl=10, clock=lambda: 100)
store.set_resource_results("session", {"id": "tmdb:1"}, [{"id": 1}])
store.set_media_results("session", [{"id": "tmdb:2"}])
assert store.get_resource_results("session") == []
def test_expired_session_is_removed(tmp_path: Path) -> None:
now = [100.0]
store = SessionContextStore(tmp_path / "sessions.json", ttl=10, clock=lambda: now[0])
store.set_media_results("session", [{"id": 1}])
now[0] = 111.0
assert store.get_media_results("session") == []

查看文件

@ -0,0 +1,72 @@
import pytest
from subscription_service import (
SubscriptionService,
build_subscription_payload,
build_torrent_payload,
)
class FakeResponse:
def __init__(self, data):
self.data = data
class FakeClient:
def __init__(self):
self.calls = []
async def post(self, path, *, params=None, json=None):
self.calls.append(("POST", path, json))
if path == "/api/v1/subscribe/":
return FakeResponse({"id": 8})
return FakeResponse({"download_id": "download-1"})
async def get(self, path, *, params=None):
self.calls.append(("GET", path, params))
return FakeResponse({"ok": True})
async def delete(self, path, *, params=None):
self.calls.append(("DELETE", path, params))
return FakeResponse({"ok": True})
@pytest.fixture
def service():
service = SubscriptionService({})
service._client = FakeClient()
return service
def test_subscription_payload_uses_public_media_fields() -> None:
payload = build_subscription_payload(
{"id": "tmdb:123", "title": "沙丘", "year": "2021", "type": "电影"}
)
assert payload == {
"name": "沙丘",
"year": "2021",
"type": "movie",
"tmdbid": 123,
}
def test_torrent_payload_drops_sensitive_or_unknown_fields() -> None:
payload = build_torrent_payload(
{"title": "Dune", "enclosure": "signed", "site_cookie": "secret", "extra": 1}
)
assert payload == {"title": "Dune", "enclosure": "signed"}
@pytest.mark.asyncio
async def test_subscription_and_download_requests(service) -> None:
media = {"id": "tmdb:123", "title": "沙丘", "type": "movie"}
resource = {"title": "Dune", "enclosure": "signed"}
assert (await service.create_subscription(media))["id"] == 8
assert (await service.trigger_subscription_search(8))["ok"]
assert (await service.download_resource(resource, media))["download_id"] == "download-1"
assert service._client.calls[0][1] == "/api/v1/subscribe/"
assert service._client.calls[1][1] == "/api/v1/subscribe/search/8"
assert service._client.calls[2][1] == "/api/v1/download/add"