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