Stats: one-time import of StreamElements watch time

seimport.js reads the SE channel from SE_JWT, fetches /kappa/v2/points/<ch>/watchtime
(all pages) into watch_import (login, minutes), replacing any previous import.
Imported minutes count as watch time and watch points (5 per 5 min, merged by
login) on the Stats page, leaderboards and viewer pages. Button on Stats warns that
importing again after our own tracking started double-counts those streams.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-22 17:50:04 +02:00
parent c364e7079b
commit dd0e92c0bb
6 changed files with 95 additions and 5 deletions

View file

@ -48,6 +48,12 @@ function everyone() {
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);
}
// StreamElements watch time imported once (seimport.js): login + minutes, counted like our ticks
if (has('watch_import')) for (const r of all('SELECT user_login, minutes FROM watch_import')) {
const x = get(null, r.user_login, null);
x.importedMinutes = (x.importedMinutes || 0) + r.minutes;
add(x, 'watching (StreamElements)', Math.floor(r.minutes / 5) * 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);
}

View file

@ -6,6 +6,7 @@ const db = require('../db');
const chatlog = require('../chatlog');
const watchtime = require('../watchtime');
const points = require('../points');
const seimport = require('../seimport');
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) : []);
@ -24,7 +25,15 @@ router.get('/', (req, res) => {
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));
// 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]));
@ -52,7 +61,7 @@ router.get('/', (req, res) => {
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),
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,
@ -60,7 +69,7 @@ router.get('/', (req, res) => {
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 })),
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']),
@ -68,9 +77,21 @@ router.get('/', (req, res) => {
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 },
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));
}
});
// one viewer: /stats/viewer?q=<login>
router.get('/viewer', (req, res) => {
chatlog.init(); watchtime.init();
@ -86,6 +107,7 @@ 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,
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) : [],

50
src/seimport.js Normal file
View file

@ -0,0 +1,50 @@
// One-time import of StreamElements' watch time (before HeyStreamer's own tracking, watchtime.js, takes over).
// SE only gives login names + minutes, so the minutes live in their own table, matched to viewers by login;
// points.js counts them like our ticks (5 points per 5 minutes) and the Stats page adds them to watch time.
// Importing again REPLACES the previous import (SE keeps counting streams we also count, so a second import
// after our tracking started would count those minutes twice; the Stats page warns about that).
const db = require('./db');
function init() {
db.raw().exec(`CREATE TABLE IF NOT EXISTS watch_import (
user_login TEXT PRIMARY KEY, minutes INTEGER NOT NULL, source TEXT, imported_at TEXT
)`);
}
// SE channel id is in the JWT payload (claim "channel")
function channelId() {
const jwt = process.env.SE_JWT;
if (!jwt) return null;
try { return JSON.parse(Buffer.from(jwt.split('.')[1], 'base64url').toString()).channel || null; } catch { return null; }
}
async function importWatchtime() {
init();
const ch = channelId();
if (!ch) throw new Error('StreamElements key (SE_JWT) missing or unreadable');
const users = [];
for (let offset = 0; offset < 100000; offset += 1000) {
const r = await fetch(`https://api.streamelements.com/kappa/v2/points/${ch}/watchtime?limit=1000&offset=${offset}`,
{ headers: { Authorization: `Bearer ${process.env.SE_JWT}`, Accept: 'application/json' } });
if (!r.ok) throw new Error(`StreamElements ${r.status}`);
const j = await r.json();
users.push(...(j.users || []));
if (!j.users?.length || users.length >= (j._total || 0)) break;
}
const at = new Date().toISOString(), d = db.raw();
d.transaction(() => {
d.prepare('DELETE FROM watch_import').run();
const ins = d.prepare('INSERT OR REPLACE INTO watch_import (user_login, minutes, source, imported_at) VALUES (?, ?, ?, ?)');
for (const u of users) if (u.username && u.minutes > 0) ins.run(String(u.username).toLowerCase(), Math.round(u.minutes), 'streamelements', at);
})();
const sum = d.prepare('SELECT COUNT(*) n, COALESCE(SUM(minutes), 0) m FROM watch_import').get();
console.log(`[seimport] imported StreamElements watch time: ${sum.n} viewers, ${Math.round(sum.m / 60)} h`);
return { viewers: sum.n, minutes: sum.m, at };
}
function status() {
init();
return db.raw().prepare('SELECT COUNT(*) n, COALESCE(SUM(minutes), 0) m, MAX(imported_at) at FROM watch_import').get();
}
module.exports = { init, importWatchtime, status, channelId };

View file

@ -21,6 +21,7 @@ server.listen(PORT, () => {
require('./chatlog').init(); // chat statistics tables + hourly 30-day cleanup of raw messages
require('./watchtime').init(); // watch time tables (ticks start when the stream goes live)
require('./seimport').init(); // StreamElements watch time import table
// Resume EventSub with the stored login, so alerts survive restarts and deploys
// without logging in again. (Set EVENTSUB_DISABLED=1 for local UI work.)