diff --git a/main.py b/main.py index 87d6749..24eea67 100644 --- a/main.py +++ b/main.py @@ -6,9 +6,11 @@ dispatch helpers for the runtime layer without starting a standalone server. from __future__ import annotations +import inspect +import json import sys from pathlib import Path -from typing import Any +from typing import Any, Callable PLUGIN_ROOT = Path(__file__).resolve().parent @@ -18,12 +20,14 @@ if str(PLUGIN_ROOT) not in sys.path: from adapters.astrbot_adapter import ( dispatch_extension_request, + normalize_extension_path, register_astrbot_runtime, runtime_health, runtime_registration_manifest, runtime_route_table, ) from adapters.webui_adapter import get_web_mount_manifest +from backend.route_registry import ROUTES from backend.services.ui_service import API_BASE from core.identity import RequestContext @@ -62,7 +66,9 @@ def get_plugin_manifest() -> dict[str, Any]: def register_plugin(runtime: Any) -> dict[str, Any]: - return register_astrbot_runtime(runtime, runtime_registration_manifest()) + result = register_astrbot_runtime(runtime, runtime_registration_manifest()) + result["bridge_api"] = register_bridge_api(runtime) + return result def get_runtime_health() -> dict[str, Any]: @@ -80,6 +86,57 @@ def dispatch_web_request( return dispatch_extension_request(ctx, method, path, query=query, payload=payload) +def register_bridge_api(runtime: Any) -> dict[str, Any]: + """Register AstrBot Plugin Page bridge endpoints under /api/plug/{plugin}.""" + + registrar = getattr(runtime, "register_web_api", None) + if not callable(registrar): + return {"registered": False, "routes_registered": 0, "missing_capabilities": ["register_web_api"]} + + registered = 0 + errors: list[dict[str, Any]] = [] + for route in _bridge_registration_routes(): + handler = _make_bridge_handler(endpoint=route["endpoint"], method=route["method"]) + try: + if _call_web_api_registrar(registrar, route["path"], handler, route["method"]): + registered += 1 + except Exception as exc: # pragma: no cover - depends on AstrBot runtime version. + errors.append( + { + "method": route["method"], + "path": route["path"], + "message": str(exc), + "exception": exc.__class__.__name__, + } + ) + + return { + "registered": registered > 0, + "routes_registered": registered, + "missing_capabilities": [], + "errors": errors, + } + + +async def dispatch_bridge_request( + endpoint: str, + *, + method: str = "GET", + request: Any | None = None, + query: dict[str, Any] | None = None, + payload: dict[str, Any] | None = None, +) -> dict[str, Any]: + ctx = _request_context_from_astrbot_request(request) + response = dispatch_web_request( + ctx, + _request_method(request, fallback=method), + _bridge_endpoint(endpoint, request), + query=query if query is not None else _request_query(request), + payload=payload if payload is not None else await _request_payload(request), + ) + return _to_bridge_response(response) + + def _register_star_class(cls: type[Any]) -> type[Any]: try: return astrbot_star_register(PLUGIN_NAME, "YokiiroBW", PLUGIN_DESC, PLUGIN_VERSION)(cls) @@ -115,3 +172,247 @@ class Main(AstrBotStar): def register_plugin(self, runtime: Any) -> dict[str, Any]: return register_plugin(runtime) + + +def _bridge_registration_routes() -> list[dict[str, str]]: + routes: list[dict[str, str]] = [] + seen: set[tuple[str, str]] = set() + catch_all_paths = ( + "/{endpoint:path}", + "/{path:path}", + "{endpoint:path}", + "{path:path}", + ) + for method in sorted({route.method for route in ROUTES}): + for path in catch_all_paths: + seen.add((method, path)) + routes.append({"method": method, "path": path, "endpoint": ""}) + for route in ROUTES: + for path in (f"/{route.endpoint}", route.endpoint): + key = (route.method, path) + if key in seen: + continue + seen.add(key) + routes.append({"method": route.method, "path": path, "endpoint": route.endpoint}) + return routes + + +def _call_web_api_registrar(registrar: Callable[..., Any], path: str, handler: Callable[..., Any], method: str) -> bool: + methods = [method] + attempts = ( + lambda: registrar(path=path, handler=handler, methods=methods), + lambda: registrar(path=path, handler=handler, method=method), + lambda: registrar(endpoint=path, handler=handler, methods=methods), + lambda: registrar(path, handler, methods=methods), + lambda: registrar(path, handler, method=method), + lambda: registrar(path, methods, handler), + lambda: registrar(path, method, handler), + lambda: registrar(path, handler), + ) + last_error: TypeError | None = None + for attempt in attempts: + try: + attempt() + return True + except TypeError as exc: + last_error = exc + if last_error is not None: + raise last_error + return False + + +def _make_bridge_handler(endpoint: str, method: str) -> Callable[..., Any]: + async def handler(request: Any | None = None, **kwargs: Any) -> dict[str, Any]: + positional_endpoint = request if isinstance(request, str) else None + actual_request = None if positional_endpoint is not None else request or kwargs.get("request") + actual_endpoint = endpoint or _first_text( + positional_endpoint, + kwargs.get("endpoint"), + kwargs.get("path"), + kwargs.get("route_path"), + kwargs.get("wildcard"), + ) + actual_query = _mapping_from_any(kwargs.get("query") or kwargs.get("params")) + actual_payload = _mapping_from_any(kwargs.get("payload") or kwargs.get("body") or kwargs.get("data")) + return await dispatch_bridge_request( + actual_endpoint, + method=method, + request=actual_request, + query=actual_query or None, + payload=actual_payload or None, + ) + + return handler + + +def _request_context_from_astrbot_request(request: Any | None) -> RequestContext: + username = _first_text( + _nested_attr(request, "user", "username"), + _nested_attr(request, "state", "user", "username"), + _nested_attr(request, "session", "username"), + _header_value(request, "x-username"), + "astrbot", + ) + user_id = _first_text( + _nested_attr(request, "user", "id"), + _nested_attr(request, "state", "user", "id"), + _nested_attr(request, "session", "user_id"), + _header_value(request, "x-user-id"), + username, + ) + return RequestContext.from_astrbot( + username=username, + user_id=user_id, + client_ip=_client_ip(request), + source="astrbot_plugin_page", + permissions={"*"}, + ) + + +def _request_method(request: Any | None, *, fallback: str) -> str: + return (_first_text(_attr(request, "method"), fallback) or "GET").upper() + + +def _bridge_endpoint(endpoint: str | None, request: Any | None) -> str: + candidate = _first_text( + endpoint, + _mapping_value(_attr(request, "path_params"), "endpoint", "path", "route_path", "wildcard"), + _mapping_value(_attr(request, "match_info"), "endpoint", "path", "route_path", "wildcard"), + _attr(request, "path"), + _nested_attr(request, "url", "path"), + _attr(request, "rel_url"), + ) + normalized = str(candidate or "").split("?", 1)[0].replace("\\", "/").strip("/") + prefixes = ( + f"api/plug/{PLUGIN_NAME}/", + f"api/v1/plugins/extensions/{PLUGIN_NAME}/", + f"{API_BASE.strip('/')}/", + ) + for prefix in prefixes: + if normalized.startswith(prefix): + normalized = normalized[len(prefix) :] + break + return normalize_extension_path(normalized) + + +def _request_query(request: Any | None) -> dict[str, Any]: + for candidate in ( + _attr(request, "query_params"), + _attr(request, "query"), + _attr(request, "args"), + _attr(request, "GET"), + ): + query = _mapping_from_any(candidate) + if query: + return query + return {} + + +async def _request_payload(request: Any | None) -> dict[str, Any]: + if request is None or _request_method(request, fallback="GET") == "GET": + return {} + for name in ("json", "get_json"): + loader = getattr(request, name, None) + if not callable(loader): + continue + try: + loaded = loader() + if inspect.isawaitable(loaded): + loaded = await loaded + payload = _mapping_from_any(loaded) + if payload: + return payload + except Exception: + continue + body = getattr(request, "body", None) + if callable(body): + body = body() + if inspect.isawaitable(body): + body = await body + if isinstance(body, bytes): + body = body.decode("utf-8") + if isinstance(body, str) and body.strip(): + try: + return _mapping_from_any(json.loads(body)) + except json.JSONDecodeError: + return {} + return {} + + +def _to_bridge_response(response: dict[str, Any]) -> dict[str, Any]: + if response.get("ok"): + return { + "status": "ok", + "message": "", + "data": response.get("data"), + "request_id": response.get("request_id"), + } + return { + "status": "error", + "message": str(response.get("message") or "request failed"), + "data": response, + "request_id": response.get("request_id"), + } + + +def _mapping_from_any(value: Any) -> dict[str, Any]: + if value is None: + return {} + if isinstance(value, dict): + return dict(value) + if hasattr(value, "items"): + return {str(key): item for key, item in value.items()} + return {} + + +def _mapping_value(value: Any, *keys: str) -> Any: + mapping = _mapping_from_any(value) + for key in keys: + if key in mapping: + return mapping[key] + return None + + +def _attr(value: Any, name: str) -> Any: + if value is None: + return None + return getattr(value, name, None) + + +def _nested_attr(value: Any, *names: str) -> Any: + current = value + for name in names: + current = _attr(current, name) + if current is None: + return None + return current + + +def _first_text(*values: Any) -> str: + for value in values: + if value is None: + continue + text = str(value).strip() + if text: + return text + return "" + + +def _header_value(request: Any | None, key: str) -> str: + headers = _mapping_from_any(_attr(request, "headers")) + for header_key, value in headers.items(): + if header_key.lower() == key.lower(): + return str(value) + return "" + + +def _client_ip(request: Any | None) -> str | None: + forwarded = _header_value(request, "x-forwarded-for") + if forwarded: + return forwarded.split(",", 1)[0].strip() + client = _attr(request, "client") + host = _attr(client, "host") + if host: + return str(host) + remote = _attr(request, "remote") + return str(remote) if remote else None diff --git a/tests/test_plugin_entrypoint.py b/tests/test_plugin_entrypoint.py index 83fe342..5fdf718 100644 --- a/tests/test_plugin_entrypoint.py +++ b/tests/test_plugin_entrypoint.py @@ -6,7 +6,16 @@ from pathlib import Path from backend.route_registry import ROUTES from core.identity import RequestContext -from main import Main, PLUGIN_NAME, dispatch_web_request, get_plugin_manifest, get_runtime_health, register_plugin +from main import ( + Main, + PLUGIN_NAME, + dispatch_bridge_request, + dispatch_web_request, + get_plugin_manifest, + get_runtime_health, + register_bridge_api, + register_plugin, +) class PluginEntrypointTests(unittest.TestCase): @@ -51,8 +60,46 @@ class PluginEntrypointTests(unittest.TestCase): self.assertTrue(result["registered"]) self.assertEqual(len(runtime.routes), len(ROUTES)) self.assertEqual(len(runtime.mounts), 1) + self.assertFalse(result["bridge_api"]["registered"]) self.assertTrue(get_runtime_health()["ok"]) + def test_register_bridge_api_registers_astrbot_web_routes(self): + class FakeRuntime: + def __init__(self): + self.web_apis = [] + + def register_web_api(self, path, handler, methods=None): + self.web_apis.append({"path": path, "handler": handler, "methods": methods or []}) + + runtime = FakeRuntime() + result = register_bridge_api(runtime) + + self.assertTrue(result["registered"]) + self.assertGreater(len(runtime.web_apis), len(ROUTES)) + self.assertTrue(any(api["path"] == "/ui/bootstrap" for api in runtime.web_apis)) + + bootstrap_api = next( + api for api in runtime.web_apis if api["path"] == "/ui/bootstrap" and api["methods"] == ["GET"] + ) + response = asyncio.run(bootstrap_api["handler"]()) + + self.assertEqual(response["status"], "ok") + self.assertEqual(response["data"]["plugin_name"], PLUGIN_NAME) + + def test_dispatch_bridge_request_accepts_astrbot_plugin_path(self): + class FakeUrl: + path = "/api/plug/astrbot_plugin_imagestudio/ui/bootstrap" + + class FakeRequest: + method = "GET" + url = FakeUrl() + query_params = {} + + response = asyncio.run(dispatch_bridge_request("", request=FakeRequest())) + + self.assertEqual(response["status"], "ok") + self.assertEqual(response["data"]["plugin_name"], PLUGIN_NAME) + def test_astrbot_main_class_exposes_manifest(self): plugin = Main(context=object()) @@ -81,6 +128,7 @@ class PluginEntrypointTests(unittest.TestCase): self.assertTrue(plugin.registration_result["registered"]) self.assertEqual(len(runtime.routes), len(ROUTES)) self.assertEqual(len(runtime.mounts), 1) + self.assertFalse(plugin.registration_result["bridge_api"]["registered"]) def test_plugin_page_uses_relative_assets(self): page = Path(__file__).resolve().parents[1] / "pages" / "imagestudio" / "index.html"