// 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)]; 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', custom_power_up: 'custom_power_up' }[alert.kind] || 'redeem', alert.key]; default: return [alert.type || 'alert', null]; } } function send(alert, raw = null) { if (!alert) return; console.log(`[alerts] ${alert.type} — ${alert.user ?? 'anonymous'} ${JSON.stringify({ ...alert, type: undefined, user: undefined })}`); const msg = { type: 'alert', alert }; ws.broadcast(msg); const [eventType, detail] = legacy(alert); dispatch.dispatchEvent(eventType, detail, alert.user, raw || alert, msg); } 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.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) { 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 } } // --- 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 raidTarget(e) { 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 */ } return { target: e.to_broadcaster_user_name || e.to_broadcaster_user_login, avatar }; } async function raidHappened(e) { const raid = pendingRaid || await raidTarget(e); // started on Twitch directly: show the card briefly const msg = { type: 'raid_card', phase: 'done', raid: { ...raid, viewers: e.viewers } }; ws.broadcast(msg); pendingRaid = null; console.log(`[alerts] raid out — ${msg.raid.target} with ${e.viewers}`); dispatch.dispatchEvent('raid_out', String(e.viewers), e.to_broadcaster_user_name, e, msg); } // --- 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) { 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' }, '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', '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 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' } }); return true; } const alert = SAMPLES[key]; if (!alert) return false; ws.broadcast({ type: 'alert', alert: { ...alert, test: true } }); return true; } module.exports = { raidTarget, send, sendTest, sendTestAlert, sendPoll, sendHypeBar, raidStarted, raidCancelled, raidHappened, getPendingRaid, fromHypeTrain, fromTip, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromBitsUse, fromChatNotification, fromOverlayNotice };