astrbot_plugin_imagestudio/main.py

445 行
14 KiB
Python

"""AstrBot ImageStudio plugin entrypoint helpers.
The plugin is mounted inside AstrBot. This module exposes pure metadata and
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, Callable
PLUGIN_ROOT = Path(__file__).resolve().parent
if str(PLUGIN_ROOT) not in sys.path:
# AstrBot may import the plugin entrypoint without adding the plugin root.
sys.path.insert(0, str(PLUGIN_ROOT))
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
from database.db_helper import Database, DatabaseSettings, load_database_settings
PLUGIN_NAME = "astrbot_plugin_imagestudio"
PLUGIN_DESC = "AstrBot ImageStudio role asset production and image-generation workspace."
PLUGIN_VERSION = "3.0.0"
try:
from astrbot.api.star import Star as AstrBotStar
from astrbot.api.star import register as astrbot_star_register
except Exception: # pragma: no cover - AstrBot is only present in runtime.
class AstrBotStar: # type: ignore[no-redef]
def __init__(self, context: Any | None = None, *args: Any, **kwargs: Any) -> None:
self.context = context
def astrbot_star_register(*args: Any, **kwargs: Any) -> Any:
def decorator(cls: type[Any]) -> type[Any]:
return cls
return decorator
def get_plugin_manifest() -> dict[str, Any]:
web_manifest = get_web_mount_manifest()
runtime = runtime_registration_manifest()
return {
"plugin_name": PLUGIN_NAME,
"api_base": API_BASE,
"contract_url": f"{API_BASE}/contract",
"web": web_manifest,
"routes": runtime_route_table(),
"runtime": runtime,
"health": runtime["health"],
}
def register_plugin(runtime: Any) -> dict[str, Any]:
result = register_astrbot_runtime(runtime, runtime_registration_manifest())
result["bridge_api"] = register_bridge_api(runtime)
return result
def get_runtime_health() -> dict[str, Any]:
return runtime_health()
def initialize_runtime_database(settings: DatabaseSettings | None = None) -> dict[str, Any]:
database = Database(settings or load_database_settings())
database.initialize()
return {"initialized": True, "backend": database.backend}
def dispatch_web_request(
ctx: RequestContext,
method: str,
path: str,
*,
query: dict[str, Any] | None = None,
payload: dict[str, Any] | None = None,
) -> dict[str, Any]:
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)
except Exception:
return cls
@_register_star_class
class Main(AstrBotStar):
"""Minimal AstrBot plugin class for runtime discovery."""
def __init__(self, context: Any | None = None, *args: Any, **kwargs: Any) -> None:
try:
super().__init__(context, *args, **kwargs)
except TypeError:
try:
super().__init__(*args, **kwargs)
except TypeError:
super().__init__()
self.context = context
self.registration_result: dict[str, Any] | None = None
self.database_result: dict[str, Any] | None = None
async def initialize(self) -> None:
if self.context is not None:
self.registration_result = register_plugin(self.context)
if self.registration_result.get("bridge_api", {}).get("registered"):
self.database_result = initialize_runtime_database()
return None
async def terminate(self) -> None:
return None
def get_plugin_manifest(self) -> dict[str, Any]:
return get_plugin_manifest()
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 = (
f"/{PLUGIN_NAME}/<path:endpoint>",
f"{PLUGIN_NAME}/<path:endpoint>",
)
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"/{PLUGIN_NAME}/{route.endpoint}", f"{PLUGIN_NAME}/{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]
desc = f"ImageStudio {method} {path}"
attempts = (
lambda: registrar(route=path, view_handler=handler, methods=methods, desc=desc),
lambda: registrar(route=path, view_handler=handler, methods=methods),
lambda: registrar(path=path, handler=handler, methods=methods),
lambda: registrar(path=path, handler=handler, methods=methods, desc=desc),
lambda: registrar(path=path, handler=handler, method=method),
lambda: registrar(endpoint=path, handler=handler, methods=methods),
lambda: registrar(path, handler, methods, desc),
lambda: registrar(path, handler, methods=methods),
lambda: registrar(path, handler, methods=methods, desc=desc),
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_request = actual_request or _current_astrbot_web_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 _current_astrbot_web_request() -> Any | None:
try:
from astrbot.api.web import request as astrbot_web_request
except Exception:
return None
try:
getattr(astrbot_web_request, "method")
except Exception:
return None
return astrbot_web_request
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