Save worktree changes
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
function createRtmpStreamService(options) {
|
||||
const mediaDir = options && options.mediaDir ? options.mediaDir : null;
|
||||
const ffmpegPath = options && options.ffmpegPath ? options.ffmpegPath : 'ffmpeg';
|
||||
const sessions = new Map();
|
||||
|
||||
if (!mediaDir) {
|
||||
throw new Error('mediaDir is required');
|
||||
}
|
||||
|
||||
const cacheRoot = path.join(mediaDir, 'rtmp-cache');
|
||||
|
||||
function normalizeSourceUrl(value) {
|
||||
const sourceUrl = String(value || '').trim();
|
||||
if (!sourceUrl || !/^rtmps?:\/\//i.test(sourceUrl)) {
|
||||
const error = new Error('A valid RTMP URL is required.');
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
return sourceUrl;
|
||||
}
|
||||
|
||||
function getSessionKey(sourceUrl, disableAudio) {
|
||||
return crypto.createHash('sha1').update(String(sourceUrl)).update('\0').update(disableAudio ? '1' : '0').digest('hex');
|
||||
}
|
||||
|
||||
async function ensureDirectory(dirPath) {
|
||||
await fs.promises.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
async function waitForFile(filePath, timeoutMs) {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
try {
|
||||
const stat = await fs.promises.stat(filePath);
|
||||
if (stat.isFile() && stat.size > 0) {
|
||||
return true;
|
||||
}
|
||||
} catch (_error) {
|
||||
// keep waiting
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function buildPlaylistUrl(key) {
|
||||
return '/api/rtmp/streams/' + encodeURIComponent(key) + '/index.m3u8';
|
||||
}
|
||||
|
||||
async function ensureSession(sourceUrl, disableAudio) {
|
||||
const normalizedSource = normalizeSourceUrl(sourceUrl);
|
||||
const normalizedDisableAudio = Boolean(disableAudio);
|
||||
const key = getSessionKey(normalizedSource, normalizedDisableAudio);
|
||||
|
||||
if (sessions.has(key)) {
|
||||
return sessions.get(key);
|
||||
}
|
||||
|
||||
const directory = path.join(cacheRoot, key);
|
||||
const manifestPath = path.join(directory, 'index.m3u8');
|
||||
|
||||
await ensureDirectory(directory);
|
||||
|
||||
const args = [
|
||||
'-hide_banner',
|
||||
'-loglevel', 'warning',
|
||||
'-nostdin',
|
||||
'-i', normalizedSource,
|
||||
'-fflags', '+genpts',
|
||||
'-f', 'hls',
|
||||
'-hls_time', '1',
|
||||
'-hls_init_time', '1',
|
||||
'-hls_list_size', '8',
|
||||
'-hls_flags', 'delete_segments+append_list+omit_endlist+independent_segments+program_date_time',
|
||||
'-hls_segment_filename', path.join(directory, 'segment-%05d.ts')
|
||||
];
|
||||
|
||||
if (normalizedDisableAudio) {
|
||||
args.push('-an');
|
||||
args.push('-c:v', 'copy');
|
||||
} else {
|
||||
args.push('-c', 'copy');
|
||||
}
|
||||
|
||||
args.push(manifestPath);
|
||||
|
||||
const child = spawn(ffmpegPath, args, {
|
||||
stdio: ['ignore', 'ignore', 'pipe']
|
||||
});
|
||||
|
||||
child.stderr.on('data', function (chunk) {
|
||||
const message = String(chunk || '').trim();
|
||||
if (message) {
|
||||
console.error('[rtmp]', message);
|
||||
}
|
||||
});
|
||||
|
||||
child.on('exit', function (code, signal) {
|
||||
const session = sessions.get(key);
|
||||
if (session && session.process === child) {
|
||||
session.process = null;
|
||||
session.exitCode = code;
|
||||
session.exitSignal = signal;
|
||||
}
|
||||
});
|
||||
|
||||
const session = {
|
||||
key: key,
|
||||
sourceUrl: normalizedSource,
|
||||
disableAudio: normalizedDisableAudio,
|
||||
directory: directory,
|
||||
manifestPath: manifestPath,
|
||||
playlistUrl: buildPlaylistUrl(key),
|
||||
process: child,
|
||||
ready: waitForFile(manifestPath, 5000)
|
||||
};
|
||||
|
||||
sessions.set(key, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
async function getPlaylistUrl(sourceUrl, disableAudio) {
|
||||
const session = await ensureSession(sourceUrl, disableAudio);
|
||||
await session.ready.catch(function () {
|
||||
return false;
|
||||
});
|
||||
return session.playlistUrl + '?t=' + Date.now();
|
||||
}
|
||||
|
||||
function getSessionByKey(key) {
|
||||
return sessions.get(String(key || '').trim()) || null;
|
||||
}
|
||||
|
||||
async function getManifestFilePath(key) {
|
||||
const session = getSessionByKey(key);
|
||||
if (!session) {
|
||||
return null;
|
||||
}
|
||||
await session.ready.catch(function () {
|
||||
return false;
|
||||
});
|
||||
return session.manifestPath;
|
||||
}
|
||||
|
||||
async function getSegmentFilePath(key, fileName) {
|
||||
const session = getSessionByKey(key);
|
||||
if (!session) {
|
||||
return null;
|
||||
}
|
||||
const segmentName = path.basename(String(fileName || '').trim());
|
||||
if (!segmentName || segmentName === 'index.m3u8') {
|
||||
return null;
|
||||
}
|
||||
return path.join(session.directory, segmentName);
|
||||
}
|
||||
|
||||
return {
|
||||
ensureSession: ensureSession,
|
||||
getPlaylistUrl: getPlaylistUrl,
|
||||
getSessionByKey: getSessionByKey,
|
||||
getManifestFilePath: getManifestFilePath,
|
||||
getSegmentFilePath: getSegmentFilePath
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createRtmpStreamService: createRtmpStreamService
|
||||
};
|
||||
@@ -1,5 +1,11 @@
|
||||
const { isClientNameAvailable, withClientNameReservation } = require('../client-name-check');
|
||||
const { isTransientDbError } = require('./onboarding-store');
|
||||
const { isClientNameAvailable, withClientNameReservation } = require('../../data/client-name-check');
|
||||
const { getSharedSecret, verifyPageAuthToken } = require('../../request-auth');
|
||||
const { isTransientDbError } = require('./store');
|
||||
|
||||
const ONBOARDING_SIGNUP_LIMIT_WINDOW_MS = 5 * 60 * 1000;
|
||||
const ONBOARDING_SIGNUP_LIMIT_MAX_ATTEMPTS = 8;
|
||||
const onboardingSignupAttempts = new Map();
|
||||
|
||||
function normalizeDeviceId(value) {
|
||||
return String(value || '').trim().replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 128);
|
||||
}
|
||||
@@ -16,6 +22,50 @@ function getPublicBaseUrl(req) {
|
||||
return `${protocol}://${host}`.replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function getRequestIp(req) {
|
||||
const forwardedFor = String(req && req.headers && req.headers['x-forwarded-for'] || '').trim().split(',')[0];
|
||||
if (forwardedFor) {
|
||||
return forwardedFor;
|
||||
}
|
||||
|
||||
const remoteAddress = req && req.socket && req.socket.remoteAddress ? String(req.socket.remoteAddress).trim() : '';
|
||||
if (!remoteAddress) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
return remoteAddress.toLowerCase().startsWith('::ffff:') ? remoteAddress.slice(7) : remoteAddress;
|
||||
}
|
||||
|
||||
function getOnboardingLimitKey(req, deviceId) {
|
||||
return [getRequestIp(req), normalizeDeviceId(deviceId) || 'anonymous'].join('|');
|
||||
}
|
||||
|
||||
function clearOnboardingSignupAttempts() {
|
||||
if (onboardingSignupAttempts.size > 1000) {
|
||||
onboardingSignupAttempts.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function isOnboardingSignupRateLimited(req, deviceId) {
|
||||
const now = Date.now();
|
||||
const key = getOnboardingLimitKey(req, deviceId);
|
||||
const attempts = onboardingSignupAttempts.get(key) || [];
|
||||
const windowStart = now - ONBOARDING_SIGNUP_LIMIT_WINDOW_MS;
|
||||
const recentAttempts = attempts.filter(function (timestamp) {
|
||||
return timestamp >= windowStart;
|
||||
});
|
||||
|
||||
if (recentAttempts.length >= ONBOARDING_SIGNUP_LIMIT_MAX_ATTEMPTS) {
|
||||
onboardingSignupAttempts.set(key, recentAttempts);
|
||||
return Math.max(1, Math.ceil((recentAttempts[0] + ONBOARDING_SIGNUP_LIMIT_WINDOW_MS - now) / 1000));
|
||||
}
|
||||
|
||||
recentAttempts.push(now);
|
||||
onboardingSignupAttempts.set(key, recentAttempts);
|
||||
clearOnboardingSignupAttempts();
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function getOnboardingStatus(pool, deviceId) {
|
||||
const normalizedDeviceId = normalizeDeviceId(deviceId);
|
||||
if (!normalizedDeviceId) {
|
||||
@@ -112,6 +162,23 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
throw new Error('registerPlayerOnboardingRoutes requires app, pool, common, playerRuntime, and QRCode.');
|
||||
}
|
||||
|
||||
const sharedSecret = getSharedSecret();
|
||||
|
||||
function requireOnboardingPageAuth(req, res, next) {
|
||||
if (!sharedSecret) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const token = String(req.headers['x-pulse-page-auth'] || '').trim();
|
||||
const payload = verifyPageAuthToken(token);
|
||||
if (!payload || String(payload.scope || '').trim() !== 'onboarding') {
|
||||
return res.status(401).json({ error: 'Onboarding page authentication required.' });
|
||||
}
|
||||
|
||||
req.playerPageAuth = payload;
|
||||
next();
|
||||
}
|
||||
|
||||
app.get('/', function (_req, res) {
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
res.send(common.renderPlayerOnboardingLandingPage());
|
||||
@@ -122,7 +189,17 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
res.send(common.renderPlayerOnboardingFormPage(String(req.query.deviceId || '').trim()));
|
||||
});
|
||||
|
||||
app.get('/api/onboarding/status', async function (req, res, next) {
|
||||
app.get('/api/onboarding/status', function (req, res, next) {
|
||||
if (sharedSecret) {
|
||||
const token = String(req.headers['x-pulse-page-auth'] || '').trim();
|
||||
const payload = verifyPageAuthToken(token);
|
||||
if (!payload || ['onboarding', 'player'].indexOf(String(payload.scope || '').trim()) === -1) {
|
||||
return res.status(401).json({ error: 'Onboarding page authentication required.' });
|
||||
}
|
||||
req.playerPageAuth = payload;
|
||||
}
|
||||
next();
|
||||
}, async function (req, res, next) {
|
||||
try {
|
||||
const status = await getOnboardingStatus(pool, req.query.deviceId);
|
||||
res.json({
|
||||
@@ -139,7 +216,7 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/onboarding/screens', async function (_req, res, next) {
|
||||
app.get('/api/onboarding/screens', requireOnboardingPageAuth, async function (_req, res, next) {
|
||||
try {
|
||||
const [rows] = await pool.query('SELECT id, name, slug FROM screens ORDER BY name ASC, id ASC');
|
||||
res.json({ screens: rows });
|
||||
@@ -164,11 +241,16 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/onboarding', async function (req, res, next) {
|
||||
app.post('/api/onboarding', requireOnboardingPageAuth, async function (req, res, next) {
|
||||
try {
|
||||
const deviceId = normalizeDeviceId(req.body && req.body.deviceId);
|
||||
const clientName = String((req.body && req.body.clientName) || '').trim();
|
||||
const screenSlug = String((req.body && req.body.screenSlug) || '').trim();
|
||||
const retryAfterSeconds = isOnboardingSignupRateLimited(req, deviceId);
|
||||
if (retryAfterSeconds) {
|
||||
res.set('Retry-After', String(retryAfterSeconds));
|
||||
return res.status(429).json({ error: 'Too many onboarding attempts. Please try again later.' });
|
||||
}
|
||||
if (!deviceId) {
|
||||
return res.status(400).json({ error: 'Device ID is required' });
|
||||
}
|
||||
+1
-1
@@ -85,4 +85,4 @@
|
||||
.catch(function (error) { setMessage(error && error.message ? error.message : "Unable to save onboarding."); });
|
||||
});
|
||||
}());
|
||||
</script>
|
||||
</script>
|
||||
+1
-1
@@ -138,4 +138,4 @@
|
||||
window.setInterval(function () { redirectIfOnboarded(deviceId); }, 2000);
|
||||
});
|
||||
}());
|
||||
</script>
|
||||
</script>
|
||||
+71
-1225
File diff suppressed because it is too large
Load Diff
+150
-70
@@ -1,8 +1,11 @@
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function createPlayerPlaylistService(options) {
|
||||
const pool = options && options.pool ? options.pool : null;
|
||||
const common = options && options.common ? options.common : null;
|
||||
const snapshotDir = options && options.snapshotDir ? options.snapshotDir : null;
|
||||
|
||||
if (!pool) {
|
||||
throw new Error('pool is required');
|
||||
@@ -11,81 +14,155 @@ function createPlayerPlaylistService(options) {
|
||||
throw new Error('common is required');
|
||||
}
|
||||
|
||||
function getSnapshotFilePath(slug) {
|
||||
if (!snapshotDir) {
|
||||
return null;
|
||||
}
|
||||
const normalizedSlug = String(slug || '').trim();
|
||||
if (!normalizedSlug) {
|
||||
return null;
|
||||
}
|
||||
return path.join(snapshotDir, `${normalizedSlug}.json`);
|
||||
}
|
||||
|
||||
async function readSnapshot(slug) {
|
||||
const filePath = getSnapshotFilePath(slug);
|
||||
if (!filePath) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const raw = await fs.promises.readFile(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== 'object') {
|
||||
return null;
|
||||
}
|
||||
return parsed;
|
||||
} catch (error) {
|
||||
if (error && error.code === 'ENOENT') {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeSnapshot(slug, payload) {
|
||||
const filePath = getSnapshotFilePath(slug);
|
||||
if (!filePath) {
|
||||
return;
|
||||
}
|
||||
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
||||
await fs.promises.writeFile(filePath, JSON.stringify(payload, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
async function buildScreenPlaylist(slug) {
|
||||
const [screenRows] = await pool.query('SELECT id, name, slug, playlist_id, created_at, modified_at, created_by, modified_by FROM screens WHERE slug = ?', [slug]);
|
||||
if (!screenRows.length) {
|
||||
return { screen: null, playlist: null, slides: [] };
|
||||
}
|
||||
try {
|
||||
const [screenRows] = await pool.query('SELECT id, name, slug, playlist_id, created_at, modified_at, created_by, modified_by FROM screens WHERE slug = ?', [slug]);
|
||||
if (!screenRows.length) {
|
||||
return { screen: null, playlist: null, slides: [], rssFeeds: [], apiSources: [] };
|
||||
}
|
||||
|
||||
const screen = screenRows[0];
|
||||
if (!screen.playlist_id) {
|
||||
return {
|
||||
screen: screen,
|
||||
playlist: null,
|
||||
slides: [],
|
||||
revision: getPlaylistRevision(screen, null, [], [], [])
|
||||
};
|
||||
}
|
||||
const screen = screenRows[0];
|
||||
if (!screen.playlist_id) {
|
||||
const payloadWithoutPlaylist = {
|
||||
screen: screen,
|
||||
playlist: null,
|
||||
slides: [],
|
||||
revision: getPlaylistRevision(screen, null, [], [], [], [], [])
|
||||
};
|
||||
await writeSnapshot(slug, payloadWithoutPlaylist);
|
||||
return payloadWithoutPlaylist;
|
||||
}
|
||||
|
||||
const [playlistRows] = await pool.query('SELECT id, name, fade_between_slides, created_at, modified_at, created_by, modified_by FROM playlists WHERE id = ?', [screen.playlist_id]);
|
||||
const playlist = playlistRows[0] || null;
|
||||
const [slideRows] = await pool.query(`
|
||||
SELECT sl.id, sl.title, sl.body, sl.template_id, sl.content_json, sl.media_path, sl.media_type, sl.created_at, sl.modified_at,
|
||||
ps.position, ps.duration_seconds AS duration_seconds, ps.schedule_mode, ps.schedule_start_datetime, ps.schedule_end_datetime, ps.schedule_start_time, ps.schedule_end_time, ps.schedule_days_json,
|
||||
st.name AS template_name, cs.name AS canvas_size_name, cs.width AS canvas_size_width, cs.height AS canvas_size_height, cs.width AS canvas_width, cs.height AS canvas_height
|
||||
FROM playlist_slides ps
|
||||
JOIN slides sl ON sl.id = ps.slide_id
|
||||
LEFT JOIN slide_templates st ON st.id = sl.template_id
|
||||
LEFT JOIN canvas_sizes cs ON cs.id = st.canvas_size_id
|
||||
WHERE ps.playlist_id = ?
|
||||
ORDER BY ps.position ASC, ps.id ASC
|
||||
`, [screen.playlist_id]);
|
||||
|
||||
const templateIds = slideRows
|
||||
.filter(function (slide) { return slide.template_id; })
|
||||
.map(function (slide) { return slide.template_id; });
|
||||
const templatesById = {};
|
||||
let templateRows = [];
|
||||
let regionRows = [];
|
||||
if (templateIds.length) {
|
||||
[templateRows] = await pool.query(`
|
||||
SELECT st.id, st.name, st.canvas_size_id, st.background_image_path, st.background_color, st.created_at, st.modified_at,
|
||||
cs.name AS canvas_size_name, cs.width AS canvas_size_width, cs.height AS canvas_size_height, cs.width AS canvas_width, cs.height AS canvas_height
|
||||
FROM slide_templates st
|
||||
const [playlistRows] = await pool.query('SELECT id, name, fade_between_slides, created_at, modified_at, created_by, modified_by FROM playlists WHERE id = ?', [screen.playlist_id]);
|
||||
const playlist = playlistRows[0] || null;
|
||||
const [slideRows] = await pool.query(`
|
||||
SELECT sl.id, sl.title, sl.body, sl.template_id, sl.content_json, sl.media_path, sl.media_type, sl.created_at, sl.modified_at,
|
||||
ps.position, ps.duration_seconds AS duration_seconds, ps.schedule_mode, ps.schedule_start_datetime, ps.schedule_end_datetime, ps.schedule_start_time, ps.schedule_end_time, ps.schedule_days_json,
|
||||
st.name AS template_name, cs.name AS canvas_size_name, cs.width AS canvas_size_width, cs.height AS canvas_size_height, cs.width AS canvas_width, cs.height AS canvas_height
|
||||
FROM playlist_slides ps
|
||||
JOIN slides sl ON sl.id = ps.slide_id
|
||||
LEFT JOIN slide_templates st ON st.id = sl.template_id
|
||||
LEFT JOIN canvas_sizes cs ON cs.id = st.canvas_size_id
|
||||
WHERE st.id IN (?)
|
||||
`, [templateIds]);
|
||||
[regionRows] = await pool.query('SELECT id, template_id, region_key, region_type, label, font_family, x, y, width, height, z_index, created_at, modified_at, created_by, modified_by FROM slide_template_regions WHERE template_id IN (?) ORDER BY template_id ASC, z_index ASC, id ASC', [templateIds]);
|
||||
templateRows.forEach(function (template) {
|
||||
template.regions = regionRows.filter(function (region) { return region.template_id === template.id; });
|
||||
templatesById[template.id] = template;
|
||||
WHERE ps.playlist_id = ?
|
||||
ORDER BY ps.position ASC, ps.id ASC
|
||||
`, [screen.playlist_id]);
|
||||
|
||||
const templateIds = slideRows
|
||||
.filter(function (slide) { return slide.template_id; })
|
||||
.map(function (slide) { return slide.template_id; });
|
||||
const templatesById = {};
|
||||
let templateRows = [];
|
||||
let regionRows = [];
|
||||
if (templateIds.length) {
|
||||
[templateRows] = await pool.query(`
|
||||
SELECT st.id, st.name, st.canvas_size_id, st.background_image_path, st.background_color, st.created_at, st.modified_at,
|
||||
cs.name AS canvas_size_name, cs.width AS canvas_size_width, cs.height AS canvas_size_height, cs.width AS canvas_width, cs.height AS canvas_height
|
||||
FROM slide_templates st
|
||||
LEFT JOIN canvas_sizes cs ON cs.id = st.canvas_size_id
|
||||
WHERE st.id IN (?)
|
||||
`, [templateIds]);
|
||||
[regionRows] = await pool.query('SELECT id, template_id, region_key, region_type, label, font_family, lock_ratio, x, y, width, height, z_index, created_at, modified_at, created_by, modified_by FROM slide_template_regions WHERE template_id IN (?) ORDER BY template_id ASC, z_index ASC, id ASC', [templateIds]);
|
||||
templateRows.forEach(function (template) {
|
||||
template.regions = regionRows.filter(function (region) { return region.template_id === template.id; });
|
||||
templatesById[template.id] = template;
|
||||
});
|
||||
}
|
||||
|
||||
const slides = slideRows.map(function (slide) {
|
||||
return {
|
||||
id: slide.id,
|
||||
title: slide.title,
|
||||
body: slide.body,
|
||||
duration_seconds: slide.duration_seconds,
|
||||
schedule_mode: slide.schedule_mode,
|
||||
schedule_start_datetime: slide.schedule_start_datetime,
|
||||
schedule_end_datetime: slide.schedule_end_datetime,
|
||||
schedule_start_time: slide.schedule_start_time,
|
||||
schedule_end_time: slide.schedule_end_time,
|
||||
schedule_days_json: slide.schedule_days_json,
|
||||
media_url: slide.media_path,
|
||||
media_type: slide.media_type,
|
||||
kind: common.mediaKind(slide.media_path),
|
||||
template_id: slide.template_id,
|
||||
template: slide.template_id ? templatesById[slide.template_id] || null : null,
|
||||
content: common.parseJsonSafe(slide.content_json) || {}
|
||||
};
|
||||
});
|
||||
|
||||
let rssFeeds = [];
|
||||
if (typeof common.fetchRssFeedsData === 'function' && typeof common.fetchRssFeedItemsByFeedId === 'function') {
|
||||
const rssData = await common.fetchRssFeedsData(pool);
|
||||
const feedRows = Array.isArray(rssData && rssData.rssFeeds) ? rssData.rssFeeds : [];
|
||||
rssFeeds = await Promise.all(feedRows.map(async function (feed) {
|
||||
const items = await common.fetchRssFeedItemsByFeedId(pool, feed.id);
|
||||
return Object.assign({}, feed, { items: items.map(function (item) {
|
||||
return typeof common.normalizeRssFeedItem === 'function' ? common.normalizeRssFeedItem(item) : item;
|
||||
}) });
|
||||
}));
|
||||
}
|
||||
|
||||
let apiSources = [];
|
||||
if (typeof common.fetchApiSourcesData === 'function') {
|
||||
const apiData = await common.fetchApiSourcesData(pool);
|
||||
const sourceRows = Array.isArray(apiData && apiData.apiSources) ? apiData.apiSources : [];
|
||||
apiSources = sourceRows.map(function (source) {
|
||||
return Object.assign({}, source, {
|
||||
responseJson: common.parseJsonSafe ? common.parseJsonSafe(source.last_response_json) : null
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const revision = getPlaylistRevision(screen, playlist, slideRows, templateRows, regionRows, rssFeeds, apiSources);
|
||||
const payload = { screen: screen, playlist: playlist, slides: slides, rssFeeds: rssFeeds, apiSources: apiSources, revision: revision };
|
||||
await writeSnapshot(slug, payload);
|
||||
return payload;
|
||||
} catch (error) {
|
||||
const snapshot = await readSnapshot(slug);
|
||||
if (snapshot) {
|
||||
return snapshot;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const slides = slideRows.map(function (slide) {
|
||||
return {
|
||||
id: slide.id,
|
||||
title: slide.title,
|
||||
body: slide.body,
|
||||
duration_seconds: slide.duration_seconds,
|
||||
schedule_mode: slide.schedule_mode,
|
||||
schedule_start_datetime: slide.schedule_start_datetime,
|
||||
schedule_end_datetime: slide.schedule_end_datetime,
|
||||
schedule_start_time: slide.schedule_start_time,
|
||||
schedule_end_time: slide.schedule_end_time,
|
||||
schedule_days_json: slide.schedule_days_json,
|
||||
media_url: slide.media_path,
|
||||
media_type: slide.media_type,
|
||||
kind: common.mediaKind(slide.media_path),
|
||||
template_id: slide.template_id,
|
||||
template: slide.template_id ? templatesById[slide.template_id] || null : null,
|
||||
content: common.parseJsonSafe(slide.content_json) || {}
|
||||
};
|
||||
});
|
||||
|
||||
const revision = getPlaylistRevision(screen, playlist, slideRows, templateRows, regionRows);
|
||||
|
||||
return { screen: screen, playlist: playlist, slides: slides, revision: revision };
|
||||
}
|
||||
|
||||
function updatePlaylistRevisionHash(hash, value) {
|
||||
@@ -93,7 +170,7 @@ function createPlayerPlaylistService(options) {
|
||||
hash.update('\0');
|
||||
}
|
||||
|
||||
function getPlaylistRevision(screen, playlist, slideRows, templateRows, regionRows) {
|
||||
function getPlaylistRevision(screen, playlist, slideRows, templateRows, regionRows, rssFeeds, apiSources) {
|
||||
const hash = crypto.createHash('sha1');
|
||||
|
||||
updatePlaylistRevisionHash(hash, screen && screen.id);
|
||||
@@ -149,6 +226,9 @@ function createPlayerPlaylistService(options) {
|
||||
updatePlaylistRevisionHash(hash, region.modified_at);
|
||||
});
|
||||
|
||||
updatePlaylistRevisionHash(hash, JSON.stringify(rssFeeds || []));
|
||||
updatePlaylistRevisionHash(hash, JSON.stringify(apiSources || []));
|
||||
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
|
||||
@@ -382,6 +382,23 @@ body.screen-blackout #app {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.template-region.rtmp {
|
||||
background: #000;
|
||||
}
|
||||
|
||||
.template-region.rtmp video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
display: block;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.template-region-rtmp-placeholder {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
.template-region-placeholder {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
// Capture the current viewport dimensions.
|
||||
function getCurrentViewport() {
|
||||
return {
|
||||
width: window.innerWidth,
|
||||
height: window.innerHeight
|
||||
};
|
||||
}
|
||||
|
||||
// Command websocket and player-state helpers.
|
||||
// Send the current playback state to the command websocket.
|
||||
function sendCommandState(currentSlide) {
|
||||
if (!commandSocket || commandSocket.readyState !== WebSocket.OPEN) {
|
||||
return;
|
||||
}
|
||||
commandSocket.send(JSON.stringify({
|
||||
type: 'state',
|
||||
clientId: getCommandClientId(),
|
||||
clientName: getOnboardingClientName() || null,
|
||||
deviceId: getOnboardingDeviceId() || null,
|
||||
userAgent: window.navigator.userAgent || '',
|
||||
page: window.location.href,
|
||||
viewport: getCurrentViewport(),
|
||||
paused: isPaused,
|
||||
blackout: isBlackout,
|
||||
currentSlide: currentSlide ? {
|
||||
id: currentSlide.id || null,
|
||||
title: currentSlide.title || '',
|
||||
kind: currentSlide.kind || '',
|
||||
playlistSignature: currentPlaylistSignature || ''
|
||||
} : null
|
||||
}));
|
||||
}
|
||||
|
||||
// Debounce command-state updates during rapid changes.
|
||||
function scheduleCommandStateUpdate() {
|
||||
if (commandStateTimer) {
|
||||
window.clearTimeout(commandStateTimer);
|
||||
}
|
||||
commandStateTimer = window.setTimeout(function () {
|
||||
commandStateTimer = null;
|
||||
sendCommandState(lastRenderedSlide);
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// Debounce rerenders after viewport changes.
|
||||
function scheduleViewportRenderUpdate() {
|
||||
if (viewportRenderTimer) {
|
||||
window.clearTimeout(viewportRenderTimer);
|
||||
}
|
||||
viewportRenderTimer = window.setTimeout(function () {
|
||||
viewportRenderTimer = null;
|
||||
if (slides.length) {
|
||||
var activeSlides = getCurrentActiveSlides();
|
||||
if (getCurrentRenderKey(activeSlides) === lastRenderedViewKey) {
|
||||
return;
|
||||
}
|
||||
showCurrent();
|
||||
}
|
||||
}, 150);
|
||||
}
|
||||
|
||||
// Cancel the current slide-advance timer.
|
||||
function clearSlideTimer() {
|
||||
if (timer) {
|
||||
window.clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Schedule the next slide transition.
|
||||
function scheduleSlideAdvance(delayMs) {
|
||||
clearSlideTimer();
|
||||
var holdDelayMs = Math.max(1, Number(delayMs || 0));
|
||||
slideExpiresAt = Date.now() + holdDelayMs;
|
||||
timer = window.setTimeout(function () {
|
||||
timer = null;
|
||||
slideExpiresAt = null;
|
||||
pausedRemainingMs = null;
|
||||
const activeSlides = getCurrentActiveSlides();
|
||||
if (activeSlides.length < 2) {
|
||||
refresh();
|
||||
return;
|
||||
}
|
||||
if (index >= activeSlides.length) {
|
||||
index = 0;
|
||||
}
|
||||
index = (index + 1) % activeSlides.length;
|
||||
showCurrent();
|
||||
}, holdDelayMs);
|
||||
}
|
||||
|
||||
// Cancel any pending fade-transition cleanup.
|
||||
function clearSlideTransitionTimer() {
|
||||
if (slideTransitionTimer) {
|
||||
window.clearTimeout(slideTransitionTimer);
|
||||
slideTransitionTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Swap slide markup with optional fade animation.
|
||||
function renderSlideMarkup(markup, shouldFade) {
|
||||
clearSlideTransitionTimer();
|
||||
if (typeof destroyRtmpRegions === 'function') {
|
||||
destroyRtmpRegions(app);
|
||||
}
|
||||
if (!shouldFade) {
|
||||
app.innerHTML = markup;
|
||||
if (typeof syncRtmpRegions === 'function') {
|
||||
syncRtmpRegions(app);
|
||||
}
|
||||
return app.firstElementChild;
|
||||
}
|
||||
|
||||
var topLevelChildren = Array.prototype.slice.call(app.children || []);
|
||||
var existingShells = topLevelChildren.filter(function (child) {
|
||||
return child && child.classList && child.classList.contains('slide-shell');
|
||||
});
|
||||
var previousShell = existingShells.length ? existingShells[existingShells.length - 1] : app.firstElementChild;
|
||||
|
||||
if (existingShells.length > 1) {
|
||||
existingShells.slice(0, -1).forEach(function (shell) {
|
||||
if (shell && shell.parentNode) {
|
||||
shell.parentNode.removeChild(shell);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var nextShell = document.createElement('div');
|
||||
nextShell.className = 'slide-shell';
|
||||
nextShell.style.opacity = '0';
|
||||
nextShell.innerHTML = markup;
|
||||
|
||||
if (!previousShell || (previousShell.classList && previousShell.classList.contains('empty'))) {
|
||||
app.innerHTML = '';
|
||||
nextShell.style.opacity = '1';
|
||||
app.appendChild(nextShell);
|
||||
if (typeof syncRtmpRegions === 'function') {
|
||||
syncRtmpRegions(nextShell);
|
||||
}
|
||||
return nextShell;
|
||||
}
|
||||
|
||||
if (!previousShell.classList.contains('slide-shell')) {
|
||||
previousShell.classList.add('slide-shell');
|
||||
}
|
||||
previousShell.style.opacity = '1';
|
||||
|
||||
app.appendChild(nextShell);
|
||||
void nextShell.offsetHeight;
|
||||
window.requestAnimationFrame(function () {
|
||||
nextShell.style.opacity = '1';
|
||||
previousShell.style.opacity = '0';
|
||||
});
|
||||
|
||||
if (typeof syncRtmpRegions === 'function') {
|
||||
syncRtmpRegions(nextShell);
|
||||
}
|
||||
|
||||
slideTransitionTimer = window.setTimeout(function () {
|
||||
if (previousShell && previousShell.parentNode) {
|
||||
previousShell.parentNode.removeChild(previousShell);
|
||||
}
|
||||
if (nextShell) {
|
||||
nextShell.style.opacity = '1';
|
||||
}
|
||||
slideTransitionTimer = null;
|
||||
}, slideFadeDurationMs);
|
||||
|
||||
return nextShell;
|
||||
}
|
||||
|
||||
// Mirror blackout state onto the document body.
|
||||
function syncBlackoutState() {
|
||||
document.body.classList.toggle('screen-blackout', isBlackout);
|
||||
}
|
||||
|
||||
// Apply pause state and preserve remaining slide time.
|
||||
function setPaused(nextPaused) {
|
||||
var normalized = Boolean(nextPaused);
|
||||
if (isPaused === normalized) {
|
||||
return;
|
||||
}
|
||||
if (normalized) {
|
||||
pausedRemainingMs = slideExpiresAt ? Math.max(0, slideExpiresAt - Date.now()) : null;
|
||||
isPaused = true;
|
||||
clearSlideTimer();
|
||||
sendCommandState(lastRenderedSlide);
|
||||
return;
|
||||
}
|
||||
|
||||
isPaused = false;
|
||||
sendCommandState(lastRenderedSlide);
|
||||
if (!slides.length || !lastRenderedSlide) {
|
||||
return;
|
||||
}
|
||||
if (pausedRemainingMs !== null) {
|
||||
scheduleSlideAdvance(pausedRemainingMs);
|
||||
pausedRemainingMs = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply blackout state and notify the server.
|
||||
function setBlackout(nextBlackout) {
|
||||
var normalized = Boolean(nextBlackout);
|
||||
if (isBlackout === normalized) {
|
||||
return;
|
||||
}
|
||||
isBlackout = normalized;
|
||||
syncBlackoutState();
|
||||
sendCommandState(lastRenderedSlide);
|
||||
}
|
||||
|
||||
// Coerce command payload values into booleans or null.
|
||||
function normalizeBoolean(value) {
|
||||
if (value === true || value === false) {
|
||||
return value;
|
||||
}
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
var normalized = String(value).trim().toLowerCase();
|
||||
if (['1', 'true', 'yes', 'on'].indexOf(normalized) !== -1) {
|
||||
return true;
|
||||
}
|
||||
if (['0', 'false', 'no', 'off', ''].indexOf(normalized) !== -1) {
|
||||
return false;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Move to the previous or next active slide.
|
||||
function navigateSlides(offset) {
|
||||
const manualSlides = getCurrentActiveSlides();
|
||||
if (!manualSlides.length) {
|
||||
return;
|
||||
}
|
||||
let currentIndex = manualSlides.findIndex(function (slide) {
|
||||
return slide && lastRenderedSlide && slide.id === lastRenderedSlide.id;
|
||||
});
|
||||
if (currentIndex < 0) {
|
||||
currentIndex = Math.min(Math.max(index, 0), manualSlides.length - 1);
|
||||
}
|
||||
const nextIndex = (currentIndex + offset + manualSlides.length) % manualSlides.length;
|
||||
clearSlideTimer();
|
||||
applyPendingPlaylistUpdate();
|
||||
renderSlideAtIndex(manualSlides, nextIndex);
|
||||
}
|
||||
|
||||
// Route incoming websocket command messages.
|
||||
function handleCommandMessage(rawMessage) {
|
||||
var payload;
|
||||
try {
|
||||
payload = JSON.parse(String(rawMessage || ''));
|
||||
} catch (_error) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!payload || payload.type !== 'command') {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (payload.command) {
|
||||
case 'refresh':
|
||||
refresh();
|
||||
return;
|
||||
case 'setclientname':
|
||||
if (payload.clientName) {
|
||||
applyOnboardingClientName(payload.clientName, commandSocket);
|
||||
}
|
||||
return;
|
||||
case 'redirect':
|
||||
if (payload.url) {
|
||||
window.location.replace(String(payload.url));
|
||||
}
|
||||
return;
|
||||
case 'pause':
|
||||
setPaused(!isPaused);
|
||||
return;
|
||||
case 'blackout':
|
||||
var desiredBlackout = normalizeBoolean(payload.blackout);
|
||||
if (desiredBlackout !== null) {
|
||||
setBlackout(desiredBlackout);
|
||||
} else {
|
||||
setBlackout(!isBlackout);
|
||||
}
|
||||
return;
|
||||
case 'previous':
|
||||
case 'left':
|
||||
navigateSlides(-1);
|
||||
return;
|
||||
case 'next':
|
||||
case 'right':
|
||||
navigateSlides(1);
|
||||
return;
|
||||
case 'reload':
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Retry the command websocket after a disconnect.
|
||||
function scheduleCommandReconnect() {
|
||||
if (commandReconnectTimer) {
|
||||
return;
|
||||
}
|
||||
commandReconnectTimer = window.setTimeout(function () {
|
||||
commandReconnectTimer = null;
|
||||
connectCommandSocket();
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Open and wire the command websocket connection.
|
||||
function connectCommandSocket() {
|
||||
if (!window.WebSocket) {
|
||||
return;
|
||||
}
|
||||
if (commandSocket && (commandSocket.readyState === WebSocket.OPEN || commandSocket.readyState === WebSocket.CONNECTING)) {
|
||||
return;
|
||||
}
|
||||
var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
var socketUrl = new URL(commandSocketPath, window.location.origin);
|
||||
if (window.__pulsePageAuthToken) {
|
||||
socketUrl.searchParams.set('auth', window.__pulsePageAuthToken);
|
||||
}
|
||||
var socket = new WebSocket(socketUrl.toString());
|
||||
commandSocket = socket;
|
||||
|
||||
socket.onopen = function () {
|
||||
if (typeof syncOnboardingClientNameFromServer === 'function') {
|
||||
syncOnboardingClientNameFromServer(socket).then(function () {
|
||||
sendCommandHello(socket);
|
||||
});
|
||||
return;
|
||||
}
|
||||
sendCommandHello(socket);
|
||||
};
|
||||
|
||||
socket.onmessage = function (event) {
|
||||
handleCommandMessage(event.data);
|
||||
};
|
||||
|
||||
socket.onclose = function () {
|
||||
commandSocket = null;
|
||||
scheduleCommandReconnect();
|
||||
};
|
||||
|
||||
socket.onerror = function () {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (_error) {
|
||||
// ignore socket close errors
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Show or hide the offline status banner.
|
||||
function setOfflineBannerVisible(visible, message) {
|
||||
var normalizedVisible = Boolean(visible);
|
||||
var bannerMessage = String(message || 'Offline mode: using cached playlist.').trim();
|
||||
if (normalizedVisible) {
|
||||
if (!offlineBanner) {
|
||||
offlineBanner = document.createElement('div');
|
||||
offlineBanner.className = 'player-offline-banner';
|
||||
offlineBanner.style.position = 'fixed';
|
||||
offlineBanner.style.right = '0';
|
||||
offlineBanner.style.bottom = '0';
|
||||
offlineBanner.style.left = 'auto';
|
||||
offlineBanner.style.top = 'auto';
|
||||
offlineBanner.style.width = '1.25rem';
|
||||
offlineBanner.style.height = '1.25rem';
|
||||
offlineBanner.style.zIndex = '9999';
|
||||
offlineBanner.style.background = 'linear-gradient(135deg, #ff4d4f 0%, #b00020 100%)';
|
||||
offlineBanner.style.clipPath = 'circle(100% at 100% 100%)';
|
||||
offlineBanner.style.webkitClipPath = 'circle(100% at 100% 100%)';
|
||||
offlineBanner.style.boxShadow = '0 0 0 1px rgba(0, 0, 0, 0.16), 0 4px 12px rgba(0, 0, 0, 0.18)';
|
||||
offlineBanner.style.pointerEvents = 'none';
|
||||
document.body.appendChild(offlineBanner);
|
||||
}
|
||||
offlineBanner.textContent = '';
|
||||
offlineBanner.setAttribute('aria-label', bannerMessage);
|
||||
offlineBanner.setAttribute('role', 'img');
|
||||
offlineBanner.title = bannerMessage;
|
||||
offlineBannerVisible = true;
|
||||
return;
|
||||
}
|
||||
|
||||
offlineBannerVisible = false;
|
||||
if (offlineBanner && offlineBanner.parentNode) {
|
||||
offlineBanner.parentNode.removeChild(offlineBanner);
|
||||
}
|
||||
offlineBanner = null;
|
||||
}
|
||||
|
||||
// Update the offline banner based on connectivity or playlist availability.
|
||||
function syncOfflineBanner() {
|
||||
if (!window.navigator.onLine) {
|
||||
setOfflineBannerVisible(true, 'Offline mode: using cached playlist.');
|
||||
return;
|
||||
}
|
||||
if (offlineBannerVisible) {
|
||||
setOfflineBannerVisible(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear any pending playlist refresh retry.
|
||||
function clearRefreshRetry() {
|
||||
if (refreshRetryTimer) {
|
||||
window.clearTimeout(refreshRetryTimer);
|
||||
refreshRetryTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Retry playlist refresh with a short backoff while the player is offline.
|
||||
function scheduleRefreshRetry() {
|
||||
if (refreshRetryTimer) {
|
||||
return;
|
||||
}
|
||||
if (window.navigator.onLine === false) {
|
||||
refreshRetryDelayMs = refreshRetryDelayMs ? Math.min(refreshRetryDelayMs * 2, 15000) : 3000;
|
||||
} else {
|
||||
refreshRetryDelayMs = refreshRetryDelayMs ? Math.min(refreshRetryDelayMs * 2, 8000) : 3000;
|
||||
}
|
||||
refreshRetryTimer = window.setTimeout(function () {
|
||||
refreshRetryTimer = null;
|
||||
refresh();
|
||||
}, refreshRetryDelayMs);
|
||||
}
|
||||
|
||||
function clearScreenWakeLockRetry() {
|
||||
if (screenWakeLockRetryTimer) {
|
||||
window.clearTimeout(screenWakeLockRetryTimer);
|
||||
screenWakeLockRetryTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function supportsScreenWakeLock() {
|
||||
return Boolean(window.navigator && window.navigator.wakeLock && typeof window.navigator.wakeLock.request === 'function');
|
||||
}
|
||||
|
||||
function scheduleScreenWakeLockRetry() {
|
||||
if (screenWakeLockRetryTimer) {
|
||||
return;
|
||||
}
|
||||
if (!supportsScreenWakeLock() || document.visibilityState !== 'visible') {
|
||||
return;
|
||||
}
|
||||
screenWakeLockRetryTimer = window.setTimeout(function () {
|
||||
screenWakeLockRetryTimer = null;
|
||||
acquireScreenWakeLock();
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function releaseScreenWakeLock() {
|
||||
if (screenWakeLock && typeof screenWakeLock.release === 'function') {
|
||||
try {
|
||||
screenWakeLock.release();
|
||||
} catch (_error) {
|
||||
// ignore wake lock release errors
|
||||
}
|
||||
}
|
||||
screenWakeLock = null;
|
||||
screenWakeLockRequestPromise = null;
|
||||
clearScreenWakeLockRetry();
|
||||
}
|
||||
|
||||
function acquireScreenWakeLock() {
|
||||
if (!supportsScreenWakeLock() || document.visibilityState !== 'visible') {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
if (screenWakeLockRequestPromise) {
|
||||
return screenWakeLockRequestPromise;
|
||||
}
|
||||
if (screenWakeLock && screenWakeLock.released === false) {
|
||||
return Promise.resolve(screenWakeLock);
|
||||
}
|
||||
|
||||
screenWakeLockRequestPromise = window.navigator.wakeLock.request('screen').then(function (sentinel) {
|
||||
screenWakeLock = sentinel;
|
||||
screenWakeLock.addEventListener('release', function () {
|
||||
screenWakeLock = null;
|
||||
if (document.visibilityState === 'visible') {
|
||||
scheduleScreenWakeLockRetry();
|
||||
}
|
||||
});
|
||||
clearScreenWakeLockRetry();
|
||||
return screenWakeLock;
|
||||
}).catch(function (error) {
|
||||
screenWakeLock = null;
|
||||
if (error && error.name !== 'NotAllowedError') {
|
||||
scheduleScreenWakeLockRetry();
|
||||
}
|
||||
return null;
|
||||
}).finally(function () {
|
||||
screenWakeLockRequestPromise = null;
|
||||
});
|
||||
|
||||
return screenWakeLockRequestPromise;
|
||||
}
|
||||
|
||||
function syncScreenWakeLock() {
|
||||
if (!supportsScreenWakeLock()) {
|
||||
return;
|
||||
}
|
||||
if (document.visibilityState === 'visible') {
|
||||
acquireScreenWakeLock();
|
||||
return;
|
||||
}
|
||||
releaseScreenWakeLock();
|
||||
}
|
||||
|
||||
// Clear the retry cadence after a successful refresh.
|
||||
function markRefreshHealthy() {
|
||||
refreshRetryDelayMs = 0;
|
||||
clearRefreshRetry();
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Render the slide at the requested index within the active set.
|
||||
function renderSlideAtIndex(sourceSlides, targetIndex) {
|
||||
const availableSlides = Array.isArray(sourceSlides) ? sourceSlides : [];
|
||||
if (!availableSlides.length) {
|
||||
renderEmpty(slides.length ? 'No slides are scheduled for this time.' : 'No slides assigned to this screen yet.');
|
||||
lastRenderedViewKey = getCurrentRenderKey(availableSlides);
|
||||
return false;
|
||||
}
|
||||
|
||||
let normalizedIndex = Number(targetIndex || 0);
|
||||
if (!Number.isFinite(normalizedIndex) || normalizedIndex < 0 || normalizedIndex >= availableSlides.length) {
|
||||
}
|
||||
|
||||
const slide = availableSlides[normalizedIndex];
|
||||
if (!slide) {
|
||||
renderEmpty(slides.length ? 'No slides are scheduled for this time.' : 'No slides assigned to this screen yet.');
|
||||
return false;
|
||||
}
|
||||
|
||||
index = normalizedIndex;
|
||||
var markup = buildSlideMarkup(slide);
|
||||
renderSlideMarkup(markup, currentPlaylistFadeBetweenSlides);
|
||||
sendCommandState(slide);
|
||||
if (!isPaused) {
|
||||
scheduleSlideAdvance(Math.max(1, Number(slide.duration_seconds || 10)) * 1000);
|
||||
}
|
||||
lastRenderedViewKey = getCurrentRenderKey(availableSlides);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Promote a deferred playlist update at the next safe point.
|
||||
function applyPendingPlaylistUpdate() {
|
||||
if (!pendingPlaylistUpdate) {
|
||||
return false;
|
||||
}
|
||||
slides = pendingPlaylistUpdate.slides;
|
||||
currentPlaylistSignature = pendingPlaylistUpdate.signature;
|
||||
currentPlaylistFadeBetweenSlides = pendingPlaylistUpdate.fadeBetweenSlides;
|
||||
pendingPlaylistUpdate = null;
|
||||
clearActiveSlidesCache();
|
||||
slideMarkupCache = Object.create(null);
|
||||
templateLayoutCache = Object.create(null);
|
||||
templateRenderPlanCache = Object.create(null);
|
||||
renderCacheViewportKey = window.innerWidth + 'x' + window.innerHeight;
|
||||
index = 0;
|
||||
logDebug('Applied updated playlist on slide transition.');
|
||||
return true;
|
||||
}
|
||||
|
||||
// Render the current active slide or the empty state.
|
||||
function showCurrent() {
|
||||
clearSlideTimer();
|
||||
applyPendingPlaylistUpdate();
|
||||
const activeSlides = getCurrentActiveSlides();
|
||||
syncWebpagePreloads(activeSlides, index);
|
||||
if (typeof syncRtmpPreloads === 'function') {
|
||||
syncRtmpPreloads(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);
|
||||
return;
|
||||
}
|
||||
renderSlideAtIndex(activeSlides, index);
|
||||
lastRenderedViewKey = getCurrentRenderKey(activeSlides);
|
||||
}
|
||||
|
||||
// Fetch the latest playlist and queue any updates.
|
||||
function refresh() {
|
||||
var request = new XMLHttpRequest();
|
||||
var url = window.location.origin + '/api/screens/' + encodeURIComponent(slug) + '/playlist?ts=' + Date.now();
|
||||
request.open('GET', url, true);
|
||||
request.timeout = 2500;
|
||||
if (window.__pulsePageAuthToken) {
|
||||
request.setRequestHeader('x-pulse-page-auth', window.__pulsePageAuthToken);
|
||||
}
|
||||
if (currentPlaylistEtag) {
|
||||
request.setRequestHeader('If-None-Match', currentPlaylistEtag);
|
||||
}
|
||||
request.onreadystatechange = function () {
|
||||
if (request.readyState !== 4) {
|
||||
return;
|
||||
}
|
||||
if (request.status === 304) {
|
||||
markRefreshHealthy();
|
||||
setOfflineBannerVisible(false);
|
||||
if (lastRenderedSlide && getCurrentActiveSlides().length < 2) {
|
||||
scheduleSlideAdvance(Math.max(1, Number(lastRenderedSlide.duration_seconds || 10)) * 1000);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (request.status < 200 || request.status >= 300) {
|
||||
setOfflineBannerVisible(true);
|
||||
scheduleRefreshRetry();
|
||||
logDebug(
|
||||
'Screen not found or playlist unavailable.',
|
||||
['URL: ' + url, 'Status: ' + request.status + ' ' + request.statusText, 'Response: ' + String(request.responseText || '').slice(0, 1000)].join(' | '),
|
||||
'error'
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const responseEtag = String(request.getResponseHeader('ETag') || '').trim();
|
||||
const data = JSON.parse(request.responseText || '{}');
|
||||
const nextSignature = getPlaylistRevision(data);
|
||||
const nextSlides = Array.isArray(data.slides) ? data.slides.map(normalizeSlide) : [];
|
||||
const nextFadeBetweenSlides = Boolean(data && data.playlist && data.playlist.fade_between_slides);
|
||||
savePlaylistSnapshot({
|
||||
slides: nextSlides,
|
||||
signature: nextSignature,
|
||||
fadeBetweenSlides: nextFadeBetweenSlides,
|
||||
etag: responseEtag
|
||||
});
|
||||
markRefreshHealthy();
|
||||
setOfflineBannerVisible(false);
|
||||
const currentActiveSlides = getCurrentActiveSlides();
|
||||
if (responseEtag) {
|
||||
currentPlaylistEtag = responseEtag;
|
||||
}
|
||||
if (!currentPlaylistSignature) {
|
||||
slides = nextSlides;
|
||||
currentPlaylistSignature = nextSignature;
|
||||
currentPlaylistFadeBetweenSlides = nextFadeBetweenSlides;
|
||||
index = 0;
|
||||
showCurrent();
|
||||
sendCommandState(lastRenderedSlide);
|
||||
return;
|
||||
}
|
||||
if (nextSignature === currentPlaylistSignature || (pendingPlaylistUpdate && nextSignature === pendingPlaylistUpdate.signature)) {
|
||||
if (currentActiveSlides.length < 2 && lastRenderedSlide) {
|
||||
scheduleSlideAdvance(Math.max(1, Number(lastRenderedSlide.duration_seconds || 10)) * 1000);
|
||||
}
|
||||
return;
|
||||
}
|
||||
syncWebpagePreloads(getActiveSlidesFrom(nextSlides), index);
|
||||
if (typeof syncRtmpPreloads === 'function') {
|
||||
syncRtmpPreloads(getActiveSlidesFrom(nextSlides), index);
|
||||
}
|
||||
if (currentActiveSlides.length < 2) {
|
||||
slides = nextSlides;
|
||||
currentPlaylistSignature = nextSignature;
|
||||
currentPlaylistFadeBetweenSlides = nextFadeBetweenSlides;
|
||||
pendingPlaylistUpdate = null;
|
||||
index = 0;
|
||||
showCurrent();
|
||||
sendCommandState(lastRenderedSlide);
|
||||
return;
|
||||
}
|
||||
pendingPlaylistUpdate = {
|
||||
slides: nextSlides,
|
||||
signature: nextSignature,
|
||||
fadeBetweenSlides: nextFadeBetweenSlides
|
||||
};
|
||||
logDebug('Playlist update detected; applying on next slide transition.');
|
||||
} catch (_error) {
|
||||
logDebug(
|
||||
'Unable to load screen playlist.',
|
||||
['URL: ' + url, 'Response: ' + String(request.responseText || '').slice(0, 1000)].join(' | '),
|
||||
'error'
|
||||
);
|
||||
setOfflineBannerVisible(true);
|
||||
scheduleRefreshRetry();
|
||||
}
|
||||
};
|
||||
request.onerror = function () {
|
||||
logDebug(
|
||||
'Unable to load screen playlist.',
|
||||
['URL: ' + url, 'Network error during request.'].join(' | '),
|
||||
'error'
|
||||
);
|
||||
setOfflineBannerVisible(true);
|
||||
scheduleRefreshRetry();
|
||||
if (lastRenderedSlide && getCurrentActiveSlides().length < 2) {
|
||||
scheduleSlideAdvance(Math.max(1, Number(lastRenderedSlide.duration_seconds || 10)) * 1000);
|
||||
}
|
||||
};
|
||||
request.ontimeout = function () {
|
||||
logDebug(
|
||||
'Playlist refresh timed out.',
|
||||
['URL: ' + url, 'Timeout after ' + request.timeout + 'ms'].join(' | '),
|
||||
'error'
|
||||
);
|
||||
setOfflineBannerVisible(true);
|
||||
scheduleRefreshRetry();
|
||||
if (lastRenderedSlide && getCurrentActiveSlides().length < 2) {
|
||||
scheduleSlideAdvance(Math.max(1, Number(lastRenderedSlide.duration_seconds || 10)) * 1000);
|
||||
}
|
||||
};
|
||||
request.send();
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// Collect unique webpage URLs from the slide list.
|
||||
function getWebpageUrls(sourceSlides) {
|
||||
const urls = [];
|
||||
(Array.isArray(sourceSlides) ? sourceSlides : []).forEach(function (slide) {
|
||||
const content = slide && slide.content ? slide.content : {};
|
||||
const regions = slide && slide.template && Array.isArray(slide.template.regions) ? slide.template.regions : [];
|
||||
regions.forEach(function (region) {
|
||||
if (region.region_type !== 'webpage') {
|
||||
return;
|
||||
}
|
||||
const regionContent = content[region.region_key] || {};
|
||||
const url = String(regionContent.value || '').trim();
|
||||
if (url && urls.indexOf(url) === -1) {
|
||||
urls.push(url);
|
||||
}
|
||||
});
|
||||
});
|
||||
return urls;
|
||||
}
|
||||
|
||||
// Filter the slides down to those that are active right now.
|
||||
function getActiveSlidesFrom(sourceSlides) {
|
||||
const now = new Date();
|
||||
return (Array.isArray(sourceSlides) ? sourceSlides : []).filter(function (slide) {
|
||||
return isSlideActive(slide, now);
|
||||
});
|
||||
}
|
||||
|
||||
// Build a cache key for the active slide set.
|
||||
function getActiveSlidesCacheKey() {
|
||||
const now = new Date();
|
||||
return [
|
||||
currentPlaylistSignature || '',
|
||||
now.getFullYear(),
|
||||
now.getMonth(),
|
||||
now.getDate(),
|
||||
now.getHours(),
|
||||
now.getMinutes(),
|
||||
now.getSeconds()
|
||||
].join('|');
|
||||
}
|
||||
|
||||
// Return the cached active slide set for the current playlist and second.
|
||||
function getCurrentActiveSlides() {
|
||||
const cacheKey = getActiveSlidesCacheKey();
|
||||
if (cacheKey !== activeSlidesCacheKey) {
|
||||
activeSlidesCacheValue = getActiveSlidesFrom(slides);
|
||||
activeSlidesCacheKey = cacheKey;
|
||||
}
|
||||
return activeSlidesCacheValue;
|
||||
}
|
||||
|
||||
// Clear the cached active slide set.
|
||||
function clearActiveSlidesCache() {
|
||||
activeSlidesCacheKey = '';
|
||||
activeSlidesCacheValue = [];
|
||||
}
|
||||
|
||||
// Reset render caches when the viewport changes.
|
||||
function syncRenderCacheViewport() {
|
||||
var viewportKey = window.innerWidth + 'x' + window.innerHeight;
|
||||
if (renderCacheViewportKey === viewportKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
renderCacheViewportKey = viewportKey;
|
||||
slideMarkupCache = Object.create(null);
|
||||
templateLayoutCache = Object.create(null);
|
||||
templateRenderPlanCache = Object.create(null);
|
||||
}
|
||||
|
||||
// Build a signature for the currently rendered view.
|
||||
function getCurrentRenderKey(activeSlides) {
|
||||
const viewportKey = window.innerWidth + 'x' + window.innerHeight;
|
||||
const availableSlides = Array.isArray(activeSlides) ? activeSlides : [];
|
||||
if (!availableSlides.length) {
|
||||
return [currentPlaylistSignature || '', viewportKey, 'empty', slides.length ? 'scheduled' : 'assigned'].join('|');
|
||||
}
|
||||
let normalizedIndex = Number(index || 0);
|
||||
if (!Number.isFinite(normalizedIndex) || normalizedIndex < 0 || normalizedIndex >= availableSlides.length) {
|
||||
normalizedIndex = 0;
|
||||
}
|
||||
const slide = availableSlides[normalizedIndex];
|
||||
return [currentPlaylistSignature || '', viewportKey, 'slide', slide && slide.id ? slide.id : ''].join('|');
|
||||
}
|
||||
|
||||
// Pick the current slide and the next slide for webpage preloading.
|
||||
function getWebpagePreloadSlides(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 currentSlide = availableSlides[normalizedIndex];
|
||||
const nextSlide = availableSlides[normalizedIndex + 1];
|
||||
|
||||
if (currentSlide) {
|
||||
preloadSlides.push(currentSlide);
|
||||
}
|
||||
if (nextSlide && nextSlide !== currentSlide) {
|
||||
preloadSlides.push(nextSlide);
|
||||
}
|
||||
|
||||
return preloadSlides;
|
||||
}
|
||||
|
||||
// Mount hidden iframe preloads for the chosen webpage URLs.
|
||||
function syncWebpagePreloads(sourceSlides, targetIndex) {
|
||||
const urls = getWebpageUrls(getWebpagePreloadSlides(sourceSlides, targetIndex));
|
||||
const signature = urls.join('\n');
|
||||
if (signature === preloadSignature) {
|
||||
return;
|
||||
}
|
||||
if (!urls.length) {
|
||||
preloadSignature = '';
|
||||
if (preloadContainer) {
|
||||
preloadContainer.innerHTML = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!preloadContainer) {
|
||||
preloadContainer = document.createElement('div');
|
||||
preloadContainer.className = 'webpage-preloads';
|
||||
preloadContainer.setAttribute('aria-hidden', 'true');
|
||||
document.body.appendChild(preloadContainer);
|
||||
}
|
||||
preloadContainer.innerHTML = urls.map(function (url) {
|
||||
return '<iframe class="webpage-preload-frame" src="' + escapeHtml(url) + '" title="Webpage preload" tabindex="-1" loading="eager" referrerpolicy="no-referrer" scrolling="no"></iframe>';
|
||||
}).join('');
|
||||
preloadSignature = signature;
|
||||
}
|
||||
|
||||
// Return a stable client id for this browser session.
|
||||
function getCommandClientId() {
|
||||
if (commandClientId) {
|
||||
return commandClientId;
|
||||
}
|
||||
try {
|
||||
var storedClientId = window.localStorage.getItem(commandClientStorageKey);
|
||||
if (storedClientId) {
|
||||
commandClientId = storedClientId;
|
||||
return commandClientId;
|
||||
}
|
||||
} catch (_error) {
|
||||
// fall through to ephemeral ID generation
|
||||
}
|
||||
commandClientId = (window.crypto && window.crypto.randomUUID ? window.crypto.randomUUID() : 'client-' + Date.now() + '-' + Math.random().toString(16).slice(2));
|
||||
try {
|
||||
window.localStorage.setItem(commandClientStorageKey, commandClientId);
|
||||
} catch (_error2) {
|
||||
// ignore storage errors
|
||||
}
|
||||
return commandClientId;
|
||||
}
|
||||
|
||||
// Load the most recent playlist snapshot from browser storage.
|
||||
function loadPlaylistSnapshot() {
|
||||
try {
|
||||
var raw = window.localStorage.getItem(playlistSnapshotStorageKey);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
var parsed = JSON.parse(raw);
|
||||
if (!parsed || !Array.isArray(parsed.slides)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
slides: parsed.slides.map(normalizeSlide),
|
||||
signature: String(parsed.signature || ''),
|
||||
fadeBetweenSlides: Boolean(parsed.fadeBetweenSlides),
|
||||
etag: String(parsed.etag || '')
|
||||
};
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Save the latest playlist snapshot for offline recovery.
|
||||
function savePlaylistSnapshot(data) {
|
||||
try {
|
||||
window.localStorage.setItem(playlistSnapshotStorageKey, JSON.stringify({
|
||||
slides: Array.isArray(data && data.slides) ? data.slides : [],
|
||||
signature: String(data && data.signature || ''),
|
||||
fadeBetweenSlides: Boolean(data && data.fadeBetweenSlides),
|
||||
etag: String(data && data.etag || ''),
|
||||
savedAt: new Date().toISOString()
|
||||
}));
|
||||
} catch (_error) {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
// Apply a playlist snapshot to the current in-memory state.
|
||||
function applyPlaylistSnapshot(data) {
|
||||
if (!data || !Array.isArray(data.slides)) {
|
||||
return false;
|
||||
}
|
||||
slides = data.slides.map(normalizeSlide);
|
||||
currentPlaylistSignature = String(data.signature || '');
|
||||
currentPlaylistFadeBetweenSlides = Boolean(data.fadeBetweenSlides);
|
||||
currentPlaylistEtag = String(data.etag || '');
|
||||
pendingPlaylistUpdate = null;
|
||||
clearActiveSlidesCache();
|
||||
slideMarkupCache = Object.create(null);
|
||||
templateLayoutCache = Object.create(null);
|
||||
templateRenderPlanCache = Object.create(null);
|
||||
renderCacheViewportKey = '';
|
||||
index = 0;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
// General sanitization and sizing helpers.
|
||||
// Strip unsupported characters from a font family string.
|
||||
function sanitizeFontFamily(value) {
|
||||
return String(value || '').replace(/[^a-zA-Z0-9 ,\"-]/g, '').trim();
|
||||
}
|
||||
|
||||
// Clamp font size to the supported range.
|
||||
function sanitizeFontSize(value) {
|
||||
return Math.max(8, Number(value || 0) || 24);
|
||||
}
|
||||
|
||||
// Validate a text color and fall back when needed.
|
||||
function sanitizeTextColor(value, fallback) {
|
||||
var raw = String(value || '').trim();
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(raw) || /^#[0-9a-fA-F]{3}$/.test(raw)) {
|
||||
return raw;
|
||||
}
|
||||
return fallback || '#000000';
|
||||
}
|
||||
|
||||
// Read the template's canvas dimensions with safe defaults.
|
||||
function getTemplateCanvasSize(template) {
|
||||
return {
|
||||
width: Math.max(1, Number(template.canvas_size_width || 1920)),
|
||||
height: Math.max(1, Number(template.canvas_size_height || 1080))
|
||||
};
|
||||
}
|
||||
|
||||
// Read the server-supplied playlist revision, or fall back to the ETag.
|
||||
function getPlaylistRevision(data) {
|
||||
if (data && data.revision) {
|
||||
return String(data.revision);
|
||||
}
|
||||
if (data && data.playlist && data.playlist.revision) {
|
||||
return String(data.playlist.revision);
|
||||
}
|
||||
if (currentPlaylistEtag) {
|
||||
return String(currentPlaylistEtag).replace(/^"|"$/g, '');
|
||||
}
|
||||
return String(Date.now());
|
||||
}
|
||||
|
||||
// Scale a canvas to fit within the viewport.
|
||||
function fitCanvasSize(canvasWidth, canvasHeight, maxWidth, maxHeight) {
|
||||
var width = Math.max(1, Number(canvasWidth || 0) || 1920);
|
||||
var height = Math.max(1, Number(canvasHeight || 0) || 1080);
|
||||
var viewportWidth = Math.max(1, Number(maxWidth || 0) || width);
|
||||
var viewportHeight = Math.max(1, Number(maxHeight || 0) || height);
|
||||
var scale = Math.min(viewportWidth / width, viewportHeight / height);
|
||||
return {
|
||||
width: Math.round(width * scale),
|
||||
height: Math.round(height * scale)
|
||||
};
|
||||
}
|
||||
|
||||
const ALLOWED_RICH_TEXT_TAGS = ['a', 'b', 'blockquote', 'br', 'code', 'div', 'em', 'figure', 'figcaption', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'li', 'ol', 'p', 'pre', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'u', 'ul'];
|
||||
|
||||
function sanitizeRichTextAttributes(tagName, attrText) {
|
||||
const allowedAttributes = {
|
||||
a: ['href', 'title', 'target', 'rel', 'class', 'style'],
|
||||
blockquote: ['class', 'style'],
|
||||
div: ['class', 'style'],
|
||||
figure: ['class', 'style'],
|
||||
figcaption: ['class', 'style'],
|
||||
h1: ['class', 'style'],
|
||||
h2: ['class', 'style'],
|
||||
h3: ['class', 'style'],
|
||||
h4: ['class', 'style'],
|
||||
h5: ['class', 'style'],
|
||||
h6: ['class', 'style'],
|
||||
li: ['class', 'style'],
|
||||
ol: ['class', 'style', 'start'],
|
||||
p: ['class', 'style'],
|
||||
pre: ['class', 'style'],
|
||||
span: ['class', 'style'],
|
||||
table: ['class', 'style'],
|
||||
td: ['class', 'style', 'colspan', 'rowspan'],
|
||||
th: ['class', 'style', 'colspan', 'rowspan', 'scope'],
|
||||
tr: ['class', 'style'],
|
||||
ul: ['class', 'style']
|
||||
};
|
||||
const allowed = allowedAttributes[tagName] || [];
|
||||
if (!allowed.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const attrs = [];
|
||||
String(attrText || '').replace(/([a-zA-Z0-9:-]+)(?:\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'>/=`]+)))?/g, (_full, key, _valuePart, doubleQuoted, singleQuoted, bareValue) => {
|
||||
const lowerKey = String(key || '').toLowerCase();
|
||||
if (!allowed.includes(lowerKey)) {
|
||||
return '';
|
||||
}
|
||||
const value = doubleQuoted !== undefined ? doubleQuoted : singleQuoted !== undefined ? singleQuoted : bareValue !== undefined ? bareValue : '';
|
||||
if (lowerKey === 'href' && /^(?:\s*javascript:|\s*data:)/i.test(String(value || ''))) {
|
||||
return '';
|
||||
}
|
||||
if (lowerKey === 'style' && /(?:expression\s*\(|javascript:|url\s*\()/i.test(String(value || ''))) {
|
||||
return '';
|
||||
}
|
||||
if (lowerKey === 'target') {
|
||||
const targetValue = String(value || '').trim();
|
||||
if (targetValue === '_blank') {
|
||||
attrs.push(' target="_blank"');
|
||||
if (!attrs.includes(' rel="noreferrer noopener"')) {
|
||||
attrs.push(' rel="noreferrer noopener"');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
}
|
||||
attrs.push(' ' + lowerKey + '="' + escapeHtml(value) + '"');
|
||||
return '';
|
||||
});
|
||||
|
||||
return attrs.join('');
|
||||
}
|
||||
|
||||
// Remove unsafe markup while preserving richer CKEditor formatting.
|
||||
function sanitizeRichText(html) {
|
||||
var output = String(html || '');
|
||||
output = output.replace(/<script[\s\S]*?<\/script>/gi, '');
|
||||
output = output.replace(/<style[\s\S]*?<\/style>/gi, '');
|
||||
return output.replace(/<[^>]+>/g, function (tag) {
|
||||
var match = tag.match(/^<\s*(\/?)\s*([a-z0-9]+)([\s\S]*?)(\/?)>$/i);
|
||||
if (!match) {
|
||||
return '';
|
||||
}
|
||||
var closing = Boolean(match[1]);
|
||||
var name = String(match[2] || '').toLowerCase();
|
||||
var attrText = String(match[3] || '');
|
||||
if (ALLOWED_RICH_TEXT_TAGS.indexOf(name) === -1) {
|
||||
return '';
|
||||
}
|
||||
if (closing) {
|
||||
return '</' + name + '>';
|
||||
}
|
||||
return '<' + name + sanitizeRichTextAttributes(name, attrText) + '>';
|
||||
});
|
||||
}
|
||||
|
||||
// Render a single Editor.js block to HTML.
|
||||
function renderEditorJsBlock(block) {
|
||||
if (!block || !block.type || !block.data) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (block.type === 'header') {
|
||||
var level = Math.max(1, Math.min(6, Number(block.data.level || 2)));
|
||||
return '<h' + level + '>' + sanitizeRichText(block.data.text || '') + '</h' + level + '>';
|
||||
}
|
||||
|
||||
if (block.type === 'list') {
|
||||
var tag = block.data.style === 'ordered' ? 'ol' : 'ul';
|
||||
var items = Array.isArray(block.data.items) ? block.data.items : [];
|
||||
return '<' + tag + ' style="list-style-type:' + (tag === 'ol' ? 'decimal' : 'disc') + ';padding-left:1.4em;">' + items.map(function (item) { return renderEditorJsListItem(item, tag); }).join('') + '</' + tag + '>';
|
||||
}
|
||||
|
||||
if (block.type === 'delimiter') {
|
||||
return '<hr />';
|
||||
}
|
||||
|
||||
if (block.type === 'code') {
|
||||
return '<pre><code>' + escapeHtml(block.data.code || '') + '</code></pre>';
|
||||
}
|
||||
|
||||
if (block.type === 'table') {
|
||||
return renderEditorJsTable(block.data);
|
||||
}
|
||||
|
||||
if (block.type === 'paragraph') {
|
||||
return '<p>' + sanitizeRichText(block.data.text || '') + '</p>';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
// Render a list item and any nested sub-items.
|
||||
function renderEditorJsListItem(item, tag) {
|
||||
if (item && typeof item === 'object') {
|
||||
var content = item.content !== undefined ? item.content : (item.text !== undefined ? item.text : item.value !== undefined ? item.value : '');
|
||||
var children = Array.isArray(item.items) ? item.items : Array.isArray(item.subItems) ? item.subItems : Array.isArray(item.children) ? item.children : [];
|
||||
var nested = children.length ? '<' + tag + ' style="list-style-type:' + (tag === 'ol' ? 'decimal' : 'disc') + ';padding-left:1.4em;">' + children.map(function (child) { return renderEditorJsListItem(child, tag); }).join('') + '</' + tag + '>' : '';
|
||||
return '<li>' + sanitizeRichText(content || '') + nested + '</li>';
|
||||
}
|
||||
return '<li>' + sanitizeRichText(item || '') + '</li>';
|
||||
}
|
||||
|
||||
// Render an Editor.js table block.
|
||||
function renderEditorJsTable(data) {
|
||||
var rows = Array.isArray(data.content) ? data.content : Array.isArray(data.rows) ? data.rows : [];
|
||||
if (!rows.length) {
|
||||
return '';
|
||||
}
|
||||
var hasHeadings = Boolean(data.withHeadings);
|
||||
var tableRows = rows.map(function (row, rowIndex) {
|
||||
var cells = Array.isArray(row) ? row : [];
|
||||
var cellTag = hasHeadings && rowIndex === 0 ? 'th' : 'td';
|
||||
var cellAttrs = cellTag === 'th' ? ' scope="col"' : '';
|
||||
return '<tr>' + cells.map(function (cell) {
|
||||
return '<' + cellTag + cellAttrs + '>' + sanitizeRichText(cell || '') + '</' + cellTag + '>';
|
||||
}).join('') + '</tr>';
|
||||
}).join('');
|
||||
return '<table class="ck-content-table">' + tableRows + '</table>';
|
||||
}
|
||||
|
||||
// Render Editor.js JSON or plain content safely.
|
||||
function renderEditorJsContent(value) {
|
||||
if (value && typeof value === 'object') {
|
||||
if (Array.isArray(value.blocks)) {
|
||||
return value.blocks.map(renderEditorJsBlock).join('');
|
||||
}
|
||||
if (value.value !== undefined) {
|
||||
return renderEditorJsContent(value.value);
|
||||
}
|
||||
}
|
||||
var raw = String(value || '');
|
||||
try {
|
||||
var parsed = JSON.parse(raw);
|
||||
if (parsed && Array.isArray(parsed.blocks)) {
|
||||
return parsed.blocks.map(renderEditorJsBlock).join('');
|
||||
}
|
||||
} catch (_error) {
|
||||
// fall through to legacy HTML rendering
|
||||
}
|
||||
return sanitizeRichText(raw);
|
||||
}
|
||||
|
||||
// Parse string values that look like JSON.
|
||||
function parseMaybeJson(value) {
|
||||
if (typeof value !== 'string') {
|
||||
return value;
|
||||
}
|
||||
var raw = value.trim();
|
||||
if (!raw) {
|
||||
return value;
|
||||
}
|
||||
if (raw.charAt(0) !== '{' && raw.charAt(0) !== '[') {
|
||||
return value;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch (_error) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize a slide region's stored content value.
|
||||
function normalizeContentValue(value) {
|
||||
var normalized;
|
||||
if (!value || typeof value !== 'object') {
|
||||
return {
|
||||
type: 'text',
|
||||
value: parseMaybeJson(value)
|
||||
};
|
||||
}
|
||||
normalized = {};
|
||||
Object.keys(value).forEach(function (key) {
|
||||
normalized[key] = value[key];
|
||||
});
|
||||
if (normalized.value !== undefined) {
|
||||
normalized.value = parseMaybeJson(normalized.value);
|
||||
}
|
||||
if (normalized.font_family !== undefined && normalized.font_family !== null) {
|
||||
normalized.font_family = sanitizeFontFamily(normalized.font_family);
|
||||
}
|
||||
if (normalized.font_size !== undefined && normalized.font_size !== null) {
|
||||
normalized.font_size = sanitizeFontSize(normalized.font_size);
|
||||
}
|
||||
if (normalized.font_color !== undefined && normalized.font_color !== null) {
|
||||
normalized.font_color = sanitizeTextColor(normalized.font_color);
|
||||
}
|
||||
if (!normalized.type) {
|
||||
normalized.type = 'text';
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
// Normalize a slide and its nested region content.
|
||||
function normalizeSlide(slide) {
|
||||
var normalized = {};
|
||||
var content;
|
||||
Object.keys(slide || {}).forEach(function (key) {
|
||||
normalized[key] = slide[key];
|
||||
});
|
||||
normalized.content = {};
|
||||
content = slide && slide.content && typeof slide.content === 'object' ? slide.content : {};
|
||||
Object.keys(content).forEach(function (regionKey) {
|
||||
normalized.content[regionKey] = normalizeContentValue(content[regionKey]);
|
||||
});
|
||||
return normalized;
|
||||
}
|
||||
|
||||
// Parse the stored schedule-day list into numbers.
|
||||
function parseScheduleDays(value) {
|
||||
if (!value) {
|
||||
return [];
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(function (item) { return Number(item); }).filter(function (item) { return !Number.isNaN(item); });
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
return Array.isArray(parsed) ? parsed.map(function (item) { return Number(item); }).filter(function (item) { return !Number.isNaN(item); }) : [];
|
||||
} catch (_error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Convert a HH:MM time string to minutes since midnight.
|
||||
function parseTimeToMinutes(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
const match = raw.match(/^(\d{2}):(\d{2})/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return Number(match[1]) * 60 + Number(match[2]);
|
||||
}
|
||||
|
||||
// Determine whether a slide should be shown at the current time.
|
||||
function isSlideActive(slide, now) {
|
||||
const mode = String(slide.schedule_mode || 'always');
|
||||
if (mode === 'always') {
|
||||
return true;
|
||||
}
|
||||
if (mode === 'dates') {
|
||||
const start = slide.schedule_start_datetime ? new Date(slide.schedule_start_datetime) : null;
|
||||
const end = slide.schedule_end_datetime ? new Date(slide.schedule_end_datetime) : null;
|
||||
if (!start || !end || Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
|
||||
return false;
|
||||
}
|
||||
return now >= start && now <= end;
|
||||
}
|
||||
if (mode === 'times') {
|
||||
const days = parseScheduleDays(slide.schedule_days_json);
|
||||
if (!days.length) {
|
||||
return false;
|
||||
}
|
||||
const day = now.getDay();
|
||||
if (days.indexOf(day) === -1) {
|
||||
return false;
|
||||
}
|
||||
const startMinutes = parseTimeToMinutes(slide.schedule_start_time);
|
||||
const endMinutes = parseTimeToMinutes(slide.schedule_end_time);
|
||||
if (startMinutes === null || endMinutes === null) {
|
||||
return false;
|
||||
}
|
||||
const nowMinutes = now.getHours() * 60 + now.getMinutes();
|
||||
if (startMinutes <= endMinutes) {
|
||||
return nowMinutes >= startMinutes && nowMinutes <= endMinutes;
|
||||
}
|
||||
return nowMinutes >= startMinutes || nowMinutes <= endMinutes;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Build the cache key for a template layout.
|
||||
function getTemplateLayoutCacheKey(template) {
|
||||
var viewportKey = window.innerWidth + 'x' + window.innerHeight;
|
||||
return [currentPlaylistSignature || '', template && template.id ? template.id : '', viewportKey].join('|');
|
||||
}
|
||||
|
||||
// Build or reuse layout metadata for a template.
|
||||
function getTemplateLayout(template) {
|
||||
if (!template || !template.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
syncRenderCacheViewport();
|
||||
|
||||
var cacheKey = getTemplateLayoutCacheKey(template);
|
||||
if (Object.prototype.hasOwnProperty.call(templateLayoutCache, cacheKey)) {
|
||||
return templateLayoutCache[cacheKey];
|
||||
}
|
||||
|
||||
var templateCanvas = getTemplateCanvasSize(template);
|
||||
var canvasSize = fitCanvasSize(templateCanvas.width, templateCanvas.height, window.innerWidth, window.innerHeight);
|
||||
var canvasScale = canvasSize.width / templateCanvas.width;
|
||||
var regions = (template.regions || []).map(function (region) {
|
||||
var left = (Number(region.x) / templateCanvas.width) * 100;
|
||||
var top = (Number(region.y) / templateCanvas.height) * 100;
|
||||
var width = (Number(region.width) / templateCanvas.width) * 100;
|
||||
var height = (Number(region.height) / templateCanvas.height) * 100;
|
||||
var baseStyle = 'left:' + left + '%;top:' + top + '%;width:' + width + '%;height:' + height + '%;z-index:' + Number(region.z_index || 0) + ';';
|
||||
var pixelWidth = Math.max(1, Math.round(Number(region.width || 0) || 1));
|
||||
var pixelHeight = Math.max(1, Math.round(Number(region.height || 0) || 1));
|
||||
|
||||
return {
|
||||
regionKey: region.region_key,
|
||||
regionType: region.region_type,
|
||||
label: region.label,
|
||||
baseStyle: baseStyle,
|
||||
pixelWidth: pixelWidth,
|
||||
pixelHeight: pixelHeight,
|
||||
fontFamily: region.font_family || null,
|
||||
fontSize: region.font_size || null,
|
||||
fontColor: region.font_color || null,
|
||||
canvasScale: canvasScale
|
||||
};
|
||||
});
|
||||
|
||||
var layout = {
|
||||
canvasWidth: canvasSize.width,
|
||||
canvasHeight: canvasSize.height,
|
||||
background: template.background_image_path ? '<img class="template-background" src="' + escapeHtml(template.background_image_path) + '" alt="" />' : '',
|
||||
backgroundColor: template.background_color || '#111111',
|
||||
regions: regions
|
||||
};
|
||||
|
||||
templateLayoutCache[cacheKey] = layout;
|
||||
return layout;
|
||||
}
|
||||
|
||||
// Build the cache key for a template render plan.
|
||||
function getTemplateRenderPlanCacheKey(template) {
|
||||
return getTemplateLayoutCacheKey(template);
|
||||
}
|
||||
|
||||
// Build or reuse the render plan for a template.
|
||||
function getTemplateRenderPlan(template) {
|
||||
if (!template || !template.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
syncRenderCacheViewport();
|
||||
|
||||
var cacheKey = getTemplateRenderPlanCacheKey(template);
|
||||
if (Object.prototype.hasOwnProperty.call(templateRenderPlanCache, cacheKey)) {
|
||||
return templateRenderPlanCache[cacheKey];
|
||||
}
|
||||
|
||||
var layout = getTemplateLayout(template);
|
||||
var plan = {
|
||||
layout: layout,
|
||||
renderRegion: function (region, regionContent) {
|
||||
if (region.regionType === 'image') {
|
||||
return renderImageRegion(region, regionContent);
|
||||
}
|
||||
if (region.regionType === 'webpage') {
|
||||
return renderWebpageRegion(region, regionContent);
|
||||
}
|
||||
if (region.regionType === 'rtmp') {
|
||||
return renderRtmpRegion(region, regionContent);
|
||||
}
|
||||
if (region.regionType === 'rss') {
|
||||
return renderRssRegion(region, regionContent);
|
||||
}
|
||||
if (region.regionType === 'api') {
|
||||
return renderApiRegion(region, regionContent);
|
||||
}
|
||||
if (region.regionType === 'html') {
|
||||
return renderHtmlRegion(region, regionContent);
|
||||
}
|
||||
return renderTextRegion(region, regionContent);
|
||||
}
|
||||
};
|
||||
|
||||
templateRenderPlanCache[cacheKey] = plan;
|
||||
return plan;
|
||||
}
|
||||
|
||||
// Render a template-based slide using the cached layout.
|
||||
function renderTemplateSlideMarkup(slide) {
|
||||
const template = slide.template;
|
||||
const content = slide.content || {};
|
||||
const plan = getTemplateRenderPlan(template);
|
||||
const layout = plan ? plan.layout : null;
|
||||
const regions = layout ? layout.regions.map(function (region) {
|
||||
const regionContent = content[region.regionKey] || {};
|
||||
return plan.renderRegion(region, regionContent);
|
||||
}).join('') : '';
|
||||
const stageStyle = layout ? 'background-color:' + escapeHtml(layout.backgroundColor || '#111111') + ';' : '';
|
||||
return renderSlideShell(slide, '', (layout ? layout.canvasWidth : 0) + 'px', (layout ? layout.canvasHeight : 0) + 'px', '<div class="template-stage" style="' + stageStyle + '">' + (layout ? layout.background : '') + regions + '</div>');
|
||||
}
|
||||
|
||||
// Media rendering helpers.
|
||||
// Build the direct media element for a slide.
|
||||
function renderMediaSlideContent(slide) {
|
||||
if (slide.kind === 'image') {
|
||||
return '<img src="' + escapeHtml(slide.media_url) + '" alt="slide" />';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
// Render a slide that contains direct media content.
|
||||
function renderMediaSlideMarkup(slide) {
|
||||
const canvasSize = fitCanvasSize(16, 9, window.innerWidth, window.innerHeight);
|
||||
const media = renderMediaSlideContent(slide);
|
||||
return renderSlideShell(slide, 'slide-media', canvasSize.width + 'px', canvasSize.height + 'px', media);
|
||||
}
|
||||
|
||||
// Render the shared slide shell around slide-specific inner content.
|
||||
function renderSlideShell(slide, canvasClass, canvasWidth, canvasHeight, innerHtml) {
|
||||
const body = slide.body ? '<div class="body">' + escapeHtml(slide.body) + '</div>' : '';
|
||||
const className = canvasClass ? 'slide-canvas ' + canvasClass : 'slide-canvas';
|
||||
return '<div class="slide"><div class="' + className + '" style="width:' + canvasWidth + ';height:' + canvasHeight + ';">' + innerHtml + body + '</div></div>';
|
||||
}
|
||||
|
||||
// Build the cache key for rendered slide markup.
|
||||
function getSlideMarkupCacheKey(slide) {
|
||||
var viewportKey = window.innerWidth + 'x' + window.innerHeight;
|
||||
return [currentPlaylistSignature || '', slide && slide.id ? slide.id : '', slide && slide.template_id ? slide.template_id : '', viewportKey].join('|');
|
||||
}
|
||||
|
||||
// Look up a previously rendered slide in the cache.
|
||||
function getCachedSlideMarkup(slide) {
|
||||
var cacheKey = getSlideMarkupCacheKey(slide);
|
||||
return Object.prototype.hasOwnProperty.call(slideMarkupCache, cacheKey) ? slideMarkupCache[cacheKey] : null;
|
||||
}
|
||||
|
||||
// Store rendered slide markup in the cache.
|
||||
function setCachedSlideMarkup(slide, markup) {
|
||||
syncRenderCacheViewport();
|
||||
slideMarkupCache[getSlideMarkupCacheKey(slide)] = markup;
|
||||
}
|
||||
|
||||
// Slide rendering and markup cache helpers.
|
||||
// Choose the right slide renderer and cache the result.
|
||||
function buildSlideMarkup(slide) {
|
||||
lastRenderedSlide = slide || null;
|
||||
syncBlackoutState();
|
||||
var cachedMarkup = getCachedSlideMarkup(slide);
|
||||
if (cachedMarkup) {
|
||||
return cachedMarkup;
|
||||
}
|
||||
|
||||
var markup = '';
|
||||
if (slide.template_id && slide.template) {
|
||||
markup = renderTemplateSlideMarkup(slide);
|
||||
setCachedSlideMarkup(slide, markup);
|
||||
return markup;
|
||||
}
|
||||
|
||||
markup = renderMediaSlideMarkup(slide);
|
||||
setCachedSlideMarkup(slide, markup);
|
||||
return markup;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
const CACHE_VERSION = 'v1';
|
||||
const PAGE_CACHE = `pulse-signage-player-pages-${CACHE_VERSION}`;
|
||||
const ASSET_CACHE = `pulse-signage-player-assets-${CACHE_VERSION}`;
|
||||
const MEDIA_CACHE = `pulse-signage-player-media-${CACHE_VERSION}`;
|
||||
const PLAYLIST_CACHE = `pulse-signage-player-playlists-${CACHE_VERSION}`;
|
||||
|
||||
function normalizeRequest(request) {
|
||||
const url = new URL(request.url);
|
||||
return new Request(`${url.origin}${url.pathname}`, {
|
||||
method: 'GET',
|
||||
headers: request.headers,
|
||||
mode: 'same-origin',
|
||||
credentials: 'same-origin'
|
||||
});
|
||||
}
|
||||
|
||||
async function cacheResponse(cacheName, request, response, cacheKeyRequest) {
|
||||
if (!response || !response.ok) {
|
||||
return;
|
||||
}
|
||||
const cache = await caches.open(cacheName);
|
||||
await cache.put(cacheKeyRequest || request, response.clone());
|
||||
}
|
||||
|
||||
async function networkFirst(request, cacheName, cacheKeyRequest) {
|
||||
try {
|
||||
const response = await fetch(request);
|
||||
if (response && response.ok) {
|
||||
await cacheResponse(cacheName, request, response, cacheKeyRequest);
|
||||
return response;
|
||||
}
|
||||
if (response && response.status === 304) {
|
||||
const cached = await caches.match(cacheKeyRequest || request);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
const cached = await caches.match(cacheKeyRequest || request);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
return response;
|
||||
} catch (_error) {
|
||||
const cached = await caches.match(cacheKeyRequest || request);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
throw _error;
|
||||
}
|
||||
}
|
||||
|
||||
async function cacheFirst(request, cacheName) {
|
||||
const cached = await caches.match(request);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const response = await fetch(request);
|
||||
if (response && response.ok) {
|
||||
await cacheResponse(cacheName, request, response);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
async function staleWhileRevalidate(request, cacheName) {
|
||||
const cached = await caches.match(request);
|
||||
const networkPromise = fetch(request).then(async function (response) {
|
||||
if (response && response.ok) {
|
||||
await cacheResponse(cacheName, request, response);
|
||||
}
|
||||
return response;
|
||||
}).catch(function () {
|
||||
return null;
|
||||
});
|
||||
|
||||
if (cached) {
|
||||
networkPromise.catch(function () {
|
||||
return null;
|
||||
});
|
||||
return cached;
|
||||
}
|
||||
|
||||
const networkResponse = await networkPromise;
|
||||
if (networkResponse) {
|
||||
return networkResponse;
|
||||
}
|
||||
|
||||
return new Response('', { status: 504, statusText: 'Offline' });
|
||||
}
|
||||
|
||||
self.addEventListener('install', function (event) {
|
||||
self.skipWaiting();
|
||||
event.waitUntil(Promise.resolve());
|
||||
});
|
||||
|
||||
self.addEventListener('activate', function (event) {
|
||||
event.waitUntil((async function () {
|
||||
const expected = [PAGE_CACHE, ASSET_CACHE, MEDIA_CACHE, PLAYLIST_CACHE];
|
||||
const keys = await caches.keys();
|
||||
await Promise.all(keys.filter(function (key) {
|
||||
return expected.indexOf(key) === -1;
|
||||
}).map(function (key) {
|
||||
return caches.delete(key);
|
||||
}));
|
||||
await self.clients.claim();
|
||||
})());
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', function (event) {
|
||||
const request = event.request;
|
||||
if (request.method !== 'GET') {
|
||||
return;
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
if (url.origin !== self.location.origin) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === '/sw.js') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith('/assets/')) {
|
||||
event.respondWith(cacheFirst(request, ASSET_CACHE));
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith('/media/')) {
|
||||
event.respondWith(staleWhileRevalidate(request, MEDIA_CACHE));
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.mode === 'navigate' || url.pathname === '/' || url.pathname === '/onboard' || /^\/screen\/[^/]+$/.test(url.pathname)) {
|
||||
event.respondWith(networkFirst(request, PAGE_CACHE, normalizeRequest(request)));
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith('/api/screens/') && url.pathname.endsWith('/playlist')) {
|
||||
event.respondWith(networkFirst(request, PLAYLIST_CACHE, normalizeRequest(request)));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
function getApiSourceById(sourceId) {
|
||||
var sources = Array.isArray(initialData && initialData.apiSources) ? initialData.apiSources : [];
|
||||
var normalizedId = Number(sourceId || 0);
|
||||
return sources.find(function (source) {
|
||||
return Number(source.id) === normalizedId;
|
||||
}) || null;
|
||||
}
|
||||
|
||||
function getApiSourceItems(sourceId) {
|
||||
var source = getApiSourceById(sourceId);
|
||||
var responseJson = source && source.responseJson && typeof source.responseJson === 'object' ? source.responseJson : null;
|
||||
if (Array.isArray(responseJson)) {
|
||||
return responseJson;
|
||||
}
|
||||
if (responseJson && Array.isArray(responseJson.items)) {
|
||||
return responseJson.items;
|
||||
}
|
||||
if (responseJson && Array.isArray(responseJson.results)) {
|
||||
return responseJson.results;
|
||||
}
|
||||
if (responseJson && Array.isArray(responseJson.data)) {
|
||||
return responseJson.data;
|
||||
}
|
||||
return responseJson ? [responseJson] : [];
|
||||
}
|
||||
|
||||
function getApiItem(sourceId, itemNumber) {
|
||||
var items = getApiSourceItems(sourceId);
|
||||
var parsedItemNumber = Math.max(1, Number(itemNumber || 1));
|
||||
var index = Number.isFinite(parsedItemNumber) && parsedItemNumber > 0 ? parsedItemNumber - 1 : 0;
|
||||
return items[index] || null;
|
||||
}
|
||||
|
||||
function resolveApiPath(value, path) {
|
||||
var current = value;
|
||||
if (!path) {
|
||||
return current;
|
||||
}
|
||||
|
||||
String(path).split('.').forEach(function (segment) {
|
||||
if (current === undefined || current === null) {
|
||||
current = '';
|
||||
return;
|
||||
}
|
||||
current = current[segment];
|
||||
});
|
||||
|
||||
return current === undefined || current === null ? '' : current;
|
||||
}
|
||||
|
||||
function substituteApiVariables(html, item) {
|
||||
var source = String(html || '');
|
||||
return source.replace(/\{\{\s*([a-zA-Z0-9_]+)(?:\.([a-zA-Z0-9_.]+))?\s*\}\}/g, function (_match, tokenName, tokenPath) {
|
||||
if (!item || typeof item !== 'object') {
|
||||
return '';
|
||||
}
|
||||
var key = tokenName === 'item' && tokenPath ? tokenPath : tokenName;
|
||||
return escapeHtml(resolveApiPath(item, key || ''));
|
||||
});
|
||||
}
|
||||
|
||||
function getApiPreviewFallback(item) {
|
||||
if (!item || typeof item !== 'object') {
|
||||
return '<div class="template-region-placeholder">API item</div>';
|
||||
}
|
||||
|
||||
var title = String(item.title || item.name || '').trim();
|
||||
var description = String(item.description || item.summary || item.text || '').trim();
|
||||
var summary = [];
|
||||
if (title) {
|
||||
summary.push('<h3>' + escapeHtml(title) + '</h3>');
|
||||
}
|
||||
if (description) {
|
||||
summary.push('<div>' + sanitizeRichText(description) + '</div>');
|
||||
}
|
||||
if (!summary.length) {
|
||||
return '<div class="template-region-placeholder">API item</div>';
|
||||
}
|
||||
return summary.join('');
|
||||
}
|
||||
|
||||
function renderApiRegion(region, regionContent) {
|
||||
var content = regionContent && regionContent.value !== undefined ? regionContent.value : '';
|
||||
var sourceId = regionContent && regionContent.source_id !== undefined ? regionContent.source_id : null;
|
||||
var itemNumber = regionContent && regionContent.item_number !== undefined ? regionContent.item_number : 1;
|
||||
var fontFamily = sanitizeFontFamily(regionContent.font_family || region.fontFamily);
|
||||
var fontSize = sanitizeFontSize(regionContent.font_size || region.fontSize);
|
||||
var fontColor = sanitizeTextColor(regionContent.font_color || region.fontColor);
|
||||
var item = getApiItem(sourceId, itemNumber);
|
||||
var body = item ? substituteApiVariables(content, item) : '';
|
||||
if (!body && item) {
|
||||
body = getApiPreviewFallback(item);
|
||||
}
|
||||
var contentStyle = 'width:' + region.pixelWidth + 'px;height:' + region.pixelHeight + 'px;transform:scale(' + region.canvasScale + ');transform-origin:top left;' + (fontFamily ? 'font-family:' + escapeHtml(fontFamily) + ';' : '') + 'font-size:' + fontSize + 'px;color:' + escapeHtml(fontColor) + ';';
|
||||
var renderedBody = body ? renderEditorJsContent(body) : '<div class="template-region-placeholder">API item</div>';
|
||||
return '<div class="template-region api" style="' + region.baseStyle + '"><div class="template-region-text-scale" style="' + contentStyle + '">' + renderedBody + '</div></div>';
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
function renderHtmlRegionContent(value) {
|
||||
var html = String(value || '').trim();
|
||||
if (!html) {
|
||||
return '<div class="template-region-placeholder">HTML</div>';
|
||||
}
|
||||
return '<iframe class="template-region-html-frame" sandbox="" scrolling="no" srcdoc="<!doctype html><html><head><style>html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent;}</style></head><body>' + escapeHtml(html) + '</body></html>" title="HTML region" loading="eager"></iframe>';
|
||||
}
|
||||
|
||||
function renderHtmlRegion(region, regionContent) {
|
||||
return '<div class="template-region html" style="' + region.baseStyle + '">' + renderHtmlRegionContent(regionContent.value || '') + '</div>';
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
function renderImageRegion(region, regionContent) {
|
||||
var src = regionContent.value || '';
|
||||
return '<div class="template-region image" style="' + region.baseStyle + '"><img src="' + escapeHtml(src) + '" alt="' + escapeHtml(region.label) + '" /></div>';
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
function getRssFeedById(feedId) {
|
||||
var feeds = Array.isArray(initialData && initialData.rssFeeds) ? initialData.rssFeeds : [];
|
||||
var normalizedId = Number(feedId || 0);
|
||||
return feeds.find(function (feed) {
|
||||
return Number(feed.id) === normalizedId;
|
||||
}) || null;
|
||||
}
|
||||
|
||||
function getRssFeedItem(feedId, itemNumber) {
|
||||
var feed = getRssFeedById(feedId);
|
||||
var items = feed && Array.isArray(feed.items) ? feed.items : [];
|
||||
var parsedItemNumber = Math.max(1, Number(itemNumber || 1));
|
||||
var index = Number.isFinite(parsedItemNumber) && parsedItemNumber > 0 ? parsedItemNumber - 1 : 0;
|
||||
return items[index] || null;
|
||||
}
|
||||
|
||||
function resolveRssPath(value, path) {
|
||||
var current = value;
|
||||
if (!path) {
|
||||
return current;
|
||||
}
|
||||
|
||||
String(path).split('.').forEach(function (segment) {
|
||||
if (current === undefined || current === null) {
|
||||
current = '';
|
||||
return;
|
||||
}
|
||||
current = current[segment];
|
||||
});
|
||||
|
||||
return current === undefined || current === null ? '' : current;
|
||||
}
|
||||
|
||||
function substituteRssVariables(html, item) {
|
||||
var source = String(html || '');
|
||||
return source.replace(/\{\{\s*([a-zA-Z0-9_]+)(?:\.([a-zA-Z0-9_.]+))?\s*\}\}/g, function (_match, tokenName, tokenPath) {
|
||||
if (!item || typeof item !== 'object') {
|
||||
return '';
|
||||
}
|
||||
var key = tokenName === 'item' && tokenPath ? tokenPath : tokenName;
|
||||
return escapeHtml(resolveRssPath(item, key || ''));
|
||||
});
|
||||
}
|
||||
|
||||
function renderRssRegion(region, regionContent) {
|
||||
var content = regionContent && regionContent.value !== undefined ? regionContent.value : '';
|
||||
var feedId = regionContent && regionContent.feed_id !== undefined ? regionContent.feed_id : null;
|
||||
var itemNumber = regionContent && regionContent.item_number !== undefined ? regionContent.item_number : 1;
|
||||
var fontFamily = sanitizeFontFamily(regionContent.font_family || region.fontFamily);
|
||||
var fontSize = sanitizeFontSize(regionContent.font_size || region.fontSize);
|
||||
var fontColor = sanitizeTextColor(regionContent.font_color || region.fontColor);
|
||||
var item = getRssFeedItem(feedId, itemNumber);
|
||||
var body = item ? substituteRssVariables(content, item) : '';
|
||||
if (!body && item) {
|
||||
var summaryParts = [];
|
||||
if (item.title) {
|
||||
summaryParts.push('<h3>' + escapeHtml(item.title) + '</h3>');
|
||||
}
|
||||
if (item.description) {
|
||||
summaryParts.push('<div>' + sanitizeRichText(item.description) + '</div>');
|
||||
}
|
||||
body = summaryParts.join('');
|
||||
}
|
||||
var contentStyle = 'width:' + region.pixelWidth + 'px;height:' + region.pixelHeight + 'px;transform:scale(' + region.canvasScale + ');transform-origin:top left;' + (fontFamily ? 'font-family:' + escapeHtml(fontFamily) + ';' : '') + 'font-size:' + fontSize + 'px;color:' + escapeHtml(fontColor) + ';';
|
||||
var renderedBody = body ? renderEditorJsContent(body) : '<div class="template-region-placeholder">RSS item</div>';
|
||||
return '<div class="template-region rss" style="' + region.baseStyle + '"><div class="template-region-text-scale" style="' + contentStyle + '">' + renderedBody + '</div></div>';
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
function renderRtmpRegion(region, regionContent) {
|
||||
var url = String(regionContent.value || '').trim();
|
||||
var disableAudio = regionContent.disable_audio === undefined ? true : Boolean(regionContent.disable_audio);
|
||||
if (!url) {
|
||||
return '<div class="template-region rtmp" style="' + region.baseStyle + '"><div class="template-region-placeholder">RTMP stream</div></div>';
|
||||
}
|
||||
|
||||
return '<div class="template-region rtmp" style="' + region.baseStyle + '"><video class="template-region-rtmp-video" data-rtmp-source="' + escapeHtml(url) + '" data-rtmp-disable-audio="' + (disableAudio ? '1' : '0') + '" autoplay playsinline preload="auto" tabindex="-1" disablepictureinpicture></video><div class="template-region-placeholder template-region-rtmp-placeholder">Loading RTMP stream...</div></div>';
|
||||
}
|
||||
|
||||
function getRtmpSessionUrl(sourceUrl, disableAudio) {
|
||||
return '/api/rtmp/session?source=' + encodeURIComponent(sourceUrl) + '&disableAudio=' + (disableAudio ? '1' : '0');
|
||||
}
|
||||
|
||||
var rtmpPreloadSignature = '';
|
||||
|
||||
function getRtmpPreloadSlides(sourceSlides, targetIndex) {
|
||||
var availableSlides = Array.isArray(sourceSlides) ? sourceSlides : [];
|
||||
if (!availableSlides.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
var normalizedIndex = Number(targetIndex || 0);
|
||||
if (!Number.isFinite(normalizedIndex) || normalizedIndex < 0 || normalizedIndex >= availableSlides.length) {
|
||||
normalizedIndex = 0;
|
||||
}
|
||||
|
||||
var preloadSlides = [];
|
||||
var currentSlide = availableSlides[normalizedIndex];
|
||||
var nextSlide = availableSlides[normalizedIndex + 1];
|
||||
|
||||
if (currentSlide) {
|
||||
preloadSlides.push(currentSlide);
|
||||
}
|
||||
if (nextSlide && nextSlide !== currentSlide) {
|
||||
preloadSlides.push(nextSlide);
|
||||
}
|
||||
|
||||
return preloadSlides;
|
||||
}
|
||||
|
||||
function getRtmpPreloadEntries(sourceSlides) {
|
||||
var entries = [];
|
||||
var seen = Object.create(null);
|
||||
|
||||
(Array.isArray(sourceSlides) ? sourceSlides : []).forEach(function (slide) {
|
||||
var content = slide && slide.content ? slide.content : {};
|
||||
var regions = slide && slide.template && Array.isArray(slide.template.regions) ? slide.template.regions : [];
|
||||
regions.forEach(function (region) {
|
||||
if (region.region_type !== 'rtmp') {
|
||||
return;
|
||||
}
|
||||
var regionContent = content[region.region_key] || {};
|
||||
var url = String(regionContent.value || '').trim();
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
var disableAudio = regionContent.disable_audio === undefined ? true : Boolean(regionContent.disable_audio);
|
||||
var key = url + '\n' + (disableAudio ? '1' : '0');
|
||||
if (seen[key]) {
|
||||
return;
|
||||
}
|
||||
seen[key] = true;
|
||||
entries.push({
|
||||
url: url,
|
||||
disableAudio: disableAudio
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function syncRtmpPreloads(sourceSlides, targetIndex) {
|
||||
var entries = getRtmpPreloadEntries(getRtmpPreloadSlides(sourceSlides, targetIndex));
|
||||
var signature = entries.map(function (entry) {
|
||||
return entry.url + '\n' + (entry.disableAudio ? '1' : '0');
|
||||
}).join('\n');
|
||||
|
||||
if (signature === rtmpPreloadSignature) {
|
||||
return;
|
||||
}
|
||||
|
||||
rtmpPreloadSignature = signature;
|
||||
if (!entries.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
entries.forEach(function (entry) {
|
||||
fetch(getRtmpSessionUrl(entry.url, entry.disableAudio), {
|
||||
credentials: 'same-origin'
|
||||
}).catch(function () {
|
||||
return null;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function syncRtmpRegions(root) {
|
||||
if (!root) {
|
||||
return;
|
||||
}
|
||||
|
||||
var videos = root.querySelectorAll('video[data-rtmp-source]');
|
||||
Array.prototype.forEach.call(videos, function (video) {
|
||||
if (!video || video.dataset.rtmpInitialized === '1') {
|
||||
return;
|
||||
}
|
||||
|
||||
var sourceUrl = String(video.dataset.rtmpSource || '').trim();
|
||||
var disableAudio = String(video.dataset.rtmpDisableAudio || '1') !== '0';
|
||||
var region = video.parentNode;
|
||||
var placeholder = region ? region.querySelector('.template-region-rtmp-placeholder') : null;
|
||||
|
||||
if (!sourceUrl) {
|
||||
if (placeholder) {
|
||||
placeholder.textContent = 'RTMP stream';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
video.dataset.rtmpInitialized = '1';
|
||||
video.muted = disableAudio;
|
||||
video.controls = false;
|
||||
video.playsInline = true;
|
||||
video.autoplay = true;
|
||||
|
||||
var markReady = function () {
|
||||
if (placeholder) {
|
||||
placeholder.style.display = 'none';
|
||||
}
|
||||
};
|
||||
|
||||
var tryPlay = function () {
|
||||
if (video && typeof video.play === 'function') {
|
||||
video.play().catch(function () {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
video.addEventListener('canplay', markReady, { once: true });
|
||||
video.addEventListener('playing', markReady, { once: true });
|
||||
|
||||
fetch(getRtmpSessionUrl(sourceUrl, disableAudio), {
|
||||
credentials: 'same-origin'
|
||||
}).then(function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error('Unable to initialize RTMP stream.');
|
||||
}
|
||||
return response.json();
|
||||
}).then(function (payload) {
|
||||
var playlistUrl = payload && payload.playlistUrl ? String(payload.playlistUrl).trim() : '';
|
||||
if (!playlistUrl) {
|
||||
throw new Error('RTMP playlist URL was not returned.');
|
||||
}
|
||||
|
||||
if (window.Hls && window.Hls.isSupported && window.Hls.isSupported()) {
|
||||
var hls = new window.Hls({
|
||||
enableWorker: true,
|
||||
lowLatencyMode: true,
|
||||
liveSyncDurationCount: 4,
|
||||
liveMaxLatencyDurationCount: 8,
|
||||
maxBufferLength: 20,
|
||||
maxLiveSyncPlaybackRate: 1,
|
||||
backBufferLength: 30
|
||||
});
|
||||
video.__rtmpHls = hls;
|
||||
hls.attachMedia(video);
|
||||
hls.on(window.Hls.Events.MEDIA_ATTACHED, function () {
|
||||
hls.loadSource(playlistUrl);
|
||||
});
|
||||
hls.on(window.Hls.Events.MANIFEST_PARSED, function () {
|
||||
tryPlay();
|
||||
});
|
||||
hls.on(window.Hls.Events.ERROR, function (_event, data) {
|
||||
if (data && data.fatal) {
|
||||
try {
|
||||
hls.destroy();
|
||||
} catch (_error) {
|
||||
// ignore cleanup errors
|
||||
}
|
||||
video.__rtmpHls = null;
|
||||
if (placeholder) {
|
||||
placeholder.style.display = 'flex';
|
||||
placeholder.textContent = 'RTMP playback failed.';
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (video.canPlayType && video.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
video.src = playlistUrl;
|
||||
tryPlay();
|
||||
return;
|
||||
}
|
||||
|
||||
if (placeholder) {
|
||||
placeholder.style.display = 'flex';
|
||||
placeholder.textContent = 'RTMP playback is not supported in this browser.';
|
||||
}
|
||||
}).catch(function (_error) {
|
||||
if (placeholder) {
|
||||
placeholder.style.display = 'flex';
|
||||
placeholder.textContent = 'Unable to load RTMP stream.';
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function destroyRtmpRegions(root) {
|
||||
if (!root) {
|
||||
return;
|
||||
}
|
||||
|
||||
var videos = root.querySelectorAll('video[data-rtmp-source]');
|
||||
Array.prototype.forEach.call(videos, function (video) {
|
||||
if (video.__rtmpHls) {
|
||||
try {
|
||||
video.__rtmpHls.destroy();
|
||||
} catch (_error) {
|
||||
// ignore cleanup errors
|
||||
}
|
||||
video.__rtmpHls = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
function renderTextRegion(region, regionContent) {
|
||||
var fontFamily = sanitizeFontFamily(regionContent.font_family || region.fontFamily);
|
||||
var fontSize = sanitizeFontSize(regionContent.font_size || region.fontSize);
|
||||
var fontColor = sanitizeTextColor(regionContent.font_color || region.fontColor);
|
||||
var contentStyle = 'width:' + region.pixelWidth + 'px;height:' + region.pixelHeight + 'px;transform:scale(' + region.canvasScale + ');transform-origin:top left;' + (fontFamily ? 'font-family:' + escapeHtml(fontFamily) + ';' : '') + 'font-size:' + fontSize + 'px;color:' + escapeHtml(fontColor) + ';';
|
||||
return '<div class="template-region text" style="' + region.baseStyle + '"><div class="template-region-text-scale" style="' + contentStyle + '">' + renderEditorJsContent(regionContent.value || '') + '</div></div>';
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
function renderWebpageRegion(region, regionContent) {
|
||||
var url = String(regionContent.value || '').trim();
|
||||
var iframe = url ? '<iframe src="' + escapeHtml(url) + '" title="' + escapeHtml(region.label) + '" loading="eager" referrerpolicy="no-referrer" scrolling="no"></iframe>' : '<div class="template-region-placeholder">Webpage</div>';
|
||||
return '<div class="template-region webpage" style="' + region.baseStyle + '">' + iframe + '</div>';
|
||||
}
|
||||
@@ -278,12 +278,32 @@ function fitCanvasSize(canvasWidth, canvasHeight, maxWidth, maxHeight) {
|
||||
|
||||
const playerPageTemplatePath = path.join(__dirname, 'player-page.template.html');
|
||||
const playerClientNameScriptPath = path.join(__dirname, 'player-client-name.script.html');
|
||||
const playerPageOfflineScriptPath = path.join(__dirname, 'public', 'js', 'player-page-offline.js');
|
||||
const playerPagePlaylistScriptPath = path.join(__dirname, 'public', 'js', 'player-page-playlist.js');
|
||||
const playerPageCommandsScriptPath = path.join(__dirname, 'public', 'js', 'player-page-commands.js');
|
||||
const playerPageRenderingScriptPath = path.join(__dirname, 'public', 'js', 'player-page-rendering.js');
|
||||
const playerPagePlaybackScriptPath = path.join(__dirname, 'public', 'js', 'player-page-playback.js');
|
||||
const playerPageScriptPath = path.join(__dirname, 'player-page.script.html');
|
||||
const playerOnboardingLandingScriptPath = path.join(__dirname, 'player-onboarding-landing.script.html');
|
||||
const playerOnboardingFormScriptPath = path.join(__dirname, 'player-onboarding-form.script.html');
|
||||
const playerRegionScriptPaths = [
|
||||
path.join(__dirname, 'regions', 'image.js'),
|
||||
path.join(__dirname, 'regions', 'webpage.js'),
|
||||
path.join(__dirname, 'regions', 'html.js'),
|
||||
path.join(__dirname, 'regions', 'rtmp.js'),
|
||||
path.join(__dirname, 'regions', 'rss.js'),
|
||||
path.join(__dirname, 'regions', 'api.js'),
|
||||
path.join(__dirname, 'regions', 'text.js')
|
||||
];
|
||||
const playerOnboardingLandingScriptPath = path.join(__dirname, 'onboarding', 'player-onboarding-landing.script.html');
|
||||
const playerOnboardingFormScriptPath = path.join(__dirname, 'onboarding', 'player-onboarding-form.script.html');
|
||||
let playerPageTemplateCache = null;
|
||||
let playerClientNameScriptCache = null;
|
||||
let playerPageOfflineScriptCache = null;
|
||||
let playerPagePlaylistScriptCache = null;
|
||||
let playerPageCommandsScriptCache = null;
|
||||
let playerPageRenderingScriptCache = null;
|
||||
let playerPagePlaybackScriptCache = null;
|
||||
let playerPageScriptCache = null;
|
||||
let playerRegionScriptsCache = null;
|
||||
let playerOnboardingLandingScriptCache = null;
|
||||
let playerOnboardingFormScriptCache = null;
|
||||
|
||||
@@ -306,10 +326,48 @@ function getPlayerClientNameScript() {
|
||||
return loadTemplate(playerClientNameScriptPath, playerClientNameScriptCache || (playerClientNameScriptCache = {}));
|
||||
}
|
||||
|
||||
function getPlayerPageOfflineScript() {
|
||||
return loadTemplate(playerPageOfflineScriptPath, playerPageOfflineScriptCache || (playerPageOfflineScriptCache = {}));
|
||||
}
|
||||
|
||||
function getPlayerPagePlaylistScript() {
|
||||
return loadTemplate(playerPagePlaylistScriptPath, playerPagePlaylistScriptCache || (playerPagePlaylistScriptCache = {}));
|
||||
}
|
||||
|
||||
function getPlayerPageCommandsScript() {
|
||||
return loadTemplate(playerPageCommandsScriptPath, playerPageCommandsScriptCache || (playerPageCommandsScriptCache = {}));
|
||||
}
|
||||
|
||||
function getPlayerPageRenderingScript() {
|
||||
return loadTemplate(playerPageRenderingScriptPath, playerPageRenderingScriptCache || (playerPageRenderingScriptCache = {}));
|
||||
}
|
||||
|
||||
function getPlayerPagePlaybackScript() {
|
||||
return loadTemplate(playerPagePlaybackScriptPath, playerPagePlaybackScriptCache || (playerPagePlaybackScriptCache = {}));
|
||||
}
|
||||
|
||||
function getPlayerPageScript() {
|
||||
return loadTemplate(playerPageScriptPath, playerPageScriptCache || (playerPageScriptCache = {}));
|
||||
}
|
||||
|
||||
function getPlayerRegionScripts() {
|
||||
const statSignature = playerRegionScriptPaths.map(function (filePath) {
|
||||
return fs.statSync(filePath).mtimeMs;
|
||||
}).join('|');
|
||||
if (playerRegionScriptsCache && playerRegionScriptsCache.signature === statSignature) {
|
||||
return playerRegionScriptsCache.value;
|
||||
}
|
||||
|
||||
const value = playerRegionScriptPaths.map(function (filePath) {
|
||||
return fs.readFileSync(filePath, 'utf8').trim();
|
||||
}).join('\n\n');
|
||||
playerRegionScriptsCache = {
|
||||
signature: statSignature,
|
||||
value: value
|
||||
};
|
||||
return value;
|
||||
}
|
||||
|
||||
function getPlayerOnboardingLandingScript() {
|
||||
return loadTemplate(playerOnboardingLandingScriptPath, playerOnboardingLandingScriptCache || (playerOnboardingLandingScriptCache = {}));
|
||||
}
|
||||
@@ -339,7 +397,13 @@ module.exports = {
|
||||
loadTemplate: loadTemplate,
|
||||
getPlayerPageTemplate: getPlayerPageTemplate,
|
||||
getPlayerClientNameScript: getPlayerClientNameScript,
|
||||
getPlayerPageOfflineScript: getPlayerPageOfflineScript,
|
||||
getPlayerPagePlaylistScript: getPlayerPagePlaylistScript,
|
||||
getPlayerPageCommandsScript: getPlayerPageCommandsScript,
|
||||
getPlayerPageRenderingScript: getPlayerPageRenderingScript,
|
||||
getPlayerPagePlaybackScript: getPlayerPagePlaybackScript,
|
||||
getPlayerPageScript: getPlayerPageScript,
|
||||
getPlayerRegionScripts: getPlayerRegionScripts,
|
||||
getPlayerOnboardingLandingScript: getPlayerOnboardingLandingScript,
|
||||
getPlayerOnboardingFormScript: getPlayerOnboardingFormScript
|
||||
};
|
||||
+31
-5
@@ -1,5 +1,6 @@
|
||||
const Handlebars = require('handlebars');
|
||||
const { mediaKind, safeJsonForScript, getPlayerPageTemplate, getPlayerClientNameScript, getPlayerPageScript, getPlayerOnboardingLandingScript, getPlayerOnboardingFormScript } = require('./render-helpers');
|
||||
const { mediaKind, safeJsonForScript, getPlayerPageTemplate, getPlayerClientNameScript, getPlayerPageOfflineScript, getPlayerPagePlaylistScript, getPlayerPageCommandsScript, getPlayerPageRenderingScript, getPlayerPagePlaybackScript, getPlayerPageScript, getPlayerRegionScripts, getPlayerOnboardingLandingScript, getPlayerOnboardingFormScript } = require('./render-helpers');
|
||||
const { createPageAuthBundle, createPageFetchAuthScript } = require('../request-auth');
|
||||
|
||||
function renderPage(template, options) {
|
||||
return template({
|
||||
@@ -10,6 +11,20 @@ function renderPage(template, options) {
|
||||
});
|
||||
}
|
||||
|
||||
function getPlayerServiceWorkerRegistrationScript() {
|
||||
return [
|
||||
'<script>',
|
||||
' if ("serviceWorker" in navigator) {',
|
||||
' window.addEventListener("load", function () {',
|
||||
' navigator.serviceWorker.register("/sw.js").catch(function () {',
|
||||
' return null;',
|
||||
' });',
|
||||
' });',
|
||||
' }',
|
||||
'</script>'
|
||||
].join('');
|
||||
}
|
||||
|
||||
function renderOnboardingLandingBody() {
|
||||
return [
|
||||
'<main class="onboarding-shell">',
|
||||
@@ -84,34 +99,45 @@ function renderOnboardingFormScript(deviceId) {
|
||||
|
||||
function renderPlayerPage(slug, initialData) {
|
||||
const onboardingScript = getPlayerClientNameScript()();
|
||||
const offlineScript = getPlayerPageOfflineScript()();
|
||||
const playlistScript = getPlayerPagePlaylistScript()();
|
||||
const commandScript = getPlayerPageCommandsScript()();
|
||||
const renderingScript = getPlayerPageRenderingScript()();
|
||||
const playbackScript = getPlayerPagePlaybackScript()();
|
||||
const serviceWorkerScript = getPlayerServiceWorkerRegistrationScript();
|
||||
const template = getPlayerPageTemplate();
|
||||
const hlsScriptTag = '<script src="/assets/vendor/hls.min.js"></script>';
|
||||
const pageAuthToken = createPageAuthBundle({ scope: 'player', slug: String(slug || '').trim() });
|
||||
const script = getPlayerPageScript()({
|
||||
SLUG_JSON: new Handlebars.SafeString(JSON.stringify(slug)),
|
||||
INITIAL_DATA_JSON: new Handlebars.SafeString(safeJsonForScript(initialData || null))
|
||||
INITIAL_DATA_JSON: new Handlebars.SafeString(safeJsonForScript(initialData || null)),
|
||||
REGION_SCRIPTS: new Handlebars.SafeString(getPlayerRegionScripts())
|
||||
});
|
||||
|
||||
return renderPage(template, {
|
||||
title: 'Screen ' + slug,
|
||||
body: '<div id="app"><div class="empty">Loading screen...</div></div>',
|
||||
script: onboardingScript + script
|
||||
script: createPageFetchAuthScript(pageAuthToken) + hlsScriptTag + serviceWorkerScript + '<script>' + offlineScript + '</script>' + '<script>' + playlistScript + '</script>' + '<script>' + commandScript + '</script>' + '<script>' + renderingScript + '</script>' + '<script>' + playbackScript + '</script>' + onboardingScript + script
|
||||
});
|
||||
}
|
||||
|
||||
function renderPlayerOnboardingLandingPage() {
|
||||
const pageAuthToken = createPageAuthBundle({ scope: 'onboarding' });
|
||||
return renderPage(getPlayerPageTemplate(), {
|
||||
title: 'Onboard player',
|
||||
bodyClass: 'onboarding-page',
|
||||
body: renderOnboardingLandingBody(),
|
||||
script: renderOnboardingLandingScript()
|
||||
script: createPageFetchAuthScript(pageAuthToken) + getPlayerServiceWorkerRegistrationScript() + renderOnboardingLandingScript()
|
||||
});
|
||||
}
|
||||
|
||||
function renderPlayerOnboardingFormPage(deviceId) {
|
||||
const pageAuthToken = createPageAuthBundle({ scope: 'onboarding', deviceId: String(deviceId || '').trim() });
|
||||
return renderPage(getPlayerPageTemplate(), {
|
||||
title: 'Onboard screen',
|
||||
bodyClass: 'onboarding-page',
|
||||
body: renderOnboardingFormBody(deviceId),
|
||||
script: renderOnboardingFormScript(deviceId)
|
||||
script: createPageFetchAuthScript(pageAuthToken) + getPlayerServiceWorkerRegistrationScript() + renderOnboardingFormScript(deviceId)
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+181
-27
@@ -1,36 +1,111 @@
|
||||
const fs = require('fs');
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const { getSharedSecret, createPageAuthBundle, verifyPageAuthToken, verifyRequestAuth } = require('../request-auth');
|
||||
|
||||
const TRANSIENT_DB_ERROR_CODES = ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'ENOTFOUND', 'PROTOCOL_CONNECTION_LOST', 'POOL_CLOSED', 'ERR_POOL_CLOSED'];
|
||||
|
||||
function isTransientDbError(error) {
|
||||
return Boolean(error && TRANSIENT_DB_ERROR_CODES.indexOf(String(error.code || '').trim()) !== -1);
|
||||
}
|
||||
|
||||
function registerPlayerRoutes(app, options) {
|
||||
const pool = options && options.pool ? options.pool : null;
|
||||
const common = options && options.common ? options.common : null;
|
||||
const uploadDir = options && options.uploadDir ? options.uploadDir : null;
|
||||
const mediaDir = options && options.mediaDir ? options.mediaDir : null;
|
||||
const assetDir = options && options.assetDir ? options.assetDir : null;
|
||||
const playerRuntime = options && options.playerRuntime ? options.playerRuntime : null;
|
||||
const playerPlaylistService = options && options.playerPlaylistService ? options.playerPlaylistService : null;
|
||||
const rtmpStreamService = options && options.rtmpStreamService ? options.rtmpStreamService : null;
|
||||
|
||||
if (!app || !pool || !common || !uploadDir || !assetDir || !playerRuntime || !playerPlaylistService) {
|
||||
throw new Error('registerPlayerRoutes requires app, pool, common, uploadDir, assetDir, playerRuntime, and playerPlaylistService.');
|
||||
if (!app || !pool || !common || !mediaDir || !assetDir || !playerRuntime || !playerPlaylistService || !rtmpStreamService) {
|
||||
throw new Error('registerPlayerRoutes requires app, pool, common, mediaDir, assetDir, playerRuntime, playerPlaylistService, and rtmpStreamService.');
|
||||
}
|
||||
|
||||
const sharedSecret = getSharedSecret();
|
||||
|
||||
function requirePageAuth(allowedScopes) {
|
||||
return function (req, res, next) {
|
||||
if (!sharedSecret) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const token = String(req.headers['x-pulse-page-auth'] || '').trim();
|
||||
const payload = verifyPageAuthToken(token);
|
||||
if (!payload) {
|
||||
return res.status(401).json({ error: 'Page authentication required.' });
|
||||
}
|
||||
|
||||
const scopes = Array.isArray(allowedScopes) ? allowedScopes : [];
|
||||
if (scopes.length && scopes.indexOf(String(payload.scope || '').trim()) === -1) {
|
||||
return res.status(403).json({ error: 'Page authentication scope is not allowed for this route.' });
|
||||
}
|
||||
|
||||
req.playerPageAuth = payload;
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
function requireRequestAuth(req, res, next) {
|
||||
if (!sharedSecret) {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (!verifyRequestAuth(req)) {
|
||||
return res.status(401).json({ error: 'Request authentication required.' });
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
app.use('/assets', express.static(assetDir));
|
||||
app.use('/uploads', express.static(uploadDir));
|
||||
app.use('/media', express.static(mediaDir));
|
||||
app.use('/assets/vendor', express.static(path.join(__dirname, '..', '..', 'node_modules', 'hls.js', 'dist')));
|
||||
|
||||
app.get('/api/uploads/config', function (_req, res) {
|
||||
app.get('/sw.js', function (_req, res) {
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
res.type('application/javascript');
|
||||
res.sendFile(path.join(__dirname, 'public', 'sw.js'));
|
||||
});
|
||||
|
||||
app.post('/api/auth/page', function (req, res, next) {
|
||||
try {
|
||||
if (!sharedSecret) {
|
||||
return res.status(404).json({ error: 'Page authentication is disabled.' });
|
||||
}
|
||||
|
||||
const token = String(req.headers['x-pulse-page-auth'] || '').trim();
|
||||
const payload = verifyPageAuthToken(token);
|
||||
if (!payload || ['player', 'onboarding'].indexOf(String(payload.scope || '').trim()) === -1) {
|
||||
return res.status(401).json({ error: 'Page authentication required.' });
|
||||
}
|
||||
|
||||
const tokenBundle = createPageAuthBundle({
|
||||
scope: payload.scope,
|
||||
slug: payload.slug || null,
|
||||
deviceId: payload.deviceId || null
|
||||
});
|
||||
res.json(tokenBundle);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/media/config', requireRequestAuth, function (_req, res) {
|
||||
res.json({
|
||||
uploadDir: uploadDir
|
||||
mediaDir: mediaDir
|
||||
});
|
||||
});
|
||||
|
||||
app.put('/api/uploads/:filename', express.raw({ type: '*/*', limit: '100mb' }), async function (req, res, next) {
|
||||
app.put('/api/media/:filename', requireRequestAuth, express.raw({ type: '*/*', limit: '100mb' }), async function (req, res, next) {
|
||||
try {
|
||||
const filename = require('path').basename(String(req.params.filename || '').trim());
|
||||
if (!filename) {
|
||||
return res.status(400).json({ error: 'Filename is required' });
|
||||
}
|
||||
const filePath = require('path').join(uploadDir, filename);
|
||||
const filePath = require('path').join(mediaDir, filename);
|
||||
const body = Buffer.isBuffer(req.body) ? req.body : Buffer.from(req.body || '');
|
||||
await fs.promises.mkdir(uploadDir, { recursive: true });
|
||||
await fs.promises.mkdir(mediaDir, { recursive: true });
|
||||
await fs.promises.writeFile(filePath, body);
|
||||
res.json({ ok: true, filename: filename });
|
||||
} catch (error) {
|
||||
@@ -38,13 +113,13 @@ function registerPlayerRoutes(app, options) {
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/uploads/:filename', async function (req, res, next) {
|
||||
app.delete('/api/media/:filename', requireRequestAuth, async function (req, res, next) {
|
||||
try {
|
||||
const filename = require('path').basename(String(req.params.filename || '').trim());
|
||||
if (!filename) {
|
||||
return res.status(400).json({ error: 'Filename is required' });
|
||||
}
|
||||
const filePath = require('path').join(uploadDir, filename);
|
||||
const filePath = require('path').join(mediaDir, filename);
|
||||
try {
|
||||
await fs.promises.unlink(filePath);
|
||||
} catch (error) {
|
||||
@@ -58,6 +133,53 @@ function registerPlayerRoutes(app, options) {
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/rtmp/session', requirePageAuth(['player']), async function (req, res, next) {
|
||||
try {
|
||||
const source = String(req.query.source || '').trim();
|
||||
const disableAudio = String(req.query.disableAudio || '').trim().toLowerCase();
|
||||
const useMutedOutput = disableAudio === '1' || disableAudio === 'true' || disableAudio === 'yes' || disableAudio === 'on';
|
||||
const session = await rtmpStreamService.ensureSession(source, useMutedOutput);
|
||||
await session.ready.catch(function () {
|
||||
return false;
|
||||
});
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
res.json({
|
||||
key: session.key,
|
||||
playlistUrl: session.playlistUrl,
|
||||
disableAudio: session.disableAudio,
|
||||
ready: true
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/rtmp/streams/:key/index.m3u8', async function (req, res, next) {
|
||||
try {
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
const manifestPath = await rtmpStreamService.getManifestFilePath(req.params.key);
|
||||
if (!manifestPath) {
|
||||
return res.status(404).send('Stream not found');
|
||||
}
|
||||
res.sendFile(manifestPath);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/rtmp/streams/:key/:fileName', async function (req, res, next) {
|
||||
try {
|
||||
const segmentPath = await rtmpStreamService.getSegmentFilePath(req.params.key, req.params.fileName);
|
||||
if (!segmentPath) {
|
||||
return res.status(404).send('Stream not found');
|
||||
}
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
res.sendFile(segmentPath);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/screen/:slug', function (req, res) {
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
res.set('Pragma', 'no-cache');
|
||||
@@ -65,11 +187,12 @@ function registerPlayerRoutes(app, options) {
|
||||
res.send(common.renderPlayerPage(req.params.slug, data));
|
||||
}).catch(function (error) {
|
||||
console.error(error);
|
||||
res.status(500).send('Internal server error');
|
||||
res.set('X-Player-Offline', '1');
|
||||
res.send(common.renderPlayerPage(req.params.slug, null));
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/screens/:slug/playlist', async function (req, res, next) {
|
||||
app.get('/api/screens/:slug/playlist', requirePageAuth(['player']), async function (req, res, next) {
|
||||
try {
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
const data = await playerPlaylistService.buildScreenPlaylist(req.params.slug);
|
||||
@@ -89,25 +212,33 @@ function registerPlayerRoutes(app, options) {
|
||||
}
|
||||
});
|
||||
|
||||
app.get(['/api/screens/:slug/connections', '/api/screens/:slug/clients'], async function (req, res, next) {
|
||||
app.get(['/api/screens/:slug/connections', '/api/screens/:slug/clients'], requireRequestAuth, async function (req, res, next) {
|
||||
try {
|
||||
const [screenRows] = await pool.query('SELECT id, name, slug FROM screens WHERE slug = ?', [req.params.slug]);
|
||||
if (!screenRows.length) {
|
||||
return res.status(404).json({ error: 'Screen not found' });
|
||||
}
|
||||
const connections = playerRuntime.snapshotConnections(req.params.slug);
|
||||
let screen = null;
|
||||
let screenLookupFailed = false;
|
||||
try {
|
||||
const [screenRows] = await pool.query('SELECT id, name, slug FROM screens WHERE slug = ?', [req.params.slug]);
|
||||
screen = screenRows[0] || null;
|
||||
} catch (error) {
|
||||
screenLookupFailed = isTransientDbError(error);
|
||||
if (!screenLookupFailed) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
res.json({
|
||||
screen: screenRows[0],
|
||||
screen: screen,
|
||||
screenSlug: req.params.slug,
|
||||
count: connections.length,
|
||||
connections: connections
|
||||
connections: connections,
|
||||
degraded: screenLookupFailed
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/screens/:slug/commands', async function (req, res, next) {
|
||||
app.post('/api/screens/:slug/commands', requireRequestAuth, async function (req, res, next) {
|
||||
try {
|
||||
const command = String((req.body && req.body.command) || req.query.command || '').trim().toLowerCase();
|
||||
const connectionId = String((req.body && (req.body.connectionId || req.body.clientId)) || req.query.connectionId || req.query.clientId || '').trim();
|
||||
@@ -121,15 +252,29 @@ function registerPlayerRoutes(app, options) {
|
||||
return res.status(400).json({ error: 'Unsupported command' });
|
||||
}
|
||||
|
||||
const liveConnections = playerRuntime.snapshotConnections(req.params.slug);
|
||||
const isRedirectCommand = command === 'redirect';
|
||||
let screenRows = [];
|
||||
let screen = null;
|
||||
let screenLookupFailed = false;
|
||||
if (!isRedirectCommand) {
|
||||
[screenRows] = await pool.query('SELECT id, name, slug FROM screens WHERE slug = ?', [req.params.slug]);
|
||||
if (!screenRows.length) {
|
||||
return res.status(404).json({ error: 'Screen not found' });
|
||||
try {
|
||||
const [screenRows] = await pool.query('SELECT id, name, slug FROM screens WHERE slug = ?', [req.params.slug]);
|
||||
screen = screenRows[0] || null;
|
||||
} catch (error) {
|
||||
screenLookupFailed = isTransientDbError(error);
|
||||
if (!screenLookupFailed) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!screen && liveConnections.length) {
|
||||
screen = {
|
||||
name: req.params.slug,
|
||||
slug: req.params.slug
|
||||
};
|
||||
}
|
||||
|
||||
const commandPayload = req.body && typeof req.body === 'object' && !Array.isArray(req.body)
|
||||
? Object.assign({}, req.body, { command: command })
|
||||
: command;
|
||||
@@ -141,12 +286,21 @@ function registerPlayerRoutes(app, options) {
|
||||
? await playerRuntime.sendCommandToConnection(req.params.slug, connectionId, commandPayload)
|
||||
: await playerRuntime.broadcastCommand(req.params.slug, commandPayload);
|
||||
|
||||
if (!screen && !screenLookupFailed && !liveConnections.length) {
|
||||
return res.status(404).json({ error: 'Screen not found' });
|
||||
}
|
||||
|
||||
if (!screen && screenLookupFailed && !liveConnections.length) {
|
||||
return res.status(503).json({ error: 'Screen metadata unavailable while the database is down.' });
|
||||
}
|
||||
|
||||
res.json({
|
||||
screen: screenRows[0] || null,
|
||||
screen: screen,
|
||||
screenSlug: req.params.slug,
|
||||
command: command,
|
||||
connectionId: connectionId || null,
|
||||
sent: sent
|
||||
sent: sent,
|
||||
degraded: screenLookupFailed
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
|
||||
+18
-1
@@ -1,6 +1,7 @@
|
||||
const crypto = require('crypto');
|
||||
const { WebSocketServer, WebSocket } = require('ws');
|
||||
const { isClientNameAvailable } = require('../client-name-check');
|
||||
const { isClientNameAvailable } = require('../data/client-name-check');
|
||||
const { verifyPageAuthToken, verifyRequestAuth } = require('../request-auth');
|
||||
|
||||
function createPlayerRuntime(options) {
|
||||
const pool = options && options.pool ? options.pool : null;
|
||||
@@ -239,6 +240,22 @@ function createPlayerRuntime(options) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (dashboardMatch) {
|
||||
if (!verifyRequestAuth(request)) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (playerMatch) {
|
||||
const authToken = String(new URL(request.url, 'http://localhost').searchParams.get('auth') || '').trim();
|
||||
const payload = verifyPageAuthToken(authToken);
|
||||
if (!payload || String(payload.scope || '').trim() !== 'player') {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const slug = decodeURIComponent((dashboardMatch || playerMatch)[1]);
|
||||
wss.handleUpgrade(request, socket, head, function (ws) {
|
||||
wss.emit('connection', ws, request, slug, dashboardMatch ? 'dashboard' : 'player');
|
||||
|
||||
Reference in New Issue
Block a user