Files
xenia-pos-local/local_backend/routers/media.py
T
bonaminandClaude Opus 5.5 5ad4c4ef55 feat(backend): products and categories point at the media library (platform-v2 step 5.2)
- products.media_id / categories.media_id (Alembic 0027): the old
  /static/product_images photos are processed into the library (named after
  their product; missing or unreadable files logged and skipped; the old
  folder is left on disk) and products.image_url goes. The static mount is gone.
- APIs give `image` {id, name, thumb, card, full}; a product's image_url is its
  card size. media_id on create/update (null clears); media.not_a_picture for
  a video. POST /api/products/{id}/image is gone: uploads go to /api/media.
- Products and categories register their media usage: a photo in use can't
  be deleted.
- Media: AVIF pictures (Pillow 12.3), GET /api/media/{id} gives each stored
  size's bytes and resolution and the uploader's name; upload processing moved
  into services/media.ingest (also used by the data move).
- QR menu photo push (contract C-3): the library's card size, WebP.
- tests: test_product_photos.py (7, incl. the 0027 data move); 497 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:57:50 +02:00

214 lines
8.1 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
uploaded_by_name: Optional[str] = None
created_at: datetime
urls: dict = Field(default_factory=dict)
class MediaDetail(MediaOut):
used_by: List[dict] = Field(default_factory=list)
files: dict = Field(default_factory=dict) # what is stored: {variant: {bytes, width, height}}
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)
info = store.ingest(tmp, sha, size)
item = Media(name=(name or "").strip()[:120] or _name_from(file.filename),
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id, **info)
try:
db.add(item)
db.commit()
except BaseException:
store.delete_files(sha)
raise
db.refresh(item)
return _out(item, UploadOut)
@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), files=store.files_info(item))
@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)