diff --git a/docs/README.md b/docs/README.md index ea5e1b5..a012cee 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,6 +48,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `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`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): 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 a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory | | `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media///` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file//` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` | +| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed | | `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) | | `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` | diff --git a/local_backend/assets/builtin_media/README.md b/local_backend/assets/builtin_media/README.md new file mode 100644 index 0000000..ad98a1a --- /dev/null +++ b/local_backend/assets/builtin_media/README.md @@ -0,0 +1,10 @@ +# Built-in media (plan step 5.4a) + +Pictures placed in this folder ship inside the backend image and are imported into every +venue's media library at start-up as **built-in** items: they show in their own "Built-in" +collection, can be picked anywhere (signage backgrounds, customer display looks, products), and +can't be deleted or renamed by a venue. The display name is the file name without its extension +(underscores and dashes become spaces). + +Only picture files are imported (JPG, PNG, WebP, AVIF, GIF); this README and anything else is +ignored. Removing a file here does not remove it from venues that already have it. diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 217dce1..255ff0a 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -105,6 +105,13 @@ CODES: dict[str, tuple[int, str]] = { "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."), "media.not_a_picture": (422, "Pick a picture here, not a video."), + "signage.playlist_unknown": (404, "Playlist {playlist_id} not found."), + "signage.slide_unknown": (404, "Slide {slide_id} not found."), + "signage.not_a_screen": (404, "Device {device_id} isn't a signage screen."), + "signage.not_a_video": (422, "Pick a video for this slide."), + "signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."), + "signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."), + "media.builtin": (409, "Built-in pictures can't be deleted or renamed."), "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.table_unknown": (404, "Table {table_id} not found."), diff --git a/local_backend/core/modules/device_config.py b/local_backend/core/modules/device_config.py index d856120..d765031 100644 --- a/local_backend/core/modules/device_config.py +++ b/local_backend/core/modules/device_config.py @@ -52,6 +52,9 @@ def _ref_exists(source: str, value: int, db) -> bool: from models.printer import Printer p = db.get(Printer, value) return p is not None and bool(p.is_active) + if source == "signage_playlists": + from models.signage import SignagePlaylist + return db.get(SignagePlaylist, value) is not None if source == "display_looks": from models.display_look import DisplayLook return db.get(DisplayLook, value) is not None diff --git a/local_backend/main.py b/local_backend/main.py index 5f8982e..78384e1 100644 --- a/local_backend/main.py +++ b/local_backend/main.py @@ -54,6 +54,11 @@ async def lifespan(app: FastAPI): _db = SessionLocal() try: apply_retention_setting(_db) + from services.media import import_builtin + try: + import_builtin(_db) # pictures shipped with the server (5.4a) + except Exception as e: # never blocks the start + logger.warning("built-in pictures not imported: %s", e) finally: _db.close() logger.info("startup version=%s", settings.VERSION) diff --git a/local_backend/migrations/versions/0029_signage.py b/local_backend/migrations/versions/0029_signage.py new file mode 100644 index 0000000..891d8ef --- /dev/null +++ b/local_backend/migrations/versions/0029_signage.py @@ -0,0 +1,70 @@ +"""Signage playlists and slides (plan step 5.4a); media.builtin for pictures shipped with the server. + +Revision ID: 0029_signage +Revises: 0028_display_looks +Create Date: 2026-11-17 20:00:00 +""" +from alembic import op +import sqlalchemy as sa +from core.timeutil import UTCDateTime + +revision = '0029_signage' +down_revision = '0028_display_looks' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table('signage_playlists', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('orientation', sa.String(), nullable=False), + sa.Column('transition', sa.String(), nullable=False), + sa.Column('created_at', UTCDateTime(), nullable=False), + sa.Column('updated_at', UTCDateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('signage_playlists', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_signage_playlists_id'), ['id'], unique=False) + + op.create_table('signage_slides', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('playlist_id', sa.Integer(), nullable=False), + sa.Column('position', sa.Integer(), nullable=False), + sa.Column('kind', sa.String(), nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('duration_s', sa.Integer(), nullable=False), + sa.Column('transition', sa.String(), nullable=True), + sa.Column('video_to_end', sa.Boolean(), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False), + sa.Column('days', sa.JSON(), nullable=True), + sa.Column('time_from', sa.String(), nullable=True), + sa.Column('time_to', sa.String(), nullable=True), + sa.Column('date_from', sa.String(), nullable=True), + sa.Column('date_to', sa.String(), nullable=True), + sa.Column('content', sa.JSON(), nullable=False), + sa.ForeignKeyConstraint(['playlist_id'], ['signage_playlists.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('signage_slides', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_signage_slides_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_signage_slides_playlist_id'), ['playlist_id'], unique=False) + + with op.batch_alter_table('media', schema=None) as batch_op: + batch_op.add_column(sa.Column('builtin', sa.Boolean(), server_default='0', nullable=False)) + + + +def downgrade() -> None: + with op.batch_alter_table('media', schema=None) as batch_op: + batch_op.drop_column('builtin') + + with op.batch_alter_table('signage_slides', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_signage_slides_playlist_id')) + batch_op.drop_index(batch_op.f('ix_signage_slides_id')) + + op.drop_table('signage_slides') + with op.batch_alter_table('signage_playlists', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_signage_playlists_id')) + + op.drop_table('signage_playlists') diff --git a/local_backend/models/all.py b/local_backend/models/all.py index a240f20..d15cff7 100644 --- a/local_backend/models/all.py +++ b/local_backend/models/all.py @@ -40,3 +40,4 @@ import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3) import models.refund # noqa: F401 Refund, RefundItem (step 3.3e) import models.media # noqa: F401 Media (media library, step 5.1) import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3) +import models.signage # noqa: F401 SignagePlaylist, SignageSlide (signage, step 5.4a) diff --git a/local_backend/models/media.py b/local_backend/models/media.py index 3369e12..40d7da2 100644 --- a/local_backend/models/media.py +++ b/local_backend/models/media.py @@ -10,7 +10,7 @@ Rows are referenced by id from what uses them (products, the customer display, s 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 sqlalchemy import Boolean, Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from core.timeutil import UTCDateTime, utcnow @@ -32,6 +32,8 @@ class Media(Base): 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) + # Shipped with the server (assets/builtin_media, step 5.4a): can't be deleted or renamed + builtin = Column(Boolean, nullable=False, default=False, server_default='0') uploader = relationship("User", lazy="joined") diff --git a/local_backend/models/signage.py b/local_backend/models/signage.py new file mode 100644 index 0000000..e4bdc84 --- /dev/null +++ b/local_backend/models/signage.py @@ -0,0 +1,53 @@ +"""Digital signage (plan steps 5.4a-5.4d): playlists of slides for TVs. + +A playlist is made for one orientation (the people who build it see the screen's shape) and +holds slides in order. A slide is a menu board, a full-screen picture, a full-screen video or +a text, with its time on screen, its transition and when it may show (days, hours, dates). +What the slide shows is `content`, typed per kind in routers/signage.py (pictures and videos +as media library ids, which the library protects while used). + +A paired signage screen plays the playlist in its device config (`playlist`), in its own +orientation and rotation (modules/signage/manifest.py). +""" +from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String +from sqlalchemy.orm import relationship + +from core.timeutil import UTCDateTime, utcnow +from database import Base + + +class SignagePlaylist(Base): + __tablename__ = "signage_playlists" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String, nullable=False) + orientation = Column(String, nullable=False, default="landscape") # landscape | portrait + transition = Column(String, nullable=False, default="fade") # the slides' default + created_at = Column(UTCDateTime, default=utcnow, nullable=False) + updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False) + + slides = relationship("SignageSlide", back_populates="playlist", cascade="all, delete-orphan", + order_by="SignageSlide.position") + + +class SignageSlide(Base): + __tablename__ = "signage_slides" + + id = Column(Integer, primary_key=True, index=True) + playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="CASCADE"), nullable=False, index=True) + position = Column(Integer, nullable=False, default=0) + kind = Column(String, nullable=False) # menu | image | video | text + name = Column(String, nullable=True) # the timeline's label (optional) + duration_s = Column(Integer, nullable=False, default=10) + transition = Column(String, nullable=True) # None: the playlist's + video_to_end = Column(Boolean, nullable=False, default=False) + enabled = Column(Boolean, nullable=False, default=True) + # When it may show (venue time); empty = always + days = Column(JSON, nullable=True) # [0..6], Monday = 0 + time_from = Column(String, nullable=True) # "HH:MM" + time_to = Column(String, nullable=True) # "HH:MM" (may pass midnight) + date_from = Column(String, nullable=True) # "YYYY-MM-DD" + date_to = Column(String, nullable=True) + content = Column(JSON, nullable=False, default=dict) + + playlist = relationship("SignagePlaylist", back_populates="slides") diff --git a/local_backend/modules/signage/manifest.py b/local_backend/modules/signage/manifest.py index 8343906..9d06b19 100644 --- a/local_backend/modules/signage/manifest.py +++ b/local_backend/modules/signage/manifest.py @@ -1,16 +1,24 @@ """Module manifest — see core/modules/model.py and APPS_PLATFORM §4.""" -from core.modules.model import DeviceApp, Limit, Module, Perm +from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm MODULE = Module( key='signage', kind='app', name='Digital signage', - description='Menus and promotions on TVs (phase 5).', + description='Menus and promotions on TVs: playlists of menu boards, pictures, videos and texts (phase 5, steps 5.4a-5.6c).', permissions=( Perm('signage.manage', 'Edit signage content', roles=('owner', 'store_manager', 'staff_manager')), ), limits=( Limit('devices', 'Number of signage screens', free=0, licensed_default=1), ), - device_app=DeviceApp(login_modes=('none',), scope=()), + routers=( + Mount('routers.signage', '/api/signage'), + ), + device_app=DeviceApp(login_modes=('none',), scope=(), config=( + # What it plays and how the TV hangs (5.4a); the editor builds for the screen's shape + ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'), + ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')), + ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)), + )), ) diff --git a/local_backend/routers/media.py b/local_backend/routers/media.py index e635357..61261d9 100644 --- a/local_backend/routers/media.py +++ b/local_backend/routers/media.py @@ -52,6 +52,7 @@ class MediaOut(BaseModel): uploaded_by: Optional[int] = None uploaded_by_name: Optional[str] = None created_at: datetime + builtin: bool = False urls: dict = Field(default_factory=dict) @@ -100,13 +101,15 @@ def _name_from(filename: str | None) -> str: @router.get("", response_model=MediaPage) def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None, - limit: int = 100, offset: int = 0, + collection: Optional[Literal["builtin", "own"]] = 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()}%")) + if collection: + query = query.filter(Media.builtin.is_(collection == "builtin")) 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() @@ -193,6 +196,8 @@ def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require @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) + if item.builtin: + raise XeniaError("media.builtin") item.name = body.name db.commit() db.refresh(item) @@ -202,6 +207,8 @@ def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), @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) + if item.builtin: + raise XeniaError("media.builtin") 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), diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py new file mode 100644 index 0000000..25663a9 --- /dev/null +++ b/local_backend/routers/signage.py @@ -0,0 +1,490 @@ +"""Digital signage (plan step 5.4a): playlists, slides, screens (models/signage.py). + +Manager side (signage.manage): + GET /api/signage/playlists the playlists (slide count, the screens playing each) + POST /api/signage/playlists {name, orientation, transition} + GET /api/signage/playlists/{id} one, with its slides + PUT /api/signage/playlists/{id} rename, orientation, default transition + DELETE /api/signage/playlists/{id} its screens stop playing it (nothing chosen) + POST /api/signage/playlists/{id}/duplicate a copy with its slides + PUT /api/signage/playlists/{id}/order {slide_ids} the timeline's order + POST /api/signage/playlists/{id}/slides a slide {kind, …} (at the end, or at `position`) + PUT /api/signage/slides/{id} change it + DELETE /api/signage/slides/{id} + POST /api/signage/slides/{id}/duplicate a copy right after it + GET /api/signage/screens the paired screens: playlist, orientation, rotation + PUT /api/signage/screens/{id} {playlist_id, orientation, rotation} + +The screen (a paired device running `signage`, no sign-in): + GET /api/signage/screen its playlist resolved for playing + +Any change sends `signage.changed` only to the screens playing that playlist (a screen's own +settings: `device.updated` plus `signage.changed` to it). A slide's content is typed per kind +(below, extra fields refused); pictures and videos are media library ids, protected while used. +""" +from __future__ import annotations + +import hashlib +import json +from typing import List, Literal, Optional + +from fastapi import APIRouter, Depends, Response +from pydantic import BaseModel, ConfigDict, Field, field_validator +from sqlalchemy.orm import Session + +from core.access.deps import require, require_device +from core.errors import XeniaError +from database import get_db +from models.signage import SignagePlaylist, SignageSlide +from services import media as media_store +from services.ws_bus import broadcast_sync + +router = APIRouter() +KEY = "signage.manage" +HEX = r"^#[0-9a-fA-F]{6}$" +TIME = r"^([01]\d|2[0-3]):[0-5]\d$" +DATE = r"^\d{4}-\d{2}-\d{2}$" +Orientation = Literal["landscape", "portrait"] +Transition = Literal["none", "fade", "slide", "zoom"] +Font = Literal["sans", "serif", "rounded", "condensed", "display"] + + +# ── what a slide shows (typed per kind) ──────────────────────────────────────── + +class _Strict(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class Background(_Strict): + kind: Literal["colour", "media"] = "colour" + colour: str = Field(default="#111827", pattern=HEX) + media_id: Optional[int] = None # a picture (built-in or the venue's) + dim: int = Field(default=0, ge=0, le=80) # % darkening over a photo, for readable text + fit: Literal["cover", "contain"] = "cover" + + +class ImageContent(_Strict): + media_id: Optional[int] = None # a picture + fit: Literal["cover", "contain"] = "cover" + background_colour: str = Field(default="#000000", pattern=HEX) # around a "contain" picture + + +class VideoContent(_Strict): + media_id: Optional[int] = None # a video + fit: Literal["cover", "contain"] = "cover" + muted: bool = True + background_colour: str = Field(default="#000000", pattern=HEX) + + +class TextContent(_Strict): + title: Optional[str] = Field(default=None, max_length=120) + body: Optional[str] = Field(default=None, max_length=1000) + align: Literal["left", "center", "right"] = "center" + vertical: Literal["top", "middle", "bottom"] = "middle" + font: Font = "sans" + text_colour: str = Field(default="#ffffff", pattern=HEX) + text_size: int = Field(default=100, ge=50, le=250) # % + background: Background = Field(default_factory=Background) + + +class MenuContent(_Strict): + """The menu board's look; what it lists comes with step 5.4b.""" + title: Optional[str] = Field(default=None, max_length=120) + font: Font = "sans" + text_colour: str = Field(default="#ffffff", pattern=HEX) + text_size: int = Field(default=100, ge=50, le=250) + background: Background = Field(default_factory=Background) + + +CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent} +Kind = Literal["menu", "image", "video", "text"] + + +# ── requests ─────────────────────────────────────────────────────────────────── + +class PlaylistBody(BaseModel): + name: str = Field(min_length=1, max_length=80) + orientation: Orientation = "landscape" + transition: Transition = "fade" + + +class PlaylistUpdate(BaseModel): + name: Optional[str] = Field(default=None, min_length=1, max_length=80) + orientation: Optional[Orientation] = None + transition: Optional[Transition] = None + + +class SlideFields(BaseModel): + name: Optional[str] = Field(default=None, max_length=80) + duration_s: Optional[int] = Field(default=None, ge=2, le=3600) + transition: Optional[Transition] = None # None: the playlist's + video_to_end: Optional[bool] = None + enabled: Optional[bool] = None + days: Optional[List[int]] = None # [0..6], Monday = 0; [] or None = every day + time_from: Optional[str] = Field(default=None, pattern=TIME) + time_to: Optional[str] = Field(default=None, pattern=TIME) + date_from: Optional[str] = Field(default=None, pattern=DATE) + date_to: Optional[str] = Field(default=None, pattern=DATE) + content: Optional[dict] = None + + @field_validator("days") + @classmethod + def _days(cls, v): + if v is None: + return v + if any(d not in range(7) for d in v): + raise ValueError("days are 0 (Monday) to 6 (Sunday)") + return sorted(set(v)) + + +class SlideCreate(SlideFields): + kind: Kind + position: Optional[int] = Field(default=None, ge=0) + + +class OrderBody(BaseModel): + slide_ids: List[int] + + +class ScreenBody(BaseModel): + playlist_id: Optional[int] = None + orientation: Optional[Orientation] = None + rotation: Optional[Literal[0, 90, 180, 270]] = None + + +# ── helpers ──────────────────────────────────────────────────────────────────── + +def _playlist(db, pid: int) -> SignagePlaylist: + p = db.get(SignagePlaylist, pid) + if p is None: + raise XeniaError("signage.playlist_unknown", playlist_id=pid) + return p + + +def _slide(db, sid: int) -> SignageSlide: + s = db.get(SignageSlide, sid) + if s is None: + raise XeniaError("signage.slide_unknown", slide_id=sid) + return s + + +def media_ids(value) -> list[int]: + """Every media id inside a slide's content (keys `media_id` / `media_ids`, at any depth).""" + out = [] + if isinstance(value, dict): + for k, v in value.items(): + if k == "media_id" and isinstance(v, int): + out.append(v) + elif k == "media_ids" and isinstance(v, list): + out.extend(i for i in v if isinstance(i, int)) + else: + out.extend(media_ids(v)) + elif isinstance(value, list): + for v in value: + out.extend(media_ids(v)) + return out + + +def _content(db, kind: str, raw: dict | None) -> dict: + """The content as stored: typed for its kind, every media id an existing file of the right kind.""" + from pydantic import ValidationError + try: + model = CONTENT[kind](**(raw or {})) + except ValidationError as e: + first = e.errors()[0] + raise XeniaError("signage.content_invalid", field=".".join(str(x) for x in first["loc"]), reason=first["msg"]) + data = model.model_dump() + from models.media import Media + for mid in media_ids(data): + m = db.get(Media, mid) + if m is None: + raise XeniaError("media.not_found", media_id=mid) + # the main media of a picture / video slide must be that kind; backgrounds are pictures + main = data.get("media_id") + if main is not None: + m = db.get(Media, main) + if kind == "video" and m.kind != "video": + raise XeniaError("signage.not_a_video") + if kind != "video" and m.kind != "image": + raise XeniaError("media.not_a_picture") + bg = (data.get("background") or {}).get("media_id") + if bg is not None and db.get(Media, bg).kind != "image": + raise XeniaError("media.not_a_picture") + return data + + +def _apply(db, slide: SignageSlide, body: SlideFields) -> None: + sent = body.model_fields_set + for key in ("name", "duration_s", "transition", "video_to_end", "enabled", "days", "time_from", "time_to", "date_from", "date_to"): + if key in sent: + value = getattr(body, key) + if key in ("duration_s", "video_to_end", "enabled") and value is None: + continue + if key == "days" and value == []: + value = None + if key == "name" and value is not None: + value = value.strip() or None + setattr(slide, key, value) + if "content" in sent: + slide.content = _content(db, slide.kind, body.content) + + +def _screens(db): + from models.device import Device + return db.query(Device).filter(Device.app_key == "signage", Device.revoked_at.is_(None)).order_by(Device.name).all() + + +def _screen_config(dev) -> dict: + from core.modules.device_config import effective, for_app + return effective(for_app("signage"), dev.config) + + +def _screens_playing(db, playlist_id: int) -> list[int]: + return [d.id for d in _screens(db) if _screen_config(d).get("playlist") == playlist_id] + + +def _tell(ids: list[int]) -> None: + if ids: + broadcast_sync("signage.changed", {}, device_ids=sorted(set(ids))) + + +def _slide_out(s: SignageSlide) -> dict: + return {"id": s.id, "kind": s.kind, "name": s.name, "position": s.position, "duration_s": s.duration_s, + "transition": s.transition, "video_to_end": bool(s.video_to_end), "enabled": bool(s.enabled), + "days": s.days or [], "time_from": s.time_from, "time_to": s.time_to, "date_from": s.date_from, "date_to": s.date_to, + "content": s.content or {}} + + +def _playlist_out(db, p: SignagePlaylist, slides: bool = False) -> dict: + playing = set(_screens_playing(db, p.id)) + out = {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, + "slide_count": len(p.slides), "screens": [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in playing]} + if slides: + out["slides"] = [_slide_out(s) for s in p.slides] + out["media"] = _media_map(db, [i for s in p.slides for i in media_ids(s.content or {})]) + return out + + +def _media_map(db, ids) -> dict: + """{media id: what a screen or the editor needs to show it} for these ids.""" + from models.media import Media + ids = sorted({i for i in ids if i}) + out = {} + for m in (db.query(Media).filter(Media.id.in_(ids)).all() if ids else []): + urls = media_store.urls(m) + out[str(m.id)] = {"id": m.id, "kind": m.kind, "name": m.name, "width": m.width, "height": m.height, + "duration_ms": m.duration_ms, "url": urls.get("full") or urls["original"], + "thumb": urls.get("thumb"), "builtin": bool(m.builtin)} + return out + + +def _renumber(p: SignagePlaylist) -> None: + for i, s in enumerate(sorted(p.slides, key=lambda x: (x.position, x.id))): + s.position = i + + +def _uses(db, media_id: int) -> list: + out = [] + for s in db.query(SignageSlide).order_by(SignageSlide.playlist_id, SignageSlide.position): + if media_id in media_ids(s.content or {}): + out.append({"id": s.id, "name": f"{s.playlist.name} · {s.name or s.position + 1}"}) + return out + + +media_store.register_usage("signage_slide", _uses) + + +# ── playlists ────────────────────────────────────────────────────────────────── + +@router.get("/playlists") +def list_playlists(db: Session = Depends(get_db), user=Depends(require(KEY))): + return [_playlist_out(db, p) for p in db.query(SignagePlaylist).order_by(SignagePlaylist.name)] + + +@router.post("/playlists", status_code=201) +def create_playlist(body: PlaylistBody, db: Session = Depends(get_db), user=Depends(require(KEY))): + p = SignagePlaylist(name=body.name.strip(), orientation=body.orientation, transition=body.transition) + db.add(p) + db.commit() + db.refresh(p) + return _playlist_out(db, p, slides=True) + + +@router.get("/playlists/{playlist_id}") +def get_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): + return _playlist_out(db, _playlist(db, playlist_id), slides=True) + + +@router.put("/playlists/{playlist_id}") +def update_playlist(playlist_id: int, body: PlaylistUpdate, db: Session = Depends(get_db), user=Depends(require(KEY))): + p = _playlist(db, playlist_id) + if body.name is not None: + p.name = body.name.strip() + if body.orientation is not None: + p.orientation = body.orientation + if body.transition is not None: + p.transition = body.transition + db.commit() + _tell(_screens_playing(db, p.id)) + return _playlist_out(db, p, slides=True) + + +@router.delete("/playlists/{playlist_id}", status_code=204) +def delete_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): + p = _playlist(db, playlist_id) + stopped = [] + for d in _screens(db): + if (d.config or {}).get("playlist") == p.id: + d.config = {**(d.config or {}), "playlist": None} + stopped.append(d.id) + db.delete(p) + db.commit() + _tell(stopped) + return Response(status_code=204) + + +@router.post("/playlists/{playlist_id}/duplicate", status_code=201) +def duplicate_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): + p = _playlist(db, playlist_id) + copy = SignagePlaylist(name=f"{p.name} (2)"[:80], orientation=p.orientation, transition=p.transition) + db.add(copy) + db.flush() + for s in p.slides: + db.add(_copy_slide(s, copy.id, s.position)) + db.commit() + db.refresh(copy) + return _playlist_out(db, copy, slides=True) + + +@router.put("/playlists/{playlist_id}/order") +def order_slides(playlist_id: int, body: OrderBody, db: Session = Depends(get_db), user=Depends(require(KEY))): + p = _playlist(db, playlist_id) + mine = {s.id: s for s in p.slides} + if sorted(body.slide_ids) != sorted(mine): + raise XeniaError("signage.order_mismatch") + for i, sid in enumerate(body.slide_ids): + mine[sid].position = i + db.commit() + db.refresh(p) + _tell(_screens_playing(db, p.id)) + return _playlist_out(db, p, slides=True) + + +# ── slides ───────────────────────────────────────────────────────────────────── + +def _copy_slide(s: SignageSlide, playlist_id: int, position: int) -> SignageSlide: + return SignageSlide(playlist_id=playlist_id, position=position, kind=s.kind, name=s.name, duration_s=s.duration_s, + transition=s.transition, video_to_end=s.video_to_end, enabled=s.enabled, days=s.days, + time_from=s.time_from, time_to=s.time_to, date_from=s.date_from, date_to=s.date_to, + content=json.loads(json.dumps(s.content or {}))) + + +@router.post("/playlists/{playlist_id}/slides", status_code=201) +def add_slide(playlist_id: int, body: SlideCreate, db: Session = Depends(get_db), user=Depends(require(KEY))): + p = _playlist(db, playlist_id) + at = len(p.slides) if body.position is None else min(body.position, len(p.slides)) + for s in p.slides: + if s.position >= at: + s.position += 1 + slide = SignageSlide(playlist_id=p.id, kind=body.kind, position=at, duration_s=10, enabled=True, + content=_content(db, body.kind, None)) + _apply(db, slide, body) + if body.kind == "video" and "video_to_end" not in body.model_fields_set: + slide.video_to_end = True + db.add(slide) + db.commit() + db.refresh(p) + _tell(_screens_playing(db, p.id)) + return _slide_out(slide) + + +@router.put("/slides/{slide_id}") +def update_slide(slide_id: int, body: SlideFields, db: Session = Depends(get_db), user=Depends(require(KEY))): + slide = _slide(db, slide_id) + _apply(db, slide, body) + db.commit() + db.refresh(slide) + _tell(_screens_playing(db, slide.playlist_id)) + return _slide_out(slide) + + +@router.delete("/slides/{slide_id}", status_code=204) +def delete_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): + slide = _slide(db, slide_id) + p = slide.playlist + db.delete(slide) + db.flush() + db.refresh(p) + _renumber(p) + db.commit() + _tell(_screens_playing(db, p.id)) + return Response(status_code=204) + + +@router.post("/slides/{slide_id}/duplicate", status_code=201) +def duplicate_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): + slide = _slide(db, slide_id) + p = slide.playlist + for s in p.slides: + if s.position > slide.position: + s.position += 1 + copy = _copy_slide(slide, p.id, slide.position + 1) + db.add(copy) + db.commit() + db.refresh(copy) + _tell(_screens_playing(db, p.id)) + return _slide_out(copy) + + +# ── screens ──────────────────────────────────────────────────────────────────── + +def _screen_out(db, d) -> dict: + cfg = _screen_config(d) + p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None + return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None, + "orientation": cfg["orientation"], "rotation": cfg["rotation"], + "orientation_mismatch": bool(p and p.orientation != cfg["orientation"])} + + +@router.get("/screens") +def list_screens(db: Session = Depends(get_db), user=Depends(require(KEY))): + return [_screen_out(db, d) for d in _screens(db)] + + +@router.put("/screens/{device_id}") +def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db), user=Depends(require(KEY))): + from core.modules.device_config import for_app, validate + from models.device import Device + d = db.get(Device, device_id) + if d is None or d.app_key != "signage" or d.revoked_at is not None: + raise XeniaError("signage.not_a_screen", device_id=device_id) + cfg = dict(d.config or {}) + for key in body.model_fields_set: + cfg[{"playlist_id": "playlist"}.get(key, key)] = getattr(body, key) + d.config = validate(for_app("signage"), cfg, db) + db.commit() + broadcast_sync("device.updated", {}, device_ids=[d.id]) + _tell([d.id]) + return _screen_out(db, d) + + +# ── the screen itself ────────────────────────────────────────────────────────── + +@router.get("/screen") +def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))): + """What this screen plays: its settings and its playlist with every slide and media address. + Slides that are off are left out; time windows are the player's (it keeps playing offline). + `version` changes whenever anything here does (the player's cache key).""" + cfg = _screen_config(dev) + p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None + playlist = None + if p is not None: + slides = [_slide_out(s) for s in p.slides if s.enabled] + for s in slides: + s["transition"] = s["transition"] or p.transition + playlist = {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides, + "media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])} + out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]}, + "playlist": playlist} + out["version"] = hashlib.sha256(json.dumps(out, sort_keys=True, default=str).encode()).hexdigest()[:16] + return out diff --git a/local_backend/services/media.py b/local_backend/services/media.py index 5ff0eb7..077b577 100644 --- a/local_backend/services/media.py +++ b/local_backend/services/media.py @@ -334,3 +334,46 @@ def uses(db, media_id: int) -> list[dict]: for u in fn(db, media_id) or (): found.append({"kind": kind, **u}) return found + + +# ── built-in pictures (shipped with the server, step 5.4a) ────────────────── + +BUILTIN_DIR = os.environ.get("XENIA_BUILTIN_MEDIA_DIR", + os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "builtin_media")) +_PICTURE_EXT = (".jpg", ".jpeg", ".png", ".webp", ".avif", ".gif") + + +def import_builtin(db, folder: str | None = None) -> int: + """Bring the built-in pictures into the library (start-up). Already there (same bytes) → marked + built-in. Returns how many were added. A file that can't be read is logged and skipped.""" + import logging + from models.media import Media + log = logging.getLogger("xenia.media") + folder = folder or BUILTIN_DIR + try: + names = sorted(n for n in os.listdir(folder) if n.lower().endswith(_PICTURE_EXT)) + except FileNotFoundError: + return 0 + added = 0 + for n in names: + path = os.path.join(folder, n) + try: + sha, size, info = ingest_path(path) + except Exception as e: # refused or unreadable + log.warning("built-in picture %s skipped (%s)", n, getattr(e, "code", e)) + continue + row = db.query(Media).filter(Media.sha256 == sha).first() + if row is not None: + if not row.builtin: + row.builtin = True + continue + if not info: # files there but no row (an earlier failed start) + delete_files(sha) + sha, size, info = ingest_path(path) + stem = os.path.splitext(n)[0].replace("_", " ").replace("-", " ").strip() + db.add(Media(name=(stem or "picture")[:120], original_name=n, sha256=sha, bytes=size, builtin=True, **info)) + added += 1 + db.commit() + if added: + log.info("built-in pictures added to the library: %d", added) + return added diff --git a/local_backend/tests/test_signage.py b/local_backend/tests/test_signage.py new file mode 100644 index 0000000..857e2d8 --- /dev/null +++ b/local_backend/tests/test_signage.py @@ -0,0 +1,176 @@ +"""Digital signage, playlists and slides (plan step 5.4a): playlists for an orientation, picture / +video / text / menu slides with their timing and windows, a screen's playlist resolved for playing, +changes told only to the screens playing them, built-in pictures.""" +import pytest + +from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures) +from tests.test_media import jpeg, media_dir, mp4, up # noqa: F401 (fixture + helpers) + + +@pytest.fixture +def sent(monkeypatch): + import routers.signage as sg + got = [] + monkeypatch.setattr(sg, "broadcast_sync", lambda kind, data, **kw: got.append((kind, kw.get("device_ids")))) + return got + + +@pytest.fixture +def screens(pair): + out = {} + for n in (1, 2): + token, r = pair("signage", f"TV {n}") + assert r.status_code == 201, r.text + out[n] = {"h": {"X-Xenia-Device": token}, "id": r.json()["id"]} + return out + + +def playlist(client, h, name="Promos", **kw): + r = client.post("/api/signage/playlists", headers=h, json={"name": name, **kw}) + assert r.status_code == 201, r.text + return r.json() + + +def slide(client, h, pid, kind, **body): + r = client.post(f"/api/signage/playlists/{pid}/slides", headers=h, json={"kind": kind, **body}) + assert r.status_code == 201, r.text + return r.json() + + +def test_a_screen_plays_its_playlist_in_order(client, owner_h, screens, sent): + """Done when (5.4a): picture, video and text slides reach a paired screen in order.""" + pic, vid, bg = up(client, owner_h, jpeg(1920, 1080)).json(), up(client, owner_h, mp4(), name="v.mp4", ctype="video/mp4").json(), \ + up(client, owner_h, jpeg(1920, 1080, (9, 9, 9))).json() + p = playlist(client, owner_h, orientation="landscape", transition="fade") + s1 = slide(client, owner_h, p["id"], "image", content={"media_id": pic["id"]}, duration_s=8) + s2 = slide(client, owner_h, p["id"], "video", content={"media_id": vid["id"]}) + s3 = slide(client, owner_h, p["id"], "text", transition="zoom", + content={"title": "Happy hour", "body": "17:00-19:00", "background": {"kind": "media", "media_id": bg["id"], "dim": 40}}) + assert s2["video_to_end"] is True and s1["video_to_end"] is False + assert client.get(f"/api/signage/screen", headers=screens[1]["h"]).json()["playlist"] is None # nothing chosen yet + r = client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": p["id"]}) + assert r.status_code == 200 and r.json()["playlist_name"] == "Promos" and r.json()["orientation"] == "landscape" + got = client.get("/api/signage/screen", headers=screens[1]["h"]).json() + pl = got["playlist"] + assert [s["id"] for s in pl["slides"]] == [s1["id"], s2["id"], s3["id"]] + assert [s["transition"] for s in pl["slides"]] == ["fade", "fade", "zoom"] # the playlist's default + assert pl["media"][str(pic["id"])]["url"] == pic["urls"]["full"] and pl["media"][str(vid["id"])]["url"] == vid["urls"]["original"] + assert pl["media"][str(bg["id"])]["kind"] == "image" and pl["slides"][2]["content"]["background"]["dim"] == 40 + assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0} + assert len(got["version"]) == 16 + + +def test_changes_reach_only_the_screens_playing_them(client, owner_h, screens, sent): + a, b = playlist(client, owner_h, "A"), playlist(client, owner_h, "B") + x = slide(client, owner_h, a["id"], "text", content={"title": "x"}) + y = slide(client, owner_h, a["id"], "text", content={"title": "y"}) + client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": a["id"]}) + client.put(f"/api/signage/screens/{screens[2]['id']}", headers=owner_h, json={"playlist_id": b["id"]}) + before = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["version"] + sent.clear() + r = client.put(f"/api/signage/playlists/{a['id']}/order", headers=owner_h, json={"slide_ids": [y["id"], x["id"]]}) + assert [s["id"] for s in r.json()["slides"]] == [y["id"], x["id"]] + assert sent == [("signage.changed", [screens[1]["id"]])] + after = client.get("/api/signage/screen", headers=screens[1]["h"]) + assert [s["content"]["title"] for s in after.json()["playlist"]["slides"]] == ["y", "x"] and after.json()["version"] != before + sent.clear() + client.put(f"/api/signage/slides/{x['id']}", headers=owner_h, json={"enabled": False}) + assert sent == [("signage.changed", [screens[1]["id"]])] + assert [s["id"] for s in client.get("/api/signage/screen", headers=screens[1]["h"]).json()["playlist"]["slides"]] == [y["id"]] + assert err(client.put(f"/api/signage/playlists/{a['id']}/order", headers=owner_h, json={"slide_ids": [y["id"]]})) == "signage.order_mismatch" + + +def test_slides_are_typed_and_checked(client, owner_h): + pic, vid = up(client, owner_h, jpeg(800, 600)).json(), up(client, owner_h, mp4(), name="v.mp4", ctype="video/mp4").json() + p = playlist(client, owner_h) + url = f"/api/signage/playlists/{p['id']}/slides" + assert err(client.post(url, headers=owner_h, json={"kind": "image", "content": {"media_id": vid["id"]}})) == "media.not_a_picture" + assert err(client.post(url, headers=owner_h, json={"kind": "video", "content": {"media_id": pic["id"]}})) == "signage.not_a_video" + assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"background": {"kind": "media", "media_id": vid["id"]}}})) == "media.not_a_picture" + assert err(client.post(url, headers=owner_h, json={"kind": "image", "content": {"media_id": 99999}})) == "media.not_found" + r = client.post(url, headers=owner_h, json={"kind": "text", "content": {"text_colour": "red"}}) + assert err(r) == "signage.content_invalid" and r.json()["error"]["params"]["field"] == "text_colour" + assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"sparkles": True}})) == "signage.content_invalid" + assert client.post(url, headers=owner_h, json={"kind": "dance"}).status_code == 422 + assert client.post(url, headers=owner_h, json={"kind": "text", "time_from": "25:00"}).status_code == 422 + assert client.post(url, headers=owner_h, json={"kind": "text", "days": [7]}).status_code == 422 + s = slide(client, owner_h, p["id"], "text", days=[4, 5, 5], time_from="12:00", time_to="15:00", date_to="2026-12-31", + content={"title": "Lunch menu", "font": "serif", "text_size": 140}) + assert s["days"] == [4, 5] and s["time_from"] == "12:00" and s["date_to"] == "2026-12-31" + assert s["content"]["background"] == {"kind": "colour", "colour": "#111827", "media_id": None, "dim": 0, "fit": "cover"} + r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"days": [], "time_from": None}) + assert r.json()["days"] == [] and r.json()["time_from"] is None and r.json()["time_to"] == "15:00" + menu = slide(client, owner_h, p["id"], "menu", content={"title": "Our menu"}) + assert menu["content"]["title"] == "Our menu" + + +def test_duplicates_positions_and_deleting(client, owner_h, screens, sent): + p = playlist(client, owner_h) + a = slide(client, owner_h, p["id"], "text", content={"title": "a"}) + b = slide(client, owner_h, p["id"], "text", content={"title": "b"}) + first = slide(client, owner_h, p["id"], "text", content={"title": "first"}, position=0) + copy = client.post(f"/api/signage/slides/{a['id']}/duplicate", headers=owner_h).json() + titles = lambda pid: [s["content"]["title"] for s in client.get(f"/api/signage/playlists/{pid}", headers=owner_h).json()["slides"]] # noqa: E731 + assert titles(p["id"]) == ["first", "a", "a", "b"] and copy["id"] != a["id"] + client.delete(f"/api/signage/slides/{first['id']}", headers=owner_h) + got = client.get(f"/api/signage/playlists/{p['id']}", headers=owner_h).json()["slides"] + assert [s["position"] for s in got] == [0, 1, 2] and [s["content"]["title"] for s in got] == ["a", "a", "b"] + dup = client.post(f"/api/signage/playlists/{p['id']}/duplicate", headers=owner_h).json() + assert dup["name"] == "Promos (2)" and titles(dup["id"]) == ["a", "a", "b"] + client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": p["id"]}) + sent.clear() + assert client.delete(f"/api/signage/playlists/{p['id']}", headers=owner_h).status_code == 204 + assert sent == [("signage.changed", [screens[1]["id"]])] + assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["playlist"] is None + assert b["id"] and err(client.get(f"/api/signage/playlists/{p['id']}", headers=owner_h)) == "signage.playlist_unknown" + + +def test_a_screens_shape_and_the_playlists(client, owner_h, screens): + tall = playlist(client, owner_h, "Tall menu", orientation="portrait") + r = client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": tall["id"], "rotation": 90}) + assert r.json()["orientation_mismatch"] is True and r.json()["rotation"] == 90 + r = client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"orientation": "portrait"}) + assert r.json()["orientation_mismatch"] is False and r.json()["playlist_id"] == tall["id"] + assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["screen"]["orientation"] == "portrait" + assert [s["name"] for s in client.get("/api/signage/playlists", headers=owner_h).json()[0]["screens"]] == ["TV 1"] + assert err(client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": 99999})) == "validation.device_config" + assert client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"rotation": 45}).status_code == 422 + # the Devices page edits the same settings + assert client.patch(f"/api/devices/{screens[2]['id']}", headers=owner_h, json={"config": {"playlist": tall["id"], "orientation": "portrait"}}).status_code == 200 + assert [s["playlist_id"] for s in client.get("/api/signage/screens", headers=owner_h).json() if s["id"] == screens[2]["id"]] == [tall["id"]] + + +def test_media_in_a_slide_cant_be_deleted(client, owner_h): + pic = up(client, owner_h, jpeg(640, 360)).json() + p = playlist(client, owner_h, "Window") + s = slide(client, owner_h, p["id"], "text", name="Opening", content={"background": {"kind": "media", "media_id": pic["id"]}}) + r = client.delete(f"/api/media/{pic['id']}", headers=owner_h) + assert r.status_code == 409 and r.json()["error"]["params"]["used_by"] == [{"kind": "signage_slide", "id": s["id"], "name": "Window · Opening"}] + + +def test_built_in_pictures(client, db, owner_h, tmp_path): + from services import media as store + folder = tmp_path / "builtin" + folder.mkdir() + (folder / "wood_table.jpg").write_bytes(jpeg(1200, 800, (120, 80, 40))) + (folder / "README.md").write_text("not a picture") + (folder / "broken.png").write_bytes(b"nope") + assert store.import_builtin(db, str(folder)) == 1 + assert store.import_builtin(db, str(folder)) == 0 # once + lib = client.get("/api/media?collection=builtin", headers=owner_h).json() + assert [(i["name"], i["builtin"]) for i in lib["items"]] == [("wood table", True)] + assert client.get("/api/media?collection=own", headers=owner_h).json()["total"] == 0 + bid = lib["items"][0]["id"] + assert err(client.delete(f"/api/media/{bid}", headers=owner_h)) == "media.builtin" + assert err(client.patch(f"/api/media/{bid}", headers=owner_h, json={"name": "mine"})) == "media.builtin" + # the same picture uploaded by the venue is the built-in one + again = up(client, owner_h, (folder / "wood_table.jpg").read_bytes()).json() + assert again["existing"] is True and again["builtin"] is True + + +def test_who_may(client, make_user, login, screens, pair): + waiter = login(make_user(role="waiter")) + assert client.get("/api/signage/playlists", headers=waiter).status_code == 403 + token, _ = pair("kds", "Kitchen") + assert err(client.get("/api/signage/screen", headers={"X-Xenia-Device": token})) == "device.out_of_scope" + assert err(client.get("/api/signage/screen")) == "device.not_paired" diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index b48c57f..7fdcffc 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -134,9 +134,18 @@ "too_many_pixels": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mp}} megapixel).", "unreadable": "Αυτή η εικόνα δεν διαβάζεται. Αποθηκεύστε τη ξανά ως JPG ή PNG και ανεβάστε τη.", "in_use": "Αυτό το αρχείο χρησιμοποιείται από: {{uses}}. Αφαιρέστε το πρώτα από εκεί.", - "not_a_picture": "Εδώ διαλέξτε εικόνα, όχι βίντεο." + "not_a_picture": "Εδώ διαλέξτε εικόνα, όχι βίντεο.", + "builtin": "Οι ενσωματωμένες εικόνες δεν διαγράφονται ούτε μετονομάζονται." }, "caller_id": { "key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος." + }, + "signage": { + "playlist_unknown": "Η λίστα {{playlist_id}} δεν βρέθηκε.", + "slide_unknown": "Η διαφάνεια {{slide_id}} δεν βρέθηκε.", + "not_a_screen": "Η συσκευή {{device_id}} δεν είναι οθόνη προβολής.", + "not_a_video": "Διαλέξτε βίντεο για αυτή τη διαφάνεια.", + "content_invalid": "Μια ρύθμιση της διαφάνειας δεν είναι έγκυρη ({{field}}: {{reason}}).", + "order_mismatch": "Η λίστα άλλαξε στο μεταξύ. Φορτώστε τη ξανά και δοκιμάστε πάλι." } } diff --git a/packages/i18n/locales/el/modules.json b/packages/i18n/locales/el/modules.json index 0a81fb2..1e827a9 100644 --- a/packages/i18n/locales/el/modules.json +++ b/packages/i18n/locales/el/modules.json @@ -386,6 +386,31 @@ }, "permissions": { "manage": "Επεξεργασία περιεχομένου σήμανσης" + }, + "config": { + "playlist": { + "label": "Λίστα προβολής", + "hint": "Τι παίζει αυτή η οθόνη (Προβολή).", + "none": "Τίποτα (κενή οθόνη)" + }, + "orientation": { + "label": "Προσανατολισμός", + "hint": "Πώς κρέμεται η τηλεόραση: οι διαφάνειες φτιάχνονται για αυτό το σχήμα.", + "choices": { + "landscape": "Οριζόντια (φαρδιά)", + "portrait": "Κάθετη (ψηλή)" + } + }, + "rotation": { + "label": "Περιστροφή εικόνας", + "hint": "Για τηλεόραση τοποθετημένη πλάγια που δεν γυρίζει μόνη της την εικόνα.", + "choices": { + "0": "Όχι", + "90": "90° δεξιά", + "180": "Ανάποδα", + "270": "90° αριστερά" + } + } } }, "staff_planning": { diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 1cb67a5..102cf17 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -134,9 +134,18 @@ "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.", - "not_a_picture": "Pick a picture here, not a video." + "not_a_picture": "Pick a picture here, not a video.", + "builtin": "Built-in pictures can't be deleted or renamed." }, "caller_id": { "key_invalid": "The phone system's key is missing or wrong." + }, + "signage": { + "playlist_unknown": "Playlist {{playlist_id}} not found.", + "slide_unknown": "Slide {{slide_id}} not found.", + "not_a_screen": "Device {{device_id}} isn't a signage screen.", + "not_a_video": "Pick a video for this slide.", + "content_invalid": "This slide's setting isn't valid ({{field}}: {{reason}}).", + "order_mismatch": "The playlist changed in the meantime. Reload it and try again." } } diff --git a/packages/i18n/locales/en/modules.json b/packages/i18n/locales/en/modules.json index 593b5d6..02c243a 100644 --- a/packages/i18n/locales/en/modules.json +++ b/packages/i18n/locales/en/modules.json @@ -386,6 +386,31 @@ }, "permissions": { "manage": "Edit signage content" + }, + "config": { + "playlist": { + "label": "Playlist", + "hint": "What this screen plays (Signage).", + "none": "Nothing (a blank screen)" + }, + "orientation": { + "label": "Orientation", + "hint": "How the TV hangs: slides are built for this shape.", + "choices": { + "landscape": "Landscape (wide)", + "portrait": "Portrait (tall)" + } + }, + "rotation": { + "label": "Turn the picture", + "hint": "For a TV mounted sideways that can't turn the picture itself.", + "choices": { + "0": "No", + "90": "90° right", + "180": "Upside down", + "270": "90° left" + } + } } }, "staff_planning": {