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,45 +0,0 @@
const express = require('express');
const router = express.Router();
const db = require('../db');
const dispatch = require('../dispatch');
const { resetCooldown } = require('../cooldowns');
router.get('/', (req, res) => {
const actions = db.getAllActions();
const media = db.getAllMedia();
res.render('actions', { actions, media });
});
router.post('/', (req, res) => {
const { name, event_type, event_detail, action_type, media_file_id, alert_text, cooldown_seconds } = req.body;
db.createAction({
name,
event_type,
event_detail: event_detail || null,
action_type,
media_file_id: media_file_id ? parseInt(media_file_id) : null,
alert_text: alert_text || null,
cooldown_seconds: parseInt(cooldown_seconds) || 0,
});
res.redirect('/actions');
});
router.post('/:id/test', (req, res) => {
const action = db.getAction(parseInt(req.params.id));
if (!action) return res.status(404).send('Not found');
resetCooldown(action.id);
dispatch.dispatchEvent(action.event_type, action.event_detail, 'test');
res.redirect('/actions');
});
router.post('/:id/toggle', (req, res) => {
db.toggleAction(parseInt(req.params.id));
res.redirect('/actions');
});
router.post('/:id/delete', (req, res) => {
db.deleteAction(parseInt(req.params.id));
res.redirect('/actions');
});
module.exports = router;

40
src/routers/alertsetup.js Normal file
View file

@ -0,0 +1,40 @@
// Actions → Alerts: how follows, subs, gifts, raids, bits, tips and the Hype Train look and sound (src/theme.js).
const express = require('express');
const router = express.Router();
const db = require('../db');
const ws = require('../ws');
const theme = require('../theme');
const library = require('../library');
router.get('/', (req, res) => {
const media = library.list();
res.render('alerts_setup', {
theme: theme.get(),
images: media.filter(m => m.type === 'image'),
sounds: media.filter(m => m.type === 'audio'),
});
});
// preview: the real overlay code with a button per alert; looks: the defaults, the optional styles, this channel's own
function previewThemes() {
const optional = theme.merge(theme.DEFAULT, { style: 'polaroid', redeemStyle: 'cassette', ttsStyle: 'letter' });
return {
mine: { label: 'Your alerts', theme: theme.get() },
defaults: { label: 'Defaults (Card)', theme: theme.DEFAULT },
optional: { label: 'Polaroid / Cassette / Letter', theme: optional },
};
}
router.get('/preview', (req, res) => {
res.render('alerts_preview', { layout: false, base: '/alerts/', themes: previewThemes(), start: req.query.look || 'mine', samples: require('../alerts').SAMPLES });
});
// whole theme as JSON from the editor
router.post('/', express.json({ limit: '200kb' }), (req, res) => {
try {
const t = theme.save(req.body || {});
ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); // overlays use it at once
res.json({ ok: true, theme: t });
} catch (e) { res.status(400).json({ ok: false, error: e.message }); }
});
module.exports = router;

View file

