From dd0e92c0bb738d1eac3b8ae32e3e502aa73f577e Mon Sep 17 00:00:00 2001 From: Bashy Date: Sun, 22 Nov 2026 17:50:04 +0200 Subject: [PATCH] Stats: one-time import of StreamElements watch time seimport.js reads the SE channel from SE_JWT, fetches /kappa/v2/points//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 --- src/points.js | 6 +++++ src/routers/stats.js | 28 ++++++++++++++++++++--- src/seimport.js | 50 ++++++++++++++++++++++++++++++++++++++++++ src/server.js | 1 + views/stats.ejs | 11 ++++++++++ views/stats_viewer.ejs | 4 ++-- 6 files changed, 95 insertions(+), 5 deletions(-) create mode 100644 src/seimport.js diff --git a/src/points.js b/src/points.js index 87e336b..fa9be50 100644 --- a/src/points.js +++ b/src/points.js @@ -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); } diff --git a/src/routers/stats.js b/src/routers/stats.js index 67acb09..2ff8c65 100644 --- a/src/routers/stats.js +++ b/src/routers/stats.js @@ -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= 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) : [], diff --git a/src/seimport.js b/src/seimport.js new file mode 100644 index 0000000..b882f8d --- /dev/null +++ b/src/seimport.js @@ -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 }; diff --git a/src/server.js b/src/server.js index fa4ca9d..9c77551 100644 --- a/src/server.js +++ b/src/server.js @@ -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.) diff --git a/views/stats.ejs b/views/stats.ejs index 30b93a9..9b46da9 100644 --- a/views/stats.ejs +++ b/views/stats.ejs @@ -29,6 +29,7 @@ .search input, .search button { margin:0; } .search button { width:auto; } .empty { color:var(--pico-muted-color); font-size:.85rem; font-style:italic; } + .warn { color:#e6b800; }
@@ -44,6 +45,16 @@ · <%= hiddenCount %> hidden bot<%= hiddenCount === 1 ? '' : 's' %> left out ⓘ

+<% if (msg) { %>

<%= msg %>

<% } %> +<% if (se.configured) { %> +
+ + <%= 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) { %> · importing again would double-count streams since then<% } %> +
+<% } %>
<%= overview.viewers.toLocaleString() %>
viewers seen
<%= overview.messages.toLocaleString() %>
chat messages
diff --git a/views/stats_viewer.ejs b/views/stats_viewer.ejs index 430f9d1..3a1983a 100644 --- a/views/stats_viewer.ejs +++ b/views/stats_viewer.ejs @@ -20,7 +20,7 @@

No statistics for this viewer (yet). Names are Twitch logins, e.g. channel.

<% } else { 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); %>

<%= viewer.name %> @<%= viewer.login %>

<%= viewer.level.name %> <% if (viewer.hidden) { %> · hidden bot<% } %> @@ -30,7 +30,7 @@

<%= viewer.total.toLocaleString() %>
points
-
<%= hm(minutes) %>
watched
+
<%= hm(minutes) %>
watched<%= viewer.importedMinutes ? ' · incl. StreamElements' : '' %>
<%= (viewer.chat.messages || 0).toLocaleString() %>
chat messages
<%= viewer.checkins %>
check-ins