455 行
21 KiB
Python
455 行
21 KiB
Python
"""AstrBot MoviePilot integration plugin."""
|
||
|
||
from astrbot.api import AstrBotConfig, logger, star
|
||
from astrbot.api.event import AstrMessageEvent, filter
|
||
|
||
try:
|
||
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
|
||
except ImportError:
|
||
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(
|
||
"astrbot_plugin_moviepilot",
|
||
"AstrBot MoviePilot Contributors",
|
||
"在 AstrBot 中通过命令和 LLM 控制 MoviePilot。",
|
||
"0.11.0",
|
||
)
|
||
class MoviePilotPlugin(star.Star):
|
||
"""MoviePilot integration entrypoint."""
|
||
|
||
def __init__(self, context: star.Context, config: AstrBotConfig) -> None:
|
||
super().__init__(context)
|
||
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 插件已加载")
|
||
|
||
@filter.command_group("mp")
|
||
def moviepilot(self) -> None:
|
||
"""MoviePilot 命令组。"""
|
||
|
||
@moviepilot.command("help", alias={"帮助"})
|
||
async def moviepilot_help(self, event: AstrMessageEvent) -> None:
|
||
"""显示 MoviePilot 插件命令入口。"""
|
||
if not self.access_policy.is_allowed(event):
|
||
return
|
||
yield event.plain_result(
|
||
"MoviePilot 命令:/mp search、/mp detail、/mp seasons、/mp resources、"
|
||
"/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:
|
||
"""释放插件资源。"""
|
||
await self.media_service.close()
|
||
await self.subscription_service.close()
|
||
await self.download_service.close()
|
||
await self.notification_poller.close()
|
||
logger.info("MoviePilot 插件已停止")
|