Stats: move a renamed viewer's StreamElements watch time to their new name

Viewer page (import-only viewers): 'Renamed on Twitch? New name -> Move'. Moves the
imported minutes (adding to any already there) and stores old -> new in watch_alias,
which importing again applies, so the hours never jump back to the old name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-22 18:10:00 +02:00
parent 3a312ab493
commit 5bf4bffaa0
3 changed files with 53 additions and 5 deletions

View file

@ -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 || '');

View file

@ -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 };

View file

@ -68,7 +68,16 @@
</table>
<% } %>
<form method="POST" action="/stats/viewer/forget" style="margin-top:1.5rem;">
<% if (viewer.importedMinutes && !viewer.user_id) { %>
<form method="POST" action="/stats/viewer/rename" style="display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-top:1.5rem;"
title="This viewer is only known from the StreamElements import (by name). If they renamed on Twitch, their imported watch time moves to the new name, and importing again later applies the rename too.">
<input type="hidden" name="from" value="<%= viewer.login %>">
<span class="meta">Renamed on Twitch? New name:</span>
<input name="to" required pattern="@?\w{2,25}" placeholder="new Twitch login" style="width:14rem; margin:0; padding:.25rem .5rem; font-size:.85rem; height:auto;">
<button type="submit" class="outline btn-sm">Move</button>
</form>
<% } %>
<form method="POST" action="/stats/viewer/forget" style="margin-top:1rem;">
<input type="hidden" name="login" value="<%= viewer.login %>">
<input type="hidden" name="user_id" value="<%= viewer.user_id || '' %>">
<button type="button" data-confirm class="outline btn-sm" style="color:#f88; border-color:#f88;"