Statistics - Per day and per stream statistics (src/periodstats.js, one generic stat_day table), backfilled once from the older tables; Stream / Week / Month / Year / All time views, Community and Streams tabs. - Viewer count every 5 minutes and title / category history per stream (EventSub channel.update): viewer graph, games played (donut), games in the streams list. - Twitch sync (src/twitchsync.js): followers with follow dates, current subs, mods, VIPs, all-time bits, channel emotes, past streams from VODs. Twitch analytics CSV import (src/twitchcsv.js). - Public stats page on its own host (Settings -> Stats and data): no message text, no bots, !hideme / !showme opt-out. Viewer page: roles, follow age, sub status, bits, a menu for rarely used actions. - StreamElements watch-time importer removed (already imported minutes stay as a baseline). Dashboard - Settings and Actions with a left sidebar; each settings page saves only its own fields. Connections (Twitch, StreamElements token now set here, HUDFX), OBS links (hidden behind an eye toggle) with a link builder, Chat (sound picked from the media library), TTS, Stats and data, Backup (export / import the whole setup), Advanced. Time zone setting for the stats pages. - Actions -> Alerts: alert style, pictures, sounds, bits tiers and card colours, stored in the database (src/theme.js); an old file-based theme is imported once. Alert preview page (/actions/alerts/preview, tools/preview/export.js for a static copy). - Old /actions page removed; Actions = Redeems / Alerts / TTS voices / Media. Alerts - New plain Card style for everyone (public/alerts/card.js); Polaroid, Cassette and the TTS letter stay as optional looks. Redeem variations can be Card, Cassette, Sound only or Video. Repo - No channel data in git: the channel's art, stickers and sounds stay on disk (gitignored) and are picked in the dashboard; examples for the server config (apache.example.sh, .env.example). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
79 lines
3.9 KiB
JavaScript
79 lines
3.9 KiB
JavaScript
// StreamElements tips via the Astro websocket (https://docs.streamelements.com/websockets).
|
|
// JWT token: Settings → Connections (StreamElements dashboard -> avatar -> channel -> copy JWT token); SE_JWT in .env
|
|
// still works as a fallback. Empty = off. Saving the token restarts the connection (restart()).
|
|
// Protocol: welcome -> subscribe {topic:'channel.tips', token, token_type:'jwt'} -> messages on topic channel.tips.
|
|
// Server PINGs every 30 s (ws answers PONG automatically); a 'reconnect' message carries reconnect_token,
|
|
// and connecting with ?reconnect_token= restores subscriptions without subscribing again.
|
|
const { WebSocket } = require('ws');
|
|
const alerts = require('./alerts');
|
|
|
|
const URL_BASE = process.env.SE_URL || 'wss://astro.streamelements.com';
|
|
let ws = null, shouldRun = false, retryTimer = null, retryMs = 5000;
|
|
const status = { enabled: false, connected: false, subscribed: false, error: null, lastTipAt: null };
|
|
const seen = new Map(); // tip _id -> time, so a resent tip alerts only once
|
|
|
|
const jwt = () => (require('./db').getSettings()?.se_jwt || process.env.SE_JWT || '').trim();
|
|
|
|
function start() {
|
|
if (!jwt()) { status.enabled = false; console.log('[se] no StreamElements token: tips off'); return; }
|
|
status.enabled = true; shouldRun = true;
|
|
connect(URL_BASE, true);
|
|
}
|
|
|
|
function stop() {
|
|
shouldRun = false; clearTimeout(retryTimer);
|
|
if (ws) { ws.removeAllListeners('close'); ws.close(); ws = null; }
|
|
status.connected = status.subscribed = false;
|
|
}
|
|
|
|
function connect(url, subscribe) {
|
|
console.log(`[se] Connecting${subscribe ? '' : ' (reconnect token)'}...`);
|
|
const sock = new WebSocket(url);
|
|
sock.on('message', raw => { let m; try { m = JSON.parse(raw); } catch { return; } handle(sock, m, subscribe); });
|
|
sock.on('close', (code) => {
|
|
if (sock !== ws) return;
|
|
status.connected = status.subscribed = false;
|
|
console.log(`[se] Disconnected (${code})`);
|
|
if (shouldRun) { clearTimeout(retryTimer); retryTimer = setTimeout(() => connect(URL_BASE, true), retryMs); retryMs = Math.min(retryMs * 2, 120000); }
|
|
});
|
|
sock.on('error', e => { status.error = e.message; console.error('[se] Error:', e.message); });
|
|
const old = ws; ws = sock;
|
|
if (old) { old.removeAllListeners('close'); old.close(); }
|
|
}
|
|
|
|
function handle(sock, m, subscribe) {
|
|
switch (m.type) {
|
|
case 'welcome':
|
|
status.connected = true; status.error = null; retryMs = 5000;
|
|
if (subscribe) sock.send(JSON.stringify({ type: 'subscribe', nonce: 'tips-' + Date.now(),
|
|
data: { topic: 'channel.tips', token: jwt(), token_type: 'jwt' } }));
|
|
else status.subscribed = true;
|
|
break;
|
|
case 'response':
|
|
if (m.error) { status.error = `${m.error}: ${m.data?.message || ''}`; console.error('[se] Subscribe failed:', status.error); }
|
|
else { status.subscribed = true; console.log(`[se] Subscribed to ${m.data?.topic} (room ${m.data?.room})`); }
|
|
break;
|
|
case 'reconnect':
|
|
if (m.data?.reconnect_token) connect(`${URL_BASE}/?reconnect_token=${encodeURIComponent(m.data.reconnect_token)}`, false);
|
|
break;
|
|
case 'message':
|
|
if (m.topic === 'channel.tips') tip(m.data);
|
|
break;
|
|
}
|
|
}
|
|
|
|
function tip(data) {
|
|
if (!data?.donation) return;
|
|
if (data.approved && data.approved !== 'allowed') { console.log(`[se] Tip ${data._id} not shown (approved: ${data.approved})`); return; }
|
|
if (data.status && data.status !== 'success') return;
|
|
const now = Date.now();
|
|
for (const [id, t] of seen) if (now - t > 3600e3) seen.delete(id);
|
|
if (data._id && seen.has(data._id)) return;
|
|
if (data._id) seen.set(data._id, now);
|
|
status.lastTipAt = new Date().toISOString();
|
|
alerts.send(alerts.fromTip(data), data);
|
|
}
|
|
|
|
function getStatus() { return { ...status, source: require('./db').getSettings()?.se_jwt ? 'settings' : process.env.SE_JWT ? 'env' : null }; }
|
|
function restart() { stop(); status.error = null; start(); }
|
|
module.exports = { start, stop, restart, getStatus };
|