Stats per stream and period, public stats page, dashboard settings, Card alert style

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>
This commit is contained in:
Bashy 2026-11-23 11:22:49 +02:00
parent 5bf4bffaa0
commit c481ca92cb
57 changed files with 3080 additions and 774 deletions

View file

@ -1,4 +1,5 @@
// Stats page: overview, activity per day, leaderboards, top emotes/commands, viewer lookup, forget a viewer.
// Stats page: one stream / week / month / year / all time (periodstats.js, shared with the public page in
// routers/public.js), all-time points board, viewer lookup, public-page opt-out, forget a viewer.
// Bots (Settings → Hidden chatters) are counted but left out of everything shown here.
const express = require('express');
const router = express.Router();
@ -6,91 +7,41 @@ const db = require('../db');
const chatlog = require('../chatlog');
const watchtime = require('../watchtime');
const points = require('../points');
const seimport = require('../seimport');
const periodstats = require('../periodstats');
const twitchsync = require('../twitchsync');
const twitchcsv = require('../twitchcsv');
const upload = require('multer')({ storage: require('multer').memoryStorage(), limits: { fileSize: 5 * 1024 * 1024, files: 30 } });
const has = t => !!db.raw().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t);
const all = (sql, ...a) => (has(sql.match(/FROM (\w+)/)[1]) ? db.raw().prepare(sql).all(...a) : []);
const one = (sql, ...a) => (has(sql.match(/FROM (\w+)/)[1]) ? db.raw().prepare(sql).get(...a) : null) || {};
function days(n) { // last n days, oldest first, as YYYY-MM-DD (UTC, like the stored days)
const out = [];
for (let i = n - 1; i >= 0; i--) out.push(new Date(Date.now() - i * 864e5).toISOString().slice(0, 10));
return out;
}
router.get('/', (req, res) => {
chatlog.init(); watchtime.init();
const hidden = new Set(chatlog.hiddenUsers());
const ok = login => !hidden.has(String(login || '').toLowerCase());
const viewers = [...points.everyone().values()].filter(x => ok(x.login));
const users = all('SELECT user_id, user_login, user_name, messages FROM chat_user').filter(r => ok(r.user_login));
// watch time = our ticks x 5 + StreamElements import, per login
const watchMin = new Map();
for (const r of all('SELECT user_id, user_login, user_name, ticks FROM watch_user')) if (ok(r.user_login))
watchMin.set(r.user_login, { user_id: r.user_id, user_login: r.user_login, user_name: r.user_name, minutes: r.ticks * 5, ticks: r.ticks });
for (const r of all('SELECT user_login, minutes FROM watch_import')) if (ok(r.user_login)) {
const w = watchMin.get(r.user_login) || { user_login: r.user_login, user_name: r.user_login, minutes: 0, ticks: 0 };
w.minutes += r.minutes; watchMin.set(r.user_login, w);
}
const watchers = [...watchMin.values()];
const actions = all('SELECT * FROM chat_action').filter(r => ok(r.user_login));
const loginOf = new Map([...users, ...watchers].map(r => [r.user_id, r.user_login]));
// per day (last 30 days), bots left out
const d30 = days(30), since = d30[0];
const msgDay = new Map(), watchDay = new Map();
for (const r of all('SELECT user_id, day, messages FROM chat_user_day WHERE day >= ?', since)) if (ok(loginOf.get(r.user_id))) msgDay.set(r.day, (msgDay.get(r.day) || 0) + r.messages);
for (const r of all('SELECT user_id, day, ticks FROM watch_user_day WHERE day >= ?', since)) if (ok(loginOf.get(r.user_id))) watchDay.set(r.day, (watchDay.get(r.day) || 0) + r.ticks * 5);
const sumAct = (types, f = r => r.amount) => {
const m = new Map();
for (const r of actions) if (types.includes(r.action)) m.set(r.user_key, { login: r.user_login, name: r.user_name, n: (m.get(r.user_key)?.n || 0) + f(r) });
return [...m.values()].sort((a, b) => b.n - a.n).slice(0, 10);
};
const emotes = new Map(), commands = new Map();
for (const r of all('SELECT user_id, emote, source, emote_id, uses FROM chat_emote')) if (ok(loginOf.get(r.user_id))) {
const e = emotes.get(r.emote) || { emote: r.emote, source: r.source, id: r.emote_id, uses: 0 }; e.uses += r.uses; emotes.set(r.emote, e);
}
for (const r of all('SELECT user_id, command, uses FROM chat_command')) if (ok(loginOf.get(r.user_id))) commands.set(r.command, (commands.get(r.command) || 0) + r.uses);
chatlog.init(); watchtime.init(); periodstats.init();
const hidden = chatlog.hiddenUsers();
const range = periodstats.parseRange(req.query, 'all');
const summary = periodstats.summary(range, { hidden, revenue: true });
const viewers = [...points.everyone().values()].filter(x => !hidden.includes(String(x.login || '').toLowerCase()));
res.render('stats', {
live: watchtime.isLive(),
hiddenCount: hidden.size,
overview: {
viewers: viewers.length,
messages: users.reduce((s, r) => s + r.messages, 0),
watchHours: Math.round(watchers.reduce((s, r) => s + r.minutes, 0) / 60),
streams: one('SELECT COUNT(*) n FROM stream_session').n || 0,
checkins: one('SELECT COUNT(*) n FROM stream_checkin').n || 0,
since: one('SELECT MIN(first_seen) t FROM chat_user').t || null,
},
perDay: d30.map(day => ({ day, messages: msgDay.get(day) || 0, watchHours: +((watchDay.get(day) || 0) / 60).toFixed(1) })),
boards: {
points: viewers.sort((a, b) => b.total - a.total).slice(0, 10).map(x => ({ login: x.login, name: x.name, n: x.total, level: x.level.name })),
watch: watchers.sort((a, b) => b.minutes - a.minutes).slice(0, 10).map(r => ({ login: r.user_login, name: r.user_name, n: r.minutes })),
chat: users.sort((a, b) => b.messages - a.messages).slice(0, 10).map(r => ({ login: r.user_login, name: r.user_name, n: r.messages })),
bits: sumAct(['bits', 'power_up', 'custom_power_up']),
channelPoints: sumAct(['channel_points', 'auto_reward']),
},
emotes: [...emotes.values()].sort((a, b) => b.uses - a.uses).slice(0, 15),
commands: [...commands.entries()].map(([command, uses]) => ({ command, uses })).sort((a, b) => b.uses - a.uses).slice(0, 15),
q: '', viewer: null,
se: { configured: !!seimport.channelId(), ...seimport.status(), ownTicks: one('SELECT COALESCE(SUM(ticks), 0) n FROM watch_user').n || 0 },
hiddenCount: hidden.length,
since: one('SELECT MIN(day) t FROM stat_day').t || null,
s: summary, q: periodstats.rangeQuery,
pointsBoard: [...viewers].sort((a, b) => b.total - a.total).slice(0, 10).map(x => ({ login: x.login, name: x.name, n: x.total, level: x.level.name })),
ranks: viewers.filter(x => x.level.name !== 'Viewer').sort((a, b) => (b.watchMinutes || 0) - (a.watchMinutes || 0)).map(x => ({ login: x.login, name: x.name, level: x.level.name })),
view: req.query.v === 'streams' ? 'streams' : 'community',
tz: db.getSettings().timezone || 'UTC',
publicUrl: publicUrl(),
sync: twitchsync.lastStatus(),
csv: twitchcsv.status(),
msg: req.query.msg || null,
});
});
// one-time StreamElements watch time import (replaces a previous import)
router.post('/import-se', async (req, res) => {
try {
const r = await seimport.importWatchtime();
res.redirect('/stats?msg=' + encodeURIComponent(`Imported StreamElements watch time: ${r.viewers} viewers, ${Math.round(r.minutes / 60)} hours`));
} catch (e) {
res.redirect('/stats?msg=' + encodeURIComponent('Import failed: ' + e.message));
}
});
function publicUrl() {
const st = db.getSettings();
return st.public_stats_enabled && st.public_stats_host ? `https://${st.public_stats_host}/` : null;
}
// one viewer: /stats/viewer?q=<login>
router.get('/viewer', (req, res) => {
@ -107,7 +58,16 @@ router.get('/viewer', (req, res) => {
hidden: chatlog.isHidden(v.login),
chat: id ? one('SELECT * FROM chat_user WHERE user_id = ?', id) : {},
watch: id ? one('SELECT * FROM watch_user WHERE user_id = ?', id) : {},
importedMinutes: one('SELECT minutes FROM watch_import WHERE user_login = ?', v.login).minutes || 0,
importedMinutes: watchtime.baselineMinutes(v.login),
publicHidden: periodstats.isOptedOut(v.user_id || v.key, v.login),
twitch: twitchsync.viewer(id, v.login),
badges: (() => { const b = id ? one('SELECT badges, sub_months, at FROM chat_badges WHERE user_id = ?', id) : {}; return { list: JSON.parse(b.badges || '[]'), subMonths: b.sub_months || null, at: b.at || null }; })(),
given: (() => {
const rows = all('SELECT action, uses, amount FROM chat_action WHERE user_key = ? OR user_login = ?', v.key, v.login);
const sum = (types, f) => rows.filter(r => types.includes(r.action)).reduce((a, r) => a + f(r), 0);
return { bits: sum(['bits', 'power_up', 'custom_power_up'], r => r.amount), subs: sum(['sub'], r => r.uses),
subMonths: sum(['sub'], r => r.amount), gifts: sum(['gift_sub'], r => r.amount) };
})(),
checkins: id ? one('SELECT COUNT(*) n FROM stream_checkin WHERE user_id = ?', id).n || 0 : 0,
emotes: id ? all('SELECT emote, source, emote_id, uses FROM chat_emote WHERE user_id = ? ORDER BY uses DESC LIMIT 20', id) : [],
commands: id ? all('SELECT command, uses, last_used FROM chat_command WHERE user_id = ? ORDER BY uses DESC LIMIT 20', id) : [],
@ -116,19 +76,50 @@ router.get('/viewer', (req, res) => {
});
});
// renamed on Twitch: move the StreamElements-imported watch time to the new name (and remember it for re-imports)
// pull followers, subs, roles, bits, emotes, VODs from Twitch now
router.post('/sync', async (req, res) => {
const st = await twitchsync.sync();
const bad = Object.entries(st.parts || {}).filter(([, v]) => !String(v).startsWith('ok'));
const text = bad.length ? `Sync with Twitch: ${bad.map(([k, v]) => `${k} failed (${v})`).join('; ')}` : 'Synced with Twitch';
res.redirect(req.query.back === 'settings' ? `/settings/stats?${bad.length ? 'err' : 'msg'}=` + encodeURIComponent(text) : '/stats?msg=' + encodeURIComponent(text));
});
// Twitch Creator Dashboard "Analytics and Revenue by day" CSV exports (several at once; importing again is safe)
router.post('/import-twitch', upload.array('files'), (req, res) => {
const done = [], bad = [];
for (const f of req.files || []) {
try { const r = twitchcsv.importCsv(f.buffer.toString('utf8')); done.push(r); }
catch (e) { bad.push(`${f.originalname}: ${e.message}`); }
}
const days = done.reduce((a, r) => a + r.days, 0);
const from = done.map(r => r.from).filter(Boolean).sort()[0], to = done.map(r => r.to).filter(Boolean).sort().pop();
const msg = (done.length ? `Imported ${days} days of Twitch analytics${from ? ` (${from} – ${to})` : ''} from ${done.length} file${done.length === 1 ? '' : 's'}.` : '')
+ (bad.length ? ` Import failed: ${bad.join('; ')}` : '');
res.redirect((req.query.back === 'settings' ? '/settings/stats?msg=' : '/stats?msg=') + encodeURIComponent(msg || 'No files chosen'));
});
// renamed on Twitch: move a viewer's StreamElements watch time (from before our tracking) to the new name
router.post('/viewer/rename', (req, res) => {
try {
const to = seimport.rename(req.body.from, req.body.to);
const to = watchtime.renameBaseline(req.body.from, req.body.to);
res.redirect('/stats/viewer?q=' + encodeURIComponent(to));
} catch (e) { res.redirect('/stats?msg=' + encodeURIComponent('Rename failed: ' + e.message)); }
});
// public stats page: leave out / show again (same as the viewer typing !hideme / !showme)
router.post('/viewer/public', (req, res) => {
const login = String(req.body.login || '').toLowerCase(), key = String(req.body.user_id || '') || `name:${login}`;
periodstats.setOptout(key, login, req.body.hide === '1');
res.redirect('/stats/viewer?q=' + encodeURIComponent(login));
});
// removal request: forget a viewer completely (stats, watch time, raw chat; activity log entries too)
router.post('/viewer/forget', (req, res) => {
const login = String(req.body.login || '').toLowerCase(), id = String(req.body.user_id || '');
if (id) { chatlog.forgetUser(id); watchtime.forgetUser(id); } else if (login) chatlog.forgetUser(login);
periodstats.forgetUser(id || null, login || null); // also the rows keyed by name (tips, watch streaks)
if (login) db.raw().prepare('DELETE FROM activity_log WHERE lower(username) = ?').run(login);
if (login && has('watch_import')) db.raw().prepare('DELETE FROM watch_import WHERE user_login = ?').run(login); // StreamElements minutes too
console.log(`[stats] forgot viewer ${login || id}`);
res.redirect('/stats');
});