From 5251f26b1679b62f88edf1eee71b3a2086d50bc6 Mon Sep 17 00:00:00 2001 From: egdev6 <18334564+egdev6@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:44:44 +0100 Subject: [PATCH] =?UTF-8?q?feat(latest):=20show=20the=20last=20supporters?= =?UTF-8?q?=20of=20all=20streams=20in=20=C2=AB=C3=9Altimos=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit «Últimos» only read the current session, so every stream started with empty cards. A separate record (latest-history.json) now keeps the last supporter of each type across streams and restarts: it is updated with every real event, rebuilt once from the archived streams when missing, and merged with imported streams. Simulated alerts are marked on the session event and never enter it. The widget state gains latestAll; latest keeps its per-stream meaning for every existing consumer. New widgets.latest.scope ('stream' by default, or 'all'), validated by the widgets API, accepted by MCP editar_widget and chosen in the panel with «Mostrar» («Este directo» / «Histórico»). READMEs describe the option. Closes #357 --- README.es.md | 2 +- README.md | 2 +- app/src/panel/views/Widgets.tsx | 11 ++++ public/widgets/latest.html | 6 +- src/config-schema.mjs | 3 +- src/engine.mjs | 5 +- src/latest-history.mjs | 89 +++++++++++++++++++++++++ src/mcp.mjs | 2 +- src/routes/widgets.mjs | 2 +- src/server.mjs | 18 ++++- src/session.mjs | 12 ++-- src/store.mjs | 2 +- test/groups.json | 2 + test/latest-history-browser.test.mjs | 55 ++++++++++++++++ test/latest-history.test.mjs | 99 ++++++++++++++++++++++++++++ 15 files changed, 290 insertions(+), 20 deletions(-) create mode 100644 src/latest-history.mjs create mode 100644 test/latest-history-browser.test.mjs create mode 100644 test/latest-history.test.mjs diff --git a/README.es.md b/README.es.md index aac1271..81c4edd 100644 --- a/README.es.md +++ b/README.es.md @@ -169,7 +169,7 @@ En el panel, la página «Fuentes del programa de emisión» lista todas con su | Entrevista | `http://127.0.0.1:4500/widget/interview` | 1920×1080 | | Redes sociales | `http://127.0.0.1:4500/widget/socials` | 1600×80 | -**Últimos y ticker.** Son dos widgets separados en **Widgets**. «Últimos» muestra el último apoyo de cada tipo marcado (seguidor, sub, bits, raid, Super Chat, miembro o cualquier evento), con una etiqueta opcional (`widgets.latest.label`; vacía no se muestra, clase `.label`). El ticker, en cambio, recorre los eventos más recientes de sus tipos, así que pueden salir varias subs seguidas. Usa los tipos de «Últimos» hasta que eliges los suyos (`widgets.ticker.items`, mismos valores). +**Últimos y ticker.** Son dos widgets separados en **Widgets**. «Últimos» muestra el último apoyo de cada tipo marcado (seguidor, sub, bits, raid, Super Chat, miembro o cualquier evento), con una etiqueta opcional (`widgets.latest.label`; vacía no se muestra, clase `.label`). Con **Mostrar** eliges «Este directo» (por defecto; empieza vacío en cada directo) o «Histórico» (`widgets.latest.scope: "all"`): el último apoyo de cada tipo de todos tus directos, guardado aparte de las sesiones; las alertas simuladas no cuentan. El ticker, en cambio, recorre los eventos más recientes de sus tipos, así que pueden salir varias subs seguidas. Usa los tipos de «Últimos» hasta que eliges los suyos (`widgets.ticker.items`, mismos valores). **Redes sociales.** En **Widgets › Redes sociales** (`/widget/socials`, 1600×80) añades, editas, quitas y ordenas hasta 12 redes (Twitch, YouTube, X, Instagram, TikTok, GitHub, Discord, Kick, LinkedIn y Web); cada una sale con el icono de su plataforma y tu nick, como texto. Las redes sin nick no se muestran y, sin redes, la capa queda vacía. Etiqueta opcional (por ejemplo «Sígueme») y CSS propio con las clases `.root`, `.label`, `.item`, `.item-`, `.ico` y `.handle`. Los iconos de marca vienen de Simple Icons (CC0); X, TikTok y GitHub van en blanco para verse sobre fondo oscuro. Los perfiles viven en `widgets.socials` y, como el resto de ajustes de widgets, viajan con los temas guardados. Se puede incrustar como hueco `socials` en overlays propios; por MCP, `editar_widget` con `widget: "socials"` (la lista se sustituye entera). diff --git a/README.md b/README.md index 3a944f2..1d0212f 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ In the panel, the «Fuentes del programa de emisión» page lists all of them wi | On-screen messages | `http://127.0.0.1:4500/widget/rotator` | 1200×120 | | Social bar | `http://127.0.0.1:4500/widget/socials` | 1600×80 | -**Latest and ticker.** They are separate widgets in **Widgets**. «Latest» shows the last supporter of each selected type (follower, sub, bits, raid, Super Chat, member or any event), with an optional label (`widgets.latest.label`; empty shows none, class `.label`). The ticker scrolls the most recent events of its types instead, so several subs can appear at once. It uses the «Latest» types until you pick its own (`widgets.ticker.items`, same values). +**Latest and ticker.** They are separate widgets in **Widgets**. «Latest» shows the last supporter of each selected type (follower, sub, bits, raid, Super Chat, member or any event), with an optional label (`widgets.latest.label`; empty shows none, class `.label`). **Show** picks «This stream» (default; starts empty on every stream) or «All streams» (`widgets.latest.scope: "all"`): the last supporter of each type across all your streams, kept apart from sessions; simulated alerts do not count. The ticker scrolls the most recent events of its types instead, so several subs can appear at once. It uses the «Latest» types until you pick its own (`widgets.ticker.items`, same values). **Preview in your broadcast program:** in **Widgets › Chat**, «Simular mensajes en Meld» makes every real chat source (the default chat, its variants and custom overlay slots) play the same sample messages as the panel preview for 2 minutes, then return to the real chat. A source loaded during the simulation joins it. Nothing is added to the chat, the history or the metrics. API: `POST /api/chat/preview` with `{ "on": true }` (optional `"seconds"`, 1–600) or `{ "on": false }`; `GET /api/chat/preview` returns `{ on, until }`. MCP: `vista_previa_chat`. diff --git a/app/src/panel/views/Widgets.tsx b/app/src/panel/views/Widgets.tsx index 9f4b916..6cbf283 100644 --- a/app/src/panel/views/Widgets.tsx +++ b/app/src/panel/views/Widgets.tsx @@ -62,6 +62,7 @@ export function Widget({ name }: { name: string }) { let form: ReactNode = null; if (name === 'latest') form = <> +
Tipos de apoyo

