- Scenes (Alembic 0043, models/scene.py, /api/scenes, core.scenes.manage): named modes on or off (optionally until a time); price rules / deals get the condition "a scene is on"; signage lines can play only during a scene; turning one on tells every screen and pushes the online menu. - Signage schedules are lines (signage_schedule_items): playlist, screens ([] = every screen), priority, days, smart days (1st / last day, first / last week, Greek public holidays or not: core/calendar_days.py, mirrored in @xenia/signage), hours, dates, scene. No line → the screen's default playlist. 0043 turns the old named schedules into lines for their screens. - Screens: default playlist, TV shape, turn; what plays now and why. - Manager: tabs Screens · Playlists · Schedules · Slides (placeholder) · Message and weather; schedule lines with playlist / screens / priority / delete on one line; the playlist editor's horizontal timeline of fixed cards, the slide's basics beside its preview (one height), then its content; Management → Scenes; the scene condition in pricing. - Tests: backend (lines, smart days, scenes, prices), player logic, e2e. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
864 lines
37 KiB
Python
864 lines
37 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/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 Dict, 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, 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"
|
|
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"
|
|
|
|
|
|
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"]
|
|
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar"]
|
|
|
|
|
|
class Widget(_Strict):
|
|
"""Something small on a menu or text slide (5.4c), in a corner or a bar."""
|
|
kind: WidgetKind
|
|
position: Position = "top-right"
|
|
size: Literal["small", "medium", "large"] = "medium"
|
|
media_id: Optional[int] = None # logo: a picture
|
|
text: Optional[str] = Field(default=None, max_length=200) # message: this text instead of the venue's
|
|
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) # today, or today + the next days
|
|
|
|
@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
|
|
|
|
|
|
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=10)
|
|
|
|
|
|
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"]
|
|
|
|
|
|
class MenuContent(_Strict):
|
|
"""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."""
|
|
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, Badge] = Field(default_factory=dict) # product id → badge
|
|
sold_out: Literal["strike", "hide"] = "strike"
|
|
language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed
|
|
# how it's laid out (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=3, le=120)
|
|
font: Font = "sans"
|
|
text_colour: str = Field(default="#ffffff", pattern=HEX)
|
|
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # prices, headings, badges
|
|
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=10)
|
|
|
|
@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")
|
|
@classmethod
|
|
def _badge_keys(cls, v):
|
|
if any(not k.isdigit() for k in v):
|
|
raise ValueError("badges are keyed by product id")
|
|
return v
|
|
|
|
|
|
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 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 ScreenBody(BaseModel):
|
|
playlist_id: Optional[int] = None # its default playlist
|
|
orientation: Optional[Orientation] = None
|
|
rotation: Optional[Literal[0, 90, 180, 270]] = None
|
|
|
|
|
|
# ── 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 _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")
|
|
pictures = [(data.get("background") or {}).get("media_id")] + [w.get("media_id") for w in data.get("widgets") or []]
|
|
if any(i is not None and db.get(Media, i).kind != "image" for i in pictures):
|
|
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 _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, "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]
|
|
for s in out["slides"]:
|
|
if s["kind"] == "menu":
|
|
s["menu"] = resolve(db, s["content"]) # the editor's preview (5.6a)
|
|
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)
|
|
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 _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 read it again."""
|
|
playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")}
|
|
if playlists:
|
|
_tell([d.id for d in _screens(db) if _screen_playlists(db, d) & playlists])
|
|
|
|
|
|
# ── 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 = _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, 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:
|
|
"""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
|
|
now_id, scheduled = now_for(db, d)
|
|
now_p = db.get(SignagePlaylist, now_id) if now_id 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()
|
|
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"],
|
|
"now": {"id": now_p.id, "name": now_p.name, "scheduled": scheduled} if now_p else None,
|
|
"orientation_mismatch": any(o != cfg["orientation"] for o in shapes)}
|
|
|
|
|
|
@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 ──────────────────────────────────────────────────────────
|
|
|
|
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]
|
|
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)
|
|
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, "transition": p.transition, "slides": slides,
|
|
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])}
|
|
|
|
|
|
@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 = cfg.get("playlist")
|
|
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 [])}
|
|
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:
|
|
p = db.get(SignagePlaylist, default) if default else None
|
|
playlist = _resolved(db, p) if p is not None else None
|
|
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
|
|
"playlist": playlist, "schedule": schedule, "playlists": playlists,
|
|
# for the widgets (5.4c): weather None = hide it (no internet, no place, too old)
|
|
"venue": {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None,
|
|
"weather": weather.current(db)}}
|
|
out["version"] = hashlib.sha256(json.dumps(out, sort_keys=True, default=str).encode()).hexdigest()[:16]
|
|
return out
|
|
|
|
|
|
# ── 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}
|
|
|
|
|
|
@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."""
|
|
from services import weather
|
|
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, "weather": weather.current(db)}
|
|
|
|
|
|
@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)}
|