Add polaroid alerts for follows, subs, gifts, streaks, raids and bits

Overlay
- public/alerts/polaroid.js + .css: animated polaroid (photo drops in, tape
  and heart stick on, caption writes in), randomized angles, per-event art,
  caption, tape colour, badge and sound, fanned photo stack for multi-month
  subs / community gifts / raids, and a queue so alerts never overlap.
- Bits: no alert under 5; sound tiers at 5/50/75/100/150/250.
- Watch streaks are read from chat (USERNOTICE viewermilestone) and reported
  to the server over the overlay WebSocket.

Server
- Subscribe to channel.chat.notification instead of channel.subscribe /
  subscription.message / subscription.gift / channel.raid: one event with
  Prime, months bought at once, gift recipient, resub message and community
  gift totals. Per-recipient gift notices of a gift bomb are skipped, so a
  bomb is one alert (was N+1). Needs the user:read:chat scope (log in again).
- src/alerts.js maps Twitch events to alerts, broadcasts them and still runs
  them through dispatch (activity log + existing actions).
- EventSub starts on boot from the stored login (alerts survive restarts),
  validates the token hourly and refreshes it on expiry or 401, follows
  session_reconnect without dropping events, and reconnects when keepalives
  stop.
- The overlay WebSocket only accepts chat_notice messages from connections
  that pass the overlay UUID; streak notices are deduped by message id.

Dashboard
- Twitch connection status and a test button per alert (POST /alerts/test/:key).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-20 19:57:36 +02:00
parent 88e906ff5d
commit d481fc4f69
16 changed files with 773 additions and 83 deletions

View file

