mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-26 13:52:44 +08:00
refactor(agent): unify tools behind API gateway and provider skills
This commit is contained in:
@@ -3,7 +3,16 @@ import mimetypes
|
||||
import uuid
|
||||
from typing import Any, AsyncIterator, Optional
|
||||
|
||||
from fastapi import Depends, File, Form, HTTPException, Request, UploadFile, status
|
||||
from fastapi import (
|
||||
Depends,
|
||||
File,
|
||||
Form,
|
||||
Header,
|
||||
HTTPException,
|
||||
Request,
|
||||
UploadFile,
|
||||
status,
|
||||
)
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
|
||||
from app.agent.mcp import agent_mcp_manager
|
||||
@@ -26,12 +35,15 @@ from app.application.messaging.chat import (
|
||||
get_configured_agent_chat_persistence,
|
||||
get_configured_agent_chat_service,
|
||||
)
|
||||
from app.runtime.events import eventmanager
|
||||
from app.runtime.localization import LocaleHelper
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.agent import AgentChatDisplaySaveRequest as _SchemaAgentChatDisplaySaveRequest
|
||||
from app.schemas.agent import AgentChatSessionDetail as _SchemaAgentChatSessionDetail
|
||||
from app.schemas.agent import AgentChatSessionSummary as _SchemaAgentChatSessionSummary
|
||||
from app.schemas.agent import AgentChatUploadAttachment as _SchemaAgentChatUploadAttachment
|
||||
from app.schemas.agent import AgentCommandRunData as _SchemaAgentCommandRunData
|
||||
from app.schemas.agent import AgentCommandRunRequest as _SchemaAgentCommandRunRequest
|
||||
from app.schemas.agent import AgentMcpServerListData as _SchemaAgentMcpServerListData
|
||||
from app.schemas.agent import AgentMcpServersSaveRequest as _SchemaAgentMcpServersSaveRequest
|
||||
from app.schemas.agent import AgentMcpServerTestRequest as _SchemaAgentMcpServerTestRequest
|
||||
@@ -42,6 +54,7 @@ from app.schemas.agent import AgentWebCommandInfo as _SchemaAgentWebCommandInfo
|
||||
from app.schemas.message import AgentWebChatRequest as _SchemaAgentWebChatRequest
|
||||
from app.schemas.message import AgentWebChoiceRequest as _SchemaAgentWebChoiceRequest
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.types import NotificationChannel
|
||||
|
||||
router = ResponseAPIRouter()
|
||||
|
||||
@@ -298,6 +311,36 @@ async def list_web_agent_commands(
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/commands/run",
|
||||
summary="执行 Agent 斜杠命令",
|
||||
response_model=_SchemaResponse[_SchemaAgentCommandRunData],
|
||||
)
|
||||
async def run_agent_command(
|
||||
payload: _SchemaAgentCommandRunRequest,
|
||||
current_user: ApiPrincipal = Depends(get_current_active_user),
|
||||
agent_channel: Optional[str] = Header(None, alias="X-MoviePilot-Agent-Channel"),
|
||||
agent_source: Optional[str] = Header(None, alias="X-MoviePilot-Agent-Source"),
|
||||
) -> _SchemaResponse:
|
||||
"""以当前认证用户和宿主透传渠道触发已注册命令。"""
|
||||
_ensure_superuser(current_user)
|
||||
try:
|
||||
channel = NotificationChannel(agent_channel) if agent_channel else None
|
||||
except ValueError:
|
||||
channel = None
|
||||
try:
|
||||
data = web_agent_application.dispatch_web_agent_command(
|
||||
payload.command,
|
||||
user_id=str(current_user.id),
|
||||
channel=channel,
|
||||
source=agent_source,
|
||||
publish_event=eventmanager.send_event,
|
||||
)
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/sessions",
|
||||
summary="获取 Agent 历史会话",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from typing import Annotated, Any, List, Optional, Union
|
||||
|
||||
import anyio
|
||||
from fastapi import Body, Depends
|
||||
|
||||
from app.adapters.web.security.access import verify_token
|
||||
@@ -9,6 +10,7 @@ from app.api.principal import ApiPrincipal
|
||||
from app.api.response import ResponseAPIRouter
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.directory import DirectoryHelper
|
||||
from app.application.download.tasks import DownloadTaskMutationService
|
||||
from app.application.security.url import SecurityUtils
|
||||
from app.application.site.query import (
|
||||
SiteQueryService,
|
||||
@@ -24,6 +26,8 @@ from app.domain.metainfo import MetaInfo
|
||||
from app.schemas.common import ServiceClientInfo as _SchemaServiceClientInfo
|
||||
from app.schemas.download import DownloadAddedData as _SchemaDownloadAddedData
|
||||
from app.schemas.download import DownloadDirectory as _SchemaDownloadDirectory
|
||||
from app.schemas.download import DownloadTaskUpdateData as _SchemaDownloadTaskUpdateData
|
||||
from app.schemas.download import DownloadTaskUpdateRequest as _SchemaDownloadTaskUpdateRequest
|
||||
from app.schemas.download import SubtitleDownloadData as _SchemaSubtitleDownloadData
|
||||
from app.schemas.file import FileURI as _SchemaFileURI
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
@@ -93,7 +97,7 @@ def _build_unrecognized_media_info(
|
||||
)
|
||||
try:
|
||||
media_type = MediaType(torrent.category)
|
||||
except (TypeError, ValueError):
|
||||
except TypeError, ValueError:
|
||||
media_type = MediaType.from_agent(torrent.category)
|
||||
if media_type == MediaType.COLLECTION:
|
||||
media_type = MediaType.MOVIE
|
||||
@@ -121,14 +125,22 @@ def _resolve_add_media(
|
||||
"""校验媒体身份并为无媒体信息下载构建识别上下文。"""
|
||||
normalized_music_type = normalize_music_type(music_type, allow_artist=False)
|
||||
if music_type is not None and not normalized_music_type:
|
||||
return None, None, _SchemaResponse(
|
||||
success=False,
|
||||
message="音乐实体类型无效,仅支持 recording 或 album",
|
||||
return (
|
||||
None,
|
||||
None,
|
||||
_SchemaResponse(
|
||||
success=False,
|
||||
message="音乐实体类型无效,仅支持 recording 或 album",
|
||||
),
|
||||
)
|
||||
if (media_source is None) != (media_id is None):
|
||||
return None, None, _SchemaResponse(
|
||||
success=False,
|
||||
message="媒体来源和媒体 ID 必须同时提供",
|
||||
return (
|
||||
None,
|
||||
None,
|
||||
_SchemaResponse(
|
||||
success=False,
|
||||
message="媒体来源和媒体 ID 必须同时提供",
|
||||
),
|
||||
)
|
||||
is_music = (
|
||||
torrent_in.category in (MediaType.MUSIC, MediaType.MUSIC.value, "music")
|
||||
@@ -136,9 +148,13 @@ def _resolve_add_media(
|
||||
or normalized_music_type is not None
|
||||
)
|
||||
if is_music and media_source and not is_music_media_source(media_source):
|
||||
return None, None, _SchemaResponse(
|
||||
success=False,
|
||||
message="音乐下载只能使用音乐元数据源",
|
||||
return (
|
||||
None,
|
||||
None,
|
||||
_SchemaResponse(
|
||||
success=False,
|
||||
message="音乐下载只能使用音乐元数据源",
|
||||
),
|
||||
)
|
||||
if is_music and not normalized_music_type:
|
||||
normalized_music_type = MUSIC_ENTITY_RECORDING
|
||||
@@ -166,23 +182,29 @@ def _resolve_add_media(
|
||||
if mediainfo:
|
||||
return metainfo, mediainfo, None
|
||||
if not allow_unrecognized:
|
||||
return metainfo, None, _SchemaResponse(
|
||||
success=False,
|
||||
message="无法识别媒体信息",
|
||||
data=_SchemaDownloadAddedData(requires_confirmation=True),
|
||||
return (
|
||||
metainfo,
|
||||
None,
|
||||
_SchemaResponse(
|
||||
success=False,
|
||||
message="无法识别媒体信息",
|
||||
data=_SchemaDownloadAddedData(requires_confirmation=True),
|
||||
),
|
||||
)
|
||||
return metainfo, _build_unrecognized_media_info(
|
||||
torrent_in,
|
||||
return (
|
||||
metainfo,
|
||||
is_music=is_music,
|
||||
music_type=normalized_music_type,
|
||||
), None
|
||||
_build_unrecognized_media_info(
|
||||
torrent_in,
|
||||
metainfo,
|
||||
is_music=is_music,
|
||||
music_type=normalized_music_type,
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/", summary="正在下载", response_model=List[_SchemaDownloaderTorrent])
|
||||
def current(
|
||||
name: Optional[str] = None, _: _SchemaTokenPayload = Depends(verify_token)
|
||||
) -> Any:
|
||||
def current(name: Optional[str] = None, _: _SchemaTokenPayload = Depends(verify_token)) -> Any:
|
||||
"""
|
||||
查询正在下载的任务
|
||||
"""
|
||||
@@ -218,9 +240,7 @@ def download(
|
||||
# 手动下载始终使用选择的下载器
|
||||
torrentinfo.site_downloader = downloader
|
||||
# 上下文
|
||||
context = Context(
|
||||
meta_info=metainfo, media_info=mediainfo, torrent_info=torrentinfo
|
||||
)
|
||||
context = Context(meta_info=metainfo, media_info=mediainfo, torrent_info=torrentinfo)
|
||||
did = DownloadChain().download_single(
|
||||
context=context,
|
||||
username=current_user.name,
|
||||
@@ -266,9 +286,7 @@ def add(
|
||||
torrentinfo = TorrentInfo()
|
||||
torrentinfo.from_dict(torrent_in.model_dump())
|
||||
# 上下文
|
||||
context = Context(
|
||||
meta_info=metainfo, media_info=mediainfo, torrent_info=torrentinfo
|
||||
)
|
||||
context = Context(meta_info=metainfo, media_info=mediainfo, torrent_info=torrentinfo)
|
||||
|
||||
did = DownloadChain().download_single(
|
||||
context=context,
|
||||
@@ -349,6 +367,39 @@ def stop(
|
||||
return _SchemaResponse(success=True if ret else False)
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/{hashString}",
|
||||
summary="高级更新下载任务",
|
||||
response_model=_SchemaResponse[_SchemaDownloadTaskUpdateData],
|
||||
)
|
||||
async def update_task(
|
||||
hashString: str,
|
||||
payload: _SchemaDownloadTaskUpdateRequest,
|
||||
_: ApiPrincipal = Depends(get_current_active_user),
|
||||
) -> _SchemaResponse:
|
||||
"""执行下载任务启停、标签、限速、Tracker 和保存位置修改。"""
|
||||
chain = DownloadChain()
|
||||
service = DownloadTaskMutationService(
|
||||
list_torrents=chain.list_torrents,
|
||||
set_tags=chain.set_torrents_tag,
|
||||
set_downloading=chain.set_downloading,
|
||||
update_torrent=chain.update_torrent,
|
||||
)
|
||||
try:
|
||||
data = await anyio.to_thread.run_sync(
|
||||
lambda: service.update(
|
||||
hash_value=hashString,
|
||||
**payload.model_dump(),
|
||||
)
|
||||
)
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(
|
||||
success=all(item.get("success") for item in data["results"]),
|
||||
data=data,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/clients",
|
||||
summary="查询可用下载器",
|
||||
@@ -360,17 +411,11 @@ async def clients(_: _SchemaTokenPayload = Depends(verify_token)) -> Any:
|
||||
"""
|
||||
downloaders: List[dict] = get_configured_system_config().get(SystemConfigKey.Downloaders)
|
||||
if downloaders:
|
||||
return [
|
||||
{"name": d.get("name"), "type": d.get("type")}
|
||||
for d in downloaders
|
||||
if d.get("enabled")
|
||||
]
|
||||
return [{"name": d.get("name"), "type": d.get("type")} for d in downloaders if d.get("enabled")]
|
||||
return []
|
||||
|
||||
|
||||
@router.get(
|
||||
"/paths", summary="查询可用下载路径", response_model=List[_SchemaDownloadDirectory]
|
||||
)
|
||||
@router.get("/paths", summary="查询可用下载路径", response_model=List[_SchemaDownloadDirectory])
|
||||
def paths(_: _SchemaTokenPayload = Depends(verify_token)) -> Any:
|
||||
"""
|
||||
查询可直接用于下载接口 save_path 参数的下载路径
|
||||
|
||||
@@ -46,16 +46,10 @@ def list_exposed_tools():
|
||||
"""
|
||||
获取 MCP 可见工具列表
|
||||
"""
|
||||
return [
|
||||
tool
|
||||
for tool in moviepilot_tool_manager.list_tools()
|
||||
if tool.name not in MCP_HIDDEN_TOOLS
|
||||
]
|
||||
return [tool for tool in moviepilot_tool_manager.list_tools() if tool.name not in MCP_HIDDEN_TOOLS]
|
||||
|
||||
|
||||
def create_jsonrpc_response(
|
||||
request_id: Union[str, int, None], result: Any
|
||||
) -> Dict[str, Any]:
|
||||
def create_jsonrpc_response(request_id: Union[str, int, None], result: Any) -> Dict[str, Any]:
|
||||
"""
|
||||
创建 JSON-RPC 成功响应
|
||||
"""
|
||||
@@ -93,9 +87,7 @@ async def _dispatch_jsonrpc_method(
|
||||
return Response(status_code=204)
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=create_jsonrpc_error(
|
||||
request_id, -32600, "initialized must be a notification"
|
||||
),
|
||||
content=create_jsonrpc_error(request_id, -32600, "initialized must be a notification"),
|
||||
)
|
||||
if method == "tools/list":
|
||||
result = await handle_tools_list()
|
||||
@@ -105,11 +97,7 @@ async def _dispatch_jsonrpc_method(
|
||||
return JSONResponse(content=create_jsonrpc_response(request_id, result))
|
||||
if method == "ping":
|
||||
return JSONResponse(content=create_jsonrpc_response(request_id, {}))
|
||||
return JSONResponse(
|
||||
content=create_jsonrpc_error(
|
||||
request_id, -32601, f"Method not found: {method}"
|
||||
)
|
||||
)
|
||||
return JSONResponse(content=create_jsonrpc_error(request_id, -32601, f"Method not found: {method}"))
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -120,9 +108,7 @@ async def _dispatch_jsonrpc_method(
|
||||
RAW_RESPONSE_OPENAPI_KEY: True,
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {
|
||||
"application/json": {"schema": _SchemaMCP_JSONRPC_REQUEST_SCHEMA}
|
||||
},
|
||||
"content": {"application/json": {"schema": _SchemaMCP_JSONRPC_REQUEST_SCHEMA}},
|
||||
},
|
||||
},
|
||||
responses={
|
||||
@@ -182,9 +168,7 @@ async def handle_initialize(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
protocol_version = params.get("protocolVersion")
|
||||
client_info = params.get("clientInfo", {})
|
||||
|
||||
logger.info(
|
||||
f"MCP 初始化请求: 客户端={client_info.get('name')}, 协议版本={protocol_version}"
|
||||
)
|
||||
logger.info(f"MCP 初始化请求: 客户端={client_info.get('name')}, 协议版本={protocol_version}")
|
||||
|
||||
# 版本协商:选择客户端和服务器都支持的版本
|
||||
negotiated_version = MCP_PROTOCOL_VERSION
|
||||
@@ -194,9 +178,7 @@ async def handle_initialize(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
logger.info(f"使用客户端协议版本: {negotiated_version}")
|
||||
else:
|
||||
# 客户端版本不支持,使用服务器默认版本
|
||||
logger.warning(
|
||||
f"协议版本不匹配: 客户端={protocol_version}, 使用服务器版本={negotiated_version}"
|
||||
)
|
||||
logger.warning(f"协议版本不匹配: 客户端={protocol_version}, 使用服务器版本={negotiated_version}")
|
||||
|
||||
return {
|
||||
"protocolVersion": negotiated_version,
|
||||
@@ -279,7 +261,7 @@ async def delete_mcp_session(
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
# ==================== 兼容的 RESTful API 端点 ====================
|
||||
# ==================== HTTP 工具管理端点 ====================
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -318,9 +300,7 @@ async def list_tools(_: Annotated[str, Depends(verify_apikey)]) -> Any:
|
||||
summary="调用工具",
|
||||
response_model=_SchemaResponse[_SchemaToolCallData],
|
||||
)
|
||||
async def call_tool(
|
||||
request: _SchemaToolCallRequest, _: Annotated[str, Depends(verify_apikey)] = None
|
||||
) -> Any:
|
||||
async def call_tool(request: _SchemaToolCallRequest, _: Annotated[str, Depends(verify_apikey)] = None) -> Any:
|
||||
"""
|
||||
调用指定的工具
|
||||
|
||||
@@ -331,9 +311,7 @@ async def call_tool(
|
||||
if request.tool_name in MCP_HIDDEN_TOOLS:
|
||||
raise ValueError(f"工具 '{request.tool_name}' 未找到")
|
||||
|
||||
result_text = await moviepilot_tool_manager.call_tool(
|
||||
request.tool_name, request.arguments
|
||||
)
|
||||
result_text = await moviepilot_tool_manager.call_tool(request.tool_name, request.arguments)
|
||||
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
@@ -349,9 +327,7 @@ async def call_tool(
|
||||
summary="获取工具详情",
|
||||
response_model=_SchemaMcpToolInfo,
|
||||
)
|
||||
async def get_tool_info(
|
||||
tool_name: str, _: Annotated[str, Depends(verify_apikey)]
|
||||
) -> Any:
|
||||
async def get_tool_info(tool_name: str, _: Annotated[str, Depends(verify_apikey)]) -> Any:
|
||||
"""
|
||||
获取指定工具的详细信息
|
||||
|
||||
@@ -384,9 +360,7 @@ async def get_tool_info(
|
||||
summary="获取工具参数Schema",
|
||||
response_model=_SchemaMcpJsonSchema,
|
||||
)
|
||||
async def get_tool_schema(
|
||||
tool_name: str, _: Annotated[str, Depends(verify_apikey)]
|
||||
) -> Any:
|
||||
async def get_tool_schema(tool_name: str, _: Annotated[str, Depends(verify_apikey)]) -> Any:
|
||||
"""
|
||||
获取指定工具的参数Schema(JSON Schema格式)
|
||||
|
||||
|
||||
@@ -13,7 +13,11 @@ from app.adapters.web.security.access import (
|
||||
verify_resource_token,
|
||||
verify_token,
|
||||
)
|
||||
from app.api.context import get_background_task_registry, resolve_background_task_registry
|
||||
from app.api.context import (
|
||||
get_background_task_registry,
|
||||
get_host_runtime,
|
||||
resolve_background_task_registry,
|
||||
)
|
||||
from app.api.dependencies.auth import (
|
||||
get_current_active_superuser,
|
||||
get_current_active_superuser_async,
|
||||
@@ -27,12 +31,14 @@ from app.application.commands import init_commands
|
||||
from app.application.configuration import get_api_runtime_config_snapshot, get_configured_system_config
|
||||
from app.application.plugin.catalog import get_plugin_catalog_query
|
||||
from app.application.plugin.config import PluginConfigCommand
|
||||
from app.application.plugin.data import PluginDataQueryService
|
||||
from app.application.plugin.folders import (
|
||||
add_clone_to_plugin_folder,
|
||||
get_plugin_folder_service,
|
||||
remove_plugin_from_folders,
|
||||
)
|
||||
from app.application.plugin.gateway import get_plugin_install_service
|
||||
from app.application.plugin.management import get_plugin_snapshot
|
||||
from app.application.plugin.rating import (
|
||||
PluginNotInstalledError,
|
||||
get_plugin_rating_service,
|
||||
@@ -72,6 +78,7 @@ from app.schemas.plugin import PluginSourceOptions as _SchemaPluginSourceOptions
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.token import TokenPayload as _SchemaTokenPayload
|
||||
from app.schemas.types import SystemConfigKey
|
||||
from app.startup.composition.context import HostRuntime
|
||||
|
||||
router = ResponseAPIRouter()
|
||||
_plugin_release_refresh_tasks: set[asyncio.Task] = set()
|
||||
@@ -100,9 +107,7 @@ async def _refresh_plugin_release_versions(plugin_id: str, repo_url: str) -> Non
|
||||
logger.warning(f"后台刷新插件 {plugin_id} Release 列表失败:{e}")
|
||||
|
||||
|
||||
def _schedule_plugin_release_refresh(
|
||||
plugin_id: str, repo_url: str, task_registry: TaskRegistry | None = None
|
||||
) -> None:
|
||||
def _schedule_plugin_release_refresh(plugin_id: str, repo_url: str, task_registry: TaskRegistry | None = None) -> None:
|
||||
"""
|
||||
保留后台任务引用,避免任务被回收,同时让 helper 负责同仓库强刷合并。
|
||||
"""
|
||||
@@ -150,7 +155,7 @@ def _is_plugin_auth_remote_file(plugin_id: str, filepath: str) -> bool:
|
||||
expected_prefix = f"plugin/file/{normalized_plugin_id}/"
|
||||
if not remote_path_lower.startswith(expected_prefix):
|
||||
continue
|
||||
remote_file = remote_path[len(expected_prefix):]
|
||||
remote_file = remote_path[len(expected_prefix) :]
|
||||
remote_dir = remote_file.rsplit("/", 1)[0] if "/" in remote_file else ""
|
||||
if path == remote_file or (remote_dir and path.startswith(f"{remote_dir}/")):
|
||||
return True
|
||||
@@ -209,18 +214,11 @@ async def runtime_status(
|
||||
statuses = plugin_manager.get_plugin_runtime_statuses()
|
||||
installed_plugin_ids = {
|
||||
plugin_id.lower()
|
||||
for plugin_id in (
|
||||
get_configured_system_config().get(
|
||||
SystemConfigKey.UserInstalledPlugins
|
||||
)
|
||||
or []
|
||||
)
|
||||
for plugin_id in (get_configured_system_config().get(SystemConfigKey.UserInstalledPlugins) or [])
|
||||
}
|
||||
restart_requirements = {
|
||||
plugin_id: distributions
|
||||
for plugin_id, distributions in (
|
||||
plugin_manager.get_plugin_restart_requirements().items()
|
||||
)
|
||||
for plugin_id, distributions in (plugin_manager.get_plugin_restart_requirements().items())
|
||||
if plugin_id.lower() in installed_plugin_ids
|
||||
}
|
||||
pending = {
|
||||
@@ -321,10 +319,7 @@ async def plugin_ratings(
|
||||
"""
|
||||
requested_ids = plugin_ids.split(",") if plugin_ids is not None else None
|
||||
ratings = await get_plugin_rating_service().ratings(requested_ids)
|
||||
return {
|
||||
plugin_id: _SchemaPluginRating.model_validate(rating)
|
||||
for plugin_id, rating in ratings.items()
|
||||
}
|
||||
return {plugin_id: _SchemaPluginRating.model_validate(rating) for plugin_id, rating in ratings.items()}
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -368,12 +363,8 @@ async def rate_plugin(
|
||||
return _SchemaResponse(success=True, data=rating)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/reload/{plugin_id}", summary="重新加载插件", response_model=_SchemaResponse[None]
|
||||
)
|
||||
def reload_plugin(
|
||||
plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser)
|
||||
) -> Any:
|
||||
@router.get("/reload/{plugin_id}", summary="重新加载插件", response_model=_SchemaResponse[None])
|
||||
def reload_plugin(plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser)) -> Any:
|
||||
"""
|
||||
重新加载插件
|
||||
"""
|
||||
@@ -470,11 +461,7 @@ async def get_plugin_source_options(
|
||||
for candidate in inspection.online_candidates
|
||||
]
|
||||
if inspection.local_candidate is not None:
|
||||
candidates.append(
|
||||
_SchemaPluginSourceCandidate.model_validate(
|
||||
inspection.local_candidate.public_dict()
|
||||
)
|
||||
)
|
||||
candidates.append(_SchemaPluginSourceCandidate.model_validate(inspection.local_candidate.public_dict()))
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data=_SchemaPluginSourceOptions(
|
||||
@@ -482,11 +469,7 @@ async def get_plugin_source_options(
|
||||
inventory_complete=inspection.inventory_complete,
|
||||
selection_status=inspection.selection.status.value,
|
||||
selection_reason=inspection.selection.reason,
|
||||
identity=(
|
||||
_plugin_source_identity_schema(inspection.identity)
|
||||
if inspection.identity is not None
|
||||
else None
|
||||
),
|
||||
identity=(_plugin_source_identity_schema(inspection.identity) if inspection.identity is not None else None),
|
||||
candidates=candidates,
|
||||
),
|
||||
)
|
||||
@@ -583,9 +566,7 @@ def plugin_sidebar_nav(_: _SchemaTokenPayload = Depends(verify_token)) -> Any:
|
||||
summary="获取插件表单页面",
|
||||
response_model=_SchemaJsonObject,
|
||||
)
|
||||
def plugin_form(
|
||||
plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser)
|
||||
) -> dict:
|
||||
def plugin_form(plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser)) -> dict:
|
||||
"""
|
||||
根据插件ID获取插件配置表单或Vue组件URL
|
||||
"""
|
||||
@@ -619,9 +600,7 @@ def plugin_form(
|
||||
summary="获取插件数据页面",
|
||||
response_model=_SchemaJsonObject,
|
||||
)
|
||||
def plugin_page(
|
||||
plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser)
|
||||
) -> dict:
|
||||
def plugin_page(plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser)) -> dict:
|
||||
"""
|
||||
根据插件ID获取插件数据页面
|
||||
"""
|
||||
@@ -686,9 +665,7 @@ def plugin_dashboard(
|
||||
return plugin_dashboard_by_key(plugin_id, "", user_agent)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/reset/{plugin_id}", summary="重置插件配置及数据", response_model=_SchemaResponse[None]
|
||||
)
|
||||
@router.get("/reset/{plugin_id}", summary="重置插件配置及数据", response_model=_SchemaResponse[None])
|
||||
def reset_plugin(
|
||||
plugin_id: str,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser),
|
||||
@@ -710,9 +687,7 @@ def reset_plugin(
|
||||
200: {
|
||||
"description": "插件静态资源",
|
||||
"content": {
|
||||
"application/octet-stream": {
|
||||
"schema": {"type": "string", "format": "binary"}
|
||||
},
|
||||
"application/octet-stream": {"schema": {"type": "string", "format": "binary"}},
|
||||
"application/javascript": {"schema": {"type": "string"}},
|
||||
"text/css": {"schema": {"type": "string"}},
|
||||
},
|
||||
@@ -729,17 +704,12 @@ async def plugin_static_file(
|
||||
"""
|
||||
# 基础安全检查
|
||||
if ".." in filepath or ".." in plugin_id:
|
||||
logger.warning(
|
||||
f"Static File API: Path traversal attempt detected: {plugin_id}/{filepath}"
|
||||
)
|
||||
logger.warning(f"Static File API: Path traversal attempt detected: {plugin_id}/{filepath}")
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
|
||||
|
||||
source_plugin_id = get_plugin_manager().get_plugin_source_id(plugin_id)
|
||||
plugin_base_dir = (
|
||||
AsyncPath(get_api_runtime_config_snapshot().root_path)
|
||||
/ "app"
|
||||
/ "plugins"
|
||||
/ source_plugin_id.lower()
|
||||
AsyncPath(get_api_runtime_config_snapshot().root_path) / "app" / "plugins" / source_plugin_id.lower()
|
||||
)
|
||||
plugin_file_path = plugin_base_dir / filepath.lstrip("/")
|
||||
|
||||
@@ -747,24 +717,16 @@ async def plugin_static_file(
|
||||
resolved_base = await plugin_base_dir.resolve()
|
||||
resolved_file = await plugin_file_path.resolve()
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid path"
|
||||
)
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid path")
|
||||
|
||||
if not resolved_file.is_relative_to(resolved_base):
|
||||
logger.warning(
|
||||
f"Static File API: Path traversal attempt detected: {plugin_id}/{filepath}"
|
||||
)
|
||||
logger.warning(f"Static File API: Path traversal attempt detected: {plugin_id}/{filepath}")
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
|
||||
|
||||
if not await plugin_file_path.exists():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=f"{plugin_file_path} 不存在"
|
||||
)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"{plugin_file_path} 不存在")
|
||||
if not await plugin_file_path.is_file():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail=f"{plugin_file_path} 不是文件"
|
||||
)
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"{plugin_file_path} 不是文件")
|
||||
|
||||
# 判断 MIME 类型
|
||||
response_type, _ = mimetypes.guess_type(str(plugin_file_path))
|
||||
@@ -788,9 +750,7 @@ async def plugin_static_file(
|
||||
return StreamingResponse(
|
||||
file_generator(),
|
||||
media_type=response_type,
|
||||
headers={
|
||||
"Content-Disposition": f"inline; filename={plugin_file_path.name}"
|
||||
},
|
||||
headers={"Content-Disposition": f"inline; filename={plugin_file_path.name}"},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
@@ -815,9 +775,7 @@ async def get_plugin_folders(
|
||||
|
||||
|
||||
@router.post("/folders", summary="保存插件文件夹配置", response_model=_SchemaResponse[None])
|
||||
async def save_plugin_folders(
|
||||
folders: dict, _: ApiPrincipal = Depends(get_current_active_superuser_async)
|
||||
) -> Any:
|
||||
async def save_plugin_folders(folders: dict, _: ApiPrincipal = Depends(get_current_active_superuser_async)) -> Any:
|
||||
"""
|
||||
保存插件文件夹分组配置
|
||||
"""
|
||||
@@ -825,12 +783,8 @@ async def save_plugin_folders(
|
||||
return _SchemaResponse(success=result.success, message=result.message)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/folders/{folder_name}", summary="创建插件文件夹", response_model=_SchemaResponse[None]
|
||||
)
|
||||
async def create_plugin_folder(
|
||||
folder_name: str, _: ApiPrincipal = Depends(get_current_active_superuser_async)
|
||||
) -> Any:
|
||||
@router.post("/folders/{folder_name}", summary="创建插件文件夹", response_model=_SchemaResponse[None])
|
||||
async def create_plugin_folder(folder_name: str, _: ApiPrincipal = Depends(get_current_active_superuser_async)) -> Any:
|
||||
"""
|
||||
创建新的插件文件夹
|
||||
"""
|
||||
@@ -838,12 +792,8 @@ async def create_plugin_folder(
|
||||
return _SchemaResponse(success=result.success, message=result.message)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/folders/{folder_name}", summary="删除插件文件夹", response_model=_SchemaResponse[None]
|
||||
)
|
||||
async def delete_plugin_folder(
|
||||
folder_name: str, _: ApiPrincipal = Depends(get_current_active_superuser_async)
|
||||
) -> Any:
|
||||
@router.delete("/folders/{folder_name}", summary="删除插件文件夹", response_model=_SchemaResponse[None])
|
||||
async def delete_plugin_folder(folder_name: str, _: ApiPrincipal = Depends(get_current_active_superuser_async)) -> Any:
|
||||
"""
|
||||
删除插件文件夹
|
||||
"""
|
||||
@@ -868,9 +818,7 @@ async def update_folder_plugins(
|
||||
return _SchemaResponse(success=result.success, message=result.message)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/clone/{plugin_id}", summary="创建插件分身", response_model=_SchemaResponse[None]
|
||||
)
|
||||
@router.post("/clone/{plugin_id}", summary="创建插件分身", response_model=_SchemaResponse[None])
|
||||
def clone_plugin(
|
||||
plugin_id: str,
|
||||
clone_data: _SchemaPluginCloneRequest,
|
||||
@@ -903,14 +851,86 @@ def clone_plugin(
|
||||
return _SchemaResponse(success=False, message=f"创建插件分身失败:{str(e)}")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/runtime/capabilities",
|
||||
summary="查询插件运行能力",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def plugin_capabilities(
|
||||
plugin_id: Optional[str] = None,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
) -> _SchemaResponse:
|
||||
"""查询运行中插件注册的命令、动作和定时服务。"""
|
||||
manager = get_plugin_manager()
|
||||
data: dict[str, Any] = {}
|
||||
commands = manager.get_plugin_commands(pid=plugin_id) or []
|
||||
if commands:
|
||||
data["commands"] = [
|
||||
{
|
||||
"cmd": command.get("cmd"),
|
||||
"desc": command.get("desc"),
|
||||
"plugin_id": command.get("pid"),
|
||||
**({"data": command.get("data")} if command.get("data") else {}),
|
||||
}
|
||||
for command in commands
|
||||
]
|
||||
actions = manager.get_plugin_actions(pid=plugin_id) or []
|
||||
if actions:
|
||||
data["actions"] = [
|
||||
{
|
||||
"plugin_id": group.get("plugin_id"),
|
||||
"plugin_name": group.get("plugin_name"),
|
||||
"actions": [{"id": item.get("id"), "name": item.get("name")} for item in group.get("actions", [])],
|
||||
}
|
||||
for group in actions
|
||||
]
|
||||
services = manager.get_plugin_services(pid=plugin_id) or []
|
||||
if services:
|
||||
data["services"] = [
|
||||
{
|
||||
"id": service.get("id"),
|
||||
"name": service.get("name"),
|
||||
**({"trigger": str(service.get("trigger"))} if service.get("trigger") else {}),
|
||||
**(
|
||||
{"trigger_kwargs": {key: str(value) for key, value in service.get("kwargs", {}).items()}}
|
||||
if service.get("kwargs")
|
||||
else {}
|
||||
),
|
||||
}
|
||||
for service in services
|
||||
]
|
||||
return _SchemaResponse(success=True, data=data)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/runtime/{plugin_id}/data",
|
||||
summary="查询插件持久化数据",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def plugin_data(
|
||||
plugin_id: str,
|
||||
key: Optional[str] = None,
|
||||
max_chars: Optional[int] = None,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""读取插件单键或全部持久化数据,并对大结果进行裁剪。"""
|
||||
try:
|
||||
data = await PluginDataQueryService(
|
||||
runtime.agent.plugin_data,
|
||||
get_plugin_snapshot,
|
||||
).query(plugin_id, key=key, max_chars=max_chars)
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, data=data)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{plugin_id}",
|
||||
summary="获取插件配置",
|
||||
response_model=_SchemaJsonObject,
|
||||
)
|
||||
async def plugin_config(
|
||||
plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser_async)
|
||||
) -> dict:
|
||||
async def plugin_config(plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser_async)) -> dict:
|
||||
"""
|
||||
根据插件ID获取插件配置信息
|
||||
"""
|
||||
@@ -932,9 +952,7 @@ def set_plugin_config(
|
||||
|
||||
|
||||
@router.delete("/{plugin_id}", summary="卸载插件", response_model=_SchemaResponse[None])
|
||||
def uninstall_plugin(
|
||||
plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser)
|
||||
) -> Any:
|
||||
def uninstall_plugin(plugin_id: str, _: ApiPrincipal = Depends(get_current_active_superuser)) -> Any:
|
||||
"""
|
||||
卸载插件
|
||||
"""
|
||||
|
||||
@@ -4,14 +4,29 @@ from fastapi import Depends, HTTPException, status
|
||||
|
||||
from app.adapters.web.security.access import verify_token
|
||||
from app.api.response import ResponseAPIRouter
|
||||
from app.application.music.projection import simplify_music_info
|
||||
from app.chain.listenbrainz import (
|
||||
LISTENBRAINZ_CHART_RANGES,
|
||||
LISTENBRAINZ_FRESH_MAX_DAYS,
|
||||
LISTENBRAINZ_FRESH_SORTS,
|
||||
)
|
||||
from app.chain.recommend import RecommendChain
|
||||
from app.domain.media import normalize_music_type
|
||||
from app.runtime.events import eventmanager
|
||||
from app.schemas.event import RecommendMediaSource as _SchemaRecommendMediaSource
|
||||
from app.schemas.event import RecommendSourceEventData
|
||||
from app.schemas.exception import TMDbException
|
||||
from app.schemas.recommend import AgentRecommendationItem as _SchemaAgentRecommendationItem
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.token import TokenPayload as _SchemaTokenPayload
|
||||
from app.schemas.transfer import MusicInfo as _SchemaMusicInfo
|
||||
from app.schemas.types import ChainEventType
|
||||
from app.schemas.types import (
|
||||
MUSIC_ENTITY_ALBUM,
|
||||
MUSIC_ENTITY_RECORDING,
|
||||
ChainEventType,
|
||||
MediaType,
|
||||
media_type_to_agent,
|
||||
)
|
||||
from app.schemas.workflow import MediaInfo as _SchemaMediaInfo
|
||||
|
||||
router = ResponseAPIRouter()
|
||||
@@ -48,6 +63,141 @@ def source(_: _SchemaTokenPayload = Depends(verify_token)) -> Any:
|
||||
return []
|
||||
|
||||
|
||||
@router.get(
|
||||
"/agent",
|
||||
summary="统一获取 Agent 推荐结果",
|
||||
response_model=_SchemaResponse[list[_SchemaAgentRecommendationItem]],
|
||||
)
|
||||
async def agent_recommendations(
|
||||
source: str = "tmdb_trending",
|
||||
media_type: str = "all",
|
||||
page: int = 1,
|
||||
music_type: Optional[str] = None,
|
||||
range_name: str = "this_month",
|
||||
sort_by: str = "listen_count.desc",
|
||||
days: int = 14,
|
||||
fresh_sort: str = "release_date",
|
||||
past: bool = True,
|
||||
future: bool = True,
|
||||
min_listen_count: int = 0,
|
||||
with_cover: bool = False,
|
||||
_: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse:
|
||||
"""按稳定来源标识返回有界影视、动画或音乐推荐结果。"""
|
||||
page = max(1, page)
|
||||
count = 20
|
||||
if media_type != "all":
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if media_type_enum is None:
|
||||
return _SchemaResponse(success=False, message="无效的媒体类型")
|
||||
media_type = media_type_enum.to_agent()
|
||||
chain = RecommendChain()
|
||||
if source in {"listenbrainz_chart", "listenbrainz_fresh"}:
|
||||
if media_type not in {"all", "music"}:
|
||||
return _SchemaResponse(
|
||||
success=False,
|
||||
message="ListenBrainz 来源只支持音乐媒体类型",
|
||||
)
|
||||
normalized_music_type = normalize_music_type(music_type, allow_artist=False) if music_type else None
|
||||
if music_type and normalized_music_type is None:
|
||||
return _SchemaResponse(success=False, message="无效的音乐实体类型")
|
||||
if source == "listenbrainz_chart":
|
||||
if range_name not in LISTENBRAINZ_CHART_RANGES:
|
||||
return _SchemaResponse(success=False, message="无效的榜单周期")
|
||||
if sort_by not in {"listen_count.desc", "listen_count.asc"}:
|
||||
return _SchemaResponse(success=False, message="无效的榜单排序")
|
||||
music_results = await chain.async_music_chart(
|
||||
range_name=range_name,
|
||||
page=page,
|
||||
count=count,
|
||||
sort_by=sort_by,
|
||||
min_listen_count=max(0, min_listen_count),
|
||||
with_cover=with_cover,
|
||||
entity=normalized_music_type or MUSIC_ENTITY_RECORDING,
|
||||
)
|
||||
else:
|
||||
if normalized_music_type not in {None, MUSIC_ENTITY_ALBUM}:
|
||||
return _SchemaResponse(
|
||||
success=False,
|
||||
message="新发行结果只支持专辑",
|
||||
)
|
||||
if fresh_sort not in LISTENBRAINZ_FRESH_SORTS:
|
||||
return _SchemaResponse(success=False, message="无效的新发行排序")
|
||||
if not past and not future:
|
||||
return _SchemaResponse(
|
||||
success=False,
|
||||
message="past 和 future 不能同时为 false",
|
||||
)
|
||||
music_results = await chain.async_music_fresh_releases(
|
||||
days=max(1, min(days, LISTENBRAINZ_FRESH_MAX_DAYS)),
|
||||
sort=fresh_sort,
|
||||
past=past,
|
||||
future=future,
|
||||
page=page,
|
||||
count=count,
|
||||
with_cover=with_cover,
|
||||
)
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data=[simplify_music_info(item) for item in music_results or []],
|
||||
)
|
||||
if media_type == "music":
|
||||
return _SchemaResponse(
|
||||
success=False,
|
||||
message="音乐推荐需使用 ListenBrainz 来源",
|
||||
)
|
||||
source_calls = {
|
||||
"tmdb_trending": lambda: chain.async_tmdb_trending(page=page),
|
||||
"tmdb_movies": lambda: chain.async_tmdb_movies(page=page),
|
||||
"tmdb_tvs": lambda: chain.async_tmdb_tvs(page=page),
|
||||
"douban_movie_hot": lambda: chain.async_douban_movie_hot(page=page, count=count),
|
||||
"douban_tv_hot": lambda: chain.async_douban_tv_hot(page=page, count=count),
|
||||
"douban_movie_showing": lambda: chain.async_douban_movie_showing(page=page, count=count),
|
||||
"douban_movies": lambda: chain.async_douban_movies(page=page, count=count),
|
||||
"douban_tvs": lambda: chain.async_douban_tvs(page=page, count=count),
|
||||
"douban_movie_top250": lambda: chain.async_douban_movie_top250(page=page, count=count),
|
||||
"douban_tv_weekly_chinese": lambda: chain.async_douban_tv_weekly_chinese(page=page, count=count),
|
||||
"douban_tv_weekly_global": lambda: chain.async_douban_tv_weekly_global(page=page, count=count),
|
||||
"douban_tv_animation": lambda: chain.async_douban_tv_animation(page=page, count=count),
|
||||
"bangumi_calendar": lambda: chain.async_bangumi_calendar(page=page, count=count),
|
||||
}
|
||||
if source == "douban_hot":
|
||||
results = []
|
||||
if media_type in {"all", "movie"}:
|
||||
results.extend(await chain.async_douban_movie_hot(page=page, count=count))
|
||||
if media_type in {"all", "tv"}:
|
||||
results.extend(await chain.async_douban_tv_hot(page=page, count=count))
|
||||
else:
|
||||
operation = source_calls.get(source)
|
||||
if operation is None:
|
||||
return _SchemaResponse(success=False, message=f"不支持的推荐来源: {source}")
|
||||
results = await operation()
|
||||
projected = []
|
||||
for item in (results or [])[:count]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
projected.append(
|
||||
{
|
||||
"title": item.get("title"),
|
||||
"en_title": item.get("en_title"),
|
||||
"year": item.get("year"),
|
||||
"type": media_type_to_agent(item.get("type")),
|
||||
"season": item.get("season"),
|
||||
"tmdb_id": item.get("tmdb_id"),
|
||||
"imdb_id": item.get("imdb_id"),
|
||||
"douban_id": item.get("douban_id"),
|
||||
"bangumi_id": item.get("bangumi_id"),
|
||||
"anilist_id": item.get("anilist_id"),
|
||||
"media_source": item.get("media_source"),
|
||||
"media_id": item.get("media_id"),
|
||||
"vote_average": item.get("vote_average"),
|
||||
"poster_path": item.get("poster_path"),
|
||||
"detail_link": item.get("detail_link"),
|
||||
}
|
||||
)
|
||||
return _SchemaResponse(success=True, data=projected)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/bangumi_calendar",
|
||||
summary="Bangumi每日放送",
|
||||
@@ -92,9 +242,7 @@ async def music_douban(
|
||||
return await RecommendChain().async_music_douban(page=page, count=count)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/douban_showing", summary="豆瓣正在热映", response_model=List[_SchemaMediaInfo]
|
||||
)
|
||||
@router.get("/douban_showing", summary="豆瓣正在热映", response_model=List[_SchemaMediaInfo])
|
||||
async def douban_showing(
|
||||
page: Optional[int] = 1,
|
||||
count: Optional[int] = 30,
|
||||
@@ -106,9 +254,7 @@ async def douban_showing(
|
||||
return await RecommendChain().async_douban_movie_showing(page=page, count=count)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/douban_movies", summary="豆瓣电影", response_model=List[_SchemaMediaInfo]
|
||||
)
|
||||
@router.get("/douban_movies", summary="豆瓣电影", response_model=List[_SchemaMediaInfo])
|
||||
async def douban_movies(
|
||||
sort: Optional[str] = "R",
|
||||
tags: Optional[str] = "",
|
||||
@@ -119,9 +265,7 @@ async def douban_movies(
|
||||
"""
|
||||
浏览豆瓣电影信息
|
||||
"""
|
||||
return await RecommendChain().async_douban_movies(
|
||||
sort=sort, tags=tags, page=page, count=count
|
||||
)
|
||||
return await RecommendChain().async_douban_movies(sort=sort, tags=tags, page=page, count=count)
|
||||
|
||||
|
||||
@router.get("/douban_tvs", summary="豆瓣剧集", response_model=List[_SchemaMediaInfo])
|
||||
@@ -135,9 +279,7 @@ async def douban_tvs(
|
||||
"""
|
||||
浏览豆瓣剧集信息
|
||||
"""
|
||||
return await RecommendChain().async_douban_tvs(
|
||||
sort=sort, tags=tags, page=page, count=count
|
||||
)
|
||||
return await RecommendChain().async_douban_tvs(sort=sort, tags=tags, page=page, count=count)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -204,9 +346,7 @@ async def douban_tv_animation(
|
||||
return await RecommendChain().async_douban_tv_animation(page=page, count=count)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/douban_movie_hot", summary="豆瓣热门电影", response_model=List[_SchemaMediaInfo]
|
||||
)
|
||||
@router.get("/douban_movie_hot", summary="豆瓣热门电影", response_model=List[_SchemaMediaInfo])
|
||||
async def douban_movie_hot(
|
||||
page: Optional[int] = 1,
|
||||
count: Optional[int] = 30,
|
||||
@@ -218,9 +358,7 @@ async def douban_movie_hot(
|
||||
return await RecommendChain().async_douban_movie_hot(page=page, count=count)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/douban_tv_hot", summary="豆瓣热门电视剧", response_model=List[_SchemaMediaInfo]
|
||||
)
|
||||
@router.get("/douban_tv_hot", summary="豆瓣热门电视剧", response_model=List[_SchemaMediaInfo])
|
||||
async def douban_tv_hot(
|
||||
page: Optional[int] = 1,
|
||||
count: Optional[int] = 30,
|
||||
@@ -296,15 +434,9 @@ async def tmdb_tvs(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/tmdb_trending", summary="TMDB流行趋势", response_model=List[_SchemaMediaInfo]
|
||||
)
|
||||
async def tmdb_trending(
|
||||
page: Optional[int] = 1, _: _SchemaTokenPayload = Depends(verify_token)
|
||||
) -> Any:
|
||||
@router.get("/tmdb_trending", summary="TMDB流行趋势", response_model=List[_SchemaMediaInfo])
|
||||
async def tmdb_trending(page: Optional[int] = 1, _: _SchemaTokenPayload = Depends(verify_token)) -> Any:
|
||||
"""
|
||||
TMDB流行趋势
|
||||
"""
|
||||
return await _require_tmdb_result(
|
||||
RecommendChain().async_tmdb_trending(page=page, raise_exception=True)
|
||||
)
|
||||
return await _require_tmdb_result(RecommendChain().async_tmdb_trending(page=page, raise_exception=True))
|
||||
|
||||
210
app/api/endpoints/rule.py
Normal file
210
app/api/endpoints/rule.py
Normal file
@@ -0,0 +1,210 @@
|
||||
"""过滤规则和规则组管理 API。"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from app.api.context import get_host_runtime
|
||||
from app.api.dependencies.auth import get_current_active_superuser_async
|
||||
from app.api.principal import ApiPrincipal
|
||||
from app.api.response import ResponseAPIRouter
|
||||
from app.application.filtering import FilterRuleService
|
||||
from app.schemas.common import JsonObject as _SchemaJsonObject
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.rule import (
|
||||
CustomFilterRuleCreateRequest as _SchemaCustomFilterRuleCreateRequest,
|
||||
)
|
||||
from app.schemas.rule import (
|
||||
CustomFilterRuleUpdateRequest as _SchemaCustomFilterRuleUpdateRequest,
|
||||
)
|
||||
from app.schemas.rule import (
|
||||
FilterRuleGroupCreateRequest as _SchemaFilterRuleGroupCreateRequest,
|
||||
)
|
||||
from app.schemas.rule import (
|
||||
FilterRuleGroupUpdateRequest as _SchemaFilterRuleGroupUpdateRequest,
|
||||
)
|
||||
from app.startup.composition.context import HostRuntime
|
||||
|
||||
router = ResponseAPIRouter()
|
||||
|
||||
|
||||
def _service(runtime: HostRuntime) -> FilterRuleService:
|
||||
"""从宿主组合根收窄出规则 API 所需端口。"""
|
||||
return FilterRuleService(
|
||||
runtime.agent.subscriptions,
|
||||
runtime.agent.async_rule_group_mutation_scope,
|
||||
runtime.system.publish_config_changed,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/builtin",
|
||||
summary="查询内置过滤规则",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def query_builtin_rules(
|
||||
rule_ids: Optional[list[str]] = None,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
) -> _SchemaResponse:
|
||||
"""返回内置规则及规则串语法。"""
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data=FilterRuleService.query_builtin(rule_ids),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/custom",
|
||||
summary="查询自定义过滤规则",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def query_custom_rules(
|
||||
rule_ids: Optional[list[str]] = None,
|
||||
include_group_refs: bool = True,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
) -> _SchemaResponse:
|
||||
"""返回自定义规则和可选规则组引用。"""
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data=FilterRuleService.query_custom(
|
||||
rule_ids,
|
||||
include_group_refs=include_group_refs,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/groups",
|
||||
summary="查询过滤规则组",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def query_rule_groups(
|
||||
group_names: Optional[list[str]] = None,
|
||||
include_usage: bool = True,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""返回规则组、解析层级和可选引用位置。"""
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data=await _service(runtime).query_groups(
|
||||
group_names,
|
||||
include_usage=include_usage,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/custom",
|
||||
summary="新增自定义过滤规则",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def add_custom_rule(
|
||||
payload: _SchemaCustomFilterRuleCreateRequest,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""校验并新增一条自定义过滤规则。"""
|
||||
try:
|
||||
data = await _service(runtime).add_custom(**payload.model_dump())
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/custom/{rule_id}",
|
||||
summary="更新自定义过滤规则",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def update_custom_rule(
|
||||
rule_id: str,
|
||||
payload: _SchemaCustomFilterRuleUpdateRequest,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""更新自定义规则并在改名时原子重写引用。"""
|
||||
try:
|
||||
data = await _service(runtime).update_custom(
|
||||
current_rule_id=rule_id,
|
||||
**payload.model_dump(),
|
||||
)
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/custom/{rule_id}",
|
||||
summary="删除自定义过滤规则",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def delete_custom_rule(
|
||||
rule_id: str,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""删除一条未被规则组引用的自定义过滤规则。"""
|
||||
try:
|
||||
data = await _service(runtime).delete_custom(rule_id)
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/groups",
|
||||
summary="新增过滤规则组",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def add_rule_group(
|
||||
payload: _SchemaFilterRuleGroupCreateRequest,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""新增一个已经完成语法与引用校验的规则组。"""
|
||||
try:
|
||||
data = await _service(runtime).add_group(**payload.model_dump())
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/groups/{name}",
|
||||
summary="更新过滤规则组",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def update_rule_group(
|
||||
name: str,
|
||||
payload: _SchemaFilterRuleGroupUpdateRequest,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""更新规则组并原子重写全部名称引用。"""
|
||||
try:
|
||||
data = await _service(runtime).update_group(
|
||||
current_name=name,
|
||||
**payload.model_dump(),
|
||||
)
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/groups/{name}",
|
||||
summary="删除过滤规则组",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def delete_rule_group(
|
||||
name: str,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""删除规则组并原子清理全部全局和订阅引用。"""
|
||||
try:
|
||||
data = await _service(runtime).delete_group(name)
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
@@ -14,6 +14,7 @@ from app.api.dependencies.auth import (
|
||||
from app.api.principal import ApiPrincipal
|
||||
from app.api.response import ResponseAPIRouter
|
||||
from app.application.configuration import get_api_runtime_config_snapshot
|
||||
from app.application.directory import DirectoryHelper
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.storage import StorageChain
|
||||
from app.chain.transfer.facade import TransferChain
|
||||
@@ -21,18 +22,74 @@ from app.foundation import text as text_tools
|
||||
from app.runtime.progress import ProgressHelper
|
||||
from app.schemas.common import ManageRequest as _SchemaManageRequest
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.system import TransferDirectoryConf as _SchemaTransferDirectoryConf
|
||||
from app.schemas.types import ProgressKey
|
||||
from app.schemas.workflow import FileItem as _SchemaFileItem
|
||||
|
||||
router = ResponseAPIRouter()
|
||||
|
||||
|
||||
@router.post(
|
||||
"/manage", summary="网盘存储统一管理", response_model=_SchemaResponse[Dict[str, Any]]
|
||||
@router.get(
|
||||
"/directories",
|
||||
summary="查询目录配置",
|
||||
response_model=_SchemaResponse[list[_SchemaTransferDirectoryConf]],
|
||||
)
|
||||
def manage(
|
||||
request: _SchemaManageRequest, _: ApiPrincipal = Depends(get_current_active_superuser)
|
||||
) -> Any:
|
||||
def directory_settings(
|
||||
directory_type: str = "all",
|
||||
storage_type: str = "all",
|
||||
name: Optional[str] = None,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser),
|
||||
) -> _SchemaResponse:
|
||||
"""按用途、存储类型和名称筛选目录配置。"""
|
||||
helper = DirectoryHelper()
|
||||
if directory_type == "download":
|
||||
directories = helper.get_download_dirs()
|
||||
elif directory_type == "library":
|
||||
directories = helper.get_library_dirs()
|
||||
elif directory_type == "all":
|
||||
directories = helper.get_dirs()
|
||||
else:
|
||||
return _SchemaResponse(success=False, message="directory_type 无效")
|
||||
results = []
|
||||
for directory in directories:
|
||||
if storage_type == "local":
|
||||
if directory_type == "download" and directory.storage != "local":
|
||||
continue
|
||||
if directory_type == "library" and directory.library_storage != "local":
|
||||
continue
|
||||
elif storage_type == "remote":
|
||||
if directory_type == "download" and directory.storage == "local":
|
||||
continue
|
||||
if directory_type == "library" and directory.library_storage == "local":
|
||||
continue
|
||||
elif storage_type != "all":
|
||||
return _SchemaResponse(success=False, message="storage_type 无效")
|
||||
if name and name.lower() not in (directory.name or "").lower():
|
||||
continue
|
||||
results.append(
|
||||
{
|
||||
"name": directory.name,
|
||||
"priority": directory.priority,
|
||||
"storage": directory.storage,
|
||||
"download_path": directory.download_path,
|
||||
"library_path": directory.library_path,
|
||||
"library_storage": directory.library_storage,
|
||||
"media_type": directory.media_type,
|
||||
"media_category": directory.media_category,
|
||||
"monitor_type": directory.monitor_type,
|
||||
"monitor_mode": directory.monitor_mode,
|
||||
"transfer_type": directory.transfer_type,
|
||||
"overwrite_mode": directory.overwrite_mode,
|
||||
"renaming": directory.renaming,
|
||||
"scraping": directory.scraping,
|
||||
"notify": directory.notify,
|
||||
}
|
||||
)
|
||||
return _SchemaResponse(success=True, data=results)
|
||||
|
||||
|
||||
@router.post("/manage", summary="网盘存储统一管理", response_model=_SchemaResponse[Dict[str, Any]])
|
||||
def manage(request: _SchemaManageRequest, _: ApiPrincipal = Depends(get_current_active_superuser)) -> Any:
|
||||
"""
|
||||
网盘存储统一管理入口
|
||||
|
||||
@@ -99,9 +156,7 @@ def mkdir(
|
||||
|
||||
|
||||
@router.post("/delete", summary="删除文件或目录", response_model=_SchemaResponse[None])
|
||||
def delete(
|
||||
fileitem: _SchemaFileItem, _: ApiPrincipal = Depends(get_current_active_manage_user)
|
||||
) -> Any:
|
||||
def delete(fileitem: _SchemaFileItem, _: ApiPrincipal = Depends(get_current_active_manage_user)) -> Any:
|
||||
"""
|
||||
删除文件或目录
|
||||
:param fileitem: 文件项
|
||||
@@ -121,18 +176,12 @@ def delete(
|
||||
responses={
|
||||
200: {
|
||||
"description": "文件内容",
|
||||
"content": {
|
||||
"application/octet-stream": {
|
||||
"schema": {"type": "string", "format": "binary"}
|
||||
}
|
||||
},
|
||||
"content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}},
|
||||
},
|
||||
404: {"model": _SchemaResponse[None], "description": "文件下载失败"},
|
||||
},
|
||||
)
|
||||
def download(
|
||||
fileitem: _SchemaFileItem, _: ApiPrincipal = Depends(get_current_active_manage_user)
|
||||
) -> Any:
|
||||
def download(fileitem: _SchemaFileItem, _: ApiPrincipal = Depends(get_current_active_manage_user)) -> Any:
|
||||
"""
|
||||
下载文件或目录
|
||||
:param fileitem: 文件项
|
||||
@@ -153,15 +202,11 @@ def download(
|
||||
responses={
|
||||
200: {
|
||||
"description": "图片内容",
|
||||
"content": {
|
||||
"image/jpeg": {"schema": {"type": "string", "format": "binary"}}
|
||||
},
|
||||
"content": {"image/jpeg": {"schema": {"type": "string", "format": "binary"}}},
|
||||
}
|
||||
},
|
||||
)
|
||||
def image(
|
||||
fileitem: _SchemaFileItem, _: ApiPrincipal = Depends(get_current_active_manage_user)
|
||||
) -> Any:
|
||||
def image(fileitem: _SchemaFileItem, _: ApiPrincipal = Depends(get_current_active_manage_user)) -> Any:
|
||||
"""
|
||||
下载文件或目录
|
||||
:param fileitem: 文件项
|
||||
@@ -196,9 +241,7 @@ def rename(
|
||||
transferchain = TransferChain()
|
||||
runtime_config = get_api_runtime_config_snapshot()
|
||||
media_exts = (
|
||||
runtime_config.media_extensions
|
||||
+ runtime_config.subtitle_extensions
|
||||
+ runtime_config.audio_extensions
|
||||
runtime_config.media_extensions + runtime_config.subtitle_extensions + runtime_config.audio_extensions
|
||||
)
|
||||
# 递归修改目录内文件(智能识别命名)
|
||||
sub_files: List[_SchemaFileItem] = StorageChain().list_files(fileitem)
|
||||
@@ -210,9 +253,7 @@ def rename(
|
||||
handled = 0
|
||||
for sub_file in sub_files:
|
||||
handled += 1
|
||||
progress.update(
|
||||
value=handled / total * 100, text=f"正在处理 {sub_file.name} ..."
|
||||
)
|
||||
progress.update(value=handled / total * 100, text=f"正在处理 {sub_file.name} ...")
|
||||
if sub_file.type == "dir":
|
||||
continue
|
||||
if not sub_file.extension:
|
||||
@@ -226,25 +267,15 @@ def rename(
|
||||
)
|
||||
if not context or not context.media_info:
|
||||
progress.end()
|
||||
return _SchemaResponse(
|
||||
success=False, message=f"{sub_path.name} 未识别到媒体信息"
|
||||
)
|
||||
new_path = transferchain.recommend_name(
|
||||
meta=context.meta_info, mediainfo=context.media_info
|
||||
)
|
||||
return _SchemaResponse(success=False, message=f"{sub_path.name} 未识别到媒体信息")
|
||||
new_path = transferchain.recommend_name(meta=context.meta_info, mediainfo=context.media_info)
|
||||
if not new_path:
|
||||
progress.end()
|
||||
return _SchemaResponse(
|
||||
success=False, message=f"{sub_path.name} 未识别到新名称"
|
||||
)
|
||||
ret: _SchemaResponse = rename(
|
||||
fileitem=sub_file, new_name=Path(new_path).name, recursive=False
|
||||
)
|
||||
return _SchemaResponse(success=False, message=f"{sub_path.name} 未识别到新名称")
|
||||
ret: _SchemaResponse = rename(fileitem=sub_file, new_name=Path(new_path).name, recursive=False)
|
||||
if not ret.success:
|
||||
progress.end()
|
||||
return _SchemaResponse(
|
||||
success=False, message=f"{sub_path.name} 重命名失败!"
|
||||
)
|
||||
return _SchemaResponse(success=False, message=f"{sub_path.name} 重命名失败!")
|
||||
progress.end()
|
||||
# 重命名自己
|
||||
result = StorageChain().rename_file(fileitem, new_name)
|
||||
|
||||
@@ -32,6 +32,7 @@ from app.application.network import get_configured_network_test_service
|
||||
from app.application.rules import RuleHelper
|
||||
from app.application.scheduling import get_scheduler
|
||||
from app.application.security.url import SecurityUtils
|
||||
from app.application.settings import SystemSettingsService
|
||||
from app.application.site.sites import SitesHelper # pylint: disable=import-error,no-name-in-module
|
||||
from app.application.system import LogFileData, LogNotFoundError
|
||||
from app.chain.media import MediaChain
|
||||
@@ -52,6 +53,7 @@ from app.schemas.common import JsonObjectList as _SchemaJsonObjectList
|
||||
from app.schemas.common import TimeData as _SchemaTimeData
|
||||
from app.schemas.common import ValueData as _SchemaValueData
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.system import CustomIdentifiersUpdateRequest as _SchemaCustomIdentifiersUpdateRequest
|
||||
from app.schemas.system import DatabaseBackupArtifactData as _SchemaDatabaseBackupArtifactData
|
||||
from app.schemas.system import DatabaseBackupVerificationData as _SchemaDatabaseBackupVerificationData
|
||||
from app.schemas.system import NetTestTarget as _SchemaNetTestTarget
|
||||
@@ -60,6 +62,7 @@ from app.schemas.system import PluginMarketSyncRequest as _SchemaPluginMarketSyn
|
||||
from app.schemas.system import RuleTestData as _SchemaRuleTestData
|
||||
from app.schemas.system import SystemEnvironmentUpdateData as _SchemaSystemEnvironmentUpdateData
|
||||
from app.schemas.system import SystemModuleListData as _SchemaSystemModuleListData
|
||||
from app.schemas.system import SystemSettingsUpdateRequest as _SchemaSystemSettingsUpdateRequest
|
||||
from app.schemas.system import SystemUpdateStatus as _SchemaSystemUpdateStatus
|
||||
from app.schemas.token import TokenPayload as _SchemaTokenPayload
|
||||
from app.schemas.types import SystemConfigKey
|
||||
@@ -108,20 +111,14 @@ def _verify_log_resource_superuser(
|
||||
return token_payload
|
||||
|
||||
|
||||
async def _build_log_zip_response(
|
||||
name: str, runtime: HostRuntime
|
||||
) -> StreamingResponse:
|
||||
async def _build_log_zip_response(name: str, runtime: HostRuntime) -> StreamingResponse:
|
||||
"""读取受限日志条目并生成兼容 ZIP 响应。"""
|
||||
try:
|
||||
entries = await runtime.system.collect_logs(name)
|
||||
except LogNotFoundError as error:
|
||||
raise HTTPException(status_code=404, detail="Not Found") from error
|
||||
zip_data, zip_stem = await anyio.to_thread.run_sync(
|
||||
_build_log_zip_data, name, entries
|
||||
)
|
||||
headers = {
|
||||
"Content-Disposition": f'attachment; filename="{zip_stem}.zip"'
|
||||
}
|
||||
zip_data, zip_stem = await anyio.to_thread.run_sync(_build_log_zip_data, name, entries)
|
||||
headers = {"Content-Disposition": f'attachment; filename="{zip_stem}.zip"'}
|
||||
return StreamingResponse(
|
||||
iter([zip_data]),
|
||||
media_type="application/zip",
|
||||
@@ -129,9 +126,7 @@ async def _build_log_zip_response(
|
||||
)
|
||||
|
||||
|
||||
def _build_log_zip_data(
|
||||
name: str, entries: list[LogFileData]
|
||||
) -> tuple[bytes, str]:
|
||||
def _build_log_zip_data(name: str, entries: list[LogFileData]) -> tuple[bytes, str]:
|
||||
"""只负责把应用服务提供的日志内容编码为 ZIP framing。"""
|
||||
zip_buffer = io.BytesIO()
|
||||
filename_time = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
@@ -145,8 +140,6 @@ def _build_log_zip_data(
|
||||
return zip_buffer.getvalue(), zip_stem
|
||||
|
||||
|
||||
|
||||
|
||||
async def fetch_image(
|
||||
url: str,
|
||||
proxy: Optional[bool] = None,
|
||||
@@ -234,11 +227,7 @@ async def proxy_img(
|
||||
图片代理,可选是否使用代理服务器,支持 HTTP 缓存
|
||||
"""
|
||||
allowed_domains = set(get_runtime_settings().get("SECURITY_IMAGE_DOMAINS", []))
|
||||
cookies = (
|
||||
MediaServerChain().get_image_cookies(server=None, image_url=imgurl)
|
||||
if use_cookies
|
||||
else None
|
||||
)
|
||||
cookies = MediaServerChain().get_image_cookies(server=None, image_url=imgurl) if use_cookies else None
|
||||
return await fetch_image(
|
||||
url=imgurl,
|
||||
proxy=proxy,
|
||||
@@ -370,9 +359,7 @@ async def list_database_backups(
|
||||
) -> list[_SchemaDatabaseBackupArtifactData]:
|
||||
"""列出当前备份目录中的正式制品,不触发内容校验。"""
|
||||
try:
|
||||
artifacts = await run_in_threadpool_to_completion(
|
||||
get_database_governance().list_backups
|
||||
)
|
||||
artifacts = await run_in_threadpool_to_completion(get_database_governance().list_backups)
|
||||
except Exception as error:
|
||||
logger.exception("读取数据库备份列表失败")
|
||||
raise HTTPException(status_code=500, detail="读取数据库备份列表失败,请查看日志") from error
|
||||
@@ -389,9 +376,7 @@ async def create_database_backup(
|
||||
) -> _SchemaDatabaseBackupArtifactData:
|
||||
"""创建、校验并原子发布当前活动数据库的一致快照。"""
|
||||
try:
|
||||
artifact = await run_in_threadpool_to_completion(
|
||||
get_database_governance().create_backup
|
||||
)
|
||||
artifact = await run_in_threadpool_to_completion(get_database_governance().create_backup)
|
||||
except DatabaseBackupInProgressError as error:
|
||||
raise HTTPException(status_code=409, detail=str(error)) from error
|
||||
except Exception as error:
|
||||
@@ -465,9 +450,7 @@ async def get_env_setting(
|
||||
"""
|
||||
查询系统环境变量,包括当前版本号(仅管理员)
|
||||
"""
|
||||
info = get_runtime_settings().snapshot(
|
||||
exclude={"SECRET_KEY", "RESOURCE_SECRET_KEY"}
|
||||
)
|
||||
info = get_runtime_settings().snapshot(exclude={"SECRET_KEY", "RESOURCE_SECRET_KEY"})
|
||||
info.update(
|
||||
{
|
||||
"VERSION": get_app_version(),
|
||||
@@ -568,9 +551,7 @@ async def get_progress(
|
||||
summary="查询公开系统设置",
|
||||
response_model=_SchemaResponse[_SchemaValueData],
|
||||
)
|
||||
async def get_public_setting(
|
||||
key: str, _: ApiPrincipal = Depends(get_current_active_user_async)
|
||||
) -> _SchemaResponse:
|
||||
async def get_public_setting(key: str, _: ApiPrincipal = Depends(get_current_active_user_async)) -> _SchemaResponse:
|
||||
"""
|
||||
查询普通用户可读取的非敏感系统设置
|
||||
"""
|
||||
@@ -598,9 +579,7 @@ async def sync_plugin_market_from_wiki(
|
||||
"""
|
||||
从 Wiki 插件文档同步插件市场仓库地址。
|
||||
"""
|
||||
result = await runtime.system.sync_plugin_market(
|
||||
request.wiki_url if request else None
|
||||
)
|
||||
result = await runtime.system.sync_plugin_market(request.wiki_url if request else None)
|
||||
return _SchemaResponse(
|
||||
success=result.success,
|
||||
message=result.message,
|
||||
@@ -613,9 +592,7 @@ async def sync_plugin_market_from_wiki(
|
||||
summary="查询系统设置",
|
||||
response_model=_SchemaResponse[_SchemaValueData],
|
||||
)
|
||||
async def get_setting(
|
||||
key: str, _: ApiPrincipal = Depends(get_current_active_superuser_async)
|
||||
) -> _SchemaResponse:
|
||||
async def get_setting(key: str, _: ApiPrincipal = Depends(get_current_active_superuser_async)) -> _SchemaResponse:
|
||||
"""
|
||||
查询系统设置(仅管理员)
|
||||
"""
|
||||
@@ -641,6 +618,103 @@ async def set_setting(
|
||||
return _SchemaResponse(success=result.success, message=result.message)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/settings",
|
||||
summary="统一查询系统设置",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def query_settings(
|
||||
setting_key: Optional[str] = None,
|
||||
group: Optional[str] = "all",
|
||||
keyword: Optional[str] = None,
|
||||
include_values: Optional[bool] = None,
|
||||
show_secrets: bool = False,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""按登记元数据查询设置,并默认对敏感值递归脱敏。"""
|
||||
try:
|
||||
data = SystemSettingsService(
|
||||
get_runtime_settings(),
|
||||
get_configured_system_config(),
|
||||
runtime.system.publish_config_changed,
|
||||
).query(
|
||||
setting_key=setting_key,
|
||||
group=group,
|
||||
keyword=keyword,
|
||||
include_values=include_values,
|
||||
show_secrets=show_secrets,
|
||||
)
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, data=data)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/settings",
|
||||
summary="统一更新系统设置",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def update_settings(
|
||||
payload: _SchemaSystemSettingsUpdateRequest,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""按替换、字典合并或列表项操作更新一个登记设置。"""
|
||||
try:
|
||||
data = await SystemSettingsService(
|
||||
get_runtime_settings(),
|
||||
get_configured_system_config(),
|
||||
runtime.system.publish_config_changed,
|
||||
).update(**payload.model_dump())
|
||||
except ValueError as error:
|
||||
return _SchemaResponse(success=False, message=str(error))
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/identifiers",
|
||||
summary="查询自定义识别词",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def query_custom_identifiers(
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
) -> _SchemaResponse:
|
||||
"""返回完整的自定义识别词列表。"""
|
||||
identifiers = get_configured_system_config().get(SystemConfigKey.CustomIdentifiers) or []
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data={"count": len(identifiers), "identifiers": identifiers},
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/identifiers",
|
||||
summary="更新自定义识别词",
|
||||
response_model=_SchemaResponse[_SchemaJsonObject],
|
||||
)
|
||||
async def update_custom_identifiers(
|
||||
payload: _SchemaCustomIdentifiersUpdateRequest,
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser_async),
|
||||
runtime: HostRuntime = Depends(get_host_runtime),
|
||||
) -> _SchemaResponse:
|
||||
"""完整替换自定义识别词并清理识别解析缓存。"""
|
||||
identifiers = [item for item in payload.identifiers if item is not None]
|
||||
data = await SystemSettingsService(
|
||||
get_runtime_settings(),
|
||||
get_configured_system_config(),
|
||||
runtime.system.publish_config_changed,
|
||||
).update(
|
||||
setting_key=SystemConfigKey.CustomIdentifiers.value,
|
||||
value=identifiers or None,
|
||||
)
|
||||
from app.domain.metainfo import clear_rust_parse_options_cache
|
||||
|
||||
clear_rust_parse_options_cache()
|
||||
data.update({"count": len(identifiers), "identifiers": identifiers})
|
||||
return _SchemaResponse(success=True, message=data.get("message"), data=data)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/message",
|
||||
summary="实时消息",
|
||||
@@ -695,13 +769,9 @@ async def _get_logging_impl(
|
||||
except LogNotFoundError as error:
|
||||
raise HTTPException(status_code=404, detail="Not Found") from error
|
||||
except Exception as error:
|
||||
return Response(
|
||||
content=f"读取日志文件失败: {error}", media_type="text/plain"
|
||||
)
|
||||
return Response(content=f"读取日志文件失败: {error}", media_type="text/plain")
|
||||
try:
|
||||
source = await runtime.system.follow_log(
|
||||
resolved_logfile, length or 50, request.is_disconnected
|
||||
)
|
||||
source = await runtime.system.follow_log(resolved_logfile, length or 50, request.is_disconnected)
|
||||
except LogNotFoundError as error:
|
||||
raise HTTPException(status_code=404, detail="Not Found") from error
|
||||
|
||||
@@ -724,7 +794,15 @@ async def _get_logging_impl(
|
||||
summary="实时日志",
|
||||
response_model=None,
|
||||
response_class=StreamingResponse,
|
||||
responses={200: {"description": "实时日志流或完整日志文本", "content": {"text/event-stream": {"schema": {"type": "string"}}, "text/plain": {"schema": {"type": "string"}}}}},
|
||||
responses={
|
||||
200: {
|
||||
"description": "实时日志流或完整日志文本",
|
||||
"content": {
|
||||
"text/event-stream": {"schema": {"type": "string"}},
|
||||
"text/plain": {"schema": {"type": "string"}},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
async def get_logging(
|
||||
request: Request,
|
||||
@@ -745,11 +823,7 @@ async def get_logging(
|
||||
responses={
|
||||
200: {
|
||||
"description": "日志 ZIP 文件",
|
||||
"content": {
|
||||
"application/zip": {
|
||||
"schema": {"type": "string", "format": "binary"}
|
||||
}
|
||||
},
|
||||
"content": {"application/zip": {"schema": {"type": "string", "format": "binary"}}},
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -935,9 +1009,7 @@ def modulelist(_: _SchemaTokenPayload = Depends(verify_token)):
|
||||
return _SchemaResponse(success=True, data={"modules": modules})
|
||||
|
||||
|
||||
@router.get(
|
||||
"/moduletest/{moduleid}", summary="模块可用性测试", response_model=_SchemaResponse[None]
|
||||
)
|
||||
@router.get("/moduletest/{moduleid}", summary="模块可用性测试", response_model=_SchemaResponse[None])
|
||||
def moduletest(moduleid: str, _: _SchemaTokenPayload = Depends(verify_token)):
|
||||
"""
|
||||
模块可用性测试接口
|
||||
@@ -1006,9 +1078,7 @@ def download_system_update(
|
||||
):
|
||||
"""启动后台下载并立即返回当前状态(仅管理员)。"""
|
||||
result = runtime.system.download_update()
|
||||
return _SchemaResponse(
|
||||
success=result.success, data=result.data, message=result.message
|
||||
)
|
||||
return _SchemaResponse(success=result.success, data=result.data, message=result.message)
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -1039,9 +1109,7 @@ def run_scheduler(jobid: str, _: ApiPrincipal = Depends(get_current_active_super
|
||||
return _SchemaResponse(success=True)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/runscheduler2", summary="运行服务(API_TOKEN)", response_model=_SchemaResponse[None]
|
||||
)
|
||||
@router.get("/runscheduler2", summary="运行服务(API_TOKEN)", response_model=_SchemaResponse[None])
|
||||
def run_scheduler2(jobid: str, _: Annotated[str, Depends(verify_apitoken)]):
|
||||
"""
|
||||
执行命令(API_TOKEN认证)
|
||||
|
||||
@@ -25,6 +25,7 @@ from app.api.endpoints import (
|
||||
openai,
|
||||
plugin,
|
||||
recommend,
|
||||
rule,
|
||||
search,
|
||||
site,
|
||||
storage,
|
||||
@@ -63,6 +64,7 @@ API_V1_ROUTER_SPECS: tuple[RouterSpec, ...] = (
|
||||
RouterSpec(douban.router, "/douban", ("douban",)),
|
||||
RouterSpec(tmdb.router, "/tmdb", ("tmdb",)),
|
||||
RouterSpec(history.router, "/history", ("history",)),
|
||||
RouterSpec(rule.router, "/rule", ("rule",)),
|
||||
RouterSpec(system.router, "/system", ("system",)),
|
||||
RouterSpec(notification.router, "/notification", ("notification",)),
|
||||
RouterSpec(llm.router, "/llm", ("llm",)),
|
||||
|
||||
Reference in New Issue
Block a user