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 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-20 23:18:15 +02:00
parent b28e56f991
commit cdcd3737a7
17 changed files with 589 additions and 140 deletions

View file

@ -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 };

View file

@ -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;

View file

@ -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,
};

View file

@ -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;
}
}
}

View file

@ -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;

View file

@ -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) => {

View file

@ -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;

View file

@ -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<part>, 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;

View file

@ -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();
});

View file

@ -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}`);