heystreamer/CLAUDE.md
Bashy d481fc4f69 Add polaroid alerts for follows, subs, gifts, streaks, raids and bits
Overlay
- public/alerts/polaroid.js + .css: animated polaroid (photo drops in, tape
  and heart stick on, caption writes in), randomized angles, per-event art,
  caption, tape colour, badge and sound, fanned photo stack for multi-month
  subs / community gifts / raids, and a queue so alerts never overlap.
- Bits: no alert under 5; sound tiers at 5/50/75/100/150/250.
- Watch streaks are read from chat (USERNOTICE viewermilestone) and reported
  to the server over the overlay WebSocket.

Server
- Subscribe to channel.chat.notification instead of channel.subscribe /
  subscription.message / subscription.gift / channel.raid: one event with
  Prime, months bought at once, gift recipient, resub message and community
  gift totals. Per-recipient gift notices of a gift bomb are skipped, so a
  bomb is one alert (was N+1). Needs the user:read:chat scope (log in again).
- src/alerts.js maps Twitch events to alerts, broadcasts them and still runs
  them through dispatch (activity log + existing actions).
- EventSub starts on boot from the stored login (alerts survive restarts),
  validates the token hourly and refreshes it on expiry or 401, follows
  session_reconnect without dropping events, and reconnects when keepalives
  stop.
- The overlay WebSocket only accepts chat_notice messages from connections
  that pass the overlay UUID; streak notices are deduped by message id.

Dashboard
- Twitch connection status and a test button per alert (POST /alerts/test/:key).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:57:36 +02:00

13 KiB

CLAUDE.md

Running the app

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, /overlay/:uuid/preview, /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
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. The DB overlay_layout row is passed as overlayLayout in all render calls.

Form value parsing. Never use parseInt(val) || default — it overwrites valid 0 values. Use:

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
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
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 /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
POST /alerts/test/:key routers/alerts.js Send a sample polaroid alert to the overlay

Overlay CSS variable system

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.

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

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.cheer 1 broadcaster_user_id bits:read bits alert
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.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.

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/ (lengths in SOUND_MS, so the alert holds for the whole sound).
  • 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.
  • 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:

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
  • Drag-to-reposition in layout editor (removed — CSS transform + interact.js coordinate mismatch; use the position inputs instead)