From c481ca92cbc7e6d6286688593a4f11ab2c50ee0f Mon Sep 17 00:00:00 2001 From: Bashy Date: Mon, 23 Nov 2026 11:22:49 +0200 Subject: [PATCH] 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 --- .gitignore | 14 + CLAUDE.md | 46 ++- apache.example.sh | 70 +++++ docs/PLANS.md | 33 +- public/alerts/art/placeholder.svg | 1 + public/alerts/card.css | 23 ++ public/alerts/card.js | 78 +++++ public/alerts/cassette.js | 5 +- public/alerts/polaroid.css | 3 + public/alerts/polaroid.js | 106 ++++--- public/alerts/raidcard.js | 7 +- src/app.js | 31 +- src/backup.js | 44 +++ src/chatlog.js | 26 +- src/db.js | 26 +- src/eventsub.js | 5 + src/nav.js | 35 +++ src/periodstats.js | 493 ++++++++++++++++++++++++++++++ src/points.js | 6 +- src/redeems.js | 5 +- src/routers/actions.js | 45 --- src/routers/alertsetup.js | 40 +++ src/routers/auth.js | 2 + src/routers/public.js | 38 +++ src/routers/redeems.js | 12 +- src/routers/settings.js | 130 +++++--- src/routers/stats.js | 145 +++++---- src/seimport.js | 81 ----- src/server.js | 5 +- src/streamelements.js | 14 +- src/theme.js | 102 +++++++ src/twitchcsv.js | 97 ++++++ src/twitchsync.js | 190 ++++++++++++ src/watchtime.js | 81 ++++- tools/preview/export.js | 19 ++ views/_statsbody.ejs | 411 +++++++++++++++++++++++++ views/actions.ejs | 88 ------ views/alerts_preview.ejs | 133 ++++++++ views/alerts_setup.ejs | 233 ++++++++++++++ views/dashboard.ejs | 58 +--- views/layout.ejs | 89 +++++- views/overlay.ejs | 2 + views/public_stats.ejs | 72 +++++ views/redeems.ejs | 14 +- views/settings.ejs | 112 ------- views/settings/_flash.ejs | 2 + views/settings/advanced.ejs | 16 + views/settings/backup.ejs | 16 + views/settings/chat.ejs | 62 ++++ views/settings/connections.ejs | 64 ++++ views/settings/general.ejs | 22 ++ views/settings/obs.ejs | 64 ++++ views/settings/stats.ejs | 38 +++ views/settings/tts.ejs | 20 ++ views/stats.ejs | 148 ++------- views/stats_viewer.ejs | 130 ++++++-- views/tts.ejs | 2 +- 57 files changed, 3080 insertions(+), 774 deletions(-) create mode 100644 apache.example.sh create mode 100644 public/alerts/art/placeholder.svg create mode 100644 public/alerts/card.css create mode 100644 public/alerts/card.js create mode 100644 src/backup.js create mode 100644 src/nav.js create mode 100644 src/periodstats.js delete mode 100644 src/routers/actions.js create mode 100644 src/routers/alertsetup.js create mode 100644 src/routers/public.js delete mode 100644 src/seimport.js create mode 100644 src/theme.js create mode 100644 src/twitchcsv.js create mode 100644 src/twitchsync.js create mode 100644 tools/preview/export.js create mode 100644 views/_statsbody.ejs delete mode 100644 views/actions.ejs create mode 100644 views/alerts_preview.ejs create mode 100644 views/alerts_setup.ejs create mode 100644 views/public_stats.ejs delete mode 100644 views/settings.ejs create mode 100644 views/settings/_flash.ejs create mode 100644 views/settings/advanced.ejs create mode 100644 views/settings/backup.ejs create mode 100644 views/settings/chat.ejs create mode 100644 views/settings/connections.ejs create mode 100644 views/settings/general.ejs create mode 100644 views/settings/obs.ejs create mode 100644 views/settings/stats.ejs create mode 100644 views/settings/tts.ejs diff --git a/.gitignore b/.gitignore index 5cde934..d04529b 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,17 @@ public/media/* public/tts/ tools/tts/venv/ tools/tts/voices/ + +# Twitch analytics exports (channel data, revenue): import them on the Stats page, never commit them +*.csv + +# The channel's own media library (pictures, stickers, sounds, videos picked on Actions → Alerts / Redeems): +# stays on disk and travels with the rsync deploy, never in git. Everything else is set in the dashboard (database). +public/alerts/art/* +!public/alerts/art/placeholder.svg +public/alerts/stickers/ +public/alerts/sounds/ +public/alerts/videos/* +!public/alerts/videos/.gitkeep +# this channel's deployment notes for Claude Code (hosts, server user) +CLAUDE.local.md diff --git a/CLAUDE.md b/CLAUDE.md index 3f936ee..a1bec27 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -133,7 +133,6 @@ Chat (`?parts=chat`) is `public/chat/chat.css` + `public/chat/chat.js` (window.H `room-id` from ROOMSTATE, refreshed every 10 min). 7TV zero-width emotes (data flag 256) stack on the emote before. Emote-only messages (up to 3 emotes) get bigger emotes. - Moderation: deleted messages, timeouts, bans and /clear remove the matching slips at once. -- Design preview with other styles: `~/Desktop/Stream/chat/index.html` (not in the repo). ## Overlay updates after a deploy @@ -237,7 +236,7 @@ Page `/redeems` (src/routers/redeems.js, views/redeems.ejs, logic in src/redeems - Shown as a cassette tape (`public/alerts/cassette.js` + `.css`, called from polaroid.js so it shares the queue): rarity = shell colour (Ultra Rare: gold, glow, foil, sparkles), reels spin over the sound's length, label = variation name + reward, paper strip = viewer + caption + typed message, sticker in the corner = the variation's - `art` (URL; '' = headset Streamer). `polaroid` column = "show cassette" (0 = sound only). + `art` (URL; '' = the theme's default sticker). `polaroid` column = "show cassette" (0 = sound only). - Special styles instead of the cassette (`STYLE` in src/redeems.js, drawn by `public/alerts/fx.js` + `.css`): Gigantify Power-up → the viewer's emote grows giant; On-Screen Celebration → 14 copies of the emote bounce around the whole screen for the sound's length; Highlight my message and the Message Effect Power-up → big taped paper note, taller than wide (stays ~2 s + 70 ms/char). @@ -247,7 +246,7 @@ Page `/redeems` (src/routers/redeems.js, views/redeems.ejs, logic in src/redeems two-pass loudnorm, so volume stays 0.8), `public/alerts/sounds/` (alert sounds + library) and audio uploaded on the Media page (`/media/`). Stickers: `public/alerts/stickers/` (cut out with rembg / hand masks). - polaroid off = sound only: it still waits its turn in the overlay queue and holds it for the sound's length. -- First run: `src/redeems-seed.json` (rebuilt from the Twitch alert setup, 2026-11-20) is loaded when the table is +- First run: `src/redeems-seed.json` (Twitch's built-in rewards / Power-ups, silent, Card look) is loaded when the table is empty. After that the dashboard is the source of truth; the seed file is never re-applied. - Test buttons: per variation, and "Test random" per trigger (`POST /redeems/variation/:id/test`, `/redeems/trigger/test`). - Power-up payload field names (`event.type === 'power_up'`, `event.power_up.type`) follow Twitch's docs but were not @@ -298,7 +297,7 @@ To re-enable: undo those three. Description of how it works when enabled: `data.donation` (`user.username`, `amount`, `currency`, `message`). Only `approved: 'allowed'` + `status: 'success'` alert; deduped by `data._id`. `reconnect` message → reconnect with `?reconnect_token=` (no re-subscribe). Server PINGs every 30 s (ws answers). Status on the dashboard. -- Alert: tip polaroid (sound emotional-damage-meme, heart-eyes Streamer, amount via Intl currency format, badge, +1/2/3 hearts at 10/25/50). +- Alert: tip polaroid (art + sound from the theme, amount via Intl currency format, badge, +1/2/3 hearts at 10/25/50). Turn off StreamElements' own tip alert in its overlay to avoid doubles. ## Polls and Hype Train @@ -308,7 +307,7 @@ To re-enable: undo those three. Description of how it works when enabled: NOT in the alert queue): bars + votes + countdown; on `completed` the winner gets a heart + WINNER stamp, then it drops away after 9 s (archived/terminated: away after 1.5 s). Begin/end are logged. Test: dashboard `poll-test`. - Hype Train (`channel.hype_train.*` v2, scope `channel:read:hype_train`): `alerts.fromHypeTrain()` → queued polaroid - alerts on start, on each NEW level (progress fires per contribution) and at the end (top contributors). HYPE Streamer + alerts on start, on each NEW level (progress fires per contribution) and at the end (top contributors). theme art art; sounds pro-gamer / toad-ya-hoo / tadaaa (in `describe()` case 'hype'). Golden Kappa / Treasure trains named. ## Polaroid alerts @@ -328,20 +327,20 @@ alerts.send() ─► ws.broadcast({type:'alert', alert}) ─► overlay ─► p ## Production deployment -Runs behind Apache on the VPS as a reverse proxy to Node on port 3000. -Production domain: `https://overlay.example.com` +Runs behind Apache (or any reverse proxy) as a proxy to Node on port 3000. This channel's real hosts, server user and +deploy command are in `CLAUDE.local.md` (not in git; Claude Code loads it automatically). -Apache vhost config is managed by `~/projects/apache.sh` (run on the VPS). Key requirements: +Apache vhost: `apache.example.sh` is a template (copy it outside the repo, fill in your hosts, run it on the server). +Key requirements: - `RequestHeader set X-Forwarded-Proto "https"` must be in the **443 vhost** — without it Express sees the connection as HTTP, `req.secure` is false, and the session cookie is never sent (OAuth login breaks) - `app.set('trust proxy', 1)` is set in `app.js` before all middleware - `/ws/overlay` must be proxied with `ws://` via `mod_proxy_wstunnel` before the catch-all `/` - Required modules: `proxy`, `proxy_http`, `proxy_wstunnel`, `headers`, `rewrite` -Deploy from Linux Mint: +Deploy by copying the working folder (rsync), not by git: the channel's media library is not in git and must travel too. ```bash -rsync -avzO --exclude='node_modules' --exclude='.env' --exclude='public/media' \ - ~/projects/heystreamer/ user@your-server:/opt/heystreamer/ - +rsync -avzO --exclude='node_modules' --exclude='.env' --exclude='public/media' --exclude='*.db*' \ + ./ user@your-server:/opt/heystreamer/ ssh user@your-server "cd /opt/heystreamer && npm install --production && sudo systemctl restart heystreamer" ``` @@ -349,6 +348,29 @@ Twitch requires HTTPS for OAuth redirect URIs in production. Register both in th - `http://localhost:3000/auth/callback` (dev) - `https://overlay.example.com/auth/callback` (production) +## Channel setup lives in the database, not in files + +Everything a channel customises is set in the dashboard and stored in the database, so the repo holds no channel +data and `git pull` never touches a channel's setup: + +| Where in the dashboard | Stored in | +|---|---| +| Actions → Alerts: style (Card / Polaroid), pictures, sounds, bits tiers, card colours (`src/theme.js`) | `settings.alert_theme` (JSON) | +| Actions → Redeems: variations, look (Card / Cassette / Sound only / Video), TTS voice | `reward_variations` | +| Actions → TTS voices, Media (uploads in `public/media/`, not in git) | `tts_voices`, `media_files` | +| Settings → General, Connections (StreamElements token), Chat, TTS, Stats, Advanced | `settings` | +| Settings → Backup: export / import all of the above as one JSON file | — | + +Alert styles: **Card** (`public/alerts/card.js`, the plain default) for everyone; **Polaroid**, **Cassette** and the +**Letter** (TTS) are optional looks anyone can pick. The overlay receives the merged theme with its settings +(`S.alert_theme`) and reads it per alert, so saving in the dashboard needs no OBS reload. An old file-based +`public/alerts/theme.js` is imported once at startup (`theme.importLegacyFile()`). + +Not in git (`.gitignore`): the database, `.env`, uploads (`public/media`), TTS clips, analytics CSV exports, the +channel's media library under `public/alerts/{art,stickers,sounds,videos}` (picked like uploads on Actions → Alerts / +Redeems), and `CLAUDE.local.md` (this channel's hosts / deploy notes). Never commit viewer names, stats, revenue, +reward ids or the channel's hosts. + ## Not yet implemented - Mod access (streamer-only login for now) diff --git a/apache.example.sh b/apache.example.sh new file mode 100644 index 0000000..2b2a5a1 --- /dev/null +++ b/apache.example.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Template (copy to apache.sh, not in git, and use your own hosts). Writes /etc/apache2/sites-available/overlay.example.conf and reloads Apache. +# Run on the VPS: bash apache.sh +set -e + +CONF=/etc/apache2/sites-available/overlay.example.conf + +sudo tee "$CONF" > /dev/null << 'EOF' +# ── overlay.example.com + heystreamer.example.com + stats.example.com ─────── +# stats.example.com = the public stats page (the app serves ONLY that page on this host). +# Its certificate: sudo certbot certonly --apache --cert-name example.com --expand -d -d stats.example.com +# HTTP: redirect everything to HTTPS + + ServerName overlay.example.com + ServerAlias heystreamer.example.com stats.example.com + + RewriteEngine on + RewriteCond %{SERVER_NAME} =heystreamer.example.com [OR] + RewriteCond %{SERVER_NAME} =stats.example.com [OR] + RewriteCond %{SERVER_NAME} =overlay.example.com + RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] + + ErrorLog ${APACHE_LOG_DIR}/example.com/overlay.error.log + CustomLog ${APACHE_LOG_DIR}/example.com/overlay.access.log combined + + +# HTTPS: proxy to Node on port 3000 + + + ServerName overlay.example.com + ServerAlias heystreamer.example.com stats.example.com + + ProxyPreserveHost On + + # Tell Express it's behind HTTPS so secure session cookies work + RequestHeader set X-Forwarded-Proto "https" + + Header always unset Content-Security-Policy + Header always set Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' https: wss: data:;" + + # WebSocket must be listed before the catch-all + ProxyPass /ws/overlay ws://127.0.0.1:3000/ws/overlay + ProxyPassReverse /ws/overlay ws://127.0.0.1:3000/ws/overlay + + ProxyPass / http://127.0.0.1:3000/ + ProxyPassReverse / http://127.0.0.1:3000/ + + ErrorLog ${APACHE_LOG_DIR}/example.com/overlay.error.log + CustomLog ${APACHE_LOG_DIR}/example.com/overlay.access.log combined + + Include /etc/letsencrypt/options-ssl-apache.conf + SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem + + +EOF + +echo "==> Enabling required modules..." +sudo a2enmod proxy proxy_http proxy_wstunnel headers rewrite + +echo "==> Enabling site..." +sudo a2ensite overlay.example.conf + +echo "==> Testing config..." +sudo apachectl configtest + +echo "==> Reloading Apache..." +sudo systemctl reload apache2 + +echo "Done. Try logging in at https://overlay.example.com" diff --git a/docs/PLANS.md b/docs/PLANS.md index 1f4918f..fc8487c 100644 --- a/docs/PLANS.md +++ b/docs/PLANS.md @@ -5,7 +5,7 @@ Ideas agreed on but not built yet. Newest first. (Started 2026-11-22.) ## 4. Point system (draft, 2026-11-22) Loyalty points calculated from the per-viewer statistics (src/chatlog.js), so values can change later and -everyone's points recalculate. Name to be decided (e.g. "Streamer points"). +everyone's points recalculate. Name to be decided (e.g. " points"). | Action | Points | Notes | |---|---|---| @@ -24,12 +24,12 @@ everyone's points recalculate. Name to be decided (e.g. "Streamer points"). | Emotes, commands | 0 | stats only, no farming | | Watch time | 5 per 5 min live (one tick updates watch time and points together; built: src/watchtime.js) | needs moderator:read:chatters (chatter list); import StreamElements' watch time once (SE key already in .env) so viewers keep their history when our bot takes over `!watchtime` | -Levels by watch time (ours + StreamElements import), her choice 2026-11-22: Viewer, Regular (50 h), Loyal (200 h), Veteran (1000 h). +Levels by watch time (ours + StreamElements import), decided: Viewer, Regular (50 h), Loyal (200 h), Veteran (1000 h). Points only rank the leaderboard; bits/subs do not buy a level. Balance: lurker 60/h, active chatter up to 180/h; Tier 1 sub (500) ~ 8 h watching. Uses: `!points`, on-stream leaderboard, level next to names in the overlay chat, spending on free Power-up uses (1). Rule: points earned from bits must never be exchanged for things with money value (Bits Acceptable Use Policy). -Activity log stays (her decision 2026-11-22: records of support, like Twitch keeps); forget-a-viewer removes theirs. +Activity log stays (decided: records of support, like Twitch keeps); forget-a-viewer removes theirs. ## 1. Free uses of Custom Power-ups ("refund") @@ -53,7 +53,7 @@ Estimate: about half a day once chat is read server-side. **Why:** one place for alerts, redeems, commands and replies; no third-party bot. **Rough shape** -- Bot account: `bot_account` logs in to HeyStreamer once (Twitch scopes `user:read:chat`, `user:write:chat`; +- Bot account: the channel's own bot account logs in to HeyStreamer once (Twitch scopes `user:read:chat`, `user:write:chat`; the bot also needs to be a mod/VIP in the channel for reliable sending). - Reads chat via EventSub `channel.chat.message`, sends via Helix `POST /chat/messages`. - Commands page: custom text commands (`!discord`, `!socials`, …) with cooldowns and permission levels @@ -75,9 +75,32 @@ Estimate: about half a day once chat is read server-side. for stream statistics. - Size: a few MB per month in SQLite. -Status: **logging built 2026-11-22** (src/chatlog.js), with her choices: per-viewer counts (messages, per day, +Status: **logging built 2026-11-22** (src/chatlog.js), with these choices: per-viewer counts (messages, per day, emotes incl. 7TV, !commands, first/last seen) parsed as messages arrive; raw messages kept **30 days** only; moderation removes stored text; hidden chatters (bots) are counted but must be left out of shown statistics and leaderboards (filter at display time with chatlog.isHidden()). Viewer actions are counted too (chat_action: rewards + points, Power-ups + bits, cheers, subs, gifts, follows, raids, watch streaks, tips). Still to do: a statistics page, and a "forget this viewer" button for removal requests (`chatlog.forgetUser()` exists). + +**2026-11-23: per-stream and period statistics + public page.** `src/periodstats.js` keeps one generic table, +`stat_day` (day x stream x viewer x kind x item), fed by chatlog.js (messages, first messages, emotes, commands, +actions) and watchtime.js (watch ticks); backfilled once from the older tables. A new statistic = a new `kind`, +then a section in `views/_statsbody.ejs` (shared by the admin Stats page and the public page). Streams keep title, +game, peak + average viewers. Public page: Settings → Public stats page (its own host name; on that +host nothing else answers; `/public` on the admin host is a preview). It never shows message text, bots, the +streamer on leaderboards, or viewers who typed `!hideme` (`!showme` undoes it; also a button on the viewer page). +The StreamElements watch-time importer is removed; the minutes imported on 2026-11-22 stay as a fixed baseline +(watch_import: All time, points, levels). + +**2026-11-23 (2): data from Twitch** (`src/twitchsync.js`, every 6 h, after each stream, "Sync with Twitch" button): +followers with follow dates (whole history), current subs, mods (`moderation:read`), VIPs (`channel:read:vips`; both +scopes need one new login), all-time bits top 100, the channel's emotes, past streams from VODs (7/60 days only). +Per stream: viewer count every 5 min (`stream_viewers`) and every title/category change (`stream_change`, EventSub +`channel.update`). Not on Twitch's API at all: past viewer counts, past titles, emote use outside this channel. +The old /actions page (event → sound rules, unused) is gone; "Actions" is now the nav group Redeems / TTS / Media. + +**2026-11-23 (3): Twitch analytics CSV** (`src/twitchcsv.js`, Stats → "Import Twitch analytics (CSV)"): the Creator +Dashboard export "Analytics and Revenue by day". No API offers this: export by hand now and then and import again (per day, safe). +Before the cutoff (first day HeyStreamer counted) it supplies messages, watch time, follows, streamed days/hours; +for every day it supplies what only Twitch measures (unique / engaged viewers, clips, live views, average + peak +viewers, revenue). Revenue: admin page only, never public. diff --git a/public/alerts/art/placeholder.svg b/public/alerts/art/placeholder.svg new file mode 100644 index 0000000..5034cb2 --- /dev/null +++ b/public/alerts/art/placeholder.svg @@ -0,0 +1 @@ +your artpublic/alerts/art diff --git a/public/alerts/card.css b/public/alerts/card.css new file mode 100644 index 0000000..5a219a4 --- /dev/null +++ b/public/alerts/card.css @@ -0,0 +1,23 @@ +/* Card alerts (card.js): the plain style every channel gets. Colours come from Actions → Alerts (theme.card). */ +#card-alert { position:fixed; left:60px; top:60px; width:600px; visibility:hidden; z-index:50; font-family:'Nunito', system-ui, sans-serif; + --accent:#9146ff; --bg:#ffffff; --fg:#1f1f23; } +#card-alert .card { position:relative; display:flex; gap:18px; align-items:center; background:var(--bg); color:var(--fg); + border-radius:20px; padding:16px 24px 18px 16px; box-shadow:0 14px 34px rgba(0,0,0,.35); overflow:hidden; } +#card-alert .card::before { content:''; position:absolute; left:0; top:0; bottom:0; width:8px; background:var(--accent); } +#card-alert .pic { width:104px; height:104px; flex:none; border-radius:16px; margin-left:6px; display:grid; place-items:center; overflow:hidden; + background:color-mix(in srgb, var(--accent) 16%, var(--bg)); } +#card-alert .pic img { width:100%; height:100%; object-fit:contain; } +#card-alert .pic .ini { font:900 50px/1 'Nunito', sans-serif; color:var(--accent); } +#card-alert .txt { min-width:0; flex:1; } +#card-alert .tag { font:800 14px/1.2 'Nunito', sans-serif; text-transform:uppercase; letter-spacing:.08em; color:var(--accent); opacity:.9; margin-bottom:2px; + white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#card-alert .name { font:900 32px/1.1 'Nunito', sans-serif; color:var(--accent); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#card-alert .line { font:800 23px/1.2 'Nunito', sans-serif; margin-top:2px; } +#card-alert .msg { font:800 19px/1.3 'Nunito', sans-serif; opacity:.72; margin-top:6px; overflow:hidden; display:-webkit-box; -webkit-line-clamp:4; -webkit-box-orient:vertical; } +#card-alert .msg .w { opacity:.25; transition:opacity .15s; } +#card-alert .msg .w.on { opacity:1; } +#card-alert .badge { position:absolute; right:16px; top:14px; background:var(--badge, var(--accent)); color:#fff; border-radius:99px; + padding:3px 13px; font:900 20px/1.3 'Nunito', sans-serif; box-shadow:0 3px 8px rgba(0,0,0,.2); } +#card-alert .badge small { font-size:13px; margin-left:4px; opacity:.9; } +#card-alert .card.has-badge .txt { padding-right:90px; } +#card-alert .bar { position:absolute; left:0; right:0; bottom:0; height:5px; background:var(--accent); opacity:.55; transform-origin:left center; } diff --git a/public/alerts/card.js b/public/alerts/card.js new file mode 100644 index 0000000..ce05469 --- /dev/null +++ b/public/alerts/card.js @@ -0,0 +1,78 @@ +/* + Card alerts: the plain style (Actions → Alerts: style "Card"). Used for events (follow, sub, gift, raid, bits, tip, + Hype Train) and for redeem variations / read-aloud redeems set to Card. Called by polaroid.js (shared queue): + window.CardAlert.show(d, cur, { url, len, volume }) -> Promise (resolves when it has left) + d: { art|sticker|emote (picture URL), name, line, msg, badge {big, small, color}, tag (small label above the name), + tts (voice URL instead of the sound), ttsEnv (loudness for word timing) } + cur: { anims, timer, audio } from polaroid.js, so reset / skip can stop it. + Timeline: slides in (0.6 s), sound starts, stays until the sound / voice ends (at least 4 s), slides out. +*/ +(function () { + const MIN_SHOW = 4000, SOUND_LEAD = 350, ENV_STEP = 0.04; + const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); + let el = null; + function root() { + if (!el) { el = document.createElement('div'); el.id = 'card-alert'; document.body.appendChild(el); } + return el; + } + const theme = () => (window.S && window.S.alert_theme) || {}; + + function show(d, cur, { url, len, volume }) { + const el = root(), c = theme().card || {}; + if (c.accent) el.style.setProperty('--accent', c.accent); + if (c.bg) el.style.setProperty('--bg', c.bg); + if (c.text) el.style.setProperty('--fg', c.text); + const pic = d.emote || d.sticker || d.art || ''; + const name = d.name || 'Someone'; + const words = d.tts && d.msg ? String(d.msg).split(/\s+/).filter(Boolean) : null; + el.innerHTML = `
+
${pic ? `` : `${esc(name.trim()[0] || '♥').toUpperCase()}`}
+
+ ${d.tag ? `
${esc(d.tag)}
` : ''} +
${esc(name)}
+
${esc(d.line || '')}
+ ${d.msg ? `
${words ? words.map(w => `${esc(w)}`).join(' ') : `“${esc(d.msg)}”`}
` : ''} +
+ ${d.badge ? `
${esc(d.badge.big)}${esc(d.badge.small || '')}
` : ''} +
+
`; + el.style.visibility = 'visible'; + const card = el.querySelector('.card'); + const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; }; + + A(card, [ + { transform:'translateX(-700px)', opacity:0 }, + { transform:'translateX(14px)', opacity:1, offset:.75 }, + { transform:'translateX(0)', opacity:1 }, + ], { duration:600, easing:'cubic-bezier(.2,.8,.3,1)' }); + A(el.querySelector('.pic'), [{ transform:'scale(.6) rotate(-8deg)' }, { transform:'scale(1.08) rotate(3deg)', offset:.6 }, { transform:'scale(1) rotate(0)' }], + { delay:350, duration:450, easing:'ease-out' }); + + // the voice (read-aloud redeems) or the sound + const voice = d.tts || null; + const playUrl = voice || url; + const playLen = voice ? (d.ttsMs || 0) : len; + if (playUrl) { + const a = new Audio(playUrl); a.volume = volume; + cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD); + // words light up roughly as they are spoken + if (words) { + const spans = [...el.querySelectorAll('.msg .w')]; + const total = Math.max(playLen, 1000), step = total / Math.max(spans.length, 1); + spans.forEach((s, i) => setTimeout(() => s.classList.add('on'), SOUND_LEAD + i * step)); + } + } else if (words) el.querySelectorAll('.msg .w').forEach(s => s.classList.add('on')); + + const stay = Math.max(MIN_SHOW, playUrl ? SOUND_LEAD + playLen + 600 : 0); + A(el.querySelector('.bar'), [{ transform:'scaleX(1)' }, { transform:'scaleX(0)' }], { delay:600, duration:Math.max(stay - 600, 500), easing:'linear' }); + const exit = A(card, [ + { transform:'translateX(0)', opacity:1 }, + { transform:'translateX(18px)', opacity:1, offset:.25 }, + { transform:'translateX(-720px)', opacity:0 }, + ], { delay:stay, duration:550, easing:'cubic-bezier(.5,0,.8,.4)' }); + return exit.finished.then(() => { el.style.visibility = 'hidden'; cur.anims.forEach(a => a.cancel()); }).catch(() => {}); + } + + function hide() { if (el) el.style.visibility = 'hidden'; } + window.CardAlert = { show, hide }; +})(); diff --git a/public/alerts/cassette.js b/public/alerts/cassette.js index e6eba97..6c879de 100644 --- a/public/alerts/cassette.js +++ b/public/alerts/cassette.js @@ -8,7 +8,8 @@ */ (function () { const AFTER_ANIM = 3000, SOUND_LEAD = 600, ANIM_END = 1200; - const DEFAULT_STICKER = (window.ALERTS_BASE || '/alerts/') + 'stickers/default-sticker.png'; + // sticker when a variation has none: Actions → Alerts → Default redeem sticker (else a plain shape) + const defaultSticker = () => (window.S && window.S.alert_theme && window.S.alert_theme.defaultSticker) || (window.ALERTS_BASE || '/alerts/') + 'art/placeholder.svg'; const RAR = { common:['r-common','COMMON'], uncommon:['r-uncommon','UNCOMMON'], rare:['r-rare','★ RARE'], ultra_rare:['r-ultra','★ ULTRA RARE ★'] }; const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); const between = (a, b) => a + Math.random() * (b - a); @@ -58,7 +59,7 @@
SIDE A${label}
${esc(d.title)}
${d.sub && d.sub !== d.title ? esc(d.sub) : ''}
-
+
${d.icon ? `
` : ''} ${ultra ? '
' + '
'.repeat(6) : ''} diff --git a/public/alerts/polaroid.css b/public/alerts/polaroid.css index 816b821..c65f23f 100644 --- a/public/alerts/polaroid.css +++ b/public/alerts/polaroid.css @@ -39,3 +39,6 @@ /* raid send-off: square Twitch avatar fills the photo instead of standing on the bottom edge */ #polaroid-alert .ph.avatar img { width:100%; height:100%; bottom:0; object-fit:cover; } + +/* no picture set (Actions → Alerts): the first letter of the name, handwritten */ +#polaroid-alert .ph .ini { position:absolute; inset:0; display:grid; place-items:center; font:700 170px/1 'Caveat', cursive; color:rgba(255,255,255,.9); text-shadow:0 4px 12px rgba(0,0,0,.12); } diff --git a/public/alerts/polaroid.js b/public/alerts/polaroid.js index b880dfc..cb1eddb 100644 --- a/public/alerts/polaroid.js +++ b/public/alerts/polaroid.js @@ -26,9 +26,10 @@ // ===================== CONFIG ===================== const BASE = window.ALERTS_BASE || '/alerts/'; // ALERTS_BASE: only set by offline test pages const rebase = u => (u && u.startsWith('/alerts/') && BASE !== '/alerts/') ? BASE + u.slice(8) : u; - const ART = n => /^(https?:)?\/\//.test(n) ? n : `${BASE}art/${n}`; // full URLs (e.g. Twitch avatars) pass through + // pictures and sounds are URLs from the Media library (Actions → Alerts); bare names = old files in public/alerts/art|sounds + const ART = n => !n ? '' : /^(https?:)?\/\//.test(n) ? n : n.startsWith('/') ? rebase(n) : `${BASE}art/${n}`; const SND = n => `${BASE}sounds/${n}`; - const VOLUME = 0.8; + const DEFAULT_VOLUME = 0.8; const TAPE = { follow:'rgba(201,182,228,.88)', sub:'rgba(244,160,168,.88)', prime:'rgba(140,200,240,.88)', @@ -36,27 +37,10 @@ bits:'rgba(190,160,240,.88)', redeem:'rgba(140,215,215,.88)', }; - // bits: under BITS_MIN = no alert; otherwise the highest matching tier wins - const BITS_MIN = 5; - const BITS_TIERS = [ - { min:250, sound:'TomDaTankLoud.mp3', art:'CharacterHype2.png', badge:'#e0457b', hearts:3, volume:0.4 }, // very loud clip: half volume - { min:150, sound:'run-vine-sound-effect.mp3', art:'CharacterHype2.png', badge:'#e0457b', hearts:2 }, - { min:100, sound:'windows-xp-startup_1ph012N.mp3', art:'CharacterHype2.png', badge:'#9b6bdc', hearts:1 }, - { min:75, sound:'we-do-a-little-trolling_80cJgd9.mp3', art:'CharacterCool.png', badge:'#9b6bdc', hearts:0 }, - { min:50, sound:'opatski.mp3', art:'CharacterCool.png', badge:'#8a8aa8', hearts:0 }, - { min:5, sound:'correct-answer.wav', art:'CharacterCool.png', badge:'#8a8aa8', hearts:0 }, - ]; - - // sound lengths in ms (ffprobe), so the alert stays up for the whole sound - const SOUND_MS = { - 'duck-toy-sound.mp3':960, 'wow.mp3':2325, 'huh.mp3':1123, 'correct-answer.wav':1960, 'opatski.mp3':1416, - 'we-do-a-little-trolling_80cJgd9.mp3':2691, 'windows-xp-startup_1ph012N.mp3':4911, - 'run-vine-sound-effect.mp3':8280, 'TomDaTankLoud.mp3':10057, 'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3':2038, - 'emotional-damage-meme.mp3':3369, - }; - - const BACK_ART = ['CharacterHeart.png','CharacterLoveEyes_Glasses.png','CharacterHappy.png', - 'CharacterLynx.png','CharacterCool.png','CharacterSelfie.png']; + // The channel's alert theme (src/theme.js, edited on Actions → Alerts) arrives with the overlay settings and is read + // per alert, so a save in the dashboard is used by the next alert without reloading OBS. + const TH = () => (window.S && window.S.alert_theme) || {}; + const SOUND_MS = {}; // sound lengths are measured in the browser once (soundLength) const RANGES = { photoTilt:[2,7], tape1:[-42,-18], tape2:[18,42], tapeX:[-12,12], tapeY:[-6,6], heart:[-8,26], heartX:[-10,6], heartY:[-14,8], badge:[-18,14] }; @@ -66,10 +50,12 @@ // Event -> what the polaroid shows. null = no alert. function describe(e) { + const th = TH(), THA = th.art || {}, THS = th.sounds || {}; + const BITS_MIN = th.bitsMin ?? 1, BITS_TIERS = th.bitsTiers || []; const who = e.user || (e.type === 'gift' ? 'An anonymous gifter' : 'Someone'); switch (e.type) { case 'follow': - return { art:'CharacterSelfie.png', name:who, line:'just followed! ♡', tape:TAPE.follow, sound:'duck-toy-sound.mp3' }; + return { art:THA.follow, name:who, line:'just followed! ♡', tape:TAPE.follow, sound:THS.follow }; case 'sub': { const months = e.months || 1, dur = e.duration || 1, multi = dur > 1; const tier = e.prime ? '' : ({ '2000':'Tier 2', '3000':'Tier 3' }[e.tier] || ''); @@ -79,26 +65,26 @@ else if (e.prime) line = months > 1 ? `resubscribed with Prime for ${months} months! ♛` : 'subscribed with Prime! ♛'; else if (months > 1) line = `resubscribed${atTier} for ${months} months! ♡`; else line = `just subscribed${atTier}! ♡`; - const art = e.prime ? 'CharacterQueen_Main.png' : (months > 1 || multi ? 'CharacterInLove.png' : 'CharacterHeart.png'); - return { art, name:who, line, msg:e.message, tape:e.prime ? TAPE.prime : TAPE.sub, sound:'wow.mp3', + const art = e.prime ? THA.prime : (months > 1 || multi ? THA.resub : THA.sub); + return { art, name:who, line, msg:e.message, tape:e.prime ? TAPE.prime : TAPE.sub, sound:THS.sub, stack: multi ? Math.min(dur - 1, 5) : 0, badge: multi ? { big:`${dur}×`, small:'months' } : months > 1 ? { big:months, small:'months' } : null, phbg: e.prime ? 'linear-gradient(#e3f2ff,#bcdcf5)' : null }; } case 'gift': { const n = e.total || 1; - return { art:'CharacterGift.png', name:who, + return { art:THA.gift, name:who, line: n > 1 ? `gifted ${n} subs to the community! ♡` : (e.recipient ? `gifted a sub to ${e.recipient}! ♡` : 'gifted a sub! ♡'), - tape:TAPE.gift, sound:'wow.mp3', stack: n > 1 ? Math.min(n - 1, 3) : 0, + tape:TAPE.gift, sound:THS.gift, stack: n > 1 ? Math.min(n - 1, 3) : 0, badge: n > 1 ? { big:`×${n}`, small:'subs' } : null, phbg:'linear-gradient(#e2f6ea,#bfe6cf)' }; } case 'streak': - return { art:'CharacterTime.png', name:who, line:`is on a ${e.streak}-stream watch streak!`, - tape:TAPE.streak, sound:'huh.mp3', badge:{ big:e.streak, small:'streams' }, phbg:'linear-gradient(#fff4d6,#f7deb0)' }; + return { art:THA.streak, name:who, line:`is on a ${e.streak}-stream watch streak!`, + tape:TAPE.streak, sound:THS.streak, badge:{ big:e.streak, small:'streams' }, phbg:'linear-gradient(#fff4d6,#f7deb0)' }; case 'raid': - return { art:'CharacterPolice.png', name:who, line:`is raiding with ${e.viewers} viewers!`, - tape:TAPE.raid, sound:'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3', badge:{ big:e.viewers, small:'raiders' }, + return { art:THA.raid, name:who, line:`is raiding with ${e.viewers} viewers!`, + tape:TAPE.raid, sound:THS.raid, badge:{ big:e.viewers, small:'raiders' }, phbg:'linear-gradient(#ffe6d6,#f8c8a8)', stack:2 }; case 'tip': { // StreamElements tip: amount in its own currency, extra hearts for bigger tips @@ -106,18 +92,17 @@ try { money = new Intl.NumberFormat('en', { style:'currency', currency:e.currency || 'USD', maximumFractionDigits: e.amount % 1 ? 2 : 0 }).format(e.amount); } catch { money = `${e.amount} ${e.currency || ''}`.trim(); } const hearts = e.amount >= 50 ? 3 : e.amount >= 25 ? 2 : e.amount >= 10 ? 1 : 0; - return { art:'CharacterLoveEyes_Glasses.png', name:who, line:`tipped ${money}! ♡`, msg:e.message, sound:'emotional-damage-meme.mp3', + return { art:THA.tip, name:who, line:`tipped ${money}! ♡`, msg:e.message, sound:THS.tip, tape:'rgba(246,206,110,.9)', badge:{ big:money, small:'tip', color:'#e0a21b' }, hearts, phbg:'linear-gradient(#fff6dc,#fbe0a8)' }; } case 'hype': { - // Hype Train: start / level up / end, HYPE Streamer, sounds picked from the library + // Hype Train: start / level up / end (art + sounds from the theme) const name = e.golden ? 'Golden Kappa Train' : e.treasure ? 'Treasure Train' : 'Hype Train'; const line = e.phase === 'begin' ? 'is leaving the station! choo choo 🚂' : e.phase === 'level' ? `reached level ${e.level}!` : `ended at level ${e.level}! ♡`; - const sound = { begin:'/alerts/sounds/redeems/pro-gamer.mp3', level:'/alerts/sounds/redeems/toad-ya-hoo.mp3', - end:'/alerts/sounds/redeems/tadaaa.mp3' }[e.phase]; - return { art:'CharacterHype2.png', name, line, tape: e.golden ? 'rgba(246,206,110,.95)' : TAPE.raid, sound, + const sound = { begin:THS.hypeBegin, level:THS.hypeLevel, end:THS.hypeEnd }[e.phase]; + return { art:THA.hype, name, line, tape: e.golden ? 'rgba(246,206,110,.95)' : TAPE.raid, sound, msg: e.phase === 'end' && e.top?.length ? `thank you ${e.top.join(', ')}!` : null, badge:{ big:e.level, small:'level', color: e.golden ? '#d4a017' : '#e0457b' }, hearts: e.phase === 'end' ? 2 : 0, stack: e.phase === 'end' ? 2 : 0, phbg: e.golden ? 'linear-gradient(#fff4d0,#f6d77a)' : 'linear-gradient(#ffe6d6,#f8c8a8)' }; @@ -133,7 +118,7 @@ } case 'bits': { if (!(e.bits >= BITS_MIN)) return null; - const t = BITS_TIERS.find(t => e.bits >= t.min); + const t = BITS_TIERS.find(t => e.bits >= t.min) || BITS_TIERS[BITS_TIERS.length - 1] || { art:THA.follow, badge:'#8a8aa8', hearts:0 }; return { art:t.art, name:who, line:`cheered ${e.bits} bits!`, msg:e.message, tape:TAPE.bits, sound:t.sound, badge:{ big:e.bits, small:'bits', color:t.badge }, hearts:t.hearts, volume:t.volume, phbg:'linear-gradient(#efe6ff,#d7c6f5)' }; } @@ -154,9 +139,8 @@ // preload images and sounds so the first alert of the stream is not blank or late function preload() { - const imgs = new Set([...BACK_ART, 'Heart.png', 'CharacterSelfie.png', 'CharacterHeart.png', - 'CharacterQueen_Main.png', 'CharacterInLove.png', 'CharacterGift.png', 'CharacterTime.png', - 'CharacterPolice.png', 'CharacterHype2.png']); + const th = TH(); + const imgs = new Set([...(th.back || []), ...Object.values(th.art || {}), th.heart, ...(th.bitsTiers || []).map(t => t.art)].filter(Boolean)); imgs.forEach(n => { new Image().src = ART(n); }); Object.keys(SOUND_MS).forEach(n => { const a = new Audio(); a.preload = 'auto'; a.src = SND(n); }); } @@ -203,7 +187,7 @@ current.anims.forEach(a => a.cancel()); current = null; if (el) el.style.visibility = 'hidden'; - window.CassetteAlert?.hide(); window.FxAlert?.hide(); + window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide(); busy = false; } @@ -230,7 +214,7 @@ current = null; } if (el) el.style.visibility = 'hidden'; - window.CassetteAlert?.hide(); window.FxAlert?.hide(); + window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide(); busy = false; } @@ -245,7 +229,7 @@ } function photoHTML(cls, art, inner) { - return `
${inner}
`; + return `
${art ? `` : ''}
${inner}
`; } async function show(d) { @@ -255,19 +239,31 @@ const len = url ? await soundLength(url) : 0; if (cur !== current) return; // skipped while measuring the sound + // which look: Card (plain, everyone) or the optional Polaroid / Cassette / Letter (Actions → Alerts, Redeems) + const th = TH(); + const asCard = window.CardAlert && !d.soundOnly && ( + d.style === 'card' || // redeem variation set to Card + (d.style === 'tts' && th.ttsStyle !== 'letter') || // read-aloud redeem + (!d.cassette && !d.style && th.style !== 'polaroid')); // follow / sub / gift / raid / bits / tip / Hype Train + if (asCard) { + if (d.cassette) d.tag = d.title && d.sub && d.title !== d.sub ? `${d.sub} · ${d.title}` : (d.sub || d.title || ''); + if (!d.sticker && d.cassette) d.sticker = ART(th.defaultSticker) || null; + return window.CardAlert.show(d, cur, { url, len, volume: d.volume ?? (th.volume ?? DEFAULT_VOLUME) }) + .then(() => { if (current === cur) current = null; }); + } const fx = { emote: 'giant', emote_rain: 'rain', message: 'message', tts: 'envelope' }[d.style]; if (fx && !d.soundOnly && window.FxAlert) { - return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? VOLUME }) + return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? (TH().volume ?? DEFAULT_VOLUME) }) .then(() => { if (current === cur) current = null; }); } if (d.cassette && !d.soundOnly && window.CassetteAlert) { - return window.CassetteAlert.show(d, cur, { url, len, volume: d.volume ?? VOLUME }) + return window.CassetteAlert.show(d, cur, { url, len, volume: d.volume ?? (TH().volume ?? DEFAULT_VOLUME) }) .then(() => { if (current === cur) current = null; }); } if (d.soundOnly) { // no picture: play the sound, hold the queue for its length if (!url) return; - const a = cur.audio = new Audio(url); a.volume = d.volume ?? VOLUME; + const a = cur.audio = new Audio(url); a.volume = d.volume ?? (TH().volume ?? DEFAULT_VOLUME); a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); const wait = el.animate([{}, {}], { duration: Math.max(len, 500) }); cur.anims.push(wait); @@ -275,16 +271,18 @@ } const nameSize = d.name.length > 18 ? 32 : d.name.length > 14 ? 36 : 40; + const backArt = th.back && th.back.length ? th.back : [d.art]; // photos fanned out behind (theme), else the same one const backs = Array.from({ length: d.stack || 0 }, (_, i) => - photoHTML('back', BACK_ART[i % BACK_ART.length], '
')).join(''); - const extraHearts = Array.from({ length: d.hearts || 0 }, () => - ``).join(''); + photoHTML('back', backArt[i % backArt.length], '
')).join(''); + const heart = ART(th.heart); // corner sticker; none set = no stickers + const extraHearts = heart ? Array.from({ length: d.hearts || 0 }, () => + ``).join('') : ''; el.innerHTML = backs + `
-
${d.tag ? `${esc(d.tag)}` : ''}
+
${d.art ? `` : `${esc((d.name || '♥').trim()[0] || '♥').toUpperCase()}`}${d.tag ? `${esc(d.tag)}` : ''}
${esc(d.name)}${esc(d.line)}${d.msg ? `“${esc(d.msg)}”` : ''}
- + ${heart ? `` : ''} ${extraHearts} ${d.badge ? `
${esc(d.badge.big)}${esc(d.badge.small)}
` : ''}
`; @@ -339,7 +337,7 @@ { transform:`translate(${x}px,${y}px) rotate(${a - 2}deg) scale(.92)`, opacity:1, offset:.82 }, { transform:`translate(${x}px,${y}px) rotate(${a}deg) scale(1)`, opacity:1 }, ], { delay:at, duration:420, easing:'ease-out' }); - slap(q('.heart:not(.extra)'), t0 + 1450, between(RANGES.heartX), between(RANGES.heartY), between(RANGES.heart)); + if (q('.heart:not(.extra)')) slap(q('.heart:not(.extra)'), t0 + 1450, between(RANGES.heartX), between(RANGES.heartY), between(RANGES.heart)); nudge(t0 + 1650, tilt > 0 ? .8 : -.8); [...el.querySelectorAll('.heart.extra')].forEach((h, i) => slap(h, t0 + 1600 + i * 160, between([-20, 10]), -110 - i * 95 + between([-15, 15]), between([-25, 25]))); @@ -354,7 +352,7 @@ const animEnd = t0 + 2400; // caption done writing const soundEnd = url ? t0 + SOUND_LEAD + len : 0; if (url) { - const a = new Audio(url); a.volume = d.volume ?? VOLUME; + const a = new Audio(url); a.volume = d.volume ?? (TH().volume ?? DEFAULT_VOLUME); cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + SOUND_LEAD); } diff --git a/public/alerts/raidcard.js b/public/alerts/raidcard.js index 8864b71..359d361 100644 --- a/public/alerts/raidcard.js +++ b/public/alerts/raidcard.js @@ -7,15 +7,16 @@ (function () { const COUNTDOWN_S = 90; const BASE = window.ALERTS_BASE || '/alerts/'; - const FALLBACK = BASE + 'art/CharacterHappy.png'; + // picture when the raided channel has none: Actions → Alerts → Raid send-off picture + const fallback = () => (window.S && window.S.alert_theme && window.S.alert_theme.raidFallback) || BASE + 'art/placeholder.svg'; const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); let el = null, timer = null, hideTimer = null, startedAt = 0, shown = false; function root() { if (!el) { el = document.createElement('div'); el.id = 'raid-card'; document.body.appendChild(el); } return el; } function render(raid, line, badge) { - const img = raid.avatar ? `` - : ``; + const img = raid.avatar ? `` + : ``; el.innerHTML = `
${img}
raiding ${esc(raid.target)}${esc(line)}
${esc(badge)}
`; diff --git a/src/app.js b/src/app.js index e8dd746..871bb2f 100644 --- a/src/app.js +++ b/src/app.js @@ -48,18 +48,33 @@ function requireAuth(req, res, next) { next(); } +// Public stats page: on its own host (Settings → Public stats page) ONLY that page is served (anything else 404s, +// the admin pages never answer there); on the admin host it is at /public as well. +const publicStats = require('./routers/public'); +const db = require('./db'); +const adminHost = (() => { try { return new URL(process.env.APP_BASE_URL).hostname; } catch { return ''; } })(); +app.use((req, res, next) => { + const host = String(db.getSettings()?.public_stats_host || '').toLowerCase(); + if (!host || req.hostname !== host || host === adminHost) return next(); // never lock the admin host out + publicStats(req, res, () => res.status(404).send('Not found')); +}); +app.use('/public', publicStats); + app.use('/auth', require('./routers/auth')); app.use('/overlay', require('./routers/overlay')); app.use('/ext', require('./routers/ext').router); // HUDFX / Blerp pages served inside the overlay (public, under the overlay id) // Now playing (Feishin) is switched off for now; uncomment to bring it back (see views/overlay.ejs). // app.use('/nowplaying', require('./routers/nowplaying')); // key-protected push from the PC helper -app.use('/actions', requireAuth, require('./routers/actions')); -app.use('/media', requireAuth, require('./routers/media')); -app.use('/stats', requireAuth, require('./routers/stats')); -app.use('/settings', requireAuth, require('./routers/settings')); -app.use('/alerts', requireAuth, require('./routers/alerts')); -app.use('/redeems', requireAuth, require('./routers/redeems')); -app.use('/tts', requireAuth, require('./routers/tts')); -app.use('/', requireAuth, require('./routers/dashboard')); +// sections with a left sidebar (src/nav.js): Actions = Redeems / Alerts / TTS voices / Media, and Settings +const { section } = require('./nav'); +app.get('/actions', requireAuth, (req, res) => res.redirect('/redeems')); +app.use('/actions/alerts', requireAuth, section('actions'), require('./routers/alertsetup')); +app.use('/redeems', requireAuth, section('actions'), require('./routers/redeems')); +app.use('/tts', requireAuth, section('actions'), require('./routers/tts')); +app.use('/media', requireAuth, section('actions'), require('./routers/media')); +app.use('/settings', requireAuth, section('settings'), require('./routers/settings')); +app.use('/stats', requireAuth, (req, res, next) => { res.locals.navActive = 'stats'; next(); }, require('./routers/stats')); +app.use('/alerts', requireAuth, require('./routers/alerts')); // test / skip / raid (POST) +app.use('/', requireAuth, (req, res, next) => { res.locals.navActive = 'dashboard'; next(); }, require('./routers/dashboard')); module.exports = app; diff --git a/src/backup.js b/src/backup.js new file mode 100644 index 0000000..39fc19e --- /dev/null +++ b/src/backup.js @@ -0,0 +1,44 @@ +// Settings → Backup: the whole setup as one JSON file (settings, alert theme, redeem variations, TTS voices). +// Not included: media files, statistics, secrets (Twitch tokens live in users; se_jwt is left out). +const db = require('./db'); + +const VERSION = 1; +const SKIP_SETTINGS = ['id', 'overlay_id', 'se_jwt', 'tts_blocklist_seeded']; + +function exportAll() { + const d = db.raw(); + const settings = { ...db.getSettings() }; + for (const k of SKIP_SETTINGS) delete settings[k]; + return { + heystreamer_backup: VERSION, exported_at: new Date().toISOString(), + settings, + variations: d.prepare('SELECT * FROM reward_variations ORDER BY id').all().map(({ id, created_at, ...v }) => v), + tts_voices: d.prepare('SELECT id, name, config FROM tts_voices ORDER BY id').all(), + }; +} + +// replaces settings (known columns only), variations and TTS voices; keeps statistics, users, media rows +function importAll(data) { + if (!data || data.heystreamer_backup !== VERSION) throw new Error('not a HeyStreamer backup file'); + const d = db.raw(); + const cols = new Set(d.prepare('PRAGMA table_info(settings)').all().map(c => c.name)); + const vcols = new Set(d.prepare('PRAGMA table_info(reward_variations)').all().map(c => c.name)); + const settings = Object.fromEntries(Object.entries(data.settings || {}).filter(([k]) => cols.has(k) && !SKIP_SETTINGS.includes(k))); + d.transaction(() => { + if (Object.keys(settings).length) db.updateSettings(settings); + // TTS voices keep their ids, so variations still point at the right voice + d.prepare('DELETE FROM tts_voices').run(); + const tv = d.prepare('INSERT INTO tts_voices (id, name, config) VALUES (?, ?, ?)'); + for (const v of data.tts_voices || []) tv.run(v.id, String(v.name || 'voice'), typeof v.config === 'string' ? v.config : JSON.stringify(v.config || {})); + d.prepare('DELETE FROM reward_variations').run(); + for (const v of data.variations || []) { + const row = Object.fromEntries(Object.entries(v).filter(([k]) => vcols.has(k) && k !== 'id')); + const keys = Object.keys(row); + if (!keys.length) continue; + d.prepare(`INSERT INTO reward_variations (${keys.join(', ')}) VALUES (${keys.map(k => '@' + k).join(', ')})`).run(row); + } + })(); + return { settings: Object.keys(settings).length, variations: (data.variations || []).length, voices: (data.tts_voices || []).length }; +} + +module.exports = { exportAll, importAll }; diff --git a/src/chatlog.js b/src/chatlog.js index f6e5ad6..e302dd4 100644 --- a/src/chatlog.js +++ b/src/chatlog.js @@ -10,6 +10,8 @@ // from every event that goes through dispatch.js (rewards, Power-ups, cheers, subs, gifts, // follows, raids, watch streaks, tips). Keyed by Twitch user id, or 'name:' when the // event has none (StreamElements tips, watch streaks). +// These are lifetime totals (points and levels come from them). The same events also go to periodstats.js per day +// and per stream, for the stream / week / month / year views. !hideme / !showme toggle the public-page opt-out. // // Moderation: a deleted message, a timeout/ban (clear_user_messages) or a chat clear removes the stored text at // once (Twitch developer rules); the counts stay, they hold no message content. @@ -56,6 +58,9 @@ function init() { first_at TEXT, last_at TEXT, PRIMARY KEY (user_key, action, item) ); + CREATE TABLE IF NOT EXISTS chat_badges ( -- latest chat badges per viewer (roles, sub months), from their last message + user_id TEXT PRIMARY KEY, badges TEXT, sub_months INTEGER, at TEXT + ); CREATE TABLE IF NOT EXISTS chat_command ( user_id TEXT NOT NULL, command TEXT NOT NULL, uses INTEGER DEFAULT 0, last_used TEXT, PRIMARY KEY (user_id, command) @@ -125,6 +130,11 @@ function onMessage(e) { 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 + // badges: moderator / vip / subscriber (info = months) / founder / artist-badge / ... + const badges = (e.badges || []).map(b => ({ set: b.set_id, id: b.id, info: b.info || '' })); + const subB = badges.find(b => b.set === 'subscriber' || b.set === 'founder'); + d.prepare('INSERT OR REPLACE INTO chat_badges (user_id, badges, sub_months, at) VALUES (?, ?, ?, ?)') + .run(e.chatter_user_id, JSON.stringify(badges), subB && /^\d+$/.test(subB.info) ? +subB.info : null, at); 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, ?) @@ -133,6 +143,17 @@ function onMessage(e) { if (command) d.prepare(`INSERT INTO chat_command (user_id, command, uses, last_used) VALUES (?, ?, 1, ?) ON CONFLICT(user_id, command) DO UPDATE SET uses = uses + 1, last_used = excluded.last_used`) .run(e.chatter_user_id, command, at); + + // per day + per stream (periodstats.js: stream / week / month / year statistics) + const ps = require('./periodstats'); + const who = { key: e.chatter_user_id, login, name: e.chatter_user_name || login }; + const rows = [{ ...who, kind: 'message', amount: scored }]; + if (e.message_type === 'user_intro') rows.push({ ...who, kind: 'intro' }); + for (const x of emotes) { rows.push({ ...who, kind: 'emote', item: x.name }); ps.emoteSeen(x.name, x.source, x.id); } + if (command) rows.push({ ...who, kind: 'command', item: command }); + ps.add(rows, at); + // public stats page: viewers can leave it (still counted, never named) and come back + if (command === '!hideme' || command === '!showme') ps.setOptout(e.chatter_user_id, login, command === '!hideme'); })(); } @@ -173,6 +194,8 @@ function onAction(eventType, detail, username, data, replay) { amount = ${act.max ? 'MAX(amount, excluded.amount)' : 'amount + excluded.amount'}, user_login = excluded.user_login, user_name = excluded.user_name, last_at = excluded.last_at`) .run(key, login, d.user_name || d.chatter_user_name || username || login, eventType, String(act.item || ''), amount, act.unit, at, at); + require('./periodstats').add([{ key, login, name: d.user_name || d.chatter_user_name || username || login, + kind: 'action:' + eventType, item: act.item || '', amount, unit: act.unit }], at); } // moderation: remove stored message text (counts stay) @@ -193,8 +216,9 @@ function forgetUser(userIdOrLogin) { 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); + if (u) for (const t of ['chat_raw', 'chat_user', 'chat_user_day', 'chat_emote', 'chat_command', 'chat_badges']) 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; + require('./periodstats').forgetUser(u ? u.user_id : null, login); return u || n ? 1 : 0; } diff --git a/src/db.js b/src/db.js index 7dbcffa..cc470e0 100644 --- a/src/db.js +++ b/src/db.js @@ -140,8 +140,14 @@ function migrate() { addColumn('settings', 'tts_blocklist_seeded', 'INTEGER DEFAULT 0'); // starter list copied in once addColumn('activity_log', 'replay_json', 'TEXT'); addColumn('settings', 'hudfx_overlay_url', "TEXT DEFAULT ''"); - addColumn('settings', 'chat_hidden_users', "TEXT DEFAULT 'bot_account, blerp, blerpbot, hudfx, hudfxbot, lumiastream'"); // never shown in the on-screen chat + addColumn('settings', 'chat_hidden_users', "TEXT DEFAULT 'streamelements, nightbot, blerp, blerpbot, hudfx, hudfxbot, lumiastream'"); // never shown in the on-screen chat addColumn('settings', 'chat_hide_commands', 'INTEGER DEFAULT 1'); // hide messages starting with ! + addColumn('settings', 'alert_theme', "TEXT DEFAULT ''"); // Actions → Alerts (src/theme.js), JSON + addColumn('settings', 'se_jwt', "TEXT DEFAULT ''"); // StreamElements JWT (Settings → Connections); secret + addColumn('settings', 'timezone', "TEXT DEFAULT 'UTC'"); // times on the stats pages + addColumn('reward_variations', 'look', "TEXT DEFAULT ''"); // card | cassette ('' = cassette, older rows) + addColumn('settings', 'public_stats_enabled', 'INTEGER DEFAULT 0'); // public stats page on/off + addColumn('settings', 'public_stats_host', "TEXT DEFAULT ''"); // its own host name (DNS + certificate needed) addColumn('reward_variations', 'video', "TEXT DEFAULT ''"); // URL of a video: full-screen on the ?parts=video overlay // HUDFX browser source URL, embedded with ?ext=hudfx // the overlay message that was shown (dashboard Replay) } @@ -169,10 +175,10 @@ function seedSettings() { function seedVariations() { if (db.prepare('SELECT COUNT(*) n FROM reward_variations').get().n > 0) return; - const seed = require('./redeems-seed.json').variations; - const ins = db.prepare(`INSERT INTO reward_variations (kind, key, title, name, rarity, sound, volume, art, enabled) - VALUES (@kind, @key, @title, @name, @rarity, @sound, @volume, @art, @enabled)`); - db.transaction(() => seed.forEach(v => ins.run({ ...v, volume: v.volume ?? 0.8, art: v.art || '', enabled: v.enabled === false ? 0 : 1 })))(); + const seed = require('./redeems-seed.json').variations; // Twitch's built-in rewards; the rest is made on Redeems + const ins = db.prepare(`INSERT INTO reward_variations (kind, key, title, name, rarity, sound, volume, art, enabled, look) + VALUES (@kind, @key, @title, @name, @rarity, @sound, @volume, @art, @enabled, @look)`); + db.transaction(() => seed.forEach(v => ins.run({ ...v, volume: v.volume ?? 0.8, art: v.art || '', enabled: v.enabled === false ? 0 : 1, look: v.look || 'card' })))(); console.log(`[db] Loaded ${seed.length} default redeem variations`); } @@ -210,8 +216,8 @@ function getSettings() { // what overlay pages get: everything except server-only values (the overlay URL is public) function getOverlaySettings() { - const { tts_blocklist, tts_blocklist_seeded, hudfx_overlay_url, ...rest } = getSettings(); - return rest; + const { tts_blocklist, tts_blocklist_seeded, hudfx_overlay_url, se_jwt, alert_theme, ...rest } = getSettings(); + return { ...rest, alert_theme: require('./theme').get() }; // the overlay gets the merged theme, never secrets } function updateSettings(fields) { @@ -283,7 +289,7 @@ function getMatchingActions(eventType, eventDetail) { } // Redeem variations -const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled', 'tts_voice_id', 'video']; +const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled', 'tts_voice_id', 'video', 'look']; function getAllVariations() { return db.prepare('SELECT * FROM reward_variations ORDER BY kind, title, id').all(); @@ -297,8 +303,8 @@ function getVariation(id) { return db.prepare('SELECT * FROM reward_variations WHERE id = ?').get(id); } -function createVariation({ kind, key, title, name }) { - const r = db.prepare('INSERT INTO reward_variations (kind, key, title, name) VALUES (?, ?, ?, ?)').run(kind, key, title, name); +function createVariation({ kind, key, title, name, look = '' }) { + const r = db.prepare('INSERT INTO reward_variations (kind, key, title, name, look) VALUES (?, ?, ?, ?, ?)').run(kind, key, title, name, look); return getVariation(r.lastInsertRowid); } diff --git a/src/eventsub.js b/src/eventsub.js index 8eab5a7..5c50e94 100644 --- a/src/eventsub.js +++ b/src/eventsub.js @@ -133,6 +133,8 @@ async function subscribeAll(sessionId) { // 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 } }, + // title / category changes (stream history, viewer graph markers); no scope needed + { type: 'channel.update', version: '2', 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 } }, @@ -227,6 +229,9 @@ function handleNotification(payload) { case 'stream.offline': watchtime.offline(); break; + case 'channel.update': + try { watchtime.channelUpdate(event.title, event.category_name); } catch (e) { console.error('[watchtime]', e.message); } + break; case 'channel.chat.message': try { chatlog.onMessage(event); } catch (e) { console.error('[chatlog]', e.message); } break; diff --git a/src/nav.js b/src/nav.js new file mode 100644 index 0000000..c7a2c59 --- /dev/null +++ b/src/nav.js @@ -0,0 +1,35 @@ +// Left sidebars of the dashboard sections. app.js mounts section('actions') / section('settings') in front of the +// pages of that section; views/layout.ejs draws the sidebar and marks the page that is open. +const SECTIONS = { + actions: { + title: 'Actions', + items: [ + { href: '/redeems', label: 'Redeems', hint: 'Channel point rewards and Power-ups: variations, sounds, looks' }, + { href: '/actions/alerts', label: 'Alerts', hint: 'Follows, subs, gifts, raids, bits, tips, Hype Train: style, pictures, sounds' }, + { href: '/tts', label: 'TTS voices', hint: 'Voices for redeems that read the viewer\'s text aloud' }, + { href: '/media', label: 'Media', hint: 'Every picture, sound and video you can pick' }, + ], + }, + settings: { + title: 'Settings', + items: [ + { href: '/settings/general', label: 'General' }, + { href: '/settings/connections', label: 'Connections', hint: 'Twitch, StreamElements, HUDFX' }, + { href: '/settings/obs', label: 'OBS sources', hint: 'Browser source links for OBS' }, + { href: '/settings/chat', label: 'Chat', hint: 'On-screen chat, hidden chatters, gap sound' }, + { href: '/settings/tts', label: 'Text to speech', hint: 'Length, blocked words' }, + { href: '/settings/stats', label: 'Stats and data', hint: 'Public stats page, Twitch sync, analytics import' }, + { href: '/settings/backup', label: 'Backup', hint: 'Export / import the whole setup' }, + { href: '/settings/advanced', label: 'Advanced', hint: 'Custom CSS / JS for the overlay' }, + ], + }, +}; + +const section = name => (req, res, next) => { + const s = SECTIONS[name]; + const here = req.baseUrl + req.path; + res.locals.sidebar = { name, title: s.title, items: s.items.map(i => ({ ...i, on: here === i.href || here.startsWith(i.href + '/') })) }; + next(); +}; + +module.exports = { SECTIONS, section }; diff --git a/src/periodstats.js b/src/periodstats.js new file mode 100644 index 0000000..4be2b7a --- /dev/null +++ b/src/periodstats.js @@ -0,0 +1,493 @@ +// Period statistics: what happened per day and per stream, so the Stats pages (admin and public) can show one +// stream, a week, a month, a year or all time. ONE generic table: a new kind of statistic is a new `kind` +// value, not a new table (e.g. bot commands later: kind 'command', or a kind of their own). +// +// stat_day day (UTC YYYY-MM-DD) x stream_id ('' = chat while offline) x viewer x kind x item -> uses, amount +// kind 'message' item '' uses = messages, amount = points-eligible messages +// kind 'intro' item '' Twitch "first message ever in this channel" +// kind 'emote' item emote name uses +// kind 'command' item '!cmd' uses +// kind 'watch' item '' uses = 5-minute watch ticks +// kind 'action:' item reward / tier uses, amount + unit (points, bits, months, viewers, EUR...) +// stat_emote emote name -> source (twitch / 7tv) + id, for pictures +// public_optout viewers who typed !hideme: counted, but never named on the public page +// stat_meta one-time jobs (backfill) +// +// The lifetime tables in chatlog.js / watchtime.js stay as they are (points and levels are calculated from them). +// Viewer key = Twitch user id, or 'name:' when an event has no id (StreamElements tips, watch streaks). +const db = require('./db'); + +let ready = false; +const d = () => db.raw(); + +function init() { + if (ready) return; + d().exec(` + CREATE TABLE IF NOT EXISTS stat_day ( + day TEXT NOT NULL, stream_id TEXT NOT NULL DEFAULT '', + user_key TEXT NOT NULL, user_login TEXT, user_name TEXT, + kind TEXT NOT NULL, item TEXT NOT NULL DEFAULT '', + uses INTEGER DEFAULT 0, amount REAL DEFAULT 0, max_amount REAL DEFAULT 0, unit TEXT, + PRIMARY KEY (day, stream_id, user_key, kind, item) + ); + CREATE INDEX IF NOT EXISTS stat_day_stream ON stat_day(stream_id); + CREATE INDEX IF NOT EXISTS stat_day_user ON stat_day(user_key); + CREATE TABLE IF NOT EXISTS stat_emote (emote TEXT PRIMARY KEY, source TEXT, emote_id TEXT); + CREATE TABLE IF NOT EXISTS public_optout (user_key TEXT PRIMARY KEY, user_login TEXT, at TEXT); + CREATE TABLE IF NOT EXISTS stat_meta (key TEXT PRIMARY KEY, value TEXT); + `); + ready = true; + try { backfill(); } catch (e) { console.error('[periodstats] backfill failed:', e.message); } +} + +const currentStream = () => require('./watchtime').currentStreamId() || ''; + +// rows: [{ key, login, name, kind, item, uses, amount, unit, max }]; at = ISO time (default now), stream = id or '' +function add(rows, at = new Date().toISOString(), stream = currentStream()) { + init(); + const ins = d().prepare(`INSERT INTO stat_day (day, stream_id, user_key, user_login, user_name, kind, item, uses, amount, max_amount, unit) + VALUES (@day, @stream, @key, @login, @name, @kind, @item, @uses, @amount, @amount, @unit) + ON CONFLICT(day, stream_id, user_key, kind, item) DO UPDATE SET + uses = uses + excluded.uses, amount = amount + excluded.amount, + max_amount = MAX(max_amount, excluded.max_amount), + user_login = COALESCE(excluded.user_login, user_login), user_name = COALESCE(excluded.user_name, user_name), + unit = COALESCE(excluded.unit, unit)`); + const day = at.slice(0, 10); + for (const r of rows) { + if (!r.key || !r.kind) continue; + ins.run({ day, stream: stream || '', key: String(r.key), login: r.login || null, name: r.name || r.login || null, + kind: r.kind, item: String(r.item ?? ''), uses: r.uses ?? 1, amount: Number(r.amount) || 0, unit: r.unit || null }); + } +} + +function emoteSeen(name, source, id) { + init(); + d().prepare('INSERT INTO stat_emote (emote, source, emote_id) VALUES (?, ?, ?) ON CONFLICT(emote) DO UPDATE SET source = excluded.source, emote_id = COALESCE(excluded.emote_id, emote_id)') + .run(name, source || null, id || null); +} + +// --- public page opt-out (!hideme / !showme in chat, or the button on the admin viewer page) --- +function setOptout(key, login, hide) { + init(); + if (hide) d().prepare('INSERT OR REPLACE INTO public_optout (user_key, user_login, at) VALUES (?, ?, ?)').run(String(key), login || null, new Date().toISOString()); + else d().prepare('DELETE FROM public_optout WHERE user_key = ? OR (user_login IS NOT NULL AND user_login = ?)').run(String(key), login || '-'); +} +function optedOut() { + init(); + const rows = d().prepare('SELECT user_key, user_login FROM public_optout').all(); + return { keys: new Set(rows.map(r => r.user_key)), logins: new Set(rows.map(r => r.user_login).filter(Boolean)) }; +} +const isOptedOut = (key, login) => { const o = optedOut(); return o.keys.has(String(key)) || o.logins.has(String(login || '').toLowerCase()); }; + +function forgetUser(key, login) { + init(); + d().prepare('DELETE FROM stat_day WHERE user_key = ? OR user_key = ? OR user_login = ?').run(String(key || '-'), `name:${login || '-'}`, login || '-'); + d().prepare('DELETE FROM public_optout WHERE user_key = ? OR user_login = ?').run(String(key || '-'), login || '-'); +} + +// --- one-time backfill from the tables that existed before (raw chat is kept 30 days) --- +function backfill() { + if (d().prepare("SELECT 1 FROM stat_meta WHERE key = 'backfill_v1'").get()) return; + const has = t => !!d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t); + const streams = has('stream_session') ? d().prepare('SELECT id, started_at, ended_at FROM stream_session').all() : []; + const at = iso => { const t = Date.parse(iso); return streams.find(s => t >= Date.parse(s.started_at) && t <= Date.parse(s.ended_at || new Date().toISOString()))?.id || ''; }; + const onDay = day => streams.find(s => s.started_at.slice(0, 10) <= day && (s.ended_at || new Date().toISOString()).slice(0, 10) >= day)?.id || ''; + let n = 0; + d().transaction(() => { + // chat from the raw buffer: exact time -> exact stream. Points-eligible = same 5-minute rule as chatlog.js. + const rawCount = new Map(); // user|day -> messages found in raw + if (has('chat_raw')) { + const lastScored = new Map(); + for (const m of d().prepare('SELECT * FROM chat_raw ORDER BY at').all()) { + const t = Date.parse(m.at), prev = lastScored.get(m.user_id); + const scored = prev == null || t - prev >= 5 * 60 * 1000 ? 1 : 0; + if (scored) lastScored.set(m.user_id, t); + const who = { key: m.user_id, login: m.user_login, name: m.user_name }; + const rows = [{ ...who, kind: 'message', amount: scored }]; + if (m.first_msg) rows.push({ ...who, kind: 'intro' }); + for (const e of JSON.parse(m.emotes || '[]')) rows.push({ ...who, kind: 'emote', item: e }); + if (m.command) rows.push({ ...who, kind: 'command', item: m.command }); + add(rows, m.at, at(m.at)); n++; + const k = `${m.user_id}|${m.at.slice(0, 10)}`; rawCount.set(k, (rawCount.get(k) || 0) + 1); + } + } + // messages counted but no longer in the raw buffer (deleted by moderation, or older than 30 days) + if (has('chat_user_day')) for (const r of d().prepare('SELECT c.user_id, c.day, c.messages, u.user_login, u.user_name FROM chat_user_day c LEFT JOIN chat_user u USING (user_id)').all()) { + const rest = r.messages - (rawCount.get(`${r.user_id}|${r.day}`) || 0); + if (rest > 0) add([{ key: r.user_id, login: r.user_login, name: r.user_name, kind: 'message', uses: rest }], r.day + 'T12:00:00.000Z', onDay(r.day)); + } + // watch ticks only happen while live: the stream of that day + if (has('watch_user_day')) for (const r of d().prepare('SELECT w.user_id, w.day, w.ticks, u.user_login, u.user_name FROM watch_user_day w LEFT JOIN watch_user u USING (user_id)').all()) + add([{ key: r.user_id, login: r.user_login, name: r.user_name, kind: 'watch', uses: r.ticks }], r.day + 'T12:00:00.000Z', onDay(r.day)); + // actions: a single use has its exact time; repeated ones are put on the last use + if (has('chat_action')) for (const r of d().prepare('SELECT * FROM chat_action').all()) { + const when = r.uses === 1 ? r.first_at : r.last_at; + add([{ key: r.user_key, login: r.user_login, name: r.user_name, kind: 'action:' + r.action, item: r.item, uses: r.uses, amount: r.amount, unit: r.unit }], when, at(when)); + } + if (has('chat_emote')) for (const r of d().prepare('SELECT emote, source, emote_id FROM chat_emote GROUP BY emote').all()) emoteSeen(r.emote, r.source, r.emote_id); + d().prepare("INSERT INTO stat_meta (key, value) VALUES ('backfill_v1', ?)").run(new Date().toISOString()); + })(); + console.log(`[periodstats] backfilled from existing statistics (${n} raw messages)`); +} + +// ===================== ranges ===================== +// ?p=stream&s= | week | month | year | all, anchored on ?d=YYYY-MM-DD (default today). Days are UTC. +const iso = t => new Date(t).toISOString().slice(0, 10); +const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; +const nice = day => { const [y, m, dd] = day.split('-'); return `${+dd} ${MONTHS[+m - 1].slice(0, 3)} ${y}`; }; + +function streams() { + init(); + return d().prepare('SELECT * FROM stream_session ORDER BY started_at DESC').all(); +} + +function parseRange(q = {}, fallback = 'all') { + let p = ['stream', 'week', 'month', 'year', 'all'].includes(q.p) ? q.p : fallback; + const anchor = /^\d{4}-\d{2}-\d{2}$/.test(q.d || '') ? q.d : iso(Date.now()); + const a = new Date(anchor + 'T00:00:00Z'); + if (p === 'stream') { + const list = streams(); + const s = list.find(x => x.id === String(q.s || '')) || list[0]; + if (!s) p = 'all'; + else { + const i = list.indexOf(s); + return { p, stream: s, label: `Stream · ${nice(s.started_at.slice(0, 10))}`, sub: s.title || '', + prev: list[i + 1] ? { p, s: list[i + 1].id } : null, next: list[i - 1] ? { p, s: list[i - 1].id } : null }; + } + } + if (p === 'week') { + const mon = new Date(a); mon.setUTCDate(a.getUTCDate() - ((a.getUTCDay() + 6) % 7)); + const from = iso(mon), to = iso(mon.getTime() + 6 * 864e5); + return { p, from, to, label: `Week of ${nice(from)}`, sub: `${nice(from)} – ${nice(to)}`, + prev: { p, d: iso(mon.getTime() - 7 * 864e5) }, next: to < iso(Date.now()) ? { p, d: iso(mon.getTime() + 7 * 864e5) } : null }; + } + if (p === 'month') { + const y = a.getUTCFullYear(), m = a.getUTCMonth(); + const from = iso(Date.UTC(y, m, 1)), to = iso(Date.UTC(y, m + 1, 0)); + return { p, from, to, label: `${MONTHS[m]} ${y}`, prev: { p, d: iso(Date.UTC(y, m - 1, 1)) }, + next: to < iso(Date.now()) ? { p, d: iso(Date.UTC(y, m + 1, 1)) } : null }; + } + if (p === 'year') { + const y = a.getUTCFullYear(); + return { p, from: `${y}-01-01`, to: `${y}-12-31`, label: String(y), prev: { p, d: `${y - 1}-01-01` }, + next: `${y}-12-31` < iso(Date.now()) ? { p, d: `${y + 1}-01-01` } : null }; + } + return { p: 'all', label: 'All time' }; +} + +// query string for a range link (prev / next / tabs) +const rangeQuery = r => '?' + Object.entries(r).filter(([, v]) => v != null).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&'); + +function whereOf(r) { + if (r.p === 'stream') return { sql: 'stream_id = ?', args: [r.stream.id] }; + if (r.from) return { sql: 'day BETWEEN ? AND ?', args: [r.from, r.to] }; + return { sql: '1 = 1', args: [] }; +} + +// ===================== the summary both Stats pages show ===================== +// opts.hidden: logins left out completely (bots); opts.anonymous: { keys, logins } counted in totals but never +// named (public page: !hideme); opts.baseline: add StreamElements' watch time from before our tracking ('all' only). +function summary(r, { hidden = [], anonymous = null, baseline = true, top = 10, revenue = false } = {}) { + init(); + const hide = new Set(hidden.map(x => String(x).toLowerCase())); + const anon = (key, login) => anonymous && (anonymous.keys.has(key) || anonymous.logins.has(String(login || '').toLowerCase())); + const w = whereOf(r); + + const names = new Map(); // latest login / name per viewer (bare columns come from the MAX(day) row) + for (const x of d().prepare(`SELECT user_key, user_login, user_name, MAX(day) FROM stat_day GROUP BY user_key`).all()) names.set(x.user_key, x); + const rows = d().prepare(`SELECT user_key, kind, item, SUM(uses) uses, SUM(amount) amount, MAX(max_amount) max_amount, MAX(unit) unit + FROM stat_day WHERE ${w.sql} GROUP BY user_key, kind, item`).all(...w.args) + .filter(x => !hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase())); + + const per = new Map(); // viewer -> { key, login, name, messages, ticks, ... } + const who = k => { + if (!per.has(k)) { const n = names.get(k) || {}; per.set(k, { key: k, login: n.user_login, name: n.user_name || n.user_login, messages: 0, ticks: 0, bits: 0, subs: 0, gifts: 0, points: 0, tips: 0 }); } + return per.get(k); + }; + const emotes = new Map(), commands = new Map(), rewards = new Map(), tipsByUnit = new Map(); + const t = { messages: 0, scored: 0, intros: 0, ticks: 0, emotes: 0, commands: 0, follows: 0, subs: 0, giftSubs: 0, bits: 0, raids: 0, raidViewers: 0, redeems: 0, channelPoints: 0, powerUps: 0, tips: 0 }; + for (const x of rows) { + const v = who(x.user_key); + switch (x.kind) { + case 'message': v.messages += x.uses; t.messages += x.uses; t.scored += x.amount; break; + case 'intro': t.intros += x.uses; break; + case 'watch': v.ticks += x.uses; t.ticks += x.uses; break; + case 'emote': t.emotes += x.uses; emotes.set(x.item, (emotes.get(x.item) || 0) + x.uses); break; + case 'command': t.commands += x.uses; commands.set(x.item, (commands.get(x.item) || 0) + x.uses); break; + case 'action:follow': t.follows += x.uses; break; + case 'action:sub': t.subs += x.uses; v.subs += x.uses; break; + case 'action:gift_sub': t.giftSubs += x.amount; v.gifts += x.amount; break; + case 'action:bits': t.bits += x.amount; v.bits += x.amount; break; + case 'action:power_up': case 'action:custom_power_up': + t.bits += x.amount; v.bits += x.amount; t.powerUps += x.uses; + rewards.set(x.item, (rewards.get(x.item) || 0) + x.uses); break; + case 'action:channel_points': case 'action:auto_reward': + t.redeems += x.uses; t.channelPoints += x.amount; v.points += x.amount; + rewards.set(x.item, (rewards.get(x.item) || 0) + x.uses); break; + case 'action:raid': t.raids += x.uses; t.raidViewers += x.amount; break; + case 'action:tip': t.tips += x.uses; v.tips += x.amount; tipsByUnit.set(x.unit || '', (tipsByUnit.get(x.unit || '') || 0) + x.amount); break; + } + } + + const hasT = t => !!d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t); + const synced = t => hasT(t) && !!d().prepare(`SELECT 1 FROM ${t} LIMIT 1`).get(); + // new followers: Twitch's follower list has every follow date (also before HeyStreamer); our events otherwise + const followWindow = r.p === 'stream' ? [r.stream.started_at, r.stream.ended_at || new Date().toISOString()] + : r.from ? [r.from, r.to + 'T23:59:59.999Z'] : null; + if (synced('tw_follower') && (!synced('tw_daily') || r.p === 'stream')) { + t.follows = followWindow ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE followed_at BETWEEN ? AND ?').get(...followWindow).n + : d().prepare('SELECT COUNT(*) n FROM tw_follower').get().n; + } + + // StreamElements watch time from before our own tracking: no dates, so it only belongs to "all time" + let baselineMinutes = 0; + if (r.p === 'all' && baseline && d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='watch_import'").get()) { + const byLogin = new Map([...per.values()].filter(v => v.login).map(v => [v.login, v])); + for (const b of d().prepare('SELECT user_login, minutes FROM watch_import').all()) { + if (hide.has(b.user_login)) continue; + const v = byLogin.get(b.user_login) || who(`name:${b.user_login}`); + if (!v.login) { v.login = b.user_login; v.name = b.user_login; } + v.extraMinutes = (v.extraMinutes || 0) + b.minutes; baselineMinutes += b.minutes; + } + } + + const people = [...per.values()]; + const named = people.filter(v => !anon(v.key, v.login)); + const board = (f, n = top) => named.map(v => ({ key: v.key, login: v.login, name: v.name, n: f(v) })).filter(x => x.n > 0).sort((a, b) => b.n - a.n).slice(0, n); + // Twitch's daily export (twitchcsv.js). Things we also count ourselves (messages, watch time, follows, streamed days) + // come from it only for days before our own counting started (cutoff); things only Twitch measures (unique / + // engaged viewers, clips, live views, revenue, average + peak viewers) come from it for every day. + const hist = { days: 0, streamedDays: 0, minutesStreamed: 0, minutesWatched: 0, messages: 0, follows: 0, viewerMinutes: 0, + maxViewers: 0, uniqueSum: 0, newEngaged: 0, returningEngaged: 0, clips: 0, clipViews: 0, liveViews: 0, revenue: 0, revenueByType: {} }; + const cutoff = d().prepare("SELECT MIN(day) d FROM stat_day WHERE kind IN ('message', 'watch')").get().d || '9999-12-31'; + let dailyRows = []; + if (r.p !== 'stream' && synced('tw_daily')) { + dailyRows = d().prepare(`SELECT * FROM tw_daily ${r.from ? 'WHERE day BETWEEN ? AND ?' : ''} ORDER BY day`).all(...(r.from ? [r.from, r.to] : [])); + for (const x of dailyRows) { + const before = x.day < cutoff; + if (before) { + hist.messages += x.chat_messages; hist.minutesWatched += x.minutes_watched; hist.follows += x.follows; + if (x.minutes_streamed > 0) { hist.streamedDays++; hist.minutesStreamed += x.minutes_streamed; } + } + if (x.minutes_streamed > 0) { hist.viewerMinutes += x.avg_viewers * x.minutes_streamed; hist.days++; hist.uniqueSum += x.unique_viewers; } + hist.maxViewers = Math.max(hist.maxViewers, x.max_viewers); + hist.newEngaged += x.new_engaged; hist.returningEngaged += x.returning_engaged; + hist.clips += x.clips_created; hist.clipViews += x.clip_views; hist.liveViews += x.live_views; + if (revenue) { + hist.revenue += x.revenue; + for (const [k, v] of Object.entries(JSON.parse(x.revenue_json || '{}'))) hist.revenueByType[k] = (hist.revenueByType[k] || 0) + v; + } + } + t.messages += hist.messages; + if (synced('tw_follower') && r.p !== 'all') { // from the cutoff on: the follower list (CSV before it) + const [a, b] = followWindow; + const from = a > cutoff ? a : cutoff; + t.follows = from <= b ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE followed_at BETWEEN ? AND ?').get(from, b).n : 0; + } else if (synced('tw_follower')) t.follows = d().prepare('SELECT COUNT(*) n FROM tw_follower').get().n; + if (!synced('tw_follower') || r.p !== 'all') t.follows += hist.follows; // all time: the follower list already counts everyone + } + + let bitsBoard = board(v => v.bits), bitsSource = 'heystreamer'; + if (r.p === 'all' && synced('tw_bits')) { + bitsSource = 'twitch'; + bitsBoard = d().prepare('SELECT user_id, user_login, user_name, score FROM tw_bits ORDER BY score DESC').all() + .filter(x => !hide.has(String(x.user_login).toLowerCase()) && !anon(x.user_id, x.user_login)) + .slice(0, top).map(x => ({ key: x.user_id, login: x.user_login, name: x.user_name, n: x.score })); + t.bits = Math.max(t.bits, d().prepare('SELECT COALESCE(SUM(score), 0) n FROM tw_bits').get().n); + } + const meta = new Map(d().prepare('SELECT * FROM stat_emote').all().map(e => [e.emote, e])); + + // the channel's own emotes (Twitch list) with how often they were used in chat in this range + let channelEmotes = []; + if (synced('tw_emote')) { + const byName = new Map(); + for (const [name, uses] of emotes) byName.set(name, uses); + const idToNames = new Map(); + for (const e of meta.values()) if (e.emote_id) idToNames.set(e.emote_id, [...(idToNames.get(e.emote_id) || []), e.emote]); + channelEmotes = d().prepare('SELECT * FROM tw_emote').all().map(e => { + const names = new Set([e.name, ...(idToNames.get(e.id) || [])]); + return { id: e.id, name: e.name, image: e.image, tier: e.tier, type: e.emote_type, gone: !!e.gone, + uses: [...names].reduce((n, x) => n + (byName.get(x) || 0), 0) }; + }).filter(e => !e.gone || e.uses).sort((a, b) => b.uses - a.uses || a.name.localeCompare(b.name)); + } + const sorted = (m, n) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, n); + + // streams in this range, with their own numbers + const streamRows = r.p === 'stream' ? [r.stream] + : streams().filter(s => !r.from || (s.started_at.slice(0, 10) >= r.from && s.started_at.slice(0, 10) <= r.to)); + const perStream = new Map(); + if (streamRows.length) { + const ids = streamRows.map(s => s.id); + for (const x of d().prepare(`SELECT stream_id, kind, user_key, SUM(uses) uses FROM stat_day WHERE stream_id IN (${ids.map(() => '?').join(',')}) + AND kind IN ('message', 'watch') GROUP BY stream_id, kind, user_key`).all(...ids)) { + if (hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase())) continue; + const s = perStream.get(x.stream_id) || { messages: 0, chatters: 0, viewers: 0 }; + if (x.kind === 'message') { s.messages += x.uses; s.chatters++; } else s.viewers++; + perStream.set(x.stream_id, s); + } + } + const checkins = streamRows.length ? d().prepare(`SELECT COUNT(*) n FROM stream_checkin WHERE stream_id IN (${streamRows.map(() => '?').join(',')})`).get(...streamRows.map(s => s.id)).n : 0; + + // activity over the range: per day (week / month), per month (year / all); none for one stream + let series = null; + if (r.p !== 'stream') { + const byMonth = r.p === 'year' || r.p === 'all'; + const buckets = new Map(); + if (r.from && !byMonth) for (let x = Date.parse(r.from + 'T00:00:00Z'); iso(x) <= r.to; x += 864e5) buckets.set(iso(x), { messages: 0, ticks: 0 }); + if (r.p === 'year') for (let m = 1; m <= 12; m++) buckets.set(`${r.from.slice(0, 4)}-${String(m).padStart(2, '0')}`, { messages: 0, ticks: 0 }); + const blank = () => ({ messages: 0, ticks: 0, follows: 0 }); + for (const b of buckets.values()) b.follows = 0; + const fFrom = synced('tw_daily') ? (r.from && r.from > cutoff ? r.from : cutoff) : (r.from || '0000-00-00'); + if (synced('tw_follower')) for (const x of d().prepare(`SELECT substr(followed_at, 1, 10) day, COUNT(*) n FROM tw_follower + WHERE followed_at >= ? ${r.from ? 'AND followed_at <= ?' : ''} GROUP BY day`).all(...[fFrom, ...(r.from ? [r.to + 'T23:59:59.999Z'] : [])])) { + const k = byMonth ? x.day.slice(0, 7) : x.day; + const b = buckets.get(k) || blank(); b.follows += x.n; buckets.set(k, b); + } + for (const x of dailyRows) { + const k = byMonth ? x.day.slice(0, 7) : x.day; + const b = buckets.get(k) || blank(); + if (x.day < cutoff) { + b.messages += x.chat_messages; b.ticks += x.minutes_watched / 5; b.streamMin = (b.streamMin || 0) + x.minutes_streamed; + b.follows += x.follows; + } + if (x.minutes_streamed > 0) { b.vMin = (b.vMin || 0) + x.avg_viewers * x.minutes_streamed; b.vW = (b.vW || 0) + x.minutes_streamed; } + buckets.set(k, b); + } + for (const x of d().prepare(`SELECT day, user_key, kind, SUM(uses) uses FROM stat_day WHERE ${w.sql} AND kind IN ('message', 'watch') GROUP BY day, user_key, kind`).all(...w.args)) { + if (hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase())) continue; + const k = byMonth ? x.day.slice(0, 7) : x.day; + const b = buckets.get(k) || blank(); + if (x.kind === 'message') b.messages += x.uses; else b.ticks += x.uses; + buckets.set(k, b); + } + for (const st of (r.p === 'stream' ? [] : streams())) { + const sd = st.started_at.slice(0, 10); + if (sd < cutoff || (r.from && (sd < r.from || sd > r.to))) continue; + const k = byMonth ? sd.slice(0, 7) : sd, b = buckets.get(k) || blank(); + const mins = (Date.parse(st.ended_at || new Date().toISOString()) - Date.parse(st.started_at)) / 60000; + b.streamMin = (b.streamMin || 0) + mins; + buckets.set(k, b); + } + if (r.p === 'all' && buckets.size) { // every month from the first one with data until now, gaps included + const ks = [...buckets.keys()].sort(); + for (let [y, m] = ks[0].split('-').map(Number), end = new Date().toISOString().slice(0, 7); ; m++) { + if (m > 12) { y++; m = 1; } + const k = `${y}-${String(m).padStart(2, '0')}`; + if (k > end) break; + if (!buckets.has(k)) buckets.set(k, blank()); + } + } + const keys = [...buckets.keys()].sort(); + series = { unit: byMonth ? 'month' : 'day', rows: keys.map(k => ({ key: k, label: byMonth ? `${MONTHS[+k.slice(5, 7) - 1].slice(0, 3)} ${k.slice(2, 4)}` : k.slice(5), + messages: buckets.get(k).messages, watchHours: +(buckets.get(k).ticks * 5 / 60).toFixed(1), follows: buckets.get(k).follows || 0, + streamHours: +((buckets.get(k).streamMin || 0) / 60).toFixed(1), + avgViewers: buckets.get(k).vW ? +(buckets.get(k).vMin / buckets.get(k).vW).toFixed(1) : 0 })) }; + } + + // games: time per category from the title / category changes (HeyStreamer-era streams; Twitch keeps no history of it) + const gameMin = new Map(), gamesOf = new Map(); + if (hasT('stream_change')) { + const prevQ = d().prepare('SELECT at, game FROM stream_change WHERE at < ? ORDER BY at DESC LIMIT 1'); + const inQ = d().prepare('SELECT at, game FROM stream_change WHERE at BETWEEN ? AND ? ORDER BY at'); + for (const st of streamRows) { + const end = st.ended_at || new Date().toISOString(); + const before = prevQ.get(st.started_at); + const segs = [...(before ? [{ at: st.started_at, game: before.game }] : []), ...inQ.all(st.started_at, end)]; + if (!segs.length && st.game) segs.push({ at: st.started_at, game: st.game }); + const list = []; + segs.forEach((c, i) => { + const a = Date.parse(c.at < st.started_at ? st.started_at : c.at), b = Date.parse(segs[i + 1]?.at || end); + const mins = Math.max(0, (b - a) / 60000); + if (!c.game || mins < 1) return; + gameMin.set(c.game, (gameMin.get(c.game) || 0) + mins); + if (!list.includes(c.game)) list.push(c.game); + }); + gamesOf.set(st.id, list); + } + } + + // community: who raided, who supported (named only when not hidden / opted out) + const showName = (key, login) => !hide.has(String(login || '').toLowerCase()) && !anon(key, login); + // (deliberately no list of new followers / first-time chatters: nobody is singled out just for showing up) + const community = { raiders: [], supporters: [] }; + for (const x of rows) { + const v = per.get(x.user_key); if (!v || !showName(v.key, v.login)) continue; + if (x.kind === 'action:raid') community.raiders.push({ login: v.login, name: v.name, raids: x.uses, viewers: x.amount }); + } + community.raiders.sort((a, b) => b.viewers - a.viewers); + community.supporters = people.filter(v => showName(v.key, v.login) && (v.bits || v.subs || v.gifts || v.tips)) + .map(v => ({ login: v.login, name: v.name, bits: v.bits, subs: v.subs, gifts: v.gifts, tips: v.tips })) + .sort((a, b) => (b.bits / 100 + (b.subs + b.gifts) * 5 + b.tips) - (a.bits / 100 + (a.subs + a.gifts) * 5 + a.tips)); + + // one stream: viewer count every 5 minutes + title / category changes (with what was set when it started) + let timeline = null; + if (r.p === 'stream' && hasT('stream_viewers')) { + const st = r.stream, end = st.ended_at || new Date().toISOString(); + const samples = d().prepare('SELECT at, viewers FROM stream_viewers WHERE stream_id = ? ORDER BY at').all(st.id); + const before = d().prepare('SELECT at, title, game FROM stream_change WHERE at < ? ORDER BY at DESC LIMIT 1').get(st.started_at); + const during = d().prepare('SELECT at, title, game FROM stream_change WHERE at BETWEEN ? AND ? ORDER BY at').all(st.started_at, end); + const changes = [...(before ? [{ ...before, at: st.started_at, start: true }] : []), ...during]; + timeline = { start: st.started_at, end, samples, changes }; + } + // across streams: peak and average viewers (streams with samples only) + const sampled = streamRows.filter(x => x.viewer_samples); + let peak = sampled.length ? Math.max(...sampled.map(x => x.peak_viewers || 0)) : null; + let avg = sampled.length ? Math.round(sampled.reduce((a, x) => a + x.viewer_sum / x.viewer_samples, 0) / sampled.length) : null; + if (hist.days) { // Twitch's daily numbers cover every streamed day (weighted by minutes streamed) + peak = Math.max(peak || 0, hist.maxViewers); + avg = Math.round(hist.viewerMinutes / dailyRows.reduce((a, x) => a + (x.minutes_streamed > 0 ? x.minutes_streamed : 0), 0) * 10) / 10; + } + const ownMinutes = streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff) + .reduce((a, x) => a + (Date.parse(x.ended_at || new Date().toISOString()) - Date.parse(x.started_at)) / 60000, 0); + const followers = synced('tw_follower') ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE unfollowed_at IS NULL').get().n : null; + const user = db.getPrimaryUser(); + const subsNow = synced('tw_sub') ? d().prepare('SELECT COUNT(*) n FROM tw_sub WHERE user_id != ?').get(String(user?.twitch_id || '')).n : null; + + return { + range: r, timeline, channelEmotes, bitsSource, community, + games: [...gameMin.entries()].map(([game, minutes]) => ({ game, minutes: Math.round(minutes) })).sort((a, b) => b.minutes - a.minutes), + channel: { followers, subsNow, peak, avg }, + twitch: hist.days || dailyRows.length ? { + cutoff, streamedDays: hist.streamedDays, hoursStreamed: Math.round((hist.minutesStreamed + ownMinutes) / 60), + uniquePerDay: hist.days ? Math.round(hist.uniqueSum / hist.days) : null, newEngaged: hist.newEngaged, returningEngaged: hist.returningEngaged, + clips: hist.clips, clipViews: hist.clipViews, liveViews: hist.liveViews, + revenue: revenue ? +hist.revenue.toFixed(2) : null, + revenueByType: revenue ? Object.entries(hist.revenueByType).filter(([, v]) => v).map(([k, v]) => [k, +v.toFixed(2)]) : null, + } : null, + totals: { + ...t, + chatters: people.filter(v => v.messages).length, + viewers: people.filter(v => v.ticks || v.extraMinutes).length, + // watch time before our counting: Twitch's channel total if imported (then the StreamElements per-viewer + // minutes only feed the leaderboards), else the StreamElements baseline + watchHours: Math.round((t.ticks * 5 + (hist.minutesWatched ? hist.minutesWatched : baselineMinutes)) / 60), + baselineHours: hist.minutesWatched ? 0 : Math.round(baselineMinutes / 60), + historyWatchHours: Math.round(hist.minutesWatched / 60), + hoursStreamed: Math.round((hist.minutesStreamed + streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff || !hist.streamedDays) + .reduce((a, x) => a + (Date.parse(x.ended_at || new Date().toISOString()) - Date.parse(x.started_at)) / 60000, 0)) / 60), + viewersFromBaseline: people.filter(v => !v.ticks && v.extraMinutes).length, + streams: streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff || !hist.streamedDays).length + hist.streamedDays, checkins, + tipsByUnit: [...tipsByUnit.entries()].map(([unit, amount]) => ({ unit, amount: +amount.toFixed(2) })), + }, + streams: streamRows.map(s => { + const n = perStream.get(s.id) || {}; + const mins = Math.round((Date.parse(s.ended_at || new Date().toISOString()) - Date.parse(s.started_at)) / 60000); + return { id: s.id, started_at: s.started_at, ended_at: s.ended_at, live: !s.ended_at, title: s.title || '', game: s.game || '', + minutes: mins, peak: s.peak_viewers || null, source: s.source || 'live', games: gamesOf.get(s.id) || (s.game ? [s.game] : []), avg: s.viewer_samples ? Math.round(s.viewer_sum / s.viewer_samples) : null, + messages: n.messages || 0, chatters: n.chatters || 0, viewers: n.viewers || 0 }; + }), + boards: { + chat: board(v => v.messages), + watch: board(v => v.ticks * 5 + (v.extraMinutes || 0)), + bits: bitsBoard, + subs: board(v => v.subs + v.gifts), + channelPoints: board(v => v.points), + }, + emotes: sorted(emotes, 24).map(([emote, uses]) => ({ emote, uses, source: meta.get(emote)?.source || null, id: meta.get(emote)?.emote_id || null })), + commands: sorted(commands, 24).map(([command, uses]) => ({ command, uses })), + rewards: sorted(rewards, 15).map(([item, uses]) => ({ item, uses })), + series, + }; +} + +module.exports = { init, add, emoteSeen, setOptout, optedOut, isOptedOut, forgetUser, parseRange, rangeQuery, streams, summary, backfill }; diff --git a/src/points.js b/src/points.js index b9cda8e..9dd83d2 100644 --- a/src/points.js +++ b/src/points.js @@ -1,4 +1,4 @@ -// Points (planned point system, values agreed 2026-11-22, see docs/PLANS.md), calculated from the statistics +// Points (point system, values in docs/PLANS.md), calculated from the statistics // tables, so changing a value here recalculates everyone. Also used by the Stats page; later by !points. const db = require('./db'); @@ -16,7 +16,7 @@ const VALUE = { streakPer: 5, streakMax: 100, }; -// Levels by watch time (our ticks + StreamElements import), not points: bits/subs do not buy a level. +// Levels by watch time (our ticks + the StreamElements baseline), not points: bits/subs do not buy a level. const LEVELS = [ { minHours: 0, name: 'Viewer' }, { minHours: 50, name: 'Regular' }, { minHours: 200, name: 'Loyal' }, { minHours: 1000, name: 'Veteran' }, ]; @@ -50,7 +50,7 @@ function everyone() { x.watchMinutes = (x.watchMinutes || 0) + (r.ticks || 0) * 5; add(x, 'watching', (r.ticks || 0) * VALUE.watchTick); } - // StreamElements watch time imported once (seimport.js): login + minutes, counted like our ticks + // StreamElements watch time from before our tracking (imported once, see watchtime.js): 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; diff --git a/src/redeems.js b/src/redeems.js index 2d5e729..b7c9d08 100644 --- a/src/redeems.js +++ b/src/redeems.js @@ -54,13 +54,14 @@ function pick(variations) { function toAlert(v, { user, input, emote, bits }) { const spoken = !!(v.tts_voice_id && input); // TTS variations: envelope letter (fx.js envelope()) // video variations play full-screen on the ?parts=video overlay (public/alerts/video.js) - const style = v.video ? 'video' : spoken ? 'tts' : (STYLE[`${v.kind}:${v.key}`] || 'cassette'); + // look: the variation's Card / Cassette (older rows: cassette); read-aloud ones: Card or Letter (Actions → Alerts) + const style = v.video ? 'video' : spoken ? 'tts' : (STYLE[`${v.kind}:${v.key}`] || (v.look === 'card' ? 'card' : 'cassette')); const line = spoken ? LINE.tts : LINE[style]; return { type: 'redeem', kind: v.kind, key: v.key, style, vid: v.id, // vid: re-speak on replay if the mp3 was pruned user, reward: v.title, variation: v.name, rarity: v.rarity, input: input || null, // special styles have their own wording unless the caption was customised - caption: style !== 'cassette' && v.caption === 'redeemed it! ♡' ? line : v.caption, + caption: style !== 'cassette' && style !== 'card' && v.caption === 'redeemed it! ♡' ? line : v.caption, sound: spoken ? null : (v.sound || null), volume: v.volume, // TTS on: the voice replaces the sound polaroid: !!v.polaroid, art: v.art || null, emote: emoteUrl(emote), video: v.video || null, bits: bits ?? null, diff --git a/src/routers/actions.js b/src/routers/actions.js deleted file mode 100644 index 1d32b1b..0000000 --- a/src/routers/actions.js +++ /dev/null @@ -1,45 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const db = require('../db'); -const dispatch = require('../dispatch'); -const { resetCooldown } = require('../cooldowns'); - -router.get('/', (req, res) => { - const actions = db.getAllActions(); - const media = db.getAllMedia(); - res.render('actions', { actions, media }); -}); - -router.post('/', (req, res) => { - const { name, event_type, event_detail, action_type, media_file_id, alert_text, cooldown_seconds } = req.body; - db.createAction({ - name, - event_type, - event_detail: event_detail || null, - action_type, - media_file_id: media_file_id ? parseInt(media_file_id) : null, - alert_text: alert_text || null, - cooldown_seconds: parseInt(cooldown_seconds) || 0, - }); - res.redirect('/actions'); -}); - -router.post('/:id/test', (req, res) => { - const action = db.getAction(parseInt(req.params.id)); - if (!action) return res.status(404).send('Not found'); - resetCooldown(action.id); - dispatch.dispatchEvent(action.event_type, action.event_detail, 'test'); - res.redirect('/actions'); -}); - -router.post('/:id/toggle', (req, res) => { - db.toggleAction(parseInt(req.params.id)); - res.redirect('/actions'); -}); - -router.post('/:id/delete', (req, res) => { - db.deleteAction(parseInt(req.params.id)); - res.redirect('/actions'); -}); - -module.exports = router; diff --git a/src/routers/alertsetup.js b/src/routers/alertsetup.js new file mode 100644 index 0000000..a216f6d --- /dev/null +++ b/src/routers/alertsetup.js @@ -0,0 +1,40 @@ +// Actions → Alerts: how follows, subs, gifts, raids, bits, tips and the Hype Train look and sound (src/theme.js). +const express = require('express'); +const router = express.Router(); +const db = require('../db'); +const ws = require('../ws'); +const theme = require('../theme'); +const library = require('../library'); + +router.get('/', (req, res) => { + const media = library.list(); + res.render('alerts_setup', { + theme: theme.get(), + images: media.filter(m => m.type === 'image'), + sounds: media.filter(m => m.type === 'audio'), + }); +}); + +// preview: the real overlay code with a button per alert; looks: the defaults, the optional styles, this channel's own +function previewThemes() { + const optional = theme.merge(theme.DEFAULT, { style: 'polaroid', redeemStyle: 'cassette', ttsStyle: 'letter' }); + return { + mine: { label: 'Your alerts', theme: theme.get() }, + defaults: { label: 'Defaults (Card)', theme: theme.DEFAULT }, + optional: { label: 'Polaroid / Cassette / Letter', theme: optional }, + }; +} +router.get('/preview', (req, res) => { + res.render('alerts_preview', { layout: false, base: '/alerts/', themes: previewThemes(), start: req.query.look || 'mine', samples: require('../alerts').SAMPLES }); +}); + +// whole theme as JSON from the editor +router.post('/', express.json({ limit: '200kb' }), (req, res) => { + try { + const t = theme.save(req.body || {}); + ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); // overlays use it at once + res.json({ ok: true, theme: t }); + } catch (e) { res.status(400).json({ ok: false, error: e.message }); } +}); + +module.exports = router; diff --git a/src/routers/auth.js b/src/routers/auth.js index 22f5fdd..7dc70bf 100644 --- a/src/routers/auth.js +++ b/src/routers/auth.js @@ -16,6 +16,8 @@ const SCOPES = [ '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) + 'moderation:read', // stats: who is a moderator (twitchsync.js) + 'channel:read:vips', // stats: who is a VIP (twitchsync.js) ].join(' '); router.get('/login', (req, res) => { diff --git a/src/routers/public.js b/src/routers/public.js new file mode 100644 index 0000000..ed940af --- /dev/null +++ b/src/routers/public.js @@ -0,0 +1,38 @@ +// Public stats page (no login): stream / week / month / year / all time, the same numbers as the admin Stats page +// (periodstats.js + views/_statsbody.ejs). Served at the host in Settings → Public stats page (e.g. +// stats.example.com, routed in app.js) and at /public on the admin host (works while logged in even when off). +// Never shown here: message text, bots (Settings → Hidden chatters), names of viewers who typed !hideme. +const express = require('express'); +const router = express.Router(); +const db = require('../db'); +const chatlog = require('../chatlog'); +const watchtime = require('../watchtime'); +const periodstats = require('../periodstats'); +const points = require('../points'); + +router.get('/', (req, res) => { + const st = db.getSettings(); + if (!st.public_stats_enabled && !req.session?.userId) return res.status(404).send('Not found'); + chatlog.init(); watchtime.init(); periodstats.init(); + const range = periodstats.parseRange(req.query, 'all'); + const user = db.getPrimaryUser(); + // the streamer herself is counted in the totals but not on the public leaderboards + const anonymous = periodstats.optedOut(); + if (user) { anonymous.keys.add(String(user.twitch_id)); if (user.login) anonymous.logins.add(user.login.toLowerCase()); } + const s = periodstats.summary(range, { hidden: chatlog.hiddenUsers(), anonymous }); + const channel = (st.channel || user?.login || '').replace(/^#/, ''); + // community ranks (Regular and up, all time), without bots, the streamer and !hideme viewers + const hidden = new Set(chatlog.hiddenUsers()); + const ranks = [...points.everyone().values()] + .filter(x => x.level.name !== 'Viewer' && !hidden.has(String(x.login || '').toLowerCase()) + && !anonymous.logins.has(String(x.login || '').toLowerCase()) && !anonymous.keys.has(String(x.user_id || x.key))) + .sort((a, b) => (b.watchMinutes || 0) - (a.watchMinutes || 0)).map(x => ({ login: x.login, name: x.name, level: x.level.name })); + res.set('Cache-Control', 'public, max-age=60'); + res.render('public_stats', { + layout: false, s, q: periodstats.rangeQuery, base: req.baseUrl || '', ranks, view: req.query.v === 'streams' ? 'streams' : 'community', tz: st.timezone || 'UTC', + channel, displayName: user?.display_name || channel, live: watchtime.isLive(), + preview: !st.public_stats_enabled, + }); +}); + +module.exports = router; diff --git a/src/routers/redeems.js b/src/routers/redeems.js index c213962..dc48774 100644 --- a/src/routers/redeems.js +++ b/src/routers/redeems.js @@ -77,6 +77,7 @@ router.get('/', async (req, res) => { for (const g of groups) for (const t of g.items) t.variations = byTrigger.get(`${t.kind}|${t.key}`) || []; res.render('redeems', { + theme: require('../theme').get(), groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY, sounds: soundOptions(), videos: videoOptions(), @@ -91,14 +92,16 @@ router.post('/variation', (req, res) => { const { kind, key, title } = req.body; if (!['reward', 'auto_reward', 'power_up', 'custom_power_up'].includes(kind) || !key) return res.status(400).send('bad trigger'); const n = db.getVariationsFor(kind, key).length; - const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key) }); + const look = require('../theme').get().redeemStyle === 'cassette' ? 'cassette' : 'card'; // Actions → Alerts: look of new variations + const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key), look }); back(res, v); }); -// one variation's fields from the editor. display: cassette | sound (sound only) | video +// one variation's fields from the editor. display: card | cassette | sound (sound only) | video function cleanVariation(v, b) { const vol = parseFloat(b.volume); - const display = ['cassette', 'sound', 'video'].includes(b.display) ? b.display : (v.video ? 'video' : v.polaroid ? 'cassette' : 'sound'); + const was = v.video ? 'video' : !v.polaroid ? 'sound' : v.look === 'card' ? 'card' : 'cassette'; + const display = ['card', 'cassette', 'sound', 'video'].includes(b.display) ? b.display : was; const videos = new Set(videoOptions().map(o => o.url)); const video = display === 'video' && videos.has(b.video) ? b.video : ''; const on = x => x === true || x === 'on' || x === 1 || x === '1'; @@ -107,7 +110,8 @@ function cleanVariation(v, b) { rarity: redeems.RARITY[b.rarity] ? b.rarity : v.rarity, sound: String(b.sound || ''), volume: isNaN(vol) ? v.volume : Math.max(0, Math.min(1, vol)), - polaroid: display === 'cassette' ? 1 : 0, + polaroid: display === 'cassette' || display === 'card' ? 1 : 0, + look: display === 'card' ? 'card' : display === 'cassette' ? 'cassette' : v.look || '', video, caption: String(b.caption || '').trim().slice(0, 120) || 'redeemed it! ♡', art: String(b.art || ''), diff --git a/src/routers/settings.js b/src/routers/settings.js index 63d7c25..23ee338 100644 --- a/src/routers/settings.js +++ b/src/routers/settings.js @@ -1,17 +1,15 @@ +// Settings: one page per category (sidebar in views/layout.ejs, list in src/nav.js). Each page saves only its own +// fields, so saving one page never resets another. Views: views/settings/
.ejs. const express = require('express'); const router = express.Router(); const db = require('../db'); -const eventsub = require('../eventsub'); const ws = require('../ws'); const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; }; -const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; }; - -router.get('/', (req, res) => { - const settings = db.getSettings(); - const baseUrl = process.env.APP_BASE_URL; - res.render('settings', { settings, baseUrl }); -}); +const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; }; +const on = v => v === 'on' ? 1 : 0; +const logins = v => String(v || '').split(/[\s,]+/).map(s => s.replace(/^@/, '').toLowerCase()).filter(Boolean).join(', ').slice(0, 2000); +const validTz = tz => { try { new Intl.DateTimeFormat('en', { timeZone: tz }); return true; } catch { return false; } }; // only a real HUDFX overlay link (https://overlays.hudfx.io/overlay/), anything else clears it function hudfxUrl(v) { @@ -21,42 +19,94 @@ function hudfxUrl(v) { } catch { return ''; } } -router.post('/', (req, res) => { - const b = req.body; - db.updateSettings({ - channel: b.channel || '', - message_timeout: int(b.message_timeout, 30), - max_messages: int(b.max_messages, 20), - gap_audio_enabled: b.gap_audio_enabled === 'on' ? 1 : 0, - gap_audio_url: b.gap_audio_url || '', - gap_audio_min_silence: int(b.gap_audio_min_silence, 60), - gap_audio_min_volume: flt(b.gap_audio_min_volume, 0.2), - gap_audio_max_volume: flt(b.gap_audio_max_volume, 1.0), - gap_audio_loud_after: int(b.gap_audio_loud_after, 3600), - tts_max_chars: Math.max(20, Math.min(500, int(b.tts_max_chars, 200))), - tts_say_name: b.tts_say_name === 'on' ? 1 : 0, - tts_blocklist: String(b.tts_blocklist || '').slice(0, 20000), - hudfx_overlay_url: hudfxUrl(b.hudfx_overlay_url), - chat_hidden_users: String(b.chat_hidden_users || '').split(/[\s,]+/).map(s => s.replace(/^@/, '').toLowerCase()).filter(Boolean).join(', ').slice(0, 2000), - chat_hide_commands: b.chat_hide_commands === 'on' ? 1 : 0, - custom_css: b.custom_css || '', - custom_js: b.custom_js || '', - }); +// section -> fields it owns (parsed from the form) +const FIELDS = { + general: b => ({ + channel: String(b.channel || '').trim().replace(/^#/, '').toLowerCase().slice(0, 25), + timezone: validTz(b.timezone) ? b.timezone : (db.getSettings().timezone || 'UTC'), // invalid: keep the old one + }), + chat: b => ({ + message_timeout: int(b.message_timeout, 30), max_messages: int(b.max_messages, 20), + chat_hidden_users: logins(b.chat_hidden_users), chat_hide_commands: on(b.chat_hide_commands), + gap_audio_enabled: on(b.gap_audio_enabled), gap_audio_url: String(b.gap_audio_url || '').trim(), + gap_audio_min_silence: int(b.gap_audio_min_silence, 60), gap_audio_min_volume: flt(b.gap_audio_min_volume, 0.2), + gap_audio_max_volume: flt(b.gap_audio_max_volume, 1.0), gap_audio_loud_after: int(b.gap_audio_loud_after, 3600), + }), + tts: b => ({ + tts_max_chars: Math.max(20, Math.min(500, int(b.tts_max_chars, 200))), tts_say_name: on(b.tts_say_name), + tts_blocklist: String(b.tts_blocklist || '').slice(0, 20000), + }), + stats: b => ({ + public_stats_enabled: on(b.public_stats_enabled), + public_stats_host: String(b.public_stats_host || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '').replace(/[^a-z0-9.-]/g, '').slice(0, 200), + }), + advanced: b => ({ custom_css: b.custom_css || '', custom_js: b.custom_js || '' }), + hudfx: b => ({ hudfx_overlay_url: hudfxUrl(b.hudfx_overlay_url) }), +}; +const PAGES = ['general', 'connections', 'obs', 'chat', 'tts', 'stats', 'backup', 'advanced']; - // Push updated settings to all connected overlays so they don't need a page reload - ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); +function locals(section, req) { + const settings = db.getSettings(); + const base = (process.env.APP_BASE_URL || '').replace(/\/$/, ''); + const out = { section, settings, base, overlayUrl: `${base}/overlay/${settings.overlay_id}`, msg: req.query.msg || null, err: req.query.err || null }; + if (section === 'connections') { + out.eventsub = require('../eventsub').getStatus(); + out.se = require('../streamelements').getStatus(); + out.user = db.getPrimaryUser(); + } + if (section === 'chat') out.sounds = require('../library').list().filter(m => m.type === 'audio'); + if (section === 'stats') { + out.sync = require('../twitchsync').lastStatus(); + out.csv = require('../twitchcsv').status(); + } + return out; +} - console.log(`[settings] Saved — channel: ${b.channel}, gap_audio: ${b.gap_audio_enabled === 'on'}`); - res.redirect('/settings'); +router.get('/', (req, res) => res.redirect('/settings/general')); + +router.get('/:section', (req, res, next) => { + const s = req.params.section; + if (!PAGES.includes(s)) return next(); + res.render(`settings/${s}`, locals(s, req)); }); -router.post('/reconnect', (req, res) => { - const user = db.getUserById(req.session.userId); - if (user) { - eventsub.start(user); - console.log('[settings] EventSub reconnect triggered'); - } - res.redirect('/settings'); +router.post('/:section', (req, res, next) => { + const s = req.params.section; + if (!FIELDS[s]) return next(); + db.updateSettings(FIELDS[s](req.body)); + ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); // overlays update without a reload + const page = s === 'hudfx' ? 'connections' : s; + res.redirect(`/settings/${page}?msg=` + encodeURIComponent('Saved')); +}); + +// Connections: StreamElements token (secret: never sent back to the page, only "set / not set") +router.post('/connections/se', (req, res) => { + const token = String(req.body.se_jwt || '').trim(); + if (req.body.clear === '1') db.updateSettings({ se_jwt: '' }); + else if (token) db.updateSettings({ se_jwt: token.slice(0, 4000) }); + require('../streamelements').restart(); + res.redirect('/settings/connections?msg=' + encodeURIComponent(req.body.clear === '1' ? 'StreamElements token removed' : token ? 'StreamElements token saved, connecting…' : 'Reconnecting to StreamElements…')); +}); + +router.post('/connections/reconnect', (req, res) => { + const user = db.getUserById(req.session.userId) || db.getPrimaryUser(); + if (user) require('../eventsub').start(user); + res.redirect('/settings/connections?msg=' + encodeURIComponent('Reconnecting to Twitch…')); +}); + +// Backup: download / restore the whole setup (src/backup.js) +router.get('/backup/export', (req, res) => { + const day = new Date().toISOString().slice(0, 10); + res.set('Content-Disposition', `attachment; filename="heystreamer-backup-${day}.json"`); + res.json(require('../backup').exportAll()); +}); +const upload = require('multer')({ storage: require('multer').memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } }); +router.post('/backup/import', upload.single('file'), (req, res) => { + try { + const r = require('../backup').importAll(JSON.parse(req.file?.buffer?.toString('utf8') || 'null')); + ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); + res.redirect('/settings/backup?msg=' + encodeURIComponent(`Imported ${r.variations} redeem variations, ${r.voices} TTS voices and the settings`)); + } catch (e) { res.redirect('/settings/backup?err=' + encodeURIComponent('Import failed: ' + e.message)); } }); module.exports = router; diff --git a/src/routers/stats.js b/src/routers/stats.js index d8bb967..f1b96b8 100644 --- a/src/routers/stats.js +++ b/src/routers/stats.js @@ -1,4 +1,5 @@ -// Stats page: overview, activity per day, leaderboards, top emotes/commands, viewer lookup, forget a viewer. +// Stats page: one stream / week / month / year / all time (periodstats.js, shared with the public page in +// routers/public.js), all-time points board, viewer lookup, public-page opt-out, forget a viewer. // Bots (Settings → Hidden chatters) are counted but left out of everything shown here. const express = require('express'); const router = express.Router(); @@ -6,91 +7,41 @@ const db = require('../db'); const chatlog = require('../chatlog'); const watchtime = require('../watchtime'); const points = require('../points'); -const seimport = require('../seimport'); +const periodstats = require('../periodstats'); +const twitchsync = require('../twitchsync'); +const twitchcsv = require('../twitchcsv'); +const upload = require('multer')({ storage: require('multer').memoryStorage(), limits: { fileSize: 5 * 1024 * 1024, files: 30 } }); 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) : []); const one = (sql, ...a) => (has(sql.match(/FROM (\w+)/)[1]) ? db.raw().prepare(sql).get(...a) : null) || {}; -function days(n) { // last n days, oldest first, as YYYY-MM-DD (UTC, like the stored days) - const out = []; - for (let i = n - 1; i >= 0; i--) out.push(new Date(Date.now() - i * 864e5).toISOString().slice(0, 10)); - return out; -} - router.get('/', (req, res) => { - chatlog.init(); watchtime.init(); - const hidden = new Set(chatlog.hiddenUsers()); - const ok = login => !hidden.has(String(login || '').toLowerCase()); - 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)); - // 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])); - - // per day (last 30 days), bots left out - const d30 = days(30), since = d30[0]; - const msgDay = new Map(), watchDay = new Map(); - for (const r of all('SELECT user_id, day, messages FROM chat_user_day WHERE day >= ?', since)) if (ok(loginOf.get(r.user_id))) msgDay.set(r.day, (msgDay.get(r.day) || 0) + r.messages); - for (const r of all('SELECT user_id, day, ticks FROM watch_user_day WHERE day >= ?', since)) if (ok(loginOf.get(r.user_id))) watchDay.set(r.day, (watchDay.get(r.day) || 0) + r.ticks * 5); - - const sumAct = (types, f = r => r.amount) => { - const m = new Map(); - for (const r of actions) if (types.includes(r.action)) m.set(r.user_key, { login: r.user_login, name: r.user_name, n: (m.get(r.user_key)?.n || 0) + f(r) }); - return [...m.values()].sort((a, b) => b.n - a.n).slice(0, 10); - }; - - const emotes = new Map(), commands = new Map(); - for (const r of all('SELECT user_id, emote, source, emote_id, uses FROM chat_emote')) if (ok(loginOf.get(r.user_id))) { - const e = emotes.get(r.emote) || { emote: r.emote, source: r.source, id: r.emote_id, uses: 0 }; e.uses += r.uses; emotes.set(r.emote, e); - } - for (const r of all('SELECT user_id, command, uses FROM chat_command')) if (ok(loginOf.get(r.user_id))) commands.set(r.command, (commands.get(r.command) || 0) + r.uses); - + chatlog.init(); watchtime.init(); periodstats.init(); + const hidden = chatlog.hiddenUsers(); + const range = periodstats.parseRange(req.query, 'all'); + const summary = periodstats.summary(range, { hidden, revenue: true }); + const viewers = [...points.everyone().values()].filter(x => !hidden.includes(String(x.login || '').toLowerCase())); res.render('stats', { live: watchtime.isLive(), - hiddenCount: hidden.size, - overview: { - viewers: viewers.length, - messages: users.reduce((s, r) => s + r.messages, 0), - 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, - }, - 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.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']), - }, - 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 }, + hiddenCount: hidden.length, + since: one('SELECT MIN(day) t FROM stat_day').t || null, + s: summary, q: periodstats.rangeQuery, + pointsBoard: [...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 })), + ranks: viewers.filter(x => x.level.name !== 'Viewer').sort((a, b) => (b.watchMinutes || 0) - (a.watchMinutes || 0)).map(x => ({ login: x.login, name: x.name, level: x.level.name })), + view: req.query.v === 'streams' ? 'streams' : 'community', + tz: db.getSettings().timezone || 'UTC', + publicUrl: publicUrl(), + sync: twitchsync.lastStatus(), + csv: twitchcsv.status(), 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)); - } -}); +function publicUrl() { + const st = db.getSettings(); + return st.public_stats_enabled && st.public_stats_host ? `https://${st.public_stats_host}/` : null; +} // one viewer: /stats/viewer?q= router.get('/viewer', (req, res) => { @@ -107,7 +58,16 @@ 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, + importedMinutes: watchtime.baselineMinutes(v.login), + publicHidden: periodstats.isOptedOut(v.user_id || v.key, v.login), + twitch: twitchsync.viewer(id, v.login), + badges: (() => { const b = id ? one('SELECT badges, sub_months, at FROM chat_badges WHERE user_id = ?', id) : {}; return { list: JSON.parse(b.badges || '[]'), subMonths: b.sub_months || null, at: b.at || null }; })(), + given: (() => { + const rows = all('SELECT action, uses, amount FROM chat_action WHERE user_key = ? OR user_login = ?', v.key, v.login); + const sum = (types, f) => rows.filter(r => types.includes(r.action)).reduce((a, r) => a + f(r), 0); + return { bits: sum(['bits', 'power_up', 'custom_power_up'], r => r.amount), subs: sum(['sub'], r => r.uses), + subMonths: sum(['sub'], r => r.amount), gifts: sum(['gift_sub'], r => r.amount) }; + })(), 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) : [], @@ -116,19 +76,50 @@ router.get('/viewer', (req, res) => { }); }); -// renamed on Twitch: move the StreamElements-imported watch time to the new name (and remember it for re-imports) +// pull followers, subs, roles, bits, emotes, VODs from Twitch now +router.post('/sync', async (req, res) => { + const st = await twitchsync.sync(); + const bad = Object.entries(st.parts || {}).filter(([, v]) => !String(v).startsWith('ok')); + const text = bad.length ? `Sync with Twitch: ${bad.map(([k, v]) => `${k} failed (${v})`).join('; ')}` : 'Synced with Twitch'; + res.redirect(req.query.back === 'settings' ? `/settings/stats?${bad.length ? 'err' : 'msg'}=` + encodeURIComponent(text) : '/stats?msg=' + encodeURIComponent(text)); +}); + +// Twitch Creator Dashboard "Analytics and Revenue by day" CSV exports (several at once; importing again is safe) +router.post('/import-twitch', upload.array('files'), (req, res) => { + const done = [], bad = []; + for (const f of req.files || []) { + try { const r = twitchcsv.importCsv(f.buffer.toString('utf8')); done.push(r); } + catch (e) { bad.push(`${f.originalname}: ${e.message}`); } + } + const days = done.reduce((a, r) => a + r.days, 0); + const from = done.map(r => r.from).filter(Boolean).sort()[0], to = done.map(r => r.to).filter(Boolean).sort().pop(); + const msg = (done.length ? `Imported ${days} days of Twitch analytics${from ? ` (${from} – ${to})` : ''} from ${done.length} file${done.length === 1 ? '' : 's'}.` : '') + + (bad.length ? ` Import failed: ${bad.join('; ')}` : ''); + res.redirect((req.query.back === 'settings' ? '/settings/stats?msg=' : '/stats?msg=') + encodeURIComponent(msg || 'No files chosen')); +}); + +// renamed on Twitch: move a viewer's StreamElements watch time (from before our tracking) to the new name router.post('/viewer/rename', (req, res) => { try { - const to = seimport.rename(req.body.from, req.body.to); + const to = watchtime.renameBaseline(req.body.from, req.body.to); res.redirect('/stats/viewer?q=' + encodeURIComponent(to)); } catch (e) { res.redirect('/stats?msg=' + encodeURIComponent('Rename failed: ' + e.message)); } }); +// public stats page: leave out / show again (same as the viewer typing !hideme / !showme) +router.post('/viewer/public', (req, res) => { + const login = String(req.body.login || '').toLowerCase(), key = String(req.body.user_id || '') || `name:${login}`; + periodstats.setOptout(key, login, req.body.hide === '1'); + res.redirect('/stats/viewer?q=' + encodeURIComponent(login)); +}); + // 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 || ''); if (id) { chatlog.forgetUser(id); watchtime.forgetUser(id); } else if (login) chatlog.forgetUser(login); + periodstats.forgetUser(id || null, login || null); // also the rows keyed by name (tips, watch streaks) if (login) db.raw().prepare('DELETE FROM activity_log WHERE lower(username) = ?').run(login); + if (login && has('watch_import')) db.raw().prepare('DELETE FROM watch_import WHERE user_login = ?').run(login); // StreamElements minutes too console.log(`[stats] forgot viewer ${login || id}`); res.redirect('/stats'); }); diff --git a/src/seimport.js b/src/seimport.js deleted file mode 100644 index 1aa6f07..0000000 --- a/src/seimport.js +++ /dev/null @@ -1,81 +0,0 @@ -// 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 - ); - 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; - 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(), alias = aliasMap(); - d.transaction(() => { - d.prepare('DELETE FROM watch_import').run(); - 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`); - 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, rename }; diff --git a/src/server.js b/src/server.js index 9c77551..e129e9b 100644 --- a/src/server.js +++ b/src/server.js @@ -9,6 +9,7 @@ const app = require('./app'); const PORT = process.env.PORT || 3000; db.init(); +require('./theme').importLegacyFile(); // once: an old public/alerts/theme.js moves into Actions → Alerts const server = http.createServer(app); const wss = new WebSocketServer({ server, path: '/ws/overlay' }); @@ -21,7 +22,9 @@ 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 + require('./periodstats').init(); // per day + per stream statistics (backfills once from the tables above) + require('./twitchcsv').init(); // Twitch daily analytics imported from CSV (Stats page) + if (process.env.EVENTSUB_DISABLED !== '1') require('./twitchsync').start(); // followers, subs, roles, bits, emotes, VODs from Twitch // 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/src/streamelements.js b/src/streamelements.js index 3315f5b..8b8e35d 100644 --- a/src/streamelements.js +++ b/src/streamelements.js @@ -1,5 +1,6 @@ // StreamElements tips via the Astro websocket (https://docs.streamelements.com/websockets). -// Set SE_JWT in .env (StreamElements dashboard -> avatar -> channel -> copy JWT token). Unset = off. +// JWT token: Settings → Connections (StreamElements dashboard -> avatar -> channel -> copy JWT token); SE_JWT in .env +// still works as a fallback. Empty = off. Saving the token restarts the connection (restart()). // Protocol: welcome -> subscribe {topic:'channel.tips', token, token_type:'jwt'} -> messages on topic channel.tips. // Server PINGs every 30 s (ws answers PONG automatically); a 'reconnect' message carries reconnect_token, // and connecting with ?reconnect_token= restores subscriptions without subscribing again. @@ -11,8 +12,10 @@ let ws = null, shouldRun = false, retryTimer = null, retryMs = 5000; const status = { enabled: false, connected: false, subscribed: false, error: null, lastTipAt: null }; const seen = new Map(); // tip _id -> time, so a resent tip alerts only once +const jwt = () => (require('./db').getSettings()?.se_jwt || process.env.SE_JWT || '').trim(); + function start() { - if (!process.env.SE_JWT) { console.log('[se] SE_JWT not set: StreamElements tips off'); return; } + if (!jwt()) { status.enabled = false; console.log('[se] no StreamElements token: tips off'); return; } status.enabled = true; shouldRun = true; connect(URL_BASE, true); } @@ -43,7 +46,7 @@ function handle(sock, m, subscribe) { case 'welcome': status.connected = true; status.error = null; retryMs = 5000; if (subscribe) sock.send(JSON.stringify({ type: 'subscribe', nonce: 'tips-' + Date.now(), - data: { topic: 'channel.tips', token: process.env.SE_JWT, token_type: 'jwt' } })); + data: { topic: 'channel.tips', token: jwt(), token_type: 'jwt' } })); else status.subscribed = true; break; case 'response': @@ -71,5 +74,6 @@ function tip(data) { alerts.send(alerts.fromTip(data), data); } -function getStatus() { return { ...status }; } -module.exports = { start, stop, getStatus }; +function getStatus() { return { ...status, source: require('./db').getSettings()?.se_jwt ? 'settings' : process.env.SE_JWT ? 'env' : null }; } +function restart() { stop(); status.error = null; start(); } +module.exports = { start, stop, restart, getStatus }; diff --git a/src/theme.js b/src/theme.js new file mode 100644 index 0000000..884e13e --- /dev/null +++ b/src/theme.js @@ -0,0 +1,102 @@ +// Alert theme: how alerts look and sound, edited on Actions → Alerts and saved in the database (settings.alert_theme, +// JSON). Nothing channel-specific lives in the code or in files: a fresh install uses DEFAULT below (the plain Card +// style, no pictures, no sounds); each channel picks its own pictures and sounds from the Media library. +// The overlay gets the merged theme through the settings it already receives (S.alert_theme) and reads it per alert, +// so a save shows up without reloading OBS. +// +// style events (follow, sub, ...): 'card' (plain, for everyone) | 'polaroid' (taped photo) +// redeemStyle default look of new redeem variations: 'card' | 'cassette' +// ttsStyle redeems with a TTS voice: 'card' | 'letter' (envelope letter) +// card colours of the Card style +// art / sounds per event: media URLs ('' = none). bitsTiers: highest matching min wins, under bitsMin no alert. +const db = require('./db'); + +const EVENTS = ['follow', 'sub', 'resub', 'prime', 'gift', 'streak', 'raid', 'tip', 'hype']; +const DEFAULT = { + style: 'card', redeemStyle: 'card', ttsStyle: 'card', + card: { accent: '#9146ff', bg: '#ffffff', text: '#1f1f23' }, + art: Object.fromEntries(EVENTS.map(e => [e, ''])), + sounds: { follow: '', sub: '', gift: '', streak: '', raid: '', tip: '', hypeBegin: '', hypeLevel: '', hypeEnd: '' }, + volume: 0.8, + heart: '', raidFallback: '', back: [], // polaroid extras: corner sticker, raid card fallback, photos stacked behind + defaultSticker: '', // cassette sticker when a variation has none + bitsMin: 1, + bitsTiers: [ + { min: 1000, art: '', sound: '', volume: null, badge: '#e0457b', hearts: 3 }, + { min: 100, art: '', sound: '', volume: null, badge: '#9b6bdc', hearts: 1 }, + { min: 1, art: '', sound: '', volume: null, badge: '#8a8aa8', hearts: 0 }, + ], +}; + +const isObj = x => x && typeof x === 'object' && !Array.isArray(x); +function merge(base, over) { + if (!isObj(over)) return base; + const out = { ...base }; + for (const [k, v] of Object.entries(over)) out[k] = isObj(base[k]) && isObj(v) ? merge(base[k], v) : v; + return out; +} + +function get() { + let saved = {}; + try { saved = JSON.parse(db.getSettings()?.alert_theme || '{}'); } catch {} + return merge(DEFAULT, saved); +} + +// clean a theme coming from the editor: only known keys, URLs as strings, numbers in range +function clean(t) { + const url = v => typeof v === 'string' && /^(\/[\w\-./%]*|https:\/\/[^\s"'<>]+)$/.test(v.trim()) ? v.trim() : ''; + const col = (v, d) => /^#[0-9a-f]{6}$/i.test(String(v || '')) ? v : d; + const vol = v => { const n = parseFloat(v); return isNaN(n) ? null : Math.max(0, Math.min(1, n)); }; + const pick = (v, ok, d) => ok.includes(v) ? v : d; + return { + style: pick(t.style, ['card', 'polaroid'], DEFAULT.style), + redeemStyle: pick(t.redeemStyle, ['card', 'cassette'], DEFAULT.redeemStyle), + ttsStyle: pick(t.ttsStyle, ['card', 'letter'], DEFAULT.ttsStyle), + card: { accent: col(t.card?.accent, DEFAULT.card.accent), bg: col(t.card?.bg, DEFAULT.card.bg), text: col(t.card?.text, DEFAULT.card.text) }, + art: Object.fromEntries(EVENTS.map(e => [e, url(t.art?.[e])])), + sounds: Object.fromEntries(Object.keys(DEFAULT.sounds).map(k => [k, url(t.sounds?.[k])])), + volume: vol(t.volume) ?? DEFAULT.volume, + heart: url(t.heart), raidFallback: url(t.raidFallback), defaultSticker: url(t.defaultSticker), + back: (Array.isArray(t.back) ? t.back : []).map(url).filter(Boolean).slice(0, 12), + bitsMin: Math.max(1, parseInt(t.bitsMin, 10) || 1), + bitsTiers: (Array.isArray(t.bitsTiers) ? t.bitsTiers : []).map(x => ({ + min: Math.max(1, parseInt(x.min, 10) || 1), art: url(x.art), sound: url(x.sound), volume: vol(x.volume), + badge: col(x.badge, '#8a8aa8'), hearts: Math.max(0, Math.min(3, parseInt(x.hearts, 10) || 0)), + })).sort((a, b) => b.min - a.min).slice(0, 12), + }; +} + +function save(t) { + const c = clean(t || {}); + db.updateSettings({ alert_theme: JSON.stringify(c) }); + return merge(DEFAULT, c); +} + +// One-time import of the old public/alerts/theme.js (file-based theme, before the theme moved into the database). +// File names there are relative to public/alerts/art and public/alerts/sounds; here they become URLs. +function importLegacyFile() { + const fs = require('fs'), path = require('path'), vm = require('vm'); + const file = path.join(__dirname, '..', 'public', 'alerts', 'theme.js'); + if (!fs.existsSync(file) || (db.getSettings()?.alert_theme || '')) return false; + try { + const box = { window: {} }; + vm.runInNewContext(fs.readFileSync(file, 'utf8'), box, { timeout: 500 }); + const o = box.window.ALERT_THEME || {}; + const art = n => !n ? '' : /^(\/|https:)/.test(n) ? n : `/alerts/art/${n}`; + const snd = n => !n ? '' : /^(\/|https:)/.test(n) ? n : `/alerts/sounds/${n}`; + const a = o.art || {}, s = o.sounds || {}; + save({ + style: 'polaroid', redeemStyle: 'cassette', ttsStyle: 'letter', card: DEFAULT.card, + art: Object.fromEntries(EVENTS.map(e => [e, art(a[e])])), + sounds: Object.fromEntries(Object.keys(DEFAULT.sounds).map(k => [k, snd(s[k])])), + volume: 0.8, heart: art(a.heart), raidFallback: art(a.raidFallback), back: (a.back || []).map(art), + defaultSticker: o.defaultSticker?.path ? `/alerts/${o.defaultSticker.path}` : '', + bitsMin: o.bitsMin || 5, + bitsTiers: (o.bitsTiers || []).map(t => ({ ...t, art: art(t.art), sound: snd(t.sound), volume: t.volume ?? null })), + }); + console.log('[theme] imported public/alerts/theme.js into the database (Actions → Alerts); the file is no longer used'); + return true; + } catch (e) { console.error('[theme] could not import public/alerts/theme.js:', e.message); return false; } +} + +module.exports = { DEFAULT, EVENTS, get, save, clean, merge, importLegacyFile }; diff --git a/src/twitchcsv.js b/src/twitchcsv.js new file mode 100644 index 0000000..b6382d7 --- /dev/null +++ b/src/twitchcsv.js @@ -0,0 +1,97 @@ +// Twitch Creator Dashboard export "Analytics and Revenue by day" (CSV, one row per day, the whole channel), uploaded +// on the Stats page. Twitch keeps this history for years; the API does not offer it. +// Used for the days BEFORE HeyStreamer counted itself (periodstats.js cutoff): streamed days, hours streamed and +// watched, average / peak viewers, follows, chat messages; revenue only on the admin page, never public. +// Importing again is safe: rows are per day, a day in two files keeps the more complete row (an export's last +// day is often still empty). +const db = require('./db'); + +// CSV column -> our column +const COLS = { + 'Average Viewers': 'avg_viewers', 'Follows': 'follows', 'Minutes Streamed': 'minutes_streamed', 'Minutes Watched': 'minutes_watched', + 'Live Views': 'live_views', 'Max Viewers': 'max_viewers', 'Unique Viewers': 'unique_viewers', 'Engaged Viewers': 'engaged_viewers', + 'Chatters': 'chatters', 'Chat Messages': 'chat_messages', 'Clips Created': 'clips_created', 'Clip Views': 'clip_views', + 'Ad Breaks (Minutes)': 'ad_minutes', 'Prime Subs': 'prime_subs', 'Total Paid Subs': 'paid_subs', 'Total Gifted Subs': 'gifted_subs', + 'New Engaged Viewers': 'new_engaged', 'Returning Engaged Viewers': 'returning_engaged', +}; +const REVENUE = ['Sub Revenue', 'Prime Revenue', 'Gifted Subs Revenue', 'Multi-Month Gifted Subs Revenue', 'Bits Revenue', 'Ad Revenue', + 'Turbo Revenue', 'Game Sales Revenue', 'Extensions Revenue', 'Bounties Revenue', 'Other Bits Interactions Revenue']; + +let ready = false; +function init() { + if (ready) return; + db.raw().exec(`CREATE TABLE IF NOT EXISTS tw_daily ( + day TEXT PRIMARY KEY, + ${Object.values(COLS).map(c => `${c} REAL DEFAULT 0`).join(', ')}, + revenue REAL DEFAULT 0, -- sum of all revenue columns (USD) + revenue_json TEXT, -- per type + raw_json TEXT, imported_at TEXT + )`); + ready = true; +} + +// minimal CSV: quoted fields with "" escapes, , separators, \n or \r\n lines +function parseCsv(text) { + const rows = []; + let row = [], f = '', q = false; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (q) { if (c === '"') { if (text[i + 1] === '"') { f += '"'; i++; } else q = false; } else f += c; continue; } + if (c === '"') q = true; + else if (c === ',') { row.push(f); f = ''; } + else if (c === '\n') { row.push(f); rows.push(row); row = []; f = ''; } + else if (c !== '\r') f += c; + } + if (f || row.length) { row.push(f); rows.push(row); } + return rows.filter(r => r.some(x => x !== '')); +} + +const MON = { Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6, Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12 }; +function dayOf(s) { // "Mon Apr 01 2024" (also accepts 2024-04-01) + const m = /([A-Z][a-z]{2}) (\d{1,2}) (\d{4})/.exec(s); + if (m && MON[m[1]]) return `${m[3]}-${String(MON[m[1]]).padStart(2, '0')}-${m[2].padStart(2, '0')}`; + return /^\d{4}-\d{2}-\d{2}/.test(s) ? s.slice(0, 10) : null; +} + +// -> { days, from, to, replaced, kept } +function importCsv(text) { + init(); + const rows = parseCsv(String(text).replace(/^/, '')); + if (rows.length < 2) throw new Error('empty file'); + const head = rows[0].map(h => h.trim()); + if (head[0] !== 'Date' || !head.includes('Minutes Streamed')) throw new Error('not a Twitch "Analytics and Revenue by day" export'); + const d = db.raw(), at = new Date().toISOString(); + const cols = Object.values(COLS); + const up = d.prepare(`INSERT OR REPLACE INTO tw_daily (day, ${cols.join(', ')}, revenue, revenue_json, raw_json, imported_at) + VALUES (@day, ${cols.map(c => '@' + c).join(', ')}, @revenue, @revenue_json, @raw_json, @imported_at)`); + const old = d.prepare('SELECT raw_json FROM tw_daily WHERE day = ?'); + const weight = obj => Object.values(obj).reduce((a, v) => a + (v === '' ? 0 : 1) + (Math.abs(parseFloat(v)) || 0), 0); + let days = 0, kept = 0, from = null, to = null; + d.transaction(() => { + for (const r of rows.slice(1)) { + const raw = Object.fromEntries(head.map((h, i) => [h, (r[i] ?? '').trim()])); + const day = dayOf(raw.Date); + if (!day) continue; + delete raw.Date; + const prev = old.get(day); + if (prev && weight(JSON.parse(prev.raw_json || '{}')) > weight(raw)) { kept++; continue; } // keep the more complete copy + const rec = { day, raw_json: JSON.stringify(raw), imported_at: at }; + for (const [csv, col] of Object.entries(COLS)) rec[col] = parseFloat(raw[csv]) || 0; + const rev = Object.fromEntries(REVENUE.filter(k => raw[k] !== undefined && raw[k] !== '').map(k => [k.replace(/ Revenue$/, ''), parseFloat(raw[k]) || 0])); + rec.revenue = +Object.values(rev).reduce((a, v) => a + v, 0).toFixed(2); + rec.revenue_json = JSON.stringify(rev); + up.run(rec); + days++; + if (!from || day < from) from = day; + if (!to || day > to) to = day; + } + })(); + return { days, kept, from, to }; +} + +function status() { + init(); + return db.raw().prepare('SELECT COUNT(*) days, MIN(day) from_day, MAX(day) to_day, SUM(minutes_streamed > 0) streamed FROM tw_daily').get(); +} + +module.exports = { init, importCsv, status, parseCsv, dayOf }; diff --git a/src/twitchsync.js b/src/twitchsync.js new file mode 100644 index 0000000..9c555c8 --- /dev/null +++ b/src/twitchsync.js @@ -0,0 +1,190 @@ +// What Twitch itself knows, copied into the database for the Stats pages. Runs at start, every 6 hours, after each +// stream, and from the "Sync with Twitch" button on the Stats page. Each part is independent: a missing scope or a +// failed call skips that part (logged once) and keeps the last good copy. +// +// tw_follower every follower with followed_at (Twitch keeps the whole history: follower growth for all time); +// unfollowed_at is set when a sync no longer lists them +// tw_sub current subscribers: tier, gift + gifter (no history on Twitch: past subs only from our events) +// tw_role moderators (moderation:read), VIPs (channel:read:vips); chat badges add founder / artist etc. +// tw_bits all-time bits leaderboard (top 100; includes everything before HeyStreamer) +// tw_emote the channel's own emotes (usage is counted by us in chat: periodstats kind 'emote') +// stream_session past broadcasts from VODs (title, start, length) that HeyStreamer did not see live. +// Twitch keeps VODs 7 days (affiliate) / 60 days (partner): older streams cannot be recovered. +// +// Not available from Twitch at all: past viewer counts, past titles, emote use outside this channel. +const db = require('./db'); +const twitch = require('./twitch'); + +const EVERY_MS = 6 * 60 * 60 * 1000; +let timer = null, ready = false, running = null; +const status = { at: null, parts: {} }; // part -> 'ok (n)' | 'error message' +const warned = new Set(); + +function init() { + if (ready) return; + db.raw().exec(` + CREATE TABLE IF NOT EXISTS tw_follower (user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, followed_at TEXT, seen_at TEXT, unfollowed_at TEXT); + CREATE INDEX IF NOT EXISTS tw_follower_at ON tw_follower(followed_at); + CREATE TABLE IF NOT EXISTS tw_sub (user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, tier TEXT, is_gift INTEGER, gifter_login TEXT, gifter_name TEXT, seen_at TEXT); + CREATE TABLE IF NOT EXISTS tw_role (user_id TEXT NOT NULL, role TEXT NOT NULL, user_login TEXT, user_name TEXT, seen_at TEXT, PRIMARY KEY (user_id, role)); + CREATE TABLE IF NOT EXISTS tw_bits (user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, score INTEGER, rank INTEGER, seen_at TEXT); + CREATE TABLE IF NOT EXISTS tw_emote (id TEXT PRIMARY KEY, name TEXT, tier TEXT, emote_type TEXT, set_id TEXT, image TEXT, seen_at TEXT, gone INTEGER DEFAULT 0); + CREATE TABLE IF NOT EXISTS tw_meta (key TEXT PRIMARY KEY, value TEXT); + `); + const cols = db.raw().prepare('PRAGMA table_info(stream_session)').all().map(c => c.name); + if (cols.length && !cols.includes('source')) db.raw().exec("ALTER TABLE stream_session ADD COLUMN source TEXT DEFAULT 'live'"); // live | vod + ready = true; +} + +function start() { + init(); + clearInterval(timer); + timer = setInterval(() => sync().catch(() => {}), EVERY_MS); + timer.unref?.(); + setTimeout(() => sync().catch(() => {}), 20 * 1000).unref?.(); // after EventSub has validated the token +} + +// all pages of a Helix list +async function pages(path, max = 200) { + const out = []; + let after = ''; + for (let i = 0; i < max; i++) { + const r = await twitch.helix(path + (after ? `&after=${encodeURIComponent(after)}` : '')); + if (r.status === 401 || r.status === 403) { const e = new Error(`no permission (${r.status}): log in again on the dashboard`); e.scope = true; throw e; } + if (!r.ok) throw new Error(`HTTP ${r.status}`); + const j = await r.json(); + out.push(...(j.data || [])); + after = j.pagination?.cursor; + if (!after || !(j.data || []).length) break; + } + return out; +} + +const now = () => new Date().toISOString(); + +const PARTS = { + async followers(b) { + const list = await pages(`/channels/followers?broadcaster_id=${b}&first=100`); + const at = now(), d = db.raw(); + d.transaction(() => { + const up = d.prepare(`INSERT INTO tw_follower (user_id, user_login, user_name, followed_at, seen_at, unfollowed_at) VALUES (?, ?, ?, ?, ?, NULL) + ON CONFLICT(user_id) DO UPDATE SET user_login = excluded.user_login, user_name = excluded.user_name, + followed_at = excluded.followed_at, seen_at = excluded.seen_at, unfollowed_at = NULL`); + for (const f of list) up.run(f.user_id, f.user_login, f.user_name, f.followed_at, at); + d.prepare('UPDATE tw_follower SET unfollowed_at = ? WHERE seen_at < ? AND unfollowed_at IS NULL').run(at, at); + })(); + return list.length; + }, + async subs(b) { + const list = await pages(`/subscriptions?broadcaster_id=${b}&first=100`); + const at = now(), d = db.raw(); + d.transaction(() => { + d.prepare('DELETE FROM tw_sub').run(); + const ins = d.prepare('INSERT OR REPLACE INTO tw_sub (user_id, user_login, user_name, tier, is_gift, gifter_login, gifter_name, seen_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'); + for (const s of list) ins.run(s.user_id, s.user_login, s.user_name, s.tier, s.is_gift ? 1 : 0, s.gifter_login || null, s.gifter_name || null, at); + })(); + return list.length; + }, + async mods(b) { return roles(b, 'moderator', `/moderation/moderators?broadcaster_id=${b}&first=100`); }, + async vips(b) { return roles(b, 'vip', `/channels/vips?broadcaster_id=${b}&first=100`); }, + async bits() { + const r = await twitch.helix('/bits/leaderboard?count=100&period=all'); + if (r.status === 401 || r.status === 403) { const e = new Error(`no permission (${r.status})`); e.scope = true; throw e; } + if (!r.ok) throw new Error(`HTTP ${r.status}`); + const list = (await r.json()).data || []; + const at = now(), d = db.raw(); + d.transaction(() => { + d.prepare('DELETE FROM tw_bits').run(); + const ins = d.prepare('INSERT INTO tw_bits (user_id, user_login, user_name, score, rank, seen_at) VALUES (?, ?, ?, ?, ?, ?)'); + for (const x of list) ins.run(x.user_id, x.user_login, x.user_name, x.score, x.rank, at); + })(); + return list.length; + }, + async emotes(b) { + const r = await twitch.helix(`/chat/emotes?broadcaster_id=${b}`); + if (!r.ok) throw new Error(`HTTP ${r.status}`); + const list = (await r.json()).data || []; + const at = now(), d = db.raw(); + d.transaction(() => { + const up = d.prepare(`INSERT INTO tw_emote (id, name, tier, emote_type, set_id, image, seen_at, gone) VALUES (?, ?, ?, ?, ?, ?, ?, 0) + ON CONFLICT(id) DO UPDATE SET name = excluded.name, tier = excluded.tier, emote_type = excluded.emote_type, + set_id = excluded.set_id, image = excluded.image, seen_at = excluded.seen_at, gone = 0`); + for (const e of list) up.run(e.id, e.name, e.tier || null, e.emote_type || null, e.emote_set_id || null, e.images?.url_2x || e.images?.url_1x || null, at); + d.prepare('UPDATE tw_emote SET gone = 1 WHERE seen_at < ?').run(at); // removed from the channel: kept for history + })(); + return list.length; + }, + async vods(b) { + const list = await pages(`/videos?user_id=${b}&type=archive&first=100`, 5); + const d = db.raw(); + let added = 0; + const secs = s => { const m = /(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/.exec(s || '') || []; return (+m[1] || 0) * 3600 + (+m[2] || 0) * 60 + (+m[3] || 0); }; + d.transaction(() => { + for (const v of list) { + if (!v.stream_id) continue; + const start = v.created_at, end = new Date(Date.parse(v.created_at) + secs(v.duration) * 1000).toISOString(); + const known = d.prepare('SELECT id FROM stream_session WHERE id = ?').get(String(v.stream_id)); + if (known) { d.prepare('UPDATE stream_session SET title = COALESCE(title, ?) WHERE id = ?').run(v.title || null, String(v.stream_id)); continue; } + d.prepare("INSERT INTO stream_session (id, started_at, ended_at, ticks, title, source) VALUES (?, ?, ?, 0, ?, 'vod')").run(String(v.stream_id), start, end, v.title || null); + added++; + } + })(); + return `${list.length} VODs, ${added} new`; + }, +}; + +async function roles(b, role, path) { + const list = await pages(path); + const at = now(), d = db.raw(); + d.transaction(() => { + d.prepare('DELETE FROM tw_role WHERE role = ?').run(role); + const ins = d.prepare('INSERT OR REPLACE INTO tw_role (user_id, role, user_login, user_name, seen_at) VALUES (?, ?, ?, ?, ?)'); + for (const x of list) ins.run(x.user_id, role, x.user_login, x.user_name, at); + })(); + return list.length; +} + +// only = list of part names (default: all) +function sync(only) { + if (running) return running; + init(); + const u = twitch.getUser(); + if (!u) return Promise.resolve(status); + require('./watchtime').init(); + running = (async () => { + for (const [name, fn] of Object.entries(PARTS)) { + if (only && !only.includes(name)) continue; + try { status.parts[name] = `ok (${await fn(u.twitch_id)})`; warned.delete(name); } + catch (e) { + status.parts[name] = e.message; + if (!warned.has(name)) { warned.add(name); console.warn(`[twitchsync] ${name}: ${e.message}`); } + } + } + status.at = now(); + db.raw().prepare("INSERT OR REPLACE INTO tw_meta (key, value) VALUES ('last_sync', ?)").run(JSON.stringify(status)); + console.log('[twitchsync] done:', Object.entries(status.parts).map(([k, v]) => `${k} ${v}`).join(', ')); + return status; + })().finally(() => { running = null; }); + return running; +} + +function lastStatus() { + init(); + if (status.at) return status; + try { return JSON.parse(db.raw().prepare("SELECT value FROM tw_meta WHERE key = 'last_sync'").get()?.value || 'null') || status; } catch { return status; } +} + +// one viewer, from the synced tables (the viewer page) +function viewer(userId, login) { + init(); + const d = db.raw(), id = String(userId || ''), lg = String(login || '').toLowerCase(); + const by = t => d.prepare(`SELECT * FROM ${t} WHERE user_id = ? OR lower(user_login) = ?`).get(id, lg) || null; + return { + follower: by('tw_follower'), + sub: by('tw_sub'), + roles: d.prepare('SELECT role FROM tw_role WHERE user_id = ? OR lower(user_login) = ?').all(id, lg).map(r => r.role), + bits: by('tw_bits'), + }; +} + +module.exports = { init, start, sync, lastStatus, viewer }; diff --git a/src/watchtime.js b/src/watchtime.js index 99939cd..d73d701 100644 --- a/src/watchtime.js +++ b/src/watchtime.js @@ -6,7 +6,13 @@ // 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) +// stream_session also keeps the stream's title, game, peak + average viewer count (Helix /streams, every tick) +// stream_viewers viewer count every 5 minutes while live (the viewer graph of a stream) +// stream_change every title / category change, live or not (EventSub channel.update + the /streams check) +// watch_import StreamElements watch time from before our own tracking (imported once before HeyStreamer counted; the +// importer is gone, the minutes stay as a fixed baseline for watch time, points and levels) // +// Every tick also goes to periodstats.js (per day + per stream). // 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). @@ -30,10 +36,40 @@ function init() { 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) ); + CREATE TABLE IF NOT EXISTS stream_viewers (stream_id TEXT NOT NULL, at TEXT NOT NULL, viewers INTEGER, PRIMARY KEY (stream_id, at)); + CREATE TABLE IF NOT EXISTS stream_change ( -- every title / category change (channel.update + the /streams check) + id INTEGER PRIMARY KEY AUTOINCREMENT, stream_id TEXT DEFAULT '', at TEXT NOT NULL, title TEXT, game TEXT + ); + CREATE INDEX IF NOT EXISTS stream_change_stream ON stream_change(stream_id); + CREATE TABLE IF NOT EXISTS watch_import ( + user_login TEXT PRIMARY KEY, minutes INTEGER NOT NULL, source TEXT, imported_at TEXT + ); `); + const cols = db.raw().prepare('PRAGMA table_info(stream_session)').all().map(c => c.name); + for (const [c, def] of [['title', 'TEXT'], ['game', 'TEXT'], ['peak_viewers', 'INTEGER'], ['viewer_sum', 'INTEGER DEFAULT 0'], ['viewer_samples', 'INTEGER DEFAULT 0']]) { + if (!cols.includes(c)) db.raw().exec(`ALTER TABLE stream_session ADD COLUMN ${c} ${def}`); + } ready = true; } +// title, game and viewer count of the running stream (Helix /streams); count = also sample the viewer count +async function refreshStream(count) { + if (!live) return; + 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 || !live || String(s.id) !== live.id) return; + channelUpdate(s.title, s.game_name); + if (count) db.raw().prepare('INSERT OR IGNORE INTO stream_viewers (stream_id, at, viewers) VALUES (?, ?, ?)').run(live.id, new Date().toISOString(), s.viewer_count || 0); + db.raw().prepare(`UPDATE stream_session SET title = ?, game = ?, peak_viewers = MAX(COALESCE(peak_viewers, 0), ?), + viewer_sum = viewer_sum + ?, viewer_samples = viewer_samples + ? WHERE id = ?`) + .run(s.title || null, s.game_name || null, s.viewer_count || 0, count ? s.viewer_count || 0 : 0, count ? 1 : 0, live.id); + } catch (e) { console.warn('[watchtime] stream info:', e.message); } +} + function startTicking() { clearInterval(timer); timer = setInterval(() => tick().catch(e => console.warn('[watchtime] tick:', e.message)), TICK_MS); @@ -47,6 +83,7 @@ function online(id, startedAt) { 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(); + setTimeout(() => refreshStream(false), 60 * 1000).unref?.(); // /streams lists a new stream with a short delay } function offline() { @@ -56,6 +93,7 @@ function offline() { console.log(`[watchtime] offline (stream ${live.id})`); live = null; clearInterval(timer); timer = null; + setTimeout(() => require('./twitchsync').sync().catch(() => {}), 2 * 60 * 1000).unref?.(); // new followers / subs / the VOD } // server (re)started: are we live right now? @@ -105,7 +143,9 @@ async function tick() { 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); + require('./periodstats').add(list.map(c => ({ key: c.user_id, login: c.user_login, name: c.user_name, kind: 'watch' })), at, live.id); })(); + refreshStream(true); console.log(`[watchtime] tick: ${list.length} watching`); } @@ -122,6 +162,43 @@ function forgetUser(userId) { 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; +// title / category changed (EventSub channel.update, or noticed by refreshStream): one row per real change +function channelUpdate(title, game) { + init(); + const sid = live?.id || ''; + const last = db.raw().prepare('SELECT title, game FROM stream_change ORDER BY id DESC LIMIT 1').get(); + if (last && last.title === (title || null) && last.game === (game || null)) return false; + db.raw().prepare('INSERT INTO stream_change (stream_id, at, title, game) VALUES (?, ?, ?, ?)').run(sid, new Date().toISOString(), title || null, game || null); + if (sid) db.raw().prepare('UPDATE stream_session SET title = ?, game = ? WHERE id = ?').run(title || null, game || null, sid); + console.log(`[watchtime] title/category: ${title} · ${game}`); + return true; +} -module.exports = { init, online, offline, checkLive, tick, checkin, forgetUser, isLive, TICK_MS }; +const isLive = () => !!live; +const currentStreamId = () => live?.id || null; + +// StreamElements baseline: minutes of a viewer by login (0 when none) +function baselineMinutes(login) { + init(); + return db.raw().prepare('SELECT minutes FROM watch_import WHERE user_login = ?').get(String(login || '').toLowerCase())?.minutes || 0; +} + +// a viewer known only from the StreamElements baseline renamed on Twitch: move their minutes to the new login +function renameBaseline(fromLogin, toLogin) { + init(); + const clean = v => String(v || '').trim().replace(/^@/, '').toLowerCase(); + const from = clean(fromLogin), to = clean(toLogin); + if (!/^\w{2,25}$/.test(from) || !/^\w{2,25}$/.test(to) || from === to) throw new Error('invalid name'); + const d = db.raw(); + d.transaction(() => { + const old = d.prepare('SELECT minutes, source, imported_at FROM watch_import WHERE user_login = ?').get(from); + if (!old) return; + 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(`[watchtime] StreamElements baseline: renamed ${from} -> ${to}`); + return to; +} + +module.exports = { init, online, offline, checkLive, tick, checkin, forgetUser, isLive, currentStreamId, channelUpdate, baselineMinutes, renameBaseline, TICK_MS }; diff --git a/tools/preview/export.js b/tools/preview/export.js new file mode 100644 index 0000000..6395667 --- /dev/null +++ b/tools/preview/export.js @@ -0,0 +1,19 @@ +// Static copy of the alert preview (views/alerts_preview.ejs) with the default looks, for viewing without a server: +// node tools/preview/export.js +// Writes /index.html plus the overlay code under /alerts/. No channel data: defaults only. +const fs = require('fs'), path = require('path'), ejs = require('ejs'); +const root = path.join(__dirname, '..', '..'); +const out = path.resolve(process.argv[2] || 'alert-preview'); +const theme = require(path.join(root, 'src', 'theme.js')); // DEFAULT only (no database needed) +const SAMPLES = require(path.join(root, 'src', 'alerts.js')).SAMPLES; +const themes = { + defaults: { label: 'Defaults (Card)', theme: theme.DEFAULT }, + optional: { label: 'Polaroid / Cassette / Letter', theme: theme.merge(theme.DEFAULT, { style: 'polaroid', redeemStyle: 'cassette', ttsStyle: 'letter' }) }, +}; +fs.mkdirSync(path.join(out, 'alerts', 'art'), { recursive: true }); +for (const f of ['card', 'polaroid', 'cassette', 'fx']) for (const ext of ['js', 'css']) + fs.copyFileSync(path.join(root, 'public', 'alerts', `${f}.${ext}`), path.join(out, 'alerts', `${f}.${ext}`)); +fs.copyFileSync(path.join(root, 'public', 'alerts', 'art', 'placeholder.svg'), path.join(out, 'alerts', 'art', 'placeholder.svg')); +const html = ejs.render(fs.readFileSync(path.join(root, 'views', 'alerts_preview.ejs'), 'utf8'), { base: 'alerts/', themes, start: 'defaults', samples: SAMPLES }); +fs.writeFileSync(path.join(out, 'index.html'), html); +console.log(`alert preview written to ${out}/index.html`); diff --git a/views/_statsbody.ejs b/views/_statsbody.ejs new file mode 100644 index 0000000..fa229eb --- /dev/null +++ b/views/_statsbody.ejs @@ -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 => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[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 ? ` ⓘ` : ''; + const person = x => { const n = esc(x.name || x.login || '?'); return viewerHref && x.login ? `${n}` : n; }; + const since = TW && TW.streamedDays ? TW.cutoff : null; // period reaches back before HeyStreamer counted +%> + + + + +
+
+ <% for (const [p, label] of [['stream', 'Stream'], ['week', 'Week'], ['month', 'Month'], ['year', 'Year'], ['all', 'All time']]) { %> + <%= label %> + <% } %> +
+
+ <% if (r.p !== 'all') { %> + <% if (r.prev) { %>‹<% } else { %>‹<% } %> + <% } %> + <%= r.label %><% if (r.sub) { %> · <%= r.sub %><% } %> + <% if (r.p !== 'all') { %> + <% if (r.next) { %>›<% } else { %>›<% } %> + <% } %> +
+
+ +<% + // ---- 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') { %> +
+ <% for (const [val, k, tip] of tiles) { %>
<%= val %>
<%= k %><%- info(tip) %>
<% } %> +
+<% } %> + +<% if (v === 'streams') { %> + <%# ===================== STREAMS ===================== %> + <% if (r.p === 'stream' && s.streams[0]) { const x = s.streams[0]; %> +

+ <%= 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) { %> · live now<% } %> + <% if (x.source === 'vod') { %> · from the VOD (HeyStreamer was not counting)<% } %> +

