Stats per stream and period, public stats page, dashboard settings, Card alert style
Statistics - Per day and per stream statistics (src/periodstats.js, one generic stat_day table), backfilled once from the older tables; Stream / Week / Month / Year / All time views, Community and Streams tabs. - Viewer count every 5 minutes and title / category history per stream (EventSub channel.update): viewer graph, games played (donut), games in the streams list. - Twitch sync (src/twitchsync.js): followers with follow dates, current subs, mods, VIPs, all-time bits, channel emotes, past streams from VODs. Twitch analytics CSV import (src/twitchcsv.js). - Public stats page on its own host (Settings -> Stats and data): no message text, no bots, !hideme / !showme opt-out. Viewer page: roles, follow age, sub status, bits, a menu for rarely used actions. - StreamElements watch-time importer removed (already imported minutes stay as a baseline). Dashboard - Settings and Actions with a left sidebar; each settings page saves only its own fields. Connections (Twitch, StreamElements token now set here, HUDFX), OBS links (hidden behind an eye toggle) with a link builder, Chat (sound picked from the media library), TTS, Stats and data, Backup (export / import the whole setup), Advanced. Time zone setting for the stats pages. - Actions -> Alerts: alert style, pictures, sounds, bits tiers and card colours, stored in the database (src/theme.js); an old file-based theme is imported once. Alert preview page (/actions/alerts/preview, tools/preview/export.js for a static copy). - Old /actions page removed; Actions = Redeems / Alerts / TTS voices / Media. Alerts - New plain Card style for everyone (public/alerts/card.js); Polaroid, Cassette and the TTS letter stay as optional looks. Redeem variations can be Card, Cassette, Sound only or Video. Repo - No channel data in git: the channel's art, stickers and sounds stay on disk (gitignored) and are picked in the dashboard; examples for the server config (apache.example.sh, .env.example). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5bf4bffaa0
commit
c481ca92cb
57 changed files with 3080 additions and 774 deletions
14
.gitignore
vendored
14
.gitignore
vendored
|
|
@ -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
|
||||
|
|
|
|||
46
CLAUDE.md
46
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/<file>`). 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)
|
||||
|
|
|
|||
70
apache.example.sh
Normal file
70
apache.example.sh
Normal file
|
|
@ -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 <every name already on it> -d stats.example.com
|
||||
# HTTP: redirect everything to HTTPS
|
||||
<VirtualHost *:80>
|
||||
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
|
||||
</VirtualHost>
|
||||
|
||||
# HTTPS: proxy to Node on port 3000
|
||||
<IfModule mod_ssl.c>
|
||||
<VirtualHost *:443>
|
||||
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
|
||||
</VirtualHost>
|
||||
</IfModule>
|
||||
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"
|
||||
|
|
@ -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. "<channel> 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.
|
||||
|
|
|
|||
1
public/alerts/art/placeholder.svg
Normal file
1
public/alerts/art/placeholder.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 260"><path d="M150 236C70 180 22 136 22 84c0-34 26-60 60-60 28 0 50 16 68 40 18-24 40-40 68-40 34 0 60 26 60 60 0 52-48 96-128 152z" fill="#f4a0a8" stroke="#fffdf7" stroke-width="10"/><text x="150" y="122" text-anchor="middle" font-family="sans-serif" font-size="26" font-weight="700" fill="#fffdf7">your art</text><text x="150" y="152" text-anchor="middle" font-family="sans-serif" font-size="16" fill="#fffdf7">public/alerts/art</text></svg>
|
||||
|
After Width: | Height: | Size: 501 B |
23
public/alerts/card.css
Normal file
23
public/alerts/card.css
Normal file
|
|
@ -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; }
|
||||
78
public/alerts/card.js
Normal file
78
public/alerts/card.js
Normal file
|
|
@ -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 = `<div class="card${d.badge ? ' has-badge' : ''}">
|
||||
<div class="pic">${pic ? `<img src="${esc(pic)}" alt="">` : `<span class="ini">${esc(name.trim()[0] || '♥').toUpperCase()}</span>`}</div>
|
||||
<div class="txt">
|
||||
${d.tag ? `<div class="tag">${esc(d.tag)}</div>` : ''}
|
||||
<div class="name">${esc(name)}</div>
|
||||
<div class="line">${esc(d.line || '')}</div>
|
||||
${d.msg ? `<div class="msg">${words ? words.map(w => `<span class="w">${esc(w)}</span>`).join(' ') : `“${esc(d.msg)}”`}</div>` : ''}
|
||||
</div>
|
||||
${d.badge ? `<div class="badge"${d.badge.color ? ` style="--badge:${esc(d.badge.color)}"` : ''}>${esc(d.badge.big)}<small>${esc(d.badge.small || '')}</small></div>` : ''}
|
||||
<div class="bar"></div>
|
||||
</div>`;
|
||||
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 };
|
||||
})();
|
||||
|
|
@ -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 @@
|
|||
<div class="band"><span>SIDE A</span><span>${label}</span></div>
|
||||
<div class="title">${esc(d.title)}</div>
|
||||
<div class="sub">${d.sub && d.sub !== d.title ? esc(d.sub) : ''}</div>
|
||||
<div class="stk"><img src="${esc(d.sticker || DEFAULT_STICKER)}" alt=""></div>
|
||||
<div class="stk"><img src="${esc(d.sticker || defaultSticker())}" alt=""></div>
|
||||
${d.icon ? `<div class="ico"><img src="${esc(d.icon)}" alt=""></div>` : ''}
|
||||
${ultra ? '<div class="foil"></div>' + '<div class="spark"></div>'.repeat(6) : ''}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -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); }
|
||||
|
|
|
|||
|
|
@ -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 `<div class="photo ${cls}"><div class="ph"><img src="${ART(art)}" alt=""></div>${inner}</div>`;
|
||||
return `<div class="photo ${cls}"><div class="ph">${art ? `<img src="${ART(art)}" alt="">` : ''}</div>${inner}</div>`;
|
||||
}
|
||||
|
||||
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], '<div class="blank"></div>')).join('');
|
||||
const extraHearts = Array.from({ length: d.hearts || 0 }, () =>
|
||||
`<img class="heart extra sticker" src="${ART('Heart.png')}" alt="">`).join('');
|
||||
photoHTML('back', backArt[i % backArt.length], '<div class="blank"></div>')).join('');
|
||||
const heart = ART(th.heart); // corner sticker; none set = no stickers
|
||||
const extraHearts = heart ? Array.from({ length: d.hearts || 0 }, () =>
|
||||
`<img class="heart extra sticker" src="${heart}" alt="">`).join('') : '';
|
||||
el.innerHTML = backs + `
|
||||
<div class="photo main" style="--tape:${d.tape}${d.phbg ? ';--phbg:' + d.phbg : ''}">
|
||||
<div class="tape t1"></div><div class="tape t2"></div>
|
||||
<div class="ph${d.avatar ? ' avatar' : ''}"><img src="${ART(d.art)}" alt="">${d.tag ? `<span class="tag">${esc(d.tag)}</span>` : ''}</div>
|
||||
<div class="ph${d.avatar ? ' avatar' : ''}">${d.art ? `<img src="${ART(d.art)}" alt="">` : `<span class="ini">${esc((d.name || '♥').trim()[0] || '♥').toUpperCase()}</span>`}${d.tag ? `<span class="tag">${esc(d.tag)}</span>` : ''}</div>
|
||||
<div class="cap"><span class="u" style="font-size:${nameSize}px">${esc(d.name)}</span>${esc(d.line)}${d.msg ? `<span class="msg">“${esc(d.msg)}”</span>` : ''}</div>
|
||||
<img class="heart sticker" src="${ART('Heart.png')}" alt="">
|
||||
${heart ? `<img class="heart sticker" src="${heart}" alt="">` : ''}
|
||||
${extraHearts}
|
||||
${d.badge ? `<div class="badge" style="${d.badge.color ? '--badge:' + d.badge.color : ''}">${esc(d.badge.big)}<small>${esc(d.badge.small)}</small></div>` : ''}
|
||||
</div>`;
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 ? `<img src="${esc(raid.avatar)}" alt="" onerror="this.onerror=null;this.className='fallback';this.src='${FALLBACK}'">`
|
||||
: `<img class="fallback" src="${FALLBACK}" alt="">`;
|
||||
const img = raid.avatar ? `<img src="${esc(raid.avatar)}" alt="" onerror="this.onerror=null;this.className='fallback';this.src='${fallback()}'">`
|
||||
: `<img class="fallback" src="${fallback()}" alt="">`;
|
||||
el.innerHTML = `<div class="ph">${img}</div>
|
||||
<div class="cap"><span class="u">raiding ${esc(raid.target)}</span>${esc(line)}</div>
|
||||
<div class="when">${esc(badge)}</div>`;
|
||||
|
|
|
|||
31
src/app.js
31
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;
|
||||
|
|
|
|||
44
src/backup.js
Normal file
44
src/backup.js
Normal file
|
|
@ -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 };
|
||||
|
|
@ -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:<login>' 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;
|
||||
}
|
||||
|
||||
|
|
|
|||
26
src/db.js
26
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);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
35
src/nav.js
Normal file
35
src/nav.js
Normal file
|
|
@ -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 };
|
||||
493
src/periodstats.js
Normal file
493
src/periodstats.js
Normal file
|
|
@ -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:<event>' 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:<login>' 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=<id> | 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 };
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
40
src/routers/alertsetup.js
Normal file
40
src/routers/alertsetup.js
Normal file
|
|
@ -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;
|
||||
|
|
@ -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) => {
|
||||
|
|
|
|||
38
src/routers/public.js
Normal file
38
src/routers/public.js
Normal file
|
|
@ -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;
|
||||
|
|
@ -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 || ''),
|
||||
|
|
|
|||
|
|
@ -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/<section>.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 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/<id>), 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,
|
||||
// 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),
|
||||
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 || '',
|
||||
});
|
||||
}),
|
||||
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() });
|
||||
|
||||
console.log(`[settings] Saved — channel: ${b.channel}, gap_audio: ${b.gap_audio_enabled === 'on'}`);
|
||||
res.redirect('/settings');
|
||||
});
|
||||
|
||||
router.post('/reconnect', (req, res) => {
|
||||
const user = db.getUserById(req.session.userId);
|
||||
if (user) {
|
||||
eventsub.start(user);
|
||||
console.log('[settings] EventSub reconnect triggered');
|
||||
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();
|
||||
}
|
||||
res.redirect('/settings');
|
||||
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;
|
||||
}
|
||||
|
||||
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('/: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;
|
||||
|
|
|
|||
|
|
@ -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=<login>
|
||||
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');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
|
|
@ -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.)
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
|
|
|
|||
102
src/theme.js
Normal file
102
src/theme.js
Normal file
|
|
@ -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 };
|
||||
97
src/twitchcsv.js
Normal file
97
src/twitchcsv.js
Normal file
|
|
@ -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 };
|
||||
190
src/twitchsync.js
Normal file
190
src/twitchsync.js
Normal file
|
|
@ -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 };
|
||||
|
|
@ -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 };
|
||||
|
|
|
|||
19
tools/preview/export.js
Normal file
19
tools/preview/export.js
Normal file
|
|
@ -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 <out-dir>
|
||||
// Writes <out-dir>/index.html plus the overlay code under <out-dir>/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`);
|
||||
411
views/_statsbody.ejs
Normal file
411
views/_statsbody.ejs
Normal file
|
|
@ -0,0 +1,411 @@
|
|||
<%#
|
||||
Shared statistics body for the admin Stats page (views/stats.ejs) and the public page (views/public_stats.ejs).
|
||||
Two views (?v=community | streams) x periods (?p=stream|week|month|year|all).
|
||||
Community: supporters, raids, leaderboards, community ranks, emotes, commands, rewards.
|
||||
Streams: numbers, one activity chart (pick what to show), games played, the streams list; one stream: viewer graph.
|
||||
Locals: s = periodstats.summary(), q = rangeQuery helper, base = link prefix ('/stats', '/public' or '/'),
|
||||
view = 'community' | 'streams', mode = 'admin' | 'public', viewerHref = viewer link prefix or null,
|
||||
extraBoards = [{ title, rows, level, wide }], ranks = [{ login, name, level }] (Regular and up, all time).
|
||||
Colours come from the page: --muted, --line, --accent, --accent-hover, --card (and --card-solid for popups).
|
||||
A new section goes here once and appears on both pages; wrap it in `if (admin)` when it is not for the public.
|
||||
%>
|
||||
<%
|
||||
const admin = locals.mode === 'admin';
|
||||
const esc = v => String(v ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const num = n => Number(n || 0).toLocaleString('en-US');
|
||||
const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${String(Math.round(m % 60)).padStart(2, '0')} m` : `${Math.round(m)} m`;
|
||||
const r = s.range, T = s.totals, C = s.channel || {}, TW = s.twitch;
|
||||
const v = locals.view === 'streams' ? 'streams' : 'community';
|
||||
const cur = { p: r.p, d: r.from || undefined, s: r.p === 'stream' ? r.stream.id : undefined };
|
||||
const link = (rq, view = v) => base + q({ ...rq, v: view === 'community' ? undefined : view });
|
||||
const TZ = locals.tz || 'UTC'; // Settings → General → Time zone
|
||||
const day = iso => new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', timeZone: TZ });
|
||||
const time = iso => new Date(iso).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: TZ });
|
||||
const emoteSrc = e => e.source === 'twitch' && e.id ? `https://static-cdn.jtvnw.net/emoticons/v2/${e.id}/default/dark/1.0`
|
||||
: e.source === '7tv' && e.id ? `https://cdn.7tv.app/emote/${e.id}/1x.webp` : null;
|
||||
// ⓘ with an instant tooltip (hover, or tap / keyboard focus)
|
||||
const info = text => text ? ` <span class="sb-i" tabindex="0" data-tip="${esc(text)}">ⓘ</span>` : '';
|
||||
const person = x => { const n = esc(x.name || x.login || '?'); return viewerHref && x.login ? `<a href="${viewerHref}${encodeURIComponent(x.login)}">${n}</a>` : n; };
|
||||
const since = TW && TW.streamedDays ? TW.cutoff : null; // period reaches back before HeyStreamer counted
|
||||
%>
|
||||
<style>
|
||||
.sb-nav { display:flex; flex-wrap:wrap; align-items:center; gap:.5rem 1rem; margin:.4rem 0 1rem; }
|
||||
.sb-views { display:flex; gap:1.2rem; border-bottom:1px solid var(--line); margin:.2rem 0 .8rem; }
|
||||
.sb-views a { padding:.4rem .1rem; text-decoration:none; color:var(--muted); font-weight:700; border-bottom:3px solid transparent; margin-bottom:-1px; }
|
||||
.sb-views a.on { color:inherit; border-bottom-color:var(--accent); }
|
||||
.sb-tabs { display:flex; gap:.25rem; flex-wrap:wrap; }
|
||||
.sb-tabs a { padding:.25rem .8rem; border-radius:99px; border:1px solid var(--line); text-decoration:none; color:inherit; font-size:.85rem; }
|
||||
.sb-tabs a.on { background:var(--accent); border-color:var(--accent); color:#fff; }
|
||||
.sb-step { display:flex; align-items:center; gap:.4rem; margin-left:auto; }
|
||||
.sb-step a, .sb-step span.off { padding:.15rem .6rem; border-radius:8px; border:1px solid var(--line); text-decoration:none; color:inherit; }
|
||||
.sb-step span.off { opacity:.35; }
|
||||
.sb-title { font-weight:700; }
|
||||
.sb-sub { color:var(--muted); font-size:.85rem; }
|
||||
.sb-i { position:relative; cursor:help; color:var(--muted); font-size:.85em; outline:none; }
|
||||
.sb-i:hover::after, .sb-i:focus::after { content:attr(data-tip); position:absolute; left:50%; bottom:calc(100% + 6px); transform:translateX(-50%);
|
||||
width:max-content; max-width:260px; white-space:normal; text-align:left; font-size:.78rem; font-weight:400; line-height:1.35; color:inherit;
|
||||
background:var(--card-solid, var(--card)); border:1px solid var(--line); border-radius:8px; padding:.4rem .55rem;
|
||||
box-shadow:0 6px 18px rgba(0,0,0,.3); z-index:30; }
|
||||
.sb-tiles { display:grid; grid-template-columns:repeat(auto-fit, minmax(140px, 1fr)); gap:.6rem; margin:.2rem 0 1.2rem; }
|
||||
.sb-tile { border:1px solid var(--line); border-radius:12px; padding:.65rem .85rem; background:var(--card); }
|
||||
.sb-tile .v { font-size:1.5rem; font-weight:700; line-height:1.1; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.sb-tile .k { font-size:.8rem; color:var(--muted); }
|
||||
.sb-h { margin:1.4rem 0 .6rem; font-size:1.1rem; }
|
||||
.sb-streams { width:100%; border-collapse:collapse; font-size:.86rem; }
|
||||
.sb-streams th, .sb-streams td { text-align:left; padding:.4rem .5rem; border-bottom:1px solid var(--line); background:none; vertical-align:top; }
|
||||
.sb-streams th { color:var(--muted); font-weight:600; font-size:.78rem; }
|
||||
.sb-streams td.n { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.sb-streams .t { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; max-width:20rem; display:block; }
|
||||
.sb-streams .g { color:var(--muted); font-size:.78rem; }
|
||||
.sb-scroll { overflow-x:auto; }
|
||||
.sb-chart { border:1px solid var(--line); border-radius:12px; padding:.7rem .9rem; position:relative; background:var(--card); }
|
||||
.sb-chart h4 { margin:0 0 .4rem; font-size:.95rem; }
|
||||
.sb-chart svg { width:100%; height:auto; display:block; }
|
||||
.sb-chart .bar { fill:var(--accent); }
|
||||
.sb-chart .hit:hover + .bar { fill:var(--accent-hover); }
|
||||
.sb-chart .grid { stroke:var(--line); stroke-width:1; }
|
||||
.sb-chart .ax { fill:var(--muted); font-size:10px; }
|
||||
.sb-metrics { display:flex; flex-wrap:wrap; gap:.3rem; margin-bottom:.5rem; }
|
||||
.sb-metrics button { all:unset; cursor:pointer; padding:.2rem .7rem; border-radius:99px; border:1px solid var(--line); font-size:.8rem; }
|
||||
.sb-metrics button.on { background:var(--accent); border-color:var(--accent); color:#fff; }
|
||||
.sb-tip { position:absolute; pointer-events:none; background:var(--card-solid, var(--card)); border:1px solid var(--line);
|
||||
border-radius:8px; padding:.25rem .5rem; font-size:.8rem; box-shadow:0 4px 12px rgba(0,0,0,.35); white-space:nowrap; display:none; z-index:5; }
|
||||
.sb-two { display:grid; grid-template-columns:minmax(0, 2fr) minmax(260px, 1fr); gap:1rem; align-items:start; }
|
||||
@media (max-width: 800px) { .sb-two { grid-template-columns:1fr; } }
|
||||
.sb-games { display:flex; gap:1rem; align-items:center; flex-wrap:wrap; }
|
||||
.sb-games svg { width:150px; height:150px; flex:none; }
|
||||
.sb-games ul { list-style:none; margin:0; padding:0; flex:1; min-width:160px; max-width:440px; font-size:.85rem; }
|
||||
.sb-games li { list-style:none; display:grid; grid-template-columns:.8rem minmax(0, 1fr) auto; gap:.45rem; align-items:center; padding:.15rem 0; }
|
||||
.sb-games .sw { width:.8rem; height:.8rem; border-radius:3px; }
|
||||
.sb-games .nm { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.sb-games .hv { color:var(--muted); font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.sb-boards { display:grid; grid-template-columns:repeat(auto-fill, minmax(290px, 1fr)); gap:1rem; }
|
||||
.sb-board { border:1px solid var(--line); border-radius:12px; padding:.6rem .8rem; background:var(--card); }
|
||||
.sb-board h4 { margin:0 0 .3rem; font-size:.95rem; }
|
||||
.sb-board ol { list-style:none; margin:0; padding:0; }
|
||||
.sb-board li { list-style:none; display:grid; grid-template-columns:1.6rem minmax(0, 1fr) var(--nw, 4.6rem); align-items:center; gap:.5rem;
|
||||
height:2rem; margin:0; padding:0 .2rem; border-bottom:1px solid var(--line); font-size:.88rem; }
|
||||
.sb-board li:last-child { border-bottom:0; }
|
||||
.sb-board .r { color:var(--muted); text-align:right; font-variant-numeric:tabular-nums; }
|
||||
.sb-board .who { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0; }
|
||||
.sb-board .who a { text-decoration:none; }
|
||||
.sb-board .lvl { font-size:.66rem; padding:.02rem .45rem; border-radius:99px; border:1px solid var(--line); color:var(--muted); white-space:nowrap; justify-self:start; }
|
||||
.sb-board .n { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
.sb-board.wide { grid-column:span 2; }
|
||||
.sb-board.wide li { grid-template-columns:1.6rem minmax(0, 1fr) 5.5rem var(--nw, 4.6rem); }
|
||||
@media (max-width: 700px) { .sb-board.wide { grid-column:auto; } }
|
||||
.sb-pills { display:flex; flex-wrap:wrap; gap:.45rem; }
|
||||
.sb-pill { display:flex; align-items:center; gap:.35rem; border:1px solid var(--line); border-radius:99px; padding:.15rem .6rem .15rem .3rem; font-size:.82rem; background:var(--card); }
|
||||
.sb-pill.txt { padding-left:.6rem; }
|
||||
.sb-pill img { width:26px; height:26px; object-fit:contain; }
|
||||
.sb-pill a { text-decoration:none; }
|
||||
.sb-pill .what { color:var(--muted); font-size:.75rem; }
|
||||
.sb-pill.zero { opacity:.5; }
|
||||
.sb-empty { color:var(--muted); font-size:.85rem; font-style:italic; }
|
||||
.sb-note { color:var(--muted); font-size:.8rem; }
|
||||
.sb-ranks { display:grid; grid-template-columns:repeat(auto-fill, minmax(220px, 1fr)); gap:1rem; }
|
||||
.sb-rank { border:1px solid var(--line); border-radius:12px; padding:.6rem .8rem; background:var(--card); }
|
||||
.sb-rank h4 { margin:0 0 .45rem; font-size:.95rem; }
|
||||
.sb-timeline .area { fill:var(--accent); opacity:.18; }
|
||||
.sb-timeline .line { fill:none; stroke:var(--accent); stroke-width:2.5; stroke-linejoin:round; }
|
||||
.sb-timeline .dot { fill:transparent; }
|
||||
.sb-timeline .dot:hover { fill:var(--accent); }
|
||||
.sb-timeline .mark { stroke:var(--muted); stroke-dasharray:4 4; }
|
||||
.sb-timeline .markdot { fill:var(--muted); }
|
||||
.sb-changes { list-style:none; padding:0; margin:.6rem 0 0; font-size:.86rem; }
|
||||
.sb-changes li { list-style:none; padding:.2rem 0; border-bottom:1px dashed var(--line); }
|
||||
.sb-changes .when { display:inline-block; min-width:3.4rem; color:var(--muted); font-variant-numeric:tabular-nums; }
|
||||
.sb-changes .game { color:var(--muted); font-size:.8rem; margin-left:.4rem; }
|
||||
.sb-vod { font-size:.65rem; border:1px solid var(--line); border-radius:99px; padding:0 .35rem; color:var(--muted); }
|
||||
</style>
|
||||
|
||||
<div class="sb-views" role="tablist">
|
||||
<a href="<%= link(cur, 'community') %>" class="<%= v === 'community' ? 'on' : '' %>">Community</a>
|
||||
<a href="<%= link(cur, 'streams') %>" class="<%= v === 'streams' ? 'on' : '' %>">Streams</a>
|
||||
</div>
|
||||
|
||||
<div class="sb-nav">
|
||||
<div class="sb-tabs">
|
||||
<% for (const [p, label] of [['stream', 'Stream'], ['week', 'Week'], ['month', 'Month'], ['year', 'Year'], ['all', 'All time']]) { %>
|
||||
<a href="<%= link(p === 'all' ? { p } : { p, ...(p === 'stream' ? {} : { d: r.from || undefined }) }) %>" class="<%= r.p === p ? 'on' : '' %>"><%= label %></a>
|
||||
<% } %>
|
||||
</div>
|
||||
<div class="sb-step">
|
||||
<% if (r.p !== 'all') { %>
|
||||
<% if (r.prev) { %><a href="<%= link(r.prev) %>" title="<%= r.p === 'stream' ? 'Older stream' : 'Earlier' %>">‹</a><% } else { %><span class="off">‹</span><% } %>
|
||||
<% } %>
|
||||
<span><span class="sb-title"><%= r.label %></span><% if (r.sub) { %> <span class="sb-sub">· <%= r.sub %></span><% } %></span>
|
||||
<% if (r.p !== 'all') { %>
|
||||
<% if (r.next) { %><a href="<%= link(r.next) %>" title="<%= r.p === 'stream' ? 'Newer stream' : 'Later' %>">›</a><% } else { %><span class="off">›</span><% } %>
|
||||
<% } %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<%
|
||||
// ---- number tiles. Public: a short, friendly set; admin: everything ----
|
||||
const T_ = {}; // id -> [value, label, tooltip]
|
||||
T_.messages = [num(T.messages), 'chat messages', since ? `Before ${since} from Twitch's daily analytics, after that counted by HeyStreamer` : ''];
|
||||
T_.watch = [num(T.watchHours), 'hours watched', T.historyWatchHours ? `${num(T.historyWatchHours)} h from Twitch's daily analytics (before ${since}), the rest counted by HeyStreamer` : T.baselineHours ? `Includes ${num(T.baselineHours)} h counted by StreamElements before HeyStreamer counted itself` : ''];
|
||||
if (r.p !== 'stream') T_.streams = [num(T.streams), T.streams === 1 ? 'stream' : 'streams', since ? `Before ${since} every day with a stream counts as one stream (Twitch's daily analytics)` : ''];
|
||||
T_.streamed = r.p === 'stream' && s.streams[0] ? [hm(s.streams[0].minutes), s.streams[0].live ? 'live for' : 'streamed'] : [num(T.hoursStreamed), 'hours streamed'];
|
||||
T_.emotes = [num(T.emotes), 'emotes used', since ? `Counted by HeyStreamer since ${since}` : ''];
|
||||
if (TW && TW.clips) T_.clips = [num(TW.clips), 'clips created', `${num(TW.clipViews)} clip views (Twitch's daily analytics)`];
|
||||
T_.redeems = [num(T.redeems), 'rewards redeemed', `${num(T.channelPoints)} channel points spent${since ? `; counted since ${since}` : ''}`];
|
||||
if (admin) {
|
||||
if (r.p === 'all' && C.followers != null) T_.followers = [num(C.followers), 'followers', 'Following the channel right now (from Twitch)'];
|
||||
if (r.p === 'all' && C.subsNow != null) T_.subsNow = [num(C.subsNow), 'subscribers', 'Subscribed right now (from Twitch, without the streamer)'];
|
||||
T_.chatters = [num(T.chatters), since ? `chatters since ${since}` : 'chatters', 'Different people who chatted. Twitch\'s export has no names, so this only counts from HeyStreamer\'s start'];
|
||||
T_.viewers = [num(T.viewers), since ? `viewers since ${since}` : 'viewers', `Different people in the chatter list while live, lurkers included${T.viewersFromBaseline ? `. Includes ${num(T.viewersFromBaseline)} viewers known only from StreamElements' watch time (from before HeyStreamer counted), which is why All time is higher than the other tabs` : ''}`];
|
||||
const pk = r.p === 'stream' ? s.streams[0] : C;
|
||||
if (pk && pk.peak != null) T_.peak = [num(pk.peak), 'peak viewers', pk.avg != null ? `About ${num(pk.avg)} on average` : ''];
|
||||
if (TW && TW.uniquePerDay != null) T_.unique = [num(TW.uniquePerDay), 'unique viewers / stream day', 'Twitch\'s count of different people who watched, averaged over the days you streamed'];
|
||||
if (TW && (TW.newEngaged || TW.returningEngaged)) T_.engaged = [num(TW.newEngaged), 'new engaged viewers', `${num(TW.returningEngaged)} returning engaged viewer-days. Engaged = watched 5+ minutes and chatted or followed (Twitch)`];
|
||||
if (TW && TW.revenue) T_.revenue = [`$${TW.revenue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`, 'revenue · admin only',
|
||||
TW.revenueByType.map(([k, x]) => `${k} $${x.toFixed(2)}`).join(', ') + ' (Twitch export, before payout fees and taxes)'];
|
||||
if (T.follows && !T_.followers) T_.follows = [num(T.follows), 'new followers'];
|
||||
if (T.intros) T_.intros = [num(T.intros), 'first-time chatters'];
|
||||
if (T.subs || T.giftSubs) T_.subs = [num(T.subs + T.giftSubs), 'subs', `${num(T.subs)} subs and resubs, ${num(T.giftSubs)} gifted`];
|
||||
if (T.bits) T_.bits = [num(T.bits), 'bits', s.bitsSource === 'twitch' ? 'All time, from Twitch (top 100 cheerers)' : T.powerUps ? `${num(T.powerUps)} Power-ups included` : ''];
|
||||
if (T.raids) T_.raids = [num(T.raids), T.raids === 1 ? 'raid' : 'raids', `${num(T.raidViewers)} viewers brought in`];
|
||||
if (T.checkins) T_.checkins = [num(T.checkins), 'check-ins', 'First message of a stream'];
|
||||
}
|
||||
const order = admin
|
||||
? ['followers', 'subsNow', 'messages', 'chatters', 'viewers', 'watch', 'streams', 'streamed', 'peak', 'unique', 'engaged', 'clips', 'revenue', 'follows', 'intros', 'emotes', 'subs', 'bits', 'redeems', 'raids', 'checkins']
|
||||
: ['messages', 'watch', 'streams', 'streamed', 'emotes', 'clips', 'redeems'];
|
||||
const tiles = order.filter(k => T_[k]).map(k => T_[k]);
|
||||
%>
|
||||
<% if (admin || v === 'streams') { %>
|
||||
<div class="sb-tiles">
|
||||
<% for (const [val, k, tip] of tiles) { %><div class="sb-tile"><div class="v"><%= val %></div><div class="k"><%= k %><%- info(tip) %></div></div><% } %>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<% if (v === 'streams') { %>
|
||||
<%# ===================== STREAMS ===================== %>
|
||||
<% if (r.p === 'stream' && s.streams[0]) { const x = s.streams[0]; %>
|
||||
<p class="sb-sub" style="margin-top:-.6rem;">
|
||||
<%= day(x.started_at) %>, <%= time(x.started_at) %>–<%= x.ended_at ? time(x.ended_at) : 'now' %><%= x.games.length ? ` · ${x.games.join(', ')}` : '' %>
|
||||
<% if (x.live) { %> · <strong>live now</strong><% } %>
|
||||
<% if (x.source === 'vod') { %> · from the VOD (HeyStreamer was not counting)<% } %>
|
||||
</p>
|
||||
<%
|
||||
// viewers every 5 minutes as an area line; title / category changes as dashed markers
|
||||
const tl = s.timeline;
|
||||
if (tl && (tl.samples.length || tl.changes.length)) {
|
||||
const W = 900, H = 200, L = 34, B = 20, TOP = 10;
|
||||
const t0 = Date.parse(tl.start), t1 = Math.max(Date.parse(tl.end), t0 + 60000);
|
||||
const max = Math.max(1, ...tl.samples.map(p => p.viewers));
|
||||
const top = (() => { const p = Math.pow(10, Math.floor(Math.log10(max))); return [1, 2, 2.5, 5, 10].map(m => m * p).find(x => x >= max); })();
|
||||
const X = t => L + (W - L) * (Date.parse(t) - t0) / (t1 - t0), Y = n => TOP + (H - TOP - B) * (1 - n / top);
|
||||
let svg = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Viewers during the stream">`;
|
||||
for (const g of [0, top / 2, top]) svg += `<line class="grid" x1="${L}" x2="${W}" y1="${Y(g)}" y2="${Y(g)}"/><text class="ax" x="${L - 4}" y="${Y(g) + 3}" text-anchor="end">${g}</text>`;
|
||||
for (let h = 0; h <= (t1 - t0) / 36e5; h++) { const tt = new Date(t0 + h * 36e5).toISOString(); svg += `<text class="ax" x="${X(tt)}" y="${H - 5}" text-anchor="middle">${time(tt)}</text>`; }
|
||||
if (tl.samples.length) {
|
||||
const pts = tl.samples.map(p => `${X(p.at).toFixed(1)},${Y(p.viewers).toFixed(1)}`);
|
||||
svg += `<path class="area" d="M${X(tl.samples[0].at).toFixed(1)},${H - B} L${pts.join(' L')} L${X(tl.samples.at(-1).at).toFixed(1)},${H - B} Z"/>`;
|
||||
svg += `<polyline class="line" points="${pts.join(' ')}"/>`;
|
||||
for (const p of tl.samples) svg += `<circle class="dot hit" cx="${X(p.at).toFixed(1)}" cy="${Y(p.viewers).toFixed(1)}" r="6" data-tip="${time(p.at)} · ${p.viewers} viewers"/>`;
|
||||
}
|
||||
for (const c of tl.changes) {
|
||||
if (c.start) continue;
|
||||
const x = X(c.at).toFixed(1);
|
||||
svg += `<line class="mark" x1="${x}" x2="${x}" y1="${TOP}" y2="${H - B}"/><circle class="markdot hit" cx="${x}" cy="${TOP + 4}" r="5" data-tip="${time(c.at)} · ${esc(c.title || '')}${c.game ? ' · ' + esc(c.game) : ''}"/>`;
|
||||
}
|
||||
%>
|
||||
<h3 class="sb-h">Viewers</h3>
|
||||
<div class="sb-chart sb-timeline"><%- svg %></svg><div class="sb-tip"></div></div>
|
||||
<% if (!tl.samples.length) { %><p class="sb-note">No viewer counts were recorded for this stream.</p><% } %>
|
||||
<% if (tl.changes.length) { %>
|
||||
<ol class="sb-changes">
|
||||
<% for (const c of tl.changes) { %><li><span class="when"><%= c.start ? 'start' : time(c.at) %></span> <span><%= c.title || '—' %></span><% if (c.game) { %> <span class="game"><%= c.game %></span><% } %></li><% } %>
|
||||
</ol>
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% } %>
|
||||
|
||||
<%
|
||||
// one activity chart, like Twitch's: pick what it shows
|
||||
const METRICS = [['messages', 'Chat messages', ''], ['watchHours', 'Hours watched', 'h'], ['streamHours', 'Hours streamed', 'h'],
|
||||
['avgViewers', 'Average viewers', ''], ['follows', 'New followers', '']];
|
||||
const rows = s.series ? s.series.rows : [];
|
||||
const shown = METRICS.filter(([k]) => rows.some(x => x[k]));
|
||||
%>
|
||||
<% if (rows.length && shown.length) { %>
|
||||
<h3 class="sb-h">Activity <span class="sb-sub">per <%= s.series.unit %></span></h3>
|
||||
<div class="sb-chart" id="sb-activity">
|
||||
<div class="sb-metrics"><% shown.forEach(([k, label], i) => { %><button type="button" data-k="<%= k %>" class="<%= i ? '' : 'on' %>"><%= label %></button><% }) %></div>
|
||||
<div class="plot"></div><div class="sb-tip"></div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
const rows = <%- JSON.stringify(rows.map(x => ({ label: x.label, messages: x.messages, watchHours: x.watchHours, streamHours: x.streamHours, avgViewers: x.avgViewers, follows: x.follows }))).replace(/</g, '\\u003c') %>;
|
||||
const units = <%- JSON.stringify(Object.fromEntries(METRICS.map(([k, l, u]) => [k, { label: l, unit: u }]))) %>;
|
||||
const box = document.getElementById('sb-activity'), plot = box.querySelector('.plot');
|
||||
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
function draw(key) {
|
||||
const W = 900, H = 200, L = 38, B = 20, TOP = 8, n = rows.length, max = Math.max(1, ...rows.map(d => d[key] || 0));
|
||||
const p = Math.pow(10, Math.floor(Math.log10(max))), top = [1, 2, 2.5, 5, 10].map(m => m * p).find(x => x >= max);
|
||||
const slot = (W - L) / n, bw = Math.max(2, Math.min(slot - 2, 44)), pad = (slot - bw) / 2, y = x => TOP + (H - TOP - B) * (1 - x / top);
|
||||
const every = Math.ceil(n / 12);
|
||||
let out = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(units[key].label)}">`;
|
||||
for (const g of [0, top / 2, top]) out += `<line class="grid" x1="${L}" x2="${W}" y1="${y(g)}" y2="${y(g)}"/><text class="ax" x="${L - 4}" y="${y(g) + 3}" text-anchor="end">${+g.toFixed(1)}</text>`;
|
||||
rows.forEach((d, i) => {
|
||||
const x = L + i * slot + pad, val = d[key] || 0, tp = y(val), h = (H - B) - tp, rr = Math.min(4, bw / 2, h);
|
||||
out += `<rect class="hit" x="${L + i * slot}" y="${TOP}" width="${slot}" height="${H - TOP - B}" fill="transparent" data-tip="${esc(d.label)} · ${val}${units[key].unit ? ' ' + units[key].unit : ''}"/>`;
|
||||
if (val > 0) out += `<path class="bar" d="M${x},${H - B} V${tp + rr} Q${x},${tp} ${x + rr},${tp} H${x + bw - rr} Q${x + bw},${tp} ${x + bw},${tp + rr} V${H - B} Z"/>`;
|
||||
if (i % every === 0) out += `<text class="ax" x="${x + bw / 2}" y="${H - 4}" text-anchor="middle">${esc(d.label)}</text>`;
|
||||
});
|
||||
plot.innerHTML = out + '</svg>';
|
||||
window.sbHoverTips && window.sbHoverTips(box);
|
||||
}
|
||||
box.querySelectorAll('.sb-metrics button').forEach(b => b.addEventListener('click', () => {
|
||||
box.querySelectorAll('.sb-metrics button').forEach(x => x.classList.toggle('on', x === b));
|
||||
draw(b.dataset.k);
|
||||
}));
|
||||
draw(box.querySelector('.sb-metrics button.on').dataset.k);
|
||||
})();
|
||||
</script>
|
||||
<% } %>
|
||||
|
||||
<%
|
||||
// games played: donut of streamed time per category (from HeyStreamer's title / category history)
|
||||
const PAL = ['#b74347', '#5b8fc7', '#d39b3a', '#4f9a68', '#8c6bb1', '#c76f9a', '#3fa3a1', '#9a8a5a'];
|
||||
const games = s.games || [];
|
||||
const totalMin = games.reduce((a, g) => a + g.minutes, 0);
|
||||
const slices = games.length > 8 ? [...games.slice(0, 7), { game: `${games.length - 7} more`, minutes: games.slice(7).reduce((a, g) => a + g.minutes, 0), other: true }] : games;
|
||||
%>
|
||||
<% if (r.p !== 'stream' || slices.length > 1) { %>
|
||||
<h3 class="sb-h">Games<%- info('Time per category, from every title / category change HeyStreamer saw. Twitch keeps no history of categories, so streams from before HeyStreamer recorded them have no game.') %></h3>
|
||||
<% if (!totalMin) { %><p class="sb-empty">no categories recorded in this period yet</p><% } else { %>
|
||||
<div class="sb-chart sb-games">
|
||||
<svg viewBox="-1 -1 2 2" role="img" aria-label="Time per game">
|
||||
<% let acc = 0; slices.forEach((g, i) => {
|
||||
const a0 = acc / totalMin * 2 * Math.PI, a1 = (acc + g.minutes) / totalMin * 2 * Math.PI; acc += g.minutes;
|
||||
const big = a1 - a0 > Math.PI ? 1 : 0, P = a => `${(Math.sin(a) * .95).toFixed(4)} ${(-Math.cos(a) * .95).toFixed(4)}`, Q = a => `${(Math.sin(a) * .55).toFixed(4)} ${(-Math.cos(a) * .55).toFixed(4)}`;
|
||||
const d = slices.length === 1 ? 'M0 -.95 A.95 .95 0 1 1 0 .95 A.95 .95 0 1 1 0 -.95 Z M0 -.55 A.55 .55 0 1 0 0 .55 A.55 .55 0 1 0 0 -.55 Z'
|
||||
: `M${P(a0)} A.95 .95 0 ${big} 1 ${P(a1)} L${Q(a1)} A.55 .55 0 ${big} 0 ${Q(a0)} Z`; %>
|
||||
<path d="<%= d %>" fill="<%= g.other ? '#8a8a8a' : PAL[i % PAL.length] %>" fill-rule="evenodd" stroke="var(--card-solid, #fff)" stroke-width=".02"><title><%= g.game %> · <%= hm(g.minutes) %></title></path>
|
||||
<% }) %>
|
||||
</svg>
|
||||
<ul>
|
||||
<% slices.forEach((g, i) => { %>
|
||||
<li><span class="sw" style="background:<%= g.other ? '#8a8a8a' : PAL[i % PAL.length] %>"></span><span class="nm" title="<%= g.game %>"><%= g.game %></span>
|
||||
<span class="hv"><%= hm(g.minutes) %> · <%= Math.round(g.minutes / totalMin * 100) %>%</span></li>
|
||||
<% }) %>
|
||||
</ul>
|
||||
</div>
|
||||
<% } %>
|
||||
<% } %>
|
||||
|
||||
<% if (r.p !== 'stream' && s.streams.length) { %>
|
||||
<h3 class="sb-h"><%= r.p === 'all' ? 'Recent streams' : 'Streams' %></h3>
|
||||
<div class="sb-scroll"><table class="sb-streams">
|
||||
<thead><tr><th>Date</th><th>Title · games</th><th style="text-align:right">Length</th><th style="text-align:right">Peak</th><th style="text-align:right">Viewers</th><th style="text-align:right">Chatters</th><th style="text-align:right">Messages</th></tr></thead>
|
||||
<tbody>
|
||||
<% for (const x of s.streams.slice(0, r.p === 'all' ? 15 : 100)) { %>
|
||||
<tr>
|
||||
<td style="white-space:nowrap"><a href="<%= link({ p: 'stream', s: x.id }) %>"><%= day(x.started_at) %></a><%= x.live ? ' · live' : '' %><% if (x.source === 'vod') { %> <span class="sb-vod" title="Known from the Twitch VOD only: HeyStreamer was not counting during this stream">VOD</span><% } %></td>
|
||||
<td><span class="t" title="<%= x.title %>"><%= x.title || '—' %></span><% if (x.games.length) { %><span class="g"><%= x.games.join(' · ') %></span><% } %></td>
|
||||
<td class="n"><%= hm(x.minutes) %></td><td class="n"><%= x.peak != null ? num(x.peak) : '—' %></td>
|
||||
<td class="n"><%= num(x.viewers) %></td><td class="n"><%= num(x.chatters) %></td><td class="n"><%= num(x.messages) %></td>
|
||||
</tr>
|
||||
<% } %>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<% } %>
|
||||
|
||||
<% } else { %>
|
||||
<%# ===================== COMMUNITY ===================== %>
|
||||
<% const cm = s.community || {}; %>
|
||||
<% if ((cm.supporters || []).length) { %>
|
||||
<h3 class="sb-h">Thank you for the support</h3>
|
||||
<div class="sb-pills">
|
||||
<% for (const x of cm.supporters.slice(0, 40)) {
|
||||
const what = [x.bits ? `${num(x.bits)} bits` : '', x.subs ? (x.subs === 1 ? 'sub' : `${x.subs} subs`) : '', x.gifts ? `${num(x.gifts)} gifted` : '', admin && x.tips ? 'tip' : ''].filter(Boolean).join(' · '); %>
|
||||
<span class="sb-pill txt"><%- person(x) %> <span class="what"><%= what %></span></span>
|
||||
<% } %>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<% if ((cm.raiders || []).length) { %>
|
||||
<h3 class="sb-h">Raids</h3>
|
||||
<div class="sb-pills"><% for (const x of cm.raiders) { %><span class="sb-pill txt"><%- person(x) %> <span class="what"><%= x.raids > 1 ? `${x.raids} raids · ` : '' %><%= num(x.viewers) %> viewers</span></span><% } %></div>
|
||||
<% } %>
|
||||
|
||||
<%
|
||||
const board = b => {
|
||||
const nw = b.nw ? ` style="--nw:${b.nw}"` : '';
|
||||
let out = `<div class="sb-board${b.wide ? ' wide' : ''}"${nw}><h4>${esc(b.title)}</h4>`;
|
||||
if (!b.rows.length) return out + '<p class="sb-empty">nothing yet</p></div>';
|
||||
out += '<ol>';
|
||||
b.rows.forEach((x, i) => {
|
||||
out += `<li><span class="r">${i + 1}</span><span class="who" title="${esc(x.name || x.login)}">${person(x)}</span>${b.level ? `<span class="lvl">${esc(b.level(x))}</span>` : ''}<span class="n">${(b.fmt || num)(x.n)}</span></li>`;
|
||||
});
|
||||
return out + '</ol></div>';
|
||||
};
|
||||
const boards = [
|
||||
...(locals.extraBoards || []),
|
||||
{ title: 'Most active in chat', rows: s.boards.chat },
|
||||
{ title: 'Watch time', rows: s.boards.watch, fmt: hm, nw: '6.4rem' },
|
||||
{ title: 'Channel points spent', rows: s.boards.channelPoints, optional: true },
|
||||
...(admin ? [{ title: 'Bits', rows: s.boards.bits, optional: true }, { title: 'Subs and gifts', rows: s.boards.subs, optional: true }] : []),
|
||||
].filter(b => !(b.optional && !b.rows.length));
|
||||
%>
|
||||
<h3 class="sb-h">Leaderboards</h3>
|
||||
<div class="sb-boards"><% for (const b of boards) { %><%- board(b) %><% } %></div>
|
||||
|
||||
<% if ((locals.ranks || []).length) {
|
||||
const LV = ['Veteran', 'Loyal', 'Regular']; %>
|
||||
<h3 class="sb-h">Community ranks<%- info('Levels by total watch time: Regular from 50 h, Loyal from 200 h, Veteran from 1000 h. All time.') %></h3>
|
||||
<div class="sb-ranks">
|
||||
<% for (const lv of LV) { const list = ranks.filter(x => x.level === lv); if (!list.length) continue; %>
|
||||
<div class="sb-rank"><h4><%= lv %> <span class="sb-sub"><%= list.length %></span></h4>
|
||||
<div class="sb-pills"><% for (const x of list) { %><span class="sb-pill txt"><%- person(x) %></span><% } %></div></div>
|
||||
<% } %>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<% if (s.channelEmotes && s.channelEmotes.length) { %>
|
||||
<h3 class="sb-h">Channel emotes<%- info('The channel\'s own emotes and how often they were used in this chat in this period. Twitch does not tell how often they are used in other channels.') %></h3>
|
||||
<div class="sb-pills">
|
||||
<% for (const e of s.channelEmotes) { %>
|
||||
<span class="sb-pill<%= e.uses ? '' : ' zero' %>" title="<%= e.name %><%= e.tier ? ` · Tier ${String(e.tier).slice(0, 1)}` : '' %><%= e.type === 'follower' ? ' · follower emote' : e.type === 'bitstier' ? ' · bits emote' : '' %><%= e.gone ? ' · removed from the channel' : '' %>"><% if (e.image) { %><img src="<%= e.image %>" alt="" loading="lazy"><% } %><%= e.name %> <strong><%= num(e.uses) %></strong></span>
|
||||
<% } %>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<h3 class="sb-h">Top emotes</h3>
|
||||
<% if (!s.emotes.length) { %><p class="sb-empty">nothing yet</p><% } else { %>
|
||||
<div class="sb-pills">
|
||||
<% for (const e of s.emotes) { const src = emoteSrc(e); %>
|
||||
<span class="sb-pill" title="<%= e.emote %><%= e.source ? ` · ${e.source === '7tv' ? '7TV' : 'Twitch'}` : '' %>"><% if (src) { %><img src="<%= src %>" alt="" loading="lazy"><% } %><%= e.emote %> <strong><%= num(e.uses) %></strong></span>
|
||||
<% } %>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<% if (s.commands.length) { %>
|
||||
<h3 class="sb-h">Top commands</h3>
|
||||
<div class="sb-pills"><% for (const c of s.commands) { %><span class="sb-pill txt"><code><%= c.command %></code> <strong><%= num(c.uses) %></strong></span><% } %></div>
|
||||
<% } %>
|
||||
|
||||
<% if (s.rewards.length) { %>
|
||||
<h3 class="sb-h">Rewards and Power-ups</h3>
|
||||
<div class="sb-pills"><% for (const x of s.rewards) { %><span class="sb-pill txt"><%= x.item %> <strong><%= num(x.uses) %></strong></span><% } %></div>
|
||||
<% } %>
|
||||
<% } %>
|
||||
|
||||
<script>
|
||||
// chart hover tooltips (bars, viewer dots, title-change markers)
|
||||
window.sbHoverTips = function (scope) {
|
||||
(scope ? [scope] : document.querySelectorAll('.sb-chart')).forEach(ch => {
|
||||
const tip = ch.querySelector('.sb-tip');
|
||||
if (!tip) return;
|
||||
ch.querySelectorAll('.hit').forEach(h => {
|
||||
h.addEventListener('mouseenter', () => { tip.textContent = h.dataset.tip; tip.style.display = 'block'; });
|
||||
h.addEventListener('mousemove', e => { const r = ch.getBoundingClientRect(); tip.style.left = (e.clientX - r.left + 12) + 'px'; tip.style.top = (e.clientY - r.top - 28) + 'px'; });
|
||||
h.addEventListener('mouseleave', () => { tip.style.display = 'none'; });
|
||||
});
|
||||
});
|
||||
};
|
||||
window.sbHoverTips();
|
||||
</script>
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
<h2>Actions</h2>
|
||||
<p><small>Map Twitch events to sounds, videos, or on-screen alerts.</small></p>
|
||||
|
||||
<details>
|
||||
<summary>Add new action</summary>
|
||||
<form method="POST" action="/actions" style="margin-top:1rem;">
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
|
||||
<label>Name <input type="text" name="name" required placeholder="e.g. Sub sound"></label>
|
||||
<label>
|
||||
Event type
|
||||
<select name="event_type" required>
|
||||
<option value="sub">Sub</option>
|
||||
<option value="gift_sub">Gift sub</option>
|
||||
<option value="bits">Bits</option>
|
||||
<option value="channel_points">Channel points</option>
|
||||
<option value="command">Chat command</option>
|
||||
<option value="follow">Follow</option>
|
||||
<option value="raid">Raid</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Event detail <small>(tier / min bits / command name / reward ID)</small>
|
||||
<input type="text" name="event_detail" placeholder="Optional">
|
||||
</label>
|
||||
<label>
|
||||
Action type
|
||||
<select name="action_type" required>
|
||||
<option value="sound">Sound</option>
|
||||
<option value="video">Video</option>
|
||||
<option value="alert">Alert text</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Media file
|
||||
<select name="media_file_id">
|
||||
<option value="">— none —</option>
|
||||
<% for (const f of media) { %>
|
||||
<option value="<%= f.id %>"><%= f.original_name %> (<%= f.media_type %>)</option>
|
||||
<% } %>
|
||||
</select>
|
||||
</label>
|
||||
<label>Alert text <input type="text" name="alert_text" placeholder="{username} just subbed!"></label>
|
||||
<label>Cooldown (seconds) <input type="number" name="cooldown_seconds" value="0" min="0"></label>
|
||||
</div>
|
||||
<button type="submit">Add action</button>
|
||||
</form>
|
||||
</details>
|
||||
|
||||
<% if (actions.length === 0) { %>
|
||||
<p><em>No actions yet.</em></p>
|
||||
<% } else { %>
|
||||
<figure>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Event</th>
|
||||
<th>Detail</th>
|
||||
<th>Action</th>
|
||||
<th>Cooldown</th>
|
||||
<th>Status</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% for (const a of actions) { %>
|
||||
<tr>
|
||||
<td><%= a.name %></td>
|
||||
<td><code><%= a.event_type %></code></td>
|
||||
<td><%= a.event_detail || '—' %></td>
|
||||
<td><code><%= a.action_type %></code></td>
|
||||
<td><%= a.cooldown_seconds %>s</td>
|
||||
<td>
|
||||
<span class="badge <%= a.enabled ? 'badge-green' : 'badge-grey' %>">
|
||||
<%= a.enabled ? 'on' : 'off' %>
|
||||
</span>
|
||||
</td>
|
||||
<td style="display:flex; gap:0.5rem;">
|
||||
<form method="POST" action="/actions/<%= a.id %>/test"><button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem;">Test</button></form>
|
||||
<form method="POST" action="/actions/<%= a.id %>/toggle"><button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem;"><%= a.enabled ? 'Disable' : 'Enable' %></button></form>
|
||||
<form method="POST" action="/actions/<%= a.id %>/delete"><button type="button" data-confirm class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem; color:#f88;">Delete</button></form>
|
||||
</td>
|
||||
</tr>
|
||||
<% } %>
|
||||
</tbody>
|
||||
</table>
|
||||
</figure>
|
||||
<% } %>
|
||||
133
views/alerts_preview.ejs
Normal file
133
views/alerts_preview.ejs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
<!doctype html>
|
||||
<%#
|
||||
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).
|
||||
%>
|
||||
<html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Alert preview</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Caveat:wght@700&family=Nunito:wght@700;800;900&display=block">
|
||||
<% for (const f of ['card', 'polaroid', 'cassette', 'fx']) { %><link rel="stylesheet" href="<%= base %><%= f %>.css"><% } %>
|
||||
<style>
|
||||
* { box-sizing:border-box; }
|
||||
html, body { margin:0; height:100%; background:#101014; color:#f1edf7; font-family:'Nunito', system-ui, sans-serif; }
|
||||
.wrap { display:grid; grid-template-columns:minmax(0, 1fr) 380px; height:100vh; }
|
||||
@media (max-width: 1000px) { .wrap { grid-template-columns:1fr; height:auto; } }
|
||||
.viewport { position:relative; overflow:hidden; display:grid; place-items:center; padding:16px; }
|
||||
.stage-box { position:relative; width:100%; aspect-ratio:16 / 9; max-height:calc(100vh - 32px); }
|
||||
#stage { position:absolute; left:0; top:0; width:1920px; height:1080px; transform-origin:0 0; overflow:hidden; border-radius:10px;
|
||||
background:var(--bg); box-shadow:0 10px 40px rgba(0,0,0,.5); }
|
||||
/* the alert elements are position:fixed in the overlay; inside the scaled stage they must follow the stage */
|
||||
#stage { contain:layout paint; transform-style:flat; }
|
||||
.bg-game { --bg:radial-gradient(1200px 700px at 30% 40%, #3a5f4f, #16261f 70%), #16261f; }
|
||||
.bg-dark { --bg:#1b1b22; }
|
||||
.bg-light { --bg:#e9e6ef; }
|
||||
.bg-check { --bg:repeating-conic-gradient(#2a2a33 0 25%, #22222a 0 50%) 0 0 / 40px 40px; }
|
||||
.scene { position:absolute; inset:0; pointer-events:none; }
|
||||
.scene .cam { position:absolute; right:60px; bottom:60px; width:480px; height:270px; border-radius:18px; background:rgba(255,255,255,.08);
|
||||
border:2px dashed rgba(255,255,255,.18); display:grid; place-items:center; color:rgba(255,255,255,.35); font:800 26px Nunito; }
|
||||
.panel { overflow:auto; background:#191720; border-left:1px solid #2b2836; padding:16px 18px 30px; }
|
||||
.panel h1 { font-size:20px; margin:0 0 4px; }
|
||||
.note { font-size:13px; color:#b9b0cc; margin:0 0 10px; line-height:1.4; }
|
||||
h3 { font-size:12px; letter-spacing:.12em; color:#b9a3ec; margin:16px 0 7px; text-transform:uppercase; }
|
||||
.row { display:flex; flex-wrap:wrap; gap:6px; }
|
||||
button { font:800 13px 'Nunito'; border:0; border-radius:14px; padding:6px 12px; cursor:pointer; background:#2c2838; color:#f1edf7; }
|
||||
button:hover { background:#3b3550; }
|
||||
button.on { background:#9146ff; color:#fff; }
|
||||
button.alt { background:#efe6ff; color:#2a1d40; }
|
||||
.colors { display:flex; gap:12px; flex-wrap:wrap; font-size:13px; align-items:center; }
|
||||
.colors label { display:flex; gap:6px; align-items:center; }
|
||||
.colors input { width:34px; height:26px; border:0; padding:0; background:none; }
|
||||
#log { font:700 12px monospace; color:#c9ffd8; margin-top:14px; min-height:1.2em; }
|
||||
</style></head><body>
|
||||
<div class="wrap">
|
||||
<div class="viewport"><div class="stage-box" id="box"><div id="stage" class="bg-game"><div class="scene"><div class="cam">camera</div></div></div></div></div>
|
||||
<div class="panel">
|
||||
<h1>Alert preview</h1>
|
||||
<p class="note">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.</p>
|
||||
|
||||
<h3>Look</h3>
|
||||
<div class="row" id="themes"><% for (const [k, t] of Object.entries(themes)) { %><button data-theme="<%= k %>"><%= t.label %></button><% } %></div>
|
||||
<div class="row" style="margin-top:6px;" id="styles">
|
||||
<button data-style="card">Alerts: Card</button><button data-style="polaroid">Alerts: Polaroid</button>
|
||||
</div>
|
||||
<div class="colors" style="margin-top:8px;">
|
||||
<label><input type="color" data-c="accent"> accent</label><label><input type="color" data-c="bg"> card</label><label><input type="color" data-c="text"> text</label>
|
||||
</div>
|
||||
|
||||
<h3>Background</h3>
|
||||
<div class="row" id="bgs"><button data-bg="bg-game" class="on">Game</button><button data-bg="bg-dark">Dark</button><button data-bg="bg-light">Light</button><button data-bg="bg-check">Transparent</button></div>
|
||||
|
||||
<h3>Follows and subs</h3>
|
||||
<div class="row"><% 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']]) { %><button data-k="<%= k %>"><%= l %></button><% } %></div>
|
||||
<h3>Bits, tips, raids</h3>
|
||||
<div class="row"><% 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']]) { %><button data-k="<%= k %>"><%= l %></button><% } %></div>
|
||||
<h3>Hype Train</h3>
|
||||
<div class="row"><% for (const [k, l] of [['hype-begin', 'Start'], ['hype-level', 'Level up'], ['hype-end', 'End'], ['hype-golden', 'Golden Kappa']]) { %><button data-k="<%= k %>"><%= l %></button><% } %></div>
|
||||
<h3>Redeems</h3>
|
||||
<div class="row">
|
||||
<button data-r="card">Card</button><button data-r="cassette">Cassette</button><button data-r="cassette-rare">Cassette rare</button><button data-r="cassette-ultra">Cassette ultra rare</button>
|
||||
<button data-r="tts">Read aloud</button><button data-r="message">Highlight message</button><button data-r="emote">Gigantify emote</button><button data-r="rain">Celebration</button>
|
||||
</div>
|
||||
<h3>Queue</h3>
|
||||
<div class="row"><button data-queue class="alt">4 alerts at once</button><button data-reset>Stop</button></div>
|
||||
<div id="log">ready</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
window.ALERTS_BASE = <%- JSON.stringify(base) %>;
|
||||
const THEMES = <%- JSON.stringify(Object.fromEntries(Object.entries(themes).map(([k, t]) => [k, t.theme]))).replace(/</g, '\\u003c') %>;
|
||||
window.S = { alert_theme: JSON.parse(JSON.stringify(THEMES[<%- JSON.stringify(start) %>])) };
|
||||
</script>
|
||||
<% for (const f of ['card', 'cassette', 'fx', 'polaroid']) { %><script src="<%= base %><%= f %>.js"></script><% } %>
|
||||
<script>
|
||||
const SAMPLES = <%- JSON.stringify(samples).replace(/</g, '\\u003c') %>;
|
||||
const REDEEMS = {
|
||||
card: { style: 'card', user: 'LurkingLynx', reward: 'Hydrate!', variation: 'Water break', rarity: 'common', caption: 'redeemed it! ♡' },
|
||||
cassette: { style: 'cassette', user: 'PixelPotato', reward: 'Posture check', variation: 'Sit up straight', rarity: 'common', caption: 'redeemed it! ♡' },
|
||||
'cassette-rare': { style: 'cassette', user: 'ChickenWhisperer', reward: 'Random sound', variation: 'Chicken dance', rarity: 'rare', caption: 'redeemed it! ♡' },
|
||||
'cassette-ultra': { style: 'cassette', user: 'BobTheBuilder99', reward: 'Random sound', variation: 'The legendary one', rarity: 'ultra_rare', caption: 'redeemed it! ♡' },
|
||||
tts: { style: 'tts', user: 'Chatty', reward: 'Read my message', variation: 'Robot voice', caption: 'says:', input: 'hello there streamer, that was a very nice shot and I was totally not camping that corner' },
|
||||
message: { style: 'message', user: 'PixelPotato', reward: 'Highlight my message', caption: 'highlighted:', input: 'this stream is the coziest place on the internet' },
|
||||
emote: { style: 'emote', user: 'LurkingLynx', reward: 'Gigantify an Emote', caption: 'gigantified an emote!', emote: 'https://static-cdn.jtvnw.net/emoticons/v2/25/default/dark/3.0' },
|
||||
rain: { style: 'emote_rain', user: 'BobTheBuilder99', reward: 'On-Screen Celebration', caption: 'is celebrating!', emote: 'https://static-cdn.jtvnw.net/emoticons/v2/25/default/dark/3.0' },
|
||||
};
|
||||
const log = t => { document.getElementById('log').textContent = t; };
|
||||
|
||||
// scale the 1920x1080 stage to its box; fixed-position alerts are kept inside it by moving them into the stage
|
||||
const stage = document.getElementById('stage'), box = document.getElementById('box');
|
||||
const fit = () => { stage.style.transform = `scale(${box.clientWidth / 1920})`; };
|
||||
new ResizeObserver(fit).observe(box); fit();
|
||||
new MutationObserver(() => {
|
||||
for (const id of ['card-alert', 'polaroid-alert', 'cassette-alert', 'fx-alert']) {
|
||||
const el = document.getElementById(id);
|
||||
if (el && el.parentElement !== stage) stage.appendChild(el);
|
||||
}
|
||||
}).observe(document.body, { childList: true });
|
||||
|
||||
const mark = (sel, attr, v) => document.querySelectorAll(sel).forEach(b => b.classList.toggle('on', b.dataset[attr] === v));
|
||||
function useTheme(k) {
|
||||
window.S.alert_theme = JSON.parse(JSON.stringify(THEMES[k]));
|
||||
mark('#themes button', 'theme', k); mark('#styles button', 'style', window.S.alert_theme.style);
|
||||
document.querySelectorAll('[data-c]').forEach(i => { i.value = window.S.alert_theme.card[i.dataset.c]; });
|
||||
PolaroidAlerts.reset(); log('look: ' + document.querySelector(`[data-theme="${k}"]`).textContent);
|
||||
}
|
||||
document.querySelectorAll('[data-theme]').forEach(b => b.addEventListener('click', () => useTheme(b.dataset.theme)));
|
||||
document.querySelectorAll('[data-style]').forEach(b => b.addEventListener('click', () => { window.S.alert_theme.style = b.dataset.style; mark('#styles button', 'style', b.dataset.style); }));
|
||||
document.querySelectorAll('[data-c]').forEach(i => i.addEventListener('input', () => { window.S.alert_theme.card[i.dataset.c] = i.value; }));
|
||||
document.querySelectorAll('[data-bg]').forEach(b => b.addEventListener('click', () => { stage.className = b.dataset.bg; mark('#bgs button', 'bg', b.dataset.bg); }));
|
||||
document.querySelectorAll('[data-k]').forEach(b => b.addEventListener('click', () => { PolaroidAlerts.playTest({ ...SAMPLES[b.dataset.k], test: true }); log(b.textContent); }));
|
||||
document.querySelectorAll('[data-r]').forEach(b => b.addEventListener('click', () => {
|
||||
const r = REDEEMS[b.dataset.r];
|
||||
PolaroidAlerts.playTest({ type: 'redeem', kind: 'reward', key: 'preview', volume: .8, polaroid: true, test: true, ...r }); log('redeem: ' + b.textContent);
|
||||
}));
|
||||
document.querySelector('[data-queue]').addEventListener('click', () => {
|
||||
PolaroidAlerts.reset(); ['follow', 'bits-120', 'gift-10', 'hype-level'].forEach(k => PolaroidAlerts.play(SAMPLES[k]));
|
||||
log('queued: follow, 120 bits, gift 10, hype level');
|
||||
});
|
||||
document.querySelector('[data-reset]').addEventListener('click', () => { PolaroidAlerts.reset(); log('stopped'); });
|
||||
useTheme(<%- JSON.stringify(start) %>);
|
||||
</script>
|
||||
</body></html>
|
||||
233
views/alerts_setup.ejs
Normal file
233
views/alerts_setup.ejs
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
<% const J = x => JSON.stringify(x).replace(/</g, '\\u003c'); %>
|
||||
<style>
|
||||
.al-grid { display:grid; grid-template-columns:minmax(150px, 200px) minmax(0, 1fr) minmax(0, 1fr) auto; gap:.5rem 1rem; align-items:center; }
|
||||
.al-grid .hd { font-size:.75rem; color:var(--pico-muted-color); text-transform:uppercase; letter-spacing:.06em; }
|
||||
.al-grid select { margin:0; font-size:.88rem; padding:.3rem .5rem; height:auto; }
|
||||
.al-name { font-weight:600; font-size:.92rem; }
|
||||
.al-name small { display:block; font-weight:400; color:var(--pico-muted-color); font-size:.78rem; }
|
||||
.pk { display:flex; align-items:center; gap:.4rem; }
|
||||
.pk img { width:34px; height:34px; object-fit:contain; border-radius:6px; background:rgba(255,255,255,.06); flex:none; }
|
||||
.pk img[src=""] { visibility:hidden; }
|
||||
.pk button, .btn-xs { width:auto; margin:0; padding:.2rem .55rem; font-size:.78rem; }
|
||||
@media (max-width: 900px) { .al-grid { grid-template-columns:1fr 1fr; } .al-grid .hd { display:none; } }
|
||||
.set-row > .seg { justify-self:start; }
|
||||
.set-row.stack { grid-template-columns:1fr; }
|
||||
.tiers .pk select { min-width:200px; }
|
||||
.seg { display:inline-flex; border:1px solid var(--pico-muted-border-color); border-radius:8px; overflow:hidden; }
|
||||
.seg label { margin:0; padding:.35rem .9rem; cursor:pointer; font-size:.88rem; border-left:1px solid var(--pico-muted-border-color); }
|
||||
.seg label:first-child { border-left:0; }
|
||||
.seg input { display:none; }
|
||||
.seg label:has(input:checked) { background:var(--pico-primary-background); color:#fff; }
|
||||
.tiers { width:100%; font-size:.86rem; }
|
||||
.tiers td, .tiers th { padding:.3rem .4rem; vertical-align:middle; }
|
||||
.tiers input, .tiers select { margin:0; padding:.25rem .4rem; font-size:.85rem; height:auto; }
|
||||
.savebar-al { 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); z-index:5; }
|
||||
.savebar-al button { width:auto; margin:0; }
|
||||
.dirty { color:#e6b800; font-weight:600; }
|
||||
.backs { display:flex; flex-wrap:wrap; gap:.4rem; align-items:center; }
|
||||
.backs .b { display:flex; align-items:center; gap:.2rem; border:1px solid var(--pico-muted-border-color); border-radius:8px; padding:.15rem .3rem; }
|
||||
.backs .b img { width:30px; height:30px; object-fit:contain; }
|
||||
.colors { display:flex; gap:1rem; flex-wrap:wrap; align-items:center; }
|
||||
.colors label { display:flex; gap:.4rem; align-items:center; margin:0; font-size:.88rem; }
|
||||
.colors input[type=color] { width:2.6rem; height:2rem; padding:0; margin:0; }
|
||||
.hint { color:var(--pico-muted-color); font-size:.8rem; }
|
||||
</style>
|
||||
|
||||
<h2 class="set-h">Alerts</h2>
|
||||
<p class="set-intro"><a href="/actions/alerts/preview" target="_blank" rel="noopener" style="float:right; margin-left:1rem;">Open the preview ↗</a>What follows, subs, gifts, raids, bits, tips and the Hype Train look and sound like. Pictures and sounds come from
|
||||
<a href="/media">Media</a> (upload your own there). Changes reach OBS as soon as you save; use Test to see them.</p>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Style</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Alerts<small>Follows, subs, gifts, raids, bits, tips, Hype Train.</small></div>
|
||||
<span class="seg"><% for (const [v, l] of [['card', 'Card'], ['polaroid', 'Polaroid']]) { %><label><input type="radio" name="style" value="<%= v %>"><%= l %></label><% } %></span>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">New redeem variations<small>Look of variations you add on Redeems (each variation can still be changed there).</small></div>
|
||||
<span class="seg"><% for (const [v, l] of [['card', 'Card'], ['cassette', 'Cassette']]) { %><label><input type="radio" name="redeemStyle" value="<%= v %>"><%= l %></label><% } %></span>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Read-aloud redeems<small>Variations with a TTS voice.</small></div>
|
||||
<span class="seg"><% for (const [v, l] of [['card', 'Card'], ['letter', 'Letter']]) { %><label><input type="radio" name="ttsStyle" value="<%= v %>"><%= l %></label><% } %></span>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Card colours</div>
|
||||
<div class="colors">
|
||||
<label><input type="color" data-k="card.accent"> accent</label>
|
||||
<label><input type="color" data-k="card.bg"> background</label>
|
||||
<label><input type="color" data-k="card.text"> text</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Volume<small>Alert sounds (a bits tier can have its own).</small></div>
|
||||
<div class="set-inline"><input type="range" min="0" max="1" step="0.05" data-k="volume" style="max-width:240px;"><span id="vol-out" class="hint"></span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Events</h3>
|
||||
<div class="al-grid" id="events">
|
||||
<span class="hd">Event</span><span class="hd">Picture</span><span class="hd">Sound</span><span class="hd"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Bits</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">No alert under</div>
|
||||
<div class="set-inline"><input type="number" min="1" data-k="bitsMin" style="max-width:7rem;"> <span class="hint">bits</span></div>
|
||||
</div>
|
||||
<div class="set-row stack">
|
||||
<div class="lbl">Tiers<small>The highest tier the cheer reaches is used.</small></div>
|
||||
<div>
|
||||
<div style="overflow-x:auto;"><table class="tiers"><thead><tr><th>From</th><th>Picture</th><th>Sound</th><th>Volume</th><th>Badge</th><th>Hearts</th><th></th></tr></thead><tbody id="tiers"></tbody></table></div>
|
||||
<div class="set-inline"><button type="button" class="outline btn-xs" id="tier-add">+ Add tier</button>
|
||||
<button type="button" class="outline btn-xs" data-test="bits-120">Test 120 bits</button><button type="button" class="outline btn-xs" data-test="bits-500">Test 500 bits</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Extras</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Corner sticker<small>Polaroid: sticker on the photo's corner (and the extra ones for big alerts).</small></div>
|
||||
<div class="pk" data-pick="heart" data-type="image"></div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Photos behind<small>Polaroid: photos fanned out behind multi-month subs, gift bombs and raids.</small></div>
|
||||
<div class="backs" id="backs"></div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Raid send-off picture<small>When the raided channel has no picture.</small></div>
|
||||
<div class="pk" data-pick="raidFallback" data-type="image"></div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Default redeem sticker<small>Card and Cassette redeems whose variation has no picture.</small></div>
|
||||
<div class="pk" data-pick="defaultSticker" data-type="image"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="savebar-al">
|
||||
<button type="button" id="save">Save</button>
|
||||
<span id="state" class="hint">No changes</span>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(() => {
|
||||
let T = <%- J(theme) %>;
|
||||
const IMAGES = <%- J(images.map(m => ({ url: m.url, label: m.label }))) %>;
|
||||
const SOUNDS = <%- J(sounds.map(m => ({ url: m.url, label: m.label }))) %>;
|
||||
const EVENTS = [
|
||||
['follow', 'Follow', '', 'follow', 'follow'], ['sub', 'New sub', '', 'sub', 'sub-new'], ['resub', 'Resub', 'sound: same as New sub', null, 'sub-resub'],
|
||||
['prime', 'Prime sub', 'sound: same as New sub', null, 'sub-prime'], ['gift', 'Gift subs', '', 'gift', 'gift-10'],
|
||||
['streak', 'Watch streak', '', 'streak', 'streak'], ['raid', 'Raid', '', 'raid', 'raid'], ['tip', 'Tip', 'StreamElements', 'tip', 'tip-25'],
|
||||
['hype', 'Hype Train', 'start sound', 'hypeBegin', 'hype-begin'],
|
||||
[null, 'Hype Train level up', '', 'hypeLevel', 'hype-level'], [null, 'Hype Train end', '', 'hypeEnd', 'hype-end'],
|
||||
];
|
||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const get = k => k.split('.').reduce((o, p) => o?.[p], T);
|
||||
const set = (k, v) => { const ps = k.split('.'); let o = T; ps.slice(0, -1).forEach(p => { o = o[p] = o[p] || {}; }); o[ps.at(-1)] = v; dirty(); };
|
||||
const state = document.getElementById('state');
|
||||
const dirty = () => { state.textContent = 'Unsaved changes'; state.className = 'dirty'; };
|
||||
|
||||
// a picker: select from the media library (+ thumbnail / play button); onChange(url)
|
||||
let audio = null;
|
||||
function picker(type, value, onChange) {
|
||||
const list = type === 'image' ? IMAGES : SOUNDS;
|
||||
const w = document.createElement('span'); w.className = 'pk';
|
||||
const opts = ['<option value="">— none —</option>', ...list.map(m => `<option value="${esc(m.url)}">${esc(m.label)}</option>`)];
|
||||
if (value && !list.some(m => m.url === value)) opts.push(`<option value="${esc(value)}">${esc(value.split('/').pop())} (missing)</option>`);
|
||||
w.innerHTML = (type === 'image' ? `<img src="${esc(value || '')}" alt="">` : '') + `<select>${opts.join('')}</select>` + (type === 'audio' ? '<button type="button" class="outline" title="Play">▶</button>' : '');
|
||||
const sel = w.querySelector('select'); sel.value = value || '';
|
||||
sel.addEventListener('change', () => { if (type === 'image') w.querySelector('img').src = sel.value; onChange(sel.value); });
|
||||
if (type === 'audio') w.querySelector('button').addEventListener('click', () => { audio?.pause(); if (sel.value) { audio = new Audio(sel.value); audio.volume = T.volume ?? .8; audio.play(); } });
|
||||
return w;
|
||||
}
|
||||
const testBtn = key => { const b = document.createElement('button'); b.type = 'button'; b.className = 'outline btn-xs'; b.textContent = 'Test'; b.dataset.test = key; return b; };
|
||||
|
||||
function render() {
|
||||
// style radios, colours, numbers
|
||||
for (const n of ['style', 'redeemStyle', 'ttsStyle']) document.querySelectorAll(`input[name=${n}]`).forEach(r => { r.checked = r.value === T[n]; });
|
||||
document.querySelectorAll('[data-k]').forEach(i => { i.value = get(i.dataset.k) ?? ''; });
|
||||
document.getElementById('vol-out').textContent = Math.round((T.volume ?? .8) * 100) + '%';
|
||||
// events grid
|
||||
const g = document.getElementById('events');
|
||||
g.querySelectorAll(':scope > :not(.hd)').forEach(x => x.remove());
|
||||
for (const [artKey, label, sub, soundKey, test] of EVENTS) {
|
||||
const name = document.createElement('div'); name.className = 'al-name'; name.innerHTML = esc(label) + (sub ? `<small>${esc(sub)}</small>` : '');
|
||||
g.append(name,
|
||||
artKey ? picker('image', T.art[artKey], v => { T.art[artKey] = v; dirty(); }) : document.createElement('span'),
|
||||
soundKey ? picker('audio', T.sounds[soundKey], v => { T.sounds[soundKey] = v; dirty(); }) : Object.assign(document.createElement('span'), { className: 'hint', textContent: '' }),
|
||||
testBtn(test));
|
||||
}
|
||||
// bits tiers
|
||||
const tb = document.getElementById('tiers'); tb.innerHTML = '';
|
||||
T.bitsTiers.forEach((t, i) => {
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = `<td><input type="number" min="1" value="${t.min}" style="width:6rem"></td><td></td><td></td>
|
||||
<td><input type="number" min="0" max="1" step="0.05" value="${t.volume ?? ''}" placeholder="default" style="width:6rem"></td>
|
||||
<td><input type="color" value="${esc(t.badge || '#8a8aa8')}" style="width:2.4rem; height:1.8rem; padding:0"></td>
|
||||
<td><select style="width:4rem">${[0, 1, 2, 3].map(h => `<option ${h === t.hearts ? 'selected' : ''}>${h}</option>`).join('')}</select></td>
|
||||
<td><button type="button" class="outline btn-xs" title="Remove tier">✕</button></td>`;
|
||||
tr.children[1].append(picker('image', t.art, v => { t.art = v; dirty(); }));
|
||||
tr.children[2].append(picker('audio', t.sound, v => { t.sound = v; dirty(); }));
|
||||
const [min, , , vol, badge, hearts] = [...tr.children].map(td => td.querySelector('input, select'));
|
||||
min.addEventListener('input', () => { t.min = +min.value || 1; dirty(); });
|
||||
vol.addEventListener('input', () => { t.volume = vol.value === '' ? null : +vol.value; dirty(); });
|
||||
badge.addEventListener('input', () => { t.badge = badge.value; dirty(); });
|
||||
hearts.addEventListener('change', () => { t.hearts = +hearts.value; dirty(); });
|
||||
tr.querySelector('button').addEventListener('click', () => { T.bitsTiers.splice(i, 1); dirty(); render(); });
|
||||
tb.append(tr);
|
||||
});
|
||||
// single pickers
|
||||
document.querySelectorAll('[data-pick]').forEach(el => {
|
||||
const key = el.dataset.pick, type = el.dataset.type;
|
||||
const w = picker(type, T[key], v => { T[key] = v; dirty(); });
|
||||
w.dataset.pick = key; w.dataset.type = type;
|
||||
el.replaceWith(w);
|
||||
});
|
||||
// photos behind
|
||||
const bk = document.getElementById('backs'); bk.innerHTML = '';
|
||||
T.back.forEach((u, i) => {
|
||||
const b = document.createElement('span'); b.className = 'b';
|
||||
b.innerHTML = `<img src="${esc(u)}" alt="" title="${esc(u.split('/').pop())}"><button type="button" class="outline btn-xs" title="Remove">✕</button>`;
|
||||
b.querySelector('button').addEventListener('click', () => { T.back.splice(i, 1); dirty(); render(); });
|
||||
bk.append(b);
|
||||
});
|
||||
const add = picker('image', '', v => { if (v) { T.back.push(v); dirty(); render(); } });
|
||||
add.querySelector('select').options[0].textContent = '+ add a photo';
|
||||
bk.append(add);
|
||||
}
|
||||
|
||||
document.querySelectorAll('input[name=style], input[name=redeemStyle], input[name=ttsStyle]').forEach(r => r.addEventListener('change', () => { T[r.name] = r.value; dirty(); }));
|
||||
document.querySelectorAll('[data-k]').forEach(i => i.addEventListener('input', () => {
|
||||
set(i.dataset.k, i.type === 'number' || i.type === 'range' ? +i.value : i.value);
|
||||
if (i.dataset.k === 'volume') document.getElementById('vol-out').textContent = Math.round(i.value * 100) + '%';
|
||||
}));
|
||||
document.getElementById('tier-add').addEventListener('click', () => { T.bitsTiers.push({ min: 1, art: '', sound: '', volume: null, badge: '#8a8aa8', hearts: 0 }); dirty(); render(); });
|
||||
|
||||
async function save() {
|
||||
state.textContent = 'Saving…'; state.className = 'hint';
|
||||
try {
|
||||
const r = await fetch('/actions/alerts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(T) });
|
||||
const j = await r.json();
|
||||
if (!j.ok) throw new Error(j.error || r.status);
|
||||
T = j.theme; render();
|
||||
state.textContent = 'Saved'; state.className = 'hint';
|
||||
} catch (e) { state.textContent = 'Save failed: ' + e.message; state.className = 'dirty'; }
|
||||
}
|
||||
document.getElementById('save').addEventListener('click', save);
|
||||
document.addEventListener('keydown', e => { if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); save(); } });
|
||||
window.addEventListener('beforeunload', e => { if (state.classList.contains('dirty')) { e.preventDefault(); e.returnValue = ''; } });
|
||||
// test buttons: save first, then play the sample on the overlay
|
||||
document.addEventListener('click', async e => {
|
||||
const b = e.target.closest('[data-test]'); if (!b) return;
|
||||
if (state.classList.contains('dirty')) await save();
|
||||
const r = await fetch('/alerts/test/' + encodeURIComponent(b.dataset.test), { method: 'POST' });
|
||||
const l = b.textContent; b.textContent = r.ok ? 'Sent' : 'Failed'; setTimeout(() => { b.textContent = l; }, 1200);
|
||||
});
|
||||
render();
|
||||
})();
|
||||
</script>
|
||||
|
|
@ -1,22 +1,20 @@
|
|||
<h2>Dashboard</h2>
|
||||
|
||||
<div style="display:flex; gap:1rem; margin-bottom:1.5rem; flex-wrap:wrap;">
|
||||
<div>
|
||||
<strong>Channel:</strong>
|
||||
<%= settings.channel || '<em>not set</em>' %>
|
||||
</div>
|
||||
<div>
|
||||
<strong>OBS browser sources</strong> (1920×1080):<br>
|
||||
<small>Chat only, set its audio to <em>Monitor Only (mute output)</em> so chat sounds stay off stream:</small><br>
|
||||
<code><%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat</code><br>
|
||||
<small>Everything except chat (alerts, redeems, poll, Hype Train bar, raid send-off):</small><br>
|
||||
<code><%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=nochat</code><br>
|
||||
<small>Chat somewhere else, e.g. in the Intermission panel (left,top,width,height in px of the 1920×1080 page; <em>up</em> = newest at the bottom):</small><br>
|
||||
<code><%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat&chat=130,640,700,360&chatflow=up</code><br>
|
||||
<small title="parts: chat, alerts, poll, hypebar, raid. List them (?parts=chat,raid) or exclude with no… (?parts=nochat,noraid). No ?parts = everything.">
|
||||
Other combinations: hover for help · everything in one source: <code>/overlay/<%= settings.overlay_id %></code></small>
|
||||
</div>
|
||||
<div class="dash-status">
|
||||
<a href="/settings/connections" title="Settings → Connections">
|
||||
Twitch <% if (eventsubStatus.connected) { %><span class="badge badge-green">connected</span><% } else if (eventsubStatus.running) { %><span class="badge badge-grey">connecting…</span><% } else { %><span class="badge badge-red">not running</span><% } %>
|
||||
</a>
|
||||
<a href="/settings/connections" title="Settings → Connections">
|
||||
StreamElements <% if (!seStatus.enabled) { %><span class="badge badge-grey">off</span><% } else if (seStatus.subscribed) { %><span class="badge badge-green">connected</span><% } else { %><span class="badge badge-grey">connecting…</span><% } %>
|
||||
</a>
|
||||
<a href="/settings/obs" title="Browser source links for OBS">OBS links →</a>
|
||||
<% if (eventsubStatus.failed.length) { %><a href="/settings/connections" style="color:#f88">Some Twitch permissions are missing: log in again</a><% } %>
|
||||
</div>
|
||||
<style>
|
||||
.dash-status { display:flex; gap:1.4rem; flex-wrap:wrap; align-items:center; margin:0 0 1.4rem; padding:.6rem .9rem;
|
||||
border:1px solid var(--pico-muted-border-color); border-radius:12px; }
|
||||
.dash-status a { text-decoration:none; font-size:.92rem; }
|
||||
</style>
|
||||
|
||||
<div style="display:flex; gap:.8rem; align-items:center; margin-bottom:1.5rem;">
|
||||
<button type="button" id="skip-alert" class="outline" style="width:auto; margin:0;"
|
||||
|
|
@ -32,32 +30,6 @@
|
|||
});
|
||||
</script>
|
||||
|
||||
<h3>Twitch connection</h3>
|
||||
<p>
|
||||
<% if (eventsubStatus.connected) { %>
|
||||
<span class="badge badge-green">connected</span>
|
||||
<% } else if (eventsubStatus.running) { %>
|
||||
<span class="badge badge-grey">connecting…</span>
|
||||
<% } else { %>
|
||||
<span class="badge badge-grey">not running</span> (log in again to start)
|
||||
<% } %>
|
||||
<% if (eventsubStatus.subscribed.length) { %><br><small>Listening to: <%= eventsubStatus.subscribed.join(', ') %></small><% } %>
|
||||
<% if (eventsubStatus.failed.length) { %><br><small style="color:#c0392b">Failed: <%= eventsubStatus.failed.join(', ') %> (log out and in again if a permission is missing)</small><% } %>
|
||||
<% if (eventsubStatus.lastEventAt) { %><br><small>Last event: <%= eventsubStatus.lastEventAt %></small><% } %>
|
||||
</p>
|
||||
|
||||
<h3>StreamElements tips</h3>
|
||||
<p>
|
||||
<% if (!seStatus.enabled) { %>
|
||||
<span class="badge badge-grey">off</span> <small>set <code>SE_JWT</code> in <code>.env</code> (StreamElements dashboard → avatar → your channel → JWT token) and restart</small>
|
||||
<% } else if (seStatus.subscribed) { %>
|
||||
<span class="badge badge-green">connected</span><% if (seStatus.lastTipAt) { %> <small>last tip: <%= seStatus.lastTipAt %></small><% } %>
|
||||
<% } else { %>
|
||||
<span class="badge badge-grey">connecting…</span>
|
||||
<% } %>
|
||||
<% if (seStatus.error) { %><br><small style="color:#c0392b"><%= seStatus.error %></small><% } %>
|
||||
</p>
|
||||
|
||||
<h3>Raid</h3>
|
||||
<p><small>Start the raid here and the send-off card stays on stream (silent) until the raid happens. Same as Twitch's Raid button.</small></p>
|
||||
<div style="display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-bottom:.4rem;">
|
||||
|
|
@ -82,7 +54,7 @@
|
|||
</script>
|
||||
|
||||
<h3>Test alerts</h3>
|
||||
<p><small>Sends a sample alert to the overlay (OBS). Not logged, no actions fired.</small></p>
|
||||
<p><small>Sends a sample alert to the overlay (OBS). Not logged, no actions fired. Looks and sounds: <a href="/actions/alerts">Actions → Alerts</a>.</small></p>
|
||||
<div id="test-alerts" style="display:flex; flex-wrap:wrap; gap:.4rem; margin-bottom:.5rem;">
|
||||
<% for (const key of testKeys) { %>
|
||||
<button type="button" class="outline" data-key="<%= key %>" style="width:auto; padding:.3rem .8rem; margin:0;"><%= key %></button>
|
||||
|
|
|
|||
|
|
@ -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; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
|
@ -22,28 +61,56 @@
|
|||
<li><a class="nav-brand" href="/">HeyStreamer</a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="/">Dashboard</a></li>
|
||||
<li><a href="/redeems">Redeems</a></li>
|
||||
<li><a href="/tts">TTS</a></li>
|
||||
<li><a href="/actions">Actions</a></li>
|
||||
<li><a href="/media">Media</a></li>
|
||||
<li><a href="/stats">Stats</a></li>
|
||||
<li><a href="/settings">Settings</a></li>
|
||||
<% const top = locals.sidebar ? locals.sidebar.name : ''; %>
|
||||
<li><a href="/" class="<%= !top && locals.navActive === 'dashboard' ? 'on' : '' %>">Dashboard</a></li>
|
||||
<li><a href="/redeems" class="<%= top === 'actions' ? 'on' : '' %>">Actions</a></li>
|
||||
<li><a href="/stats" class="<%= locals.navActive === 'stats' ? 'on' : '' %>">Stats</a></li>
|
||||
<li><a href="/settings" class="<%= top === 'settings' ? 'on' : '' %>">Settings</a></li>
|
||||
<% if (locals.user) { %>
|
||||
<li><a href="/auth/logout">Logout (<%= user.login %>)</a></li>
|
||||
<% } %>
|
||||
</ul>
|
||||
</nav>
|
||||
<main class="container">
|
||||
<main class="container<%= locals.sidebar ? '-fluid with-side' : '' %>">
|
||||
<% if (locals.sidebar) { %>
|
||||
<div class="shell">
|
||||
<aside class="side">
|
||||
<div class="side-title"><%= sidebar.title %></div>
|
||||
<% for (const i of sidebar.items) { %>
|
||||
<a href="<%= i.href %>" class="<%= i.on ? 'on' : '' %>"<% if (i.hint) { %> title="<%= i.hint %>"<% } %>><%= i.label %></a>
|
||||
<% } %>
|
||||
</aside>
|
||||
<section class="pane"><%- body %></section>
|
||||
</div>
|
||||
<% } else { %>
|
||||
<%- body %>
|
||||
<% } %>
|
||||
</main>
|
||||
<script>
|
||||
// eye buttons: <button data-reveal="#id"> shows / hides a blurred .secret element or a password input
|
||||
document.addEventListener('click', e => {
|
||||
const b = e.target.closest('[data-reveal]');
|
||||
if (!b) return;
|
||||
const t = document.querySelector(b.dataset.reveal);
|
||||
if (!t) return;
|
||||
const show = t.tagName === 'INPUT' ? t.type === 'password' : !t.classList.contains('shown');
|
||||
if (t.tagName === 'INPUT') t.type = show ? 'text' : 'password'; else t.classList.toggle('shown', show);
|
||||
b.textContent = show ? '🙈' : '👁'; b.title = show ? 'Hide' : 'Show';
|
||||
});
|
||||
// copy buttons: <button data-copy="text"> or data-copy-from="#id"
|
||||
document.addEventListener('click', e => {
|
||||
const b = e.target.closest('[data-copy],[data-copy-from]');
|
||||
if (!b) return;
|
||||
const text = b.dataset.copy ?? document.querySelector(b.dataset.copyFrom)?.textContent ?? '';
|
||||
navigator.clipboard?.writeText(text).then(() => { const l = b.textContent; b.textContent = 'Copied'; setTimeout(() => { b.textContent = l; }, 1200); });
|
||||
});
|
||||
// Two-click delete instead of a browser confirm() dialog: first click arms the button, second submits.
|
||||
document.addEventListener('click', e => {
|
||||
const b = e.target.closest('button[data-confirm]');
|
||||
if (!b) return;
|
||||
if (b.dataset.armed) { b.form.requestSubmit(); return; }
|
||||
b.dataset.armed = '1'; b.dataset.label = b.textContent; b.textContent = 'Really delete?';
|
||||
if (b.dataset.armed) { if (b.type !== 'submit') b.form.requestSubmit(); return; } // armed submit button: let it submit
|
||||
e.preventDefault();
|
||||
b.dataset.armed = '1'; b.dataset.label = b.textContent; b.textContent = b.dataset.confirm || 'Really delete?';
|
||||
b.style.fontWeight = '700';
|
||||
setTimeout(() => { delete b.dataset.armed; b.textContent = b.dataset.label; b.style.fontWeight = ''; }, 4000);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Caveat:wght@700&family=Nunito:wght@800;900&display=swap">
|
||||
<% const has = p => parts.includes(p); %>
|
||||
<% if (has('alerts')) { %>
|
||||
<link rel="stylesheet" href="/alerts/card.css?v=<%= boot %>">
|
||||
<link rel="stylesheet" href="/alerts/polaroid.css?v=<%= boot %>">
|
||||
<link rel="stylesheet" href="/alerts/cassette.css?v=<%= boot %>">
|
||||
<link rel="stylesheet" href="/alerts/fx.css?v=<%= boot %>">
|
||||
|
|
@ -81,6 +82,7 @@
|
|||
<script src="/vendor/tmi.min.js"></script>
|
||||
<% if (has('chat')) { %><script src="/chat/chat.js?v=<%= boot %>"></script><% } %>
|
||||
<% if (has('alerts')) { %>
|
||||
<script src="/alerts/card.js?v=<%= boot %>"></script>
|
||||
<script src="/alerts/cassette.js?v=<%= boot %>"></script>
|
||||
<script src="/alerts/fx.js?v=<%= boot %>"></script>
|
||||
<script src="/alerts/polaroid.js?v=<%= boot %>"></script>
|
||||
|
|
|
|||
72
views/public_stats.ejs
Normal file
72
views/public_stats.ejs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title><%= displayName %> · Stream stats</title>
|
||||
<meta name="description" content="Stream statistics for <%= displayName %> on Twitch: streams, chat, emotes, leaderboards.">
|
||||
<%# viewer names are listed: keep the page out of search engines (remove this line to allow indexing) %>
|
||||
<meta name="robots" content="noindex">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Caveat:wght@700&family=Nunito:wght@400;600;700;800;900&display=swap">
|
||||
<style>
|
||||
/* paper look of the overlay alerts (polaroid / letter): cream paper, ink, red, lilac washi tape */
|
||||
:root { --bg:#f3ece2; --paper:#fffdf7; --ink:#3a2a20; --muted:#8a7565; --line:#e4d9cb; --accent:#b74347; --accent-hover:#9a3539;
|
||||
--card:var(--paper); --card-solid:var(--paper); --tape:rgba(201,182,228,.85); --link:#b74347; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root { --bg:#1d1916; --paper:#2a2420; --ink:#f1e7da; --muted:#b09d8b; --line:#3d342d; --accent:#d0626a; --accent-hover:#e07a82;
|
||||
--card:var(--paper); --card-solid:var(--paper); --tape:rgba(155,130,195,.7); --link:#e58b91; }
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
html, body { margin:0; background:var(--bg); color:var(--ink); }
|
||||
body { font:400 15px/1.45 'Nunito', system-ui, sans-serif; }
|
||||
a { color:var(--link); }
|
||||
.wrap { max-width:1100px; margin:0 auto; padding:24px 16px 48px; }
|
||||
header.hero { position:relative; background:var(--paper); padding:22px 24px 18px; margin:14px 0 22px; box-shadow:0 10px 24px rgba(0,0,0,.12);
|
||||
transform:rotate(-.4deg); display:flex; flex-wrap:wrap; align-items:center; gap:.5rem 1.2rem; }
|
||||
header.hero:before, header.hero:after { content:''; position:absolute; top:-14px; width:120px; height:32px; background-color:var(--tape);
|
||||
background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px); box-shadow:0 1px 2px rgba(0,0,0,.15); }
|
||||
header.hero:before { left:-18px; transform:rotate(-8deg); }
|
||||
header.hero:after { right:-18px; transform:rotate(7deg); }
|
||||
header.hero h1 { font:700 46px/1 'Caveat', cursive; margin:0; }
|
||||
header.hero h1 span { color:var(--accent); }
|
||||
header.hero .sub { color:var(--muted); font-weight:600; }
|
||||
.live { display:inline-flex; align-items:center; gap:.4rem; background:var(--accent); color:#fff; border-radius:99px; padding:.2rem .8rem;
|
||||
font-weight:800; font-size:.85rem; text-decoration:none; margin-left:auto; }
|
||||
.live:before { content:''; width:8px; height:8px; border-radius:50%; background:#fff; animation:blink 1.4s infinite; }
|
||||
.watch { margin-left:auto; font-weight:700; text-decoration:none; }
|
||||
@keyframes blink { 50% { opacity:.3; } }
|
||||
.preview { background:#e6b800; color:#221a00; padding:.4rem .8rem; border-radius:8px; font-weight:700; font-size:.85rem; margin-bottom:.6rem; }
|
||||
h3.sb-h { font:700 30px/1 'Caveat', cursive; margin:1.8rem 0 .7rem; }
|
||||
.sb-tile .v { font-weight:900; }
|
||||
.sb-board h4, .sb-chart h4 { font-weight:800; }
|
||||
.sb-tabs a.on { color:#fff; }
|
||||
code { font-family:ui-monospace, monospace; font-size:.9em; }
|
||||
footer { margin-top:2.4rem; color:var(--muted); font-size:.85rem; border-top:1px dashed var(--line); padding-top:1rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<% if (preview) { %><div class="preview">Preview: the public page is off (Settings → Public stats page). Only you can see this.</div><% } %>
|
||||
<header class="hero">
|
||||
<h1><span><%= displayName %></span>'s stream stats</h1>
|
||||
<span class="sub">the people who make the streams fun ♡</span>
|
||||
<% if (live) { %>
|
||||
<a class="live" href="https://twitch.tv/<%= encodeURIComponent(channel) %>" target="_blank" rel="noopener">live now</a>
|
||||
<% } else if (channel) { %>
|
||||
<a class="watch" href="https://twitch.tv/<%= encodeURIComponent(channel) %>" target="_blank" rel="noopener">twitch.tv/<%= channel %> ↗</a>
|
||||
<% } %>
|
||||
</header>
|
||||
|
||||
<%- include('_statsbody', { s, q, base: base || '/', viewerHref: null, mode: 'public', view, ranks, tz }) %>
|
||||
|
||||
<footer>
|
||||
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 <code>!hideme</code> in chat (you still count in the totals, unnamed);
|
||||
<code>!showme</code> brings it back. To have your data deleted completely, ask in chat or whisper the streamer.
|
||||
Days are UTC; numbers update every few minutes.
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -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; }
|
||||
</style>
|
||||
|
|
@ -114,7 +115,7 @@
|
|||
</summary>
|
||||
|
||||
<% 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'; %>
|
||||
<div class="vcard<%= v.enabled ? '' : ' off' %>" data-id="<%= v.id %>" data-display="<%= display %>">
|
||||
<div class="vrow">
|
||||
<input type="checkbox" role="switch" data-f="enabled" <%= v.enabled ? 'checked' : '' %> title="On: this variation can play">
|
||||
|
|
@ -129,8 +130,8 @@
|
|||
</div>
|
||||
|
||||
<div class="vrow">
|
||||
<span class="seg" title="Cassette: tape alert with sound. Sound only: just the sound. Video: full-screen video on the ?parts=video overlay">
|
||||
<% for (const [val, lbl] of [['cassette', 'Cassette'], ['sound', 'Sound only'], ['video', 'Video']]) { %>
|
||||
<span class="seg" title="Card: plain alert card with sound. Cassette: tape alert with sound. Sound only: just the sound. Video: full-screen video on the ?parts=video overlay">
|
||||
<% for (const [val, lbl] of [['card', 'Card'], ['cassette', 'Cassette'], ['sound', 'Sound only'], ['video', 'Video']]) { %>
|
||||
<label><input type="radio" name="display-<%= v.id %>" data-f="display" value="<%= val %>" <%= display === val ? 'checked' : '' %>><%= lbl %></label>
|
||||
<% } %>
|
||||
</span>
|
||||
|
|
@ -147,7 +148,7 @@
|
|||
|
||||
<div class="vrow" data-show="cassette">
|
||||
<input type="hidden" data-f="art" value="<%= v.art || '' %>">
|
||||
<span class="pick" data-pick="art" title="Sticker in the cassette's corner"></span>
|
||||
<span class="pick" data-pick="art" title="Picture on the card / sticker in the cassette's corner"></span>
|
||||
<span class="field grow"><input data-f="caption" value="<%= v.caption %>" title="Text after the viewer's name on the paper strip. {reward} = reward name, {variation} = this variation's name. The viewer's typed message is added automatically."></span>
|
||||
<input type="hidden" data-f="tts_voice_id" value="<%= v.tts_voice_id || '' %>">
|
||||
<span class="pick" data-pick="tts_voice_id" title="Read the viewer's typed text aloud (voice from the TTS page), shown as a big paper note. The voice replaces the sound. The reward needs 'Require Viewer to Enter Text' on Twitch."></span>
|
||||
|
|
@ -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]'));
|
||||
|
|
|
|||
|
|
@ -1,112 +0,0 @@
|
|||
<h2>Settings</h2>
|
||||
|
||||
<article>
|
||||
<header><strong>Overlay URL</strong></header>
|
||||
<p>Add this as a <strong>Browser Source</strong> in OBS (1920×1080, transparent background):</p>
|
||||
<code><%= baseUrl %>/overlay/<%= settings.overlay_id %></code>
|
||||
</article>
|
||||
|
||||
<form method="POST" action="/settings">
|
||||
|
||||
<h3>Chat</h3>
|
||||
<label>
|
||||
Twitch channel
|
||||
<input type="text" name="channel" value="<%= settings.channel %>" placeholder="yourchannel">
|
||||
</label>
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
|
||||
<label>
|
||||
Message timeout (seconds)
|
||||
<input type="number" name="message_timeout" value="<%= settings.message_timeout %>" min="0" max="600">
|
||||
<small>0 = messages stay forever</small>
|
||||
</label>
|
||||
<label>
|
||||
Max messages shown
|
||||
<input type="number" name="max_messages" value="<%= settings.max_messages %>" min="1" max="100">
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label title="Messages from these accounts never appear in the on-screen chat (bots, alert services). Twitch login names, separated by commas or spaces.">
|
||||
Hidden chatters
|
||||
<input type="text" name="chat_hidden_users" value="<%= settings.chat_hidden_users || '' %>" placeholder="bot_account, blerp, …">
|
||||
</label>
|
||||
<label title="Chat commands like !discord or !lurk are not shown in the on-screen chat. The bot's answer is hidden too if the bot is in Hidden chatters.">
|
||||
<input type="checkbox" name="chat_hide_commands" role="switch" <%= settings.chat_hide_commands ? 'checked' : '' %>> Hide ! commands
|
||||
</label>
|
||||
|
||||
<h3>Gap audio</h3>
|
||||
<p><small>Plays a sound when a new message arrives after a period of silence.</small></p>
|
||||
<label>
|
||||
<input type="checkbox" name="gap_audio_enabled" role="switch" <%= settings.gap_audio_enabled ? 'checked' : '' %>>
|
||||
Enable gap audio
|
||||
</label>
|
||||
<label>
|
||||
Sound URL
|
||||
<input type="text" name="gap_audio_url" value="<%= settings.gap_audio_url %>" placeholder="https://... or /media/filename.mp3">
|
||||
</label>
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:1rem;">
|
||||
<label>
|
||||
Min silence before triggering (s)
|
||||
<input type="number" name="gap_audio_min_silence" value="<%= settings.gap_audio_min_silence %>" min="0">
|
||||
<small>Sound won't play if chat was more recent than this</small>
|
||||
</label>
|
||||
<label>
|
||||
Min volume (0–1)
|
||||
<input type="number" name="gap_audio_min_volume" value="<%= settings.gap_audio_min_volume %>" min="0" max="1" step="0.05">
|
||||
<small>Volume right after min silence</small>
|
||||
</label>
|
||||
<label>
|
||||
Max volume (0–1)
|
||||
<input type="number" name="gap_audio_max_volume" value="<%= settings.gap_audio_max_volume %>" min="0" max="1" step="0.05">
|
||||
<small>Volume after long silence</small>
|
||||
</label>
|
||||
</div>
|
||||
<label>
|
||||
Full volume after silence of (seconds)
|
||||
<input type="number" name="gap_audio_loud_after" value="<%= settings.gap_audio_loud_after %>" min="0">
|
||||
<small>e.g. 3600 = 1 hour of silence → max volume</small>
|
||||
</label>
|
||||
|
||||
<h3>TTS redeems</h3>
|
||||
<p><small>For redeem variations with a TTS voice (set on the Redeems page; voices are made on the TTS page).</small></p>
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
|
||||
<label>
|
||||
Max length (characters)
|
||||
<input type="number" name="tts_max_chars" value="<%= settings.tts_max_chars %>" min="20" max="500">
|
||||
<small>Longer messages are cut at a word.</small>
|
||||
</label>
|
||||
<label style="align-self:center;">
|
||||
<input type="checkbox" name="tts_say_name" role="switch" <%= settings.tts_say_name ? 'checked' : '' %>>
|
||||
Say the name first ("ChickenWhisperer says: …")
|
||||
</label>
|
||||
</div>
|
||||
<label>
|
||||
Blocked words
|
||||
<textarea name="tts_blocklist" rows="4" placeholder="one per line, or comma-separated"><%= settings.tts_blocklist %></textarea>
|
||||
<small>If a message contains one, nothing is read and the letter shows "(message removed)". Whole words and phrases, not case-sensitive, plurals included; also catches swaps like 0→o, $→s and spaced-out letters (k y s). Starts with a list of slurs and Twitch-risky phrases (normal swearing is allowed); edit freely. Links are always removed.</small>
|
||||
</label>
|
||||
|
||||
<h3>HUDFX</h3>
|
||||
<label title="Paste the browser source URL from HUDFX. Then add &ext=hudfx to an overlay URL in OBS: HUDFX effects play inside that overlay (one audio fader), with the camcorder look. Leave empty to turn it off.">
|
||||
HUDFX overlay URL
|
||||
<input type="url" name="hudfx_overlay_url" value="<%= settings.hudfx_overlay_url || '' %>" placeholder="https://overlays.hudfx.io/overlay/…">
|
||||
</label>
|
||||
|
||||
<h3>Custom CSS / JS</h3>
|
||||
<label>
|
||||
Custom CSS (injected into the overlay)
|
||||
<textarea name="custom_css" rows="6" style="font-family:monospace"><%= settings.custom_css %></textarea>
|
||||
</label>
|
||||
<label>
|
||||
Custom JS (injected into the overlay, runs after init)
|
||||
<textarea name="custom_js" rows="6" style="font-family:monospace"><%= settings.custom_js %></textarea>
|
||||
</label>
|
||||
|
||||
<button type="submit">Save settings</button>
|
||||
</form>
|
||||
|
||||
<hr>
|
||||
<h3>EventSub</h3>
|
||||
<form method="POST" action="/settings/reconnect" style="display:inline;">
|
||||
<button type="submit" class="outline">Reconnect EventSub</button>
|
||||
</form>
|
||||
<small style="margin-left:1rem;">Use this if Twitch alerts stop working after a token refresh.</small>
|
||||
2
views/settings/_flash.ejs
Normal file
2
views/settings/_flash.ejs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
<% if (locals.msg) { %><p class="flash"><%= msg %></p><% } %>
|
||||
<% if (locals.err) { %><p class="flash err"><%= err %></p><% } %>
|
||||
16
views/settings/advanced.ejs
Normal file
16
views/settings/advanced.ejs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<h2 class="set-h">Advanced</h2>
|
||||
<p class="set-intro">Extra CSS and JavaScript added to every overlay page.</p>
|
||||
<%- include('_flash') %>
|
||||
<form method="POST" action="/settings/advanced">
|
||||
<div class="set-card">
|
||||
<div class="set-row">
|
||||
<div class="lbl">Custom CSS</div>
|
||||
<textarea name="custom_css" rows="10" style="font-family:monospace"><%= settings.custom_css %></textarea>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Custom JS<small>Runs after the overlay starts.</small></div>
|
||||
<textarea name="custom_js" rows="10" style="font-family:monospace"><%= settings.custom_js %></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="savebar-set"><button type="submit">Save</button></div>
|
||||
</form>
|
||||
16
views/settings/backup.ejs
Normal file
16
views/settings/backup.ejs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<h2 class="set-h">Backup</h2>
|
||||
<p class="set-intro">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).</p>
|
||||
<%- include('_flash') %>
|
||||
<div class="set-card">
|
||||
<div class="set-row">
|
||||
<div class="lbl">Export<small>Download a .json file.</small></div>
|
||||
<div><a href="/settings/backup/export" role="button" class="btn-auto">Download backup</a></div>
|
||||
</div>
|
||||
<form method="POST" action="/settings/backup/import" enctype="multipart/form-data" class="set-row">
|
||||
<div class="lbl">Import<small>Replaces the current settings, theme, redeems and TTS voices with the ones in the file. Statistics stay.</small></div>
|
||||
<div class="set-inline">
|
||||
<input type="file" name="file" accept=".json,application/json" required>
|
||||
<button type="submit" class="outline btn-auto" data-confirm="Really replace everything?">Import and replace</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
62
views/settings/chat.ejs
Normal file
62
views/settings/chat.ejs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
<h2 class="set-h">Chat</h2>
|
||||
<p class="set-intro">The chat shown on the overlay (OBS source with the chat part).</p>
|
||||
<%- include('_flash') %>
|
||||
<form method="POST" action="/settings/chat">
|
||||
<div class="set-card">
|
||||
<h3>Messages</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Message timeout<small>Seconds a message stays. 0 = forever.</small></div>
|
||||
<input type="number" name="message_timeout" value="<%= settings.message_timeout %>" min="0" max="600" style="max-width:8rem;">
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Max messages shown</div>
|
||||
<input type="number" name="max_messages" value="<%= settings.max_messages %>" min="1" max="100" style="max-width:8rem;">
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Hidden chatters<small>Bots and alert services: never shown in the on-screen chat and left out of the statistics. Twitch logins, commas or spaces.</small></div>
|
||||
<input type="text" name="chat_hidden_users" value="<%= settings.chat_hidden_users || '' %>" placeholder="streamelements, nightbot, …">
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Hide ! commands<small>!discord, !lurk … are not shown. Add the bot to Hidden chatters to hide its answer too.</small></div>
|
||||
<label><input type="checkbox" name="chat_hide_commands" role="switch" <%= settings.chat_hide_commands ? 'checked' : '' %>></label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Gap sound</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Play a sound after silence<small>When a message arrives after chat was quiet for a while.</small></div>
|
||||
<label><input type="checkbox" name="gap_audio_enabled" role="switch" <%= settings.gap_audio_enabled ? 'checked' : '' %>></label>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Sound<small>From your <a href="/media">Media</a> library (upload new sounds there).</small></div>
|
||||
<div class="set-inline">
|
||||
<select name="gap_audio_url" id="gap-sound" style="flex:1; min-width:220px;">
|
||||
<option value="">— none —</option>
|
||||
<% for (const m of sounds) { %><option value="<%= m.url %>" <%= m.url === settings.gap_audio_url ? 'selected' : '' %>><%= m.label %></option><% } %>
|
||||
<% if (settings.gap_audio_url && !sounds.some(m => m.url === settings.gap_audio_url)) { %><option value="<%= settings.gap_audio_url %>" selected>link: <%= settings.gap_audio_url.split('/').pop() %></option><% } %>
|
||||
</select>
|
||||
<button type="button" class="outline btn-auto" id="gap-play" title="Play">▶</button>
|
||||
</div>
|
||||
<script>
|
||||
document.getElementById('gap-play').addEventListener('click', () => {
|
||||
const u = document.getElementById('gap-sound').value;
|
||||
if (u) { const a = new Audio(u); a.volume = parseFloat(document.querySelector('[name=gap_audio_max_volume]').value) || 1; a.play(); }
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Quiet for at least<small>Seconds of silence before the sound plays.</small></div>
|
||||
<input type="number" name="gap_audio_min_silence" value="<%= settings.gap_audio_min_silence %>" min="0" style="max-width:8rem;">
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Volume<small>Quiet right after the minimum silence, louder the longer chat was quiet.</small></div>
|
||||
<div class="set-inline">
|
||||
<label>from <input type="number" name="gap_audio_min_volume" value="<%= settings.gap_audio_min_volume %>" min="0" max="1" step="0.05" style="max-width:6rem;"></label>
|
||||
<label>to <input type="number" name="gap_audio_max_volume" value="<%= settings.gap_audio_max_volume %>" min="0" max="1" step="0.05" style="max-width:6rem;"></label>
|
||||
<label>full after <input type="number" name="gap_audio_loud_after" value="<%= settings.gap_audio_loud_after %>" min="0" style="max-width:7rem;"> s</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="savebar-set"><button type="submit">Save</button></div>
|
||||
</form>
|
||||
64
views/settings/connections.ejs
Normal file
64
views/settings/connections.ejs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
<h2 class="set-h">Connections</h2>
|
||||
<p class="set-intro">Services HeyStreamer talks to.</p>
|
||||
<%- include('_flash') %>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Twitch</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Account</div>
|
||||
<div><%= user ? (user.display_name || user.login) : 'not logged in' %></div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Events (EventSub)<small>Follows, subs, bits, rewards, raids, chat, stream on / off.</small></div>
|
||||
<div>
|
||||
<% if (eventsub.connected) { %><span class="badge badge-green">connected</span>
|
||||
<% } else if (eventsub.running) { %><span class="badge badge-grey">connecting…</span>
|
||||
<% } else { %><span class="badge badge-red">not running</span><% } %>
|
||||
<% if (eventsub.lastEventAt) { %> <small>last event <%= eventsub.lastEventAt.slice(0, 16).replace('T', ' ') %> UTC</small><% } %>
|
||||
<% if (eventsub.failed.length) { %><p><small style="color:#f88">Not allowed: <%= eventsub.failed.join(', ') %>. Log in again to give HeyStreamer the missing permission.</small></p><% } %>
|
||||
<% if (eventsub.subscribed.length) { %><details style="margin:.4rem 0 0;"><summary><small>Listening to <%= eventsub.subscribed.length %> events</small></summary><small><%= eventsub.subscribed.join(', ') %></small></details><% } %>
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Fix it<small>Log in again after new features ask for more permissions, or reconnect if alerts stop.</small></div>
|
||||
<div class="set-inline">
|
||||
<a href="/auth/twitch" role="button" class="btn-auto">Log in again with Twitch</a>
|
||||
<form method="POST" action="/settings/connections/reconnect"><button type="submit" class="outline btn-auto">Reconnect</button></form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>StreamElements tips</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Status</div>
|
||||
<div>
|
||||
<% if (!se.enabled) { %><span class="badge badge-grey">off</span> <small>no token</small>
|
||||
<% } else if (se.subscribed) { %><span class="badge badge-green">connected</span><% if (se.lastTipAt) { %> <small>last tip <%= se.lastTipAt %></small><% } %>
|
||||
<% } else { %><span class="badge badge-grey">connecting…</span><% } %>
|
||||
<% if (se.error) { %><br><small style="color:#f88"><%= se.error %></small><% } %>
|
||||
<% if (se.source === 'env') { %><br><small>Token comes from <code>.env</code> (SE_JWT). Saving one here replaces it.</small><% } %>
|
||||
</div>
|
||||
</div>
|
||||
<form method="POST" action="/settings/connections/se" class="set-row">
|
||||
<div class="lbl">JWT token<small>StreamElements → your avatar → Channel settings → Show secrets → JWT Token. Kept secret: it is never shown again here.</small></div>
|
||||
<div class="set-inline">
|
||||
<input type="password" id="se-jwt" name="se_jwt" autocomplete="off" placeholder="<%= settings.se_jwt ? '•••••••• (saved: paste a new one to replace it)' : 'paste the JWT token' %>" style="flex:1; min-width:220px;">
|
||||
<button type="button" class="outline eye" data-reveal="#se-jwt" title="Show what you typed">👁</button>
|
||||
<button type="submit" class="btn-auto">Save and connect</button>
|
||||
<% if (settings.se_jwt) { %><button type="submit" name="clear" value="1" class="outline btn-auto" data-confirm="Really remove?">Remove token</button><% } %>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="/settings/hudfx" class="set-card">
|
||||
<h3>HUDFX</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">HUDFX overlay URL<small>Then add <code>&ext=hudfx</code> to an OBS source link: HUDFX effects play inside that overlay. Empty = off.</small></div>
|
||||
<div class="set-inline">
|
||||
<input type="password" id="hudfx-url" name="hudfx_overlay_url" value="<%= settings.hudfx_overlay_url || '' %>" placeholder="https://overlays.hudfx.io/overlay/…" autocomplete="off" style="flex:1; min-width:220px;">
|
||||
<button type="button" class="outline eye" data-reveal="#hudfx-url" title="Show">👁</button>
|
||||
<button type="submit" class="btn-auto">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
22
views/settings/general.ejs
Normal file
22
views/settings/general.ejs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
<h2 class="set-h">General</h2>
|
||||
<p class="set-intro">Basics about your channel.</p>
|
||||
<%- include('_flash') %>
|
||||
<form method="POST" action="/settings/general">
|
||||
<div class="set-card">
|
||||
<div class="set-row">
|
||||
<div class="lbl">Twitch channel<small>The chat shown on the overlay. Usually your own channel name.</small></div>
|
||||
<input type="text" name="channel" value="<%= settings.channel || '' %>" placeholder="yourchannel" required pattern="#?[A-Za-z0-9_]{2,25}">
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Time zone<small>Used for times and days on the stats pages.</small></div>
|
||||
<div>
|
||||
<input type="text" name="timezone" value="<%= settings.timezone || 'UTC' %>" list="tz-list" placeholder="Europe/London">
|
||||
<datalist id="tz-list">
|
||||
<% let zones = []; try { zones = Intl.supportedValuesOf('timeZone'); } catch {} %>
|
||||
<% for (const z of zones) { %><option value="<%= z %>"><% } %>
|
||||
</datalist>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="savebar-set"><button type="submit">Save</button></div>
|
||||
</form>
|
||||
64
views/settings/obs.ejs
Normal file
64
views/settings/obs.ejs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
<h2 class="set-h">OBS sources</h2>
|
||||
<p class="set-intro">The links are hidden (anyone with one can open your overlay): 👁 shows one, Copy copies it either way. Add them as <strong>Browser Source</strong> in OBS (1920 × 1080, transparent). Pick what one source shows, then copy its link.</p>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Ready-made links</h3>
|
||||
<% 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) => { %>
|
||||
<div class="set-row">
|
||||
<div class="lbl"><%= title %><small><%= hint %></small></div>
|
||||
<div class="copy"><code id="obs-<%= i %>" class="secret"><%= overlayUrl + q %></code><button type="button" class="outline eye" data-reveal="#obs-<%= i %>" title="Show">👁</button><button type="button" class="outline" data-copy-from="#obs-<%= i %>">Copy</button></div>
|
||||
</div>
|
||||
<% }) %>
|
||||
</div>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Build your own</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Parts</div>
|
||||
<div class="set-inline" id="obs-parts">
|
||||
<% for (const [p, l] of [['alerts', 'Alerts and redeems'], ['chat', 'Chat'], ['poll', 'Poll'], ['hypebar', 'Hype Train bar'], ['raid', 'Raid send-off'], ['video', 'Videos']]) { %>
|
||||
<label><input type="checkbox" value="<%= p %>" <%= p !== 'video' ? 'checked' : '' %>> <%= l %></label>
|
||||
<% } %>
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Chat box<small>Optional: left, top, width, height in px of the 1920 × 1080 page. Empty = default place.</small></div>
|
||||
<div class="set-inline">
|
||||
<input type="text" id="obs-box" placeholder="130,640,700,360" style="max-width:12rem;">
|
||||
<label><input type="checkbox" id="obs-up"> newest at the bottom</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Extras</div>
|
||||
<div class="set-inline"><label title="Needs the HUDFX URL in Settings → Connections"><input type="checkbox" id="obs-hudfx"> HUDFX effects</label></div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Link</div>
|
||||
<div class="copy"><code id="obs-built" class="secret"></code><button type="button" class="outline eye" data-reveal="#obs-built" title="Show">👁</button><button type="button" class="outline" data-copy-from="#obs-built">Copy</button></div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(() => {
|
||||
const base = <%- JSON.stringify(overlayUrl) %>;
|
||||
const all = ['alerts', 'chat', 'poll', 'hypebar', 'raid'];
|
||||
const build = () => {
|
||||
const picked = [...document.querySelectorAll('#obs-parts input:checked')].map(i => i.value);
|
||||
const std = picked.filter(p => p !== 'video');
|
||||
const q = [];
|
||||
if (!(std.length === all.length && !picked.includes('video'))) q.push('parts=' + picked.join(','));
|
||||
const box = document.getElementById('obs-box').value.trim();
|
||||
if (picked.includes('chat') && /^\d+,\d+,\d+,\d+$/.test(box)) q.push('chat=' + box);
|
||||
if (picked.includes('chat') && document.getElementById('obs-up').checked) q.push('chatflow=up');
|
||||
if (document.getElementById('obs-hudfx').checked) q.push('ext=hudfx');
|
||||
document.getElementById('obs-built').textContent = base + (q.length ? '?' + q.join('&') : '');
|
||||
};
|
||||
document.querySelectorAll('#obs-parts input, #obs-box, #obs-up, #obs-hudfx').forEach(i => i.addEventListener('input', build));
|
||||
build();
|
||||
})();
|
||||
</script>
|
||||
38
views/settings/stats.ejs
Normal file
38
views/settings/stats.ejs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<h2 class="set-h">Stats and data</h2>
|
||||
<p class="set-intro">The public stats page, and data copied from Twitch.</p>
|
||||
<%- include('_flash') %>
|
||||
<form method="POST" action="/settings/stats" class="set-card">
|
||||
<h3>Public stats page</h3>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Public page on<small>Off: it answers “not found” for everyone except you (preview below). Never shows message text, bots, or viewers who typed !hideme.</small></div>
|
||||
<label><input type="checkbox" name="public_stats_enabled" role="switch" <%= settings.public_stats_enabled ? 'checked' : '' %>></label>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Host name<small>Its 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.</small></div>
|
||||
<input type="text" name="public_stats_host" value="<%= settings.public_stats_host || '' %>" placeholder="stats.example.com">
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl"></div>
|
||||
<div class="set-inline"><button type="submit" class="btn-auto">Save</button><a href="/public" target="_blank" rel="noopener">Preview ↗</a></div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="set-card">
|
||||
<h3>Twitch</h3>
|
||||
<% const bad = Object.entries(sync.parts || {}).filter(([, v]) => !String(v).startsWith('ok')); %>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Sync with Twitch<small>Followers with follow dates, current subs, mods, VIPs, all-time bits, your emotes, past streams (VODs). Runs every 6 hours and after each stream.</small></div>
|
||||
<div>
|
||||
<form method="POST" action="/stats/sync?back=settings" class="set-inline"><button type="submit" class="outline btn-auto">Sync now</button>
|
||||
<small><%= sync.at ? `last ${sync.at.slice(0, 16).replace('T', ' ')} UTC` : 'never' %></small></form>
|
||||
<% if (sync.at) { %><small><% for (const [k, v] of Object.entries(sync.parts || {})) { %><%= k %>: <span style="<%= String(v).startsWith('ok') ? '' : 'color:#f88' %>"><%= v %></span> · <% } %></small><% } %>
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Twitch analytics (CSV)<small>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.</small></div>
|
||||
<form method="POST" action="/stats/import-twitch?back=settings" enctype="multipart/form-data" class="set-inline">
|
||||
<label role="button" class="outline btn-auto">Choose CSV files…<input type="file" name="files" accept=".csv,text/csv" multiple hidden onchange="this.form.requestSubmit()"></label>
|
||||
<small><%= csv.days ? `${csv.days} days imported (${csv.from_day} – ${csv.to_day})` : 'none imported yet' %></small>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
20
views/settings/tts.ejs
Normal file
20
views/settings/tts.ejs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<h2 class="set-h">Text to speech</h2>
|
||||
<p class="set-intro">For redeem variations with a TTS voice (set on Actions → Redeems; voices are made on Actions → TTS voices).</p>
|
||||
<%- include('_flash') %>
|
||||
<form method="POST" action="/settings/tts">
|
||||
<div class="set-card">
|
||||
<div class="set-row">
|
||||
<div class="lbl">Max length<small>Characters. Longer messages are cut at a word.</small></div>
|
||||
<input type="number" name="tts_max_chars" value="<%= settings.tts_max_chars %>" min="20" max="500" style="max-width:8rem;">
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Say the name first<small>“ChickenWhisperer says: …”</small></div>
|
||||
<label><input type="checkbox" name="tts_say_name" role="switch" <%= settings.tts_say_name ? 'checked' : '' %>></label>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lbl">Blocked words<small>One 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.</small></div>
|
||||
<textarea name="tts_blocklist" rows="10"><%= settings.tts_blocklist %></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="savebar-set"><button type="submit">Save</button></div>
|
||||
</form>
|
||||
148
views/stats.ejs
148
views/stats.ejs
|
|
@ -1,44 +1,11 @@
|
|||
<style>
|
||||
/* colours for the shared stats body (_statsbody.ejs), from Pico */
|
||||
main { --muted:var(--pico-muted-color); --line:var(--pico-muted-border-color); --accent:var(--pico-primary-background);
|
||||
--accent-hover:var(--pico-primary-hover-background); --card:transparent; --card-solid:var(--pico-card-background-color); }
|
||||
.meta { color:var(--pico-muted-color); font-size:.85rem; }
|
||||
.tiles { display:grid; grid-template-columns:repeat(auto-fit, minmax(150px, 1fr)); gap:.6rem; margin:.6rem 0 1.2rem; }
|
||||
.tile { border:1px solid var(--pico-muted-border-color); border-radius:12px; padding:.7rem .9rem; }
|
||||
.tile .v { font-size:1.7rem; font-weight:700; line-height:1.1; }
|
||||
.tile .k { font-size:.8rem; color:var(--pico-muted-color); }
|
||||
.charts { display:grid; grid-template-columns:repeat(auto-fit, minmax(320px, 1fr)); gap:1rem; margin-bottom:1.2rem; }
|
||||
.chart { border:1px solid var(--pico-muted-border-color); border-radius:12px; padding:.7rem .9rem; position:relative; }
|
||||
.chart h4 { margin:0 0 .4rem; font-size:.95rem; }
|
||||
.chart svg { width:100%; height:auto; display:block; }
|
||||
.chart .bar { fill:var(--pico-primary); }
|
||||
.chart .bar:hover, .chart .hit:hover + .bar { fill:var(--pico-primary-hover); }
|
||||
.chart .grid { stroke:var(--pico-muted-border-color); stroke-width:1; }
|
||||
.chart .ax { fill:var(--pico-muted-color); font-size:10px; }
|
||||
.tip { position:absolute; pointer-events:none; background:var(--pico-card-background-color); border:1px solid var(--pico-muted-border-color);
|
||||
border-radius:8px; padding:.25rem .5rem; font-size:.8rem; box-shadow:0 4px 12px rgba(0,0,0,.35); white-space:nowrap; display:none; z-index:5; }
|
||||
.boards { display:grid; grid-template-columns:repeat(auto-fill, minmax(320px, 1fr)); gap:1rem; }
|
||||
.board { border:1px solid var(--pico-muted-border-color); border-radius:12px; padding:.6rem .8rem; }
|
||||
.board h4 { margin:0 0 .3rem; font-size:.95rem; }
|
||||
.board ol { list-style:none; margin:0; padding:0; }
|
||||
.board li { list-style:none; display:grid; grid-template-columns:1.6rem minmax(0, 1fr) var(--nw, 4.6rem); align-items:center; gap:.5rem;
|
||||
height:2rem; margin:0; padding:0 .2rem; border-bottom:1px solid var(--pico-muted-border-color); font-size:.88rem; }
|
||||
.board li:last-child { border-bottom:0; }
|
||||
.board .r { color:var(--pico-muted-color); text-align:right; font-variant-numeric:tabular-nums; }
|
||||
.board .who { display:flex; align-items:center; gap:.4rem; min-width:0; }
|
||||
.board .who a { text-decoration:none; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0; }
|
||||
.board .lvl { flex:none; font-size:.66rem; padding:.02rem .45rem; border-radius:99px; border:1px solid var(--pico-muted-border-color);
|
||||
color:var(--pico-muted-color); white-space:nowrap; }
|
||||
.board .n { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
||||
/* points: the main board, twice as wide, level in its own column so the pills line up */
|
||||
.board.wide { grid-column:span 2; }
|
||||
.board.wide li { grid-template-columns:1.6rem minmax(0, 1fr) 5.5rem var(--nw, 4.6rem); }
|
||||
.board.wide .lvl { justify-self:start; }
|
||||
@media (max-width: 700px) { .board.wide { grid-column:auto; } }
|
||||
.emotes { display:flex; flex-wrap:wrap; gap:.5rem; }
|
||||
.emote { display:flex; align-items:center; gap:.35rem; border:1px solid var(--pico-muted-border-color); border-radius:99px; padding:.15rem .6rem .15rem .25rem; font-size:.8rem; }
|
||||
.emote img { width:26px; height:26px; object-fit:contain; }
|
||||
.search { display:flex; gap:.5rem; max-width:420px; }
|
||||
.search input, .search button { margin:0; }
|
||||
.search button { width:auto; }
|
||||
.empty { color:var(--pico-muted-color); font-size:.85rem; font-style:italic; }
|
||||
.warn { color:#e6b800; }
|
||||
</style>
|
||||
|
||||
|
|
@ -50,100 +17,23 @@
|
|||
<button type="submit" class="outline">Find</button>
|
||||
</form>
|
||||
</div>
|
||||
<p class="meta" title="Bots (Settings → Hidden chatters) are counted but left out of everything shown here. Chat is counted from the first restart after 2026-11-22; watch time from the first stream after the chatter-list permission was approved.">
|
||||
<%= 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 ⓘ
|
||||
<p class="meta">
|
||||
<span title="Bots (Settings → Hidden chatters) are counted but left out of everything shown here. Days are UTC. Watch time from before HeyStreamer counted comes from StreamElements (or Twitch's analytics export) and only shows under All time."><%= since ? `Counting since ${since}` : 'Nothing counted yet: stats start with the next stream.' %>
|
||||
· <%= hiddenCount %> hidden bot<%= hiddenCount === 1 ? '' : 's' %> left out ⓘ</span>
|
||||
· <% if (publicUrl) { %><a href="<%= publicUrl %>" target="_blank" rel="noopener" title="What viewers see: no message text, bots and !hideme viewers not named">Public page ↗</a><% } else { %><a href="/public" target="_blank" rel="noopener" title="Public page is off (Settings → Public stats page). This preview works while you are logged in.">Public page preview ↗</a><% } %>
|
||||
</p>
|
||||
|
||||
<%
|
||||
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';
|
||||
%>
|
||||
<p class="meta" style="margin-top:-.4rem;">
|
||||
<span title="<%= syncTip %>">Twitch sync: <%= sync.at ? `${sync.at.slice(0, 16).replace('T', ' ')} UTC` : 'never' %><% if (syncBad.length) { %> · <span class="warn"><%= syncBad.map(([k]) => k).join(', ') %> failed</span><% } %> ⓘ</span>
|
||||
· analytics: <%= csv.days ? `${csv.days} days imported` : 'none imported' %>
|
||||
· <a href="/settings/stats">Sync, import and the public page: Settings → Stats and data</a>
|
||||
</p>
|
||||
|
||||
<% if (msg) { %><p class="<%= /failed/i.test(msg) ? 'warn' : '' %>" style="font-weight:600;"><%= msg %></p><% } %>
|
||||
<% if (se.configured) { %>
|
||||
<form method="POST" action="/stats/import-se" style="display:flex; gap:.6rem; align-items:center; flex-wrap:wrap; margin:.2rem 0 .8rem;">
|
||||
<button type="submit" class="outline" style="width:auto; margin:0; padding:.3rem .9rem; font-size:.85rem;"
|
||||
title="Copies StreamElements' watch time (per viewer) into HeyStreamer once. It counts like our own watch time (5 points per 5 minutes). Importing again replaces the previous import.<%= se.ownTicks ? ' HeyStreamer is already counting watch time itself: StreamElements has counted those streams too, so importing again now counts them twice.' : '' %>">
|
||||
<%= se.n ? 'Import again from StreamElements' : 'Import watch time from StreamElements' %></button>
|
||||
<span class="meta"><%= 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) { %><span class="warn"> · importing again would double-count streams since then</span><% } %></span>
|
||||
</form>
|
||||
<% } %>
|
||||
<div class="tiles">
|
||||
<div class="tile"><div class="v"><%= overview.viewers.toLocaleString() %></div><div class="k">viewers seen</div></div>
|
||||
<div class="tile"><div class="v"><%= overview.messages.toLocaleString() %></div><div class="k">chat messages</div></div>
|
||||
<div class="tile"><div class="v"><%= overview.watchHours.toLocaleString() %></div><div class="k">hours watched</div></div>
|
||||
<div class="tile"><div class="v"><%= overview.streams %></div><div class="k">streams</div></div>
|
||||
<div class="tile"><div class="v"><%= overview.checkins.toLocaleString() %></div><div class="k">check-ins</div></div>
|
||||
</div>
|
||||
|
||||
<%
|
||||
// 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 = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${title}">`;
|
||||
for (const g of [0, nice / 2, nice]) s += `<line class="grid" x1="${L}" x2="${W}" y1="${y(g)}" y2="${y(g)}"/><text class="ax" x="${L - 4}" y="${y(g) + 3}" text-anchor="end">${g}</text>`;
|
||||
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 += `<rect class="hit" x="${x - 1}" y="${T}" width="${slot}" height="${H - T - B}" fill="transparent" data-tip="${label}"/>`;
|
||||
if (v > 0) s += `<path class="bar" d="M${x},${H - B} V${top + Math.min(4, h)} Q${x},${top} ${x + Math.min(4, bw / 2)},${top} H${x + bw - Math.min(4, bw / 2)} Q${x + bw},${top} ${x + bw},${top + Math.min(4, h)} V${H - B} Z"/>`;
|
||||
if (i % 7 === 0 && i < n - 4) s += `<text class="ax" x="${x + bw / 2}" y="${H - 4}" text-anchor="middle">${d.day.slice(5)}</text>`;
|
||||
if (i === n - 1) s += `<text class="ax" x="${x + bw}" y="${H - 4}" text-anchor="end">${d.day.slice(5)}</text>`;
|
||||
});
|
||||
return `<div class="chart"><h4>${title}</h4>${s}</svg><div class="tip"></div></div>`;
|
||||
};
|
||||
%>
|
||||
<div class="charts">
|
||||
<%- chart('Chat messages per day', 'messages', 'messages') %>
|
||||
<%- chart('Watch hours per day', 'watchHours', 'h') %>
|
||||
</div>
|
||||
|
||||
<h3>Leaderboards</h3>
|
||||
<%
|
||||
const board = (title, rows, fmt, extra, nw) => {
|
||||
let s = `<div class="board${extra ? ' wide' : ''}"${nw ? ` style="--nw:${nw}"` : ''}><h4>${title}</h4>`;
|
||||
if (!rows.length) return s + '<p class="empty">nothing yet</p></div>';
|
||||
s += '<ol>';
|
||||
rows.forEach((r, i) => {
|
||||
const name = (r.name || r.login || '?').replace(/[<>&"]/g, '');
|
||||
s += `<li><span class="r">${i + 1}</span><span class="who"><a href="/stats/viewer?q=${encodeURIComponent(r.login || '')}" title="${name}">${name}</a></span>`
|
||||
+ `${extra ? `<span class="lvl">${extra(r)}</span>` : ''}<span class="n">${fmt(r.n)}</span></li>`;
|
||||
});
|
||||
return s + '</ol></div>';
|
||||
};
|
||||
const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${m % 60} m` : `${m} m`;
|
||||
%>
|
||||
<div class="boards">
|
||||
<%- 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()) %>
|
||||
</div>
|
||||
|
||||
<h3 style="margin-top:1.4rem;">Top emotes</h3>
|
||||
<% if (!emotes.length) { %><p class="empty">nothing yet</p><% } else { %>
|
||||
<div class="emotes">
|
||||
<% 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; %>
|
||||
<span class="emote" title="<%= e.emote %> · <%= e.source %>"><% if (src) { %><img src="<%= src %>" alt="" loading="lazy"><% } %><%= e.emote %> <strong><%= e.uses.toLocaleString() %></strong></span>
|
||||
<% } %>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<h3 style="margin-top:1.4rem;">Top commands</h3>
|
||||
<% if (!commands.length) { %><p class="empty">nothing yet</p><% } else { %>
|
||||
<div class="emotes"><% for (const c of commands) { %><span class="emote" style="padding-left:.6rem;"><code><%= c.command %></code> <strong><%= c.uses.toLocaleString() %></strong></span><% } %></div>
|
||||
<% } %>
|
||||
|
||||
<script>
|
||||
// bar hover tooltips (per day)
|
||||
document.querySelectorAll('.chart').forEach(ch => {
|
||||
const tip = ch.querySelector('.tip');
|
||||
ch.querySelectorAll('.hit').forEach(h => {
|
||||
h.addEventListener('mouseenter', () => { tip.textContent = h.dataset.tip; tip.style.display = 'block'; });
|
||||
h.addEventListener('mousemove', e => { const r = ch.getBoundingClientRect(); tip.style.left = (e.clientX - r.left + 12) + 'px'; tip.style.top = (e.clientY - r.top - 28) + 'px'; });
|
||||
h.addEventListener('mouseleave', () => { tip.style.display = 'none'; });
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<%- 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 }] }) %>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
<style>
|
||||
.meta { color:var(--pico-muted-color); font-size:.85rem; }
|
||||
.card { border:1px solid var(--pico-muted-border-color); border-radius:12px; padding:.8rem 1rem; margin-bottom:1rem; }
|
||||
.tiles { display:grid; grid-template-columns:repeat(auto-fit, minmax(140px, 1fr)); gap:.6rem; }
|
||||
.tiles { display:grid; grid-template-columns:repeat(auto-fit, minmax(175px, 1fr)); gap:.6rem; }
|
||||
.tile { border:1px solid var(--pico-muted-border-color); border-radius:12px; padding:.6rem .8rem; }
|
||||
.tile .v { font-size:1.5rem; font-weight:700; line-height:1.1; }
|
||||
.tile .v { font-size:1.2rem; font-weight:700; line-height:1.2; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.tile .k { font-size:.8rem; color:var(--pico-muted-color); }
|
||||
.parts { display:flex; flex-wrap:wrap; gap:.4rem; margin-top:.6rem; }
|
||||
.part { border:1px solid var(--pico-muted-border-color); border-radius:99px; padding:.1rem .6rem; font-size:.8rem; }
|
||||
|
|
@ -12,31 +12,119 @@
|
|||
.emote img { width:24px; height:24px; object-fit:contain; }
|
||||
table { font-size:.85rem; }
|
||||
.btn-sm { margin:0; padding:.25rem .7rem; font-size:.8rem; width:auto; }
|
||||
.head { display:flex; align-items:flex-start; gap:1rem; }
|
||||
.head h2 { margin:0 0 .2rem; }
|
||||
.roles { display:flex; flex-wrap:wrap; gap:.35rem; margin:.3rem 0 .8rem; align-items:center; }
|
||||
.role { font-size:.72rem; font-weight:700; padding:.12rem .55rem; border-radius:99px; border:1px solid var(--pico-muted-border-color); }
|
||||
.role.broadcaster { background:#7a1a1a; border-color:#7a1a1a; color:#f6c8c8; }
|
||||
.role.moderator { background:#0d5d22; border-color:#0d5d22; color:#b9f0c6; }
|
||||
.role.vip { background:#7a1a6e; border-color:#7a1a6e; color:#f3c4ec; }
|
||||
.role.subscriber, .role.founder { background:#3b2a7a; border-color:#3b2a7a; color:#d6ccff; }
|
||||
/* ⋯ menu: rarely used things (public page, rename, forget) */
|
||||
.more { position:relative; margin-left:auto; }
|
||||
.more > summary { list-style:none; cursor:pointer; padding:.1rem .7rem; border:1px solid var(--pico-muted-border-color); border-radius:8px; font-size:1.2rem; line-height:1.3; }
|
||||
.more > summary::-webkit-details-marker { display:none; }
|
||||
.more > summary::after { display:none !important; }
|
||||
.more .menu { position:absolute; right:0; top:calc(100% + .3rem); z-index:10; width:320px; background:var(--pico-card-background-color);
|
||||
border:1px solid var(--pico-muted-border-color); border-radius:12px; box-shadow:0 10px 24px rgba(0,0,0,.4); padding:.4rem; }
|
||||
.menu form { margin:0; padding:.5rem .55rem; border-bottom:1px solid var(--pico-muted-border-color); }
|
||||
.menu form:last-child { border-bottom:0; }
|
||||
.menu .lbl { display:block; font-size:.78rem; color:var(--pico-muted-color); margin-bottom:.35rem; }
|
||||
.menu .row { display:flex; gap:.4rem; align-items:center; }
|
||||
.menu input { margin:0; padding:.25rem .5rem; font-size:.85rem; height:auto; }
|
||||
</style>
|
||||
|
||||
<p><a href="/stats">← Stats</a></p>
|
||||
<% if (!viewer) { %>
|
||||
<h2><%= q %></h2>
|
||||
<p class="meta">No statistics for this viewer (yet). Names are Twitch logins, e.g. <code>channel</code>.</p>
|
||||
<p class="meta">No statistics for this viewer (yet). Names are Twitch logins, e.g. <code>some_viewer</code>.</p>
|
||||
<% } 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); %>
|
||||
<h2 style="margin-bottom:.2rem;"><%= viewer.name %> <span class="meta">@<%= viewer.login %></span></h2>
|
||||
<p class="meta"><%= viewer.level.name %>
|
||||
<% if (viewer.hidden) { %> · <span class="badge badge-grey" title="In Settings → Hidden chatters: counted, but not shown in leaderboards">hidden bot</span><% } %>
|
||||
<% if (viewer.chat.first_seen) { %> · first chat <%= viewer.chat.first_seen.slice(0, 10) %>, last <%= viewer.chat.last_seen.slice(0, 10) %><% } %>
|
||||
</p>
|
||||
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; %>
|
||||
|
||||
<div class="head">
|
||||
<div>
|
||||
<h2><%= viewer.name %> <span class="meta">@<%= viewer.login %></span></h2>
|
||||
<div class="roles">
|
||||
<a href="https://twitch.tv/<%= encodeURIComponent(viewer.login) %>" target="_blank" rel="noopener" class="meta">twitch.tv/<%= viewer.login %> ↗</a>
|
||||
<span class="role" title="Level by watch time"><%= viewer.level.name %></span>
|
||||
<% for (const [set, tip] of roles) { %><span class="role <%= set %>" title="<%= tip %>"><%= set === 'subscriber' && tw.sub ? (TIER[tw.sub.tier] || 'Sub') + ' sub' : BADGE[set] || set %></span><% } %>
|
||||
<% if (viewer.hidden) { %><span class="role" title="In Settings → Hidden chatters: counted, but not shown in leaderboards">hidden bot</span><% } %>
|
||||
<% if (viewer.publicHidden) { %><span class="role" title="Opted out of the public stats page (!hideme)">not on public page</span><% } %>
|
||||
</div>
|
||||
</div>
|
||||
<details class="more">
|
||||
<summary title="More">⋯</summary>
|
||||
<div class="menu">
|
||||
<form method="POST" action="/stats/viewer/public"
|
||||
title="The public stats page never names viewers who opted out (they typed !hideme in chat, or you set it here). They still count in the totals. !showme brings them back.">
|
||||
<input type="hidden" name="login" value="<%= viewer.login %>">
|
||||
<input type="hidden" name="user_id" value="<%= viewer.user_id || '' %>">
|
||||
<input type="hidden" name="hide" value="<%= viewer.publicHidden ? '0' : '1' %>">
|
||||
<span class="lbl">Public page: <strong><%= viewer.publicHidden ? 'not named (opted out)' : viewer.hidden ? 'not shown (hidden bot)' : 'shown' %></strong> ⓘ</span>
|
||||
<button type="submit" class="outline btn-sm"><%= viewer.publicHidden ? 'Show again' : 'Leave out of the public page' %></button>
|
||||
</form>
|
||||
<% if (viewer.importedMinutes && !viewer.user_id) { %>
|
||||
<form method="POST" action="/stats/viewer/rename"
|
||||
title="This viewer is only known from StreamElements' watch time (by name, from before HeyStreamer counted). If they renamed on Twitch, those minutes move to the new name.">
|
||||
<input type="hidden" name="from" value="<%= viewer.login %>">
|
||||
<span class="lbl">Renamed on Twitch? ⓘ</span>
|
||||
<div class="row"><input name="to" required pattern="@?\w{2,25}" placeholder="new Twitch login"><button type="submit" class="outline btn-sm">Move</button></div>
|
||||
</form>
|
||||
<% } %>
|
||||
<form method="POST" action="/stats/viewer/forget">
|
||||
<input type="hidden" name="login" value="<%= viewer.login %>">
|
||||
<input type="hidden" name="user_id" value="<%= viewer.user_id || '' %>">
|
||||
<span class="lbl" title="For removal requests: deletes all of this viewer's statistics, watch time, stored chat and activity-log entries. Cannot be undone.">Removal request ⓘ</span>
|
||||
<button type="button" data-confirm class="outline btn-sm" style="color:#f88; border-color:#f88;">Forget this viewer</button>
|
||||
</form>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="tiles">
|
||||
<div class="tile"><div class="v"><%= viewer.total.toLocaleString() %></div><div class="k">points</div></div>
|
||||
<div class="tile" title="<%= viewer.importedMinutes ? `includes ${hm(viewer.importedMinutes)} imported from StreamElements` : '' %>"><div class="v"><%= hm(minutes) %></div><div class="k">watched<%= viewer.importedMinutes ? ' · incl. StreamElements' : '' %></div></div>
|
||||
<div class="tile"><div class="v"><%= (viewer.chat.messages || 0).toLocaleString() %></div><div class="k">chat messages</div></div>
|
||||
<div class="tile"><div class="v"><%= num(viewer.total) %></div><div class="k">points</div></div>
|
||||
<div class="tile" title="<%= viewer.importedMinutes ? `includes ${hm(viewer.importedMinutes)} counted by StreamElements before HeyStreamer counted` : '' %>"><div class="v"><%= hm(minutes) %></div><div class="k">watched<%= viewer.importedMinutes ? ' · incl. StreamElements ⓘ' : '' %></div></div>
|
||||
<div class="tile"><div class="v"><%= num(viewer.chat.messages) %></div><div class="k">chat messages</div></div>
|
||||
<div class="tile"><div class="v"><%= viewer.checkins %></div><div class="k">check-ins</div></div>
|
||||
<div class="tile" title="<%= tw.follower ? `Following since ${tw.follower.followed_at.slice(0, 10)}${tw.follower.unfollowed_at ? `; unfollowed around ${tw.follower.unfollowed_at.slice(0, 10)}` : ''}` : 'Not in the follower list from the last sync with Twitch' %>">
|
||||
<div class="v"><%= tw.follower && !tw.follower.unfollowed_at ? ago(tw.follower.followed_at) : tw.follower ? 'unfollowed' : '—' %></div>
|
||||
<div class="k"><%= tw.follower && !tw.follower.unfollowed_at ? `following since ${tw.follower.followed_at.slice(0, 10)}` : 'not following' %> ⓘ</div>
|
||||
</div>
|
||||
<div class="tile" title="<%= tw.sub ? `Subscribed now (${TIER[tw.sub.tier] || tw.sub.tier}${tw.sub.is_gift ? `, gift from ${tw.sub.gifter_name || tw.sub.gifter_login}` : ''})` : 'Not subscribed at the last sync with Twitch' %>. Months come from their sub badge in chat or their resub messages; Twitch has no sub history for other viewers.">
|
||||
<div class="v"><%= tw.sub ? (TIER[tw.sub.tier] || 'Sub') : 'no sub' %><%= subMonths ? ` · ${subMonths} mo` : '' %></div>
|
||||
<div class="k"><%= tw.sub ? (tw.sub.is_gift ? 'gifted sub' : 'subscribed now') : subMonths ? 'subscribed before' : 'subscription' %> ⓘ</div>
|
||||
</div>
|
||||
<div class="tile" title="<%= tw.bits ? `Twitch all-time leaderboard: rank ${tw.bits.rank}` : 'Not in Twitch\'s top 100 all-time cheerers' %>. Counted by HeyStreamer: <%= num(viewer.given.bits) %> bits.">
|
||||
<div class="v"><%= num(Math.max(tw.bits?.score || 0, viewer.given.bits)) %></div><div class="k">bits given<%= tw.bits ? ` · #${tw.bits.rank}` : '' %> ⓘ</div>
|
||||
</div>
|
||||
<div class="tile"><div class="v"><%= num(viewer.given.gifts) %></div><div class="k">subs gifted</div></div>
|
||||
</div>
|
||||
<div class="parts" title="Where the points come from (values in docs/PLANS.md)">
|
||||
<% for (const [k, v] of Object.entries(viewer.parts).sort((a, b) => b[1] - a[1])) { %><span class="part"><%= k %>: <strong><%= v.toLocaleString() %></strong></span><% } %>
|
||||
<% for (const [k, v] of Object.entries(viewer.parts).sort((a, b) => b[1] - a[1])) { %><span class="part"><%= k %>: <strong><%= num(v) %></strong></span><% } %>
|
||||
</div>
|
||||
<p class="meta" style="margin:.6rem 0 0;">
|
||||
<% if (viewer.chat.first_seen) { %>First chat <%= viewer.chat.first_seen.slice(0, 10) %>, last <%= viewer.chat.last_seen.slice(0, 10) %>.<% } %>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<% if (viewer.emotes.length) { %>
|
||||
|
|
@ -67,20 +155,4 @@
|
|||
</tbody>
|
||||
</table>
|
||||
<% } %>
|
||||
|
||||
<% if (viewer.importedMinutes && !viewer.user_id) { %>
|
||||
<form method="POST" action="/stats/viewer/rename" style="display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-top:1.5rem;"
|
||||
title="This viewer is only known from the StreamElements import (by name). If they renamed on Twitch, their imported watch time moves to the new name, and importing again later applies the rename too.">
|
||||
<input type="hidden" name="from" value="<%= viewer.login %>">
|
||||
<span class="meta">Renamed on Twitch? New name:</span>
|
||||
<input name="to" required pattern="@?\w{2,25}" placeholder="new Twitch login" style="width:14rem; margin:0; padding:.25rem .5rem; font-size:.85rem; height:auto;">
|
||||
<button type="submit" class="outline btn-sm">Move</button>
|
||||
</form>
|
||||
<% } %>
|
||||
<form method="POST" action="/stats/viewer/forget" style="margin-top:1rem;">
|
||||
<input type="hidden" name="login" value="<%= viewer.login %>">
|
||||
<input type="hidden" name="user_id" value="<%= viewer.user_id || '' %>">
|
||||
<button type="button" data-confirm class="outline btn-sm" style="color:#f88; border-color:#f88;"
|
||||
title="For removal requests: deletes all of this viewer's statistics, watch time, stored chat and activity-log entries. Cannot be undone.">Forget this viewer</button>
|
||||
</form>
|
||||
<% } %>
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@
|
|||
<div>
|
||||
<div class="card">
|
||||
<h4>Test</h4>
|
||||
<textarea id="text" rows="3" maxlength="<%= maxChars %>">Streamer! Hydrate check. Also, nice shot. I was totally not camping that container.</textarea>
|
||||
<textarea id="text" rows="3" maxlength="<%= maxChars %>">Hydrate check! Also, nice shot. I was totally not camping that container.</textarea>
|
||||
<div class="row">
|
||||
<button type="button" id="play" class="btn-sm">▶ Play</button>
|
||||
<button type="button" id="stop" class="outline secondary btn-sm">■ Stop</button>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue