astrbot_plugin_route_gateway/page_api.py

154 行
6 KiB
Python

"""Dashboard-facing API for the route management page.
Everything here is a thin pass-through to the route controller over its Unix socket; the plugin
holds no key material of its own. A secret value only ever travels inbound — `secrets` returns
reference names and usage counts, and nothing in this module can read a stored value back.
"""
from __future__ import annotations
from typing import Any
from astrbot.api import logger
from .gateway_client import GatewayError
def _ok(data: Any = None, message: str = "") -> dict[str, Any]:
return {"status": "ok", "message": message, "data": data if data is not None else {}}
def _err(message: str) -> dict[str, Any]:
return {"status": "error", "message": message, "data": {}}
class RouteGatewayPageApi:
PREFIX = "/route-gateway"
def __init__(self, plugin: Any) -> None:
self.plugin = plugin
def register_routes(self) -> None:
register = self.plugin.context.register_web_api
routes = [
("/routes", self.routes, ["GET"], "Route gateway: list routes"),
("/status", self.status, ["GET"], "Route gateway: active route status"),
("/secrets", self.secrets, ["GET"], "Route gateway: list secret references"),
("/secrets/import", self.secret_import, ["POST"], "Route gateway: import a secret"),
("/secrets/delete", self.secret_delete, ["POST"], "Route gateway: delete a secret"),
("/routes/create", self.route_create, ["POST"], "Route gateway: create a route"),
("/routes/use", self.route_use, ["POST"], "Route gateway: switch active route"),
("/routes/test", self.route_test, ["POST"], "Route gateway: test a route"),
("/routes/delete", self.route_delete, ["POST"], "Route gateway: soft-delete a route"),
]
for path, handler, methods, desc in routes:
register(self.PREFIX + path, handler, methods, desc)
# ──── helpers ────
@staticmethod
async def _body() -> dict[str, Any]:
from quart import request # noqa: PLC0415 (provided by the dashboard's compat layer)
try:
value = await request.get_json(force=True, silent=True)
except Exception:
value = None
return value if isinstance(value, dict) else {}
def _actor(self) -> str:
try:
from quart import g # noqa: PLC0415
return str(getattr(g, "username", "") or "dashboard")[:128]
except Exception:
return "dashboard"
async def _call(self, coro_factory) -> dict[str, Any]:
try:
response = await coro_factory()
except GatewayError as exc:
return _err(str(exc) or "路由控制器请求失败")
except Exception as exc: # noqa: BLE001 - surface a safe message, log the detail
logger.warning("Route gateway page API 失败:%s", type(exc).__name__, exc_info=True)
return _err("处理失败,请查看 AstrBot 日志")
return _ok(response.data, response.message)
# ──── read ────
async def routes(self):
return await self._call(self.plugin.gateway.list_routes)
async def status(self):
return await self._call(self.plugin.gateway.status)
async def secrets(self):
return await self._call(self.plugin.gateway.list_secrets)
# ──── write ────
async def secret_import(self):
body = await self._body()
secret_ref = str(body.get("secret_ref") or "").strip().lower()
value = str(body.get("value") or "")
if not secret_ref or not value.strip():
return _err("secret_ref 与密钥值都不能为空")
return await self._call(
lambda: self.plugin.gateway.import_secret(secret_ref, value, actor=self._actor())
)
async def secret_delete(self):
body = await self._body()
secret_ref = str(body.get("secret_ref") or "").strip().lower()
if not secret_ref:
return _err("secret_ref 不能为空")
return await self._call(
lambda: self.plugin.gateway.delete_secret(secret_ref, actor=self._actor())
)
async def route_create(self):
body = await self._body()
required = ("route_id", "secret_ref", "base_url", "model")
missing = [k for k in required if not str(body.get(k) or "").strip()]
if missing:
return _err("缺少字段:" + "、".join(missing))
route_id = str(body["route_id"]).strip()
return await self._call(
lambda: self.plugin.gateway.create_route(
route_id=route_id,
# display_name is required downstream; fall back to the id rather than sending None.
display_name=str(body.get("display_name") or "").strip() or route_id,
secret_ref=str(body["secret_ref"]).strip().lower(),
base_url=str(body["base_url"]).strip(),
model=str(body["model"]).strip(),
actor=self._actor(),
)
)
async def route_use(self):
body = await self._body()
route_id = str(body.get("route_id") or "").strip()
if not route_id:
return _err("route_id 不能为空")
return await self._call(
lambda: self.plugin.gateway.use_route(route_id, actor=self._actor(), force=False)
)
async def route_test(self):
body = await self._body()
route_id = str(body.get("route_id") or "").strip()
if not route_id:
return _err("route_id 不能为空")
return await self._call(
lambda: self.plugin.gateway.test_route(route_id, actor=self._actor())
)
async def route_delete(self):
body = await self._body()
route_id = str(body.get("route_id") or "").strip()
if not route_id:
return _err("route_id 不能为空")
return await self._call(
lambda: self.plugin.gateway.delete_route(
route_id=route_id, actor=self._actor(), confirm=True, force=False
)
)