"""Safely persist chat-platform image references into ImageStudio storage.""" from __future__ import annotations import base64 import hashlib from pathlib import Path from urllib.parse import urlsplit from core.remote_fetch import read_http_response_limited from core.storage import VfsStorage MAX_CHAT_IMAGE_BYTES = 20 * 1024 * 1024 class ChatMediaImportService: def __init__(self, storage: VfsStorage | None = None): self.storage = storage or VfsStorage() def import_image(self, reference: str) -> tuple[str, str, int]: text = str(reference or "").strip() if text.startswith("storage://"): path = self.storage.ensure_file(text) return text, path.name, path.stat().st_size if text.startswith("data:image/"): header, encoded = text.split(",", 1) body = base64.b64decode(encoded, validate=True) extension = header.split("/", 1)[1].split(";", 1)[0].replace("jpeg", "jpg") elif text.startswith(("http://", "https://")): body = read_http_response_limited(text, timeout_seconds=30, max_bytes=MAX_CHAT_IMAGE_BYTES) extension = Path(urlsplit(text).path).suffix.lstrip(".").lower() or "jpg" else: source = Path(text).expanduser().resolve() body = source.read_bytes() extension = source.suffix.lstrip(".").lower() or "jpg" if not body or len(body) > MAX_CHAT_IMAGE_BYTES: raise ValueError("聊天图片为空或超过 20MB") if extension not in {"png", "jpg", "jpeg", "webp", "gif"}: extension = "jpg" digest = hashlib.sha256(body).hexdigest() uri = f"storage://materials/chat/{digest[:2]}/{digest}.{extension}" target = self.storage.resolve_uri(uri) target.parent.mkdir(parents=True, exist_ok=True) if not target.exists(): target.write_bytes(body) return uri, target.name, len(body)