heystreamer/public/alerts/polaroid.js
Bashy c481ca92cb Stats per stream and period, public stats page, dashboard settings, Card alert style
Statistics
- Per day and per stream statistics (src/periodstats.js, one generic stat_day table), backfilled
  once from the older tables; Stream / Week / Month / Year / All time views, Community and Streams tabs.
- Viewer count every 5 minutes and title / category history per stream (EventSub channel.update):
  viewer graph, games played (donut), games in the streams list.
- Twitch sync (src/twitchsync.js): followers with follow dates, current subs, mods, VIPs, all-time
  bits, channel emotes, past streams from VODs. Twitch analytics CSV import (src/twitchcsv.js).
- Public stats page on its own host (Settings -> Stats and data): no message text, no bots,
  !hideme / !showme opt-out. Viewer page: roles, follow age, sub status, bits, a menu for rarely used actions.
- StreamElements watch-time importer removed (already imported minutes stay as a baseline).

Dashboard
- Settings and Actions with a left sidebar; each settings page saves only its own fields.
  Connections (Twitch, StreamElements token now set here, HUDFX), OBS links (hidden behind an eye
  toggle) with a link builder, Chat (sound picked from the media library), TTS, Stats and data,
  Backup (export / import the whole setup), Advanced. Time zone setting for the stats pages.
- Actions -> Alerts: alert style, pictures, sounds, bits tiers and card colours, stored in the
  database (src/theme.js); an old file-based theme is imported once. Alert preview page
  (/actions/alerts/preview, tools/preview/export.js for a static copy).
- Old /actions page removed; Actions = Redeems / Alerts / TTS voices / Media.

Alerts
- New plain Card style for everyone (public/alerts/card.js); Polaroid, Cassette and the TTS letter
  stay as optional looks. Redeem variations can be Card, Cassette, Sound only or Video.

Repo
- No channel data in git: the channel's art, stickers and sounds stay on disk (gitignored) and are
  picked in the dashboard; examples for the server config (apache.example.sh, .env.example).

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

