diff --git a/.env.example b/.env.example deleted file mode 100644 index 18b2fb4..0000000 --- a/.env.example +++ /dev/null @@ -1,18 +0,0 @@ -PULSE_SIGNAGE_IMAGE=git.lzstealth.com/lzstealth/pulse-signage:latest -PULSE_SIGNAGE_SHARED_SECRET= - -DB_HOST=mysql -DB_PORT=3306 -DB_NAME=pulse-signage -DB_USER=pulse-signage -DB_PASSWORD=signage_password -MYSQL_ROOT_PASSWORD=root_password - -PLAYER_PUBLIC_BASE_URL=http://localhost:8081 -PLAYER_INTERNAL_BASE_URL=http://player:8081 - -SESSION_MAX_AGE_DAYS=14 -DEFAULT_ADMIN_USERNAME=admin -DEFAULT_ADMIN_NAME=Admin -DEFAULT_ADMIN_PASSWORD=admin -PASSWORD_HASH_ITERATIONS=310000 \ No newline at end of file diff --git a/.gitignore b/.gitignore index fb61e35..6093592 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,10 @@ media/ !src/web/lib/media/ !src/web/lib/media/** docker-compose.dev.yml +/docker-compose/*.dev.yml +/docker-compose/*.env +/docker-compose/*.env.local +/docker-compose/*.env.remote /dev-demo-seed.js .vscode/ .env diff --git a/README.md b/README.md index aeec578..f0f4aeb 100644 --- a/README.md +++ b/README.md @@ -1,81 +1,38 @@ # Pulse Signage -Pulse Signage is a self-hosted digital signage platform built for teams that want clear, flexible control over what appears on every screen. +Pulse Signage is a self-hosted digital signage platform for teams that want clear, reliable control over the content on every screen. -It gives you one place to manage playlists, slides, templates, screen assignments, announcements, data-driven content, and live player control without handing that workflow to a third-party service. +It gives you one place to publish playlists, slides, announcements, and live updates without handing the workflow to a third-party service. -## Why It Stands Out +## What It Can Do -- Keep signage under your own control. -- Build polished screen experiences with reusable templates and playlists. -- Push announcements, schedules, RSS feeds, API content, and other dynamic content to screens. -- See what is live, what is queued, and what needs attention from a single admin dashboard. -- Use the same system for everyday signage, timed messages, and more structured information displays. +- Run polished screen experiences with playlists, slides, and reusable templates. +- Keep announcements, schedules, RSS feeds, API content, and other live data in sync. +- Manage many screens from a single dashboard. +- Support everyday signage, event messages, lobbies, dashboards, and other always-on displays. +- Keep the player, dashboard, and bridge connected so updates move quickly and consistently. -## What It Handles +## Why It Fits -- Screens and playlist assignments. -- Slides, templates, and canvas sizes. -- Announcements and screen-specific targeting. -- RSS feeds, API sources, and schedule-based content. -- Roles and permissions for admin access. -- Background tasks and scheduled refresh jobs. -- Player onboarding and live playback control. +- It keeps signage under your own control. +- It is built for teams that need screens to stay current without extra manual work. +- It works well for offices, venues, campuses, and operations teams. +- It stays focused on display management instead of trying to be a general-purpose CMS. -## Simple Deployment +## Deploying -Pulse Signage ships with a Docker Compose stack for the published image: +Docker Compose is the recommended way to deploy Pulse Signage. It keeps the web app, player, bridge, and database together in a predictable setup. -- Published-image stack: `docker compose -f docker-compose.yml up -d` +If you want the details, start with the [Compose guide](docker-compose/README.md). -Use this stack when you want to run the tagged image instead of building from source. +## Docs -## Environment File +- [Documentation home](docs/README.md) - the technical reference index. +- [API reference](docs/api.md) - the player HTTP surface and onboarding endpoints. +- [Database schema](docs/schema.md) - the tables and data model the app maintains. +- [WebSocket reference](docs/websocket.md) - the live player and snapshot channels. +- [Compose guide](docker-compose/README.md) - deployment options and service layout. -The compose files read from a root `.env` file. Start by copying `.env.example` to `.env`, then adjust the values for your setup. +## Explore The Docs -The variables are split by who uses them: - -Shared across the stack: - -- `PULSE_SIGNAGE_IMAGE` -- `PULSE_SIGNAGE_SHARED_SECRET` - -Web container: - -- `SESSION_MAX_AGE_DAYS` -- `DEFAULT_ADMIN_USERNAME` -- `DEFAULT_ADMIN_NAME` -- `DEFAULT_ADMIN_PASSWORD` -- `PASSWORD_HASH_ITERATIONS` - -Player container: - -- `PLAYER_PUBLIC_BASE_URL` -- `PLAYER_INTERNAL_BASE_URL` - -MySQL container: - -- `DB_HOST` -- `DB_PORT` -- `DB_NAME` -- `DB_USER` -- `DB_PASSWORD` -- `MYSQL_ROOT_PASSWORD` - -`DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, and `DB_PASSWORD` are shared in practice because both app containers talk to the same database service. - -`PLAYER_INTERNAL_BASE_URL` is used by the web side for server-to-player calls, while `PLAYER_PUBLIC_BASE_URL` is used for browser-facing player links. - -## First-Time Use - -The first startup seeds a default admin account if the database is empty. - -- Username: `admin` -- Password: `admin` - -## In Practice - -Pulse Signage is designed to feel focused and reliable rather than heavy or noisy. It works well when you want a clean internal signage system for offices, venues, dashboards, or any environment where screens need to stay up to date without a lot of manual effort. - -The player and admin pieces stay linked, so changes made in the dashboard can flow out to screens quickly and consistently. \ No newline at end of file +The project includes a dashboard for managing content, a player runtime for rendering screens, an onboarding flow for connecting devices, and a bridge layer for remote screens. If you want to understand how the pieces fit together, the docs above cover the technical details without repeating the project overview. \ No newline at end of file diff --git a/docker-compose/.env.example b/docker-compose/.env.example new file mode 100644 index 0000000..1fbc4db --- /dev/null +++ b/docker-compose/.env.example @@ -0,0 +1,26 @@ +# Shared application settings +PULSE_SIGNAGE_IMAGE="git.lzstealth.com/lzstealth/pulse-signage:latest" +PULSE_SIGNAGE_SHARED_SECRET="" + +# Database settings for the web, player, and bridge services +DB_HOST="mysql" +DB_PORT=3306 +DB_NAME="pulse-signage" +DB_USER="pulse-signage" +DB_PASSWORD="signage_password" +MYSQL_ROOT_PASSWORD="root_password" + +# Player settings +PLAYER_IDENTIFIER="player-local" +PLAYER_PUBLIC_BASE_URL="http://localhost:8081" +PLAYER_INTERNAL_BASE_URL="http://player:8081" + +# Web app bootstrap settings +SESSION_MAX_AGE_DAYS=14 +DEFAULT_ADMIN_USERNAME="admin" +DEFAULT_ADMIN_NAME="Admin" +DEFAULT_ADMIN_PASSWORD="admin" +PASSWORD_HASH_ITERATIONS=310000 + +# Bridge settings for the player-bridge service +WEB_BASE_URL="http://web:8080" \ No newline at end of file diff --git a/docker-compose/.env.remote.example b/docker-compose/.env.remote.example new file mode 100644 index 0000000..d542bc5 --- /dev/null +++ b/docker-compose/.env.remote.example @@ -0,0 +1,11 @@ +# Shared application settings +PULSE_SIGNAGE_IMAGE="git.lzstealth.com/lzstealth/pulse-signage:latest" +PULSE_SIGNAGE_SHARED_SECRET="" + +# Player settings +PLAYER_IDENTIFIER="player-remote" +PLAYER_PUBLIC_BASE_URL="http://localhost:8081" +PLAYER_AGENT_RECONNECT_DELAY_MS=5000 + +# Remote player connectivity settings +THIN_CLIENT_BASE_URL="http://192.168.0.80:8090" \ No newline at end of file diff --git a/docker-compose/docker-compose.remote.yml b/docker-compose/docker-compose.remote.yml new file mode 100644 index 0000000..457e78c --- /dev/null +++ b/docker-compose/docker-compose.remote.yml @@ -0,0 +1,28 @@ +name: pulse-signage-remote + +services: + + player: + image: ${PULSE_SIGNAGE_IMAGE:-git.lzstealth.com/lzstealth/pulse-signage:latest} + restart: unless-stopped + ports: + - "8081:8081" + environment: + PLAYER_PUBLIC_BASE_URL: ${PLAYER_PUBLIC_BASE_URL:-http://localhost:8081} + THIN_CLIENT_BASE_URL: ${THIN_CLIENT_BASE_URL:-} + PULSE_SIGNAGE_SHARED_SECRET: ${PULSE_SIGNAGE_SHARED_SECRET:-} + volumes: + - pulse-signage:/app/media + command: ["node", "src/player.js"] + networks: + - pulse_signage + + + +volumes: + pulse-signage: + +networks: + pulse_signage: + name: pulse-signage-remote + external: false \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose/docker-compose.yml similarity index 64% rename from docker-compose.yml rename to docker-compose/docker-compose.yml index 6a533e2..9d06751 100644 --- a/docker-compose.yml +++ b/docker-compose/docker-compose.yml @@ -1,3 +1,5 @@ +name: pulse-signage + services: web: image: ${PULSE_SIGNAGE_IMAGE:-git.lzstealth.com/lzstealth/pulse-signage:latest} @@ -7,18 +9,17 @@ services: environment: DB_HOST: ${DB_HOST:-mysql} DB_PORT: ${DB_PORT:-3306} - DB_NAME: ${DB_NAME:-signage} - DB_USER: ${DB_USER:-signage_user} + DB_NAME: ${DB_NAME:-pulse-signage} + DB_USER: ${DB_USER:-pulse-signage} DB_PASSWORD: ${DB_PASSWORD:-signage_password} PULSE_SIGNAGE_SHARED_SECRET: ${PULSE_SIGNAGE_SHARED_SECRET:-} SESSION_MAX_AGE_DAYS: ${SESSION_MAX_AGE_DAYS:-14} - DASHBOARD_REFRESH_INTERVAL_MS: ${DASHBOARD_REFRESH_INTERVAL_MS:-2000} DEFAULT_ADMIN_USERNAME: ${DEFAULT_ADMIN_USERNAME:-admin} DEFAULT_ADMIN_NAME: ${DEFAULT_ADMIN_NAME:-Admin} DEFAULT_ADMIN_PASSWORD: ${DEFAULT_ADMIN_PASSWORD:-admin} PASSWORD_HASH_ITERATIONS: ${PASSWORD_HASH_ITERATIONS:-310000} volumes: - - media:/app/media + - pulse-signage:/app/media command: ["node", "src/web.js"] depends_on: mysql: @@ -34,14 +35,15 @@ services: environment: PLAYER_PUBLIC_BASE_URL: ${PLAYER_PUBLIC_BASE_URL:-http://localhost:8081} PLAYER_INTERNAL_BASE_URL: ${PLAYER_INTERNAL_BASE_URL:-http://player:8081} + PLAYER_IDENTIFIER: ${PLAYER_IDENTIFIER:-player-local} PULSE_SIGNAGE_SHARED_SECRET: ${PULSE_SIGNAGE_SHARED_SECRET:-} DB_HOST: ${DB_HOST:-mysql} DB_PORT: ${DB_PORT:-3306} - DB_NAME: ${DB_NAME:-signage} - DB_USER: ${DB_USER:-signage_user} + DB_NAME: ${DB_NAME:-pulse-signage} + DB_USER: ${DB_USER:-pulse-signage} DB_PASSWORD: ${DB_PASSWORD:-signage_password} volumes: - - media:/app/media + - pulse-signage:/app/media command: ["node", "src/player.js"] depends_on: mysql: @@ -49,12 +51,34 @@ services: networks: - pulse_signage + player-bridge: + image: ${PULSE_SIGNAGE_IMAGE:-git.lzstealth.com/lzstealth/pulse-signage:latest} + restart: unless-stopped + ports: + - "8090:8090" + environment: + WEB_BASE_URL: ${WEB_BASE_URL:-http://web:8080} + PULSE_SIGNAGE_SHARED_SECRET: ${PULSE_SIGNAGE_SHARED_SECRET:-} + DB_HOST: ${DB_HOST:-mysql} + DB_PORT: ${DB_PORT:-3306} + DB_NAME: ${DB_NAME:-pulse-signage} + DB_USER: ${DB_USER:-pulse-signage} + DB_PASSWORD: ${DB_PASSWORD:-signage_password} + command: ["node", "src/player-bridge/index.js"] + depends_on: + mysql: + condition: service_healthy + networks: + - pulse_signage + mysql: image: mysql:8.4 restart: unless-stopped + ports: + - "3306:3306" environment: - MYSQL_DATABASE: ${DB_NAME:-signage} - MYSQL_USER: ${DB_USER:-signage_user} + MYSQL_DATABASE: ${DB_NAME:-pulse-signage} + MYSQL_USER: ${DB_USER:-pulse-signage} MYSQL_PASSWORD: ${DB_PASSWORD:-signage_password} MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root_password} command: @@ -72,9 +96,9 @@ services: volumes: mysql_data: - media: + pulse-signage: networks: pulse_signage: - name: pulse_signage - external: false + name: pulse-signage + external: false \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..4fb0d23 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,13 @@ +# Documentation + +This folder contains the technical reference material for Pulse Signage. + +## What’s Here + +- [API reference](api.md) - the player HTTP surface and onboarding endpoints. +- [Database schema](schema.md) - the tables and data model used by the app. +- [WebSocket reference](websocket.md) - the live player and snapshot channels. + +## How To Read It + +If you want the big picture first, start with the main [project README](../README.md). It gives a plain overview of what Pulse Signage does, while the pages in this folder explain how the pieces work. \ No newline at end of file diff --git a/docs/schema.md b/docs/schema.md index 2f4f855..ed53229 100644 --- a/docs/schema.md +++ b/docs/schema.md @@ -113,7 +113,7 @@ Primary keys are `id` unless noted otherwise. Timestamps are stored as `created_ ## Devices - `d_players` - player registry and connection metadata. -- `d_screens` - screen records and playlist/player assignment. +- `d_screens` - screen records and playlist assignment. - `d_onboarding_devices` - device-to-screen bindings and onboarded client names. ## Announcements @@ -123,18 +123,18 @@ Primary keys are `id` unless noted otherwise. Timestamps are stored as `created_ ### `d_players` -- `device_id`, `public_base_url`, `internal_base_url`, `last_seen_at`, `created_at`, `modified_at` -- `device_id` is the primary key. +- `id`, `identifier`, `public_base_url`, `internal_base_url`, `last_seen_at`, `created_at`, `modified_at` +- `id` is the primary key. +- `identifier` is unique and is the stable player identity used by the app. ### `d_screens` -- `id`, `name`, `slug`, `playlist_id`, `player_id`, `created_at`, `created_by`, `modified_at`, `modified_by` +- `id`, `name`, `slug`, `playlist_id`, `created_at`, `created_by`, `modified_at`, `modified_by` - `slug` is unique. - Foreign keys: - `playlist_id` -> `c_playlists.id` with `ON DELETE SET NULL` - - `player_id` -> `d_players.id` with `ON DELETE RESTRICT` -- `player_id` is required and defaults to `'1'` for the current singleton-player model. +- Screens are no longer tied to a player foreign key directly; player registration and live connection metadata are tracked separately in `d_players`. ### `d_onboarding_devices` @@ -276,7 +276,6 @@ erDiagram C_SLIDES ||--o{ C_PLAYLIST_SLIDES : included_in C_PLAYLIST_SLIDES ||--o{ C_PLAYLIST_SLIDE_SCHEDULE_RULES : has_rules - D_PLAYERS ||--o{ D_SCREENS : assigned_to C_PLAYLISTS ||--o{ D_SCREENS : uses D_SCREENS ||--o{ D_ONBOARDING_DEVICES : binds D_ANNOUNCEMENTS ||--o{ D_ANNOUNCEMENT_SCREENS : targets diff --git a/package.json b/package.json index 48dfc24..cb2960b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pulse-signage", - "version": "2.5.14", + "version": "2.6.5", "private": false, "description": "Pulse Signage application with MySQL and media storage", "repository": { diff --git a/src/common.js b/src/common.js index 41e29d9..382db83 100644 --- a/src/common.js +++ b/src/common.js @@ -89,6 +89,7 @@ module.exports = { fetchPlayerPublicBaseUrl: data.fetchPlayerPublicBaseUrl, fetchScreenPlayerRecord: data.fetchScreenPlayerRecord, fetchTemplateById: data.fetchTemplateById, + fetchPlayerRegistrations: data.fetchPlayerRegistrations, fetchSlideById: data.fetchSlideById, fetchTemplatesData: data.fetchTemplatesData, fetchCanvasSizesData: data.fetchCanvasSizesData, diff --git a/src/data/admin.js b/src/data/admin.js index 61bb47e..2aa0b4b 100644 --- a/src/data/admin.js +++ b/src/data/admin.js @@ -22,10 +22,9 @@ async function fetchAdminData(pool) { ORDER BY s.id DESC `); const [screens] = await pool.query(` - SELECT s.id, s.name, s.slug, s.playlist_id, s.created_at, s.modified_at, s.created_by, s.modified_by, p.name AS playlist_name, pl.public_base_url + SELECT s.id, s.name, s.slug, s.playlist_id, s.created_at, s.modified_at, s.created_by, s.modified_by, p.name AS playlist_name FROM d_screens s LEFT JOIN c_playlists p ON p.id = s.playlist_id - LEFT JOIN d_players pl ON pl.device_id = s.player_id ORDER BY s.id DESC `); const [playlistSlides] = await pool.query(` diff --git a/src/data/index.js b/src/data/index.js index c6b066c..fa0a0ab 100644 --- a/src/data/index.js +++ b/src/data/index.js @@ -7,7 +7,8 @@ const { fetchPlaylistById } = require('./playlists'); const { normalizeDisplayMode, fetchTimetablesData, fetchTimetableGroupsPage, fetchTimetableGroupById, fetchTimetableEntriesByGroupId, buildTimetableGroupPayload } = require('./schedules'); const { fetchApiSourcesData, fetchApiSourcesPage, fetchApiSourceById, fetchApiSourceResponse, buildApiSourcePayload } = require('./api-sources'); const { fetchRssFeedsData, fetchRssFeedsPage, fetchRssFeedById, fetchRssFeedItemsByFeedId, normalizeRssFeedItem, buildRssFeedPayload, fetchRssFeedItems, replaceRssFeedItems } = require('./rss-feeds'); -const { slugify, uniqueScreenSlug, fetchScreenById, fetchScreenEditData, fetchScreenPlayerUrls, fetchPlayerPublicBaseUrl, fetchScreenPlayerRecord } = require('./screens'); +const { slugify, uniqueScreenSlug, fetchScreenById, fetchScreenEditData, fetchScreenPlayerUrls, fetchPlayerPublicBaseUrl, fetchScreenPlayerRecord, fetchPlayerRecordByIdentifier } = require('./screens'); +const { fetchPlayerRegistrations } = require('./player-registry'); const { fetchTemplateById, fetchTemplatesData, extractTemplateRegions, buildTemplatePayload } = require('./templates'); const { fetchCanvasSizesData, fetchCanvasSizeById, buildCanvasSizePayload, MAX_CANVAS_SIZE_DIMENSION } = require('./canvas-sizes'); const { fetchSlideById, buildSlidePayload } = require('./slides'); @@ -63,6 +64,8 @@ module.exports = { fetchScreenPlayerUrls, fetchPlayerPublicBaseUrl, fetchScreenPlayerRecord, + fetchPlayerRecordByIdentifier, + fetchPlayerRegistrations, fetchTemplateById, fetchSlideById, fetchTemplatesData, diff --git a/src/data/player-registry.js b/src/data/player-registry.js new file mode 100644 index 0000000..3a33d87 --- /dev/null +++ b/src/data/player-registry.js @@ -0,0 +1,140 @@ +function normalizeDeviceId(value) { + return String(value || '') + .trim() + .replace(/[^a-zA-Z0-9_-]/g, '') + .slice(0, 128); +} + +function normalizeBaseUrl(value) { + return String(value || '').trim().replace(/\/$/, ''); +} + +function normalizeIdentifier(value) { + return String(value || '').trim().slice(0, 255); +} + +async function columnExists(pool, tableName, columnName) { + const [rows] = await pool.query( + `SELECT COUNT(*) AS column_count + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = ? + AND COLUMN_NAME = ?`, + [tableName, columnName] + ); + + return Number(rows && rows[0] && rows[0].column_count) > 0; +} + +async function fetchPlayerRegistrations(pool) { + if (!pool) { + return []; + } + + const [rows] = await pool.query( + `SELECT id, identifier, public_base_url, internal_base_url, last_seen_at, modified_at + FROM d_players + ORDER BY modified_at DESC, identifier ASC` + ); + + return rows; +} + +function getConfiguredPlayerIdentifier() { + return normalizeDeviceId(process.env.PLAYER_IDENTIFIER || process.env.PLAYER_DEVICE_ID || ''); +} + +async function resolvePlayerRegistration(pool, identifier) { + const normalizedIdentifier = normalizeDeviceId(identifier); + if (!pool || !normalizedIdentifier) { + return null; + } + + const hasIdentifierColumn = await columnExists(pool, 'd_players', 'identifier'); + const hasDeviceIdColumn = await columnExists(pool, 'd_players', 'device_id'); + const identifierColumn = hasIdentifierColumn ? 'identifier' : (hasDeviceIdColumn ? 'device_id' : ''); + if (!identifierColumn) { + return null; + } + + const selectIdExpression = hasIdentifierColumn ? 'id' : 'NULL AS id'; + const selectIdentifierExpression = hasIdentifierColumn ? 'identifier' : 'device_id AS identifier'; + const orderByExpression = hasIdentifierColumn ? 'modified_at DESC, id DESC' : 'modified_at DESC'; + + const [rows] = await pool.query( + `SELECT ${selectIdExpression}, ${selectIdentifierExpression}, public_base_url, internal_base_url, last_seen_at + FROM d_players + WHERE ${identifierColumn} = ? + LIMIT 1`, + [normalizedIdentifier] + ); + + if (rows[0]) { + return rows[0]; + } + + const [fallbackRows] = await pool.query( + `SELECT ${selectIdExpression}, ${selectIdentifierExpression}, public_base_url, internal_base_url, last_seen_at + FROM d_players + ORDER BY ${orderByExpression} + LIMIT 1` + ); + + return fallbackRows[0] || null; +} + +async function upsertPlayerRegistration(pool, options) { + const identifier = normalizeDeviceId(options && (options.identifier || options.deviceId)); + const publicBaseUrl = normalizeBaseUrl(options && options.publicBaseUrl); + const internalBaseUrl = normalizeBaseUrl(options && options.internalBaseUrl); + + if (!pool || !identifier) { + return null; + } + + await pool.query( + `INSERT INTO d_players (identifier, public_base_url, internal_base_url, last_seen_at) + VALUES (?, ?, ?, CURRENT_TIMESTAMP) + ON DUPLICATE KEY UPDATE + public_base_url = VALUES(public_base_url), + internal_base_url = VALUES(internal_base_url), + last_seen_at = CURRENT_TIMESTAMP, + modified_at = CURRENT_TIMESTAMP`, + [identifier, publicBaseUrl || null, internalBaseUrl || null] + ); + + return resolvePlayerRegistration(pool, identifier); +} + +async function recordPlayerHeartbeat(pool, options) { + const identifier = normalizeDeviceId(options && (options.identifier || options.deviceId)); + const publicBaseUrl = normalizeBaseUrl(options && options.publicBaseUrl); + const internalBaseUrl = normalizeBaseUrl(options && options.internalBaseUrl); + + if (!pool || !identifier) { + return null; + } + + await pool.query( + `INSERT INTO d_players (identifier, public_base_url, internal_base_url, last_seen_at) + VALUES (?, ?, ?, CURRENT_TIMESTAMP) + ON DUPLICATE KEY UPDATE + public_base_url = COALESCE(VALUES(public_base_url), public_base_url), + internal_base_url = COALESCE(VALUES(internal_base_url), internal_base_url), + last_seen_at = CURRENT_TIMESTAMP, + modified_at = CURRENT_TIMESTAMP`, + [identifier, publicBaseUrl || null, internalBaseUrl || null] + ); + + return resolvePlayerRegistration(pool, identifier); +} + +module.exports = { + normalizeDeviceId: normalizeDeviceId, + normalizeIdentifier: normalizeIdentifier, + getConfiguredPlayerIdentifier: getConfiguredPlayerIdentifier, + fetchPlayerRegistrations: fetchPlayerRegistrations, + resolvePlayerRegistration: resolvePlayerRegistration, + upsertPlayerRegistration: upsertPlayerRegistration, + recordPlayerHeartbeat: recordPlayerHeartbeat +}; \ No newline at end of file diff --git a/src/data/screens.js b/src/data/screens.js index cff9207..69c25a0 100644 --- a/src/data/screens.js +++ b/src/data/screens.js @@ -13,6 +13,27 @@ function normalizePlayerBaseUrl(value) { return String(value || '').trim().replace(/\/$/, ''); } +function getConfiguredPlayerIdentifier() { + return String(process.env.PLAYER_IDENTIFIER || process.env.PLAYER_DEVICE_ID || '').trim() || null; +} + +async function fetchPlayerRecordByIdentifier(pool, identifier) { + const normalizedIdentifier = String(identifier || '').trim(); + if (!normalizedIdentifier) { + return null; + } + + const [rows] = await pool.query( + `SELECT id, identifier, public_base_url, internal_base_url, last_seen_at + FROM d_players + WHERE identifier = ? + LIMIT 1`, + [normalizedIdentifier] + ); + + return rows[0] || null; +} + function buildScreenPlayerUrl(screen, fallbackBaseUrl) { const slug = String(screen && screen.slug || '').trim(); if (!slug) { @@ -28,20 +49,21 @@ function buildScreenPlayerUrl(screen, fallbackBaseUrl) { } async function fetchScreenPlayerUrls(pool) { + const playerBaseUrl = await fetchPlayerPublicBaseUrl(pool); + if (!playerBaseUrl) { + return {}; + } + const [rows] = await pool.query(` - SELECT s.slug, p.public_base_url - FROM d_screens s - LEFT JOIN d_players p ON p.device_id = s.player_id - WHERE p.public_base_url IS NOT NULL - AND TRIM(p.public_base_url) <> '' - ORDER BY p.modified_at DESC, s.slug ASC + SELECT slug + FROM d_screens + ORDER BY slug ASC `); const playerUrls = {}; rows.forEach(function (row) { const slug = String(row && row.slug || '').trim(); - const publicBaseUrl = normalizePlayerBaseUrl(row && row.public_base_url); - const playerUrl = buildScreenPlayerUrl({ slug: slug }, publicBaseUrl); + const playerUrl = buildScreenPlayerUrl({ slug: slug }, playerBaseUrl); if (slug && playerUrl && !playerUrls[slug]) { playerUrls[slug] = playerUrl; } @@ -51,27 +73,32 @@ async function fetchScreenPlayerUrls(pool) { } async function fetchPlayerPublicBaseUrl(pool) { + const configuredPlayerIdentifier = getConfiguredPlayerIdentifier(); const [rows] = await pool.query(` SELECT public_base_url FROM d_players - WHERE device_id = '1' + WHERE identifier = ? LIMIT 1 - `); + `, [configuredPlayerIdentifier]); return normalizePlayerBaseUrl(rows[0] && rows[0].public_base_url) || null; } async function fetchScreenPlayerRecord(pool, slug) { - const [rows] = await pool.query(` - SELECT p.device_id, p.public_base_url, p.internal_base_url, p.last_seen_at - FROM d_screens s - JOIN d_players p ON p.device_id = s.player_id - WHERE s.slug = ? - ORDER BY p.modified_at DESC, p.device_id ASC - LIMIT 1 - `, [slug]); + if (slug) { + const [rows] = await pool.query( + `SELECT slug + FROM d_screens + WHERE slug = ? + LIMIT 1`, + [slug] + ); + if (!rows.length) { + return null; + } + } - return rows[0] || null; + return fetchPlayerRecordByIdentifier(pool, getConfiguredPlayerIdentifier()); } async function uniqueScreenSlug(pool, baseSlug, excludeId) { @@ -112,6 +139,8 @@ async function fetchScreenEditData(pool) { module.exports = { slugify, normalizePlayerBaseUrl, + getConfiguredPlayerIdentifier, + fetchPlayerRecordByIdentifier, buildScreenPlayerUrl, fetchScreenPlayerUrls, fetchPlayerPublicBaseUrl, diff --git a/src/db/index.js b/src/db/index.js index 44d84a9..2ff57a4 100644 --- a/src/db/index.js +++ b/src/db/index.js @@ -1,6 +1,18 @@ // Snapshot only: keep this file aligned with the current schema state. async function ensureSchema(pool, options) { - await pool.query(` + const schemaLockName = 'pulse_signage_schema_lock'; + const schemaConnection = await pool.getConnection(); + + try { + pool = schemaConnection; + + const [lockRows] = await pool.query('SELECT GET_LOCK(?, 120) AS lock_acquired', [schemaLockName]); + if (!Number(lockRows && lockRows[0] && lockRows[0].lock_acquired)) { + throw new Error('Unable to acquire the schema migration lock.'); + } + + try { + await pool.query(` CREATE TABLE IF NOT EXISTS c_canvas_sizes ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, @@ -116,13 +128,24 @@ async function ensureSchema(pool, options) { ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci `); + await pool.query(` + CREATE TABLE IF NOT EXISTS d_players ( + id INT AUTO_INCREMENT PRIMARY KEY, + identifier VARCHAR(128) NOT NULL UNIQUE, + public_base_url VARCHAR(512) NULL, + internal_base_url VARCHAR(512) NULL, + last_seen_at TIMESTAMP NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + await pool.query(` CREATE TABLE IF NOT EXISTS d_screens ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, slug VARCHAR(255) NOT NULL UNIQUE, playlist_id INT NULL, - player_id INT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, created_by INT NULL, modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, @@ -360,8 +383,15 @@ async function ensureSchema(pool, options) { ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci `); - const { runMigrations } = require('./migrations'); - await runMigrations(pool, options); + const { runMigrations } = require('./migrations'); + await runMigrations(pool, options); + } finally { + await pool.query('SELECT RELEASE_LOCK(?)', [schemaLockName]).catch(function () { + }); + } + } finally { + schemaConnection.release(); + } } module.exports = { diff --git a/src/db/migrations.js b/src/db/migrations.js index 9a2c262..82b12d4 100644 --- a/src/db/migrations.js +++ b/src/db/migrations.js @@ -19,10 +19,6 @@ const VERSIONED_MIGRATIONS = [ `); } - // Seed the singleton player row used by the current one-player model. - // For multi-player support, this seed and the hardcoded screen_id/player_id mapping will need to be replaced. - await pool.query(`INSERT IGNORE INTO d_players (device_id) VALUES ('1')`); - // Store the player pointer on screens so we can resolve the player without needing a player-side screen_id. // This is the singleton-player shortcut; a multi-player model should make this relational instead of hardcoded to '1'. if (!(await columnExists(pool, 'd_screens', 'player_id'))) { @@ -212,6 +208,93 @@ const VERSIONED_MIGRATIONS = [ run: async function (pool) { await ensureColumn(pool, 'c_template_regions', 'animation_json', 'JSON NULL', 'lock_ratio'); } + }, + { + version: '2.6.2', + label: 'v2.6.2 player identity schema', + run: async function (pool) { + if (!(await columnExists(pool, 'd_players', 'device_id'))) { + await dropForeignKeyIfExists(pool, 'd_screens', 'player_id'); + + if (!(await columnExists(pool, 'd_players', 'identifier'))) { + await ensureColumn(pool, 'd_players', 'identifier', 'VARCHAR(128) NOT NULL UNIQUE', 'id'); + } + if (!(await columnExists(pool, 'd_players', 'id'))) { + await ensureColumn(pool, 'd_players', 'id', 'INT NOT NULL AUTO_INCREMENT', null); + await pool.query('ALTER TABLE d_players ADD PRIMARY KEY (id)'); + } else if (!(await columnIsAutoIncrement(pool, 'd_players', 'id'))) { + await pool.query('ALTER TABLE d_players MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT'); + } + await pool.query('ALTER TABLE d_screens MODIFY COLUMN player_id INT NULL AFTER playlist_id'); + return; + } + + await dropForeignKeyIfExists(pool, 'd_screens', 'player_id'); + + await pool.query('DROP TABLE IF EXISTS d_players_rebuild'); + await pool.query(` + CREATE TABLE d_players_rebuild ( + id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, + identifier VARCHAR(128) NOT NULL UNIQUE, + public_base_url VARCHAR(512) NULL, + internal_base_url VARCHAR(512) NULL, + last_seen_at TIMESTAMP NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + await pool.query(` + INSERT INTO d_players_rebuild (identifier, public_base_url, internal_base_url, last_seen_at, created_at, modified_at) + SELECT DISTINCT + device_id AS identifier, + public_base_url, + internal_base_url, + last_seen_at, + created_at, + modified_at + FROM d_players + ORDER BY COALESCE(created_at, modified_at, device_id), device_id + `); + + await pool.query('DROP TEMPORARY TABLE IF EXISTS d_player_id_map'); + await pool.query(` + CREATE TEMPORARY TABLE d_player_id_map AS + SELECT old_players.device_id AS old_device_id, rebuilt_players.id AS new_player_id + FROM d_players old_players + JOIN d_players_rebuild rebuilt_players ON rebuilt_players.identifier = old_players.device_id + `); + + await pool.query( + `UPDATE d_screens s + JOIN d_player_id_map m ON m.old_device_id = CAST(s.player_id AS CHAR) + SET s.player_id = m.new_player_id + WHERE s.player_id IS NOT NULL` + ); + + await pool.query('DROP TABLE d_players'); + await pool.query('RENAME TABLE d_players_rebuild TO d_players'); + + await pool.query('ALTER TABLE d_screens MODIFY COLUMN player_id INT NULL AFTER playlist_id'); + } + }, + { + version: '2.6.3', + label: 'v2.6.3 screen-player fk removal', + run: async function (pool) { + await dropForeignKeyIfExists(pool, 'd_screens', 'player_id'); + if (await columnExists(pool, 'd_screens', 'player_id')) { + await pool.query('ALTER TABLE d_screens MODIFY COLUMN player_id INT NULL AFTER playlist_id'); + } + } + }, + { + version: '2.6.4', + label: 'v2.6.4 drop screen player id', + run: async function (pool) { + await dropForeignKeyIfExists(pool, 'd_screens', 'player_id'); + await dropColumnIfExists(pool, 'd_screens', 'player_id'); + } } ]; @@ -228,6 +311,20 @@ async function columnExists(pool, tableName, columnName) { return Number(rows && rows[0] && rows[0].column_count) > 0; } +async function columnIsAutoIncrement(pool, tableName, columnName) { + const [rows] = await pool.query( + `SELECT COUNT(*) AS auto_increment_count + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = ? + AND COLUMN_NAME = ? + AND EXTRA LIKE '%auto_increment%'`, + [tableName, columnName] + ); + + return Number(rows && rows[0] && rows[0].auto_increment_count) > 0; +} + async function ensureColumn(pool, tableName, columnName, columnDefinition, afterColumn) { if (await columnExists(pool, tableName, columnName)) { return; @@ -289,6 +386,32 @@ async function ensureForeignKey(pool, tableName, constraintName, columnName, ref } } +async function dropForeignKeyIfExists(pool, tableName, columnName) { + const [rows] = await pool.query( + `SELECT CONSTRAINT_NAME AS constraint_name + FROM information_schema.KEY_COLUMN_USAGE + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = ? + AND COLUMN_NAME = ? + AND REFERENCED_TABLE_NAME IS NOT NULL + LIMIT 1`, + [tableName, columnName] + ); + + const constraintName = String(rows && rows[0] && rows[0].constraint_name || '').trim(); + if (!constraintName) { + return; + } + + try { + await pool.query('ALTER TABLE ' + tableName + ' DROP FOREIGN KEY ' + constraintName); + } catch (error) { + if (!error || (error.code !== 'ER_CANT_DROP_FIELD_OR_KEY' && error.errno !== 1091)) { + throw error; + } + } +} + async function dropColumnIfExists(pool, tableName, columnName) { if (await columnExists(pool, tableName, columnName)) { try { @@ -443,9 +566,20 @@ async function runMigrations(pool, options) { // Only run migrations that are newer than the installed schema version and not beyond the app version. const targetVersion = String(appVersion || '0.0.0').trim(); const currentVersion = String(options && options.currentVersion || '0.0.0').trim(); + const legacyPlayerSchemaPresent = await columnExists(pool, 'd_players', 'device_id'); + const screenPlayerColumnPresent = await columnExists(pool, 'd_screens', 'player_id'); + let effectiveCurrentVersion = currentVersion; + + if (!legacyPlayerSchemaPresent && compareVersions(effectiveCurrentVersion, '2.1.0') < 0) { + effectiveCurrentVersion = '2.1.0'; + } + + if (!screenPlayerColumnPresent && compareVersions(effectiveCurrentVersion, '2.6.3') < 0) { + effectiveCurrentVersion = '2.6.3'; + } for (const migration of VERSIONED_MIGRATIONS) { - if (compareVersions(migration.version, currentVersion) > 0 && compareVersions(migration.version, targetVersion) <= 0) { + if (compareVersions(migration.version, effectiveCurrentVersion) > 0 && compareVersions(migration.version, targetVersion) <= 0) { await migration.run(pool); } } diff --git a/src/player/onboarding/index.js b/src/player/onboarding/index.js index df4256b..6f38572 100644 --- a/src/player/onboarding/index.js +++ b/src/player/onboarding/index.js @@ -1,8 +1,10 @@ // Player onboarding routes and signup flow helpers. +const express = require('express'); const { isClientNameAvailable, withClientNameReservation } = require('#src/data/client-name-check'); const { createStyledQrCodeSvg } = require('#src/data/qr-code'); -const { getSharedSecret, verifyPageAuthToken } = require('#src/request-auth'); +const { getSharedSecret, verifyPageAuthToken, createRequestAuthHeaders } = require('#src/request-auth'); +const { resolvePlayerRegistration, upsertPlayerRegistration: upsertPlayerRegistrationRecord } = require('#src/data/player-registry'); const { isTransientDbError } = require('./store'); const ONBOARDING_SIGNUP_LIMIT_WINDOW_MS = 5 * 60 * 1000; @@ -133,7 +135,7 @@ async function commitDeviceBinding(pool, deviceId, clientName, screenSlug, isNam }); } -async function upsertPlayerRegistration(pool, deviceId, publicBaseUrl, internalBaseUrl, screenSlug) { +async function upsertPlayerRegistration(pool, deviceId, publicBaseUrl, internalBaseUrl) { const normalizedDeviceId = normalizeDeviceId(deviceId); const normalizedPublicBaseUrl = String(publicBaseUrl || '').trim().replace(/\/$/, ''); const normalizedInternalBaseUrl = String(internalBaseUrl || '').trim().replace(/\/$/, ''); @@ -141,18 +143,11 @@ async function upsertPlayerRegistration(pool, deviceId, publicBaseUrl, internalB return null; } - await pool.query( - `INSERT INTO d_players (device_id, public_base_url, internal_base_url, last_seen_at) - VALUES (?, ?, ?, CURRENT_TIMESTAMP) - ON DUPLICATE KEY UPDATE public_base_url = VALUES(public_base_url), internal_base_url = VALUES(internal_base_url), last_seen_at = CURRENT_TIMESTAMP, modified_at = CURRENT_TIMESTAMP`, - [normalizedDeviceId, normalizedPublicBaseUrl || null, normalizedInternalBaseUrl || null] - ); - - return { - device_id: normalizedDeviceId, - public_base_url: normalizedPublicBaseUrl || null, - internal_base_url: normalizedInternalBaseUrl || null - }; + return upsertPlayerRegistrationRecord(pool, { + identifier: normalizedDeviceId, + publicBaseUrl: normalizedPublicBaseUrl || null, + internalBaseUrl: normalizedInternalBaseUrl || null + }); } async function bindPlayerToScreen(pool, deviceId, screenSlug) { @@ -167,25 +162,9 @@ async function bindPlayerToScreen(pool, deviceId, screenSlug) { return null; } - const screenId = Number(screenRows[0].id); - const connection = await pool.getConnection(); - try { - await connection.beginTransaction(); - // Current model: every screen binds to the shared player row '1'. - // If we introduce multiple players, resolve the correct player row here instead of hardcoding it. - await connection.query("UPDATE d_screens SET player_id = '1', modified_at = CURRENT_TIMESTAMP WHERE id = ?", [screenId]); - await connection.commit(); - } catch (error) { - await connection.rollback(); - throw error; - } finally { - connection.release(); - } - return { - screen_id: screenId, - screen_slug: normalizedScreenSlug, - player_id: '1' + screen_id: Number(screenRows[0].id), + screen_slug: normalizedScreenSlug }; } @@ -224,13 +203,66 @@ function registerPlayerOnboardingRoutes(app, options) { const common = options && options.common ? options.common : null; const playerRuntime = options && options.playerRuntime ? options.playerRuntime : null; const onboardingStore = options && options.onboardingStore ? options.onboardingStore : null; + const playerPublicBaseUrl = String(options && options.playerPublicBaseUrl || process.env.PLAYER_PUBLIC_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, ''); + const thinClientBaseUrl = String(options && options.thinClientBaseUrl || process.env.THIN_CLIENT_BASE_URL || '').trim().replace(/\/$/, ''); + const playerDeviceId = normalizeDeviceId(options && options.playerDeviceId); - if (!app || !pool || !common || !playerRuntime) { - throw new Error('registerPlayerOnboardingRoutes requires app, pool, common, and playerRuntime.'); + if (!app || !common) { + throw new Error('registerPlayerOnboardingRoutes requires app and common.'); + } + + if (!thinClientBaseUrl && (!pool || !playerRuntime)) { + throw new Error('registerPlayerOnboardingRoutes requires pool and playerRuntime unless thinClientBaseUrl is configured.'); } const sharedSecret = getSharedSecret(); + async function fetchThinClient(req, pathname, options) { + if (!thinClientBaseUrl) { + return null; + } + + const requestOptions = options && typeof options === 'object' ? options : {}; + const method = String(requestOptions.method || req.method || 'GET').trim().toUpperCase(); + const body = Object.prototype.hasOwnProperty.call(requestOptions, 'body') ? requestOptions.body : undefined; + const requestPathname = String(pathname || '').split('?')[0]; + const headers = Object.assign({}, requestOptions.headers || {}, createRequestAuthHeaders({ + method: method, + pathname: requestPathname, + body: body + })); + + if (req.headers['x-pulse-page-auth']) { + headers['x-pulse-page-auth'] = String(req.headers['x-pulse-page-auth']).trim(); + } + if (requestOptions.contentType) { + headers['content-type'] = requestOptions.contentType; + } + + return fetch(new URL(pathname, thinClientBaseUrl).toString(), { + method: method, + headers: headers, + body: body === undefined || body === null || method === 'GET' || method === 'HEAD' ? undefined : body + }); + } + + async function readJsonResponse(response) { + if (!response) { + return null; + } + + const contentType = String(response.headers && typeof response.headers.get === 'function' ? response.headers.get('content-type') : '').toLowerCase(); + if (contentType.indexOf('application/json') === -1 && contentType.indexOf('+json') === -1) { + return null; + } + + try { + return await response.json(); + } catch (_error) { + return null; + } + } + function requireOnboardingPageAuth(req, res, next) { if (!sharedSecret) { return next(); @@ -254,7 +286,7 @@ function registerPlayerOnboardingRoutes(app, options) { app.get('/onboard', async function (req, res, next) { res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate'); try { - res.send(common.renderPlayerOnboardingFormPage(String(req.query.deviceId || '').trim())); + res.send(common.renderPlayerOnboardingFormPage(String(req.query.deviceId || playerDeviceId || '').trim())); } catch (error) { next(error); } @@ -272,15 +304,32 @@ function registerPlayerOnboardingRoutes(app, options) { next(); }, async function (req, res, next) { try { - const status = await getOnboardingStatus(pool, req.query.deviceId); + const deviceId = normalizeDeviceId(req.query.deviceId) || playerDeviceId; + if (thinClientBaseUrl) { + const response = await fetchThinClient(req, '/api/onboarding/status?deviceId=' + encodeURIComponent(deviceId || ''), { + method: 'GET' + }); + if (!response) { + return res.status(502).json({ error: 'Player bridge unavailable.' }); + } + res.status(response.status); + const payload = await readJsonResponse(response); + if (!payload) { + return res.status(502).json({ error: 'Player bridge returned an invalid response.' }); + } + payload.playerUrl = payload && payload.screenSlug ? `${getPublicBaseUrl(req, playerPublicBaseUrl)}/screen/${encodeURIComponent(payload.screenSlug)}` : null; + return res.json(payload); + } + + const status = await getOnboardingStatus(pool, deviceId); res.json({ - deviceId: normalizeDeviceId(req.query.deviceId), + deviceId: normalizeDeviceId(deviceId), onboarded: Boolean(status && status.screen_id), clientName: status ? status.client_name : null, screenId: status ? status.screen_id : null, screenSlug: status ? status.screen_slug : null, screenName: status ? status.screen_name : null, - playerUrl: status && status.screen_slug ? `${getPublicBaseUrl(req)}/screen/${encodeURIComponent(status.screen_slug)}` : null + playerUrl: status && status.screen_slug ? `${getPublicBaseUrl(req, playerPublicBaseUrl)}/screen/${encodeURIComponent(status.screen_slug)}` : null }); } catch (error) { next(error); @@ -289,6 +338,16 @@ function registerPlayerOnboardingRoutes(app, options) { app.get('/api/onboarding/screens', requireOnboardingPageAuth, async function (_req, res, next) { try { + if (thinClientBaseUrl) { + const response = await fetchThinClient(_req, '/api/onboarding/screens', { + method: 'GET' + }); + res.status(response.status); + const text = await response.text(); + res.type(response.headers.get('content-type') || 'application/json'); + return res.send(text); + } + const [rows] = await pool.query('SELECT id, name, slug FROM d_screens ORDER BY name ASC, id ASC'); res.json({ screens: rows }); } catch (error) { @@ -298,11 +357,11 @@ function registerPlayerOnboardingRoutes(app, options) { app.get('/api/onboarding/qr', async function (req, res, next) { try { - const deviceId = normalizeDeviceId(req.query.deviceId); + const deviceId = normalizeDeviceId(req.query.deviceId) || playerDeviceId; if (!deviceId) { return res.status(400).json({ error: 'Device ID is required' }); } - const onboardingUrl = `${getPublicBaseUrl(req, options && options.playerPublicBaseUrl)}/onboard?deviceId=${encodeURIComponent(deviceId)}`; + const onboardingUrl = `${getPublicBaseUrl(req, playerPublicBaseUrl)}/onboard?deviceId=${encodeURIComponent(deviceId)}`; const svg = await createStyledQrCodeSvg({ value: onboardingUrl, qr_margin: 20 }); res.set('Content-Type', 'image/svg+xml; charset=utf-8'); res.set('Cache-Control', 'no-store'); @@ -312,9 +371,9 @@ function registerPlayerOnboardingRoutes(app, options) { } }); - app.post('/api/onboarding', requireOnboardingPageAuth, async function (req, res, next) { + app.post('/api/onboarding', requireOnboardingPageAuth, express.json(), async function (req, res, next) { try { - const deviceId = normalizeDeviceId(req.body && req.body.deviceId); + const deviceId = normalizeDeviceId(req.body && req.body.deviceId) || playerDeviceId; const clientName = String((req.body && req.body.clientName) || '').trim(); const screenSlug = String((req.body && req.body.screenSlug) || '').trim(); const retryAfterSeconds = isOnboardingSignupRateLimited(req, deviceId); @@ -322,6 +381,30 @@ function registerPlayerOnboardingRoutes(app, options) { res.set('Retry-After', String(retryAfterSeconds)); return res.status(429).json({ error: 'Too many onboarding attempts. Please try again later.' }); } + + if (thinClientBaseUrl) { + const forwardedBody = Object.assign({}, req.body || {}, { + deviceId: deviceId + }); + const response = await fetch(new URL('/api/onboarding', thinClientBaseUrl).toString(), { + method: 'POST', + headers: Object.assign({ + 'content-type': 'application/json' + }, createRequestAuthHeaders({ + method: 'POST', + pathname: '/api/onboarding', + body: forwardedBody + }), req.headers['x-pulse-page-auth'] ? { 'x-pulse-page-auth': String(req.headers['x-pulse-page-auth']).trim() } : {}), + body: JSON.stringify(forwardedBody) + }); + res.status(response.status); + const payload = await readJsonResponse(response); + if (!payload) { + return res.status(502).json({ error: 'Player bridge returned an invalid response.' }); + } + payload.playerUrl = payload && payload.screenSlug ? `${getPublicBaseUrl(req, playerPublicBaseUrl)}/screen/${encodeURIComponent(payload.screenSlug)}` : `${getPublicBaseUrl(req, playerPublicBaseUrl)}/screen/${encodeURIComponent(screenSlug)}`; + return res.json(payload); + } if (!deviceId) { return res.status(400).json({ error: 'Device ID is required' }); } @@ -340,11 +423,14 @@ function registerPlayerOnboardingRoutes(app, options) { screenId: status && status.screen_id ? status.screen_id : null, screenSlug: status ? status.screen_slug : screenSlug, screenName: status && status.screen_name ? status.screen_name : null, - playerUrl: status && status.screen_slug ? `${getPublicBaseUrl(req)}/screen/${encodeURIComponent(status.screen_slug)}` : `${getPublicBaseUrl(req)}/screen/${encodeURIComponent(screenSlug)}`, + playerUrl: status && status.screen_slug ? `${getPublicBaseUrl(req, playerPublicBaseUrl)}/screen/${encodeURIComponent(status.screen_slug)}` : `${getPublicBaseUrl(req, playerPublicBaseUrl)}/screen/${encodeURIComponent(screenSlug)}`, queued: Boolean(status && status.queued) }); } catch (error) { - next(error); + const statusCode = Number(error && error.statusCode || error && error.status || 500); + res.status(Number.isFinite(statusCode) && statusCode >= 400 ? statusCode : 500).json({ + error: error && error.message ? error.message : 'Onboarding failed.' + }); } }); } diff --git a/src/player/onboarding/player-onboarding-form.script.html b/src/player/onboarding/player-onboarding-form.script.html index 3c1a8db..e82e2e7 100644 --- a/src/player/onboarding/player-onboarding-form.script.html +++ b/src/player/onboarding/player-onboarding-form.script.html @@ -39,8 +39,14 @@ return screens; }); } - if (!deviceId) { setMessage("Missing device id. Scan the QR code from the player screen again."); return; } - try { window.localStorage.setItem(deviceKey, deviceId); } catch (_error) {} + try { + if (!deviceId) { + deviceId = window.localStorage.getItem(deviceKey) || ""; + } + if (deviceId) { + window.localStorage.setItem(deviceKey, deviceId); + } + } catch (_error) {} loadScreens().then(function () { try { var storedClientName = window.localStorage.getItem(clientNameKey) || ""; @@ -58,10 +64,14 @@ if (!clientName) { setMessage("Client name is required."); return; } if (!screenSlug) { setMessage("Screen is required."); return; } setMessage("Saving client..."); + var payload = { clientName: clientName, screenSlug: screenSlug }; + if (deviceId) { + payload.deviceId = deviceId; + } fetch("/api/onboarding", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, - body: JSON.stringify({ deviceId: deviceId, clientName: clientName, screenSlug: screenSlug }) + body: JSON.stringify(payload) }) .then(function (response) { if (response.ok) { diff --git a/src/player/onboarding/player-onboarding-landing.script.html b/src/player/onboarding/player-onboarding-landing.script.html index 85f8f73..2a89920 100644 --- a/src/player/onboarding/player-onboarding-landing.script.html +++ b/src/player/onboarding/player-onboarding-landing.script.html @@ -131,7 +131,7 @@ if (!storedClientName && storedScreenSlug) { storedClientName = window.localStorage.getItem(getClientNameStorageKey(storedScreenSlug)) || ""; } if (storedClientName && localForm) { var clientNameInput = localForm.querySelector("input[name=\"clientName\"]"); - if (clientNameInput && !clientNameInput.value) { clientNameInput.value = storedClientName; } + if (clientNameInput) { clientNameInput.value = storedClientName; } } if (storedScreenSlug && localScreenSelect) { localScreenSelect.value = storedScreenSlug; } } catch (_error) {} diff --git a/src/player/public/js/player-page-commands.js b/src/player/public/js/player-page-commands.js index 07c8899..b036ecd 100644 --- a/src/player/public/js/player-page-commands.js +++ b/src/player/public/js/player-page-commands.js @@ -263,20 +263,33 @@ function renderSlideMarkup(markup, shouldFade) { }); } + function schedulePostRenderSetup(root, delayMs) { + if (!root) { + return; + } + + if (root.isConnected === false) { + return; + } + + if (typeof syncRtmpRegions === 'function') { + syncRtmpRegions(root); + } + + if (!isThumbnailPreview()) { + initializeRegionInstances(root); + } + + initializeRenderedVideoPlayback(root, delayMs); + + if (typeof playRegionAnimations === 'function') { + playRegionAnimations(root, 'intro'); + } + } + if (!shouldFade) { app.innerHTML = markup; - if (typeof syncRtmpRegions === 'function') { - syncRtmpRegions(app); - } - if (!isThumbnailPreview()) { - initializeRegionInstances(app); - } - initializeRenderedVideoPlayback(app); - if (typeof playRegionAnimations === 'function') { - window.requestAnimationFrame(function () { - playRegionAnimations(app, 'intro'); - }); - } + schedulePostRenderSetup(app, 0); return app.firstElementChild; } @@ -325,11 +338,7 @@ function renderSlideMarkup(markup, shouldFade) { app.innerHTML = ''; nextShell.style.opacity = '1'; app.appendChild(nextShell); - if (typeof syncRtmpRegions === 'function') { - syncRtmpRegions(nextShell); - } - initializeRegionInstances(nextShell); - initializeRenderedVideoPlayback(nextShell, slideFadeDurationMs / 2); + schedulePostRenderSetup(nextShell, slideFadeDurationMs / 2); return nextShell; } @@ -340,24 +349,12 @@ function renderSlideMarkup(markup, shouldFade) { pauseRenderedVideoPlayback(previousShell, slideFadeDurationMs / 2); app.appendChild(nextShell); - void nextShell.offsetHeight; window.requestAnimationFrame(function () { nextShell.style.opacity = '1'; previousShell.style.opacity = '0'; - if (typeof playRegionAnimations === 'function') { - playRegionAnimations(nextShell, 'intro'); - } + schedulePostRenderSetup(nextShell, slideFadeDurationMs / 2); }); - if (typeof syncRtmpRegions === 'function') { - syncRtmpRegions(nextShell); - } - - if (!isThumbnailPreview()) { - initializeRegionInstances(nextShell); - } - initializeRenderedVideoPlayback(nextShell, slideFadeDurationMs / 2); - slideTransitionTimer = window.setTimeout(function () { if (previousShell && previousShell.parentNode) { previousShell.parentNode.removeChild(previousShell); diff --git a/src/player/public/js/player-page-playback.js b/src/player/public/js/player-page-playback.js index f689396..9907067 100644 --- a/src/player/public/js/player-page-playback.js +++ b/src/player/public/js/player-page-playback.js @@ -54,6 +54,9 @@ async function renderSlideAtIndex(sourceSlides, targetIndex) { index = currentIndex; var markup = buildSlideMarkup(slide); renderSlideMarkup(markup, currentPlaylistFadeBetweenSlides); + if (typeof scheduleSlideMarkupPreload === 'function') { + scheduleSlideMarkupPreload(availableSlides, currentIndex); + } sendCommandState(slide); if (!isPaused) { scheduleSlideAdvance(getSlideHoldDelay(Math.max(1, Number(slide.duration_seconds || 10)) * 1000)); @@ -90,6 +93,9 @@ function showCurrent() { if (typeof syncRtmpWarmups === 'function') { syncRtmpWarmups(activeSlides, index); } + if (typeof scheduleSlideMarkupPreload === 'function') { + scheduleSlideMarkupPreload(activeSlides, index); + } if (!activeSlides.length) { renderEmpty(slides.length ? 'No slides are scheduled for this time.' : 'No slides assigned to this screen yet.'); lastRenderedViewKey = getCurrentRenderKey(activeSlides); @@ -211,6 +217,9 @@ function refresh() { if (typeof syncRtmpWarmups === 'function') { syncRtmpWarmups(nextActiveSlides, index); } + if (typeof scheduleSlideMarkupPreload === 'function') { + scheduleSlideMarkupPreload(nextActiveSlides, index); + } if (nextActiveSlides.length < 2) { pendingPlaylistUpdate = { slides: nextSlides, diff --git a/src/player/public/js/player-page-playlist.js b/src/player/public/js/player-page-playlist.js index ec72f58..5d6b6c5 100644 --- a/src/player/public/js/player-page-playlist.js +++ b/src/player/public/js/player-page-playlist.js @@ -84,7 +84,7 @@ function getCurrentRenderKey(activeSlides) { return [currentPlaylistSignature || '', viewportKey, 'slide', slide && slide.id ? slide.id : ''].join('|'); } -// Pick the current slide and the next slide for webpage preloading. +// Pick the next slide for webpage preloading. function getWebpagePreloadSlides(sourceSlides, targetIndex) { const availableSlides = Array.isArray(sourceSlides) ? sourceSlides : []; if (!availableSlides.length) { @@ -97,19 +97,71 @@ function getWebpagePreloadSlides(sourceSlides, targetIndex) { } const preloadSlides = []; - const currentSlide = availableSlides[normalizedIndex]; const nextSlide = availableSlides[normalizedIndex + 1]; - if (currentSlide) { - preloadSlides.push(currentSlide); - } - if (nextSlide && nextSlide !== currentSlide) { + if (nextSlide) { preloadSlides.push(nextSlide); } return preloadSlides; } +// Pick the next slide to warm its markup before it becomes visible. +function getSlideMarkupPreloadSlides(sourceSlides, targetIndex) { + const availableSlides = Array.isArray(sourceSlides) ? sourceSlides : []; + if (!availableSlides.length) { + return []; + } + + let normalizedIndex = Number(targetIndex || 0); + if (!Number.isFinite(normalizedIndex) || normalizedIndex < 0 || normalizedIndex >= availableSlides.length) { + normalizedIndex = 0; + } + + const preloadSlides = []; + const nextSlide = availableSlides[normalizedIndex + 1]; + + if (nextSlide) { + preloadSlides.push(nextSlide); + } + + return preloadSlides; +} + +function scheduleSlideMarkupPreload(sourceSlides, targetIndex) { + if (window.__pulseThumbnailPreview) { + return; + } + + const preloadSlides = getSlideMarkupPreloadSlides(sourceSlides, targetIndex); + if (!preloadSlides.length || typeof primeSlideMarkup !== 'function') { + return; + } + + const slide = preloadSlides[0]; + const preloadSignature = [ + currentPlaylistSignature || '', + slide && slide.id ? slide.id : '', + slide && slide.template_id ? slide.template_id : '', + slide && slide.modified_at ? slide.modified_at : '', + window.innerWidth + 'x' + window.innerHeight, + videoRegionRenderVersion || 0 + ].join('|'); + + if (scheduleSlideMarkupPreload.signature === preloadSignature) { + return; + } + + scheduleSlideMarkupPreload.signature = preloadSignature; + + window.setTimeout(function () { + if (scheduleSlideMarkupPreload.signature !== preloadSignature) { + return; + } + primeSlideMarkup(slide); + }, 0); +} + // Mount hidden iframe preloads for the chosen webpage URLs. function syncWebpagePreloads(sourceSlides, targetIndex) { const urls = getWebpageUrls(getWebpagePreloadSlides(sourceSlides, targetIndex)); diff --git a/src/player/public/js/player-page-rendering.js b/src/player/public/js/player-page-rendering.js index 673b1d3..8e3a2e3 100644 --- a/src/player/public/js/player-page-rendering.js +++ b/src/player/public/js/player-page-rendering.js @@ -893,6 +893,45 @@ function getSlideMarkupCacheKey(slide) { return [currentPlaylistSignature || '', slide && slide.id ? slide.id : '', slide && slide.template_id ? slide.template_id : '', slide && slide.modified_at ? slide.modified_at : '', viewportKey, videoRegionRenderVersion || 0].join('|'); } +function restorePlayerCanvasDimensions(width, height) { + if (!document || !document.documentElement) { + return; + } + + var style = document.documentElement.style; + if (width) { + style.setProperty('--player-canvas-width', width); + } else { + style.removeProperty('--player-canvas-width'); + } + + if (height) { + style.setProperty('--player-canvas-height', height); + } else { + style.removeProperty('--player-canvas-height'); + } +} + +function primeSlideMarkup(slide) { + if (!slide) { + return ''; + } + + var cachedMarkup = getCachedSlideMarkup(slide); + if (cachedMarkup) { + return cachedMarkup; + } + + var previousWidth = document && document.documentElement && document.documentElement.style ? String(document.documentElement.style.getPropertyValue('--player-canvas-width') || '') : ''; + var previousHeight = document && document.documentElement && document.documentElement.style ? String(document.documentElement.style.getPropertyValue('--player-canvas-height') || '') : ''; + + try { + return buildSlideMarkupForState(slide, false); + } finally { + restorePlayerCanvasDimensions(previousWidth.trim(), previousHeight.trim()); + } +} + function notifyVideoRegionSourceReady() { if (typeof videoRegionRenderVersion === 'number') { videoRegionRenderVersion += 1; @@ -919,9 +958,12 @@ function setCachedSlideMarkup(slide, markup) { // Slide rendering and markup cache helpers. // Choose the right slide renderer and cache the result. -function buildSlideMarkup(slide) { - lastRenderedSlide = slide || null; - syncBlackoutState(); +function buildSlideMarkupForState(slide, updateCurrentState) { + if (updateCurrentState) { + lastRenderedSlide = slide || null; + syncBlackoutState(); + } + var cachedMarkup = getCachedSlideMarkup(slide); if (cachedMarkup) { return cachedMarkup; @@ -938,3 +980,7 @@ function buildSlideMarkup(slide) { setCachedSlideMarkup(slide, markup); return markup; } + +function buildSlideMarkup(slide) { + return buildSlideMarkupForState(slide, true); +} diff --git a/src/player/regions/rtmp.js b/src/player/regions/rtmp.js index ea4275b..1c70235 100644 --- a/src/player/regions/rtmp.js +++ b/src/player/regions/rtmp.js @@ -304,13 +304,9 @@ function getRtmpWarmupSlides(sourceSlides, targetIndex) { } var warmupSlides = []; - var currentSlide = availableSlides[normalizedIndex]; var nextSlide = availableSlides[normalizedIndex + 1]; - if (currentSlide) { - warmupSlides.push(currentSlide); - } - if (nextSlide && nextSlide !== currentSlide) { + if (nextSlide) { warmupSlides.push(nextSlide); } @@ -693,12 +689,11 @@ function startRtmpPlayback(video, sourceUrl, disableAudio, skipUnavailable, plac if (window.Hls && window.Hls.isSupported && window.Hls.isSupported()) { var hls = new window.Hls({ enableWorker: true, - lowLatencyMode: true, - liveSyncDurationCount: 4, - liveMaxLatencyDurationCount: 8, - maxBufferLength: 20, + liveSyncDurationCount: 6, + liveMaxLatencyDurationCount: 12, + maxBufferLength: 30, maxLiveSyncPlaybackRate: 1, - backBufferLength: 30 + backBufferLength: 60 }); video.__rtmpHls = hls; hls.attachMedia(video); diff --git a/src/player/regions/video.js b/src/player/regions/video.js index 84d7b13..20d4fd9 100644 --- a/src/player/regions/video.js +++ b/src/player/regions/video.js @@ -122,7 +122,7 @@ function renderVideoRegion(region, regionContent) { videoRegionLastGoodSrcCache[regionKey] = requestedSrc; } setVideoSourceAvailability(requestedSrc, true); - return '
'; + return ''; } var requestedState = getVideoSourceAvailability(requestedSrc); @@ -132,7 +132,7 @@ function renderVideoRegion(region, regionContent) { if (regionKey) { videoRegionLastGoodSrcCache[regionKey] = requestedSrc; } - return ''; + return ''; } scheduleVideoSourceProbe(regionKey, requestedSrc, false); @@ -141,7 +141,7 @@ function renderVideoRegion(region, regionContent) { if (cachedSrc !== requestedSrc) { logVideoRegionStatus('Keeping the previous playable video until the new mirrored file finishes transferring.', 'region=' + regionKey + ' old=' + cachedSrc + ' new=' + requestedSrc); } - return ''; + return ''; } return ''; diff --git a/src/player/routes.js b/src/player/routes.js index 17fd1dd..8b3d986 100644 --- a/src/player/routes.js +++ b/src/player/routes.js @@ -3,7 +3,7 @@ const fs = require('fs'); const express = require('express'); const path = require('path'); -const { getSharedSecret, createPageAuthBundle, verifyPageAuthToken, verifyRequestAuth } = require('#src/request-auth'); +const { getSharedSecret, createPageAuthBundle, verifyPageAuthToken, verifyRequestAuth, createRequestAuthHeaders } = require('#src/request-auth'); const { buildThumbnailPreviewData } = require('./thumbnail-preview'); const TRANSIENT_DB_ERROR_CODES = ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'ENOTFOUND', 'PROTOCOL_CONNECTION_LOST', 'POOL_CLOSED', 'ERR_POOL_CLOSED']; @@ -12,6 +12,17 @@ function isTransientDbError(error) { return Boolean(error && TRANSIENT_DB_ERROR_CODES.indexOf(String(error.code || '').trim()) !== -1); } +function isBridgeFetchError(error) { + const message = String(error && error.message || '').toLowerCase(); + return Boolean(error && ( + message.indexOf('fetch failed') !== -1 || + message.indexOf('network error') !== -1 || + message.indexOf('econnreset') !== -1 || + message.indexOf('econnrefused') !== -1 || + message.indexOf('enotfound') !== -1 + )); +} + function registerPlayerRoutes(app, options) { const pool = options && options.pool ? options.pool : null; const common = options && options.common ? options.common : null; @@ -22,14 +33,68 @@ function registerPlayerRoutes(app, options) { const rtmpStreamService = options && options.rtmpStreamService ? options.rtmpStreamService : null; const playerPublicBaseUrl = String(options && options.playerPublicBaseUrl || process.env.PLAYER_PUBLIC_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, ''); const playerInternalBaseUrl = String(options && options.playerInternalBaseUrl || process.env.PLAYER_INTERNAL_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, ''); - const playerIdentifier = String(options && options.playerIdentifier || '1').trim() || '1'; + const thinClientBaseUrl = String(options && options.thinClientBaseUrl || process.env.THIN_CLIENT_BASE_URL || '').trim().replace(/\/$/, ''); + const playerDeviceId = String(options && options.playerDeviceId || '').trim() || null; - if (!app || !pool || !common || !mediaDir || !assetDir || !playerRuntime || !playerPlaylistService || !rtmpStreamService) { - throw new Error('registerPlayerRoutes requires app, pool, common, mediaDir, assetDir, playerRuntime, playerPlaylistService, and rtmpStreamService.'); + if (!app || !common || !mediaDir || !assetDir || !playerRuntime || !rtmpStreamService) { + throw new Error('registerPlayerRoutes requires app, common, mediaDir, assetDir, playerRuntime, and rtmpStreamService.'); + } + + if (!thinClientBaseUrl && (!pool || !playerPlaylistService)) { + throw new Error('registerPlayerRoutes requires pool and playerPlaylistService unless thinClientBaseUrl is configured.'); } const sharedSecret = getSharedSecret(); + async function fetchThinClient(req, pathname, options) { + if (!thinClientBaseUrl) { + return null; + } + + const requestOptions = options && typeof options === 'object' ? options : {}; + const method = String(requestOptions.method || req.method || 'GET').trim().toUpperCase(); + const body = Object.prototype.hasOwnProperty.call(requestOptions, 'body') ? requestOptions.body : undefined; + const requestPathname = String(pathname || '').split('?')[0]; + const headers = Object.assign({}, requestOptions.headers || {}, createRequestAuthHeaders({ + method: method, + pathname: requestPathname, + body: body + })); + + if (req.headers['x-pulse-page-auth']) { + headers['x-pulse-page-auth'] = String(req.headers['x-pulse-page-auth']).trim(); + } + if (req.headers['if-none-match']) { + headers['if-none-match'] = String(req.headers['if-none-match']).trim(); + } + if (requestOptions.contentType) { + headers['content-type'] = requestOptions.contentType; + } + + return fetch(new URL(pathname, thinClientBaseUrl).toString(), { + method: method, + headers: headers, + body: body === undefined || body === null || method === 'GET' || method === 'HEAD' ? undefined : body + }); + } + + async function readJsonResponse(response) { + if (!response) { + return null; + } + + const contentType = String(response.headers && typeof response.headers.get === 'function' ? response.headers.get('content-type') : '').toLowerCase(); + if (contentType.indexOf('application/json') === -1 && contentType.indexOf('+json') === -1) { + return null; + } + + try { + return await response.json(); + } catch (_error) { + return null; + } + } + function requirePageAuth(allowedScopes) { return function (req, res, next) { if (!sharedSecret) { @@ -114,6 +179,26 @@ function registerPlayerRoutes(app, options) { }); app.get('/api/media/config', requireRequestAuth, function (_req, res) { + if (thinClientBaseUrl) { + void fetch(new URL('/api/media/config', thinClientBaseUrl).toString(), { + method: 'GET', + headers: createRequestAuthHeaders({ + method: 'GET', + pathname: '/api/media/config' + }) + }).then(async function (response) { + res.status(response.status); + const contentType = response.headers.get('content-type'); + if (contentType) { + res.type(contentType); + } + res.send(await response.text()); + }).catch(function (_error) { + res.status(502).json({ error: 'Thin client unavailable.' }); + }); + return; + } + res.json({ mediaDir: mediaDir, uploadDir: path.join(mediaDir, 'uploads') @@ -213,9 +298,35 @@ function registerPlayerRoutes(app, options) { app.get('/screen/:slug', function (req, res) { res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate'); res.set('Pragma', 'no-cache'); + if (thinClientBaseUrl) { + const pageAuthToken = createPageAuthBundle({ scope: 'player', slug: String(req.params.slug || '').trim() }).token; + void fetchThinClient(req, '/api/screens/' + encodeURIComponent(req.params.slug) + '/playlist?ts=' + Date.now(), { + method: 'GET', + headers: pageAuthToken ? { 'x-pulse-page-auth': pageAuthToken } : {} + }).then(async function (response) { + if (!response || response.status >= 400) { + res.set('X-Player-Offline', '1'); + return res.send(common.renderPlayerPage(req.params.slug, null)); + } + const data = await readJsonResponse(response); + if (!data) { + res.set('X-Player-Offline', '1'); + return res.send(common.renderPlayerPage(req.params.slug, null)); + } + res.send(common.renderPlayerPage(req.params.slug, data)); + }).catch(function (error) { + if (!isBridgeFetchError(error)) { + console.error(error); + } + res.set('X-Player-Offline', '1'); + res.send(common.renderPlayerPage(req.params.slug, null)); + }); + return; + } + const { bindPlayerToScreen } = require('./onboarding'); - if (playerIdentifier) { - void bindPlayerToScreen(pool, playerIdentifier, req.params.slug) + if (playerDeviceId) { + void bindPlayerToScreen(pool, playerDeviceId, req.params.slug) .catch(function (error) { console.error(error); }); @@ -231,6 +342,19 @@ function registerPlayerRoutes(app, options) { app.get('/api/internal/slide-thumbnails/:id/preview', requireRequestAuth, async function (req, res, next) { try { + if (thinClientBaseUrl) { + const response = await fetchThinClient(req, '/api/internal/slide-thumbnails/' + encodeURIComponent(req.params.id) + '/preview', { + method: 'GET' + }); + if (!response) { + return res.status(502).send('Thin client unavailable'); + } + res.status(response.status); + res.set('Cache-Control', response.headers.get('cache-control') || 'no-store, no-cache, must-revalidate, proxy-revalidate'); + res.type(response.headers.get('content-type') || 'text/html; charset=utf-8'); + return res.send(await response.text()); + } + const slide = await common.fetchSlideById(pool, Number(req.params.id)); if (!slide) { return res.status(404).send('Slide not found'); @@ -273,6 +397,29 @@ function registerPlayerRoutes(app, options) { app.get('/api/screens/:slug/playlist', requirePageAuth(['player']), async function (req, res, next) { try { + if (thinClientBaseUrl) { + const response = await fetchThinClient(req, '/api/screens/' + encodeURIComponent(req.params.slug) + '/playlist', { + method: 'GET' + }); + if (!response) { + return res.status(502).json({ error: 'Thin client unavailable.' }); + } + res.status(response.status); + const etag = response.headers.get('etag'); + const cacheControl = response.headers.get('cache-control'); + if (etag) { + res.set('ETag', etag); + } + if (cacheControl) { + res.set('Cache-Control', cacheControl); + } + if (response.status === 304) { + return res.end(); + } + res.type(response.headers.get('content-type') || 'application/json'); + return res.send(await response.text()); + } + res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate'); const data = await playerPlaylistService.buildScreenPlaylist(req.params.slug); if (!data.screen) { @@ -293,6 +440,29 @@ function registerPlayerRoutes(app, options) { app.get('/api/screens/:slug/announcement', requirePageAuth(['player']), async function (req, res, next) { try { + if (thinClientBaseUrl) { + const response = await fetchThinClient(req, '/api/screens/' + encodeURIComponent(req.params.slug) + '/announcement', { + method: 'GET' + }); + if (!response) { + return res.status(502).json({ error: 'Thin client unavailable.' }); + } + res.status(response.status); + const etag = response.headers.get('etag'); + const cacheControl = response.headers.get('cache-control'); + if (etag) { + res.set('ETag', etag); + } + if (cacheControl) { + res.set('Cache-Control', cacheControl); + } + if (response.status === 304) { + return res.end(); + } + res.type(response.headers.get('content-type') || 'application/json'); + return res.send(await response.text()); + } + res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate'); const announcement = typeof common.fetchActiveAnnouncement === 'function' ? await common.fetchActiveAnnouncement(pool, req.params.slug) @@ -335,13 +505,15 @@ function registerPlayerRoutes(app, options) { const connections = playerRuntime.snapshotConnections(req.params.slug); let screen = null; let screenLookupFailed = false; - try { - const [screenRows] = await pool.query('SELECT id, name, slug FROM d_screens WHERE slug = ?', [req.params.slug]); - screen = screenRows[0] || null; - } catch (error) { - screenLookupFailed = isTransientDbError(error); - if (!screenLookupFailed) { - throw error; + if (pool && typeof pool.query === 'function') { + try { + const [screenRows] = await pool.query('SELECT id, name, slug FROM d_screens WHERE slug = ?', [req.params.slug]); + screen = screenRows[0] || null; + } catch (error) { + screenLookupFailed = isTransientDbError(error); + if (!screenLookupFailed) { + throw error; + } } } res.json({ @@ -374,7 +546,7 @@ function registerPlayerRoutes(app, options) { const isRedirectCommand = command === 'redirect'; let screen = null; let screenLookupFailed = false; - if (!isRedirectCommand) { + if (!isRedirectCommand && pool && typeof pool.query === 'function') { try { const [screenRows] = await pool.query('SELECT id, name, slug FROM d_screens WHERE slug = ?', [req.params.slug]); screen = screenRows[0] || null; diff --git a/src/web.js b/src/web.js index 4fc433f..255a963 100644 --- a/src/web.js +++ b/src/web.js @@ -62,7 +62,7 @@ async function start() { const playerActionService = createPlayerActionService({ pool: pool, common: common, - playerInternalBaseUrl: webConfig.playerInternalBaseUrl + playerInternalBaseUrl: webConfig.thinClientBaseUrl }); const notifyPlayerScreens = createNotifyPlayerScreens(playerActionService.forwardPlayerCommand); @@ -71,6 +71,7 @@ async function start() { pool: pool, common: common, playerInternalBaseUrl: webConfig.playerInternalBaseUrl, + thinClientBaseUrl: webConfig.thinClientBaseUrl, uploadDir: webConfig.uploadsDir, formatDashboardDate: formatDashboardDate, notifyPlayerScreens: notifyPlayerScreens, @@ -155,6 +156,8 @@ async function start() { }, hasAnyPermission: hasAnyPermission, backgroundTaskQueue: backgroundTaskQueue, + mediaDir: webConfig.mediaDir, + uploadSyncService: webBootstrap.uploadSyncService, collectUploadReferencesFromSlide: collectUploadReferencesFromSlide, collectUploadReferencesFromTemplate: collectUploadReferencesFromTemplate, collectUploadReferencesFromPayload: collectUploadReferencesFromPayload, @@ -207,6 +210,7 @@ async function start() { initializeBackgroundTasks: initializeBackgroundTasks, captureSlideThumbnail: captureSlideThumbnail, server: server, + webBaseUrl: webConfig.webBaseUrl, dataSourceStartupRefreshStaggerMs: webConfig.dataSourceStartupRefreshStaggerMs }); diff --git a/src/web/bootstrap.js b/src/web/bootstrap.js index ee43bb8..3ed2f1e 100644 --- a/src/web/bootstrap.js +++ b/src/web/bootstrap.js @@ -9,6 +9,7 @@ function createWebBootstrap(options) { const pool = options && options.pool; const common = options && options.common; const configuredPlayerInternalBaseUrl = String(options && options.playerInternalBaseUrl || '').replace(/\/$/, ''); + const configuredThinClientBaseUrl = String(options && options.thinClientBaseUrl || process.env.THIN_CLIENT_BASE_URL || '').trim().replace(/\/$/, ''); const uploadDir = String(options && options.uploadDir || '').trim(); const dashboardRefreshIntervalMs = 5000; const formatDashboardDate = options && options.formatDashboardDate; @@ -25,49 +26,8 @@ function createWebBootstrap(options) { const playerSnapshotSockets = options && options.playerSnapshotSockets ? options.playerSnapshotSockets : new Map(); let dashboardRefreshInFlight = null; let broadcastDashboardState = null; - let playerInternalBaseUrl = null; - let playerInternalBaseUrlPromise = null; - - async function getPlayerInternalBaseUrl() { - if (playerInternalBaseUrl) { - return playerInternalBaseUrl; - } - - if (playerInternalBaseUrlPromise) { - return playerInternalBaseUrlPromise; - } - - playerInternalBaseUrlPromise = (async function () { - if (!pool) { - return configuredPlayerInternalBaseUrl || null; - } - - try { - const [rows] = await pool.query( - `SELECT internal_base_url - FROM d_players - WHERE device_id = '1' - LIMIT 1` - ); - const resolvedBaseUrl = String(rows && rows[0] && rows[0].internal_base_url || '').trim().replace(/\/$/, ''); - return resolvedBaseUrl || configuredPlayerInternalBaseUrl || null; - } catch (_error) { - return configuredPlayerInternalBaseUrl || null; - } - })().then(function (baseUrl) { - playerInternalBaseUrl = baseUrl || null; - playerInternalBaseUrlPromise = null; - return playerInternalBaseUrl; - }, function () { - playerInternalBaseUrlPromise = null; - return configuredPlayerInternalBaseUrl || null; - }); - - return playerInternalBaseUrlPromise; - } - - async function getPlayerSnapshotSocketUrl(slug) { - const resolvedPlayerInternalBaseUrl = await getPlayerInternalBaseUrl(); + function getPlayerSnapshotSocketUrl(slug) { + const resolvedPlayerInternalBaseUrl = configuredThinClientBaseUrl || configuredPlayerInternalBaseUrl; if (!resolvedPlayerInternalBaseUrl) { throw new Error('Unable to resolve the player internal base URL.'); } @@ -78,16 +38,6 @@ function createWebBootstrap(options) { return url.toString(); } - function storePlayerSnapshot(slug, connections) { - const normalizedSlug = String(slug || '').trim(); - const normalizedConnections = Array.isArray(connections) ? connections : []; - playerSnapshotCache.set(normalizedSlug, { - slug: normalizedSlug, - count: normalizedConnections.length, - connections: normalizedConnections - }); - } - function clearPlayerSnapshotSocket(slug) { const key = String(slug || '').trim(); playerSnapshotSockets.delete(key); @@ -104,12 +54,12 @@ function createWebBootstrap(options) { } playerSnapshotSockets.set(key, null); - const socketUrlPromise = getPlayerSnapshotSocketUrl(key); const authHeaders = createRequestAuthHeaders({ method: 'GET', pathname: `/ws/screens/${encodeURIComponent(key)}/events` }); - socketUrlPromise.then(function (socketUrl) { + + Promise.resolve(getPlayerSnapshotSocketUrl(key)).then(function (socketUrl) { const socket = new WebSocket(socketUrl, { headers: authHeaders }); @@ -121,7 +71,11 @@ function createWebBootstrap(options) { if (!payload || payload.type !== 'snapshot' || payload.slug !== key) { return; } - storePlayerSnapshot(key, payload.connections || []); + playerSnapshotCache.set(key, { + slug: key, + count: Array.isArray(payload.connections) ? payload.connections.length : 0, + connections: Array.isArray(payload.connections) ? payload.connections : [] + }); if (broadcastDashboardState) { broadcastDashboardState().catch(function (error) { console.error(error); @@ -155,6 +109,7 @@ function createWebBootstrap(options) { const dashboardStateService = createDashboardStateService({ pool: pool, common: common, + thinClientBaseUrl: configuredThinClientBaseUrl, playerSnapshotCache: playerSnapshotCache, playerSnapshotSockets: playerSnapshotSockets, ensurePlayerSnapshotSubscription: ensurePlayerSnapshotSubscription, @@ -298,6 +253,7 @@ function createWebBootstrap(options) { return { upload: upload, uploadSyncService: uploadSyncService, + playerInternalBaseUrl: configuredPlayerInternalBaseUrl || null, buildDashboardState: buildDashboardState, collectUploadReferencesFromSlide: collectUploadReferencesFromSlide, collectUploadReferencesFromTemplate: collectUploadReferencesFromTemplate, diff --git a/src/web/lib/background-tasks/tasks-adhoc/thumbnail-refresh-slide.js b/src/web/lib/background-tasks/tasks-adhoc/thumbnail-refresh-slide.js index ddab50a..f55ffbb 100644 --- a/src/web/lib/background-tasks/tasks-adhoc/thumbnail-refresh-slide.js +++ b/src/web/lib/background-tasks/tasks-adhoc/thumbnail-refresh-slide.js @@ -1,16 +1,18 @@ +const { resolvePlayerRegistration } = require('#src/data/player-registry'); + const TASK = { taskType: 'slide-thumbnail-refresh' }; -async function fetchPlayerInternalBaseUrl(pool) { - const [rows] = await pool.query( - `SELECT internal_base_url - FROM d_players - WHERE device_id = '1' - LIMIT 1` - ); +async function fetchPlayerInternalBaseUrl(pool, configuredPlayerInternalBaseUrl) { + const configured = String(configuredPlayerInternalBaseUrl || '').trim().replace(/\/$/, ''); + if (configured) { + return configured; + } - return String(rows && rows[0] && rows[0].internal_base_url || '').trim().replace(/\/$/, '') || null; + const { getConfiguredPlayerIdentifier } = require('#src/data/player-registry'); + const player = await resolvePlayerRegistration(pool, getConfiguredPlayerIdentifier()); + return String(player && player.internal_base_url || '').trim().replace(/\/$/, '') || null; } function registerSlideThumbnailRefreshTask(options) { @@ -19,6 +21,7 @@ function registerSlideThumbnailRefreshTask(options) { const pool = options && options.pool; const common = options && options.common; const mediaDir = String(options && options.mediaDir || '').trim(); + const configuredWebBaseUrl = String(options && options.webBaseUrl || '').trim().replace(/\/$/, ''); if (!backgroundTaskQueue || typeof captureSlideThumbnail !== 'function' || !pool || !common || !mediaDir) { throw new Error('registerSlideThumbnailRefreshTask requires the slide thumbnail dependencies.'); @@ -32,18 +35,19 @@ function registerSlideThumbnailRefreshTask(options) { throw new Error('Slide id is required.'); } - const playerInternalBaseUrl = await fetchPlayerInternalBaseUrl(pool); - if (!playerInternalBaseUrl) { - throw new Error('Player internal base URL is required.'); + const webBaseUrl = configuredWebBaseUrl || `http://127.0.0.1:${Number(process.env.WEB_PORT || 8080)}`; + if (!webBaseUrl) { + throw new Error('Web base URL is required.'); } return captureSlideThumbnail({ pool: pool, common: common, mediaDir: mediaDir, - baseUrl: playerInternalBaseUrl, + baseUrl: webBaseUrl, slideId: slideId, - previousThumbnailPath: payload.previousThumbnailPath || null + previousThumbnailPath: payload.previousThumbnailPath || null, + fontStylesheetHref: payload.fontStylesheetHref || '' }); }); } diff --git a/src/web/lib/background-tasks/tasks-adhoc/thumbnail-refresh-template.js b/src/web/lib/background-tasks/tasks-adhoc/thumbnail-refresh-template.js index 42d8053..a747ac5 100644 --- a/src/web/lib/background-tasks/tasks-adhoc/thumbnail-refresh-template.js +++ b/src/web/lib/background-tasks/tasks-adhoc/thumbnail-refresh-template.js @@ -1,16 +1,18 @@ +const { resolvePlayerRegistration } = require('#src/data/player-registry'); + const TASK = { taskType: 'template-slide-thumbnail-refresh' }; -async function fetchPlayerInternalBaseUrl(pool) { - const [rows] = await pool.query( - `SELECT internal_base_url - FROM d_players - WHERE device_id = '1' - LIMIT 1` - ); +async function fetchPlayerInternalBaseUrl(pool, configuredPlayerInternalBaseUrl) { + const configured = String(configuredPlayerInternalBaseUrl || '').trim().replace(/\/$/, ''); + if (configured) { + return configured; + } - return String(rows && rows[0] && rows[0].internal_base_url || '').trim().replace(/\/$/, '') || null; + const { getConfiguredPlayerIdentifier } = require('#src/data/player-registry'); + const player = await resolvePlayerRegistration(pool, getConfiguredPlayerIdentifier()); + return String(player && player.internal_base_url || '').trim().replace(/\/$/, '') || null; } function registerTemplateSlideThumbnailRefreshTask(options) { @@ -19,6 +21,7 @@ function registerTemplateSlideThumbnailRefreshTask(options) { const pool = options && options.pool; const common = options && options.common; const mediaDir = String(options && options.mediaDir || '').trim(); + const configuredWebBaseUrl = String(options && options.webBaseUrl || '').trim().replace(/\/$/, ''); if (!backgroundTaskQueue || typeof captureSlideThumbnail !== 'function' || !pool || !common || !mediaDir) { throw new Error('registerTemplateSlideThumbnailRefreshTask requires the template thumbnail dependencies.'); @@ -32,9 +35,9 @@ function registerTemplateSlideThumbnailRefreshTask(options) { throw new Error('Template id is required.'); } - const playerInternalBaseUrl = await fetchPlayerInternalBaseUrl(pool); - if (!playerInternalBaseUrl) { - throw new Error('Player internal base URL is required.'); + const webBaseUrl = configuredWebBaseUrl || `http://127.0.0.1:${Number(process.env.WEB_PORT || 8080)}`; + if (!webBaseUrl) { + throw new Error('Web base URL is required.'); } const [slides] = await pool.query( @@ -52,7 +55,7 @@ function registerTemplateSlideThumbnailRefreshTask(options) { pool: pool, common: common, mediaDir: mediaDir, - baseUrl: playerInternalBaseUrl, + baseUrl: webBaseUrl, slideId: slideId, previousThumbnailPath: slide && slide.thumbnail_path ? slide.thumbnail_path : null }); diff --git a/src/web/lib/background-tasks/tasks-scheduled/font-sweep.js b/src/web/lib/background-tasks/tasks-scheduled/font-sweep.js index 95f787c..7ba61d2 100644 --- a/src/web/lib/background-tasks/tasks-scheduled/font-sweep.js +++ b/src/web/lib/background-tasks/tasks-scheduled/font-sweep.js @@ -18,50 +18,57 @@ function registerFontSweepTask(options) { const uploadSyncService = options && options.uploadSyncService; const pushUploadFileToPlayer = uploadSyncService && uploadSyncService.pushUploadFileToPlayer; const removeUploadFileFromPlayer = uploadSyncService && uploadSyncService.removeUploadFileFromPlayer; + const getPlayerTaskMetadata = uploadSyncService && uploadSyncService.getPlayerTaskMetadata; const mediaDir = String(options && options.mediaDir || '').trim(); if (!backgroundTaskQueue || typeof pushUploadFileToPlayer !== 'function' || typeof removeUploadFileFromPlayer !== 'function' || !mediaDir) { throw new Error('registerFontSweepTask requires the font sweep dependencies.'); } - backgroundTaskQueue.registerRecurringTask({ - key: TASK.key, - title: TASK.title, - category: TASK.category, - intervalMs: TASK.intervalMs, - metadata: { - mediaDir: mediaDir - }, - run: async function () { - const desiredOperations = collectFontLibrarySyncOperations(mediaDir); - const desiredUploadPaths = new Set(desiredOperations.map(function (operation) { - return operation && operation.uploadPath ? operation.uploadPath : ''; - }).filter(Boolean)); - const currentUploadPaths = await collectFontLibraryDirectoryUploadPaths(mediaDir); + const metadataPromise = typeof getPlayerTaskMetadata === 'function' + ? Promise.resolve(getPlayerTaskMetadata()) + : Promise.resolve({}); - for (let i = 0; i < desiredOperations.length; i += 1) { - const operation = desiredOperations[i] || {}; - const uploadPath = String(operation.uploadPath || '').trim(); - if (!uploadPath) { - continue; + return metadataPromise.then(function (metadata) { + backgroundTaskQueue.registerRecurringTask({ + key: TASK.key, + title: TASK.title, + category: TASK.category, + intervalMs: TASK.intervalMs, + metadata: Object.assign({ + mediaDir: mediaDir + }, metadata || {}), + run: async function () { + const desiredOperations = collectFontLibrarySyncOperations(mediaDir); + const desiredUploadPaths = new Set(desiredOperations.map(function (operation) { + return operation && operation.uploadPath ? operation.uploadPath : ''; + }).filter(Boolean)); + const currentUploadPaths = await collectFontLibraryDirectoryUploadPaths(mediaDir); + + for (let i = 0; i < desiredOperations.length; i += 1) { + const operation = desiredOperations[i] || {}; + const uploadPath = String(operation.uploadPath || '').trim(); + if (!uploadPath) { + continue; + } + + if (String(operation.type || '').trim().toLowerCase() === 'delete') { + await removeUploadFileFromPlayer(uploadPath, mediaDir); + } else { + await pushUploadFileToPlayer(uploadPath, mediaDir); + } } - if (String(operation.type || '').trim().toLowerCase() === 'delete') { + for (let i = 0; i < currentUploadPaths.length; i += 1) { + const uploadPath = String(currentUploadPaths[i] || '').trim(); + if (!uploadPath || desiredUploadPaths.has(uploadPath)) { + continue; + } + await removeUploadFileFromPlayer(uploadPath, mediaDir); - } else { - await pushUploadFileToPlayer(uploadPath, mediaDir); } } - - for (let i = 0; i < currentUploadPaths.length; i += 1) { - const uploadPath = String(currentUploadPaths[i] || '').trim(); - if (!uploadPath || desiredUploadPaths.has(uploadPath)) { - continue; - } - - await removeUploadFileFromPlayer(uploadPath, mediaDir); - } - } + }); }); } diff --git a/src/web/lib/background-tasks/tasks-startup/font-sync.js b/src/web/lib/background-tasks/tasks-startup/font-sync.js index 1fe7d7e..b415342 100644 --- a/src/web/lib/background-tasks/tasks-startup/font-sync.js +++ b/src/web/lib/background-tasks/tasks-startup/font-sync.js @@ -8,22 +8,30 @@ const TASK = { function registerInitialFontSyncTask(options) { const backgroundTaskQueue = options && options.backgroundTaskQueue; const mediaDir = String(options && options.mediaDir || '').trim(); + const uploadSyncService = options && options.uploadSyncService; if (!backgroundTaskQueue || !mediaDir) { throw new Error('registerInitialFontSyncTask requires the initial font sync dependencies.'); } - return backgroundTaskQueue.enqueueTask({ - key: TASK.key, - title: 'Initial font sync', - category: TASK.category, - taskType: 'font-sync', - payload: { - mode: 'initial', - uploadDir: mediaDir, - operations: collectFontLibrarySyncOperations(mediaDir) - }, - persist: true + const metadataPromise = uploadSyncService && typeof uploadSyncService.getPlayerTaskMetadata === 'function' + ? uploadSyncService.getPlayerTaskMetadata() + : Promise.resolve({}); + + return Promise.resolve(metadataPromise).then(function (metadata) { + return backgroundTaskQueue.enqueueTask({ + key: TASK.key, + title: 'Initial font sync', + category: TASK.category, + taskType: 'font-sync', + metadata: Object.assign({}, metadata || {}), + payload: { + mode: 'initial', + uploadDir: mediaDir, + operations: collectFontLibrarySyncOperations(mediaDir) + }, + persist: true + }); }).catch(function (error) { console.warn('Unable to queue initial font sync:', error); }); diff --git a/src/web/lib/background-tasks/tasks-startup/media-sync.js b/src/web/lib/background-tasks/tasks-startup/media-sync.js index 5eb69ea..56e3cd6 100644 --- a/src/web/lib/background-tasks/tasks-startup/media-sync.js +++ b/src/web/lib/background-tasks/tasks-startup/media-sync.js @@ -6,21 +6,29 @@ const TASK = { function registerInitialMediaSyncTask(options) { const backgroundTaskQueue = options && options.backgroundTaskQueue; const mediaDir = String(options && options.mediaDir || '').trim(); + const uploadSyncService = options && options.uploadSyncService; if (!backgroundTaskQueue || !mediaDir) { throw new Error('registerInitialMediaSyncTask requires the initial media sync dependencies.'); } - return backgroundTaskQueue.enqueueTask({ - key: TASK.key, - title: 'Initial media sync', - category: TASK.category, - taskType: 'media-sync', - payload: { - mode: 'initial', - uploadDir: mediaDir - }, - persist: true + const metadataPromise = uploadSyncService && typeof uploadSyncService.getPlayerTaskMetadata === 'function' + ? uploadSyncService.getPlayerTaskMetadata() + : Promise.resolve({}); + + return Promise.resolve(metadataPromise).then(function (metadata) { + return backgroundTaskQueue.enqueueTask({ + key: TASK.key, + title: 'Initial media sync', + category: TASK.category, + taskType: 'media-sync', + metadata: Object.assign({}, metadata || {}), + payload: { + mode: 'initial', + uploadDir: mediaDir + }, + persist: true + }); }).catch(function (error) { console.warn('Unable to queue initial media sync:', error); }); diff --git a/src/web/lib/config.js b/src/web/lib/config.js index 516c718..27da7b5 100644 --- a/src/web/lib/config.js +++ b/src/web/lib/config.js @@ -6,6 +6,8 @@ function createWebConfig() { const thumbnailsDir = path.join(mediaDir, 'thumbnails'); const assetDir = path.join(__dirname, '..', 'public'); const playerInternalBaseUrl = (process.env.PLAYER_INTERNAL_BASE_URL || process.env.PLAYER_BASE_URL || 'http://player:8081').replace(/\/$/, ''); + const thinClientBaseUrl = (process.env.THIN_CLIENT_BASE_URL || 'http://player-bridge:8090').replace(/\/$/, ''); + const webBaseUrl = (process.env.WEB_BASE_URL || `http://127.0.0.1:${Number(process.env.WEB_PORT || 8080)}`).replace(/\/$/, ''); const sessionCookieName = 'digital_signage_session'; const sessionMaxAgeDays = Number(process.env.SESSION_MAX_AGE_DAYS || 14); const sessionMaxAgeMs = (Number.isFinite(sessionMaxAgeDays) && sessionMaxAgeDays > 0 ? sessionMaxAgeDays : 14) * 24 * 60 * 60 * 1000; @@ -19,6 +21,8 @@ function createWebConfig() { thumbnailsDir: thumbnailsDir, assetDir: assetDir, playerInternalBaseUrl: playerInternalBaseUrl, + thinClientBaseUrl: thinClientBaseUrl, + webBaseUrl: webBaseUrl, sessionCookieName: sessionCookieName, sessionMaxAgeMs: sessionMaxAgeMs, dataSourceStartupRefreshStaggerMs: dataSourceStartupRefreshStaggerMs diff --git a/src/web/lib/dashboard-state.js b/src/web/lib/dashboard-state.js index 9da9dbf..1852de5 100644 --- a/src/web/lib/dashboard-state.js +++ b/src/web/lib/dashboard-state.js @@ -6,6 +6,10 @@ function normalizeClientName(value) { return String(value || '').trim(); } +function normalizePlayerBaseUrl(value) { + return String(value || '').trim().replace(/\/$/, ''); +} + function enrichScreensWithConnections(screens, connectionsBySlug, onboardingNameBySlug, playerUrlsBySlug) { return (screens || []).map(function (screen) { const connectionState = connectionsBySlug[screen.slug] || { count: 0, connections: [] }; @@ -18,11 +22,12 @@ function enrichScreensWithConnections(screens, connectionsBySlug, onboardingName }); } -function buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboardingNameByDeviceId, formatDashboardDate) { +function buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboardingNameByDeviceId, playerIdentifierByBaseUrl, formatDashboardDate) { return (screens || []).flatMap(function (screen) { const connectionState = connectionsBySlug[screen.slug] || { count: 0, connections: [] }; return (connectionState.connections || []).map(function (connection) { const deviceId = String(connection.deviceId || '').trim(); + const playerBaseUrl = normalizePlayerBaseUrl(connection.playerPublicBaseUrl); return Object.assign({}, connection, { screen_slug: screen.slug, screen_name: screen.name, @@ -30,12 +35,55 @@ function buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboa playlist_name: screen.playlist_name || null, connectedAtLabel: formatDashboardDate(connection.connectedAt), lastSeenAtLabel: formatDashboardDate(connection.lastSeenAt), - player_url: screen.player_url || String(connection.page || '').trim() || null + player_identifier: playerIdentifierByBaseUrl && playerBaseUrl ? (playerIdentifierByBaseUrl[playerBaseUrl] || null) : null, + player_url: playerBaseUrl || null }); }); }); } +function isRecentPlayerRegistration(player, staleSeconds) { + const lastSeenAt = player && player.last_seen_at; + const lastSeenAtValue = lastSeenAt instanceof Date ? lastSeenAt.getTime() : new Date(lastSeenAt).getTime(); + const cutoffTime = Date.now() - Math.max(30, Number(staleSeconds || 60)) * 1000; + + return Number.isFinite(lastSeenAtValue) && lastSeenAtValue >= cutoffTime; +} + +function buildKioskLauncherPlayers(playerRegistrations, staleSeconds) { + return (Array.isArray(playerRegistrations) ? playerRegistrations : []) + .filter(function (player) { + return Boolean(player && String(player.identifier || '').trim() && String(player.public_base_url || '').trim() && isRecentPlayerRegistration(player, staleSeconds)); + }) + .map(function (player) { + return { + player_identifier: String(player.identifier || '').trim(), + player_url: String(player.public_base_url || '').trim().replace(/\/$/, '') + }; + }); +} + +async function fetchConnectedPlayerCount(pool, connectedPlayerCountStaleSeconds) { + const staleSeconds = Math.max(30, Number(connectedPlayerCountStaleSeconds || 60)); + if (!pool || typeof pool.query !== 'function' || !Number.isFinite(staleSeconds)) { + return null; + } + + try { + const [rows] = await pool.query( + `SELECT COUNT(*) AS connected_count + FROM d_players + WHERE last_seen_at IS NOT NULL + AND last_seen_at >= DATE_SUB(NOW(), INTERVAL ${staleSeconds} SECOND)` + ); + + const count = Number(rows && rows[0] && rows[0].connected_count); + return Number.isFinite(count) && count >= 0 ? count : null; + } catch (_error) { + return null; + } +} + function compareScreenNames(left, right) { const leftName = String(left && left.name || '').trim(); const rightName = String(right && right.name || '').trim(); @@ -51,6 +99,7 @@ function compareScreenNames(left, right) { function createDashboardStateService(options) { const pool = options && options.pool; const common = options && options.common; + const connectedPlayerCountStaleSeconds = options && options.connectedPlayerCountStaleSeconds; const playerSnapshotCache = options && options.playerSnapshotCache; const playerSnapshotSockets = options && options.playerSnapshotSockets; const ensurePlayerSnapshotSubscription = options && options.ensurePlayerSnapshotSubscription; @@ -63,9 +112,13 @@ function createDashboardStateService(options) { async function buildDashboardState() { const data = await common.fetchAdminData(pool); const screensData = data.screens || []; + const connectedPlayersCount = await fetchConnectedPlayerCount(pool, connectedPlayerCountStaleSeconds); const playerUrlsBySlug = typeof common.fetchScreenPlayerUrls === 'function' ? await common.fetchScreenPlayerUrls(pool) : {}; + const playerRegistrations = typeof common.fetchPlayerRegistrations === 'function' + ? await common.fetchPlayerRegistrations(pool) + : []; screensData.forEach(function (screen) { try { ensurePlayerSnapshotSubscription(screen.slug); @@ -95,6 +148,15 @@ function createDashboardStateService(options) { } }); + const playerIdentifierByBaseUrl = {}; + (Array.isArray(playerRegistrations) ? playerRegistrations : []).forEach(function (player) { + const baseUrl = normalizePlayerBaseUrl(player && player.public_base_url); + const identifier = normalizeClientName(player && player.identifier); + if (baseUrl && identifier) { + playerIdentifierByBaseUrl[baseUrl] = identifier; + } + }); + const connectionsBySlug = {}; screensData.forEach(function (screen) { const cached = playerSnapshotCache.get(String(screen.slug || '').trim()); @@ -110,7 +172,8 @@ function createDashboardStateService(options) { }); }) .sort(compareScreenNames); - const clients = buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboardingNameByDeviceId, formatDashboardDate); + const clients = buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboardingNameByDeviceId, playerIdentifierByBaseUrl, formatDashboardDate); + const kioskPlayers = buildKioskLauncherPlayers(playerRegistrations, connectedPlayerCountStaleSeconds); const playerServiceConnected = Array.from(playerSnapshotSockets.values()).some(function (socket) { return socket && socket.readyState === WebSocket.OPEN; }); @@ -119,8 +182,10 @@ function createDashboardStateService(options) { playlists: data.playlists || [], screens: screens, clients: clients, + kioskPlayers: kioskPlayers, slides: data.slides || [], playerServiceConnected: playerServiceConnected, + connectedPlayersCount: connectedPlayersCount !== null ? connectedPlayersCount : 0, connectedClientsCount: screens.reduce(function (total, screen) { return total + Number(screen.player_connection_count || 0); }, 0) diff --git a/src/web/lib/media/index.js b/src/web/lib/media/index.js index a5e522f..9c6fc46 100644 --- a/src/web/lib/media/index.js +++ b/src/web/lib/media/index.js @@ -2,6 +2,8 @@ module.exports = { createUploadSyncService: require('./upload-sync').createUploadSyncService, - captureSlideThumbnail: require('./slide-thumbnails').captureSlideThumbnail, + captureSlideThumbnail: function captureSlideThumbnail(options) { + return require('./slide-thumbnails').captureSlideThumbnail(options); + }, fontLibrary: require('./font-library') }; \ No newline at end of file diff --git a/src/web/lib/media/slide-thumbnail-preview.js b/src/web/lib/media/slide-thumbnail-preview.js new file mode 100644 index 0000000..4436a26 --- /dev/null +++ b/src/web/lib/media/slide-thumbnail-preview.js @@ -0,0 +1,156 @@ +// Pure thumbnail preview payload helpers shared by routes and screenshot capture. + +const { + escapeHtml, + renderEditorJsContent, + sanitizeFontFamily, + sanitizeFontSize, + sanitizeTextColor +} = require('#src/player/render-helpers'); + +function normalizeBaseUrl(baseUrl) { + return String(baseUrl || '').trim().replace(/\/$/, ''); +} + +function resolveAssetUrl(baseUrl, value) { + const raw = String(value || '').trim(); + if (!raw) { + return ''; + } + if (/^(?:https?:)?\/\//i.test(raw) || raw.startsWith('data:')) { + return raw; + } + const normalizedBaseUrl = normalizeBaseUrl(baseUrl); + if (!normalizedBaseUrl) { + return raw; + } + if (raw.startsWith('/')) { + return normalizedBaseUrl + raw; + } + return normalizedBaseUrl + '/' + raw.replace(/^\/+/, ''); +} + +function getThumbnailCanvasSize(slide) { + const template = slide && slide.template ? slide.template : null; + return { + width: Math.max(1, Number(template && template.canvas_size_width ? template.canvas_size_width : 1920)), + height: Math.max(1, Number(template && template.canvas_size_height ? template.canvas_size_height : 1080)) + }; +} + +function getRegionContent(slide, region) { + const content = slide && slide.content && slide.content[region.region_key] ? slide.content[region.region_key] : {}; + return content && typeof content === 'object' ? content : { value: content }; +} + +function buildThumbnailRegionStyle(region, canvasWidth, canvasHeight) { + const left = Number.isFinite(Number(region && region.x)) && canvasWidth > 0 ? (Number(region.x) / canvasWidth) * 100 : 0; + const top = Number.isFinite(Number(region && region.y)) && canvasHeight > 0 ? (Number(region.y) / canvasHeight) * 100 : 0; + const width = Number.isFinite(Number(region && region.width)) && canvasWidth > 0 ? (Number(region.width) / canvasWidth) * 100 : 0; + const height = Number.isFinite(Number(region && region.height)) && canvasHeight > 0 ? (Number(region.height) / canvasHeight) * 100 : 0; + + return 'left:' + left + '%;top:' + top + '%;width:' + width + '%;height:' + height + '%;z-index:' + Number(region && region.z_index || 0) + ';'; +} + +function hasVisibleContent(html) { + return Boolean(String(html || '').replace(/<[^>]+>/g, '').trim()); +} + +function buildTextRegionMarkup(region, regionContent) { + const fontFamily = sanitizeFontFamily(regionContent.font_family || region.font_family); + const fontSize = sanitizeFontSize(regionContent.font_size || region.font_size); + const fontColor = sanitizeTextColor(regionContent.font_color || region.font_color); + const renderedBody = renderEditorJsContent(regionContent.value || ''); + if (!hasVisibleContent(renderedBody)) { + return ''; + } + + return ''; +} + +function buildRegionInnerHtml(region, regionContent, baseUrl) { + const regionType = String(regionContent.type || region.region_type || 'text').trim().toLowerCase(); + const rawValue = regionContent && regionContent.value !== undefined ? regionContent.value : ''; + + if (regionType === 'image') { + const src = resolveAssetUrl(baseUrl, rawValue); + return src + ? '' + : ''; + } + + if (regionType === 'video') { + const src = resolveAssetUrl(baseUrl, rawValue); + return src + ? '' + : ''; + } + + if (regionType === 'webpage') { + const src = resolveAssetUrl(baseUrl, rawValue); + return src + ? '' + : ''; + } + + if (regionType === 'qr-code') { + const src = String(regionContent.qr_preview || '').trim(); + const borderRadius = Math.max(0, Math.round(Number(regionContent.qr_border_radius || 0))); + const radiusStyle = borderRadius > 0 ? ' style="border-radius:' + borderRadius + 'px;overflow:hidden;"' : ''; + return src + ? '' + : ''; + } + + if (regionType === 'html') { + const html = String(rawValue || '').trim(); + return html + ? '' + : ''; + } + + if (regionType === 'rtmp') { + const label = String(rawValue || '').trim() || 'RTMP source'; + return ''; + } + + return buildTextRegionMarkup(region, regionContent); +} + +function buildThumbnailPreviewMarkup(slide, baseUrl) { + const template = slide && slide.template ? slide.template : null; + if (!template) { + return ''; + } + + const canvasSize = getThumbnailCanvasSize(slide); + const normalizedBaseUrl = normalizeBaseUrl(baseUrl); + return (Array.isArray(template.regions) ? template.regions : []).map(function (region) { + const regionContent = getRegionContent(slide, region); + const previewRegion = Object.assign({}, region, { + baseStyle: buildThumbnailRegionStyle(region, canvasSize.width, canvasSize.height), + pixelWidth: Math.max(1, Math.round(Number(region && region.width || 0) || 1)), + pixelHeight: Math.max(1, Math.round(Number(region && region.height || 0) || 1)) + }); + return buildRegionInnerHtml(previewRegion, regionContent, normalizedBaseUrl); + }).join(''); +} + +function buildThumbnailPreviewPayload(slide, options) { + const template = slide && slide.template ? slide.template : null; + const canvasSize = getThumbnailCanvasSize(slide); + return { + thumbnailPreview: true, + canvasWidth: canvasSize.width, + canvasHeight: canvasSize.height, + backgroundColor: template && template.background_color ? String(template.background_color) : '#111111', + backgroundImagePath: template && template.background_image_path ? String(template.background_image_path) : '', + fontStylesheetHref: String(options && options.fontStylesheetHref || '').trim(), + html: buildThumbnailPreviewMarkup(slide, options && options.baseUrl) + }; +} + +module.exports = { + buildThumbnailPreviewPayload: buildThumbnailPreviewPayload, + buildThumbnailPreviewMarkup: buildThumbnailPreviewMarkup +}; \ No newline at end of file diff --git a/src/web/lib/media/slide-thumbnails.js b/src/web/lib/media/slide-thumbnails.js index e8580f9..b19f67e 100644 --- a/src/web/lib/media/slide-thumbnails.js +++ b/src/web/lib/media/slide-thumbnails.js @@ -2,14 +2,6 @@ const fs = require('fs'); const path = require('path'); -const puppeteer = require('puppeteer-core'); -const chromiumModule = require('@sparticuz/chromium'); -const sharp = require('sharp'); -const chromium = chromiumModule && typeof chromiumModule.executablePath === 'function' - ? chromiumModule - : chromiumModule && chromiumModule.default && typeof chromiumModule.default.executablePath === 'function' - ? chromiumModule.default - : chromiumModule; const { escapeHtml, mediaKind, @@ -73,6 +65,23 @@ function getRegionContent(slide, region) { return content && typeof content === 'object' ? content : { value: content }; } +function getThumbnailCanvasSize(slide) { + const template = slide && slide.template ? slide.template : null; + return { + width: Math.max(1, Number(template && template.canvas_size_width ? template.canvas_size_width : 1920)), + height: Math.max(1, Number(template && template.canvas_size_height ? template.canvas_size_height : 1080)) + }; +} + +function buildThumbnailRegionStyle(region, canvasWidth, canvasHeight) { + const left = Number.isFinite(Number(region && region.x)) && canvasWidth > 0 ? (Number(region.x) / canvasWidth) * 100 : 0; + const top = Number.isFinite(Number(region && region.y)) && canvasHeight > 0 ? (Number(region.y) / canvasHeight) * 100 : 0; + const width = Number.isFinite(Number(region && region.width)) && canvasWidth > 0 ? (Number(region.width) / canvasWidth) * 100 : 0; + const height = Number.isFinite(Number(region && region.height)) && canvasHeight > 0 ? (Number(region.height) / canvasHeight) * 100 : 0; + + return 'left:' + left + '%;top:' + top + '%;width:' + width + '%;height:' + height + '%;z-index:' + Number(region && region.z_index || 0) + ';'; +} + function hasVisibleContent(html) { return Boolean(String(html || '').replace(/<[^>]+>/g, '').trim()); } @@ -86,7 +95,7 @@ function buildTextRegionMarkup(region, regionContent) { return ''; } - return 'Check this box to enable the Windows and Linux downloads.
+The download will open the selected player's public URL when the kiosk starts.
+Player URL, playlist assignment, - and live connection count without the spreadsheet feel.
+Playlist assignment and live connection state without the spreadsheet feel.