Files
xenia-pos-local/local_backend/services/signage_schedule.py
T
bonaminandClaude Opus 5.5 83551714f7 feat(signage): Slides library, widgets placed on the preview, blank slides, slide editor rework
- Slides library (Alembic 0044, /api/signage/library): slides kept with a name and a
  description, added to playlists as copies ("Add a slide" → Your slides, "Keep in Slides"),
  or shown alone as a screen's default (device config `slide`, played as "slide:<id>",
  also as a schedule's fallback). Signage → Slides: gallery + a two-pane editor.
- Widgets moved and sized by hand on the preview (WidgetCanvas: handles, snapping, arrow
  keys): position/size "custom" with a box the TV draws the same; alignment per widget.
- Blank slides (background + widgets); menu boards narrower and placed left/centre/right.
- Slide editor reworked: name | show, transition effect | seconds; sections; text look on
  one row with ready colours; one card per widget, settings on one row.
- Questions inside the page (@xenia/ui ConfirmDialog/useConfirm), Switch boxed, Segmented
  fill; the timeline's drop line; schedule lines run on weekdays or smart days, not both;
  the playlist editor stays within 1080p with a long timeline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:53:27 +02:00

149 lines
6.2 KiB
Python

"""Signage schedules (plan step 5.4d; lines with their screens and scenes, owner 2026-11-21): which
playlist a screen plays when.
A screen's lines are the schedule lines (models/signage.py SignageScheduleItem) that are on and
name it (or no screen = every screen). At a moment (venue time) a line matches when:
- its days include today (empty = every day),
- its smart days hold (core/calendar_days.py: 1st / last day, first / last week, public
holidays or not; empty = every day),
- the time is inside [time_from, time_to) (empty = all day; a window that passes midnight,
e.g. 22:00-02:00, counts the after-midnight part for the day it started),
- today is inside [date_from, date_to] (empty = no limit),
- its scene (if any) is on.
The winner is the highest priority, then the most specific (dates > days > hours), then the
later line. No match → the screen's default playlist (None = a blank screen).
`pick()` is pure (unit-tested; the player in 5.5a does the same in JavaScript so a screen
switches by itself while the server is down). `schedule_worker` tells a screen when its pick
changes.
"""
from __future__ import annotations
import asyncio
import logging
from datetime import datetime, timedelta
logger = logging.getLogger("xenia.signage")
def _minutes(hhmm: str | None) -> int | None:
if not hhmm:
return None
h, m = hhmm.split(":")
return int(h) * 60 + int(m)
def _date_ok(e: dict, day) -> bool:
from core.calendar_days import month_days_ok
d = day.isoformat()
return (not e.get("date_from") or d >= e["date_from"]) and (not e.get("date_to") or d <= e["date_to"]) and month_days_ok(e.get("month_days"), day)
def matches(e: dict, local: datetime, scenes=None) -> bool:
"""Does entry `e` cover this venue-local moment (with these scenes on)?"""
if e.get("scene_id") is not None and e["scene_id"] not in (scenes or ()):
return False
days = e.get("days") or []
start, end = _minutes(e.get("time_from")), _minutes(e.get("time_to"))
now = local.hour * 60 + local.minute
if start is None and end is None:
return (not days or local.weekday() in days) and _date_ok(e, local.date())
start = 0 if start is None else start
end = 24 * 60 if end is None else end
if start < end: # the same day
return start <= now < end and (not days or local.weekday() in days) and _date_ok(e, local.date())
# passes midnight: before midnight it is today's window, after midnight yesterday's
if now >= start:
return (not days or local.weekday() in days) and _date_ok(e, local.date())
if now < end:
y = local - timedelta(days=1)
return (not days or y.weekday() in days) and _date_ok(e, y.date())
return False
def _specific(e: dict) -> int:
return (4 if (e.get("date_from") or e.get("date_to")) else 0) + (2 if (e.get("days") or e.get("month_days")) else 0) + \
(1 if (e.get("time_from") or e.get("time_to")) else 0)
def pick(entries: list[dict], fallback: int | None, local: datetime, scenes=None) -> int | None:
"""The playlist id that plays at `local` (venue time)."""
best, best_key = None, None
for i, e in enumerate(entries or []):
if e.get("playlist_id") is None or not matches(e, local, scenes):
continue
key = (e.get("priority") or 0, _specific(e), i)
if best_key is None or key > best_key:
best, best_key = e["playlist_id"], key
return best if best is not None else fallback
# ── telling screens when their pick changes ───────────────────────────────────
_playing: dict[int, int | None] = {} # screen id → the playlist it was told about
ENTRY_KEYS = ("playlist_id", "days", "month_days", "time_from", "time_to", "date_from", "date_to", "priority", "scene_id")
def entry_of(item) -> dict:
"""A schedule line as the screens and pick() read it."""
return {k: getattr(item, k) for k in ENTRY_KEYS}
def lines_for(db, screen_id: int) -> list:
"""The schedule lines that are on and name this screen (or no screen), in order."""
from models.signage import SignageScheduleItem
return [i for i in db.query(SignageScheduleItem).filter(SignageScheduleItem.enabled.is_(True))
.order_by(SignageScheduleItem.position, SignageScheduleItem.id) if not i.screen_ids or screen_id in i.screen_ids]
def now_for(db, dev, local: datetime | None = None, scenes=None) -> tuple[int | str | None, bool]:
"""(the playlist a screen plays now, whether a schedule line picked it)."""
from core.timeutil import venue_now
from routers.signage import _screen_config, default_of
from services.scenes import active_ids
local = local or venue_now()
scenes = active_ids(db) if scenes is None else scenes
default = default_of(_screen_config(dev)) # a playlist id, or "slide:<id>" (a library slide)
got = pick([entry_of(i) for i in lines_for(db, dev.id)], None, local, scenes)
return (got, True) if got is not None else (default, False)
def due_changes(db, local: datetime | None = None) -> list[int]:
"""The screens whose pick is different from the last one seen (and remember it)."""
from core.timeutil import venue_now
from routers.signage import _screens
from services.scenes import active_ids
local = local or venue_now()
scenes = active_ids(db)
changed = []
for d in _screens(db):
now = now_for(db, d, local, scenes)[0]
if d.id in _playing and _playing[d.id] != now:
changed.append(d.id)
_playing[d.id] = now
return changed
async def schedule_worker():
"""Every 30 s (a signage module worker): a screen whose schedule now picks another playlist is told."""
from database import SessionLocal
while True:
db = SessionLocal()
try:
ids = due_changes(db)
if ids:
from routers.signage import _tell
_tell(ids)
logger.info("signage: schedule switched screens %s", ids)
except Exception as e:
logger.warning("signage schedule worker: %s", e)
finally:
db.close()
await asyncio.sleep(30)
def reset() -> None:
_playing.clear()