374 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
Polaroid alerts for the OBS overlay.
window.PolaroidAlerts.play(alert) queue an alert (never overlaps)
window.PolaroidAlerts.playTest(alert) test alert: replaces a showing/queued TEST alert at once,
but never interrupts or drops a real one (it queues behind it).
A real alert cuts off a test that is showing.
window.PolaroidAlerts.reset() stop the current alert and clear the queue
window.PolaroidAlerts.skip() stop the current alert (e.g. a TTS message), carry on with the queue
Alert shapes come from src/alerts.js:
{ type:'follow', user }
{ type:'sub', user, tier, prime, months, duration, message }
{ type:'gift', user|null, total, recipient, tier }
{ type:'streak', user, streak }
{ type:'raid', user, viewers }
{ type:'bits', user|null, bits, message }
{ type:'tip', user, amount, currency, message } (StreamElements)
{ type:'hype', phase:'begin'|'level'|'end', level, golden, treasure, top } (Hype Train v2)
{ type:'redeem', kind, key, user, reward, variation, rarity, input, caption, sound (URL), volume, polaroid, art }
channel point rewards / Power-ups, configured on the dashboard Redeems page; drawn as a
cassette tape by cassette.js (polaroid:false = sound only, art = sticker URL)
Everything per event (art, caption, tape colour, badge, sound) is in describe() below.
*/
(function () {
// ===================== CONFIG =====================
const BASE = window.ALERTS_BASE || '/alerts/'; // ALERTS_BASE: only set by offline test pages
const rebase = u => (u && u.startsWith('/alerts/') && BASE !== '/alerts/') ? BASE + u.slice(8) : u;
// pictures and sounds are URLs from the Media library (Actions → Alerts); bare names = old files in public/alerts/art|sounds
const ART = n => !n ? '' : /^(https?:)?\/\//.test(n) ? n : n.startsWith('/') ? rebase(n) : `${BASE}art/${n}`;
const SND = n => `${BASE}sounds/${n}`;
const DEFAULT_VOLUME = 0.8;
const TAPE = {
follow:'rgba(201,182,228,.88)', sub:'rgba(244,160,168,.88)', prime:'rgba(140,200,240,.88)',
gift:'rgba(150,215,180,.88)', streak:'rgba(246,206,110,.9)', raid:'rgba(250,170,120,.88)',
bits:'rgba(190,160,240,.88)', redeem:'rgba(140,215,215,.88)',
};
// The channel's alert theme (src/theme.js, edited on Actions → Alerts) arrives with the overlay settings and is read
// per alert, so a save in the dashboard is used by the next alert without reloading OBS.
const TH = () => (window.S && window.S.alert_theme) || {};
const SOUND_MS = {}; // sound lengths are measured in the browser once (soundLength)
const RANGES = { photoTilt:[2,7], tape1:[-42,-18], tape2:[18,42], tapeX:[-12,12], tapeY:[-6,6],
heart:[-8,26], heartX:[-10,6], heartY:[-14,8], badge:[-18,14] };
const AFTER_ANIM = 3000; // ms the finished polaroid stays up after its entrance animation
const SOUND_LEAD = 400; // ms after the photo starts dropping that the sound starts
const GAP = 600; // ms between queued alerts
// Event -> what the polaroid shows. null = no alert.
function describe(e) {
const th = TH(), THA = th.art || {}, THS = th.sounds || {};
const BITS_MIN = th.bitsMin ?? 1, BITS_TIERS = th.bitsTiers || [];
const who = e.user || (e.type === 'gift' ? 'An anonymous gifter' : 'Someone');
switch (e.type) {
case 'follow':
return { art:THA.follow, name:who, line:'just followed! ♡', tape:TAPE.follow, sound:THS.follow };
case 'sub': {
const months = e.months || 1, dur = e.duration || 1, multi = dur > 1;
const tier = e.prime ? '' : ({ '2000':'Tier 2', '3000':'Tier 3' }[e.tier] || '');
const atTier = tier ? ` at ${tier}` : '';
let line;
if (multi) line = `subscribed${atTier} for ${dur} months at once! ♡`;
else if (e.prime) line = months > 1 ? `resubscribed with Prime for ${months} months! ♛` : 'subscribed with Prime! ♛';
else if (months > 1) line = `resubscribed${atTier} for ${months} months! ♡`;
else line = `just subscribed${atTier}! ♡`;
const art = e.prime ? THA.prime : (months > 1 || multi ? THA.resub : THA.sub);
return { art, name:who, line, msg:e.message, tape:e.prime ? TAPE.prime : TAPE.sub, sound:THS.sub,
stack: multi ? Math.min(dur - 1, 5) : 0,
badge: multi ? { big:`${dur}×`, small:'months' } : months > 1 ? { big:months, small:'months' } : null,
phbg: e.prime ? 'linear-gradient(#e3f2ff,#bcdcf5)' : null };
}
case 'gift': {
const n = e.total || 1;
return { art:THA.gift, name:who,
line: n > 1 ? `gifted ${n} subs to the community! ♡`
: (e.recipient ? `gifted a sub to ${e.recipient}! ♡` : 'gifted a sub! ♡'),
tape:TAPE.gift, sound:THS.gift, stack: n > 1 ? Math.min(n - 1, 3) : 0,
badge: n > 1 ? { big:`×${n}`, small:'subs' } : null, phbg:'linear-gradient(#e2f6ea,#bfe6cf)' };
}
case 'streak':
return { art:THA.streak, name:who, line:`is on a ${e.streak}-stream watch streak!`,
tape:TAPE.streak, sound:THS.streak, badge:{ big:e.streak, small:'streams' }, phbg:'linear-gradient(#fff4d6,#f7deb0)' };
case 'raid':
return { art:THA.raid, name:who, line:`is raiding with ${e.viewers} viewers!`,
tape:TAPE.raid, sound:THS.raid, badge:{ big:e.viewers, small:'raiders' },
phbg:'linear-gradient(#ffe6d6,#f8c8a8)', stack:2 };
case 'tip': {
// StreamElements tip: amount in its own currency, extra hearts for bigger tips
let money;
try { money = new Intl.NumberFormat('en', { style:'currency', currency:e.currency || 'USD', maximumFractionDigits: e.amount % 1 ? 2 : 0 }).format(e.amount); }
catch { money = `${e.amount} ${e.currency || ''}`.trim(); }
const hearts = e.amount >= 50 ? 3 : e.amount >= 25 ? 2 : e.amount >= 10 ? 1 : 0;
return { art:THA.tip, name:who, line:`tipped ${money}! ♡`, msg:e.message, sound:THS.tip,
tape:'rgba(246,206,110,.9)', badge:{ big:money, small:'tip', color:'#e0a21b' }, hearts,
phbg:'linear-gradient(#fff6dc,#fbe0a8)' };
}
case 'hype': {
// Hype Train: start / level up / end (art + sounds from the theme)
const name = e.golden ? 'Golden Kappa Train' : e.treasure ? 'Treasure Train' : 'Hype Train';
const line = e.phase === 'begin' ? 'is leaving the station! choo choo 🚂'
: e.phase === 'level' ? `reached level ${e.level}!` : `ended at level ${e.level}! ♡`;
const sound = { begin:THS.hypeBegin, level:THS.hypeLevel, end:THS.hypeEnd }[e.phase];
return { art:THA.hype, name, line, tape: e.golden ? 'rgba(246,206,110,.95)' : TAPE.raid, sound,
msg: e.phase === 'end' && e.top?.length ? `thank you ${e.top.join(', ')}!` : null,
badge:{ big:e.level, small:'level', color: e.golden ? '#d4a017' : '#e0457b' }, hearts: e.phase === 'end' ? 2 : 0,
stack: e.phase === 'end' ? 2 : 0, phbg: e.golden ? 'linear-gradient(#fff4d0,#f6d77a)' : 'linear-gradient(#ffe6d6,#f8c8a8)' };
}
case 'redeem': {
// shown as a cassette tape (cassette.js); polaroid:false = sound only
const fill = t => String(t || '').replace(/\{reward\}/g, e.reward || '').replace(/\{variation\}/g, e.variation || '');
return { cassette: true, style: e.style || 'cassette', emote: e.emote || null, sticker: rebase(e.art) || null, icon: e.icon || null,
name: e.user || 'Someone', line: fill(e.caption || 'redeemed it! ♡'), msg: e.input,
title: e.variation || e.reward, sub: e.reward, rarity: e.rarity,
sound: e.sound || null, volume: e.volume, soundOnly: e.polaroid === false && !e.tts,
tts: e.tts ? rebase(e.tts) : null, ttsMs: e.tts_ms || 0, ttsEnv: e.tts_env || [], ttsPrefix: e.tts_prefix || 0 };
}
case 'bits': {
if (!(e.bits >= BITS_MIN)) return null;
const t = BITS_TIERS.find(t => e.bits >= t.min) || BITS_TIERS[BITS_TIERS.length - 1] || { art:THA.follow, badge:'#8a8aa8', hearts:0 };
return { art:t.art, name:who, line:`cheered ${e.bits} bits!`, msg:e.message, tape:TAPE.bits, sound:t.sound,
badge:{ big:e.bits, small:'bits', color:t.badge }, hearts:t.hearts, volume:t.volume, phbg:'linear-gradient(#efe6ff,#d7c6f5)' };
}
}
return null;
}
// ===================== ENGINE =====================
const rnd = Math.random;
const between = ([a, b]) => a + rnd() * (b - a);
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
let el = null;
function root() {
if (!el) { el = document.createElement('div'); el.id = 'polaroid-alert'; document.body.appendChild(el); }
return el;
}
// preload images and sounds so the first alert of the stream is not blank or late
function preload() {
const th = TH();
const imgs = new Set([...(th.back || []), ...Object.values(th.art || {}), th.heart, ...(th.bitsTiers || []).map(t => t.art)].filter(Boolean));
imgs.forEach(n => { new Image().src = ART(n); });
Object.keys(SOUND_MS).forEach(n => { const a = new Audio(); a.preload = 'auto'; a.src = SND(n); });
}
// built-in sounds are file names, redeem sounds are URLs
const soundUrl = s => !s ? null : (s.startsWith('/') ? rebase(s) : SND(s));
const lengths = {};
// sound length in ms: known table, else measured once in the browser (max 3 s wait)
function soundLength(url) {
const base = decodeURIComponent(url.split('/').pop());
if (SOUND_MS[base]) return Promise.resolve(SOUND_MS[base]);
if (lengths[url] != null) return Promise.resolve(lengths[url]);
return new Promise(res => {
const a = new Audio(); a.preload = 'metadata';
const done = ms => { clearTimeout(t); res(lengths[url] = ms); };
const t = setTimeout(() => done(0), 3000);
a.addEventListener('loadedmetadata', () => done(isFinite(a.duration) ? a.duration * 1000 : 0), { once:true });
a.addEventListener('error', () => done(0), { once:true });
a.src = url;
});
}
const queue = [];
let busy = false, current = null, gen = 0;
function play(alert) {
const d = describe(alert);
if (!d) { console.log('[alerts] skipped', alert); return; }
d.test = !!alert.test;
if (!d.test) {
// a real alert is never delayed by tests: drop queued tests, cut a test that is on screen
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1);
if (current && current.test) skipCurrent();
}
queue.push(d);
if (!busy) next();
}
// stop what is on screen and carry on with the queue
function skipCurrent() {
gen++;
clearTimeout(current.timer);
if (current.audio) { current.audio.pause(); current.audio.currentTime = 0; }
current.anims.forEach(a => a.cancel());
current = null;
if (el) el.style.visibility = 'hidden';
window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide();
busy = false;
}
function playTest(alert) {
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1); // older tests: gone
if (current && current.test) skipCurrent(); // a test on screen: cut it
play({ ...alert, test: true }); // a real one on screen: wait
}
// dashboard Skip button: cut what is on screen (sound/TTS too), then play the next queued alert
function skip() {
if (!current) return;
skipCurrent();
setTimeout(() => { if (!busy) next(); }, GAP);
}
function reset() {
gen++;
queue.length = 0;
if (current) {
clearTimeout(current.timer);
if (current.audio) { current.audio.pause(); current.audio.currentTime = 0; }
current.anims.forEach(a => a.cancel());
current = null;
}
if (el) el.style.visibility = 'hidden';
window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide();
busy = false;
}
async function next() {
const d = queue.shift();
if (!d) { busy = false; return; }
busy = true;
const my = gen;
await show(d);
if (my !== gen) return;
setTimeout(() => { if (my === gen) next(); }, GAP);
}
function photoHTML(cls, art, inner) {
return `<div class="photo ${cls}"><div class="ph">${art ? `<img src="${ART(art)}" alt="">` : ''}</div>${inner}</div>`;
}
async function show(d) {
const el = root();
const cur = current = { anims:[], timer:null, audio:null, test:!!d.test };
const url = soundUrl(d.sound);
const len = url ? await soundLength(url) : 0;
if (cur !== current) return; // skipped while measuring the sound
// which look: Card (plain, everyone) or the optional Polaroid / Cassette / Letter (Actions → Alerts, Redeems)
const th = TH();
const asCard = window.CardAlert && !d.soundOnly && (
d.style === 'card' || // redeem variation set to Card
(d.style === 'tts' && th.ttsStyle !== 'letter') || // read-aloud redeem
(!d.cassette && !d.style && th.style !== 'polaroid')); // follow / sub / gift / raid / bits / tip / Hype Train
if (asCard) {
if (d.cassette) d.tag = d.title && d.sub && d.title !== d.sub ? `${d.sub} · ${d.title}` : (d.sub || d.title || '');
if (!d.sticker && d.cassette) d.sticker = ART(th.defaultSticker) || null;
return window.CardAlert.show(d, cur, { url, len, volume: d.volume ?? (th.volume ?? DEFAULT_VOLUME) })
.then(() => { if (current === cur) current = null; });
}
const fx = { emote: 'giant', emote_rain: 'rain', message: 'message', tts: 'envelope' }[d.style];
if (fx && !d.soundOnly && window.FxAlert) {
return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? (TH().volume ?? DEFAULT_VOLUME) })
.then(() => { if (current === cur) current = null; });
}
if (d.cassette && !d.soundOnly && window.CassetteAlert) {
return window.CassetteAlert.show(d, cur, { url, len, volume: d.volume ?? (TH().volume ?? DEFAULT_VOLUME) })
.then(() => { if (current === cur) current = null; });
}
if (d.soundOnly) { // no picture: play the sound, hold the queue for its length
if (!url) return;
const a = cur.audio = new Audio(url); a.volume = d.volume ?? (TH().volume ?? DEFAULT_VOLUME);
a.play().catch(err => console.warn('[alerts] sound blocked:', err.message));
const wait = el.animate([{}, {}], { duration: Math.max(len, 500) });
cur.anims.push(wait);
return wait.finished.then(() => { if (current === cur) current = null; }).catch(() => {});
}
const nameSize = d.name.length > 18 ? 32 : d.name.length > 14 ? 36 : 40;
const backArt = th.back && th.back.length ? th.back : [d.art]; // photos fanned out behind (theme), else the same one
const backs = Array.from({ length: d.stack || 0 }, (_, i) =>
photoHTML('back', backArt[i % backArt.length], '<div class="blank"></div>')).join('');
const heart = ART(th.heart); // corner sticker; none set = no stickers
const extraHearts = heart ? Array.from({ length: d.hearts || 0 }, () =>
`<img class="heart extra sticker" src="${heart}" alt="">`).join('') : '';
el.innerHTML = backs + `
<div class="photo main" style="--tape:${d.tape}${d.phbg ? ';--phbg:' + d.phbg : ''}">
<div class="tape t1"></div><div class="tape t2"></div>
<div class="ph${d.avatar ? ' avatar' : ''}">${d.art ? `<img src="${ART(d.art)}" alt="">` : `<span class="ini">${esc((d.name || '♥').trim()[0] || '♥').toUpperCase()}</span>`}${d.tag ? `<span class="tag">${esc(d.tag)}</span>` : ''}</div>
<div class="cap"><span class="u" style="font-size:${nameSize}px">${esc(d.name)}</span>${esc(d.line)}${d.msg ? `<span class="msg">“${esc(d.msg)}”</span>` : ''}</div>
${heart ? `<img class="heart sticker" src="${heart}" alt="">` : ''}
${extraHearts}
${d.badge ? `<div class="badge" style="${d.badge.color ? '--badge:' + d.badge.color : ''}">${esc(d.badge.big)}<small>${esc(d.badge.small)}</small></div>` : ''}
</div>`;
el.style.visibility = 'visible';
const q = s => el.querySelector(s);
const main = q('.photo.main');
const tilt = between(RANGES.photoTilt) * (rnd() < .5 ? -1 : 1);
const rot = dd => `rotate(${tilt + dd}deg)`;
const anims = cur.anims;
const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); anims.push(a); return a; };
// fanned stack behind the main photo (multi-month subs, community gifts, raids)
const backEls = [...el.querySelectorAll('.photo.back')];
const t0 = backEls.length ? 120 * backEls.length + 150 : 0;
backEls.forEach((b, i) => {
const ang = 4 + i * 4 + between([-2, 2]), dx = 24 + i * 26 + between([-4, 4]), dy = i * 5 + between([-4, 4]);
A(b, [
{ transform:`translate(${dx}px,${dy - 150}px) rotate(${ang * 2}deg)`, opacity:0 },
{ transform:`translate(${dx}px,${dy}px) rotate(${ang}deg)`, opacity:1 },
], { delay:i * 120, duration:450, easing:'cubic-bezier(.2,.8,.3,1)' });
});
// 1. photo drops in
A(main, [
{ transform:`translateY(-160px) rotate(${tilt * -2.5}deg) scale(1.15)`, opacity:0 },
{ transform:`translateY(10px) ${rot(tilt > 0 ? 1.5 : -1.5)} scale(.99)`, opacity:1, offset:.7 },
{ transform:`translateY(0) ${rot(0)} scale(1)`, opacity:1 },
], { delay:t0, duration:750, easing:'cubic-bezier(.2,.8,.3,1)' });
const nudge = (at, dx) => A(main, [
{ transform:`translateY(0) ${rot(0)}` }, { transform:`translateY(3px) ${rot(dx)}` }, { transform:`translateY(0) ${rot(0)}` },
], { delay:at, duration:220, easing:'ease-out', fill:'none' });
// 2. tapes press on
const tapeT = (x, y, a, s) => `translate(${x}px,${y}px) rotate(${a}deg) scale(${s})`;
const stick = (node, a, at) => {
const x = between(RANGES.tapeX), y = between(RANGES.tapeY);
A(node, [
{ transform:tapeT(x, y - 30, a - 8, 1.35), opacity:0 },
{ transform:tapeT(x, y, a, .94), opacity:1, offset:.75 },
{ transform:tapeT(x, y, a, 1), opacity:1 },
], { delay:at, duration:260, easing:'cubic-bezier(.3,.7,.4,1)' });
};
stick(q('.t1'), between(RANGES.tape1), t0 + 800); nudge(t0 + 1000, -.6);
stick(q('.t2'), between(RANGES.tape2), t0 + 1080); nudge(t0 + 1280, .6);
// 3. stickers slap on
const slap = (node, at, x, y, a) => A(node, [
{ transform:`translate(${x}px,${y}px) rotate(${a - 40}deg) scale(0)`, opacity:0 },
{ transform:`translate(${x}px,${y}px) rotate(${a + 6}deg) scale(1.25)`, opacity:1, offset:.6 },
{ transform:`translate(${x}px,${y}px) rotate(${a - 2}deg) scale(.92)`, opacity:1, offset:.82 },
{ transform:`translate(${x}px,${y}px) rotate(${a}deg) scale(1)`, opacity:1 },
], { delay:at, duration:420, easing:'ease-out' });
if (q('.heart:not(.extra)')) slap(q('.heart:not(.extra)'), t0 + 1450, between(RANGES.heartX), between(RANGES.heartY), between(RANGES.heart));
nudge(t0 + 1650, tilt > 0 ? .8 : -.8);
[...el.querySelectorAll('.heart.extra')].forEach((h, i) =>
slap(h, t0 + 1600 + i * 160, between([-20, 10]), -110 - i * 95 + between([-15, 15]), between([-25, 25])));
const badge = q('.badge');
if (badge) slap(badge, t0 + 1250, 0, 0, between(RANGES.badge));
// 4. caption writes in
A(q('.cap'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }],
{ delay:t0 + 1700, duration:700, easing:'ease-in-out' });
// stays up: entrance animation + 3 s, or until the sound has finished if that is later
const animEnd = t0 + 2400; // caption done writing
const soundEnd = url ? t0 + SOUND_LEAD + len : 0;
if (url) {
const a = new Audio(url); a.volume = d.volume ?? (TH().volume ?? DEFAULT_VOLUME);
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + SOUND_LEAD);
}
// 5. exit: lift and drop away
const exitAt = Math.max(animEnd + AFTER_ANIM, soundEnd);
const exit = A(el, [
{ transform:'translateY(0) rotate(0) scale(1)', opacity:1 },
{ transform:'translateY(-20px) rotate(0deg) scale(1.04)', opacity:1, offset:.25 },
{ transform:`translateY(140px) rotate(${tilt > 0 ? 14 : -14}deg) scale(.9)`, opacity:0 },
], { delay:exitAt, duration:650, easing:'ease-in' });
return exit.finished
.then(() => { el.style.visibility = 'hidden'; anims.forEach(a => a.cancel()); if (current === cur) current = null; })
.catch(() => {}); // cancelled by reset()
}
window.PolaroidAlerts = { play, playTest, reset, skip, describe };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload();
})();