@ -16,6 +16,8 @@ const SCOPES = [
'channel:read:hype_train', // channel.hype_train.* (Hype Train alerts)
'channel:manage:raids', // start/cancel raids from the dashboard (send-off card stays during the countdown)
'moderator:read:chatters', // watch time: chatter list every 5 min while live (watchtime.js)
'moderation:read', // stats: who is a moderator (twitchsync.js)
'channel:read:vips', // stats: who is a VIP (twitchsync.js)
].join(' ');
router.get('/login', (req, res) => {

38
src/routers/public.js Normal file
View file

@ -0,0 +1,38 @@
// Public stats page (no login): stream / week / month / year / all time, the same numbers as the admin Stats page
// (periodstats.js + views/_statsbody.ejs). Served at the host in Settings → Public stats page (e.g.
// stats.example.com, routed in app.js) and at /public on the admin host (works while logged in even when off).
// Never shown here: message text, bots (Settings → Hidden chatters), names of viewers who typed !hideme.
const express = require('express');
const router = express.Router();
const db = require('../db');
const chatlog = require('../chatlog');
const watchtime = require('../watchtime');
const periodstats = require('../periodstats');
const points = require('../points');
router.get('/', (req, res) => {
const st = db.getSettings();
if (!st.public_stats_enabled && !req.session?.userId) return res.status(404).send('Not found');
chatlog.init(); watchtime.init(); periodstats.init();
const range = periodstats.parseRange(req.query, 'all');
const user = db.getPrimaryUser();
// the streamer herself is counted in the totals but not on the public leaderboards
const anonymous = periodstats.optedOut();
if (user) { anonymous.keys.add(String(user.twitch_id)); if (user.login) anonymous.logins.add(user.login.toLowerCase()); }
const s = periodstats.summary(range, { hidden: chatlog.hiddenUsers(), anonymous });
const channel = (st.channel || user?.login || '').replace(/^#/, '');
// community ranks (Regular and up, all time), without bots, the streamer and !hideme viewers
const hidden = new Set(chatlog.hiddenUsers());
const ranks = [...points.everyone().values()]
.filter(x => x.level.name !== 'Viewer' && !hidden.has(String(x.login || '').toLowerCase())
&& !anonymous.logins.has(String(x.login || '').toLowerCase()) && !anonymous.keys.has(String(x.user_id || x.key)))
.sort((a, b) => (b.watchMinutes || 0) - (a.watchMinutes || 0)).map(x => ({ login: x.login, name: x.name, level: x.level.name }));
res.set('Cache-Control', 'public, max-age=60');
res.render('public_stats', {
layout: false, s, q: periodstats.rangeQuery, base: req.baseUrl || '', ranks, view: req.query.v === 'streams' ? 'streams' : 'community', tz: st.timezone || 'UTC',
channel, displayName: user?.display_name || channel, live: watchtime.isLive(),
preview: !st.public_stats_enabled,
});
});
module.exports = router;

View file

@ -77,6 +77,7 @@ router.get('/', async (req, res) => {
for (const g of groups) for (const t of g.items) t.variations = byTrigger.get(`${t.kind}|${t.key}`) || [];
res.render('redeems', {
theme: require('../theme').get(),
groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY,
sounds: soundOptions(),
videos: videoOptions(),
@ -91,14 +92,16 @@ router.post('/variation', (req, res) => {
const { kind, key, title } = req.body;
if (!['reward', 'auto_reward', 'power_up', 'custom_power_up'].includes(kind) || !key) return res.status(400).send('bad trigger');
const n = db.getVariationsFor(kind, key).length;
const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key) });
const look = require('../theme').get().redeemStyle === 'cassette' ? 'cassette' : 'card'; // Actions → Alerts: look of new variations
const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key), look });
back(res, v);
});
// one variation's fields from the editor. display: cassette | sound (sound only) | video
// one variation's fields from the editor. display: card | cassette | sound (sound only) | video
function cleanVariation(v, b) {
const vol = parseFloat(b.volume);
const display = ['cassette', 'sound', 'video'].includes(b.display) ? b.display : (v.video ? 'video' : v.polaroid ? 'cassette' : 'sound');
const was = v.video ? 'video' : !v.polaroid ? 'sound' : v.look === 'card' ? 'card' : 'cassette';
const display = ['card', 'cassette', 'sound', 'video'].includes(b.display) ? b.display : was;
const videos = new Set(videoOptions().map(o => o.url));
const video = display === 'video' && videos.has(b.video) ? b.video : '';
const on = x => x === true || x === 'on' || x === 1 || x === '1';
@ -107,7 +110,8 @@ function cleanVariation(v, b) {
rarity: redeems.RARITY[b.rarity] ? b.rarity : v.rarity,
sound: String(b.sound || ''),
volume: isNaN(vol) ? v.volume : Math.max(0, Math.min(1, vol)),
polaroid: display === 'cassette' ? 1 : 0,
polaroid: display === 'cassette' || display === 'card' ? 1 : 0,
look: display === 'card' ? 'card' : display === 'cassette' ? 'cassette' : v.look || '',
video,
caption: String(b.caption || '').trim().slice(0, 120) || 'redeemed it! ♡',
art: String(b.art || ''),

View file

@ -1,17 +1,15 @@
// Settings: one page per category (sidebar in views/layout.ejs, list in src/nav.js). Each page saves only its own
// fields, so saving one page never resets another. Views: views/settings/<section>.ejs.
const express = require('express');
const router = express.Router();
const db = require('../db');
const eventsub = require('../eventsub');
const ws = require('../ws');
const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; };
const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
router.get('/', (req, res) => {
const settings = db.getSettings();
const baseUrl = process.env.APP_BASE_URL;
res.render('settings', { settings, baseUrl });
});
const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
const on = v => v === 'on' ? 1 : 0;
const logins = v => String(v || '').split(/[\s,]+/).map(s => s.replace(/^@/, '').toLowerCase()).filter(Boolean).join(', ').slice(0, 2000);
const validTz = tz => { try { new Intl.DateTimeFormat('en', { timeZone: tz }); return true; } catch { return false; } };
// only a real HUDFX overlay link (https://overlays.hudfx.io/overlay/<id>), anything else clears it
function hudfxUrl(v) {
@ -21,42 +19,94 @@ function hudfxUrl(v) {
} catch { return ''; }
}
router.post('/', (req, res) => {
const b = req.body;
db.updateSettings({
channel: b.channel || '',
message_timeout: int(b.message_timeout, 30),
max_messages: int(b.max_messages, 20),
gap_audio_enabled: b.gap_audio_enabled === 'on' ? 1 : 0,
gap_audio_url: b.gap_audio_url || '',
gap_audio_min_silence: int(b.gap_audio_min_silence, 60),
gap_audio_min_volume: flt(b.gap_audio_min_volume, 0.2),
gap_audio_max_volume: flt(b.gap_audio_max_volume, 1.0),
gap_audio_loud_after: int(b.gap_audio_loud_after, 3600),
tts_max_chars: Math.max(20, Math.min(500, int(b.tts_max_chars, 200))),
tts_say_name: b.tts_say_name === 'on' ? 1 : 0,
tts_blocklist: String(b.tts_blocklist || '').slice(0, 20000),
hudfx_overlay_url: hudfxUrl(b.hudfx_overlay_url),
chat_hidden_users: String(b.chat_hidden_users || '').split(/[\s,]+/).map(s => s.replace(/^@/, '').toLowerCase()).filter(Boolean).join(', ').slice(0, 2000),
chat_hide_commands: b.chat_hide_commands === 'on' ? 1 : 0,
custom_css: b.custom_css || '',
custom_js: b.custom_js || '',
});
// section -> fields it owns (parsed from the form)
const FIELDS = {
general: b => ({
channel: String(b.channel || '').trim().replace(/^#/, '').toLowerCase().slice(0, 25),
timezone: validTz(b.timezone) ? b.timezone : (db.getSettings().timezone || 'UTC'), // invalid: keep the old one
}),
chat: b => ({
message_timeout: int(b.message_timeout, 30), max_messages: int(b.max_messages, 20),
chat_hidden_users: logins(b.chat_hidden_users), chat_hide_commands: on(b.chat_hide_commands),
gap_audio_enabled: on(b.gap_audio_enabled), gap_audio_url: String(b.gap_audio_url || '').trim(),
gap_audio_min_silence: int(b.gap_audio_min_silence, 60), gap_audio_min_volume: flt(b.gap_audio_min_volume, 0.2),
gap_audio_max_volume: flt(b.gap_audio_max_volume, 1.0), gap_audio_loud_after: int(b.gap_audio_loud_after, 3600),
}),
tts: b => ({
tts_max_chars: Math.max(20, Math.min(500, int(b.tts_max_chars, 200))), tts_say_name: on(b.tts_say_name),
tts_blocklist: String(b.tts_blocklist || '').slice(0, 20000),
}),
stats: b => ({
public_stats_enabled: on(b.public_stats_enabled),
public_stats_host: String(b.public_stats_host || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '').replace(/[^a-z0-9.-]/g, '').slice(0, 200),
}),
advanced: b => ({ custom_css: b.custom_css || '', custom_js: b.custom_js || '' }),
hudfx: b => ({ hudfx_overlay_url: hudfxUrl(b.hudfx_overlay_url) }),
};
const PAGES = ['general', 'connections', 'obs', 'chat', 'tts', 'stats', 'backup', 'advanced'];
// Push updated settings to all connected overlays so they don't need a page reload
ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() });
function locals(section, req) {
const settings = db.getSettings();
const base = (process.env.APP_BASE_URL || '').replace(/\/$/, '');
const out = { section, settings, base, overlayUrl: `${base}/overlay/${settings.overlay_id}`, msg: req.query.msg || null, err: req.query.err || null };
if (section === 'connections') {
out.eventsub = require('../eventsub').getStatus();
out.se = require('../streamelements').getStatus();
out.user = db.getPrimaryUser();
}
if (section === 'chat') out.sounds = require('../library').list().filter(m => m.type === 'audio');
if (section === 'stats') {
out.sync = require('../twitchsync').lastStatus();
out.csv = require('../twitchcsv').status();
}
return out;
}
console.log(`[settings] Saved — channel: ${b.channel}, gap_audio: ${b.gap_audio_enabled === 'on'}`);
res.redirect('/settings');
router.get('/', (req, res) => res.redirect('/settings/general'));
router.get('/:section', (req, res, next) => {
const s = req.params.section;
if (!PAGES.includes(s)) return next();
res.render(`settings/${s}`, locals(s, req));
});
router.post('/reconnect', (req, res) => {
const user = db.getUserById(req.session.userId);
if (user) {
eventsub.start(user);
console.log('[settings] EventSub reconnect triggered');
}
res.redirect('/settings');
router.post('/:section', (req, res, next) => {
const s = req.params.section;
if (!FIELDS[s]) return next();
db.updateSettings(FIELDS[s](req.body));
ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); // overlays update without a reload
const page = s === 'hudfx' ? 'connections' : s;
res.redirect(`/settings/${page}?msg=` + encodeURIComponent('Saved'));
});
// Connections: StreamElements token (secret: never sent back to the page, only "set / not set")
router.post('/connections/se', (req, res) => {
const token = String(req.body.se_jwt || '').trim();
if (req.body.clear === '1') db.updateSettings({ se_jwt: '' });
else if (token) db.updateSettings({ se_jwt: token.slice(0, 4000) });
require('../streamelements').restart();
res.redirect('/settings/connections?msg=' + encodeURIComponent(req.body.clear === '1' ? 'StreamElements token removed' : token ? 'StreamElements token saved, connecting…' : 'Reconnecting to StreamElements…'));
});
router.post('/connections/reconnect', (req, res) => {
const user = db.getUserById(req.session.userId) || db.getPrimaryUser();
if (user) require('../eventsub').start(user);
res.redirect('/settings/connections?msg=' + encodeURIComponent('Reconnecting to Twitch…'));
});
// Backup: download / restore the whole setup (src/backup.js)
router.get('/backup/export', (req, res) => {
const day = new Date().toISOString().slice(0, 10);
res.set('Content-Disposition', `attachment; filename="heystreamer-backup-${day}.json"`);
res.json(require('../backup').exportAll());
});
const upload = require('multer')({ storage: require('multer').memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } });
router.post('/backup/import', upload.single('file'), (req, res) => {
try {
const r = require('../backup').importAll(JSON.parse(req.file?.buffer?.toString('utf8') || 'null'));
ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() });
res.redirect('/settings/backup?msg=' + encodeURIComponent(`Imported ${r.variations} redeem variations, ${r.voices} TTS voices and the settings`));
} catch (e) { res.redirect('/settings/backup?err=' + encodeURIComponent('Import failed: ' + e.message)); }
});
module.exports = router;

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');
});