Stats per stream and period, public stats page, dashboard settings, Card alert style

Statistics
- Per day and per stream statistics (src/periodstats.js, one generic stat_day table), backfilled
  once from the older tables; Stream / Week / Month / Year / All time views, Community and Streams tabs.
- Viewer count every 5 minutes and title / category history per stream (EventSub channel.update):
  viewer graph, games played (donut), games in the streams list.
- Twitch sync (src/twitchsync.js): followers with follow dates, current subs, mods, VIPs, all-time
  bits, channel emotes, past streams from VODs. Twitch analytics CSV import (src/twitchcsv.js).
- Public stats page on its own host (Settings -> Stats and data): no message text, no bots,
  !hideme / !showme opt-out. Viewer page: roles, follow age, sub status, bits, a menu for rarely used actions.
- StreamElements watch-time importer removed (already imported minutes stay as a baseline).

Dashboard
- Settings and Actions with a left sidebar; each settings page saves only its own fields.
  Connections (Twitch, StreamElements token now set here, HUDFX), OBS links (hidden behind an eye
  toggle) with a link builder, Chat (sound picked from the media library), TTS, Stats and data,
  Backup (export / import the whole setup), Advanced. Time zone setting for the stats pages.
- Actions -> Alerts: alert style, pictures, sounds, bits tiers and card colours, stored in the
  database (src/theme.js); an old file-based theme is imported once. Alert preview page
  (/actions/alerts/preview, tools/preview/export.js for a static copy).
- Old /actions page removed; Actions = Redeems / Alerts / TTS voices / Media.

Alerts
- New plain Card style for everyone (public/alerts/card.js); Polaroid, Cassette and the TTS letter
  stay as optional looks. Redeem variations can be Card, Cassette, Sound only or Video.

Repo
- No channel data in git: the channel's art, stickers and sounds stay on disk (gitignored) and are
  picked in the dashboard; examples for the server config (apache.example.sh, .env.example).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-23 11:22:49 +02:00
parent 5bf4bffaa0
commit c481ca92cb
57 changed files with 3080 additions and 774 deletions

411
views/_statsbody.ejs Normal file
View file

