Wire it up: Twitch events, dashboard, overlay parts, layout editor removed

Twitch / server
- bits via channel.bits.use (cheers + Power-ups, replaces channel.cheer); built-in
  channel point rewards; polls; Hype Train v2; outgoing raids. New scopes:
  channel:read:polls, channel:read:hype_train, channel:manage:raids (log in again).
- Hype Train: alerts on start / each new level / end, plus the progress bar.
- Raid send-off: start/cancel raids from the dashboard (Helix /raids); the card
  stays until channel.raid reports the raid happened.
- StreamElements client started on boot; tip alerts.

Dashboard
- Twitch + StreamElements status, test buttons (poll, Hype Train bar, raid card),
  Raid box, activity Reload + auto-refresh, Redeems in the nav.
- Two-click delete instead of browser confirm() on Media and Actions.

Overlay
- ?parts= splits the overlay into OBS sources: chat, alerts, poll, hypebar, raid,
  or exclusions like ?parts=nochat. Recommended: ?parts=chat (audio Monitor Only,
  chat sounds stay off stream) + ?parts=nochat.
- Now playing switched off (commented, see CLAUDE.md to re-enable).

Removed the layout editor and preview page; chat position/style is baked into
overlay.ejs from the last saved layout (overlay_layout table kept, unused).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-20 23:18:15 +02:00
parent b28e56f991
commit cdcd3737a7
17 changed files with 589 additions and 140 deletions

132
CLAUDE.md
View file