@ -121,6 +121,7 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
| POST | `/layout/positions` | routers/layout.js | JSON position update (legacy, kept for future drag) | | POST | `/layout/positions` | routers/layout.js | JSON position update (legacy, kept for future drag) |
| GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS; broadcasts settings_update on save | | GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS; broadcasts settings_update on save |
| POST | `/settings/reconnect` | routers/settings.js | Restart EventSub | | POST | `/settings/reconnect` | routers/settings.js | Restart EventSub |
| POST | `/alerts/test/:key` | routers/alerts.js | Send a sample polaroid alert to the overlay |
## Overlay CSS variable system ## Overlay CSS variable system
@ -176,17 +177,38 @@ activity_log — append-only event log
## EventSub subscriptions ## EventSub subscriptions
| Twitch event | Version | Condition | Scope | | Twitch event | Version | Condition | Scope | Used for |
|---|---|---|---| |---|---|---|---|---|
| `channel.subscribe` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | | `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | follow alert |
| `channel.subscription.message` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | | `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` | bits alert |
| `channel.subscription.gift` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | | `channel.chat.notification` | 1 | `broadcaster_user_id` + `user_id` | `user:read:chat` | subs, resubs, Prime, multi-month, gifts, community gifts, raids |
| `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` | | `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | actions only (no polaroid yet) |
| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` |
| `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` |
| `channel.raid` | 1 | `to_broadcaster_user_id` | none |
Token refresh triggered on 401 during subscription. `channel.chat.notification` replaced `channel.subscribe` / `subscription.message` / `subscription.gift` / `channel.raid`:
one event carries `is_prime`, `duration_months` (months bought at once), `cumulative_months`, the gift recipient,
community gift totals and the resub message. `sub_gift` notices with a `community_gift_id` are skipped (the
`community_sub_gift` notice covers the whole bomb), so a gift bomb is one alert.
**Lifecycle (src/eventsub.js, src/twitch.js):**
- Started on boot from the stored login (`db.getPrimaryUser()`), and again after OAuth login. `EVENTSUB_DISABLED=1` skips it (local UI work).
- Token: validated hourly and before subscribing; refreshed when it expires or on any 401 (`twitch.helix()`), new tokens saved to `users`.
- `session_reconnect`: connects to the given URL (subscriptions carry over), swaps sockets on its welcome.
- Keepalive watchdog: no message for `keepalive_timeout_seconds + 10s` → reconnect.
- Status (connected / subscribed / failed / last event) shown on the dashboard.
## Polaroid alerts
```
Twitch EventSub ─► eventsub.js ─► alerts.js (fromFollow / fromCheer / fromChatNotification) ─► alerts.send()
Overlay chat (tmi.js USERNOTICE viewermilestone) ─► WS up {type:'chat_notice'} ─► alerts.fromOverlayNotice() ─┘
alerts.send() ─► ws.broadcast({type:'alert', alert}) ─► overlay ─► public/alerts/polaroid.js (queue + animation + sound)
└─► dispatch.dispatchEvent() (activity log + legacy actions keep working)
```
- Alert shape and per-event look (art, caption, tape colour, badge, sound, bits tiers) live in `public/alerts/polaroid.js` (`describe()` + CONFIG block). Art in `public/alerts/art/`, sounds in `public/alerts/sounds/` (lengths in `SOUND_MS`, so the alert holds for the whole sound).
- Watch streaks only exist in chat. The overlay reports them; the server only accepts `chat_notice` from WS connections that pass `?overlay=<overlay_id>` and dedupes by message id (several overlays may report the same notice).
- Test buttons on the dashboard: `POST /alerts/test/:key` (keys = `alerts.TEST_KEYS`). Test alerts (`test:true`) replace what is showing; `queue-test` sends four that queue. Not logged, no actions fired.
- Bits under 5: no alert (`BITS_MIN`).
## Production deployment ## Production deployment

View file

@ -0,0 +1,33 @@
/* Polaroid alerts (see polaroid.js). Fonts: Caveat (loaded by overlay.ejs). */
#polaroid-alert { --red:#b74347; --ink:#3a2a20;
position:fixed; left:85px; top:90px; width:340px; visibility:hidden; z-index:50; }
#polaroid-alert .photo { position:absolute; left:0; top:0; width:340px; padding:18px 18px 0; background:#fffdf7;
box-shadow:0 14px 30px rgba(0,0,0,.45); transform-origin:50% 40%; box-sizing:content-box; }
#polaroid-alert .photo.main { position:relative; }
#polaroid-alert .ph { height:290px; background:var(--phbg, linear-gradient(#ffd9e0,#f8c3cf)); position:relative; overflow:hidden; }
#polaroid-alert .ph img { position:absolute; bottom:0; left:50%; transform:translateX(-50%); width:300px; display:block; }
#polaroid-alert .back .blank { height:70px; }
#polaroid-alert .cap { font:700 34px/1.05 'Caveat', cursive; color:var(--ink); text-align:center; padding:14px 34px 20px; }
#polaroid-alert .cap .u { color:var(--red); display:block; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#polaroid-alert .cap .msg { font-size:24px; line-height:1.1; color:#7a6656; margin-top:6px;
overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
#polaroid-alert .tape { position:absolute; z-index:3; width:130px; height:36px; top:-16px; opacity:0;
background-color:var(--tape, rgba(201,182,228,.85));
background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px);
box-shadow:0 1px 2px rgba(0,0,0,.15); }
#polaroid-alert .t1 { left:-30px; }
#polaroid-alert .t2 { right:-30px; }
#polaroid-alert .sticker { filter:drop-shadow(4px 0 0 #fff) drop-shadow(-4px 0 0 #fff) drop-shadow(0 4px 0 #fff)
drop-shadow(0 -4px 0 #fff) drop-shadow(0 6px 10px rgba(0,0,0,.35)); }
#polaroid-alert .heart { position:absolute; z-index:4; right:-66px; bottom:-34px; width:104px; opacity:0; }
#polaroid-alert .heart.extra { width:70px; bottom:30px; }
#polaroid-alert .badge { position:absolute; z-index:5; right:-34px; top:40px; width:96px; height:96px; border-radius:50%;
background:var(--badge, #f6c75b); border:5px solid #fff; box-shadow:0 6px 10px rgba(0,0,0,.35); box-sizing:content-box;
display:flex; flex-direction:column; align-items:center; justify-content:center; opacity:0;
font:700 40px/0.9 'Caveat', cursive; color:#fff; text-shadow:0 2px 0 rgba(0,0,0,.25); }
#polaroid-alert .badge small { font-size:19px; line-height:1; }

260
public/alerts/polaroid.js Normal file
View file

@ -0,0 +1,260 @@
/*
Polaroid alerts for the OBS overlay.
window.PolaroidAlerts.play(alert) queue an alert (never overlaps)
window.PolaroidAlerts.reset() stop the current alert and clear 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 }
Everything per event (art, caption, tape colour, badge, sound) is in describe() below.
*/
(function () {
// ===================== CONFIG =====================
const BASE = '/alerts/';
const ART = n => `${BASE}art/${n}`;
const SND = n => `${BASE}sounds/${n}`;
const 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)',
};
// bits: under BITS_MIN = no alert; otherwise the highest matching tier wins
const BITS_MIN = 5;
const BITS_TIERS = [
{ min:250, sound:'TomDaTankLoud.mp3', art:'CharacterHype2.png', badge:'#e0457b', hearts:3 },
{ min:150, sound:'run-vine-sound-effect.mp3', art:'CharacterHype2.png', badge:'#e0457b', hearts:2 },
{ min:100, sound:'windows-xp-startup_1ph012N.mp3', art:'CharacterHype2.png', badge:'#9b6bdc', hearts:1 },
{ min:75, sound:'we-do-a-little-trolling_80cJgd9.mp3', art:'CharacterCool.png', badge:'#9b6bdc', hearts:0 },
{ min:50, sound:'opatski.mp3', art:'CharacterCool.png', badge:'#8a8aa8', hearts:0 },
{ min:5, sound:'correct-answer.wav', art:'CharacterCool.png', badge:'#8a8aa8', hearts:0 },
];
// sound lengths in ms (ffprobe), so the alert stays up for the whole sound
const SOUND_MS = {
'duck-toy-sound.mp3':960, 'wow.mp3':2325, 'huh.mp3':1123, 'correct-answer.wav':1960, 'opatski.mp3':1416,
'we-do-a-little-trolling_80cJgd9.mp3':2691, 'windows-xp-startup_1ph012N.mp3':4911,
'run-vine-sound-effect.mp3':8280, 'TomDaTankLoud.mp3':10057, 'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3':2038,
};
const BACK_ART = ['CharacterHeart.png','CharacterLoveEyes_Glasses.png','CharacterHappy.png',
'CharacterLynx.png','CharacterCool.png','CharacterSelfie.png'];
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 MIN_HOLD = 6000; // ms fully visible, at least
const SOUND_PAD = 1500; // ms after the sound ends
const GAP = 600; // ms between queued alerts
// Event -> what the polaroid shows. null = no alert.
function describe(e) {
const who = e.user || (e.type === 'gift' ? 'An anonymous gifter' : 'Someone');
switch (e.type) {
case 'follow':
return { art:'CharacterSelfie.png', name:who, line:'just followed! ♡', tape:TAPE.follow, sound:'duck-toy-sound.mp3' };
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 ? 'CharacterQueen_Main.png' : (months > 1 || multi ? 'CharacterInLove.png' : 'CharacterHeart.png');
return { art, name:who, line, msg:e.message, tape:e.prime ? TAPE.prime : TAPE.sub, sound:'wow.mp3',
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:'CharacterGift.png', 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:'wow.mp3', 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:'CharacterTime.png', name:who, line:`is on a ${e.streak}-stream watch streak!`,
tape:TAPE.streak, sound:'huh.mp3', badge:{ big:e.streak, small:'streams' }, phbg:'linear-gradient(#fff4d6,#f7deb0)' };
case 'raid':
return { art:'CharacterPolice.png', name:who, line:`is raiding with ${e.viewers} viewers!`,
tape:TAPE.raid, sound:'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3', badge:{ big:e.viewers, small:'raiders' },
phbg:'linear-gradient(#ffe6d6,#f8c8a8)', stack:2 };
case 'bits': {
if (!(e.bits >= BITS_MIN)) return null;
const t = BITS_TIERS.find(t => e.bits >= t.min);
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, 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 imgs = new Set([...BACK_ART, 'Heart.png', 'CharacterSelfie.png', 'CharacterHeart.png',
'CharacterQueen_Main.png', 'CharacterInLove.png', 'CharacterGift.png', 'CharacterTime.png',
'CharacterPolice.png', 'CharacterHype2.png']);
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); });
}
const queue = [];
let busy = false, current = null, gen = 0;
function play(alert) {
const d = describe(alert);
if (!d) { console.log('[alerts] skipped', alert); return; }
queue.push(d);
if (!busy) next();
}
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';
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"><img src="${ART(art)}" alt=""></div>${inner}</div>`;
}
function show(d) {
const el = root();
const nameSize = d.name.length > 18 ? 32 : d.name.length > 14 ? 36 : 40;
const backs = Array.from({ length: d.stack || 0 }, (_, i) =>
photoHTML('back', BACK_ART[i % BACK_ART.length], '<div class="blank"></div>')).join('');
const extraHearts = Array.from({ length: d.hearts || 0 }, () =>
`<img class="heart extra sticker" src="${ART('Heart.png')}" 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"><img src="${ART(d.art)}" alt=""></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>
<img class="heart sticker" src="${ART('Heart.png')}" 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 = [];
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' });
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' });
// sound as the photo lands; hold covers the whole sound
const hold = Math.max(MIN_HOLD, (SOUND_MS[d.sound] || 0) + SOUND_PAD);
const cur = current = { anims, timer:null, audio:null };
if (d.sound) {
const a = new Audio(SND(d.sound)); a.volume = VOLUME;
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + 400);
}
// 5. exit: lift and drop away
const exitAt = t0 + 2400 + hold;
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, reset, describe };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload();
})();

127
src/alerts.js Normal file
View file

@ -0,0 +1,127 @@
// Turns Twitch events into polaroid alerts and pushes them to the overlay.
//
// Alert shape (what public/alerts/polaroid.js renders):
// { type:'follow', user }
// { type:'sub', user, tier:'1000'|'2000'|'3000', prime, months, duration, message }
// { type:'gift', user|null (anonymous), total, recipient, tier } total>1 = community gift
// { type:'streak', user, streak }
// { type:'raid', user, viewers }
// { type:'bits', user|null (anonymous), bits, message }
//
// Every alert also goes through dispatch.dispatchEvent() so the existing actions system
// (sounds/videos per event) and the dashboard activity log keep working.
const ws = require('./ws');
const dispatch = require('./dispatch');
// legacy action event types + detail, so existing action matching rules still apply
function legacy(alert) {
switch (alert.type) {
case 'sub': return ['sub', alert.tier];
case 'gift': return ['gift_sub', alert.tier];
case 'bits': return ['bits', String(alert.bits)];
case 'streak': return ['watch_streak', String(alert.streak)];
default: return [alert.type, null];
}
}
function send(alert, raw = null) {
if (!alert) return;
console.log(`[alerts] ${alert.type} — ${alert.user ?? 'anonymous'} ${JSON.stringify({ ...alert, type: undefined, user: undefined })}`);
ws.broadcast({ type: 'alert', alert });
const [eventType, detail] = legacy(alert);
dispatch.dispatchEvent(eventType, detail, alert.user, raw || alert);
}
const text = m => (m && typeof m.text === 'string' && m.text.trim()) ? m.text.trim() : null;
// --- EventSub mappers ---
function fromFollow(e) {
return { type: 'follow', user: e.user_name || e.user_login };
}
function fromCheer(e) {
return { type: 'bits', user: e.is_anonymous ? null : (e.user_name || e.user_login), bits: e.bits, message: e.message || null };
}
// channel.chat.notification: one event type that carries all sub/gift/raid details
// (Prime flag, months bought at once, gift recipient, resub message, community gift totals).
function fromChatNotification(e) {
const user = e.chatter_is_anonymous ? null : (e.chatter_user_name || e.chatter_user_login);
switch (e.notice_type) {
case 'sub':
return { type: 'sub', user, tier: e.sub.sub_tier, prime: !!e.sub.is_prime, months: 1,
duration: e.sub.duration_months || 1, message: text(e.message) };
case 'resub':
return { type: 'sub', user, tier: e.resub.sub_tier, prime: !!e.resub.is_prime,
months: e.resub.cumulative_months || 1, duration: e.resub.duration_months || 1, message: text(e.message) };
case 'gift_paid_upgrade':
case 'prime_paid_upgrade':
// gifted/Prime sub continued as a paid sub: show as a sub
return { type: 'sub', user, tier: e.prime_paid_upgrade?.sub_tier || '1000', prime: false, months: 1, duration: 1, message: null };
case 'sub_gift':
// part of a community gift: the community_sub_gift notice already covers it (no alert per recipient)
if (e.sub_gift.community_gift_id) return null;
return { type: 'gift', user, total: 1, recipient: e.sub_gift.recipient_user_name, tier: e.sub_gift.sub_tier };
case 'community_sub_gift':
return { type: 'gift', user, total: e.community_sub_gift.total, tier: e.community_sub_gift.sub_tier };
case 'raid':
return { type: 'raid', user: e.raid.user_name || e.raid.user_login, viewers: e.raid.viewer_count };
default:
return null; // announcements, pay-it-forward, bits badge tiers, ...: no alert
}
}
// --- watch streaks, reported by the overlay (they only exist as a chat USERNOTICE) ---
const seenNotices = new Map(); // message id -> time; several overlays may report the same notice
function fromOverlayNotice(n) {
if (n.kind !== 'watch_streak') return null;
const streak = parseInt(n.streak, 10);
if (!n.id || !n.user || !(streak > 0)) return null;
const now = Date.now();
for (const [id, t] of seenNotices) if (now - t > 10 * 60 * 1000) seenNotices.delete(id);
if (seenNotices.has(n.id)) return null;
seenNotices.set(n.id, now);
return { type: 'streak', user: String(n.user).slice(0, 40), streak };
}
// --- test alerts (dashboard buttons) ---
const SAMPLES = {
'follow': { type: 'follow', user: 'ChickenWhisperer' },
'sub-new': { type: 'sub', user: 'PixelPotato', tier: '1000', prime: false, months: 1, duration: 1 },
'sub-prime': { type: 'sub', user: 'LurkingLynx', tier: '1000', prime: true, months: 1, duration: 1 },
'sub-resub': { type: 'sub', user: 'ChickenWhisperer', tier: '1000', prime: false, months: 14, duration: 1, message: 'still here for the chickens and the chaos' },
'sub-3': { type: 'sub', user: 'BobTheBuilder99', tier: '1000', prime: false, months: 3, duration: 3 },
'sub-6': { type: 'sub', user: 'xX_Lurker_Xx', tier: '1000', prime: false, months: 6, duration: 6 },
'gift-1': { type: 'gift', user: 'PixelPotato', total: 1, recipient: 'ChickenWhisperer', tier: '1000' },
'gift-10': { type: 'gift', user: 'BobTheBuilder99', total: 10, tier: '1000' },
'gift-anon': { type: 'gift', user: null, total: 5, tier: '1000' },
'streak': { type: 'streak', user: 'LurkingLynx', streak: 5 },
'raid': { type: 'raid', user: 'CozyStreamer', viewers: 42 },
'bits-3': { type: 'bits', user: 'PixelPotato', bits: 3 },
'bits-20': { type: 'bits', user: 'PixelPotato', bits: 20 },
'bits-60': { type: 'bits', user: 'ChickenWhisperer', bits: 60 },
'bits-80': { type: 'bits', user: 'BobTheBuilder99', bits: 80, message: 'we do a little trolling' },
'bits-120': { type: 'bits', user: 'LurkingLynx', bits: 120 },
'bits-200': { type: 'bits', user: 'xX_Lurker_Xx', bits: 200, message: 'RUN' },
'bits-500': { type: 'bits', user: 'BobTheBuilder99', bits: 500, message: 'Tom da Tank says hi' },
};
const TEST_KEYS = [...Object.keys(SAMPLES), 'queue-test'];
// Test alerts go straight to the overlay; they are not logged and do not fire actions.
// test:true makes the overlay drop what it is showing (fast checking);
// 'queue-test' sends four alerts that queue like real ones.
function sendTest(key) {
if (key === 'queue-test') {
ws.broadcast({ type: 'alert', alert: { ...SAMPLES['follow'], test: true } });
for (const k of ['bits-60', 'gift-10', 'streak']) ws.broadcast({ type: 'alert', alert: { ...SAMPLES[k], test: 'queue' } });
return true;
}
const alert = SAMPLES[key];
if (!alert) return false;
ws.broadcast({ type: 'alert', alert: { ...alert, test: true } });
return true;
}
module.exports = { send, sendTest, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromChatNotification, fromOverlayNotice };

View file

@ -53,6 +53,7 @@ app.use('/actions', requireAuth, require('./routers/actions'));
app.use('/media', requireAuth, require('./routers/media')); app.use('/media', requireAuth, require('./routers/media'));
app.use('/layout', requireAuth, require('./routers/layout')); app.use('/layout', requireAuth, require('./routers/layout'));
app.use('/settings', requireAuth, require('./routers/settings')); app.use('/settings', requireAuth, require('./routers/settings'));
app.use('/alerts', requireAuth, require('./routers/alerts'));
app.use('/', requireAuth, require('./routers/dashboard')); app.use('/', requireAuth, require('./routers/dashboard'));
module.exports = app; module.exports = app;

View file

@ -130,6 +130,15 @@ function getUserById(id) {
return db.prepare('SELECT * FROM users WHERE id = ?').get(id); return db.prepare('SELECT * FROM users WHERE id = ?').get(id);
} }
// The streamer account (single-user app for now): used to start EventSub on boot.
function getPrimaryUser() {
return db.prepare('SELECT * FROM users ORDER BY id LIMIT 1').get();
}
function updateUserTokens(id, access_token, refresh_token) {
db.prepare('UPDATE users SET access_token = ?, refresh_token = ? WHERE id = ?').run(access_token, refresh_token, id);
}
// Settings // Settings
function getSettings() { function getSettings() {
return db.prepare('SELECT * FROM settings WHERE id = 1').get(); return db.prepare('SELECT * FROM settings WHERE id = 1').get();
@ -243,7 +252,7 @@ function getActivityLog(limit = 50) {
module.exports = { module.exports = {
init, init,
upsertUser, getUserById, upsertUser, getUserById, getPrimaryUser, updateUserTokens,
getSettings, updateSettings, getSettings, updateSettings,
getLayout, updateLayout, updateLayoutPositions, getLayout, updateLayout, updateLayoutPositions,
getAllMedia, getMediaFile, createMedia, deleteMedia, getAllMedia, getMediaFile, createMedia, deleteMedia,

View file

@ -1,118 +1,182 @@
// Twitch EventSub over WebSocket.
//
// - start(user) is called on boot (stored login) and after OAuth login.
// - session_reconnect: connect to the given URL, subscriptions carry over, then close the old socket.
// - keepalive watchdog: if Twitch goes silent longer than keepalive_timeout_seconds, reconnect.
// - subscription requests refresh the token on 401 (see twitch.js).
const { WebSocket } = require('ws'); const { WebSocket } = require('ws');
const twitch = require('./twitch');
const alerts = require('./alerts');
const dispatch = require('./dispatch'); const dispatch = require('./dispatch');
const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws'; const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws';
const CLIENT_ID = process.env.TWITCH_CLIENT_ID;
let ws = null; let ws = null;
let shouldRun = false; let shouldRun = false;
let sessionId = null; let broadcasterId = null;
let _accessToken = null; let keepaliveMs = 30_000;
let _broadcasterId = null; let watchdog = null;
let reconnectTimer = null;
const status = { connected: false, sessionId: null, subscribed: [], failed: [], lastEventAt: null };
function start(accessToken, broadcasterId) { function start(user) {
_accessToken = accessToken; twitch.setUser(user);
_broadcasterId = broadcasterId; broadcasterId = user.twitch_id;
shouldRun = true; shouldRun = true;
connect(); console.log(`[eventsub] Starting — broadcaster: ${user.login} (${broadcasterId})`);
console.log(`[eventsub] Starting — broadcaster: ${broadcasterId}, base_url: ${process.env.APP_BASE_URL}`); closeSocket(ws);
connect(EVENTSUB_URL, true);
} }
function stop() { function stop() {
shouldRun = false; shouldRun = false;
if (ws) ws.close(); clearTimeout(reconnectTimer);
clearTimeout(watchdog);
closeSocket(ws);
ws = null;
status.connected = false;
console.log('[eventsub] Stopped'); console.log('[eventsub] Stopped');
} }
function connect() { function closeSocket(sock) {
console.log('[eventsub] Connecting...'); if (!sock) return;
ws = new WebSocket(EVENTSUB_URL); sock.removeAllListeners('close'); // a deliberate close must not trigger the auto-reconnect
sock.on('error', () => {});
ws.on('open', () => console.log('[eventsub] Connected to Twitch EventSub')); try { sock.close(); } catch { /* already closed */ }
ws.on('message', (raw) => handleMessage(JSON.parse(raw)));
ws.on('close', () => {
console.log('[eventsub] Disconnected');
if (shouldRun) setTimeout(connect, 10_000);
});
ws.on('error', (e) => console.error('[eventsub] Error:', e.message));
} }
async function handleMessage(msg) { function scheduleReconnect(delay = 10_000) {
clearTimeout(reconnectTimer);
if (!shouldRun) return;
reconnectTimer = setTimeout(() => connect(EVENTSUB_URL, true), delay);
}
function armWatchdog() {
clearTimeout(watchdog);
watchdog = setTimeout(() => {
console.warn('[eventsub] Keepalive missed — reconnecting');
closeSocket(ws);
ws = null;
status.connected = false;
scheduleReconnect(1000);
}, keepaliveMs + 10_000);
}
// fresh = new session (needs subscriptions); false = reconnect URL (subscriptions carry over)
function connect(url, fresh) {
console.log(`[eventsub] Connecting${fresh ? '' : ' (reconnect URL)'}...`);
const sock = new WebSocket(url);
sock.on('message', raw => {
let msg;
try { msg = JSON.parse(raw); } catch { return; }
handleMessage(sock, msg, fresh).catch(e => console.error('[eventsub] handler error:', e.message));
});
sock.on('close', code => {
if (sock !== ws) return; // an old socket we already replaced
console.log(`[eventsub] Disconnected (${code})`);
status.connected = false;
clearTimeout(watchdog);
scheduleReconnect();
});
sock.on('error', e => console.error('[eventsub] Error:', e.message));
if (fresh) { closeSocket(ws); ws = sock; }
}
async function handleMessage(sock, msg, fresh) {
const type = msg.metadata?.message_type; const type = msg.metadata?.message_type;
if (type === 'session_welcome') { if (sock === ws || type === 'session_welcome') armWatchdog();
sessionId = msg.payload.session.id;
console.log('[eventsub] Session established:', sessionId); switch (type) {
await subscribeAll(); case 'session_welcome': {
} else if (type === 'session_reconnect') { const s = msg.payload.session;
console.log('[eventsub] Reconnect requested'); keepaliveMs = (s.keepalive_timeout_seconds || 10) * 1000;
ws.close(); if (!fresh) { // handover from session_reconnect: swap sockets
} else if (type === 'notification') { const old = ws;
ws = sock;
closeSocket(old);
}
status.connected = true;
status.sessionId = s.id;
console.log(`[eventsub] Session ${fresh ? 'established' : 'resumed'}: ${s.id}`);
armWatchdog();
if (fresh) await subscribeAll(s.id);
break;
}
case 'session_reconnect':
console.log('[eventsub] Reconnect requested by Twitch');
connect(msg.payload.session.reconnect_url, false);
break;
case 'notification':
status.lastEventAt = new Date().toISOString();
handleNotification(msg.payload); handleNotification(msg.payload);
break;
case 'revocation':
console.warn(`[eventsub] Subscription revoked: ${msg.payload.subscription.type} (${msg.payload.subscription.status})`);
break;
} }
} }
async function subscribeAll() { async function subscribeAll(sessionId) {
const b = broadcasterId;
const subs = [ const subs = [
{ type: 'channel.subscribe', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, { type: 'channel.follow', version: '2', condition: { broadcaster_user_id: b, moderator_user_id: b } },
{ type: 'channel.subscription.message', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, { type: 'channel.cheer', version: '1', condition: { broadcaster_user_id: b } },
{ type: 'channel.subscription.gift', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, // subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details
{ type: 'channel.cheer', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, { type: 'channel.chat.notification', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
{ type: 'channel.channel_points_custom_reward_redemption.add',version: '1', condition: { broadcaster_user_id: _broadcasterId } }, { type: 'channel.channel_points_custom_reward_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
{ type: 'channel.follow', version: '2', condition: { broadcaster_user_id: _broadcasterId, moderator_user_id: _broadcasterId } },
{ type: 'channel.raid', version: '1', condition: { to_broadcaster_user_id: _broadcasterId } },
]; ];
try { await twitch.validate(); } catch (e) { console.error('[eventsub]', e.message); }
status.subscribed = [];
status.failed = [];
for (const sub of subs) { for (const sub of subs) {
try { try {
const res = await fetch('https://api.twitch.tv/helix/eventsub/subscriptions', { const res = await twitch.helix('/eventsub/subscriptions', {
method: 'POST', method: 'POST',
headers: { body: { ...sub, transport: { method: 'websocket', session_id: sessionId } },
'Authorization': `Bearer ${_accessToken}`,
'Client-Id': CLIENT_ID,
'Content-Type': 'application/json',
},
body: JSON.stringify({ ...sub, transport: { method: 'websocket', session_id: sessionId } }),
}); });
if (res.status === 202) { if (res.status === 202) {
status.subscribed.push(sub.type);
console.log(`[eventsub] Subscribed: ${sub.type}`); console.log(`[eventsub] Subscribed: ${sub.type}`);
} else { } else {
const body = await res.text(); const body = await res.text();
status.failed.push(`${sub.type} (${res.status})`);
console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`); console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`);
} }
} catch (e) { } catch (e) {
status.failed.push(`${sub.type} (${e.message})`);
console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message); console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message);
} }
} }
} }
function handleNotification(payload) { function handleNotification(payload) {
const sub = payload.subscription; const type = payload.subscription.type;
const event = payload.event; const event = payload.event;
const username = event.user_login || event.from_broadcaster_user_login || null;
console.log(`[eventsub] Notification: ${sub.type} — user: ${username}`); switch (type) {
case 'channel.follow':
switch (sub.type) { alerts.send(alerts.fromFollow(event), event);
case 'channel.subscribe':
case 'channel.subscription.message':
dispatch.dispatchEvent('sub', event.tier, username, event);
break;
case 'channel.subscription.gift':
dispatch.dispatchEvent('gift_sub', event.tier, username, event);
break; break;
case 'channel.cheer': case 'channel.cheer':
dispatch.dispatchEvent('bits', String(event.bits), username, event); alerts.send(alerts.fromCheer(event), event);
break; break;
case 'channel.chat.notification': {
const alert = alerts.fromChatNotification(event);
if (alert) alerts.send(alert, event);
else console.log(`[eventsub] chat notification ${event.notice_type} — no alert`);
break;
}
case 'channel.channel_points_custom_reward_redemption.add': case 'channel.channel_points_custom_reward_redemption.add':
dispatch.dispatchEvent('channel_points', event.reward?.id, username, event); // no polaroid alert yet; existing actions still fire
break; dispatch.dispatchEvent('channel_points', event.reward?.id, event.user_name || event.user_login, event);
case 'channel.follow':
dispatch.dispatchEvent('follow', null, username, event);
break;
case 'channel.raid':
dispatch.dispatchEvent('raid', null, username, event);
break; break;
} }
} }
module.exports = { start, stop }; function getStatus() { return { ...status, running: shouldRun }; }
module.exports = { start, stop, getStatus };

11
src/routers/alerts.js Normal file
View file

@ -0,0 +1,11 @@
const express = require('express');
const router = express.Router();
const alerts = require('../alerts');
// POST /alerts/test/:key — send a sample alert to every connected overlay (dashboard test buttons)
router.post('/test/:key', (req, res) => {
const ok = alerts.sendTest(req.params.key);
res.status(ok ? 200 : 404).json({ ok });
});
module.exports = router;

View file

@ -11,6 +11,7 @@ const SCOPES = [
'bits:read', 'bits:read',
'channel:read:redemptions', 'channel:read:redemptions',
'moderator:read:followers', 'moderator:read:followers',
'user:read:chat', // channel.chat.notification (sub/gift/raid details)
].join(' '); ].join(' ');
router.get('/login', (req, res) => { router.get('/login', (req, res) => {
@ -81,7 +82,7 @@ router.get('/callback', async (req, res) => {
req.session.userId = user.id; req.session.userId = user.id;
req.session.user = { login: user.login, display_name: user.display_name }; req.session.user = { login: user.login, display_name: user.display_name };
eventsub.start(tokens.access_token, twitchUser.id); eventsub.start(user);
console.log(`[auth] Login OK — ${twitchUser.login} (twitch_id:${twitchUser.id})`); console.log(`[auth] Login OK — ${twitchUser.login} (twitch_id:${twitchUser.id})`);
res.redirect('/'); res.redirect('/');

View file

@ -1,11 +1,13 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const db = require('../db'); const db = require('../db');
const eventsub = require('../eventsub');
const alerts = require('../alerts');
router.get('/', (req, res) => { router.get('/', (req, res) => {
const logs = db.getActivityLog(50); const logs = db.getActivityLog(50);
const settings = db.getSettings(); const settings = db.getSettings();
res.render('dashboard', { logs, settings }); res.render('dashboard', { logs, settings, eventsubStatus: eventsub.getStatus(), testKeys: alerts.TEST_KEYS });
}); });
module.exports = router; module.exports = router;

View file

@ -39,7 +39,7 @@ router.post('/', (req, res) => {
router.post('/reconnect', (req, res) => { router.post('/reconnect', (req, res) => {
const user = db.getUserById(req.session.userId); const user = db.getUserById(req.session.userId);
if (user) { if (user) {
eventsub.start(user.access_token, user.twitch_id); eventsub.start(user);
console.log('[settings] EventSub reconnect triggered'); console.log('[settings] EventSub reconnect triggered');
} }
res.redirect('/settings'); res.redirect('/settings');

View file

@ -18,4 +18,15 @@ server.listen(PORT, () => {
console.log(`[server] HeyStreamer running on port ${PORT}`); console.log(`[server] HeyStreamer running on port ${PORT}`);
console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`); console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`);
console.log(`[server] DB_PATH: ${process.env.DB_PATH}`); console.log(`[server] DB_PATH: ${process.env.DB_PATH}`);
// Resume EventSub with the stored login, so alerts survive restarts and deploys
// without logging in again. (Set EVENTSUB_DISABLED=1 for local UI work.)
const user = db.getPrimaryUser();
if (process.env.EVENTSUB_DISABLED === '1') {
console.log('[server] EventSub disabled (EVENTSUB_DISABLED=1)');
} else if (user) {
require('./eventsub').start(user);
} else {
console.log('[server] No Twitch login stored yet — log in at /auth/login to start alerts');
}
}); });

75
src/twitch.js Normal file
View file

@ -0,0 +1,75 @@
// Twitch API access for the streamer account: holds the user token, validates it hourly
// (Twitch asks apps to), and refreshes it when it expires (user tokens last ~4 hours).
const db = require('./db');
const CLIENT_ID = process.env.TWITCH_CLIENT_ID;
const CLIENT_SECRET = process.env.TWITCH_CLIENT_SECRET;
let user = null; // users row
let refreshing = null; // in-flight refresh promise, so parallel 401s refresh once
let validateTimer = null;
function setUser(u) {
user = u;
clearInterval(validateTimer);
if (u) validateTimer = setInterval(() => validate().catch(e => console.error('[twitch] validate:', e.message)), 60 * 60 * 1000);
}
function getUser() { return user; }
function token() { return user?.access_token; }
async function refresh() {
if (!user) throw new Error('no user');
if (refreshing) return refreshing;
refreshing = (async () => {
const res = await fetch('https://id.twitch.tv/oauth2/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: CLIENT_ID, client_secret: CLIENT_SECRET,
grant_type: 'refresh_token', refresh_token: user.refresh_token,
}),
});
const body = await res.json().catch(() => ({}));
if (!res.ok || !body.access_token) {
throw new Error(`token refresh failed (${res.status}): ${body.message || 'unknown'} — log in again at /auth/login`);
}
db.updateUserTokens(user.id, body.access_token, body.refresh_token || user.refresh_token);
user = db.getUserById(user.id);
console.log('[twitch] Token refreshed');
})();
try { await refreshing; } finally { refreshing = null; }
}
// Returns true when the token is (now) valid.
async function validate() {
if (!user) return false;
const res = await fetch('https://id.twitch.tv/oauth2/validate', { headers: { Authorization: `OAuth ${token()}` } });
if (res.status === 401) { await refresh(); return true; }
if (res.ok) {
const info = await res.json();
if (info.expires_in < 15 * 60) await refresh(); // refresh early, before a reconnect needs it
return true;
}
return false;
}
// Helix call with one automatic refresh-and-retry on 401.
async function helix(path, { method = 'GET', body } = {}, retry = true) {
const res = await fetch(`https://api.twitch.tv/helix${path}`, {
method,
headers: {
Authorization: `Bearer ${token()}`,
'Client-Id': CLIENT_ID,
...(body ? { 'Content-Type': 'application/json' } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
if (res.status === 401 && retry) {
await refresh();
return helix(path, { method, body }, false);
}
return res;
}
module.exports = { setUser, getUser, token, refresh, validate, helix };

View file

@ -2,10 +2,25 @@ const { WebSocket } = require('ws');
const clients = new Set(); const clients = new Set();
// Overlay -> server messages. Only accepted from connections that present the overlay UUID
// (?overlay=<uuid>, the same secret as the OBS URL), so strangers cannot inject alerts.
function handleIncoming(raw) {
let msg;
try { msg = JSON.parse(raw); } catch { return; }
if (msg?.type === 'chat_notice') {
const alerts = require('./alerts'); // lazy: alerts.js requires this module
alerts.send(alerts.fromOverlayNotice(msg));
}
}
function init(wss) { function init(wss) {
wss.on('connection', (ws) => { wss.on('connection', (ws, req) => {
clients.add(ws); clients.add(ws);
console.log(`[ws] Client connected — total: ${clients.size}`); const db = require('./db');
const overlayId = new URL(req.url, 'http://x').searchParams.get('overlay');
const trusted = !!overlayId && overlayId === db.getSettings().overlay_id;
console.log(`[ws] Client connected${trusted ? ' (overlay)' : ''} — total: ${clients.size}`);
if (trusted) ws.on('message', data => handleIncoming(String(data).slice(0, 2000)));
ws.on('close', () => { ws.on('close', () => {
clients.delete(ws); clients.delete(ws);
console.log(`[ws] Client disconnected — total: ${clients.size}`); console.log(`[ws] Client disconnected — total: ${clients.size}`);

View file

@ -11,6 +11,38 @@
</div> </div>
</div> </div>
<h3>Twitch connection</h3>
<p>
<% if (eventsubStatus.connected) { %>
<span class="badge badge-green">connected</span>
<% } else if (eventsubStatus.running) { %>
<span class="badge badge-grey">connecting…</span>
<% } else { %>
<span class="badge badge-grey">not running</span> (log in again to start)
<% } %>
<% if (eventsubStatus.subscribed.length) { %><br><small>Listening to: <%= eventsubStatus.subscribed.join(', ') %></small><% } %>
<% if (eventsubStatus.failed.length) { %><br><small style="color:#c0392b">Failed: <%= eventsubStatus.failed.join(', ') %> (log out and in again if a permission is missing)</small><% } %>
<% if (eventsubStatus.lastEventAt) { %><br><small>Last event: <%= eventsubStatus.lastEventAt %></small><% } %>
</p>
<h3>Test alerts</h3>
<p><small>Sends a sample alert to the overlay (OBS). Not logged, no actions fired.</small></p>
<div id="test-alerts" style="display:flex; flex-wrap:wrap; gap:.4rem; margin-bottom:.5rem;">
<% for (const key of testKeys) { %>
<button type="button" class="outline" data-key="<%= key %>" style="width:auto; padding:.3rem .8rem; margin:0;"><%= key %></button>
<% } %>
</div>
<p><small id="test-status"></small></p>
<script>
document.querySelectorAll('#test-alerts button').forEach(b => b.addEventListener('click', async () => {
const out = document.getElementById('test-status');
try {
const r = await fetch('/alerts/test/' + encodeURIComponent(b.dataset.key), { method: 'POST' });
out.textContent = r.ok ? `Sent: ${b.dataset.key}` : `Failed (${r.status})`;
} catch (e) { out.textContent = 'Failed: ' + e.message; }
}));
</script>
<h3>Recent activity</h3> <h3>Recent activity</h3>
<% if (logs.length === 0) { %> <% if (logs.length === 0) { %>
<p><em>No activity yet. Events will appear here once your overlay is connected and Twitch fires events.</em></p> <p><em>No activity yet. Events will appear here once your overlay is connected and Twitch fires events.</em></p>

View file

@ -2,6 +2,9 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Caveat:wght@700&display=swap">
<link rel="stylesheet" href="/alerts/polaroid.css">
<style> <style>
:root { :root {
--chat-left: <%= overlayLayout.chat_left %>%; --chat-left: <%= overlayLayout.chat_left %>%;
@ -85,6 +88,7 @@
<video id="alert-video" autoplay></video> <video id="alert-video" autoplay></video>
<script src="/vendor/tmi.min.js"></script> <script src="/vendor/tmi.min.js"></script>
<script src="/alerts/polaroid.js"></script>
<script> <script>
const S = <%- JSON.stringify(settings) %>; const S = <%- JSON.stringify(settings) %>;
const chat = document.getElementById('chat'); const chat = document.getElementById('chat');
@ -98,6 +102,15 @@
const client = new tmi.Client({ channels: [S.channel] }); const client = new tmi.Client({ channels: [S.channel] });
client.connect().catch(console.error); client.connect().catch(console.error);
// Watch streaks only exist as a chat USERNOTICE (msg-id=viewermilestone).
// Report them to the server, which logs them and sends the alert back to every overlay.
client.on('raw_message', (_copy, m) => {
const t = m.tags || {};
if (m.command !== 'USERNOTICE' || t['msg-id'] !== 'viewermilestone' || t['msg-param-category'] !== 'watch-streak') return;
sendUp({ type: 'chat_notice', kind: 'watch_streak', id: t.id,
user: t['display-name'] || t.login, streak: t['msg-param-value'] });
});
client.on('message', (channel, tags, message) => { client.on('message', (channel, tags, message) => {
const now = Date.now(); const now = Date.now();
const silence = (now - lastMsgTime) / 1000; const silence = (now - lastMsgTime) / 1000;
@ -135,9 +148,17 @@
} }
// --- Alert WebSocket --- // --- Alert WebSocket ---
// ?overlay=<id> marks this page as the real overlay, so the server accepts chat_notice messages from it
let ws = null;
const pending = [];
function sendUp(obj) {
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(obj));
else pending.push(obj);
}
function connectWS() { function connectWS() {
const proto = location.protocol === 'https:' ? 'wss' : 'ws'; const proto = location.protocol === 'https:' ? 'wss' : 'ws';
const ws = new WebSocket(`${proto}://${location.host}/ws/overlay`); ws = new WebSocket(`${proto}://${location.host}/ws/overlay?overlay=${encodeURIComponent(S.overlay_id)}`);
ws.onopen = () => { while (pending.length) ws.send(JSON.stringify(pending.shift())); };
ws.onmessage = (e) => { ws.onmessage = (e) => {
const msg = JSON.parse(e.data); const msg = JSON.parse(e.data);
@ -145,6 +166,12 @@
Object.assign(S, msg.settings); Object.assign(S, msg.settings);
return; return;
} }
if (msg.type === 'alert') {
// test alerts replace whatever is showing (fast checking); real ones queue
if (msg.alert.test === true) PolaroidAlerts.reset();
PolaroidAlerts.play(msg.alert);
return;
}
document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg })); document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }));
handleAction(msg); handleAction(msg);
}; };