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')) { 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); 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')) { 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); 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 chatlog = require('../chatlog');
const watchtime = require('../watchtime'); const watchtime = require('../watchtime');
const points = require('../points'); 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 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 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 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 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 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])); const loginOf = new Map([...users, ...watchers].map(r => [r.user_id, r.user_login]));
@ -52,7 +61,7 @@ router.get('/', (req, res) => {
overview: { overview: {
viewers: viewers.length, viewers: viewers.length,
messages: users.reduce((s, r) => s + r.messages, 0), 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, streams: one('SELECT COUNT(*) n FROM stream_session').n || 0,
checkins: one('SELECT COUNT(*) n FROM stream_checkin').n || 0, checkins: one('SELECT COUNT(*) n FROM stream_checkin').n || 0,
since: one('SELECT MIN(first_seen) t FROM chat_user').t || null, 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) })), perDay: d30.map(day => ({ day, messages: msgDay.get(day) || 0, watchHours: +((watchDay.get(day) || 0) / 60).toFixed(1) })),
boards: { 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 })), 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 })), 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']), bits: sumAct(['bits', 'power_up', 'custom_power_up']),
channelPoints: sumAct(['channel_points', 'auto_reward']), 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), 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), commands: [...commands.entries()].map(([command, uses]) => ({ command, uses })).sort((a, b) => b.uses - a.uses).slice(0, 15),
q: '', viewer: null, 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> // one viewer: /stats/viewer?q=<login>
router.get('/viewer', (req, res) => { router.get('/viewer', (req, res) => {
chatlog.init(); watchtime.init(); chatlog.init(); watchtime.init();
@ -86,6 +107,7 @@ router.get('/viewer', (req, res) => {
hidden: chatlog.isHidden(v.login), hidden: chatlog.isHidden(v.login),
chat: id ? one('SELECT * FROM chat_user WHERE user_id = ?', id) : {}, chat: id ? one('SELECT * FROM chat_user WHERE user_id = ?', id) : {},
watch: id ? one('SELECT * FROM watch_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, 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) : [], 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) : [], 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('./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('./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 // Resume EventSub with the stored login, so alerts survive restarts and deploys
// without logging in again. (Set EVENTSUB_DISABLED=1 for local UI work.) // without logging in again. (Set EVENTSUB_DISABLED=1 for local UI work.)

View file

@ -29,6 +29,7 @@
.search input, .search button { margin:0; } .search input, .search button { margin:0; }
.search button { width:auto; } .search button { width:auto; }
.empty { color:var(--pico-muted-color); font-size:.85rem; font-style:italic; } .empty { color:var(--pico-muted-color); font-size:.85rem; font-style:italic; }
.warn { color:#e6b800; }
</style> </style>
<div style="display:flex; align-items:center; gap:1rem; flex-wrap:wrap;"> <div style="display:flex; align-items:center; gap:1rem; flex-wrap:wrap;">
@ -44,6 +45,16 @@
· <%= hiddenCount %> hidden bot<%= hiddenCount === 1 ? '' : 's' %> left out ⓘ · <%= hiddenCount %> hidden bot<%= hiddenCount === 1 ? '' : 's' %> left out ⓘ
</p> </p>
<% if (msg) { %><p class="<%= /failed/i.test(msg) ? 'warn' : '' %>" style="font-weight:600;"><%= msg %></p><% } %>
<% if (se.configured) { %>
<form method="POST" action="/stats/import-se" style="display:flex; gap:.6rem; align-items:center; flex-wrap:wrap; margin:.2rem 0 .8rem;">
<button type="submit" class="outline" style="width:auto; margin:0; padding:.3rem .9rem; font-size:.85rem;"
title="Copies StreamElements' watch time (per viewer) into HeyStreamer once. It counts like our own watch time (5 points per 5 minutes). Importing again replaces the previous import.<%= se.ownTicks ? ' HeyStreamer is already counting watch time itself: StreamElements has counted those streams too, so importing again now counts them twice.' : '' %>">
<%= se.n ? 'Import again from StreamElements' : 'Import watch time from StreamElements' %></button>
<span class="meta"><%= se.n ? `Imported ${se.n} viewers · ${Math.round(se.m / 60)} h on ${String(se.at).slice(0, 10)}` : 'Not imported yet: best done before the first stream HeyStreamer counts.' %>
<% if (se.n && se.ownTicks) { %><span class="warn"> · importing again would double-count streams since then</span><% } %></span>
</form>
<% } %>
<div class="tiles"> <div class="tiles">
<div class="tile"><div class="v"><%= overview.viewers.toLocaleString() %></div><div class="k">viewers seen</div></div> <div class="tile"><div class="v"><%= overview.viewers.toLocaleString() %></div><div class="k">viewers seen</div></div>
<div class="tile"><div class="v"><%= overview.messages.toLocaleString() %></div><div class="k">chat messages</div></div> <div class="tile"><div class="v"><%= overview.messages.toLocaleString() %></div><div class="k">chat messages</div></div>

View file

@ -20,7 +20,7 @@
<p class="meta">No statistics for this viewer (yet). Names are Twitch logins, e.g. <code>channel</code>.</p> <p class="meta">No statistics for this viewer (yet). Names are Twitch logins, e.g. <code>channel</code>.</p>
<% } else { <% } else {
const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${m % 60} m` : `${m} m`; const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${m % 60} m` : `${m} m`;
const minutes = (viewer.watch.ticks || 0) * 5; %> const minutes = (viewer.watch.ticks || 0) * 5 + (viewer.importedMinutes || 0); %>
<h2 style="margin-bottom:.2rem;"><%= viewer.name %> <span class="meta">@<%= viewer.login %></span></h2> <h2 style="margin-bottom:.2rem;"><%= viewer.name %> <span class="meta">@<%= viewer.login %></span></h2>
<p class="meta"><%= viewer.level.name %> <p class="meta"><%= viewer.level.name %>
<% if (viewer.hidden) { %> · <span class="badge badge-grey" title="In Settings → Hidden chatters: counted, but not shown in leaderboards">hidden bot</span><% } %> <% if (viewer.hidden) { %> · <span class="badge badge-grey" title="In Settings → Hidden chatters: counted, but not shown in leaderboards">hidden bot</span><% } %>
@ -30,7 +30,7 @@
<div class="card"> <div class="card">
<div class="tiles"> <div class="tiles">
<div class="tile"><div class="v"><%= viewer.total.toLocaleString() %></div><div class="k">points</div></div> <div class="tile"><div class="v"><%= viewer.total.toLocaleString() %></div><div class="k">points</div></div>
<div class="tile"><div class="v"><%= hm(minutes) %></div><div class="k">watched</div></div> <div class="tile" title="<%= viewer.importedMinutes ? `includes ${hm(viewer.importedMinutes)} imported from StreamElements` : '' %>"><div class="v"><%= hm(minutes) %></div><div class="k">watched<%= viewer.importedMinutes ? ' · incl. StreamElements' : '' %></div></div>
<div class="tile"><div class="v"><%= (viewer.chat.messages || 0).toLocaleString() %></div><div class="k">chat messages</div></div> <div class="tile"><div class="v"><%= (viewer.chat.messages || 0).toLocaleString() %></div><div class="k">chat messages</div></div>
<div class="tile"><div class="v"><%= viewer.checkins %></div><div class="k">check-ins</div></div> <div class="tile"><div class="v"><%= viewer.checkins %></div><div class="k">check-ins</div></div>
</div> </div>