Add polaroid alerts for follows, subs, gifts, streaks, raids and bits
Overlay - public/alerts/polaroid.js + .css: animated polaroid (photo drops in, tape and heart stick on, caption writes in), randomized angles, per-event art, caption, tape colour, badge and sound, fanned photo stack for multi-month subs / community gifts / raids, and a queue so alerts never overlap. - Bits: no alert under 5; sound tiers at 5/50/75/100/150/250. - Watch streaks are read from chat (USERNOTICE viewermilestone) and reported to the server over the overlay WebSocket. Server - Subscribe to channel.chat.notification instead of channel.subscribe / subscription.message / subscription.gift / channel.raid: one event with Prime, months bought at once, gift recipient, resub message and community gift totals. Per-recipient gift notices of a gift bomb are skipped, so a bomb is one alert (was N+1). Needs the user:read:chat scope (log in again). - src/alerts.js maps Twitch events to alerts, broadcasts them and still runs them through dispatch (activity log + existing actions). - EventSub starts on boot from the stored login (alerts survive restarts), validates the token hourly and refreshes it on expiry or 401, follows session_reconnect without dropping events, and reconnects when keepalives stop. - The overlay WebSocket only accepts chat_notice messages from connections that pass the overlay UUID; streak notices are deduped by message id. Dashboard - Twitch connection status and a test button per alert (POST /alerts/test/:key). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
88e906ff5d
commit
d481fc4f69
16 changed files with 773 additions and 83 deletions
127
src/alerts.js
Normal file
127
src/alerts.js
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
// Turns Twitch events into polaroid alerts and pushes them to the overlay.
|
||||
//
|
||||
// Alert shape (what public/alerts/polaroid.js renders):
|
||||
// { type:'follow', user }
|
||||
// { type:'sub', user, tier:'1000'|'2000'|'3000', prime, months, duration, message }
|
||||
// { type:'gift', user|null (anonymous), total, recipient, tier } total>1 = community gift
|
||||
// { type:'streak', user, streak }
|
||||
// { type:'raid', user, viewers }
|
||||
// { type:'bits', user|null (anonymous), bits, message }
|
||||
//
|
||||
// Every alert also goes through dispatch.dispatchEvent() so the existing actions system
|
||||
// (sounds/videos per event) and the dashboard activity log keep working.
|
||||
const ws = require('./ws');
|
||||
const dispatch = require('./dispatch');
|
||||
|
||||
// legacy action event types + detail, so existing action matching rules still apply
|
||||
function legacy(alert) {
|
||||
switch (alert.type) {
|
||||
case 'sub': return ['sub', alert.tier];
|
||||
case 'gift': return ['gift_sub', alert.tier];
|
||||
case 'bits': return ['bits', String(alert.bits)];
|
||||
case 'streak': return ['watch_streak', String(alert.streak)];
|
||||
default: return [alert.type, null];
|
||||
}
|
||||
}
|
||||
|
||||
function send(alert, raw = null) {
|
||||
if (!alert) return;
|
||||
console.log(`[alerts] ${alert.type} — ${alert.user ?? 'anonymous'} ${JSON.stringify({ ...alert, type: undefined, user: undefined })}`);
|
||||
ws.broadcast({ type: 'alert', alert });
|
||||
const [eventType, detail] = legacy(alert);
|
||||
dispatch.dispatchEvent(eventType, detail, alert.user, raw || alert);
|
||||
}
|
||||
|
||||
const text = m => (m && typeof m.text === 'string' && m.text.trim()) ? m.text.trim() : null;
|
||||
|
||||
// --- EventSub mappers ---
|
||||
|
||||
function fromFollow(e) {
|
||||
return { type: 'follow', user: e.user_name || e.user_login };
|
||||
}
|
||||
|
||||
function fromCheer(e) {
|
||||
return { type: 'bits', user: e.is_anonymous ? null : (e.user_name || e.user_login), bits: e.bits, message: e.message || null };
|
||||
}
|
||||
|
||||
// channel.chat.notification: one event type that carries all sub/gift/raid details
|
||||
// (Prime flag, months bought at once, gift recipient, resub message, community gift totals).
|
||||
function fromChatNotification(e) {
|
||||
const user = e.chatter_is_anonymous ? null : (e.chatter_user_name || e.chatter_user_login);
|
||||
switch (e.notice_type) {
|
||||
case 'sub':
|
||||
return { type: 'sub', user, tier: e.sub.sub_tier, prime: !!e.sub.is_prime, months: 1,
|
||||
duration: e.sub.duration_months || 1, message: text(e.message) };
|
||||
case 'resub':
|
||||
return { type: 'sub', user, tier: e.resub.sub_tier, prime: !!e.resub.is_prime,
|
||||
months: e.resub.cumulative_months || 1, duration: e.resub.duration_months || 1, message: text(e.message) };
|
||||
case 'gift_paid_upgrade':
|
||||
case 'prime_paid_upgrade':
|
||||
// gifted/Prime sub continued as a paid sub: show as a sub
|
||||
return { type: 'sub', user, tier: e.prime_paid_upgrade?.sub_tier || '1000', prime: false, months: 1, duration: 1, message: null };
|
||||
case 'sub_gift':
|
||||
// part of a community gift: the community_sub_gift notice already covers it (no alert per recipient)
|
||||
if (e.sub_gift.community_gift_id) return null;
|
||||
return { type: 'gift', user, total: 1, recipient: e.sub_gift.recipient_user_name, tier: e.sub_gift.sub_tier };
|
||||
case 'community_sub_gift':
|
||||
return { type: 'gift', user, total: e.community_sub_gift.total, tier: e.community_sub_gift.sub_tier };
|
||||
case 'raid':
|
||||
return { type: 'raid', user: e.raid.user_name || e.raid.user_login, viewers: e.raid.viewer_count };
|
||||
default:
|
||||
return null; // announcements, pay-it-forward, bits badge tiers, ...: no alert
|
||||
}
|
||||
}
|
||||
|
||||
// --- watch streaks, reported by the overlay (they only exist as a chat USERNOTICE) ---
|
||||
const seenNotices = new Map(); // message id -> time; several overlays may report the same notice
|
||||
function fromOverlayNotice(n) {
|
||||
if (n.kind !== 'watch_streak') return null;
|
||||
const streak = parseInt(n.streak, 10);
|
||||
if (!n.id || !n.user || !(streak > 0)) return null;
|
||||
const now = Date.now();
|
||||
for (const [id, t] of seenNotices) if (now - t > 10 * 60 * 1000) seenNotices.delete(id);
|
||||
if (seenNotices.has(n.id)) return null;
|
||||
seenNotices.set(n.id, now);
|
||||
return { type: 'streak', user: String(n.user).slice(0, 40), streak };
|
||||
}
|
||||
|
||||
// --- test alerts (dashboard buttons) ---
|
||||
const SAMPLES = {
|
||||
'follow': { type: 'follow', user: 'ChickenWhisperer' },
|
||||
'sub-new': { type: 'sub', user: 'PixelPotato', tier: '1000', prime: false, months: 1, duration: 1 },
|
||||
'sub-prime': { type: 'sub', user: 'LurkingLynx', tier: '1000', prime: true, months: 1, duration: 1 },
|
||||
'sub-resub': { type: 'sub', user: 'ChickenWhisperer', tier: '1000', prime: false, months: 14, duration: 1, message: 'still here for the chickens and the chaos' },
|
||||
'sub-3': { type: 'sub', user: 'BobTheBuilder99', tier: '1000', prime: false, months: 3, duration: 3 },
|
||||
'sub-6': { type: 'sub', user: 'xX_Lurker_Xx', tier: '1000', prime: false, months: 6, duration: 6 },
|
||||
'gift-1': { type: 'gift', user: 'PixelPotato', total: 1, recipient: 'ChickenWhisperer', tier: '1000' },
|
||||
'gift-10': { type: 'gift', user: 'BobTheBuilder99', total: 10, tier: '1000' },
|
||||
'gift-anon': { type: 'gift', user: null, total: 5, tier: '1000' },
|
||||
'streak': { type: 'streak', user: 'LurkingLynx', streak: 5 },
|
||||
'raid': { type: 'raid', user: 'CozyStreamer', viewers: 42 },
|
||||
'bits-3': { type: 'bits', user: 'PixelPotato', bits: 3 },
|
||||
'bits-20': { type: 'bits', user: 'PixelPotato', bits: 20 },
|
||||
'bits-60': { type: 'bits', user: 'ChickenWhisperer', bits: 60 },
|
||||
'bits-80': { type: 'bits', user: 'BobTheBuilder99', bits: 80, message: 'we do a little trolling' },
|
||||
'bits-120': { type: 'bits', user: 'LurkingLynx', bits: 120 },
|
||||
'bits-200': { type: 'bits', user: 'xX_Lurker_Xx', bits: 200, message: 'RUN' },
|
||||
'bits-500': { type: 'bits', user: 'BobTheBuilder99', bits: 500, message: 'Tom da Tank says hi' },
|
||||
};
|
||||
|
||||
const TEST_KEYS = [...Object.keys(SAMPLES), 'queue-test'];
|
||||
|
||||
// Test alerts go straight to the overlay; they are not logged and do not fire actions.
|
||||
// test:true makes the overlay drop what it is showing (fast checking);
|
||||
// 'queue-test' sends four alerts that queue like real ones.
|
||||
function sendTest(key) {
|
||||
if (key === 'queue-test') {
|
||||
ws.broadcast({ type: 'alert', alert: { ...SAMPLES['follow'], test: true } });
|
||||
for (const k of ['bits-60', 'gift-10', 'streak']) ws.broadcast({ type: 'alert', alert: { ...SAMPLES[k], test: 'queue' } });
|
||||
return true;
|
||||
}
|
||||
const alert = SAMPLES[key];
|
||||
if (!alert) return false;
|
||||
ws.broadcast({ type: 'alert', alert: { ...alert, test: true } });
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = { send, sendTest, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromChatNotification, fromOverlayNotice };
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
11
src/db.js
11
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,
|
||||
|
|
|
|||
196
src/eventsub.js
196
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 };
|
||||
|
|
|
|||
11
src/routers/alerts.js
Normal file
11
src/routers/alerts.js
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const alerts = require('../alerts');
|
||||
|
||||
// POST /alerts/test/:key — send a sample alert to every connected overlay (dashboard test buttons)
|
||||
router.post('/test/:key', (req, res) => {
|
||||
const ok = alerts.sendTest(req.params.key);
|
||||
res.status(ok ? 200 : 404).json({ ok });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
|
@ -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('/');
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
}
|
||||
});
|
||||
|
|
|
|||
75
src/twitch.js
Normal file
75
src/twitch.js
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// Twitch API access for the streamer account: holds the user token, validates it hourly
|
||||
// (Twitch asks apps to), and refreshes it when it expires (user tokens last ~4 hours).
|
||||
const db = require('./db');
|
||||
|
||||
const CLIENT_ID = process.env.TWITCH_CLIENT_ID;
|
||||
const CLIENT_SECRET = process.env.TWITCH_CLIENT_SECRET;
|
||||
|
||||
let user = null; // users row
|
||||
let refreshing = null; // in-flight refresh promise, so parallel 401s refresh once
|
||||
let validateTimer = null;
|
||||
|
||||
function setUser(u) {
|
||||
user = u;
|
||||
clearInterval(validateTimer);
|
||||
if (u) validateTimer = setInterval(() => validate().catch(e => console.error('[twitch] validate:', e.message)), 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
function getUser() { return user; }
|
||||
function token() { return user?.access_token; }
|
||||
|
||||
async function refresh() {
|
||||
if (!user) throw new Error('no user');
|
||||
if (refreshing) return refreshing;
|
||||
refreshing = (async () => {
|
||||
const res = await fetch('https://id.twitch.tv/oauth2/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
client_id: CLIENT_ID, client_secret: CLIENT_SECRET,
|
||||
grant_type: 'refresh_token', refresh_token: user.refresh_token,
|
||||
}),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !body.access_token) {
|
||||
throw new Error(`token refresh failed (${res.status}): ${body.message || 'unknown'} — log in again at /auth/login`);
|
||||
}
|
||||
db.updateUserTokens(user.id, body.access_token, body.refresh_token || user.refresh_token);
|
||||
user = db.getUserById(user.id);
|
||||
console.log('[twitch] Token refreshed');
|
||||
})();
|
||||
try { await refreshing; } finally { refreshing = null; }
|
||||
}
|
||||
|
||||
// Returns true when the token is (now) valid.
|
||||
async function validate() {
|
||||
if (!user) return false;
|
||||
const res = await fetch('https://id.twitch.tv/oauth2/validate', { headers: { Authorization: `OAuth ${token()}` } });
|
||||
if (res.status === 401) { await refresh(); return true; }
|
||||
if (res.ok) {
|
||||
const info = await res.json();
|
||||
if (info.expires_in < 15 * 60) await refresh(); // refresh early, before a reconnect needs it
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Helix call with one automatic refresh-and-retry on 401.
|
||||
async function helix(path, { method = 'GET', body } = {}, retry = true) {
|
||||
const res = await fetch(`https://api.twitch.tv/helix${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token()}`,
|
||||
'Client-Id': CLIENT_ID,
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (res.status === 401 && retry) {
|
||||
await refresh();
|
||||
return helix(path, { method, body }, false);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
module.exports = { setUser, getUser, token, refresh, validate, helix };
|
||||
19
src/ws.js
19
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=<uuid>, the same secret as the OBS URL), so strangers cannot inject alerts.
|
||||
function handleIncoming(raw) {
|
||||
let msg;
|
||||
try { msg = JSON.parse(raw); } catch { return; }
|
||||
if (msg?.type === 'chat_notice') {
|
||||
const alerts = require('./alerts'); // lazy: alerts.js requires this module
|
||||
alerts.send(alerts.fromOverlayNotice(msg));
|
||||
}
|
||||
}
|
||||
|
||||
function init(wss) {
|
||||
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}`);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue