astrbot_plugin_imagestudio/backend/services/asset_import_service.py

159 行
5.3 KiB
Python

"""Planning and guarded execution skeleton for ImageStudio asset pack imports."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from backend.dto.common import ApiError, ErrorCode
from core.config_service import ConfigService
from core.storage import VfsStorage
_MANIFEST_FILENAMES = {"manifest.json", "imagestudio-pack.json", "pack.json"}
_MANIFEST_FILENAME_PRIORITY = {
"imagestudio-pack.json": 0,
"manifest.json": 1,
"pack.json": 2,
}
class AssetImportService:
def __init__(self, config_service: ConfigService | None = None):
self.storage = VfsStorage(config_service)
def plan_import_pack(self, package_uri: str, *, dry_run: bool = True) -> dict[str, Any]:
root, relative = self.storage.split_uri(package_uri)
package_path = self.storage.resolve_uri(package_uri)
if not package_path.exists():
raise ApiError(ErrorCode.MEDIA_NOT_FOUND, "asset pack not found", {"uri": package_uri})
files, total_bytes = _path_file_stats(package_path)
manifest_candidates = _manifest_candidates(root, relative, package_path)
manifest_summary = _manifest_summary(package_path, manifest_candidates)
if not dry_run and not manifest_summary["valid"]:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"asset pack manifest is invalid",
{"field": "manifest", "errors": manifest_summary["errors"]},
)
return {
"dry_run": dry_run,
"status": "planned" if dry_run else "applied",
"package_uri": package_uri,
"files": files,
"bytes": total_bytes,
"manifest_candidates": [item["uri"] for item in manifest_candidates],
"manifest": manifest_summary,
"import_enabled": manifest_summary["valid"],
"execution_enabled": True,
"applied": {
"materials": 0 if dry_run else manifest_summary["materials"],
"styles": 0 if dry_run else manifest_summary["styles"],
},
}
def _manifest_candidates(root: str, relative: Path, package_path: Path) -> list[dict[str, Any]]:
if package_path.is_file():
return (
[{"uri": _storage_uri(root, relative), "path": package_path, "relative": Path(package_path.name)}]
if package_path.name in _MANIFEST_FILENAMES
else []
)
candidates: list[dict[str, Any]] = []
for child in package_path.rglob("*"):
if child.is_file() and child.name in _MANIFEST_FILENAMES:
pack_relative = child.relative_to(package_path)
child_relative = relative / pack_relative
candidates.append({"uri": _storage_uri(root, child_relative), "path": child, "relative": pack_relative})
return sorted(candidates, key=_manifest_sort_key)
def _manifest_sort_key(item: dict[str, Any]) -> tuple[int, int, str]:
relative = item["relative"]
filename = relative.name
return (
len(relative.parts),
_MANIFEST_FILENAME_PRIORITY.get(filename, 99),
item["uri"],
)
def _manifest_summary(package_path: Path, candidates: list[dict[str, Any]]) -> dict[str, Any]:
if not candidates:
return {
"present": False,
"valid": False,
"uri": None,
"name": None,
"version": None,
"materials": 0,
"styles": 0,
"errors": [{"code": "MANIFEST_MISSING", "message": "asset pack manifest was not found"}],
}
selected = candidates[0]
try:
payload = json.loads(selected["path"].read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
return {
"present": True,
"valid": False,
"uri": selected["uri"],
"name": None,
"version": None,
"materials": 0,
"styles": 0,
"errors": [{"code": "MANIFEST_INVALID_JSON", "message": exc.msg, "line": exc.lineno}],
}
if not isinstance(payload, dict):
return {
"present": True,
"valid": False,
"uri": selected["uri"],
"name": None,
"version": None,
"materials": 0,
"styles": 0,
"errors": [{"code": "MANIFEST_NOT_OBJECT", "message": "asset pack manifest must be a JSON object"}],
}
return {
"present": True,
"valid": True,
"uri": selected["uri"],
"name": _optional_text(payload.get("name")),
"version": _optional_text(payload.get("version")),
"materials": _list_count(payload.get("materials")),
"styles": _list_count(payload.get("styles")),
"errors": [],
}
def _storage_uri(root: str, relative: Path) -> str:
return f"storage://{root}/{relative.as_posix()}"
def _optional_text(value: Any) -> str | None:
text = str(value or "").strip()
return text or None
def _list_count(value: Any) -> int:
return len(value) if isinstance(value, list) else 0
def _path_file_stats(path: Path) -> tuple[int, int]:
if path.is_file():
return 1, path.stat().st_size
files = 0
total = 0
for child in path.rglob("*"):
if child.is_file():
files += 1
total += child.stat().st_size
return files, total