87 lines
2.6 KiB
Python
87 lines
2.6 KiB
Python
"""Local image storage and the controlled GoView asset URL."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
from fastapi import APIRouter, UploadFile
|
|
from fastapi.responses import FileResponse
|
|
|
|
from deerflow.config.runtime_paths import runtime_home
|
|
|
|
router = APIRouter(prefix="/api/goview", tags=["goview-assets"])
|
|
|
|
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
|
_NAME_RE = re.compile(r"^[a-f0-9]{32}\.(png|jpg|gif|webp)$")
|
|
_TYPES = {"png": "image/png", "jpg": "image/jpeg", "gif": "image/gif", "webp": "image/webp"}
|
|
|
|
|
|
class AssetRejected(ValueError):
|
|
"""The upload is not a bounded local image."""
|
|
|
|
|
|
def asset_root() -> Path:
|
|
root = runtime_home() / "goview-assets"
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
return root
|
|
|
|
|
|
def sniff_image(data: bytes) -> str | None:
|
|
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
return "png"
|
|
if data.startswith(b"\xff\xd8\xff"):
|
|
return "jpg"
|
|
if data.startswith((b"GIF87a", b"GIF89a")):
|
|
return "gif"
|
|
if len(data) >= 12 and data.startswith(b"RIFF") and data[8:12] == b"WEBP":
|
|
return "webp"
|
|
return None
|
|
|
|
|
|
def save_image_bytes(data: bytes) -> tuple[str, str]:
|
|
if len(data) > MAX_IMAGE_BYTES:
|
|
raise AssetRejected("图片超过大小限制")
|
|
kind = sniff_image(data)
|
|
if kind is None:
|
|
raise AssetRejected("只接受 PNG、JPEG、GIF 或 WEBP 图片")
|
|
name = f"{uuid.uuid4().hex}.{kind}"
|
|
if not _NAME_RE.fullmatch(name):
|
|
raise AssetRejected("文件名无效")
|
|
root = asset_root().resolve()
|
|
path = (root / name).resolve()
|
|
if not path.is_relative_to(root):
|
|
raise AssetRejected("文件名无效")
|
|
path.write_bytes(data)
|
|
return name, f"/api/goview/assets/{name}"
|
|
|
|
|
|
def resolve_asset(name: str) -> Path:
|
|
if not _NAME_RE.fullmatch(name):
|
|
raise AssetRejected("文件名无效")
|
|
root = asset_root().resolve()
|
|
path = (root / name).resolve()
|
|
if not path.is_relative_to(root) or not path.is_file():
|
|
raise AssetRejected("文件不存在")
|
|
return path
|
|
|
|
|
|
async def read_upload(upload: UploadFile) -> bytes:
|
|
filename = upload.filename or ""
|
|
if "/" in filename or "\\" in filename or ".." in filename:
|
|
raise AssetRejected("文件名无效")
|
|
return await upload.read(MAX_IMAGE_BYTES + 1)
|
|
|
|
|
|
@router.get("/assets/{name}")
|
|
async def read_goview_asset(name: str):
|
|
try:
|
|
path = resolve_asset(name)
|
|
except AssetRejected:
|
|
from app.gateway.goview_http import fail
|
|
|
|
return fail(404, "图片不存在")
|
|
media = _TYPES.get(path.suffix.lstrip("."), "application/octet-stream")
|
|
return FileResponse(path, media_type=media)
|