Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/themes.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ Los nombres se recortan en los extremos, deben ser únicos sin distinguir mayús

El `<html>` del overlay, widgets y marco propio recibe `data-tema="<id>"`; las previews `previewTheme` usan el id elegido. Los widgets y el marco propio cambian el marcador inmediatamente; si hay una alerta visible, el overlay difiere el marcador junto con el aspecto hasta que la alerta termine de salir. En `/api/stream`, `?themeInfo=1` añade `activeTheme: { id, name }` después de las tramas iniciales existentes; está separado de `theme` y de su `version`, por lo que renombrar no cambia el hash de apariencia ni las miniaturas. La shell solicita además `customTheme=1` para recibir el snapshot `customOverlayTheme`; los clientes sin estos parámetros conservan su secuencia anterior. En overlays propios `antena.on('theme', fn)` y `antena.state.theme` incluyen `id` y `name` junto con las variables habituales. Una instantánea única lleva identidad, aspecto y CSS del overlay; el SDK aplica ambos CSS y el marcador antes de notificar el evento.

Con `?build=1`, `/api/stream` añade al final de las tramas iniciales `build: { version }`, la versión de Antena. El overlay de alertas, los widgets y la shell de los overlays propios la piden y se recargan una sola vez si, al reconectar, la versión es distinta de la primera que recibieron: tras actualizar Antena, las fuentes abiertas en OBS o Meld cargan el código nuevo sin refrescarlas a mano. Un reinicio con la misma versión no recarga nada (#355).

Activar guarda el look saliente, aplica el entrante y actualiza `activeId` en una única escritura atómica con copia local previa. El cambio se difunde a los overlays, widgets y panel. Las alertas que ya están en pantalla o en la cola del overlay conservan los ajustes de alerta y CSS con los que se construyeron; las alertas construidas después del cambio usan los del nuevo tema. El tema global del overlay cambia entre alertas, no durante la salida de la actual. Se descarta cualquier borrador de Apariencia del tema anterior. Un objetivo o variante de chat inexistente se rechaza en su API con 404 sin cambiar contadores ni configuración; los atajos actuales no incluyen acciones de objetivo o variante.

## Stream Deck
Expand Down
5 changes: 3 additions & 2 deletions public/overlay.html
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@
<!-- logos de plataforma a color para los iconos y la etiqueta del tema (Apariencia) -->
<script type="module">import * as P from '/platform-icons.js'; window.egPlatform = P;</script>
<script type="module">
import { AntenaStream } from '/stream-client.js';
import { AntenaStream, reloadOnNewBuild } from '/stream-client.js';
const ICONS = {
heart:'<path d="M12 20.5s-7.5-4.6-7.5-10.2A4.3 4.3 0 0 1 12 7.6a4.3 4.3 0 0 1 7.5 2.7c0 5.6-7.5 10.2-7.5 10.2z"/>',
star:'<path d="M12 3.2l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17.2l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/>',
Expand Down Expand Up @@ -592,7 +592,8 @@

// ---------- conexión ----------
if (PREVIEW) stage.insertAdjacentHTML('beforebegin', '<div class="hint" id="hint">Vista previa</div>');
const es = STILL ? new EventTarget() : new AntenaStream('/api/stream?client=' + (PREVIEW ? 'preview' : 'overlay') + '&themeInfo=1' + (qs.has('themeDraft') ? '&themeDraft=1' : ''));
const es = STILL ? new EventTarget() : new AntenaStream('/api/stream?client=' + (PREVIEW ? 'preview' : 'overlay') + '&themeInfo=1' + (qs.has('themeDraft') ? '&themeDraft=1' : '') + '&build=1');
if (!STILL) reloadOnNewBuild(es);
// El panel no debe enviar el ejemplo hasta que el servidor haya admitido este marco.
if (PREVIEW && !STILL) window.antenaPreviewReady = new Promise(resolve => { es.onopen = resolve; });
es.addEventListener('alert', e => {
Expand Down
15 changes: 15 additions & 0 deletions public/stream-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,18 @@ export class AntenaStream extends EventTarget {
this.source?.close();
}
}

/** Reloads the page once when the stream reconnects to a different Antena version (#355).
* The page's own code (overlay shell, widget, alerts) is otherwise kept from before an update
* until OBS/Meld refreshes the browser source. Needs `build=1` in the stream URL. */
export function reloadOnNewBuild(stream, reload = () => location.reload()) {
let first = null, reloading = false;
stream.addEventListener('build', e => {
let version;
try { version = JSON.parse(e.data).version; } catch { return; }
if (typeof version !== 'string' || !version) return;
if (first === null) { first = version; return; }
if (version !== first && !reloading) { reloading = true; reload(); }
});
return stream;
}
7 changes: 4 additions & 3 deletions public/widgets/widget.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Utilidades comunes de los widgets: conexión, modo demo y CSS propio.
import { AntenaStream } from '../stream-client.js';
import { AntenaStream, reloadOnNewBuild } from '../stream-client.js';
export const qs = new URLSearchParams(location.search);
export const DEMO = qs.has('demo');
const THEME_DRAFT = qs.has('themeDraft');
Expand Down Expand Up @@ -40,7 +40,8 @@ export function connect(handlers, client = 'widget') {
return es;
}
const es = new AntenaStream('/api/stream?client=' + encodeURIComponent(client) + '&themeInfo=1' +
(handlers.customOverlayTheme ? '&customTheme=1' : '') + (handlers.scene ? '&scene=1' : '') + (THEME_DRAFT ? '&themeDraft=1' : ''));
(handlers.customOverlayTheme ? '&customTheme=1' : '') + (handlers.scene ? '&scene=1' : '') + (THEME_DRAFT ? '&themeDraft=1' : '') + '&build=1');
reloadOnNewBuild(es);
// Apariencia: al cambiar el tema se recarga /theme.css (sin recargar la página). Con ?themeDraft
// (vista previa del panel) se ve también el borrador sin guardar; en Meld, solo lo guardado.
es.addEventListener('activeTheme', e => {
Expand All @@ -55,7 +56,7 @@ export function connect(handlers, client = 'widget') {
if (link && !link.href.endsWith(href)) link.href = href;
handlers.theme?.(t);
});
for (const [ev, fn] of Object.entries(handlers)) if (ev !== 'theme' && ev !== 'activeTheme') es.addEventListener(ev, e => fn(JSON.parse(e.data)));
for (const [ev, fn] of Object.entries(handlers)) if (ev !== 'theme' && ev !== 'activeTheme' && ev !== 'build') es.addEventListener(ev, e => fn(JSON.parse(e.data)));
return es;
}

Expand Down
6 changes: 5 additions & 1 deletion src/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@ function sdRequestAllowed(req) {

export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA || path.join(ROOT, 'media'), log = console.log, heldRecoveryWindows, heldRecoveryIO, appDist, recordingTimers,
push = { url: process.env.ANTENA_PUSH_URL, token: process.env.ANTENA_PUSH_TOKEN }, pushTimers, pushNow, pushTimeoutMs, configTransferIO, zipUploadLimit, zipExportLimit,
discordFetch, discordRetryDelayMs, discordTimeoutMs, scheduleCalendarTimeoutMs } = {}) {
discordFetch, discordRetryDelayMs, discordTimeoutMs, scheduleCalendarTimeoutMs, appVersion } = {}) {
// Version announced to overlay pages (#355): a page that reconnects to another version reloads once.
const buildVersion = appVersion ?? JSON.parse(await readFile(path.join(ROOT, 'package.json'), 'utf8')).version;
let notifyPushStatus = () => {}, requestPushReconciliation = () => {}, notifyPushCheckpoint = () => {}, notifyDiscordStatus = () => {}, notifyScheduleStatus = () => {};
// Validate private process settings before loading or changing any application state.
const pushExport = createPushExport({ config: push, timers: pushTimers, now: pushNow, timeoutMs: pushTimeoutMs,
Expand Down Expand Up @@ -1322,6 +1324,7 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA |
const themeInfo = url.searchParams.get('themeInfo') === '1';
const customTheme = kind === 'widget' && url.searchParams.get('customTheme') === '1';
const scene = kind === 'widget' && url.searchParams.get('scene') === '1';
const build = url.searchParams.get('build') === '1';
bus.addClient(res, kind, { events: [...(themeInfo ? ['themeInfo'] : []), ...(customTheme ? ['customTheme'] : []), ...(scene ? ['scene'] : [])] });
if (kind === 'dock-meters') {
meterWatchers.add(res);
Expand Down Expand Up @@ -1353,6 +1356,7 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA |
if (customTheme) res.write(`event: customOverlayTheme\ndata: ${JSON.stringify(customOverlayThemeSnapshot())}\n\n`);
}
if (scene) res.write(`event: scene\ndata: ${JSON.stringify(onAirScenes())}\n\n`);
if (build) res.write(`event: build\ndata: ${JSON.stringify({ version: buildVersion })}\n\n`);
// A chat source or panel that connects during a chat preview joins it.
if ((kind === 'widget' || kind === 'panel') && chatPreview.snapshot().on) res.write(`event: chatPreview\ndata: ${JSON.stringify(chatPreview.snapshot())}\n\n`);
pushStatus();
Expand Down
87 changes: 87 additions & 0 deletions test/build-reload.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// #355: overlay pages opened in OBS/Meld reload themselves once when they reconnect to an
// Antena of a different version, so a stale page never misses widgets added by an update.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { createApp } from '../src/server.mjs';
import { closeAll, closeChrome, findChrome, openChromePage, waitDom } from './helpers/react-browser.mjs';
import { evaluateChrome } from './helpers/chrome-dom.mjs';

async function startApp(t, appVersion, port = 0) {
const dataDir = await mkdtemp(path.join(tmpdir(), 'antena-build-reload-'));
t.after(() => rm(dataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
const app = await createApp({ dataDir, mediaDir: path.join(dataDir, 'media'), log: () => {}, appVersion });
await new Promise((resolve, reject) => { app.server.once('error', reject); app.server.listen(port, '127.0.0.1', resolve); });
return { app, port: app.server.address().port };
}

/** Reads the first frames of a stream until `ms` elapse. */
async function firstFrames(base, query, ms = 400) {
const ctrl = new AbortController();
const res = await fetch(`${base}/api/stream?${query}`, { signal: ctrl.signal, headers: { accept: 'text/event-stream' } });
const reader = res.body.getReader(), dec = new TextDecoder();
let text = '';
const timer = setTimeout(() => ctrl.abort(), ms);
try { for (;;) { const { value, done } = await reader.read(); if (done) break; text += dec.decode(value); } }
catch {} finally { clearTimeout(timer); }
return text;
}

test('the stream announces the app version only to clients that ask for it', async t => {
const { app, port } = await startApp(t, '9.9.9');
t.after(() => app.closeHttp());
const base = `http://127.0.0.1:${port}`;
const opted = await firstFrames(base, 'client=widget&themeInfo=1&build=1');
assert.match(opted, /event: build\ndata: \{"version":"9\.9\.9"\}\n\n/);
const legacy = await firstFrames(base, 'client=widget&themeInfo=1');
assert.doesNotMatch(legacy, /event: build/);
assert.match(legacy, /event: widgets\n/);
const overlay = await firstFrames(base, 'client=overlay&build=1');
assert.match(overlay, /event: build\ndata: \{"version":"9\.9\.9"\}\n\n/);
});

test('the stream defaults to the package version', async t => {
const { app, port } = await startApp(t, undefined);
t.after(() => app.closeHttp());
const { version } = JSON.parse(await (await import('node:fs/promises')).readFile(new URL('../package.json', import.meta.url), 'utf8'));
const text = await firstFrames(`http://127.0.0.1:${port}`, 'client=widget&build=1');
assert.ok(text.includes(`event: build\ndata: ${JSON.stringify({ version })}\n\n`));
});

test('widget, alert overlay and custom overlay pages reload once after an update, not after a plain restart', { timeout: 90000 }, async t => {
const bin = await findChrome();
if (!bin) return t.skip('sin Chrome local');
let { app, port } = await startApp(t, '1.0.0');
const base = `http://127.0.0.1:${port}`;
const overlay = (await (await fetch(base + '/api/custom-overlays', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'Reload', js: '' }) })).json()).overlay;
const pages = ['/widget/latest', '/overlay', `/custom/${overlay.id}`];
const chromes = [];
try {
for (const p of pages) {
const chrome = await openChromePage(bin, base + p);
chromes.push(chrome);
await waitDom(chrome.cdp, `document.readyState === 'complete'`);
await new Promise(r => setTimeout(r, 500));
await evaluateChrome(chrome.cdp, `window.__stale = 1`);
}
const restart = async version => {
await app.closeHttp();
// A fresh data dir per app: the custom shell only checks its own reload (its frame may 404 after it).
({ app } = await startApp(t, version, port));
};
// Plain restart, same version: the pages reconnect and keep running.
await restart('1.0.0');
await new Promise(r => setTimeout(r, 4500));
for (const [i, chrome] of chromes.entries()) assert.equal(await evaluateChrome(chrome.cdp, `window.__stale`), 1, `${pages[i]} reloaded without an update`);
// Update: each page reloads once and drops its stale state.
await restart('1.0.1');
for (const chrome of chromes) await waitDom(chrome.cdp, `window.__stale === undefined && document.readyState === 'complete'`, { timeoutMs: 15000 });
for (const chrome of chromes) await evaluateChrome(chrome.cdp, `window.__fresh = 1`);
await new Promise(r => setTimeout(r, 3000));
for (const [i, chrome] of chromes.entries()) assert.equal(await evaluateChrome(chrome.cdp, `window.__fresh`), 1, `${pages[i]} reloaded more than once`);
} finally {
await closeAll(...chromes.map(c => () => closeChrome(c)), () => app.closeHttp());
}
});
1 change: 1 addition & 0 deletions test/groups.json
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@
"test/alert-thumbs-browser.test.mjs",
"test/apariencia-browser.test.mjs",
"test/apariencia-save.test.mjs",
"test/build-reload.test.mjs",
"test/charts-style-browser.test.mjs",
"test/chat-backlog-browser.test.mjs",
"test/chat-preview-browser.test.mjs",
Expand Down
4 changes: 2 additions & 2 deletions test/overlay-theme-deferral.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Element {

async function overlay({ search = '', hidden = false } = {}) {
const html = await readFile(new URL('../public/overlay.html', import.meta.url), 'utf8');
const script = /<script type="module">\s*import \{ AntenaStream \}[^\n]*\n([\s\S]*?)<\/script>/.exec(html);
const script = /<script type="module">\s*import \{ AntenaStream(?:, reloadOnNewBuild)? \}[^\n]*\n([\s\S]*?)<\/script>/.exec(html);
assert.ok(script, 'módulo del overlay');
const elements = { stage: new Element(), bg: new Element(), 'custom-css': new Element(), 'eg-theme': new Element('link'),
'tpl-card': { content: { firstElementChild: new Element() } } };
Expand All @@ -36,7 +36,7 @@ async function overlay({ search = '', hidden = false } = {}) {
const setTimeout = (fn, ms) => { const id = ++nextId; timers.set(id, { at: now + ms, fn }); return id; };
const clearTimeout = id => timers.delete(id);
runInNewContext(script[1], { document, window: {}, location: { search }, URLSearchParams, EventTarget,
AntenaStream: FakeStream, Audio, setTimeout, clearTimeout, requestAnimationFrame: fn => fn(),
AntenaStream: FakeStream, reloadOnNewBuild: () => {}, Audio, setTimeout, clearTimeout, requestAnimationFrame: fn => fn(),
getComputedStyle: () => ({ fontSize: '80' }), performance: { now: () => now }, console });
const emit = (type, data) => stream.dispatchEvent(new MessageEvent(type, { data: JSON.stringify(data) }));
const advance = async ms => {
Expand Down
Loading