Stats page: overview, activity per day, leaderboards, top emotes/commands, viewer lookup

/stats (dashboard nav): totals, chat messages and watch hours per day (30 days,
single-series bar charts with hover), leaderboards for points (with level), watch
time, chat, bits, channel points spent; top emotes (with images) and commands.
/stats/viewer?q=: one viewer's points breakdown, watch time, messages, check-ins,
emotes, commands, actions, and 'Forget this viewer' (removal requests: stats, watch
time, raw chat, activity log). Bots (Hidden chatters) left out of everything shown.
src/points.js: the agreed point values in one place, calculated from the stats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-22 17:40:05 +02:00
parent 1c36e80f66
commit c364e7079b
6 changed files with 383 additions and 0 deletions

View file

@ -55,6 +55,7 @@ app.use('/ext', require('./routers/ext').router); // HUDFX / Blerp pages serve
// app.use('/nowplaying', require('./routers/nowplaying')); // key-protected push from the PC helper
app.use('/actions', requireAuth, require('./routers/actions'));
app.use('/media', requireAuth, require('./routers/media'));
app.use('/stats', requireAuth, require('./routers/stats'));
app.use('/settings', requireAuth, require('./routers/settings'));
app.use('/alerts', requireAuth, require('./routers/alerts'));
app.use('/redeems', requireAuth, require('./routers/redeems'));

72
src/points.js Normal file
View file

@ -0,0 +1,72 @@
// Points (planned point system, values agreed 2026-11-22, see docs/PLANS.md), calculated from the statistics
// tables, so changing a value here recalculates everyone. Also used by the Stats page; later by !points.
const db = require('./db');
const VALUE = {
watchTick: 5, // per 5-minute watch tick
chat: 10, // per points-eligible message (max 1 per 5 min, counted in chatlog.js)
checkin: 25, // first message of a stream
intro: 50, // first message ever on the channel
follow: 50, // once
bit: 1, // cheers, Power-ups, Custom Power-ups
per100ChannelPoints: 1,
subMonth: { 'Tier 1': 500, Prime: 500, 'Tier 2': 1000, 'Tier 3': 2500 },
tipPerUnit: 100, // per 1 EUR (or whatever currency the tip was in)
raid: 100, // flat, no reward for raid size
streakPer: 5, streakMax: 100,
};
const LEVELS = [ // cassette theme
{ min: 0, name: 'Newcomer' }, { min: 500, name: 'Regular' }, { min: 2000, name: 'Tape Collector' },
{ min: 6000, name: 'Mixtape Maker' }, { min: 15000, name: 'Side B Legend' },
];
const levelOf = p => [...LEVELS].reverse().find(l => p >= l.min);
const has = t => !!db.raw().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t);
const all = (sql, ...a) => db.raw().prepare(sql).all(...a);
// -> Map key -> viewer { key, user_id, login, name, parts: {watch, chat, ...}, total, level }
// key = Twitch user id; viewers known only by name (tips, watch streaks) are merged by login when possible
function everyone() {
const v = new Map(), byLogin = new Map();
const get = (id, login, name) => {
let key = id ? String(id) : null;
if (!key && login && byLogin.has(login)) key = byLogin.get(login);
if (!key) key = `name:${login}`;
if (!v.has(key)) v.set(key, { key, user_id: id || null, login, name: name || login, parts: {}, total: 0 });
const x = v.get(key);
if (login) { byLogin.set(login, key); x.login = x.login || login; }
if (name) x.name = name;
return x;
};
const add = (x, part, pts) => { if (!pts) return; x.parts[part] = (x.parts[part] || 0) + pts; x.total += pts; };
if (has('chat_user')) for (const r of all('SELECT user_id, user_login, user_name, scored, intro FROM chat_user')) {
const x = get(r.user_id, r.user_login, r.user_name);
add(x, 'chat', (r.scored || 0) * VALUE.chat); add(x, 'first message', r.intro ? VALUE.intro : 0);
}
if (has('watch_user')) for (const r of all('SELECT user_id, user_login, user_name, ticks FROM watch_user')) {
add(get(r.user_id, r.user_login, r.user_name), 'watching', (r.ticks || 0) * VALUE.watchTick);
}
if (has('stream_checkin')) for (const r of all('SELECT user_id, COUNT(*) n FROM stream_checkin GROUP BY user_id')) {
add(get(r.user_id, null, null), 'check-ins', r.n * VALUE.checkin);
}
if (has('chat_action')) for (const r of all('SELECT * FROM chat_action ORDER BY user_key LIKE \'name:%\'')) {
const id = r.user_key.startsWith('name:') ? null : r.user_key;
const x = get(id, r.user_login, r.user_name);
switch (r.action) {
case 'follow': add(x, 'follow', VALUE.follow); break;
case 'bits': case 'power_up': case 'custom_power_up': add(x, 'bits', Math.round(r.amount * VALUE.bit)); break;
case 'channel_points': case 'auto_reward': add(x, 'channel points', Math.floor(r.amount / 100) * VALUE.per100ChannelPoints); break;
case 'sub': add(x, 'subs', Math.round(r.amount * (VALUE.subMonth[r.item] || VALUE.subMonth['Tier 1']))); break;
case 'gift_sub': add(x, 'gift subs', Math.round(r.amount * (VALUE.subMonth[r.item] || VALUE.subMonth['Tier 1']))); break;
case 'tip': add(x, 'tips', Math.round(r.amount * VALUE.tipPerUnit)); break;
case 'raid': add(x, 'raids', r.uses * VALUE.raid); break;
case 'watch_streak': add(x, 'watch streak', Math.min(VALUE.streakMax, r.amount * VALUE.streakPer)); break;
}
}
for (const x of v.values()) x.level = levelOf(x.total);
return v;
}
module.exports = { VALUE, LEVELS, levelOf, everyone };

106
src/routers/stats.js Normal file
View file

@ -0,0 +1,106 @@
// Stats page: overview, activity per day, leaderboards, top emotes/commands, viewer lookup, forget a viewer.
// Bots (Settings → Hidden chatters) are counted but left out of everything shown here.
const express = require('express');
const router = express.Router();
const db = require('../db');
const chatlog = require('../chatlog');
const watchtime = require('../watchtime');
const points = require('../points');
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));
const watchers = all('SELECT user_id, user_login, user_name, ticks FROM watch_user').filter(r => ok(r.user_login));
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);
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.ticks, 0) * 5 / 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.ticks - a.ticks).slice(0, 10).map(r => ({ login: r.user_login, name: r.user_name, n: r.ticks * 5 })),
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,
});
});
// one viewer: /stats/viewer?q=<login>
router.get('/viewer', (req, res) => {
chatlog.init(); watchtime.init();
const q = String(req.query.q || '').trim().replace(/^@/, '').toLowerCase();
if (!q) return res.redirect('/stats');
const v = [...points.everyone().values()].find(x => x.login === q || x.key === q);
if (!v) return res.render('stats_viewer', { q, viewer: null });
const id = v.user_id;
res.render('stats_viewer', {
q,
viewer: {
...v,
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) : {},
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) : [],
actions: all('SELECT action, item, uses, amount, unit, last_at FROM chat_action WHERE user_key = ? OR user_login = ? ORDER BY last_at DESC', v.key, v.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);
if (login) db.raw().prepare('DELETE FROM activity_log WHERE lower(username) = ?').run(login);
console.log(`[stats] forgot viewer ${login || id}`);
res.redirect('/stats');
});
module.exports = router;