feat: add media and resource search flow
这个提交存在于:
父节点
4faaa1180c
当前提交
cfb37396a6
共有 4 个文件被更改,包括 298 次插入 和 5 次删除
|
|
@ -76,6 +76,11 @@
|
|||
"hint": "超过有效期后,搜索结果编号不能继续用于订阅或下载",
|
||||
"default": 600
|
||||
},
|
||||
"search_result_count": {
|
||||
"description": "每次搜索返回的结果数量",
|
||||
"type": "int",
|
||||
"default": 5
|
||||
},
|
||||
"enable_notification_polling": {
|
||||
"description": "启用 MoviePilot 通知轮询",
|
||||
"type": "bool",
|
||||
|
|
|
|||
90
main.py
90
main.py
|
|
@ -1,10 +1,11 @@
|
|||
"""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.star import AstrBotConfig
|
||||
|
||||
from access_policy import AccessPolicy
|
||||
from media_service import MediaService, format_media_results, format_resource_results
|
||||
from session_context import SessionContextStore
|
||||
|
||||
|
||||
@star.register(
|
||||
|
|
@ -20,18 +21,97 @@ class MoviePilotPlugin(star.Star):
|
|||
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)
|
||||
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:
|
||||
"""显示 MoviePilot 插件命令入口。"""
|
||||
if not self.access_policy.is_allowed(event):
|
||||
return
|
||||
yield event.plain_result(
|
||||
"MoviePilot 插件已加载。当前开发中,后续将支持 /mp search、/mp resources、"
|
||||
"/mp subscribe 和 /mp download。"
|
||||
"MoviePilot 命令:/mp search、/mp detail、/mp seasons、/mp resources、"
|
||||
"/mp subscribe、/mp download。"
|
||||
)
|
||||
|
||||
@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}")
|
||||
|
||||
async def terminate(self) -> None:
|
||||
"""释放插件资源。"""
|
||||
await self.media_service.close()
|
||||
logger.info("MoviePilot 插件已停止")
|
||||
|
|
|
|||
150
media_service.py
普通文件
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)
|
||||
58
tests/test_media_service.py
普通文件
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([])
|
||||
正在加载…
添加表格
在新工单中引用