Files
xenia-pos-local/local_backend/routers/media.py
T
bonaminandClaude Opus 5.5 238f8ec5a0 feat(backend): media library: files once by hash, WebP sizes, cached, protected while used (platform-v2 step 5.1)
- Table `media` (Alembic 0026): kind, name, original name, type, sha256
  (unique), bytes, width/height, video length, who and when.
- Files under /app/data/media/<sha[:2]>/<sha>/: the original, and for
  pictures thumb (200 px) / card (600) / full (1920) WebP, upright from
  EXIF, never enlarged, transparency kept. Videos (MP4, WebM) kept as
  uploaded; an MP4's length and size come from its header.
- GET/POST /api/media, GET/PATCH/DELETE /api/media/{id} for whoever manages
  the menu, customer display, signage or menu tablets. The same file again
  returns the existing item. The type comes from the bytes; 20 MB pictures,
  200 MB videos, 60 MP; refused uploads leave nothing behind.
- GET /api/media/file/<sha>/<variant>: public (LAN), Cache-Control
  public, max-age=1 year, immutable; byte ranges for video; a missing size
  is made again from the original.
- register_usage(kind, fn): what uses media (products, displays, signage
  from 5.2-5.4) declares it; delete is refused with media.in_use listing
  the users.
- tests: test_media.py (12); stack.mjs uploads 3 MB through both nginx hops
  and fetches a size with its cache headers (compose stack: all passed).
  Backend suite: 490 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:22:26 +02:00

235 lines
8.9 KiB
Python

