diff --git a/.env.example b/.env.example index 1158885..a99ff3f 100644 --- a/.env.example +++ b/.env.example @@ -10,3 +10,9 @@ SECRET_KEY=change_this_to_a_random_string APP_BASE_URL=https://overlay.example.com DB_PATH=./heystreamer.db PORT=3000 + +# StreamElements tips (optional): dashboard -> avatar -> channel -> JWT token. Keep it secret. +SE_JWT= + +# Now playing (Feishin) helper: long random secret shared with tools/nowplaying (e.g. `openssl rand -hex 32`). +NOWPLAYING_KEY= diff --git a/.gitignore b/.gitignore index d39b694..d04529b 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,29 @@ __pycache__/ venv/ static/media/* !static/media/.gitkeep + +# Node +node_modules/ +*.db-shm +*.db-wal +public/media/* +!public/media/.gitkeep + +# TTS: generated audio, Piper install and voice models (tools/tts/setup.sh) +public/tts/ +tools/tts/venv/ +tools/tts/voices/ + +# Twitch analytics exports (channel data, revenue): import them on the Stats page, never commit them +*.csv + +# The channel's own media library (pictures, stickers, sounds, videos picked on Actions → Alerts / Redeems): +# stays on disk and travels with the rsync deploy, never in git. Everything else is set in the dashboard (database). +public/alerts/art/* +!public/alerts/art/placeholder.svg +public/alerts/stickers/ +public/alerts/sounds/ +public/alerts/videos/* +!public/alerts/videos/.gitkeep +# this channel's deployment notes for Claude Code (hosts, server user) +CLAUDE.local.md diff --git a/CLAUDE.md b/CLAUDE.md index 06b7e62..a1bec27 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,8 +14,8 @@ Requires `.env` — copy from `.env.example`. Database is created automatically - **Node.js** · Express · EJS templates - **better-sqlite3** — SQLite, synchronous, simple -- **ws** — WebSocket server for pushing alerts to overlay clients -- **tmi.js** — Twitch IRC, runs in the browser on the overlay page (no server-side IRC) +- **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 @@ -26,6 +26,7 @@ Requires `.env` — copy from `.env.example`. Database is created automatically ``` 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 @@ -34,6 +35,7 @@ Twitch ──IRC (tmi.js in browser) ────────────── - `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 @@ -49,23 +51,22 @@ 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 public/ media/ — uploaded files (gitignored) + vendor/ + tmi.min.js — self-hosted tmi.js browser build ``` ## Key conventions @@ -87,6 +88,14 @@ 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. 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 | @@ -97,7 +106,6 @@ public/ | 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 | @@ -105,30 +113,61 @@ public/ | 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 | Style form | -| POST | `/layout/positions` | routers/layout.js | JSON, called by drag JS | -| GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS | +| 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: +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`. -| 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 | +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. -The layout editor (`/layout`) overlays drag handles on an iframe pointing to `/overlay/:uuid/preview`. Same-origin, so the editor sets CSS variables directly on the iframe's document for live preview. Saved via `POST /layout/positions`. +## Overlay updates after a deploy + +OBS keeps an overlay page running for hours, so after a deploy it would keep the old alert code. `src/ws.js` has a +`BOOT_ID` (new on every server start); the overlay page is rendered with it, and the server sends +`{type:'hello', boot}` on every WebSocket connect. When the overlay reconnects after a restart and the ID differs, it +reloads itself (1.5 s later). Asset URLs in overlay.ejs carry `?v=` so the reload never uses cached files. + +## 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 @@ -137,19 +176,19 @@ Configured in `settings`. When a chat message arrives in the overlay, tmi.js che 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 only serves the config. +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 an action broadcast: +When the overlay WebSocket receives a message: -```javascript -document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg })); -``` +- **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 }`. -Available: `sub`, `gift_sub`, `bits`, `channel_points`, `command`, `follow`, `raid`. +- **Settings update:** `{ type: 'settings_update', settings }` — overlay does `Object.assign(S, msg.settings)` to update live. -`msg` shape: `{ event_type, action_type, media_url, alert_text, username }`. +Alert text supports `{username}` interpolation. ## Database schema @@ -164,51 +203,176 @@ activity_log — append-only event log ## EventSub subscriptions -| Twitch event | Version | Condition | Scope | -|---|---|---|---| -| `channel.subscribe` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | -| `channel.subscription.message` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | -| `channel.subscription.gift` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | -| `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` | -| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | -| `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | -| `channel.raid` | 1 | `to_broadcaster_user_id` | none | +| 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 | -Token refresh triggered on 401 during subscription. +`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; '' = 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). + 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` (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 + 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 (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 + +- 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). theme art + 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` +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). -Minimal Apache vhost config (requires `mod_proxy`, `mod_proxy_http`, `mod_proxy_wstunnel`): -```apache - - ServerName overlay.example.com +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` - ProxyPreserveHost On - 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/ - - # SSL config here (certbot/Let's Encrypt) - -``` - -The `/ws/overlay` must be proxied separately with `ws://` via `mod_proxy_wstunnel` — if it's not listed before the catch-all `/`, WebSocket connections will fail. Enable the required modules with: +Deploy by copying the working folder (rsync), not by git: the channel's media library is not in git and must travel too. ```bash -sudo a2enmod proxy proxy_http proxy_wstunnel -sudo systemctl reload apache2 +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" ``` 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) +## 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 -- Alert variable interpolation (`{username}` in alert text) - Mod access (streamer-only login for now) - Chat commands triggering actions - Stripe / PayPal / ETH payment notifications diff --git a/apache.example.sh b/apache.example.sh new file mode 100644 index 0000000..2b2a5a1 --- /dev/null +++ b/apache.example.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Template (copy to apache.sh, not in git, and use your own hosts). Writes /etc/apache2/sites-available/overlay.example.conf and reloads Apache. +# Run on the VPS: bash apache.sh +set -e + +CONF=/etc/apache2/sites-available/overlay.example.conf + +sudo tee "$CONF" > /dev/null << 'EOF' +# ── overlay.example.com + heystreamer.example.com + stats.example.com ─────── +# stats.example.com = the public stats page (the app serves ONLY that page on this host). +# Its certificate: sudo certbot certonly --apache --cert-name example.com --expand -d -d stats.example.com +# HTTP: redirect everything to HTTPS + + ServerName overlay.example.com + ServerAlias heystreamer.example.com stats.example.com + + RewriteEngine on + RewriteCond %{SERVER_NAME} =heystreamer.example.com [OR] + RewriteCond %{SERVER_NAME} =stats.example.com [OR] + RewriteCond %{SERVER_NAME} =overlay.example.com + RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] + + ErrorLog ${APACHE_LOG_DIR}/example.com/overlay.error.log + CustomLog ${APACHE_LOG_DIR}/example.com/overlay.access.log combined + + +# HTTPS: proxy to Node on port 3000 + + + ServerName overlay.example.com + ServerAlias heystreamer.example.com stats.example.com + + ProxyPreserveHost On + + # Tell Express it's behind HTTPS so secure session cookies work + RequestHeader set X-Forwarded-Proto "https" + + Header always unset Content-Security-Policy + Header always set Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' https: wss: data:;" + + # WebSocket must be listed before the catch-all + ProxyPass /ws/overlay ws://127.0.0.1:3000/ws/overlay + ProxyPassReverse /ws/overlay ws://127.0.0.1:3000/ws/overlay + + ProxyPass / http://127.0.0.1:3000/ + ProxyPassReverse / http://127.0.0.1:3000/ + + ErrorLog ${APACHE_LOG_DIR}/example.com/overlay.error.log + CustomLog ${APACHE_LOG_DIR}/example.com/overlay.access.log combined + + Include /etc/letsencrypt/options-ssl-apache.conf + SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem + + +EOF + +echo "==> Enabling required modules..." +sudo a2enmod proxy proxy_http proxy_wstunnel headers rewrite + +echo "==> Enabling site..." +sudo a2ensite overlay.example.conf + +echo "==> Testing config..." +sudo apachectl configtest + +echo "==> Reloading Apache..." +sudo systemctl reload apache2 + +echo "Done. Try logging in at https://overlay.example.com" diff --git a/docs/PLANS.md b/docs/PLANS.md new file mode 100644 index 0000000..fc8487c --- /dev/null +++ b/docs/PLANS.md @@ -0,0 +1,106 @@ +# HeyStreamer plans + +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. " points"). + +| Action | Points | Notes | +|---|---|---| +| Chat message | 10 | max 1 per 5 min per viewer (counted at ingestion: chat_user.scored / chat_user_day.scored) | +| First message in a stream (check-in) | 25 | once per stream (stream_checkin, built with watch time) | +| First message ever on the channel | 50 | Twitch's first-time chatter flag, kept in chat_user.intro | +| Follow | 50 | once | +| Watch streak | 5 x streak | max 100 | +| Channel point redeem | 1 per 100 points spent | | +| Cheer / Power-up / Custom Power-up | 1 per bit | | +| Sub Tier 1 / Prime | 500 per month | resubs: their months | +| Sub Tier 2 / Tier 3 | 1000 / 2500 per month | | +| Gift sub | as a sub, per gifted sub | to the gifter | +| Tip | 100 per 1 EUR | | +| Incoming raid | 100 flat | no reward for raid size | +| 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), 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 (decided: records of support, like Twitch keeps); forget-a-viewer removes theirs. + +## 1. Free uses of Custom Power-ups ("refund") + +**Why:** when a viewer paid for a Power-up but it did not show (overlay was off, OBS crashed, server down), +give them one free use to trigger it again. + +**How it would work** +- Granting: on the **Redeems page**, a small "Give a free use" control (viewer name + Power-up + count) next to + the page's reload/save controls. Later maybe also a mod chat command (`!giveuse @viewer jumpscare`). +- Using: the viewer types the Power-up's command, made from its name (`Jump Scare` → `!jumpscare`, renameable). + With a free use left it plays like a bits Power-up (random variation, video + box), the box says + **free use** instead of the bits amount. Without one: nothing happens. +- Storage: table `power_up_credits (user_id, user_login, power_up_id, uses, granted_by, granted_at)`. +- Recent activity logs grants and uses (with Replay). + +**Needs:** chat read on the server (see 3), credits table, Redeems UI, command handling. +Estimate: about half a day once chat is read server-side. + +## 2. Own chat bot in HeyStreamer (instead of StreamElements' bot) + +**Why:** one place for alerts, redeems, commands and replies; no third-party bot. + +**Rough shape** +- 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 + (everyone / sub / VIP / mod), variables like `{user}`, `{uptime}`, `{count}`. +- Timers (repeating messages while live), shoutouts, free-use replies (see 1). +- Move StreamElements' commands over, then turn its bot off. StreamElements stays for tips until replaced. + +## 3. Chat log for statistics + +**Why:** advanced statistics later (activity over time, regulars, first-time chatters, emote use, peak moments). + +**Rules (GDPR, Twitch developer rules)** +- Log on the server via EventSub `channel.chat.message` (works without OBS, no duplicates). +- Store only: message id, time, user id + login + display name, text, badges, emotes, first-message / reply flags. +- Honour moderation: `channel.chat.message_delete`, `channel.chat.clear_user_messages` (timeouts/bans) and + `channel.chat.clear` remove or blank the stored messages. +- Retention: raw messages 30 days (then deleted), aggregated statistics kept. +- "Delete this user's messages" control for removal requests; a line in the Twitch panels that chat is logged + for stream statistics. +- Size: a few MB per month in SQLite. + +Status: **logging built 2026-11-22** (src/chatlog.js), with these choices: per-viewer counts (messages, per day, +emotes incl. 7TV, !commands, first/last seen) parsed as messages arrive; raw messages kept **30 days** only; +moderation removes stored text; hidden chatters (bots) are counted but must be left out of shown +statistics and leaderboards (filter at display time with chatlog.isHidden()). Viewer actions are counted too +(chat_action: rewards + points, Power-ups + bits, cheers, subs, gifts, follows, raids, watch streaks, tips). Still to do: a statistics page, and a +"forget this viewer" button for removal requests (`chatlog.forgetUser()` exists). + +**2026-11-23: per-stream and period statistics + public page.** `src/periodstats.js` keeps one generic table, +`stat_day` (day x stream x viewer x kind x item), fed by chatlog.js (messages, first messages, emotes, commands, +actions) and watchtime.js (watch ticks); backfilled once from the older tables. A new statistic = a new `kind`, +then a section in `views/_statsbody.ejs` (shared by the admin Stats page and the public page). Streams keep title, +game, peak + average viewers. Public page: Settings → Public stats page (its own host name; on that +host nothing else answers; `/public` on the admin host is a preview). It never shows message text, bots, the +streamer on leaderboards, or viewers who typed `!hideme` (`!showme` undoes it; also a button on the viewer page). +The StreamElements watch-time importer is removed; the minutes imported on 2026-11-22 stay as a fixed baseline +(watch_import: All time, points, levels). + +**2026-11-23 (2): data from Twitch** (`src/twitchsync.js`, every 6 h, after each stream, "Sync with Twitch" button): +followers with follow dates (whole history), current subs, mods (`moderation:read`), VIPs (`channel:read:vips`; both +scopes need one new login), all-time bits top 100, the channel's emotes, past streams from VODs (7/60 days only). +Per stream: viewer count every 5 min (`stream_viewers`) and every title/category change (`stream_change`, EventSub +`channel.update`). Not on Twitch's API at all: past viewer counts, past titles, emote use outside this channel. +The old /actions page (event → sound rules, unused) is gone; "Actions" is now the nav group Redeems / TTS / Media. + +**2026-11-23 (3): Twitch analytics CSV** (`src/twitchcsv.js`, Stats → "Import Twitch analytics (CSV)"): the Creator +Dashboard export "Analytics and Revenue by day". No API offers this: export by hand now and then and import again (per day, safe). +Before the cutoff (first day HeyStreamer counted) it supplies messages, watch time, follows, streamed days/hours; +for every day it supplies what only Twitch measures (unique / engaged viewers, clips, live views, average + peak +viewers, revenue). Revenue: admin page only, never public. diff --git a/public/alerts/art/placeholder.svg b/public/alerts/art/placeholder.svg new file mode 100644 index 0000000..5034cb2 --- /dev/null +++ b/public/alerts/art/placeholder.svg @@ -0,0 +1 @@ +your artpublic/alerts/art diff --git a/public/alerts/card.css b/public/alerts/card.css new file mode 100644 index 0000000..5a219a4 --- /dev/null +++ b/public/alerts/card.css @@ -0,0 +1,23 @@ +/* Card alerts (card.js): the plain style every channel gets. Colours come from Actions → Alerts (theme.card). */ +#card-alert { position:fixed; left:60px; top:60px; width:600px; visibility:hidden; z-index:50; font-family:'Nunito', system-ui, sans-serif; + --accent:#9146ff; --bg:#ffffff; --fg:#1f1f23; } +#card-alert .card { position:relative; display:flex; gap:18px; align-items:center; background:var(--bg); color:var(--fg); + border-radius:20px; padding:16px 24px 18px 16px; box-shadow:0 14px 34px rgba(0,0,0,.35); overflow:hidden; } +#card-alert .card::before { content:''; position:absolute; left:0; top:0; bottom:0; width:8px; background:var(--accent); } +#card-alert .pic { width:104px; height:104px; flex:none; border-radius:16px; margin-left:6px; display:grid; place-items:center; overflow:hidden; + background:color-mix(in srgb, var(--accent) 16%, var(--bg)); } +#card-alert .pic img { width:100%; height:100%; object-fit:contain; } +#card-alert .pic .ini { font:900 50px/1 'Nunito', sans-serif; color:var(--accent); } +#card-alert .txt { min-width:0; flex:1; } +#card-alert .tag { font:800 14px/1.2 'Nunito', sans-serif; text-transform:uppercase; letter-spacing:.08em; color:var(--accent); opacity:.9; margin-bottom:2px; + white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#card-alert .name { font:900 32px/1.1 'Nunito', sans-serif; color:var(--accent); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#card-alert .line { font:800 23px/1.2 'Nunito', sans-serif; margin-top:2px; } +#card-alert .msg { font:800 19px/1.3 'Nunito', sans-serif; opacity:.72; margin-top:6px; overflow:hidden; display:-webkit-box; -webkit-line-clamp:4; -webkit-box-orient:vertical; } +#card-alert .msg .w { opacity:.25; transition:opacity .15s; } +#card-alert .msg .w.on { opacity:1; } +#card-alert .badge { position:absolute; right:16px; top:14px; background:var(--badge, var(--accent)); color:#fff; border-radius:99px; + padding:3px 13px; font:900 20px/1.3 'Nunito', sans-serif; box-shadow:0 3px 8px rgba(0,0,0,.2); } +#card-alert .badge small { font-size:13px; margin-left:4px; opacity:.9; } +#card-alert .card.has-badge .txt { padding-right:90px; } +#card-alert .bar { position:absolute; left:0; right:0; bottom:0; height:5px; background:var(--accent); opacity:.55; transform-origin:left center; } diff --git a/public/alerts/card.js b/public/alerts/card.js new file mode 100644 index 0000000..ce05469 --- /dev/null +++ b/public/alerts/card.js @@ -0,0 +1,78 @@ +/* + Card alerts: the plain style (Actions → Alerts: style "Card"). Used for events (follow, sub, gift, raid, bits, tip, + Hype Train) and for redeem variations / read-aloud redeems set to Card. Called by polaroid.js (shared queue): + window.CardAlert.show(d, cur, { url, len, volume }) -> Promise (resolves when it has left) + d: { art|sticker|emote (picture URL), name, line, msg, badge {big, small, color}, tag (small label above the name), + tts (voice URL instead of the sound), ttsEnv (loudness for word timing) } + cur: { anims, timer, audio } from polaroid.js, so reset / skip can stop it. + Timeline: slides in (0.6 s), sound starts, stays until the sound / voice ends (at least 4 s), slides out. +*/ +(function () { + const MIN_SHOW = 4000, SOUND_LEAD = 350, ENV_STEP = 0.04; + const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); + let el = null; + function root() { + if (!el) { el = document.createElement('div'); el.id = 'card-alert'; document.body.appendChild(el); } + return el; + } + const theme = () => (window.S && window.S.alert_theme) || {}; + + function show(d, cur, { url, len, volume }) { + const el = root(), c = theme().card || {}; + if (c.accent) el.style.setProperty('--accent', c.accent); + if (c.bg) el.style.setProperty('--bg', c.bg); + if (c.text) el.style.setProperty('--fg', c.text); + const pic = d.emote || d.sticker || d.art || ''; + const name = d.name || 'Someone'; + const words = d.tts && d.msg ? String(d.msg).split(/\s+/).filter(Boolean) : null; + el.innerHTML = `
+
${pic ? `` : `${esc(name.trim()[0] || '♥').toUpperCase()}`}
+
+ ${d.tag ? `
${esc(d.tag)}
` : ''} +
${esc(name)}
+
${esc(d.line || '')}
+ ${d.msg ? `
${words ? words.map(w => `${esc(w)}`).join(' ') : `“${esc(d.msg)}”`}
` : ''} +
+ ${d.badge ? `
${esc(d.badge.big)}${esc(d.badge.small || '')}
` : ''} +
+
`; + el.style.visibility = 'visible'; + const card = el.querySelector('.card'); + const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; }; + + A(card, [ + { transform:'translateX(-700px)', opacity:0 }, + { transform:'translateX(14px)', opacity:1, offset:.75 }, + { transform:'translateX(0)', opacity:1 }, + ], { duration:600, easing:'cubic-bezier(.2,.8,.3,1)' }); + A(el.querySelector('.pic'), [{ transform:'scale(.6) rotate(-8deg)' }, { transform:'scale(1.08) rotate(3deg)', offset:.6 }, { transform:'scale(1) rotate(0)' }], + { delay:350, duration:450, easing:'ease-out' }); + + // the voice (read-aloud redeems) or the sound + const voice = d.tts || null; + const playUrl = voice || url; + const playLen = voice ? (d.ttsMs || 0) : len; + if (playUrl) { + const a = new Audio(playUrl); a.volume = volume; + cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD); + // words light up roughly as they are spoken + if (words) { + const spans = [...el.querySelectorAll('.msg .w')]; + const total = Math.max(playLen, 1000), step = total / Math.max(spans.length, 1); + spans.forEach((s, i) => setTimeout(() => s.classList.add('on'), SOUND_LEAD + i * step)); + } + } else if (words) el.querySelectorAll('.msg .w').forEach(s => s.classList.add('on')); + + const stay = Math.max(MIN_SHOW, playUrl ? SOUND_LEAD + playLen + 600 : 0); + A(el.querySelector('.bar'), [{ transform:'scaleX(1)' }, { transform:'scaleX(0)' }], { delay:600, duration:Math.max(stay - 600, 500), easing:'linear' }); + const exit = A(card, [ + { transform:'translateX(0)', opacity:1 }, + { transform:'translateX(18px)', opacity:1, offset:.25 }, + { transform:'translateX(-720px)', opacity:0 }, + ], { delay:stay, duration:550, easing:'cubic-bezier(.5,0,.8,.4)' }); + return exit.finished.then(() => { el.style.visibility = 'hidden'; cur.anims.forEach(a => a.cancel()); }).catch(() => {}); + } + + function hide() { if (el) el.style.visibility = 'hidden'; } + window.CardAlert = { show, hide }; +})(); diff --git a/public/alerts/cassette.css b/public/alerts/cassette.css new file mode 100644 index 0000000..adbedd1 --- /dev/null +++ b/public/alerts/cassette.css @@ -0,0 +1,45 @@ +/* Cassette tape alert for redeems (see cassette.js). Same corner as the polaroid; they share one queue. */ +#cassette-alert { --ink:#3a2a20; --red:#b74347; position:fixed; left:85px; top:110px; width:440px; visibility:hidden; z-index:50; } +#cassette-alert * { box-sizing:border-box; } + +#cassette-alert.r-common { --shell:#f3ead9; --shell2:#e6dac3; --edge:#8a7558; --band:#f4a0a8; --bandtxt:#7a2f3a; } +#cassette-alert.r-uncommon { --shell:#cdeedd; --shell2:#b5e2cb; --edge:#4f8a6b; --band:#7fcfa6; --bandtxt:#1f5a3c; } +#cassette-alert.r-rare { --shell:#ddd0f4; --shell2:#cbb9ee; --edge:#6b54a8; --band:#a88be0; --bandtxt:#ffffff; } +#cassette-alert.r-ultra { --shell:#f6d77a; --shell2:#eec456; --edge:#9a6a10; --band:#3c2006; --bandtxt:#f6d77a; } + +#cassette-alert .tape-wrap { position:relative; width:440px; height:282px; filter:drop-shadow(0 14px 22px rgba(0,0,0,.45)); } +#cassette-alert.r-ultra .tape-wrap { filter:drop-shadow(0 0 16px #ffd76a) drop-shadow(0 0 4px #fff2c0) drop-shadow(0 14px 22px rgba(0,0,0,.45)); } +#cassette-alert svg { position:absolute; inset:0; width:100%; height:100%; overflow:visible; } +#cassette-alert .reel-hub, #cassette-alert .wound { transform-box:fill-box; transform-origin:center; } + +#cassette-alert .band { position:absolute; left:34px; right:34px; top:24px; height:32px; display:flex; align-items:center; + justify-content:space-between; padding:0 14px; font:900 15px 'Nunito', sans-serif; letter-spacing:2px; color:var(--bandtxt); } +#cassette-alert .title { position:absolute; left:40px; right:40px; top:58px; text-align:center; font:700 40px/1 'Caveat', cursive; + color:var(--ink); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#cassette-alert .sub { position:absolute; left:40px; right:40px; top:156px; text-align:center; font:700 22px/1 'Caveat', cursive; + color:#7a6656; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } + +/* per-redeem sticker, bottom-right corner; any shape fits inside 150x125 */ +#cassette-alert .stk { position:absolute; right:-50px; top:150px; width:175px; height:150px; display:flex; align-items:center; justify-content:center; } +#cassette-alert .stk img { max-width:175px; max-height:150px; transform:rotate(10deg); + filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 5px 8px rgba(0,0,0,.35)); } + +#cassette-alert .foil { position:absolute; inset:0; border-radius:20px; pointer-events:none; opacity:0; + background:linear-gradient(115deg,#0000 35%,#fff9 48%,#fff3 52%,#0000 62%); mix-blend-mode:screen; } +#cassette-alert .spark { position:absolute; width:44px; height:44px; opacity:0; pointer-events:none; background:#fffbe6; + clip-path:polygon(50% 0,60% 40%,100% 50%,60% 60%,50% 100%,40% 60%,0 50%,40% 40%); filter:drop-shadow(0 0 6px #fff4b0); } + +#cassette-alert .strip { position:relative; margin:-6px 0 0 30px; display:inline-block; max-width:400px; padding:8px 22px 10px; + background:#fffdf7; transform:rotate(-2deg); box-shadow:0 6px 14px rgba(0,0,0,.35); font:700 30px/1.05 'Caveat', cursive; color:var(--ink); } +#cassette-alert .strip .u { color:var(--red); } +#cassette-alert .strip .msg { display:block; font-size:22px; color:#7a6656; margin-top:4px; + overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; } +#cassette-alert .strip:before, #cassette-alert .strip:after { content:''; position:absolute; top:-10px; width:70px; height:24px; + background:rgba(201,182,228,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 7px,#0000 7px 14px); } +#cassette-alert .strip:before { left:-22px; transform:rotate(-28deg); } +#cassette-alert .strip:after { right:-22px; transform:rotate(24deg); } + +/* the reward's / Power-up's Twitch icon as a small sticker on the top-left corner (only when Twitch has one) */ +#cassette-alert .ico { position:absolute; left:-30px; top:-28px; width:76px; height:76px; display:flex; align-items:center; justify-content:center; z-index:2; } +#cassette-alert .ico img { max-width:76px; max-height:76px; + filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 5px 8px rgba(0,0,0,.35)); } diff --git a/public/alerts/cassette.js b/public/alerts/cassette.js new file mode 100644 index 0000000..6c879de --- /dev/null +++ b/public/alerts/cassette.js @@ -0,0 +1,130 @@ +/* + Cassette tape renderer for redeem alerts. Called by polaroid.js (shared queue): + window.CassetteAlert.show(d, cur, { url, len, volume }) -> Promise (resolves when ejected) + d: { title (variation), sub (reward), rarity, sticker (URL), name (user), line (strip text), msg (viewer input) } + cur: { anims, timer, audio } from polaroid.js, so reset/skip can stop it. + Timeline: slides in (0.7 s), sticker + strip pop on, reels spin and tape winds over the sound's length, + stays animation + 3 s or until the sound ends, then ejects upward. +*/ +(function () { + const AFTER_ANIM = 3000, SOUND_LEAD = 600, ANIM_END = 1200; + // 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); + + let el = null; + function root() { + if (!el) { el = document.createElement('div'); el.id = 'cassette-alert'; document.body.appendChild(el); } + return el; + } + + function reel(cx, id) { + const teeth = Array.from({ length: 6 }, (_, i) => + ``).join(''); + return ` + ${teeth} + `; + } + + function svg() { + const uid = 'c' + Math.random().toString(36).slice(2, 8); + return ` + + + + + ${[[22,22],[418,22],[22,260],[418,260]].map(([x, y]) => ``).join('')} + + + + + + ${reel(160, 'reelL')}${reel(280, 'reelR')} + + + ${[148,180,260,292].map(x => ``).join('')} + + `; + } + + function show(d, cur, { url, len, volume }) { + const el = root(); + const [cls, label] = RAR[d.rarity] || RAR.common; + const ultra = d.rarity === 'ultra_rare'; + el.className = cls; + el.innerHTML = ` +
${svg()} +
SIDE A${label}
+
${esc(d.title)}
+
${d.sub && d.sub !== d.title ? esc(d.sub) : ''}
+
+ ${d.icon ? `
` : ''} + ${ultra ? '
' + '
'.repeat(6) : ''} +
+
${esc(d.name)} ${esc(d.line)}${d.msg ? `“${esc(d.msg)}”` : ''}
`; + el.style.visibility = 'visible'; + + const q = s => el.querySelector(s); + const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; }; + const tilt = between(-4, 4); + + A(q('.tape-wrap'), [ + { transform:'translateX(-620px) rotate(-14deg)', opacity:0 }, + { transform:`translateX(18px) rotate(${tilt + 2}deg)`, opacity:1, offset:.72 }, + { transform:`translateX(-4px) rotate(${tilt - .6}deg)`, offset:.88 }, + { transform:`translateX(0) rotate(${tilt}deg)`, opacity:1 }, + ], { duration:700, easing:'cubic-bezier(.2,.8,.3,1)' }); + if (q('.ico')) A(q('.ico'), [ // the reward's / Power-up's Twitch icon, top-left corner + { transform:'rotate(10deg) scale(0)', opacity:0 }, + { transform:'rotate(-18deg) scale(1.2)', opacity:1, offset:.6 }, + { transform:'rotate(-10deg) scale(1)', opacity:1 }, + ], { delay:560, duration:360, easing:'ease-out' }); + A(q('.stk'), [ + { transform:'rotate(-30deg) scale(0)', opacity:0 }, + { transform:'rotate(8deg) scale(1.2)', opacity:1, offset:.6 }, + { transform:'rotate(0deg) scale(1)', opacity:1 }, + ], { delay:650, duration:380, easing:'ease-out' }); + A(q('.strip'), [ + { transform:'translateY(-20px) rotate(-6deg) scale(1.1)', opacity:0 }, + { transform:'translateY(0) rotate(-2deg) scale(1)', opacity:1 }, + ], { delay:850, duration:320, easing:'cubic-bezier(.3,.7,.4,1)' }); + + // reels spin and tape winds while the sound plays + const playMs = Math.max(len, 600); + const turns = Math.round(playMs / 1000 * 540); + ['reelL', 'reelR'].forEach(id => A(q(`[data-id="${id}"]`), [{ transform:'rotate(0deg)' }, { transform:`rotate(${turns}deg)` }], + { delay:SOUND_LEAD, duration:playMs, easing:'linear', fill:'none' })); + A(q('[data-id="reelL-tape"]'), [{ transform:'scale(1)' }, { transform:'scale(.55)' }], { delay:SOUND_LEAD, duration:playMs, easing:'linear' }); + A(q('[data-id="reelR-tape"]'), [{ transform:'scale(.55)' }, { transform:'scale(1)' }], { delay:SOUND_LEAD, duration:playMs, easing:'linear' }); + A(q('.tape-wrap'), [{ translate:'0 0' }, { translate:'0 -2px' }, { translate:'0 0' }], + { delay:SOUND_LEAD, duration:420, iterations:Math.ceil(playMs / 420), easing:'ease-in-out', fill:'none', composite:'add' }); + + if (ultra) { + A(q('.foil'), [{ opacity:0 }, { opacity:1, offset:.2 }, { opacity:1, offset:.8 }, { opacity:0 }], + { delay:700, duration:1400, iterations:3, easing:'ease-in-out', fill:'none' }); + el.querySelectorAll('.spark').forEach((s, i) => { + s.style.left = `${between(10, 410)}px`; s.style.top = `${between(-10, 250)}px`; + A(s, [{ opacity:0, transform:'scale(0) rotate(0deg)' }, { opacity:1, transform:'scale(1) rotate(45deg)', offset:.5 }, { opacity:0, transform:'scale(0) rotate(90deg)' }], + { delay:800 + i * 230, duration:900, iterations:4, fill:'none' }); + }); + } + + if (url) { + const a = new Audio(url); a.volume = volume; + cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD); + } + + const exitAt = Math.max(ANIM_END + AFTER_ANIM, url ? SOUND_LEAD + len : 0); + const exit = A(el, [ + { transform:'translateY(0)', opacity:1 }, + { transform:'translateY(14px)', opacity:1, offset:.2 }, + { transform:'translateY(-420px) rotate(-8deg)', opacity:0 }, + ], { delay:exitAt, duration:600, 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.CassetteAlert = { show, hide }; +})(); diff --git a/public/alerts/fx.css b/public/alerts/fx.css new file mode 100644 index 0000000..d324954 --- /dev/null +++ b/public/alerts/fx.css @@ -0,0 +1,68 @@ +/* Special redeem visuals (see fx.js): giant emote, bouncing emote celebration, highlighted message. */ +#fx-alert { --ink:#3a2a20; --red:#b74347; position:fixed; inset:0; pointer-events:none; visibility:hidden; z-index:55; } +#fx-alert * { box-sizing:border-box; } + +/* name strip, same paper + tape look as the cassette */ +#fx-alert .strip { position:absolute; display:inline-block; max-width:520px; padding:8px 22px 10px; background:#fffdf7; + box-shadow:0 6px 14px rgba(0,0,0,.35); font:700 30px/1.05 'Caveat', cursive; color:var(--ink); } +#fx-alert .strip .u { color:var(--red); } +#fx-alert .strip:before, #fx-alert .strip:after { content:''; position:absolute; top:-10px; width:70px; height:24px; + background:rgba(190,160,240,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 7px,#0000 7px 14px); } +#fx-alert .strip:before { left:-22px; transform:rotate(-28deg); } +#fx-alert .strip:after { right:-22px; transform:rotate(24deg); } + +/* gigantify */ +#fx-alert .giant { position:absolute; left:85px; top:70px; width:380px; height:380px; display:flex; align-items:center; justify-content:center; } +#fx-alert .giant img { width:100%; height:100%; object-fit:contain; filter:drop-shadow(0 12px 24px rgba(0,0,0,.5)); } + +/* celebration */ +#fx-alert .bounce { position:absolute; left:0; top:0; will-change:transform; filter:drop-shadow(0 6px 10px rgba(0,0,0,.4)); } + +/* highlighted message / message effect: big taped paper note, tall rather than wide */ +#fx-alert .note { position:absolute; left:90px; top:90px; width:440px; min-height:300px; padding:30px 32px 34px; background:#fffdf7; + box-shadow:0 14px 30px rgba(0,0,0,.45); transform-origin:50% 0; + background-image:repeating-linear-gradient(#0000 0 51px, #0000001a 51px 52px); background-position:0 79px; } +#fx-alert .note:before, #fx-alert .note:after { content:''; position:absolute; top:-14px; width:120px; height:34px; + background:rgba(190,160,240,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px); + box-shadow:0 1px 2px rgba(0,0,0,.15); } +#fx-alert .note:before { left:-34px; transform:rotate(-32deg); } +#fx-alert .note:after { right:-34px; transform:rotate(28deg); } +#fx-alert .note .who { font:700 34px/1.1 'Caveat', cursive; color:var(--ink); margin-bottom:10px; } +#fx-alert .note .who .u { color:var(--red); } +#fx-alert .note .text { font:700 46px/52px 'Caveat', cursive; color:var(--ink); word-wrap:break-word; + overflow:hidden; display:-webkit-box; -webkit-line-clamp:9; -webkit-box-orient:vertical; } + +/* TTS redeems: envelope letter (fx.js envelope()). The flap opens, the letter rises all the way out (its peak may + leave the screen), then comes down in front of the envelope and ends ~80px from the top; words ink in as spoken. + Coordinates are bottom-up inside .envl (360x560); the letter's slot is clipped at the envelope's bottom edge. */ +#fx-alert .envl { position:absolute; left:90px; top:-146px; width:360px; height:560px; } +#fx-alert .envl .env { position:absolute; left:0; bottom:0; width:360px; height:216px; z-index:3; background:#e9d3b0; border-radius:6px; + box-shadow:0 10px 20px rgba(0,0,0,.45); } +#fx-alert .envl .env:before { content:''; position:absolute; inset:0; border-radius:6px; z-index:3; + background:linear-gradient(32deg, #dcc39b 50%, transparent 50%) left/50% 100% no-repeat, + linear-gradient(-32deg, #dcc39b 50%, transparent 50%) right/50% 100% no-repeat; } +#fx-alert .envl .flap { position:absolute; left:0; bottom:216px; width:360px; height:122px; transform-origin:bottom; z-index:1; + background:#d8bd93; clip-path:polygon(0 100%, 50% 0, 100% 100%); animation:fx-flap .6s .35s ease-out both; } +@keyframes fx-flap { from { transform:rotateX(180deg); z-index:4; } } +#fx-alert .envl .slot { position:absolute; left:-40px; right:-40px; bottom:0; top:-400px; overflow:hidden; z-index:2; animation:fx-zswap 1.6s .8s both; } +@keyframes fx-zswap { 0%, 54% { z-index:2; } 55%, 100% { z-index:6; } } +#fx-alert .envl .letter { --fs:24px; --lh:30px; position:absolute; left:62px; bottom:30px; width:316px; min-height:290px; background:#fffdf7; padding:18px 22px 22px; + box-shadow:0 4px 12px rgba(0,0,0,.3); animation:fx-rise 1.6s .8s both; + background-image:repeating-linear-gradient(transparent 0 calc(var(--lh) - 1px), rgba(110,150,200,.3) calc(var(--lh) - 1px) var(--lh)); + background-position:0 calc(22px + var(--lh) - 6px); } +/* longer messages: smaller handwriting, the ruled lines follow */ +#fx-alert .envl .letter.long { --fs:20px; --lh:25px; } +#fx-alert .envl .letter.longer { --fs:17px; --lh:21px; width:340px; } +#fx-alert .envl .letter.huge { --fs:15px; --lh:18px; width:356px; } +@keyframes fx-rise { + 0% { transform:translateY(110px); animation-timing-function:cubic-bezier(.3,.7,.4,1); } + 45% { transform:translateY(-200px) rotate(-1deg); } + 55% { transform:translateY(-200px) rotate(-1deg); animation-timing-function:cubic-bezier(.4,0,.3,1.2); } + 100% { transform:translateY(-14px) rotate(-2deg); } +} +#fx-alert .envl .to { font:700 22px/1 Caveat, cursive; color:var(--red); margin-bottom:6px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#fx-alert .envl .tx { font:700 var(--fs)/var(--lh) Caveat, cursive; color:var(--ink); word-wrap:break-word; } +#fx-alert .envl .w { opacity:.12; transition:opacity .25s; } +#fx-alert .envl .w.on { opacity:1; } +#fx-alert .envl .seal { position:absolute; left:157px; bottom:86px; width:46px; height:46px; z-index:5; border-radius:50%; background:#b74347; + box-shadow:inset 0 -3px 0 rgba(0,0,0,.2), 0 3px 6px rgba(0,0,0,.35); color:#ffd9d4; font:22px/46px sans-serif; text-align:center; } diff --git a/public/alerts/fx.js b/public/alerts/fx.js new file mode 100644 index 0000000..2a4970e --- /dev/null +++ b/public/alerts/fx.js @@ -0,0 +1,196 @@ +/* + Special redeem visuals, called by polaroid.js (shared queue). Each returns a Promise that resolves when done. + FxAlert.giant(d, cur, snd) Gigantify Power-up: the viewer's emote grows huge, pulses while the sound plays + FxAlert.rain(d, cur, snd) On-Screen Celebration Power-up: copies of the emote bounce around the screen + FxAlert.message(d, cur, snd) Highlight my message / Message Effect: big taped paper note with the message + FxAlert.envelope(d, cur, snd) TTS redeems: envelope opens, the letter rises out and settles in front, words ink in as + they are spoken (d.tts URL, d.ttsMs length, d.ttsEnv loudness per 40 ms, d.ttsPrefix + = words said before the message, e.g. " says:") + d: { name (user), line, msg, emote (image URL or null) }; snd: { url, len, volume } + cur: { anims, timer, audio } so reset/skip can stop it (anything with cancel() can go in anims). +*/ +(function () { + const AFTER_ANIM = 3000, SOUND_LEAD = 300; + // when Twitch sends no emote: the corner sticker from Actions → Alerts, else a plain shape + const fallback = () => window.FX_FALLBACK || (window.S && window.S.alert_theme && window.S.alert_theme.heart) || (window.ALERTS_BASE || '/alerts/') + 'art/placeholder.svg'; + const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); + const between = (a, b) => a + Math.random() * (b - a); + + let el = null; + function root() { + if (!el) { el = document.createElement('div'); el.id = 'fx-alert'; document.body.appendChild(el); } + return el; + } + function hide() { if (el) { el.style.visibility = 'hidden'; el.innerHTML = ''; } } + + function playSound(cur, { url, volume }) { + if (!url) return; + const a = new Audio(url); a.volume = volume; + cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD); + } + const imgTag = (src, cls = '') => ``; + const A = (cur, node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; }; + const done = (cur, anim) => anim.finished.then(() => hide()).catch(() => {}); + + // ---- Gigantify: emote grows huge ---- + function giant(d, cur, snd) { + const el = root(); + el.innerHTML = `
${imgTag(d.emote)}
+
${esc(d.name)} ${esc(d.line)}
`; + el.style.visibility = 'visible'; + const g = el.querySelector('.giant'), strip = el.querySelector('.strip'); + A(cur, g, [ + { transform:'scale(.12) rotate(-20deg)', opacity:0 }, + { transform:'scale(.3) rotate(-8deg)', opacity:1, offset:.25 }, + { transform:'scale(1.18) rotate(6deg)', offset:.7 }, + { transform:'scale(.95) rotate(-2deg)', offset:.85 }, + { transform:'scale(1) rotate(0deg)', opacity:1 }, + ], { duration:900, easing:'cubic-bezier(.2,.8,.3,1)' }); + A(cur, strip, [{ transform:'translateY(-20px) rotate(-6deg) scale(1.1)', opacity:0 }, { transform:'translateY(0) rotate(-2deg) scale(1)', opacity:1 }], + { delay:700, duration:320 }); + const playMs = Math.max(snd.len, 600); + A(cur, g, [{ scale:'1' }, { scale:'1.06' }, { scale:'1' }], { delay:900, duration:600, iterations:Math.ceil(playMs / 600), fill:'none', composite:'add' }); + playSound(cur, snd); + const exitAt = Math.max(1000 + AFTER_ANIM, SOUND_LEAD + snd.len); + return done(cur, A(cur, el, [{ opacity:1, transform:'scale(1)' }, { opacity:0, transform:'scale(.6)' }], + { delay:exitAt, duration:450, easing:'ease-in' })); + } + + // ---- Celebration: emotes bounce around the screen ---- + function rain(d, cur, snd) { + const el = root(), N = 14, Wd = 1920, Ht = 1080; + el.innerHTML = Array.from({ length: N }, () => imgTag(d.emote, 'bounce')).join('') + + `
${esc(d.name)} ${esc(d.line)}
`; + el.style.visibility = 'visible'; + const strip = el.querySelector('.strip'); + A(cur, strip, [{ transform:'translateY(-20px) rotate(-6deg) scale(1.1)', opacity:0 }, { transform:'translateY(0) rotate(-2deg) scale(1)', opacity:1 }], + { delay:200, duration:320 }); + const items = [...el.querySelectorAll('.bounce')].map(img => { + const s = between(90, 170); + img.style.width = img.style.height = `${s}px`; + // enter from a random screen edge + const side = Math.floor(Math.random() * 4); + const x = side === 0 ? -s : side === 1 ? Wd : between(0, Wd - s), y = side === 2 ? -s : side === 3 ? Ht : between(0, Ht - s); + const sp = between(420, 760), dir = Math.atan2(Ht / 2 - y, Wd / 2 - x) + between(-.7, .7); + return { img, s, x, y, vx: Math.cos(dir) * sp, vy: Math.sin(dir) * sp, r: between(0, 360), vr: between(-220, 220), inside: false }; + }); + const life = Math.max(1000 + AFTER_ANIM, SOUND_LEAD + snd.len); + let raf = 0, last = performance.now(), start = last, stopped = false, resolve; + const finished = new Promise(r => { resolve = r; }); + function frame(now) { + if (stopped) return; + const dt = Math.min((now - last) / 1000, .05), t = now - start; last = now; + const leaving = t > life; + for (const o of items) { + if (leaving) { o.vy -= 1800 * dt; } // float away upward at the end + o.x += o.vx * dt; o.y += o.vy * dt; o.r += o.vr * dt; + if (!leaving) { + if (!o.inside && o.x > 0 && o.y > 0 && o.x < Wd - o.s && o.y < Ht - o.s) o.inside = true; + if (o.inside) { + if (o.x < 0 || o.x > Wd - o.s) { o.vx *= -1; o.x = Math.max(0, Math.min(Wd - o.s, o.x)); o.vr *= -1; } + if (o.y < 0 || o.y > Ht - o.s) { o.vy *= -1; o.y = Math.max(0, Math.min(Ht - o.s, o.y)); } + } + } + o.img.style.transform = `translate(${o.x}px,${o.y}px) rotate(${o.r}deg)`; + } + if (leaving && items.every(o => o.y < -o.s - 50)) { end(); return; } + if (leaving) strip.style.opacity = Math.max(0, 1 - (t - life) / 400); + raf = requestAnimationFrame(frame); + } + function end() { stopped = true; cancelAnimationFrame(raf); hide(); resolve(); } + cur.anims.push({ cancel() { stopped = true; cancelAnimationFrame(raf); resolve(); } }); + raf = requestAnimationFrame(frame); + playSound(cur, snd); + return finished; + } + + // ---- Highlight my message / Message Effect: big taped paper note ---- + function message(d, cur, snd) { + const el = root(); + const text = d.msg || ''; + const tilt = between(-3, 3); + el.innerHTML = `
${esc(d.name)} ${esc(d.line)}
+
${esc(text)}
`; + el.style.visibility = 'visible'; + const n = el.querySelector('.note'); + A(cur, n, [ + { transform:`translateY(-140px) rotate(${tilt * -3}deg) scale(1.12)`, opacity:0 }, + { transform:`translateY(8px) rotate(${tilt + 1}deg) scale(.99)`, opacity:1, offset:.7 }, + { transform:`translateY(0) rotate(${tilt}deg) scale(1)`, opacity:1 }, + ], { duration:650, easing:'cubic-bezier(.2,.8,.3,1)' }); + A(cur, n.querySelector('.text'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }], + { delay:550, duration:Math.min(1600, 300 + 18 * text.length), easing:'ease-in-out' }); + playSound(cur, snd); + const read = 2000 + 70 * text.length; // time to read it + let exitAt = Math.max(650 + AFTER_ANIM, 650 + read, SOUND_LEAD + snd.len); + if (d.tts) { // TTS: after the intro sound, keep the note up until it is said + const ttsAt = SOUND_LEAD + (snd.url ? snd.len + 250 : 300); + const a = new Audio(d.tts); a.volume = snd.volume; + const t = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] TTS blocked:', err.message)); }, ttsAt); + cur.anims.push({ cancel: () => { clearTimeout(t); a.pause(); } }); // skip/reset stop the voice too + exitAt = Math.max(exitAt, ttsAt + (d.ttsMs || 4000) + 900); + } + return done(cur, A(cur, el, [{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(140px) rotate(8deg)', opacity:0 }], + { delay:exitAt, duration:500, easing:'ease-in' })); + } + + // ---- TTS redeems: envelope letter ---- + const VOICE_AT = 1300; // ms: the voice starts while the letter comes back down + const ENV_STEP = 0.04; // s per loudness value (src/tts.js ENV_STEP_MS) + + // when each shown word starts (s), spread over the voiced part of the clip, longer words and pauses after + // punctuation get more time. The first `prefix` spoken words (" says:") are not on the letter. + function wordStarts(env, prefixWords, words) { + let s = 0, e = env.length - 1; + while (s < e && env[s] < .08) s++; + while (e > s && env[e] < .08) e--; + const all = [...prefixWords, ...words]; + const weight = all.map(x => x.length + 2 + (/[.!?,:]$/.test(x) ? 5 : 0)); + const total = weight.reduce((a, b) => a + b, 0) || 1; + let acc = 0; + const starts = all.map((_, i) => { const t = (s + (e - s + 1) * acc / total) * ENV_STEP; acc += weight[i]; return t; }); + return starts.slice(prefixWords.length); + } + + function envelope(d, cur, snd) { + const el = root(); + const text = d.msg || ''; + const words = text.split(/\s+/).filter(Boolean); + el.innerHTML = `
+
from ${esc(d.name)} ♡
+
${words.map(w => `${esc(w)}`).join(' ')}
+
♥
`; + el.style.visibility = 'visible'; + const box = el.querySelector('.envl'); + const spans = [...box.querySelectorAll('.w')]; + A(cur, box, [{ transform:'translateY(-40px) scale(.92) rotate(-3deg)', opacity:0 }, { transform:'none', opacity:1 }], + { duration:600, easing:'cubic-bezier(.2,1.25,.4,1)' }); + + let exitAt; + if (d.tts) { + const prefix = d.ttsPrefix ? [d.name, 'says:'].slice(0, d.ttsPrefix) : []; + const starts = d.ttsEnv && d.ttsEnv.length ? wordStarts(d.ttsEnv, prefix, words) : null; + const a = new Audio(d.tts); a.volume = snd.volume; + const t = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] TTS blocked:', err.message)); }, VOICE_AT); + let raf = 0, failed = false; + const fail = () => { failed = true; }; // voice missing/blocked: show the whole text anyway + a.addEventListener('error', fail, { once:true }); + const t2 = setTimeout(() => { if (!a.currentTime) fail(); }, VOICE_AT + 1500); + const tick = () => { // ink in each word as it is said + const now = a.ended ? Infinity : a.currentTime + .05; + spans.forEach((w, i) => w.classList.toggle('on', failed || a.ended || (!a.paused || a.currentTime > 0) && (!starts || now >= starts[i]))); + raf = requestAnimationFrame(tick); + }; + raf = requestAnimationFrame(tick); + cur.anims.push({ cancel: () => { clearTimeout(t); clearTimeout(t2); cancelAnimationFrame(raf); a.pause(); } }); + exitAt = VOICE_AT + (d.ttsMs || 4000) + 1400; + } else { // blocked or no voice: just show the letter + spans.forEach(w => w.classList.add('on')); + exitAt = 2400 + 2000 + 60 * text.length; + } + return done(cur, A(cur, box, [{ transform:'none', opacity:1 }, { transform:'translateY(40px) scale(.95) rotate(4deg)', opacity:0 }], + { delay:exitAt, duration:500, easing:'ease-in' })); + } + + window.FxAlert = { giant, rain, message, envelope, hide }; +})(); diff --git a/public/alerts/hypebar.css b/public/alerts/hypebar.css new file mode 100644 index 0000000..3a7f526 --- /dev/null +++ b/public/alerts/hypebar.css @@ -0,0 +1,14 @@ +/* Hype Train progress strip (see hypebar.js): slim taped paper, top-left above the alert corner. */ +#hype-bar { --ink:#3a2a20; --red:#b74347; --fill:#f8a070; position:fixed; left:85px; top:14px; width:440px; z-index:60; visibility:hidden; + padding:8px 16px 10px; background:#fffdf7; box-shadow:0 8px 18px rgba(0,0,0,.4); transform-origin:50% 0; } +#hype-bar.golden { --fill:#f2c040; background:#fff8e2; } +#hype-bar * { box-sizing:border-box; } +#hype-bar:before { content:''; position:absolute; left:50%; top:-12px; width:90px; height:26px; margin-left:-45px; transform:rotate(-2deg); + background:rgba(250,170,120,.88); background-image:repeating-linear-gradient(45deg,#fff6 0 7px,#0000 7px 14px); } +#hype-bar.golden:before { background-color:rgba(246,206,110,.95); } +#hype-bar .top { display:flex; justify-content:space-between; align-items:baseline; font:900 15px 'Nunito', sans-serif; letter-spacing:2px; color:var(--ink); } +#hype-bar .lv { color:var(--red); } +#hype-bar .time { font:700 22px 'Caveat', cursive; letter-spacing:0; color:#7a6656; } +#hype-bar .track { margin-top:5px; height:16px; border:3px solid var(--ink); border-radius:10px; background:#fff; overflow:hidden; } +#hype-bar .fill { height:100%; width:0; background-color:var(--fill); transition:width .7s cubic-bezier(.3,.7,.4,1); + background-image:repeating-linear-gradient(45deg,#fff5 0 6px,#0000 6px 12px); } diff --git a/public/alerts/hypebar.js b/public/alerts/hypebar.js new file mode 100644 index 0000000..0a529f9 --- /dev/null +++ b/public/alerts/hypebar.js @@ -0,0 +1,43 @@ +/* + Hype Train progress strip. Persistent while a train runs; not part of the alert queue. + HypeBar.update(phase, train) phase: begin | progress | end + train: { id, level, progress, goal, total, expires_at, golden, treasure } +*/ +(function () { + let el = null, timer = null, hideTimer = null, expires = 0, shownId = null; + function root() { + if (!el) { el = document.createElement('div'); el.id = 'hype-bar'; document.body.appendChild(el); + el.innerHTML = '
'; } + return el; + } + function tick() { + const s = Math.max(0, Math.round((expires - Date.now()) / 1000)); + el.querySelector('.time').textContent = s ? `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')} left` : ''; + } + function update(phase, t) { + const el = root(); + clearTimeout(hideTimer); + el.classList.toggle('golden', !!t.golden); + const kind = t.golden ? 'GOLDEN KAPPA TRAIN' : t.treasure ? 'TREASURE TRAIN' : 'HYPE TRAIN'; + if (phase === 'end') { + clearInterval(timer); + el.querySelector('.name').innerHTML = `${kind} · ENDED AT LV ${t.level} ♡`; + el.querySelector('.time').textContent = ''; + el.querySelector('.fill').style.width = '100%'; + hideTimer = setTimeout(() => el.animate([{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(-90px)', opacity:0 }], + { duration:500, easing:'ease-in', fill:'forwards' }).finished.then(() => { el.style.visibility = 'hidden'; shownId = null; }).catch(() => {}), 5000); + return; + } + if (shownId !== t.id || el.style.visibility !== 'visible') { + el.getAnimations().forEach(a => a.cancel()); + el.style.visibility = 'visible'; shownId = t.id; + el.animate([{ transform:'translateY(-90px) rotate(-3deg)', opacity:0 }, { transform:'translateY(4px) rotate(1deg)', opacity:1, offset:.75 }, + { transform:'translateY(0) rotate(0)', opacity:1 }], { duration:550, easing:'cubic-bezier(.2,.8,.3,1)' }); + } + el.querySelector('.name').innerHTML = `${kind} · LV ${t.level}`; + const pct = t.goal ? Math.min(100, Math.round(100 * (t.progress || 0) / t.goal)) : 0; + el.querySelector('.fill').style.width = `${Math.max(2, pct)}%`; + if (t.expires_at) { expires = Date.parse(t.expires_at); clearInterval(timer); timer = setInterval(tick, 500); tick(); } + } + window.HypeBar = { update }; +})(); diff --git a/public/alerts/nowplaying.css b/public/alerts/nowplaying.css new file mode 100644 index 0000000..8b8283a --- /dev/null +++ b/public/alerts/nowplaying.css @@ -0,0 +1,16 @@ +/* "Now playing" strip (see nowplaying.js): small, top-right corner, visible only while music plays. */ +#now-playing { --ink:#3a2a20; --red:#b74347; position:fixed; right:24px; top:18px; height:84px; z-index:40; visibility:hidden; + display:flex; align-items:center; gap:0; } +#now-playing * { box-sizing:border-box; } + +/* paper slip with the song, taped on */ +#now-playing .slip { position:relative; display:flex; align-items:center; gap:10px; max-width:340px; padding:6px 13px 6px 8px; + background:#fffdf7; box-shadow:0 6px 12px rgba(0,0,0,.4); transform:rotate(-1.5deg); } +#now-playing .slip:before { content:''; position:absolute; left:40%; top:-9px; width:58px; height:18px; transform:rotate(-4deg); + background:rgba(201,182,228,.88); background-image:repeating-linear-gradient(45deg,#fff6 0 6px,#0000 6px 12px); } +#now-playing .cover { width:50px; height:50px; flex:none; background:#e8dcc8 center/cover; box-shadow:0 2px 4px rgba(0,0,0,.3); + border:2px solid #fff; transform:rotate(3deg); } +#now-playing .txt { min-width:0; } +#now-playing .t { font:700 23px/1.05 'Caveat', cursive; color:var(--ink); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#now-playing .t:before { content:'♪ '; color:var(--red); } +#now-playing .a { font:700 17px/1.1 'Caveat', cursive; color:#7a6656; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } diff --git a/public/alerts/nowplaying.js b/public/alerts/nowplaying.js new file mode 100644 index 0000000..88bda3d --- /dev/null +++ b/public/alerts/nowplaying.js @@ -0,0 +1,53 @@ +/* + "Now playing" slip, top-right: taped paper with cover, title and artist. Visible exactly while a song is playing; hides on pause/stop. + NowPlaying.update(np) np: { playing, title, artist, album, cover (data URL or null) } + Small grace period on hide so skipping to the next song does not make it flicker. +*/ +(function () { + const HIDE_GRACE_MS = 1500; + const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); + let el = null, shown = false, hideTimer = null, key = ''; + + function root() { + if (!el) { + el = document.createElement('div'); el.id = 'now-playing'; + el.innerHTML = `
`; + document.body.appendChild(el); + } + return el; + } + + function show() { + clearTimeout(hideTimer); + if (shown) return; + shown = true; el.style.visibility = 'visible'; + el.getAnimations().forEach(a => a.cancel()); + el.animate([{ transform:'translateY(-140px)', opacity:0 }, { transform:'translateY(6px)', opacity:1, offset:.75 }, { transform:'translateY(0)', opacity:1 }], + { duration:550, easing:'cubic-bezier(.2,.8,.3,1)' }); + } + function hide() { + clearTimeout(hideTimer); + hideTimer = setTimeout(() => { + if (!shown) return; + shown = false; + el.animate([{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(-140px)', opacity:0 }], { duration:450, easing:'ease-in', fill:'forwards' }) + .finished.then(() => { if (!shown) el.style.visibility = 'hidden'; }).catch(() => {}); + }, HIDE_GRACE_MS); + } + + function update(np) { + root(); + if (!np || !np.title) { hide(); return; } + const k = `${np.title}|${np.artist}`; + if (k !== key) { + key = k; + el.querySelector('.t').textContent = np.title; + el.querySelector('.a').textContent = np.artist || np.album || ''; + el.querySelector('.cover').style.backgroundImage = np.cover ? `url("${np.cover}")` : ''; + if (shown) el.querySelector('.slip').animate([{ opacity:.2, transform:'rotate(-1.5deg) translateX(14px)' }, { opacity:1, transform:'rotate(-1.5deg)' }], { duration:350 }); + } + np.playing ? show() : hide(); + } + + window.NowPlaying = { update }; +})(); diff --git a/public/alerts/polaroid.css b/public/alerts/polaroid.css new file mode 100644 index 0000000..c65f23f --- /dev/null +++ b/public/alerts/polaroid.css @@ -0,0 +1,44 @@ +/* Polaroid alerts (see polaroid.js). Fonts: Caveat (loaded by overlay.ejs). */ +#polaroid-alert { --red:#b74347; --ink:#3a2a20; + position:fixed; left:85px; top:90px; width:340px; visibility:hidden; z-index:50; } + +#polaroid-alert .photo { position:absolute; left:0; top:0; width:340px; padding:18px 18px 0; background:#fffdf7; + box-shadow:0 14px 30px rgba(0,0,0,.45); transform-origin:50% 40%; box-sizing:content-box; } +#polaroid-alert .photo.main { position:relative; } +#polaroid-alert .ph { height:290px; background:var(--phbg, linear-gradient(#ffd9e0,#f8c3cf)); position:relative; overflow:hidden; } +#polaroid-alert .ph img { position:absolute; bottom:0; left:50%; transform:translateX(-50%); width:300px; display:block; } +#polaroid-alert .back .blank { height:70px; } + +#polaroid-alert .cap { font:700 34px/1.05 'Caveat', cursive; color:var(--ink); text-align:center; padding:14px 34px 20px; } +#polaroid-alert .cap .u { color:var(--red); display:block; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#polaroid-alert .cap .msg { font-size:24px; line-height:1.1; color:#7a6656; margin-top:6px; + overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; } + +#polaroid-alert .tape { position:absolute; z-index:3; width:130px; height:36px; top:-16px; opacity:0; + background-color:var(--tape, rgba(201,182,228,.85)); + background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px); + box-shadow:0 1px 2px rgba(0,0,0,.15); } +#polaroid-alert .t1 { left:-30px; } +#polaroid-alert .t2 { right:-30px; } + +#polaroid-alert .sticker { filter:drop-shadow(4px 0 0 #fff) drop-shadow(-4px 0 0 #fff) drop-shadow(0 4px 0 #fff) + drop-shadow(0 -4px 0 #fff) drop-shadow(0 6px 10px rgba(0,0,0,.35)); } +#polaroid-alert .heart { position:absolute; z-index:4; right:-66px; bottom:-34px; width:104px; opacity:0; } +#polaroid-alert .heart.extra { width:70px; bottom:30px; } + +#polaroid-alert .badge { position:absolute; z-index:5; right:-34px; top:40px; width:96px; height:96px; border-radius:50%; + background:var(--badge, #f6c75b); border:5px solid #fff; box-shadow:0 6px 10px rgba(0,0,0,.35); box-sizing:content-box; + display:flex; flex-direction:column; align-items:center; justify-content:center; opacity:0; + font:700 40px/0.9 'Caveat', cursive; color:#fff; text-shadow:0 2px 0 rgba(0,0,0,.25); } +#polaroid-alert .badge small { font-size:19px; line-height:1; } + +/* variation name on a paper label (redeems) */ +#polaroid-alert .tag { position:absolute; left:10px; bottom:10px; max-width:85%; padding:2px 12px; background:#fffdf7; + font:700 26px/1.2 'Caveat', cursive; color:var(--ink); transform:rotate(-3deg); box-shadow:0 2px 4px rgba(0,0,0,.25); + white-space:nowrap; overflow:hidden; text-overflow:ellipsis; box-sizing:border-box; } + +/* raid send-off: square Twitch avatar fills the photo instead of standing on the bottom edge */ +#polaroid-alert .ph.avatar img { width:100%; height:100%; bottom:0; object-fit:cover; } + +/* no picture set (Actions → Alerts): the first letter of the name, handwritten */ +#polaroid-alert .ph .ini { position:absolute; inset:0; display:grid; place-items:center; font:700 170px/1 'Caveat', cursive; color:rgba(255,255,255,.9); text-shadow:0 4px 12px rgba(0,0,0,.12); } diff --git a/public/alerts/polaroid.js b/public/alerts/polaroid.js new file mode 100644 index 0000000..cb1eddb --- /dev/null +++ b/public/alerts/polaroid.js @@ -0,0 +1,374 @@ +/* + Polaroid alerts for the OBS overlay. + + window.PolaroidAlerts.play(alert) queue an alert (never overlaps) + window.PolaroidAlerts.playTest(alert) test alert: replaces a showing/queued TEST alert at once, + but never interrupts or drops a real one (it queues behind it). + A real alert cuts off a test that is showing. + window.PolaroidAlerts.reset() stop the current alert and clear the queue + window.PolaroidAlerts.skip() stop the current alert (e.g. a TTS message), carry on with the queue + + Alert shapes come from src/alerts.js: + { type:'follow', user } + { type:'sub', user, tier, prime, months, duration, message } + { type:'gift', user|null, total, recipient, tier } + { type:'streak', user, streak } + { type:'raid', user, viewers } + { type:'bits', user|null, bits, message } + { type:'tip', user, amount, currency, message } (StreamElements) + { type:'hype', phase:'begin'|'level'|'end', level, golden, treasure, top } (Hype Train v2) + { type:'redeem', kind, key, user, reward, variation, rarity, input, caption, sound (URL), volume, polaroid, art } + channel point rewards / Power-ups, configured on the dashboard Redeems page; drawn as a + cassette tape by cassette.js (polaroid:false = sound only, art = sticker URL) + Everything per event (art, caption, tape colour, badge, sound) is in describe() below. +*/ +(function () { + // ===================== 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; + // 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 DEFAULT_VOLUME = 0.8; + + const TAPE = { + follow:'rgba(201,182,228,.88)', sub:'rgba(244,160,168,.88)', prime:'rgba(140,200,240,.88)', + gift:'rgba(150,215,180,.88)', streak:'rgba(246,206,110,.9)', raid:'rgba(250,170,120,.88)', + bits:'rgba(190,160,240,.88)', redeem:'rgba(140,215,215,.88)', + }; + + // 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] }; + const AFTER_ANIM = 3000; // ms the finished polaroid stays up after its entrance animation + const SOUND_LEAD = 400; // ms after the photo starts dropping that the sound starts + const GAP = 600; // ms between queued alerts + + // 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: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] || ''); + const atTier = tier ? ` at ${tier}` : ''; + let line; + if (multi) line = `subscribed${atTier} for ${dur} months at once! ♡`; + 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 ? 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: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: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: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: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 + let money; + 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: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 (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: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)' }; + } + case 'redeem': { + // shown as a cassette tape (cassette.js); polaroid:false = sound only + const fill = t => String(t || '').replace(/\{reward\}/g, e.reward || '').replace(/\{variation\}/g, e.variation || ''); + return { cassette: true, style: e.style || 'cassette', emote: e.emote || null, sticker: rebase(e.art) || null, icon: e.icon || null, + name: e.user || 'Someone', line: fill(e.caption || 'redeemed it! ♡'), msg: e.input, + title: e.variation || e.reward, sub: e.reward, rarity: e.rarity, + sound: e.sound || null, volume: e.volume, soundOnly: e.polaroid === false && !e.tts, + tts: e.tts ? rebase(e.tts) : null, ttsMs: e.tts_ms || 0, ttsEnv: e.tts_env || [], ttsPrefix: e.tts_prefix || 0 }; + } + case 'bits': { + if (!(e.bits >= BITS_MIN)) return null; + 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)' }; + } + } + return null; + } + + // ===================== ENGINE ===================== + const rnd = Math.random; + const between = ([a, b]) => a + rnd() * (b - a); + const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); + + let el = null; + function root() { + if (!el) { el = document.createElement('div'); el.id = 'polaroid-alert'; document.body.appendChild(el); } + return el; + } + + // preload images and sounds so the first alert of the stream is not blank or late + function preload() { + 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); }); + } + + // built-in sounds are file names, redeem sounds are URLs + const soundUrl = s => !s ? null : (s.startsWith('/') ? rebase(s) : SND(s)); + const lengths = {}; + // sound length in ms: known table, else measured once in the browser (max 3 s wait) + function soundLength(url) { + const base = decodeURIComponent(url.split('/').pop()); + if (SOUND_MS[base]) return Promise.resolve(SOUND_MS[base]); + if (lengths[url] != null) return Promise.resolve(lengths[url]); + return new Promise(res => { + const a = new Audio(); a.preload = 'metadata'; + const done = ms => { clearTimeout(t); res(lengths[url] = ms); }; + const t = setTimeout(() => done(0), 3000); + a.addEventListener('loadedmetadata', () => done(isFinite(a.duration) ? a.duration * 1000 : 0), { once:true }); + a.addEventListener('error', () => done(0), { once:true }); + a.src = url; + }); + } + + const queue = []; + let busy = false, current = null, gen = 0; + + function play(alert) { + const d = describe(alert); + if (!d) { console.log('[alerts] skipped', alert); return; } + d.test = !!alert.test; + if (!d.test) { + // a real alert is never delayed by tests: drop queued tests, cut a test that is on screen + for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1); + if (current && current.test) skipCurrent(); + } + queue.push(d); + if (!busy) next(); + } + + // stop what is on screen and carry on with the queue + function skipCurrent() { + gen++; + clearTimeout(current.timer); + if (current.audio) { current.audio.pause(); current.audio.currentTime = 0; } + current.anims.forEach(a => a.cancel()); + current = null; + if (el) el.style.visibility = 'hidden'; + window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide(); + busy = false; + } + + function playTest(alert) { + for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1); // older tests: gone + if (current && current.test) skipCurrent(); // a test on screen: cut it + play({ ...alert, test: true }); // a real one on screen: wait + } + + // dashboard Skip button: cut what is on screen (sound/TTS too), then play the next queued alert + function skip() { + if (!current) return; + skipCurrent(); + setTimeout(() => { if (!busy) next(); }, GAP); + } + + function reset() { + gen++; + queue.length = 0; + if (current) { + clearTimeout(current.timer); + if (current.audio) { current.audio.pause(); current.audio.currentTime = 0; } + current.anims.forEach(a => a.cancel()); + current = null; + } + if (el) el.style.visibility = 'hidden'; + window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide(); + busy = false; + } + + async function next() { + const d = queue.shift(); + if (!d) { busy = false; return; } + busy = true; + const my = gen; + await show(d); + if (my !== gen) return; + setTimeout(() => { if (my === gen) next(); }, GAP); + } + + function photoHTML(cls, art, inner) { + return `
${art ? `` : ''}
${inner}
`; + } + + async function show(d) { + const el = root(); + const cur = current = { anims:[], timer:null, audio:null, test:!!d.test }; + const url = soundUrl(d.sound); + 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 ?? (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 ?? (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 ?? (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); + return wait.finished.then(() => { if (current === cur) current = null; }).catch(() => {}); + } + + 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', backArt[i % backArt.length], '
')).join(''); + const heart = ART(th.heart); // corner sticker; none set = no stickers + const extraHearts = heart ? Array.from({ length: d.hearts || 0 }, () => + ``).join('') : ''; + el.innerHTML = backs + ` +
+
+
${d.art ? `` : `${esc((d.name || '♥').trim()[0] || '♥').toUpperCase()}`}${d.tag ? `${esc(d.tag)}` : ''}
+
${esc(d.name)}${esc(d.line)}${d.msg ? `“${esc(d.msg)}”` : ''}
+ ${heart ? `` : ''} + ${extraHearts} + ${d.badge ? `
${esc(d.badge.big)}${esc(d.badge.small)}
` : ''} +
`; + el.style.visibility = 'visible'; + + const q = s => el.querySelector(s); + const main = q('.photo.main'); + const tilt = between(RANGES.photoTilt) * (rnd() < .5 ? -1 : 1); + const rot = dd => `rotate(${tilt + dd}deg)`; + const anims = cur.anims; + const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); anims.push(a); return a; }; + + // fanned stack behind the main photo (multi-month subs, community gifts, raids) + const backEls = [...el.querySelectorAll('.photo.back')]; + const t0 = backEls.length ? 120 * backEls.length + 150 : 0; + backEls.forEach((b, i) => { + const ang = 4 + i * 4 + between([-2, 2]), dx = 24 + i * 26 + between([-4, 4]), dy = i * 5 + between([-4, 4]); + A(b, [ + { transform:`translate(${dx}px,${dy - 150}px) rotate(${ang * 2}deg)`, opacity:0 }, + { transform:`translate(${dx}px,${dy}px) rotate(${ang}deg)`, opacity:1 }, + ], { delay:i * 120, duration:450, easing:'cubic-bezier(.2,.8,.3,1)' }); + }); + + // 1. photo drops in + A(main, [ + { transform:`translateY(-160px) rotate(${tilt * -2.5}deg) scale(1.15)`, opacity:0 }, + { transform:`translateY(10px) ${rot(tilt > 0 ? 1.5 : -1.5)} scale(.99)`, opacity:1, offset:.7 }, + { transform:`translateY(0) ${rot(0)} scale(1)`, opacity:1 }, + ], { delay:t0, duration:750, easing:'cubic-bezier(.2,.8,.3,1)' }); + + const nudge = (at, dx) => A(main, [ + { transform:`translateY(0) ${rot(0)}` }, { transform:`translateY(3px) ${rot(dx)}` }, { transform:`translateY(0) ${rot(0)}` }, + ], { delay:at, duration:220, easing:'ease-out', fill:'none' }); + + // 2. tapes press on + const tapeT = (x, y, a, s) => `translate(${x}px,${y}px) rotate(${a}deg) scale(${s})`; + const stick = (node, a, at) => { + const x = between(RANGES.tapeX), y = between(RANGES.tapeY); + A(node, [ + { transform:tapeT(x, y - 30, a - 8, 1.35), opacity:0 }, + { transform:tapeT(x, y, a, .94), opacity:1, offset:.75 }, + { transform:tapeT(x, y, a, 1), opacity:1 }, + ], { delay:at, duration:260, easing:'cubic-bezier(.3,.7,.4,1)' }); + }; + stick(q('.t1'), between(RANGES.tape1), t0 + 800); nudge(t0 + 1000, -.6); + stick(q('.t2'), between(RANGES.tape2), t0 + 1080); nudge(t0 + 1280, .6); + + // 3. stickers slap on + const slap = (node, at, x, y, a) => A(node, [ + { transform:`translate(${x}px,${y}px) rotate(${a - 40}deg) scale(0)`, opacity:0 }, + { transform:`translate(${x}px,${y}px) rotate(${a + 6}deg) scale(1.25)`, opacity:1, offset:.6 }, + { 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' }); + 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]))); + const badge = q('.badge'); + if (badge) slap(badge, t0 + 1250, 0, 0, between(RANGES.badge)); + + // 4. caption writes in + A(q('.cap'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }], + { delay:t0 + 1700, duration:700, easing:'ease-in-out' }); + + // stays up: entrance animation + 3 s, or until the sound has finished if that is later + 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 ?? (TH().volume ?? DEFAULT_VOLUME); + cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + SOUND_LEAD); + } + + // 5. exit: lift and drop away + const exitAt = Math.max(animEnd + AFTER_ANIM, soundEnd); + const exit = A(el, [ + { transform:'translateY(0) rotate(0) scale(1)', opacity:1 }, + { transform:'translateY(-20px) rotate(0deg) scale(1.04)', opacity:1, offset:.25 }, + { transform:`translateY(140px) rotate(${tilt > 0 ? 14 : -14}deg) scale(.9)`, opacity:0 }, + ], { delay:exitAt, duration:650, easing:'ease-in' }); + + return exit.finished + .then(() => { el.style.visibility = 'hidden'; anims.forEach(a => a.cancel()); if (current === cur) current = null; }) + .catch(() => {}); // cancelled by reset() + } + + window.PolaroidAlerts = { play, playTest, reset, skip, describe }; + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload(); +})(); diff --git a/public/alerts/poll.css b/public/alerts/poll.css new file mode 100644 index 0000000..d894da9 --- /dev/null +++ b/public/alerts/poll.css @@ -0,0 +1,23 @@ +/* Live poll card (see poll.js): taped paper, left side below the alert corner. */ +#poll-card { --ink:#3a2a20; --red:#b74347; position:fixed; left:85px; top:650px; width:460px; z-index:45; visibility:hidden; + padding:24px 26px 22px; background:#fffdf7; box-shadow:0 14px 30px rgba(0,0,0,.45); } +#poll-card * { box-sizing:border-box; } +#poll-card:before, #poll-card:after { content:''; position:absolute; top:-14px; width:110px; height:32px; + background:rgba(140,215,215,.88); background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px); box-shadow:0 1px 2px rgba(0,0,0,.15); } +#poll-card:before { left:-30px; transform:rotate(-30deg); } +#poll-card:after { right:-30px; transform:rotate(26deg); } +#poll-card .head { display:flex; justify-content:space-between; align-items:baseline; font:900 15px 'Nunito', sans-serif; letter-spacing:2px; color:#7a6656; } +#poll-card .timer { font:700 26px 'Caveat', cursive; letter-spacing:0; color:var(--red); } +#poll-card .q { font:700 38px/1.05 'Caveat', cursive; color:var(--ink); margin:4px 0 12px; } +#poll-card .c { position:relative; margin:8px 0; } +#poll-card .row { display:flex; justify-content:space-between; font:700 28px/1 'Caveat', cursive; color:var(--ink); margin-bottom:3px; } +#poll-card .row .n { font-size:24px; color:#7a6656; } +#poll-card .track { height:18px; border:3px solid var(--ink); border-radius:10px; background:#fff; overflow:hidden; } +#poll-card .fill { height:100%; width:0; border-radius:6px; transition:width .6s cubic-bezier(.3,.7,.4,1); + background-image:repeating-linear-gradient(45deg,#fff5 0 6px,#0000 6px 12px); } +#poll-card .c.win .row .t { color:var(--red); } +#poll-card .c.lose { opacity:.55; } +#poll-card .heart { position:absolute; right:-78px; top:-22px; width:64px; opacity:0; + filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 4px 6px rgba(0,0,0,.35)); } +#poll-card .stamp { position:absolute; right:22px; top:14px; padding:4px 14px; border:4px solid var(--red); border-radius:8px; color:var(--red); + font:900 26px 'Nunito', sans-serif; letter-spacing:3px; transform:rotate(-12deg); opacity:0; } diff --git a/public/alerts/poll.js b/public/alerts/poll.js new file mode 100644 index 0000000..13d4aed --- /dev/null +++ b/public/alerts/poll.js @@ -0,0 +1,92 @@ +/* + Live poll card for the overlay. Not part of the alert queue: it stays up while the poll runs. + PollCard.update(phase, poll) phase: begin | progress | end + poll: { id, title, choices:[{ id, title, votes }], ends_at, status } (status on end: completed | archived | terminated) + Votes animate live; on 'completed' the winner(s) get a heart and a WINNER stamp, then the card drops away. +*/ +(function () { + const COLORS = ['#f4a0a8', '#a88be0', '#7fcfa6', '#f6c75b', '#8cc8f0']; + // heart on the winning option: the corner sticker from Actions → Alerts, else a plain shape + const heart = () => (window.S && window.S.alert_theme && window.S.alert_theme.heart) || (window.ALERTS_BASE || '/alerts/') + 'art/placeholder.svg'; + const SHOW_RESULT_MS = 9000; + const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c])); + let el = null, pollId = null, timer = null, hideTimer = null, endsAt = 0; + + function root() { + if (!el) { el = document.createElement('div'); el.id = 'poll-card'; document.body.appendChild(el); } + return el; + } + + function build(poll) { + const el = root(); + clearTimeout(hideTimer); el.getAnimations().forEach(a => a.cancel()); + pollId = poll.id; + el.innerHTML = `
POLL
+
${esc(poll.title)}
+ ${poll.choices.map((c, i) => `
+
${esc(c.title)}0
+
+
`).join('')} +
WINNER
`; + el.style.visibility = 'visible'; + const tilt = (Math.random() * 4 - 2).toFixed(2); + el.animate([ + { transform:`translateX(-560px) rotate(-8deg)`, opacity:0 }, + { transform:`translateX(10px) rotate(${+tilt + 1}deg)`, opacity:1, offset:.75 }, + { transform:`translateX(0) rotate(${tilt}deg)`, opacity:1 }, + ], { duration:650, easing:'cubic-bezier(.2,.8,.3,1)', fill:'forwards' }); + } + + function votes(poll) { + const total = poll.choices.reduce((s, c) => s + c.votes, 0); + for (const c of poll.choices) { + const row = el.querySelector(`.c[data-id="${CSS.escape(c.id)}"]`); + if (!row) continue; + const pct = total ? Math.round(100 * c.votes / total) : 0; + row.querySelector('.n').textContent = `${c.votes} · ${pct}%`; + row.querySelector('.fill').style.width = `${total ? Math.max(3, pct) : 0}%`; + } + return total; + } + + function tick() { + const s = Math.max(0, Math.round((endsAt - Date.now()) / 1000)); + const t = el.querySelector('.timer'); + if (t) t.textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')} left`; + } + + function hide(delay) { + clearTimeout(hideTimer); + hideTimer = setTimeout(() => { + el.animate([{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(160px) rotate(10deg)', opacity:0 }], + { duration:550, easing:'ease-in', fill:'forwards' }).finished.then(() => { el.style.visibility = 'hidden'; pollId = null; }).catch(() => {}); + }, delay); + } + + function update(phase, poll) { + if (!poll || !poll.choices) return; + if (phase === 'begin' || pollId !== poll.id) build(poll); + votes(poll); + if (poll.ends_at) { endsAt = Date.parse(poll.ends_at); clearInterval(timer); timer = setInterval(tick, 500); tick(); } + if (phase !== 'end') return; + clearInterval(timer); + const t = el.querySelector('.timer'); + if (poll.status !== 'completed') { if (t) t.textContent = 'cancelled'; hide(1500); return; } + if (t) t.textContent = ''; // the WINNER stamp takes this corner + const max = Math.max(...poll.choices.map(c => c.votes)); + el.querySelectorAll('.c').forEach(row => { + const c = poll.choices.find(x => x.id === row.dataset.id); + const win = max > 0 && c.votes === max; + row.classList.add(win ? 'win' : 'lose'); + if (win) row.querySelector('.heart').animate([ + { transform:'rotate(-40deg) scale(0)', opacity:0 }, { transform:'rotate(10deg) scale(1.3)', opacity:1, offset:.6 }, { transform:'rotate(6deg) scale(1)', opacity:1 }, + ], { delay:300, duration:450, easing:'ease-out', fill:'forwards' }); + }); + if (max > 0) el.querySelector('.stamp').animate([ + { transform:'rotate(-12deg) scale(2.2)', opacity:0 }, { transform:'rotate(-12deg) scale(.9)', opacity:1, offset:.7 }, { transform:'rotate(-12deg) scale(1)', opacity:1 }, + ], { delay:700, duration:380, easing:'ease-in', fill:'forwards' }); + hide(SHOW_RESULT_MS); + } + + window.PollCard = { update }; +})(); diff --git a/public/alerts/raidcard.css b/public/alerts/raidcard.css new file mode 100644 index 0000000..cb22434 --- /dev/null +++ b/public/alerts/raidcard.css @@ -0,0 +1,15 @@ +/* Outgoing raid send-off card (see raidcard.js): big taped polaroid, top-centre, silent, stays during the countdown. */ +#raid-card { --ink:#3a2a20; --red:#b74347; position:fixed; left:50%; top:60px; width:340px; margin-left:-170px; z-index:58; visibility:hidden; + padding:16px 16px 0; background:#fffdf7; box-shadow:0 16px 34px rgba(0,0,0,.5); } +#raid-card * { box-sizing:border-box; } +#raid-card:before, #raid-card:after { content:''; position:absolute; top:-15px; width:120px; height:34px; z-index:2; + background:rgba(250,170,120,.9); background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px); box-shadow:0 1px 2px rgba(0,0,0,.15); } +#raid-card:before { left:-30px; transform:rotate(-28deg); } +#raid-card:after { right:-30px; transform:rotate(26deg); } +#raid-card .ph { height:300px; background:linear-gradient(#ffe6d6,#f8c8a8) ; position:relative; overflow:hidden; } +#raid-card .ph img { width:100%; height:100%; object-fit:cover; display:block; } +#raid-card .ph img.fallback { object-fit:contain; object-position:bottom; } +#raid-card .cap { font:700 32px/1.05 'Caveat', cursive; color:var(--ink); text-align:center; padding:12px 10px 16px; } +#raid-card .cap .u { color:var(--red); display:block; font-size:38px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +#raid-card .when { position:absolute; right:-40px; top:28px; padding:6px 14px; background:#e07a45; color:#fff; border:4px solid #fff; border-radius:30px; + font:900 20px 'Nunito', sans-serif; letter-spacing:1px; box-shadow:0 6px 10px rgba(0,0,0,.35); transform:rotate(6deg); white-space:nowrap; } diff --git a/public/alerts/raidcard.js b/public/alerts/raidcard.js new file mode 100644 index 0000000..359d361 --- /dev/null +++ b/public/alerts/raidcard.js @@ -0,0 +1,64 @@ +/* + Outgoing raid send-off card. Silent, outside the alert queue. + RaidCard.update(phase, raid) phase: start | done | cancel + raid: { target, avatar (Twitch profile picture URL or null), viewers, started_at } + start: appears and stays with a countdown (Twitch raids wait up to 90 s); done: "raid sent!" then leaves; cancel: leaves. +*/ +(function () { + const COUNTDOWN_S = 90; + const BASE = window.ALERTS_BASE || '/alerts/'; + // 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 ? `` + : ``; + el.innerHTML = `
${img}
+
raiding ${esc(raid.target)}${esc(line)}
+
${esc(badge)}
`; + } + function tick() { + const left = Math.max(0, COUNTDOWN_S - Math.round((Date.now() - startedAt) / 1000)); + const w = el.querySelector('.when'); + if (w) w.textContent = left ? `raid in ${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}` : 'any second now…'; + } + function enter() { + if (shown) return; + shown = true; el.style.visibility = 'visible'; + el.getAnimations().forEach(a => a.cancel()); + el.animate([{ transform:'translateY(-420px) rotate(-10deg)', opacity:0 }, { transform:'translateY(10px) rotate(2deg)', opacity:1, offset:.75 }, + { transform:'translateY(0) rotate(-1deg)', opacity:1 }], { duration:700, easing:'cubic-bezier(.2,.8,.3,1)', fill:'forwards' }); + } + function leave(delay) { + clearTimeout(hideTimer); + hideTimer = setTimeout(() => { + clearInterval(timer); + el.animate([{ transform:'translateY(0) rotate(-1deg)', opacity:1 }, { transform:'translateX(700px) rotate(18deg)', opacity:0 }], + { duration:700, easing:'ease-in', fill:'forwards' }).finished.then(() => { el.style.visibility = 'hidden'; shown = false; }).catch(() => {}); + }, delay); + } + + function update(phase, raid) { + root(); clearTimeout(hideTimer); + const viewers = raid.viewers != null ? `with ${raid.viewers} of you, be nice! ♡` : 'with all of you, be nice! ♡'; + if (phase === 'start') { + startedAt = raid.started_at ? Date.parse(raid.started_at) : Date.now(); + render(raid, viewers, ''); + enter(); clearInterval(timer); timer = setInterval(tick, 500); tick(); + } else if (phase === 'done') { + clearInterval(timer); + render(raid, 'raid sent! see you there ♡', 'GO GO GO'); + enter(); leave(6000); + } else if (phase === 'cancel') { + clearInterval(timer); + if (!shown) return; + const w = el.querySelector('.when'); if (w) w.textContent = 'cancelled'; + leave(1500); + } + } + window.RaidCard = { update }; +})(); diff --git a/public/alerts/video.css b/public/alerts/video.css new file mode 100644 index 0000000..b2b377e --- /dev/null +++ b/public/alerts/video.css @@ -0,0 +1,40 @@ +/* Video redeems (?parts=video, see video.js): full-screen video + a camcorder notification box, + the HUDFX box's look in yellow, in the alert corner (85,110, 440px wide on 1920x1080; video.js zooms the box + to the page width, so a 2560x1440 source looks the same, only sharper). */ +@import url('https://fonts.googleapis.com/css2?family=VT323&display=swap'); + +#vfx-video { position:fixed; inset:0; width:100vw; height:100vh; object-fit:contain; background:transparent; + visibility:hidden; pointer-events:none; z-index:40; } + +#vfx-box { + --yellow:#eeb434; --pale:#ffe7a3; --screen:#241e12; + position:fixed; left:85px; top:110px; width:440px; box-sizing:border-box; z-index:41; visibility:hidden; + padding:46px 22px 26px; border:5px solid var(--yellow); border-radius:12px; + box-shadow:0 0 0 3px #15110a, 0 0 22px rgba(238,180,52,.55), 0 14px 26px rgba(0,0,0,.5); + background: + linear-gradient(#fff,#fff) 12px 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) 12px 12px / 4px 26px no-repeat, + linear-gradient(#fff,#fff) right 12px top 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) right 12px top 12px / 4px 26px no-repeat, + linear-gradient(#fff,#fff) left 12px bottom 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) left 12px bottom 12px / 4px 26px no-repeat, + linear-gradient(#fff,#fff) right 12px bottom 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) right 12px bottom 12px / 4px 26px no-repeat, + repeating-linear-gradient(0deg, rgba(255,255,255,.045) 0 2px, transparent 2px 4px), + radial-gradient(ellipse at 50% 45%, #43361a 0%, var(--screen) 70%) #241e12; + font-family:'VT323', monospace; color:#fff; text-align:center; +} +#vfx-box .rec { position:absolute; left:58px; top:16px; font-size:26px; color:#ff3b4e; text-shadow:0 0 6px rgba(255,59,78,.7); + animation:vfx-blink 1s steps(1) infinite; } +#vfx-box .tc { position:absolute; right:24px; top:16px; font-size:24px; opacity:.85; } +#vfx-box .title { font-size:36px; line-height:1; text-transform:uppercase; overflow-wrap:anywhere; + text-shadow:2px 0 rgba(255,59,120,.75), -2px 0 rgba(80,220,255,.75); } +#vfx-box .who { font-size:32px; line-height:1; margin-top:10px; color:var(--pale); text-transform:uppercase; overflow-wrap:anywhere; + text-shadow:2px 0 rgba(255,59,120,.6), -2px 0 rgba(80,220,255,.6); } +#vfx-box .amt { display:inline-block; margin-top:16px; padding:2px 16px; background:var(--yellow); color:#241e12; font-size:28px; + border-radius:4px; text-transform:uppercase; box-shadow:0 0 12px rgba(238,180,52,.7); } +#vfx-box .amt:empty { display:none; } +#vfx-box .brand { position:absolute; right:46px; bottom:14px; font:900 13px/1 'Nunito', sans-serif; letter-spacing:1.5px; + color:var(--yellow); opacity:.8; } +@keyframes vfx-blink { 0% { opacity:1; } 50% { opacity:0; } } + +/* the Power-up's / reward's Twitch icon as a sticker on the box's top-left corner */ +#vfx-box .ico { position:absolute; left:-30px; top:-30px; width:72px; height:72px; object-fit:contain; transform:rotate(-10deg); z-index:2; + filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 5px 8px rgba(0,0,0,.35)); } +#vfx-box .ico[hidden] { display:none; } diff --git a/public/alerts/video.js b/public/alerts/video.js new file mode 100644 index 0000000..8c6e6f6 --- /dev/null +++ b/public/alerts/video.js @@ -0,0 +1,77 @@ +/* + Video redeems, for the ?parts=video overlay (an OBS source of its own, e.g. instead of HUDFX). + Any source size works; 2560x1440 like HUDFX gives sharper video. The box is laid out for 1920x1080 and + zoomed to the page width, so it always lands in the alert corner. + Redeem variations with a video (style 'video', see src/redeems.js) play here full-screen, one at a time, + with a camcorder notification box (video.css) while the video runs. + VideoFX.play(alert) queue it + VideoFX.playTest(alert) test: replaces a playing/queued test at once + VideoFX.skip() stop the current one, carry on with the queue + alert: { video, volume, user, reward, variation, bits, test } +*/ +(() => { + const queue = []; + let cur = null, vid = null, box = null, tcTimer = null; + + function els() { + if (vid) return; + vid = document.createElement('video'); vid.id = 'vfx-video'; vid.playsInline = true; document.body.appendChild(vid); + box = document.createElement('div'); box.id = 'vfx-box'; + box.innerHTML = '
● REC
POWER-UP
'; + document.body.appendChild(box); + fit(); addEventListener('resize', fit); + } + function fit() { if (box) box.style.zoom = innerWidth / 1920; } + const fmt = s => { s = Math.max(0, Math.floor(s)); return `▶ ${Math.floor(s / 3600)}:${String(Math.floor(s / 60) % 60).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`; }; + + function show(a) { + els(); + const name = a.variation && a.variation !== a.reward ? a.variation : (a.reward || 'Power-up'); + box.querySelector('.title').textContent = `Triggered ${name}`; + box.querySelector('.who').textContent = a.user || ''; + box.querySelector('.amt').textContent = a.bits ? `◆ ${a.bits} bits ◆` : ''; + box.querySelector('.tc').textContent = fmt(0); + const ico = box.querySelector('.ico'); // the Power-up's / reward's Twitch icon, top-left corner + if (a.icon) { ico.src = a.icon; ico.hidden = false; } else { ico.removeAttribute('src'); ico.hidden = true; } + box.style.visibility = 'visible'; + box.animate([{ opacity: 0, transform: 'translateY(-12px)' }, { opacity: 1, transform: 'none' }], { duration: 400, easing: 'ease-out', fill: 'both' }); + clearInterval(tcTimer); tcTimer = setInterval(() => { box.querySelector('.tc').textContent = fmt(vid.currentTime); }, 250); + } + function hideBox() { + clearInterval(tcTimer); + if (!box || box.style.visibility !== 'visible') return; + box.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 500, fill: 'both' }).finished + .then(() => { if (!cur) box.style.visibility = 'hidden'; }).catch(() => {}); + } + + function finish(a) { + if (cur !== a) return; + clearTimeout(a._guard); + vid.pause(); vid.removeAttribute('src'); vid.load(); vid.style.visibility = 'hidden'; + cur = null; + hideBox(); + setTimeout(next, 600); + } + function next() { + if (cur || !queue.length) return; + const a = cur = queue.shift(); + show(a); + vid.src = a.video; vid.volume = Math.max(0, Math.min(1, a.volume ?? 0.8)); vid.currentTime = 0; + vid.style.visibility = 'visible'; + vid.onended = () => finish(a); + vid.onerror = () => { console.warn('[video] could not play', a.video); setTimeout(() => finish(a), 2500); }; + vid.play().catch(e => { console.warn('[video] play:', e.message); setTimeout(() => finish(a), 2500); }); + a._guard = setTimeout(() => finish(a), 120000); // never block the queue on a broken/endless file + } + + function play(a) { if (!a?.video) return; queue.push(a); next(); } + function playTest(a) { + if (!a?.video) return; + for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1); + if (cur?.test) { queue.unshift({ ...a, test: true }); finish(cur); } + else play({ ...a, test: true }); + } + function skip() { if (cur) finish(cur); } + + window.VideoFX = { play, playTest, skip }; +})(); diff --git a/public/alerts/videos/.gitkeep b/public/alerts/videos/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/public/chat/chat.css b/public/chat/chat.css new file mode 100644 index 0000000..c30f69d --- /dev/null +++ b/public/chat/chat.css @@ -0,0 +1,82 @@ +/* Chat: cream paper slips with the name on a washi-tape label ("style 5" from the chat preview). + The box sits under the webcam (Game scene: camera group at 1920,600, 640x360 on the 2560 canvas + = 1440,450 480x270 on this 1920x1080 page). Newest message on top, slides out from under the camera, + older ones are pushed down and dissolve at the bottom edge. + Per browser source: ?chat=left,top,width,height (px of the 1920x1080 page) and ?chatflow=up (newest at the bottom), + e.g. the Intermission panel: ?parts=chat&chat=130,640,700,360&chatflow=up. Default (no ?chat): under the camera, flowing down. */ +#chat { + --chat-left: 78%; + --chat-top: 63%; /* 680px: just above the bottom of the camera ring, so messages come out from under it */ + --chat-width: 20%; + --chat-height: 34%; /* down to the bottom edge */ + --ink: #3a2a20; + --cream: #fffdf7; + position: fixed; + left: var(--chat-left); + top: var(--chat-top); + width: var(--chat-width); + height: var(--chat-height); + display: flex; + flex-direction: column; + justify-content: flex-start; + gap: 8px; + padding: 26px 8px 0; + overflow: hidden; + -webkit-mask-image: linear-gradient(transparent 0, #000 30px, #000 calc(100% - 60px), transparent); + mask-image: linear-gradient(transparent 0, #000 30px, #000 calc(100% - 60px), transparent); +} + +/* up: like a normal chat, newest at the bottom, the oldest fade out at the top */ +#chat.up { + justify-content: flex-end; + padding: 14px 8px 8px; + -webkit-mask-image: linear-gradient(transparent 0, #000 50px); + mask-image: linear-gradient(transparent 0, #000 50px); +} +#chat.up .msg.in { animation-name: chat-in-up; } +@keyframes chat-in-up { from { opacity: 0; transform: translateY(24px) rotate(calc(var(--tilt, 0deg) * -3)) scale(.95); } } + +#chat .msg { + position: relative; + flex: none; + margin: 9px 6px 0; + padding: 19px 14px 9px; + border-radius: 2px; + background: var(--cream); + color: var(--ink); + font: 800 17px/1.3 Nunito, sans-serif; + word-break: break-word; + box-shadow: 0 3px 8px rgba(0, 0, 0, .35); + transform: rotate(var(--tilt, 0deg)); +} +#chat .msg.action { font-style: italic; } + +/* the name on a strip of washi tape, tinted with the chatter's Twitch colour */ +#chat .msg .u { + position: absolute; + top: -12px; + left: 10px; + max-width: 85%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 1px 12px 2px; + font: 700 23px/1 Caveat, cursive; + color: var(--ink); + background-color: var(--tape, rgba(201, 182, 228, .92)); + background-image: repeating-linear-gradient(45deg, #fff5 0 6px, #0000 6px 12px); + transform: rotate(calc(var(--tilt, 0deg) * -2)); + box-shadow: 0 1px 2px rgba(0, 0, 0, .2); + clip-path: polygon(0 8%, 3% 0, 97% 4%, 100% 0, 98% 100%, 2% 94%); +} + +/* emotes (Twitch + 7TV). Zero-width 7TV emotes (RainTime, PETPET...) stack on the emote before them. */ +#chat .em { position: relative; display: inline-grid; vertical-align: -0.45em; margin: 0 1px; } +#chat .em > img { grid-area: 1 / 1; height: 1.6em; width: auto; justify-self: center; align-self: center; + filter: drop-shadow(0 0 1px rgba(58, 42, 32, .55)); } /* white emotes (Clap...) stay visible on cream */ +#chat .msg.big .em > img { height: 2.6em; } /* emote-only messages: bigger emotes */ + +#chat .msg.in { animation: chat-in .45s cubic-bezier(.2, 1.3, .4, 1) both; } +#chat .msg.out { animation: chat-out .6s ease-in both; } +@keyframes chat-in { from { opacity: 0; transform: translateY(-24px) rotate(calc(var(--tilt, 0deg) * -3)) scale(.95); } } +@keyframes chat-out { to { opacity: 0; transform: translate(40px, 30px) rotate(calc(var(--tilt, 0deg) + 12deg)); } } diff --git a/public/chat/chat.js b/public/chat/chat.js new file mode 100644 index 0000000..1582536 --- /dev/null +++ b/public/chat/chat.js @@ -0,0 +1,165 @@ +/* Chat messages for the overlay (?parts=chat). tmi.js in overlay.ejs feeds them in via HSChat.add(). + Look: public/chat/chat.css. Emotes: Twitch (from the message tags) + 7TV channel and global sets. + Settings used: S.message_timeout (seconds, 0 = never fade) and S.max_messages. */ +(function () { + const box = document.getElementById('chat'); + if (!box) return; + + const TWITCH_EMOTE = id => `https://static-cdn.jtvnw.net/emoticons/v2/${id}/default/dark/2.0`; + const SEVENTV = 'https://7tv.io/v3'; + const ZERO_WIDTH = 256; // 7TV emote data flag: overlays the emote before it + const REFRESH_MS = 10 * 60 * 1000; // pick up newly added 7TV emotes without an OBS refresh + + let emotes7tv = new Map(); // name -> { url, zw } + let roomId = null, seq = 0; + + // ---------- 7TV ---------- + function setFrom(list, into) { + for (const e of list || []) { + const host = e.data && e.data.host; + if (!host || !host.url) continue; + const file = (host.files || []).find(f => f.name === '2x.webp') || (host.files || []).find(f => /\.webp$/.test(f.name)); + if (!file) continue; + into.set(e.name, { url: 'https:' + host.url + '/' + file.name, zw: ((e.data.flags || 0) & ZERO_WIDTH) !== 0 }); + } + } + async function getJSON(url) { + const r = await fetch(url); + if (!r.ok) throw new Error(url + ' -> ' + r.status); + return r.json(); + } + async function load7tv() { + const next = new Map(); + try { setFrom((await getJSON(`${SEVENTV}/emote-sets/global`)).emotes, next); } + catch (e) { console.warn('[chat] 7TV global emotes:', e.message); } + if (roomId) { + try { setFrom(((await getJSON(`${SEVENTV}/users/twitch/${roomId}`)).emote_set || {}).emotes, next); } // channel wins over global + catch (e) { console.warn('[chat] 7TV channel emotes:', e.message); } + } + if (next.size) emotes7tv = next; + console.log(`[chat] 7TV emotes loaded: ${next.size}`); + } + function setRoom(id) { + if (!id || id === roomId) return; + roomId = id; + load7tv(); + } + load7tv(); + setInterval(load7tv, REFRESH_MS); + + // ---------- message -> HTML ---------- + const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + const img = (url, name) => `${esc(name)}`; + + // Returns { html, emoteOnly, emoteCount }. + function render(text, twitchEmotes) { + // Twitch emote positions are in code points, so work on an array of characters + const chars = Array.from(text); + const ranges = []; + for (const [id, list] of Object.entries(twitchEmotes || {})) { + for (const r of list) { const [a, b] = r.split('-').map(Number); ranges.push({ a, b, id }); } + } + ranges.sort((x, y) => x.a - y.a); + + const tokens = []; // { t:'text', s } | { t:'em', url, name, zw } + let i = 0; + for (const r of ranges) { + if (r.a > i) tokens.push({ t: 'text', s: chars.slice(i, r.a).join('') }); + tokens.push({ t: 'em', url: TWITCH_EMOTE(r.id), name: chars.slice(r.a, r.b + 1).join(''), zw: false }); + i = r.b + 1; + } + if (i < chars.length) tokens.push({ t: 'text', s: chars.slice(i).join('') }); + + // 7TV: whole words inside the text parts + const out = []; + for (const tk of tokens) { + if (tk.t !== 'text') { out.push(tk); continue; } + for (const part of tk.s.split(/(\s+)/)) { + const e = part && emotes7tv.get(part); + out.push(e ? { t: 'em', url: e.url, name: part, zw: e.zw } : { t: 'text', s: part }); + } + } + + // build HTML; a zero-width emote joins the emote stack before it (skipping whitespace) + let html = '', open = false, count = 0, words = 0; + for (let k = 0; k < out.length; k++) { + const tk = out[k]; + if (tk.t === 'text') { + if (/^\s*$/.test(tk.s)) { + const nx = out.slice(k + 1).find(x => !(x.t === 'text' && /^\s*$/.test(x.s))); + if (open && nx && nx.t === 'em' && nx.zw) continue; // keep the stack open for the overlay emote + if (open) { html += ''; open = false; } + html += esc(tk.s); + continue; + } + if (open) { html += ''; open = false; } + html += esc(tk.s); words++; + continue; + } + count++; + if (tk.zw && open) { html += img(tk.url, tk.name); continue; } + if (open) html += ''; + html += '' + img(tk.url, tk.name); open = true; + } + if (open) html += ''; + return { html, emoteOnly: count > 0 && words === 0, emoteCount: count }; + } + + // ---------- add / remove ---------- + function tapeFrom(hex) { + const m = /^#?([0-9a-f]{6})$/i.exec(hex || ''); + const n = m ? parseInt(m[1], 16) : 0xc9b6e4; + const c = [n >> 16, (n >> 8) & 255, n & 255].map(v => Math.round(v * .55 + 255 * .45)); + return `rgba(${c[0]},${c[1]},${c[2]},.92)`; + } + const S = () => window.S || {}; + + function add(tags, text, isAction) { + if (tags && tags['room-id']) setRoom(tags['room-id']); + const name = (tags && (tags['display-name'] || tags.username)) || '?'; + const r = render(text, tags && tags.emotes); + + const d = document.createElement('div'); + d.className = 'msg in' + (r.emoteOnly && r.emoteCount <= 3 ? ' big' : '') + (isAction ? ' action' : ''); + d.dataset.id = (tags && tags.id) || ''; + d.dataset.user = ((tags && tags.username) || '').toLowerCase(); + d.style.setProperty('--tilt', (Math.random() * 3.2 - 1.6).toFixed(2) + 'deg'); + d.style.setProperty('--tape', tapeFrom(tags && tags.color)); + d.innerHTML = `${esc(name)}${r.html}`; + d._n = ++seq; + + // FLIP: remember where the others are, add the new one (on top, or at the bottom for ?chatflow=up), + // then glide the others from their old spot + const before = new Map([...box.children].map(m => [m, m.getBoundingClientRect().top])); + if (box.classList.contains('up')) box.append(d); else box.prepend(d); + before.forEach((top, m) => { + const dy = top - m.getBoundingClientRect().top; + if (dy && m.animate) m.animate([{ translate: `0 ${dy}px` }, { translate: '0 0' }], { duration: 320, easing: 'cubic-bezier(.2,.8,.3,1)' }); + }); + d.addEventListener('animationend', () => d.classList.remove('in'), { once: true }); + + // over the cap: the oldest leave with their exit animation + const live = [...box.children].filter(m => !m.classList.contains('out')).sort((a, b) => a._n - b._n); + const max = Number(S().max_messages) || 10; + live.slice(0, Math.max(0, live.length - max)).forEach(leave); + + const t = Number(S().message_timeout); + if (t > 0) d._t = setTimeout(() => leave(d), t * 1000); + } + + function leave(d) { + if (d.classList.contains('out')) return; + clearTimeout(d._t); + d.classList.remove('in'); + d.classList.add('out'); + d.addEventListener('animationend', () => d.remove(), { once: true }); + setTimeout(() => d.remove(), 1200); // in case the animation never ends (hidden source) + } + + // moderation: a deleted message, or everything from a user who got timed out / banned, leaves at once + function removeId(id) { [...box.children].filter(m => id && m.dataset.id === id).forEach(leave); } + function removeUser(user) { const u = String(user || '').toLowerCase(); [...box.children].filter(m => u && m.dataset.user === u).forEach(leave); } + function clear() { [...box.children].forEach(leave); } + + window.HSChat = { add, removeId, removeUser, clear, setRoom, reload7tv: load7tv, render }; +})(); diff --git a/public/favicon.svg b/public/favicon.svg new file mode 100644 index 0000000..560f184 --- /dev/null +++ b/public/favicon.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/public/vendor/tmi.min.js b/public/vendor/tmi.min.js new file mode 100644 index 0000000..cfe8d15 --- /dev/null +++ b/public/vendor/tmi.min.js @@ -0,0 +1 @@ +!function s(o,i,r){function a(t,e){if(!i[t]){if(!o[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(c)return c(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=i[t]={exports:{}},o[t][0].call(n.exports,function(e){return a(o[t][1][e]||e)},n,n.exports,s,o,i,r)}return i[t].exports}for(var c="function"==typeof require&&require,e=0;ee.length)&&(t=e.length);for(var n=0,s=new Array(t);n: ").concat(h)),V.hasOwn(t.tags,"username")||(t.tags.username=J),t.tags["message-type"]="whisper";J=V.channel(t.tags.username);this.emits(["whisper","message"],[[J,t.tags,h,!1]]);break;case"PRIVMSG":t.tags.username=t.prefix.split("!")[0],"jtv"===t.tags.username?(c=V.username(h.split(" ")[0]),u=h.includes("auto"),h.includes("hosting you for")?(a=V.extractNumber(h),this.emit("hosted",m,c,a,u)):h.includes("hosting you")&&this.emit("hosted",m,c,0,u)):(a=V.get(this.opts.options.messagesLogLevel,"info"),c=V.actionMessage(h),t.tags["message-type"]=c?"action":"chat",h=c?c[1]:h,V.hasOwn(t.tags,"bits")?this.emit("cheer",m,t.tags,h):(V.hasOwn(t.tags,"msg-id")?"highlighted-message"===t.tags["msg-id"]?(u=t.tags["msg-id"],this.emit("redeem",m,t.tags.username,u,t.tags,h)):"skip-subs-mode-message"===t.tags["msg-id"]&&(l=t.tags["msg-id"],this.emit("redeem",m,t.tags.username,l,t.tags,h)):V.hasOwn(t.tags,"custom-reward-id")&&(l=t.tags["custom-reward-id"],this.emit("redeem",m,t.tags.username,l,t.tags,h)),c?(this.log[a]("[".concat(m,"] *<").concat(t.tags.username,">: ").concat(h)),this.emits(["action","message"],[[m,t.tags,h,!1]])):(this.log[a]("[".concat(m,"] <").concat(t.tags.username,">: ").concat(h)),this.emits(["chat","message"],[[m,t.tags,h,!1]]))));break;default:this.log.warn("Could not parse message:\n".concat(JSON.stringify(t,null,4)))}}},n.prototype.connect=function(){var s=this;return new Promise(function(t,n){s.server=V.get(s.opts.connection.server,"irc-ws.chat.twitch.tv"),s.port=V.get(s.opts.connection.port,80),s.secure&&(s.port=443),443===s.port&&(s.secure=!0),s.reconnectTimer=s.reconnectTimer*s.reconnectDecay,s.reconnectTimer>=s.maxReconnectInterval&&(s.reconnectTimer=s.maxReconnectInterval),s._openConnection(),s.once("_promiseConnect",function(e){e?n(e):t([s.server,~~s.port])})})},n.prototype._openConnection=function(){var e="".concat(this.secure?"wss":"ws","://").concat(this.server,":").concat(this.port,"/"),t={};"agent"in this.opts.connection&&(t.agent=this.opts.connection.agent),this.ws=new r(e,"irc",t),this.ws.onmessage=this._onMessage.bind(this),this.ws.onerror=this._onError.bind(this),this.ws.onclose=this._onClose.bind(this),this.ws.onopen=this._onOpen.bind(this)},n.prototype._onOpen=function(){var n=this;this._isConnected()&&(this.log.info("Connecting to ".concat(this.server," on port ").concat(this.port,"..")),this.emit("connecting",this.server,~~this.port),this.username=V.get(this.opts.identity.username,V.justinfan()),this._getToken().then(function(e){var t=V.password(e);n.log.info("Sending authentication to server.."),n.emit("logon");e="twitch.tv/tags twitch.tv/commands";n._skipMembership||(e+=" twitch.tv/membership"),n.ws.send("CAP REQ :"+e),t?n.ws.send("PASS ".concat(t)):V.isJustinfan(n.username)&&n.ws.send("PASS SCHMOOPIIE"),n.ws.send("NICK ".concat(n.username))}).catch(function(e){n.emits(["_promiseConnect","disconnected"],[[e],["Could not get a token."]])}))},n.prototype._getToken=function(){var e,t=this.opts.identity.password;return"function"==typeof t?(e=t())instanceof Promise?e:Promise.resolve(e):Promise.resolve(t)},n.prototype._onMessage=function(e){var t=this;e.data.trim().split("\r\n").forEach(function(e){e=q.msg(e);e&&t.handleMessage(e)})},n.prototype._onError=function(){var t=this;this.moderators={},this.userstate={},this.globaluserstate={},clearInterval(this.pingLoop),clearTimeout(this.pingTimeout),clearTimeout(this._updateEmotesetsTimer),this.reason=null===this.ws?"Connection closed.":"Unable to connect.",this.emits(["_promiseConnect","disconnected"],[[this.reason]]),this.reconnect&&this.reconnections===this.maxReconnectAttempts&&(this.emit("maxreconnect"),this.log.error("Maximum reconnection attempts reached.")),this.reconnect&&!this.reconnecting&&this.reconnections<=this.maxReconnectAttempts-1&&(this.reconnecting=!0,this.reconnections=this.reconnections+1,this.log.error("Reconnecting in ".concat(Math.round(this.reconnectTimer/1e3)," seconds..")),this.emit("reconnect"),setTimeout(function(){t.reconnecting=!1,t.connect().catch(function(e){return t.log.error(e)})},this.reconnectTimer)),this.ws=null},n.prototype._onClose=function(){var t=this;this.moderators={},this.userstate={},this.globaluserstate={},clearInterval(this.pingLoop),clearTimeout(this.pingTimeout),clearTimeout(this._updateEmotesetsTimer),this.wasCloseCalled?(this.wasCloseCalled=!1,this.reason="Connection closed.",this.log.info(this.reason),this.emits(["_promiseConnect","_promiseDisconnect","disconnected"],[[this.reason],[null],[this.reason]])):(this.emits(["_promiseConnect","disconnected"],[[this.reason]]),this.reconnect&&this.reconnections===this.maxReconnectAttempts&&(this.emit("maxreconnect"),this.log.error("Maximum reconnection attempts reached.")),this.reconnect&&!this.reconnecting&&this.reconnections<=this.maxReconnectAttempts-1&&(this.reconnecting=!0,this.reconnections=this.reconnections+1,this.log.error("Could not connect to server. Reconnecting in ".concat(Math.round(this.reconnectTimer/1e3)," seconds..")),this.emit("reconnect"),setTimeout(function(){t.reconnecting=!1,t.connect().catch(function(e){return t.log.error(e)})},this.reconnectTimer))),this.ws=null},n.prototype._getPromiseDelay=function(){return this.currentLatency<=600?600:this.currentLatency+100},n.prototype._sendCommand=function(s,o,i,r){var a=this;return new Promise(function(e,t){if(!a._isConnected())return t("Not connected to server.");var n;null!==s&&"number"!=typeof s||(null===s&&(s=a._getPromiseDelay()),V.promiseDelay(s).then(function(){return t("No response from Twitch.")})),null!==o?(n=V.channel(o),a.log.info("[".concat(n,"] Executing command: ").concat(i)),a.ws.send("PRIVMSG ".concat(n," :").concat(i))):(a.log.info("Executing command: ".concat(i)),a.ws.send(i)),"function"==typeof r?r(e,t):e()})},n.prototype._sendMessage=function(c,u,l,m){var h=this;return new Promise(function(e,t){if(!h._isConnected())return t("Not connected to server.");if(V.isJustinfan(h.getUsername()))return t("Cannot send anonymous messages.");var n,s=V.channel(u);h.userstate[s]||(h.userstate[s]={}),500<=l.length&&(n=V.splitLine(l,500),l=n[0],setTimeout(function(){h._sendMessage(c,u,n[1],function(){})},350)),h.ws.send("PRIVMSG ".concat(s," :").concat(l));var o={};Object.keys(h.emotesets).forEach(function(e){return h.emotesets[e].forEach(function(e){return(V.isRegex(e.code)?q.emoteRegex:q.emoteString)(l,e.code,e.id,o)})});var i=Object.assign(h.userstate[s],q.emotes({emotes:q.transformEmotes(o)||null})),r=V.get(h.opts.options.messagesLogLevel,"info"),a=V.actionMessage(l);a?(i["message-type"]="action",h.log[r]("[".concat(s,"] *<").concat(h.getUsername(),">: ").concat(a[1])),h.emits(["action","message"],[[s,i,a[1],!0]])):(i["message-type"]="chat",h.log[r]("[".concat(s,"] <").concat(h.getUsername(),">: ").concat(l)),h.emits(["chat","message"],[[s,i,l,!0]])),"function"==typeof m?m(e,t):e()})},n.prototype._updateEmoteset=function(s){var t,o=this,e=void 0!==s;e&&(s===this.emotes?e=!1:this.emotes=s),this._skipUpdatingEmotesets?e&&this.emit("emotesets",s,{}):(t=function(){0n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},o.prototype.once=function(e,t){if(!c(t))throw TypeError("listener must be a function");var n=!1;if(this._events.hasOwnProperty(e)&&"_"===e.charAt(0)){var s,o=1,i=e;for(s in this._events)this._events.hasOwnProperty(s)&&s.startsWith(i)&&o++;e+=o}function r(){"_"!==e.charAt(0)||isNaN(e.substr(e.length-1))||(e=e.substring(0,e.length-1)),this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},o.prototype.removeListener=function(e,t){var n,s,o,i;if(!c(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(o=(n=this._events[e]).length,s=-1,n===t||c(n.listener)&&n.listener===t){if(delete this._events[e],this._events.hasOwnProperty(e+"2")&&"_"===e.charAt(0)){var r,a=e;for(r in this._events)this._events.hasOwnProperty(r)&&r.startsWith(a)&&(isNaN(parseInt(r.substr(r.length-1)))||(this._events[e+parseInt(r.substr(r.length-1)-1)]=this._events[r],delete this._events[r]));this._events[e]=this._events[e+"1"],delete this._events[e+"1"]}this._events.removeListener&&this.emit("removeListener",e,t)}else if(u(n)){for(i=o;0n?(t.command=e.slice(n),t):null;for(t.command=e.slice(n,s),n=s+1;32===e.charCodeAt(n);)n++;for(;n").replace(/\\"\\;/g,'"').replace(/\\'\\;/g,"'")},unescapeIRC:function(e){return e&&"string"==typeof e&&e.includes("\\")?e.replace(i,function(e,t){return t in a?a[t]:t}):e},escapeIRC:function(e){return e&&"string"==typeof e?e.replace(r,function(e,t){return t in c?"\\".concat(c[t]):t}):e},addWord:function(e,t){return e.length?e+" "+t:e+t},splitLine:function(e,t){var n=e.substring(0,t).lastIndexOf(" ");return[e.substring(0,n=-1===n?t-1:n),e.substring(n+1)]},extractNumber:function(e){for(var t=e.split(" "),n=0;n { label, title, tags: [string], message } +function describe(log) { + const raw = parse(log.data_json); + const replay = parse(log.replay_json); + const a = replay?.type === 'alert' ? replay.alert : null; + const t = log.event_type; + const out = { label: LABEL[t] || t, title: null, tags: [], message: null }; + + if (REDEEM_KIND[t]) { + out.title = rewardTitle(t, raw, a) || log.event_detail; + if (raw?.reward?.cost) out.tags.push(`${raw.reward.cost} points`); + else if (raw?.reward?.channel_points) out.tags.push(`${raw.reward.channel_points} points`); + else if (raw?.bits) out.tags.push(`${raw.bits} bits`); + else if (raw?.custom_power_up?.bits) out.tags.push(`${raw.custom_power_up.bits} bits`); + if (a) { + if (a.variation && a.variation !== a.reward) out.tags.push(`played: ${a.variation}`); + if (a.rarity && a.rarity !== 'common') out.tags.push(RARITY[a.rarity] || a.rarity); + if (a.tts) out.tags.push('TTS'); + if (a.video) out.tags.push('video'); + } + out.message = a?.input || raw?.user_input || raw?.message?.text || null; + } else if (a) { + switch (a.type) { + case 'sub': + out.title = a.prime ? 'Prime' : TIERS[a.tier] || a.tier; + if (a.months > 1) out.tags.push(`${a.months} months`); + if (a.duration > 1) out.tags.push(`${a.duration} months at once`); + out.message = a.message || null; break; + case 'gift': + out.title = a.total > 1 ? `${a.total} gift subs` : `gift to ${a.recipient || 'someone'}`; + if (TIERS[a.tier]) out.tags.push(TIERS[a.tier]); + if (!a.user) out.tags.push('anonymous'); break; + case 'bits': out.title = `${a.bits} bits`; out.message = a.message || null; break; + case 'streak': out.title = `${a.streak} streams in a row`; break; + case 'raid': out.title = `${a.viewers} viewers`; break; + case 'hype': + out.title = a.phase === 'begin' ? 'started' : a.phase === 'level' ? `level ${a.level}` : `ended at level ${a.level}`; + if (a.golden) out.tags.push('Golden Kappa'); if (a.treasure) out.tags.push('Treasure'); + if (a.top?.length) out.message = `top: ${a.top.join(', ')}`; break; + case 'tip': out.title = `${a.amount} ${a.currency}`; out.message = a.message || null; break; + } + } else if (t === 'raid_out') { + out.title = `to ${raw?.to_broadcaster_user_name || log.username || '?'}`; + if (raw?.viewers != null) out.tags.push(`${raw.viewers} viewers`); + } else if (t === 'poll_begin' || t === 'poll_end') { + out.title = raw?.title || null; + if (t === 'poll_end' && raw?.choices?.length) { + const sorted = [...raw.choices].sort((x, y) => (y.votes || 0) - (x.votes || 0)); + out.message = sorted.map(c => `${c.title}: ${c.votes ?? 0}`).join(' · '); + } + } else if (log.event_detail) { + out.title = log.event_detail; + } + if (t === 'raid_out' && replay?.raid) { + out.title = `to ${replay.raid.target}`; + out.tags = [`${replay.raid.viewers} viewers`]; + } + return out; +} + +// Can this row be replayed? (cheap check for the table; replay() does the real work) +function canReplay(log) { + if (log.replay_json) return true; + return !!log.data_json && (!!REDEEM_KIND[log.event_type] || log.event_type === 'raid_out'); +} + +const PUBLIC = path.join(__dirname, '..', 'public'); +const fileGone = url => !url || !fs.existsSync(path.join(PUBLIC, url.replace(/^\/+/, '').split('?')[0])); + +// -> the overlay message to broadcast, or null +async function replayMessage(log) { + const stored = parse(log.replay_json); + if (stored) { + if (stored.type === 'alert' && stored.alert.tts && fileGone(stored.alert.tts)) await require('./redeems').respeak(stored.alert); + return stored; + } + const raw = parse(log.data_json); + if (!raw) return null; + if (REDEEM_KIND[log.event_type]) { + const kind = REDEEM_KIND[log.event_type]; + const key = log.event_detail; + const input = raw.user_input || raw.message?.text || null; + const emote = raw.reward?.emote?.id || raw.power_up?.emote?.id || null; + const bits = raw.custom_power_up?.bits ?? null; + const alert = await require('./redeems').rebuild(kind, key, { user: raw.user_name || raw.user_login || log.username, input, emote, bits }); + return alert ? { type: 'alert', alert } : null; + } + if (log.event_type === 'raid_out') { + const raid = await require('./alerts').raidTarget(raw); + return { type: 'raid_card', phase: 'done', raid: { ...raid, viewers: raw.viewers } }; + } + return null; +} + +module.exports = { describe, canReplay, replayMessage }; diff --git a/src/alerts.js b/src/alerts.js new file mode 100644 index 0000000..fc062cd --- /dev/null +++ b/src/alerts.js @@ -0,0 +1,258 @@ +// Turns Twitch events into polaroid alerts and pushes them to the overlay. +// +// Alert shape (what public/alerts/polaroid.js renders): +// { type:'follow', user } +// { type:'sub', user, tier:'1000'|'2000'|'3000', prime, months, duration, message } +// { type:'gift', user|null (anonymous), total, recipient, tier } total>1 = community gift +// { type:'streak', user, streak } +// { type:'raid', user, viewers } +// { type:'bits', user|null (anonymous), bits, message } +// +// Every alert also goes through dispatch.dispatchEvent() so the existing actions system +// (sounds/videos per event) and the dashboard activity log keep working. +const ws = require('./ws'); +const dispatch = require('./dispatch'); + +// legacy action event types + detail, so existing action matching rules still apply +function legacy(alert) { + switch (alert.type) { + case 'sub': return ['sub', alert.tier]; + case 'gift': return ['gift_sub', alert.tier]; + case 'bits': return ['bits', String(alert.bits)]; + case 'streak': return ['watch_streak', String(alert.streak)]; + case 'hype': return ['hype_train', alert.phase]; + case 'tip': return ['tip', `${alert.amount} ${alert.currency}`]; + case 'redeem': return [{ reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up', custom_power_up: 'custom_power_up' }[alert.kind] || 'redeem', alert.key]; + default: return [alert.type || 'alert', null]; + } +} + +function send(alert, raw = null) { + if (!alert) return; + console.log(`[alerts] ${alert.type} — ${alert.user ?? 'anonymous'} ${JSON.stringify({ ...alert, type: undefined, user: undefined })}`); + const msg = { type: 'alert', alert }; + ws.broadcast(msg); + const [eventType, detail] = legacy(alert); + dispatch.dispatchEvent(eventType, detail, alert.user, raw || alert, msg); +} + +const text = m => (m && typeof m.text === 'string' && m.text.trim()) ? m.text.trim() : null; + +// --- EventSub mappers --- + +function fromFollow(e) { + return { type: 'follow', user: e.user_name || e.user_login }; +} + +function fromCheer(e) { + return { type: 'bits', user: e.is_anonymous ? null : (e.user_name || e.user_login), bits: e.bits, message: e.message || null }; +} + +// channel.bits.use with type 'cheer' (Power-ups are handled by redeems.js) +function fromBitsUse(e) { + return { type: 'bits', user: e.user_name || e.user_login || null, bits: e.bits, message: text(e.message) }; +} + +// channel.chat.notification: one event type that carries all sub/gift/raid details +// (Prime flag, months bought at once, gift recipient, resub message, community gift totals). +function fromChatNotification(e) { + const user = e.chatter_is_anonymous ? null : (e.chatter_user_name || e.chatter_user_login); + switch (e.notice_type) { + case 'sub': + return { type: 'sub', user, tier: e.sub.sub_tier, prime: !!e.sub.is_prime, months: 1, + duration: e.sub.duration_months || 1, message: text(e.message) }; + case 'resub': + return { type: 'sub', user, tier: e.resub.sub_tier, prime: !!e.resub.is_prime, + months: e.resub.cumulative_months || 1, duration: e.resub.duration_months || 1, message: text(e.message) }; + case 'gift_paid_upgrade': + case 'prime_paid_upgrade': + // gifted/Prime sub continued as a paid sub: show as a sub + return { type: 'sub', user, tier: e.prime_paid_upgrade?.sub_tier || '1000', prime: false, months: 1, duration: 1, message: null }; + case 'sub_gift': + // part of a community gift: the community_sub_gift notice already covers it (no alert per recipient) + if (e.sub_gift.community_gift_id) return null; + return { type: 'gift', user, total: 1, recipient: e.sub_gift.recipient_user_name, tier: e.sub_gift.sub_tier }; + case 'community_sub_gift': + return { type: 'gift', user, total: e.community_sub_gift.total, tier: e.community_sub_gift.sub_tier }; + case 'raid': + return { type: 'raid', user: e.raid.user_name || e.raid.user_login, viewers: e.raid.viewer_count }; + default: + return null; // announcements, pay-it-forward, bits badge tiers, ...: no alert + } +} + +// --- StreamElements tip (Astro channel.tips message data) --- +function fromTip(d) { + const t = d.donation || {}; + return { type: 'tip', user: t.user?.username || 'Someone', amount: Number(t.amount) || 0, currency: t.currency || 'USD', + message: (t.message || '').trim() || null }; +} + +// --- Hype Train (v2): alert on start, on each NEW level, and at the end --- +const hypeLevels = new Map(); // train id -> last announced level +function fromHypeTrain(phase, e) { + const base = { type: 'hype', golden: e.type === 'golden_kappa', treasure: e.type === 'treasure', shared: !!e.is_shared_train, level: e.level }; + if (phase === 'begin') { + hypeLevels.set(e.id, e.level); + return { ...base, phase: 'begin' }; + } + if (phase === 'progress') { + if ((hypeLevels.get(e.id) || 0) >= e.level) return null; // every contribution sends progress: only level-ups alert + hypeLevels.set(e.id, e.level); + return { ...base, phase: 'level' }; + } + hypeLevels.delete(e.id); + const top = (e.top_contributions || []).map(c => c.user_name || c.user_login).filter(Boolean); + return { ...base, phase: 'end', top: [...new Set(top)].slice(0, 3) }; +} + +// --- Hype Train progress bar (persistent while the train runs, outside the queue) --- +function sendHypeBar(phase, e) { + ws.broadcast({ type: 'hype_bar', phase, train: { + id: e.id, level: e.level, progress: e.progress ?? null, goal: e.goal ?? null, total: e.total, + expires_at: e.expires_at || null, golden: e.type === 'golden_kappa', treasure: e.type === 'treasure' } }); +} + +// --- outgoing raid send-off card (persistent, silent, outside the queue) --- +// Twitch has no "raid started" event: the card appears when the raid is started from the dashboard +// (routers/alerts.js -> Helix POST /raids) and stays until channel.raid reports the raid happened. +let pendingRaid = null; // { target, avatar, viewers, started_at } +function raidCard(phase, raid) { ws.broadcast({ type: 'raid_card', phase, raid }); } +function raidStarted(raid) { pendingRaid = { ...raid, started_at: new Date().toISOString() }; raidCard('start', pendingRaid); } +function raidCancelled() { if (pendingRaid) raidCard('cancel', pendingRaid); pendingRaid = null; } +function getPendingRaid() { return pendingRaid; } +// channel.raid from us: the raid happened (started from the dashboard or straight on Twitch) +async function raidTarget(e) { + let avatar = null; + try { + const res = await require('./twitch').helix(`/users?id=${encodeURIComponent(e.to_broadcaster_user_id)}`); + if (res.ok) avatar = (await res.json()).data?.[0]?.profile_image_url || null; + } catch { /* fallback art */ } + return { target: e.to_broadcaster_user_name || e.to_broadcaster_user_login, avatar }; +} +async function raidHappened(e) { + const raid = pendingRaid || await raidTarget(e); // started on Twitch directly: show the card briefly + const msg = { type: 'raid_card', phase: 'done', raid: { ...raid, viewers: e.viewers } }; + ws.broadcast(msg); + pendingRaid = null; + console.log(`[alerts] raid out — ${msg.raid.target} with ${e.viewers}`); + dispatch.dispatchEvent('raid_out', String(e.viewers), e.to_broadcaster_user_name, e, msg); +} + +// --- polls: a live card on the overlay, outside the alert queue --- +function pollShape(phase, e) { + return { + id: e.id, title: e.title, status: e.status || null, ends_at: e.ends_at || null, + choices: (e.choices || []).map(c => ({ id: c.id, title: c.title, votes: c.votes || 0 })), + }; +} +function sendPoll(phase, e) { + ws.broadcast({ type: 'poll', phase, poll: pollShape(phase, e) }); + if (phase !== 'progress') { + const detail = phase === 'end' ? e.status : null; + dispatch.dispatchEvent(`poll_${phase}`, detail, null, e); // activity log (begin + end only) + } +} + +// --- watch streaks, reported by the overlay (they only exist as a chat USERNOTICE) --- +const seenNotices = new Map(); // message id -> time; several overlays may report the same notice +function fromOverlayNotice(n) { + if (n.kind !== 'watch_streak') return null; + const streak = parseInt(n.streak, 10); + if (!n.id || !n.user || !(streak > 0)) return null; + const now = Date.now(); + for (const [id, t] of seenNotices) if (now - t > 10 * 60 * 1000) seenNotices.delete(id); + if (seenNotices.has(n.id)) return null; + seenNotices.set(n.id, now); + return { type: 'streak', user: String(n.user).slice(0, 40), streak }; +} + +// --- test alerts (dashboard buttons) --- +const SAMPLES = { + 'follow': { type: 'follow', user: 'ChickenWhisperer' }, + 'sub-new': { type: 'sub', user: 'PixelPotato', tier: '1000', prime: false, months: 1, duration: 1 }, + 'sub-prime': { type: 'sub', user: 'LurkingLynx', tier: '1000', prime: true, months: 1, duration: 1 }, + 'sub-resub': { type: 'sub', user: 'ChickenWhisperer', tier: '1000', prime: false, months: 14, duration: 1, message: 'still here for the chickens and the chaos' }, + 'sub-3': { type: 'sub', user: 'BobTheBuilder99', tier: '1000', prime: false, months: 3, duration: 3 }, + 'sub-6': { type: 'sub', user: 'xX_Lurker_Xx', tier: '1000', prime: false, months: 6, duration: 6 }, + 'gift-1': { type: 'gift', user: 'PixelPotato', total: 1, recipient: 'ChickenWhisperer', tier: '1000' }, + 'gift-10': { type: 'gift', user: 'BobTheBuilder99', total: 10, tier: '1000' }, + 'gift-anon': { type: 'gift', user: null, total: 5, tier: '1000' }, + 'streak': { type: 'streak', user: 'LurkingLynx', streak: 5 }, + 'raid': { type: 'raid', user: 'CozyStreamer', viewers: 42 }, + 'bits-3': { type: 'bits', user: 'PixelPotato', bits: 3 }, + 'bits-20': { type: 'bits', user: 'PixelPotato', bits: 20 }, + 'bits-60': { type: 'bits', user: 'ChickenWhisperer', bits: 60 }, + 'bits-80': { type: 'bits', user: 'BobTheBuilder99', bits: 80, message: 'we do a little trolling' }, + 'bits-120': { type: 'bits', user: 'LurkingLynx', bits: 120 }, + 'bits-200': { type: 'bits', user: 'xX_Lurker_Xx', bits: 200, message: 'RUN' }, + 'bits-500': { type: 'bits', user: 'BobTheBuilder99', bits: 500, message: 'Tom da Tank says hi' }, + 'hype-begin':{ type: 'hype', phase: 'begin', level: 1, golden: false }, + 'hype-level':{ type: 'hype', phase: 'level', level: 3, golden: false }, + 'hype-end': { type: 'hype', phase: 'end', level: 4, golden: false, top: ['ChickenWhisperer', 'PixelPotato', 'LurkingLynx'] }, + 'hype-golden':{ type: 'hype', phase: 'begin', level: 1, golden: true }, + 'tip-5': { type: 'tip', user: 'PixelPotato', amount: 5, currency: 'EUR', message: 'for the hydration fund' }, + 'tip-25': { type: 'tip', user: 'ChickenWhisperer', amount: 25, currency: 'EUR', message: 'great stream today, have a coffee on me ♡' }, + 'tip-100': { type: 'tip', user: 'BobTheBuilder99', amount: 100, currency: 'USD', message: null }, +}; + +const TEST_KEYS = [...Object.keys(SAMPLES), 'queue-test', 'poll-test', 'hype-bar-test', 'raid-card-test']; + +// fake Hype Train bar: starts at level 1, fills up, levels up twice, ends +let hypeTimers = []; +function testHypeBar() { + hypeTimers.forEach(clearTimeout); hypeTimers = []; + const t = { id: 'test-' + Date.now(), level: 1, progress: 0, goal: 1000, total: 0, type: 'regular' }; + const send = phase => sendHypeBar(phase, { ...t, expires_at: new Date(Date.now() + 300000).toISOString() }); + send('begin'); + for (let i = 1; i <= 12; i++) hypeTimers.push(setTimeout(() => { + t.progress += 300; t.total += 300; + if (t.progress >= t.goal) { t.progress -= t.goal; t.level++; t.goal += 500; } + send('progress'); + }, i * 800)); + hypeTimers.push(setTimeout(() => send('end'), 11000)); +} + +// fake poll: begins, votes come in over ~9 s, then it ends with a winner +let pollTimers = []; +function testPoll() { + pollTimers.forEach(clearTimeout); pollTimers = []; + const ends = new Date(Date.now() + 10000).toISOString(); + const poll = { id: 'test-' + Date.now(), title: 'Which map next?', ends_at: ends, status: null, + choices: [{ id: 'a', title: 'Customs', votes: 0 }, { id: 'b', title: 'Woods', votes: 0 }, { id: 'c', title: 'Reserve', votes: 0 }, { id: 'd', title: 'Factory (chaos)', votes: 0 }] }; + const send = phase => ws.broadcast({ type: 'poll', phase, poll: JSON.parse(JSON.stringify(poll)) }); + send('begin'); + for (let i = 1; i <= 8; i++) pollTimers.push(setTimeout(() => { + poll.choices.forEach((c, k) => { c.votes += Math.floor(Math.random() * (k === 2 ? 6 : 4)); }); + send('progress'); + }, i * 1000)); + pollTimers.push(setTimeout(() => { poll.status = 'completed'; send('end'); }, 10000)); +} + +function sendTestAlert(alert) { + ws.broadcast({ type: 'alert', alert: { ...alert, test: true } }); +} + +// Test alerts go straight to the overlay; they are not logged and do not fire actions. +// test:true replaces another test alert at once (fast checking) but never cuts off a real alert; +// 'queue-test' sends four alerts that queue like real ones. +function sendTest(key) { + if (key === 'poll-test') { testPoll(); return true; } + if (key === 'hype-bar-test') { testHypeBar(); return true; } + if (key === 'raid-card-test') { // countdown card, then "raid sent" after 12 s + raidCard('start', { target: 'CozyStreamer', avatar: null, viewers: 42, started_at: new Date().toISOString() }); + setTimeout(() => raidCard('done', { target: 'CozyStreamer', avatar: null, viewers: 42 }), 12000); + return true; + } + if (key === 'queue-test') { + ws.broadcast({ type: 'alert', alert: { ...SAMPLES['follow'], test: true } }); + for (const k of ['bits-60', 'gift-10', 'streak']) ws.broadcast({ type: 'alert', alert: { ...SAMPLES[k], test: 'queue' } }); + return true; + } + const alert = SAMPLES[key]; + if (!alert) return false; + ws.broadcast({ type: 'alert', alert: { ...alert, test: true } }); + return true; +} + +module.exports = { raidTarget, send, sendTest, sendTestAlert, sendPoll, sendHypeBar, raidStarted, raidCancelled, raidHappened, getPendingRaid, fromHypeTrain, fromTip, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromBitsUse, fromChatNotification, fromOverlayNotice }; diff --git a/src/app.js b/src/app.js index 73b2691..871bb2f 100644 --- a/src/app.js +++ b/src/app.js @@ -22,7 +22,8 @@ app.use((req, res, next) => { next(); }); -app.use(express.static(path.join(__dirname, '../public'))); +// redirect:false: /media (the uploads folder) must not bounce to /media/ before the Media page route +app.use(express.static(path.join(__dirname, '../public'), { redirect: false })); app.use(express.urlencoded({ extended: true })); app.use(express.json()); @@ -47,12 +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('/actions', requireAuth, require('./routers/actions')); -app.use('/media', requireAuth, require('./routers/media')); -app.use('/layout', requireAuth, require('./routers/layout')); -app.use('/settings', requireAuth, require('./routers/settings')); -app.use('/', requireAuth, require('./routers/dashboard')); +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 +// sections with a left sidebar (src/nav.js): Actions = Redeems / Alerts / TTS voices / Media, and Settings +const { section } = require('./nav'); +app.get('/actions', requireAuth, (req, res) => res.redirect('/redeems')); +app.use('/actions/alerts', requireAuth, section('actions'), require('./routers/alertsetup')); +app.use('/redeems', requireAuth, section('actions'), require('./routers/redeems')); +app.use('/tts', requireAuth, section('actions'), require('./routers/tts')); +app.use('/media', requireAuth, section('actions'), require('./routers/media')); +app.use('/settings', requireAuth, section('settings'), require('./routers/settings')); +app.use('/stats', requireAuth, (req, res, next) => { res.locals.navActive = 'stats'; next(); }, require('./routers/stats')); +app.use('/alerts', requireAuth, require('./routers/alerts')); // test / skip / raid (POST) +app.use('/', requireAuth, (req, res, next) => { res.locals.navActive = 'dashboard'; next(); }, require('./routers/dashboard')); module.exports = app; diff --git a/src/backup.js b/src/backup.js new file mode 100644 index 0000000..39fc19e --- /dev/null +++ b/src/backup.js @@ -0,0 +1,44 @@ +// Settings → Backup: the whole setup as one JSON file (settings, alert theme, redeem variations, TTS voices). +// Not included: media files, statistics, secrets (Twitch tokens live in users; se_jwt is left out). +const db = require('./db'); + +const VERSION = 1; +const SKIP_SETTINGS = ['id', 'overlay_id', 'se_jwt', 'tts_blocklist_seeded']; + +function exportAll() { + const d = db.raw(); + const settings = { ...db.getSettings() }; + for (const k of SKIP_SETTINGS) delete settings[k]; + return { + heystreamer_backup: VERSION, exported_at: new Date().toISOString(), + settings, + variations: d.prepare('SELECT * FROM reward_variations ORDER BY id').all().map(({ id, created_at, ...v }) => v), + tts_voices: d.prepare('SELECT id, name, config FROM tts_voices ORDER BY id').all(), + }; +} + +// replaces settings (known columns only), variations and TTS voices; keeps statistics, users, media rows +function importAll(data) { + if (!data || data.heystreamer_backup !== VERSION) throw new Error('not a HeyStreamer backup file'); + const d = db.raw(); + const cols = new Set(d.prepare('PRAGMA table_info(settings)').all().map(c => c.name)); + const vcols = new Set(d.prepare('PRAGMA table_info(reward_variations)').all().map(c => c.name)); + const settings = Object.fromEntries(Object.entries(data.settings || {}).filter(([k]) => cols.has(k) && !SKIP_SETTINGS.includes(k))); + d.transaction(() => { + if (Object.keys(settings).length) db.updateSettings(settings); + // TTS voices keep their ids, so variations still point at the right voice + d.prepare('DELETE FROM tts_voices').run(); + const tv = d.prepare('INSERT INTO tts_voices (id, name, config) VALUES (?, ?, ?)'); + for (const v of data.tts_voices || []) tv.run(v.id, String(v.name || 'voice'), typeof v.config === 'string' ? v.config : JSON.stringify(v.config || {})); + d.prepare('DELETE FROM reward_variations').run(); + for (const v of data.variations || []) { + const row = Object.fromEntries(Object.entries(v).filter(([k]) => vcols.has(k) && k !== 'id')); + const keys = Object.keys(row); + if (!keys.length) continue; + d.prepare(`INSERT INTO reward_variations (${keys.join(', ')}) VALUES (${keys.map(k => '@' + k).join(', ')})`).run(row); + } + })(); + return { settings: Object.keys(settings).length, variations: (data.variations || []).length, voices: (data.tts_voices || []).length }; +} + +module.exports = { exportAll, importAll }; diff --git a/src/chatlog.js b/src/chatlog.js new file mode 100644 index 0000000..e302dd4 --- /dev/null +++ b/src/chatlog.js @@ -0,0 +1,225 @@ +// Chat statistics. Every chat message (EventSub channel.chat.message, read on the server) is counted right away +// into per-viewer totals; the raw message is only a 30-day buffer. +// +// chat_user per viewer: messages, first/last seen +// chat_user_day per viewer per day: messages (activity over time) +// chat_emote per viewer per emote: uses (Twitch emotes from the message, 7TV channel + global by name) +// chat_command per viewer per !command: uses, last used +// chat_raw the messages themselves, deleted after RAW_DAYS +// chat_action per viewer per action + item: uses, total spent (points / bits / subs / viewers / tip money), +// from every event that goes through dispatch.js (rewards, Power-ups, cheers, subs, gifts, +// follows, raids, watch streaks, tips). Keyed by Twitch user id, or 'name:' when the +// event has none (StreamElements tips, watch streaks). +// These are lifetime totals (points and levels come from them). The same events also go to periodstats.js per day +// and per stream, for the stream / week / month / year views. !hideme / !showme toggle the public-page opt-out. +// +// Moderation: a deleted message, a timeout/ban (clear_user_messages) or a chat clear removes the stored text at +// once (Twitch developer rules); the counts stay, they hold no message content. +// Accounts in Settings → Hidden chatters (bots) ARE counted, but statistics pages / leaderboards must leave them +// out when showing data: use isHidden(login) / hiddenUsers() there (changing the list then applies at once). +const db = require('./db'); + +const RAW_DAYS = 30; +const SCORE_GAP_MS = 5 * 60 * 1000; // point system: a message earns points only 5 min after the viewer's last one that did +let ready = false; + +function init() { + if (ready) return; + db.raw().exec(` + CREATE TABLE IF NOT EXISTS chat_raw ( + id TEXT PRIMARY KEY, -- Twitch message id + at TEXT NOT NULL, -- ISO time + user_id TEXT NOT NULL, user_login TEXT, user_name TEXT, + text TEXT, emotes TEXT, -- emotes: JSON [name, ...] as counted + command TEXT, + first_msg INTEGER DEFAULT 0 + ); + CREATE INDEX IF NOT EXISTS chat_raw_at ON chat_raw(at); + CREATE INDEX IF NOT EXISTS chat_raw_user ON chat_raw(user_id); + CREATE TABLE IF NOT EXISTS chat_user ( + user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, + messages INTEGER DEFAULT 0, first_seen TEXT, last_seen TEXT + ); + CREATE TABLE IF NOT EXISTS chat_user_day ( + user_id TEXT NOT NULL, day TEXT NOT NULL, messages INTEGER DEFAULT 0, + PRIMARY KEY (user_id, day) + ); + CREATE TABLE IF NOT EXISTS chat_emote ( + user_id TEXT NOT NULL, emote TEXT NOT NULL, -- emote name as typed + source TEXT, emote_id TEXT, uses INTEGER DEFAULT 0, last_used TEXT, + PRIMARY KEY (user_id, emote) + ); + CREATE TABLE IF NOT EXISTS chat_action ( + user_key TEXT NOT NULL, -- Twitch user id, or 'name:' + user_login TEXT, user_name TEXT, + action TEXT NOT NULL, -- channel_points, custom_power_up, bits, sub, gift_sub, follow, raid, tip, ... + item TEXT NOT NULL DEFAULT '', -- reward / Power-up title, sub tier, ... + uses INTEGER DEFAULT 0, amount REAL DEFAULT 0, unit TEXT, + 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) + ); + `); + // point-system columns (added after the first version): points-eligible messages, first-ever-message flag + const cols = db.raw().prepare('PRAGMA table_info(chat_user)').all().map(c => c.name); + for (const [c, def] of [['scored', 'INTEGER DEFAULT 0'], ['last_scored', 'TEXT'], ['intro', 'INTEGER DEFAULT 0']]) { + if (!cols.includes(c)) db.raw().exec(`ALTER TABLE chat_user ADD COLUMN ${c} ${def}`); + } + const dcols = db.raw().prepare('PRAGMA table_info(chat_user_day)').all().map(c => c.name); + if (!dcols.includes('scored')) db.raw().exec('ALTER TABLE chat_user_day ADD COLUMN scored INTEGER DEFAULT 0'); + ready = true; + setInterval(prune, 60 * 60 * 1000).unref(); + prune(); +} + +// --- 7TV emotes (channel set + global), refreshed every hour; Twitch emotes come marked in the message --- +let seventv = new Map(), seventvAt = 0; +async function load7tv(twitchId) { + if (Date.now() - seventvAt < 60 * 60 * 1000) return; + seventvAt = Date.now(); + const next = new Map(); + const add = set => { for (const e of set?.emotes || []) next.set(e.name, e.id); }; + try { const r = await fetch('https://7tv.io/v3/emote-sets/global'); if (r.ok) add(await r.json()); } catch {} + try { const r = await fetch(`https://7tv.io/v3/users/twitch/${encodeURIComponent(twitchId)}`); if (r.ok) add((await r.json()).emote_set); } catch {} + if (next.size) seventv = next; +} + +// Settings → Hidden chatters: counted, but left out of shown statistics and leaderboards +function hiddenUsers() { + return String(db.getSettings().chat_hidden_users || '').toLowerCase().split(/[\s,]+/).filter(Boolean); +} +const isHidden = login => hiddenUsers().includes(String(login || '').toLowerCase()); + +// one chat message: count it, keep the raw copy +function onMessage(e) { + init(); + if (e.broadcaster_user_id) load7tv(e.broadcaster_user_id).catch(() => {}); + const login = String(e.chatter_user_login || '').toLowerCase(); + if (!e.chatter_user_id) return; + const text = String(e.message?.text || ''); + const at = new Date().toISOString(), day = at.slice(0, 10); + + // emotes: Twitch ones are marked by Twitch; any other word that is a 7TV emote counts too + const emotes = []; + for (const f of e.message?.fragments || []) { + if (f.type === 'emote') emotes.push({ name: f.text, source: 'twitch', id: f.emote?.id || null }); + else if (f.type === 'text') for (const w of f.text.split(/\s+/)) if (w && seventv.has(w)) emotes.push({ name: w, source: '7tv', id: seventv.get(w) }); + } + const m = /^\s*!(\w[\w-]{0,30})/.exec(text); + const command = m ? '!' + m[1].toLowerCase() : null; + + const d = db.raw(); + d.transaction(() => { + d.prepare(`INSERT OR IGNORE INTO chat_raw (id, at, user_id, user_login, user_name, text, emotes, command, first_msg) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`) + .run(e.message_id, at, e.chatter_user_id, login, e.chatter_user_name || login, text, + JSON.stringify(emotes.map(x => x.name)), command, e.message_type === 'user_intro' ? 1 : 0); + d.prepare(`INSERT INTO chat_user (user_id, user_login, user_name, messages, first_seen, last_seen) VALUES (?, ?, ?, 1, ?, ?) + ON CONFLICT(user_id) DO UPDATE SET messages = messages + 1, user_login = excluded.user_login, + user_name = excluded.user_name, last_seen = excluded.last_seen`) + .run(e.chatter_user_id, login, e.chatter_user_name || login, at, at); + // points-eligible: at least SCORE_GAP_MS since this viewer's last eligible message + const prev = d.prepare('SELECT last_scored FROM chat_user WHERE user_id = ?').get(e.chatter_user_id); + const scored = !prev?.last_scored || Date.parse(at) - Date.parse(prev.last_scored) >= SCORE_GAP_MS ? 1 : 0; + 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, ?) + ON CONFLICT(user_id, emote) DO UPDATE SET uses = uses + 1, last_used = excluded.last_used`); + for (const x of emotes) em.run(e.chatter_user_id, x.name, x.source, x.id, at); + 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'); + })(); +} + +// --- viewer actions (called by dispatch.js for every logged event) --- +const TIER = { 1000: 'Tier 1', 2000: 'Tier 2', 3000: 'Tier 3' }; +function actionOf(eventType, detail, data, a) { + const { AUTO_REWARDS, POWER_UPS } = require('./redeems'); + const d = data || {}; + switch (eventType) { + case 'channel_points': return { item: d.reward?.title || detail, amount: d.reward?.cost, unit: 'points' }; + case 'auto_reward': return { item: AUTO_REWARDS[d.reward?.type] || d.reward?.type || detail, amount: d.reward?.channel_points, unit: 'points' }; + case 'power_up': return { item: POWER_UPS[d.power_up?.type] || d.power_up?.type || detail, amount: d.bits, unit: 'bits' }; + case 'custom_power_up': return { item: d.custom_power_up?.title || detail, amount: d.custom_power_up?.bits, unit: 'bits' }; + case 'bits': return { item: 'cheer', amount: d.bits ?? a?.bits, unit: 'bits' }; + case 'sub': return { item: a?.prime ? 'Prime' : TIER[a?.tier] || 'sub', amount: a?.duration || 1, unit: 'months' }; + case 'gift_sub': return { item: TIER[a?.tier] || 'gift subs', amount: a?.total || 1, unit: 'subs' }; + case 'follow': return { item: 'follow', amount: 0, unit: null }; + case 'raid': return { item: 'raid', amount: a?.viewers, unit: 'viewers' }; + case 'watch_streak': return { item: 'watch streak', amount: a?.streak, unit: 'streak', max: true }; + case 'tip': return { item: 'tip', amount: a?.amount, unit: a?.currency || null }; + default: return null; // polls, hype train, raid out, legacy commands: no single viewer + } +} +function onAction(eventType, detail, username, data, replay) { + init(); + const a = replay?.type === 'alert' ? replay.alert : null; + const act = actionOf(eventType, detail, data, a); + if (!act) return; + const d = data || {}; + const id = d.user_id || d.chatter_user_id || null; + const login = String(d.user_login || d.chatter_user_login || username || a?.user || '').toLowerCase(); + if (!id && !login) return; // anonymous gifts / cheers + const key = id ? String(id) : `name:${login}`; + const amount = Number(act.amount) || 0, at = new Date().toISOString(); + db.raw().prepare(`INSERT INTO chat_action (user_key, user_login, user_name, action, item, uses, amount, unit, first_at, last_at) + VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?) + ON CONFLICT(user_key, action, item) DO UPDATE SET uses = uses + 1, + 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) +function onDelete(e) { init(); db.raw().prepare('DELETE FROM chat_raw WHERE id = ?').run(e.message_id); } +function onClearUser(e) { init(); db.raw().prepare('DELETE FROM chat_raw WHERE user_id = ?').run(e.target_user_id); } +function onClear() { init(); db.raw().prepare(`DELETE FROM chat_raw WHERE at >= ?`).run(new Date(Date.now() - 24 * 3600e3).toISOString()); } + +function prune() { + const cut = new Date(Date.now() - RAW_DAYS * 24 * 3600e3).toISOString(); + const n = db.raw().prepare('DELETE FROM chat_raw WHERE at < ?').run(cut).changes; + if (n) console.log(`[chatlog] pruned ${n} raw message(s) older than ${RAW_DAYS} days`); +} + +// removal request: forget a viewer completely (raw + counts) +function forgetUser(userIdOrLogin) { + init(); + const d = db.raw(); + 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', '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; +} + +module.exports = { init, onMessage, onAction, onDelete, onClearUser, onClear, prune, forgetUser, hiddenUsers, isHidden, RAW_DAYS }; diff --git a/src/db.js b/src/db.js index 46464d6..cc470e0 100644 --- a/src/db.js +++ b/src/db.js @@ -10,8 +10,10 @@ function init() { db.pragma('journal_mode = WAL'); db.pragma('foreign_keys = ON'); createSchema(); + migrate(); seedSettings(); - seedLayout(); + seedTtsBlocklist(); + seedVariations(); console.log(`[db] Initialised — path: ${DB_PATH}`); } @@ -43,6 +45,7 @@ function createSchema() { custom_js TEXT DEFAULT '' ); + -- unused since the layout editor was removed (2026-11-20); kept so old data is not lost CREATE TABLE IF NOT EXISTS overlay_layout ( id INTEGER PRIMARY KEY CHECK(id = 1), chat_left REAL DEFAULT 2.0, @@ -83,6 +86,32 @@ function createSchema() { created_at TEXT DEFAULT (datetime('now')) ); + -- Channel point rewards / built-in rewards / bits Power-ups: each trigger has variations, + -- one is picked at random weighted by rarity (like Twitch alert variations). + -- TTS voices built on the /tts page: config is JSON (layers + effects, see src/tts.js normalize()). + CREATE TABLE IF NOT EXISTS tts_voices ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + config TEXT NOT NULL, + created_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS reward_variations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, -- reward | auto_reward | power_up | custom_power_up + key TEXT NOT NULL, -- reward id / built-in reward type / power-up type + title TEXT NOT NULL, -- trigger name shown in the UI (last known) + name TEXT NOT NULL, -- variation name, shown on the polaroid + rarity TEXT NOT NULL DEFAULT 'common', + sound TEXT DEFAULT '', -- URL path under /public, '' = silent + volume REAL DEFAULT 0.8, + polaroid INTEGER DEFAULT 1, -- 0 = sound only + caption TEXT DEFAULT 'redeemed it! ♡', -- text after the viewer's name on the cassette strip + art TEXT DEFAULT '', -- file in /alerts/art, '' = default + enabled INTEGER DEFAULT 1, + created_at TEXT DEFAULT (datetime('now')) + ); + CREATE TABLE IF NOT EXISTS activity_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, event_type TEXT NOT NULL, @@ -95,6 +124,46 @@ function createSchema() { `); } +// columns added after the first deploy: ALTER only when missing, so existing databases keep their data +function addColumn(table, col, def) { + if (!db.prepare(`PRAGMA table_info(${table})`).all().some(c => c.name === col)) { + db.exec(`ALTER TABLE ${table} ADD COLUMN ${col} ${def}`); + console.log(`[db] Added ${table}.${col}`); + } +} + +function migrate() { + addColumn('reward_variations', 'tts_voice_id', 'INTEGER'); // tts_voices.id; NULL = no TTS + addColumn('settings', 'tts_max_chars', 'INTEGER DEFAULT 200'); // longer redeem text is cut + addColumn('settings', 'tts_blocklist', "TEXT DEFAULT ''"); // words/phrases, one per line or comma-separated + addColumn('settings', 'tts_say_name', 'INTEGER DEFAULT 1'); // " says: ..." before the message + 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 '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) +} + +// Put the starter TTS blocklist (src/tts-blocklist.txt) into the settings ONCE; after that it is the user's list +// (clearing or editing it in Settings is respected). +function seedTtsBlocklist() { + const s = db.prepare('SELECT tts_blocklist, tts_blocklist_seeded FROM settings WHERE id = 1').get(); + if (!s || s.tts_blocklist_seeded) return; + const starter = require('fs').readFileSync(require('path').join(__dirname, 'tts-blocklist.txt'), 'utf8') + .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')); + const mine = String(s.tts_blocklist || '').split(/[\n,]/).map(w => w.trim()).filter(Boolean); + const merged = [...mine, ...starter.filter(w => !mine.some(m => m.toLowerCase() === w.toLowerCase()))]; + db.prepare('UPDATE settings SET tts_blocklist = ?, tts_blocklist_seeded = 1 WHERE id = 1').run(merged.join('\n')); + console.log(`[db] TTS blocklist: added ${merged.length - mine.length} starter words`); +} + function seedSettings() { const row = db.prepare('SELECT id FROM settings WHERE id = 1').get(); if (!row) { @@ -104,12 +173,13 @@ function seedSettings() { } } -function seedLayout() { - const row = db.prepare('SELECT id FROM overlay_layout WHERE id = 1').get(); - if (!row) { - db.prepare('INSERT INTO overlay_layout (id) VALUES (1)').run(); - console.log('[db] Created default layout row'); - } +function seedVariations() { + if (db.prepare('SELECT COUNT(*) n FROM reward_variations').get().n > 0) return; + 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`); } // Users @@ -130,36 +200,31 @@ function getUserById(id) { return db.prepare('SELECT * FROM users WHERE id = ?').get(id); } +// The streamer account (single-user app for now): used to start EventSub on boot. +function getPrimaryUser() { + return db.prepare('SELECT * FROM users ORDER BY id LIMIT 1').get(); +} + +function updateUserTokens(id, access_token, refresh_token) { + db.prepare('UPDATE users SET access_token = ?, refresh_token = ? WHERE id = ?').run(access_token, refresh_token, id); +} + // Settings function getSettings() { return db.prepare('SELECT * FROM settings WHERE id = 1').get(); } +// 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, se_jwt, alert_theme, ...rest } = getSettings(); + return { ...rest, alert_theme: require('./theme').get() }; // the overlay gets the merged theme, never secrets +} + function updateSettings(fields) { const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', '); db.prepare(`UPDATE settings SET ${cols} WHERE id = 1`).run(fields); } -// Layout -function getLayout() { - return db.prepare('SELECT * FROM overlay_layout WHERE id = 1').get(); -} - -function updateLayout(fields) { - const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', '); - db.prepare(`UPDATE overlay_layout SET ${cols} WHERE id = 1`).run(fields); -} - -function updateLayoutPositions(fields) { - db.prepare(` - UPDATE overlay_layout SET - chat_left = @chat_left, chat_top = @chat_top, - chat_width = @chat_width, chat_height = @chat_height, - alert_left = @alert_left, alert_top = @alert_top - WHERE id = 1 - `).run(fields); -} - // Media function getAllMedia() { return db.prepare('SELECT * FROM media_files ORDER BY uploaded_at DESC').all(); @@ -223,12 +288,76 @@ function getMatchingActions(eventType, eventDetail) { }); } +// Redeem variations +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(); +} + +function getVariationsFor(kind, key) { + return db.prepare('SELECT * FROM reward_variations WHERE kind = ? AND key = ? ORDER BY id').all(kind, key); +} + +function getVariation(id) { + return db.prepare('SELECT * FROM reward_variations WHERE id = ?').get(id); +} + +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); +} + +function updateVariation(id, fields) { + const f = Object.fromEntries(Object.entries(fields).filter(([k]) => VARIATION_FIELDS.includes(k))); + if (!Object.keys(f).length) return; + const cols = Object.keys(f).map(k => `${k} = @${k}`).join(', '); + db.prepare(`UPDATE reward_variations SET ${cols} WHERE id = @id`).run({ ...f, id }); +} + +// keep the trigger name current when Twitch reports a renamed reward +function renameTrigger(kind, key, title) { + db.prepare('UPDATE reward_variations SET title = ? WHERE kind = ? AND key = ? AND title != ?').run(title, kind, key, title); +} + +function deleteVariation(id) { + db.prepare('DELETE FROM reward_variations WHERE id = ?').run(id); +} + +// TTS voices (config is stored as JSON text, returned parsed) +const ttsRow = r => r && { ...r, config: JSON.parse(r.config) }; + +function getAllTtsVoices() { + return db.prepare('SELECT * FROM tts_voices ORDER BY name COLLATE NOCASE, id').all().map(ttsRow); +} + +function getTtsVoice(id) { + return ttsRow(db.prepare('SELECT * FROM tts_voices WHERE id = ?').get(id)); +} + +function createTtsVoice(name, config) { + const r = db.prepare('INSERT INTO tts_voices (name, config) VALUES (?, ?)').run(name, JSON.stringify(config)); + return getTtsVoice(r.lastInsertRowid); +} + +function updateTtsVoice(id, name, config) { + db.prepare('UPDATE tts_voices SET name = ?, config = ? WHERE id = ?').run(name, JSON.stringify(config), id); +} + +function deleteTtsVoice(id) { + db.transaction(() => { + db.prepare('UPDATE reward_variations SET tts_voice_id = NULL WHERE tts_voice_id = ?').run(id); + db.prepare('DELETE FROM tts_voices WHERE id = ?').run(id); + })(); +} + // Activity log -function logActivity(eventType, eventDetail, username, data, actionsFired) { +function logActivity(eventType, eventDetail, username, data, actionsFired, replay = null) { db.prepare(` - INSERT INTO activity_log (event_type, event_detail, username, data_json, actions_fired) - VALUES (@event_type, @event_detail, @username, @data_json, @actions_fired) + INSERT INTO activity_log (event_type, event_detail, username, data_json, actions_fired, replay_json) + VALUES (@event_type, @event_detail, @username, @data_json, @actions_fired, @replay_json) `).run({ + replay_json: replay ? JSON.stringify(replay) : null, event_type: eventType, event_detail: eventDetail || null, username: username || null, @@ -238,15 +367,21 @@ function logActivity(eventType, eventDetail, username, data, actionsFired) { } function getActivityLog(limit = 50) { - return db.prepare('SELECT * FROM activity_log ORDER BY created_at DESC LIMIT ?').all(limit); + return db.prepare('SELECT * FROM activity_log ORDER BY created_at DESC, id DESC LIMIT ?').all(limit); +} + +function getActivity(id) { + return db.prepare('SELECT * FROM activity_log WHERE id = ?').get(id); } module.exports = { init, - upsertUser, getUserById, - getSettings, updateSettings, - getLayout, updateLayout, updateLayoutPositions, + upsertUser, getUserById, getPrimaryUser, updateUserTokens, + getSettings, getOverlaySettings, updateSettings, getAllMedia, getMediaFile, createMedia, deleteMedia, getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions, - logActivity, getActivityLog, + getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation, + getAllTtsVoices, getTtsVoice, createTtsVoice, updateTtsVoice, deleteTtsVoice, + logActivity, getActivityLog, getActivity, + raw: () => db, // for modules that keep their own tables (chatlog.js) }; diff --git a/src/dispatch.js b/src/dispatch.js index 3d3003a..4b3a223 100644 --- a/src/dispatch.js +++ b/src/dispatch.js @@ -2,7 +2,8 @@ const db = require('./db'); const ws = require('./ws'); const { isOnCooldown, setCooldown } = require('./cooldowns'); -function dispatchEvent(eventType, eventDetail = null, username = null, data = null) { +// replay: the overlay message that was shown for this event, stored so the dashboard can play it again +function dispatchEvent(eventType, eventDetail = null, username = null, data = null, replay = null) { const actions = db.getMatchingActions(eventType, eventDetail); let fired = 0; @@ -31,7 +32,12 @@ function dispatchEvent(eventType, eventDetail = null, username = null, data = nu console.log(`[dispatch] Fired action ${action.id} (${action.name}) — event: ${eventType}, user: ${username}`); } - db.logActivity(eventType, eventDetail, username, data, fired); + // the log must never take the server down (a bad row once crashed it mid-stream) + try { db.logActivity(eventType || 'unknown', eventDetail, username, data, fired, replay); } + catch (e) { console.error(`[dispatch] activity log failed (${eventType}):`, e.message); } + // per-viewer action statistics (chatlog.js) + try { require('./chatlog').onAction(eventType, eventDetail, username, data, replay); } + catch (e) { console.error(`[dispatch] action stats failed (${eventType}):`, e.message); } } module.exports = { dispatchEvent }; diff --git a/src/eventsub.js b/src/eventsub.js index faeae1c..5c50e94 100644 --- a/src/eventsub.js +++ b/src/eventsub.js @@ -1,118 +1,267 @@ +// Twitch EventSub over WebSocket. +// +// - start(user) is called on boot (stored login) and after OAuth login. +// - session_reconnect: connect to the given URL, subscriptions carry over, then close the old socket. +// - keepalive watchdog: if Twitch goes silent longer than keepalive_timeout_seconds, reconnect. +// - subscription requests refresh the token on 401 (see twitch.js). const { WebSocket } = require('ws'); -const dispatch = require('./dispatch'); +const twitch = require('./twitch'); +const alerts = require('./alerts'); +const redeems = require('./redeems'); +const chatlog = require('./chatlog'); +const watchtime = require('./watchtime'); const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws'; -const CLIENT_ID = process.env.TWITCH_CLIENT_ID; let ws = null; let shouldRun = false; -let sessionId = null; -let _accessToken = null; -let _broadcasterId = null; +let broadcasterId = null; +let keepaliveMs = 30_000; +let watchdog = null; +let reconnectTimer = null; +const status = { connected: false, sessionId: null, subscribed: [], failed: [], lastEventAt: null }; -function start(accessToken, broadcasterId) { - _accessToken = accessToken; - _broadcasterId = broadcasterId; +function start(user) { + twitch.setUser(user); + broadcasterId = user.twitch_id; shouldRun = true; - connect(); - console.log(`[eventsub] Starting — broadcaster: ${broadcasterId}, base_url: ${process.env.APP_BASE_URL}`); + console.log(`[eventsub] Starting — broadcaster: ${user.login} (${broadcasterId})`); + closeSocket(ws); + connect(EVENTSUB_URL, true); } function stop() { shouldRun = false; - if (ws) ws.close(); + clearTimeout(reconnectTimer); + clearTimeout(watchdog); + closeSocket(ws); + ws = null; + status.connected = false; console.log('[eventsub] Stopped'); } -function connect() { - console.log('[eventsub] Connecting...'); - ws = new WebSocket(EVENTSUB_URL); - - ws.on('open', () => console.log('[eventsub] Connected to Twitch EventSub')); - ws.on('message', (raw) => handleMessage(JSON.parse(raw))); - ws.on('close', () => { - console.log('[eventsub] Disconnected'); - if (shouldRun) setTimeout(connect, 10_000); - }); - ws.on('error', (e) => console.error('[eventsub] Error:', e.message)); +function closeSocket(sock) { + if (!sock) return; + sock.removeAllListeners('close'); // a deliberate close must not trigger the auto-reconnect + sock.on('error', () => {}); + try { sock.close(); } catch { /* already closed */ } } -async function handleMessage(msg) { +function scheduleReconnect(delay = 10_000) { + clearTimeout(reconnectTimer); + if (!shouldRun) return; + reconnectTimer = setTimeout(() => connect(EVENTSUB_URL, true), delay); +} + +function armWatchdog() { + clearTimeout(watchdog); + watchdog = setTimeout(() => { + console.warn('[eventsub] Keepalive missed — reconnecting'); + closeSocket(ws); + ws = null; + status.connected = false; + scheduleReconnect(1000); + }, keepaliveMs + 10_000); +} + +// fresh = new session (needs subscriptions); false = reconnect URL (subscriptions carry over) +function connect(url, fresh) { + console.log(`[eventsub] Connecting${fresh ? '' : ' (reconnect URL)'}...`); + const sock = new WebSocket(url); + + sock.on('message', raw => { + let msg; + try { msg = JSON.parse(raw); } catch { return; } + handleMessage(sock, msg, fresh).catch(e => console.error('[eventsub] handler error:', e.message)); + }); + sock.on('close', code => { + if (sock !== ws) return; // an old socket we already replaced + console.log(`[eventsub] Disconnected (${code})`); + status.connected = false; + clearTimeout(watchdog); + scheduleReconnect(); + }); + sock.on('error', e => console.error('[eventsub] Error:', e.message)); + + if (fresh) { closeSocket(ws); ws = sock; } +} + +async function handleMessage(sock, msg, fresh) { const type = msg.metadata?.message_type; - if (type === 'session_welcome') { - sessionId = msg.payload.session.id; - console.log('[eventsub] Session established:', sessionId); - await subscribeAll(); - } else if (type === 'session_reconnect') { - console.log('[eventsub] Reconnect requested'); - ws.close(); - } else if (type === 'notification') { - handleNotification(msg.payload); + if (sock === ws || type === 'session_welcome') armWatchdog(); + + switch (type) { + case 'session_welcome': { + const s = msg.payload.session; + keepaliveMs = (s.keepalive_timeout_seconds || 10) * 1000; + if (!fresh) { // handover from session_reconnect: swap sockets + const old = ws; + ws = sock; + closeSocket(old); + } + status.connected = true; + status.sessionId = s.id; + console.log(`[eventsub] Session ${fresh ? 'established' : 'resumed'}: ${s.id}`); + armWatchdog(); + if (fresh) await subscribeAll(s.id); + break; + } + case 'session_reconnect': + console.log('[eventsub] Reconnect requested by Twitch'); + connect(msg.payload.session.reconnect_url, false); + break; + case 'notification': + status.lastEventAt = new Date().toISOString(); + handleNotification(msg.payload); + break; + case 'revocation': + console.warn(`[eventsub] Subscription revoked: ${msg.payload.subscription.type} (${msg.payload.subscription.status})`); + break; } } -async function subscribeAll() { +async function subscribeAll(sessionId) { + const b = broadcasterId; const subs = [ - { type: 'channel.subscribe', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, - { type: 'channel.subscription.message', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, - { type: 'channel.subscription.gift', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, - { type: 'channel.cheer', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, - { type: 'channel.channel_points_custom_reward_redemption.add',version: '1', condition: { broadcaster_user_id: _broadcasterId } }, - { type: 'channel.follow', version: '2', condition: { broadcaster_user_id: _broadcasterId, moderator_user_id: _broadcasterId } }, - { type: 'channel.raid', version: '1', condition: { to_broadcaster_user_id: _broadcasterId } }, + { type: 'channel.follow', version: '2', condition: { broadcaster_user_id: b, moderator_user_id: b } }, + // cheers AND bits Power-ups (message effect, celebration, gigantify); replaces channel.cheer + { type: 'channel.bits.use', version: '1', condition: { broadcaster_user_id: b } }, + // Custom Power-ups (bits, made on Twitch): redeem variations, e.g. full-screen videos + { type: 'channel.custom_power_up_redemption.add', version: '1', condition: { broadcaster_user_id: b } }, + // subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details + { type: 'channel.chat.notification', version: '1', condition: { broadcaster_user_id: b, user_id: b } }, + // 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 } }, + { type: 'channel.chat.clear_user_messages', version: '1', condition: { broadcaster_user_id: b, user_id: b } }, + { type: 'channel.chat.clear', version: '1', condition: { broadcaster_user_id: b, user_id: b } }, + { type: 'channel.channel_points_custom_reward_redemption.add', version: '1', condition: { broadcaster_user_id: b } }, + // built-in rewards: highlight message, unlock emote, ... + { type: 'channel.channel_points_automatic_reward_redemption.add', version: '2', condition: { broadcaster_user_id: b } }, + // live poll card on the overlay + { type: 'channel.poll.begin', version: '1', condition: { broadcaster_user_id: b } }, + { type: 'channel.poll.progress', version: '1', condition: { broadcaster_user_id: b } }, + { type: 'channel.poll.end', version: '1', condition: { broadcaster_user_id: b } }, + // outgoing raid: send-off card (incoming raids come through channel.chat.notification) + { type: 'channel.raid', version: '1', condition: { from_broadcaster_user_id: b } }, + // Hype Train alerts (start, level up, end) + { type: 'channel.hype_train.begin', version: '2', condition: { broadcaster_user_id: b } }, + { type: 'channel.hype_train.progress', version: '2', condition: { broadcaster_user_id: b } }, + { type: 'channel.hype_train.end', version: '2', condition: { broadcaster_user_id: b } }, ]; + try { await twitch.validate(); } catch (e) { console.error('[eventsub]', e.message); } + + watchtime.checkLive(); // restarted mid-stream: pick up the running stream + + status.subscribed = []; + status.failed = []; for (const sub of subs) { try { - const res = await fetch('https://api.twitch.tv/helix/eventsub/subscriptions', { + const res = await twitch.helix('/eventsub/subscriptions', { method: 'POST', - headers: { - 'Authorization': `Bearer ${_accessToken}`, - 'Client-Id': CLIENT_ID, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ ...sub, transport: { method: 'websocket', session_id: sessionId } }), + body: { ...sub, transport: { method: 'websocket', session_id: sessionId } }, }); if (res.status === 202) { + status.subscribed.push(sub.type); console.log(`[eventsub] Subscribed: ${sub.type}`); } else { const body = await res.text(); + status.failed.push(`${sub.type} (${res.status})`); console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`); } } catch (e) { + status.failed.push(`${sub.type} (${e.message})`); console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message); } } } function handleNotification(payload) { - const sub = payload.subscription; + const type = payload.subscription.type; const event = payload.event; - const username = event.user_login || event.from_broadcaster_user_login || null; - console.log(`[eventsub] Notification: ${sub.type} — user: ${username}`); - - switch (sub.type) { - case 'channel.subscribe': - case 'channel.subscription.message': - dispatch.dispatchEvent('sub', event.tier, username, event); - break; - case 'channel.subscription.gift': - dispatch.dispatchEvent('gift_sub', event.tier, username, event); - break; - case 'channel.cheer': - dispatch.dispatchEvent('bits', String(event.bits), username, event); - break; - case 'channel.channel_points_custom_reward_redemption.add': - dispatch.dispatchEvent('channel_points', event.reward?.id, username, event); - break; + switch (type) { case 'channel.follow': - dispatch.dispatchEvent('follow', null, username, event); + alerts.send(alerts.fromFollow(event), event); break; + case 'channel.bits.use': + if (event.type === 'power_up' && event.power_up?.type) { + const t = event.power_up.type; + redeems.handle('power_up', t, redeems.POWER_UPS[t] || `Power-up: ${t}`, + { user: event.user_name || event.user_login, input: event.message?.text || null, emote: event.power_up.emote?.id }, event); + } else { + alerts.send(alerts.fromBitsUse(event), event); + } + break; + case 'channel.chat.notification': { + const alert = alerts.fromChatNotification(event); + if (alert) alerts.send(alert, event); + else console.log(`[eventsub] chat notification ${event.notice_type} — no alert`); + break; + } + case 'channel.channel_points_custom_reward_redemption.add': + redeems.handle('reward', event.reward.id, event.reward.title, + { user: event.user_name || event.user_login, input: event.user_input || null }, event); + break; + case 'channel.poll.begin': + case 'channel.poll.progress': + case 'channel.poll.end': + alerts.sendPoll(type.split('.').pop(), event); + break; + case 'channel.hype_train.begin': + case 'channel.hype_train.progress': + case 'channel.hype_train.end': { + const phase = type.split('.').pop(); + alerts.sendHypeBar(phase, event); // persistent progress bar + const alert = alerts.fromHypeTrain(phase, event); // queued alert on start / new level / end + if (alert) alerts.send(alert, event); + break; + } + case 'stream.online': + watchtime.online(event.id, event.started_at); + break; + 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; + case 'channel.chat.message_delete': + try { chatlog.onDelete(event); } catch (e) { console.error('[chatlog]', e.message); } + break; + case 'channel.chat.clear_user_messages': + try { chatlog.onClearUser(event); } catch (e) { console.error('[chatlog]', e.message); } + break; + case 'channel.chat.clear': + try { chatlog.onClear(event); } catch (e) { console.error('[chatlog]', e.message); } + break; + case 'channel.custom_power_up_redemption.add': { + const p = event.custom_power_up || {}; + if (p.id) redeems.handle('custom_power_up', p.id, p.title || 'Custom Power-up', + { user: event.user_name || event.user_login, input: event.user_input || null, bits: p.bits ?? null }, event); + break; + } case 'channel.raid': - dispatch.dispatchEvent('raid', null, username, event); + if (event.from_broadcaster_user_id === broadcasterId) alerts.raidHappened(event).catch(e => console.error('[alerts] raid out:', e.message)); break; + case 'channel.channel_points_automatic_reward_redemption.add': { + const t = event.reward?.type; + redeems.handle('auto_reward', t, redeems.AUTO_REWARDS[t] || t, + { user: event.user_name || event.user_login, input: event.message?.text || null, emote: event.reward?.emote?.id }, event); + break; + } } } -module.exports = { start, stop }; +function getStatus() { return { ...status, running: shouldRun }; } + +module.exports = { start, stop, getStatus }; diff --git a/src/ext/blerp.css b/src/ext/blerp.css new file mode 100644 index 0000000..ea22dca --- /dev/null +++ b/src/ext/blerp.css @@ -0,0 +1,157 @@ +/* Blerp: OBS browser source → Properties → Custom CSS (source 1920x1080, covering the whole canvas in OBS). + Looks like HeyStreamer's redeem tapes: pastel shell with screws, lined label with a SIDE A band, handwritten + title, reel window, a paper strip underneath (" shared!") and the Blerp logo as the sticker. + The sound's own picture sits in the reel window. Built only from Blerp's own elements; its swing-in stays. */ +@import url('https://fonts.googleapis.com/css2?family=Caveat:wght@600;700&family=Nunito:wght@800;900&display=swap'); + +body { background-color: rgba(0, 0, 0, 0); margin: 0 auto; overflow: hidden; } + +/* --- position: top-left corner 85,110, 440px wide (same spot and size as the other alerts) --- */ +#blerp-alert-wrapper { justify-content: flex-start !important; align-items: flex-start !important; } +#blerp-generic-template { + width: auto !important; min-height: 0 !important; overflow: visible !important; + margin: 110px 0 0 85px !important; transform-origin: left top !important; +} + +/* --- the shell (drawn at 540x346, zoomed to 440 wide) --- */ +.blerpOuterBackground { + --shell: #ffd3dc; --shell2: #ffc1cd; --edge: #c8284f; --band: #fe295c; --bandtxt: #ffffff; + --ink: #3a2a20; --red: #b74347; --window: #3b2f45; + zoom: 0.815; + position: relative !important; width: 540px !important; height: 346px !important; + border: 3px solid var(--edge) !important; border-radius: 24px !important; overflow: visible !important; + box-shadow: 0 14px 22px rgba(0, 0, 0, .45) !important; + background: + /* screws */ + radial-gradient(circle at 20px 20px, #fff 0 3px, var(--edge) 3px 5px, #0000 6px), + radial-gradient(circle at 514px 20px, #fff 0 3px, var(--edge) 3px 5px, #0000 6px), + radial-gradient(circle at 20px 318px, #fff 0 3px, var(--edge) 3px 5px, #0000 6px), + radial-gradient(circle at 514px 318px, #fff 0 3px, var(--edge) 3px 5px, #0000 6px), + /* lined label */ + repeating-linear-gradient(#0000 0 25px, rgba(110, 130, 170, .22) 25px 26px) 42px 70px / 454px 160px no-repeat, + linear-gradient(#fffdf6, #fffdf6) 42px 30px / 454px 200px no-repeat, + linear-gradient(var(--shell), var(--shell2)) !important; +} +/* bottom part with the drive holes */ +.blerpOuterBackground::before { + content: ""; position: absolute; left: 118px; right: 118px; bottom: -3px; height: 86px; + clip-path: polygon(9% 0, 91% 0, 100% 100%, 0 100%); + background: + radial-gradient(circle at 22% 55%, var(--window) 0 8px, #0000 9px), + radial-gradient(circle at 34% 55%, var(--window) 0 8px, #0000 9px), + linear-gradient(var(--window), var(--window)) 50% 52% / 28px 24px no-repeat, + radial-gradient(circle at 66% 55%, var(--window) 0 8px, #0000 9px), + radial-gradient(circle at 78% 55%, var(--window) 0 8px, #0000 9px), + #ffadbf; +} +/* Blerp logo sticker, top-right corner, white outline like the redeem stickers */ +.blerpOuterBackground::after { + content: ""; position: absolute; right: -44px; top: -40px; width: 112px; height: 104px; z-index: 3; + background: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2244.716%22%20height%3D%2241.642%22%20viewBox%3D%220%200%2044.716%2041.642%22%3E%20%20%20%3Cg%20id%3D%22BlerpIconRed%22%20transform%3D%22translate%28-145.998%20-27%29%22%3E%20%20%20%20%20%3Cpath%20id%3D%22Path_1731%22%20data-name%3D%22Path%201731%22%20d%3D%22M37.36%2C17.914c-.91-4.766%2C3.258-8.281.4-11.831-3.881-4.815-8.637%2C1.76-12.993-.133C21.935%2C4.718%2C19.1.565%2C14.924%2C2.083s-3.683%2C6.526-5.038%2C9.285C7.751%2C15.62-.12%2C13.642%2C0%2C19.827c.094%2C4.558%2C5.542%2C4.573%2C7.91%2C8.805S4.814%2C38%2C9.728%2C42.05c5.953%2C4.914%2C11.974-5.072%2C17.2-6.986h0c5.211-1.9%2C16.266%2C1.913%2C17.67-5.705C45.745%2C23.1%2C38.25%2C22.606%2C37.36%2C17.914ZM24.021%2C27.09a9.068%2C9.068%2C0%2C0%2C1-10.308-3.461%2C1.483%2C1.483%2C0%2C0%2C1%2C1.043-2.358%2C29.169%2C29.169%2C0%2C0%2C0%2C6.556-1.587%2C29.342%2C29.342%2C0%2C0%2C0%2C6.046-3%2C1.483%2C1.483%2C0%2C0%2C1%2C2.3%2C1.1A9.062%2C9.062%2C0%2C0%2C1%2C24.021%2C27.09Z%22%20transform%3D%22translate%28146.001%2025.246%29%22%20fill%3D%22%23fe295c%22%2F%3E%20%20%20%3C%2Fg%3E%20%3C%2Fsvg%3E%20") center / contain no-repeat; + transform: rotate(10deg); + filter: drop-shadow(4px 0 0 #fff) drop-shadow(-4px 0 0 #fff) drop-shadow(0 4px 0 #fff) drop-shadow(0 -4px 0 #fff) drop-shadow(0 6px 9px rgba(0,0,0,.35)); +} + +/* --- the label (holds everything else) --- */ +.alertNewPill { + position: absolute !important; left: 42px; top: 30px; width: 454px !important; height: 200px !important; + box-sizing: border-box !important; padding: 0 !important; display: block !important; + background: transparent !important; overflow: visible !important; +} +/* SIDE A band */ +.alertNewPill::before, .alertNewPill::after { + position: absolute; top: 0; height: 40px; font: 900 19px/40px 'Nunito', sans-serif; letter-spacing: 2.5px; color: var(--bandtxt); +} +.alertNewPill::before { content: "SIDE A"; left: 0; right: 0; padding-left: 20px; background: var(--band); border-radius: 6px 6px 0 0; } +.alertNewPill::after { content: "★ BLERP"; right: 70px; } + +.innerBackgroundText { position: absolute !important; inset: 0; display: block !important; overflow: visible !important; padding: 0 !important; } +/* reel window with two white reels */ +.innerBackgroundText::before { + content: ""; position: absolute; left: 82px; top: 92px; width: 290px; height: 82px; border-radius: 41px; + border: 3px solid var(--edge); box-sizing: border-box; + background: + radial-gradient(circle at 62px 38px, var(--window) 0 6px, #fff 7px 13px, #d9d2ca 13px 16px, #fff 16px 25px, #cfc6bd 25px 27px, #5a4036 28px 33px, #0000 34px), + radial-gradient(circle at 222px 38px, var(--window) 0 6px, #fff 7px 13px, #d9d2ca 13px 16px, #fff 16px 25px, #cfc6bd 25px 27px, #5a4036 28px 33px, #0000 34px), + var(--window); +} +/* small caption under the window */ +.innerBackgroundText::after { + content: "Blerp sound"; position: absolute; left: 0; right: 0; top: 176px; text-align: center; + font: 700 27px/1 'Caveat', cursive; color: #7a6656; +} + +/* the sound's picture: a sticker in the bottom-right corner (where the redeem tapes have theirs): + thick white border, softly rounded, one corner curling up */ +#innerBackgroundImage { + position: absolute !important; left: 392px; top: 188px; z-index: 5; + width: 150px !important; height: 150px !important; margin: 0 !important; padding: 8px !important; + border: none !important; border-radius: 16px 16px 26px 16px !important; background: #fff !important; box-sizing: border-box !important; + box-shadow: 0 7px 12px rgba(0, 0, 0, .35), 0 1px 2px rgba(0, 0, 0, .25) !important; + overflow: hidden !important; +} +#innerBackgroundImageReal { width: 134px !important; height: 134px !important; border-radius: 10px 10px 18px 10px !important; object-fit: cover; } +/* curled corner, bottom right */ +#innerBackgroundImage::after { + content: ""; position: absolute; right: 0; bottom: 0; width: 34px; height: 34px; + background: linear-gradient(135deg, rgba(0, 0, 0, .18) 0%, #f4f0ea 46%, #fff 50%, #0000 51%); + border-top-left-radius: 10px; box-shadow: -2px -2px 4px rgba(0, 0, 0, .12); +} + +/* title: the sound name, handwritten on the label */ +#secondary-alert-text { + position: absolute !important; left: 24px; right: 24px; top: 42px; width: auto !important; height: auto !important; + text-align: center !important; font-family: 'Caveat', cursive !important; font-weight: 700 !important; + font-size: 48px !important; line-height: 1 !important; color: var(--ink) !important; + white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; +} + +/* " shared!" on a taped paper strip under the tape */ +#main-alert-text { + position: absolute !important; left: -6px; top: 318px; width: auto !important; height: auto !important; max-width: 470px; + padding: 10px 28px 12px !important; background: #fffdf7; transform: rotate(-2deg); + box-shadow: 0 6px 14px rgba(0, 0, 0, .35); z-index: 4; + font-family: 'Caveat', cursive !important; font-weight: 700 !important; font-size: 38px !important; line-height: 1.05 !important; + color: var(--red) !important; white-space: nowrap !important; overflow: visible !important; margin: 0 !important; min-width: 0 !important; +} +#main-alert-text::before, #main-alert-text::after { + content: ""; position: absolute; top: -12px; width: 86px; height: 28px; + background: rgba(201, 182, 228, .85); background-image: repeating-linear-gradient(45deg, #fff6 0 8px, #0000 8px 16px); +} +#main-alert-text::before { left: -26px; transform: rotate(-28deg); } +#main-alert-text::after { right: -26px; transform: rotate(24deg); } + +/* --- motion: same as HeyStreamer's tapes (public/alerts/cassette.js) --- */ +/* Blerp's own entrance ("swing") off; its exit animation stays */ +@keyframes swing { from { transform: none; } to { transform: none; } } +/* Blerp fades the text in after a delay: show it with the tape */ +.innerBackgroundText { opacity: 1 !important; transition: none !important; } + +/* tape slides in from the left with a little overshoot, settles tilted; then bobs while the sound plays */ +.blerpOuterBackground { animation: hs-tape-in 700ms cubic-bezier(.2, .8, .3, 1) both, hs-bob 420ms ease-in-out 700ms 12; } +@keyframes hs-tape-in { + 0% { transform: translateX(-620px) rotate(-14deg); opacity: 0; } + 72% { transform: translateX(18px) rotate(0deg); opacity: 1; } + 88% { transform: translateX(-4px) rotate(-2.6deg); } + 100% { transform: translateX(0) rotate(-2deg); opacity: 1; } +} +@keyframes hs-bob { 0%, 100% { translate: 0 0; } 50% { translate: 0 -2px; } } +/* stickers pop in: the picture like the redeem sticker, the logo just after */ +#innerBackgroundImage { animation: hs-img-in 380ms ease-out 650ms both; } +@keyframes hs-img-in { + 0% { transform: rotate(-22deg) scale(0); opacity: 0; } + 60% { transform: rotate(14deg) scale(1.2); opacity: 1; } + 100% { transform: rotate(7deg) scale(1); opacity: 1; } +} +.blerpOuterBackground::after { animation: hs-stk-in 380ms ease-out 780ms both; } +@keyframes hs-stk-in { + 0% { transform: rotate(-30deg) scale(0); opacity: 0; } + 60% { transform: rotate(18deg) scale(1.2); opacity: 1; } + 100% { transform: rotate(10deg) scale(1); opacity: 1; } +} +/* paper strip drops in */ +#main-alert-text { animation: hs-strip-in 320ms cubic-bezier(.3, .7, .4, 1) 850ms both; } +@keyframes hs-strip-in { + 0% { transform: translateY(-20px) rotate(-6deg) scale(1.1); opacity: 0; } + 100% { transform: translateY(0) rotate(-2deg) scale(1); opacity: 1; } +} diff --git a/src/ext/hudfx.css b/src/ext/hudfx.css new file mode 100644 index 0000000..f7a70b9 --- /dev/null +++ b/src/ext/hudfx.css @@ -0,0 +1,68 @@ +/* HUDFX: OBS browser source → Properties → Custom CSS (source 2560x1440). + The notification as a camcorder viewfinder in HUDFX colours: scanlines, corner brackets, ● REC, timecode, VCR text. + Built only from HUDFX's own elements (.alert-inner-container …); full-screen effect videos are untouched. */ +@import url('https://fonts.googleapis.com/css2?family=VT323&display=swap'); + +body { background-color: rgba(0, 0, 0, 0); margin: 0 auto; overflow: hidden; } + +div.alert-contain > div.alert-inner-container.branded { + --purple: #734ffe; --lilac: #b9a6ff; --navy: #1c1f2f; + width: 440px !important; height: auto !important; min-height: 250px !important; + padding: 58px 26px 30px !important; + border: 6px solid var(--purple) !important; border-radius: 14px !important; + box-shadow: 0 0 0 3px #0e0f18, 0 0 26px rgba(115, 79, 254, .6), 0 14px 26px rgba(0, 0, 0, .5) !important; + background: + /* corner brackets */ + linear-gradient(#fff, #fff) 14px 14px / 30px 4px no-repeat, linear-gradient(#fff, #fff) 14px 14px / 4px 30px no-repeat, + linear-gradient(#fff, #fff) right 14px top 14px / 30px 4px no-repeat, linear-gradient(#fff, #fff) right 14px top 14px / 4px 30px no-repeat, + linear-gradient(#fff, #fff) left 14px bottom 14px / 30px 4px no-repeat, linear-gradient(#fff, #fff) left 14px bottom 14px / 4px 30px no-repeat, + linear-gradient(#fff, #fff) right 14px bottom 14px / 30px 4px no-repeat, linear-gradient(#fff, #fff) right 14px bottom 14px / 4px 30px no-repeat, + /* scanlines + a soft purple glow on the screen */ + repeating-linear-gradient(0deg, rgba(255, 255, 255, .045) 0 2px, transparent 2px 4px), + radial-gradient(ellipse at 50% 45%, #2b2550 0%, #1c1f2f 70%) #1c1f2f !important; + background-color: #1c1f2f !important; /* solid screen, never see-through */ + animation: hfx-jitter 3.2s steps(1) infinite; +} +/* ● REC (blinking) and timecode */ +div.alert-contain > div.alert-inner-container.branded::before { + content: "● REC"; position: absolute; left: 28px; top: 20px; + font: 30px/1 'VT323', monospace; color: #ff3b4e; letter-spacing: 1px; text-shadow: 0 0 6px rgba(255, 59, 78, .7); + animation: hfx-blink 1s steps(1) infinite; +} +div.alert-contain > div.alert-inner-container.branded::after { + content: "▶ 0:00:13"; position: absolute; right: 28px; top: 20px; + font: 26px/1 'VT323', monospace; color: #fff; opacity: .85; +} + +.alert-media-contain { display: none !important; } /* little avatar badge on the top edge */ + +/* "Triggered " + viewer name: VCR text with a slight colour split */ +.alert-text-contain pre { + font-family: 'VT323', monospace !important; font-weight: 400 !important; + font-size: 40px !important; line-height: 1 !important; text-transform: uppercase; + color: #fff !important; white-space: pre-wrap !important; text-align: center !important; margin: 0 !important; + text-shadow: 2px 0 rgba(255, 59, 120, .75), -2px 0 rgba(80, 220, 255, .75) !important; +} +.alert-text-contain .animate__pulse pre { color: var(--lilac) !important; font-size: 36px !important; margin-top: 10px !important; } + +/* "50 bits" as the tape label strip */ +.alert-amount-contain { + background: var(--purple) !important; border-radius: 4px !important; height: auto !important; + padding: 4px 18px !important; margin-top: 18px !important; box-shadow: 0 0 12px rgba(115, 79, 254, .7) !important; +} +.alert-amount-contain pre { font-family: 'VT323', monospace !important; font-size: 30px !important; color: #fff !important; text-transform: uppercase; } + +.branded-logo-contain { opacity: .6; transform: translate(-30px, -12px); } + +@keyframes hfx-blink { 0% { opacity: 1; } 50% { opacity: 0; } } +@keyframes hfx-jitter { 0%, 100% { transform: none; } 92% { transform: translateX(2px) skewX(-1deg); } 94% { transform: translateX(-2px); } 96% { transform: none; } } + +/* Put the box where HeyStreamer's own alerts appear (top left: 85,110 on the 1920x1080 overlay, 440px wide). + This page is 2560x1440 shown at 75%, so: scale 1.45 makes the box ~440px wide on the overlay, and the layer + position puts its top-left corner at 85,110. #BCOvP… is the alert layer's id in this HUDFX overlay's settings; + :has() catches it if that id ever changes. */ +#BCOvPCnfVtwksnH8vmgmm, +.overlay-layer:has(.alert-contain) { + left: 44px !important; top: 46px !important; + transform: scale(1.45) !important; transform-origin: 0 0 !important; +} diff --git a/src/library.js b/src/library.js new file mode 100644 index 0000000..d1be6fa --- /dev/null +++ b/src/library.js @@ -0,0 +1,58 @@ +// Every media file HeyStreamer can use, in one list: the built-in library under public/alerts (shipped with +// the code) and uploads from the Media page (public/media, kept only on the server, listed in media_files). +// Used by the Media page and by the Redeems pickers, so both always show the same files. +// { url, label, type: 'audio' | 'video' | 'image', source: 'library' | 'upload', id?, size, file } +const fs = require('fs'); +const path = require('path'); +const db = require('./db'); + +const PUBLIC = path.join(__dirname, '..', 'public'); +const RE = { audio: /\.(mp3|wav|ogg|m4a)$/i, video: /\.(webm|mp4|mov)$/i, image: /\.(png|webp|gif|jpe?g)$/i }; + +// built-in folders, in the order they are listed +const DIRS = [ + { dir: 'alerts/videos', type: 'video' }, + { dir: 'alerts/sounds/redeems', type: 'audio', note: 'normalized' }, + { dir: 'alerts/sounds', type: 'audio' }, + { dir: 'alerts/stickers', type: 'image' }, + { dir: 'alerts/art', type: 'image' }, +]; + +const pretty = f => f.replace(/\.\w+$/, '').replace(/_Contrast$/, '').replace(/[_]+/g, ' '); + +function typeOf(mime, name) { + if (/^video\//.test(mime) || RE.video.test(name)) return 'video'; + if (/^audio\//.test(mime) || RE.audio.test(name)) return 'audio'; + if (/^image\/(png|webp|gif|jpeg)$/.test(mime) || RE.image.test(name)) return 'image'; + return null; +} + +function list() { + const out = []; + for (const d of DIRS) { + let files = []; + try { files = fs.readdirSync(path.join(PUBLIC, d.dir)).filter(f => RE[d.type].test(f)).sort(); } catch { /* folder missing */ } + for (const f of files) { + let size = 0; + try { size = fs.statSync(path.join(PUBLIC, d.dir, f)).size; } catch {} + out.push({ url: `/${d.dir}/${f}`, label: pretty(f), file: f, type: d.type, source: 'library', size, note: d.note || null }); + } + } + for (const m of db.getAllMedia()) { + const type = m.media_type === 'image' ? 'image' : m.media_type === 'video' ? 'video' : 'audio'; + out.push({ url: `/media/${m.filename}`, label: pretty(m.original_name), file: m.original_name, type, source: 'upload', + id: m.id, size: m.size_bytes, uploaded_at: m.uploaded_at }); + } + return out; +} + +const ofType = type => list().filter(i => i.type === type); + +// how many redeem variations use each URL (as sound, video or sticker) +function usage() { + const n = new Map(); + for (const v of db.getAllVariations()) for (const u of [v.sound, v.video, v.art]) if (u) n.set(u, (n.get(u) || 0) + 1); + return n; +} + +module.exports = { list, ofType, usage, typeOf, PUBLIC }; diff --git a/src/nav.js b/src/nav.js new file mode 100644 index 0000000..c7a2c59 --- /dev/null +++ b/src/nav.js @@ -0,0 +1,35 @@ +// Left sidebars of the dashboard sections. app.js mounts section('actions') / section('settings') in front of the +// pages of that section; views/layout.ejs draws the sidebar and marks the page that is open. +const SECTIONS = { + actions: { + title: 'Actions', + items: [ + { href: '/redeems', label: 'Redeems', hint: 'Channel point rewards and Power-ups: variations, sounds, looks' }, + { href: '/actions/alerts', label: 'Alerts', hint: 'Follows, subs, gifts, raids, bits, tips, Hype Train: style, pictures, sounds' }, + { href: '/tts', label: 'TTS voices', hint: 'Voices for redeems that read the viewer\'s text aloud' }, + { href: '/media', label: 'Media', hint: 'Every picture, sound and video you can pick' }, + ], + }, + settings: { + title: 'Settings', + items: [ + { href: '/settings/general', label: 'General' }, + { href: '/settings/connections', label: 'Connections', hint: 'Twitch, StreamElements, HUDFX' }, + { href: '/settings/obs', label: 'OBS sources', hint: 'Browser source links for OBS' }, + { href: '/settings/chat', label: 'Chat', hint: 'On-screen chat, hidden chatters, gap sound' }, + { href: '/settings/tts', label: 'Text to speech', hint: 'Length, blocked words' }, + { href: '/settings/stats', label: 'Stats and data', hint: 'Public stats page, Twitch sync, analytics import' }, + { href: '/settings/backup', label: 'Backup', hint: 'Export / import the whole setup' }, + { href: '/settings/advanced', label: 'Advanced', hint: 'Custom CSS / JS for the overlay' }, + ], + }, +}; + +const section = name => (req, res, next) => { + const s = SECTIONS[name]; + const here = req.baseUrl + req.path; + res.locals.sidebar = { name, title: s.title, items: s.items.map(i => ({ ...i, on: here === i.href || here.startsWith(i.href + '/') })) }; + next(); +}; + +module.exports = { SECTIONS, section }; diff --git a/src/nowplaying.js b/src/nowplaying.js new file mode 100644 index 0000000..7f51224 --- /dev/null +++ b/src/nowplaying.js @@ -0,0 +1,12 @@ +// "Now playing" from the streamer's music player (Feishin via MPRIS), pushed by tools/nowplaying/feishin_nowplaying.py. +// The helper sends only text + a small JPEG cover (data URL); no player/server URLs or credentials reach this app. +let current = null; // { playing, title, artist, album, cover, length, updatedAt } + +function set(np) { + current = { ...np, updatedAt: Date.now() }; + require('./ws').broadcast({ type: 'nowplaying', np: current }); + return current; +} +function get() { return current; } + +module.exports = { set, get }; diff --git a/src/periodstats.js b/src/periodstats.js new file mode 100644 index 0000000..4be2b7a --- /dev/null +++ b/src/periodstats.js @@ -0,0 +1,493 @@ +// Period statistics: what happened per day and per stream, so the Stats pages (admin and public) can show one +// stream, a week, a month, a year or all time. ONE generic table: a new kind of statistic is a new `kind` +// value, not a new table (e.g. bot commands later: kind 'command', or a kind of their own). +// +// stat_day day (UTC YYYY-MM-DD) x stream_id ('' = chat while offline) x viewer x kind x item -> uses, amount +// kind 'message' item '' uses = messages, amount = points-eligible messages +// kind 'intro' item '' Twitch "first message ever in this channel" +// kind 'emote' item emote name uses +// kind 'command' item '!cmd' uses +// kind 'watch' item '' uses = 5-minute watch ticks +// kind 'action:' item reward / tier uses, amount + unit (points, bits, months, viewers, EUR...) +// stat_emote emote name -> source (twitch / 7tv) + id, for pictures +// public_optout viewers who typed !hideme: counted, but never named on the public page +// stat_meta one-time jobs (backfill) +// +// The lifetime tables in chatlog.js / watchtime.js stay as they are (points and levels are calculated from them). +// Viewer key = Twitch user id, or 'name:' when an event has no id (StreamElements tips, watch streaks). +const db = require('./db'); + +let ready = false; +const d = () => db.raw(); + +function init() { + if (ready) return; + d().exec(` + CREATE TABLE IF NOT EXISTS stat_day ( + day TEXT NOT NULL, stream_id TEXT NOT NULL DEFAULT '', + user_key TEXT NOT NULL, user_login TEXT, user_name TEXT, + kind TEXT NOT NULL, item TEXT NOT NULL DEFAULT '', + uses INTEGER DEFAULT 0, amount REAL DEFAULT 0, max_amount REAL DEFAULT 0, unit TEXT, + PRIMARY KEY (day, stream_id, user_key, kind, item) + ); + CREATE INDEX IF NOT EXISTS stat_day_stream ON stat_day(stream_id); + CREATE INDEX IF NOT EXISTS stat_day_user ON stat_day(user_key); + CREATE TABLE IF NOT EXISTS stat_emote (emote TEXT PRIMARY KEY, source TEXT, emote_id TEXT); + CREATE TABLE IF NOT EXISTS public_optout (user_key TEXT PRIMARY KEY, user_login TEXT, at TEXT); + CREATE TABLE IF NOT EXISTS stat_meta (key TEXT PRIMARY KEY, value TEXT); + `); + ready = true; + try { backfill(); } catch (e) { console.error('[periodstats] backfill failed:', e.message); } +} + +const currentStream = () => require('./watchtime').currentStreamId() || ''; + +// rows: [{ key, login, name, kind, item, uses, amount, unit, max }]; at = ISO time (default now), stream = id or '' +function add(rows, at = new Date().toISOString(), stream = currentStream()) { + init(); + const ins = d().prepare(`INSERT INTO stat_day (day, stream_id, user_key, user_login, user_name, kind, item, uses, amount, max_amount, unit) + VALUES (@day, @stream, @key, @login, @name, @kind, @item, @uses, @amount, @amount, @unit) + ON CONFLICT(day, stream_id, user_key, kind, item) DO UPDATE SET + uses = uses + excluded.uses, amount = amount + excluded.amount, + max_amount = MAX(max_amount, excluded.max_amount), + user_login = COALESCE(excluded.user_login, user_login), user_name = COALESCE(excluded.user_name, user_name), + unit = COALESCE(excluded.unit, unit)`); + const day = at.slice(0, 10); + for (const r of rows) { + if (!r.key || !r.kind) continue; + ins.run({ day, stream: stream || '', key: String(r.key), login: r.login || null, name: r.name || r.login || null, + kind: r.kind, item: String(r.item ?? ''), uses: r.uses ?? 1, amount: Number(r.amount) || 0, unit: r.unit || null }); + } +} + +function emoteSeen(name, source, id) { + init(); + d().prepare('INSERT INTO stat_emote (emote, source, emote_id) VALUES (?, ?, ?) ON CONFLICT(emote) DO UPDATE SET source = excluded.source, emote_id = COALESCE(excluded.emote_id, emote_id)') + .run(name, source || null, id || null); +} + +// --- public page opt-out (!hideme / !showme in chat, or the button on the admin viewer page) --- +function setOptout(key, login, hide) { + init(); + if (hide) d().prepare('INSERT OR REPLACE INTO public_optout (user_key, user_login, at) VALUES (?, ?, ?)').run(String(key), login || null, new Date().toISOString()); + else d().prepare('DELETE FROM public_optout WHERE user_key = ? OR (user_login IS NOT NULL AND user_login = ?)').run(String(key), login || '-'); +} +function optedOut() { + init(); + const rows = d().prepare('SELECT user_key, user_login FROM public_optout').all(); + return { keys: new Set(rows.map(r => r.user_key)), logins: new Set(rows.map(r => r.user_login).filter(Boolean)) }; +} +const isOptedOut = (key, login) => { const o = optedOut(); return o.keys.has(String(key)) || o.logins.has(String(login || '').toLowerCase()); }; + +function forgetUser(key, login) { + init(); + d().prepare('DELETE FROM stat_day WHERE user_key = ? OR user_key = ? OR user_login = ?').run(String(key || '-'), `name:${login || '-'}`, login || '-'); + d().prepare('DELETE FROM public_optout WHERE user_key = ? OR user_login = ?').run(String(key || '-'), login || '-'); +} + +// --- one-time backfill from the tables that existed before (raw chat is kept 30 days) --- +function backfill() { + if (d().prepare("SELECT 1 FROM stat_meta WHERE key = 'backfill_v1'").get()) return; + const has = t => !!d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t); + const streams = has('stream_session') ? d().prepare('SELECT id, started_at, ended_at FROM stream_session').all() : []; + const at = iso => { const t = Date.parse(iso); return streams.find(s => t >= Date.parse(s.started_at) && t <= Date.parse(s.ended_at || new Date().toISOString()))?.id || ''; }; + const onDay = day => streams.find(s => s.started_at.slice(0, 10) <= day && (s.ended_at || new Date().toISOString()).slice(0, 10) >= day)?.id || ''; + let n = 0; + d().transaction(() => { + // chat from the raw buffer: exact time -> exact stream. Points-eligible = same 5-minute rule as chatlog.js. + const rawCount = new Map(); // user|day -> messages found in raw + if (has('chat_raw')) { + const lastScored = new Map(); + for (const m of d().prepare('SELECT * FROM chat_raw ORDER BY at').all()) { + const t = Date.parse(m.at), prev = lastScored.get(m.user_id); + const scored = prev == null || t - prev >= 5 * 60 * 1000 ? 1 : 0; + if (scored) lastScored.set(m.user_id, t); + const who = { key: m.user_id, login: m.user_login, name: m.user_name }; + const rows = [{ ...who, kind: 'message', amount: scored }]; + if (m.first_msg) rows.push({ ...who, kind: 'intro' }); + for (const e of JSON.parse(m.emotes || '[]')) rows.push({ ...who, kind: 'emote', item: e }); + if (m.command) rows.push({ ...who, kind: 'command', item: m.command }); + add(rows, m.at, at(m.at)); n++; + const k = `${m.user_id}|${m.at.slice(0, 10)}`; rawCount.set(k, (rawCount.get(k) || 0) + 1); + } + } + // messages counted but no longer in the raw buffer (deleted by moderation, or older than 30 days) + if (has('chat_user_day')) for (const r of d().prepare('SELECT c.user_id, c.day, c.messages, u.user_login, u.user_name FROM chat_user_day c LEFT JOIN chat_user u USING (user_id)').all()) { + const rest = r.messages - (rawCount.get(`${r.user_id}|${r.day}`) || 0); + if (rest > 0) add([{ key: r.user_id, login: r.user_login, name: r.user_name, kind: 'message', uses: rest }], r.day + 'T12:00:00.000Z', onDay(r.day)); + } + // watch ticks only happen while live: the stream of that day + if (has('watch_user_day')) for (const r of d().prepare('SELECT w.user_id, w.day, w.ticks, u.user_login, u.user_name FROM watch_user_day w LEFT JOIN watch_user u USING (user_id)').all()) + add([{ key: r.user_id, login: r.user_login, name: r.user_name, kind: 'watch', uses: r.ticks }], r.day + 'T12:00:00.000Z', onDay(r.day)); + // actions: a single use has its exact time; repeated ones are put on the last use + if (has('chat_action')) for (const r of d().prepare('SELECT * FROM chat_action').all()) { + const when = r.uses === 1 ? r.first_at : r.last_at; + add([{ key: r.user_key, login: r.user_login, name: r.user_name, kind: 'action:' + r.action, item: r.item, uses: r.uses, amount: r.amount, unit: r.unit }], when, at(when)); + } + if (has('chat_emote')) for (const r of d().prepare('SELECT emote, source, emote_id FROM chat_emote GROUP BY emote').all()) emoteSeen(r.emote, r.source, r.emote_id); + d().prepare("INSERT INTO stat_meta (key, value) VALUES ('backfill_v1', ?)").run(new Date().toISOString()); + })(); + console.log(`[periodstats] backfilled from existing statistics (${n} raw messages)`); +} + +// ===================== ranges ===================== +// ?p=stream&s= | week | month | year | all, anchored on ?d=YYYY-MM-DD (default today). Days are UTC. +const iso = t => new Date(t).toISOString().slice(0, 10); +const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; +const nice = day => { const [y, m, dd] = day.split('-'); return `${+dd} ${MONTHS[+m - 1].slice(0, 3)} ${y}`; }; + +function streams() { + init(); + return d().prepare('SELECT * FROM stream_session ORDER BY started_at DESC').all(); +} + +function parseRange(q = {}, fallback = 'all') { + let p = ['stream', 'week', 'month', 'year', 'all'].includes(q.p) ? q.p : fallback; + const anchor = /^\d{4}-\d{2}-\d{2}$/.test(q.d || '') ? q.d : iso(Date.now()); + const a = new Date(anchor + 'T00:00:00Z'); + if (p === 'stream') { + const list = streams(); + const s = list.find(x => x.id === String(q.s || '')) || list[0]; + if (!s) p = 'all'; + else { + const i = list.indexOf(s); + return { p, stream: s, label: `Stream · ${nice(s.started_at.slice(0, 10))}`, sub: s.title || '', + prev: list[i + 1] ? { p, s: list[i + 1].id } : null, next: list[i - 1] ? { p, s: list[i - 1].id } : null }; + } + } + if (p === 'week') { + const mon = new Date(a); mon.setUTCDate(a.getUTCDate() - ((a.getUTCDay() + 6) % 7)); + const from = iso(mon), to = iso(mon.getTime() + 6 * 864e5); + return { p, from, to, label: `Week of ${nice(from)}`, sub: `${nice(from)} – ${nice(to)}`, + prev: { p, d: iso(mon.getTime() - 7 * 864e5) }, next: to < iso(Date.now()) ? { p, d: iso(mon.getTime() + 7 * 864e5) } : null }; + } + if (p === 'month') { + const y = a.getUTCFullYear(), m = a.getUTCMonth(); + const from = iso(Date.UTC(y, m, 1)), to = iso(Date.UTC(y, m + 1, 0)); + return { p, from, to, label: `${MONTHS[m]} ${y}`, prev: { p, d: iso(Date.UTC(y, m - 1, 1)) }, + next: to < iso(Date.now()) ? { p, d: iso(Date.UTC(y, m + 1, 1)) } : null }; + } + if (p === 'year') { + const y = a.getUTCFullYear(); + return { p, from: `${y}-01-01`, to: `${y}-12-31`, label: String(y), prev: { p, d: `${y - 1}-01-01` }, + next: `${y}-12-31` < iso(Date.now()) ? { p, d: `${y + 1}-01-01` } : null }; + } + return { p: 'all', label: 'All time' }; +} + +// query string for a range link (prev / next / tabs) +const rangeQuery = r => '?' + Object.entries(r).filter(([, v]) => v != null).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&'); + +function whereOf(r) { + if (r.p === 'stream') return { sql: 'stream_id = ?', args: [r.stream.id] }; + if (r.from) return { sql: 'day BETWEEN ? AND ?', args: [r.from, r.to] }; + return { sql: '1 = 1', args: [] }; +} + +// ===================== the summary both Stats pages show ===================== +// opts.hidden: logins left out completely (bots); opts.anonymous: { keys, logins } counted in totals but never +// named (public page: !hideme); opts.baseline: add StreamElements' watch time from before our tracking ('all' only). +function summary(r, { hidden = [], anonymous = null, baseline = true, top = 10, revenue = false } = {}) { + init(); + const hide = new Set(hidden.map(x => String(x).toLowerCase())); + const anon = (key, login) => anonymous && (anonymous.keys.has(key) || anonymous.logins.has(String(login || '').toLowerCase())); + const w = whereOf(r); + + const names = new Map(); // latest login / name per viewer (bare columns come from the MAX(day) row) + for (const x of d().prepare(`SELECT user_key, user_login, user_name, MAX(day) FROM stat_day GROUP BY user_key`).all()) names.set(x.user_key, x); + const rows = d().prepare(`SELECT user_key, kind, item, SUM(uses) uses, SUM(amount) amount, MAX(max_amount) max_amount, MAX(unit) unit + FROM stat_day WHERE ${w.sql} GROUP BY user_key, kind, item`).all(...w.args) + .filter(x => !hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase())); + + const per = new Map(); // viewer -> { key, login, name, messages, ticks, ... } + const who = k => { + if (!per.has(k)) { const n = names.get(k) || {}; per.set(k, { key: k, login: n.user_login, name: n.user_name || n.user_login, messages: 0, ticks: 0, bits: 0, subs: 0, gifts: 0, points: 0, tips: 0 }); } + return per.get(k); + }; + const emotes = new Map(), commands = new Map(), rewards = new Map(), tipsByUnit = new Map(); + const t = { messages: 0, scored: 0, intros: 0, ticks: 0, emotes: 0, commands: 0, follows: 0, subs: 0, giftSubs: 0, bits: 0, raids: 0, raidViewers: 0, redeems: 0, channelPoints: 0, powerUps: 0, tips: 0 }; + for (const x of rows) { + const v = who(x.user_key); + switch (x.kind) { + case 'message': v.messages += x.uses; t.messages += x.uses; t.scored += x.amount; break; + case 'intro': t.intros += x.uses; break; + case 'watch': v.ticks += x.uses; t.ticks += x.uses; break; + case 'emote': t.emotes += x.uses; emotes.set(x.item, (emotes.get(x.item) || 0) + x.uses); break; + case 'command': t.commands += x.uses; commands.set(x.item, (commands.get(x.item) || 0) + x.uses); break; + case 'action:follow': t.follows += x.uses; break; + case 'action:sub': t.subs += x.uses; v.subs += x.uses; break; + case 'action:gift_sub': t.giftSubs += x.amount; v.gifts += x.amount; break; + case 'action:bits': t.bits += x.amount; v.bits += x.amount; break; + case 'action:power_up': case 'action:custom_power_up': + t.bits += x.amount; v.bits += x.amount; t.powerUps += x.uses; + rewards.set(x.item, (rewards.get(x.item) || 0) + x.uses); break; + case 'action:channel_points': case 'action:auto_reward': + t.redeems += x.uses; t.channelPoints += x.amount; v.points += x.amount; + rewards.set(x.item, (rewards.get(x.item) || 0) + x.uses); break; + case 'action:raid': t.raids += x.uses; t.raidViewers += x.amount; break; + case 'action:tip': t.tips += x.uses; v.tips += x.amount; tipsByUnit.set(x.unit || '', (tipsByUnit.get(x.unit || '') || 0) + x.amount); break; + } + } + + const hasT = t => !!d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t); + const synced = t => hasT(t) && !!d().prepare(`SELECT 1 FROM ${t} LIMIT 1`).get(); + // new followers: Twitch's follower list has every follow date (also before HeyStreamer); our events otherwise + const followWindow = r.p === 'stream' ? [r.stream.started_at, r.stream.ended_at || new Date().toISOString()] + : r.from ? [r.from, r.to + 'T23:59:59.999Z'] : null; + if (synced('tw_follower') && (!synced('tw_daily') || r.p === 'stream')) { + t.follows = followWindow ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE followed_at BETWEEN ? AND ?').get(...followWindow).n + : d().prepare('SELECT COUNT(*) n FROM tw_follower').get().n; + } + + // StreamElements watch time from before our own tracking: no dates, so it only belongs to "all time" + let baselineMinutes = 0; + if (r.p === 'all' && baseline && d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='watch_import'").get()) { + const byLogin = new Map([...per.values()].filter(v => v.login).map(v => [v.login, v])); + for (const b of d().prepare('SELECT user_login, minutes FROM watch_import').all()) { + if (hide.has(b.user_login)) continue; + const v = byLogin.get(b.user_login) || who(`name:${b.user_login}`); + if (!v.login) { v.login = b.user_login; v.name = b.user_login; } + v.extraMinutes = (v.extraMinutes || 0) + b.minutes; baselineMinutes += b.minutes; + } + } + + const people = [...per.values()]; + const named = people.filter(v => !anon(v.key, v.login)); + const board = (f, n = top) => named.map(v => ({ key: v.key, login: v.login, name: v.name, n: f(v) })).filter(x => x.n > 0).sort((a, b) => b.n - a.n).slice(0, n); + // Twitch's daily export (twitchcsv.js). Things we also count ourselves (messages, watch time, follows, streamed days) + // come from it only for days before our own counting started (cutoff); things only Twitch measures (unique / + // engaged viewers, clips, live views, revenue, average + peak viewers) come from it for every day. + const hist = { days: 0, streamedDays: 0, minutesStreamed: 0, minutesWatched: 0, messages: 0, follows: 0, viewerMinutes: 0, + maxViewers: 0, uniqueSum: 0, newEngaged: 0, returningEngaged: 0, clips: 0, clipViews: 0, liveViews: 0, revenue: 0, revenueByType: {} }; + const cutoff = d().prepare("SELECT MIN(day) d FROM stat_day WHERE kind IN ('message', 'watch')").get().d || '9999-12-31'; + let dailyRows = []; + if (r.p !== 'stream' && synced('tw_daily')) { + dailyRows = d().prepare(`SELECT * FROM tw_daily ${r.from ? 'WHERE day BETWEEN ? AND ?' : ''} ORDER BY day`).all(...(r.from ? [r.from, r.to] : [])); + for (const x of dailyRows) { + const before = x.day < cutoff; + if (before) { + hist.messages += x.chat_messages; hist.minutesWatched += x.minutes_watched; hist.follows += x.follows; + if (x.minutes_streamed > 0) { hist.streamedDays++; hist.minutesStreamed += x.minutes_streamed; } + } + if (x.minutes_streamed > 0) { hist.viewerMinutes += x.avg_viewers * x.minutes_streamed; hist.days++; hist.uniqueSum += x.unique_viewers; } + hist.maxViewers = Math.max(hist.maxViewers, x.max_viewers); + hist.newEngaged += x.new_engaged; hist.returningEngaged += x.returning_engaged; + hist.clips += x.clips_created; hist.clipViews += x.clip_views; hist.liveViews += x.live_views; + if (revenue) { + hist.revenue += x.revenue; + for (const [k, v] of Object.entries(JSON.parse(x.revenue_json || '{}'))) hist.revenueByType[k] = (hist.revenueByType[k] || 0) + v; + } + } + t.messages += hist.messages; + if (synced('tw_follower') && r.p !== 'all') { // from the cutoff on: the follower list (CSV before it) + const [a, b] = followWindow; + const from = a > cutoff ? a : cutoff; + t.follows = from <= b ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE followed_at BETWEEN ? AND ?').get(from, b).n : 0; + } else if (synced('tw_follower')) t.follows = d().prepare('SELECT COUNT(*) n FROM tw_follower').get().n; + if (!synced('tw_follower') || r.p !== 'all') t.follows += hist.follows; // all time: the follower list already counts everyone + } + + let bitsBoard = board(v => v.bits), bitsSource = 'heystreamer'; + if (r.p === 'all' && synced('tw_bits')) { + bitsSource = 'twitch'; + bitsBoard = d().prepare('SELECT user_id, user_login, user_name, score FROM tw_bits ORDER BY score DESC').all() + .filter(x => !hide.has(String(x.user_login).toLowerCase()) && !anon(x.user_id, x.user_login)) + .slice(0, top).map(x => ({ key: x.user_id, login: x.user_login, name: x.user_name, n: x.score })); + t.bits = Math.max(t.bits, d().prepare('SELECT COALESCE(SUM(score), 0) n FROM tw_bits').get().n); + } + const meta = new Map(d().prepare('SELECT * FROM stat_emote').all().map(e => [e.emote, e])); + + // the channel's own emotes (Twitch list) with how often they were used in chat in this range + let channelEmotes = []; + if (synced('tw_emote')) { + const byName = new Map(); + for (const [name, uses] of emotes) byName.set(name, uses); + const idToNames = new Map(); + for (const e of meta.values()) if (e.emote_id) idToNames.set(e.emote_id, [...(idToNames.get(e.emote_id) || []), e.emote]); + channelEmotes = d().prepare('SELECT * FROM tw_emote').all().map(e => { + const names = new Set([e.name, ...(idToNames.get(e.id) || [])]); + return { id: e.id, name: e.name, image: e.image, tier: e.tier, type: e.emote_type, gone: !!e.gone, + uses: [...names].reduce((n, x) => n + (byName.get(x) || 0), 0) }; + }).filter(e => !e.gone || e.uses).sort((a, b) => b.uses - a.uses || a.name.localeCompare(b.name)); + } + const sorted = (m, n) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, n); + + // streams in this range, with their own numbers + const streamRows = r.p === 'stream' ? [r.stream] + : streams().filter(s => !r.from || (s.started_at.slice(0, 10) >= r.from && s.started_at.slice(0, 10) <= r.to)); + const perStream = new Map(); + if (streamRows.length) { + const ids = streamRows.map(s => s.id); + for (const x of d().prepare(`SELECT stream_id, kind, user_key, SUM(uses) uses FROM stat_day WHERE stream_id IN (${ids.map(() => '?').join(',')}) + AND kind IN ('message', 'watch') GROUP BY stream_id, kind, user_key`).all(...ids)) { + if (hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase())) continue; + const s = perStream.get(x.stream_id) || { messages: 0, chatters: 0, viewers: 0 }; + if (x.kind === 'message') { s.messages += x.uses; s.chatters++; } else s.viewers++; + perStream.set(x.stream_id, s); + } + } + const checkins = streamRows.length ? d().prepare(`SELECT COUNT(*) n FROM stream_checkin WHERE stream_id IN (${streamRows.map(() => '?').join(',')})`).get(...streamRows.map(s => s.id)).n : 0; + + // activity over the range: per day (week / month), per month (year / all); none for one stream + let series = null; + if (r.p !== 'stream') { + const byMonth = r.p === 'year' || r.p === 'all'; + const buckets = new Map(); + if (r.from && !byMonth) for (let x = Date.parse(r.from + 'T00:00:00Z'); iso(x) <= r.to; x += 864e5) buckets.set(iso(x), { messages: 0, ticks: 0 }); + if (r.p === 'year') for (let m = 1; m <= 12; m++) buckets.set(`${r.from.slice(0, 4)}-${String(m).padStart(2, '0')}`, { messages: 0, ticks: 0 }); + const blank = () => ({ messages: 0, ticks: 0, follows: 0 }); + for (const b of buckets.values()) b.follows = 0; + const fFrom = synced('tw_daily') ? (r.from && r.from > cutoff ? r.from : cutoff) : (r.from || '0000-00-00'); + if (synced('tw_follower')) for (const x of d().prepare(`SELECT substr(followed_at, 1, 10) day, COUNT(*) n FROM tw_follower + WHERE followed_at >= ? ${r.from ? 'AND followed_at <= ?' : ''} GROUP BY day`).all(...[fFrom, ...(r.from ? [r.to + 'T23:59:59.999Z'] : [])])) { + const k = byMonth ? x.day.slice(0, 7) : x.day; + const b = buckets.get(k) || blank(); b.follows += x.n; buckets.set(k, b); + } + for (const x of dailyRows) { + const k = byMonth ? x.day.slice(0, 7) : x.day; + const b = buckets.get(k) || blank(); + if (x.day < cutoff) { + b.messages += x.chat_messages; b.ticks += x.minutes_watched / 5; b.streamMin = (b.streamMin || 0) + x.minutes_streamed; + b.follows += x.follows; + } + if (x.minutes_streamed > 0) { b.vMin = (b.vMin || 0) + x.avg_viewers * x.minutes_streamed; b.vW = (b.vW || 0) + x.minutes_streamed; } + buckets.set(k, b); + } + for (const x of d().prepare(`SELECT day, user_key, kind, SUM(uses) uses FROM stat_day WHERE ${w.sql} AND kind IN ('message', 'watch') GROUP BY day, user_key, kind`).all(...w.args)) { + if (hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase())) continue; + const k = byMonth ? x.day.slice(0, 7) : x.day; + const b = buckets.get(k) || blank(); + if (x.kind === 'message') b.messages += x.uses; else b.ticks += x.uses; + buckets.set(k, b); + } + for (const st of (r.p === 'stream' ? [] : streams())) { + const sd = st.started_at.slice(0, 10); + if (sd < cutoff || (r.from && (sd < r.from || sd > r.to))) continue; + const k = byMonth ? sd.slice(0, 7) : sd, b = buckets.get(k) || blank(); + const mins = (Date.parse(st.ended_at || new Date().toISOString()) - Date.parse(st.started_at)) / 60000; + b.streamMin = (b.streamMin || 0) + mins; + buckets.set(k, b); + } + if (r.p === 'all' && buckets.size) { // every month from the first one with data until now, gaps included + const ks = [...buckets.keys()].sort(); + for (let [y, m] = ks[0].split('-').map(Number), end = new Date().toISOString().slice(0, 7); ; m++) { + if (m > 12) { y++; m = 1; } + const k = `${y}-${String(m).padStart(2, '0')}`; + if (k > end) break; + if (!buckets.has(k)) buckets.set(k, blank()); + } + } + const keys = [...buckets.keys()].sort(); + series = { unit: byMonth ? 'month' : 'day', rows: keys.map(k => ({ key: k, label: byMonth ? `${MONTHS[+k.slice(5, 7) - 1].slice(0, 3)} ${k.slice(2, 4)}` : k.slice(5), + messages: buckets.get(k).messages, watchHours: +(buckets.get(k).ticks * 5 / 60).toFixed(1), follows: buckets.get(k).follows || 0, + streamHours: +((buckets.get(k).streamMin || 0) / 60).toFixed(1), + avgViewers: buckets.get(k).vW ? +(buckets.get(k).vMin / buckets.get(k).vW).toFixed(1) : 0 })) }; + } + + // games: time per category from the title / category changes (HeyStreamer-era streams; Twitch keeps no history of it) + const gameMin = new Map(), gamesOf = new Map(); + if (hasT('stream_change')) { + const prevQ = d().prepare('SELECT at, game FROM stream_change WHERE at < ? ORDER BY at DESC LIMIT 1'); + const inQ = d().prepare('SELECT at, game FROM stream_change WHERE at BETWEEN ? AND ? ORDER BY at'); + for (const st of streamRows) { + const end = st.ended_at || new Date().toISOString(); + const before = prevQ.get(st.started_at); + const segs = [...(before ? [{ at: st.started_at, game: before.game }] : []), ...inQ.all(st.started_at, end)]; + if (!segs.length && st.game) segs.push({ at: st.started_at, game: st.game }); + const list = []; + segs.forEach((c, i) => { + const a = Date.parse(c.at < st.started_at ? st.started_at : c.at), b = Date.parse(segs[i + 1]?.at || end); + const mins = Math.max(0, (b - a) / 60000); + if (!c.game || mins < 1) return; + gameMin.set(c.game, (gameMin.get(c.game) || 0) + mins); + if (!list.includes(c.game)) list.push(c.game); + }); + gamesOf.set(st.id, list); + } + } + + // community: who raided, who supported (named only when not hidden / opted out) + const showName = (key, login) => !hide.has(String(login || '').toLowerCase()) && !anon(key, login); + // (deliberately no list of new followers / first-time chatters: nobody is singled out just for showing up) + const community = { raiders: [], supporters: [] }; + for (const x of rows) { + const v = per.get(x.user_key); if (!v || !showName(v.key, v.login)) continue; + if (x.kind === 'action:raid') community.raiders.push({ login: v.login, name: v.name, raids: x.uses, viewers: x.amount }); + } + community.raiders.sort((a, b) => b.viewers - a.viewers); + community.supporters = people.filter(v => showName(v.key, v.login) && (v.bits || v.subs || v.gifts || v.tips)) + .map(v => ({ login: v.login, name: v.name, bits: v.bits, subs: v.subs, gifts: v.gifts, tips: v.tips })) + .sort((a, b) => (b.bits / 100 + (b.subs + b.gifts) * 5 + b.tips) - (a.bits / 100 + (a.subs + a.gifts) * 5 + a.tips)); + + // one stream: viewer count every 5 minutes + title / category changes (with what was set when it started) + let timeline = null; + if (r.p === 'stream' && hasT('stream_viewers')) { + const st = r.stream, end = st.ended_at || new Date().toISOString(); + const samples = d().prepare('SELECT at, viewers FROM stream_viewers WHERE stream_id = ? ORDER BY at').all(st.id); + const before = d().prepare('SELECT at, title, game FROM stream_change WHERE at < ? ORDER BY at DESC LIMIT 1').get(st.started_at); + const during = d().prepare('SELECT at, title, game FROM stream_change WHERE at BETWEEN ? AND ? ORDER BY at').all(st.started_at, end); + const changes = [...(before ? [{ ...before, at: st.started_at, start: true }] : []), ...during]; + timeline = { start: st.started_at, end, samples, changes }; + } + // across streams: peak and average viewers (streams with samples only) + const sampled = streamRows.filter(x => x.viewer_samples); + let peak = sampled.length ? Math.max(...sampled.map(x => x.peak_viewers || 0)) : null; + let avg = sampled.length ? Math.round(sampled.reduce((a, x) => a + x.viewer_sum / x.viewer_samples, 0) / sampled.length) : null; + if (hist.days) { // Twitch's daily numbers cover every streamed day (weighted by minutes streamed) + peak = Math.max(peak || 0, hist.maxViewers); + avg = Math.round(hist.viewerMinutes / dailyRows.reduce((a, x) => a + (x.minutes_streamed > 0 ? x.minutes_streamed : 0), 0) * 10) / 10; + } + const ownMinutes = streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff) + .reduce((a, x) => a + (Date.parse(x.ended_at || new Date().toISOString()) - Date.parse(x.started_at)) / 60000, 0); + const followers = synced('tw_follower') ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE unfollowed_at IS NULL').get().n : null; + const user = db.getPrimaryUser(); + const subsNow = synced('tw_sub') ? d().prepare('SELECT COUNT(*) n FROM tw_sub WHERE user_id != ?').get(String(user?.twitch_id || '')).n : null; + + return { + range: r, timeline, channelEmotes, bitsSource, community, + games: [...gameMin.entries()].map(([game, minutes]) => ({ game, minutes: Math.round(minutes) })).sort((a, b) => b.minutes - a.minutes), + channel: { followers, subsNow, peak, avg }, + twitch: hist.days || dailyRows.length ? { + cutoff, streamedDays: hist.streamedDays, hoursStreamed: Math.round((hist.minutesStreamed + ownMinutes) / 60), + uniquePerDay: hist.days ? Math.round(hist.uniqueSum / hist.days) : null, newEngaged: hist.newEngaged, returningEngaged: hist.returningEngaged, + clips: hist.clips, clipViews: hist.clipViews, liveViews: hist.liveViews, + revenue: revenue ? +hist.revenue.toFixed(2) : null, + revenueByType: revenue ? Object.entries(hist.revenueByType).filter(([, v]) => v).map(([k, v]) => [k, +v.toFixed(2)]) : null, + } : null, + totals: { + ...t, + chatters: people.filter(v => v.messages).length, + viewers: people.filter(v => v.ticks || v.extraMinutes).length, + // watch time before our counting: Twitch's channel total if imported (then the StreamElements per-viewer + // minutes only feed the leaderboards), else the StreamElements baseline + watchHours: Math.round((t.ticks * 5 + (hist.minutesWatched ? hist.minutesWatched : baselineMinutes)) / 60), + baselineHours: hist.minutesWatched ? 0 : Math.round(baselineMinutes / 60), + historyWatchHours: Math.round(hist.minutesWatched / 60), + hoursStreamed: Math.round((hist.minutesStreamed + streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff || !hist.streamedDays) + .reduce((a, x) => a + (Date.parse(x.ended_at || new Date().toISOString()) - Date.parse(x.started_at)) / 60000, 0)) / 60), + viewersFromBaseline: people.filter(v => !v.ticks && v.extraMinutes).length, + streams: streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff || !hist.streamedDays).length + hist.streamedDays, checkins, + tipsByUnit: [...tipsByUnit.entries()].map(([unit, amount]) => ({ unit, amount: +amount.toFixed(2) })), + }, + streams: streamRows.map(s => { + const n = perStream.get(s.id) || {}; + const mins = Math.round((Date.parse(s.ended_at || new Date().toISOString()) - Date.parse(s.started_at)) / 60000); + return { id: s.id, started_at: s.started_at, ended_at: s.ended_at, live: !s.ended_at, title: s.title || '', game: s.game || '', + minutes: mins, peak: s.peak_viewers || null, source: s.source || 'live', games: gamesOf.get(s.id) || (s.game ? [s.game] : []), avg: s.viewer_samples ? Math.round(s.viewer_sum / s.viewer_samples) : null, + messages: n.messages || 0, chatters: n.chatters || 0, viewers: n.viewers || 0 }; + }), + boards: { + chat: board(v => v.messages), + watch: board(v => v.ticks * 5 + (v.extraMinutes || 0)), + bits: bitsBoard, + subs: board(v => v.subs + v.gifts), + channelPoints: board(v => v.points), + }, + emotes: sorted(emotes, 24).map(([emote, uses]) => ({ emote, uses, source: meta.get(emote)?.source || null, id: meta.get(emote)?.emote_id || null })), + commands: sorted(commands, 24).map(([command, uses]) => ({ command, uses })), + rewards: sorted(rewards, 15).map(([item, uses]) => ({ item, uses })), + series, + }; +} + +module.exports = { init, add, emoteSeen, setOptout, optedOut, isOptedOut, forgetUser, parseRange, rangeQuery, streams, summary, backfill }; diff --git a/src/points.js b/src/points.js new file mode 100644 index 0000000..9dd83d2 --- /dev/null +++ b/src/points.js @@ -0,0 +1,81 @@ +// 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'); + +const VALUE = { + watchTick: 5, // per 5-minute watch tick + chat: 10, // per points-eligible message (max 1 per 5 min, counted in chatlog.js) + checkin: 25, // first message of a stream + intro: 50, // first message ever on the channel + follow: 50, // once + bit: 1, // cheers, Power-ups, Custom Power-ups + per100ChannelPoints: 1, + subMonth: { 'Tier 1': 500, Prime: 500, 'Tier 2': 1000, 'Tier 3': 2500 }, + tipPerUnit: 100, // per 1 EUR (or whatever currency the tip was in) + raid: 100, // flat, no reward for raid size + streakPer: 5, streakMax: 100, +}; + +// 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' }, +]; +const levelOf = watchMinutes => [...LEVELS].reverse().find(l => watchMinutes >= l.minHours * 60); + +const has = t => !!db.raw().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t); +const all = (sql, ...a) => db.raw().prepare(sql).all(...a); + +// -> Map key -> viewer { key, user_id, login, name, parts: {watch, chat, ...}, total, level } +// key = Twitch user id; viewers known only by name (tips, watch streaks) are merged by login when possible +function everyone() { + const v = new Map(), byLogin = new Map(); + const get = (id, login, name) => { + let key = id ? String(id) : null; + if (!key && login && byLogin.has(login)) key = byLogin.get(login); + if (!key) key = `name:${login}`; + if (!v.has(key)) v.set(key, { key, user_id: id || null, login, name: name || login, parts: {}, total: 0 }); + const x = v.get(key); + if (login) { byLogin.set(login, key); x.login = x.login || login; } + if (name) x.name = name; + return x; + }; + const add = (x, part, pts) => { if (!pts) return; x.parts[part] = (x.parts[part] || 0) + pts; x.total += pts; }; + + if (has('chat_user')) for (const r of all('SELECT user_id, user_login, user_name, scored, intro FROM chat_user')) { + const x = get(r.user_id, r.user_login, r.user_name); + add(x, 'chat', (r.scored || 0) * VALUE.chat); add(x, 'first message', r.intro ? VALUE.intro : 0); + } + if (has('watch_user')) for (const r of all('SELECT user_id, user_login, user_name, ticks FROM watch_user')) { + const x = get(r.user_id, r.user_login, r.user_name); + x.watchMinutes = (x.watchMinutes || 0) + (r.ticks || 0) * 5; + add(x, 'watching', (r.ticks || 0) * VALUE.watchTick); + } + // 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; + x.watchMinutes = (x.watchMinutes || 0) + r.minutes; + add(x, 'watching (StreamElements)', Math.floor(r.minutes / 5) * VALUE.watchTick); + } + if (has('stream_checkin')) for (const r of all('SELECT user_id, COUNT(*) n FROM stream_checkin GROUP BY user_id')) { + add(get(r.user_id, null, null), 'check-ins', r.n * VALUE.checkin); + } + if (has('chat_action')) for (const r of all('SELECT * FROM chat_action ORDER BY user_key LIKE \'name:%\'')) { + const id = r.user_key.startsWith('name:') ? null : r.user_key; + const x = get(id, r.user_login, r.user_name); + switch (r.action) { + case 'follow': add(x, 'follow', VALUE.follow); break; + case 'bits': case 'power_up': case 'custom_power_up': add(x, 'bits', Math.round(r.amount * VALUE.bit)); break; + case 'channel_points': case 'auto_reward': add(x, 'channel points', Math.floor(r.amount / 100) * VALUE.per100ChannelPoints); break; + case 'sub': add(x, 'subs', Math.round(r.amount * (VALUE.subMonth[r.item] || VALUE.subMonth['Tier 1']))); break; + case 'gift_sub': add(x, 'gift subs', Math.round(r.amount * (VALUE.subMonth[r.item] || VALUE.subMonth['Tier 1']))); break; + case 'tip': add(x, 'tips', Math.round(r.amount * VALUE.tipPerUnit)); break; + case 'raid': add(x, 'raids', r.uses * VALUE.raid); break; + case 'watch_streak': add(x, 'watch streak', Math.min(VALUE.streakMax, r.amount * VALUE.streakPer)); break; + } + } + for (const x of v.values()) x.level = levelOf(x.watchMinutes || 0); + return v; +} + +module.exports = { VALUE, LEVELS, levelOf, everyone }; diff --git a/src/redeems-seed.json b/src/redeems-seed.json new file mode 100644 index 0000000..82af76e --- /dev/null +++ b/src/redeems-seed.json @@ -0,0 +1,41 @@ +{ + "_comment": "Example first-run defaults for the Redeems page: one silent variation per Twitch built-in reward / Power-up. A channel's own seed goes in src/redeems-seed.json (not in git; used instead of this file when present). Loaded only when the reward_variations table is empty; after that the dashboard is the source of truth. sound = URL under /public ('' = silent), art = cassette sticker URL ('' = the theme's default sticker).", + "variations": [ + { + "kind": "auto_reward", + "key": "send_highlighted_message", + "title": "Highlight my message", + "name": "Highlighted", + "rarity": "common", + "sound": "", + "art": "" + }, + { + "kind": "power_up", + "key": "message_effect", + "title": "Power-up: Message Effect", + "name": "Message effect", + "rarity": "common", + "sound": "", + "art": "" + }, + { + "kind": "power_up", + "key": "celebration", + "title": "Power-up: On-Screen Celebration", + "name": "Celebration", + "rarity": "common", + "sound": "", + "art": "" + }, + { + "kind": "power_up", + "key": "gigantify_an_emote", + "title": "Power-up: Gigantify an Emote", + "name": "Giant emote", + "rarity": "common", + "sound": "", + "art": "" + } + ] +} diff --git a/src/redeems.js b/src/redeems.js new file mode 100644 index 0000000..b7c9d08 --- /dev/null +++ b/src/redeems.js @@ -0,0 +1,185 @@ +// Channel point rewards, built-in channel point rewards and bits Power-ups. +// Each trigger (kind + key) has variations; one enabled variation is picked at random, +// weighted by rarity (like Twitch alert variations), and played as a polaroid or sound-only alert. +const db = require('./db'); +const alerts = require('./alerts'); +const dispatch = require('./dispatch'); +const tts = require('./tts'); + +// relative weight per rarity (Twitch does not publish its numbers; tune here). +// chance of a variation = its weight / sum of the weights of the trigger's ENABLED variations +const RARITY = { + common: { label: 'Common', weight: 50 }, + uncommon: { label: 'Uncommon', weight: 25 }, + rare: { label: 'Rare', weight: 12 }, + ultra_rare: { label: 'Ultra Rare', weight: 3 }, +}; + +// built-in (automatic) channel point rewards, channel.channel_points_automatic_reward_redemption.add v2 +const AUTO_REWARDS = { + send_highlighted_message: 'Highlight my message', + single_message_bypass_sub_mode: 'Send a message in sub-only mode', + random_sub_emote_unlock: 'Unlock a random sub emote', + chosen_sub_emote_unlock: 'Choose an emote to unlock', + chosen_modified_sub_emote_unlock: 'Modify a single emote', +}; + +// bits Power-ups, channel.bits.use with type = power_up +const POWER_UPS = { + message_effect: 'Power-up: Message Effect', + celebration: 'Power-up: On-Screen Celebration', + gigantify_an_emote: 'Power-up: Gigantify an Emote', +}; + +// Custom Power-ups (bits, made by the streamer on Twitch): kind 'custom_power_up', key = power-up id + +// how a trigger is drawn on the overlay (everything else: cassette tape) +const STYLE = { + 'power_up:gigantify_an_emote': 'emote', // the viewer's emote, giant + 'power_up:celebration': 'emote_rain', // copies of the emote bouncing around the screen + 'auto_reward:send_highlighted_message': 'message', // big taped paper note with the message + 'power_up:message_effect': 'message', // same as highlight +}; +const LINE = { emote: 'gigantified an emote!', emote_rain: 'is celebrating!', message: 'highlighted:', tts: 'says:' }; +const emoteUrl = id => id ? `https://static-cdn.jtvnw.net/emoticons/v2/${encodeURIComponent(id)}/default/dark/3.0` : null; + +function pick(variations) { + const pool = variations.filter(v => v.enabled); + const total = pool.reduce((s, v) => s + (RARITY[v.rarity]?.weight || 1), 0); + let r = Math.random() * total; + for (const v of pool) { r -= RARITY[v.rarity]?.weight || 1; if (r < 0) return v; } + return pool[pool.length - 1] || null; +} + +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) + // 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' && 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, + }; +} + +// TTS: clean the viewer's text, speak it with the variation's saved voice, attach { tts, tts_ms }. +// Never throws: on any problem the alert still goes out, just without speech. +async function addSpeech(v, alert) { + try { + const voice = db.getTtsVoice(v.tts_voice_id); + if (!voice || !alert.input) return; + const s = db.getSettings(); + const { text, blocked } = tts.prepareViewerText(alert.input, { maxChars: s.tts_max_chars, blocklist: s.tts_blocklist }); + if (blocked) { + console.log(`[tts] blocked message from ${alert.user}`); + alert.input = '(message removed)'; + return; + } + alert.input = text; // the note shows what is read + if (!text) return; + const say = s.tts_say_name && alert.user ? `${alert.user} says: ${text}` : text; + const out = await tts.synth(voice.config, say); + alert.tts = out.url; + alert.tts_ms = out.durationMs; + alert.tts_env = await tts.loudness(out.file); // word timing on the overlay + alert.tts_prefix = say === text ? 0 : 2; // words spoken before the message (" says:") + } catch (e) { + console.warn(`[tts] ${alert.user}: ${e.message}`); + } +} + +// Twitch icons of channel point rewards (custom images only) and Custom Power-ups. +// alert.icon -> top-left sticker on the cassette (cassette.js) and the video box (video.js). +// Cached; reloaded every 10 min, or (at most every 30 s) when an unknown trigger comes in. +const icons = new Map(); +let iconsAt = 0, iconsLoading = null; +const bestImg = i => (i && (i.url_4x || i.url_2x || i.url_1x)) || null; +async function loadIcons() { + const twitch = require('./twitch'); + const u = twitch.getUser(); + if (!u) return; + const next = new Map(); + try { + const r = await twitch.helix(`/channel_points/custom_rewards?broadcaster_id=${u.twitch_id}`); + if (r.ok) for (const x of (await r.json()).data || []) { const img = bestImg(x.image); if (img) next.set(`reward|${x.id}`, img); } + } catch (e) { console.warn('[redeems] reward icons:', e.message); } + try { + const r = await twitch.helix(`/bits/custom_power_ups?broadcaster_id=${u.twitch_id}`); + if (r.ok) for (const x of (await r.json()).data || []) { + const img = bestImg(x.image) || bestImg(x.icon) || bestImg(x.default_image) || x.image_url || null; + if (img) next.set(`custom_power_up|${x.id}`, img); + } + } catch (e) { console.warn('[redeems] power-up icons:', e.message); } + if (next.size || !icons.size) { icons.clear(); for (const [k, v] of next) icons.set(k, v); } + iconsAt = Date.now(); +} +async function iconFor(kind, key) { + if (kind !== 'reward' && kind !== 'custom_power_up') return null; + const age = Date.now() - iconsAt; + if (age > 10 * 60000 || (!icons.has(`${kind}|${key}`) && age > 30000)) { + iconsLoading = iconsLoading || loadIcons().finally(() => { iconsLoading = null; }); + await Promise.race([iconsLoading, new Promise(r => setTimeout(r, 2000))]); // never hold an alert long + } + return icons.get(`${kind}|${key}`) || null; +} + +// legacy action event type for the actions system / activity log +const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up', custom_power_up: 'custom_power_up' }; + +// A redemption arrived from Twitch. +function handle(kind, key, title, { user, input, emote, bits }, raw) { + if (title) db.renameTrigger(kind, key, title); + const v = pick(db.getVariationsFor(kind, key)); + if (!v) { + // nothing configured (or all off): still log it and run legacy actions + dispatch.dispatchEvent(LEGACY[kind], key, user, raw); + return null; + } + const alert = toAlert(v, { user, input, emote, bits }); + const ready = iconFor(kind, key).then(icon => { alert.icon = icon; }); + if (v.tts_voice_id && input && !v.video) ready.then(() => addSpeech(v, alert)).then(() => alerts.send(alert, raw)); // speech first, then the alert + else ready.then(() => alerts.send(alert, raw)); + return alert; +} + +// Dashboard Replay of an old activity row that has no stored alert: a fresh pick for the trigger, +// with the viewer's original name and text. Resolves to the alert, or null if nothing is configured. +async function rebuild(kind, key, { user, input, emote, bits }) { + const v = pick(db.getVariationsFor(kind, key)); + if (!v) return null; + const alert = toAlert(v, { user, input, emote, bits }); + alert.icon = await iconFor(kind, key); + if (v.tts_voice_id && input && !v.video) await addSpeech(v, alert); + return alert; +} + +// Replay of a stored TTS alert whose mp3 was pruned: speak it again with the same variation's voice. +async function respeak(alert) { + const v = alert.vid && db.getVariation(alert.vid); + for (const k of ['tts', 'tts_ms', 'tts_env', 'tts_prefix']) delete alert[k]; + if (v && v.tts_voice_id && alert.input) await addSpeech(v, alert); + return alert; +} + +// Dashboard test: one specific variation, or a random pick for the whole trigger. +function test({ id, kind, key }) { + const v = id ? db.getVariation(id) : pick(db.getVariationsFor(kind, key)); + if (!v) return false; + const input = v.tts_voice_id ? 'Hydrate check! Also, nice shot, I was totally not camping that container.' + : ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!' + : v.kind === 'reward' ? 'test input' : null; + const alert = toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null, + bits: v.kind === 'custom_power_up' ? 50 : null }); // 25 = Kappa + const ready = iconFor(v.kind, v.key).then(icon => { alert.icon = icon; }); + if (v.tts_voice_id && !v.video) ready.then(() => addSpeech(v, alert)).then(() => alerts.sendTestAlert(alert)); + else ready.then(() => alerts.sendTestAlert(alert)); + return true; +} + +module.exports = { RARITY, AUTO_REWARDS, POWER_UPS, STYLE, LEGACY, pick, handle, test, rebuild, respeak }; diff --git a/src/routers/actions.js b/src/routers/actions.js deleted file mode 100644 index 1d32b1b..0000000 --- a/src/routers/actions.js +++ /dev/null @@ -1,45 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const db = require('../db'); -const dispatch = require('../dispatch'); -const { resetCooldown } = require('../cooldowns'); - -router.get('/', (req, res) => { - const actions = db.getAllActions(); - const media = db.getAllMedia(); - res.render('actions', { actions, media }); -}); - -router.post('/', (req, res) => { - const { name, event_type, event_detail, action_type, media_file_id, alert_text, cooldown_seconds } = req.body; - db.createAction({ - name, - event_type, - event_detail: event_detail || null, - action_type, - media_file_id: media_file_id ? parseInt(media_file_id) : null, - alert_text: alert_text || null, - cooldown_seconds: parseInt(cooldown_seconds) || 0, - }); - res.redirect('/actions'); -}); - -router.post('/:id/test', (req, res) => { - const action = db.getAction(parseInt(req.params.id)); - if (!action) return res.status(404).send('Not found'); - resetCooldown(action.id); - dispatch.dispatchEvent(action.event_type, action.event_detail, 'test'); - res.redirect('/actions'); -}); - -router.post('/:id/toggle', (req, res) => { - db.toggleAction(parseInt(req.params.id)); - res.redirect('/actions'); -}); - -router.post('/:id/delete', (req, res) => { - db.deleteAction(parseInt(req.params.id)); - res.redirect('/actions'); -}); - -module.exports = router; diff --git a/src/routers/alerts.js b/src/routers/alerts.js new file mode 100644 index 0000000..5946a74 --- /dev/null +++ b/src/routers/alerts.js @@ -0,0 +1,52 @@ +const express = require('express'); +const router = express.Router(); +const alerts = require('../alerts'); +const twitch = require('../twitch'); +const ws = require('../ws'); + +// POST /alerts/test/:key: send a sample alert to every connected overlay (dashboard test buttons) +router.post('/test/:key', (req, res) => { + const ok = alerts.sendTest(req.params.key); + res.status(ok ? 200 : 404).json({ ok }); +}); + +// POST /alerts/skip: stop the alert on screen right now (e.g. a TTS message), the queue carries on +router.post('/skip', (req, res) => { + ws.broadcast({ type: 'alert_skip' }); + console.log('[alerts] skip requested from the dashboard'); + res.json({ ok: true }); +}); + +// POST /alerts/raid/start {target}: start a raid on Twitch and show the send-off card until it happens +router.post('/raid/start', async (req, res) => { + const me = twitch.getUser(); + const login = String(req.body.target || '').trim().replace(/^@/, '').toLowerCase(); + if (!me) return res.status(400).json({ ok: false, error: 'not connected to Twitch' }); + if (!/^[a-z0-9_]{2,25}$/.test(login)) return res.status(400).json({ ok: false, error: 'invalid channel name' }); + try { + const u = await twitch.helix(`/users?login=${encodeURIComponent(login)}`); + const target = u.ok ? (await u.json()).data?.[0] : null; + if (!target) return res.status(404).json({ ok: false, error: 'channel not found' }); + const r = await twitch.helix(`/raids?from_broadcaster_id=${me.twitch_id}&to_broadcaster_id=${target.id}`, { method: 'POST' }); + if (!r.ok) { + const body = await r.json().catch(() => ({})); + return res.status(r.status).json({ ok: false, error: body.message || `Twitch said ${r.status}` }); + } + let viewers = null; + const s = await twitch.helix(`/streams?user_id=${me.twitch_id}`); + if (s.ok) viewers = (await s.json()).data?.[0]?.viewer_count ?? null; + alerts.raidStarted({ target: target.display_name, avatar: target.profile_image_url || null, viewers }); + res.json({ ok: true, target: target.display_name, viewers }); + } catch (e) { res.status(500).json({ ok: false, error: e.message }); } +}); + +// POST /alerts/raid/cancel: cancel the pending raid on Twitch and remove the card +router.post('/raid/cancel', async (req, res) => { + const me = twitch.getUser(); + if (!me) return res.status(400).json({ ok: false, error: 'not connected to Twitch' }); + const r = await twitch.helix(`/raids?broadcaster_id=${me.twitch_id}`, { method: 'DELETE' }).catch(e => ({ ok: false, status: 500, e })); + alerts.raidCancelled(); + res.status(r.ok || r.status === 404 ? 200 : r.status).json({ ok: r.ok || r.status === 404 }); +}); + +module.exports = router; diff --git a/src/routers/alertsetup.js b/src/routers/alertsetup.js new file mode 100644 index 0000000..a216f6d --- /dev/null +++ b/src/routers/alertsetup.js @@ -0,0 +1,40 @@ +// Actions → Alerts: how follows, subs, gifts, raids, bits, tips and the Hype Train look and sound (src/theme.js). +const express = require('express'); +const router = express.Router(); +const db = require('../db'); +const ws = require('../ws'); +const theme = require('../theme'); +const library = require('../library'); + +router.get('/', (req, res) => { + const media = library.list(); + res.render('alerts_setup', { + theme: theme.get(), + images: media.filter(m => m.type === 'image'), + sounds: media.filter(m => m.type === 'audio'), + }); +}); + +// preview: the real overlay code with a button per alert; looks: the defaults, the optional styles, this channel's own +function previewThemes() { + const optional = theme.merge(theme.DEFAULT, { style: 'polaroid', redeemStyle: 'cassette', ttsStyle: 'letter' }); + return { + mine: { label: 'Your alerts', theme: theme.get() }, + defaults: { label: 'Defaults (Card)', theme: theme.DEFAULT }, + optional: { label: 'Polaroid / Cassette / Letter', theme: optional }, + }; +} +router.get('/preview', (req, res) => { + res.render('alerts_preview', { layout: false, base: '/alerts/', themes: previewThemes(), start: req.query.look || 'mine', samples: require('../alerts').SAMPLES }); +}); + +// whole theme as JSON from the editor +router.post('/', express.json({ limit: '200kb' }), (req, res) => { + try { + const t = theme.save(req.body || {}); + ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); // overlays use it at once + res.json({ ok: true, theme: t }); + } catch (e) { res.status(400).json({ ok: false, error: e.message }); } +}); + +module.exports = router; diff --git a/src/routers/auth.js b/src/routers/auth.js index 4168e65..7dc70bf 100644 --- a/src/routers/auth.js +++ b/src/routers/auth.js @@ -11,6 +11,13 @@ const SCOPES = [ 'bits:read', 'channel:read:redemptions', 'moderator:read:followers', + 'user:read:chat', // channel.chat.notification (sub/gift/raid details) + 'channel:read:polls', // channel.poll.* (poll card on the overlay) + '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) => { @@ -81,7 +88,7 @@ router.get('/callback', async (req, res) => { req.session.userId = user.id; req.session.user = { login: user.login, display_name: user.display_name }; - eventsub.start(tokens.access_token, twitchUser.id); + eventsub.start(user); console.log(`[auth] Login OK — ${twitchUser.login} (twitch_id:${twitchUser.id})`); res.redirect('/'); diff --git a/src/routers/dashboard.js b/src/routers/dashboard.js index b7b6fb8..a91b33c 100644 --- a/src/routers/dashboard.js +++ b/src/routers/dashboard.js @@ -1,11 +1,36 @@ const express = require('express'); const router = express.Router(); const db = require('../db'); +const eventsub = require('../eventsub'); +const alerts = require('../alerts'); +const streamelements = require('../streamelements'); +const activity = require('../activity'); +const ws = require('../ws'); router.get('/', (req, res) => { const logs = db.getActivityLog(50); const settings = db.getSettings(); - res.render('dashboard', { logs, settings }); + res.render('dashboard', { logs, activity, settings, eventsubStatus: eventsub.getStatus(), seStatus: streamelements.getStatus(), testKeys: alerts.TEST_KEYS }); +}); + +// Activity table only (dashboard Reload button / auto-refresh) +router.get('/activity', (req, res) => { + res.render('_activity', { layout: false, logs: db.getActivityLog(50), activity }); +}); + +// Replay: play a logged event on the overlay again (queued like a real alert; not logged again, no actions fired) +router.post('/activity/:id/replay', async (req, res) => { + const log = db.getActivity(parseInt(req.params.id, 10)); + if (!log) return res.status(404).json({ ok: false, error: 'not found' }); + try { + const msg = await activity.replayMessage(log); + if (!msg) return res.json({ ok: false, error: 'nothing to replay for this event' }); + ws.broadcast(msg); + res.json({ ok: true }); + } catch (e) { + console.error('[activity] replay:', e.message); + res.status(500).json({ ok: false, error: e.message }); + } }); module.exports = router; diff --git a/src/routers/ext.js b/src/routers/ext.js new file mode 100644 index 0000000..dd585df --- /dev/null +++ b/src/routers/ext.js @@ -0,0 +1,146 @@ +// HUDFX and Blerp inside our overlay (one OBS source, one audio fader, our CSS). +// +// Their overlay pages are fetched here and served from our domain with a few things injected: +// their own files and APIs still load from their sites +// page address their apps read the overlay id from location.pathname, so it is set back to theirs +// API redirect HUDFX's settings API refuses other sites (CORS), so those calls go through /hudfx-api here +// volume every