"""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): //original. the bytes as uploaded //{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, AVIF 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"), "AVIF": ("image/avif", "avif")} 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 image_of(item) -> dict | None: """What an app needs to show a picture from the library: {"id", "name", "thumb", "card", "full"}.""" if item is None or item.kind != "image": return None return {"id": item.id, "name": item.name, **{k: v for k, v in urls(item).items() if k != "original"}} 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 "image" if head[8:12] in (b"avif", b"avis") else "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 ingest(tmp: str, sha: str, size: int) -> dict: """Check a received temp file, make its sizes and store it under its hash. → {"kind", "content_type", "width", "height", "duration_ms"} (the last three may be missing). Refused or failed: nothing is kept (neither the temp file nor anything made from it).""" try: found = sniff(tmp) if found == "image": if size > IMAGE_MAX_BYTES: raise XeniaError("media.too_big", max_mb=IMAGE_MAX_BYTES // (1024 * 1024)) img, fmt = open_image(tmp) content_type, ext = IMAGE_TYPES[fmt] info = {"kind": "image", "content_type": content_type, "width": img.width, "height": img.height} os.makedirs(folder(sha), exist_ok=True) make_variants(img, sha) elif found in VIDEO_TYPES: ext = found info = {"kind": "video", "content_type": VIDEO_TYPES[found], **(mp4_info(tmp) if found == "mp4" else {})} else: raise XeniaError("media.type") store(tmp, sha, ext) return info except BaseException: _remove(tmp) delete_files(sha) raise def ingest_path(path: str) -> tuple[str, int, dict]: """A file already on disk (a data move, e.g. the old product images): → (sha, size, info). The file itself is left where it is.""" with open(path, "rb") as f: tmp, sha, size = receive(f, VIDEO_MAX_BYTES) if original_path(sha): # already in the library _remove(tmp) return sha, size, {} return sha, size, ingest(tmp, sha, size) def files_info(item) -> dict: """{variant: {"bytes", "width", "height"}} of what is stored for an item (missing sizes left out; a video's original has no picture size here).""" from PIL import Image out = {} for v in VARIANTS: p = original_path(item.sha256) if v == "original" else variant_path(item.sha256, v) if not p or not os.path.exists(p): continue info = {"bytes": os.path.getsize(p), "width": None, "height": None} if v == "original": info.update(width=item.width, height=item.height) else: try: with Image.open(p) as im: info.update(width=im.width, height=im.height) except Exception: pass out[v] = info return out 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 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