+ <% + // 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 = ``; + for (const g of [0, top / 2, top]) svg += `${g}`; + for (let h = 0; h <= (t1 - t0) / 36e5; h++) { const tt = new Date(t0 + h * 36e5).toISOString(); svg += `${time(tt)}`; } + if (tl.samples.length) { + const pts = tl.samples.map(p => `${X(p.at).toFixed(1)},${Y(p.viewers).toFixed(1)}`); + svg += ``; + svg += ``; + for (const p of tl.samples) svg += ``; + } + for (const c of tl.changes) { + if (c.start) continue; + const x = X(c.at).toFixed(1); + svg += ``; + } + %> +

Viewers

+
<%- svg %>
+ <% if (!tl.samples.length) { %>

No viewer counts were recorded for this stream.

<% } %> + <% if (tl.changes.length) { %> +
    + <% for (const c of tl.changes) { %>
  1. <%= c.start ? 'start' : time(c.at) %> <%= c.title || '—' %><% if (c.game) { %> <%= c.game %><% } %>
  2. <% } %> +
+ <% } %> + <% } %> + <% } %> + + <% + // 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) { %> +

Activity per <%= s.series.unit %>

+
+
<% shown.forEach(([k, label], i) => { %><% }) %>
+
+
+ + <% } %> + + <% + // 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) { %> +

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.') %>

