Folded under each widget card like Text and colours. The TV puts them on the element that places the widget (fx), animations on translate / scale so its place's transform stays (an older TV only fades); an entrance animates to the widget's own opacity. Calibrating: a strict-mode remount no longer ends it. Plan 6R.17, F-115. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1648 lines
75 KiB
Python
1648 lines
75 KiB
Python
"""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/library the Slides library (2026-11-21): kept slides
|
||
POST /api/signage/library {name, description, orientation, kind, …slide fields}
|
||
GET /api/signage/library/{id} one (a menu board resolved for its preview)
|
||
PUT /api/signage/library/{id} change it (a screen showing it is told)
|
||
DELETE /api/signage/library/{id} screens that had it as their default show nothing
|
||
POST /api/signage/library/{id}/duplicate a copy
|
||
GET /api/signage/reviews the venue's reviews (6R.19); PUT: all of them at once
|
||
GET /api/signage/screens the paired screens: playlist or slide, orientation, rotation,
|
||
picture area (insets), fit, the window size it reported
|
||
PUT /api/signage/screens/{id} {playlist_id | slide_id, orientation, rotation, area_*, fit}
|
||
POST /api/signage/screens/{id}/calibrate {on} the TV outlines its picture area (6R.13)
|
||
|
||
The screen (a paired device running `signage`, no sign-in):
|
||
GET /api/signage/screen its playlist resolved for playing
|
||
POST /api/signage/screen/viewport {width, height, ratio} its window (for calibrating)
|
||
|
||
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 Dict, List, Literal, Optional
|
||
|
||
from fastapi import APIRouter, Depends, Response
|
||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_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, SignageSavedSlide, SignageScheduleItem, SignageSlide
|
||
from services import media as media_store
|
||
from services import video as video_store
|
||
from services.ws_bus import broadcast_sync
|
||
|
||
router = APIRouter()
|
||
KEY = "signage.manage"
|
||
MESSAGE = "signage.message"
|
||
REVIEWS = "signage.reviews" # the venue's reviews, typed in by hand (6R.19)
|
||
MAX_WIDGETS = "signage.max_widgets" # widgets a slide may hold (owner review 6: Performance; 10 recommended)
|
||
MAX_WIDGETS_CAP = 50 # never more, whatever the setting
|
||
AREA_MAX = 4000 # px a screen's picture area may cut off one edge (6R.13)
|
||
AREA_KEYS = ("area_left", "area_top", "area_right", "area_bottom")
|
||
CALIBRATE_S = 15 * 60 # a calibration nobody ends stops by itself
|
||
_viewports: dict = {} # device id → {width, height, ratio} (what the TV reported; memory only)
|
||
_calibrating: dict = {} # device id → when calibration started (monotonic)
|
||
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$" # #rrggbb, or #rrggbbaa (see-through, 2026-11-21)
|
||
TIME = r"^([01]\d|2[0-3]):[0-5]\d$"
|
||
DATE = r"^\d{4}-\d{2}-\d{2}$"
|
||
Orientation = Literal["landscape", "portrait"]
|
||
ASPECT = r"^\d{1,2}:\d{1,2}$" # a custom shape "21:9" (6R.13), from 1:4 to 4:1
|
||
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"
|
||
|
||
|
||
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack",
|
||
"shape", "ticker", "countdown", "hours", "wifi", "contact", # 6R.15
|
||
"reviews", "gallery"] # 6R.19, 6R.16
|
||
WHEN = r"^(\d{4}-\d{2}-\d{2}T)?([01]\d|2[0-3]):[0-5]\d$" # a countdown's moment: "HH:MM" (every day) or "YYYY-MM-DDTHH:MM"
|
||
ContactKey = Literal["phone", "phone2", "email", "address", "website", "google", "facebook", "instagram", "tiktok", "tripadvisor", "whatsapp", "viber"]
|
||
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
|
||
|
||
|
||
BADGE_KEY = r"^[a-z0-9][a-z0-9_-]{0,23}$" # a badge of the venue's list (services/signage_badges.py)
|
||
Align = Literal["left", "center", "right"]
|
||
|
||
|
||
class TextStyle(_Strict):
|
||
"""How a menu's headings, product names or prices look (owner review 3, 2026-11-21). Empty
|
||
values follow the board: its text size and font, the text colour (names) or the accent colour
|
||
(headings, prices)."""
|
||
size: Optional[int] = Field(default=None, ge=50, le=300) # % like the board's text size
|
||
colour: Optional[str] = Field(default=None, pattern=HEX)
|
||
font: Optional[Font] = None
|
||
bold: bool = True
|
||
italic: bool = False
|
||
underline: bool = False
|
||
align: Optional[Align] = None # None: names left, prices right, headings as the list
|
||
|
||
|
||
class DotStyle(_Strict):
|
||
"""The line between a product's name and its price."""
|
||
size: int = Field(default=100, ge=50, le=300)
|
||
colour: Optional[str] = Field(default=None, pattern=HEX) # None: the text colour, faint
|
||
style: Literal["dotted", "dashed", "solid", "none"] = "dotted"
|
||
|
||
|
||
def _names(v: dict) -> dict:
|
||
if any(not k.isdigit() for k in v):
|
||
raise ValueError("names are keyed by id")
|
||
out = {k: " ".join(str(x).split())[:80] for k, x in v.items()}
|
||
return {k: x for k, x in out.items() if x}
|
||
|
||
|
||
class MenuList(_Strict):
|
||
"""What a menu board lists and how its lines look (5.4b): services/signage_menu.py resolves it.
|
||
A menu slide (MenuContent) adds its background, widgets and width; a menu widget (2026-11-21)
|
||
carries one as its `board`."""
|
||
title: Optional[str] = Field(default=None, max_length=120)
|
||
# what it lists
|
||
select: Literal["all", "custom"] = "custom"
|
||
category_ids: List[int] = Field(default_factory=list, max_length=200) # whole categories (live)
|
||
product_ids: List[int] = Field(default_factory=list, max_length=1000) # single products
|
||
exclude_ids: List[int] = Field(default_factory=list, max_length=1000)
|
||
group_by_category: bool = True
|
||
category_titles: bool = True # a heading over each group
|
||
category_order: List[int] = Field(default_factory=list, max_length=200) # the board's own order
|
||
product_order: List[int] = Field(default_factory=list, max_length=1000)
|
||
# what each line shows
|
||
sales_point: Optional[str] = "in_store" # whose prices; None = no prices
|
||
show_photos: bool = False
|
||
show_descriptions: bool = False
|
||
badges: Dict[str, List[str]] = Field(default_factory=dict) # product id → its badges (keys of the venue's list; up to 4)
|
||
sold_out: Literal["strike", "hide"] = "strike"
|
||
language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed
|
||
# pages (the player pages through what doesn't fit, 5.5b)
|
||
columns: int = Field(default=2, ge=1, le=3)
|
||
page_size: Optional[int] = Field(default=None, ge=3, le=60) # items per page; None = as many as fit
|
||
page_seconds: int = Field(default=10, ge=1, le=120)
|
||
font: Font = "sans"
|
||
text_colour: str = Field(default="#ffffff", pattern=HEX)
|
||
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # page dots; headings and prices until their own
|
||
badge_colour: Optional[str] = Field(default=None, pattern=HEX) # None: each badge its own (the venue's list)
|
||
badge_text_colour: Optional[str] = Field(default=None, pattern=HEX) # None: each badge its own (else white / black)
|
||
text_size: int = Field(default=100, ge=50, le=250)
|
||
# the look of each part (owner review 3, 2026-11-21)
|
||
heading_style: TextStyle = Field(default_factory=TextStyle)
|
||
item_style: TextStyle = Field(default_factory=TextStyle)
|
||
price_style: TextStyle = Field(default_factory=TextStyle)
|
||
dot_style: DotStyle = Field(default_factory=DotStyle)
|
||
line_height: Optional[float] = Field(default=None, ge=0.8, le=3) # × the text; None = auto
|
||
letter_spacing: Optional[float] = Field(default=None, ge=-0.1, le=0.5) # em; None = auto
|
||
photo_size: int = Field(default=100, ge=50, le=250)
|
||
photo_shape: Literal["square", "rounded", "round"] = "rounded"
|
||
# this board's own names (the menu's "official" names; the catalogue keeps its own)
|
||
names: Dict[str, str] = Field(default_factory=dict) # product id → name
|
||
category_names: Dict[str, str] = Field(default_factory=dict) # category id → name
|
||
|
||
@field_validator("names", "category_names")
|
||
@classmethod
|
||
def _own_names(cls, v):
|
||
return _names(v)
|
||
|
||
@field_validator("sales_point")
|
||
@classmethod
|
||
def _point(cls, v):
|
||
from core import sales_points
|
||
if v is not None and v not in sales_points.ALL:
|
||
raise ValueError(f"one of {', '.join(sales_points.ALL)}")
|
||
return v
|
||
|
||
@field_validator("badges", mode="before")
|
||
@classmethod
|
||
def _badge_keys(cls, v):
|
||
import re as _re
|
||
if not isinstance(v, dict):
|
||
return v
|
||
out = {}
|
||
for k, x in v.items():
|
||
if not str(k).isdigit():
|
||
raise ValueError("badges are keyed by product id")
|
||
keys = [x] if isinstance(x, str) else list(x or []) # one badge (before owner review 5) or several
|
||
keys = list(dict.fromkeys(str(b) for b in keys))
|
||
if len(keys) > 4 or any(not _re.match(BADGE_KEY, b) for b in keys):
|
||
raise ValueError("up to 4 badges of the venue's list")
|
||
if keys:
|
||
out[str(k)] = keys
|
||
return out
|
||
|
||
|
||
class Box(_Strict):
|
||
"""Where a widget moved by hand sits (2026-11-21): % of the slide's (or its stack place's) width /
|
||
height. Owner review 6: it may run off the slide, as long as a strip of it (5 %) stays on it to
|
||
grab it back; a text, clock, QR… is as big as its content (its height sets the size)."""
|
||
x: float = Field(ge=-100, le=100)
|
||
y: float = Field(ge=-100, le=100)
|
||
w: float = Field(ge=1, le=100)
|
||
h: float = Field(ge=1, le=100)
|
||
|
||
@model_validator(mode="after")
|
||
def _inside(self):
|
||
self.w = round(min(self.w, 100), 2)
|
||
self.h = round(min(self.h, 100), 2)
|
||
self.x = round(min(max(self.x, 5 - self.w), 95), 2)
|
||
self.y = round(min(max(self.y, 5 - self.h), 95), 2)
|
||
return self
|
||
|
||
|
||
class Cell(_Strict):
|
||
"""A part of a stack (2026-11-21): its share of the stack (the parts' shares are weights; the
|
||
editor keeps them adding up to 100) and what it shows: widgets (another stack too, one level
|
||
deep; several share the part, one over the other in a side-by-side stack, side by side in the
|
||
other), or a slide of the Slides library, drawn whole inside the part; or nothing."""
|
||
share: float = Field(default=50, ge=1, le=100)
|
||
widgets: List["Widget"] = Field(default_factory=list, max_length=6)
|
||
slide_id: Optional[int] = None
|
||
|
||
@model_validator(mode="before")
|
||
@classmethod
|
||
def _one_widget(cls, v):
|
||
# a part held one widget (`widget`) until owner review 4 (2026-11-21)
|
||
if isinstance(v, dict) and "widget" in v:
|
||
v = dict(v)
|
||
w = v.pop("widget")
|
||
if w is not None:
|
||
v["widgets"] = [w, *(v.get("widgets") or [])]
|
||
return v
|
||
|
||
@model_validator(mode="after")
|
||
def _one(self):
|
||
if self.widgets and self.slide_id is not None:
|
||
raise ValueError("a part shows widgets or a slide, not both")
|
||
self.share = round(self.share, 2)
|
||
return self
|
||
|
||
|
||
class Widget(_Strict):
|
||
"""Something small on a menu, text or blank slide (5.4c), in a corner or a bar, or (moved and
|
||
sized by hand on the editor's preview, 2026-11-21) in its own box: position and size "custom".
|
||
2026-11-21: a text of its own, a menu (a board's list in the widget's place) and stacks: parts
|
||
side by side (direction "row") or one over the other ("column"), each showing a widget or a
|
||
whole library slide."""
|
||
kind: WidgetKind
|
||
position: Position = "top-right"
|
||
size: Literal["small", "medium", "large", "custom"] = "medium"
|
||
box: Optional[Box] = None # position "custom"
|
||
align: Literal["auto", "left", "center", "right"] = "auto" # inside its place; auto: by its corner / box
|
||
media_id: Optional[int] = None # logo: a picture; QR: a logo in its middle (6R.17)
|
||
text: Optional[str] = Field(default=None, max_length=500) # message: this text instead of the venue's; text, ticker, a countdown's / hours' title
|
||
date_style: Literal["short", "long"] = "long"
|
||
clock_seconds: bool = False
|
||
qr_target: Literal["ordering", "menu", "custom"] = "ordering"
|
||
qr_url: Optional[str] = Field(default=None, max_length=300)
|
||
qr_caption: Optional[str] = Field(default=None, max_length=80)
|
||
weather_days: int = Field(default=1, ge=1, le=3) # how many days, from weather_from
|
||
weather_from: int = Field(default=0, ge=0, le=2) # 0 today (now), 1 tomorrow, 2 the day after
|
||
weather_style: Literal["both", "icon", "text"] = "both" # picture and degrees, the picture, the degrees
|
||
board: Optional[MenuList] = None # menu: what it lists and how
|
||
# its look (owner review 5, 2026-11-21): None = the slide's
|
||
vertical: Literal["auto", "top", "middle", "bottom"] = "auto" # inside its place (a stack's part, its box)
|
||
colour: Optional[str] = Field(default=None, pattern=HEX) # its text and pictures (weather, clock…)
|
||
background_colour: Optional[str] = Field(default=None, pattern=HEX) # a plate behind it
|
||
font: Optional[Font] = None
|
||
bold: Optional[bool] = None # None: as the widget usually is
|
||
italic: bool = False
|
||
underline: bool = False
|
||
text_size: int = Field(default=100, ge=50, le=200) # % of its usual text
|
||
qr_colour: Optional[str] = Field(default=None, pattern=HEX) # the code's dots (default black)
|
||
qr_background: Optional[str] = Field(default=None, pattern=HEX) # around them (default white)
|
||
direction: Literal["row", "column"] = "row" # stack: side by side / one over the other
|
||
cells: List[Cell] = Field(default_factory=list, max_length=6)
|
||
# a shape (6R.15): in its box; a fill (flat, or a gradient to fill_to at fill_angle), a border
|
||
shape: Literal["rectangle", "circle", "triangle", "polygon", "star", "custom"] = "rectangle"
|
||
shape_sides: int = Field(default=6, ge=3, le=12) # polygon: its sides; star: its points
|
||
shape_inner: int = Field(default=45, ge=15, le=90) # star: its inner corners, % of the outer
|
||
shape_points: Optional[str] = Field(default=None, max_length=600) # custom: "x,y x,y …" in % of its box
|
||
fill: Optional[str] = Field(default=None, pattern=HEX)
|
||
fill_to: Optional[str] = Field(default=None, pattern=HEX) # None: one colour
|
||
fill_angle: int = Field(default=180, ge=0, le=359)
|
||
stroke: Optional[str] = Field(default=None, pattern=HEX)
|
||
stroke_width: int = Field(default=0, ge=0, le=20) # steps of ½ % of the shape's shorter side
|
||
radius: int = Field(default=0, ge=0, le=50) # rectangle: rounded corners, % of its shorter side
|
||
# scrolling text
|
||
ticker_speed: int = Field(default=4, ge=1, le=10)
|
||
ticker_direction: Literal["left", "right"] = "left"
|
||
# a countdown: to a time every day or a date and time (venue time); it counts from now, from a span
|
||
# before, or from a time; before that it shows the whole span or nothing; at the end a text or nothing
|
||
countdown_to: Optional[str] = Field(default=None, pattern=WHEN)
|
||
countdown_start: Literal["now", "before", "at"] = "now"
|
||
countdown_before: int = Field(default=120, ge=1, le=10080) # minutes
|
||
countdown_at: Optional[str] = Field(default=None, pattern=WHEN)
|
||
countdown_waiting: Literal["full", "hide"] = "full"
|
||
countdown_done: Optional[str] = Field(default=None, max_length=80)
|
||
countdown_done_hide: bool = False
|
||
# the opening hours (from the Schedule page): the week, or today only; days with the same hours on one line
|
||
hours_style: Literal["week", "today"] = "week"
|
||
hours_group: bool = True
|
||
# Wi-Fi (from the identity): its code to join, the password written out
|
||
wifi_qr: bool = True
|
||
wifi_password: bool = True
|
||
# contact details (from the identity): which, in this order
|
||
contact_fields: List[ContactKey] = Field(default_factory=lambda: ["phone", "website", "instagram"], max_length=12)
|
||
# reviews (6R.19): the venue's, typed in under Message & settings; one at a time, turning
|
||
reviews_seconds: int = Field(default=8, ge=3, le=120)
|
||
reviews_min: int = Field(default=4, ge=1, le=5) # only reviews with at least these stars
|
||
reviews_stars: bool = True
|
||
reviews_name: bool = True
|
||
# a gallery (6R.16): pictures and videos one after another, from its own list or a media folder
|
||
gallery_source: Literal["pictures", "folder"] = "pictures"
|
||
media_ids: List[int] = Field(default_factory=list, max_length=100)
|
||
gallery_folder: Optional[int] = None
|
||
gallery_seconds: int = Field(default=5, ge=3, le=120)
|
||
gallery_transition: Literal["fade", "slide", "zoom", "none"] = "fade"
|
||
gallery_fit: Literal["cover", "contain"] = "cover"
|
||
# more settings (6R.17), every widget: on the element that places it
|
||
opacity: int = Field(default=100, ge=10, le=100)
|
||
rotation: int = Field(default=0, ge=-180, le=180)
|
||
shadow: Literal["none", "soft", "strong", "glow"] = "none"
|
||
shadow_colour: Optional[str] = Field(default=None, pattern=HEX)
|
||
border_width: int = Field(default=0, ge=0, le=20) # tenths of a usual unit
|
||
border_colour: Optional[str] = Field(default=None, pattern=HEX)
|
||
border_radius: int = Field(default=0, ge=0, le=100) # tenths of a usual unit
|
||
animation: Literal["none", "fade", "rise", "drop", "slide-left", "slide-right", "zoom", "pop", "pulse", "float"] = "none"
|
||
animation_delay: int = Field(default=0, ge=0, le=50) # tenths of a second
|
||
fit: Literal["contain", "cover", "fill"] = "contain" # a logo / picture in its box
|
||
# texts
|
||
weight: Optional[int] = Field(default=None, ge=100, le=900) # None: as the widget usually is (bold switch)
|
||
highlight: Optional[str] = Field(default=None, pattern=HEX) # a marker behind the text
|
||
text_effect: Literal["none", "typewriter"] = "none"
|
||
# dates and clocks
|
||
date_format: Optional[Literal["long", "short", "weekday", "day_month", "weekday_day_month", "numeric", "numeric_short", "iso"]] = None
|
||
date_separator: Optional[Literal["/", ".", "-", " "]] = None
|
||
clock_format: Literal["24", "12"] = "24"
|
||
clock_separator: Literal[":", "."] = ":"
|
||
clock_blink: bool = False
|
||
|
||
@model_validator(mode="after")
|
||
def _place(self):
|
||
if self.position == "custom":
|
||
if self.box is None:
|
||
raise ValueError("a widget placed by hand needs its box")
|
||
self.size = "custom"
|
||
else:
|
||
self.box = None
|
||
if self.size == "custom":
|
||
self.size = "medium"
|
||
return self
|
||
|
||
@model_validator(mode="after")
|
||
def _kind_fields(self):
|
||
if self.kind == "stack" and not self.cells:
|
||
raise ValueError("a stack has at least one part")
|
||
if self.kind != "stack":
|
||
self.cells = []
|
||
if self.kind == "menu" and self.board is None:
|
||
self.board = MenuList(select="all", columns=1)
|
||
if self.kind != "menu":
|
||
self.board = None
|
||
if self.weather_from + self.weather_days > 3:
|
||
self.weather_days = 3 - self.weather_from # the forecast has three days
|
||
return self
|
||
|
||
@field_validator("qr_url")
|
||
@classmethod
|
||
def _url(cls, v):
|
||
import re as _re
|
||
v = (v or "").strip() or None
|
||
if v and not _re.match(r"^https?://", v):
|
||
raise ValueError("a link starts with http:// or https://")
|
||
return v
|
||
|
||
|
||
Cell.model_rebuild()
|
||
|
||
|
||
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)
|
||
widgets: List[Widget] = Field(default_factory=list, max_length=MAX_WIDGETS_CAP) # the venue's limit: _content
|
||
|
||
|
||
class BlankContent(_Strict):
|
||
"""A blank slide (2026-11-21): only its background and its widgets."""
|
||
background: Background = Field(default_factory=Background)
|
||
widgets: List[Widget] = Field(default_factory=list, max_length=MAX_WIDGETS_CAP) # the venue's limit: _content
|
||
|
||
|
||
class MenuContent(MenuList):
|
||
"""A menu board (5.4b): which products (services/signage_menu.py resolves them), in the board's
|
||
own order, with a sales point's live prices, and how it looks (MenuList), on its background
|
||
with its widgets."""
|
||
board_width: int = Field(default=100, ge=40, le=100) # % of the screen the list takes (2026-11-21)
|
||
board_align: Literal["left", "center", "right"] = "left" # where a narrower list sits, and its title
|
||
board_valign: Literal["top", "middle", "bottom"] = "top" # where a shorter list sits (owner review 5)
|
||
background: Background = Field(default_factory=Background)
|
||
widgets: List[Widget] = Field(default_factory=list, max_length=MAX_WIDGETS_CAP) # the venue's limit: _content
|
||
|
||
|
||
CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent, "blank": BlankContent}
|
||
Kind = Literal["menu", "image", "video", "text", "blank"]
|
||
|
||
|
||
# ── requests ───────────────────────────────────────────────────────────────────
|
||
|
||
def _aspect(v):
|
||
"""A custom shape "W:H" (6R.13): None / "" = none; between 1:4 and 4:1."""
|
||
import re as _re
|
||
v = (v or "").strip() or None
|
||
if v is None:
|
||
return None
|
||
if not _re.match(ASPECT, v):
|
||
raise ValueError("a shape is written W:H, e.g. 21:9")
|
||
w, h = (int(x) for x in v.split(":"))
|
||
if not w or not h or w / h > 4 or h / w > 4:
|
||
raise ValueError("a shape between 1:4 and 4:1")
|
||
return v
|
||
|
||
|
||
class _Shaped(BaseModel):
|
||
aspect: Optional[str] = None # a custom shape "21:9"; None / "" = landscape / portrait
|
||
|
||
@field_validator("aspect")
|
||
@classmethod
|
||
def _shape(cls, v):
|
||
return _aspect(v)
|
||
|
||
|
||
def set_shape(obj, body) -> None:
|
||
"""A playlist's / library slide's shape from a body: `aspect` sets orientation too (wide or tall;
|
||
"16:9" / "9:16" are plain landscape / portrait); `orientation` alone drops a custom shape."""
|
||
sent = body.model_fields_set
|
||
if "aspect" in sent:
|
||
a = body.aspect
|
||
if a is None:
|
||
obj.aspect = None
|
||
if body.orientation is not None:
|
||
obj.orientation = body.orientation
|
||
return
|
||
w, h = (int(x) for x in a.split(":"))
|
||
obj.orientation = "landscape" if w >= h else "portrait"
|
||
obj.aspect = None if a in ("16:9", "9:16") else a
|
||
elif body.orientation is not None:
|
||
obj.orientation = body.orientation
|
||
obj.aspect = None
|
||
|
||
|
||
class PlaylistBody(_Shaped):
|
||
name: str = Field(min_length=1, max_length=80)
|
||
orientation: Orientation = "landscape"
|
||
transition: Transition = "fade"
|
||
|
||
|
||
class PlaylistUpdate(_Shaped):
|
||
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=1, 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 ScheduleLine(BaseModel):
|
||
"""A schedule line (owner 2026-11-21): a playlist on some screens ([] = every screen), when, with a priority."""
|
||
id: Optional[int] = None
|
||
name: Optional[str] = Field(default=None, max_length=80)
|
||
playlist_id: int
|
||
screen_ids: List[int] = Field(default_factory=list)
|
||
priority: int = Field(default=0, ge=0, le=100)
|
||
enabled: bool = True
|
||
days: List[int] = Field(default_factory=list) # [0..6], Monday = 0; [] = every day
|
||
month_days: List[str] = Field(default_factory=list) # core/calendar_days.MONTH_DAYS
|
||
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)
|
||
scene_id: Optional[int] = None
|
||
|
||
@field_validator("days")
|
||
@classmethod
|
||
def _days(cls, 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))
|
||
|
||
@field_validator("month_days")
|
||
@classmethod
|
||
def _month_days(cls, v):
|
||
from core.calendar_days import MONTH_DAYS
|
||
if any(d not in MONTH_DAYS for d in v):
|
||
raise ValueError(f"smart days are {', '.join(MONTH_DAYS)}")
|
||
return [d for d in MONTH_DAYS if d in v]
|
||
|
||
|
||
class SchedulesBody(BaseModel):
|
||
lines: List[ScheduleLine] = Field(default_factory=list, max_length=200)
|
||
|
||
|
||
class SavedSlideBody(SlideFields):
|
||
"""A library slide: its name and description, the shape it is built for, its kind (new ones)."""
|
||
kind: Optional[Kind] = None
|
||
description: Optional[str] = Field(default=None, max_length=300)
|
||
orientation: Optional[Orientation] = None
|
||
aspect: Optional[str] = None # a custom shape (6R.13)
|
||
|
||
@field_validator("aspect")
|
||
@classmethod
|
||
def _shape(cls, v):
|
||
return _aspect(v)
|
||
|
||
|
||
class ScreenBody(BaseModel):
|
||
playlist_id: Optional[int] = None # its default playlist
|
||
slide_id: Optional[int] = None # … or a library slide (one or the other)
|
||
orientation: Optional[Orientation] = None
|
||
rotation: Optional[Literal[0, 90, 180, 270]] = None
|
||
# its picture area (6R.13): px cut off each edge of the TV's window; how a slide of another shape fits
|
||
area_left: Optional[int] = Field(default=None, ge=0, le=AREA_MAX)
|
||
area_top: Optional[int] = Field(default=None, ge=0, le=AREA_MAX)
|
||
area_right: Optional[int] = Field(default=None, ge=0, le=AREA_MAX)
|
||
area_bottom: Optional[int] = Field(default=None, ge=0, le=AREA_MAX)
|
||
fit: Optional[Literal["keep", "stretch"]] = None
|
||
|
||
|
||
class CalibrateBody(BaseModel):
|
||
on: bool
|
||
|
||
|
||
class ViewportBody(BaseModel):
|
||
width: int = Field(ge=1, le=20000)
|
||
height: int = Field(ge=1, le=20000)
|
||
ratio: float = Field(default=1, gt=0, le=10) # device pixels per CSS px
|
||
|
||
|
||
# ── helpers ────────────────────────────────────────────────────────────────────
|
||
|
||
def _setting(db, key: str, default: str = "") -> str:
|
||
from models.settings import PosSettings
|
||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||
return row.value if row and row.value is not None else default
|
||
|
||
|
||
def _save_setting(db, key: str, value: str) -> None:
|
||
from models.settings import PosSettings
|
||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||
if row is None:
|
||
db.add(PosSettings(key=key, value=value))
|
||
else:
|
||
row.value = value
|
||
|
||
|
||
def _qr_link(w: dict) -> str | None:
|
||
from routers.customer_display import _qr_link as link
|
||
return link({"qr_target": w.get("qr_target") or "ordering", "qr_url": w.get("qr_url")})
|
||
|
||
|
||
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 walk_widgets(widgets, prefix: str = ""):
|
||
"""Every widget of a slide, inside stacks too, with its path ("2"; "2.1.0": the widget's index,
|
||
then its part's, then its place in the part): → (path, widget, None), and ("2.1", None, slide
|
||
id) for a part that shows a library slide. The editor and the player find a widget's extras by its path."""
|
||
for i, w in enumerate(widgets or []):
|
||
yield from _walk_one(w, f"{prefix}{i}")
|
||
|
||
|
||
def cell_widgets(c: dict) -> list:
|
||
"""A part's widgets (stored before owner review 4 as one `widget`)."""
|
||
return c.get("widgets") or ([c["widget"]] if c.get("widget") else [])
|
||
|
||
|
||
def _walk_one(w: dict, path: str):
|
||
yield path, w, None
|
||
for j, c in enumerate(w.get("cells") or []):
|
||
cp = f"{path}.{j}"
|
||
ws = cell_widgets(c)
|
||
for k, cw in enumerate(ws):
|
||
yield from _walk_one(cw, f"{cp}.{k}")
|
||
if not ws and c.get("slide_id"):
|
||
yield cp, None, c["slide_id"]
|
||
|
||
|
||
def embedded_ids(content: dict) -> set:
|
||
"""The library slides a slide's stacks show."""
|
||
return {sid for _, _, sid in walk_widgets((content or {}).get("widgets")) if sid}
|
||
|
||
|
||
def _needs_menu(kind: str, content: dict) -> bool:
|
||
"""Does a slide show products (a menu board, a menu widget, a library slide inside a stack)?"""
|
||
return kind == "menu" or any((w and w.get("kind") == "menu") or sid for _, w, sid in walk_widgets((content or {}).get("widgets")))
|
||
|
||
|
||
def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0):
|
||
"""What a slide's widgets need beyond what is stored (2026-11-21), by widget path: a QR code's
|
||
link, a menu widget's products (`menu`), a part's library slide (`slide`: its kind, content,
|
||
menu and extras; slides inside it don't show further slides). → (extras, media ids they show)."""
|
||
from services.signage_menu import resolve
|
||
out, mids = {}, []
|
||
for path, w, sid in walk_widgets((content or {}).get("widgets")):
|
||
if w is not None:
|
||
if w.get("kind") == "qr":
|
||
out[path] = {"link": _qr_link(w)}
|
||
elif w.get("kind") == "menu":
|
||
out[path] = {"menu": resolve(db, w.get("board") or {}, keep_hidden=keep_hidden)}
|
||
elif w.get("kind") == "gallery" and w.get("gallery_source") == "folder":
|
||
ids = gallery_folder_ids(db, w.get("gallery_folder")) # 6R.16: the folder as it is now
|
||
out[path] = {"gallery": ids}
|
||
mids += ids
|
||
elif depth == 0:
|
||
s = db.get(SignageSavedSlide, sid)
|
||
if s is None:
|
||
continue
|
||
inner, inner_media = extras(db, s.content or {}, depth=1)
|
||
one = {"id": s.id, "name": s.name, "kind": s.kind, "content": s.content or {}, "extras": inner,
|
||
"orientation": s.orientation}
|
||
if s.kind == "menu":
|
||
one["menu"] = resolve(db, one["content"])
|
||
out[path] = {"slide": one}
|
||
mids += media_ids(one["content"]) + inner_media
|
||
return out, mids
|
||
|
||
|
||
def gallery_folder_ids(db, folder_id) -> list[int]:
|
||
"""A media folder's files for a gallery (6R.16), newest last as uploaded; none for a folder that's gone."""
|
||
from models.media import Media
|
||
if not folder_id:
|
||
return []
|
||
return [m.id for m in db.query(Media).filter(Media.folder_id == folder_id).order_by(Media.created_at, Media.id).limit(200)]
|
||
|
||
|
||
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()
|
||
most = max_widgets(db)
|
||
if len(data.get("widgets") or []) > most:
|
||
raise XeniaError("signage.too_many_widgets", max=most)
|
||
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")
|
||
found = list(walk_widgets(data.get("widgets")))
|
||
pictures = [(data.get("background") or {}).get("media_id")] + [w.get("media_id") for _, w, _ in found if w]
|
||
if any(i is not None and db.get(Media, i).kind != "image" for i in pictures):
|
||
raise XeniaError("media.not_a_picture")
|
||
for path, w, sid in found:
|
||
# a stack inside a stack, not deeper (2026-11-21)
|
||
if w and w.get("kind") == "stack" and path.count(".") > 2:
|
||
raise XeniaError("signage.content_invalid", field=f"widgets.{path}", reason="a stack goes at most one stack deep")
|
||
if sid and db.get(SignageSavedSlide, sid) is None:
|
||
raise XeniaError("signage.slide_unknown", slide_id=sid)
|
||
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 slide_key(slide_id: int) -> str:
|
||
"""A library slide shown alone, where a playlist id goes (a screen's default, 2026-11-21)."""
|
||
return f"slide:{slide_id}"
|
||
|
||
|
||
def default_of(cfg: dict):
|
||
"""A screen's default: its playlist's id, else "slide:<id>" for its library slide, else None."""
|
||
if cfg.get("playlist"):
|
||
return cfg["playlist"]
|
||
if cfg.get("slide"):
|
||
return slide_key(cfg["slide"])
|
||
return None
|
||
|
||
|
||
def _screens_showing_slide(db, slide_id: int) -> list[int]:
|
||
return [d.id for d in _screens(db) if not _screen_config(d).get("playlist") and _screen_config(d).get("slide") == slide_id]
|
||
|
||
|
||
def _screen_playlists(db, d) -> set:
|
||
"""Every playlist a screen may play: its default and those of its schedule lines."""
|
||
from services.signage_schedule import lines_for
|
||
out = {i.playlist_id for i in lines_for(db, d.id)}
|
||
if _screen_config(d).get("playlist"):
|
||
out.add(_screen_config(d)["playlist"])
|
||
return out
|
||
|
||
|
||
def _screens_playing(db, playlist_id: int) -> list[int]:
|
||
"""The screens that may play it: as their default, or in one of their schedule lines."""
|
||
return [d.id for d in _screens(db) if playlist_id in _screen_playlists(db, d)]
|
||
|
||
|
||
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, "aspect": p.aspect, "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:
|
||
from services.signage_menu import resolve
|
||
out["slides"] = [_slide_out(s) for s in p.slides]
|
||
more = []
|
||
for s in out["slides"]:
|
||
if s["kind"] == "menu":
|
||
s["menu"] = resolve(db, s["content"], keep_hidden=True) # the editor's preview (5.6a)
|
||
s["extras"], m = extras(db, s["content"], keep_hidden=True)
|
||
more += m
|
||
out["media"] = _media_map(db, [i for s in p.slides for i in media_ids(s.content or {})] + more)
|
||
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)
|
||
video = m.kind == "video"
|
||
out[str(m.id)] = {"id": m.id, "kind": m.kind, "name": m.name, "width": m.width, "height": m.height,
|
||
"duration_ms": m.duration_ms,
|
||
# a video plays its version made for screens once there is one (5.4e)
|
||
"url": media_store.video_src(m) if video else urls.get("full") or urls["original"],
|
||
"poster": urls.get("full") if video else None,
|
||
"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)
|
||
|
||
|
||
def _saved_uses(db, media_id: int) -> list:
|
||
return [{"id": s.id, "name": s.name} for s in db.query(SignageSavedSlide).order_by(SignageSavedSlide.name)
|
||
if media_id in media_ids(s.content or {})]
|
||
|
||
|
||
media_store.register_usage("signage_saved_slide", _saved_uses)
|
||
|
||
|
||
def _video_done(db, media_id: int) -> None:
|
||
"""A video's playable version is ready (services/video.py): the screens playing it switch to it."""
|
||
playlists = {s.playlist_id for s in db.query(SignageSlide).filter(SignageSlide.kind == "video")
|
||
if media_id in media_ids(s.content or {})}
|
||
if playlists:
|
||
_tell([d for pid in playlists for d in _screens_playing(db, pid)])
|
||
|
||
|
||
video_store.on_done(_video_done)
|
||
|
||
|
||
def tell_all_screens(db) -> None:
|
||
"""Something every screen may show changed (the message of the day, the weather)."""
|
||
_tell([d.id for d in _screens(db)])
|
||
|
||
|
||
def menu_changed(db) -> None:
|
||
"""Products, categories or prices changed (main.py, the same requests that push the online menu):
|
||
the screens with a menu board on their playlist (or as their default slide) read it again."""
|
||
playlists = {x.playlist_id for x in db.query(SignageSlide) if _needs_menu(x.kind, x.content)}
|
||
boards = {slide_key(x.id) for x in db.query(SignageSavedSlide) if _needs_menu(x.kind, x.content)}
|
||
if playlists or boards:
|
||
_tell([d.id for d in _screens(db) if _screen_playlists(db, d) & playlists or default_of(_screen_config(d)) in boards])
|
||
|
||
|
||
# ── 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)
|
||
set_shape(p, body)
|
||
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()
|
||
set_shape(p, body)
|
||
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 = _screens_playing(db, p.id)
|
||
for d in _screens(db):
|
||
if (d.config or {}).get("playlist") == p.id:
|
||
d.config = {**(d.config or {}), "playlist": None}
|
||
for item in db.query(SignageScheduleItem).filter(SignageScheduleItem.playlist_id == p.id):
|
||
db.delete(item) # its schedule lines go with it
|
||
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, aspect=p.aspect, 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)
|
||
|
||
|
||
# ── the Slides library (owner 2026-11-21) ──────────────────────────────────────
|
||
|
||
def _saved(db, sid: int) -> SignageSavedSlide:
|
||
s = db.get(SignageSavedSlide, sid)
|
||
if s is None:
|
||
raise XeniaError("signage.slide_unknown", slide_id=sid)
|
||
return s
|
||
|
||
|
||
def _saved_out(s: SignageSavedSlide, db=None) -> dict:
|
||
out = {"id": s.id, "name": s.name, "description": s.description, "orientation": s.orientation, "aspect": s.aspect, "kind": s.kind,
|
||
"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 {}}
|
||
if db is not None:
|
||
if s.kind == "menu":
|
||
from services.signage_menu import resolve
|
||
out["menu"] = resolve(db, out["content"], keep_hidden=True)
|
||
out["extras"], out["extra_media"] = extras(db, out["content"], keep_hidden=True)
|
||
showing = set(_screens_showing_slide(db, s.id))
|
||
out["screens"] = [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in showing]
|
||
return out
|
||
|
||
|
||
def _saved_one(db, s: SignageSavedSlide) -> dict:
|
||
"""One library slide for the editor, with the media it shows (its own and its stacks')."""
|
||
out = _saved_out(s, db)
|
||
out["media"] = _media_map(db, media_ids(s.content or {}) + out.pop("extra_media"))
|
||
return out
|
||
|
||
|
||
def _embedding_screens(db, sid: int) -> list[int]:
|
||
"""The screens that may show a library slide inside a stack (of a playlist's slide, or of a
|
||
library slide that is a screen's default): told when it changes."""
|
||
playlists = {x.playlist_id for x in db.query(SignageSlide) if sid in embedded_ids(x.content)}
|
||
saved = {x.id for x in db.query(SignageSavedSlide) if sid in embedded_ids(x.content)}
|
||
return [d.id for d in _screens(db) if _screen_playlists(db, d) & playlists
|
||
or (not _screen_config(d).get("playlist") and _screen_config(d).get("slide") in saved)]
|
||
|
||
|
||
def _saved_name(body) -> str:
|
||
name = (body.name or "").strip()
|
||
if not name:
|
||
raise XeniaError("signage.content_invalid", field="name", reason="required")
|
||
return name
|
||
|
||
|
||
@router.get("/library")
|
||
def list_saved(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""Every kept slide, with its menu resolved (the gallery's previews) and the media they show."""
|
||
rows = db.query(SignageSavedSlide).order_by(SignageSavedSlide.name, SignageSavedSlide.id).all()
|
||
slides = [_saved_out(s, db) for s in rows]
|
||
return {"slides": slides,
|
||
"media": _media_map(db, [i for s in rows for i in media_ids(s.content or {})] + [i for x in slides for i in x.pop("extra_media")])}
|
||
|
||
|
||
@router.post("/library", status_code=201)
|
||
def create_saved(body: SavedSlideBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
if body.kind is None:
|
||
raise XeniaError("signage.content_invalid", field="kind", reason="required")
|
||
name = _saved_name(body)
|
||
s = SignageSavedSlide(name=name, kind=body.kind, orientation=body.orientation or "landscape", duration_s=10, enabled=True,
|
||
video_to_end=body.kind == "video", content=_content(db, body.kind, None))
|
||
set_shape(s, body)
|
||
_apply(db, s, body)
|
||
s.name = name
|
||
s.description = (body.description or "").strip() or None
|
||
db.add(s)
|
||
db.commit()
|
||
db.refresh(s)
|
||
return _saved_one(db, s)
|
||
|
||
|
||
@router.get("/library/{slide_id}")
|
||
def get_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
s = _saved(db, slide_id)
|
||
out = _saved_out(s, db)
|
||
out["media"] = _media_map(db, media_ids(s.content or {}) + out.pop("extra_media"))
|
||
return out
|
||
|
||
|
||
@router.put("/library/{slide_id}")
|
||
def update_saved(slide_id: int, body: SavedSlideBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
s = _saved(db, slide_id)
|
||
if body.kind is not None and body.kind != s.kind:
|
||
raise XeniaError("signage.content_invalid", field="kind", reason="a slide keeps its kind")
|
||
name = _saved_name(body) if "name" in body.model_fields_set else s.name
|
||
_apply(db, s, body)
|
||
s.name = name
|
||
if "description" in body.model_fields_set:
|
||
s.description = (body.description or "").strip() or None
|
||
set_shape(s, body)
|
||
db.commit()
|
||
db.refresh(s)
|
||
_tell(_screens_showing_slide(db, s.id) + _embedding_screens(db, s.id))
|
||
return _saved_one(db, s)
|
||
|
||
|
||
@router.delete("/library/{slide_id}", status_code=204)
|
||
def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
s = _saved(db, slide_id)
|
||
showing = _screens_showing_slide(db, s.id) + _embedding_screens(db, s.id)
|
||
for d in _screens(db):
|
||
if (d.config or {}).get("slide") == s.id:
|
||
d.config = {**(d.config or {}), "slide": None}
|
||
db.delete(s)
|
||
db.commit()
|
||
_tell(showing)
|
||
return Response(status_code=204)
|
||
|
||
|
||
@router.post("/library/{slide_id}/duplicate", status_code=201)
|
||
def duplicate_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
s = _saved(db, slide_id)
|
||
copy = SignageSavedSlide(name=f"{s.name} (2)"[:80], description=s.description, orientation=s.orientation, aspect=s.aspect, kind=s.kind,
|
||
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 {})))
|
||
db.add(copy)
|
||
db.commit()
|
||
db.refresh(copy)
|
||
return _saved_one(db, copy)
|
||
|
||
|
||
# ── screens ────────────────────────────────────────────────────────────────────
|
||
|
||
def _screen_out(db, d) -> dict:
|
||
"""A screen: its default playlist, shape and turn, and what plays on it now (a schedule line wins)."""
|
||
from services.signage_schedule import now_for
|
||
cfg = _screen_config(d)
|
||
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
|
||
sl = db.get(SignageSavedSlide, cfg["slide"]) if cfg.get("slide") and not p else None
|
||
now_id, scheduled = now_for(db, d)
|
||
if isinstance(now_id, str):
|
||
now = {"id": now_id, "name": sl.name, "scheduled": False, "slide": True} if sl else None
|
||
else:
|
||
now_p = db.get(SignagePlaylist, now_id) if now_id else None
|
||
now = {"id": now_p.id, "name": now_p.name, "scheduled": scheduled} if now_p else None
|
||
ids = _screen_playlists(db, d)
|
||
shapes = {x.orientation for x in db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids))} if ids else set()
|
||
if sl:
|
||
shapes.add(sl.orientation)
|
||
return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None,
|
||
"slide_id": sl.id if sl else None, "slide_name": sl.name if sl else None,
|
||
"orientation": cfg["orientation"], "rotation": cfg["rotation"], "now": now,
|
||
"orientation_mismatch": any(o != cfg["orientation"] for o in shapes),
|
||
**_picture(d, cfg), "viewport": _viewports.get(d.id)}
|
||
|
||
|
||
def _area(cfg: dict) -> dict:
|
||
return {k[5:]: int(cfg.get(k) or 0) for k in AREA_KEYS}
|
||
|
||
|
||
def calibrating(device_id: int) -> bool:
|
||
import time
|
||
at = _calibrating.get(device_id)
|
||
if at is not None and time.monotonic() - at > CALIBRATE_S:
|
||
_calibrating.pop(device_id, None)
|
||
return False
|
||
return at is not None
|
||
|
||
|
||
def _picture(d, cfg: dict) -> dict:
|
||
"""A screen's picture (6R.13): the insets of its area, how a slide of another shape fits, calibrating now."""
|
||
return {"area": _area(cfg), "fit": cfg.get("fit") or "keep", "calibrating": calibrating(d.id)}
|
||
|
||
|
||
def _tell_calibration(d, cfg: dict) -> None:
|
||
broadcast_sync("signage.calibrate", {"on": calibrating(d.id), "area": _area(cfg)}, device_ids=[d.id])
|
||
|
||
|
||
@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", "slide_id": "slide"}.get(key, key)] = getattr(body, key)
|
||
# the default is a playlist or a library slide, never both
|
||
if "playlist_id" in body.model_fields_set and body.playlist_id is not None:
|
||
cfg["slide"] = None
|
||
if "slide_id" in body.model_fields_set and body.slide_id is not None:
|
||
cfg["playlist"] = None
|
||
d.config = validate(for_app("signage"), cfg, db)
|
||
db.commit()
|
||
if calibrating(d.id):
|
||
_tell_calibration(d, _screen_config(d)) # the TV moves its outline at once
|
||
broadcast_sync("device.updated", {}, device_ids=[d.id])
|
||
_tell([d.id])
|
||
return _screen_out(db, d)
|
||
|
||
|
||
def _a_screen(db, device_id: int):
|
||
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)
|
||
return d
|
||
|
||
|
||
@router.post("/screens/{device_id}/calibrate")
|
||
def calibrate_screen(device_id: int, body: CalibrateBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""Calibrating a screen's picture (6R.13): on, the TV outlines its picture area with arrows
|
||
pointing out and its size, and follows every change of the insets at once; off (the manager's
|
||
dialog closes, or after 15 min) it plays again."""
|
||
import time
|
||
d = _a_screen(db, device_id)
|
||
if body.on:
|
||
_calibrating[d.id] = time.monotonic()
|
||
else:
|
||
_calibrating.pop(d.id, None)
|
||
_tell_calibration(d, _screen_config(d))
|
||
return _screen_out(db, d)
|
||
|
||
|
||
# ── the screen itself ──────────────────────────────────────────────────────────
|
||
|
||
def _resolved(db, p: SignagePlaylist) -> dict:
|
||
"""A playlist as a screen plays it: enabled slides, transitions filled in, menus, QR links, media."""
|
||
from services.signage_menu import resolve
|
||
slides = [_slide_out(s) for s in p.slides if s.enabled]
|
||
more = []
|
||
for s in slides:
|
||
s["transition"] = s["transition"] or p.transition
|
||
if s["kind"] == "menu":
|
||
s["menu"] = resolve(db, s["content"]) # live prices and availability (5.4b)
|
||
s["extras"], m = extras(db, s["content"]) # menus, library slides inside stacks, links (2026-11-21)
|
||
more += m
|
||
for w in s["content"].get("widgets") or []:
|
||
if w["kind"] == "qr":
|
||
w["link"] = _qr_link(w)
|
||
return {"id": p.id, "name": p.name, "orientation": p.orientation, "aspect": p.aspect, "transition": p.transition, "slides": slides,
|
||
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])] + more)}
|
||
|
||
|
||
def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict:
|
||
"""A library slide shown alone as a screen's default: a playlist of that one slide."""
|
||
from services.signage_menu import resolve
|
||
one = _saved_out(s)
|
||
one["transition"] = one["transition"] or "fade"
|
||
if one["kind"] == "menu":
|
||
one["menu"] = resolve(db, one["content"])
|
||
one["extras"], more = extras(db, one["content"])
|
||
for w in one["content"].get("widgets") or []:
|
||
if w["kind"] == "qr":
|
||
w["link"] = _qr_link(w)
|
||
slides = [one] if s.enabled else []
|
||
return {"id": slide_key(s.id), "name": s.name, "orientation": s.orientation, "aspect": s.aspect, "transition": "fade", "slides": slides,
|
||
"media": _media_map(db, media_ids(one["content"]) + more)}
|
||
|
||
|
||
def _default_resolved(db, cfg: dict):
|
||
d = default_of(cfg)
|
||
if isinstance(d, str):
|
||
s = db.get(SignageSavedSlide, cfg["slide"])
|
||
return d, (_resolved_slide(db, s, cfg["orientation"]) if s else None)
|
||
p = db.get(SignagePlaylist, d) if d else None
|
||
return d, (_resolved(db, p) if p else None)
|
||
|
||
|
||
@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).
|
||
With schedule lines for it (5.4d, 2026-11-21): the lines, the scenes on now and every playlist
|
||
they name, so the screen switches by itself; `playlist` is the one playing now and the
|
||
schedule's `fallback_playlist_id` is the screen's default. `version` changes whenever anything
|
||
here does."""
|
||
from core.timeutil import venue_now, venue_tz
|
||
from services import weather
|
||
from services.scenes import active_ids
|
||
from services.signage_schedule import entry_of, lines_for, pick
|
||
cfg = _screen_config(dev)
|
||
lines = lines_for(db, dev.id)
|
||
schedule, playlists, playlist = None, None, None
|
||
default, fallback = _default_resolved(db, cfg)
|
||
if lines:
|
||
ids = _screen_playlists(db, dev)
|
||
playlists = {str(p.id): _resolved(db, p) for p in
|
||
(db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids)).all() if ids else [])}
|
||
if isinstance(default, str) and fallback:
|
||
playlists[default] = fallback # its library slide, under "slide:<id>"
|
||
scenes = sorted(active_ids(db))
|
||
entries = [entry_of(i) for i in lines]
|
||
now_id = pick(entries, default, venue_now(), scenes)
|
||
playlist = playlists.get(str(now_id)) if now_id else None
|
||
schedule = {"entries": entries, "fallback_playlist_id": default, "scenes": scenes, "timezone": venue_tz().key}
|
||
else:
|
||
playlist = fallback
|
||
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"], **_picture(dev, cfg)},
|
||
"playlist": playlist, "schedule": schedule, "playlists": playlists,
|
||
# for the widgets (5.4c): weather None = hide it (no internet, no place, too old)
|
||
"venue": _venue(db)}
|
||
out["version"] = hashlib.sha256(json.dumps(out, sort_keys=True, default=str).encode()).hexdigest()[:16]
|
||
return out
|
||
|
||
|
||
@router.post("/screen/viewport")
|
||
def screen_viewport(body: ViewportBody, dev=Depends(require_device("signage"))):
|
||
"""The TV's window size (6R.13), sent when it starts and when it changes: the calibration
|
||
dialog's presets fit a shape into it. Kept in memory only (the TV sends it again after a restart)."""
|
||
_viewports[dev.id] = {"width": body.width, "height": body.height, "ratio": round(body.ratio, 3)}
|
||
return {"ok": True}
|
||
|
||
|
||
# ── schedules (5.4d; lines with their screens and scenes, owner 2026-11-21) ─────
|
||
|
||
def _line_out(i: SignageScheduleItem, now_ids: dict) -> dict:
|
||
return {"id": i.id, "name": i.name, "playlist_id": i.playlist_id, "screen_ids": i.screen_ids or [], "priority": i.priority,
|
||
"enabled": bool(i.enabled), "days": i.days or [], "month_days": i.month_days or [], "time_from": i.time_from,
|
||
"time_to": i.time_to, "date_from": i.date_from, "date_to": i.date_to, "scene_id": i.scene_id, "position": i.position,
|
||
# the screens where this line wins now
|
||
"playing_on": now_ids.get(i.id, [])}
|
||
|
||
|
||
def _lines_out(db) -> list:
|
||
from core.timeutil import venue_now
|
||
from services.scenes import active_ids
|
||
from services.signage_schedule import entry_of, lines_for, matches
|
||
local, scenes = venue_now(), active_ids(db)
|
||
winners: dict = {}
|
||
for d in _screens(db):
|
||
best, key = None, None
|
||
for n, i in enumerate(lines_for(db, d.id)):
|
||
e = entry_of(i)
|
||
if not matches(e, local, scenes):
|
||
continue
|
||
from services.signage_schedule import _specific
|
||
k = (i.priority or 0, _specific(e), n)
|
||
if key is None or k > key:
|
||
best, key = i.id, k
|
||
if best is not None:
|
||
winners.setdefault(best, []).append({"id": d.id, "name": d.name})
|
||
items = db.query(SignageScheduleItem).order_by(SignageScheduleItem.position, SignageScheduleItem.id).all()
|
||
return [_line_out(i, winners) for i in items]
|
||
|
||
|
||
@router.get("/schedules")
|
||
def list_schedules(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
return _lines_out(db)
|
||
|
||
|
||
@router.put("/schedules")
|
||
def save_schedules(body: SchedulesBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""Every schedule line at once (the tab saves them together); ids that aren't sent are deleted."""
|
||
from models.scene import Scene
|
||
screens = {d.id for d in _screens(db)}
|
||
for line in body.lines:
|
||
_playlist(db, line.playlist_id)
|
||
if line.scene_id is not None and db.get(Scene, line.scene_id) is None:
|
||
raise XeniaError("signage.scene_unknown", scene_id=line.scene_id)
|
||
for sid in line.screen_ids:
|
||
if sid not in screens:
|
||
raise XeniaError("signage.screen_unknown", device_id=sid)
|
||
keep = {line.id for line in body.lines if line.id}
|
||
for item in db.query(SignageScheduleItem):
|
||
if item.id not in keep:
|
||
db.delete(item)
|
||
db.flush()
|
||
for n, line in enumerate(body.lines):
|
||
item = db.get(SignageScheduleItem, line.id) if line.id else None
|
||
if item is None:
|
||
item = SignageScheduleItem()
|
||
db.add(item)
|
||
for k, v in line.model_dump(exclude={"id"}).items():
|
||
setattr(item, k, (v or "").strip() or None if k == "name" else v)
|
||
item.screen_ids = sorted(set(line.screen_ids))
|
||
item.position = n
|
||
db.commit()
|
||
_tell([d.id for d in _screens(db)]) # their lines may have changed
|
||
return _lines_out(db)
|
||
|
||
|
||
# ── the message of the day and the weather (5.4c) ──────────────────────────────
|
||
|
||
class MessageBody(BaseModel):
|
||
text: Optional[str] = Field(default=None, max_length=200)
|
||
|
||
|
||
class PlaceBody(BaseModel):
|
||
name: str = Field(min_length=1, max_length=120)
|
||
latitude: float = Field(ge=-90, le=90)
|
||
longitude: float = Field(ge=-180, le=180)
|
||
units: Literal["celsius", "fahrenheit"] = "celsius"
|
||
|
||
|
||
@router.get("/message")
|
||
def get_message(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
return {"text": _setting(db, MESSAGE) or None}
|
||
|
||
|
||
@router.put("/message")
|
||
def put_message(body: MessageBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""The message of the day: one place to change it for every screen, at once."""
|
||
_save_setting(db, MESSAGE, (body.text or "").strip())
|
||
db.commit()
|
||
tell_all_screens(db)
|
||
return {"text": (body.text or "").strip() or None}
|
||
|
||
|
||
def max_widgets(db) -> int:
|
||
"""How many widgets a slide may hold: the venue's setting (Performance), 10 until it changes it."""
|
||
try:
|
||
return max(1, min(MAX_WIDGETS_CAP, int(_setting(db, MAX_WIDGETS, "10") or 10)))
|
||
except ValueError:
|
||
return 10
|
||
|
||
|
||
class PerformanceBody(BaseModel):
|
||
max_widgets: int = Field(ge=1, le=MAX_WIDGETS_CAP)
|
||
|
||
|
||
@router.get("/performance")
|
||
def get_performance(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""Limits that keep the TVs smooth (owner review 6): widgets per slide (10 recommended)."""
|
||
return {"max_widgets": max_widgets(db), "recommended": 10, "cap": MAX_WIDGETS_CAP}
|
||
|
||
|
||
@router.put("/performance")
|
||
def put_performance(body: PerformanceBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
_save_setting(db, MAX_WIDGETS, str(body.max_widgets))
|
||
db.commit()
|
||
return {"max_widgets": body.max_widgets, "recommended": 10, "cap": MAX_WIDGETS_CAP}
|
||
|
||
|
||
class Review(_Strict):
|
||
"""A review the venue typed in (6R.19): who, how many stars, what they wrote, when, where it was posted."""
|
||
name: str = Field(min_length=1, max_length=60)
|
||
stars: int = Field(ge=1, le=5)
|
||
text: str = Field(min_length=1, max_length=400)
|
||
date: Optional[str] = Field(default=None, pattern=DATE)
|
||
source: Optional[str] = Field(default=None, max_length=40) # "Google", "Tripadvisor"…
|
||
|
||
@field_validator("name", "text", "source")
|
||
@classmethod
|
||
def _trim(cls, v):
|
||
v = " ".join(str(v).split()) if v is not None else None
|
||
return v or None
|
||
|
||
|
||
class ReviewsBody(BaseModel):
|
||
reviews: List[Review] = Field(default_factory=list, max_length=100)
|
||
|
||
|
||
def reviews(db) -> list:
|
||
"""The venue's reviews as stored (a broken value reads as none)."""
|
||
try:
|
||
return ReviewsBody(reviews=json.loads(_setting(db, REVIEWS) or "[]")).model_dump()["reviews"]
|
||
except Exception:
|
||
return []
|
||
|
||
|
||
@router.get("/reviews")
|
||
def get_reviews(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
return {"reviews": reviews(db)}
|
||
|
||
|
||
@router.put("/reviews")
|
||
def put_reviews(body: ReviewsBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
_save_setting(db, REVIEWS, json.dumps(body.model_dump()["reviews"], ensure_ascii=False))
|
||
db.commit()
|
||
tell_all_screens(db)
|
||
return {"reviews": reviews(db)}
|
||
|
||
|
||
class BadgesBody(BaseModel):
|
||
badges: list = Field(default_factory=list)
|
||
|
||
|
||
@router.get("/badges")
|
||
def get_badges(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""The badges boards can put on products (owner review 5), with the icons they may have."""
|
||
from services import signage_badges
|
||
return {"badges": signage_badges.load(db), "icons": list(signage_badges.ICONS)}
|
||
|
||
|
||
@router.put("/badges")
|
||
def put_badges(body: BadgesBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""The venue's badges, all at once: their names, colours (the boards' defaults) and icons."""
|
||
from pydantic import ValidationError
|
||
from services import signage_badges
|
||
try:
|
||
parsed = signage_badges.BadgeList(badges=body.badges)
|
||
except ValidationError as e:
|
||
first = e.errors()[0]
|
||
raise XeniaError("signage.content_invalid", field=".".join(str(x) for x in first.get("loc", ())), reason=first.get("msg", ""))
|
||
out = signage_badges.save(db, parsed.badges)
|
||
db.commit()
|
||
tell_all_screens(db)
|
||
return {"badges": out, "icons": list(signage_badges.ICONS)}
|
||
|
||
|
||
@router.get("/weather")
|
||
def weather_status(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
from services import weather
|
||
return weather.status(db)
|
||
|
||
|
||
@router.put("/weather/place")
|
||
async def weather_place(body: PlaceBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
from services import weather
|
||
_save_setting(db, "signage.weather.place", body.name.strip())
|
||
_save_setting(db, "signage.weather.latitude", f"{body.latitude:.4f}")
|
||
_save_setting(db, "signage.weather.longitude", f"{body.longitude:.4f}")
|
||
_save_setting(db, "signage.weather.units", body.units)
|
||
db.commit()
|
||
await weather.refresh(db)
|
||
return weather.status(db)
|
||
|
||
|
||
@router.delete("/weather/place")
|
||
async def weather_forget(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
from services import weather
|
||
for k in ("signage.weather.place", "signage.weather.latitude", "signage.weather.longitude"):
|
||
_save_setting(db, k, "")
|
||
db.commit()
|
||
await weather.refresh(db)
|
||
return weather.status(db)
|
||
|
||
|
||
@router.post("/weather/refresh")
|
||
async def weather_refresh(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
from services import weather
|
||
await weather.refresh(db)
|
||
return weather.status(db)
|
||
|
||
|
||
@router.get("/weather/places")
|
||
async def weather_places(q: str, language: str = "en", user=Depends(require(KEY))):
|
||
"""Towns for the editor's search (needs internet: none → `signage.weather_offline`)."""
|
||
from services import weather
|
||
if len(q.strip()) < 2:
|
||
return []
|
||
try:
|
||
return await weather.search(q.strip(), language if language in ("en", "el") else "en")
|
||
except Exception:
|
||
raise XeniaError("signage.weather_offline")
|
||
|
||
|
||
# ── for the editor's previews (5.6a) ───────────────────────────────────────────
|
||
|
||
class MenuPreviewBody(BaseModel):
|
||
content: dict = Field(default_factory=dict)
|
||
|
||
|
||
@router.get("/venue")
|
||
def preview_venue(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""What the widgets show (the same as a screen gets), for the editor's previews."""
|
||
return _venue(db)
|
||
|
||
|
||
def _venue(db) -> dict:
|
||
"""What the widgets need of the venue: its name, the message of the day, the weather (None = hide
|
||
it: no internet, no place, too old) and its badges (owner review 5); its identity (6R.14: slogan,
|
||
colours, logos, Wi-Fi, contact) and time zone."""
|
||
from core.timeutil import venue_tz
|
||
from routers.identity import hours_out, identity_out
|
||
from services import signage_badges, weather
|
||
ident = identity_out(db)
|
||
ident.pop("name", None)
|
||
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None,
|
||
"weather": weather.current(db), "badges": signage_badges.load(db), "identity": ident, "timezone": venue_tz().key,
|
||
"hours": hours_out(db), "reviews": reviews(db)}
|
||
|
||
|
||
class SlidePreviewBody(BaseModel):
|
||
kind: Kind
|
||
content: dict = Field(default_factory=dict)
|
||
|
||
|
||
@router.post("/preview/slide")
|
||
def preview_slide(body: SlidePreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""A slide not saved yet, as the editor's preview needs it (2026-11-21): a menu board's
|
||
products (hidden ones kept, marked), the extras of its widgets (menus, library slides inside
|
||
stacks, QR links) and the media they show."""
|
||
from services.signage_menu import resolve
|
||
content = _content(db, body.kind, body.content)
|
||
ex, more = extras(db, content, keep_hidden=True)
|
||
return {"menu": resolve(db, content, keep_hidden=True) if body.kind == "menu" else None, "extras": ex,
|
||
"media": _media_map(db, more)}
|
||
|
||
|
||
@router.post("/preview/menu")
|
||
def preview_menu(body: MenuPreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||
"""A menu board not saved yet, resolved like a screen gets it (the editor's live preview)."""
|
||
from services.signage_menu import resolve
|
||
content = _content(db, "menu", body.content)
|
||
return {"content": content, "menu": resolve(db, content, keep_hidden=True)}
|