feat(backend): signage schedules: which playlist plays when, switching by itself (platform-v2 step 5.4d)
- signage_schedules (Alembic 0030): entries {playlist, days, hours (may pass
midnight), dates, priority} and a fallback playlist. A screen's `schedule`
(ref) wins over its single playlist.
- services/signage_schedule.pick (pure): highest priority, then the most
specific (dates > days > hours), then the later entry; no match → fallback.
- GET /api/signage/screen with a schedule: the schedule (with the venue's time
zone) and every playlist in it, `playlist` = the one playing now, so the
player can switch while the server is down.
- schedule_worker (signage module, 30 s) tells a screen when its pick changes.
- /api/signage/schedules CRUD (playing now, the screens on it); deleting a
playlist takes it out of schedules; changes reach screens through schedules.
- Devices page: a signage screen's Schedule.
- tests: test_signage_schedule.py (6); 526 passed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -35,7 +35,7 @@ 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 models.signage import SignagePlaylist, SignageSchedule, SignageSlide
|
||||
from services import media as media_store
|
||||
from services.ws_bus import broadcast_sync
|
||||
|
||||
@@ -216,8 +216,32 @@ class OrderBody(BaseModel):
|
||||
slide_ids: List[int]
|
||||
|
||||
|
||||
class ScheduleEntry(BaseModel):
|
||||
playlist_id: int
|
||||
days: List[int] = Field(default_factory=list) # [0..6], Monday = 0; [] = 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)
|
||||
priority: int = Field(default=0, ge=0, le=100)
|
||||
|
||||
@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))
|
||||
|
||||
|
||||
class ScheduleBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
fallback_playlist_id: Optional[int] = None
|
||||
entries: List[ScheduleEntry] = Field(default_factory=list, max_length=100)
|
||||
|
||||
|
||||
class ScreenBody(BaseModel):
|
||||
playlist_id: Optional[int] = None
|
||||
schedule_id: Optional[int] = None
|
||||
orientation: Optional[Orientation] = None
|
||||
rotation: Optional[Literal[0, 90, 180, 270]] = None
|
||||
|
||||
@@ -330,7 +354,23 @@ def _screen_config(dev) -> dict:
|
||||
|
||||
|
||||
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]
|
||||
"""The screens that play it: as their playlist, or anywhere in their schedule."""
|
||||
in_schedules = {s.id for s in db.query(SignageSchedule) if playlist_id in _schedule_playlists(s)}
|
||||
out = []
|
||||
for d in _screens(db):
|
||||
cfg = _screen_config(d)
|
||||
if cfg.get("schedule") in in_schedules or (not cfg.get("schedule") and cfg.get("playlist") == playlist_id):
|
||||
out.append(d.id)
|
||||
return out
|
||||
|
||||
|
||||
def _schedule_playlists(s) -> set:
|
||||
if s is None:
|
||||
return set()
|
||||
out = {e.get("playlist_id") for e in (s.entries or []) if e.get("playlist_id")}
|
||||
if s.fallback_playlist_id:
|
||||
out.add(s.fallback_playlist_id)
|
||||
return out
|
||||
|
||||
|
||||
def _tell(ids: list[int]) -> None:
|
||||
@@ -435,11 +475,16 @@ def update_playlist(playlist_id: int, body: PlaylistUpdate, db: Session = Depend
|
||||
@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 = []
|
||||
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}
|
||||
stopped.append(d.id)
|
||||
for sch in db.query(SignageSchedule):
|
||||
kept = [e for e in (sch.entries or []) if e.get("playlist_id") != p.id]
|
||||
if kept != (sch.entries or []):
|
||||
sch.entries = kept
|
||||
if sch.fallback_playlist_id == p.id:
|
||||
sch.fallback_playlist_id = None
|
||||
db.delete(p)
|
||||
db.commit()
|
||||
_tell(stopped)
|
||||
@@ -544,9 +589,16 @@ def duplicate_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(r
|
||||
def _screen_out(db, d) -> dict:
|
||||
cfg = _screen_config(d)
|
||||
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
|
||||
sch = db.get(SignageSchedule, cfg["schedule"]) if cfg.get("schedule") else None
|
||||
if sch is not None:
|
||||
ids = _schedule_playlists(sch)
|
||||
shapes = {x.orientation for x in db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids))} if ids else set()
|
||||
else:
|
||||
shapes = {p.orientation} if p 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,
|
||||
"schedule_id": sch.id if sch else None, "schedule_name": sch.name if sch else None,
|
||||
"orientation": cfg["orientation"], "rotation": cfg["rotation"],
|
||||
"orientation_mismatch": bool(p and p.orientation != cfg["orientation"])}
|
||||
"orientation_mismatch": any(o != cfg["orientation"] for o in shapes)}
|
||||
|
||||
|
||||
@router.get("/screens")
|
||||
@@ -563,7 +615,7 @@ def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db
|
||||
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)
|
||||
cfg[{"playlist_id": "playlist", "schedule_id": "schedule"}.get(key, key)] = getattr(body, key)
|
||||
d.config = validate(for_app("signage"), cfg, db)
|
||||
db.commit()
|
||||
broadcast_sync("device.updated", {}, device_ids=[d.id])
|
||||
@@ -573,29 +625,46 @@ def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db
|
||||
|
||||
# ── 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).
|
||||
`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"])])}
|
||||
With a schedule (5.4d): the schedule and every playlist in it, so the screen switches by
|
||||
itself; `playlist` is the one playing now. `version` changes whenever anything here does."""
|
||||
from core.timeutil import venue_now, venue_tz
|
||||
from services import weather
|
||||
from services.signage_schedule import pick
|
||||
cfg = _screen_config(dev)
|
||||
sch = db.get(SignageSchedule, cfg["schedule"]) if cfg.get("schedule") else None
|
||||
schedule, playlists, playlist = None, None, None
|
||||
if sch is not None:
|
||||
ids = _schedule_playlists(sch)
|
||||
playlists = {str(p.id): _resolved(db, p) for p in
|
||||
(db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids)).all() if ids else [])}
|
||||
now_id = pick(sch.entries or [], sch.fallback_playlist_id, venue_now())
|
||||
playlist = playlists.get(str(now_id)) if now_id else None
|
||||
schedule = {"id": sch.id, "name": sch.name, "entries": sch.entries or [], "fallback_playlist_id": sch.fallback_playlist_id,
|
||||
"timezone": venue_tz().key}
|
||||
else:
|
||||
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") 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,
|
||||
"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)}}
|
||||
@@ -603,6 +672,73 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
|
||||
return out
|
||||
|
||||
|
||||
# ── schedules (5.4d) ───────────────────────────────────────────────────────────
|
||||
|
||||
def _schedule(db, sid: int) -> SignageSchedule:
|
||||
s = db.get(SignageSchedule, sid)
|
||||
if s is None:
|
||||
raise XeniaError("signage.schedule_unknown", schedule_id=sid)
|
||||
return s
|
||||
|
||||
|
||||
def _schedule_out(db, s: SignageSchedule) -> dict:
|
||||
from core.timeutil import venue_now
|
||||
from services.signage_schedule import pick
|
||||
names = {p.id: p.name for p in db.query(SignagePlaylist)}
|
||||
now_id = pick(s.entries or [], s.fallback_playlist_id, venue_now())
|
||||
return {"id": s.id, "name": s.name, "fallback_playlist_id": s.fallback_playlist_id, "entries": s.entries or [],
|
||||
"playing_now": {"id": now_id, "name": names.get(now_id)} if now_id else None,
|
||||
"screens": [{"id": d.id, "name": d.name} for d in _screens(db) if _screen_config(d).get("schedule") == s.id]}
|
||||
|
||||
|
||||
def _check_schedule(db, body: ScheduleBody) -> None:
|
||||
for pid in [body.fallback_playlist_id, *[e.playlist_id for e in body.entries]]:
|
||||
if pid is not None:
|
||||
_playlist(db, pid)
|
||||
|
||||
|
||||
@router.get("/schedules")
|
||||
def list_schedules(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
return [_schedule_out(db, s) for s in db.query(SignageSchedule).order_by(SignageSchedule.name)]
|
||||
|
||||
|
||||
@router.post("/schedules", status_code=201)
|
||||
def create_schedule(body: ScheduleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
_check_schedule(db, body)
|
||||
s = SignageSchedule(name=body.name.strip(), fallback_playlist_id=body.fallback_playlist_id,
|
||||
entries=[e.model_dump() for e in body.entries])
|
||||
db.add(s)
|
||||
db.commit()
|
||||
db.refresh(s)
|
||||
return _schedule_out(db, s)
|
||||
|
||||
|
||||
@router.put("/schedules/{schedule_id}")
|
||||
def update_schedule(schedule_id: int, body: ScheduleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
s = _schedule(db, schedule_id)
|
||||
_check_schedule(db, body)
|
||||
s.name = body.name.strip()
|
||||
s.fallback_playlist_id = body.fallback_playlist_id
|
||||
s.entries = [e.model_dump() for e in body.entries]
|
||||
db.commit()
|
||||
db.refresh(s)
|
||||
_tell([d.id for d in _screens(db) if _screen_config(d).get("schedule") == s.id])
|
||||
return _schedule_out(db, s)
|
||||
|
||||
|
||||
@router.delete("/schedules/{schedule_id}", status_code=204)
|
||||
def delete_schedule(schedule_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
s = _schedule(db, schedule_id)
|
||||
moved = []
|
||||
for d in _screens(db):
|
||||
if (d.config or {}).get("schedule") == s.id:
|
||||
d.config = {**(d.config or {}), "schedule": None}
|
||||
moved.append(d.id)
|
||||
db.delete(s)
|
||||
db.commit()
|
||||
_tell(moved)
|
||||
return Response(status_code=204)
|
||||
|
||||
# ── the message of the day and the weather (5.4c) ──────────────────────────────
|
||||
|
||||
class MessageBody(BaseModel):
|
||||
|
||||
Reference in New Issue
Block a user