Files
xenia-pos-local/packages/signage/src/logic.js
T
bonaminandClaude Opus 5.5 b5361e10ca feat(media): video versions: still frame + a version every screen plays (platform-v2 5.4e)
- services/video.py: background worker (one video at a time, low priority) makes a still
  frame (thumb/card/full WebP) and, when needed, play.mp4 (H.264+AAC, <=1920 px, HDR
  tone-mapped, faststart); the original is kept. Media.processing/progress (migration 0031,
  existing videos queued). ffmpeg from the pinned imageio-ffmpeg wheel; none = as uploaded.
- MOV (video/quicktime) accepted; /api/media/file/<sha>/play served with ranges.
- Signage plays the version (poster = still frame) and tells the screens playing it when ready.
- Manager library: still frames in the grid, preparing progress, status in the details.
- Tests: test_video.py (8), backend 541 passed; e2e media/signage/stack new checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:10:22 +02:00

209 lines
9.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The signage player's logic (plan steps 5.5a, 5.5b; @xenia/signage since 5.6a). Pure: unit-tested in
// Node (packages/signage/tests/logic.test.mjs).
// The schedule rules are the server's (local_backend/services/signage_schedule.py) so a screen
// switches playlists by itself while the server is down; the same cases are tested on both sides.
/** The venue's local clock at `date`: { weekday (0 = Monday), minutes, date: "YYYY-MM-DD" }. */
export function localNow(timeZone, date = new Date()) {
// the venue's zone (the schedule's), not the TV's: a TV set to another zone still switches on time
const opts = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short', hourCycle: 'h23' }
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', { timeZone: timeZone || undefined, ...opts })
.formatToParts(date).map(p => [p.type, p.value]))
const weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].indexOf(parts.weekday)
return { weekday, minutes: Number(parts.hour) * 60 + Number(parts.minute), date: `${parts.year}-${parts.month}-${parts.day}` }
}
/** The day before a local moment (for windows that pass midnight). */
function yesterday(local) {
const d = new Date(`${local.date}T12:00:00Z`)
d.setUTCDate(d.getUTCDate() - 1)
return { weekday: (local.weekday + 6) % 7, minutes: local.minutes, date: d.toISOString().slice(0, 10) }
}
const mins = hhmm => {
if (!hhmm) return null
const [h, m] = hhmm.split(':').map(Number)
return h * 60 + m
}
function dayOk(w, local) {
const days = w.days || []
return (!days.length || days.includes(local.weekday)) &&
(!w.date_from || local.date >= w.date_from) && (!w.date_to || local.date <= w.date_to)
}
/** Does a window (days, time_from / time_to that may pass midnight, date_from / date_to) cover `local`? */
export function matches(w, local) {
let start = mins(w.time_from)
let end = mins(w.time_to)
if (start == null && end == null) return dayOk(w, local)
start = start ?? 0
end = end ?? 24 * 60
if (start < end) return local.minutes >= start && local.minutes < end && dayOk(w, local)
if (local.minutes >= start) return dayOk(w, local)
if (local.minutes < end) return dayOk(w, yesterday(local))
return false
}
const specific = e => ((e.date_from || e.date_to) ? 4 : 0) + (e.days?.length ? 2 : 0) + ((e.time_from || e.time_to) ? 1 : 0)
/** The playlist a schedule plays at `local`: highest priority, then the most specific, then the later entry. */
export function pick(entries, fallback, local) {
let best = null
let bestKey = null
;(entries || []).forEach((e, i) => {
if (e.playlist_id == null || !matches(e, local)) return
const key = [e.priority || 0, specific(e), i]
if (!bestKey || key[0] > bestKey[0] || (key[0] === bestKey[0] && (key[1] > bestKey[1] || (key[1] === bestKey[1] && key[2] > bestKey[2])))) {
best = e.playlist_id
bestKey = key
}
})
return best ?? fallback ?? null
}
/** The playlist to play now from the screen's answer (GET /api/signage/screen). */
export function playlistNow(data, now = new Date()) {
if (!data) return null
if (!data.schedule) return data.playlist || null
const id = pick(data.schedule.entries, data.schedule.fallback_playlist_id, localNow(data.schedule.timezone, now))
return id != null ? data.playlists?.[String(id)] ?? null : null
}
/** A slide may show now: its own window (days / hours / dates), in venue time. */
export function slideShows(slide, local) {
return matches({ days: slide.days, time_from: slide.time_from, time_to: slide.time_to, date_from: slide.date_from, date_to: slide.date_to }, local)
}
/** The index of the next slide that may show after `current` (wrapping), or -1 when none may. */
export function nextSlide(slides, current, local) {
const n = slides?.length || 0
for (let step = 1; step <= n; step++) {
const i = (((current ?? -1) + step) % n + n) % n
if (slideShows(slides[i], local)) return i
}
return -1
}
/** How long a slide stays, in ms; null = until its video ends (with a safety limit in the player). */
export function slideMs(slide) {
if (slide.kind === 'video' && slide.video_to_end) return null
return Math.max(2, slide.duration_s || 10) * 1000
}
/** The frame's size and turn for a screen: CSS for the box that holds the slides. */
export function frameStyle(rotation) {
const r = Number(rotation) || 0
if (r === 90 || r === 270) {
return { width: '100vh', height: '100vw', transform: `translate(-50%, -50%) rotate(${r}deg)`, top: '50%', left: '50%', position: 'absolute', containerType: 'size' }
}
return { width: '100vw', height: '100vh', transform: r === 180 ? 'rotate(180deg)' : undefined, top: 0, left: 0, position: 'absolute', containerType: 'size' }
}
/** Every media address a playlist (or a schedule's playlists) needs, to keep on the device. */
export function mediaUrls(data) {
if (!data) return []
const lists = data.schedule ? Object.values(data.playlists || {}) : (data.playlist ? [data.playlist] : [])
const out = new Set()
for (const p of lists) {
for (const m of Object.values(p.media || {})) {
if (m.url) out.add(m.url)
if (m.poster) out.add(m.poster) // a video's still frame (5.4e), shown while it loads
}
}
return [...out]
}
/** The fonts a slide can choose (all on the device: nothing to download, works offline). */
export const FONTS = {
sans: 'system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
serif: 'Georgia, "Times New Roman", serif',
rounded: 'ui-rounded, "SF Pro Rounded", "Arial Rounded MT Bold", system-ui, sans-serif',
condensed: '"Arial Narrow", "Roboto Condensed", "Helvetica Neue", sans-serif',
display: 'Impact, "Arial Black", system-ui, sans-serif',
}
// ── menu boards (5.5b) ───────────────────────────────────────────────────────
/** The frame's height in cqmin (its shorter side is 100) for a screen w × h: 100 when wide, ~178 when tall (16:9). */
export function frameHeightVmin(rotation, w = 16, h = 9) {
const turned = Number(rotation) === 90 || Number(rotation) === 270
const frameTall = turned ? w > h : h > w // the screen's sides, swapped when the picture is turned
return frameTall ? (100 * Math.max(w, h)) / Math.min(w, h) : 100
}
/**
* How many rows fit in one column of a menu board: rows are items (taller with a photo or a
* description) and group headings. Sizes in cqmin, as the board draws them.
*/
export function rowsPerColumn({ heightVmin = 100, textSize = 100, photos = false, descriptions = false, title = false, bars = 0 }) {
const s = (textSize || 100) / 100
const row = (photos ? 8 : descriptions ? 7 : 4.8) * s
const used = 10 + (title ? 11 * s : 0) + bars * 9 // padding, the title, top / bottom bars of widgets
return Math.max(3, Math.floor((heightVmin - used) / row))
}
/**
* The board's pages: groups split into pages of at most `perPage` rows (a heading counts as a
* row; a group cut in two repeats its heading on the next page). → [[{category, items}], …]
*/
export function menuPages(groups, perPage, headings = true) {
const per = Math.max(1, perPage | 0)
const pages = []
let page = []
let used = 0
const flush = () => { if (page.length) pages.push(page); page = []; used = 0 }
for (const g of groups || []) {
let items = [...(g.items || [])]
if (!items.length) continue
while (items.length) {
const head = headings && g.category ? 1 : 0
if (used + head + 1 > per) flush()
const room = per - used - head
const take = items.slice(0, Math.max(1, room))
page.push({ category: g.category, items: take })
used += head + take.length
items = items.slice(take.length)
if (items.length) flush()
}
}
flush()
return pages
}
/** A menu slide's time: every page for its seconds, at least the slide's own time. */
export function menuMs(slide, pageCount) {
const per = Math.max(3, slide.content?.page_seconds || 10) * 1000
return Math.max(slideMs(slide), pageCount > 1 ? pageCount * per : 0)
}
/** The page on screen `elapsedMs` into the slide (the pages go round while the slide lasts). */
export function pageAt(pageCount, pageSeconds, elapsedMs) {
if (pageCount <= 1 || !(elapsedMs > 0)) return 0 // the clock's last tick may be just before the slide began
return Math.floor(elapsedMs / (Math.max(3, pageSeconds || 10) * 1000)) % pageCount // round and round while the slide lasts
}
/** A weather code (WMO, as Open-Meteo sends it) → an icon name for the widget. */
export function weatherIcon(code, isDay = true) {
if (code == null) return 'cloud'
if (code === 0) return isDay ? 'sun' : 'moon'
if (code <= 2) return isDay ? 'cloud-sun' : 'cloud-moon'
if (code === 3) return 'cloud'
if (code === 45 || code === 48) return 'fog'
if ((code >= 51 && code <= 67) || (code >= 80 && code <= 82)) return 'rain'
if ((code >= 71 && code <= 77) || code === 85 || code === 86) return 'snow'
if (code >= 95) return 'storm'
return 'cloud'
}
/** A menu slide's pages for this screen (w × h pixels, turned by `rotation`). */
export function boardPages(slide, rotation, w, h) {
const c = slide.content || {}
const widgets = c.widgets || []
const bars = ['top-bar', 'bottom-bar'].filter(p => widgets.some(x => x.position === p)).length
const rows = rowsPerColumn({ heightVmin: frameHeightVmin(rotation, w, h), textSize: c.text_size, photos: c.show_photos,
descriptions: c.show_descriptions, title: !!c.title, bars })
const per = c.page_size || rows * (c.columns || 2)
return menuPages(slide.menu?.groups || [], per, c.category_titles !== false)
}