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
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 };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue