"""VFS storage helpers.""" from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Any from backend.dto.common import ApiError, ErrorCode from core.config_service import ConfigService, ImageStudioConfig from database.db_helper import REPO_ROOT @dataclass(frozen=True) class VfsEntry: root: str uri_prefix: str exists: bool writable: bool bytes: int def to_dict(self) -> dict[str, Any]: return { "root": self.root, "uri_prefix": self.uri_prefix, "exists": self.exists, "writable": self.writable, "bytes": self.bytes, } class VfsStorage: def __init__(self, config_service: ConfigService | None = None): self.config_service = config_service or ConfigService() def status(self) -> dict[str, Any]: roots = [self._entry(root, path) for root, path in self._root_paths().items()] return { "roots": [entry.to_dict() for entry in roots], "total_bytes": sum(entry.bytes for entry in roots), } def resolve_uri(self, uri: str) -> Path: root, relative = self.split_uri(uri) root_path = self._root_paths().get(root) if root_path is None: raise ApiError(ErrorCode.MEDIA_NOT_FOUND, "unknown storage root", {"uri": uri, "root": root}) resolved_root = _resolve_data_path(root_path).resolve() resolved_path = (resolved_root / relative).resolve() if resolved_path != resolved_root and resolved_root not in resolved_path.parents: raise ApiError(ErrorCode.FORBIDDEN, "storage uri escapes its root", {"uri": uri}) return resolved_path def ensure_file(self, uri: str) -> Path: path = self.resolve_uri(uri) if not path.exists() or not path.is_file(): raise ApiError(ErrorCode.MEDIA_NOT_FOUND, "media file not found", {"uri": uri}) return path def split_uri(self, uri: str) -> tuple[str, Path]: if not uri.startswith("storage://"): raise ApiError(ErrorCode.VALIDATION_FAILED, "uri must use storage://", {"field": "uri"}) rest = uri[len("storage://") :] if "/" not in rest: raise ApiError(ErrorCode.VALIDATION_FAILED, "storage uri must include a root and path", {"uri": uri}) root, relative = rest.split("/", 1) if not root or not relative: raise ApiError(ErrorCode.VALIDATION_FAILED, "storage uri must include a root and path", {"uri": uri}) relative_path = Path(relative) if relative_path.is_absolute() or ".." in relative_path.parts: raise ApiError(ErrorCode.FORBIDDEN, "storage uri contains an unsafe path", {"uri": uri}) return root, relative_path def _entry(self, root: str, path: str) -> VfsEntry: resolved = _resolve_data_path(path) return VfsEntry( root=root, uri_prefix=f"storage://{root}/", exists=resolved.exists(), writable=_is_writable(resolved), bytes=_directory_size(resolved), ) def _root_paths(self) -> dict[str, str]: config = self.config_service.load() return _storage_roots(config) def _storage_roots(config: ImageStudioConfig) -> dict[str, str]: return { "images": config.storage.images_path, "thumbnails": config.storage.thumbnails_path, "materials": config.storage.materials_path, "styles": config.storage.styles_path, "archives": config.storage.archives_path, "temp": config.storage.temp_path, } def _resolve_data_path(path: str) -> Path: resolved = Path(path) if not resolved.is_absolute(): resolved = REPO_ROOT / resolved return resolved def _directory_size(path: Path) -> int: if not path.exists(): return 0 total = 0 for child in path.rglob("*"): if child.is_file(): total += child.stat().st_size return total def _is_writable(path: Path) -> bool: target = path if path.exists() else path.parent return target.exists() and target.is_dir()