"""The media library API (plan step 5.1; models/media.py, services/media.py).
GET /api/media the library (kind, search, paging)
POST /api/media upload one file (image or video); the same file again
returns the existing item (`existing: true`)
GET /api/media/{id} one item, with what uses it
PATCH /api/media/{id} rename
DELETE /api/media/{id} refused with `media.in_use` while something uses it
GET /api/media/file/{sha}/{variant} the bytes: thumb | card | full (images, WebP)
| original. Public (LAN, like the customer display's
images), cached for a year: a URL never changes meaning.
Whoever manages the menu, the customer display, signage or the menu tablets manages the
library (one library for all of them).
"""
from __future__ import annotations
import os
import re
from typing import List, Literal, Optional
from fastapi import APIRouter, Depends, File, Form, Request, UploadFile
from fastapi.responses import FileResponse, Response, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator
from sqlalchemy.orm import Session
from core.access.deps import public, require_any
from core.errors import XeniaError
from database import get_db
from datetime import datetime
from models.media import Media
from services import media as store
router = APIRouter()
MANAGE = ("catalog.menu.manage", "customer_display.manage", "signage.manage", "menu_tablet.manage")
SHA = re.compile(r"^[0-9a-f]{64}$")
CACHE = "public, max-age=31536000, immutable"
class MediaOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
kind: str
name: str
original_name: Optional[str] = None
content_type: str
sha256: str
bytes: int
width: Optional[int] = None
height: Optional[int] = None
duration_ms: Optional[int] = None
uploaded_by: Optional[int] = None
created_at: datetime
urls: dict = Field(default_factory=dict)
class MediaDetail(MediaOut):
used_by: List[dict] = Field(default_factory=list)
class UploadOut(MediaOut):
existing: bool = False
class MediaPage(BaseModel):
items: List[MediaOut]
total: int
class RenameBody(BaseModel):
name: str = Field(min_length=1, max_length=120)
@field_validator("name")
@classmethod
def _strip(cls, v):
v = v.strip()
if not v:
raise ValueError("empty")
return v
def _out(item: Media, cls=MediaOut, **extra):
return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra})
def _get(db: Session, media_id: int) -> Media:
item = db.get(Media, media_id)
if item is None:
raise XeniaError("media.not_found", media_id=media_id)
return item
def _name_from(filename: str | None) -> str:
base = os.path.basename(filename or "").strip()
stem = base.rsplit(".", 1)[0] if "." in base else base
return (stem or "file")[:120]
@router.get("", response_model=MediaPage)
def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None,
limit: int = 100, offset: int = 0,
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
query = db.query(Media)
if kind:
query = query.filter(Media.kind == kind)
if q and q.strip():
query = query.filter(Media.name.ilike(f"%{q.strip()}%"))
total = query.count()
rows = query.order_by(Media.created_at.desc(), Media.id.desc()) \
.offset(max(offset, 0)).limit(min(max(limit, 1), 500)).all()
return MediaPage(items=[_out(m) for m in rows], total=total)
@router.post("", response_model=UploadOut, status_code=201)
def upload_media(response: Response, file: UploadFile = File(...), name: Optional[str] = Form(None),
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
# The type comes from the bytes; the browser's content type only picks the size limit.
declared = (file.content_type or "").lower()
limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES
tmp, sha, size = store.receive(file.file, limit)
existing = db.query(Media).filter(Media.sha256 == sha).first()
if existing is not None:
store._remove(tmp)
response.status_code = 200
return _out(existing, UploadOut, existing=True)
try:
found = store.sniff(tmp)
info: dict = {}
if found == "image":
if size > store.IMAGE_MAX_BYTES:
raise XeniaError("media.too_big", max_mb=store.IMAGE_MAX_BYTES // (1024 * 1024))
img, fmt = store.open_image(tmp)
content_type, ext = store.IMAGE_TYPES[fmt]
kind = "image"
info = {"width": img.width, "height": img.height}
os.makedirs(store.folder(sha), exist_ok=True)
store.make_variants(img, sha)
elif found in store.VIDEO_TYPES:
kind, ext, content_type = "video", found, store.VIDEO_TYPES[found]
if found == "mp4":
info = store.mp4_info(tmp)
else:
raise XeniaError("media.type")
store.store(tmp, sha, ext)
tmp = None
item = Media(kind=kind, name=(name or "").strip()[:120] or _name_from(file.filename),
original_name=(file.filename or None), content_type=content_type,
sha256=sha, bytes=size, uploaded_by=user.id, **info)
db.add(item)
db.commit()
db.refresh(item)
return _out(item, UploadOut)
except BaseException:
# Refused or failed: keep nothing (the temp file, sizes already made, a stored original).
if tmp is not None:
store._remove(tmp)
store.delete_files(sha)
raise
@router.get("/file/{sha}/{variant}", dependencies=[Depends(public())])
def media_file(sha: str, variant: str, request: Request, db: Session = Depends(get_db)):
if not SHA.match(sha) or variant not in store.VARIANTS:
raise XeniaError("media.not_found", media_id=sha)
item = db.query(Media).filter(Media.sha256 == sha).first()
path = store.ensure_variant(item, variant) if item is not None else None
if not path or not os.path.exists(path):
raise XeniaError("media.not_found", media_id=sha)
ctype = item.content_type if variant == "original" else "image/webp"
headers = {"Cache-Control": CACHE, "Accept-Ranges": "bytes"}
rng = request.headers.get("range")
if rng and variant == "original":
return _ranged(path, ctype, rng, headers)
return FileResponse(path, media_type=ctype, headers=headers)
def _ranged(path: str, ctype: str, rng: str, headers: dict):
"""One byte range of a file (videos seek with these; Starlette 0.38 doesn't do it)."""
size = os.path.getsize(path)
m = re.match(r"^bytes=(\d*)-(\d*)$", rng.strip())
if not m or (not m.group(1) and not m.group(2)):
return FileResponse(path, media_type=ctype, headers=headers)
if m.group(1):
start = int(m.group(1))
end = int(m.group(2)) if m.group(2) else size - 1
else: # bytes=-N: the last N bytes
start, end = max(size - int(m.group(2)), 0), size - 1
end = min(end, size - 1)
if start > end or start >= size:
return Response(status_code=416, headers={"Content-Range": f"bytes */{size}"})
def chunks():
with open(path, "rb") as f:
f.seek(start)
left = end - start + 1
while left > 0:
data = f.read(min(256 * 1024, left))
if not data:
break
left -= len(data)
yield data
return StreamingResponse(chunks(), status_code=206, media_type=ctype, headers={
**headers, "Content-Range": f"bytes {start}-{end}/{size}", "Content-Length": str(end - start + 1)})
@router.get("/{media_id}", response_model=MediaDetail)
def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
item = _get(db, media_id)
return _out(item, MediaDetail, used_by=store.uses(db, item.id))
@router.patch("/{media_id}", response_model=MediaOut)
def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
item = _get(db, media_id)
item.name = body.name
db.commit()
db.refresh(item)
return _out(item)
@router.delete("/{media_id}", status_code=204)
def delete_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
item = _get(db, media_id)
used = store.uses(db, item.id)
if used:
raise XeniaError("media.in_use", uses=", ".join(u.get("name") or f"{u['kind']} {u.get('id')}" for u in used),
used_by=used)
sha = item.sha256
db.delete(item)
db.commit()
store.delete_files(sha)
return Response(status_code=204)