844 行
29 KiB
Python
844 行
29 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 asyncio
|
|
import base64
|
|
import binascii
|
|
import inspect
|
|
import importlib
|
|
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.model_provider_bootstrap import (
|
|
sync_generation_provider_from_config,
|
|
sync_vision_provider_from_config,
|
|
)
|
|
from backend.services.model_provider_service import ModelProviderService
|
|
from backend.services.ui_service import API_BASE
|
|
from core.identity import RequestContext
|
|
from core.media_proxy import MediaProxy
|
|
from database import db_helper as _database_db_helper
|
|
from database.repositories.model_provider_repository import ModelProviderRepository
|
|
from database.seed import seed_default_material_categories
|
|
|
|
try:
|
|
if not hasattr(_database_db_helper, "set_runtime_config_overrides"):
|
|
_database_db_helper = importlib.reload(_database_db_helper)
|
|
except Exception:
|
|
pass
|
|
|
|
Database = _database_db_helper.Database
|
|
DatabaseSettings = _database_db_helper.DatabaseSettings
|
|
load_database_settings = _database_db_helper.load_database_settings
|
|
|
|
|
|
PLUGIN_NAME = "astrbot_plugin_imagestudio"
|
|
PLUGIN_DESC = "AstrBot ImageStudio role asset production and image-generation workspace."
|
|
PLUGIN_VERSION = "3.0.0"
|
|
BRIDGE_PERMISSIONS = frozenset(
|
|
{"can_write", "can_manage_config", "can_manage_materials", "can_retry_tasks"}
|
|
)
|
|
_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()
|
|
seed = seed_default_material_categories(database)
|
|
model_provider_service = ModelProviderService(ModelProviderRepository(database))
|
|
config_payload = _database_db_helper.load_config_payload()
|
|
generation_provider = sync_generation_provider_from_config(model_provider_service, config_payload)
|
|
vision_provider = sync_vision_provider_from_config(model_provider_service, config_payload)
|
|
return {
|
|
"initialized": True,
|
|
"backend": database.backend,
|
|
"seed": {"material_categories": seed},
|
|
"generation_provider": generation_provider,
|
|
"vision_provider": vision_provider,
|
|
}
|
|
|
|
|
|
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,
|
|
) -> Any:
|
|
ctx = _request_context_from_astrbot_request(request)
|
|
request_method = _request_method(request, fallback=method)
|
|
request_payload = payload if payload is not None else await _request_payload(request)
|
|
dispatch_method, dispatch_payload = _unwrap_method_override(request_method, request_payload)
|
|
dispatch_endpoint = _bridge_endpoint(endpoint, request)
|
|
dispatch_query = query if query is not None else _request_query(request)
|
|
if dispatch_method == "GET" and normalize_extension_path(dispatch_endpoint) == "media/fetch":
|
|
file_response = await _to_media_file_response(dispatch_query)
|
|
if file_response is not None:
|
|
return file_response
|
|
response = await asyncio.to_thread(
|
|
dispatch_web_request,
|
|
ctx,
|
|
dispatch_method,
|
|
dispatch_endpoint,
|
|
query=dispatch_query,
|
|
payload=dispatch_payload,
|
|
)
|
|
media_response = _to_media_http_response(dispatch_endpoint, response)
|
|
if media_response is not None:
|
|
return media_response
|
|
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]]:
|
|
path = f"/{PLUGIN_NAME}/<path:endpoint>"
|
|
return [
|
|
{"method": method, "path": path, "endpoint": ""}
|
|
for method in sorted({route.method for route in 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",
|
|
"generation_provider_id",
|
|
"generation_provider_base_url",
|
|
"generation_provider_image_endpoint",
|
|
"generation_provider_model",
|
|
"generation_provider_route",
|
|
"generation_provider_api_key_env_var",
|
|
"generation_provider_timeout_seconds",
|
|
"vision_provider_id",
|
|
"vision_provider_base_url",
|
|
"vision_provider_endpoint",
|
|
"vision_provider_model",
|
|
"vision_provider_route",
|
|
"vision_provider_api_key_env_var",
|
|
"vision_provider_timeout_seconds",
|
|
"vision_provider_enabled",
|
|
"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 _set_runtime_config_overrides(patch: Mapping[str, Any]) -> None:
|
|
setter = getattr(_database_db_helper, "set_runtime_config_overrides", None)
|
|
if callable(setter):
|
|
setter(patch)
|
|
|
|
|
|
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"))
|
|
vision = _mapping_from_any(mapping.get("vision"))
|
|
vision_provider_config = _mapping_from_any(vision.get("provider")) if vision else {}
|
|
|
|
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)
|
|
|
|
generation_provider_fields = {
|
|
"provider_id": "generation_provider_id",
|
|
"base_url": "generation_provider_base_url",
|
|
"image_endpoint": "generation_provider_image_endpoint",
|
|
"model_id": "generation_provider_model",
|
|
"route_name": "generation_provider_route",
|
|
"api_key_env_var": "generation_provider_api_key_env_var",
|
|
}
|
|
generation_provider: dict[str, Any] = {}
|
|
for target_key, source_key in generation_provider_fields.items():
|
|
value = _runtime_text(_runtime_value(mapping, source_key))
|
|
if value:
|
|
generation_provider[target_key] = value
|
|
timeout = _runtime_text(_runtime_value(mapping, "generation_provider_timeout_seconds"))
|
|
if timeout:
|
|
try:
|
|
generation_provider["timeout_seconds"] = int(timeout)
|
|
except ValueError:
|
|
generation_provider["timeout_seconds"] = timeout
|
|
if generation_provider:
|
|
_set_nested(patch, ("generation", "provider"), generation_provider)
|
|
|
|
vision_route = _runtime_text(
|
|
_runtime_value(
|
|
mapping,
|
|
"vision_provider_route",
|
|
fallback=vision_provider_config.get("route_name", vision.get("default_route", _MISSING)),
|
|
)
|
|
)
|
|
if vision_route:
|
|
_set_nested(patch, ("vision", "default_route"), vision_route)
|
|
|
|
vision_provider_fields = {
|
|
"provider_id": "vision_provider_id",
|
|
"base_url": "vision_provider_base_url",
|
|
"vision_endpoint": "vision_provider_endpoint",
|
|
"model_id": "vision_provider_model",
|
|
"route_name": "vision_provider_route",
|
|
"api_key_env_var": "vision_provider_api_key_env_var",
|
|
}
|
|
vision_provider: dict[str, Any] = {}
|
|
for target_key, source_key in vision_provider_fields.items():
|
|
value = _runtime_text(
|
|
_runtime_value(mapping, source_key, fallback=vision_provider_config.get(target_key, _MISSING))
|
|
)
|
|
if value:
|
|
vision_provider[target_key] = value
|
|
vision_timeout = _runtime_text(
|
|
_runtime_value(
|
|
mapping,
|
|
"vision_provider_timeout_seconds",
|
|
fallback=vision_provider_config.get("timeout_seconds", _MISSING),
|
|
)
|
|
)
|
|
if vision_timeout:
|
|
try:
|
|
vision_provider["timeout_seconds"] = int(vision_timeout)
|
|
except ValueError:
|
|
vision_provider["timeout_seconds"] = vision_timeout
|
|
vision_enabled = _runtime_value(
|
|
mapping,
|
|
"vision_provider_enabled",
|
|
fallback=vision_provider_config.get("enabled", _MISSING),
|
|
)
|
|
if vision_enabled is not _MISSING:
|
|
vision_provider["enabled"] = _runtime_bool(vision_enabled)
|
|
if vision_provider:
|
|
_set_nested(patch, ("vision", "provider"), vision_provider)
|
|
|
|
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) -> 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:
|
|
astrbot_web_request = None
|
|
if astrbot_web_request is not None:
|
|
try:
|
|
getattr(astrbot_web_request, "method")
|
|
return astrbot_web_request
|
|
except Exception:
|
|
pass
|
|
try:
|
|
from quart import request as quart_request
|
|
getattr(quart_request, "method")
|
|
return quart_request
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def _request_context_from_astrbot_request(request: Any | None) -> RequestContext:
|
|
username = _first_text(
|
|
_attr(request, "username"),
|
|
_current_quart_username(),
|
|
) or None
|
|
user_id = _first_text(
|
|
_attr(request, "user_id"),
|
|
username,
|
|
) or None
|
|
# AstrBot authenticates extension routes before invoking the plugin, but
|
|
# PluginRequest currently exposes only the authenticated username. Grant
|
|
# the capabilities that exist today explicitly instead of a wildcard so a
|
|
# future permission cannot become enabled accidentally.
|
|
permissions = BRIDGE_PERMISSIONS if username or user_id else frozenset()
|
|
return RequestContext.from_astrbot(
|
|
username=username,
|
|
user_id=user_id,
|
|
client_ip=_client_ip(request),
|
|
source="astrbot_plugin_page",
|
|
permissions=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"),
|
|
_attr(request, "query_params"),
|
|
_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)
|
|
payload = _mapping_from_any(loader)
|
|
if payload:
|
|
return payload
|
|
if not callable(loader):
|
|
continue
|
|
try:
|
|
try:
|
|
loaded = loader(default={}) if name == "json" else loader(silent=True)
|
|
except TypeError:
|
|
loaded = loader()
|
|
if inspect.isawaitable(loaded):
|
|
loaded = await loaded
|
|
payload = _mapping_from_any(loaded)
|
|
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 _unwrap_method_override(method: str, payload: dict[str, Any]) -> tuple[str, dict[str, Any]]:
|
|
normalized_method = str(method or "GET").upper()
|
|
if normalized_method != "POST":
|
|
return normalized_method, payload
|
|
override = str(payload.get("__imagestudio_method") or "").strip().upper()
|
|
if override not in {"PUT", "DELETE", "PATCH"}:
|
|
return normalized_method, payload
|
|
body = payload.get("__imagestudio_body", {})
|
|
return override, _mapping_from_any(body)
|
|
|
|
|
|
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 _to_media_http_response(endpoint: str, response: dict[str, Any]) -> Any | None:
|
|
if normalize_extension_path(endpoint) != "media/fetch" or not response.get("ok"):
|
|
return None
|
|
data = _mapping_from_any(response.get("data"))
|
|
encoded = str(data.get("body_base64") or "")
|
|
try:
|
|
body = base64.urlsafe_b64decode(encoded + ("=" * (-len(encoded) % 4)))
|
|
except (binascii.Error, ValueError):
|
|
return None
|
|
content_type = str(data.get("content_type") or "application/octet-stream")
|
|
cache_control = str(data.get("cache_control") or "private, max-age=300")
|
|
headers = {"Cache-Control": cache_control}
|
|
|
|
try:
|
|
from astrbot.api.web import request as _astrbot_request # noqa: F401
|
|
from starlette.responses import Response
|
|
|
|
return Response(content=body, media_type=content_type, headers=headers)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
from quart import Response
|
|
|
|
return Response(body, content_type=content_type, headers=headers)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
async def _to_media_file_response(query: dict[str, Any]) -> Any | None:
|
|
"""Use AstrBot/Quart native file responses to avoid base64 memory copies."""
|
|
|
|
token = str(query.get("token") or "").strip()
|
|
if not token:
|
|
return None
|
|
try:
|
|
path, metadata = MediaProxy().resolve_file(token)
|
|
except Exception:
|
|
return None
|
|
content_type = str(metadata.get("content_type") or "application/octet-stream")
|
|
headers = {"Cache-Control": "private, max-age=300"}
|
|
try:
|
|
from astrbot.api.web import file_response
|
|
|
|
return file_response(path, content_type=content_type, headers=headers)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
from quart import send_file
|
|
|
|
response = send_file(path, mimetype=content_type, conditional=True, max_age=300)
|
|
if inspect.isawaitable(response):
|
|
response = await response
|
|
response.headers["Cache-Control"] = headers["Cache-Control"]
|
|
return response
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
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
|
|
try:
|
|
return getattr(value, name, None)
|
|
except Exception:
|
|
return 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 _current_quart_username() -> str:
|
|
try:
|
|
from quart import g
|
|
|
|
return _first_text(getattr(g, "username", None))
|
|
except Exception:
|
|
return ""
|
|
|
|
|
|
def _client_ip(request: Any | None) -> str | None:
|
|
client_host = _attr(request, "client_host")
|
|
if client_host:
|
|
return str(client_host)
|
|
remote_addr = _attr(request, "remote_addr")
|
|
if remote_addr:
|
|
return str(remote_addr)
|
|
client = _attr(request, "client")
|
|
host = _attr(client, "host")
|
|
if host:
|
|
return str(host)
|
|
remote = _attr(request, "remote")
|
|
return str(remote) if remote else None
|