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>
This commit is contained in:
@@ -0,0 +1,269 @@
|
||||
"""The media library's files (plan step 5.1; models/media.py).
|
||||
|
||||
Layout under MEDIA_DIR (`/app/data/media`: inside the site's DATA_PATH next to pos.db, so
|
||||
whatever copies the database must copy this folder too):
|
||||
<sha[:2]>/<sha>/original.<ext> the bytes as uploaded
|
||||
<sha[:2]>/<sha>/{thumb,card,full}.webp images only, made on upload (and again on
|
||||
request if missing, e.g. after a partial restore)
|
||||
|
||||
Images: JPEG, PNG, WebP or GIF (first frame), turned upright from their EXIF, never made
|
||||
bigger than they are. Videos: MP4 or WebM, kept as uploaded (no transcoding on the venue's
|
||||
box); an MP4's length and size are read from its header when it has them.
|
||||
|
||||
Usage: what points at a media item registers a check with `register_usage(kind, fn)`,
|
||||
fn(db, media_id) -> [{"kind", "id", "name"}]. Delete is refused while any check finds a use.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import tempfile
|
||||
import threading
|
||||
from typing import Callable, IO
|
||||
|
||||
from core.errors import XeniaError
|
||||
|
||||
MEDIA_DIR = os.environ.get("XENIA_MEDIA_DIR", "/app/data/media")
|
||||
|
||||
IMAGE_MAX_BYTES = 20 * 1024 * 1024
|
||||
VIDEO_MAX_BYTES = 200 * 1024 * 1024
|
||||
MAX_PIXELS = 60_000_000 # a 60 MP photo is fine; bigger is a decompression bomb
|
||||
|
||||
# name → longest side in pixels (never upscaled)
|
||||
SIZES = {"thumb": 200, "card": 600, "full": 1920}
|
||||
WEBP_QUALITY = 80
|
||||
IMAGE_TYPES = {"JPEG": ("image/jpeg", "jpg"), "PNG": ("image/png", "png"),
|
||||
"WEBP": ("image/webp", "webp"), "GIF": ("image/gif", "gif")}
|
||||
VIDEO_TYPES = {"mp4": "video/mp4", "webm": "video/webm"}
|
||||
VARIANTS = (*SIZES, "original")
|
||||
|
||||
_lock = threading.Lock() # one writer per file set at a time
|
||||
|
||||
|
||||
# ── where files are ─────────────────────────────────────────────────────────
|
||||
|
||||
def folder(sha: str) -> str:
|
||||
return os.path.join(MEDIA_DIR, sha[:2], sha)
|
||||
|
||||
|
||||
def original_path(sha: str) -> str | None:
|
||||
d = folder(sha)
|
||||
try:
|
||||
for n in os.listdir(d):
|
||||
if n.startswith("original."):
|
||||
return os.path.join(d, n)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def variant_path(sha: str, variant: str) -> str:
|
||||
return os.path.join(folder(sha), f"{variant}.webp")
|
||||
|
||||
|
||||
def urls(item) -> dict:
|
||||
base = f"/api/media/file/{item.sha256}"
|
||||
out = {"original": f"{base}/original"}
|
||||
if item.kind == "image":
|
||||
out.update({v: f"{base}/{v}" for v in SIZES})
|
||||
return out
|
||||
|
||||
|
||||
# ── receiving an upload ─────────────────────────────────────────────────────
|
||||
|
||||
def receive(src: IO[bytes], max_bytes: int) -> tuple[str, str, int]:
|
||||
"""Copy an upload into a temp file under MEDIA_DIR while hashing it.
|
||||
Returns (temp path, sha256, size). Refuses beyond max_bytes without keeping anything."""
|
||||
tmp_dir = os.path.join(MEDIA_DIR, "tmp")
|
||||
os.makedirs(tmp_dir, exist_ok=True)
|
||||
h = hashlib.sha256()
|
||||
size = 0
|
||||
fd, tmp = tempfile.mkstemp(dir=tmp_dir)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
while True:
|
||||
chunk = src.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise XeniaError("media.too_big", max_mb=max_bytes // (1024 * 1024))
|
||||
h.update(chunk)
|
||||
out.write(chunk)
|
||||
except BaseException:
|
||||
_remove(tmp)
|
||||
raise
|
||||
if size == 0:
|
||||
_remove(tmp)
|
||||
raise XeniaError("media.type")
|
||||
return tmp, h.hexdigest(), size
|
||||
|
||||
|
||||
def sniff(path: str) -> str | None:
|
||||
"""'image' | 'mp4' | 'webm' | None, from the first bytes (never from the name)."""
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(16)
|
||||
if head[4:8] == b"ftyp":
|
||||
return "mp4"
|
||||
if head[:4] == b"\x1a\x45\xdf\xa3":
|
||||
return "webm"
|
||||
if head[:3] == b"\xff\xd8\xff" or head[:8] == b"\x89PNG\r\n\x1a\n" or head[:6] in (b"GIF87a", b"GIF89a") \
|
||||
or (head[:4] == b"RIFF" and head[8:12] == b"WEBP"):
|
||||
return "image"
|
||||
return None
|
||||
|
||||
|
||||
def open_image(path: str):
|
||||
"""The image upright and fully decoded; refuses anything Pillow can't read safely."""
|
||||
from PIL import Image, ImageOps
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
try:
|
||||
img = Image.open(path)
|
||||
fmt = img.format
|
||||
if fmt not in IMAGE_TYPES:
|
||||
raise XeniaError("media.type")
|
||||
if img.width * img.height > MAX_PIXELS:
|
||||
raise XeniaError("media.too_many_pixels", max_mp=MAX_PIXELS // 1_000_000)
|
||||
img.seek(0)
|
||||
img = ImageOps.exif_transpose(img)
|
||||
img.load()
|
||||
except XeniaError:
|
||||
raise
|
||||
except Image.DecompressionBombError:
|
||||
raise XeniaError("media.too_many_pixels", max_mp=MAX_PIXELS // 1_000_000)
|
||||
except Exception:
|
||||
raise XeniaError("media.unreadable")
|
||||
return img, fmt
|
||||
|
||||
|
||||
def make_variants(img, sha: str) -> None:
|
||||
from PIL import Image
|
||||
has_alpha = img.mode in ("RGBA", "LA", "PA") or (img.mode == "P" and "transparency" in img.info)
|
||||
base = img.convert("RGBA" if has_alpha else "RGB")
|
||||
for name, side in SIZES.items():
|
||||
v = base.copy()
|
||||
v.thumbnail((side, side), Image.LANCZOS)
|
||||
tmp = variant_path(sha, name) + ".part"
|
||||
v.save(tmp, "WEBP", quality=WEBP_QUALITY, method=4)
|
||||
os.replace(tmp, variant_path(sha, name))
|
||||
|
||||
|
||||
def ensure_variant(item, variant: str) -> str | None:
|
||||
"""The file to serve for a variant, re-making image sizes that are missing."""
|
||||
if variant == "original":
|
||||
return original_path(item.sha256)
|
||||
if item.kind != "image" or variant not in SIZES:
|
||||
return None
|
||||
p = variant_path(item.sha256, variant)
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
src = original_path(item.sha256)
|
||||
if not src:
|
||||
return None
|
||||
with _lock:
|
||||
if not os.path.exists(p):
|
||||
img, _ = open_image(src)
|
||||
make_variants(img, item.sha256)
|
||||
return p
|
||||
|
||||
|
||||
def store(tmp: str, sha: str, ext: str) -> None:
|
||||
"""Move the received temp file into place as the original."""
|
||||
d = folder(sha)
|
||||
os.makedirs(d, exist_ok=True)
|
||||
os.replace(tmp, os.path.join(d, f"original.{ext}"))
|
||||
|
||||
|
||||
def delete_files(sha: str) -> None:
|
||||
shutil.rmtree(folder(sha), ignore_errors=True)
|
||||
try:
|
||||
os.rmdir(os.path.dirname(folder(sha))) # the <sha[:2]> folder, when empty
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _remove(path: str) -> None:
|
||||
try:
|
||||
os.remove(path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
# ── MP4 header: length and picture size ─────────────────────────────────────
|
||||
|
||||
def mp4_info(path: str) -> dict:
|
||||
"""{"duration_ms", "width", "height"} from an MP4's moov box (any it has; never raises)."""
|
||||
out: dict = {}
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
end = os.fstat(f.fileno()).st_size
|
||||
_walk(f, 0, end, out)
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def _boxes(f, start, end):
|
||||
pos = start
|
||||
while pos + 8 <= end:
|
||||
f.seek(pos)
|
||||
size, kind = struct.unpack(">I4s", f.read(8))
|
||||
head = 8
|
||||
if size == 1:
|
||||
size = struct.unpack(">Q", f.read(8))[0]
|
||||
head = 16
|
||||
elif size == 0:
|
||||
size = end - pos
|
||||
if size < head:
|
||||
return
|
||||
yield kind, pos + head, pos + size
|
||||
pos += size
|
||||
|
||||
|
||||
def _walk(f, start, end, out):
|
||||
for kind, body, stop in _boxes(f, start, end):
|
||||
if kind in (b"moov", b"trak"):
|
||||
_walk(f, body, stop, out)
|
||||
elif kind == b"mvhd":
|
||||
f.seek(body)
|
||||
version = f.read(1)[0]
|
||||
f.read(3)
|
||||
if version == 1:
|
||||
f.read(16)
|
||||
scale, dur = struct.unpack(">IQ", f.read(12))
|
||||
else:
|
||||
f.read(8)
|
||||
scale, dur = struct.unpack(">II", f.read(8))
|
||||
if scale:
|
||||
out["duration_ms"] = int(dur * 1000 / scale)
|
||||
elif kind == b"tkhd" and stop - body >= 8:
|
||||
f.seek(stop - 8)
|
||||
w, h = struct.unpack(">II", f.read(8))
|
||||
w, h = w >> 16, h >> 16
|
||||
if w and h and w * h > out.get("width", 0) * out.get("height", 0):
|
||||
out["width"], out["height"] = w, h
|
||||
|
||||
|
||||
# ── what uses a media item ──────────────────────────────────────────────────
|
||||
|
||||
UsageCheck = Callable[[object, int], list]
|
||||
_usage: dict[str, UsageCheck] = {}
|
||||
|
||||
|
||||
def register_usage(kind: str, fn: UsageCheck) -> None:
|
||||
"""kind: what uses media ("product", "display", "playlist"...); fn(db, media_id) lists them."""
|
||||
_usage[kind] = fn
|
||||
|
||||
|
||||
def unregister_usage(kind: str) -> None:
|
||||
_usage.pop(kind, None)
|
||||
|
||||
|
||||
def uses(db, media_id: int) -> list[dict]:
|
||||
found = []
|
||||
for kind, fn in _usage.items():
|
||||
for u in fn(db, media_id) or ():
|
||||
found.append({"kind": kind, **u})
|
||||
return found
|
||||
Reference in New Issue
Block a user