"""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, Mapping 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, set_runtime_config_overrides PLUGIN_NAME = "astrbot_plugin_imagestudio" PLUGIN_DESC = "AstrBot ImageStudio role asset production and image-generation workspace." PLUGIN_VERSION = "3.0.0" _MISSING = object() 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 apply_astrbot_config_overrides(config: Any | None) -> dict[str, Any]: mapping = _mapping_from_runtime_config(config) patch = _runtime_config_patch_from_mapping(mapping) set_runtime_config_overrides(patch) return {"applied": bool(patch), "keys": _flatten_config_keys(patch)} 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: runtime_config = _runtime_config_argument(args, kwargs) try: super().__init__(context, *args, **kwargs) except TypeError: try: super().__init__(*args, **kwargs) except TypeError: super().__init__() self.context = context self.astrbot_config = runtime_config if runtime_config is not None else _attr(self, "config") self.registration_result: dict[str, Any] | None = None self.database_result: dict[str, Any] | None = None self.runtime_config_result: dict[str, Any] | None = None async def initialize(self) -> None: self.runtime_config_result = apply_astrbot_config_overrides(self.astrbot_config) 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}/", f"{PLUGIN_NAME}/", ) 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 _mapping_from_runtime_config(config: Any | None) -> dict[str, Any]: if config is None: return {} mapping = _mapping_from_any(config) if mapping: return mapping for method_name in ("to_dict", "dict", "model_dump"): method = getattr(config, method_name, None) if not callable(method): continue try: mapping = _mapping_from_any(method()) except Exception: mapping = {} if mapping: return mapping for attr_name in ("config", "data", "_config", "_data"): mapping = _mapping_from_any(_attr(config, attr_name)) if mapping: return mapping known_keys = ( "default_generation_model", "enable_private_companion_integration", "database_backend", "sqlite_path", "postgresql_enabled", "postgresql_dsn", "postgresql_host", "postgresql_port", "postgresql_database", "postgresql_user", "postgresql_password", ) getter = getattr(config, "get", None) if not callable(getter): return {} values: dict[str, Any] = {} for key in known_keys: try: value = getter(key, _MISSING) except TypeError: try: value = getter(key) except Exception: value = _MISSING except Exception: value = _MISSING if value is not _MISSING: values[key] = value return values def _runtime_config_argument(args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> Any | None: if "config" in kwargs and kwargs["config"] is not None: return kwargs["config"] if "plugin_config" in kwargs and kwargs["plugin_config"] is not None: return kwargs["plugin_config"] return args[0] if args else None def _runtime_config_patch_from_mapping(mapping: Mapping[str, Any]) -> dict[str, Any]: patch: dict[str, Any] = {} if not mapping: return patch database = _mapping_from_any(mapping.get("database")) sqlite = _mapping_from_any(database.get("sqlite")) if database else {} postgresql = _mapping_from_any(database.get("postgresql")) if database else {} features = _mapping_from_any(mapping.get("features")) plugin = _mapping_from_any(mapping.get("plugin")) display_name = _runtime_text(_runtime_value(mapping, "display_name", fallback=plugin.get("display_name", _MISSING))) if display_name: _set_nested(patch, ("plugin", "display_name"), display_name) default_model = _runtime_text(_runtime_value(mapping, "default_generation_model")) if default_model: _set_nested(patch, ("generation", "default_model"), default_model) private_companion = _runtime_value( mapping, "enable_private_companion_integration", fallback=features.get("private_companion_integration", _MISSING), ) if private_companion is not _MISSING: _set_nested(patch, ("features", "private_companion_integration"), _runtime_bool(private_companion)) backend = _runtime_text(_runtime_value(mapping, "database_backend", fallback=database.get("backend", _MISSING))).lower() if backend: _set_nested(patch, ("database", "backend"), backend) sqlite_path = _runtime_text(_runtime_value(mapping, "sqlite_path", fallback=sqlite.get("path", _MISSING))) if sqlite_path: _set_nested(patch, ("database", "sqlite", "path"), sqlite_path) pg_patch: dict[str, Any] = {} pg_enabled = _runtime_value(mapping, "postgresql_enabled", fallback=postgresql.get("enabled", _MISSING)) if pg_enabled is not _MISSING and (_runtime_bool(pg_enabled) or backend == "sqlite"): pg_patch["enabled"] = _runtime_bool(pg_enabled) elif backend in {"postgresql", "postgres", "pg"}: pg_patch["enabled"] = True pg_text_fields = { "dsn": ("postgresql_dsn", "dsn"), "host": ("postgresql_host", "host"), "database": ("postgresql_database", "database"), "user": ("postgresql_user", "user"), "password": ("postgresql_password", "password"), } for target_key, (flat_key, nested_key) in pg_text_fields.items(): value = _runtime_text(_runtime_value(mapping, flat_key, fallback=postgresql.get(nested_key, _MISSING))) if value: pg_patch[target_key] = value pg_port = _runtime_text(_runtime_value(mapping, "postgresql_port", fallback=postgresql.get("port", _MISSING))) if pg_port: try: pg_patch["port"] = int(pg_port) except ValueError: pg_patch["port"] = pg_port has_connection_fields = any(key in pg_patch for key in ("dsn", "host", "database", "user", "password")) if has_connection_fields and backend != "sqlite" and "enabled" not in pg_patch: pg_patch["enabled"] = True if pg_patch: _set_nested(patch, ("database", "postgresql"), pg_patch) return patch def _runtime_value(mapping: Mapping[str, Any], key: str, *, fallback: Any = _MISSING) -> Any: if key in mapping: return mapping[key] return fallback def _runtime_text(value: Any) -> str: if value is _MISSING or value is None: return "" return str(value).strip() def _runtime_bool(value: Any) -> bool: if isinstance(value, bool): return value if isinstance(value, str): return value.strip().lower() in {"1", "true", "yes", "on", "enabled", "启用", "是"} return bool(value) def _set_nested(target: dict[str, Any], path: tuple[str, ...], value: Any) -> None: current = target for key in path[:-1]: child = current.get(key) if not isinstance(child, dict): child = {} current[key] = child current = child current[path[-1]] = value def _flatten_config_keys(value: Mapping[str, Any], prefix: str = "") -> list[str]: keys: list[str] = [] for key, child in value.items(): path = f"{prefix}.{key}" if prefix else str(key) if isinstance(child, Mapping): keys.extend(_flatten_config_keys(child, path)) else: keys.append(path) return sorted(keys) 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