diff --git a/src/routers/stats.js b/src/routers/stats.js index 2ff8c65..d8bb967 100644 --- a/src/routers/stats.js +++ b/src/routers/stats.js @@ -116,6 +116,14 @@ router.get('/viewer', (req, res) => { }); }); +// renamed on Twitch: move the StreamElements-imported watch time to the new name (and remember it for re-imports) +router.post('/viewer/rename', (req, res) => { + try { + const to = seimport.rename(req.body.from, req.body.to); + res.redirect('/stats/viewer?q=' + encodeURIComponent(to)); + } catch (e) { res.redirect('/stats?msg=' + encodeURIComponent('Rename failed: ' + e.message)); } +}); + // 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 || ''); diff --git a/src/seimport.js b/src/seimport.js index b882f8d..1aa6f07 100644 --- a/src/seimport.js +++ b/src/seimport.js @@ -8,9 +8,35 @@ 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 + ); + CREATE TABLE IF NOT EXISTS watch_alias ( -- renamed on Twitch: StreamElements still lists the old name + old_login TEXT PRIMARY KEY, new_login TEXT NOT NULL, added_at TEXT )`); } +const aliasMap = () => new Map(db.raw().prepare('SELECT old_login, new_login FROM watch_alias').all().map(r => [r.old_login, r.new_login])); + +// Stats page: a viewer renamed on Twitch. Move their imported minutes to the new login (adding to any there) +// and remember it, so importing again applies the rename too. +function rename(fromLogin, toLogin) { + init(); + const from = String(fromLogin || '').trim().replace(/^@/, '').toLowerCase(), to = String(toLogin || '').trim().replace(/^@/, '').toLowerCase(); + if (!/^\w{2,25}$/.test(from) || !/^\w{2,25}$/.test(to) || from === to) throw new Error('invalid name'); + const d = db.raw(); + d.transaction(() => { + d.prepare('INSERT OR REPLACE INTO watch_alias (old_login, new_login, added_at) VALUES (?, ?, ?)').run(from, to, new Date().toISOString()); + d.prepare('UPDATE watch_alias SET new_login = ? WHERE new_login = ?').run(to, from); // chains: a -> from -> to + const old = d.prepare('SELECT minutes, source, imported_at FROM watch_import WHERE user_login = ?').get(from); + if (old) { + d.prepare(`INSERT INTO watch_import (user_login, minutes, source, imported_at) VALUES (?, ?, ?, ?) + ON CONFLICT(user_login) DO UPDATE SET minutes = minutes + excluded.minutes`).run(to, old.minutes, old.source, old.imported_at); + d.prepare('DELETE FROM watch_import WHERE user_login = ?').run(from); + } + })(); + console.log(`[seimport] renamed ${from} -> ${to}`); + return to; +} + // SE channel id is in the JWT payload (claim "channel") function channelId() { const jwt = process.env.SE_JWT; @@ -31,11 +57,16 @@ async function importWatchtime() { users.push(...(j.users || [])); if (!j.users?.length || users.length >= (j._total || 0)) break; } - const at = new Date().toISOString(), d = db.raw(); + const at = new Date().toISOString(), d = db.raw(), alias = aliasMap(); 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 ins = d.prepare(`INSERT INTO watch_import (user_login, minutes, source, imported_at) VALUES (?, ?, ?, ?) + ON CONFLICT(user_login) DO UPDATE SET minutes = minutes + excluded.minutes`); + for (const u of users) { + if (!u.username || !(u.minutes > 0)) continue; + const login = String(u.username).toLowerCase(); + ins.run(alias.get(login) || login, Math.round(u.minutes), 'streamelements', at); // renamed viewers land on their new name + } })(); 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`); @@ -47,4 +78,4 @@ function status() { 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 }; +module.exports = { init, importWatchtime, status, channelId, rename }; diff --git a/views/stats_viewer.ejs b/views/stats_viewer.ejs index 3a1983a..e7f3d3d 100644 --- a/views/stats_viewer.ejs +++ b/views/stats_viewer.ejs @@ -68,7 +68,16 @@ <% } %> -
+ <% } %> +