// 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= 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;