heystreamer/src/routers/stats.js
Bashy c481ca92cb 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>
2026-11-23 11:22:49 +02:00

127 lines
7.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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();
const db = require('../db');
const chatlog = require('../chatlog');
const watchtime = require('../watchtime');
const points = require('../points');
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) || {};
router.get('/', (req, res) => {
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.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,
});
});
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) => {
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) : {},
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) : [],
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),
},
});
});
// 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 = 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');
});
module.exports = router;