- Widget on text and menu slides: logo (a picture), name, date (short/long), clock (seconds), message (the venue's or its own text), QR code (ordering / QR menu / a link; the screen gets the link), weather (1-3 days); position (corners, top / bottom bar) and size. Logos count as media usage. - The screen gets `venue`: name, message of the day, weather. - PUT /api/signage/message (one place, every screen told at once). - services/weather.py: the venue's place (town search through /api/signage/weather/places, PUT/DELETE /weather/place, °C/°F), Open-Meteo every 30 min (signage worker), kept in memory; no place, no internet or older than 3 h → weather null and the widget hides. signage.weather_offline when the town search can't reach the service. Checked against the real service. - tests: test_signage_widgets.py (5, a fake Open-Meteo); 520 passed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
678 lines
28 KiB
Python
678 lines
28 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, SignageSlide
|
|
from services import media as media_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"
|
|
# 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 ScreenBody(BaseModel):
|
|
playlist_id: Optional[int] = None
|
|
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 _screens_playing(db, playlist_id: int) -> list[int]:
|
|
return [d.id for d in _screens(db) if _screen_config(d).get("playlist") == playlist_id]
|
|
|
|
|
|
def _tell(ids: list[int]) -> None:
|
|
if ids:
|
|
broadcast_sync("signage.changed", {}, device_ids=sorted(set(ids)))
|
|
|
|
|
|
def _slide_out(s: SignageSlide) -> dict:
|
|
return {"id": s.id, "kind": s.kind, "name": s.name, "position": s.position, "duration_s": s.duration_s,
|
|
"transition": s.transition, "video_to_end": bool(s.video_to_end), "enabled": bool(s.enabled),
|
|
"days": s.days or [], "time_from": s.time_from, "time_to": s.time_to, "date_from": s.date_from, "date_to": s.date_to,
|
|
"content": s.content or {}}
|
|
|
|
|
|
def _playlist_out(db, p: SignagePlaylist, slides: bool = False) -> dict:
|
|
playing = set(_screens_playing(db, p.id))
|
|
out = {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition,
|
|
"slide_count": len(p.slides), "screens": [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in playing]}
|
|
if slides:
|
|
out["slides"] = [_slide_out(s) for s in p.slides]
|
|
out["media"] = _media_map(db, [i for s in p.slides for i in media_ids(s.content or {})])
|
|
return out
|
|
|
|
|
|
def _media_map(db, ids) -> dict:
|
|
"""{media id: what a screen or the editor needs to show it} for these ids."""
|
|
from models.media import Media
|
|
ids = sorted({i for i in ids if i})
|
|
out = {}
|
|
for m in (db.query(Media).filter(Media.id.in_(ids)).all() if ids else []):
|
|
urls = media_store.urls(m)
|
|
out[str(m.id)] = {"id": m.id, "kind": m.kind, "name": m.name, "width": m.width, "height": m.height,
|
|
"duration_ms": m.duration_ms, "url": urls.get("full") or urls["original"],
|
|
"thumb": urls.get("thumb"), "builtin": bool(m.builtin)}
|
|
return out
|
|
|
|
|
|
def _renumber(p: SignagePlaylist) -> None:
|
|
for i, s in enumerate(sorted(p.slides, key=lambda x: (x.position, x.id))):
|
|
s.position = i
|
|
|
|
|
|
def _uses(db, media_id: int) -> list:
|
|
out = []
|
|
for s in db.query(SignageSlide).order_by(SignageSlide.playlist_id, SignageSlide.position):
|
|
if media_id in media_ids(s.content or {}):
|
|
out.append({"id": s.id, "name": f"{s.playlist.name} · {s.name or s.position + 1}"})
|
|
return out
|
|
|
|
|
|
media_store.register_usage("signage_slide", _uses)
|
|
|
|
|
|
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_config(d).get("playlist") in 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 = []
|
|
for d in _screens(db):
|
|
if (d.config or {}).get("playlist") == p.id:
|
|
d.config = {**(d.config or {}), "playlist": None}
|
|
stopped.append(d.id)
|
|
db.delete(p)
|
|
db.commit()
|
|
_tell(stopped)
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.post("/playlists/{playlist_id}/duplicate", status_code=201)
|
|
def duplicate_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
p = _playlist(db, playlist_id)
|
|
copy = SignagePlaylist(name=f"{p.name} (2)"[:80], orientation=p.orientation, transition=p.transition)
|
|
db.add(copy)
|
|
db.flush()
|
|
for s in p.slides:
|
|
db.add(_copy_slide(s, copy.id, s.position))
|
|
db.commit()
|
|
db.refresh(copy)
|
|
return _playlist_out(db, copy, slides=True)
|
|
|
|
|
|
@router.put("/playlists/{playlist_id}/order")
|
|
def order_slides(playlist_id: int, body: OrderBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
p = _playlist(db, playlist_id)
|
|
mine = {s.id: s for s in p.slides}
|
|
if sorted(body.slide_ids) != sorted(mine):
|
|
raise XeniaError("signage.order_mismatch")
|
|
for i, sid in enumerate(body.slide_ids):
|
|
mine[sid].position = i
|
|
db.commit()
|
|
db.refresh(p)
|
|
_tell(_screens_playing(db, p.id))
|
|
return _playlist_out(db, p, slides=True)
|
|
|
|
|
|
# ── slides ─────────────────────────────────────────────────────────────────────
|
|
|
|
def _copy_slide(s: SignageSlide, playlist_id: int, position: int) -> SignageSlide:
|
|
return SignageSlide(playlist_id=playlist_id, position=position, kind=s.kind, name=s.name, duration_s=s.duration_s,
|
|
transition=s.transition, video_to_end=s.video_to_end, enabled=s.enabled, days=s.days,
|
|
time_from=s.time_from, time_to=s.time_to, date_from=s.date_from, date_to=s.date_to,
|
|
content=json.loads(json.dumps(s.content or {})))
|
|
|
|
|
|
@router.post("/playlists/{playlist_id}/slides", status_code=201)
|
|
def add_slide(playlist_id: int, body: SlideCreate, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
p = _playlist(db, playlist_id)
|
|
at = len(p.slides) if body.position is None else min(body.position, len(p.slides))
|
|
for s in p.slides:
|
|
if s.position >= at:
|
|
s.position += 1
|
|
slide = SignageSlide(playlist_id=p.id, kind=body.kind, position=at, duration_s=10, enabled=True,
|
|
content=_content(db, body.kind, None))
|
|
_apply(db, slide, body)
|
|
if body.kind == "video" and "video_to_end" not in body.model_fields_set:
|
|
slide.video_to_end = True
|
|
db.add(slide)
|
|
db.commit()
|
|
db.refresh(p)
|
|
_tell(_screens_playing(db, p.id))
|
|
return _slide_out(slide)
|
|
|
|
|
|
@router.put("/slides/{slide_id}")
|
|
def update_slide(slide_id: int, body: SlideFields, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
slide = _slide(db, slide_id)
|
|
_apply(db, slide, body)
|
|
db.commit()
|
|
db.refresh(slide)
|
|
_tell(_screens_playing(db, slide.playlist_id))
|
|
return _slide_out(slide)
|
|
|
|
|
|
@router.delete("/slides/{slide_id}", status_code=204)
|
|
def delete_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
slide = _slide(db, slide_id)
|
|
p = slide.playlist
|
|
db.delete(slide)
|
|
db.flush()
|
|
db.refresh(p)
|
|
_renumber(p)
|
|
db.commit()
|
|
_tell(_screens_playing(db, p.id))
|
|
return Response(status_code=204)
|
|
|
|
|
|
@router.post("/slides/{slide_id}/duplicate", status_code=201)
|
|
def duplicate_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
slide = _slide(db, slide_id)
|
|
p = slide.playlist
|
|
for s in p.slides:
|
|
if s.position > slide.position:
|
|
s.position += 1
|
|
copy = _copy_slide(slide, p.id, slide.position + 1)
|
|
db.add(copy)
|
|
db.commit()
|
|
db.refresh(copy)
|
|
_tell(_screens_playing(db, p.id))
|
|
return _slide_out(copy)
|
|
|
|
|
|
# ── screens ────────────────────────────────────────────────────────────────────
|
|
|
|
def _screen_out(db, d) -> dict:
|
|
cfg = _screen_config(d)
|
|
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
|
|
return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None,
|
|
"orientation": cfg["orientation"], "rotation": cfg["rotation"],
|
|
"orientation_mismatch": bool(p and p.orientation != cfg["orientation"])}
|
|
|
|
|
|
@router.get("/screens")
|
|
def list_screens(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
return [_screen_out(db, d) for d in _screens(db)]
|
|
|
|
|
|
@router.put("/screens/{device_id}")
|
|
def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
|
from core.modules.device_config import for_app, validate
|
|
from models.device import Device
|
|
d = db.get(Device, device_id)
|
|
if d is None or d.app_key != "signage" or d.revoked_at is not None:
|
|
raise XeniaError("signage.not_a_screen", device_id=device_id)
|
|
cfg = dict(d.config or {})
|
|
for key in body.model_fields_set:
|
|
cfg[{"playlist_id": "playlist"}.get(key, key)] = getattr(body, key)
|
|
d.config = validate(for_app("signage"), cfg, db)
|
|
db.commit()
|
|
broadcast_sync("device.updated", {}, device_ids=[d.id])
|
|
_tell([d.id])
|
|
return _screen_out(db, d)
|
|
|
|
|
|
# ── the screen itself ──────────────────────────────────────────────────────────
|
|
|
|
@router.get("/screen")
|
|
def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))):
|
|
"""What this screen plays: its settings and its playlist with every slide and media address.
|
|
Slides that are off are left out; time windows are the player's (it keeps playing offline).
|
|
`version` changes whenever anything here does (the player's cache key)."""
|
|
cfg = _screen_config(dev)
|
|
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
|
|
playlist = None
|
|
if p is not None:
|
|
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)
|
|
playlist = {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides,
|
|
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])}
|
|
from services import weather
|
|
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
|
|
"playlist": playlist,
|
|
# 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
|
|
|
|
|
|
# ── 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")
|