# CLAUDE.md ## Running the app ```bash npm install npm run dev # development (nodemon) npm start # production ``` Requires `.env` — copy from `.env.example`. Database is created automatically on startup (better-sqlite3 runs migrations on init). ## Stack - **Node.js** · Express · EJS templates - **better-sqlite3** — SQLite, synchronous, simple - **ws** — WebSocket server for pushing alerts and settings to overlay clients - **tmi.js** — Twitch IRC, runs in the browser on the overlay page (no server-side IRC). Self-hosted at `public/vendor/tmi.min.js` — the npm package has no browser build, downloaded from GitHub release - **multer** — file uploads - **uuid** — UUID generation - **dotenv** — env vars - **express-session** — session management (signed cookie) ## Architecture ``` Twitch ──EventSub WebSocket──► src/eventsub.js ──► dispatch.js ──► ws.js ──► OBS overlay Twitch ──IRC (tmi.js in browser) ────────────────────────────────────────► OBS overlay Dashboard /settings save ────────────────────────────────────────────────► ws.js ──► OBS overlay (settings_update) ``` - `eventsub.js` opens a WebSocket to Twitch on startup, managed as a module-level singleton - On notification it calls `dispatch.dispatchEvent()` - `dispatch.dispatchEvent()` queries matching `event_actions` rows, checks cooldowns, logs to `activity_log`, calls `wss.broadcast()` - `wss` (ws.js) holds all active WebSocket connections from `/ws/overlay` - The overlay JS receives the broadcast and plays the action - Chat messages come directly from tmi.js running in the browser — no server relay - When settings are saved, the server broadcasts `{ type: 'settings_update', settings }` to all overlay clients — overlay updates `S` in place, no OBS reload needed ## Project structure ``` src/ app.js — Express app setup, middleware, router mounting server.js — HTTP server + WebSocket server startup, EventSub init db.js — better-sqlite3 setup, migrations, singleton helpers eventsub.js — Twitch EventSub WebSocket client (module singleton) dispatch.js — event → action resolution, cooldowns, DB log, broadcast ws.js — WebSocket connection manager cooldowns.js — in-memory cooldown tracking routers/ auth.js — /auth/* (Twitch OAuth) dashboard.js — / (activity log, EventSub status) overlay.js — /overlay/:uuid, /ws/overlay actions.js — /actions CRUD media.js — /media upload/delete settings.js — /settings views/ layout.ejs — base shell (nav, Pico CSS) login.ejs dashboard.ejs overlay.ejs — OBS browser source actions.ejs media.ejs settings.ejs public/ media/ — uploaded files (gitignored) vendor/ tmi.min.js — self-hosted tmi.js browser build ``` ## Key conventions **No passwords anywhere.** Auth is Twitch OAuth only. Session stored via `express-session` with a signed cookie. `req.session.userId` stores the DB user ID after login. **Singleton tables.** `settings` and `overlay_layout` each have one row (id=1). `db.getSettings()` and `db.getLayout()` create the row on first call if missing. **Cooldowns are in-memory.** `cooldowns.js` tracks `{ actionId: triggeredAt }`. Restarting the server resets all cooldowns. Intentional — DB cooldowns not worth the complexity. **Multiple actions per event.** `dispatchEvent()` loops through ALL matching `event_actions` rows and fires each one (subject to its own cooldown). No "first match wins". **Event matching rules:** - `event_type="command"`: `event_detail` must match the command name (case-insensitive) - `event_type="bits"`: if `event_detail` set, treat as minimum bits threshold - `event_type="channel_points"`: `event_detail` is the reward ID; null matches any reward - `event_type="sub"/"gift_sub"`: `event_detail` is tier ("1000", "2000", "3000"); null matches any - `event_type="follow"/"raid"`: `event_detail` not used **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. 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 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; }; ``` ## Route map | Method | Path | File | Notes | |---|---|---|---| | GET | `/` | routers/dashboard.js | Activity log, EventSub status | | GET | `/auth/login` | routers/auth.js | Login page | | GET | `/auth/twitch` | routers/auth.js | Redirect to Twitch OAuth | | 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 | | 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 | | POST | `/actions/:id/toggle` | routers/actions.js | Enable/disable | | 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 | `/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 chat position and style The layout editor was removed (2026-11-20); the `overlay_layout` table is still created but unused, so old data is kept. The legacy text/video action alert position lives in the `:root` block of `views/overlay.ejs`. Chat (`?parts=chat`) is `public/chat/chat.css` + `public/chat/chat.js` (window.HSChat), fed by tmi.js in overlay.ejs: - Look: cream paper slips, name on a washi-tape label tinted with the chatter's Twitch colour, slight random tilt. - Flow: the box sits under the webcam (Game scene camera group 1920,600 640x360 on the 2560 canvas), newest on top; a new message slides out from under the camera, the rest glide down (FLIP with the `translate` property) and the oldest dissolve at the bottom (mask-image fade). Expire after `message_timeout` s, cap `max_messages`. - Move/resize with Custom CSS: `#chat { --chat-top: 63%; --chat-right: 2%; --chat-width: 20%; --chat-height: 34%; }`. - Emotes: Twitch (from `tags.emotes`, code-point ranges) + 7TV global and channel sets (`7tv.io/v3`, channel by `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). ## TTS voices (/tts) Builder page to make named TTS voices, used by redeem variations (Redeems page: "TTS: " per variation). - Redeem with a TTS voice + viewer text: `redeems.addSpeech()` cleans the text (`tts.prepareViewerText`: links out, repeats collapsed, cut to `settings.tts_max_chars` at a word, `settings.tts_blocklist` -> nothing read, letter says "(message removed)"; whole-word matching with plurals, look-alike swaps and spaced-out letters; starter list `src/tts-blocklist.txt` is merged into the setting once, `tts_blocklist_seeded`), synthesizes " says: " (`tts_say_name`), and only then sends the alert with `tts` (URL), `tts_ms`, `tts_env` (loudness per 40 ms, `tts.loudness()`) and `tts_prefix` (words said before the message). Shown as the envelope letter (style `tts`, `public/alerts/fx.js` envelope(), CSS in fx.css): flap opens, the letter rises out and settles in front ~80px from the top, words ink in as spoken (timing estimated from tts_env; if the voice does not start, the whole text shows). Design preview: `~/Desktop/Stream/tts-alerts/`. TTS on = the variation's sound is not sent (the voice replaces it; the Redeems page greys the picker out). Synthesis errors: the note still shows, silent. - Dashboard "Skip current alert" -> POST `/alerts/skip` -> WS `{type:'alert_skip'}` -> `PolaroidAlerts.skip()`. - `tts_blocklist` never goes to overlay pages: they get `db.getOverlaySettings()` (render and settings_update). - New columns on existing DBs are added by `db.migrate()` (`addColumn`, ALTER only when missing). - `src/tts.js`: `synth(config, text)` -> cached mp3 in `public/tts/.mp3` (gitignored, newest 300 kept). Config = up to 3 `layers` (engine `piper`|`espeak`, voice, speaker, speed, pitch in semitones, volume, delay ms) + `effects` {stadium, echo, crush, radio, robot, chorus, flanger, tremolo: 0..1}. `normalize()` clamps everything and only accepts plain voice/speaker names (no paths). Pitch = asetrate+atempo (formants shift too: the demon sound). ffmpeg: per-layer pitch/volume/delay -> amix -> effects -> loudnorm -> mono mp3. - `tools/tts/worker.py`: long-running Python process (JSON lines over stdin/stdout), started on first use. Piper models stay loaded (LRU, `TTS_MAX_LOADED`=4, ~100 MB each); espeak-ng via libespeak-ng + ctypes (no binary needed). - Setup (server): `sudo apt install python3-venv ffmpeg espeak-ng`, then `tools/tts/setup.sh` (venv + default voices into `tools/tts/voices/`, both gitignored). Extra voices: `tools/tts/setup.sh en_US-amy-medium ...`. Env overrides: `TTS_PYTHON`, `TTS_VOICES_DIR`. - Table `tts_voices` (name, config JSON). Routes: GET `/tts`, POST `/tts/preview`, POST `/tts/voices`, POST `/tts/voices/:id/delete`. - SAM (C64 voice) was left out on purpose: the only JS port has no licence (abandonware). ## Gap / new-message audio Configured in `settings`. When a chat message arrives in the overlay, tmi.js checks: 1. Is `gap_audio_enabled` true and `gap_audio_url` set? 2. Has at least `gap_audio_min_silence` seconds passed since the last message? 3. If yes: play the audio. Volume = linear interpolation between `gap_audio_min_volume` and `gap_audio_max_volume` based on silence duration vs `gap_audio_loud_after`. All logic runs in the browser. The server pushes updated settings to the overlay via WebSocket on save — no OBS reload needed. Gap audio has `[gap]` debug logging in the browser console. ## Custom events dispatched to overlay JS When the overlay WebSocket receives a message: - **Action broadcast:** `document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }))` Available types: `sub`, `gift_sub`, `bits`, `channel_points`, `command`, `follow`, `raid`. `msg` shape: `{ event_type, action_type, media_url, alert_text, username }`. - **Settings update:** `{ type: 'settings_update', settings }` — overlay does `Object.assign(S, msg.settings)` to update live. Alert text supports `{username}` interpolation. ## Database schema ```sql users — Twitch OAuth user (twitch_id unique) settings — singleton id=1: overlay_id, channel, gap audio, message_timeout, custom_css/js overlay_layout — singleton id=1: widget positions and styles media_files — uploaded sounds/videos event_actions — event → action mapping (media_file_id FK) activity_log — append-only event log ``` ## EventSub subscriptions | Twitch event | Version | Condition | Scope | Used for | |---|---|---|---|---| | `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | follow 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` | 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, community gift totals and the resub message. `sub_gift` notices with a `community_gift_id` are skipped (the `community_sub_gift` notice covers the whole bomb), so a gift bomb is one alert. **Lifecycle (src/eventsub.js, src/twitch.js):** - Started on boot from the stored login (`db.getPrimaryUser()`), and again after OAuth login. `EVENTSUB_DISABLED=1` skips it (local UI work). - Token: validated hourly and before subscribing; refreshed when it expires or on any 401 (`twitch.helix()`), new tokens saved to `users`. - `session_reconnect`: connects to the given URL (subscriptions carry over), swaps sockets on its welcome. - 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//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/`). 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` (`?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 ``` Twitch EventSub ─► eventsub.js ─► alerts.js (fromFollow / fromCheer / fromChatNotification) ─► alerts.send() Overlay chat (tmi.js USERNOTICE viewermilestone) ─► WS up {type:'chat_notice'} ─► alerts.fromOverlayNotice() ─┘ alerts.send() ─► ws.broadcast({type:'alert', alert}) ─► overlay ─► public/alerts/polaroid.js (queue + animation + sound) └─► 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/`. 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=` 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`). 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 Runs behind Apache on the VPS as a reverse proxy to Node on port 3000. Production domain: `https://overlay.example.com` Apache vhost config is managed by `~/projects/apache.sh` (run on the VPS). 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: ```bash rsync -avzO --exclude='node_modules' --exclude='.env' --exclude='public/media' \ ~/projects/heystreamer/ user@your-server:/opt/heystreamer/ ssh user@your-server "cd /opt/heystreamer && npm install --production && sudo systemctl restart heystreamer" ``` Twitch requires HTTPS for OAuth redirect URIs in production. Register both in the Twitch dev console: - `http://localhost:3000/auth/callback` (dev) - `https://overlay.example.com/auth/callback` (production) ## Not yet implemented - Mod access (streamer-only login for now) - Chat commands triggering actions - Stripe / PayPal / ETH payment notifications - Multiple overlays (multi-user; UUID foundation is in place) - HudFX integration