Compare commits

..
2 Commits
Author SHA1 Message Date
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
bonaminandClaude Opus 5.5 24971533a0 fix(proxy): accept uploads up to 250 MB in every nginx hop
nginx's default client_max_body_size is 1 MB, so a phone photo (3-5 MB)
uploaded as a product image or customer-display image was refused with
413 before it reached the backend. The proxy (both copies, CS-5) and the
waiter, manager and terminal images now allow 250 MB; the backend checks
the real limits (media library: 20 MB pictures, 200 MB videos, step 5.1).
All five configs pass `nginx -t`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:22:26 +02:00
17 changed files with 838 additions and 1 deletions
+1
View File
@@ -47,6 +47,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` | | `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` |
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) | | `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
| `local_backend/routers/customer_display.py`, `terminal/src/apps/customer-display/` | The customer display (3.4): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is the venue's design (`customer_display.idle`: name, logo, both, blank, image, slideshow, QR, a line of text, dark/light), images in `/app/data/display_media`, served by name at `/api/display/media/{name}` (public, LAN, random names). The POS's last state lives in memory | | `local_backend/routers/customer_display.py`, `terminal/src/apps/customer-display/` | The customer display (3.4): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is the venue's design (`customer_display.idle`: name, logo, both, blank, image, slideshow, QR, a line of text, dark/light), images in `/app/data/display_media`, served by name at `/api/display/media/{name}` (public, LAN, random names). The POS's last state lives in memory |
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py` | The media library (5.1): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (original + `thumb`/`card`/`full` WebP for pictures; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). Whoever manages the menu, customer display, signage or menu tablets manages it. **Anything that points at a media item registers `register_usage(kind, fn)`** so delete is refused (`media.in_use`) while it's used. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` (the default 1 MB refused phone photos) |
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more | | `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) | | `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` | | `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
+4
View File
@@ -123,6 +123,10 @@ map $http_upgrade $connection_upgrade {
'' close; '' close;
} }
# Uploads: the media library takes pictures up to 20 MB and videos up to 200 MB
# (local_backend/services/media.py checks the real limits; nginx's default is 1 MB).
client_max_body_size 250m;
# ── Plain HTTP ──────────────────────────────────────────────────────────────── # ── Plain HTTP ────────────────────────────────────────────────────────────────
server { server {
+6
View File
@@ -98,6 +98,12 @@ CODES: dict[str, tuple[int, str]] = {
"display.media_type": (422, "Upload a JPG, PNG, WebP or GIF image."), "display.media_type": (422, "Upload a JPG, PNG, WebP or GIF image."),
"display.media_too_big": (413, "The image is too big (at most {max_mb} MB)."), "display.media_too_big": (413, "The image is too big (at most {max_mb} MB)."),
"display.qr_url_missing": (422, "Enter the link the QR code opens."), "display.qr_url_missing": (422, "Enter the link the QR code opens."),
"media.not_found": (404, "File {media_id} isn't in the media library."),
"media.type": (422, "Upload a picture (JPG, PNG, WebP or GIF) or a video (MP4 or WebM)."),
"media.too_big": (413, "The file is too big (at most {max_mb} MB)."),
"media.too_many_pixels": (422, "The picture is too large (at most {max_mp} megapixels)."),
"media.unreadable": (422, "This picture can't be read. Save it again as JPG or PNG and upload it."),
"media.in_use": (409, "This file is used by {uses}. Remove it there first."),
"reservation.not_found": (404, "Booking {reservation_id} not found."), "reservation.not_found": (404, "Booking {reservation_id} not found."),
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."), "reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
"reservation.table_unknown": (404, "Table {table_id} not found."), "reservation.table_unknown": (404, "Table {table_id} not found."),
@@ -0,0 +1,47 @@
"""media: the media library (plan step 5.1).
One row per file (unique sha256); the bytes live under data/media (services/media.py).
Products, the customer display and signage point at these rows from steps 5.2-5.4.
Revision ID: 0026_media
Revises: 0025_order_item_source
Create Date: 2026-11-18 12:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0026_media'
down_revision = '0025_order_item_source'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('media',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('kind', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('original_name', sa.String(), nullable=True),
sa.Column('content_type', sa.String(), nullable=False),
sa.Column('sha256', sa.String(length=64), nullable=False),
sa.Column('bytes', sa.Integer(), nullable=False),
sa.Column('width', sa.Integer(), nullable=True),
sa.Column('height', sa.Integer(), nullable=True),
sa.Column('duration_ms', sa.Integer(), nullable=True),
sa.Column('uploaded_by', sa.Integer(), nullable=True),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.ForeignKeyConstraint(['uploaded_by'], ['users.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('sha256')
)
with op.batch_alter_table('media', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_media_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_media_kind'), ['kind'], unique=False)
def downgrade() -> None:
with op.batch_alter_table('media', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_media_kind'))
batch_op.drop_index(batch_op.f('ix_media_id'))
op.drop_table('media')
+1
View File
@@ -38,3 +38,4 @@ import models.support_challenge # noqa: F401 SupportChallenge (support access,
import models.notification # noqa: F401 Notification, NotificationRead (step 1.11) import models.notification # noqa: F401 Notification, NotificationRead (step 1.11)
import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3) import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3)
import models.refund # noqa: F401 Refund, RefundItem (step 3.3e) import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
import models.media # noqa: F401 Media (media library, step 5.1)
+33
View File
@@ -0,0 +1,33 @@
"""The media library (plan step 5.1): every picture and video the venue uses, kept once.
A row is one file, identified by the sha256 of its bytes (unique: uploading the same file
again returns the existing row). The bytes live under `data/media/<sha[:2]>/<sha>/`
(services/media.py): the original as uploaded, and for images three WebP sizes (thumb,
card, full). Files are served by hash at `/api/media/file/<sha>/<variant>` with long cache
headers, so a URL never changes meaning: a different file is a different URL.
Rows are referenced by id from what uses them (products, the customer display, signage;
steps 5.2-5.4). Those users register a usage check in services/media.py so a file in use
can't be deleted.
"""
from sqlalchemy import Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class Media(Base):
__tablename__ = "media"
id = Column(Integer, primary_key=True, index=True)
kind = Column(String, nullable=False, index=True) # image | video
name = Column(String, nullable=False) # shown in the library; editable
original_name = Column(String, nullable=True) # the uploaded file's name
content_type = Column(String, nullable=False) # of the original
sha256 = Column(String(64), nullable=False, unique=True)
bytes = Column(Integer, nullable=False) # of the original
width = Column(Integer, nullable=True) # images; videos when the file says
height = Column(Integer, nullable=True)
duration_ms = Column(Integer, nullable=True) # videos (MP4) when the file says
uploaded_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
+1
View File
@@ -45,6 +45,7 @@ MODULE = Module(
Mount('routers.ws', '/api/ws'), Mount('routers.ws', '/api/ws'),
Mount('routers.recovery', '/api/recovery'), Mount('routers.recovery', '/api/recovery'),
Mount('routers.devices', '/api/devices'), Mount('routers.devices', '/api/devices'),
Mount('routers.media', '/api/media'),
Mount('routers.access', '/api/access'), Mount('routers.access', '/api/access'),
Mount('routers.notifications', '/api/platform/notifications'), Mount('routers.notifications', '/api/platform/notifications'),
Mount('core.modules.api', '/api/platform'), Mount('core.modules.api', '/api/platform'),
+234
View File
@@ -0,0 +1,234 @@
"""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)
+269
View File
@@ -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
+187
View File
@@ -0,0 +1,187 @@
"""The media library (plan step 5.1): files kept once by content, three WebP sizes for every
picture, served with long cache headers, and a file in use can't be deleted."""
import io
import os
import struct
import pytest
from PIL import Image
from tests.test_live import err, owner_h # noqa: F401 (fixtures)
@pytest.fixture(autouse=True)
def media_dir(tmp_path, monkeypatch):
import services.media as store
monkeypatch.setattr(store, "MEDIA_DIR", str(tmp_path / "media"))
return tmp_path / "media"
def jpeg(w=3000, h=2000, colour=(200, 80, 40), exif=None):
buf = io.BytesIO()
img = Image.new("RGB", (w, h), colour)
kw = {"exif": exif} if exif is not None else {}
img.save(buf, "JPEG", quality=85, **kw)
return buf.getvalue()
def png_alpha(w=300, h=300):
buf = io.BytesIO()
Image.new("RGBA", (w, h), (0, 128, 255, 100)).save(buf, "PNG")
return buf.getvalue()
def box(kind, body):
return struct.pack(">I4s", 8 + len(body), kind) + body
def mp4(seconds=12.5, w=1920, h=1080):
"""A tiny file with the boxes a real MP4 starts with (enough for the header reader)."""
mvhd = bytes(4) + bytes(8) + struct.pack(">II", 1000, int(seconds * 1000)) + bytes(80)
tkhd = bytes(4) + bytes(72) + struct.pack(">II", w << 16, h << 16)
moov = box(b"moov", box(b"mvhd", mvhd) + box(b"trak", box(b"tkhd", tkhd)))
return box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2mp41") + moov + box(b"mdat", bytes(5000))
def up(client, h, data, name="photo.jpg", ctype="image/jpeg", **form):
return client.post("/api/media", headers=h, files={"file": (name, data, ctype)}, data=form)
def files_left(root):
return sorted(str(p.relative_to(root)).replace("\\", "/") for p in root.rglob("*") if p.is_file()) if root.exists() else []
def test_a_jpeg_gets_three_sizes_served_with_cache_headers(client, owner_h, media_dir):
r = up(client, owner_h, jpeg(), name="Souvlaki pita.JPG")
assert r.status_code == 201, r.text
m = r.json()
assert (m["kind"], m["name"], m["original_name"]) == ("image", "Souvlaki pita", "Souvlaki pita.JPG")
assert (m["width"], m["height"], m["content_type"]) == (3000, 2000, "image/jpeg")
assert set(m["urls"]) == {"thumb", "card", "full", "original"}
for variant, side in (("thumb", 200), ("card", 600), ("full", 1920)):
f = client.get(m["urls"][variant]) # public: no sign-in needed
assert f.status_code == 200, (variant, f.text)
assert f.headers["content-type"] == "image/webp"
assert "immutable" in f.headers["cache-control"] and "max-age=31536000" in f.headers["cache-control"]
img = Image.open(io.BytesIO(f.content))
assert (img.format, img.size[0]) == ("WEBP", side) and abs(img.size[1] - side * 2 / 3) <= 1
orig = client.get(m["urls"]["original"])
assert orig.headers["content-type"] == "image/jpeg" and len(orig.content) == m["bytes"]
sha = m["sha256"]
assert files_left(media_dir) == [f"{sha[:2]}/{sha}/{n}" for n in ("card.webp", "full.webp", "original.jpg", "thumb.webp")]
def test_the_same_file_twice_is_kept_once(client, owner_h, media_dir):
data = jpeg(800, 600)
a = up(client, owner_h, data, name="a.jpg").json()
b = up(client, owner_h, data, name="copy of a.jpg")
assert b.status_code == 200 and b.json()["existing"] is True and b.json()["id"] == a["id"]
assert client.get("/api/media", headers=owner_h).json()["total"] == 1
assert len(files_left(media_dir)) == 4 # no temp file left either
def test_small_pictures_are_never_made_bigger_and_keep_transparency(client, owner_h):
m = up(client, owner_h, png_alpha(300, 150), name="logo.png", ctype="image/png").json()
for variant, size in (("thumb", (200, 100)), ("card", (300, 150)), ("full", (300, 150))):
img = Image.open(io.BytesIO(client.get(m["urls"][variant]).content))
assert img.size == size and img.mode == "RGBA"
def test_a_phone_photo_is_turned_upright(client, owner_h):
exif = Image.Exif()
exif[0x0112] = 6 # "rotate 90° clockwise to view"
m = up(client, owner_h, jpeg(400, 300, exif=exif.tobytes())).json()
assert (m["width"], m["height"]) == (300, 400)
img = Image.open(io.BytesIO(client.get(m["urls"]["full"]).content))
assert img.size == (300, 400)
def test_what_isnt_a_picture_or_video_is_refused_and_nothing_kept(client, owner_h, media_dir):
r = up(client, owner_h, b"hello, not a picture" * 10, name="evil.jpg")
assert r.status_code == 422 and err(r) == "media.type"
broken = jpeg(100, 100)[:200] # a JPEG cut short
r = up(client, owner_h, broken, name="cut.jpg")
assert r.status_code == 422 and err(r) == "media.unreadable"
assert files_left(media_dir) == []
def test_too_big_is_refused_while_receiving(client, owner_h, media_dir, monkeypatch):
import services.media as store
monkeypatch.setattr(store, "IMAGE_MAX_BYTES", 10_000)
r = up(client, owner_h, jpeg(2000, 2000, colour=(1, 2, 3)) + os.urandom(20_000))
assert r.status_code == 413 and err(r) == "media.too_big"
assert files_left(media_dir) == []
def test_a_video_is_kept_as_uploaded_with_its_length_and_seekable(client, owner_h, media_dir):
data = mp4()
r = up(client, owner_h, data, name="promo.mp4", ctype="video/mp4")
assert r.status_code == 201, r.text
m = r.json()
assert (m["kind"], m["content_type"], m["duration_ms"], m["width"], m["height"]) == ("video", "video/mp4", 12500, 1920, 1080)
assert set(m["urls"]) == {"original"}
assert client.get(f"/api/media/file/{m['sha256']}/card").status_code == 404
part = client.get(m["urls"]["original"], headers={"Range": "bytes=100-199"})
assert part.status_code == 206 and part.content == data[100:200]
assert part.headers["content-range"] == f"bytes 100-199/{len(data)}"
tail = client.get(m["urls"]["original"], headers={"Range": "bytes=-10"})
assert tail.status_code == 206 and tail.content == data[-10:]
assert client.get(m["urls"]["original"], headers={"Range": f"bytes={len(data)}-"}).status_code == 416
assert client.get(m["urls"]["original"]).content == data
def test_list_search_rename(client, owner_h):
a = up(client, owner_h, jpeg(300, 300, (1, 1, 1)), name="Burger classic.jpg").json()
up(client, owner_h, jpeg(300, 300, (2, 2, 2)), name="Greek salad.jpg")
up(client, owner_h, mp4(), name="Promo.mp4", ctype="video/mp4")
page = client.get("/api/media", headers=owner_h).json()
assert page["total"] == 3 and [i["name"] for i in page["items"]][0] == "Promo"
assert [i["name"] for i in client.get("/api/media?kind=image&q=burg", headers=owner_h).json()["items"]] == ["Burger classic"]
r = client.patch(f"/api/media/{a['id']}", headers=owner_h, json={"name": " Burger "})
assert r.status_code == 200 and r.json()["name"] == "Burger"
assert client.patch(f"/api/media/{a['id']}", headers=owner_h, json={"name": " "}).status_code == 422
def test_delete_frees_the_files_but_a_file_in_use_is_refused(client, owner_h, media_dir):
import services.media as store
used = up(client, owner_h, jpeg(300, 300, (9, 9, 9)), name="used.jpg").json()
free = up(client, owner_h, jpeg(300, 300, (8, 8, 8)), name="free.jpg").json()
store.register_usage("product", lambda db, mid: [{"id": 7, "name": "Pork souvlaki"}] if mid == used["id"] else [])
try:
r = client.delete(f"/api/media/{used['id']}", headers=owner_h)
assert r.status_code == 409 and err(r) == "media.in_use"
assert r.json()["error"]["params"]["used_by"] == [{"kind": "product", "id": 7, "name": "Pork souvlaki"}]
assert "Pork souvlaki" in r.json()["error"]["message"]
assert client.get(f"/api/media/{used['id']}", headers=owner_h).json()["used_by"][0]["name"] == "Pork souvlaki"
assert client.get(used["urls"]["card"]).status_code == 200
assert client.delete(f"/api/media/{free['id']}", headers=owner_h).status_code == 204
finally:
store.unregister_usage("product")
assert client.get(f"/api/media/{free['id']}", headers=owner_h).status_code == 404
assert client.get(free["urls"]["card"]).status_code == 404
assert not any(free["sha256"] in f for f in files_left(media_dir))
def test_a_missing_size_is_made_again(client, owner_h, media_dir):
m = up(client, owner_h, jpeg(900, 900)).json()
sha = m["sha256"]
os.remove(media_dir / sha[:2] / sha / "card.webp")
f = client.get(m["urls"]["card"])
assert f.status_code == 200 and Image.open(io.BytesIO(f.content)).size == (600, 600)
def test_bad_file_addresses(client):
assert client.get("/api/media/file/../../etc/passwd/original").status_code == 404
assert err(client.get("/api/media/file/" + "a" * 64 + "/original")) == "media.not_found"
assert err(client.get("/api/media/file/" + "a" * 64 + "/huge")) == "media.not_found"
def test_who_may_use_the_library(client, make_user, login):
waiter = login(make_user(role="waiter"))
assert client.get("/api/media", headers=waiter).status_code == 403
assert up(client, waiter, jpeg(100, 100)).status_code == 403
display_only = login(make_user(role="waiter", keys=["customer_display.manage"]))
assert up(client, display_only, jpeg(100, 100)).status_code == 201
menu_only = login(make_user(role="waiter", keys=["catalog.menu.manage"]))
assert client.get("/api/media", headers=menu_only).json()["total"] == 1
assert client.get("/api/media").status_code in (401, 403)
+4
View File
@@ -1,3 +1,7 @@
# Uploads: the media library takes pictures up to 20 MB and videos up to 200 MB
# (local_backend/services/media.py checks the real limits; nginx's default is 1 MB).
client_max_body_size 250m;
server { server {
listen 80; listen 80;
+4
View File
@@ -20,6 +20,10 @@ map $http_upgrade $connection_upgrade {
'' close; '' close;
} }
# Uploads: the media library takes pictures up to 20 MB and videos up to 200 MB
# (local_backend/services/media.py checks the real limits; nginx's default is 1 MB).
client_max_body_size 250m;
# ── Plain HTTP ──────────────────────────────────────────────────────────────── # ── Plain HTTP ────────────────────────────────────────────────────────────────
server { server {
+8
View File
@@ -127,6 +127,14 @@
"media_too_big": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mb}} MB).", "media_too_big": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mb}} MB).",
"qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός." "qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός."
}, },
"media": {
"not_found": "Το αρχείο {{media_id}} δεν υπάρχει στη βιβλιοθήκη πολυμέσων.",
"type": "Ανεβάστε εικόνα (JPG, PNG, WebP ή GIF) ή βίντεο (MP4 ή WebM).",
"too_big": "Το αρχείο είναι πολύ μεγάλο (έως {{max_mb}} MB).",
"too_many_pixels": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mp}} megapixel).",
"unreadable": "Αυτή η εικόνα δεν διαβάζεται. Αποθηκεύστε τη ξανά ως JPG ή PNG και ανεβάστε τη.",
"in_use": "Αυτό το αρχείο χρησιμοποιείται από: {{uses}}. Αφαιρέστε το πρώτα από εκεί."
},
"caller_id": { "caller_id": {
"key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος." "key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος."
} }
+8
View File
@@ -127,6 +127,14 @@
"media_too_big": "The image is too big (at most {{max_mb}} MB).", "media_too_big": "The image is too big (at most {{max_mb}} MB).",
"qr_url_missing": "Enter the link the QR code opens." "qr_url_missing": "Enter the link the QR code opens."
}, },
"media": {
"not_found": "File {{media_id}} isn't in the media library.",
"type": "Upload a picture (JPG, PNG, WebP or GIF) or a video (MP4 or WebM).",
"too_big": "The file is too big (at most {{max_mb}} MB).",
"too_many_pixels": "The picture is too large (at most {{max_mp}} megapixels).",
"unreadable": "This picture can't be read. Save it again as JPG or PNG and upload it.",
"in_use": "This file is used by {{uses}}. Remove it there first."
},
"caller_id": { "caller_id": {
"key_invalid": "The phone system's key is missing or wrong." "key_invalid": "The phone system's key is missing or wrong."
} }
+4
View File
@@ -1,5 +1,9 @@
# Terminal image (plan step 3.1b): the static app + /api and /static forwarded to the backend. # Terminal image (plan step 3.1b): the static app + /api and /static forwarded to the backend.
# Reached through the proxy on :8082 (LAN only). Same as the manager's image. # Reached through the proxy on :8082 (LAN only). Same as the manager's image.
# Uploads: the media library takes pictures up to 20 MB and videos up to 200 MB
# (local_backend/services/media.py checks the real limits; nginx's default is 1 MB).
client_max_body_size 250m;
server { server {
listen 80; listen 80;
+23 -1
View File
@@ -6,10 +6,12 @@
// - the plain-HTTP ports (:8082, and :8081 as a control) refuse a non-LAN address and // - the plain-HTTP ports (:8082, and :8081 as a control) refuse a non-LAN address and
// answer a LAN one (two docker networks: 100.64.50.0/24 is not in the allow list) // answer a LAN one (two docker networks: 100.64.50.0/24 is not in the allow list)
// - the proxy still starts when the stack has no terminal container (older compose file) // - the proxy still starts when the stack has no terminal container (older compose file)
// - a media upload bigger than nginx's 1 MB default gets through the proxy and the manager's
// nginx (step 5.1), and its sizes come back with year-long cache headers
// node stack.mjs (builds the images: a few minutes the first time, cached after) // node stack.mjs (builds the images: a few minutes the first time, cached after)
import { execFileSync, spawnSync } from 'node:child_process' import { execFileSync, spawnSync } from 'node:child_process'
import { reporter } from './lib/env.mjs' import { reporter } from './lib/env.mjs'
import { composeStack, waitHttp } from './lib/proc.mjs' import { composeStack, login, waitHttp } from './lib/proc.mjs'
const PROJECT = 'xenia-e2e-stack' const PROJECT = 'xenia-e2e-stack'
const T = 19082 const T = 19082
@@ -56,6 +58,26 @@ try {
r.check('terminal: the live connection upgrades through both proxies (refused: no credentials)', r.check('terminal: the live connection upgrades through both proxies (refused: no credentials)',
frame?.type === 'refused' && frame.data?.code === 'auth.session_ended', JSON.stringify(frame)) frame?.type === 'refused' && frame.data?.code === 'auth.session_ended', JSON.stringify(frame))
// Media library (5.1): a 3 MB upload through :8081 (proxy + the manager's nginx)
const M = 'http://127.0.0.1:19081'
const token = await login(M)
const big = new Uint8Array(3 * 1024 * 1024)
crypto.getRandomValues(big.subarray(0, 65536))
const form = new FormData()
form.append('file', new Blob([big], { type: 'image/jpeg' }), 'big.jpg')
const upload = await fetch(`${M}/api/media`, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form })
const refused = await upload.json().catch(() => ({}))
r.check('media: a 3 MB upload reaches the backend through both nginx hops (not 413 from nginx)',
upload.status === 422 && refused?.error?.code === 'media.type', `${upload.status} ${JSON.stringify(refused).slice(0, 120)}`)
const photo = execFileSync('python', ['-c', "import io,sys;from PIL import Image;b=io.BytesIO();Image.new('RGB',(2400,1600),(90,140,60)).save(b,'JPEG');sys.stdout.buffer.write(b.getvalue())"])
const pf = new FormData()
pf.append('file', new Blob([photo], { type: 'image/jpeg' }), 'Horiatiki.jpg')
const item = await (await fetch(`${M}/api/media`, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: pf })).json()
const card = item?.urls ? await fetch(`http://127.0.0.1:19080${item.urls.card}`) : null
r.check('media: a photo gets its sizes, served on :80 with year-long cache headers',
card?.status === 200 && card.headers.get('content-type') === 'image/webp' && /immutable/.test(card.headers.get('cache-control') || ''),
`${card?.status} ${card?.headers.get('cache-control')}`)
// LAN vs not: the proxy joins a second network whose addresses aren't private // LAN vs not: the proxy joins a second network whose addresses aren't private
const proxy = stack.compose('ps', '-q', 'proxy').trim() const proxy = stack.compose('ps', '-q', 'proxy').trim()
docker('network', 'create', '--subnet', '100.64.50.0/24', WAN) docker('network', 'create', '--subnet', '100.64.50.0/24', WAN)
+4
View File
@@ -1,3 +1,7 @@
# Uploads: the media library takes pictures up to 20 MB and videos up to 200 MB
# (local_backend/services/media.py checks the real limits; nginx's default is 1 MB).
client_max_body_size 250m;
server { server {
listen 80; listen 80;