+ <% if (!totalMin) { %>

no categories recorded in this period yet

<% } else { %> +
+ + <% 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`; %> + <%= g.game %> · <%= hm(g.minutes) %> + <% }) %> + +
    + <% slices.forEach((g, i) => { %> +
  • <%= g.game %> + <%= hm(g.minutes) %> · <%= Math.round(g.minutes / totalMin * 100) %>%
  • + <% }) %> +
+
+ <% } %> + <% } %> + + <% if (r.p !== 'stream' && s.streams.length) { %> +

<%= r.p === 'all' ? 'Recent streams' : 'Streams' %>

+
+ + + <% for (const x of s.streams.slice(0, r.p === 'all' ? 15 : 100)) { %> + + + + + + + <% } %> + +
DateTitle · gamesLengthPeakViewersChattersMessages
<%= day(x.started_at) %><%= x.live ? ' · live' : '' %><% if (x.source === 'vod') { %> VOD<% } %><%= x.title || '—' %><% if (x.games.length) { %><%= x.games.join(' · ') %><% } %><%= hm(x.minutes) %><%= x.peak != null ? num(x.peak) : '—' %><%= num(x.viewers) %><%= num(x.chatters) %><%= num(x.messages) %>
+ <% } %> + +<% } else { %> + <%# ===================== COMMUNITY ===================== %> + <% const cm = s.community || {}; %> + <% if ((cm.supporters || []).length) { %> +

Thank you for the support

+
+ <% 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(' · '); %> + <%- person(x) %> <%= what %> + <% } %> +
+ <% } %> + + <% if ((cm.raiders || []).length) { %> +

Raids

+
<% for (const x of cm.raiders) { %><%- person(x) %> <%= x.raids > 1 ? `${x.raids} raids · ` : '' %><%= num(x.viewers) %> viewers<% } %>
+ <% } %> + + <% + const board = b => { + const nw = b.nw ? ` style="--nw:${b.nw}"` : ''; + let out = `

${esc(b.title)}

`; + if (!b.rows.length) return out + '

nothing yet

'; + out += '
    '; + b.rows.forEach((x, i) => { + out += `
  1. ${i + 1}${person(x)}${b.level ? `${esc(b.level(x))}` : ''}${(b.fmt || num)(x.n)}
  2. `; + }); + return out + '
'; + }; + 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)); + %> +

Leaderboards

+
<% for (const b of boards) { %><%- board(b) %><% } %>
+ + <% if ((locals.ranks || []).length) { + const LV = ['Veteran', 'Loyal', 'Regular']; %> +

Community ranks<%- info('Levels by total watch time: Regular from 50 h, Loyal from 200 h, Veteran from 1000 h. All time.') %>

+
+ <% for (const lv of LV) { const list = ranks.filter(x => x.level === lv); if (!list.length) continue; %> +

<%= lv %> <%= list.length %>

+
<% for (const x of list) { %><%- person(x) %><% } %>
+ <% } %> +
+ <% } %> + + <% if (s.channelEmotes && s.channelEmotes.length) { %> +

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.') %>

+
+ <% for (const e of s.channelEmotes) { %> + <% if (e.image) { %><% } %><%= e.name %> <%= num(e.uses) %> + <% } %> +
+ <% } %> + +

Top emotes

+ <% if (!s.emotes.length) { %>

nothing yet

<% } else { %> +
+ <% for (const e of s.emotes) { const src = emoteSrc(e); %> + <% if (src) { %><% } %><%= e.emote %> <%= num(e.uses) %> + <% } %> +
+ <% } %> + + <% if (s.commands.length) { %> +

Top commands

+
<% for (const c of s.commands) { %><%= c.command %> <%= num(c.uses) %><% } %>
+ <% } %> + + <% if (s.rewards.length) { %> +

Rewards and Power-ups

+
<% for (const x of s.rewards) { %><%= x.item %> <%= num(x.uses) %><% } %>
+ <% } %> +<% } %> + + diff --git a/views/actions.ejs b/views/actions.ejs deleted file mode 100644 index 9a39b77..0000000 --- a/views/actions.ejs +++ /dev/null @@ -1,88 +0,0 @@ -

Actions

-

Map Twitch events to sounds, videos, or on-screen alerts.

- -
- Add new action -
-
- - - - - - - -
- -
-
- -<% if (actions.length === 0) { %> -

No actions yet.

-<% } else { %> -
- - - - - - - - - - - - - - <% for (const a of actions) { %> - - - - - - - - - - <% } %> - -
NameEventDetailActionCooldownStatus
<%= a.name %><%= a.event_type %><%= a.event_detail || '—' %><%= a.action_type %><%= a.cooldown_seconds %>s - - <%= a.enabled ? 'on' : 'off' %> - - -
-
-
-
-
-<% } %> diff --git a/views/alerts_preview.ejs b/views/alerts_preview.ejs new file mode 100644 index 0000000..abd0dd7 --- /dev/null +++ b/views/alerts_preview.ejs @@ -0,0 +1,133 @@ + +<%# + Alert preview: the real overlay code on a 1920x1080 stage, with a button for every alert. Served at + /actions/alerts/preview (logged in) and exported as a static page by tools/export-preview.js. + Locals: base ('/alerts/' or 'alerts/'), themes { key: { label, theme } }, start (theme key), samples (src/alerts.js SAMPLES). +%> + + +Alert preview + +<% for (const f of ['card', 'polaroid', 'cassette', 'fx']) { %><% } %> + +
+
camera
+
+

Alert preview

+

The real overlay code. Click a button to play an alert; a click replaces the one showing. Click anywhere once first so the browser allows sound.

+ +

Look

+
<% for (const [k, t] of Object.entries(themes)) { %><% } %>
+
+ +
+
+ +
+ +

Background

+
+ +

Follows and subs

+
<% for (const [k, l] of [['follow', 'Follow'], ['sub-new', 'New sub'], ['sub-prime', 'Prime'], ['sub-resub', 'Resub 14 months'], ['sub-6', '6 months at once'], ['gift-1', 'Gift 1'], ['gift-10', 'Gift 10'], ['gift-anon', 'Anonymous gift']]) { %><% } %>
+

Bits, tips, raids

+
<% for (const [k, l] of [['bits-20', '20 bits'], ['bits-120', '120 bits'], ['bits-500', '500 bits'], ['tip-5', 'Tip 5'], ['tip-100', 'Tip 100'], ['raid', 'Raid'], ['streak', 'Watch streak']]) { %><% } %>
+

Hype Train

+
<% for (const [k, l] of [['hype-begin', 'Start'], ['hype-level', 'Level up'], ['hype-end', 'End'], ['hype-golden', 'Golden Kappa']]) { %><% } %>
+

Redeems

+
+ + +
+

Queue

+
+
ready
+
+
+ + +<% for (const f of ['card', 'cassette', 'fx', 'polaroid']) { %><% } %> + + diff --git a/views/alerts_setup.ejs b/views/alerts_setup.ejs new file mode 100644 index 0000000..8342410 --- /dev/null +++ b/views/alerts_setup.ejs @@ -0,0 +1,233 @@ +<% const J = x => JSON.stringify(x).replace(/ + + +

Alerts

+

Open the preview ↗What follows, subs, gifts, raids, bits, tips and the Hype Train look and sound like. Pictures and sounds come from + Media (upload your own there). Changes reach OBS as soon as you save; use Test to see them.

+ +
+

Style

+
+
AlertsFollows, subs, gifts, raids, bits, tips, Hype Train.
+ <% for (const [v, l] of [['card', 'Card'], ['polaroid', 'Polaroid']]) { %><% } %> +
+
+
New redeem variationsLook of variations you add on Redeems (each variation can still be changed there).
+ <% for (const [v, l] of [['card', 'Card'], ['cassette', 'Cassette']]) { %><% } %> +
+
+
Read-aloud redeemsVariations with a TTS voice.
+ <% for (const [v, l] of [['card', 'Card'], ['letter', 'Letter']]) { %><% } %> +
+
+
Card colours
+
+ + + +
+
+
+
VolumeAlert sounds (a bits tier can have its own).
+
+
+
+ +
+

Events

+
+ EventPictureSound +
+
+ +
+

Bits

+
+
No alert under
+
bits
+
+
+
TiersThe highest tier the cheer reaches is used.
+
+
FromPictureSoundVolumeBadgeHearts
+
+
+
+
+
+ +
+

Extras

+
+
Corner stickerPolaroid: sticker on the photo's corner (and the extra ones for big alerts).
+
+
+
+
Photos behindPolaroid: photos fanned out behind multi-month subs, gift bombs and raids.
+
+
+
+
Raid send-off pictureWhen the raided channel has no picture.
+
+
+
+
Default redeem stickerCard and Cassette redeems whose variation has no picture.
+
+
+
+ +
+ + No changes +
+ + diff --git a/views/dashboard.ejs b/views/dashboard.ejs index adeb961..17894a6 100644 --- a/views/dashboard.ejs +++ b/views/dashboard.ejs @@ -1,22 +1,20 @@

Dashboard

-
-
- Channel: - <%= settings.channel || 'not set' %> -
-
- OBS browser sources (1920×1080):
- Chat only, set its audio to Monitor Only (mute output) so chat sounds stay off stream:
- <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat
- Everything except chat (alerts, redeems, poll, Hype Train bar, raid send-off):
- <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=nochat
- Chat somewhere else, e.g. in the Intermission panel (left,top,width,height in px of the 1920×1080 page; up = newest at the bottom):
- <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat&chat=130,640,700,360&chatflow=up
- - Other combinations: hover for help · everything in one source: /overlay/<%= settings.overlay_id %> -
+ +
diff --git a/views/layout.ejs b/views/layout.ejs index 32dbdc7..1788a0e 100644 --- a/views/layout.ejs +++ b/views/layout.ejs @@ -14,6 +14,45 @@ .badge-green { background: #1a7a1a; color: #a8f0a8; } .badge-red { background: #7a1a1a; color: #f0a8a8; } .badge-grey { background: #333; color: #aaa; } + nav ul li a.on { color: var(--pico-color); font-weight: 700; } + /* left sidebar of Actions / Settings */ + main.with-side { max-width: 1400px; margin: 0 auto; } + .shell { display: grid; grid-template-columns: 210px minmax(0, 1fr); gap: 2rem; align-items: start; } + .side { position: sticky; top: 1rem; display: flex; flex-direction: column; gap: .15rem; } + .side-title { font-size: .75rem; text-transform: uppercase; letter-spacing: .08em; color: var(--pico-muted-color); margin: 0 0 .4rem .75rem; } + .side a { display: block; padding: .45rem .75rem; border-radius: 8px; text-decoration: none; color: var(--pico-muted-color); font-size: .95rem; } + .side a:hover { background: var(--pico-card-background-color); color: var(--pico-color); } + .side a.on { background: var(--pico-primary-background); color: #fff; font-weight: 600; } + @media (max-width: 800px) { + .shell { grid-template-columns: 1fr; gap: 1rem; } + .side { position: static; flex-direction: row; flex-wrap: wrap; } + .side-title { display: none; } + } + /* settings pages: one card per group, label left, control right */ + .set-h { margin: 0 0 .3rem; } + .set-intro { color: var(--pico-muted-color); margin: 0 0 1.2rem; } + .set-card { border: 1px solid var(--pico-muted-border-color); border-radius: 12px; padding: 1rem 1.2rem; margin-bottom: 1.2rem; } + .set-card > h3 { font-size: 1.05rem; margin: 0 0 .8rem; } + .set-row { display: grid; grid-template-columns: minmax(180px, 280px) minmax(0, 1fr); gap: .4rem 1.4rem; align-items: start; padding: .7rem 0; border-top: 1px solid var(--pico-muted-border-color); } + .set-card > h3 + .set-row, .set-card > .set-row:first-child { border-top: 0; padding-top: 0; } + .set-row > .lbl { font-weight: 600; font-size: .92rem; } + .set-row > .lbl small { display: block; font-weight: 400; color: var(--pico-muted-color); font-size: .8rem; margin-top: .15rem; } + .set-row input:not([type=checkbox]):not([type=radio]), .set-row select, .set-row textarea { margin: 0; } + .set-row label { margin: 0; } + @media (max-width: 700px) { .set-row { grid-template-columns: 1fr; } } + .set-inline { display: flex; gap: .6rem; flex-wrap: wrap; align-items: center; } + .set-inline > * { margin: 0 !important; } + .btn-auto { width: auto !important; } + .savebar-set { position: sticky; bottom: 0; display: flex; gap: .8rem; align-items: center; padding: .7rem 0; background: var(--pico-background-color); border-top: 1px solid var(--pico-muted-border-color); margin-top: .5rem; z-index: 5; } + .savebar-set button { width: auto; margin: 0; } + .flash { padding: .5rem .8rem; border-radius: 8px; margin: 0 0 1rem; background: rgba(63,185,80,.15); border: 1px solid rgba(63,185,80,.5); } + .flash.err { background: rgba(248,136,136,.12); border-color: #f88; } + .copy { display: flex; gap: .4rem; align-items: center; } + .copy code { flex: 1; overflow-x: auto; white-space: nowrap; padding: .35rem .55rem; } + .copy button { width: auto; margin: 0; padding: .25rem .7rem; font-size: .8rem; } + /* sensitive values (OBS links, HUDFX link, tokens): blurred until the eye is clicked; Copy still copies them */ + .secret:not(.shown) { filter: blur(6px); user-select: none; pointer-events: none; } + .eye { width: auto !important; margin: 0 !important; padding: .25rem .55rem !important; font-size: .9rem !important; line-height: 1; } @@ -22,28 +61,56 @@
  • HeyStreamer
  • -
    - <%- body %> +
    + <% if (locals.sidebar) { %> +
    + +
    <%- body %>
    +
    + <% } else { %> + <%- body %> + <% } %>
    <% if (has('chat')) { %><% } %> <% if (has('alerts')) { %> + diff --git a/views/public_stats.ejs b/views/public_stats.ejs new file mode 100644 index 0000000..2b7745d --- /dev/null +++ b/views/public_stats.ejs @@ -0,0 +1,72 @@ + + + + + + <%= displayName %> · Stream stats + + <%# viewer names are listed: keep the page out of search engines (remove this line to allow indexing) %> + + + + + + + +
    + <% if (preview) { %>
    Preview: the public page is off (Settings → Public stats page). Only you can see this.
    <% } %> +
    +

    <%= displayName %>'s stream stats

    + the people who make the streams fun ♡ + <% if (live) { %> + live now + <% } else if (channel) { %> + twitch.tv/<%= channel %> ↗ + <% } %> +
    + + <%- include('_statsbody', { s, q, base: base || '/', viewerHref: null, mode: 'public', view, ranks, tz }) %> + +
    + Chat activity and watch time are counted for these statistics; message text is never shown here. + Don't want your name on this page? Type !hideme in chat (you still count in the totals, unnamed); + !showme brings it back. To have your data deleted completely, ask in chat or whisper the streamer. + Days are UTC; numbers update every few minutes. +
    +
    + + diff --git a/views/redeems.ejs b/views/redeems.ejs index be88ffd..012931d 100644 --- a/views/redeems.ejs +++ b/views/redeems.ejs @@ -71,6 +71,7 @@ .pick ul.opts li.none { color:var(--pico-muted-color); cursor:default; } [data-show] { display:none !important; } .vcard[data-display="cassette"] [data-show~="cassette"], + .vcard[data-display="card"] [data-show~="cassette"], .vcard[data-display="sound"] [data-show~="sound"], .vcard[data-display="video"] [data-show~="video"] { display:flex !important; } @@ -114,7 +115,7 @@ <% for (const v of t.variations) { - const display = v.video ? 'video' : v.polaroid ? 'cassette' : 'sound'; %> + const display = v.video ? 'video' : !v.polaroid ? 'sound' : v.look === 'card' ? 'card' : 'cassette'; %>
    title="On: this variation can play"> @@ -129,8 +130,8 @@
    - - <% for (const [val, lbl] of [['cassette', 'Cassette'], ['sound', 'Sound only'], ['video', 'Video']]) { %> + + <% for (const [val, lbl] of [['card', 'Card'], ['cassette', 'Cassette'], ['sound', 'Sound only'], ['video', 'Video']]) { %> <% } %> @@ -147,7 +148,7 @@
    - + @@ -184,7 +185,8 @@ tts_voice_id: <%- JSON.stringify(ttsVoices.map(t => ({ url: String(t.id), label: t.name }))) %>, }; const ADD = { sound: '+ sound', video: '+ video', art: '+ sticker', tts_voice_id: '+ TTS voice' }; - const DEFAULT_STICKER = { url: '', label: 'headset Streamer (default)', img: '/alerts/stickers/default-sticker.png' }; + const THEME_STICKER = <%- JSON.stringify(theme.defaultSticker || '') %>; // Actions → Alerts → Default redeem sticker + const DEFAULT_STICKER = { url: '', label: 'default picture', img: THEME_STICKER || '/alerts/art/placeholder.svg' }; const DRAFT_KEY = 'redeemsDraft', OPEN_KEY = 'redeemsOpen'; const stateEl = document.getElementById('save-state'); const dirty = new Set(); @@ -224,7 +226,7 @@ c.dataset.display = o.display; c.classList.toggle('off', !o.enabled); c.querySelector('[data-vol]').textContent = Math.round(o.volume * 100) + '%'; - const ttsOn = !!o.tts_voice_id && o.display === 'cassette'; + const ttsOn = !!o.tts_voice_id && (o.display === 'cassette' || o.display === 'card'); c.querySelector('[data-pick="sound"]').classList.toggle('disabled', ttsOn); c.querySelectorAll('[data-pick]').forEach(renderPick); chances(c.closest('[data-trigger]')); diff --git a/views/settings.ejs b/views/settings.ejs deleted file mode 100644 index 47abb87..0000000 --- a/views/settings.ejs +++ /dev/null @@ -1,112 +0,0 @@ -

    Settings

    - -
    -
    Overlay URL
    -

    Add this as a Browser Source in OBS (1920×1080, transparent background):

    - <%= baseUrl %>/overlay/<%= settings.overlay_id %> -
    - -
    - -

    Chat

    - -
    - - -
    - - - - -

    Gap audio

    -

    Plays a sound when a new message arrives after a period of silence.

    - - -
    - - - -
    - - -

    TTS redeems

    -

    For redeem variations with a TTS voice (set on the Redeems page; voices are made on the TTS page).

    -
    - - -
    - - -

    HUDFX

    - - -

    Custom CSS / JS

    - - - - -
    - -
    -

    EventSub

    -
    - -
    -Use this if Twitch alerts stop working after a token refresh. diff --git a/views/settings/_flash.ejs b/views/settings/_flash.ejs new file mode 100644 index 0000000..7e742e7 --- /dev/null +++ b/views/settings/_flash.ejs @@ -0,0 +1,2 @@ +<% if (locals.msg) { %>

    <%= msg %>

    <% } %> +<% if (locals.err) { %>

    <%= err %>

    <% } %> diff --git a/views/settings/advanced.ejs b/views/settings/advanced.ejs new file mode 100644 index 0000000..b768b32 --- /dev/null +++ b/views/settings/advanced.ejs @@ -0,0 +1,16 @@ +

    Advanced

    +

    Extra CSS and JavaScript added to every overlay page.

    +<%- include('_flash') %> +
    +
    +
    +
    Custom CSS
    + +
    +
    +
    Custom JSRuns after the overlay starts.
    + +
    +
    +
    +
    diff --git a/views/settings/backup.ejs b/views/settings/backup.ejs new file mode 100644 index 0000000..97655d7 --- /dev/null +++ b/views/settings/backup.ejs @@ -0,0 +1,16 @@ +

    Backup

    +

    Your whole setup in one file: settings, alert theme, redeems and their variations, TTS voices. Not included: the media files themselves (keep a copy of your uploads), statistics, and secrets (Twitch login, StreamElements token).

    +<%- include('_flash') %> +
    +
    +
    ExportDownload a .json file.
    + +
    +
    +
    ImportReplaces the current settings, theme, redeems and TTS voices with the ones in the file. Statistics stay.
    +
    + + +
    +
    +
    diff --git a/views/settings/chat.ejs b/views/settings/chat.ejs new file mode 100644 index 0000000..1489666 --- /dev/null +++ b/views/settings/chat.ejs @@ -0,0 +1,62 @@ +

    Chat

    +

    The chat shown on the overlay (OBS source with the chat part).

    +<%- include('_flash') %> +
    +
    +

    Messages

    +
    +
    Message timeoutSeconds a message stays. 0 = forever.
    + +
    +
    +
    Max messages shown
    + +
    +
    +
    Hidden chattersBots and alert services: never shown in the on-screen chat and left out of the statistics. Twitch logins, commas or spaces.
    + +
    +
    +
    Hide ! commands!discord, !lurk … are not shown. Add the bot to Hidden chatters to hide its answer too.
    + +
    +
    + +
    +

    Gap sound

    +
    +
    Play a sound after silenceWhen a message arrives after chat was quiet for a while.
    + +
    +
    +
    SoundFrom your Media library (upload new sounds there).
    +
    + + +
    + +
    +
    +
    Quiet for at leastSeconds of silence before the sound plays.
    + +
    +
    +
    VolumeQuiet right after the minimum silence, louder the longer chat was quiet.
    +
    + + + +
    +
    +
    +
    +
    diff --git a/views/settings/connections.ejs b/views/settings/connections.ejs new file mode 100644 index 0000000..d4ff4c1 --- /dev/null +++ b/views/settings/connections.ejs @@ -0,0 +1,64 @@ +

    Connections

    +

    Services HeyStreamer talks to.

    +<%- include('_flash') %> + +
    +

    Twitch

    +
    +
    Account
    +
    <%= user ? (user.display_name || user.login) : 'not logged in' %>
    +
    +
    +
    Events (EventSub)Follows, subs, bits, rewards, raids, chat, stream on / off.
    +
    + <% if (eventsub.connected) { %>connected + <% } else if (eventsub.running) { %>connecting… + <% } else { %>not running<% } %> + <% if (eventsub.lastEventAt) { %> last event <%= eventsub.lastEventAt.slice(0, 16).replace('T', ' ') %> UTC<% } %> + <% if (eventsub.failed.length) { %>

    Not allowed: <%= eventsub.failed.join(', ') %>. Log in again to give HeyStreamer the missing permission.

    <% } %> + <% if (eventsub.subscribed.length) { %>
    Listening to <%= eventsub.subscribed.length %> events<%= eventsub.subscribed.join(', ') %>
    <% } %> +
    +
    +
    +
    Fix itLog in again after new features ask for more permissions, or reconnect if alerts stop.
    +
    + Log in again with Twitch +
    +
    +
    +
    + +
    +

    StreamElements tips

    +
    +
    Status
    +
    + <% if (!se.enabled) { %>off no token + <% } else if (se.subscribed) { %>connected<% if (se.lastTipAt) { %> last tip <%= se.lastTipAt %><% } %> + <% } else { %>connecting…<% } %> + <% if (se.error) { %>
    <%= se.error %><% } %> + <% if (se.source === 'env') { %>
    Token comes from .env (SE_JWT). Saving one here replaces it.<% } %> +
    +
    +
    +
    JWT tokenStreamElements → your avatar → Channel settings → Show secrets → JWT Token. Kept secret: it is never shown again here.
    +
    + + + + <% if (settings.se_jwt) { %><% } %> +
    +
    +
    + +
    +

    HUDFX

    +
    +
    HUDFX overlay URLThen add &ext=hudfx to an OBS source link: HUDFX effects play inside that overlay. Empty = off.
    +
    + + + +
    +
    +
    diff --git a/views/settings/general.ejs b/views/settings/general.ejs new file mode 100644 index 0000000..fc4b44c --- /dev/null +++ b/views/settings/general.ejs @@ -0,0 +1,22 @@ +

    General

    +

    Basics about your channel.

    +<%- include('_flash') %> +
    +
    +
    +
    Twitch channelThe chat shown on the overlay. Usually your own channel name.
    + +
    +
    +
    Time zoneUsed for times and days on the stats pages.
    +
    + + + <% let zones = []; try { zones = Intl.supportedValuesOf('timeZone'); } catch {} %> + <% for (const z of zones) { %> +
    +
    +
    +
    +
    diff --git a/views/settings/obs.ejs b/views/settings/obs.ejs new file mode 100644 index 0000000..5cf8172 --- /dev/null +++ b/views/settings/obs.ejs @@ -0,0 +1,64 @@ +

    OBS sources

    +

    The links are hidden (anyone with one can open your overlay): 👁 shows one, Copy copies it either way. Add them as Browser Source in OBS (1920 × 1080, transparent). Pick what one source shows, then copy its link.

    + +
    +

    Ready-made links

    + <% const links = [ + ['Everything except chat', '?parts=nochat', 'Alerts, redeems, poll, Hype Train bar, raid send-off.'], + ['Chat only', '?parts=chat', 'Set its audio to “Monitor Only (mute output)” so chat sounds stay off stream.'], + ['Full-screen videos', '?parts=video', 'Video redeems / Power-ups. 2560 × 1440 source looks sharpest.'], + ['Everything in one source', '', 'Simplest, but chat and alert sounds share one fader.'], + ]; %> + <% links.forEach(([title, q, hint], i) => { %> +
    +
    <%= title %><%= hint %>
    +
    <%= overlayUrl + q %>
    +
    + <% }) %> +
    + +
    +

    Build your own

    +
    +
    Parts
    +
    + <% for (const [p, l] of [['alerts', 'Alerts and redeems'], ['chat', 'Chat'], ['poll', 'Poll'], ['hypebar', 'Hype Train bar'], ['raid', 'Raid send-off'], ['video', 'Videos']]) { %> + + <% } %> +
    +
    +
    +
    Chat boxOptional: left, top, width, height in px of the 1920 × 1080 page. Empty = default place.
    +
    + + +
    +
    +
    +
    Extras
    +
    +
    +
    +
    Link
    +
    +
    +
    + diff --git a/views/settings/stats.ejs b/views/settings/stats.ejs new file mode 100644 index 0000000..fb56aab --- /dev/null +++ b/views/settings/stats.ejs @@ -0,0 +1,38 @@ +

    Stats and data

    +

    The public stats page, and data copied from Twitch.

    +<%- include('_flash') %> +
    +

    Public stats page

    +
    +
    Public page onOff: it answers “not found” for everyone except you (preview below). Never shows message text, bots, or viewers who typed !hideme.
    + +
    +
    +
    Host nameIts own address. Needs a DNS record to this server, a certificate, and the web server sending it to HeyStreamer. On that host only the public page answers.
    + +
    +
    +
    + +
    +
    + +
    +

    Twitch

    + <% const bad = Object.entries(sync.parts || {}).filter(([, v]) => !String(v).startsWith('ok')); %> +
    +
    Sync with TwitchFollowers with follow dates, current subs, mods, VIPs, all-time bits, your emotes, past streams (VODs). Runs every 6 hours and after each stream.
    +
    +
    + <%= sync.at ? `last ${sync.at.slice(0, 16).replace('T', ' ')} UTC` : 'never' %>
    + <% if (sync.at) { %><% for (const [k, v] of Object.entries(sync.parts || {})) { %><%= k %>: <%= v %> · <% } %><% } %> +
    +
    +
    +
    Twitch analytics (CSV)Creator Dashboard → Analytics → export “Analytics and Revenue by day”. Fills in your history before HeyStreamer, and numbers only Twitch has. Importing again only updates days. Revenue is never public.
    +
    + + <%= csv.days ? `${csv.days} days imported (${csv.from_day} – ${csv.to_day})` : 'none imported yet' %> +
    +
    +
    diff --git a/views/settings/tts.ejs b/views/settings/tts.ejs new file mode 100644 index 0000000..975df98 --- /dev/null +++ b/views/settings/tts.ejs @@ -0,0 +1,20 @@ +

    Text to speech

    +

    For redeem variations with a TTS voice (set on Actions → Redeems; voices are made on Actions → TTS voices).

    +<%- include('_flash') %> +
    +
    +
    +
    Max lengthCharacters. Longer messages are cut at a word.
    + +
    +
    +
    Say the name first“ChickenWhisperer says: …”
    + +
    +
    +
    Blocked wordsOne per line or comma-separated. A message containing one is not read (“message removed”). Whole words, not case-sensitive, plurals and swaps like 0→o, $→s, k y s included. Links are always removed.
    + +
    +
    +
    +
    diff --git a/views/stats.ejs b/views/stats.ejs index 4c1c7ae..623f822 100644 --- a/views/stats.ejs +++ b/views/stats.ejs @@ -1,44 +1,11 @@ @@ -50,100 +17,23 @@
    -

    - <%= overview.since ? `Counting since ${overview.since.slice(0, 10)}` : 'Nothing counted yet: stats start with the next stream.' %> - · <%= hiddenCount %> hidden bot<%= hiddenCount === 1 ? '' : 's' %> left out ⓘ +

    + <%= since ? `Counting since ${since}` : 'Nothing counted yet: stats start with the next stream.' %> + · <%= hiddenCount %> hidden bot<%= hiddenCount === 1 ? '' : 's' %> left out ⓘ + · <% if (publicUrl) { %>Public page ↗<% } else { %>Public page preview ↗<% } %> +

    + +<% + const syncBad = Object.entries(sync.parts || {}).filter(([, v]) => !String(v).startsWith('ok')); + const syncTip = sync.at ? `Last sync ${sync.at.slice(0, 16).replace('T', ' ')} UTC: ` + Object.entries(sync.parts).map(([k, v]) => `${k} ${v}`).join(', ') : 'Not synced yet'; +%> +

    + Twitch sync: <%= sync.at ? `${sync.at.slice(0, 16).replace('T', ' ')} UTC` : 'never' %><% if (syncBad.length) { %> · <%= syncBad.map(([k]) => k).join(', ') %> failed<% } %> ⓘ + · analytics: <%= csv.days ? `${csv.days} days imported` : 'none imported' %> + · Sync, import and the public page: Settings → Stats and data

    <% 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
    -
    <%= overview.watchHours.toLocaleString() %>
    hours watched
    -
    <%= overview.streams %>
    streams
    -
    <%= overview.checkins.toLocaleString() %>
    check-ins
    -
    -<% - // one single-series bar chart (no legend: the title names it); x = last 30 days - const chart = (title, key, unit) => { - const W = 600, H = 150, L = 34, B = 18, T = 8, n = perDay.length, max = Math.max(1, ...perDay.map(d => d[key])); - const nice = (() => { const p = Math.pow(10, Math.floor(Math.log10(max))); return [1, 2, 2.5, 5, 10].map(m => m * p).find(v => v >= max); })(); - const slot = (W - L) / n, bw = Math.max(2, slot - 2), y = v => T + (H - T - B) * (1 - v / nice); - let s = ``; - for (const g of [0, nice / 2, nice]) s += `${g}`; - perDay.forEach((d, i) => { - const x = L + i * slot + 1, v = d[key], top = y(v), h = (H - B) - top; - const label = `${d.day.slice(5)} · ${v} ${unit}`; - s += ``; - if (v > 0) s += ``; - if (i % 7 === 0 && i < n - 4) s += `${d.day.slice(5)}`; - if (i === n - 1) s += `${d.day.slice(5)}`; - }); - return `

    ${title}

    ${s}
    `; - }; -%> -
    - <%- chart('Chat messages per day', 'messages', 'messages') %> - <%- chart('Watch hours per day', 'watchHours', 'h') %> -
    - -

    Leaderboards

    -<% - const board = (title, rows, fmt, extra, nw) => { - let s = `

    ${title}

    `; - if (!rows.length) return s + '

    nothing yet

    '; - s += '
      '; - rows.forEach((r, i) => { - const name = (r.name || r.login || '?').replace(/[<>&"]/g, ''); - s += `
    1. ${i + 1}${name}` - + `${extra ? `${extra(r)}` : ''}${fmt(r.n)}
    2. `; - }); - return s + '
    '; - }; - const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${m % 60} m` : `${m} m`; -%> -
    - <%- board('Points', boards.points, n => n.toLocaleString(), r => r.level) %> - <%- board('Watch time', boards.watch, hm, null, '6.4rem') %> - <%- board('Chat messages', boards.chat, n => n.toLocaleString()) %> - <%- board('Bits', boards.bits, n => n.toLocaleString()) %> - <%- board('Channel points spent', boards.channelPoints, n => n.toLocaleString()) %> -
    - -

    Top emotes

    -<% if (!emotes.length) { %>

    nothing yet

    <% } else { %> -
    - <% for (const e of emotes) { - const src = 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; %> - <% if (src) { %><% } %><%= e.emote %> <%= e.uses.toLocaleString() %> - <% } %> -
    -<% } %> - -

    Top commands

    -<% if (!commands.length) { %>

    nothing yet

    <% } else { %> -
    <% for (const c of commands) { %><%= c.command %> <%= c.uses.toLocaleString() %><% } %>
    -<% } %> - - +<%- include('_statsbody', { s, q, base: '/stats', viewerHref: '/stats/viewer?q=', mode: 'admin', view, ranks, tz, + extraBoards: [{ title: 'Points · all time', rows: pointsBoard, level: x => x.level, wide: true }] }) %> diff --git a/views/stats_viewer.ejs b/views/stats_viewer.ejs index e7f3d3d..a522bfa 100644 --- a/views/stats_viewer.ejs +++ b/views/stats_viewer.ejs @@ -1,9 +1,9 @@

    ← Stats

    <% if (!viewer) { %>

    <%= q %>

    -

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

    +

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

    <% } else { const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${m % 60} m` : `${m} m`; - const minutes = (viewer.watch.ticks || 0) * 5 + (viewer.importedMinutes || 0); %> -

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

    -

    <%= viewer.level.name %> - <% if (viewer.hidden) { %> · hidden bot<% } %> - <% if (viewer.chat.first_seen) { %> · first chat <%= viewer.chat.first_seen.slice(0, 10) %>, last <%= viewer.chat.last_seen.slice(0, 10) %><% } %> -

    + const num = n => Number(n || 0).toLocaleString('en-US'); + const minutes = (viewer.watch.ticks || 0) * 5 + (viewer.importedMinutes || 0); + const tw = viewer.twitch, b = viewer.badges; + // how long ago, in words: "2 years 3 months", "5 months", "12 days" + const ago = iso => { + const a = new Date(iso), n = new Date(); + let months = (n.getUTCFullYear() - a.getUTCFullYear()) * 12 + n.getUTCMonth() - a.getUTCMonth() - (n.getUTCDate() < a.getUTCDate() ? 1 : 0); + if (months < 1) { const d = Math.floor((n - a) / 864e5); return `${d} day${d === 1 ? '' : 's'}`; } + const y = Math.floor(months / 12), m = months % 12; + return [y ? `${y} y` : '', m ? `${m} mo` : ''].filter(Boolean).join(' '); + }; + const TIER = { 1000: 'Tier 1', 2000: 'Tier 2', 3000: 'Tier 3' }; + // roles: synced from Twitch (mods / VIPs / subs) + chat badges from their last message (founder, artist, ...) + const roles = new Map(); + const BADGE = { broadcaster: 'Broadcaster', moderator: 'Moderator', vip: 'VIP', founder: 'Founder', 'artist-badge': 'Artist', subscriber: 'Subscriber', 'lead_moderator': 'Lead moderator' }; + for (const x of b.list) if (BADGE[x.set]) roles.set(x.set, `${BADGE[x.set]} (chat badge${b.at ? `, ${b.at.slice(0, 10)}` : ''})`); + for (const r of tw.roles) roles.set(r, `${BADGE[r] || r} (from Twitch)`); + if (tw.sub) roles.set('subscriber', `${TIER[tw.sub.tier] || 'Subscriber'}${tw.sub.is_gift ? ` · gifted by ${tw.sub.gifter_name || tw.sub.gifter_login}` : ''} (from Twitch)`); + const subMonths = b.subMonths || viewer.given.subMonths || null; %> + +
    +
    +

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

    +
    + twitch.tv/<%= viewer.login %> ↗ + <%= viewer.level.name %> + <% for (const [set, tip] of roles) { %><%= set === 'subscriber' && tw.sub ? (TIER[tw.sub.tier] || 'Sub') + ' sub' : BADGE[set] || set %><% } %> + <% if (viewer.hidden) { %>hidden bot<% } %> + <% if (viewer.publicHidden) { %>not on public page<% } %> +
    +
    +
    + ⋯ + +
    +
    -
    <%= viewer.total.toLocaleString() %>
    points
    -
    <%= hm(minutes) %>
    watched<%= viewer.importedMinutes ? ' · incl. StreamElements' : '' %>
    -
    <%= (viewer.chat.messages || 0).toLocaleString() %>
    chat messages
    +
    <%= num(viewer.total) %>
    points
    +
    <%= hm(minutes) %>
    watched<%= viewer.importedMinutes ? ' · incl. StreamElements ⓘ' : '' %>
    +
    <%= num(viewer.chat.messages) %>
    chat messages
    <%= viewer.checkins %>
    check-ins
    +
    +
    <%= tw.follower && !tw.follower.unfollowed_at ? ago(tw.follower.followed_at) : tw.follower ? 'unfollowed' : '—' %>
    +
    <%= tw.follower && !tw.follower.unfollowed_at ? `following since ${tw.follower.followed_at.slice(0, 10)}` : 'not following' %> ⓘ
    +
    +
    +
    <%= tw.sub ? (TIER[tw.sub.tier] || 'Sub') : 'no sub' %><%= subMonths ? ` · ${subMonths} mo` : '' %>
    +
    <%= tw.sub ? (tw.sub.is_gift ? 'gifted sub' : 'subscribed now') : subMonths ? 'subscribed before' : 'subscription' %> ⓘ
    +
    +
    +
    <%= num(Math.max(tw.bits?.score || 0, viewer.given.bits)) %>
    bits given<%= tw.bits ? ` · #${tw.bits.rank}` : '' %> ⓘ
    +
    +
    <%= num(viewer.given.gifts) %>
    subs gifted
    - <% for (const [k, v] of Object.entries(viewer.parts).sort((a, b) => b[1] - a[1])) { %><%= k %>: <%= v.toLocaleString() %><% } %> + <% for (const [k, v] of Object.entries(viewer.parts).sort((a, b) => b[1] - a[1])) { %><%= k %>: <%= num(v) %><% } %>
    +

    + <% if (viewer.chat.first_seen) { %>First chat <%= viewer.chat.first_seen.slice(0, 10) %>, last <%= viewer.chat.last_seen.slice(0, 10) %>.<% } %> +

    <% if (viewer.emotes.length) { %> @@ -67,20 +155,4 @@ <% } %> - - <% if (viewer.importedMinutes && !viewer.user_id) { %> -
    - - Renamed on Twitch? New name: - - -
    - <% } %> -
    - - - -
    <% } %> diff --git a/views/tts.ejs b/views/tts.ejs index 2556dcf..24d799a 100644 --- a/views/tts.ejs +++ b/views/tts.ejs @@ -54,7 +54,7 @@

    Test

    - +