Clases: .root .root.col .label .item .item-{''} .item.empty .item.flash .kick .big .extra

; @@ -163,6 +164,16 @@ function SocialsSettings() { ; } +function LatestScope() { + const scope = String(useLive(s => s.config.widgets.latest?.scope) || 'stream'); + return <> + +

«Este directo» empieza vacío en cada directo. «Histórico» muestra el último apoyo de cada tipo de todos tus directos; las alertas simuladas no cuentan.

+ ; +} + function ThanksSettings() { const window = useLive(s => s.config.widgets.thanks?.window || 'lastStream'); return <> diff --git a/public/widgets/latest.html b/public/widgets/latest.html index 2d350be..65aa1d8 100644 --- a/public/widgets/latest.html +++ b/public/widgets/latest.html @@ -27,14 +27,16 @@ function apply(s) { const cfg = s.widgets?.latest || {}; setCss(cfg.css); + // scope «all» (#357): the last supporters of every stream; otherwise only this stream's. + const latest = cfg.scope === 'all' && s.latestAll ? s.latestAll : s.latest; const items = (qs.get('items')?.split(',') || cfg.items || ['follow', 'sub', 'cheer', 'superchat']).filter(k => LABELS[k]); // Optional label (widgets.latest.label): empty shows nothing. root.innerHTML = (cfg.label ? `

${esc(cfg.label)}

` : '') + items.map(k => { - const e = s.latest?.[k]; + const e = latest?.[k]; const changed = e && prev[k] && prev[k] !== e.user + e.at; return `

${LABELS[k]}

${e ? esc(e.user) : '—'}

${e && extra(k, e) ? `

${esc(extra(k, e))}

` : ''}
`; }).join(''); - prev = Object.fromEntries(items.map(k => [k, s.latest?.[k] ? s.latest[k].user + s.latest[k].at : null])); + prev = Object.fromEntries(items.map(k => [k, latest?.[k] ? latest[k].user + latest[k].at : null])); } connect({ widgets: s => apply(DEMO ? { ...demoState(), widgets: s.widgets } : s) }); if (DEMO) apply(demoState()); diff --git a/src/config-schema.mjs b/src/config-schema.mjs index a81133d..89d1e4d 100644 --- a/src/config-schema.mjs +++ b/src/config-schema.mjs @@ -309,7 +309,8 @@ export const CONFIG_SCHEMA = { chat: CHAT_FIELDS, chatVariants: CHAT_VARIANTS, goals: list(GOAL_BOX), - latest: { items: arrStr(SUPPORT_TYPES), label: str, css: str }, + // scope (#357): «stream» = this stream's last supporters; «all» = the last ones of every stream. + latest: { items: arrStr(SUPPORT_TYPES), label: str, scope: en(['stream', 'all']), css: str }, // items is optional: without it the ticker shows the «Últimos» types. ticker: { label: str, items: arrStr(SUPPORT_TYPES), count: num({ int: true, min: 1, max: 100 }), speed: num({ int: true, min: 10, max: 500 }), css: str }, credits: { title: str, subtitle: str, speed: num({ int: true, min: 10, max: 500 }), css: str }, diff --git a/src/engine.mjs b/src/engine.mjs index 8d8d4b3..534ca43 100644 --- a/src/engine.mjs +++ b/src/engine.mjs @@ -95,7 +95,7 @@ export class Engine extends EventEmitter { const clean = cleanVars(vars, this.config.filters); const a = buildAlert(type, clean, this.config); if (!a) return null; - this.session.record(a); + this.session.record(a, { simulated: String(externalId || '').startsWith('sim:') }); this.log(`[alerta] ${type}${a.variation ? ' (' + a.variation.name + ')' : ''} · ${a.text}`); return this.deliver(a); } @@ -614,7 +614,8 @@ export class Engine extends EventEmitter { bars: (g.bars || []).map(b => ({ ...b, value: s.goalValue(b.metric, b.platform), source: isTotalMetric(b.metric, b.platform) ? 'channel' : 'session' })), })); return { - totals: s.totals(), latest: s.latest(), goals, + // #357: latestAll = last supporters of every stream; latest stays per stream for every consumer. + totals: s.totals(), latest: s.latest(), latestAll: this.latestHistory ? this.latestHistory.snapshot() : s.latest(), goals, recent: s.data.events.filter(e => !ALERT_TYPES[e.type]?.system).slice(-30).reverse().map(e => ({ type: e.type, label: ALERT_TYPES[e.type]?.label || e.type, user: e.user, sub: e.sub, at: e.at })), credits: s.credits(), session: { id: s.data.id, title: s.data.title, startedAt: s.data.startedAt }, thanks: this.thanksState?.() ?? { names: [], anonymous: 0 }, diff --git a/src/latest-history.mjs b/src/latest-history.mjs new file mode 100644 index 0000000..559f47c --- /dev/null +++ b/src/latest-history.mjs @@ -0,0 +1,89 @@ +// #357: the last supporter of each «Últimos» type across all streams, kept apart from sessions. +// One entry per type (bounded size), updated with every real event and never cleared when a +// stream starts. Simulated alerts are tests and never enter it. +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; +import { isSystemType } from './alerts.mjs'; +import { writeJson } from './json-file.mjs'; + +export const LATEST_FILE = 'latest-history.json'; +// Same grouping as the per-stream «Últimos» (Session#latest). +export const LATEST_GROUPS = { + follow: ['follow', 'ytsub'], sub: ['sub', 'resub', 'giftsub'], cheer: ['cheer'], raid: ['raid'], + superchat: ['superchat', 'supersticker'], member: ['member', 'milestone', 'giftmember'], +}; +export const LATEST_KEYS = [...Object.keys(LATEST_GROUPS), 'any']; + +/** «Últimos» keys an event type counts for. */ +export const latestKeys = type => [ + ...Object.keys(LATEST_GROUPS).filter(k => LATEST_GROUPS[k].includes(type)), + ...(type && !isSystemType(type) ? ['any'] : []), +]; + +/** Last event of each «Últimos» type in a list ordered oldest first. */ +export function latestOf(events = []) { + const out = Object.fromEntries(LATEST_KEYS.map(k => [k, null])); + for (const e of events) for (const k of latestKeys(e?.type)) out[k] = e; + return out; +} + +const validEntry = e => !!e && typeof e === 'object' && typeof e.type === 'string' && typeof e.at === 'string'; + +export class LatestHistory { + constructor({ dir, write = writeJson, log = () => {} } = {}) { + this.file = path.join(dir, LATEST_FILE); + this.write = write; this.log = log; + this.entries = Object.fromEntries(LATEST_KEYS.map(k => [k, null])); + this.loaded = false; + this.writing = Promise.resolve(); + } + + async load() { + try { + const data = JSON.parse(await readFile(this.file, 'utf8')); + for (const k of LATEST_KEYS) this.entries[k] = validEntry(data?.entries?.[k]) ? data.entries[k] : null; + this.loaded = true; + } catch (err) { + if (err?.code !== 'ENOENT') this.log(`[últimos] no se pudo leer ${LATEST_FILE}: ${err.message}; se reconstruye`); + this.loaded = false; + } + return this; + } + + /** True when there is no saved record yet (first run or unreadable): rebuild it from the archives. */ + get needsBackfill() { return !this.loaded; } + + #apply(ev) { + if (!validEntry(ev) || ev.simulated) return false; + let changed = false; + for (const k of latestKeys(ev.type)) { + const cur = this.entries[k]; + if (!cur || ev.at >= cur.at) { this.entries[k] = { ...ev }; changed = true; } + } + return changed; + } + + /** A new real event: keep it when it is the newest of its types. */ + observe(ev) { + const changed = this.#apply(ev); + if (changed) this.save(); + return changed; + } + + /** Several events (backfill, imported streams): newest wins, one write. */ + merge(events = []) { + for (const ev of events) this.#apply(ev); + this.loaded = true; + return this.save(); + } + + snapshot() { return { ...this.entries }; } + + save() { + const data = { version: 1, entries: this.entries }; + this.writing = this.writing.then(() => this.write(this.file, data)).catch(err => this.log(`[últimos] no se pudo guardar ${LATEST_FILE}: ${err.message}`)); + return this.writing; + } + + flush() { return this.writing; } +} diff --git a/src/mcp.mjs b/src/mcp.mjs index 94ec9bd..9ace3ea 100644 --- a/src/mcp.mjs +++ b/src/mcp.mjs @@ -308,7 +308,7 @@ tool('ver_widgets', 'Configuración y datos de los widgets (chat y sus variantes const chatVariantes = (w.widgets.chatVariants || []).map(v => ({ id: v.id, nombre: v.name, url: b + '/widget/chat?variant=' + enc(v.id) })); return { urls: { chat: b + '/widget/chat', objetivo: b + '/widget/goal?id=', ultimos: b + '/widget/latest', ticker: b + '/widget/ticker', creditos: b + '/widget/credits', espectadores: b + '/widget/viewers', agradecimientos: b + '/widget/thanks', mensajesEnPantalla: b + '/widget/rotator', redesSociales: b + '/widget/socials', chatVariantes }, config: w.widgets, objetivos: w.goals, totales: w.totals, ultimos: w.latest }; }); -tool('editar_widget', 'Edita un widget. chat: platforms, maxMessages, fadeAfterSec, fontSize, hideCommands, hideOwner, showPlatform, reverse, animIn, animOut, layout (vertical|horizontal), css · latest: items (follow, sub, cheer, raid, superchat, member, any), label (vacía = sin etiqueta), css · ticker: label, items (follow, sub, cheer, raid, superchat, member, any; sin items usa los de latest), count, speed, css · credits: title, subtitle, speed, css · viewers: platforms (twitch, youtube), showTotal, showPeak, css · thanks: title, platforms (twitch, youtube), window (all|lastStream|days), days, maxNames, intervalSec, showAnonymous, css · rotator (mensajes en pantalla, distintos de los mensajes programados del chat): label, messages ([{ id, text }] en orden; la lista se reemplaza entera), intervalSec (5–3600, de un mensaje al siguiente), durationSec (segundos visibles, como mucho el intervalo), order (sequential|random: aleatorio sin repetir el mismo dos veces seguidas), css · socials (barra de redes sociales): label, items ([{ id, platform, handle }] en orden, máximo 12; platform: twitch, youtube, x, instagram, tiktok, github, discord, kick, linkedin, web; la lista se reemplaza entera), css.', +tool('editar_widget', 'Edita un widget. chat: platforms, maxMessages, fadeAfterSec, fontSize, hideCommands, hideOwner, showPlatform, reverse, animIn, animOut, layout (vertical|horizontal), css · latest: items (follow, sub, cheer, raid, superchat, member, any), label (vacía = sin etiqueta), scope (stream = este directo | all = histórico de todos los directos), css · ticker: label, items (follow, sub, cheer, raid, superchat, member, any; sin items usa los de latest), count, speed, css · credits: title, subtitle, speed, css · viewers: platforms (twitch, youtube), showTotal, showPeak, css · thanks: title, platforms (twitch, youtube), window (all|lastStream|days), days, maxNames, intervalSec, showAnonymous, css · rotator (mensajes en pantalla, distintos de los mensajes programados del chat): label, messages ([{ id, text }] en orden; la lista se reemplaza entera), intervalSec (5–3600, de un mensaje al siguiente), durationSec (segundos visibles, como mucho el intervalo), order (sequential|random: aleatorio sin repetir el mismo dos veces seguidas), css · socials (barra de redes sociales): label, items ([{ id, platform, handle }] en orden, máximo 12; platform: twitch, youtube, x, instagram, tiktok, github, discord, kick, linkedin, web; la lista se reemplaza entera), css.', { widget: S.enum('Widget', ['chat', 'latest', 'ticker', 'credits', 'viewers', 'thanks', 'rotator', 'socials']), cambios: S.obj('Campos a cambiar') }, ({ widget, cambios }) => put('/api/widgets', { [widget]: cambios }), ['widget', 'cambios']); tool('editar_variante_chat', 'Edita una variante del chat (ids en ver_widgets › chatVariantes; el chat predeterminado se edita con editar_widget). Cambia solo lo que pases: name, platforms, maxMessages, fadeAfterSec, fontSize, hideCommands, hideOwner, showPlatform, reverse, animIn, animOut, layout (vertical|horizontal), css. El id no cambia. Con layout horizontal, el css no debe fijar tamaño, posición, padding ni máscara de .root, ni flex, tamaño o letra de .msg: el widget ajusta la fila solo.', { id: S.str('Id de la variante'), cambios: S.obj('Campos a cambiar') }, ({ id, cambios }) => put('/api/widgets/chat/variants/' + enc(id), cambios), ['id', 'cambios']); diff --git a/src/routes/widgets.mjs b/src/routes/widgets.mjs index 6201e9f..00da2fb 100644 --- a/src/routes/widgets.mjs +++ b/src/routes/widgets.mjs @@ -13,7 +13,7 @@ export function registerWidgetRoutes({ route, store, engine }) { if (error) throw httpError(400, error.message); } // Support types and the «Últimos» label are new fields: validate only them, keep the legacy merge for the rest. - for (const [name, field] of [['latest', 'items'], ['latest', 'label'], ['ticker', 'items']]) { + for (const [name, field] of [['latest', 'items'], ['latest', 'label'], ['latest', 'scope'], ['ticker', 'items']]) { if (!patch[name] || typeof patch[name] !== 'object' || !Object.hasOwn(patch[name], field)) continue; const [error] = validatePath(`widgets.${name}.${field}`, patch[name][field]); if (error) throw httpError(400, error.message); diff --git a/src/server.mjs b/src/server.mjs index 1ee127a..3e60a1e 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -54,6 +54,7 @@ import { activeTheme, applyLook, extractLook, isThemedWrite, isThemeTargetReques import { ViewerWatch } from './viewers.mjs'; import { ChannelTotals } from './channel-totals.mjs'; import { FollowerRegistry } from './followers.mjs'; +import { LatestHistory } from './latest-history.mjs'; import { registerTeleprompterRoutes } from './routes/teleprompter.mjs'; import { registerInterviewRoutes } from './routes/interviews.mjs'; import { Interviews } from './interviews.mjs'; @@ -264,6 +265,18 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA | // #132: barras de objetivo con el total real del canal (persisten entre directos) const channelTotals = await new ChannelTotals({ dir: store.dir, twitch, youtube, log }).load(); const followers = await new FollowerRegistry({ dir: store.dir, twitch, youtube, log }).load(); + // #357: last supporters of every stream, apart from sessions; rebuilt from the archives when missing. + const latestHistory = await new LatestHistory({ dir: store.dir, log }).load(); + const backfillLatest = async () => { + const events = []; + for (const meta of await session.list({ limit: Infinity })) { + try { events.push(...((await session.getArchived(meta.id)).events || [])); } catch { /* unreadable archive: skipped */ } + } + events.push(...(session.data.events || [])); + await latestHistory.merge(events); + }; + if (latestHistory.needsBackfill) await backfillLatest(); + engine.latestHistory = latestHistory; // Session.list is asynchronous; snapshots stay synchronous and only use this cached cutoff. let lastStreamCutoff = null, cutoffGeneration = 0; const refreshLastStream = async () => { @@ -360,6 +373,7 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA | chat.on('delete', ({ id }) => engine.deleteChat(id)); chat.on('clearUser', ({ login }) => engine.clearChatUser(login)); session.on('change', change => { + if (change?.event) latestHistory.observe(change.event); engine.pushWidgets(); pushTimeline(); if (change?.reset) refreshLastStream().then(() => engine.pushWidgets()).catch(() => {}); }); @@ -1028,7 +1042,7 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA | // Export v1 excludes credentials; import previews the same strict schema before a local backup. const configTransfer = registerConfigTransferRoutes({ route, store, customOverlays, afterConfig, mediaDir, configTransferIO, zipUploadLimit, zipExportLimit, session, retention: () => Number(store.config.sessions?.retention) || 0, - afterSessions: () => refreshLastStream().then(() => engine.pushWidgets()).catch(() => {}) }); + afterSessions: () => Promise.all([refreshLastStream(), backfillLatest()]).then(() => engine.pushWidgets()).catch(() => {}) }); let mediaQueue = Promise.resolve(); const withMediaLock = async fn => { const previous = mediaQueue; let release; mediaQueue = new Promise(resolve => { release = resolve; }); @@ -1607,7 +1621,7 @@ export async function createApp({ dataDir, mediaDir = process.env.ANTENA_MEDIA | return httpClosePromise; }; - const app = { server, store, bus, twitch, youtube, chat, meld, program, session, engine, timers, interactive, viewers, channelTotals, followers, refreshFollowers, teleprompter, interviews, customOverlays, mediaDir, port: null, stopAdmission, closeHttp, isHttpClosing, closeUpgradedConnections, beginAckWindow, captureAckWindow, closeAckWindow, ackWindowPhase, waitIdle: whenIdle, beginLayerHideDrain, drainLayerHides, beginAutoSessionDrain, drainAutoSession, drainChatMetrics, settleChatMetrics }; + const app = { latestHistory, server, store, bus, twitch, youtube, chat, meld, program, session, engine, timers, interactive, viewers, channelTotals, followers, refreshFollowers, teleprompter, interviews, customOverlays, mediaDir, port: null, stopAdmission, closeHttp, isHttpClosing, closeUpgradedConnections, beginAckWindow, captureAckWindow, closeAckWindow, ackWindowPhase, waitIdle: whenIdle, beginLayerHideDrain, drainLayerHides, beginAutoSessionDrain, drainAutoSession, drainChatMetrics, settleChatMetrics }; return app; } diff --git a/src/session.mjs b/src/session.mjs index 2d2c73e..fc84bfc 100644 --- a/src/session.mjs +++ b/src/session.mjs @@ -9,6 +9,7 @@ import { writeJson, serialize } from './json-file.mjs'; import { ALERT_TYPES, isSystemType } from './alerts.mjs'; import { splitEventsOffsets, platformValue } from './goals.mjs'; import { isTotalMetric } from './channel-totals.mjs'; +import { latestOf } from './latest-history.mjs'; // El resumen conserva su zona histórica; solo se fija el formato visible (#126). const summaryDateFormat = new Intl.DateTimeFormat('en-GB', { @@ -455,9 +456,10 @@ export class Session extends EventEmitter { } /** Registra una alerta real (no pruebas). */ - record(alert) { + record(alert, { simulated = false } = {}) { const ev = { id: alert.id, type: alert.type, at: alert.at, user: alert.vars?.user || alert.text, vars: alert.vars || {}, text: alert.text, sub: alert.sub, variation: alert.variation?.name || null }; if (isSystemType(alert.type)) ev.thanked = true; // un récord no se agradece a nadie + if (simulated) ev.simulated = true; // #357: a test, never part of the historical «Últimos» this.data.events.push(ev); this.save(); this.emit('change', { event: ev }); @@ -1007,13 +1009,7 @@ export class Session extends EventEmitter { t.superchats = Math.round(t.superchats * 100) / 100; return t; } - latest(data = this.data) { - const last = types => [...data.events].reverse().find(e => types.includes(e.type)) || null; - return { - follow: last(['follow', 'ytsub']), sub: last(['sub', 'resub', 'giftsub']), cheer: last(['cheer']), raid: last(['raid']), - superchat: last(['superchat', 'supersticker']), member: last(['member', 'milestone', 'giftmember']), any: [...data.events].reverse().find(e => !isSystemType(e.type)) || null, - }; - } + latest(data = this.data) { return latestOf(data.events); } goalValue(metric, platform) { // Barras con total del canal (#132): el valor lo da src/channel-totals.mjs (total de la // plataforma + corrección persistente); los goalOffsets de sesión ya no se aplican a ellas. diff --git a/src/store.mjs b/src/store.mjs index 197f037..131248b 100644 --- a/src/store.mjs +++ b/src/store.mjs @@ -60,7 +60,7 @@ export const DEFAULT_CONFIG = { chat: { platforms: ['twitch', 'youtube'], maxMessages: 12, fadeAfterSec: 0, fontSize: 26, hideCommands: true, hideOwner: true, showPlatform: true, reverse: false, animIn: 'slide', animOut: 'slide', layout: 'vertical', css: '' }, // hideOwner: tus mensajes no salen en pantalla; animIn/animOut #130 chatVariants: [], goals: [{ id: 'principal', title: 'Objetivo de seguidores', visible: true, showMetric: true, css: '', bars: [{ id: 'principal-1', platform: 'twitch', metric: 'follows', target: 20, visible: true }] }], - latest: { items: ['follow', 'sub', 'cheer', 'superchat'], label: '', css: '' }, + latest: { items: ['follow', 'sub', 'cheer', 'superchat'], label: '', scope: 'stream', css: '' }, ticker: { label: 'Gracias a', count: 15, speed: 70, css: '' }, viewers: { platforms: ['twitch', 'youtube'], showTotal: true, showPeak: false, css: '' }, // espectadores a la vez por plataforma thanks: { title: 'Gracias por seguir', platforms: ['twitch', 'youtube'], window: 'lastStream', days: 30, maxNames: 20, intervalSec: 5, showAnonymous: true, css: '' }, diff --git a/test/groups.json b/test/groups.json index 4130ad7..41c4807 100644 --- a/test/groups.json +++ b/test/groups.json @@ -50,6 +50,7 @@ "test/interviews-mcp.test.mjs", "test/interviews.test.mjs", "test/lan-key.test.mjs", + "test/latest-history.test.mjs", "test/latest-ticker-types.test.mjs", "test/legacy-retirement.test.mjs", "test/live-load-race.test.mjs", @@ -203,6 +204,7 @@ "test/interview-rounds-browser.test.mjs", "test/interview-stop-layout-browser.test.mjs", "test/interview-widget-browser.test.mjs", + "test/latest-history-browser.test.mjs", "test/latest-ticker-panel-browser.test.mjs", "test/live-selectors.test.mjs", "test/manual-discard-browser.test.mjs", diff --git a/test/latest-history-browser.test.mjs b/test/latest-history-browser.test.mjs new file mode 100644 index 0000000..08c361a --- /dev/null +++ b/test/latest-history-browser.test.mjs @@ -0,0 +1,55 @@ +// #357 in Chrome: the «Mostrar» selector of «Últimos» switches the widget between this stream and all streams. +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, openChromePage, skipIfNoBrowserOrUi, waitDom } from './helpers/react-browser.mjs'; +import { evaluateChrome } from './helpers/chrome-dom.mjs'; + +test('«Mostrar» switches «Últimos» between this stream and the historical record', { timeout: 120000 }, async t => { + const bin = await skipIfNoBrowserOrUi(t); + if (!bin) return; + const dataDir = await mkdtemp(path.join(tmpdir(), 'antena-latest-history-browser-')); + t.after(() => rm(dataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })); + const app = await createApp({ dataDir, mediaDir: path.join(dataDir, 'media'), log: () => {} }); + await new Promise(r => app.server.listen(0, '127.0.0.1', r)); + const base = `http://127.0.0.1:${app.server.address().port}`; + const call = async (method, url, body) => { const r = await fetch(base + url, { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); assert.equal(r.status, 200, url); }; + const widgets = async () => (await (await fetch(base + '/api/widgets')).json()).widgets; + const until = async (fn, what) => { for (let i = 0; i < 60; i++) { if (await fn()) return; await new Promise(r => setTimeout(r, 100)); } assert.fail(what); }; + const big = `document.querySelector('#root .item-follow .big')?.textContent`; + const chromes = []; + try { + await call('PUT', '/api/config', { panel: { onboardingDone: true } }); + app.engine.handleEvent({ externalId: 'real:follow:Ana', type: 'follow', vars: { user: 'Ana' } }); + await call('POST', '/api/session/new', { title: 'Nuevo directo' }); + + // The widget follows the saved scope: this stream starts empty, the record keeps Ana. + const widget = await openChromePage(bin, base + '/widget/latest'); + chromes.push(widget); + await waitDom(widget.cdp, `${big} === '—'`, { timeoutMs: 10000 }); + + // Panel: «Mostrar» starts on «Este directo»; choosing «Histórico» and saving stores scope «all». + const panel = await openChromePage(bin, base + '/#/widgets/latest'); + chromes.push(panel); + const c = panel.cdp, ev = s => evaluateChrome(c, s); + const select = `[...document.querySelectorAll('main label')].find(l => l.textContent.trim().startsWith('Mostrar'))?.querySelector('select')`; + await waitDom(c, `!!(${select})`, { timeoutMs: 15000 }); + assert.equal(await ev(`${select}.value`), 'stream'); + assert.deepEqual(await ev(`[...${select}.options].map(o => o.textContent)`), ['Este directo', 'Histórico']); + await ev(`(() => { const s = ${select}; Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value').set.call(s, 'all'); s.dispatchEvent(new Event('change', { bubbles: true })); return true; })()`); + const save = `[...document.querySelectorAll('button')].find(b => /^Guardar/.test(b.textContent.trim()) && !b.disabled)`; + await waitDom(c, `!!(${save})`, { timeoutMs: 5000 }); + await ev(`${save}.click(); true`); + await until(async () => (await widgets()).latest.scope === 'all', 'the scope was not saved'); + await waitDom(widget.cdp, `${big} === 'Ana'`, { timeoutMs: 10000 }); + + // Back to this stream: the card is empty again. + await call('PUT', '/api/widgets', { latest: { scope: 'stream' } }); + await waitDom(widget.cdp, `${big} === '—'`, { timeoutMs: 10000 }); + } finally { + await closeAll(...chromes.map(ch => () => closeChrome(ch)), () => new Promise(r => { app.viewers.stop(); app.meld.stop(); app.server.closeAllConnections(); app.server.close(r); })); + } +}); diff --git a/test/latest-history.test.mjs b/test/latest-history.test.mjs new file mode 100644 index 0000000..9fde7ee --- /dev/null +++ b/test/latest-history.test.mjs @@ -0,0 +1,99 @@ +// #357: «Últimos» can show the last supporter of each type across all streams. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, rm, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createApp } from '../src/server.mjs'; +import { DEFAULT_CONFIG } from '../src/store.mjs'; + +async function start(dataDir) { + const app = await createApp({ dataDir, mediaDir: path.join(dataDir, 'media'), log: () => {} }); + await new Promise(r => app.server.listen(0, '127.0.0.1', r)); + const base = `http://127.0.0.1:${app.server.address().port}`; + const call = async (method, url, body) => { + const r = await fetch(base + url, { method, headers: { 'content-type': 'application/json' }, body: body && JSON.stringify(body) }); + return { status: r.status, body: await r.json() }; + }; + const state = async () => (await call('GET', '/api/widgets')).body; + const real = (type, user, extra = {}) => app.engine.handleEvent({ externalId: `real:${type}:${user}`, type, vars: { user, ...extra } }); + const stop = async () => { await app.session.flush(); await app.latestHistory.flush(); await new Promise(r => { app.viewers.stop(); app.meld.stop(); app.server.closeAllConnections(); app.server.close(r); }); }; + return { app, call, state, real, stop }; +} +const who = entry => entry?.user ?? null; +const users = latest => Object.fromEntries(Object.entries(latest).map(([k, v]) => [k, who(v)])); + +async function dir(t) { + const d = await mkdtemp(path.join(tmpdir(), 'antena-latest-history-')); + t.after(() => rm(d, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })); + return d; +} + +test('the historical record keeps the last supporters across streams and restarts; the per-stream one resets', async t => { + const dataDir = await dir(t); + let a = await start(dataDir); + try { + a.real('follow', 'Ana'); a.real('sub', 'Bea'); a.real('superchat', 'Cris', { amount: 5, amountText: '5 €' }); + await a.call('POST', '/api/session/new', { title: 'Next stream' }); + a.real('raid', 'Dani', { viewers: 12 }); + const s = await a.state(); + assert.deepEqual(users(s.latest), { follow: null, sub: null, cheer: null, raid: 'Dani', superchat: null, member: null, any: 'Dani' }); + assert.deepEqual(users(s.latestAll), { follow: 'Ana', sub: 'Bea', cheer: null, raid: 'Dani', superchat: 'Cris', member: null, any: 'Dani' }); + assert.equal(s.latestAll.superchat.vars.amountText, '5 €'); + } finally { await a.stop(); } + a = await start(dataDir); + try { + const s = await a.state(); + assert.deepEqual(users(s.latestAll), { follow: 'Ana', sub: 'Bea', cheer: null, raid: 'Dani', superchat: 'Cris', member: null, any: 'Dani' }, 'survives a restart'); + } finally { await a.stop(); } +}); + +test('simulated alerts count for the current stream but never for the historical record', async t => { + const dataDir = await dir(t); + const a = await start(dataDir); + try { + a.real('follow', 'Ana'); + const sim = await a.call('POST', '/api/simulate', { type: 'follow', vars: { user: 'Prueba' } }); + assert.equal(sim.status, 200); + const s = await a.state(); + assert.equal(who(s.latest.follow), 'Prueba'); + assert.equal(who(s.latestAll.follow), 'Ana'); + assert.equal(who(s.latestAll.any), 'Ana'); + } finally { await a.stop(); } +}); + +test('a missing record is rebuilt once from the archived and current streams, newest first', async t => { + const dataDir = await dir(t); + let a = await start(dataDir); + try { + a.real('follow', 'Old'); a.real('cheer', 'Bits', { amount: 100 }); + await a.call('POST', '/api/session/new', {}); + await new Promise(r => setTimeout(r, 20)); + a.real('follow', 'New'); a.real('member', 'Socio'); + } finally { await a.stop(); } + await rm(path.join(dataDir, 'latest-history.json'), { force: true }); // an install from before #357 + a = await start(dataDir); + try { + const s = await a.state(); + assert.deepEqual(users(s.latestAll), { follow: 'New', sub: null, cheer: 'Bits', raid: null, superchat: null, member: 'Socio', any: 'Socio' }); + } finally { await a.stop(); } + const saved = JSON.parse(await readFile(path.join(dataDir, 'latest-history.json'), 'utf8')); + assert.equal(saved.entries.follow.user, 'New'); +}); + +test('«Últimos» scope defaults to the current stream, accepts «all» and rejects anything else', async t => { + assert.equal(DEFAULT_CONFIG.widgets.latest.scope, 'stream'); + const dataDir = await dir(t); + const a = await start(dataDir); + try { + assert.equal((await a.state()).widgets.latest.scope, 'stream'); + assert.equal((await a.call('PUT', '/api/widgets', { latest: { scope: 'all' } })).status, 200); + assert.equal((await a.state()).widgets.latest.scope, 'all'); + const bad = await a.call('PUT', '/api/widgets', { latest: { scope: 'forever' } }); + assert.equal(bad.status, 400); + assert.equal((await a.state()).widgets.latest.scope, 'all', 'a rejected value leaves the saved one'); + const viaConfig = await a.call('PUT', '/api/config', { widgets: { latest: { scope: 'stream' } } }); + assert.equal(viaConfig.status, 200, JSON.stringify(viaConfig.body)); + assert.equal((await a.state()).widgets.latest.scope, 'stream'); + } finally { await a.stop(); } +});