@ -51,18 +51,15 @@ src/
routers/
auth.js — /auth/* (Twitch OAuth)
dashboard.js — / (activity log, EventSub status)
overlay.js — /overlay/:uuid, /overlay/:uuid/preview, /ws/overlay
overlay.js — /overlay/:uuid, /ws/overlay
actions.js — /actions CRUD
media.js — /media upload/delete
layout.js — /layout editor + /layout/positions
settings.js — /settings
views/
layout.ejs — base shell (nav, Pico CSS)
login.ejs
dashboard.ejs
overlay.ejs — OBS browser source
overlay_preview.ejs
layout_editor.ejs
actions.ejs
media.ejs
settings.ejs
@ -91,7 +88,7 @@ public/
**UUID overlays.** `settings.overlay_id` is a UUID generated on first run. OBS browser source URL is `/overlay/:uuid`. Future multi-user support creates multiple settings rows.
**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. The DB `overlay_layout` row is passed as `overlayLayout` in all render calls.
**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. Pass `layout: false` to render without the shell (overlay, `_activity` partial).
**Form value parsing.** Never use `parseInt(val) || default` — it overwrites valid `0` values. Use:
```javascript
@ -109,7 +106,6 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
| GET | `/auth/callback` | routers/auth.js | Exchange code, save user, start EventSub |
| GET | `/auth/logout` | routers/auth.js | Clear session |
| GET | `/overlay/:uuid` | routers/overlay.js | Live OBS browser source |
| GET | `/overlay/:uuid/preview` | routers/overlay.js | Mock preview for layout editor |
| WS | `/ws/overlay` | routers/overlay.js | Bidirectional: commands up, actions down |
| GET/POST | `/actions` | routers/actions.js | List and create actions |
| POST | `/actions/:id/test` | routers/actions.js | Fire immediately, skip cooldown |
@ -117,31 +113,17 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
| DELETE | `/actions/:id` | routers/actions.js | Delete |
| GET/POST | `/media` | routers/media.js | Upload, list |
| DELETE | `/media/:id` | routers/media.js | Delete file + DB row |
| GET/POST | `/layout` | routers/layout.js | Position + style form (saves all layout fields) |
| POST | `/layout/positions` | routers/layout.js | JSON position update (legacy, kept for future drag) |
| GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS; broadcasts settings_update on save |
| POST | `/settings/reconnect` | routers/settings.js | Restart EventSub |
| GET | `/activity` | routers/dashboard.js | Activity table partial (dashboard Reload / auto-refresh) |
| POST | `/alerts/test/:key` | routers/alerts.js | Send a sample polaroid alert to the overlay |
## Overlay CSS variable system
## Overlay chat position and style
All overlay positioning and styling uses CSS custom properties rendered into `overlay.ejs` and `overlay_preview.ejs` from the `overlay_layout` row:
| Variable | Controls |
|---|---|
| `--chat-left`, `--chat-top` | Chat box position (%) |
| `--chat-width`, `--chat-height` | Chat box size (%) |
| `--chat-font-size` | Chat font size (px) |
| `--chat-font-family` | Chat font family |
| `--chat-bg-opacity` | Chat message background opacity |
| `--chat-text-color` | Chat message text colour |
| `--chat-border-radius` | Message border radius (px) |
| `--alert-left`, `--alert-top` | Alert position (%, centered via transform) |
| `--alert-font-size` | Alert font size (px) |
| `--alert-bg-opacity` | Alert background opacity |
| `--alert-text-color` | Alert text colour |
The layout editor (`/layout`) shows position and style inputs, with a scaled iframe preview of `/overlay/:uuid/preview`. Position inputs update CSS variables in the iframe live on `input` event. All fields (position + style) are saved via `POST /layout`.
The layout editor was removed (2026-11-20). Chat box position/size/font and the legacy text/video action alert
position are fixed CSS custom properties in the `:root` block of `views/overlay.ejs` (values copied from the last
saved layout). Change them there, or override with Custom CSS in Settings. The `overlay_layout` table is still
created but unused, so old data is kept.
## Gap / new-message audio
@ -180,9 +162,10 @@ activity_log — append-only event log
| Twitch event | Version | Condition | Scope | Used for |
|---|---|---|---|---|
| `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | follow alert |
| `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` | bits alert |
| `channel.bits.use` | 1 | `broadcaster_user_id` | `bits:read` | cheers (bits alert) **and** Power-ups (`type: power_up` → Redeems); replaced `channel.cheer` |
| `channel.chat.notification` | 1 | `broadcaster_user_id` + `user_id` | `user:read:chat` | subs, resubs, Prime, multi-month, gifts, community gifts, raids |
| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | actions only (no polaroid yet) |
| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | channel point rewards → Redeems |
| `channel.channel_points_automatic_reward_redemption.add` | 2 | `broadcaster_user_id` | `channel:read:redemptions` | built-in rewards (highlight message, emote unlocks) → Redeems |
`channel.chat.notification` replaced `channel.subscribe` / `subscription.message` / `subscription.gift` / `channel.raid`:
one event carries `is_prime`, `duration_months` (months bought at once), `cumulative_months`, the gift recipient,
@ -196,6 +179,93 @@ community gift totals and the resub message. `sub_gift` notices with a `communit
- Keepalive watchdog: no message for `keepalive_timeout_seconds + 10s` → reconnect.
- Status (connected / subscribed / failed / last event) shown on the dashboard.
## Redeems (channel points, built-in rewards, bits Power-ups)
Page `/redeems` (src/routers/redeems.js, views/redeems.ejs, logic in src/redeems.js), table `reward_variations`.
- A trigger is `kind` + `key`: `reward` + Twitch reward id, `auto_reward` + built-in type, `power_up` + Power-up type.
- Each trigger has variations (name, rarity, sound, volume, polaroid on/off, caption, art, enabled). On a redemption
ONE enabled variation is picked at random, weighted by rarity (`RARITY` in src/redeems.js: weights Common 50 / Uncommon 25 / Rare 12 / Ultra Rare 3 (Twitch's Super Rare merged into Ultra Rare); chance = weight ÷ sum of the trigger's enabled weights), like
Twitch alert variations. No enabled variation → only logged (and legacy actions run).
- Custom rewards are listed live from Helix `GET /channel_points/custom_rewards` (title, cost, icon); built-in rewards
and Power-ups are fixed lists. Titles are refreshed when a redemption arrives with a new name.
- 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).
- 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).
Emote image = `https://static-cdn.jtvnw.net/emoticons/v2/<id>/default/dark/3.0` from `event.power_up.emote.id`
(fallback: heart). Default caption becomes "gigantified an emote!" / "is celebrating!" / "highlighted:".
- Sound picker = `public/alerts/sounds/redeems/` (redeem clips, loudness-normalized to -16 LUFS with ffmpeg
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
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
yet seen live; check `activity_log.data_json` of the first real Power-up.
## Raid send-off and Hype Train bar
- Outgoing raid send-off: Twitch has no "raid started" event, so raids are started from the dashboard Raid box
(`POST /alerts/raid/start` → Helix `POST /raids`, scope `channel:manage:raids`; `/alerts/raid/cancel` → `DELETE /raids`).
The silent card (`public/alerts/raidcard.js`, top-centre polaroid with the target's Twitch avatar, "raiding X / with N
of you, be nice! ♡", 90 s countdown) stays until `channel.raid` (`from_broadcaster_user_id` = us) arrives, then
shows "raid sent!" and leaves. Raid started on Twitch directly: card shows only at that moment. Test: `raid-card-test`.
- Hype Train bar: every `channel.hype_train.*` event also goes out as `{type:'hype_bar', phase, train}`;
`public/alerts/hypebar.js` shows a slim taped strip top-left (LV, progress/goal bar, time left; gold for Golden
Kappa), outside the queue; on end it shows the final level for 5 s and slides away. Test: dashboard `hype-bar-test`.
## Overlay parts (two OBS sources)
`/overlay/:uuid?parts=` picks what a browser source shows: `chat` (chat box + gap audio), `alerts` (polaroid queue,
redeems, legacy actions), `poll`, `hypebar`, `raid`. List parts (`?parts=chat,raid`) or exclude them with `no<part>`
(`?parts=nochat`, `?parts=nochat,noraid`). No `?parts=` = all. Recommended: `?parts=chat` as a source with audio
"Monitor Only (mute output)" (chat sounds stay off stream) and `?parts=nochat` as the main source. Every source receives every WebSocket message and ignores the parts it does not show, so nothing plays twice.
Every source still listens to chat for watch streaks; the server dedupes the reports by message id.
## Now playing (Feishin) — SWITCHED OFF for now
Kept in the repo but disabled: the `/nowplaying` route is commented out in `src/app.js`, `nowplaying` is not in
`PARTS` (src/routers/overlay.js) and the overlay lines are commented (marked NOWPLAYING in views/overlay.ejs).
To re-enable: undo those three. Description of how it works when enabled:
- `tools/nowplaying/feishin_nowplaying.py` runs on the streaming PC: watches Feishin over MPRIS (D-Bus, PyGObject),
POSTs `{status,title,artist,album,length,cover}` to `/nowplaying` with `Authorization: Bearer NOWPLAYING_KEY`
on every change + every 30 s. Config `~/.config/heystreamer-nowplaying.env` (HEYSTREAMER_URL, NOWPLAYING_KEY);
systemd user unit next to the script.
- Feishin's `mpris:artUrl` points at Navidrome on the LAN and carries the Subsonic token: the helper downloads the
cover itself and sends a 160 px JPEG data URL, so no URL/credential ever leaves the PC.
- Server: `src/routers/nowplaying.js` (key check, sanitised fields, data-URL-only cover) → `src/nowplaying.js` keeps
the current song and broadcasts `{type:'nowplaying', np}`; new overlay connections get it on connect.
- Overlay: `public/alerts/nowplaying.js` small taped paper slip (cover, title, artist) top-right, visible only while
`playing`; hides 1.5 s after pause/stop (grace so track changes do not flicker). Chat position unchanged.
## StreamElements tips
- `src/streamelements.js`: Astro websocket (`wss://astro.streamelements.com`, override `SE_URL` for tests). Off unless
`SE_JWT` is set in `.env` (StreamElements dashboard → avatar → channel → JWT token; secret, never commit).
- welcome → subscribe `{topic:'channel.tips', token, token_type:'jwt'}` → `message` on `channel.tips`; tip fields in
`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).
Turn off StreamElements' own tip alert in its overlay to avoid doubles.
## Polls and Hype Train
- Polls (`channel.poll.begin/progress/end` v1, scope `channel:read:polls`): `alerts.sendPoll()` broadcasts
`{type:'poll', phase, poll}`; `public/alerts/poll.js` shows a live taped-paper card (left, below the alert corner,
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
art; sounds pro-gamer / toad-ya-hoo / tadaaa (in `describe()` case 'hype'). Golden Kappa / Treasure trains named.
## Polaroid alerts
```
@ -205,9 +275,10 @@ alerts.send() ─► ws.broadcast({type:'alert', alert}) ─► overlay ─► p
└─► dispatch.dispatchEvent() (activity log + legacy actions keep working)
```
- Alert shape and per-event look (art, caption, tape colour, badge, sound, bits tiers) live in `public/alerts/polaroid.js` (`describe()` + CONFIG block). Art in `public/alerts/art/`, sounds in `public/alerts/sounds/` (lengths in `SOUND_MS`, so the alert holds for the whole sound).
- Alert shape and per-event look (art, caption, tape colour, badge, sound, bits tiers) live in `public/alerts/polaroid.js` (`describe()` + CONFIG block). Art in `public/alerts/art/`, sounds in `public/alerts/sounds/`. Sound lengths come from `SOUND_MS` or are measured in the browser (redeem sounds picked in the UI), so the alert holds for the whole sound. Redeem alerts carry their own sound URL, volume, art and caption.
- Watch streaks only exist in chat. The overlay reports them; the server only accepts `chat_notice` from WS connections that pass `?overlay=<overlay_id>` and dedupes by message id (several overlays may report the same notice).
- Test buttons on the dashboard: `POST /alerts/test/:key` (keys = `alerts.TEST_KEYS`). Test alerts (`test:true`) replace what is showing; `queue-test` sends four that queue. Not logged, no actions fired.
- Test buttons on the dashboard: `POST /alerts/test/:key` (keys = `alerts.TEST_KEYS`). A test alert (`test:true`, `PolaroidAlerts.playTest`) instantly replaces another *test* alert, but never cuts off or drops a real one: it queues behind it. A real alert arriving during a test cuts the test off. `queue-test` sends four that queue. Not logged, no actions fired.
- Timing: entrance animation ~2.4 s (+0.12 s per stacked photo), then it stays `AFTER_ANIM` (3 s) — or until the sound ends if that is later (sound starts 0.4 s in) — then a 0.65 s exit. ~6 s for most alerts, ~9.3 s for 150+ bits, ~11.1 s for 250+ bits.
- Bits under 5: no alert (`BITS_MIN`).
## Production deployment
@ -240,4 +311,3 @@ Twitch requires HTTPS for OAuth redirect URIs in production. Register both in th
- Stripe / PayPal / ETH payment notifications
- Multiple overlays (multi-user; UUID foundation is in place)
- HudFX integration
- Drag-to-reposition in layout editor (removed — CSS transform + interact.js coordinate mismatch; use the position inputs instead)