astrbot_plugin_imagestudio/backend/services/web_hosting_service.py

66 行
2.5 KiB
Python

"""Web UI mount metadata and static asset resolution."""
from __future__ import annotations
import mimetypes
from pathlib import Path
from typing import Any
from backend.dto.common import ApiError, ErrorCode
from database.db_helper import REPO_ROOT
PLUGIN_PAGE_DIR = REPO_ROOT / "pages" / "imagestudio"
STANDALONE_WEB_DIR = REPO_ROOT / "web"
PLUGIN_PAGE_URL = "/plugin/imagestudio"
STANDALONE_WEB_URL = "/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web"
class WebHostingService:
def __init__(
self,
plugin_page_dir: Path = PLUGIN_PAGE_DIR,
standalone_web_dir: Path = STANDALONE_WEB_DIR,
):
self.plugin_page_dir = plugin_page_dir
self.standalone_web_dir = standalone_web_dir
def manifest(self) -> dict[str, Any]:
return {
"plugin_page": {
"url": PLUGIN_PAGE_URL,
"built": (self.plugin_page_dir / "index.html").exists(),
},
"standalone_web": {
"url": STANDALONE_WEB_URL,
"assets_url": f"{STANDALONE_WEB_URL}/assets",
"built": (self.standalone_web_dir / "index.html").exists(),
},
}
def resolve_standalone_asset(self, relative_path: str = "index.html") -> dict[str, Any]:
asset_path = self._resolve(self.standalone_web_dir, relative_path or "index.html")
return _asset_metadata(asset_path)
def resolve_plugin_page_asset(self, relative_path: str = "index.html") -> dict[str, Any]:
asset_path = self._resolve(self.plugin_page_dir, relative_path or "index.html")
return _asset_metadata(asset_path)
def _resolve(self, root: Path, relative_path: str) -> Path:
root = root.resolve()
candidate = (root / relative_path).resolve()
if candidate != root and root not in candidate.parents:
raise ApiError(ErrorCode.FORBIDDEN, "web asset escapes its root", {"asset": relative_path})
if candidate.is_dir():
candidate = candidate / "index.html"
if not candidate.exists() or not candidate.is_file():
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "web asset not built", {"asset": relative_path})
return candidate
def _asset_metadata(path: Path) -> dict[str, Any]:
return {
"content_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
"size_bytes": path.stat().st_size,
"etag": f"{path.stat().st_mtime_ns:x}-{path.stat().st_size:x}",
}