astrbot_plugin_imagestudio/backend/services/asset_import_service.py

136 行
4.5 KiB
Python

"""Dry-run planning 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"}
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]:
if not dry_run:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"asset pack import execution is not enabled; run with dry_run=true",
{"field": "dry_run"},
)
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)
return {
"dry_run": True,
"status": "planned",
"package_uri": package_uri,
"files": files,
"bytes": total_bytes,
"manifest_candidates": [item["uri"] for item in manifest_candidates],
"manifest": manifest_summary,
"import_enabled": False,
"execution_enabled": False,
}
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}] 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:
child_relative = relative / child.relative_to(package_path)
candidates.append({"uri": _storage_uri(root, child_relative), "path": child})
return sorted(candidates, key=lambda item: 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