@ -0,0 +1,411 @@
<%#
Shared statistics body for the admin Stats page (views/stats.ejs) and the public page (views/public_stats.ejs).
Two views (?v=community | streams) x periods (?p=stream|week|month|year|all).
Community: supporters, raids, leaderboards, community ranks, emotes, commands, rewards.
Streams: numbers, one activity chart (pick what to show), games played, the streams list; one stream: viewer graph.
Locals: s = periodstats.summary(), q = rangeQuery helper, base = link prefix ('/stats', '/public' or '/'),
view = 'community' | 'streams', mode = 'admin' | 'public', viewerHref = viewer link prefix or null,
extraBoards = [{ title, rows, level, wide }], ranks = [{ login, name, level }] (Regular and up, all time).
Colours come from the page: --muted, --line, --accent, --accent-hover, --card (and --card-solid for popups).
A new section goes here once and appears on both pages; wrap it in `if (admin)` when it is not for the public.
%>
<%
const admin = locals.mode === 'admin';
const esc = v => String(v ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const num = n => Number(n || 0).toLocaleString('en-US');
const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${String(Math.round(m % 60)).padStart(2, '0')} m` : `${Math.round(m)} m`;
const r = s.range, T = s.totals, C = s.channel || {}, TW = s.twitch;
const v = locals.view === 'streams' ? 'streams' : 'community';
const cur = { p: r.p, d: r.from || undefined, s: r.p === 'stream' ? r.stream.id : undefined };
const link = (rq, view = v) => base + q({ ...rq, v: view === 'community' ? undefined : view });
const TZ = locals.tz || 'UTC'; // Settings → General → Time zone
const day = iso => new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', timeZone: TZ });
const time = iso => new Date(iso).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: TZ });
const emoteSrc = e => e.source === 'twitch' && e.id ? `https://static-cdn.jtvnw.net/emoticons/v2/${e.id}/default/dark/1.0`
: e.source === '7tv' && e.id ? `https://cdn.7tv.app/emote/${e.id}/1x.webp` : null;
// ⓘ with an instant tooltip (hover, or tap / keyboard focus)
const info = text => text ? ` <span class="sb-i" tabindex="0" data-tip="${esc(text)}">ⓘ</span>` : '';
const person = x => { const n = esc(x.name || x.login || '?'); return viewerHref && x.login ? `<a href="${viewerHref}${encodeURIComponent(x.login)}">${n}</a>` : n; };
const since = TW && TW.streamedDays ? TW.cutoff : null; // period reaches back before HeyStreamer counted
%>
<style>
.sb-nav { display:flex; flex-wrap:wrap; align-items:center; gap:.5rem 1rem; margin:.4rem 0 1rem; }
.sb-views { display:flex; gap:1.2rem; border-bottom:1px solid var(--line); margin:.2rem 0 .8rem; }
.sb-views a { padding:.4rem .1rem; text-decoration:none; color:var(--muted); font-weight:700; border-bottom:3px solid transparent; margin-bottom:-1px; }
.sb-views a.on { color:inherit; border-bottom-color:var(--accent); }
.sb-tabs { display:flex; gap:.25rem; flex-wrap:wrap; }
.sb-tabs a { padding:.25rem .8rem; border-radius:99px; border:1px solid var(--line); text-decoration:none; color:inherit; font-size:.85rem; }
.sb-tabs a.on { background:var(--accent); border-color:var(--accent); color:#fff; }
.sb-step { display:flex; align-items:center; gap:.4rem; margin-left:auto; }
.sb-step a, .sb-step span.off { padding:.15rem .6rem; border-radius:8px; border:1px solid var(--line); text-decoration:none; color:inherit; }
.sb-step span.off { opacity:.35; }
.sb-title { font-weight:700; }
.sb-sub { color:var(--muted); font-size:.85rem; }
.sb-i { position:relative; cursor:help; color:var(--muted); font-size:.85em; outline:none; }
.sb-i:hover::after, .sb-i:focus::after { content:attr(data-tip); position:absolute; left:50%; bottom:calc(100% + 6px); transform:translateX(-50%);
width:max-content; max-width:260px; white-space:normal; text-align:left; font-size:.78rem; font-weight:400; line-height:1.35; color:inherit;
background:var(--card-solid, var(--card)); border:1px solid var(--line); border-radius:8px; padding:.4rem .55rem;
box-shadow:0 6px 18px rgba(0,0,0,.3); z-index:30; }
.sb-tiles { display:grid; grid-template-columns:repeat(auto-fit, minmax(140px, 1fr)); gap:.6rem; margin:.2rem 0 1.2rem; }
.sb-tile { border:1px solid var(--line); border-radius:12px; padding:.65rem .85rem; background:var(--card); }
.sb-tile .v { font-size:1.5rem; font-weight:700; line-height:1.1; font-variant-numeric:tabular-nums; white-space:nowrap; }
.sb-tile .k { font-size:.8rem; color:var(--muted); }
.sb-h { margin:1.4rem 0 .6rem; font-size:1.1rem; }
.sb-streams { width:100%; border-collapse:collapse; font-size:.86rem; }
.sb-streams th, .sb-streams td { text-align:left; padding:.4rem .5rem; border-bottom:1px solid var(--line); background:none; vertical-align:top; }
.sb-streams th { color:var(--muted); font-weight:600; font-size:.78rem; }
.sb-streams td.n { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
.sb-streams .t { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; max-width:20rem; display:block; }
.sb-streams .g { color:var(--muted); font-size:.78rem; }
.sb-scroll { overflow-x:auto; }
.sb-chart { border:1px solid var(--line); border-radius:12px; padding:.7rem .9rem; position:relative; background:var(--card); }
.sb-chart h4 { margin:0 0 .4rem; font-size:.95rem; }
.sb-chart svg { width:100%; height:auto; display:block; }
.sb-chart .bar { fill:var(--accent); }
.sb-chart .hit:hover + .bar { fill:var(--accent-hover); }
.sb-chart .grid { stroke:var(--line); stroke-width:1; }
.sb-chart .ax { fill:var(--muted); font-size:10px; }
.sb-metrics { display:flex; flex-wrap:wrap; gap:.3rem; margin-bottom:.5rem; }
.sb-metrics button { all:unset; cursor:pointer; padding:.2rem .7rem; border-radius:99px; border:1px solid var(--line); font-size:.8rem; }
.sb-metrics button.on { background:var(--accent); border-color:var(--accent); color:#fff; }
.sb-tip { position:absolute; pointer-events:none; background:var(--card-solid, var(--card)); border:1px solid var(--line);
border-radius:8px; padding:.25rem .5rem; font-size:.8rem; box-shadow:0 4px 12px rgba(0,0,0,.35); white-space:nowrap; display:none; z-index:5; }
.sb-two { display:grid; grid-template-columns:minmax(0, 2fr) minmax(260px, 1fr); gap:1rem; align-items:start; }
@media (max-width: 800px) { .sb-two { grid-template-columns:1fr; } }
.sb-games { display:flex; gap:1rem; align-items:center; flex-wrap:wrap; }
.sb-games svg { width:150px; height:150px; flex:none; }
.sb-games ul { list-style:none; margin:0; padding:0; flex:1; min-width:160px; max-width:440px; font-size:.85rem; }
.sb-games li { list-style:none; display:grid; grid-template-columns:.8rem minmax(0, 1fr) auto; gap:.45rem; align-items:center; padding:.15rem 0; }
.sb-games .sw { width:.8rem; height:.8rem; border-radius:3px; }
.sb-games .nm { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.sb-games .hv { color:var(--muted); font-variant-numeric:tabular-nums; white-space:nowrap; }
.sb-boards { display:grid; grid-template-columns:repeat(auto-fill, minmax(290px, 1fr)); gap:1rem; }
.sb-board { border:1px solid var(--line); border-radius:12px; padding:.6rem .8rem; background:var(--card); }
.sb-board h4 { margin:0 0 .3rem; font-size:.95rem; }
.sb-board ol { list-style:none; margin:0; padding:0; }
.sb-board li { list-style:none; display:grid; grid-template-columns:1.6rem minmax(0, 1fr) var(--nw, 4.6rem); align-items:center; gap:.5rem;
height:2rem; margin:0; padding:0 .2rem; border-bottom:1px solid var(--line); font-size:.88rem; }
.sb-board li:last-child { border-bottom:0; }
.sb-board .r { color:var(--muted); text-align:right; font-variant-numeric:tabular-nums; }
.sb-board .who { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0; }
.sb-board .who a { text-decoration:none; }
.sb-board .lvl { font-size:.66rem; padding:.02rem .45rem; border-radius:99px; border:1px solid var(--line); color:var(--muted); white-space:nowrap; justify-self:start; }
.sb-board .n { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
.sb-board.wide { grid-column:span 2; }
.sb-board.wide li { grid-template-columns:1.6rem minmax(0, 1fr) 5.5rem var(--nw, 4.6rem); }
@media (max-width: 700px) { .sb-board.wide { grid-column:auto; } }
.sb-pills { display:flex; flex-wrap:wrap; gap:.45rem; }
.sb-pill { display:flex; align-items:center; gap:.35rem; border:1px solid var(--line); border-radius:99px; padding:.15rem .6rem .15rem .3rem; font-size:.82rem; background:var(--card); }
.sb-pill.txt { padding-left:.6rem; }
.sb-pill img { width:26px; height:26px; object-fit:contain; }
.sb-pill a { text-decoration:none; }
.sb-pill .what { color:var(--muted); font-size:.75rem; }
.sb-pill.zero { opacity:.5; }
.sb-empty { color:var(--muted); font-size:.85rem; font-style:italic; }
.sb-note { color:var(--muted); font-size:.8rem; }
.sb-ranks { display:grid; grid-template-columns:repeat(auto-fill, minmax(220px, 1fr)); gap:1rem; }
.sb-rank { border:1px solid var(--line); border-radius:12px; padding:.6rem .8rem; background:var(--card); }
.sb-rank h4 { margin:0 0 .45rem; font-size:.95rem; }
.sb-timeline .area { fill:var(--accent); opacity:.18; }
.sb-timeline .line { fill:none; stroke:var(--accent); stroke-width:2.5; stroke-linejoin:round; }
.sb-timeline .dot { fill:transparent; }
.sb-timeline .dot:hover { fill:var(--accent); }
.sb-timeline .mark { stroke:var(--muted); stroke-dasharray:4 4; }
.sb-timeline .markdot { fill:var(--muted); }
.sb-changes { list-style:none; padding:0; margin:.6rem 0 0; font-size:.86rem; }
.sb-changes li { list-style:none; padding:.2rem 0; border-bottom:1px dashed var(--line); }
.sb-changes .when { display:inline-block; min-width:3.4rem; color:var(--muted); font-variant-numeric:tabular-nums; }
.sb-changes .game { color:var(--muted); font-size:.8rem; margin-left:.4rem; }
.sb-vod { font-size:.65rem; border:1px solid var(--line); border-radius:99px; padding:0 .35rem; color:var(--muted); }
</style>
<div class="sb-views" role="tablist">
<a href="<%= link(cur, 'community') %>" class="<%= v === 'community' ? 'on' : '' %>">Community</a>
<a href="<%= link(cur, 'streams') %>" class="<%= v === 'streams' ? 'on' : '' %>">Streams</a>
</div>
<div class="sb-nav">
<div class="sb-tabs">
<% for (const [p, label] of [['stream', 'Stream'], ['week', 'Week'], ['month', 'Month'], ['year', 'Year'], ['all', 'All time']]) { %>
<a href="<%= link(p === 'all' ? { p } : { p, ...(p === 'stream' ? {} : { d: r.from || undefined }) }) %>" class="<%= r.p === p ? 'on' : '' %>"><%= label %></a>
<% } %>
</div>
<div class="sb-step">
<% if (r.p !== 'all') { %>
<% if (r.prev) { %><a href="<%= link(r.prev) %>" title="<%= r.p === 'stream' ? 'Older stream' : 'Earlier' %>">‹</a><% } else { %><span class="off">‹</span><% } %>
<% } %>
<span><span class="sb-title"><%= r.label %></span><% if (r.sub) { %> <span class="sb-sub">· <%= r.sub %></span><% } %></span>
<% if (r.p !== 'all') { %>
<% if (r.next) { %><a href="<%= link(r.next) %>" title="<%= r.p === 'stream' ? 'Newer stream' : 'Later' %>">›</a><% } else { %><span class="off">›</span><% } %>
<% } %>
</div>
</div>
<%
// ---- number tiles. Public: a short, friendly set; admin: everything ----
const T_ = {}; // id -> [value, label, tooltip]
T_.messages = [num(T.messages), 'chat messages', since ? `Before ${since} from Twitch's daily analytics, after that counted by HeyStreamer` : ''];
T_.watch = [num(T.watchHours), 'hours watched', T.historyWatchHours ? `${num(T.historyWatchHours)} h from Twitch's daily analytics (before ${since}), the rest counted by HeyStreamer` : T.baselineHours ? `Includes ${num(T.baselineHours)} h counted by StreamElements before HeyStreamer counted itself` : ''];
if (r.p !== 'stream') T_.streams = [num(T.streams), T.streams === 1 ? 'stream' : 'streams', since ? `Before ${since} every day with a stream counts as one stream (Twitch's daily analytics)` : ''];
T_.streamed = r.p === 'stream' && s.streams[0] ? [hm(s.streams[0].minutes), s.streams[0].live ? 'live for' : 'streamed'] : [num(T.hoursStreamed), 'hours streamed'];
T_.emotes = [num(T.emotes), 'emotes used', since ? `Counted by HeyStreamer since ${since}` : ''];
if (TW && TW.clips) T_.clips = [num(TW.clips), 'clips created', `${num(TW.clipViews)} clip views (Twitch's daily analytics)`];
T_.redeems = [num(T.redeems), 'rewards redeemed', `${num(T.channelPoints)} channel points spent${since ? `; counted since ${since}` : ''}`];
if (admin) {
if (r.p === 'all' && C.followers != null) T_.followers = [num(C.followers), 'followers', 'Following the channel right now (from Twitch)'];
if (r.p === 'all' && C.subsNow != null) T_.subsNow = [num(C.subsNow), 'subscribers', 'Subscribed right now (from Twitch, without the streamer)'];
T_.chatters = [num(T.chatters), since ? `chatters since ${since}` : 'chatters', 'Different people who chatted. Twitch\'s export has no names, so this only counts from HeyStreamer\'s start'];
T_.viewers = [num(T.viewers), since ? `viewers since ${since}` : 'viewers', `Different people in the chatter list while live, lurkers included${T.viewersFromBaseline ? `. Includes ${num(T.viewersFromBaseline)} viewers known only from StreamElements' watch time (from before HeyStreamer counted), which is why All time is higher than the other tabs` : ''}`];
const pk = r.p === 'stream' ? s.streams[0] : C;
if (pk && pk.peak != null) T_.peak = [num(pk.peak), 'peak viewers', pk.avg != null ? `About ${num(pk.avg)} on average` : ''];
if (TW && TW.uniquePerDay != null) T_.unique = [num(TW.uniquePerDay), 'unique viewers / stream day', 'Twitch\'s count of different people who watched, averaged over the days you streamed'];
if (TW && (TW.newEngaged || TW.returningEngaged)) T_.engaged = [num(TW.newEngaged), 'new engaged viewers', `${num(TW.returningEngaged)} returning engaged viewer-days. Engaged = watched 5+ minutes and chatted or followed (Twitch)`];
if (TW && TW.revenue) T_.revenue = [`$${TW.revenue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`, 'revenue · admin only',
TW.revenueByType.map(([k, x]) => `${k} $${x.toFixed(2)}`).join(', ') + ' (Twitch export, before payout fees and taxes)'];
if (T.follows && !T_.followers) T_.follows = [num(T.follows), 'new followers'];
if (T.intros) T_.intros = [num(T.intros), 'first-time chatters'];
if (T.subs || T.giftSubs) T_.subs = [num(T.subs + T.giftSubs), 'subs', `${num(T.subs)} subs and resubs, ${num(T.giftSubs)} gifted`];
if (T.bits) T_.bits = [num(T.bits), 'bits', s.bitsSource === 'twitch' ? 'All time, from Twitch (top 100 cheerers)' : T.powerUps ? `${num(T.powerUps)} Power-ups included` : ''];
if (T.raids) T_.raids = [num(T.raids), T.raids === 1 ? 'raid' : 'raids', `${num(T.raidViewers)} viewers brought in`];
if (T.checkins) T_.checkins = [num(T.checkins), 'check-ins', 'First message of a stream'];
}
const order = admin
? ['followers', 'subsNow', 'messages', 'chatters', 'viewers', 'watch', 'streams', 'streamed', 'peak', 'unique', 'engaged', 'clips', 'revenue', 'follows', 'intros', 'emotes', 'subs', 'bits', 'redeems', 'raids', 'checkins']
: ['messages', 'watch', 'streams', 'streamed', 'emotes', 'clips', 'redeems'];
const tiles = order.filter(k => T_[k]).map(k => T_[k]);
%>
<% if (admin || v === 'streams') { %>
<div class="sb-tiles">
<% for (const [val, k, tip] of tiles) { %><div class="sb-tile"><div class="v"><%= val %></div><div class="k"><%= k %><%- info(tip) %></div></div><% } %>
</div>
<% } %>
<% if (v === 'streams') { %>
<%# ===================== STREAMS ===================== %>
<% if (r.p === 'stream' && s.streams[0]) { const x = s.streams[0]; %>
<p class="sb-sub" style="margin-top:-.6rem;">
<%= day(x.started_at) %>, <%= time(x.started_at) %>–<%= x.ended_at ? time(x.ended_at) : 'now' %><%= x.games.length ? ` · ${x.games.join(', ')}` : '' %>
<% if (x.live) { %> · <strong>live now</strong><% } %>
<% if (x.source === 'vod') { %> · from the VOD (HeyStreamer was not counting)<% } %>
</p>
<%
// viewers every 5 minutes as an area line; title / category changes as dashed markers
const tl = s.timeline;
if (tl && (tl.samples.length || tl.changes.length)) {
const W = 900, H = 200, L = 34, B = 20, TOP = 10;
const t0 = Date.parse(tl.start), t1 = Math.max(Date.parse(tl.end), t0 + 60000);
const max = Math.max(1, ...tl.samples.map(p => p.viewers));
const top = (() => { const p = Math.pow(10, Math.floor(Math.log10(max))); return [1, 2, 2.5, 5, 10].map(m => m * p).find(x => x >= max); })();
const X = t => L + (W - L) * (Date.parse(t) - t0) / (t1 - t0), Y = n => TOP + (H - TOP - B) * (1 - n / top);
let svg = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Viewers during the stream">`;
for (const g of [0, top / 2, top]) svg += `<line class="grid" x1="${L}" x2="${W}" y1="${Y(g)}" y2="${Y(g)}"/><text class="ax" x="${L - 4}" y="${Y(g) + 3}" text-anchor="end">${g}</text>`;
for (let h = 0; h <= (t1 - t0) / 36e5; h++) { const tt = new Date(t0 + h * 36e5).toISOString(); svg += `<text class="ax" x="${X(tt)}" y="${H - 5}" text-anchor="middle">${time(tt)}</text>`; }
if (tl.samples.length) {
const pts = tl.samples.map(p => `${X(p.at).toFixed(1)},${Y(p.viewers).toFixed(1)}`);
svg += `<path class="area" d="M${X(tl.samples[0].at).toFixed(1)},${H - B} L${pts.join(' L')} L${X(tl.samples.at(-1).at).toFixed(1)},${H - B} Z"/>`;
svg += `<polyline class="line" points="${pts.join(' ')}"/>`;
for (const p of tl.samples) svg += `<circle class="dot hit" cx="${X(p.at).toFixed(1)}" cy="${Y(p.viewers).toFixed(1)}" r="6" data-tip="${time(p.at)} · ${p.viewers} viewers"/>`;
}
for (const c of tl.changes) {
if (c.start) continue;
const x = X(c.at).toFixed(1);
svg += `<line class="mark" x1="${x}" x2="${x}" y1="${TOP}" y2="${H - B}"/><circle class="markdot hit" cx="${x}" cy="${TOP + 4}" r="5" data-tip="${time(c.at)} · ${esc(c.title || '')}${c.game ? ' · ' + esc(c.game) : ''}"/>`;
}
%>
<h3 class="sb-h">Viewers</h3>
<div class="sb-chart sb-timeline"><%- svg %></svg><div class="sb-tip"></div></div>
<% if (!tl.samples.length) { %><p class="sb-note">No viewer counts were recorded for this stream.</p><% } %>
<% if (tl.changes.length) { %>
<ol class="sb-changes">
<% for (const c of tl.changes) { %><li><span class="when"><%= c.start ? 'start' : time(c.at) %></span> <span><%= c.title || '—' %></span><% if (c.game) { %> <span class="game"><%= c.game %></span><% } %></li><% } %>
</ol>
<% } %>
<% } %>
<% } %>
<%
// one activity chart, like Twitch's: pick what it shows
const METRICS = [['messages', 'Chat messages', ''], ['watchHours', 'Hours watched', 'h'], ['streamHours', 'Hours streamed', 'h'],
['avgViewers', 'Average viewers', ''], ['follows', 'New followers', '']];
const rows = s.series ? s.series.rows : [];
const shown = METRICS.filter(([k]) => rows.some(x => x[k]));
%>
<% if (rows.length && shown.length) { %>
<h3 class="sb-h">Activity <span class="sb-sub">per <%= s.series.unit %></span></h3>
<div class="sb-chart" id="sb-activity">
<div class="sb-metrics"><% shown.forEach(([k, label], i) => { %><button type="button" data-k="<%= k %>" class="<%= i ? '' : 'on' %>"><%= label %></button><% }) %></div>
<div class="plot"></div><div class="sb-tip"></div>
</div>
<script>
(function () {
const rows = <%- JSON.stringify(rows.map(x => ({ label: x.label, messages: x.messages, watchHours: x.watchHours, streamHours: x.streamHours, avgViewers: x.avgViewers, follows: x.follows }))).replace(/</g, '\\u003c') %>;
const units = <%- JSON.stringify(Object.fromEntries(METRICS.map(([k, l, u]) => [k, { label: l, unit: u }]))) %>;
const box = document.getElementById('sb-activity'), plot = box.querySelector('.plot');
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
function draw(key) {
const W = 900, H = 200, L = 38, B = 20, TOP = 8, n = rows.length, max = Math.max(1, ...rows.map(d => d[key] || 0));
const p = Math.pow(10, Math.floor(Math.log10(max))), top = [1, 2, 2.5, 5, 10].map(m => m * p).find(x => x >= max);
const slot = (W - L) / n, bw = Math.max(2, Math.min(slot - 2, 44)), pad = (slot - bw) / 2, y = x => TOP + (H - TOP - B) * (1 - x / top);
const every = Math.ceil(n / 12);
let out = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(units[key].label)}">`;
for (const g of [0, top / 2, top]) out += `<line class="grid" x1="${L}" x2="${W}" y1="${y(g)}" y2="${y(g)}"/><text class="ax" x="${L - 4}" y="${y(g) + 3}" text-anchor="end">${+g.toFixed(1)}</text>`;
rows.forEach((d, i) => {
const x = L + i * slot + pad, val = d[key] || 0, tp = y(val), h = (H - B) - tp, rr = Math.min(4, bw / 2, h);
out += `<rect class="hit" x="${L + i * slot}" y="${TOP}" width="${slot}" height="${H - TOP - B}" fill="transparent" data-tip="${esc(d.label)} · ${val}${units[key].unit ? ' ' + units[key].unit : ''}"/>`;
if (val > 0) out += `<path class="bar" d="M${x},${H - B} V${tp + rr} Q${x},${tp} ${x + rr},${tp} H${x + bw - rr} Q${x + bw},${tp} ${x + bw},${tp + rr} V${H - B} Z"/>`;
if (i % every === 0) out += `<text class="ax" x="${x + bw / 2}" y="${H - 4}" text-anchor="middle">${esc(d.label)}</text>`;
});
plot.innerHTML = out + '</svg>';
window.sbHoverTips && window.sbHoverTips(box);
}
box.querySelectorAll('.sb-metrics button').forEach(b => b.addEventListener('click', () => {
box.querySelectorAll('.sb-metrics button').forEach(x => x.classList.toggle('on', x === b));
draw(b.dataset.k);
}));
draw(box.querySelector('.sb-metrics button.on').dataset.k);
})();
</script>
<% } %>
<%
// games played: donut of streamed time per category (from HeyStreamer's title / category history)
const PAL = ['#b74347', '#5b8fc7', '#d39b3a', '#4f9a68', '#8c6bb1', '#c76f9a', '#3fa3a1', '#9a8a5a'];
const games = s.games || [];
const totalMin = games.reduce((a, g) => a + g.minutes, 0);
const slices = games.length > 8 ? [...games.slice(0, 7), { game: `${games.length - 7} more`, minutes: games.slice(7).reduce((a, g) => a + g.minutes, 0), other: true }] : games;
%>
<% if (r.p !== 'stream' || slices.length > 1) { %>
<h3 class="sb-h">Games<%- info('Time per category, from every title / category change HeyStreamer saw. Twitch keeps no history of categories, so streams from before HeyStreamer recorded them have no game.') %></h3>
<% if (!totalMin) { %><p class="sb-empty">no categories recorded in this period yet</p><% } else { %>
<div class="sb-chart sb-games">
<svg viewBox="-1 -1 2 2" role="img" aria-label="Time per game">
<% let acc = 0; slices.forEach((g, i) => {
const a0 = acc / totalMin * 2 * Math.PI, a1 = (acc + g.minutes) / totalMin * 2 * Math.PI; acc += g.minutes;
const big = a1 - a0 > Math.PI ? 1 : 0, P = a => `${(Math.sin(a) * .95).toFixed(4)} ${(-Math.cos(a) * .95).toFixed(4)}`, Q = a => `${(Math.sin(a) * .55).toFixed(4)} ${(-Math.cos(a) * .55).toFixed(4)}`;
const d = slices.length === 1 ? 'M0 -.95 A.95 .95 0 1 1 0 .95 A.95 .95 0 1 1 0 -.95 Z M0 -.55 A.55 .55 0 1 0 0 .55 A.55 .55 0 1 0 0 -.55 Z'
: `M${P(a0)} A.95 .95 0 ${big} 1 ${P(a1)} L${Q(a1)} A.55 .55 0 ${big} 0 ${Q(a0)} Z`; %>
<path d="<%= d %>" fill="<%= g.other ? '#8a8a8a' : PAL[i % PAL.length] %>" fill-rule="evenodd" stroke="var(--card-solid, #fff)" stroke-width=".02"><title><%= g.game %> · <%= hm(g.minutes) %></title></path>
<% }) %>
</svg>
<ul>
<% slices.forEach((g, i) => { %>
<li><span class="sw" style="background:<%= g.other ? '#8a8a8a' : PAL[i % PAL.length] %>"></span><span class="nm" title="<%= g.game %>"><%= g.game %></span>
<span class="hv"><%= hm(g.minutes) %> · <%= Math.round(g.minutes / totalMin * 100) %>%</span></li>
<% }) %>
</ul>
</div>
<% } %>
<% } %>
<% if (r.p !== 'stream' && s.streams.length) { %>
<h3 class="sb-h"><%= r.p === 'all' ? 'Recent streams' : 'Streams' %></h3>
<div class="sb-scroll"><table class="sb-streams">
<thead><tr><th>Date</th><th>Title · games</th><th style="text-align:right">Length</th><th style="text-align:right">Peak</th><th style="text-align:right">Viewers</th><th style="text-align:right">Chatters</th><th style="text-align:right">Messages</th></tr></thead>
<tbody>
<% for (const x of s.streams.slice(0, r.p === 'all' ? 15 : 100)) { %>
<tr>
<td style="white-space:nowrap"><a href="<%= link({ p: 'stream', s: x.id }) %>"><%= day(x.started_at) %></a><%= x.live ? ' · live' : '' %><% if (x.source === 'vod') { %> <span class="sb-vod" title="Known from the Twitch VOD only: HeyStreamer was not counting during this stream">VOD</span><% } %></td>
<td><span class="t" title="<%= x.title %>"><%= x.title || '—' %></span><% if (x.games.length) { %><span class="g"><%= x.games.join(' · ') %></span><% } %></td>
<td class="n"><%= hm(x.minutes) %></td><td class="n"><%= x.peak != null ? num(x.peak) : '—' %></td>
<td class="n"><%= num(x.viewers) %></td><td class="n"><%= num(x.chatters) %></td><td class="n"><%= num(x.messages) %></td>
</tr>
<% } %>
</tbody>
</table></div>
<% } %>
<% } else { %>
<%# ===================== COMMUNITY ===================== %>
<% const cm = s.community || {}; %>
<% if ((cm.supporters || []).length) { %>
<h3 class="sb-h">Thank you for the support</h3>
<div class="sb-pills">
<% for (const x of cm.supporters.slice(0, 40)) {
const what = [x.bits ? `${num(x.bits)} bits` : '', x.subs ? (x.subs === 1 ? 'sub' : `${x.subs} subs`) : '', x.gifts ? `${num(x.gifts)} gifted` : '', admin && x.tips ? 'tip' : ''].filter(Boolean).join(' · '); %>
<span class="sb-pill txt"><%- person(x) %> <span class="what"><%= what %></span></span>
<% } %>
</div>
<% } %>
<% if ((cm.raiders || []).length) { %>
<h3 class="sb-h">Raids</h3>
<div class="sb-pills"><% for (const x of cm.raiders) { %><span class="sb-pill txt"><%- person(x) %> <span class="what"><%= x.raids > 1 ? `${x.raids} raids · ` : '' %><%= num(x.viewers) %> viewers</span></span><% } %></div>
<% } %>
<%
const board = b => {
const nw = b.nw ? ` style="--nw:${b.nw}"` : '';
let out = `<div class="sb-board${b.wide ? ' wide' : ''}"${nw}><h4>${esc(b.title)}</h4>`;
if (!b.rows.length) return out + '<p class="sb-empty">nothing yet</p></div>';
out += '<ol>';
b.rows.forEach((x, i) => {
out += `<li><span class="r">${i + 1}</span><span class="who" title="${esc(x.name || x.login)}">${person(x)}</span>${b.level ? `<span class="lvl">${esc(b.level(x))}</span>` : ''}<span class="n">${(b.fmt || num)(x.n)}</span></li>`;
});
return out + '</ol></div>';
};
const boards = [
...(locals.extraBoards || []),
{ title: 'Most active in chat', rows: s.boards.chat },
{ title: 'Watch time', rows: s.boards.watch, fmt: hm, nw: '6.4rem' },
{ title: 'Channel points spent', rows: s.boards.channelPoints, optional: true },
...(admin ? [{ title: 'Bits', rows: s.boards.bits, optional: true }, { title: 'Subs and gifts', rows: s.boards.subs, optional: true }] : []),
].filter(b => !(b.optional && !b.rows.length));
%>
<h3 class="sb-h">Leaderboards</h3>
<div class="sb-boards"><% for (const b of boards) { %><%- board(b) %><% } %></div>
<% if ((locals.ranks || []).length) {
const LV = ['Veteran', 'Loyal', 'Regular']; %>
<h3 class="sb-h">Community ranks<%- info('Levels by total watch time: Regular from 50 h, Loyal from 200 h, Veteran from 1000 h. All time.') %></h3>
<div class="sb-ranks">
<% for (const lv of LV) { const list = ranks.filter(x => x.level === lv); if (!list.length) continue; %>
<div class="sb-rank"><h4><%= lv %> <span class="sb-sub"><%= list.length %></span></h4>
<div class="sb-pills"><% for (const x of list) { %><span class="sb-pill txt"><%- person(x) %></span><% } %></div></div>
<% } %>
</div>
<% } %>
<% if (s.channelEmotes && s.channelEmotes.length) { %>
<h3 class="sb-h">Channel emotes<%- info('The channel\'s own emotes and how often they were used in this chat in this period. Twitch does not tell how often they are used in other channels.') %></h3>
<div class="sb-pills">
<% for (const e of s.channelEmotes) { %>
<span class="sb-pill<%= e.uses ? '' : ' zero' %>" title="<%= e.name %><%= e.tier ? ` · Tier ${String(e.tier).slice(0, 1)}` : '' %><%= e.type === 'follower' ? ' · follower emote' : e.type === 'bitstier' ? ' · bits emote' : '' %><%= e.gone ? ' · removed from the channel' : '' %>"><% if (e.image) { %><img src="<%= e.image %>" alt="" loading="lazy"><% } %><%= e.name %> <strong><%= num(e.uses) %></strong></span>
<% } %>
</div>
<% } %>
<h3 class="sb-h">Top emotes</h3>
<% if (!s.emotes.length) { %><p class="sb-empty">nothing yet</p><% } else { %>
<div class="sb-pills">
<% for (const e of s.emotes) { const src = emoteSrc(e); %>
<span class="sb-pill" title="<%= e.emote %><%= e.source ? ` · ${e.source === '7tv' ? '7TV' : 'Twitch'}` : '' %>"><% if (src) { %><img src="<%= src %>" alt="" loading="lazy"><% } %><%= e.emote %> <strong><%= num(e.uses) %></strong></span>
<% } %>
</div>
<% } %>
<% if (s.commands.length) { %>
<h3 class="sb-h">Top commands</h3>
<div class="sb-pills"><% for (const c of s.commands) { %><span class="sb-pill txt"><code><%= c.command %></code> <strong><%= num(c.uses) %></strong></span><% } %></div>
<% } %>
<% if (s.rewards.length) { %>
<h3 class="sb-h">Rewards and Power-ups</h3>
<div class="sb-pills"><% for (const x of s.rewards) { %><span class="sb-pill txt"><%= x.item %> <strong><%= num(x.uses) %></strong></span><% } %></div>
<% } %>
<% } %>
<script>
// chart hover tooltips (bars, viewer dots, title-change markers)
window.sbHoverTips = function (scope) {
(scope ? [scope] : document.querySelectorAll('.sb-chart')).forEach(ch => {
const tip = ch.querySelector('.sb-tip');
if (!tip) return;
ch.querySelectorAll('.hit').forEach(h => {
h.addEventListener('mouseenter', () => { tip.textContent = h.dataset.tip; tip.style.display = 'block'; });
h.addEventListener('mousemove', e => { const r = ch.getBoundingClientRect(); tip.style.left = (e.clientX - r.left + 12) + 'px'; tip.style.top = (e.clientY - r.top - 28) + 'px'; });
h.addEventListener('mouseleave', () => { tip.style.display = 'none'; });
});
});
};
window.sbHoverTips();
</script>