`;
+ 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();
+})();
diff --git a/src/alerts.js b/src/alerts.js
new file mode 100644
index 0000000..0beee16
--- /dev/null
+++ b/src/alerts.js
@@ -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 };
diff --git a/src/app.js b/src/app.js
index 73b2691..e9a8557 100644
--- a/src/app.js
+++ b/src/app.js
@@ -53,6 +53,7 @@ app.use('/actions', requireAuth, require('./routers/actions'));
app.use('/media', requireAuth, require('./routers/media'));
app.use('/layout', requireAuth, require('./routers/layout'));
app.use('/settings', requireAuth, require('./routers/settings'));
+app.use('/alerts', requireAuth, require('./routers/alerts'));
app.use('/', requireAuth, require('./routers/dashboard'));
module.exports = app;
diff --git a/src/db.js b/src/db.js
index 46464d6..ffac595 100644
--- a/src/db.js
+++ b/src/db.js
@@ -130,6 +130,15 @@ function getUserById(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
function getSettings() {
return db.prepare('SELECT * FROM settings WHERE id = 1').get();
@@ -243,7 +252,7 @@ function getActivityLog(limit = 50) {
module.exports = {
init,
- upsertUser, getUserById,
+ upsertUser, getUserById, getPrimaryUser, updateUserTokens,
getSettings, updateSettings,
getLayout, updateLayout, updateLayoutPositions,
getAllMedia, getMediaFile, createMedia, deleteMedia,
diff --git a/src/eventsub.js b/src/eventsub.js
index faeae1c..a88e95b 100644
--- a/src/eventsub.js
+++ b/src/eventsub.js
@@ -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 twitch = require('./twitch');
+const alerts = require('./alerts');
const dispatch = require('./dispatch');
const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws';
-const CLIENT_ID = process.env.TWITCH_CLIENT_ID;
let ws = null;
let shouldRun = false;
-let sessionId = null;
-let _accessToken = null;
-let _broadcasterId = null;
+let broadcasterId = null;
+let keepaliveMs = 30_000;
+let watchdog = null;
+let reconnectTimer = null;
+const status = { connected: false, sessionId: null, subscribed: [], failed: [], lastEventAt: null };
-function start(accessToken, broadcasterId) {
- _accessToken = accessToken;
- _broadcasterId = broadcasterId;
+function start(user) {
+ twitch.setUser(user);
+ broadcasterId = user.twitch_id;
shouldRun = true;
- connect();
- console.log(`[eventsub] Starting — broadcaster: ${broadcasterId}, base_url: ${process.env.APP_BASE_URL}`);
+ console.log(`[eventsub] Starting — broadcaster: ${user.login} (${broadcasterId})`);
+ closeSocket(ws);
+ connect(EVENTSUB_URL, true);
}
function stop() {
shouldRun = false;
- if (ws) ws.close();
+ clearTimeout(reconnectTimer);
+ clearTimeout(watchdog);
+ closeSocket(ws);
+ ws = null;
+ status.connected = false;
console.log('[eventsub] Stopped');
}
-function connect() {
- console.log('[eventsub] Connecting...');
- ws = new WebSocket(EVENTSUB_URL);
-
- ws.on('open', () => console.log('[eventsub] Connected to Twitch EventSub'));
- 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));
+function closeSocket(sock) {
+ if (!sock) return;
+ sock.removeAllListeners('close'); // a deliberate close must not trigger the auto-reconnect
+ sock.on('error', () => {});
+ try { sock.close(); } catch { /* already closed */ }
}
-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;
- if (type === 'session_welcome') {
- sessionId = msg.payload.session.id;
- console.log('[eventsub] Session established:', sessionId);
- await subscribeAll();
- } else if (type === 'session_reconnect') {
- console.log('[eventsub] Reconnect requested');
- ws.close();
- } else if (type === 'notification') {
- handleNotification(msg.payload);
+ if (sock === ws || type === 'session_welcome') armWatchdog();
+
+ switch (type) {
+ case 'session_welcome': {
+ const s = msg.payload.session;
+ keepaliveMs = (s.keepalive_timeout_seconds || 10) * 1000;
+ if (!fresh) { // handover from session_reconnect: swap sockets
+ 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);
+ 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 = [
- { type: 'channel.subscribe', version: '1', condition: { broadcaster_user_id: _broadcasterId } },
- { type: 'channel.subscription.message', version: '1', condition: { broadcaster_user_id: _broadcasterId } },
- { type: 'channel.subscription.gift', version: '1', condition: { broadcaster_user_id: _broadcasterId } },
- { type: 'channel.cheer', version: '1', condition: { broadcaster_user_id: _broadcasterId } },
- { type: 'channel.channel_points_custom_reward_redemption.add',version: '1', condition: { broadcaster_user_id: _broadcasterId } },
- { 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 } },
+ { type: 'channel.follow', version: '2', condition: { broadcaster_user_id: b, moderator_user_id: b } },
+ { type: 'channel.cheer', version: '1', condition: { broadcaster_user_id: b } },
+ // subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details
+ { 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: b } },
];
+ try { await twitch.validate(); } catch (e) { console.error('[eventsub]', e.message); }
+
+ status.subscribed = [];
+ status.failed = [];
for (const sub of subs) {
try {
- const res = await fetch('https://api.twitch.tv/helix/eventsub/subscriptions', {
+ const res = await twitch.helix('/eventsub/subscriptions', {
method: 'POST',
- headers: {
- 'Authorization': `Bearer ${_accessToken}`,
- 'Client-Id': CLIENT_ID,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({ ...sub, transport: { method: 'websocket', session_id: sessionId } }),
+ body: { ...sub, transport: { method: 'websocket', session_id: sessionId } },
});
if (res.status === 202) {
+ status.subscribed.push(sub.type);
console.log(`[eventsub] Subscribed: ${sub.type}`);
} else {
const body = await res.text();
+ status.failed.push(`${sub.type} (${res.status})`);
console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`);
}
} catch (e) {
+ status.failed.push(`${sub.type} (${e.message})`);
console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message);
}
}
}
function handleNotification(payload) {
- const sub = payload.subscription;
+ const type = payload.subscription.type;
const event = payload.event;
- const username = event.user_login || event.from_broadcaster_user_login || null;
- console.log(`[eventsub] Notification: ${sub.type} — user: ${username}`);
-
- switch (sub.type) {
- 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);
+ switch (type) {
+ case 'channel.follow':
+ alerts.send(alerts.fromFollow(event), event);
break;
case 'channel.cheer':
- dispatch.dispatchEvent('bits', String(event.bits), username, event);
+ alerts.send(alerts.fromCheer(event), event);
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':
- dispatch.dispatchEvent('channel_points', event.reward?.id, username, event);
- break;
- case 'channel.follow':
- dispatch.dispatchEvent('follow', null, username, event);
- break;
- case 'channel.raid':
- dispatch.dispatchEvent('raid', null, username, event);
+ // no polaroid alert yet; existing actions still fire
+ dispatch.dispatchEvent('channel_points', event.reward?.id, event.user_name || event.user_login, event);
break;
}
}
-module.exports = { start, stop };
+function getStatus() { return { ...status, running: shouldRun }; }
+
+module.exports = { start, stop, getStatus };
diff --git a/src/routers/alerts.js b/src/routers/alerts.js
new file mode 100644
index 0000000..203ffdd
--- /dev/null
+++ b/src/routers/alerts.js
@@ -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;
diff --git a/src/routers/auth.js b/src/routers/auth.js
index 4168e65..3a5d20f 100644
--- a/src/routers/auth.js
+++ b/src/routers/auth.js
@@ -11,6 +11,7 @@ const SCOPES = [
'bits:read',
'channel:read:redemptions',
'moderator:read:followers',
+ 'user:read:chat', // channel.chat.notification (sub/gift/raid details)
].join(' ');
router.get('/login', (req, res) => {
@@ -81,7 +82,7 @@ router.get('/callback', async (req, res) => {
req.session.userId = user.id;
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})`);
res.redirect('/');
diff --git a/src/routers/dashboard.js b/src/routers/dashboard.js
index b7b6fb8..78cfe6f 100644
--- a/src/routers/dashboard.js
+++ b/src/routers/dashboard.js
@@ -1,11 +1,13 @@
const express = require('express');
const router = express.Router();
const db = require('../db');
+const eventsub = require('../eventsub');
+const alerts = require('../alerts');
router.get('/', (req, res) => {
const logs = db.getActivityLog(50);
const settings = db.getSettings();
- res.render('dashboard', { logs, settings });
+ res.render('dashboard', { logs, settings, eventsubStatus: eventsub.getStatus(), testKeys: alerts.TEST_KEYS });
});
module.exports = router;
diff --git a/src/routers/settings.js b/src/routers/settings.js
index dcd59e6..4dd2b84 100644
--- a/src/routers/settings.js
+++ b/src/routers/settings.js
@@ -39,7 +39,7 @@ router.post('/', (req, res) => {
router.post('/reconnect', (req, res) => {
const user = db.getUserById(req.session.userId);
if (user) {
- eventsub.start(user.access_token, user.twitch_id);
+ eventsub.start(user);
console.log('[settings] EventSub reconnect triggered');
}
res.redirect('/settings');
diff --git a/src/server.js b/src/server.js
index b680599..b819fc7 100644
--- a/src/server.js
+++ b/src/server.js
@@ -18,4 +18,15 @@ server.listen(PORT, () => {
console.log(`[server] HeyStreamer running on port ${PORT}`);
console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`);
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');
+ }
});
diff --git a/src/twitch.js b/src/twitch.js
new file mode 100644
index 0000000..58b5a32
--- /dev/null
+++ b/src/twitch.js
@@ -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 };
diff --git a/src/ws.js b/src/ws.js
index 4d7531d..91a9015 100644
--- a/src/ws.js
+++ b/src/ws.js
@@ -2,10 +2,25 @@ const { WebSocket } = require('ws');
const clients = new Set();
+// Overlay -> server messages. Only accepted from connections that present the overlay UUID
+// (?overlay=, 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) {
- wss.on('connection', (ws) => {
+ wss.on('connection', (ws, req) => {
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', () => {
clients.delete(ws);
console.log(`[ws] Client disconnected — total: ${clients.size}`);
diff --git a/views/dashboard.ejs b/views/dashboard.ejs
index 702ac8d..e6d8464 100644
--- a/views/dashboard.ejs
+++ b/views/dashboard.ejs
@@ -11,6 +11,38 @@
+
Twitch connection
+
+ <% if (eventsubStatus.connected) { %>
+ connected
+ <% } else if (eventsubStatus.running) { %>
+ connecting…
+ <% } else { %>
+ not running (log in again to start)
+ <% } %>
+ <% if (eventsubStatus.subscribed.length) { %> Listening to: <%= eventsubStatus.subscribed.join(', ') %><% } %>
+ <% if (eventsubStatus.failed.length) { %> Failed: <%= eventsubStatus.failed.join(', ') %> (log out and in again if a permission is missing)<% } %>
+ <% if (eventsubStatus.lastEventAt) { %> Last event: <%= eventsubStatus.lastEventAt %><% } %>
+
+
+
Test alerts
+
Sends a sample alert to the overlay (OBS). Not logged, no actions fired.
+
+ <% for (const key of testKeys) { %>
+
+ <% } %>
+
+
+
+
Recent activity
<% if (logs.length === 0) { %>
No activity yet. Events will appear here once your overlay is connected and Twitch fires events.
`;
+ }
+ function tick() {
+ const left = Math.max(0, COUNTDOWN_S - Math.round((Date.now() - startedAt) / 1000));
+ const w = el.querySelector('.when');
+ if (w) w.textContent = left ? `raid in ${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}` : 'any second now…';
+ }
+ function enter() {
+ if (shown) return;
+ shown = true; el.style.visibility = 'visible';
+ el.getAnimations().forEach(a => a.cancel());
+ el.animate([{ transform:'translateY(-420px) rotate(-10deg)', opacity:0 }, { transform:'translateY(10px) rotate(2deg)', opacity:1, offset:.75 },
+ { transform:'translateY(0) rotate(-1deg)', opacity:1 }], { duration:700, easing:'cubic-bezier(.2,.8,.3,1)', fill:'forwards' });
+ }
+ function leave(delay) {
+ clearTimeout(hideTimer);
+ hideTimer = setTimeout(() => {
+ clearInterval(timer);
+ el.animate([{ transform:'translateY(0) rotate(-1deg)', opacity:1 }, { transform:'translateX(700px) rotate(18deg)', opacity:0 }],
+ { duration:700, easing:'ease-in', fill:'forwards' }).finished.then(() => { el.style.visibility = 'hidden'; shown = false; }).catch(() => {});
+ }, delay);
+ }
+
+ function update(phase, raid) {
+ root(); clearTimeout(hideTimer);
+ const viewers = raid.viewers != null ? `with ${raid.viewers} of you, be nice! ♡` : 'with all of you, be nice! ♡';
+ if (phase === 'start') {
+ startedAt = raid.started_at ? Date.parse(raid.started_at) : Date.now();
+ render(raid, viewers, '');
+ enter(); clearInterval(timer); timer = setInterval(tick, 500); tick();
+ } else if (phase === 'done') {
+ clearInterval(timer);
+ render(raid, 'raid sent! see you there ♡', 'GO GO GO');
+ enter(); leave(6000);
+ } else if (phase === 'cancel') {
+ clearInterval(timer);
+ if (!shown) return;
+ const w = el.querySelector('.when'); if (w) w.textContent = 'cancelled';
+ leave(1500);
+ }
+ }
+ window.RaidCard = { update };
+})();
From 553cc35b9ea5fc8a5c011063a55874c691d14e4c Mon Sep 17 00:00:00 2001
From: Bashy
Date: Fri, 20 Nov 2026 23:18:15 +0200
Subject: [PATCH 06/40] Add Redeems: channel points, built-in rewards and bits
Power-ups
- reward_variations (src/db.js in the wiring commit): each trigger has variations,
one is picked at random weighted by rarity (Common 50 / Uncommon 25 / Rare 12 /
Ultra Rare 3), like Twitch alert variations.
- /redeems page: rewards listed live from Twitch, plus Power-ups and built-in
rewards; per variation name, rarity (with % chance), sound + volume, show cassette
or sound only, caption, sticker, on/off, play/test/two-click delete.
- Special styles: Gigantify -> giant emote, Celebration -> bouncing emotes,
Highlight my message / Message Effect -> big taped note.
- redeems-seed.json: first-run defaults rebuilt from the Twitch alert setup
(96 variations, 21 triggers); only loaded when the table is empty.
Co-Authored-By: Claude Opus 5.5
---
src/redeems-seed.json | 41 +++++++++++++
src/redeems.js | 89 +++++++++++++++++++++++++++
src/routers/redeems.js | 110 ++++++++++++++++++++++++++++++++++
views/redeems.ejs | 132 +++++++++++++++++++++++++++++++++++++++++
4 files changed, 372 insertions(+)
create mode 100644 src/redeems-seed.json
create mode 100644 src/redeems.js
create mode 100644 src/routers/redeems.js
create mode 100644 views/redeems.ejs
diff --git a/src/redeems-seed.json b/src/redeems-seed.json
new file mode 100644
index 0000000..82af76e
--- /dev/null
+++ b/src/redeems-seed.json
@@ -0,0 +1,41 @@
+{
+ "_comment": "Example first-run defaults for the Redeems page: one silent variation per Twitch built-in reward / Power-up. A channel's own seed goes in src/redeems-seed.json (not in git; used instead of this file when present). Loaded only when the reward_variations table is empty; after that the dashboard is the source of truth. sound = URL under /public ('' = silent), art = cassette sticker URL ('' = the theme's default sticker).",
+ "variations": [
+ {
+ "kind": "auto_reward",
+ "key": "send_highlighted_message",
+ "title": "Highlight my message",
+ "name": "Highlighted",
+ "rarity": "common",
+ "sound": "",
+ "art": ""
+ },
+ {
+ "kind": "power_up",
+ "key": "message_effect",
+ "title": "Power-up: Message Effect",
+ "name": "Message effect",
+ "rarity": "common",
+ "sound": "",
+ "art": ""
+ },
+ {
+ "kind": "power_up",
+ "key": "celebration",
+ "title": "Power-up: On-Screen Celebration",
+ "name": "Celebration",
+ "rarity": "common",
+ "sound": "",
+ "art": ""
+ },
+ {
+ "kind": "power_up",
+ "key": "gigantify_an_emote",
+ "title": "Power-up: Gigantify an Emote",
+ "name": "Giant emote",
+ "rarity": "common",
+ "sound": "",
+ "art": ""
+ }
+ ]
+}
diff --git a/src/redeems.js b/src/redeems.js
new file mode 100644
index 0000000..a92e8d4
--- /dev/null
+++ b/src/redeems.js
@@ -0,0 +1,89 @@
+// Channel point rewards, built-in channel point rewards and bits Power-ups.
+// Each trigger (kind + key) has variations; one enabled variation is picked at random,
+// weighted by rarity (like Twitch alert variations), and played as a polaroid or sound-only alert.
+const db = require('./db');
+const alerts = require('./alerts');
+const dispatch = require('./dispatch');
+
+// relative weight per rarity (Twitch does not publish its numbers; tune here).
+// chance of a variation = its weight / sum of the weights of the trigger's ENABLED variations
+const RARITY = {
+ common: { label: 'Common', weight: 50 },
+ uncommon: { label: 'Uncommon', weight: 25 },
+ rare: { label: 'Rare', weight: 12 },
+ ultra_rare: { label: 'Ultra Rare', weight: 3 },
+};
+
+// built-in (automatic) channel point rewards, channel.channel_points_automatic_reward_redemption.add v2
+const AUTO_REWARDS = {
+ send_highlighted_message: 'Highlight my message',
+ single_message_bypass_sub_mode: 'Send a message in sub-only mode',
+ random_sub_emote_unlock: 'Unlock a random sub emote',
+ chosen_sub_emote_unlock: 'Choose an emote to unlock',
+ chosen_modified_sub_emote_unlock: 'Modify a single emote',
+};
+
+// bits Power-ups, channel.bits.use with type = power_up
+const POWER_UPS = {
+ message_effect: 'Power-up: Message Effect',
+ celebration: 'Power-up: On-Screen Celebration',
+ gigantify_an_emote: 'Power-up: Gigantify an Emote',
+};
+
+// how a trigger is drawn on the overlay (everything else: cassette tape)
+const STYLE = {
+ 'power_up:gigantify_an_emote': 'emote', // the viewer's emote, giant
+ 'power_up:celebration': 'emote_rain', // copies of the emote bouncing around the screen
+ 'auto_reward:send_highlighted_message': 'message', // big taped paper note with the message
+ 'power_up:message_effect': 'message', // same as highlight
+};
+const LINE = { emote: 'gigantified an emote!', emote_rain: 'is celebrating!', message: 'highlighted:' };
+const emoteUrl = id => id ? `https://static-cdn.jtvnw.net/emoticons/v2/${encodeURIComponent(id)}/default/dark/3.0` : null;
+
+function pick(variations) {
+ const pool = variations.filter(v => v.enabled);
+ const total = pool.reduce((s, v) => s + (RARITY[v.rarity]?.weight || 1), 0);
+ let r = Math.random() * total;
+ for (const v of pool) { r -= RARITY[v.rarity]?.weight || 1; if (r < 0) return v; }
+ return pool[pool.length - 1] || null;
+}
+
+function toAlert(v, { user, input, emote }) {
+ const style = STYLE[`${v.kind}:${v.key}`] || 'cassette';
+ return {
+ type: 'redeem', kind: v.kind, key: v.key, style,
+ user, reward: v.title, variation: v.name, rarity: v.rarity, input: input || null,
+ // special styles have their own wording unless the caption was customised
+ caption: style !== 'cassette' && v.caption === 'redeemed it! ♡' ? LINE[style] : v.caption,
+ sound: v.sound || null, volume: v.volume, polaroid: !!v.polaroid, art: v.art || null, emote: emoteUrl(emote),
+ };
+}
+
+// legacy action event type for the actions system / activity log
+const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up' };
+
+// A redemption arrived from Twitch.
+function handle(kind, key, title, { user, input, emote }, raw) {
+ if (title) db.renameTrigger(kind, key, title);
+ const v = pick(db.getVariationsFor(kind, key));
+ if (!v) {
+ // nothing configured (or all off): still log it and run legacy actions
+ dispatch.dispatchEvent(LEGACY[kind], key, user, raw);
+ return null;
+ }
+ const alert = toAlert(v, { user, input, emote });
+ alerts.send(alert, raw);
+ return alert;
+}
+
+// Dashboard test: one specific variation, or a random pick for the whole trigger.
+function test({ id, kind, key }) {
+ const v = id ? db.getVariation(id) : pick(db.getVariationsFor(kind, key));
+ if (!v) return false;
+ const input = ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!'
+ : v.kind === 'reward' ? 'test input' : null;
+ alerts.sendTestAlert(toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null })); // 25 = Kappa
+ return true;
+}
+
+module.exports = { RARITY, AUTO_REWARDS, POWER_UPS, STYLE, pick, handle, test };
diff --git a/src/routers/redeems.js b/src/routers/redeems.js
new file mode 100644
index 0000000..504acd0
--- /dev/null
+++ b/src/routers/redeems.js
@@ -0,0 +1,110 @@
+const express = require('express');
+const fs = require('fs');
+const path = require('path');
+const router = express.Router();
+const db = require('../db');
+const twitch = require('../twitch');
+const redeems = require('../redeems');
+
+const PUBLIC = path.join(__dirname, '../../public');
+const listDir = (dir, re) => { try { return fs.readdirSync(path.join(PUBLIC, dir)).filter(f => re.test(f)).sort(); } catch { return []; } };
+
+function soundOptions() {
+ const re = /\.(mp3|wav|ogg|m4a)$/i;
+ const lib = [
+ ...listDir('alerts/sounds/redeems', re).map(f => ({ url: `/alerts/sounds/redeems/${f}`, label: `${f} (normalized)` })),
+ ...listDir('alerts/sounds', re).map(f => ({ url: `/alerts/sounds/${f}`, label: f })),
+ ];
+ const uploads = db.getAllMedia().filter(m => m.media_type === 'audio')
+ .map(m => ({ url: `/media/${m.filename}`, label: `${m.original_name} (uploaded)` }));
+ return [...lib, ...uploads];
+}
+
+// live list of the channel's custom rewards (title, cost, icon); null when Twitch is not reachable
+async function twitchRewards() {
+ const u = twitch.getUser();
+ if (!u) return null;
+ try {
+ const res = await twitch.helix(`/channel_points/custom_rewards?broadcaster_id=${u.twitch_id}`);
+ if (!res.ok) return null;
+ return (await res.json()).data.map(r => ({
+ kind: 'reward', key: r.id, title: r.title, cost: r.cost, live: r.is_enabled,
+ image: r.image?.url_1x || r.default_image?.url_1x || null,
+ }));
+ } catch { return null; }
+}
+
+router.get('/', async (req, res) => {
+ const variations = db.getAllVariations();
+ const byTrigger = new Map();
+ for (const v of variations) {
+ const k = `${v.kind}|${v.key}`;
+ if (!byTrigger.has(k)) byTrigger.set(k, []);
+ byTrigger.get(k).push(v);
+ }
+
+ const fromTwitch = await twitchRewards();
+ const rewards = fromTwitch ? [...fromTwitch] : [];
+ // rewards that have variations but were not in the Twitch list (offline, or deleted on Twitch)
+ for (const v of variations) {
+ if (v.kind === 'reward' && !rewards.some(r => r.key === v.key)) {
+ rewards.push({ kind: 'reward', key: v.key, title: v.title, cost: null, missing: !!fromTwitch });
+ }
+ }
+ const uniq = (list) => list.filter((r, i) => list.findIndex(x => x.key === r.key) === i);
+ const groups = [
+ { name: 'Channel point rewards', items: uniq(rewards).sort((a, b) => (a.cost ?? 1e9) - (b.cost ?? 1e9)) },
+ { name: 'Bits Power-ups', items: Object.entries(redeems.POWER_UPS).map(([key, title]) => ({ kind: 'power_up', key, title })) },
+ { name: 'Built-in channel point rewards', items: Object.entries(redeems.AUTO_REWARDS).map(([key, title]) => ({ kind: 'auto_reward', key, title })) },
+ ];
+ for (const g of groups) for (const t of g.items) t.variations = byTrigger.get(`${t.kind}|${t.key}`) || [];
+
+ res.render('redeems', {
+ groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY,
+ sounds: soundOptions(),
+ stickers: [
+ ...listDir('alerts/stickers', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/stickers/${f}`, label: f.replace(/\.\w+$/, '') })),
+ ...listDir('alerts/art', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/art/${f}`, label: f.replace('_Contrast', '').replace(/\.\w+$/, '') })),
+ ],
+ });
+});
+
+const back = (res, v) => res.redirect(`/redeems#t-${encodeURIComponent(`${v.kind}-${v.key}`)}`);
+
+router.post('/variation', (req, res) => {
+ const { kind, key, title } = req.body;
+ if (!['reward', 'auto_reward', 'power_up'].includes(kind) || !key) return res.status(400).send('bad trigger');
+ const n = db.getVariationsFor(kind, key).length;
+ const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key) });
+ back(res, v);
+});
+
+router.post('/variation/:id', (req, res) => {
+ const v = db.getVariation(req.params.id);
+ if (!v) return res.status(404).send('not found');
+ const b = req.body;
+ const vol = parseFloat(b.volume);
+ db.updateVariation(v.id, {
+ name: (b.name || '').trim() || v.name,
+ rarity: redeems.RARITY[b.rarity] ? b.rarity : v.rarity,
+ sound: b.sound || '',
+ volume: isNaN(vol) ? v.volume : Math.max(0, Math.min(1, vol)),
+ polaroid: b.polaroid === 'on' ? 1 : 0,
+ caption: (b.caption || '').trim() || 'redeemed it! ♡',
+ art: b.art || '',
+ enabled: b.enabled === 'on' ? 1 : 0,
+ });
+ back(res, v);
+});
+
+router.post('/variation/:id/delete', (req, res) => {
+ const v = db.getVariation(req.params.id);
+ if (v) db.deleteVariation(v.id);
+ v ? back(res, v) : res.redirect('/redeems');
+});
+
+// tests send the alert to the overlay only (not logged)
+router.post('/variation/:id/test', (req, res) => res.json({ ok: redeems.test({ id: req.params.id }) }));
+router.post('/trigger/test', (req, res) => res.json({ ok: redeems.test({ kind: req.body.kind, key: req.body.key }) }));
+
+module.exports = router;
diff --git a/views/redeems.ejs b/views/redeems.ejs
new file mode 100644
index 0000000..3b5912f
--- /dev/null
+++ b/views/redeems.ejs
@@ -0,0 +1,132 @@
+
+
+
Redeems
+
+ Each redeem plays one of its enabled variations, picked at random by rarity
+ (<% for (const [k, r] of Object.entries(rarity)) { %><%= r.label %> <%= r.weight %><% if (k !== 'ultra_rare') { %> · <% } %><% } %>, relative weights).
+ Sounds: built-in library, or upload more on the Media page.
+ <% if (!twitchOk) { %> Could not load your rewards from Twitch right now, so only rewards that already have variations are listed.<% } %>
+
+
+<% for (const g of groups) { %>
+
<%= g.name %>
+ <% for (const t of g.items) {
+ const on = t.variations.filter(v => v.enabled);
+ const total = on.reduce((s, v) => s + (rarity[v.rarity]?.weight || 1), 0);
+ const anchor = `t-${t.kind}-${t.key}`; %>
+
+
+ <% if (t.image) { %><% } %>
+ <%= t.title %>
+ <% if (t.cost != null) { %><%= t.cost %> pts<% } %>
+ <% if (t.missing) { %>not on Twitch anymore<% } %>
+ <% if (t.live === false) { %>paused on Twitch<% } %>
+
+ <%= t.variations.length ? `${on.length}/${t.variations.length} variation${t.variations.length === 1 ? '' : 's'} on` : 'no alert' %>
+
+ <% if (on.length) { %>
+
+ <% } %>
+
+
+ <% for (const v of t.variations) { %>
+
+ <% } %>
+
+
+
+ <% } %>
+<% } %>
+
+
+
+
From b28e56f99162e0a61bf95a6b4f0fc83aa41c2157 Mon Sep 17 00:00:00 2001
From: Bashy
Date: Fri, 20 Nov 2026 23:18:15 +0200
Subject: [PATCH 07/40] Add StreamElements tips and a Feishin now-playing
helper (disabled)
- src/streamelements.js: StreamElements Astro websocket, channel.tips with SE_JWT.
Only allowed + successful tips alert, deduped by id, follows reconnect tokens.
Off unless SE_JWT is set.
- tools/nowplaying/: PC helper that reads Feishin over MPRIS and posts title,
artist and a small cover thumbnail to /nowplaying (Bearer NOWPLAYING_KEY). The
cover is fetched on the LAN so the Navidrome token never leaves the PC.
Endpoint and overlay widget are kept but switched off for now.
- .env.example: SE_JWT, NOWPLAYING_KEY.
Co-Authored-By: Claude Opus 5.5
---
.env.example | 6 +
src/nowplaying.js | 12 ++
src/routers/nowplaying.js | 28 +++++
src/streamelements.js | 75 +++++++++++
tools/nowplaying/feishin_nowplaying.py | 119 ++++++++++++++++++
.../nowplaying/heystreamer-nowplaying.service | 13 ++
6 files changed, 253 insertions(+)
create mode 100644 src/nowplaying.js
create mode 100644 src/routers/nowplaying.js
create mode 100644 src/streamelements.js
create mode 100755 tools/nowplaying/feishin_nowplaying.py
create mode 100644 tools/nowplaying/heystreamer-nowplaying.service
diff --git a/.env.example b/.env.example
index 1158885..a99ff3f 100644
--- a/.env.example
+++ b/.env.example
@@ -10,3 +10,9 @@ SECRET_KEY=change_this_to_a_random_string
APP_BASE_URL=https://overlay.example.com
DB_PATH=./heystreamer.db
PORT=3000
+
+# StreamElements tips (optional): dashboard -> avatar -> channel -> JWT token. Keep it secret.
+SE_JWT=
+
+# Now playing (Feishin) helper: long random secret shared with tools/nowplaying (e.g. `openssl rand -hex 32`).
+NOWPLAYING_KEY=
diff --git a/src/nowplaying.js b/src/nowplaying.js
new file mode 100644
index 0000000..7f51224
--- /dev/null
+++ b/src/nowplaying.js
@@ -0,0 +1,12 @@
+// "Now playing" from the streamer's music player (Feishin via MPRIS), pushed by tools/nowplaying/feishin_nowplaying.py.
+// The helper sends only text + a small JPEG cover (data URL); no player/server URLs or credentials reach this app.
+let current = null; // { playing, title, artist, album, cover, length, updatedAt }
+
+function set(np) {
+ current = { ...np, updatedAt: Date.now() };
+ require('./ws').broadcast({ type: 'nowplaying', np: current });
+ return current;
+}
+function get() { return current; }
+
+module.exports = { set, get };
diff --git a/src/routers/nowplaying.js b/src/routers/nowplaying.js
new file mode 100644
index 0000000..6042a85
--- /dev/null
+++ b/src/routers/nowplaying.js
@@ -0,0 +1,28 @@
+const express = require('express');
+const crypto = require('crypto');
+const router = express.Router();
+const nowplaying = require('../nowplaying');
+
+// POST /nowplaying (Authorization: Bearer ) from the PC helper; no login session involved.
+const key = () => process.env.NOWPLAYING_KEY || '';
+function authorized(req) {
+ const k = key(), got = (req.get('authorization') || '').replace(/^Bearer\s+/i, '');
+ if (!k || !got) return false;
+ const a = Buffer.from(k), b = Buffer.from(got);
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
+}
+const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
+
+router.post('/', express.json({ limit: '300kb' }), (req, res) => {
+ if (!authorized(req)) return res.status(401).json({ ok: false });
+ const b = req.body || {};
+ const cover = typeof b.cover === 'string' && /^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/.test(b.cover) && b.cover.length < 250000 ? b.cover : null;
+ nowplaying.set({
+ playing: b.status === 'Playing',
+ title: str(b.title, 200), artist: str(b.artist, 200), album: str(b.album, 200),
+ length: Number.isFinite(b.length) ? b.length : null, cover,
+ });
+ res.json({ ok: true });
+});
+
+module.exports = router;
diff --git a/src/streamelements.js b/src/streamelements.js
new file mode 100644
index 0000000..3315f5b
--- /dev/null
+++ b/src/streamelements.js
@@ -0,0 +1,75 @@
+// StreamElements tips via the Astro websocket (https://docs.streamelements.com/websockets).
+// Set SE_JWT in .env (StreamElements dashboard -> avatar -> channel -> copy JWT token). Unset = off.
+// Protocol: welcome -> subscribe {topic:'channel.tips', token, token_type:'jwt'} -> messages on topic channel.tips.
+// Server PINGs every 30 s (ws answers PONG automatically); a 'reconnect' message carries reconnect_token,
+// and connecting with ?reconnect_token= restores subscriptions without subscribing again.
+const { WebSocket } = require('ws');
+const alerts = require('./alerts');
+
+const URL_BASE = process.env.SE_URL || 'wss://astro.streamelements.com';
+let ws = null, shouldRun = false, retryTimer = null, retryMs = 5000;
+const status = { enabled: false, connected: false, subscribed: false, error: null, lastTipAt: null };
+const seen = new Map(); // tip _id -> time, so a resent tip alerts only once
+
+function start() {
+ if (!process.env.SE_JWT) { console.log('[se] SE_JWT not set: StreamElements tips off'); return; }
+ status.enabled = true; shouldRun = true;
+ connect(URL_BASE, true);
+}
+
+function stop() {
+ shouldRun = false; clearTimeout(retryTimer);
+ if (ws) { ws.removeAllListeners('close'); ws.close(); ws = null; }
+ status.connected = status.subscribed = false;
+}
+
+function connect(url, subscribe) {
+ console.log(`[se] Connecting${subscribe ? '' : ' (reconnect token)'}...`);
+ const sock = new WebSocket(url);
+ sock.on('message', raw => { let m; try { m = JSON.parse(raw); } catch { return; } handle(sock, m, subscribe); });
+ sock.on('close', (code) => {
+ if (sock !== ws) return;
+ status.connected = status.subscribed = false;
+ console.log(`[se] Disconnected (${code})`);
+ if (shouldRun) { clearTimeout(retryTimer); retryTimer = setTimeout(() => connect(URL_BASE, true), retryMs); retryMs = Math.min(retryMs * 2, 120000); }
+ });
+ sock.on('error', e => { status.error = e.message; console.error('[se] Error:', e.message); });
+ const old = ws; ws = sock;
+ if (old) { old.removeAllListeners('close'); old.close(); }
+}
+
+function handle(sock, m, subscribe) {
+ switch (m.type) {
+ case 'welcome':
+ status.connected = true; status.error = null; retryMs = 5000;
+ if (subscribe) sock.send(JSON.stringify({ type: 'subscribe', nonce: 'tips-' + Date.now(),
+ data: { topic: 'channel.tips', token: process.env.SE_JWT, token_type: 'jwt' } }));
+ else status.subscribed = true;
+ break;
+ case 'response':
+ if (m.error) { status.error = `${m.error}: ${m.data?.message || ''}`; console.error('[se] Subscribe failed:', status.error); }
+ else { status.subscribed = true; console.log(`[se] Subscribed to ${m.data?.topic} (room ${m.data?.room})`); }
+ break;
+ case 'reconnect':
+ if (m.data?.reconnect_token) connect(`${URL_BASE}/?reconnect_token=${encodeURIComponent(m.data.reconnect_token)}`, false);
+ break;
+ case 'message':
+ if (m.topic === 'channel.tips') tip(m.data);
+ break;
+ }
+}
+
+function tip(data) {
+ if (!data?.donation) return;
+ if (data.approved && data.approved !== 'allowed') { console.log(`[se] Tip ${data._id} not shown (approved: ${data.approved})`); return; }
+ if (data.status && data.status !== 'success') return;
+ const now = Date.now();
+ for (const [id, t] of seen) if (now - t > 3600e3) seen.delete(id);
+ if (data._id && seen.has(data._id)) return;
+ if (data._id) seen.set(data._id, now);
+ status.lastTipAt = new Date().toISOString();
+ alerts.send(alerts.fromTip(data), data);
+}
+
+function getStatus() { return { ...status }; }
+module.exports = { start, stop, getStatus };
diff --git a/tools/nowplaying/feishin_nowplaying.py b/tools/nowplaying/feishin_nowplaying.py
new file mode 100755
index 0000000..35600a1
--- /dev/null
+++ b/tools/nowplaying/feishin_nowplaying.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+"""
+Feishin -> HeyStreamer "now playing".
+
+Watches Feishin over MPRIS (D-Bus) and POSTs {status, title, artist, album, length, cover} to
+/nowplaying with "Authorization: Bearer ".
+
+The cover is fetched here on the LAN (Feishin's artUrl points at Navidrome and contains the
+Subsonic login token) and sent as a small JPEG data URL, so no URL or credential leaves this PC.
+
+Config: ~/.config/heystreamer-nowplaying.env (HEYSTREAMER_URL=..., NOWPLAYING_KEY=...)
+Run: python3 feishin_nowplaying.py (or the systemd user unit next to this file)
+"""
+import base64, io, json, os, sys, time, urllib.request
+import gi
+gi.require_version('Gio', '2.0')
+from gi.repository import Gio, GLib
+
+BUS_NAME = 'org.mpris.MediaPlayer2.Feishin'
+PATH, PLAYER_IF = '/org/mpris/MediaPlayer2', 'org.mpris.MediaPlayer2.Player'
+HEARTBEAT_S = 30
+
+
+def load_config():
+ cfg = dict(os.environ)
+ p = os.path.expanduser('~/.config/heystreamer-nowplaying.env')
+ if os.path.exists(p):
+ for line in open(p):
+ line = line.strip()
+ if line and not line.startswith('#') and '=' in line:
+ k, v = line.split('=', 1)
+ cfg.setdefault(k.strip(), v.strip().strip('"').strip("'"))
+ if not cfg.get('HEYSTREAMER_URL') or not cfg.get('NOWPLAYING_KEY'):
+ sys.exit('set HEYSTREAMER_URL and NOWPLAYING_KEY in ~/.config/heystreamer-nowplaying.env')
+ return cfg['HEYSTREAMER_URL'].rstrip('/'), cfg['NOWPLAYING_KEY']
+
+
+URL, KEY = load_config()
+bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+last_sent, cover_cache = None, {}
+
+
+def prop(name):
+ try:
+ r = bus.call_sync(BUS_NAME, PATH, 'org.freedesktop.DBus.Properties', 'Get',
+ GLib.Variant('(ss)', (PLAYER_IF, name)), None, Gio.DBusCallFlags.NONE, 2000, None)
+ return r.unpack()[0]
+ except GLib.Error:
+ return None # Feishin not running
+
+
+def cover_data(art_url):
+ """Fetch the cover on the LAN, shrink to 160 px JPEG, return a data URL (cached per URL)."""
+ if not art_url or not art_url.startswith(('http://', 'https://', 'file://')):
+ return None
+ if art_url in cover_cache:
+ return cover_cache[art_url]
+ try:
+ from PIL import Image
+ if art_url.startswith('file://'):
+ raw = open(urllib.request.url2pathname(art_url[7:]), 'rb').read()
+ else:
+ raw = urllib.request.urlopen(art_url, timeout=5).read()
+ im = Image.open(io.BytesIO(raw)).convert('RGB')
+ im.thumbnail((160, 160))
+ buf = io.BytesIO(); im.save(buf, 'JPEG', quality=82)
+ data = 'data:image/jpeg;base64,' + base64.b64encode(buf.getvalue()).decode()
+ except Exception as e:
+ print('cover fetch failed:', type(e).__name__, flush=True)
+ data = None
+ cover_cache.clear(); cover_cache[art_url] = data
+ return data
+
+
+def state():
+ md, status = prop('Metadata'), prop('PlaybackStatus')
+ if not md or not status:
+ return {'status': 'Stopped', 'title': '', 'artist': '', 'album': '', 'length': None, 'cover': None}
+ artists = md.get('xesam:artist') or md.get('xesam:albumArtist') or []
+ return {
+ 'status': status,
+ 'title': md.get('xesam:title') or '',
+ 'artist': ', '.join(artists) if isinstance(artists, list) else str(artists),
+ 'album': md.get('xesam:album') or '',
+ 'length': round(md['mpris:length'] / 1e6, 1) if md.get('mpris:length') else None,
+ 'cover': cover_data(md.get('mpris:artUrl')),
+ }
+
+
+def send(force=False):
+ global last_sent
+ s = state()
+ sig = (s['status'], s['title'], s['artist'])
+ if not force and sig == last_sent:
+ return True
+ req = urllib.request.Request(URL + '/nowplaying', data=json.dumps(s).encode(), method='POST',
+ headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + KEY})
+ try:
+ urllib.request.urlopen(req, timeout=8).read()
+ if sig != last_sent:
+ print(f"{s['status']}: {s['artist']} - {s['title']}", flush=True)
+ last_sent = sig
+ except Exception as e:
+ print('send failed:', type(e).__name__, getattr(e, 'code', ''), flush=True)
+ return True
+
+
+def on_signal(*_):
+ GLib.timeout_add(150, lambda: send() and False) # let Feishin finish updating all properties
+
+
+bus.signal_subscribe(BUS_NAME, 'org.freedesktop.DBus.Properties', 'PropertiesChanged', PATH, None,
+ Gio.DBusSignalFlags.NONE, on_signal)
+bus.signal_subscribe('org.freedesktop.DBus', 'org.freedesktop.DBus', 'NameOwnerChanged', '/org/freedesktop/DBus',
+ BUS_NAME, Gio.DBusSignalFlags.NONE, on_signal) # Feishin started / quit
+GLib.timeout_add_seconds(HEARTBEAT_S, lambda: send(force=True)) # overlay recovers after restarts
+send(force=True)
+print('watching Feishin ->', URL, flush=True)
+GLib.MainLoop().run()
diff --git a/tools/nowplaying/heystreamer-nowplaying.service b/tools/nowplaying/heystreamer-nowplaying.service
new file mode 100644
index 0000000..3bf58c5
--- /dev/null
+++ b/tools/nowplaying/heystreamer-nowplaying.service
@@ -0,0 +1,13 @@
+# systemd user unit: copy to ~/.config/systemd/user/, then
+# systemctl --user daemon-reload && systemctl --user enable --now heystreamer-nowplaying
+[Unit]
+Description=Feishin now-playing -> HeyStreamer overlay
+After=graphical-session.target
+
+[Service]
+ExecStart=/usr/bin/python3 %h/projects/heystreamer/tools/nowplaying/feishin_nowplaying.py
+Restart=always
+RestartSec=10
+
+[Install]
+WantedBy=default.target
From cdcd3737a716963fc81a0a70d11678c512d5408c Mon Sep 17 00:00:00 2001
From: Bashy
Date: Fri, 20 Nov 2026 23:18:15 +0200
Subject: [PATCH 08/40] Wire it up: Twitch events, dashboard, overlay parts,
layout editor removed
Twitch / server
- bits via channel.bits.use (cheers + Power-ups, replaces channel.cheer); built-in
channel point rewards; polls; Hype Train v2; outgoing raids. New scopes:
channel:read:polls, channel:read:hype_train, channel:manage:raids (log in again).
- Hype Train: alerts on start / each new level / end, plus the progress bar.
- Raid send-off: start/cancel raids from the dashboard (Helix /raids); the card
stays until channel.raid reports the raid happened.
- StreamElements client started on boot; tip alerts.
Dashboard
- Twitch + StreamElements status, test buttons (poll, Hype Train bar, raid card),
Raid box, activity Reload + auto-refresh, Redeems in the nav.
- Two-click delete instead of browser confirm() on Media and Actions.
Overlay
- ?parts= splits the overlay into OBS sources: chat, alerts, poll, hypebar, raid,
or exclusions like ?parts=nochat. Recommended: ?parts=chat (audio Monitor Only,
chat sounds stay off stream) + ?parts=nochat.
- Now playing switched off (commented, see CLAUDE.md to re-enable).
Removed the layout editor and preview page; chat position/style is baked into
overlay.ejs from the last saved layout (overlay_layout table kept, unused).
Co-Authored-By: Claude Opus 5.5
---
CLAUDE.md | 132 +++++++++++++++++++++++++++++---------
src/alerts.js | 134 ++++++++++++++++++++++++++++++++++++++-
src/app.js | 4 +-
src/db.js | 92 +++++++++++++++++++--------
src/eventsub.js | 54 ++++++++++++++--
src/routers/alerts.js | 35 +++++++++-
src/routers/auth.js | 3 +
src/routers/dashboard.js | 8 ++-
src/routers/overlay.js | 25 +++++---
src/server.js | 1 +
src/ws.js | 5 ++
views/_activity.ejs | 32 ++++++++++
views/actions.ejs | 2 +-
views/dashboard.ejs | 109 +++++++++++++++++++++----------
views/layout.ejs | 13 +++-
views/media.ejs | 4 +-
views/overlay.ejs | 76 +++++++++++++++-------
17 files changed, 589 insertions(+), 140 deletions(-)
create mode 100644 views/_activity.ejs
diff --git a/CLAUDE.md b/CLAUDE.md
index 48e7dfe..56e64d5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -51,18 +51,15 @@ src/
routers/
auth.js — /auth/* (Twitch OAuth)
dashboard.js — / (activity log, EventSub status)
- overlay.js — /overlay/:uuid, /overlay/:uuid/preview, /ws/overlay
+ overlay.js — /overlay/:uuid, /ws/overlay
actions.js — /actions CRUD
media.js — /media upload/delete
- layout.js — /layout editor + /layout/positions
settings.js — /settings
views/
layout.ejs — base shell (nav, Pico CSS)
login.ejs
dashboard.ejs
overlay.ejs — OBS browser source
- overlay_preview.ejs
- layout_editor.ejs
actions.ejs
media.ejs
settings.ejs
@@ -91,7 +88,7 @@ public/
**UUID overlays.** `settings.overlay_id` is a UUID generated on first run. OBS browser source URL is `/overlay/:uuid`. Future multi-user support creates multiple settings rows.
-**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. The DB `overlay_layout` row is passed as `overlayLayout` in all render calls.
+**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. Pass `layout: false` to render without the shell (overlay, `_activity` partial).
**Form value parsing.** Never use `parseInt(val) || default` — it overwrites valid `0` values. Use:
```javascript
@@ -109,7 +106,6 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
| GET | `/auth/callback` | routers/auth.js | Exchange code, save user, start EventSub |
| GET | `/auth/logout` | routers/auth.js | Clear session |
| GET | `/overlay/:uuid` | routers/overlay.js | Live OBS browser source |
-| GET | `/overlay/:uuid/preview` | routers/overlay.js | Mock preview for layout editor |
| WS | `/ws/overlay` | routers/overlay.js | Bidirectional: commands up, actions down |
| GET/POST | `/actions` | routers/actions.js | List and create actions |
| POST | `/actions/:id/test` | routers/actions.js | Fire immediately, skip cooldown |
@@ -117,31 +113,17 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
| DELETE | `/actions/:id` | routers/actions.js | Delete |
| GET/POST | `/media` | routers/media.js | Upload, list |
| DELETE | `/media/:id` | routers/media.js | Delete file + DB row |
-| GET/POST | `/layout` | routers/layout.js | Position + style form (saves all layout fields) |
-| 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 |
| POST | `/settings/reconnect` | routers/settings.js | Restart EventSub |
+| GET | `/activity` | routers/dashboard.js | Activity table partial (dashboard Reload / auto-refresh) |
| POST | `/alerts/test/:key` | routers/alerts.js | Send a sample polaroid alert to the overlay |
-## Overlay CSS variable system
+## Overlay chat position and style
-All overlay positioning and styling uses CSS custom properties rendered into `overlay.ejs` and `overlay_preview.ejs` from the `overlay_layout` row:
-
-| Variable | Controls |
-|---|---|
-| `--chat-left`, `--chat-top` | Chat box position (%) |
-| `--chat-width`, `--chat-height` | Chat box size (%) |
-| `--chat-font-size` | Chat font size (px) |
-| `--chat-font-family` | Chat font family |
-| `--chat-bg-opacity` | Chat message background opacity |
-| `--chat-text-color` | Chat message text colour |
-| `--chat-border-radius` | Message border radius (px) |
-| `--alert-left`, `--alert-top` | Alert position (%, centered via transform) |
-| `--alert-font-size` | Alert font size (px) |
-| `--alert-bg-opacity` | Alert background opacity |
-| `--alert-text-color` | Alert text colour |
-
-The layout editor (`/layout`) shows position and style inputs, with a scaled iframe preview of `/overlay/:uuid/preview`. Position inputs update CSS variables in the iframe live on `input` event. All fields (position + style) are saved via `POST /layout`.
+The layout editor was removed (2026-11-20). Chat box position/size/font and the legacy text/video action alert
+position are fixed CSS custom properties in the `:root` block of `views/overlay.ejs` (values copied from the last
+saved layout). Change them there, or override with Custom CSS in Settings. The `overlay_layout` table is still
+created but unused, so old data is kept.
## Gap / new-message audio
@@ -180,9 +162,10 @@ activity_log — append-only event log
| Twitch event | Version | Condition | Scope | Used for |
|---|---|---|---|---|
| `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | follow alert |
-| `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` | bits alert |
+| `channel.bits.use` | 1 | `broadcaster_user_id` | `bits:read` | cheers (bits alert) **and** Power-ups (`type: power_up` → Redeems); replaced `channel.cheer` |
| `channel.chat.notification` | 1 | `broadcaster_user_id` + `user_id` | `user:read:chat` | subs, resubs, Prime, multi-month, gifts, community gifts, raids |
-| `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 point rewards → Redeems |
+| `channel.channel_points_automatic_reward_redemption.add` | 2 | `broadcaster_user_id` | `channel:read:redemptions` | built-in rewards (highlight message, emote unlocks) → Redeems |
`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,
@@ -196,6 +179,93 @@ community gift totals and the resub message. `sub_gift` notices with a `communit
- Keepalive watchdog: no message for `keepalive_timeout_seconds + 10s` → reconnect.
- Status (connected / subscribed / failed / last event) shown on the dashboard.
+## Redeems (channel points, built-in rewards, bits Power-ups)
+
+Page `/redeems` (src/routers/redeems.js, views/redeems.ejs, logic in src/redeems.js), table `reward_variations`.
+
+- A trigger is `kind` + `key`: `reward` + Twitch reward id, `auto_reward` + built-in type, `power_up` + Power-up type.
+- Each trigger has variations (name, rarity, sound, volume, polaroid on/off, caption, art, enabled). On a redemption
+ ONE enabled variation is picked at random, weighted by rarity (`RARITY` in src/redeems.js: weights Common 50 / Uncommon 25 / Rare 12 / Ultra Rare 3 (Twitch's Super Rare merged into Ultra Rare); chance = weight ÷ sum of the trigger's enabled weights), like
+ Twitch alert variations. No enabled variation → only logged (and legacy actions run).
+- Custom rewards are listed live from Helix `GET /channel_points/custom_rewards` (title, cost, icon); built-in rewards
+ and Power-ups are fixed lists. Titles are refreshed when a redemption arrives with a new name.
+- Shown as a cassette tape (`public/alerts/cassette.js` + `.css`, called from polaroid.js so it shares the queue):
+ rarity = shell colour (Ultra Rare: gold, glow, foil, sparkles), reels spin over the sound's length, label =
+ variation name + reward, paper strip = viewer + caption + typed message, sticker in the corner = the variation's
+ `art` (URL; '' = headset Streamer). `polaroid` column = "show cassette" (0 = sound only).
+- Special styles instead of the cassette (`STYLE` in src/redeems.js, drawn by `public/alerts/fx.js` + `.css`):
+ Gigantify Power-up → the viewer's emote grows giant; On-Screen Celebration → 14 copies of the emote bounce around
+ the whole screen for the sound's length; Highlight my message and the Message Effect Power-up → big taped paper note, taller than wide (stays ~2 s + 70 ms/char).
+ Emote image = `https://static-cdn.jtvnw.net/emoticons/v2//default/dark/3.0` from `event.power_up.emote.id`
+ (fallback: heart). Default caption becomes "gigantified an emote!" / "is celebrating!" / "highlighted:".
+- Sound picker = `public/alerts/sounds/redeems/` (redeem clips, loudness-normalized to -16 LUFS with ffmpeg
+ two-pass loudnorm, so volume stays 0.8), `public/alerts/sounds/` (alert sounds + library) and audio uploaded on
+ the Media page (`/media/`). Stickers: `public/alerts/stickers/` (cut out with rembg / hand masks).
+- polaroid off = sound only: it still waits its turn in the overlay queue and holds it for the sound's length.
+- First run: `src/redeems-seed.json` (rebuilt from the Twitch alert setup, 2026-11-20) is loaded when the table is
+ empty. After that the dashboard is the source of truth; the seed file is never re-applied.
+- Test buttons: per variation, and "Test random" per trigger (`POST /redeems/variation/:id/test`, `/redeems/trigger/test`).
+- Power-up payload field names (`event.type === 'power_up'`, `event.power_up.type`) follow Twitch's docs but were not
+ yet seen live; check `activity_log.data_json` of the first real Power-up.
+
+## Raid send-off and Hype Train bar
+
+- Outgoing raid send-off: Twitch has no "raid started" event, so raids are started from the dashboard Raid box
+ (`POST /alerts/raid/start` → Helix `POST /raids`, scope `channel:manage:raids`; `/alerts/raid/cancel` → `DELETE /raids`).
+ The silent card (`public/alerts/raidcard.js`, top-centre polaroid with the target's Twitch avatar, "raiding X / with N
+ of you, be nice! ♡", 90 s countdown) stays until `channel.raid` (`from_broadcaster_user_id` = us) arrives, then
+ shows "raid sent!" and leaves. Raid started on Twitch directly: card shows only at that moment. Test: `raid-card-test`.
+- Hype Train bar: every `channel.hype_train.*` event also goes out as `{type:'hype_bar', phase, train}`;
+ `public/alerts/hypebar.js` shows a slim taped strip top-left (LV, progress/goal bar, time left; gold for Golden
+ Kappa), outside the queue; on end it shows the final level for 5 s and slides away. Test: dashboard `hype-bar-test`.
+
+## Overlay parts (two OBS sources)
+
+`/overlay/:uuid?parts=` picks what a browser source shows: `chat` (chat box + gap audio), `alerts` (polaroid queue,
+redeems, legacy actions), `poll`, `hypebar`, `raid`. List parts (`?parts=chat,raid`) or exclude them with `no`
+(`?parts=nochat`, `?parts=nochat,noraid`). No `?parts=` = all. Recommended: `?parts=chat` as a source with audio
+"Monitor Only (mute output)" (chat sounds stay off stream) and `?parts=nochat` as the main source. Every source receives every WebSocket message and ignores the parts it does not show, so nothing plays twice.
+Every source still listens to chat for watch streaks; the server dedupes the reports by message id.
+
+## Now playing (Feishin) — SWITCHED OFF for now
+
+Kept in the repo but disabled: the `/nowplaying` route is commented out in `src/app.js`, `nowplaying` is not in
+`PARTS` (src/routers/overlay.js) and the overlay lines are commented (marked NOWPLAYING in views/overlay.ejs).
+To re-enable: undo those three. Description of how it works when enabled:
+
+
+- `tools/nowplaying/feishin_nowplaying.py` runs on the streaming PC: watches Feishin over MPRIS (D-Bus, PyGObject),
+ POSTs `{status,title,artist,album,length,cover}` to `/nowplaying` with `Authorization: Bearer NOWPLAYING_KEY`
+ on every change + every 30 s. Config `~/.config/heystreamer-nowplaying.env` (HEYSTREAMER_URL, NOWPLAYING_KEY);
+ systemd user unit next to the script.
+- Feishin's `mpris:artUrl` points at Navidrome on the LAN and carries the Subsonic token: the helper downloads the
+ cover itself and sends a 160 px JPEG data URL, so no URL/credential ever leaves the PC.
+- Server: `src/routers/nowplaying.js` (key check, sanitised fields, data-URL-only cover) → `src/nowplaying.js` keeps
+ the current song and broadcasts `{type:'nowplaying', np}`; new overlay connections get it on connect.
+- Overlay: `public/alerts/nowplaying.js` small taped paper slip (cover, title, artist) top-right, visible only while
+ `playing`; hides 1.5 s after pause/stop (grace so track changes do not flicker). Chat position unchanged.
+
+## StreamElements tips
+
+- `src/streamelements.js`: Astro websocket (`wss://astro.streamelements.com`, override `SE_URL` for tests). Off unless
+ `SE_JWT` is set in `.env` (StreamElements dashboard → avatar → channel → JWT token; secret, never commit).
+- welcome → subscribe `{topic:'channel.tips', token, token_type:'jwt'}` → `message` on `channel.tips`; tip fields in
+ `data.donation` (`user.username`, `amount`, `currency`, `message`). Only `approved: 'allowed'` + `status: 'success'`
+ alert; deduped by `data._id`. `reconnect` message → reconnect with `?reconnect_token=` (no re-subscribe). Server
+ PINGs every 30 s (ws answers). Status on the dashboard.
+- Alert: tip polaroid (sound emotional-damage-meme, heart-eyes Streamer, amount via Intl currency format, badge, +1/2/3 hearts at 10/25/50).
+ Turn off StreamElements' own tip alert in its overlay to avoid doubles.
+
+## Polls and Hype Train
+
+- Polls (`channel.poll.begin/progress/end` v1, scope `channel:read:polls`): `alerts.sendPoll()` broadcasts
+ `{type:'poll', phase, poll}`; `public/alerts/poll.js` shows a live taped-paper card (left, below the alert corner,
+ NOT in the alert queue): bars + votes + countdown; on `completed` the winner gets a heart + WINNER stamp, then it
+ drops away after 9 s (archived/terminated: away after 1.5 s). Begin/end are logged. Test: dashboard `poll-test`.
+- Hype Train (`channel.hype_train.*` v2, scope `channel:read:hype_train`): `alerts.fromHypeTrain()` → queued polaroid
+ alerts on start, on each NEW level (progress fires per contribution) and at the end (top contributors). HYPE Streamer
+ art; sounds pro-gamer / toad-ya-hoo / tadaaa (in `describe()` case 'hype'). Golden Kappa / Treasure trains named.
+
## Polaroid alerts
```
@@ -205,9 +275,10 @@ alerts.send() ─► ws.broadcast({type:'alert', alert}) ─► overlay ─► p
└─► 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).
+- 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/`. Sound lengths come from `SOUND_MS` or are measured in the browser (redeem sounds picked in the UI), so the alert holds for the whole sound. Redeem alerts carry their own sound URL, volume, art and caption.
- Watch streaks only exist in chat. The overlay reports them; the server only accepts `chat_notice` from WS connections that pass `?overlay=` 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.
+- Test buttons on the dashboard: `POST /alerts/test/:key` (keys = `alerts.TEST_KEYS`). A test alert (`test:true`, `PolaroidAlerts.playTest`) instantly replaces another *test* alert, but never cuts off or drops a real one: it queues behind it. A real alert arriving during a test cuts the test off. `queue-test` sends four that queue. Not logged, no actions fired.
+- Timing: entrance animation ~2.4 s (+0.12 s per stacked photo), then it stays `AFTER_ANIM` (3 s) — or until the sound ends if that is later (sound starts 0.4 s in) — then a 0.65 s exit. ~6 s for most alerts, ~9.3 s for 150+ bits, ~11.1 s for 250+ bits.
- Bits under 5: no alert (`BITS_MIN`).
## Production deployment
@@ -240,4 +311,3 @@ Twitch requires HTTPS for OAuth redirect URIs in production. Register both in th
- Stripe / PayPal / ETH payment notifications
- Multiple overlays (multi-user; UUID foundation is in place)
- HudFX integration
-- Drag-to-reposition in layout editor (removed — CSS transform + interact.js coordinate mismatch; use the position inputs instead)
diff --git a/src/alerts.js b/src/alerts.js
index 0beee16..ad2b726 100644
--- a/src/alerts.js
+++ b/src/alerts.js
@@ -20,6 +20,9 @@ function legacy(alert) {
case 'gift': return ['gift_sub', alert.tier];
case 'bits': return ['bits', String(alert.bits)];
case 'streak': return ['watch_streak', String(alert.streak)];
+ case 'hype': return ['hype_train', alert.phase];
+ case 'tip': return ['tip', `${alert.amount} ${alert.currency}`];
+ case 'redeem': return [{ reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up' }[alert.kind], alert.key];
default: return [alert.type, null];
}
}
@@ -44,6 +47,11 @@ 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.bits.use with type 'cheer' (Power-ups are handled by redeems.js)
+function fromBitsUse(e) {
+ return { type: 'bits', user: e.user_name || e.user_login || null, bits: e.bits, message: text(e.message) };
+}
+
// 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) {
@@ -72,6 +80,77 @@ function fromChatNotification(e) {
}
}
+// --- StreamElements tip (Astro channel.tips message data) ---
+function fromTip(d) {
+ const t = d.donation || {};
+ return { type: 'tip', user: t.user?.username || 'Someone', amount: Number(t.amount) || 0, currency: t.currency || 'USD',
+ message: (t.message || '').trim() || null };
+}
+
+// --- Hype Train (v2): alert on start, on each NEW level, and at the end ---
+const hypeLevels = new Map(); // train id -> last announced level
+function fromHypeTrain(phase, e) {
+ const base = { type: 'hype', golden: e.type === 'golden_kappa', treasure: e.type === 'treasure', shared: !!e.is_shared_train, level: e.level };
+ if (phase === 'begin') {
+ hypeLevels.set(e.id, e.level);
+ return { ...base, phase: 'begin' };
+ }
+ if (phase === 'progress') {
+ if ((hypeLevels.get(e.id) || 0) >= e.level) return null; // every contribution sends progress: only level-ups alert
+ hypeLevels.set(e.id, e.level);
+ return { ...base, phase: 'level' };
+ }
+ hypeLevels.delete(e.id);
+ const top = (e.top_contributions || []).map(c => c.user_name || c.user_login).filter(Boolean);
+ return { ...base, phase: 'end', top: [...new Set(top)].slice(0, 3) };
+}
+
+// --- Hype Train progress bar (persistent while the train runs, outside the queue) ---
+function sendHypeBar(phase, e) {
+ ws.broadcast({ type: 'hype_bar', phase, train: {
+ id: e.id, level: e.level, progress: e.progress ?? null, goal: e.goal ?? null, total: e.total,
+ expires_at: e.expires_at || null, golden: e.type === 'golden_kappa', treasure: e.type === 'treasure' } });
+}
+
+// --- outgoing raid send-off card (persistent, silent, outside the queue) ---
+// Twitch has no "raid started" event: the card appears when the raid is started from the dashboard
+// (routers/alerts.js -> Helix POST /raids) and stays until channel.raid reports the raid happened.
+let pendingRaid = null; // { target, avatar, viewers, started_at }
+function raidCard(phase, raid) { ws.broadcast({ type: 'raid_card', phase, raid }); }
+function raidStarted(raid) { pendingRaid = { ...raid, started_at: new Date().toISOString() }; raidCard('start', pendingRaid); }
+function raidCancelled() { if (pendingRaid) raidCard('cancel', pendingRaid); pendingRaid = null; }
+function getPendingRaid() { return pendingRaid; }
+// channel.raid from us: the raid happened (started from the dashboard or straight on Twitch)
+async function raidHappened(e) {
+ let raid = pendingRaid;
+ if (!raid) { // started on Twitch directly: show the card briefly
+ let avatar = null;
+ try {
+ const res = await require('./twitch').helix(`/users?id=${encodeURIComponent(e.to_broadcaster_user_id)}`);
+ if (res.ok) avatar = (await res.json()).data?.[0]?.profile_image_url || null;
+ } catch { /* fallback art */ }
+ raid = { target: e.to_broadcaster_user_name || e.to_broadcaster_user_login, avatar };
+ }
+ raidCard('done', { ...raid, viewers: e.viewers });
+ pendingRaid = null;
+ dispatch.dispatchEvent('raid_out', String(e.viewers), e.to_broadcaster_user_name, e);
+}
+
+// --- polls: a live card on the overlay, outside the alert queue ---
+function pollShape(phase, e) {
+ return {
+ id: e.id, title: e.title, status: e.status || null, ends_at: e.ends_at || null,
+ choices: (e.choices || []).map(c => ({ id: c.id, title: c.title, votes: c.votes || 0 })),
+ };
+}
+function sendPoll(phase, e) {
+ ws.broadcast({ type: 'poll', phase, poll: pollShape(phase, e) });
+ if (phase !== 'progress') {
+ const detail = phase === 'end' ? e.status : null;
+ dispatch.dispatchEvent(`poll_${phase}`, detail, null, e); // activity log (begin + end only)
+ }
+}
+
// --- 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) {
@@ -105,14 +184,63 @@ const SAMPLES = {
'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' },
+ 'hype-begin':{ type: 'hype', phase: 'begin', level: 1, golden: false },
+ 'hype-level':{ type: 'hype', phase: 'level', level: 3, golden: false },
+ 'hype-end': { type: 'hype', phase: 'end', level: 4, golden: false, top: ['ChickenWhisperer', 'PixelPotato', 'LurkingLynx'] },
+ 'hype-golden':{ type: 'hype', phase: 'begin', level: 1, golden: true },
+ 'tip-5': { type: 'tip', user: 'PixelPotato', amount: 5, currency: 'EUR', message: 'for the hydration fund' },
+ 'tip-25': { type: 'tip', user: 'ChickenWhisperer', amount: 25, currency: 'EUR', message: 'great stream today, have a coffee on me ♡' },
+ 'tip-100': { type: 'tip', user: 'BobTheBuilder99', amount: 100, currency: 'USD', message: null },
};
-const TEST_KEYS = [...Object.keys(SAMPLES), 'queue-test'];
+const TEST_KEYS = [...Object.keys(SAMPLES), 'queue-test', 'poll-test', 'hype-bar-test', 'raid-card-test'];
+
+// fake Hype Train bar: starts at level 1, fills up, levels up twice, ends
+let hypeTimers = [];
+function testHypeBar() {
+ hypeTimers.forEach(clearTimeout); hypeTimers = [];
+ const t = { id: 'test-' + Date.now(), level: 1, progress: 0, goal: 1000, total: 0, type: 'regular' };
+ const send = phase => sendHypeBar(phase, { ...t, expires_at: new Date(Date.now() + 300000).toISOString() });
+ send('begin');
+ for (let i = 1; i <= 12; i++) hypeTimers.push(setTimeout(() => {
+ t.progress += 300; t.total += 300;
+ if (t.progress >= t.goal) { t.progress -= t.goal; t.level++; t.goal += 500; }
+ send('progress');
+ }, i * 800));
+ hypeTimers.push(setTimeout(() => send('end'), 11000));
+}
+
+// fake poll: begins, votes come in over ~9 s, then it ends with a winner
+let pollTimers = [];
+function testPoll() {
+ pollTimers.forEach(clearTimeout); pollTimers = [];
+ const ends = new Date(Date.now() + 10000).toISOString();
+ const poll = { id: 'test-' + Date.now(), title: 'Which map next?', ends_at: ends, status: null,
+ choices: [{ id: 'a', title: 'Customs', votes: 0 }, { id: 'b', title: 'Woods', votes: 0 }, { id: 'c', title: 'Reserve', votes: 0 }, { id: 'd', title: 'Factory (chaos)', votes: 0 }] };
+ const send = phase => ws.broadcast({ type: 'poll', phase, poll: JSON.parse(JSON.stringify(poll)) });
+ send('begin');
+ for (let i = 1; i <= 8; i++) pollTimers.push(setTimeout(() => {
+ poll.choices.forEach((c, k) => { c.votes += Math.floor(Math.random() * (k === 2 ? 6 : 4)); });
+ send('progress');
+ }, i * 1000));
+ pollTimers.push(setTimeout(() => { poll.status = 'completed'; send('end'); }, 10000));
+}
+
+function sendTestAlert(alert) {
+ ws.broadcast({ type: 'alert', alert: { ...alert, test: true } });
+}
// 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);
+// test:true replaces another test alert at once (fast checking) but never cuts off a real alert;
// 'queue-test' sends four alerts that queue like real ones.
function sendTest(key) {
+ if (key === 'poll-test') { testPoll(); return true; }
+ if (key === 'hype-bar-test') { testHypeBar(); return true; }
+ if (key === 'raid-card-test') { // countdown card, then "raid sent" after 12 s
+ raidCard('start', { target: 'CozyStreamer', avatar: null, viewers: 42, started_at: new Date().toISOString() });
+ setTimeout(() => raidCard('done', { target: 'CozyStreamer', avatar: null, viewers: 42 }), 12000);
+ return true;
+ }
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' } });
@@ -124,4 +252,4 @@ function sendTest(key) {
return true;
}
-module.exports = { send, sendTest, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromChatNotification, fromOverlayNotice };
+module.exports = { send, sendTest, sendTestAlert, sendPoll, sendHypeBar, raidStarted, raidCancelled, raidHappened, getPendingRaid, fromHypeTrain, fromTip, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromBitsUse, fromChatNotification, fromOverlayNotice };
diff --git a/src/app.js b/src/app.js
index e9a8557..0c40d91 100644
--- a/src/app.js
+++ b/src/app.js
@@ -49,11 +49,13 @@ function requireAuth(req, res, next) {
app.use('/auth', require('./routers/auth'));
app.use('/overlay', require('./routers/overlay'));
+// Now playing (Feishin) is switched off for now; uncomment to bring it back (see views/overlay.ejs).
+// app.use('/nowplaying', require('./routers/nowplaying')); // key-protected push from the PC helper
app.use('/actions', requireAuth, require('./routers/actions'));
app.use('/media', requireAuth, require('./routers/media'));
-app.use('/layout', requireAuth, require('./routers/layout'));
app.use('/settings', requireAuth, require('./routers/settings'));
app.use('/alerts', requireAuth, require('./routers/alerts'));
+app.use('/redeems', requireAuth, require('./routers/redeems'));
app.use('/', requireAuth, require('./routers/dashboard'));
module.exports = app;
diff --git a/src/db.js b/src/db.js
index ffac595..7c09d81 100644
--- a/src/db.js
+++ b/src/db.js
@@ -11,7 +11,7 @@ function init() {
db.pragma('foreign_keys = ON');
createSchema();
seedSettings();
- seedLayout();
+ seedVariations();
console.log(`[db] Initialised — path: ${DB_PATH}`);
}
@@ -43,6 +43,7 @@ function createSchema() {
custom_js TEXT DEFAULT ''
);
+ -- unused since the layout editor was removed (2026-11-20); kept so old data is not lost
CREATE TABLE IF NOT EXISTS overlay_layout (
id INTEGER PRIMARY KEY CHECK(id = 1),
chat_left REAL DEFAULT 2.0,
@@ -83,6 +84,24 @@ function createSchema() {
created_at TEXT DEFAULT (datetime('now'))
);
+ -- Channel point rewards / built-in rewards / bits Power-ups: each trigger has variations,
+ -- one is picked at random weighted by rarity (like Twitch alert variations).
+ CREATE TABLE IF NOT EXISTS reward_variations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ kind TEXT NOT NULL, -- reward | auto_reward | power_up
+ key TEXT NOT NULL, -- reward id / built-in reward type / power-up type
+ title TEXT NOT NULL, -- trigger name shown in the UI (last known)
+ name TEXT NOT NULL, -- variation name, shown on the polaroid
+ rarity TEXT NOT NULL DEFAULT 'common',
+ sound TEXT DEFAULT '', -- URL path under /public, '' = silent
+ volume REAL DEFAULT 0.8,
+ polaroid INTEGER DEFAULT 1, -- 0 = sound only
+ caption TEXT DEFAULT 'redeemed it! ♡', -- text after the viewer's name on the cassette strip
+ art TEXT DEFAULT '', -- file in /alerts/art, '' = default
+ enabled INTEGER DEFAULT 1,
+ created_at TEXT DEFAULT (datetime('now'))
+ );
+
CREATE TABLE IF NOT EXISTS activity_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_type TEXT NOT NULL,
@@ -104,12 +123,13 @@ function seedSettings() {
}
}
-function seedLayout() {
- const row = db.prepare('SELECT id FROM overlay_layout WHERE id = 1').get();
- if (!row) {
- db.prepare('INSERT INTO overlay_layout (id) VALUES (1)').run();
- console.log('[db] Created default layout row');
- }
+function seedVariations() {
+ if (db.prepare('SELECT COUNT(*) n FROM reward_variations').get().n > 0) return;
+ const seed = require('./redeems-seed.json').variations;
+ const ins = db.prepare(`INSERT INTO reward_variations (kind, key, title, name, rarity, sound, volume, art, enabled)
+ VALUES (@kind, @key, @title, @name, @rarity, @sound, @volume, @art, @enabled)`);
+ db.transaction(() => seed.forEach(v => ins.run({ ...v, volume: v.volume ?? 0.8, art: v.art || '', enabled: v.enabled === false ? 0 : 1 })))();
+ console.log(`[db] Loaded ${seed.length} default redeem variations`);
}
// Users
@@ -149,26 +169,6 @@ function updateSettings(fields) {
db.prepare(`UPDATE settings SET ${cols} WHERE id = 1`).run(fields);
}
-// Layout
-function getLayout() {
- return db.prepare('SELECT * FROM overlay_layout WHERE id = 1').get();
-}
-
-function updateLayout(fields) {
- const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', ');
- db.prepare(`UPDATE overlay_layout SET ${cols} WHERE id = 1`).run(fields);
-}
-
-function updateLayoutPositions(fields) {
- db.prepare(`
- UPDATE overlay_layout SET
- chat_left = @chat_left, chat_top = @chat_top,
- chat_width = @chat_width, chat_height = @chat_height,
- alert_left = @alert_left, alert_top = @alert_top
- WHERE id = 1
- `).run(fields);
-}
-
// Media
function getAllMedia() {
return db.prepare('SELECT * FROM media_files ORDER BY uploaded_at DESC').all();
@@ -232,6 +232,42 @@ function getMatchingActions(eventType, eventDetail) {
});
}
+// Redeem variations
+const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled'];
+
+function getAllVariations() {
+ return db.prepare('SELECT * FROM reward_variations ORDER BY kind, title, id').all();
+}
+
+function getVariationsFor(kind, key) {
+ return db.prepare('SELECT * FROM reward_variations WHERE kind = ? AND key = ? ORDER BY id').all(kind, key);
+}
+
+function getVariation(id) {
+ return db.prepare('SELECT * FROM reward_variations WHERE id = ?').get(id);
+}
+
+function createVariation({ kind, key, title, name }) {
+ const r = db.prepare('INSERT INTO reward_variations (kind, key, title, name) VALUES (?, ?, ?, ?)').run(kind, key, title, name);
+ return getVariation(r.lastInsertRowid);
+}
+
+function updateVariation(id, fields) {
+ const f = Object.fromEntries(Object.entries(fields).filter(([k]) => VARIATION_FIELDS.includes(k)));
+ if (!Object.keys(f).length) return;
+ const cols = Object.keys(f).map(k => `${k} = @${k}`).join(', ');
+ db.prepare(`UPDATE reward_variations SET ${cols} WHERE id = @id`).run({ ...f, id });
+}
+
+// keep the trigger name current when Twitch reports a renamed reward
+function renameTrigger(kind, key, title) {
+ db.prepare('UPDATE reward_variations SET title = ? WHERE kind = ? AND key = ? AND title != ?').run(title, kind, key, title);
+}
+
+function deleteVariation(id) {
+ db.prepare('DELETE FROM reward_variations WHERE id = ?').run(id);
+}
+
// Activity log
function logActivity(eventType, eventDetail, username, data, actionsFired) {
db.prepare(`
@@ -254,8 +290,8 @@ module.exports = {
init,
upsertUser, getUserById, getPrimaryUser, updateUserTokens,
getSettings, updateSettings,
- getLayout, updateLayout, updateLayoutPositions,
getAllMedia, getMediaFile, createMedia, deleteMedia,
getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions,
+ getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation,
logActivity, getActivityLog,
};
diff --git a/src/eventsub.js b/src/eventsub.js
index a88e95b..77443d6 100644
--- a/src/eventsub.js
+++ b/src/eventsub.js
@@ -7,7 +7,7 @@
const { WebSocket } = require('ws');
const twitch = require('./twitch');
const alerts = require('./alerts');
-const dispatch = require('./dispatch');
+const redeems = require('./redeems');
const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws';
@@ -122,10 +122,23 @@ async function subscribeAll(sessionId) {
const b = broadcasterId;
const subs = [
{ type: 'channel.follow', version: '2', condition: { broadcaster_user_id: b, moderator_user_id: b } },
- { type: 'channel.cheer', version: '1', condition: { broadcaster_user_id: b } },
+ // cheers AND bits Power-ups (message effect, celebration, gigantify); replaces channel.cheer
+ { type: 'channel.bits.use', version: '1', condition: { broadcaster_user_id: b } },
// subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details
{ 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: b } },
+ // built-in rewards: highlight message, unlock emote, ...
+ { type: 'channel.channel_points_automatic_reward_redemption.add', version: '2', condition: { broadcaster_user_id: b } },
+ // live poll card on the overlay
+ { type: 'channel.poll.begin', version: '1', condition: { broadcaster_user_id: b } },
+ { type: 'channel.poll.progress', version: '1', condition: { broadcaster_user_id: b } },
+ { type: 'channel.poll.end', version: '1', condition: { broadcaster_user_id: b } },
+ // outgoing raid: send-off card (incoming raids come through channel.chat.notification)
+ { type: 'channel.raid', version: '1', condition: { from_broadcaster_user_id: b } },
+ // Hype Train alerts (start, level up, end)
+ { type: 'channel.hype_train.begin', version: '2', condition: { broadcaster_user_id: b } },
+ { type: 'channel.hype_train.progress', version: '2', condition: { broadcaster_user_id: b } },
+ { type: 'channel.hype_train.end', version: '2', condition: { broadcaster_user_id: b } },
];
try { await twitch.validate(); } catch (e) { console.error('[eventsub]', e.message); }
@@ -161,8 +174,14 @@ function handleNotification(payload) {
case 'channel.follow':
alerts.send(alerts.fromFollow(event), event);
break;
- case 'channel.cheer':
- alerts.send(alerts.fromCheer(event), event);
+ case 'channel.bits.use':
+ if (event.type === 'power_up' && event.power_up?.type) {
+ const t = event.power_up.type;
+ redeems.handle('power_up', t, redeems.POWER_UPS[t] || `Power-up: ${t}`,
+ { user: event.user_name || event.user_login, input: event.message?.text || null, emote: event.power_up.emote?.id }, event);
+ } else {
+ alerts.send(alerts.fromBitsUse(event), event);
+ }
break;
case 'channel.chat.notification': {
const alert = alerts.fromChatNotification(event);
@@ -171,9 +190,32 @@ function handleNotification(payload) {
break;
}
case 'channel.channel_points_custom_reward_redemption.add':
- // no polaroid alert yet; existing actions still fire
- dispatch.dispatchEvent('channel_points', event.reward?.id, event.user_name || event.user_login, event);
+ redeems.handle('reward', event.reward.id, event.reward.title,
+ { user: event.user_name || event.user_login, input: event.user_input || null }, event);
break;
+ case 'channel.poll.begin':
+ case 'channel.poll.progress':
+ case 'channel.poll.end':
+ alerts.sendPoll(type.split('.').pop(), event);
+ break;
+ case 'channel.hype_train.begin':
+ case 'channel.hype_train.progress':
+ case 'channel.hype_train.end': {
+ const phase = type.split('.').pop();
+ alerts.sendHypeBar(phase, event); // persistent progress bar
+ const alert = alerts.fromHypeTrain(phase, event); // queued alert on start / new level / end
+ if (alert) alerts.send(alert, event);
+ break;
+ }
+ case 'channel.raid':
+ if (event.from_broadcaster_user_id === broadcasterId) alerts.raidHappened(event).catch(e => console.error('[alerts] raid out:', e.message));
+ break;
+ case 'channel.channel_points_automatic_reward_redemption.add': {
+ const t = event.reward?.type;
+ redeems.handle('auto_reward', t, redeems.AUTO_REWARDS[t] || t,
+ { user: event.user_name || event.user_login, input: event.message?.text || null, emote: event.reward?.emote?.id }, event);
+ break;
+ }
}
}
diff --git a/src/routers/alerts.js b/src/routers/alerts.js
index 203ffdd..2f634e8 100644
--- a/src/routers/alerts.js
+++ b/src/routers/alerts.js
@@ -1,11 +1,44 @@
const express = require('express');
const router = express.Router();
const alerts = require('../alerts');
+const twitch = require('../twitch');
-// POST /alerts/test/:key — send a sample alert to every connected overlay (dashboard test buttons)
+// 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 });
});
+// POST /alerts/raid/start {target}: start a raid on Twitch and show the send-off card until it happens
+router.post('/raid/start', async (req, res) => {
+ const me = twitch.getUser();
+ const login = String(req.body.target || '').trim().replace(/^@/, '').toLowerCase();
+ if (!me) return res.status(400).json({ ok: false, error: 'not connected to Twitch' });
+ if (!/^[a-z0-9_]{2,25}$/.test(login)) return res.status(400).json({ ok: false, error: 'invalid channel name' });
+ try {
+ const u = await twitch.helix(`/users?login=${encodeURIComponent(login)}`);
+ const target = u.ok ? (await u.json()).data?.[0] : null;
+ if (!target) return res.status(404).json({ ok: false, error: 'channel not found' });
+ const r = await twitch.helix(`/raids?from_broadcaster_id=${me.twitch_id}&to_broadcaster_id=${target.id}`, { method: 'POST' });
+ if (!r.ok) {
+ const body = await r.json().catch(() => ({}));
+ return res.status(r.status).json({ ok: false, error: body.message || `Twitch said ${r.status}` });
+ }
+ let viewers = null;
+ const s = await twitch.helix(`/streams?user_id=${me.twitch_id}`);
+ if (s.ok) viewers = (await s.json()).data?.[0]?.viewer_count ?? null;
+ alerts.raidStarted({ target: target.display_name, avatar: target.profile_image_url || null, viewers });
+ res.json({ ok: true, target: target.display_name, viewers });
+ } catch (e) { res.status(500).json({ ok: false, error: e.message }); }
+});
+
+// POST /alerts/raid/cancel: cancel the pending raid on Twitch and remove the card
+router.post('/raid/cancel', async (req, res) => {
+ const me = twitch.getUser();
+ if (!me) return res.status(400).json({ ok: false, error: 'not connected to Twitch' });
+ const r = await twitch.helix(`/raids?broadcaster_id=${me.twitch_id}`, { method: 'DELETE' }).catch(e => ({ ok: false, status: 500, e }));
+ alerts.raidCancelled();
+ res.status(r.ok || r.status === 404 ? 200 : r.status).json({ ok: r.ok || r.status === 404 });
+});
+
module.exports = router;
diff --git a/src/routers/auth.js b/src/routers/auth.js
index 3a5d20f..ab4025b 100644
--- a/src/routers/auth.js
+++ b/src/routers/auth.js
@@ -12,6 +12,9 @@ const SCOPES = [
'channel:read:redemptions',
'moderator:read:followers',
'user:read:chat', // channel.chat.notification (sub/gift/raid details)
+ 'channel:read:polls', // channel.poll.* (poll card on the overlay)
+ 'channel:read:hype_train', // channel.hype_train.* (Hype Train alerts)
+ 'channel:manage:raids', // start/cancel raids from the dashboard (send-off card stays during the countdown)
].join(' ');
router.get('/login', (req, res) => {
diff --git a/src/routers/dashboard.js b/src/routers/dashboard.js
index 78cfe6f..7e8304e 100644
--- a/src/routers/dashboard.js
+++ b/src/routers/dashboard.js
@@ -3,11 +3,17 @@ const router = express.Router();
const db = require('../db');
const eventsub = require('../eventsub');
const alerts = require('../alerts');
+const streamelements = require('../streamelements');
router.get('/', (req, res) => {
const logs = db.getActivityLog(50);
const settings = db.getSettings();
- res.render('dashboard', { logs, settings, eventsubStatus: eventsub.getStatus(), testKeys: alerts.TEST_KEYS });
+ res.render('dashboard', { logs, settings, eventsubStatus: eventsub.getStatus(), seStatus: streamelements.getStatus(), testKeys: alerts.TEST_KEYS });
+});
+
+// Activity table only (dashboard Reload button / auto-refresh)
+router.get('/activity', (req, res) => {
+ res.render('_activity', { layout: false, logs: db.getActivityLog(50) });
});
module.exports = router;
diff --git a/src/routers/overlay.js b/src/routers/overlay.js
index b8078d2..824d653 100644
--- a/src/routers/overlay.js
+++ b/src/routers/overlay.js
@@ -2,17 +2,26 @@ const express = require('express');
const router = express.Router();
const db = require('../db');
+// Parts of the overlay. One OBS browser source can show all of them, or the overlay can be split into
+// several sources with ?parts=, e.g. chat in its own source (audio "Monitor Only" in OBS, so chat
+// sounds never reach the stream) and everything else in another.
+const PARTS = ['chat', 'alerts', 'poll', 'hypebar', 'raid']; // 'nowplaying' is off for now (see overlay.ejs)
+// ?parts=chat,raid only those parts
+// ?parts=nochat everything except chat (no, several allowed: nochat,noraid)
+// no ?parts / nothing valid: everything
+function partsFrom(q) {
+ if (!q) return PARTS;
+ const tokens = String(q).split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
+ const excluded = tokens.filter(t => t.startsWith('no') && PARTS.includes(t.slice(2))).map(t => t.slice(2));
+ if (excluded.length) return PARTS.filter(p => !excluded.includes(p));
+ const asked = tokens.filter(p => PARTS.includes(p));
+ return asked.length ? asked : PARTS;
+}
+
router.get('/:uuid', (req, res) => {
const settings = db.getSettings();
if (req.params.uuid !== settings.overlay_id) return res.status(404).send('Overlay not found');
- const overlayLayout = db.getLayout();
- res.render('overlay', { layout: false, settings, overlayLayout });
-});
-
-router.get('/:uuid/preview', (req, res) => {
- const settings = db.getSettings();
- const overlayLayout = db.getLayout();
- res.render('overlay_preview', { layout: false, settings, overlayLayout });
+ res.render('overlay', { layout: false, settings, parts: partsFrom(req.query.parts) });
});
module.exports = router;
diff --git a/src/server.js b/src/server.js
index b819fc7..c12a1e3 100644
--- a/src/server.js
+++ b/src/server.js
@@ -29,4 +29,5 @@ server.listen(PORT, () => {
} else {
console.log('[server] No Twitch login stored yet — log in at /auth/login to start alerts');
}
+ if (process.env.EVENTSUB_DISABLED !== '1') require('./streamelements').start();
});
diff --git a/src/ws.js b/src/ws.js
index 91a9015..3e07f52 100644
--- a/src/ws.js
+++ b/src/ws.js
@@ -21,6 +21,11 @@ function init(wss) {
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)));
+ // a freshly loaded overlay gets the current song right away
+ const np = require('./nowplaying').get();
+ if (np) ws.send(JSON.stringify({ type: 'nowplaying', np }));
+ const raid = require('./alerts').getPendingRaid(); // overlay reloaded during a raid countdown
+ if (raid) ws.send(JSON.stringify({ type: 'raid_card', phase: 'start', raid }));
ws.on('close', () => {
clients.delete(ws);
console.log(`[ws] Client disconnected — total: ${clients.size}`);
diff --git a/views/_activity.ejs b/views/_activity.ejs
new file mode 100644
index 0000000..b77aaca
--- /dev/null
+++ b/views/_activity.ejs
@@ -0,0 +1,32 @@
+<% if (logs.length === 0) { %>
+
No activity yet. Events will appear here once your overlay is connected and Twitch fires events.