Watch time: one 5-minute tick while live (lurkers included), per-stream check-ins

watchtime.js: stream.online/offline (+ Helix /streams check at start) give the live
state; every 5 min the chatter list (Helix /chat/chatters, new scope
moderator:read:chatters) gets +1 tick = 5 minutes = 5 points, overall and per day,
so watch time and points share one sync. First chat message per stream is stored as
a check-in. Without the scope the tick logs once and skips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-22 17:35:21 +02:00
parent f4ee205d4a
commit 1c36e80f66
6 changed files with 145 additions and 2 deletions

View file

@ -124,6 +124,7 @@ function onMessage(e) {
const scored = !prev?.last_scored || Date.parse(at) - Date.parse(prev.last_scored) >= SCORE_GAP_MS ? 1 : 0;
if (scored) d.prepare('UPDATE chat_user SET scored = scored + 1, last_scored = ? WHERE user_id = ?').run(at, e.chatter_user_id);
if (e.message_type === 'user_intro') d.prepare('UPDATE chat_user SET intro = 1 WHERE user_id = ?').run(e.chatter_user_id);
require('./watchtime').checkin(e.chatter_user_id); // first message of this stream = check-in
d.prepare(`INSERT INTO chat_user_day (user_id, day, messages, scored) VALUES (?, ?, 1, ?)
ON CONFLICT(user_id, day) DO UPDATE SET messages = messages + 1, scored = scored + excluded.scored`).run(e.chatter_user_id, day, scored);
const em = d.prepare(`INSERT INTO chat_emote (user_id, emote, source, emote_id, uses, last_used) VALUES (?, ?, ?, ?, 1, ?)
@ -191,6 +192,7 @@ function forgetUser(userIdOrLogin) {
const d = db.raw();
const u = d.prepare('SELECT user_id FROM chat_user WHERE user_id = ? OR user_login = ?').get(String(userIdOrLogin), String(userIdOrLogin).toLowerCase());
const login = String(userIdOrLogin).toLowerCase();
if (u) require('./watchtime').forgetUser(u.user_id);
if (u) for (const t of ['chat_raw', 'chat_user', 'chat_user_day', 'chat_emote', 'chat_command']) d.prepare(`DELETE FROM ${t} WHERE user_id = ?`).run(u.user_id);
const n = d.prepare('DELETE FROM chat_action WHERE user_key = ? OR user_key = ? OR user_login = ?').run(u ? u.user_id : '-', `name:${login}`, login).changes;
return u || n ? 1 : 0;

View file

@ -9,6 +9,7 @@ const twitch = require('./twitch');
const alerts = require('./alerts');
const redeems = require('./redeems');
const chatlog = require('./chatlog');
const watchtime = require('./watchtime');
const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws';
@ -129,6 +130,9 @@ async function subscribeAll(sessionId) {
{ type: 'channel.custom_power_up_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
// subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details
{ type: 'channel.chat.notification', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
// watch time (watchtime.js): live state for the 5-minute ticks and per-stream check-ins
{ type: 'stream.online', version: '1', condition: { broadcaster_user_id: b } },
{ type: 'stream.offline', version: '1', condition: { broadcaster_user_id: b } },
// chat statistics (chatlog.js): every message, plus deletes / timeouts+bans / clears to drop stored text
{ type: 'channel.chat.message', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
{ type: 'channel.chat.message_delete', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
@ -151,6 +155,8 @@ async function subscribeAll(sessionId) {
try { await twitch.validate(); } catch (e) { console.error('[eventsub]', e.message); }
watchtime.checkLive(); // restarted mid-stream: pick up the running stream
status.subscribed = [];
status.failed = [];
for (const sub of subs) {
@ -215,6 +221,12 @@ function handleNotification(payload) {
if (alert) alerts.send(alert, event);
break;
}
case 'stream.online':
watchtime.online(event.id, event.started_at);
break;
case 'stream.offline':
watchtime.offline();
break;
case 'channel.chat.message':
try { chatlog.onMessage(event); } catch (e) { console.error('[chatlog]', e.message); }
break;

View file

@ -15,6 +15,7 @@ const SCOPES = [
'channel:read:polls', // channel.poll.* (poll card on the overlay)
'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)
].join(' ');
router.get('/login', (req, res) => {

View file

@ -20,6 +20,7 @@ server.listen(PORT, () => {
console.log(`[server] DB_PATH: ${process.env.DB_PATH}`);
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)
// Resume EventSub with the stored login, so alerts survive restarts and deploys
// without logging in again. (Set EVENTSUB_DISABLED=1 for local UI work.)

127
src/watchtime.js Normal file
View file

@ -0,0 +1,127 @@
// Watch time. While the channel is live, one tick every 5 minutes: the chatter list (Helix GET /chat/chatters,
// lurkers included) gets +1 tick = 5 minutes. Watch time and watch points come from the same tick
// (points = ticks x 5), so they can never drift apart.
//
// stream_session one row per stream (Twitch stream id, start, end)
// watch_user per viewer: ticks (x5 = minutes and points), first/last seen watching
// watch_user_day per viewer per day: ticks
// stream_checkin per viewer per stream: first chat message time (point system check-in)
//
// Live state: EventSub stream.online / stream.offline, plus a Helix /streams check at start (server restarted
// mid-stream). Needs the moderator:read:chatters scope; without it the tick logs once and skips.
// Bots are counted (statistics hide Settings → Hidden chatters when showing data, see chatlog.js).
const db = require('./db');
const twitch = require('./twitch');
const TICK_MS = 5 * 60 * 1000;
let live = null; // { id, started_at } of the current stream
let timer = null, ready = false, warnedScope = false;
function init() {
if (ready) return;
db.raw().exec(`
CREATE TABLE IF NOT EXISTS stream_session (id TEXT PRIMARY KEY, started_at TEXT, ended_at TEXT, ticks INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS watch_user (
user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, ticks INTEGER DEFAULT 0, first_seen TEXT, last_seen TEXT
);
CREATE TABLE IF NOT EXISTS watch_user_day (
user_id TEXT NOT NULL, day TEXT NOT NULL, ticks INTEGER DEFAULT 0, PRIMARY KEY (user_id, day)
);
CREATE TABLE IF NOT EXISTS stream_checkin (
stream_id TEXT NOT NULL, user_id TEXT NOT NULL, at TEXT, PRIMARY KEY (stream_id, user_id)
);
`);
ready = true;
}
function startTicking() {
clearInterval(timer);
timer = setInterval(() => tick().catch(e => console.warn('[watchtime] tick:', e.message)), TICK_MS);
timer.unref?.();
}
function online(id, startedAt) {
init();
if (live?.id === id) return;
live = { id: String(id), started_at: startedAt || new Date().toISOString() };
db.raw().prepare('INSERT OR IGNORE INTO stream_session (id, started_at) VALUES (?, ?)').run(live.id, live.started_at);
console.log(`[watchtime] live (stream ${live.id}) — counting every 5 min`);
startTicking();
}
function offline() {
init();
if (!live) return;
db.raw().prepare('UPDATE stream_session SET ended_at = ? WHERE id = ?').run(new Date().toISOString(), live.id);
console.log(`[watchtime] offline (stream ${live.id})`);
live = null;
clearInterval(timer); timer = null;
}
// server (re)started: are we live right now?
async function checkLive() {
init();
const u = twitch.getUser();
if (!u) return;
try {
const r = await twitch.helix(`/streams?user_id=${u.twitch_id}`);
if (!r.ok) return;
const s = (await r.json()).data?.[0];
if (s) online(s.id, s.started_at); else offline();
} catch (e) { console.warn('[watchtime] live check:', e.message); }
}
async function chatters() {
const u = twitch.getUser();
const out = [];
let after = '';
for (let page = 0; page < 20; page++) {
const r = await twitch.helix(`/chat/chatters?broadcaster_id=${u.twitch_id}&moderator_id=${u.twitch_id}&first=1000${after ? `&after=${after}` : ''}`);
if (r.status === 401 || r.status === 403) {
if (!warnedScope) { warnedScope = true; console.warn('[watchtime] no permission to read the chatter list: log in again on the dashboard (moderator:read:chatters)'); }
return null;
}
if (!r.ok) throw new Error(`chatters ${r.status}`);
const j = await r.json();
out.push(...(j.data || []));
after = j.pagination?.cursor;
if (!after) break;
}
warnedScope = false;
return out;
}
async function tick() {
if (!live) return;
const list = await chatters();
if (!list) return;
const at = new Date().toISOString(), day = at.slice(0, 10);
const d = db.raw();
d.transaction(() => {
const w = d.prepare(`INSERT INTO watch_user (user_id, user_login, user_name, ticks, first_seen, last_seen) VALUES (?, ?, ?, 1, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET ticks = ticks + 1, user_login = excluded.user_login,
user_name = excluded.user_name, last_seen = excluded.last_seen`);
const wd = d.prepare(`INSERT INTO watch_user_day (user_id, day, ticks) VALUES (?, ?, 1)
ON CONFLICT(user_id, day) DO UPDATE SET ticks = ticks + 1`);
for (const c of list) { w.run(c.user_id, c.user_login, c.user_name, at, at); wd.run(c.user_id, day); }
d.prepare('UPDATE stream_session SET ticks = ticks + 1 WHERE id = ?').run(live.id);
})();
console.log(`[watchtime] tick: ${list.length} watching`);
}
// chatlog.js: first message of this viewer in the current stream = check-in
function checkin(userId) {
if (!live || !userId) return false;
init();
return db.raw().prepare('INSERT OR IGNORE INTO stream_checkin (stream_id, user_id, at) VALUES (?, ?, ?)')
.run(live.id, String(userId), new Date().toISOString()).changes > 0;
}
function forgetUser(userId) {
init();
for (const t of ['watch_user', 'watch_user_day', 'stream_checkin']) db.raw().prepare(`DELETE FROM ${t} WHERE user_id = ?`).run(String(userId));
}
const isLive = () => !!live;
module.exports = { init, online, offline, checkLive, tick, checkin, forgetUser, isLive, TICK_MS };