94 行
3.9 KiB
Python
94 行
3.9 KiB
Python
"""Safely persist chat-platform image references into ImageStudio storage."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import os
|
|
import tempfile
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit
|
|
|
|
from core.image_formats import detect_image_format
|
|
from core.remote_fetch import read_http_response_limited
|
|
from core.runtime_paths import get_runtime_data_root
|
|
from core.storage import VfsStorage
|
|
|
|
|
|
MAX_CHAT_IMAGE_BYTES = 20 * 1024 * 1024
|
|
|
|
# Extra directories that may hold platform-cached chat images (AstrBot writes
|
|
# OneBot/WeChat downloads outside the plugin's own data root).
|
|
LOCAL_IMAGE_ROOTS_ENV_VAR = "IMAGESTUDIO_CHAT_IMAGE_ROOTS"
|
|
|
|
|
|
def _allowed_local_roots() -> list[Path]:
|
|
"""Directories a chat message is permitted to reference by local path."""
|
|
|
|
roots = [get_runtime_data_root(), Path(tempfile.gettempdir())]
|
|
configured = str(os.environ.get(LOCAL_IMAGE_ROOTS_ENV_VAR, "")).strip()
|
|
if configured:
|
|
roots.extend(Path(part) for part in configured.split(os.pathsep) if part.strip())
|
|
resolved: list[Path] = []
|
|
for root in roots:
|
|
try:
|
|
resolved.append(root.expanduser().resolve())
|
|
except OSError:
|
|
continue
|
|
return resolved
|
|
|
|
|
|
def _read_local_image(text: str) -> tuple[bytes, str]:
|
|
"""Read a platform-cached image, refusing paths outside the allowed roots.
|
|
|
|
``image_references_from_event`` forwards the raw ``file``/``path``
|
|
attribute of an inbound message component. On OneBot that is a local cache
|
|
path, so the branch has to exist -- but the value ultimately originates
|
|
from the remote peer, and the previous ``Path(text).read_bytes()`` would
|
|
happily return ``config.yaml`` or an SSH key, store it as a "material",
|
|
and hand it back to the requester through the media endpoints.
|
|
"""
|
|
|
|
source = Path(text).expanduser().resolve()
|
|
allowed = _allowed_local_roots()
|
|
if not any(source == root or root in source.parents for root in allowed):
|
|
raise ValueError("聊天图片路径不在允许的目录内")
|
|
if not source.is_file():
|
|
raise ValueError("聊天图片路径不存在")
|
|
body = source.read_bytes()
|
|
# Even inside an allowed root, only accept real image bytes so a text file
|
|
# cannot be laundered into the material library.
|
|
if detect_image_format(body) is None:
|
|
raise ValueError("聊天图片格式无法识别")
|
|
return body, source.suffix.lstrip(".").lower() or "jpg"
|
|
|
|
|
|
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:
|
|
body, extension = _read_local_image(text)
|
|
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)
|