From 9e0ddb8182cc279b620de426c7137233319ca7d6 Mon Sep 17 00:00:00 2001 From: Bashynx Date: Fri, 20 Nov 2026 18:53:12 +0100 Subject: [PATCH 01/40] Update gitignore --- .env.example | 12 + .github/workflows/ci.yml | 36 + .gitignore | 13 + CLAUDE.md | 221 +++++ deploy.sh | 31 + package-lock.json | 1981 +++++++++++++++++++++++++++++++++++++ package.json | 24 + public/favicon.svg | 14 + public/vendor/tmi.min.js | 1 + src/app.js | 58 ++ src/cooldowns.js | 18 + src/db.js | 252 +++++ src/dispatch.js | 37 + src/eventsub.js | 118 +++ src/routers/actions.js | 45 + src/routers/auth.js | 101 ++ src/routers/dashboard.js | 11 + src/routers/layout.js | 37 + src/routers/media.js | 42 + src/routers/overlay.js | 18 + src/routers/settings.js | 48 + src/server.js | 21 + src/ws.js | 26 + views/actions.ejs | 88 ++ views/dashboard.ejs | 46 + views/layout.ejs | 39 + views/layout_editor.ejs | 73 ++ views/login.ejs | 34 + views/media.ejs | 53 + views/overlay.ejs | 199 ++++ views/overlay_preview.ejs | 87 ++ views/settings.ejs | 79 ++ 32 files changed, 3863 insertions(+) create mode 100644 .env.example create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100755 deploy.sh create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/favicon.svg create mode 100644 public/vendor/tmi.min.js create mode 100644 src/app.js create mode 100644 src/cooldowns.js create mode 100644 src/db.js create mode 100644 src/dispatch.js create mode 100644 src/eventsub.js create mode 100644 src/routers/actions.js create mode 100644 src/routers/auth.js create mode 100644 src/routers/dashboard.js create mode 100644 src/routers/layout.js create mode 100644 src/routers/media.js create mode 100644 src/routers/overlay.js create mode 100644 src/routers/settings.js create mode 100644 src/server.js create mode 100644 src/ws.js create mode 100644 views/actions.ejs create mode 100644 views/dashboard.ejs create mode 100644 views/layout.ejs create mode 100644 views/layout_editor.ejs create mode 100644 views/login.ejs create mode 100644 views/media.ejs create mode 100644 views/overlay.ejs create mode 100644 views/overlay_preview.ejs create mode 100644 views/settings.ejs diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..1158885 --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +TWITCH_CLIENT_ID=your_client_id +TWITCH_CLIENT_SECRET=your_client_secret + +# Local dev: +# TWITCH_REDIRECT_URI=http://localhost:3000/auth/callback +# Production: +TWITCH_REDIRECT_URI=https://overlay.example.com/auth/callback + +SECRET_KEY=change_this_to_a_random_string +APP_BASE_URL=https://overlay.example.com +DB_PATH=./heystreamer.db +PORT=3000 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..45ce070 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + check: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Syntax check + run: node --check src/app.js src/server.js src/db.js src/eventsub.js src/dispatch.js src/ws.js src/cooldowns.js src/routers/*.js + + - name: Import check + run: node -e "require('./src/app')" + env: + TWITCH_CLIENT_ID: ci-placeholder + TWITCH_CLIENT_SECRET: ci-placeholder + TWITCH_REDIRECT_URI: http://localhost:3000/auth/callback + SECRET_KEY: ci-test-secret-not-real + APP_BASE_URL: http://localhost:3000 + DB_PATH: ./test.db + PORT: 3000 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1e4073e --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +*.db +*.pyc +__pycache__/ +.env +.venv/ +venv/ +static/media/* +!static/media/.gitkeep + +node_modules/ +*.db-shm +*.db-wal +public/media/* diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..0f55387 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,221 @@ +# CLAUDE.md + +## Running the app + +```bash +npm install +npm run dev # development (nodemon) +npm start # production +``` + +Requires `.env` — copy from `.env.example`. Database is created automatically on startup (better-sqlite3 runs migrations on init). + +## Stack + +- **Node.js** · Express · EJS templates +- **better-sqlite3** — SQLite, synchronous, simple +- **ws** — WebSocket server for pushing alerts and settings to overlay clients +- **tmi.js** — Twitch IRC, runs in the browser on the overlay page (no server-side IRC). Self-hosted at `public/vendor/tmi.min.js` — the npm package has no browser build, downloaded from GitHub release +- **multer** — file uploads +- **uuid** — UUID generation +- **dotenv** — env vars +- **express-session** — session management (signed cookie) + +## Architecture + +``` +Twitch ──EventSub WebSocket──► src/eventsub.js ──► dispatch.js ──► ws.js ──► OBS overlay +Twitch ──IRC (tmi.js in browser) ────────────────────────────────────────► OBS overlay +Dashboard /settings save ────────────────────────────────────────────────► ws.js ──► OBS overlay (settings_update) +``` + +- `eventsub.js` opens a WebSocket to Twitch on startup, managed as a module-level singleton +- On notification it calls `dispatch.dispatchEvent()` +- `dispatch.dispatchEvent()` queries matching `event_actions` rows, checks cooldowns, logs to `activity_log`, calls `wss.broadcast()` +- `wss` (ws.js) holds all active WebSocket connections from `/ws/overlay` +- The overlay JS receives the broadcast and plays the action +- Chat messages come directly from tmi.js running in the browser — no server relay +- When settings are saved, the server broadcasts `{ type: 'settings_update', settings }` to all overlay clients — overlay updates `S` in place, no OBS reload needed + +## Project structure + +``` +src/ + app.js — Express app setup, middleware, router mounting + server.js — HTTP server + WebSocket server startup, EventSub init + db.js — better-sqlite3 setup, migrations, singleton helpers + eventsub.js — Twitch EventSub WebSocket client (module singleton) + dispatch.js — event → action resolution, cooldowns, DB log, broadcast + ws.js — WebSocket connection manager + cooldowns.js — in-memory cooldown tracking + routers/ + auth.js — /auth/* (Twitch OAuth) + dashboard.js — / (activity log, EventSub status) + overlay.js — /overlay/:uuid, /overlay/:uuid/preview, /ws/overlay + actions.js — /actions CRUD + media.js — /media upload/delete + layout.js — /layout editor + /layout/positions + settings.js — /settings +views/ + layout.ejs — base shell (nav, Pico CSS) + login.ejs + dashboard.ejs + overlay.ejs — OBS browser source + overlay_preview.ejs + layout_editor.ejs + actions.ejs + media.ejs + settings.ejs +public/ + media/ — uploaded files (gitignored) + vendor/ + tmi.min.js — self-hosted tmi.js browser build +``` + +## Key conventions + +**No passwords anywhere.** Auth is Twitch OAuth only. Session stored via `express-session` with a signed cookie. `req.session.userId` stores the DB user ID after login. + +**Singleton tables.** `settings` and `overlay_layout` each have one row (id=1). `db.getSettings()` and `db.getLayout()` create the row on first call if missing. + +**Cooldowns are in-memory.** `cooldowns.js` tracks `{ actionId: triggeredAt }`. Restarting the server resets all cooldowns. Intentional — DB cooldowns not worth the complexity. + +**Multiple actions per event.** `dispatchEvent()` loops through ALL matching `event_actions` rows and fires each one (subject to its own cooldown). No "first match wins". + +**Event matching rules:** +- `event_type="command"`: `event_detail` must match the command name (case-insensitive) +- `event_type="bits"`: if `event_detail` set, treat as minimum bits threshold +- `event_type="channel_points"`: `event_detail` is the reward ID; null matches any reward +- `event_type="sub"/"gift_sub"`: `event_detail` is tier ("1000", "2000", "3000"); null matches any +- `event_type="follow"/"raid"`: `event_detail` not used + +**UUID overlays.** `settings.overlay_id` is a UUID generated on first run. OBS browser source URL is `/overlay/:uuid`. Future multi-user support creates multiple settings rows. + +**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. The DB `overlay_layout` row is passed as `overlayLayout` in all render calls. + +**Form value parsing.** Never use `parseInt(val) || default` — it overwrites valid `0` values. Use: +```javascript +const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; }; +const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; }; +``` + +## Route map + +| Method | Path | File | Notes | +|---|---|---|---| +| GET | `/` | routers/dashboard.js | Activity log, EventSub status | +| GET | `/auth/login` | routers/auth.js | Login page | +| GET | `/auth/twitch` | routers/auth.js | Redirect to Twitch OAuth | +| GET | `/auth/callback` | routers/auth.js | Exchange code, save user, start EventSub | +| GET | `/auth/logout` | routers/auth.js | Clear session | +| GET | `/overlay/:uuid` | routers/overlay.js | Live OBS browser source | +| GET | `/overlay/:uuid/preview` | routers/overlay.js | Mock preview for layout editor | +| WS | `/ws/overlay` | routers/overlay.js | Bidirectional: commands up, actions down | +| GET/POST | `/actions` | routers/actions.js | List and create actions | +| POST | `/actions/:id/test` | routers/actions.js | Fire immediately, skip cooldown | +| POST | `/actions/:id/toggle` | routers/actions.js | Enable/disable | +| DELETE | `/actions/:id` | routers/actions.js | Delete | +| GET/POST | `/media` | routers/media.js | Upload, list | +| DELETE | `/media/:id` | routers/media.js | Delete file + DB row | +| GET/POST | `/layout` | routers/layout.js | Position + style form (saves all layout fields) | +| POST | `/layout/positions` | routers/layout.js | JSON position update (legacy, kept for future drag) | +| GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS; broadcasts settings_update on save | +| POST | `/settings/reconnect` | routers/settings.js | Restart EventSub | + +## Overlay CSS variable system + +All overlay positioning and styling uses CSS custom properties rendered into `overlay.ejs` and `overlay_preview.ejs` from the `overlay_layout` row: + +| Variable | Controls | +|---|---| +| `--chat-left`, `--chat-top` | Chat box position (%) | +| `--chat-width`, `--chat-height` | Chat box size (%) | +| `--chat-font-size` | Chat font size (px) | +| `--chat-font-family` | Chat font family | +| `--chat-bg-opacity` | Chat message background opacity | +| `--chat-text-color` | Chat message text colour | +| `--chat-border-radius` | Message border radius (px) | +| `--alert-left`, `--alert-top` | Alert position (%, centered via transform) | +| `--alert-font-size` | Alert font size (px) | +| `--alert-bg-opacity` | Alert background opacity | +| `--alert-text-color` | Alert text colour | + +The layout editor (`/layout`) shows position and style inputs, with a scaled iframe preview of `/overlay/:uuid/preview`. Position inputs update CSS variables in the iframe live on `input` event. All fields (position + style) are saved via `POST /layout`. + +## Gap / new-message audio + +Configured in `settings`. When a chat message arrives in the overlay, tmi.js checks: +1. Is `gap_audio_enabled` true and `gap_audio_url` set? +2. Has at least `gap_audio_min_silence` seconds passed since the last message? +3. If yes: play the audio. Volume = linear interpolation between `gap_audio_min_volume` and `gap_audio_max_volume` based on silence duration vs `gap_audio_loud_after`. + +All logic runs in the browser. The server pushes updated settings to the overlay via WebSocket on save — no OBS reload needed. Gap audio has `[gap]` debug logging in the browser console. + +## Custom events dispatched to overlay JS + +When the overlay WebSocket receives a message: + +- **Action broadcast:** `document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }))` + Available types: `sub`, `gift_sub`, `bits`, `channel_points`, `command`, `follow`, `raid`. + `msg` shape: `{ event_type, action_type, media_url, alert_text, username }`. + +- **Settings update:** `{ type: 'settings_update', settings }` — overlay does `Object.assign(S, msg.settings)` to update live. + +Alert text supports `{username}` interpolation. + +## Database schema + +```sql +users — Twitch OAuth user (twitch_id unique) +settings — singleton id=1: overlay_id, channel, gap audio, message_timeout, custom_css/js +overlay_layout — singleton id=1: widget positions and styles +media_files — uploaded sounds/videos +event_actions — event → action mapping (media_file_id FK) +activity_log — append-only event log +``` + +## EventSub subscriptions + +| Twitch event | Version | Condition | Scope | +|---|---|---|---| +| `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 | + +Token refresh triggered on 401 during subscription. + +## Production deployment + +Runs behind Apache on the VPS as a reverse proxy to Node on port 3000. +Production domain: `https://overlay.example.com` + +Apache vhost config is managed by `~/projects/apache.sh` (run on the VPS). Key requirements: +- `RequestHeader set X-Forwarded-Proto "https"` must be in the **443 vhost** — without it Express sees the connection as HTTP, `req.secure` is false, and the session cookie is never sent (OAuth login breaks) +- `app.set('trust proxy', 1)` is set in `app.js` before all middleware +- `/ws/overlay` must be proxied with `ws://` via `mod_proxy_wstunnel` before the catch-all `/` +- Required modules: `proxy`, `proxy_http`, `proxy_wstunnel`, `headers`, `rewrite` + +Deploy from Linux Mint: +```bash +rsync -avzO --exclude='node_modules' --exclude='.env' --exclude='public/media' \ + ~/projects/heystreamer/ user@your-server:/opt/heystreamer/ + +ssh user@your-server "cd /opt/heystreamer && npm install --production && sudo systemctl restart heystreamer" +``` + +Twitch requires HTTPS for OAuth redirect URIs in production. Register both in the Twitch dev console: +- `http://localhost:3000/auth/callback` (dev) +- `https://overlay.example.com/auth/callback` (production) + +## Not yet implemented + +- Mod access (streamer-only login for now) +- Chat commands triggering actions +- Stripe / PayPal / ETH payment notifications +- Multiple overlays (multi-user; UUID foundation is in place) +- HudFX integration +- Drag-to-reposition in layout editor (removed — CSS transform + interact.js coordinate mismatch; use the position inputs instead) diff --git a/deploy.sh b/deploy.sh new file mode 100755 index 0000000..9af0581 --- /dev/null +++ b/deploy.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -e + +echo "==> Checking Node.js..." +node_version=$(node -v 2>/dev/null | cut -c2- | cut -d. -f1) +if [ -z "$node_version" ] || [ "$node_version" -lt 18 ]; then + echo "ERROR: Node.js 18+ required. Install via: https://nodejs.org" + exit 1 +fi +echo " Node $(node -v) OK" + +echo "==> Installing dependencies..." +npm install --production + +echo "==> Checking .env..." +if [ ! -f .env ]; then + echo "ERROR: .env not found. Copy .env.example and fill in your values." + exit 1 +fi + +for var in TWITCH_CLIENT_ID TWITCH_CLIENT_SECRET SECRET_KEY APP_BASE_URL; do + val=$(grep "^${var}=" .env | cut -d= -f2-) + if [ -z "$val" ] || echo "$val" | grep -q "your_\|change_this"; then + echo "ERROR: $var is not set in .env" + exit 1 + fi +done +echo " .env OK" + +echo "==> Starting HeyStreamer..." +node src/server.js diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..2aff27a --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1981 @@ +{ + "name": "heystreamer", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "heystreamer", + "version": "1.0.0", + "dependencies": { + "better-sqlite3": "^11.0.0", + "dotenv": "^16.4.5", + "ejs": "^3.1.10", + "express": "^4.19.2", + "express-ejs-layouts": "^2.5.1", + "express-session": "^1.18.0", + "multer": "^1.4.5-lts.1", + "uuid": "^9.0.1", + "ws": "^8.17.0" + }, + "devDependencies": { + "nodemon": "^3.1.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "11.10.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz", + "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/body-parser": { + "version": "1.20.5", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz", + "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.15.1", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/brace-expansion": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz", + "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-ejs-layouts": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/express-ejs-layouts/-/express-ejs-layouts-2.5.1.tgz", + "integrity": "sha512-IXROv9n3xKga7FowT06n1Qn927JR8ZWDn5Dc9CJQoiiaaDqbhW5PDmWShzbpAa2wjWT1vJqaIM1S6vJwwX11gA==" + }, + "node_modules/express-session": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.19.0.tgz", + "integrity": "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA==", + "license": "MIT", + "dependencies": { + "cookie": "~0.7.2", + "cookie-signature": "~1.0.7", + "debug": "~2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.1.0", + "parseurl": "~1.3.3", + "safe-buffer": "~5.2.1", + "uid-safe": "~2.1.5" + }, + "engines": { + "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/filelist": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz", + "integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", + "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true, + "license": "ISC" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/jake": { + "version": "10.9.4", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", + "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "1.4.5-lts.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz", + "integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==", + "deprecated": "Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "3.89.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz", + "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/nodemon": { + "version": "3.1.14", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz", + "integrity": "sha512-jakjZi93UtB3jHMWsXL68FXSAosbLfY0In5gtKq3niLSkrWznrVBzXFNOEMJUfc9+Ke7SHWoAZsiMkNP3vq6Jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^10.2.1", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/nodemon/node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/nodemon/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/nodemon/node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/nodemon/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/qs": { + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", + "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar-stream/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "license": "MIT", + "dependencies": { + "random-bytes": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", + "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..5bfb41f --- /dev/null +++ b/package.json @@ -0,0 +1,24 @@ +{ + "name": "heystreamer", + "version": "1.0.0", + "description": "Self-hosted Twitch overlay platform", + "main": "src/server.js", + "scripts": { + "start": "node src/server.js", + "dev": "nodemon src/server.js" + }, + "dependencies": { + "better-sqlite3": "^11.0.0", + "dotenv": "^16.4.5", + "ejs": "^3.1.10", + "express": "^4.19.2", + "express-ejs-layouts": "^2.5.1", + "express-session": "^1.18.0", + "multer": "^1.4.5-lts.1", + "uuid": "^9.0.1", + "ws": "^8.17.0" + }, + "devDependencies": { + "nodemon": "^3.1.0" + } +} 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 { + const start = Date.now(); + res.on('finish', () => { + const ms = Date.now() - start; + console.log(`[http] ${req.method} ${req.path} ${res.statusCode} ${ms}ms — ip:${req.ip} secure:${req.secure}`); + }); + next(); +}); + +app.use(express.static(path.join(__dirname, '../public'))); +app.use(express.urlencoded({ extended: true })); +app.use(express.json()); + +app.use(session({ + secret: process.env.SECRET_KEY || 'dev-secret', + resave: false, + saveUninitialized: false, + cookie: { + secure: process.env.APP_BASE_URL?.startsWith('https'), + httpOnly: true, + maxAge: 7 * 24 * 60 * 60 * 1000, + }, +})); + +app.use((req, res, next) => { + res.locals.user = req.session.user || null; + next(); +}); + +function requireAuth(req, res, next) { + if (!req.session.userId) return res.redirect('/auth/login'); + next(); +} + +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')); + +module.exports = app; diff --git a/src/cooldowns.js b/src/cooldowns.js new file mode 100644 index 0000000..10b68a1 --- /dev/null +++ b/src/cooldowns.js @@ -0,0 +1,18 @@ +const cooldowns = new Map(); + +function isOnCooldown(actionId, cooldownSeconds) { + if (!cooldownSeconds) return false; + const last = cooldowns.get(actionId); + if (!last) return false; + return (Date.now() - last) < cooldownSeconds * 1000; +} + +function setCooldown(actionId) { + cooldowns.set(actionId, Date.now()); +} + +function resetCooldown(actionId) { + cooldowns.delete(actionId); +} + +module.exports = { isOnCooldown, setCooldown, resetCooldown }; diff --git a/src/db.js b/src/db.js new file mode 100644 index 0000000..46464d6 --- /dev/null +++ b/src/db.js @@ -0,0 +1,252 @@ +const Database = require('better-sqlite3'); +const { v4: uuidv4 } = require('uuid'); +require('dotenv').config(); + +const DB_PATH = process.env.DB_PATH || './heystreamer.db'; +let db; + +function init() { + db = new Database(DB_PATH); + db.pragma('journal_mode = WAL'); + db.pragma('foreign_keys = ON'); + createSchema(); + seedSettings(); + seedLayout(); + console.log(`[db] Initialised — path: ${DB_PATH}`); +} + +function createSchema() { + db.exec(` + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + twitch_id TEXT UNIQUE NOT NULL, + login TEXT NOT NULL, + display_name TEXT NOT NULL, + access_token TEXT NOT NULL, + refresh_token TEXT NOT NULL, + created_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS settings ( + id INTEGER PRIMARY KEY CHECK(id = 1), + overlay_id TEXT NOT NULL, + channel TEXT DEFAULT '', + message_timeout INTEGER DEFAULT 30, + max_messages INTEGER DEFAULT 20, + gap_audio_enabled INTEGER DEFAULT 0, + gap_audio_url TEXT DEFAULT '', + gap_audio_min_silence INTEGER DEFAULT 60, + gap_audio_min_volume REAL DEFAULT 0.2, + gap_audio_max_volume REAL DEFAULT 1.0, + gap_audio_loud_after INTEGER DEFAULT 3600, + custom_css TEXT DEFAULT '', + custom_js TEXT DEFAULT '' + ); + + CREATE TABLE IF NOT EXISTS overlay_layout ( + id INTEGER PRIMARY KEY CHECK(id = 1), + chat_left REAL DEFAULT 2.0, + chat_top REAL DEFAULT 60.0, + chat_width REAL DEFAULT 25.0, + chat_height REAL DEFAULT 35.0, + chat_font_size INTEGER DEFAULT 15, + chat_font_family TEXT DEFAULT 'Inter, sans-serif', + chat_bg_opacity REAL DEFAULT 0.45, + chat_text_color TEXT DEFAULT '#ffffff', + chat_border_radius INTEGER DEFAULT 8, + alert_left REAL DEFAULT 50.0, + alert_top REAL DEFAULT 40.0, + alert_font_size INTEGER DEFAULT 32, + alert_bg_opacity REAL DEFAULT 0.7, + alert_text_color TEXT DEFAULT '#ffffff' + ); + + CREATE TABLE IF NOT EXISTS media_files ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + filename TEXT NOT NULL, + original_name TEXT NOT NULL, + media_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + uploaded_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS event_actions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + event_type TEXT NOT NULL, + event_detail TEXT, + action_type TEXT NOT NULL, + media_file_id INTEGER REFERENCES media_files(id) ON DELETE SET NULL, + alert_text TEXT, + cooldown_seconds INTEGER DEFAULT 0, + 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, + event_detail TEXT, + username TEXT, + data_json TEXT, + actions_fired INTEGER DEFAULT 0, + created_at TEXT DEFAULT (datetime('now')) + ); + `); +} + +function seedSettings() { + const row = db.prepare('SELECT id FROM settings WHERE id = 1').get(); + if (!row) { + const id = uuidv4(); + db.prepare('INSERT INTO settings (id, overlay_id) VALUES (1, ?)').run(id); + console.log(`[db] Created default settings — overlay_id: ${id}`); + } +} + +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'); + } +} + +// Users +function upsertUser({ twitch_id, login, display_name, access_token, refresh_token }) { + db.prepare(` + INSERT INTO users (twitch_id, login, display_name, access_token, refresh_token) + VALUES (@twitch_id, @login, @display_name, @access_token, @refresh_token) + ON CONFLICT(twitch_id) DO UPDATE SET + login = excluded.login, + display_name = excluded.display_name, + access_token = excluded.access_token, + refresh_token = excluded.refresh_token + `).run({ twitch_id, login, display_name, access_token, refresh_token }); + return db.prepare('SELECT * FROM users WHERE twitch_id = ?').get(twitch_id); +} + +function getUserById(id) { + return db.prepare('SELECT * FROM users WHERE id = ?').get(id); +} + +// Settings +function getSettings() { + return db.prepare('SELECT * FROM settings WHERE id = 1').get(); +} + +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(); +} + +function getMediaFile(id) { + return db.prepare('SELECT * FROM media_files WHERE id = ?').get(id); +} + +function createMedia(fields) { + return db.prepare(` + INSERT INTO media_files (filename, original_name, media_type, size_bytes) + VALUES (@filename, @original_name, @media_type, @size_bytes) + `).run(fields); +} + +function deleteMedia(id) { + db.prepare('DELETE FROM media_files WHERE id = ?').run(id); +} + +// Actions +function getAllActions() { + return db.prepare('SELECT * FROM event_actions ORDER BY created_at DESC').all(); +} + +function getAction(id) { + return db.prepare('SELECT * FROM event_actions WHERE id = ?').get(id); +} + +function createAction(fields) { + db.prepare(` + INSERT INTO event_actions (name, event_type, event_detail, action_type, media_file_id, alert_text, cooldown_seconds) + VALUES (@name, @event_type, @event_detail, @action_type, @media_file_id, @alert_text, @cooldown_seconds) + `).run(fields); +} + +function toggleAction(id) { + db.prepare('UPDATE event_actions SET enabled = NOT enabled WHERE id = ?').run(id); +} + +function deleteAction(id) { + db.prepare('DELETE FROM event_actions WHERE id = ?').run(id); +} + +function getMatchingActions(eventType, eventDetail) { + const rows = db.prepare('SELECT * FROM event_actions WHERE event_type = ? AND enabled = 1').all(eventType); + return rows.filter(a => { + if (eventType === 'command') { + return a.event_detail && a.event_detail.toLowerCase() === (eventDetail || '').toLowerCase(); + } + if (eventType === 'bits' && a.event_detail) { + return parseInt(eventDetail || 0) >= parseInt(a.event_detail); + } + if (eventType === 'channel_points' && a.event_detail) { + return a.event_detail === eventDetail; + } + if ((eventType === 'sub' || eventType === 'gift_sub') && a.event_detail) { + return a.event_detail === eventDetail; + } + return true; + }); +} + +// Activity log +function logActivity(eventType, eventDetail, username, data, actionsFired) { + 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) + `).run({ + event_type: eventType, + event_detail: eventDetail || null, + username: username || null, + data_json: data ? JSON.stringify(data) : null, + actions_fired: actionsFired, + }); +} + +function getActivityLog(limit = 50) { + return db.prepare('SELECT * FROM activity_log ORDER BY created_at DESC LIMIT ?').all(limit); +} + +module.exports = { + init, + upsertUser, getUserById, + getSettings, updateSettings, + getLayout, updateLayout, updateLayoutPositions, + getAllMedia, getMediaFile, createMedia, deleteMedia, + getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions, + logActivity, getActivityLog, +}; diff --git a/src/dispatch.js b/src/dispatch.js new file mode 100644 index 0000000..3d3003a --- /dev/null +++ b/src/dispatch.js @@ -0,0 +1,37 @@ +const db = require('./db'); +const ws = require('./ws'); +const { isOnCooldown, setCooldown } = require('./cooldowns'); + +function dispatchEvent(eventType, eventDetail = null, username = null, data = null) { + const actions = db.getMatchingActions(eventType, eventDetail); + let fired = 0; + + for (const action of actions) { + if (isOnCooldown(action.id, action.cooldown_seconds)) { + console.log(`[dispatch] Action ${action.id} on cooldown — skipping`); + continue; + } + + let mediaUrl = null; + if (action.media_file_id) { + const media = db.getMediaFile(action.media_file_id); + if (media) mediaUrl = `/media/${media.filename}`; + } + + ws.broadcast({ + event_type: eventType, + action_type: action.action_type, + media_url: mediaUrl, + alert_text: action.alert_text, + username, + }); + + setCooldown(action.id); + fired++; + console.log(`[dispatch] Fired action ${action.id} (${action.name}) — event: ${eventType}, user: ${username}`); + } + + db.logActivity(eventType, eventDetail, username, data, fired); +} + +module.exports = { dispatchEvent }; diff --git a/src/eventsub.js b/src/eventsub.js new file mode 100644 index 0000000..faeae1c --- /dev/null +++ b/src/eventsub.js @@ -0,0 +1,118 @@ +const { WebSocket } = require('ws'); +const dispatch = require('./dispatch'); + +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; + +function start(accessToken, broadcasterId) { + _accessToken = accessToken; + _broadcasterId = broadcasterId; + shouldRun = true; + connect(); + console.log(`[eventsub] Starting — broadcaster: ${broadcasterId}, base_url: ${process.env.APP_BASE_URL}`); +} + +function stop() { + shouldRun = false; + if (ws) ws.close(); + 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)); +} + +async function handleMessage(msg) { + 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); + } +} + +async function subscribeAll() { + 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 } }, + ]; + + for (const sub of subs) { + try { + const res = await fetch('https://api.twitch.tv/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 } }), + }); + if (res.status === 202) { + console.log(`[eventsub] Subscribed: ${sub.type}`); + } else { + const body = await res.text(); + console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`); + } + } catch (e) { + console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message); + } + } +} + +function handleNotification(payload) { + const sub = payload.subscription; + 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; + case 'channel.follow': + dispatch.dispatchEvent('follow', null, username, event); + break; + case 'channel.raid': + dispatch.dispatchEvent('raid', null, username, event); + break; + } +} + +module.exports = { start, stop }; diff --git a/src/routers/actions.js b/src/routers/actions.js new file mode 100644 index 0000000..1d32b1b --- /dev/null +++ b/src/routers/actions.js @@ -0,0 +1,45 @@ +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/auth.js b/src/routers/auth.js new file mode 100644 index 0000000..4168e65 --- /dev/null +++ b/src/routers/auth.js @@ -0,0 +1,101 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); +const eventsub = require('../eventsub'); + +const CLIENT_ID = process.env.TWITCH_CLIENT_ID; +const CLIENT_SECRET = process.env.TWITCH_CLIENT_SECRET; +const REDIRECT_URI = process.env.TWITCH_REDIRECT_URI; +const SCOPES = [ + 'channel:read:subscriptions', + 'bits:read', + 'channel:read:redemptions', + 'moderator:read:followers', +].join(' '); + +router.get('/login', (req, res) => { + if (req.session.userId) return res.redirect('/'); + res.render('login', { layout: false }); +}); + +router.get('/twitch', (req, res) => { + const state = Math.random().toString(36).slice(2); + req.session.oauthState = state; + console.log(`[auth] OAuth init — sessionID:${req.sessionID} secure:${req.secure} redirect_uri:${REDIRECT_URI}`); + const url = new URL('https://id.twitch.tv/oauth2/authorize'); + url.searchParams.set('client_id', CLIENT_ID); + url.searchParams.set('redirect_uri', REDIRECT_URI); + url.searchParams.set('response_type', 'code'); + url.searchParams.set('scope', SCOPES); + url.searchParams.set('state', state); + res.redirect(url.toString()); +}); + +router.get('/callback', async (req, res) => { + const { code, state, error, error_description } = req.query; + + if (error) { + console.error(`[auth] Twitch denied OAuth — ${error}: ${error_description}`); + return res.redirect('/auth/login'); + } + + console.log(`[auth] Callback — sessionID:${req.sessionID} secure:${req.secure} hasSession:${!!req.session.oauthState}`); + + if (state !== req.session.oauthState) { + console.warn(`[auth] State mismatch — got:${state} expected:${req.session.oauthState} sessionID:${req.sessionID}`); + return res.redirect('/auth/login'); + } + + try { + const tokenRes = await fetch('https://id.twitch.tv/oauth2/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code, grant_type: 'authorization_code', redirect_uri: REDIRECT_URI }), + }); + const tokens = await tokenRes.json(); + + if (!tokenRes.ok || tokens.error) { + console.error(`[auth] Token exchange failed — ${tokenRes.status}: ${tokens.message || tokens.error}`); + return res.redirect('/auth/login'); + } + + const userRes = await fetch('https://api.twitch.tv/helix/users', { + headers: { 'Authorization': `Bearer ${tokens.access_token}`, 'Client-Id': CLIENT_ID }, + }); + const userData = await userRes.json(); + + if (!userRes.ok || !userData.data?.[0]) { + console.error(`[auth] Twitch user fetch failed — ${userRes.status}:`, userData); + return res.redirect('/auth/login'); + } + + const twitchUser = userData.data[0]; + const user = db.upsertUser({ + twitch_id: twitchUser.id, + login: twitchUser.login, + display_name: twitchUser.display_name, + access_token: tokens.access_token, + refresh_token: tokens.refresh_token, + }); + + req.session.userId = user.id; + req.session.user = { login: user.login, display_name: user.display_name }; + + eventsub.start(tokens.access_token, twitchUser.id); + + console.log(`[auth] Login OK — ${twitchUser.login} (twitch_id:${twitchUser.id})`); + res.redirect('/'); + } catch (e) { + console.error('[auth] OAuth error:', e.message, e.stack); + res.redirect('/auth/login'); + } +}); + +router.get('/logout', (req, res) => { + console.log(`[auth] Logout: ${req.session.user?.login}`); + req.session.destroy(); + eventsub.stop(); + res.redirect('/auth/login'); +}); + +module.exports = router; diff --git a/src/routers/dashboard.js b/src/routers/dashboard.js new file mode 100644 index 0000000..b7b6fb8 --- /dev/null +++ b/src/routers/dashboard.js @@ -0,0 +1,11 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); + +router.get('/', (req, res) => { + const logs = db.getActivityLog(50); + const settings = db.getSettings(); + res.render('dashboard', { logs, settings }); +}); + +module.exports = router; diff --git a/src/routers/layout.js b/src/routers/layout.js new file mode 100644 index 0000000..4a443a5 --- /dev/null +++ b/src/routers/layout.js @@ -0,0 +1,37 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); + +router.get('/', (req, res) => { + res.render('layout_editor', { overlayLayout: db.getLayout(), settings: db.getSettings() }); +}); + +router.post('/', (req, res) => { + const b = req.body; + 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; }; + db.updateLayout({ + chat_left: flt(b.chat_left, 2.0), + chat_top: flt(b.chat_top, 60.0), + chat_width: flt(b.chat_width, 25.0), + chat_height: flt(b.chat_height, 35.0), + alert_left: flt(b.alert_left, 50.0), + alert_top: flt(b.alert_top, 40.0), + chat_font_size: int(b.chat_font_size, 15), + chat_font_family: b.chat_font_family || 'Inter, sans-serif', + chat_bg_opacity: flt(b.chat_bg_opacity, 0.45), + chat_text_color: b.chat_text_color || '#ffffff', + chat_border_radius: int(b.chat_border_radius, 8), + alert_font_size: int(b.alert_font_size, 32), + alert_bg_opacity: flt(b.alert_bg_opacity, 0.7), + alert_text_color: b.alert_text_color || '#ffffff', + }); + res.redirect('/layout'); +}); + +router.post('/positions', (req, res) => { + db.updateLayoutPositions(req.body); + res.json({ ok: true }); +}); + +module.exports = router; diff --git a/src/routers/media.js b/src/routers/media.js new file mode 100644 index 0000000..42159c4 --- /dev/null +++ b/src/routers/media.js @@ -0,0 +1,42 @@ +const express = require('express'); +const router = express.Router(); +const multer = require('multer'); +const path = require('path'); +const fs = require('fs'); +const { v4: uuidv4 } = require('uuid'); +const db = require('../db'); + +const storage = multer.diskStorage({ + destination: path.join(__dirname, '../../public/media'), + filename: (req, file, cb) => cb(null, uuidv4() + path.extname(file.originalname)), +}); +const upload = multer({ storage, limits: { fileSize: 50 * 1024 * 1024 } }); + +router.get('/', (req, res) => { + res.render('media', { files: db.getAllMedia() }); +}); + +router.post('/upload', upload.single('file'), (req, res) => { + if (!req.file) return res.redirect('/media'); + db.createMedia({ + filename: req.file.filename, + original_name: req.file.originalname, + media_type: req.file.mimetype.startsWith('video') ? 'video' : 'audio', + size_bytes: req.file.size, + }); + console.log(`[media] Uploaded: ${req.file.originalname} (${req.file.size} bytes)`); + res.redirect('/media'); +}); + +router.post('/:id/delete', (req, res) => { + const file = db.getMediaFile(parseInt(req.params.id)); + if (file) { + const filePath = path.join(__dirname, '../../public/media', file.filename); + if (fs.existsSync(filePath)) fs.unlinkSync(filePath); + db.deleteMedia(file.id); + console.log(`[media] Deleted: ${file.original_name}`); + } + res.redirect('/media'); +}); + +module.exports = router; diff --git a/src/routers/overlay.js b/src/routers/overlay.js new file mode 100644 index 0000000..b8078d2 --- /dev/null +++ b/src/routers/overlay.js @@ -0,0 +1,18 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); + +router.get('/:uuid', (req, res) => { + const settings = db.getSettings(); + if (req.params.uuid !== settings.overlay_id) return res.status(404).send('Overlay not found'); + const overlayLayout = db.getLayout(); + res.render('overlay', { layout: false, settings, overlayLayout }); +}); + +router.get('/:uuid/preview', (req, res) => { + const settings = db.getSettings(); + const overlayLayout = db.getLayout(); + res.render('overlay_preview', { layout: false, settings, overlayLayout }); +}); + +module.exports = router; diff --git a/src/routers/settings.js b/src/routers/settings.js new file mode 100644 index 0000000..dcd59e6 --- /dev/null +++ b/src/routers/settings.js @@ -0,0 +1,48 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); +const eventsub = require('../eventsub'); +const ws = require('../ws'); + +const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; }; +const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; }; + +router.get('/', (req, res) => { + const settings = db.getSettings(); + const baseUrl = process.env.APP_BASE_URL; + res.render('settings', { settings, baseUrl }); +}); + +router.post('/', (req, res) => { + const b = req.body; + db.updateSettings({ + channel: b.channel || '', + message_timeout: int(b.message_timeout, 30), + max_messages: int(b.max_messages, 20), + gap_audio_enabled: b.gap_audio_enabled === 'on' ? 1 : 0, + gap_audio_url: b.gap_audio_url || '', + gap_audio_min_silence: int(b.gap_audio_min_silence, 60), + gap_audio_min_volume: flt(b.gap_audio_min_volume, 0.2), + gap_audio_max_volume: flt(b.gap_audio_max_volume, 1.0), + gap_audio_loud_after: int(b.gap_audio_loud_after, 3600), + custom_css: b.custom_css || '', + custom_js: b.custom_js || '', + }); + + // Push updated settings to all connected overlays so they don't need a page reload + ws.broadcast({ type: 'settings_update', settings: db.getSettings() }); + + console.log(`[settings] Saved — channel: ${b.channel}, gap_audio: ${b.gap_audio_enabled === 'on'}`); + res.redirect('/settings'); +}); + +router.post('/reconnect', (req, res) => { + const user = db.getUserById(req.session.userId); + if (user) { + eventsub.start(user.access_token, user.twitch_id); + console.log('[settings] EventSub reconnect triggered'); + } + res.redirect('/settings'); +}); + +module.exports = router; diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..b680599 --- /dev/null +++ b/src/server.js @@ -0,0 +1,21 @@ +require('dotenv').config(); +const http = require('http'); +const { WebSocketServer } = require('ws'); + +const db = require('./db'); +const ws = require('./ws'); +const app = require('./app'); + +const PORT = process.env.PORT || 3000; + +db.init(); + +const server = http.createServer(app); +const wss = new WebSocketServer({ server, path: '/ws/overlay' }); +ws.init(wss); + +server.listen(PORT, () => { + console.log(`[server] HeyStreamer running on port ${PORT}`); + console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`); + console.log(`[server] DB_PATH: ${process.env.DB_PATH}`); +}); diff --git a/src/ws.js b/src/ws.js new file mode 100644 index 0000000..4d7531d --- /dev/null +++ b/src/ws.js @@ -0,0 +1,26 @@ +const { WebSocket } = require('ws'); + +const clients = new Set(); + +function init(wss) { + wss.on('connection', (ws) => { + clients.add(ws); + console.log(`[ws] Client connected — total: ${clients.size}`); + ws.on('close', () => { + clients.delete(ws); + console.log(`[ws] Client disconnected — total: ${clients.size}`); + }); + ws.on('error', () => clients.delete(ws)); + }); +} + +function broadcast(data) { + const msg = JSON.stringify(data); + for (const client of clients) { + if (client.readyState === WebSocket.OPEN) { + client.send(msg); + } + } +} + +module.exports = { init, broadcast }; diff --git a/views/actions.ejs b/views/actions.ejs new file mode 100644 index 0000000..8af7df7 --- /dev/null +++ b/views/actions.ejs @@ -0,0 +1,88 @@ +

Actions

+

Map Twitch events to sounds, videos, or on-screen alerts.

+ +
+ Add new action +
+
+ + + + + + + +
+ +
+
+ +<% if (actions.length === 0) { %> +

No actions yet.

+<% } else { %> +
+ + + + + + + + + + + + + + <% for (const a of actions) { %> + + + + + + + + + + <% } %> + +
NameEventDetailActionCooldownStatus
<%= a.name %><%= a.event_type %><%= a.event_detail || '—' %><%= a.action_type %><%= a.cooldown_seconds %>s + + <%= a.enabled ? 'on' : 'off' %> + + +
+
+
+
+
+<% } %> diff --git a/views/dashboard.ejs b/views/dashboard.ejs new file mode 100644 index 0000000..702ac8d --- /dev/null +++ b/views/dashboard.ejs @@ -0,0 +1,46 @@ +

Dashboard

+ +
+
+ Channel: + <%= settings.channel || 'not set' %> +
+
+ Overlay URL: + <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %> +
+
+ +

Recent activity

+<% if (logs.length === 0) { %> +

No activity yet. Events will appear here once your overlay is connected and Twitch fires events.

+<% } else { %> +
+ + + + + + + + + + + + <% for (const log of logs) { %> + + + + + + + + <% } %> + +
TimeEventUserDetailActions fired
<%= log.created_at %><%= log.event_type %><%= log.username || '—' %><%= log.event_detail || '—' %> + + <%= log.actions_fired %> + +
+
+<% } %> diff --git a/views/layout.ejs b/views/layout.ejs new file mode 100644 index 0000000..9aadd32 --- /dev/null +++ b/views/layout.ejs @@ -0,0 +1,39 @@ + + + + + + HeyStreamer + + + + + + +
+ <%- body %> +
+ + diff --git a/views/layout_editor.ejs b/views/layout_editor.ejs new file mode 100644 index 0000000..12b56c6 --- /dev/null +++ b/views/layout_editor.ejs @@ -0,0 +1,73 @@ +

Layout editor

+ +
+ +
+ +
+ +

Chat position & size

+
+ + + + +
+ +

Chat style

+
+ + + + + +
+ +

Alert position

+
+ + +
+ +

Alert style

+
+ + + +
+ + +
+ + diff --git a/views/login.ejs b/views/login.ejs new file mode 100644 index 0000000..d158de4 --- /dev/null +++ b/views/login.ejs @@ -0,0 +1,34 @@ + + + + + + HeyStreamer — Login + + + + + + + + diff --git a/views/media.ejs b/views/media.ejs new file mode 100644 index 0000000..0d03b66 --- /dev/null +++ b/views/media.ejs @@ -0,0 +1,53 @@ +

Media library

+

Upload audio (MP3, WAV, OGG) or video (MP4, WebM) files to use in actions. Max 50 MB.

+ +
+
+ + +
+
+ +<% if (files.length === 0) { %> +

No files uploaded yet.

+<% } else { %> +
+ + + + + + + + + + + + + <% for (const f of files) { %> + + + + + + + + + <% } %> + +
NameTypeSizeUploadedPreview
<%= f.original_name %><%= f.media_type %><%= (f.size_bytes / 1024).toFixed(0) %> KB<%= f.uploaded_at %> + <% if (f.media_type === 'audio') { %> + + <% } else { %> + + <% } %> + +
+ +
+
+
+<% } %> diff --git a/views/overlay.ejs b/views/overlay.ejs new file mode 100644 index 0000000..b1e57bb --- /dev/null +++ b/views/overlay.ejs @@ -0,0 +1,199 @@ + + + + + + + +
+
+ + + + + + diff --git a/views/overlay_preview.ejs b/views/overlay_preview.ejs new file mode 100644 index 0000000..5c8a0e9 --- /dev/null +++ b/views/overlay_preview.ejs @@ -0,0 +1,87 @@ + + + + + + + +
+
channel: This is a preview message
+
someviewer: Looking great!
+
anotheruser: pog pog pog
+
+
Alert preview
+
+
+ + diff --git a/views/settings.ejs b/views/settings.ejs new file mode 100644 index 0000000..d54e29c --- /dev/null +++ b/views/settings.ejs @@ -0,0 +1,79 @@ +

Settings

+ +
+
Overlay URL
+

Add this as a Browser Source in OBS (1920×1080, transparent background):

+ <%= baseUrl %>/overlay/<%= settings.overlay_id %> +
+ +
+ +

Chat

+ +
+ + +
+ +

Gap audio

+

Plays a sound when a new message arrives after a period of silence.

+ + +
+ + + +
+ + +

Custom CSS / JS

+ + + + +
+ +
+

EventSub

+
+ +
+Use this if Twitch alerts stop working after a token refresh. From 88e906ff5da0fc443667b6342914e4641ca201df Mon Sep 17 00:00:00 2001 From: Bashy Date: Fri, 20 Nov 2026 19:57:29 +0200 Subject: [PATCH 02/40] Tidy repo: rename vhost script, keep media folder - `sh` -> `apache.sh` (it writes the Apache vhost for overlay.example.com) - keep public/media/ in git via .gitkeep while ignoring uploads Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 ++ public/media/.gitkeep | 0 2 files changed, 2 insertions(+) create mode 100644 public/media/.gitkeep diff --git a/.gitignore b/.gitignore index 1e4073e..962c904 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,9 @@ venv/ static/media/* !static/media/.gitkeep +# Node node_modules/ *.db-shm *.db-wal public/media/* +!public/media/.gitkeep diff --git a/public/media/.gitkeep b/public/media/.gitkeep new file mode 100644 index 0000000..e69de29 From d481fc4f69d78367ad8baf5ea6892e5fa2c8a12e Mon Sep 17 00:00:00 2001 From: Bashy Date: Fri, 20 Nov 2026 19:57:36 +0200 Subject: [PATCH 03/40] Add polaroid alerts for follows, subs, gifts, streaks, raids and bits Overlay - public/alerts/polaroid.js + .css: animated polaroid (photo drops in, tape and heart stick on, caption writes in), randomized angles, per-event art, caption, tape colour, badge and sound, fanned photo stack for multi-month subs / community gifts / raids, and a queue so alerts never overlap. - Bits: no alert under 5; sound tiers at 5/50/75/100/150/250. - Watch streaks are read from chat (USERNOTICE viewermilestone) and reported to the server over the overlay WebSocket. Server - Subscribe to channel.chat.notification instead of channel.subscribe / subscription.message / subscription.gift / channel.raid: one event with Prime, months bought at once, gift recipient, resub message and community gift totals. Per-recipient gift notices of a gift bomb are skipped, so a bomb is one alert (was N+1). Needs the user:read:chat scope (log in again). - src/alerts.js maps Twitch events to alerts, broadcasts them and still runs them through dispatch (activity log + existing actions). - EventSub starts on boot from the stored login (alerts survive restarts), validates the token hourly and refreshes it on expiry or 401, follows session_reconnect without dropping events, and reconnects when keepalives stop. - The overlay WebSocket only accepts chat_notice messages from connections that pass the overlay UUID; streak notices are deduped by message id. Dashboard - Twitch connection status and a test button per alert (POST /alerts/test/:key). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 42 ++++-- public/alerts/polaroid.css | 33 +++++ public/alerts/polaroid.js | 260 +++++++++++++++++++++++++++++++++++++ src/alerts.js | 127 ++++++++++++++++++ src/app.js | 1 + src/db.js | 11 +- src/eventsub.js | 196 ++++++++++++++++++---------- src/routers/alerts.js | 11 ++ src/routers/auth.js | 3 +- src/routers/dashboard.js | 4 +- src/routers/settings.js | 2 +- src/server.js | 11 ++ src/twitch.js | 75 +++++++++++ src/ws.js | 19 ++- views/dashboard.ejs | 32 +++++ views/overlay.ejs | 29 ++++- 16 files changed, 773 insertions(+), 83 deletions(-) create mode 100644 public/alerts/polaroid.css create mode 100644 public/alerts/polaroid.js create mode 100644 src/alerts.js create mode 100644 src/routers/alerts.js create mode 100644 src/twitch.js diff --git a/CLAUDE.md b/CLAUDE.md index 0f55387..48e7dfe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -121,6 +121,7 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; }; | POST | `/layout/positions` | routers/layout.js | JSON position update (legacy, kept for future drag) | | GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS; broadcasts settings_update on save | | POST | `/settings/reconnect` | routers/settings.js | Restart EventSub | +| POST | `/alerts/test/:key` | routers/alerts.js | Send a sample polaroid alert to the overlay | ## Overlay CSS variable system @@ -176,17 +177,38 @@ 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.cheer` | 1 | `broadcaster_user_id` | `bits:read` | bits alert | +| `channel.chat.notification` | 1 | `broadcaster_user_id` + `user_id` | `user:read:chat` | subs, resubs, Prime, multi-month, gifts, community gifts, raids | +| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | actions only (no polaroid yet) | -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. + +## Polaroid alerts + +``` +Twitch EventSub ─► eventsub.js ─► alerts.js (fromFollow / fromCheer / fromChatNotification) ─► alerts.send() +Overlay chat (tmi.js USERNOTICE viewermilestone) ─► WS up {type:'chat_notice'} ─► alerts.fromOverlayNotice() ─┘ +alerts.send() ─► ws.broadcast({type:'alert', alert}) ─► overlay ─► public/alerts/polaroid.js (queue + animation + sound) + └─► dispatch.dispatchEvent() (activity log + legacy actions keep working) +``` + +- Alert shape and per-event look (art, caption, tape colour, badge, sound, bits tiers) live in `public/alerts/polaroid.js` (`describe()` + CONFIG block). Art in `public/alerts/art/`, sounds in `public/alerts/sounds/` (lengths in `SOUND_MS`, so the alert holds for the whole sound). +- Watch streaks only exist in chat. The overlay reports them; the server only accepts `chat_notice` from WS connections that pass `?overlay=` and dedupes by message id (several overlays may report the same notice). +- Test buttons on the dashboard: `POST /alerts/test/:key` (keys = `alerts.TEST_KEYS`). Test alerts (`test:true`) replace what is showing; `queue-test` sends four that queue. Not logged, no actions fired. +- Bits under 5: no alert (`BITS_MIN`). ## Production deployment diff --git a/public/alerts/polaroid.css b/public/alerts/polaroid.css new file mode 100644 index 0000000..fe99976 --- /dev/null +++ b/public/alerts/polaroid.css @@ -0,0 +1,33 @@ +/* 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; } diff --git a/public/alerts/polaroid.js b/public/alerts/polaroid.js new file mode 100644 index 0000000..09a0d63 --- /dev/null +++ b/public/alerts/polaroid.js @@ -0,0 +1,260 @@ +/* + Polaroid alerts for the OBS overlay. + + window.PolaroidAlerts.play(alert) queue an alert (never overlaps) + window.PolaroidAlerts.reset() stop the current alert and clear 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 } + Everything per event (art, caption, tape colour, badge, sound) is in describe() below. +*/ +(function () { + // ===================== CONFIG ===================== + const BASE = '/alerts/'; + const ART = n => `${BASE}art/${n}`; + const SND = n => `${BASE}sounds/${n}`; + const 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)', + }; + + // bits: under BITS_MIN = no alert; otherwise the highest matching tier wins + const BITS_MIN = 5; + const BITS_TIERS = [ + { min:250, sound:'TomDaTankLoud.mp3', art:'CharacterHype2.png', badge:'#e0457b', hearts:3 }, + { min:150, sound:'run-vine-sound-effect.mp3', art:'CharacterHype2.png', badge:'#e0457b', hearts:2 }, + { min:100, sound:'windows-xp-startup_1ph012N.mp3', art:'CharacterHype2.png', badge:'#9b6bdc', hearts:1 }, + { min:75, sound:'we-do-a-little-trolling_80cJgd9.mp3', art:'CharacterCool.png', badge:'#9b6bdc', hearts:0 }, + { min:50, sound:'opatski.mp3', art:'CharacterCool.png', badge:'#8a8aa8', hearts:0 }, + { min:5, sound:'correct-answer.wav', art:'CharacterCool.png', badge:'#8a8aa8', hearts:0 }, + ]; + + // sound lengths in ms (ffprobe), so the alert stays up for the whole sound + const SOUND_MS = { + 'duck-toy-sound.mp3':960, 'wow.mp3':2325, 'huh.mp3':1123, 'correct-answer.wav':1960, 'opatski.mp3':1416, + 'we-do-a-little-trolling_80cJgd9.mp3':2691, 'windows-xp-startup_1ph012N.mp3':4911, + 'run-vine-sound-effect.mp3':8280, 'TomDaTankLoud.mp3':10057, 'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3':2038, + }; + + const BACK_ART = ['CharacterHeart.png','CharacterLoveEyes_Glasses.png','CharacterHappy.png', + 'CharacterLynx.png','CharacterCool.png','CharacterSelfie.png']; + + 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 MIN_HOLD = 6000; // ms fully visible, at least + const SOUND_PAD = 1500; // ms after the sound ends + const GAP = 600; // ms between queued alerts + + // Event -> what the polaroid shows. null = no alert. + function describe(e) { + const who = e.user || (e.type === 'gift' ? 'An anonymous gifter' : 'Someone'); + switch (e.type) { + case 'follow': + return { art:'CharacterSelfie.png', name:who, line:'just followed! ♡', tape:TAPE.follow, sound:'duck-toy-sound.mp3' }; + 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 ? 'CharacterQueen_Main.png' : (months > 1 || multi ? 'CharacterInLove.png' : 'CharacterHeart.png'); + return { art, name:who, line, msg:e.message, tape:e.prime ? TAPE.prime : TAPE.sub, sound:'wow.mp3', + stack: multi ? Math.min(dur - 1, 5) : 0, + badge: multi ? { big:`${dur}×`, small:'months' } : months > 1 ? { big:months, small:'months' } : null, + phbg: e.prime ? 'linear-gradient(#e3f2ff,#bcdcf5)' : null }; + } + case 'gift': { + const n = e.total || 1; + return { art:'CharacterGift.png', name:who, + line: n > 1 ? `gifted ${n} subs to the community! ♡` + : (e.recipient ? `gifted a sub to ${e.recipient}! ♡` : 'gifted a sub! ♡'), + tape:TAPE.gift, sound:'wow.mp3', stack: n > 1 ? Math.min(n - 1, 3) : 0, + badge: n > 1 ? { big:`×${n}`, small:'subs' } : null, phbg:'linear-gradient(#e2f6ea,#bfe6cf)' }; + } + case 'streak': + return { art:'CharacterTime.png', name:who, line:`is on a ${e.streak}-stream watch streak!`, + tape:TAPE.streak, sound:'huh.mp3', badge:{ big:e.streak, small:'streams' }, phbg:'linear-gradient(#fff4d6,#f7deb0)' }; + case 'raid': + return { art:'CharacterPolice.png', name:who, line:`is raiding with ${e.viewers} viewers!`, + tape:TAPE.raid, sound:'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3', badge:{ big:e.viewers, small:'raiders' }, + phbg:'linear-gradient(#ffe6d6,#f8c8a8)', stack:2 }; + case 'bits': { + if (!(e.bits >= BITS_MIN)) return null; + const t = BITS_TIERS.find(t => e.bits >= t.min); + 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, 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 imgs = new Set([...BACK_ART, 'Heart.png', 'CharacterSelfie.png', 'CharacterHeart.png', + 'CharacterQueen_Main.png', 'CharacterInLove.png', 'CharacterGift.png', 'CharacterTime.png', + 'CharacterPolice.png', 'CharacterHype2.png']); + 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); }); + } + + const queue = []; + let busy = false, current = null, gen = 0; + + function play(alert) { + const d = describe(alert); + if (!d) { console.log('[alerts] skipped', alert); return; } + queue.push(d); + if (!busy) next(); + } + + 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'; + 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 `
${inner}
`; + } + + function show(d) { + const el = root(); + const nameSize = d.name.length > 18 ? 32 : d.name.length > 14 ? 36 : 40; + const backs = Array.from({ length: d.stack || 0 }, (_, i) => + photoHTML('back', BACK_ART[i % BACK_ART.length], '
')).join(''); + const extraHearts = Array.from({ length: d.hearts || 0 }, () => + ``).join(''); + el.innerHTML = backs + ` +
+
+
+
${esc(d.name)}${esc(d.line)}${d.msg ? `“${esc(d.msg)}”` : ''}
+ + ${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 = []; + 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' }); + 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' }); + + // sound as the photo lands; hold covers the whole sound + const hold = Math.max(MIN_HOLD, (SOUND_MS[d.sound] || 0) + SOUND_PAD); + const cur = current = { anims, timer:null, audio:null }; + if (d.sound) { + const a = new Audio(SND(d.sound)); a.volume = VOLUME; + cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + 400); + } + + // 5. exit: lift and drop away + const exitAt = t0 + 2400 + hold; + 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, reset, describe }; + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload(); +})(); diff --git a/src/alerts.js b/src/alerts.js new file mode 100644 index 0000000..0beee16 --- /dev/null +++ b/src/alerts.js @@ -0,0 +1,127 @@ +// 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)]; + default: return [alert.type, null]; + } +} + +function send(alert, raw = null) { + if (!alert) return; + console.log(`[alerts] ${alert.type} — ${alert.user ?? 'anonymous'} ${JSON.stringify({ ...alert, type: undefined, user: undefined })}`); + ws.broadcast({ type: 'alert', alert }); + const [eventType, detail] = legacy(alert); + dispatch.dispatchEvent(eventType, detail, alert.user, raw || alert); +} + +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.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 + } +} + +// --- 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' }, +}; + +const TEST_KEYS = [...Object.keys(SAMPLES), 'queue-test']; + +// Test alerts go straight to the overlay; they are not logged and do not fire actions. +// test:true makes the overlay drop what it is showing (fast checking); +// 'queue-test' sends four alerts that queue like real ones. +function sendTest(key) { + 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 = { send, sendTest, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromChatNotification, fromOverlayNotice }; diff --git a/src/app.js b/src/app.js index 73b2691..e9a8557 100644 --- a/src/app.js +++ b/src/app.js @@ -53,6 +53,7 @@ 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('/alerts', requireAuth, require('./routers/alerts')); app.use('/', requireAuth, require('./routers/dashboard')); module.exports = app; diff --git a/src/db.js b/src/db.js index 46464d6..ffac595 100644 --- a/src/db.js +++ b/src/db.js @@ -130,6 +130,15 @@ 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(); @@ -243,7 +252,7 @@ function getActivityLog(limit = 50) { module.exports = { init, - upsertUser, getUserById, + upsertUser, getUserById, getPrimaryUser, updateUserTokens, getSettings, updateSettings, getLayout, updateLayout, updateLayoutPositions, getAllMedia, getMediaFile, createMedia, deleteMedia, diff --git a/src/eventsub.js b/src/eventsub.js index faeae1c..a88e95b 100644 --- a/src/eventsub.js +++ b/src/eventsub.js @@ -1,118 +1,182 @@ +// 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 twitch = require('./twitch'); +const alerts = require('./alerts'); const dispatch = require('./dispatch'); 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 } }, + { type: 'channel.cheer', 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 } }, + { type: 'channel.channel_points_custom_reward_redemption.add', version: '1', condition: { broadcaster_user_id: b } }, ]; + try { await twitch.validate(); } catch (e) { console.error('[eventsub]', e.message); } + + 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); + switch (type) { + case 'channel.follow': + alerts.send(alerts.fromFollow(event), event); break; case 'channel.cheer': - dispatch.dispatchEvent('bits', String(event.bits), username, event); + alerts.send(alerts.fromCheer(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': - dispatch.dispatchEvent('channel_points', event.reward?.id, username, event); - break; - case 'channel.follow': - dispatch.dispatchEvent('follow', null, username, event); - break; - case 'channel.raid': - dispatch.dispatchEvent('raid', null, username, event); + // no polaroid alert yet; existing actions still fire + dispatch.dispatchEvent('channel_points', event.reward?.id, event.user_name || event.user_login, event); break; } } -module.exports = { start, stop }; +function getStatus() { return { ...status, running: shouldRun }; } + +module.exports = { start, stop, getStatus }; diff --git a/src/routers/alerts.js b/src/routers/alerts.js new file mode 100644 index 0000000..203ffdd --- /dev/null +++ b/src/routers/alerts.js @@ -0,0 +1,11 @@ +const express = require('express'); +const router = express.Router(); +const alerts = require('../alerts'); + +// 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 }); +}); + +module.exports = router; diff --git a/src/routers/auth.js b/src/routers/auth.js index 4168e65..3a5d20f 100644 --- a/src/routers/auth.js +++ b/src/routers/auth.js @@ -11,6 +11,7 @@ const SCOPES = [ 'bits:read', 'channel:read:redemptions', 'moderator:read:followers', + 'user:read:chat', // channel.chat.notification (sub/gift/raid details) ].join(' '); router.get('/login', (req, res) => { @@ -81,7 +82,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..78cfe6f 100644 --- a/src/routers/dashboard.js +++ b/src/routers/dashboard.js @@ -1,11 +1,13 @@ const express = require('express'); const router = express.Router(); const db = require('../db'); +const eventsub = require('../eventsub'); +const alerts = require('../alerts'); router.get('/', (req, res) => { const logs = db.getActivityLog(50); const settings = db.getSettings(); - res.render('dashboard', { logs, settings }); + res.render('dashboard', { logs, settings, eventsubStatus: eventsub.getStatus(), testKeys: alerts.TEST_KEYS }); }); module.exports = router; diff --git a/src/routers/settings.js b/src/routers/settings.js index dcd59e6..4dd2b84 100644 --- a/src/routers/settings.js +++ b/src/routers/settings.js @@ -39,7 +39,7 @@ router.post('/', (req, res) => { router.post('/reconnect', (req, res) => { const user = db.getUserById(req.session.userId); if (user) { - eventsub.start(user.access_token, user.twitch_id); + eventsub.start(user); console.log('[settings] EventSub reconnect triggered'); } res.redirect('/settings'); diff --git a/src/server.js b/src/server.js index b680599..b819fc7 100644 --- a/src/server.js +++ b/src/server.js @@ -18,4 +18,15 @@ server.listen(PORT, () => { console.log(`[server] HeyStreamer running on port ${PORT}`); console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`); console.log(`[server] DB_PATH: ${process.env.DB_PATH}`); + + // Resume EventSub with the stored login, so alerts survive restarts and deploys + // without logging in again. (Set EVENTSUB_DISABLED=1 for local UI work.) + const user = db.getPrimaryUser(); + if (process.env.EVENTSUB_DISABLED === '1') { + console.log('[server] EventSub disabled (EVENTSUB_DISABLED=1)'); + } else if (user) { + require('./eventsub').start(user); + } else { + console.log('[server] No Twitch login stored yet — log in at /auth/login to start alerts'); + } }); diff --git a/src/twitch.js b/src/twitch.js new file mode 100644 index 0000000..58b5a32 --- /dev/null +++ b/src/twitch.js @@ -0,0 +1,75 @@ +// Twitch API access for the streamer account: holds the user token, validates it hourly +// (Twitch asks apps to), and refreshes it when it expires (user tokens last ~4 hours). +const db = require('./db'); + +const CLIENT_ID = process.env.TWITCH_CLIENT_ID; +const CLIENT_SECRET = process.env.TWITCH_CLIENT_SECRET; + +let user = null; // users row +let refreshing = null; // in-flight refresh promise, so parallel 401s refresh once +let validateTimer = null; + +function setUser(u) { + user = u; + clearInterval(validateTimer); + if (u) validateTimer = setInterval(() => validate().catch(e => console.error('[twitch] validate:', e.message)), 60 * 60 * 1000); +} + +function getUser() { return user; } +function token() { return user?.access_token; } + +async function refresh() { + if (!user) throw new Error('no user'); + if (refreshing) return refreshing; + refreshing = (async () => { + const res = await fetch('https://id.twitch.tv/oauth2/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + client_id: CLIENT_ID, client_secret: CLIENT_SECRET, + grant_type: 'refresh_token', refresh_token: user.refresh_token, + }), + }); + const body = await res.json().catch(() => ({})); + if (!res.ok || !body.access_token) { + throw new Error(`token refresh failed (${res.status}): ${body.message || 'unknown'} — log in again at /auth/login`); + } + db.updateUserTokens(user.id, body.access_token, body.refresh_token || user.refresh_token); + user = db.getUserById(user.id); + console.log('[twitch] Token refreshed'); + })(); + try { await refreshing; } finally { refreshing = null; } +} + +// Returns true when the token is (now) valid. +async function validate() { + if (!user) return false; + const res = await fetch('https://id.twitch.tv/oauth2/validate', { headers: { Authorization: `OAuth ${token()}` } }); + if (res.status === 401) { await refresh(); return true; } + if (res.ok) { + const info = await res.json(); + if (info.expires_in < 15 * 60) await refresh(); // refresh early, before a reconnect needs it + return true; + } + return false; +} + +// Helix call with one automatic refresh-and-retry on 401. +async function helix(path, { method = 'GET', body } = {}, retry = true) { + const res = await fetch(`https://api.twitch.tv/helix${path}`, { + method, + headers: { + Authorization: `Bearer ${token()}`, + 'Client-Id': CLIENT_ID, + ...(body ? { 'Content-Type': 'application/json' } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + }); + if (res.status === 401 && retry) { + await refresh(); + return helix(path, { method, body }, false); + } + return res; +} + +module.exports = { setUser, getUser, token, refresh, validate, helix }; diff --git a/src/ws.js b/src/ws.js index 4d7531d..91a9015 100644 --- a/src/ws.js +++ b/src/ws.js @@ -2,10 +2,25 @@ const { WebSocket } = require('ws'); const clients = new Set(); +// Overlay -> server messages. Only accepted from connections that present the overlay UUID +// (?overlay=, the same secret as the OBS URL), so strangers cannot inject alerts. +function handleIncoming(raw) { + let msg; + try { msg = JSON.parse(raw); } catch { return; } + if (msg?.type === 'chat_notice') { + const alerts = require('./alerts'); // lazy: alerts.js requires this module + alerts.send(alerts.fromOverlayNotice(msg)); + } +} + function init(wss) { - wss.on('connection', (ws) => { + wss.on('connection', (ws, req) => { clients.add(ws); - console.log(`[ws] Client connected — total: ${clients.size}`); + const db = require('./db'); + const overlayId = new URL(req.url, 'http://x').searchParams.get('overlay'); + const trusted = !!overlayId && overlayId === db.getSettings().overlay_id; + console.log(`[ws] Client connected${trusted ? ' (overlay)' : ''} — total: ${clients.size}`); + if (trusted) ws.on('message', data => handleIncoming(String(data).slice(0, 2000))); ws.on('close', () => { clients.delete(ws); console.log(`[ws] Client disconnected — total: ${clients.size}`); diff --git a/views/dashboard.ejs b/views/dashboard.ejs index 702ac8d..e6d8464 100644 --- a/views/dashboard.ejs +++ b/views/dashboard.ejs @@ -11,6 +11,38 @@ +

Twitch connection

+

+ <% if (eventsubStatus.connected) { %> + connected + <% } else if (eventsubStatus.running) { %> + connecting… + <% } else { %> + not running (log in again to start) + <% } %> + <% if (eventsubStatus.subscribed.length) { %>
Listening to: <%= eventsubStatus.subscribed.join(', ') %><% } %> + <% if (eventsubStatus.failed.length) { %>
Failed: <%= eventsubStatus.failed.join(', ') %> (log out and in again if a permission is missing)<% } %> + <% if (eventsubStatus.lastEventAt) { %>
Last event: <%= eventsubStatus.lastEventAt %><% } %> +

+ +

Test alerts

+

Sends a sample alert to the overlay (OBS). Not logged, no actions fired.

+
+ <% for (const key of testKeys) { %> + + <% } %> +
+

+ +

Recent activity

<% if (logs.length === 0) { %>

No activity yet. Events will appear here once your overlay is connected and Twitch fires events.

diff --git a/views/overlay.ejs b/views/overlay.ejs index b1e57bb..db65550 100644 --- a/views/overlay.ejs +++ b/views/overlay.ejs @@ -2,6 +2,9 @@ + + + - - -
-
channel: This is a preview message
-
someviewer: Looking great!
-
anotheruser: pog pog pog
-
-
Alert preview
-
-
- - From 1766e373369577c51cb9295aed459bc5decaaa15 Mon Sep 17 00:00:00 2001 From: Bashy Date: Fri, 20 Nov 2026 23:18:15 +0200 Subject: [PATCH 05/40] Overlay: cassette redeems, emote effects, poll card, Hype Train bar, raid card New overlay modules (taped-paper look, shared with the polaroid alerts): - cassette.js: redeems as a cassette tape; rarity = shell colour (Ultra Rare gold with glow, foil and sparkles), reels spin for the sound's length, sticker corner. - fx.js: Gigantify (viewer's emote grows giant), On-Screen Celebration (emote copies bounce around the screen), highlight / Message Effect (tall taped note). - poll.js: live poll card with bars, countdown and a WINNER stamp. - hypebar.js: persistent Hype Train strip (level, progress, time left). - raidcard.js: silent raid send-off card that stays during the raid countdown. - nowplaying.js: Feishin now-playing slip (not loaded yet, see overlay). polaroid.js: shared queue now also drives cassettes/effects; test alerts replace only other tests and never cut off real alerts; alerts stay up for the animation + 3 s or the sound's length; sound lengths measured in the browser for UI-picked sounds; tip and Hype Train alerts; optional ALERTS_BASE for offline test pages. Co-Authored-By: Claude Opus 5.5 --- public/alerts/cassette.css | 40 ++++++++++ public/alerts/cassette.js | 123 ++++++++++++++++++++++++++++++ public/alerts/fx.css | 33 ++++++++ public/alerts/fx.js | 127 +++++++++++++++++++++++++++++++ public/alerts/hypebar.css | 14 ++++ public/alerts/hypebar.js | 43 +++++++++++ public/alerts/nowplaying.css | 16 ++++ public/alerts/nowplaying.js | 53 +++++++++++++ public/alerts/polaroid.css | 8 ++ public/alerts/polaroid.js | 143 ++++++++++++++++++++++++++++++----- public/alerts/poll.css | 23 ++++++ public/alerts/poll.js | 91 ++++++++++++++++++++++ public/alerts/raidcard.css | 15 ++++ public/alerts/raidcard.js | 63 +++++++++++++++ 14 files changed, 774 insertions(+), 18 deletions(-) create mode 100644 public/alerts/cassette.css create mode 100644 public/alerts/cassette.js create mode 100644 public/alerts/fx.css create mode 100644 public/alerts/fx.js create mode 100644 public/alerts/hypebar.css create mode 100644 public/alerts/hypebar.js create mode 100644 public/alerts/nowplaying.css create mode 100644 public/alerts/nowplaying.js create mode 100644 public/alerts/poll.css create mode 100644 public/alerts/poll.js create mode 100644 public/alerts/raidcard.css create mode 100644 public/alerts/raidcard.js diff --git a/public/alerts/cassette.css b/public/alerts/cassette.css new file mode 100644 index 0000000..62f615d --- /dev/null +++ b/public/alerts/cassette.css @@ -0,0 +1,40 @@ +/* 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); } diff --git a/public/alerts/cassette.js b/public/alerts/cassette.js new file mode 100644 index 0000000..e5b1ad4 --- /dev/null +++ b/public/alerts/cassette.js @@ -0,0 +1,123 @@ +/* + 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; + const DEFAULT_STICKER = (window.ALERTS_BASE || '/alerts/') + 'stickers/default-sticker.png'; + 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) : ''}
+
+ ${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)' }); + 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..87fa550 --- /dev/null +++ b/public/alerts/fx.css @@ -0,0 +1,33 @@ +/* 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; } diff --git a/public/alerts/fx.js b/public/alerts/fx.js new file mode 100644 index 0000000..6a91e6a --- /dev/null +++ b/public/alerts/fx.js @@ -0,0 +1,127 @@ +/* + 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 + 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; + const FALLBACK = window.FX_FALLBACK || (window.ALERTS_BASE || '/alerts/') + 'art/Heart.png'; // when Twitch sends no emote + 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 + const exitAt = Math.max(650 + AFTER_ANIM, 650 + read, SOUND_LEAD + snd.len); + 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' })); + } + + window.FxAlert = { giant, rain, message, 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 index fe99976..816b821 100644 --- a/public/alerts/polaroid.css +++ b/public/alerts/polaroid.css @@ -31,3 +31,11 @@ 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; } diff --git a/public/alerts/polaroid.js b/public/alerts/polaroid.js index 09a0d63..815b60a 100644 --- a/public/alerts/polaroid.js +++ b/public/alerts/polaroid.js @@ -1,8 +1,11 @@ /* Polaroid alerts for the OBS overlay. - window.PolaroidAlerts.play(alert) queue an alert (never overlaps) - window.PolaroidAlerts.reset() stop the current alert and clear the queue + 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 Alert shapes come from src/alerts.js: { type:'follow', user } @@ -11,19 +14,25 @@ { 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 = '/alerts/'; - const ART = n => `${BASE}art/${n}`; + const BASE = window.ALERTS_BASE || '/alerts/'; // ALERTS_BASE: only set by offline test pages + const rebase = u => (u && u.startsWith('/alerts/') && BASE !== '/alerts/') ? BASE + u.slice(8) : u; + const ART = n => /^(https?:)?\/\//.test(n) ? n : `${BASE}art/${n}`; // full URLs (e.g. Twitch avatars) pass through const SND = n => `${BASE}sounds/${n}`; const 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)', + bits:'rgba(190,160,240,.88)', redeem:'rgba(140,215,215,.88)', }; // bits: under BITS_MIN = no alert; otherwise the highest matching tier wins @@ -42,6 +51,7 @@ 'duck-toy-sound.mp3':960, 'wow.mp3':2325, 'huh.mp3':1123, 'correct-answer.wav':1960, 'opatski.mp3':1416, 'we-do-a-little-trolling_80cJgd9.mp3':2691, 'windows-xp-startup_1ph012N.mp3':4911, 'run-vine-sound-effect.mp3':8280, 'TomDaTankLoud.mp3':10057, 'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3':2038, + 'emotional-damage-meme.mp3':3369, }; const BACK_ART = ['CharacterHeart.png','CharacterLoveEyes_Glasses.png','CharacterHappy.png', @@ -49,8 +59,8 @@ 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 MIN_HOLD = 6000; // ms fully visible, at least - const SOUND_PAD = 1500; // ms after the sound ends + 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. @@ -89,6 +99,36 @@ return { art:'CharacterPolice.png', name:who, line:`is raiding with ${e.viewers} viewers!`, tape:TAPE.raid, sound:'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3', badge:{ big:e.viewers, small:'raiders' }, 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:'CharacterLoveEyes_Glasses.png', name:who, line:`tipped ${money}! ♡`, msg:e.message, sound:'emotional-damage-meme.mp3', + tape:'rgba(246,206,110,.9)', badge:{ big:money, small:'tip', color:'#e0a21b' }, hearts, + phbg:'linear-gradient(#fff6dc,#fbe0a8)' }; + } + case 'hype': { + // Hype Train: start / level up / end, HYPE Streamer, sounds picked from the library + const name = e.golden ? 'Golden Kappa Train' : e.treasure ? 'Treasure Train' : 'Hype Train'; + const line = e.phase === 'begin' ? 'is leaving the station! choo choo 🚂' + : e.phase === 'level' ? `reached level ${e.level}!` : `ended at level ${e.level}! ♡`; + const sound = { begin:'/alerts/sounds/redeems/pro-gamer.mp3', level:'/alerts/sounds/redeems/toad-ya-hoo.mp3', + end:'/alerts/sounds/redeems/tadaaa.mp3' }[e.phase]; + return { art:'CharacterHype2.png', name, line, tape: e.golden ? 'rgba(246,206,110,.95)' : TAPE.raid, sound, + 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, + 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 }; + } case 'bits': { if (!(e.bits >= BITS_MIN)) return null; const t = BITS_TIERS.find(t => e.bits >= t.min); @@ -119,16 +159,58 @@ 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(); + 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 + } + function reset() { gen++; queue.length = 0; @@ -139,6 +221,7 @@ current = null; } if (el) el.style.visibility = 'hidden'; + window.CassetteAlert?.hide(); window.FxAlert?.hide(); busy = false; } @@ -156,8 +239,32 @@ return `
${inner}
`; } - function show(d) { + 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 + + const fx = { emote: 'giant', emote_rain: 'rain', message: 'message' }[d.style]; + if (fx && !d.soundOnly && window.FxAlert) { + return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? VOLUME }) + .then(() => { if (current === cur) current = null; }); + } + if (d.cassette && !d.soundOnly && window.CassetteAlert) { + return window.CassetteAlert.show(d, cur, { url, len, volume: d.volume ?? VOLUME }) + .then(() => { if (current === cur) current = null; }); + } + + if (d.soundOnly) { // no picture: play the sound, hold the queue for its length + if (!url) return; + const a = cur.audio = new Audio(url); a.volume = d.volume ?? VOLUME; + 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 backs = Array.from({ length: d.stack || 0 }, (_, i) => photoHTML('back', BACK_ART[i % BACK_ART.length], '
')).join(''); @@ -166,7 +273,7 @@ el.innerHTML = backs + `
-
+
${d.tag ? `${esc(d.tag)}` : ''}
${esc(d.name)}${esc(d.line)}${d.msg ? `“${esc(d.msg)}”` : ''}
${extraHearts} @@ -178,7 +285,7 @@ const main = q('.photo.main'); const tilt = between(RANGES.photoTilt) * (rnd() < .5 ? -1 : 1); const rot = dd => `rotate(${tilt + dd}deg)`; - const anims = []; + 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) @@ -234,16 +341,16 @@ A(q('.cap'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }], { delay:t0 + 1700, duration:700, easing:'ease-in-out' }); - // sound as the photo lands; hold covers the whole sound - const hold = Math.max(MIN_HOLD, (SOUND_MS[d.sound] || 0) + SOUND_PAD); - const cur = current = { anims, timer:null, audio:null }; - if (d.sound) { - const a = new Audio(SND(d.sound)); a.volume = VOLUME; - cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + 400); + // 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 ?? 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 = t0 + 2400 + hold; + 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 }, @@ -255,6 +362,6 @@ .catch(() => {}); // cancelled by reset() } - window.PolaroidAlerts = { play, reset, describe }; + window.PolaroidAlerts = { play, playTest, reset, 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..0fc9c06 --- /dev/null +++ b/public/alerts/poll.js @@ -0,0 +1,91 @@ +/* + 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']; + const HEART = (window.ALERTS_BASE || '/alerts/') + 'art/Heart.png'; + 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..8864b71 --- /dev/null +++ b/public/alerts/raidcard.js @@ -0,0 +1,63 @@ +/* + 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/'; + const FALLBACK = BASE + 'art/CharacterHappy.png'; + 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 }; +})(); From 553cc35b9ea5fc8a5c011063a55874c691d14e4c Mon Sep 17 00:00:00 2001 From: Bashy Date: Fri, 20 Nov 2026 23:18:15 +0200 Subject: [PATCH 06/40] Add Redeems: channel points, built-in rewards and bits Power-ups - reward_variations (src/db.js in the wiring commit): each trigger has variations, one is picked at random weighted by rarity (Common 50 / Uncommon 25 / Rare 12 / Ultra Rare 3), like Twitch alert variations. - /redeems page: rewards listed live from Twitch, plus Power-ups and built-in rewards; per variation name, rarity (with % chance), sound + volume, show cassette or sound only, caption, sticker, on/off, play/test/two-click delete. - Special styles: Gigantify -> giant emote, Celebration -> bouncing emotes, Highlight my message / Message Effect -> big taped note. - redeems-seed.json: first-run defaults rebuilt from the Twitch alert setup (96 variations, 21 triggers); only loaded when the table is empty. Co-Authored-By: Claude Opus 5.5 --- src/redeems-seed.json | 41 +++++++++++++ src/redeems.js | 89 +++++++++++++++++++++++++++ src/routers/redeems.js | 110 ++++++++++++++++++++++++++++++++++ views/redeems.ejs | 132 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 372 insertions(+) create mode 100644 src/redeems-seed.json create mode 100644 src/redeems.js create mode 100644 src/routers/redeems.js create mode 100644 views/redeems.ejs 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..a92e8d4 --- /dev/null +++ b/src/redeems.js @@ -0,0 +1,89 @@ +// 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'); + +// 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', +}; + +// 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:' }; +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 }) { + const style = STYLE[`${v.kind}:${v.key}`] || 'cassette'; + return { + type: 'redeem', kind: v.kind, key: v.key, style, + user, reward: v.title, variation: v.name, rarity: v.rarity, input: input || null, + // special styles have their own wording unless the caption was customised + caption: style !== 'cassette' && v.caption === 'redeemed it! ♡' ? LINE[style] : v.caption, + sound: v.sound || null, volume: v.volume, polaroid: !!v.polaroid, art: v.art || null, emote: emoteUrl(emote), + }; +} + +// legacy action event type for the actions system / activity log +const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up' }; + +// A redemption arrived from Twitch. +function handle(kind, key, title, { user, input, emote }, 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 }); + alerts.send(alert, raw); + 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 = ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!' + : v.kind === 'reward' ? 'test input' : null; + alerts.sendTestAlert(toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null })); // 25 = Kappa + return true; +} + +module.exports = { RARITY, AUTO_REWARDS, POWER_UPS, STYLE, pick, handle, test }; diff --git a/src/routers/redeems.js b/src/routers/redeems.js new file mode 100644 index 0000000..504acd0 --- /dev/null +++ b/src/routers/redeems.js @@ -0,0 +1,110 @@ +const express = require('express'); +const fs = require('fs'); +const path = require('path'); +const router = express.Router(); +const db = require('../db'); +const twitch = require('../twitch'); +const redeems = require('../redeems'); + +const PUBLIC = path.join(__dirname, '../../public'); +const listDir = (dir, re) => { try { return fs.readdirSync(path.join(PUBLIC, dir)).filter(f => re.test(f)).sort(); } catch { return []; } }; + +function soundOptions() { + const re = /\.(mp3|wav|ogg|m4a)$/i; + const lib = [ + ...listDir('alerts/sounds/redeems', re).map(f => ({ url: `/alerts/sounds/redeems/${f}`, label: `${f} (normalized)` })), + ...listDir('alerts/sounds', re).map(f => ({ url: `/alerts/sounds/${f}`, label: f })), + ]; + const uploads = db.getAllMedia().filter(m => m.media_type === 'audio') + .map(m => ({ url: `/media/${m.filename}`, label: `${m.original_name} (uploaded)` })); + return [...lib, ...uploads]; +} + +// live list of the channel's custom rewards (title, cost, icon); null when Twitch is not reachable +async function twitchRewards() { + const u = twitch.getUser(); + if (!u) return null; + try { + const res = await twitch.helix(`/channel_points/custom_rewards?broadcaster_id=${u.twitch_id}`); + if (!res.ok) return null; + return (await res.json()).data.map(r => ({ + kind: 'reward', key: r.id, title: r.title, cost: r.cost, live: r.is_enabled, + image: r.image?.url_1x || r.default_image?.url_1x || null, + })); + } catch { return null; } +} + +router.get('/', async (req, res) => { + const variations = db.getAllVariations(); + const byTrigger = new Map(); + for (const v of variations) { + const k = `${v.kind}|${v.key}`; + if (!byTrigger.has(k)) byTrigger.set(k, []); + byTrigger.get(k).push(v); + } + + const fromTwitch = await twitchRewards(); + const rewards = fromTwitch ? [...fromTwitch] : []; + // rewards that have variations but were not in the Twitch list (offline, or deleted on Twitch) + for (const v of variations) { + if (v.kind === 'reward' && !rewards.some(r => r.key === v.key)) { + rewards.push({ kind: 'reward', key: v.key, title: v.title, cost: null, missing: !!fromTwitch }); + } + } + const uniq = (list) => list.filter((r, i) => list.findIndex(x => x.key === r.key) === i); + const groups = [ + { name: 'Channel point rewards', items: uniq(rewards).sort((a, b) => (a.cost ?? 1e9) - (b.cost ?? 1e9)) }, + { name: 'Bits Power-ups', items: Object.entries(redeems.POWER_UPS).map(([key, title]) => ({ kind: 'power_up', key, title })) }, + { name: 'Built-in channel point rewards', items: Object.entries(redeems.AUTO_REWARDS).map(([key, title]) => ({ kind: 'auto_reward', key, title })) }, + ]; + for (const g of groups) for (const t of g.items) t.variations = byTrigger.get(`${t.kind}|${t.key}`) || []; + + res.render('redeems', { + groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY, + sounds: soundOptions(), + stickers: [ + ...listDir('alerts/stickers', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/stickers/${f}`, label: f.replace(/\.\w+$/, '') })), + ...listDir('alerts/art', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/art/${f}`, label: f.replace('_Contrast', '').replace(/\.\w+$/, '') })), + ], + }); +}); + +const back = (res, v) => res.redirect(`/redeems#t-${encodeURIComponent(`${v.kind}-${v.key}`)}`); + +router.post('/variation', (req, res) => { + const { kind, key, title } = req.body; + if (!['reward', 'auto_reward', 'power_up'].includes(kind) || !key) return res.status(400).send('bad trigger'); + const n = db.getVariationsFor(kind, key).length; + const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key) }); + back(res, v); +}); + +router.post('/variation/:id', (req, res) => { + const v = db.getVariation(req.params.id); + if (!v) return res.status(404).send('not found'); + const b = req.body; + const vol = parseFloat(b.volume); + db.updateVariation(v.id, { + name: (b.name || '').trim() || v.name, + rarity: redeems.RARITY[b.rarity] ? b.rarity : v.rarity, + sound: b.sound || '', + volume: isNaN(vol) ? v.volume : Math.max(0, Math.min(1, vol)), + polaroid: b.polaroid === 'on' ? 1 : 0, + caption: (b.caption || '').trim() || 'redeemed it! ♡', + art: b.art || '', + enabled: b.enabled === 'on' ? 1 : 0, + }); + back(res, v); +}); + +router.post('/variation/:id/delete', (req, res) => { + const v = db.getVariation(req.params.id); + if (v) db.deleteVariation(v.id); + v ? back(res, v) : res.redirect('/redeems'); +}); + +// tests send the alert to the overlay only (not logged) +router.post('/variation/:id/test', (req, res) => res.json({ ok: redeems.test({ id: req.params.id }) })); +router.post('/trigger/test', (req, res) => res.json({ ok: redeems.test({ kind: req.body.kind, key: req.body.key }) })); + +module.exports = router; diff --git a/views/redeems.ejs b/views/redeems.ejs new file mode 100644 index 0000000..3b5912f --- /dev/null +++ b/views/redeems.ejs @@ -0,0 +1,132 @@ + + +

Redeems

+

+ Each redeem plays one of its enabled variations, picked at random by rarity + (<% for (const [k, r] of Object.entries(rarity)) { %><%= r.label %> <%= r.weight %><% if (k !== 'ultra_rare') { %> · <% } %><% } %>, relative weights). + Sounds: built-in library, or upload more on the Media page. + <% if (!twitchOk) { %>
Could not load your rewards from Twitch right now, so only rewards that already have variations are listed.<% } %> +

+ +<% for (const g of groups) { %> +

<%= g.name %>

+ <% for (const t of g.items) { + const on = t.variations.filter(v => v.enabled); + const total = on.reduce((s, v) => s + (rarity[v.rarity]?.weight || 1), 0); + const anchor = `t-${t.kind}-${t.key}`; %> +
+ + <% if (t.image) { %><% } %> + <%= t.title %> + <% if (t.cost != null) { %><%= t.cost %> pts<% } %> + <% if (t.missing) { %>not on Twitch anymore<% } %> + <% if (t.live === false) { %>paused on Twitch<% } %> + + <%= t.variations.length ? `${on.length}/${t.variations.length} variation${t.variations.length === 1 ? '' : 's'} on` : 'no alert' %> + + <% if (on.length) { %> + + <% } %> + + + <% for (const v of t.variations) { %> +
+
+
+ + <% if (v.enabled && total) { %><%= Math.round(100 * (rarity[v.rarity]?.weight || 1) / total) %>% chance<% } %> +
+
+ +
+
+
+ + + + + + + + + +
+
+ <% } %> + +
+ + + + +
+
+ <% } %> +<% } %> + +

+ + From b28e56f99162e0a61bf95a6b4f0fc83aa41c2157 Mon Sep 17 00:00:00 2001 From: Bashy Date: Fri, 20 Nov 2026 23:18:15 +0200 Subject: [PATCH 07/40] Add StreamElements tips and a Feishin now-playing helper (disabled) - src/streamelements.js: StreamElements Astro websocket, channel.tips with SE_JWT. Only allowed + successful tips alert, deduped by id, follows reconnect tokens. Off unless SE_JWT is set. - tools/nowplaying/: PC helper that reads Feishin over MPRIS and posts title, artist and a small cover thumbnail to /nowplaying (Bearer NOWPLAYING_KEY). The cover is fetched on the LAN so the Navidrome token never leaves the PC. Endpoint and overlay widget are kept but switched off for now. - .env.example: SE_JWT, NOWPLAYING_KEY. Co-Authored-By: Claude Opus 5.5 --- .env.example | 6 + src/nowplaying.js | 12 ++ src/routers/nowplaying.js | 28 +++++ src/streamelements.js | 75 +++++++++++ tools/nowplaying/feishin_nowplaying.py | 119 ++++++++++++++++++ .../nowplaying/heystreamer-nowplaying.service | 13 ++ 6 files changed, 253 insertions(+) create mode 100644 src/nowplaying.js create mode 100644 src/routers/nowplaying.js create mode 100644 src/streamelements.js create mode 100755 tools/nowplaying/feishin_nowplaying.py create mode 100644 tools/nowplaying/heystreamer-nowplaying.service 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/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/routers/nowplaying.js b/src/routers/nowplaying.js new file mode 100644 index 0000000..6042a85 --- /dev/null +++ b/src/routers/nowplaying.js @@ -0,0 +1,28 @@ +const express = require('express'); +const crypto = require('crypto'); +const router = express.Router(); +const nowplaying = require('../nowplaying'); + +// POST /nowplaying (Authorization: Bearer ) from the PC helper; no login session involved. +const key = () => process.env.NOWPLAYING_KEY || ''; +function authorized(req) { + const k = key(), got = (req.get('authorization') || '').replace(/^Bearer\s+/i, ''); + if (!k || !got) return false; + const a = Buffer.from(k), b = Buffer.from(got); + return a.length === b.length && crypto.timingSafeEqual(a, b); +} +const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : ''); + +router.post('/', express.json({ limit: '300kb' }), (req, res) => { + if (!authorized(req)) return res.status(401).json({ ok: false }); + const b = req.body || {}; + const cover = typeof b.cover === 'string' && /^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/.test(b.cover) && b.cover.length < 250000 ? b.cover : null; + nowplaying.set({ + playing: b.status === 'Playing', + title: str(b.title, 200), artist: str(b.artist, 200), album: str(b.album, 200), + length: Number.isFinite(b.length) ? b.length : null, cover, + }); + res.json({ ok: true }); +}); + +module.exports = router; diff --git a/src/streamelements.js b/src/streamelements.js new file mode 100644 index 0000000..3315f5b --- /dev/null +++ b/src/streamelements.js @@ -0,0 +1,75 @@ +// StreamElements tips via the Astro websocket (https://docs.streamelements.com/websockets). +// Set SE_JWT in .env (StreamElements dashboard -> avatar -> channel -> copy JWT token). Unset = off. +// Protocol: welcome -> subscribe {topic:'channel.tips', token, token_type:'jwt'} -> messages on topic channel.tips. +// Server PINGs every 30 s (ws answers PONG automatically); a 'reconnect' message carries reconnect_token, +// and connecting with ?reconnect_token= restores subscriptions without subscribing again. +const { WebSocket } = require('ws'); +const alerts = require('./alerts'); + +const URL_BASE = process.env.SE_URL || 'wss://astro.streamelements.com'; +let ws = null, shouldRun = false, retryTimer = null, retryMs = 5000; +const status = { enabled: false, connected: false, subscribed: false, error: null, lastTipAt: null }; +const seen = new Map(); // tip _id -> time, so a resent tip alerts only once + +function start() { + if (!process.env.SE_JWT) { console.log('[se] SE_JWT not set: StreamElements tips off'); return; } + status.enabled = true; shouldRun = true; + connect(URL_BASE, true); +} + +function stop() { + shouldRun = false; clearTimeout(retryTimer); + if (ws) { ws.removeAllListeners('close'); ws.close(); ws = null; } + status.connected = status.subscribed = false; +} + +function connect(url, subscribe) { + console.log(`[se] Connecting${subscribe ? '' : ' (reconnect token)'}...`); + const sock = new WebSocket(url); + sock.on('message', raw => { let m; try { m = JSON.parse(raw); } catch { return; } handle(sock, m, subscribe); }); + sock.on('close', (code) => { + if (sock !== ws) return; + status.connected = status.subscribed = false; + console.log(`[se] Disconnected (${code})`); + if (shouldRun) { clearTimeout(retryTimer); retryTimer = setTimeout(() => connect(URL_BASE, true), retryMs); retryMs = Math.min(retryMs * 2, 120000); } + }); + sock.on('error', e => { status.error = e.message; console.error('[se] Error:', e.message); }); + const old = ws; ws = sock; + if (old) { old.removeAllListeners('close'); old.close(); } +} + +function handle(sock, m, subscribe) { + switch (m.type) { + case 'welcome': + status.connected = true; status.error = null; retryMs = 5000; + if (subscribe) sock.send(JSON.stringify({ type: 'subscribe', nonce: 'tips-' + Date.now(), + data: { topic: 'channel.tips', token: process.env.SE_JWT, token_type: 'jwt' } })); + else status.subscribed = true; + break; + case 'response': + if (m.error) { status.error = `${m.error}: ${m.data?.message || ''}`; console.error('[se] Subscribe failed:', status.error); } + else { status.subscribed = true; console.log(`[se] Subscribed to ${m.data?.topic} (room ${m.data?.room})`); } + break; + case 'reconnect': + if (m.data?.reconnect_token) connect(`${URL_BASE}/?reconnect_token=${encodeURIComponent(m.data.reconnect_token)}`, false); + break; + case 'message': + if (m.topic === 'channel.tips') tip(m.data); + break; + } +} + +function tip(data) { + if (!data?.donation) return; + if (data.approved && data.approved !== 'allowed') { console.log(`[se] Tip ${data._id} not shown (approved: ${data.approved})`); return; } + if (data.status && data.status !== 'success') return; + const now = Date.now(); + for (const [id, t] of seen) if (now - t > 3600e3) seen.delete(id); + if (data._id && seen.has(data._id)) return; + if (data._id) seen.set(data._id, now); + status.lastTipAt = new Date().toISOString(); + alerts.send(alerts.fromTip(data), data); +} + +function getStatus() { return { ...status }; } +module.exports = { start, stop, getStatus }; diff --git a/tools/nowplaying/feishin_nowplaying.py b/tools/nowplaying/feishin_nowplaying.py new file mode 100755 index 0000000..35600a1 --- /dev/null +++ b/tools/nowplaying/feishin_nowplaying.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +""" +Feishin -> HeyStreamer "now playing". + +Watches Feishin over MPRIS (D-Bus) and POSTs {status, title, artist, album, length, cover} to +/nowplaying with "Authorization: Bearer ". + +The cover is fetched here on the LAN (Feishin's artUrl points at Navidrome and contains the +Subsonic login token) and sent as a small JPEG data URL, so no URL or credential leaves this PC. + +Config: ~/.config/heystreamer-nowplaying.env (HEYSTREAMER_URL=..., NOWPLAYING_KEY=...) +Run: python3 feishin_nowplaying.py (or the systemd user unit next to this file) +""" +import base64, io, json, os, sys, time, urllib.request +import gi +gi.require_version('Gio', '2.0') +from gi.repository import Gio, GLib + +BUS_NAME = 'org.mpris.MediaPlayer2.Feishin' +PATH, PLAYER_IF = '/org/mpris/MediaPlayer2', 'org.mpris.MediaPlayer2.Player' +HEARTBEAT_S = 30 + + +def load_config(): + cfg = dict(os.environ) + p = os.path.expanduser('~/.config/heystreamer-nowplaying.env') + if os.path.exists(p): + for line in open(p): + line = line.strip() + if line and not line.startswith('#') and '=' in line: + k, v = line.split('=', 1) + cfg.setdefault(k.strip(), v.strip().strip('"').strip("'")) + if not cfg.get('HEYSTREAMER_URL') or not cfg.get('NOWPLAYING_KEY'): + sys.exit('set HEYSTREAMER_URL and NOWPLAYING_KEY in ~/.config/heystreamer-nowplaying.env') + return cfg['HEYSTREAMER_URL'].rstrip('/'), cfg['NOWPLAYING_KEY'] + + +URL, KEY = load_config() +bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) +last_sent, cover_cache = None, {} + + +def prop(name): + try: + r = bus.call_sync(BUS_NAME, PATH, 'org.freedesktop.DBus.Properties', 'Get', + GLib.Variant('(ss)', (PLAYER_IF, name)), None, Gio.DBusCallFlags.NONE, 2000, None) + return r.unpack()[0] + except GLib.Error: + return None # Feishin not running + + +def cover_data(art_url): + """Fetch the cover on the LAN, shrink to 160 px JPEG, return a data URL (cached per URL).""" + if not art_url or not art_url.startswith(('http://', 'https://', 'file://')): + return None + if art_url in cover_cache: + return cover_cache[art_url] + try: + from PIL import Image + if art_url.startswith('file://'): + raw = open(urllib.request.url2pathname(art_url[7:]), 'rb').read() + else: + raw = urllib.request.urlopen(art_url, timeout=5).read() + im = Image.open(io.BytesIO(raw)).convert('RGB') + im.thumbnail((160, 160)) + buf = io.BytesIO(); im.save(buf, 'JPEG', quality=82) + data = 'data:image/jpeg;base64,' + base64.b64encode(buf.getvalue()).decode() + except Exception as e: + print('cover fetch failed:', type(e).__name__, flush=True) + data = None + cover_cache.clear(); cover_cache[art_url] = data + return data + + +def state(): + md, status = prop('Metadata'), prop('PlaybackStatus') + if not md or not status: + return {'status': 'Stopped', 'title': '', 'artist': '', 'album': '', 'length': None, 'cover': None} + artists = md.get('xesam:artist') or md.get('xesam:albumArtist') or [] + return { + 'status': status, + 'title': md.get('xesam:title') or '', + 'artist': ', '.join(artists) if isinstance(artists, list) else str(artists), + 'album': md.get('xesam:album') or '', + 'length': round(md['mpris:length'] / 1e6, 1) if md.get('mpris:length') else None, + 'cover': cover_data(md.get('mpris:artUrl')), + } + + +def send(force=False): + global last_sent + s = state() + sig = (s['status'], s['title'], s['artist']) + if not force and sig == last_sent: + return True + req = urllib.request.Request(URL + '/nowplaying', data=json.dumps(s).encode(), method='POST', + headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + KEY}) + try: + urllib.request.urlopen(req, timeout=8).read() + if sig != last_sent: + print(f"{s['status']}: {s['artist']} - {s['title']}", flush=True) + last_sent = sig + except Exception as e: + print('send failed:', type(e).__name__, getattr(e, 'code', ''), flush=True) + return True + + +def on_signal(*_): + GLib.timeout_add(150, lambda: send() and False) # let Feishin finish updating all properties + + +bus.signal_subscribe(BUS_NAME, 'org.freedesktop.DBus.Properties', 'PropertiesChanged', PATH, None, + Gio.DBusSignalFlags.NONE, on_signal) +bus.signal_subscribe('org.freedesktop.DBus', 'org.freedesktop.DBus', 'NameOwnerChanged', '/org/freedesktop/DBus', + BUS_NAME, Gio.DBusSignalFlags.NONE, on_signal) # Feishin started / quit +GLib.timeout_add_seconds(HEARTBEAT_S, lambda: send(force=True)) # overlay recovers after restarts +send(force=True) +print('watching Feishin ->', URL, flush=True) +GLib.MainLoop().run() diff --git a/tools/nowplaying/heystreamer-nowplaying.service b/tools/nowplaying/heystreamer-nowplaying.service new file mode 100644 index 0000000..3bf58c5 --- /dev/null +++ b/tools/nowplaying/heystreamer-nowplaying.service @@ -0,0 +1,13 @@ +# systemd user unit: copy to ~/.config/systemd/user/, then +# systemctl --user daemon-reload && systemctl --user enable --now heystreamer-nowplaying +[Unit] +Description=Feishin now-playing -> HeyStreamer overlay +After=graphical-session.target + +[Service] +ExecStart=/usr/bin/python3 %h/projects/heystreamer/tools/nowplaying/feishin_nowplaying.py +Restart=always +RestartSec=10 + +[Install] +WantedBy=default.target From cdcd3737a716963fc81a0a70d11678c512d5408c Mon Sep 17 00:00:00 2001 From: Bashy Date: Fri, 20 Nov 2026 23:18:15 +0200 Subject: [PATCH 08/40] Wire it up: Twitch events, dashboard, overlay parts, layout editor removed Twitch / server - bits via channel.bits.use (cheers + Power-ups, replaces channel.cheer); built-in channel point rewards; polls; Hype Train v2; outgoing raids. New scopes: channel:read:polls, channel:read:hype_train, channel:manage:raids (log in again). - Hype Train: alerts on start / each new level / end, plus the progress bar. - Raid send-off: start/cancel raids from the dashboard (Helix /raids); the card stays until channel.raid reports the raid happened. - StreamElements client started on boot; tip alerts. Dashboard - Twitch + StreamElements status, test buttons (poll, Hype Train bar, raid card), Raid box, activity Reload + auto-refresh, Redeems in the nav. - Two-click delete instead of browser confirm() on Media and Actions. Overlay - ?parts= splits the overlay into OBS sources: chat, alerts, poll, hypebar, raid, or exclusions like ?parts=nochat. Recommended: ?parts=chat (audio Monitor Only, chat sounds stay off stream) + ?parts=nochat. - Now playing switched off (commented, see CLAUDE.md to re-enable). Removed the layout editor and preview page; chat position/style is baked into overlay.ejs from the last saved layout (overlay_layout table kept, unused). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 132 +++++++++++++++++++++++++++++--------- src/alerts.js | 134 ++++++++++++++++++++++++++++++++++++++- src/app.js | 4 +- src/db.js | 92 +++++++++++++++++++-------- src/eventsub.js | 54 ++++++++++++++-- src/routers/alerts.js | 35 +++++++++- src/routers/auth.js | 3 + src/routers/dashboard.js | 8 ++- src/routers/overlay.js | 25 +++++--- src/server.js | 1 + src/ws.js | 5 ++ views/_activity.ejs | 32 ++++++++++ views/actions.ejs | 2 +- views/dashboard.ejs | 109 +++++++++++++++++++++---------- views/layout.ejs | 13 +++- views/media.ejs | 4 +- views/overlay.ejs | 76 +++++++++++++++------- 17 files changed, 589 insertions(+), 140 deletions(-) create mode 100644 views/_activity.ejs diff --git a/CLAUDE.md b/CLAUDE.md index 48e7dfe..56e64d5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,18 +51,15 @@ src/ routers/ auth.js — /auth/* (Twitch OAuth) dashboard.js — / (activity log, EventSub status) - overlay.js — /overlay/:uuid, /overlay/:uuid/preview, /ws/overlay + overlay.js — /overlay/:uuid, /ws/overlay actions.js — /actions CRUD media.js — /media upload/delete - layout.js — /layout editor + /layout/positions settings.js — /settings views/ layout.ejs — base shell (nav, Pico CSS) login.ejs dashboard.ejs overlay.ejs — OBS browser source - overlay_preview.ejs - layout_editor.ejs actions.ejs media.ejs settings.ejs @@ -91,7 +88,7 @@ public/ **UUID overlays.** `settings.overlay_id` is a UUID generated on first run. OBS browser source URL is `/overlay/:uuid`. Future multi-user support creates multiple settings rows. -**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. The DB `overlay_layout` row is passed as `overlayLayout` in all render calls. +**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. Pass `layout: false` to render without the shell (overlay, `_activity` partial). **Form value parsing.** Never use `parseInt(val) || default` — it overwrites valid `0` values. Use: ```javascript @@ -109,7 +106,6 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; }; | GET | `/auth/callback` | routers/auth.js | Exchange code, save user, start EventSub | | GET | `/auth/logout` | routers/auth.js | Clear session | | GET | `/overlay/:uuid` | routers/overlay.js | Live OBS browser source | -| GET | `/overlay/:uuid/preview` | routers/overlay.js | Mock preview for layout editor | | WS | `/ws/overlay` | routers/overlay.js | Bidirectional: commands up, actions down | | GET/POST | `/actions` | routers/actions.js | List and create actions | | POST | `/actions/:id/test` | routers/actions.js | Fire immediately, skip cooldown | @@ -117,31 +113,17 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; }; | DELETE | `/actions/:id` | routers/actions.js | Delete | | GET/POST | `/media` | routers/media.js | Upload, list | | DELETE | `/media/:id` | routers/media.js | Delete file + DB row | -| GET/POST | `/layout` | routers/layout.js | Position + style form (saves all layout fields) | -| POST | `/layout/positions` | routers/layout.js | JSON position update (legacy, kept for future drag) | | GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS; broadcasts settings_update on save | | POST | `/settings/reconnect` | routers/settings.js | Restart EventSub | +| GET | `/activity` | routers/dashboard.js | Activity table partial (dashboard Reload / auto-refresh) | | POST | `/alerts/test/:key` | routers/alerts.js | Send a sample polaroid alert to the overlay | -## Overlay CSS variable system +## Overlay chat position and style -All overlay positioning and styling uses CSS custom properties rendered into `overlay.ejs` and `overlay_preview.ejs` from the `overlay_layout` row: - -| Variable | Controls | -|---|---| -| `--chat-left`, `--chat-top` | Chat box position (%) | -| `--chat-width`, `--chat-height` | Chat box size (%) | -| `--chat-font-size` | Chat font size (px) | -| `--chat-font-family` | Chat font family | -| `--chat-bg-opacity` | Chat message background opacity | -| `--chat-text-color` | Chat message text colour | -| `--chat-border-radius` | Message border radius (px) | -| `--alert-left`, `--alert-top` | Alert position (%, centered via transform) | -| `--alert-font-size` | Alert font size (px) | -| `--alert-bg-opacity` | Alert background opacity | -| `--alert-text-color` | Alert text colour | - -The layout editor (`/layout`) shows position and style inputs, with a scaled iframe preview of `/overlay/:uuid/preview`. Position inputs update CSS variables in the iframe live on `input` event. All fields (position + style) are saved via `POST /layout`. +The layout editor was removed (2026-11-20). Chat box position/size/font and the legacy text/video action alert +position are fixed CSS custom properties in the `:root` block of `views/overlay.ejs` (values copied from the last +saved layout). Change them there, or override with Custom CSS in Settings. The `overlay_layout` table is still +created but unused, so old data is kept. ## Gap / new-message audio @@ -180,9 +162,10 @@ activity_log — append-only event log | Twitch event | Version | Condition | Scope | Used for | |---|---|---|---|---| | `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | follow alert | -| `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` | bits alert | +| `channel.bits.use` | 1 | `broadcaster_user_id` | `bits:read` | cheers (bits alert) **and** Power-ups (`type: power_up` → Redeems); replaced `channel.cheer` | | `channel.chat.notification` | 1 | `broadcaster_user_id` + `user_id` | `user:read:chat` | subs, resubs, Prime, multi-month, gifts, community gifts, raids | -| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | actions only (no polaroid yet) | +| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | channel point rewards → Redeems | +| `channel.channel_points_automatic_reward_redemption.add` | 2 | `broadcaster_user_id` | `channel:read:redemptions` | built-in rewards (highlight message, emote unlocks) → Redeems | `channel.chat.notification` replaced `channel.subscribe` / `subscription.message` / `subscription.gift` / `channel.raid`: one event carries `is_prime`, `duration_months` (months bought at once), `cumulative_months`, the gift recipient, @@ -196,6 +179,93 @@ community gift totals and the resub message. `sub_gift` notices with a `communit - Keepalive watchdog: no message for `keepalive_timeout_seconds + 10s` → reconnect. - Status (connected / subscribed / failed / last event) shown on the dashboard. +## Redeems (channel points, built-in rewards, bits Power-ups) + +Page `/redeems` (src/routers/redeems.js, views/redeems.ejs, logic in src/redeems.js), table `reward_variations`. + +- A trigger is `kind` + `key`: `reward` + Twitch reward id, `auto_reward` + built-in type, `power_up` + Power-up type. +- Each trigger has variations (name, rarity, sound, volume, polaroid on/off, caption, art, enabled). On a redemption + ONE enabled variation is picked at random, weighted by rarity (`RARITY` in src/redeems.js: weights Common 50 / Uncommon 25 / Rare 12 / Ultra Rare 3 (Twitch's Super Rare merged into Ultra Rare); chance = weight ÷ sum of the trigger's enabled weights), like + Twitch alert variations. No enabled variation → only logged (and legacy actions run). +- Custom rewards are listed live from Helix `GET /channel_points/custom_rewards` (title, cost, icon); built-in rewards + and Power-ups are fixed lists. Titles are refreshed when a redemption arrives with a new name. +- Shown as a cassette tape (`public/alerts/cassette.js` + `.css`, called from polaroid.js so it shares the queue): + rarity = shell colour (Ultra Rare: gold, glow, foil, sparkles), reels spin over the sound's length, label = + variation name + reward, paper strip = viewer + caption + typed message, sticker in the corner = the variation's + `art` (URL; '' = headset Streamer). `polaroid` column = "show cassette" (0 = sound only). +- Special styles instead of the cassette (`STYLE` in src/redeems.js, drawn by `public/alerts/fx.js` + `.css`): + Gigantify Power-up → the viewer's emote grows giant; On-Screen Celebration → 14 copies of the emote bounce around + the whole screen for the sound's length; Highlight my message and the Message Effect Power-up → big taped paper note, taller than wide (stays ~2 s + 70 ms/char). + Emote image = `https://static-cdn.jtvnw.net/emoticons/v2//default/dark/3.0` from `event.power_up.emote.id` + (fallback: heart). Default caption becomes "gigantified an emote!" / "is celebrating!" / "highlighted:". +- Sound picker = `public/alerts/sounds/redeems/` (redeem clips, loudness-normalized to -16 LUFS with ffmpeg + two-pass loudnorm, so volume stays 0.8), `public/alerts/sounds/` (alert sounds + library) and audio uploaded on + the Media page (`/media/`). Stickers: `public/alerts/stickers/` (cut out with rembg / hand masks). +- polaroid off = sound only: it still waits its turn in the overlay queue and holds it for the sound's length. +- First run: `src/redeems-seed.json` (rebuilt from the Twitch alert setup, 2026-11-20) is loaded when the table is + empty. After that the dashboard is the source of truth; the seed file is never re-applied. +- Test buttons: per variation, and "Test random" per trigger (`POST /redeems/variation/:id/test`, `/redeems/trigger/test`). +- Power-up payload field names (`event.type === 'power_up'`, `event.power_up.type`) follow Twitch's docs but were not + yet seen live; check `activity_log.data_json` of the first real Power-up. + +## Raid send-off and Hype Train bar + +- Outgoing raid send-off: Twitch has no "raid started" event, so raids are started from the dashboard Raid box + (`POST /alerts/raid/start` → Helix `POST /raids`, scope `channel:manage:raids`; `/alerts/raid/cancel` → `DELETE /raids`). + The silent card (`public/alerts/raidcard.js`, top-centre polaroid with the target's Twitch avatar, "raiding X / with N + of you, be nice! ♡", 90 s countdown) stays until `channel.raid` (`from_broadcaster_user_id` = us) arrives, then + shows "raid sent!" and leaves. Raid started on Twitch directly: card shows only at that moment. Test: `raid-card-test`. +- Hype Train bar: every `channel.hype_train.*` event also goes out as `{type:'hype_bar', phase, train}`; + `public/alerts/hypebar.js` shows a slim taped strip top-left (LV, progress/goal bar, time left; gold for Golden + Kappa), outside the queue; on end it shows the final level for 5 s and slides away. Test: dashboard `hype-bar-test`. + +## Overlay parts (two OBS sources) + +`/overlay/:uuid?parts=` picks what a browser source shows: `chat` (chat box + gap audio), `alerts` (polaroid queue, +redeems, legacy actions), `poll`, `hypebar`, `raid`. List parts (`?parts=chat,raid`) or exclude them with `no` +(`?parts=nochat`, `?parts=nochat,noraid`). No `?parts=` = all. Recommended: `?parts=chat` as a source with audio +"Monitor Only (mute output)" (chat sounds stay off stream) and `?parts=nochat` as the main source. Every source receives every WebSocket message and ignores the parts it does not show, so nothing plays twice. +Every source still listens to chat for watch streaks; the server dedupes the reports by message id. + +## Now playing (Feishin) — SWITCHED OFF for now + +Kept in the repo but disabled: the `/nowplaying` route is commented out in `src/app.js`, `nowplaying` is not in +`PARTS` (src/routers/overlay.js) and the overlay lines are commented (marked NOWPLAYING in views/overlay.ejs). +To re-enable: undo those three. Description of how it works when enabled: + + +- `tools/nowplaying/feishin_nowplaying.py` runs on the streaming PC: watches Feishin over MPRIS (D-Bus, PyGObject), + POSTs `{status,title,artist,album,length,cover}` to `/nowplaying` with `Authorization: Bearer NOWPLAYING_KEY` + on every change + every 30 s. Config `~/.config/heystreamer-nowplaying.env` (HEYSTREAMER_URL, NOWPLAYING_KEY); + systemd user unit next to the script. +- Feishin's `mpris:artUrl` points at Navidrome on the LAN and carries the Subsonic token: the helper downloads the + cover itself and sends a 160 px JPEG data URL, so no URL/credential ever leaves the PC. +- Server: `src/routers/nowplaying.js` (key check, sanitised fields, data-URL-only cover) → `src/nowplaying.js` keeps + the current song and broadcasts `{type:'nowplaying', np}`; new overlay connections get it on connect. +- Overlay: `public/alerts/nowplaying.js` small taped paper slip (cover, title, artist) top-right, visible only while + `playing`; hides 1.5 s after pause/stop (grace so track changes do not flicker). Chat position unchanged. + +## StreamElements tips + +- `src/streamelements.js`: Astro websocket (`wss://astro.streamelements.com`, override `SE_URL` for tests). Off unless + `SE_JWT` is set in `.env` (StreamElements dashboard → avatar → channel → JWT token; secret, never commit). +- welcome → subscribe `{topic:'channel.tips', token, token_type:'jwt'}` → `message` on `channel.tips`; tip fields in + `data.donation` (`user.username`, `amount`, `currency`, `message`). Only `approved: 'allowed'` + `status: 'success'` + alert; deduped by `data._id`. `reconnect` message → reconnect with `?reconnect_token=` (no re-subscribe). Server + PINGs every 30 s (ws answers). Status on the dashboard. +- Alert: tip polaroid (sound emotional-damage-meme, heart-eyes Streamer, amount via Intl currency format, badge, +1/2/3 hearts at 10/25/50). + Turn off StreamElements' own tip alert in its overlay to avoid doubles. + +## Polls and Hype Train + +- Polls (`channel.poll.begin/progress/end` v1, scope `channel:read:polls`): `alerts.sendPoll()` broadcasts + `{type:'poll', phase, poll}`; `public/alerts/poll.js` shows a live taped-paper card (left, below the alert corner, + NOT in the alert queue): bars + votes + countdown; on `completed` the winner gets a heart + WINNER stamp, then it + drops away after 9 s (archived/terminated: away after 1.5 s). Begin/end are logged. Test: dashboard `poll-test`. +- Hype Train (`channel.hype_train.*` v2, scope `channel:read:hype_train`): `alerts.fromHypeTrain()` → queued polaroid + alerts on start, on each NEW level (progress fires per contribution) and at the end (top contributors). HYPE Streamer + art; sounds pro-gamer / toad-ya-hoo / tadaaa (in `describe()` case 'hype'). Golden Kappa / Treasure trains named. + ## Polaroid alerts ``` @@ -205,9 +275,10 @@ alerts.send() ─► ws.broadcast({type:'alert', alert}) ─► overlay ─► p └─► dispatch.dispatchEvent() (activity log + legacy actions keep working) ``` -- Alert shape and per-event look (art, caption, tape colour, badge, sound, bits tiers) live in `public/alerts/polaroid.js` (`describe()` + CONFIG block). Art in `public/alerts/art/`, sounds in `public/alerts/sounds/` (lengths in `SOUND_MS`, so the alert holds for the whole sound). +- Alert shape and per-event look (art, caption, tape colour, badge, sound, bits tiers) live in `public/alerts/polaroid.js` (`describe()` + CONFIG block). Art in `public/alerts/art/`, sounds in `public/alerts/sounds/`. Sound lengths come from `SOUND_MS` or are measured in the browser (redeem sounds picked in the UI), so the alert holds for the whole sound. Redeem alerts carry their own sound URL, volume, art and caption. - Watch streaks only exist in chat. The overlay reports them; the server only accepts `chat_notice` from WS connections that pass `?overlay=` and dedupes by message id (several overlays may report the same notice). -- Test buttons on the dashboard: `POST /alerts/test/:key` (keys = `alerts.TEST_KEYS`). Test alerts (`test:true`) replace what is showing; `queue-test` sends four that queue. Not logged, no actions fired. +- Test buttons on the dashboard: `POST /alerts/test/:key` (keys = `alerts.TEST_KEYS`). A test alert (`test:true`, `PolaroidAlerts.playTest`) instantly replaces another *test* alert, but never cuts off or drops a real one: it queues behind it. A real alert arriving during a test cuts the test off. `queue-test` sends four that queue. Not logged, no actions fired. +- Timing: entrance animation ~2.4 s (+0.12 s per stacked photo), then it stays `AFTER_ANIM` (3 s) — or until the sound ends if that is later (sound starts 0.4 s in) — then a 0.65 s exit. ~6 s for most alerts, ~9.3 s for 150+ bits, ~11.1 s for 250+ bits. - Bits under 5: no alert (`BITS_MIN`). ## Production deployment @@ -240,4 +311,3 @@ Twitch requires HTTPS for OAuth redirect URIs in production. Register both in th - Stripe / PayPal / ETH payment notifications - Multiple overlays (multi-user; UUID foundation is in place) - HudFX integration -- Drag-to-reposition in layout editor (removed — CSS transform + interact.js coordinate mismatch; use the position inputs instead) diff --git a/src/alerts.js b/src/alerts.js index 0beee16..ad2b726 100644 --- a/src/alerts.js +++ b/src/alerts.js @@ -20,6 +20,9 @@ function legacy(alert) { 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' }[alert.kind], alert.key]; default: return [alert.type, null]; } } @@ -44,6 +47,11 @@ 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) { @@ -72,6 +80,77 @@ function fromChatNotification(e) { } } +// --- 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 raidHappened(e) { + let raid = pendingRaid; + if (!raid) { // started on Twitch directly: show the card briefly + 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 */ } + raid = { target: e.to_broadcaster_user_name || e.to_broadcaster_user_login, avatar }; + } + raidCard('done', { ...raid, viewers: e.viewers }); + pendingRaid = null; + dispatch.dispatchEvent('raid_out', String(e.viewers), e.to_broadcaster_user_name, e); +} + +// --- 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) { @@ -105,14 +184,63 @@ const SAMPLES = { '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']; +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 makes the overlay drop what it is showing (fast checking); +// 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' } }); @@ -124,4 +252,4 @@ function sendTest(key) { return true; } -module.exports = { send, sendTest, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromChatNotification, fromOverlayNotice }; +module.exports = { 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 e9a8557..0c40d91 100644 --- a/src/app.js +++ b/src/app.js @@ -49,11 +49,13 @@ function requireAuth(req, res, next) { app.use('/auth', require('./routers/auth')); app.use('/overlay', require('./routers/overlay')); +// Now playing (Feishin) is switched off for now; uncomment to bring it back (see views/overlay.ejs). +// app.use('/nowplaying', require('./routers/nowplaying')); // key-protected push from the PC helper app.use('/actions', requireAuth, require('./routers/actions')); app.use('/media', requireAuth, require('./routers/media')); -app.use('/layout', requireAuth, require('./routers/layout')); app.use('/settings', requireAuth, require('./routers/settings')); app.use('/alerts', requireAuth, require('./routers/alerts')); +app.use('/redeems', requireAuth, require('./routers/redeems')); app.use('/', requireAuth, require('./routers/dashboard')); module.exports = app; diff --git a/src/db.js b/src/db.js index ffac595..7c09d81 100644 --- a/src/db.js +++ b/src/db.js @@ -11,7 +11,7 @@ function init() { db.pragma('foreign_keys = ON'); createSchema(); seedSettings(); - seedLayout(); + seedVariations(); console.log(`[db] Initialised — path: ${DB_PATH}`); } @@ -43,6 +43,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 +84,24 @@ 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). + CREATE TABLE IF NOT EXISTS reward_variations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, -- reward | auto_reward | 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, @@ -104,12 +123,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; + const ins = db.prepare(`INSERT INTO reward_variations (kind, key, title, name, rarity, sound, volume, art, enabled) + VALUES (@kind, @key, @title, @name, @rarity, @sound, @volume, @art, @enabled)`); + db.transaction(() => seed.forEach(v => ins.run({ ...v, volume: v.volume ?? 0.8, art: v.art || '', enabled: v.enabled === false ? 0 : 1 })))(); + console.log(`[db] Loaded ${seed.length} default redeem variations`); } // Users @@ -149,26 +169,6 @@ function updateSettings(fields) { 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(); @@ -232,6 +232,42 @@ function getMatchingActions(eventType, eventDetail) { }); } +// Redeem variations +const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled']; + +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 }) { + const r = db.prepare('INSERT INTO reward_variations (kind, key, title, name) VALUES (?, ?, ?, ?)').run(kind, key, title, name); + 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); +} + // Activity log function logActivity(eventType, eventDetail, username, data, actionsFired) { db.prepare(` @@ -254,8 +290,8 @@ module.exports = { init, upsertUser, getUserById, getPrimaryUser, updateUserTokens, getSettings, updateSettings, - getLayout, updateLayout, updateLayoutPositions, getAllMedia, getMediaFile, createMedia, deleteMedia, getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions, + getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation, logActivity, getActivityLog, }; diff --git a/src/eventsub.js b/src/eventsub.js index a88e95b..77443d6 100644 --- a/src/eventsub.js +++ b/src/eventsub.js @@ -7,7 +7,7 @@ const { WebSocket } = require('ws'); const twitch = require('./twitch'); const alerts = require('./alerts'); -const dispatch = require('./dispatch'); +const redeems = require('./redeems'); const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws'; @@ -122,10 +122,23 @@ async function subscribeAll(sessionId) { const b = broadcasterId; const subs = [ { type: 'channel.follow', version: '2', condition: { broadcaster_user_id: b, moderator_user_id: b } }, - { type: 'channel.cheer', version: '1', condition: { broadcaster_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 } }, // 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 } }, { 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); } @@ -161,8 +174,14 @@ function handleNotification(payload) { case 'channel.follow': alerts.send(alerts.fromFollow(event), event); break; - case 'channel.cheer': - alerts.send(alerts.fromCheer(event), event); + 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); @@ -171,9 +190,32 @@ function handleNotification(payload) { break; } case 'channel.channel_points_custom_reward_redemption.add': - // no polaroid alert yet; existing actions still fire - dispatch.dispatchEvent('channel_points', event.reward?.id, event.user_name || event.user_login, event); + 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 'channel.raid': + 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; + } } } diff --git a/src/routers/alerts.js b/src/routers/alerts.js index 203ffdd..2f634e8 100644 --- a/src/routers/alerts.js +++ b/src/routers/alerts.js @@ -1,11 +1,44 @@ const express = require('express'); const router = express.Router(); const alerts = require('../alerts'); +const twitch = require('../twitch'); -// POST /alerts/test/:key — send a sample alert to every connected overlay (dashboard test buttons) +// 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/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/auth.js b/src/routers/auth.js index 3a5d20f..ab4025b 100644 --- a/src/routers/auth.js +++ b/src/routers/auth.js @@ -12,6 +12,9 @@ const SCOPES = [ '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) ].join(' '); router.get('/login', (req, res) => { diff --git a/src/routers/dashboard.js b/src/routers/dashboard.js index 78cfe6f..7e8304e 100644 --- a/src/routers/dashboard.js +++ b/src/routers/dashboard.js @@ -3,11 +3,17 @@ const router = express.Router(); const db = require('../db'); const eventsub = require('../eventsub'); const alerts = require('../alerts'); +const streamelements = require('../streamelements'); router.get('/', (req, res) => { const logs = db.getActivityLog(50); const settings = db.getSettings(); - res.render('dashboard', { logs, settings, eventsubStatus: eventsub.getStatus(), testKeys: alerts.TEST_KEYS }); + res.render('dashboard', { logs, 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) }); }); module.exports = router; diff --git a/src/routers/overlay.js b/src/routers/overlay.js index b8078d2..824d653 100644 --- a/src/routers/overlay.js +++ b/src/routers/overlay.js @@ -2,17 +2,26 @@ const express = require('express'); const router = express.Router(); const db = require('../db'); +// Parts of the overlay. One OBS browser source can show all of them, or the overlay can be split into +// several sources with ?parts=, e.g. chat in its own source (audio "Monitor Only" in OBS, so chat +// sounds never reach the stream) and everything else in another. +const PARTS = ['chat', 'alerts', 'poll', 'hypebar', 'raid']; // 'nowplaying' is off for now (see overlay.ejs) +// ?parts=chat,raid only those parts +// ?parts=nochat everything except chat (no, several allowed: nochat,noraid) +// no ?parts / nothing valid: everything +function partsFrom(q) { + if (!q) return PARTS; + const tokens = String(q).split(',').map(s => s.trim().toLowerCase()).filter(Boolean); + const excluded = tokens.filter(t => t.startsWith('no') && PARTS.includes(t.slice(2))).map(t => t.slice(2)); + if (excluded.length) return PARTS.filter(p => !excluded.includes(p)); + const asked = tokens.filter(p => PARTS.includes(p)); + return asked.length ? asked : PARTS; +} + router.get('/:uuid', (req, res) => { const settings = db.getSettings(); if (req.params.uuid !== settings.overlay_id) return res.status(404).send('Overlay not found'); - const overlayLayout = db.getLayout(); - res.render('overlay', { layout: false, settings, overlayLayout }); -}); - -router.get('/:uuid/preview', (req, res) => { - const settings = db.getSettings(); - const overlayLayout = db.getLayout(); - res.render('overlay_preview', { layout: false, settings, overlayLayout }); + res.render('overlay', { layout: false, settings, parts: partsFrom(req.query.parts) }); }); module.exports = router; diff --git a/src/server.js b/src/server.js index b819fc7..c12a1e3 100644 --- a/src/server.js +++ b/src/server.js @@ -29,4 +29,5 @@ server.listen(PORT, () => { } else { console.log('[server] No Twitch login stored yet — log in at /auth/login to start alerts'); } + if (process.env.EVENTSUB_DISABLED !== '1') require('./streamelements').start(); }); diff --git a/src/ws.js b/src/ws.js index 91a9015..3e07f52 100644 --- a/src/ws.js +++ b/src/ws.js @@ -21,6 +21,11 @@ function init(wss) { const trusted = !!overlayId && overlayId === db.getSettings().overlay_id; console.log(`[ws] Client connected${trusted ? ' (overlay)' : ''} — total: ${clients.size}`); if (trusted) ws.on('message', data => handleIncoming(String(data).slice(0, 2000))); + // a freshly loaded overlay gets the current song right away + const np = require('./nowplaying').get(); + if (np) ws.send(JSON.stringify({ type: 'nowplaying', np })); + const raid = require('./alerts').getPendingRaid(); // overlay reloaded during a raid countdown + if (raid) ws.send(JSON.stringify({ type: 'raid_card', phase: 'start', raid })); ws.on('close', () => { clients.delete(ws); console.log(`[ws] Client disconnected — total: ${clients.size}`); diff --git a/views/_activity.ejs b/views/_activity.ejs new file mode 100644 index 0000000..b77aaca --- /dev/null +++ b/views/_activity.ejs @@ -0,0 +1,32 @@ +<% if (logs.length === 0) { %> +

No activity yet. Events will appear here once your overlay is connected and Twitch fires events.

+<% } else { %> +
+ + + + + + + + + + + + <% for (const log of logs) { %> + + + + + + + + <% } %> + +
TimeEventUserDetailActions fired
<%= log.created_at %><%= log.event_type %><%= log.username || '—' %><%= log.event_detail || '—' %> + + <%= log.actions_fired %> + +
+
+<% } %> diff --git a/views/actions.ejs b/views/actions.ejs index 8af7df7..9a39b77 100644 --- a/views/actions.ejs +++ b/views/actions.ejs @@ -78,7 +78,7 @@
-
+
<% } %> diff --git a/views/dashboard.ejs b/views/dashboard.ejs index e6d8464..7e05b53 100644 --- a/views/dashboard.ejs +++ b/views/dashboard.ejs @@ -6,8 +6,13 @@ <%= settings.channel || 'not set' %>
- Overlay URL: - <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %> + OBS browser sources (1920×1080):
+ Chat only, set its audio to Monitor Only (mute output) so chat sounds stay off stream:
+ <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat
+ Everything except chat (alerts, redeems, poll, Hype Train bar, raid send-off):
+ <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=nochat
+ + Other combinations: hover for help · everything in one source: /overlay/<%= settings.overlay_id %>
@@ -25,6 +30,41 @@ <% if (eventsubStatus.lastEventAt) { %>
Last event: <%= eventsubStatus.lastEventAt %><% } %>

+

StreamElements tips

+

+ <% if (!seStatus.enabled) { %> + off set SE_JWT in .env (StreamElements dashboard → avatar → your channel → JWT token) and restart + <% } else if (seStatus.subscribed) { %> + connected<% if (seStatus.lastTipAt) { %> last tip: <%= seStatus.lastTipAt %><% } %> + <% } else { %> + connecting… + <% } %> + <% if (seStatus.error) { %>
<%= seStatus.error %><% } %> +

+ +

Raid

+

Start the raid here and the send-off card stays on stream (silent) until the raid happens. Same as Twitch's Raid button.

+
+ + + + +
+ +

Test alerts

Sends a sample alert to the overlay (OBS). Not logged, no actions fired.

@@ -43,36 +83,35 @@ })); -

Recent activity

-<% if (logs.length === 0) { %> -

No activity yet. Events will appear here once your overlay is connected and Twitch fires events.

-<% } else { %> -
- - - - - - - - - - - - <% for (const log of logs) { %> - - - - - - - - <% } %> - -
TimeEventUserDetailActions fired
<%= log.created_at %><%= log.event_type %><%= log.username || '—' %><%= log.event_detail || '—' %> - - <%= log.actions_fired %> - -
-
-<% } %> +
+

Recent activity

+ + + +
+
<%- include('_activity') %>
+ diff --git a/views/layout.ejs b/views/layout.ejs index 9aadd32..4788dc0 100644 --- a/views/layout.ejs +++ b/views/layout.ejs @@ -23,9 +23,9 @@
  • Dashboard
  • +
  • Redeems
  • Actions
  • Media
  • -
  • Layout
  • Settings
  • <% if (locals.user) { %>
  • Logout (<%= user.login %>)
  • @@ -35,5 +35,16 @@
    <%- body %>
    + diff --git a/views/media.ejs b/views/media.ejs index 0d03b66..40bb214 100644 --- a/views/media.ejs +++ b/views/media.ejs @@ -41,8 +41,8 @@ <% } %> -
    - + +
    diff --git a/views/overlay.ejs b/views/overlay.ejs index db65550..348cf54 100644 --- a/views/overlay.ejs +++ b/views/overlay.ejs @@ -3,24 +3,39 @@ - + + <% const has = p => parts.includes(p); %> + <% if (has('alerts')) { %> + + + <% } %> + <% if (has('poll')) { %><% } %> + <% if (has('hypebar')) { %><% } %> + <% if (has('raid')) { %><% } %> + <%# Now playing (Feishin) is switched off for now. To bring it back: add 'nowplaying' to PARTS in + src/routers/overlay.js, uncomment the /nowplaying route in src/app.js and restore the NOWPLAYING lines here: + (inside an if (has('nowplaying'))) + (same) + the nowplaying line in ws.onmessage below %> -
    -
    - + <% if (has('chat')) { %>
    <% } %> + <% if (has('alerts')) { %>
    + <% } %> + <% if (has('alerts')) { %> + + + <% } %> + <% if (has('poll')) { %><% } %> + <% if (has('hypebar')) { %><% } %> + <% if (has('raid')) { %><% } %> (same) the nowplaying line in ws.onmessage below %> + +

    TTS voices

    +<% if (error) { %> +
    + The TTS engine is not running. +

    <%= error %>

    +

    Set it up once with tools/tts/setup.sh (installs Piper and downloads voices), then reload this page.

    +
    +<% } else { %> +
    +
    +
    +

    Quick start

    +
    +
    +
    +
    + +
    +
    +

    Effects +

    +
    +
    +
    + +
    +
    +

    Test

    + +
    + + + +
    +
    +
    +

    Save

    + +
    + + + +
    +
    +
    +

    Saved voices

    +
      +
      +
      +
      + + +<% } %> From 4fda6060bf1f187f7b94375879b34ecb614f58fb Mon Sep 17 00:00:00 2001 From: Bashy Date: Sat, 21 Nov 2026 14:34:41 +0200 Subject: [PATCH 12/40] TTS redeems, skip button, per-source chat placement - Redeem variations can have a TTS voice: the viewer's text is cleaned (links out, repeats collapsed, max length, blocked words -> not read), spoken as " says: ..." and shown as the big paper note; the variation's sound is not played when TTS is on (picker greyed out) - Settings: TTS max length, say-the-name, blocked words (never sent to overlay pages: db.getOverlaySettings) - Dashboard "Skip current alert" -> /alerts/skip -> overlay skips it - db.migrate()/addColumn: new columns on existing databases - Chat: ?chat=left,top,width,height and ?chatflow=up per browser source (e.g. the Intermission panel); default unchanged Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 10 ++++++++- public/alerts/fx.js | 12 +++++++++-- public/alerts/polaroid.js | 13 +++++++++-- public/chat/chat.css | 17 ++++++++++++--- public/chat/chat.js | 5 +++-- src/db.js | 31 ++++++++++++++++++++++++--- src/redeems.js | 45 +++++++++++++++++++++++++++++++++------ src/routers/alerts.js | 8 +++++++ src/routers/overlay.js | 15 +++++++++++-- src/routers/redeems.js | 2 ++ src/routers/settings.js | 5 ++++- src/tts.js | 39 +++++++++++++++++++++++++++++---- views/dashboard.ejs | 16 ++++++++++++++ views/overlay.ejs | 3 ++- views/redeems.ejs | 16 ++++++++++++++ views/settings.ejs | 19 +++++++++++++++++ 16 files changed, 228 insertions(+), 28 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 36e7ef4..ae04fb0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -137,7 +137,15 @@ Chat (`?parts=chat`) is `public/chat/chat.css` + `public/chat/chat.js` (window.H ## TTS voices (/tts) -Builder page to make named TTS voices; redeems do not use them yet. +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, note says + "(message removed)"), synthesizes " says: " (`tts_say_name`), and only then sends the alert with + `tts` (URL) + `tts_ms`. Shown as the big paper note (style `message`, caption "says:"). 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 diff --git a/public/alerts/fx.js b/public/alerts/fx.js index 6a91e6a..3ed9dbf 100644 --- a/public/alerts/fx.js +++ b/public/alerts/fx.js @@ -2,7 +2,8 @@ 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.message(d, cur, snd) Highlight my message / Message Effect / TTS redeems: big taped paper note with the message + (d.tts = spoken message URL, d.ttsMs = its length; TTS redeems come without a sound) 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). */ @@ -118,7 +119,14 @@ { 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 - const exitAt = Math.max(650 + AFTER_ANIM, 650 + read, SOUND_LEAD + snd.len); + 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' })); } diff --git a/public/alerts/polaroid.js b/public/alerts/polaroid.js index 55c2ed4..4917806 100644 --- a/public/alerts/polaroid.js +++ b/public/alerts/polaroid.js @@ -6,6 +6,7 @@ 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 } @@ -127,7 +128,8 @@ return { cassette: true, style: e.style || 'cassette', emote: e.emote || null, sticker: rebase(e.art) || 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 }; + 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 }; } case 'bits': { if (!(e.bits >= BITS_MIN)) return null; @@ -211,6 +213,13 @@ 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; @@ -362,6 +371,6 @@ .catch(() => {}); // cancelled by reset() } - window.PolaroidAlerts = { play, playTest, reset, describe }; + window.PolaroidAlerts = { play, playTest, reset, skip, describe }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload(); })(); diff --git a/public/chat/chat.css b/public/chat/chat.css index b8ad45c..c30f69d 100644 --- a/public/chat/chat.css +++ b/public/chat/chat.css @@ -2,16 +2,17 @@ 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. - Move or resize it with Custom CSS in Settings, e.g. #chat { --chat-top: 60%; --chat-height: 37%; } */ + 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-right: 2%; + --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; - right: var(--chat-right); + left: var(--chat-left); top: var(--chat-top); width: var(--chat-width); height: var(--chat-height); @@ -25,6 +26,16 @@ 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; diff --git a/public/chat/chat.js b/public/chat/chat.js index 8cb5bd8..1582536 100644 --- a/public/chat/chat.js +++ b/public/chat/chat.js @@ -128,9 +128,10 @@ d.innerHTML = `${esc(name)}${r.html}`; d._n = ++seq; - // FLIP: remember where the others are, put the new one on top, then glide them down from the old spot + // 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])); - box.prepend(d); + 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)' }); diff --git a/src/db.js b/src/db.js index fcc8ed6..5085287 100644 --- a/src/db.js +++ b/src/db.js @@ -10,6 +10,7 @@ function init() { db.pragma('journal_mode = WAL'); db.pragma('foreign_keys = ON'); createSchema(); + migrate(); seedSettings(); seedVariations(); console.log(`[db] Initialised — path: ${DB_PATH}`); @@ -122,6 +123,21 @@ 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 +} + function seedSettings() { const row = db.prepare('SELECT id FROM settings WHERE id = 1').get(); if (!row) { @@ -172,6 +188,12 @@ 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, ...rest } = getSettings(); + return rest; +} + function updateSettings(fields) { const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', '); db.prepare(`UPDATE settings SET ${cols} WHERE id = 1`).run(fields); @@ -241,7 +263,7 @@ function getMatchingActions(eventType, eventDetail) { } // Redeem variations -const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled']; +const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled', 'tts_voice_id']; function getAllVariations() { return db.prepare('SELECT * FROM reward_variations ORDER BY kind, title, id').all(); @@ -297,7 +319,10 @@ function updateTtsVoice(id, name, config) { } function deleteTtsVoice(id) { - db.prepare('DELETE FROM tts_voices WHERE id = ?').run(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 @@ -321,7 +346,7 @@ function getActivityLog(limit = 50) { module.exports = { init, upsertUser, getUserById, getPrimaryUser, updateUserTokens, - getSettings, updateSettings, + getSettings, getOverlaySettings, updateSettings, getAllMedia, getMediaFile, createMedia, deleteMedia, getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions, getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation, diff --git a/src/redeems.js b/src/redeems.js index a92e8d4..a5734f0 100644 --- a/src/redeems.js +++ b/src/redeems.js @@ -4,6 +4,7 @@ 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 @@ -37,7 +38,7 @@ const STYLE = { '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:' }; +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) { @@ -49,16 +50,42 @@ function pick(variations) { } function toAlert(v, { user, input, emote }) { - const style = STYLE[`${v.kind}:${v.key}`] || 'cassette'; + const spoken = !!(v.tts_voice_id && input); // TTS variations are shown as the big paper note + const style = spoken ? 'message' : (STYLE[`${v.kind}:${v.key}`] || 'cassette'); + const line = spoken ? LINE.tts : LINE[style]; return { type: 'redeem', kind: v.kind, key: v.key, style, user, reward: v.title, variation: v.name, rarity: v.rarity, input: input || null, // special styles have their own wording unless the caption was customised - caption: style !== 'cassette' && v.caption === 'redeemed it! ♡' ? LINE[style] : v.caption, - sound: v.sound || null, volume: v.volume, polaroid: !!v.polaroid, art: v.art || null, emote: emoteUrl(emote), + caption: style !== 'cassette' && 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), }; } +// 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; + } catch (e) { + console.warn(`[tts] ${alert.user}: ${e.message}`); + } +} + // legacy action event type for the actions system / activity log const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up' }; @@ -72,7 +99,8 @@ function handle(kind, key, title, { user, input, emote }, raw) { return null; } const alert = toAlert(v, { user, input, emote }); - alerts.send(alert, raw); + if (v.tts_voice_id && input) addSpeech(v, alert).then(() => alerts.send(alert, raw)); // speech first, then the alert + else alerts.send(alert, raw); return alert; } @@ -80,9 +108,12 @@ function handle(kind, key, title, { user, input, emote }, raw) { function test({ id, kind, key }) { const v = id ? db.getVariation(id) : pick(db.getVariationsFor(kind, key)); if (!v) return false; - const input = ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!' + 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; - alerts.sendTestAlert(toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null })); // 25 = Kappa + const alert = toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null }); // 25 = Kappa + if (v.tts_voice_id) addSpeech(v, alert).then(() => alerts.sendTestAlert(alert)); + else alerts.sendTestAlert(alert); return true; } diff --git a/src/routers/alerts.js b/src/routers/alerts.js index 2f634e8..5946a74 100644 --- a/src/routers/alerts.js +++ b/src/routers/alerts.js @@ -2,6 +2,7 @@ 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) => { @@ -9,6 +10,13 @@ router.post('/test/:key', (req, res) => { 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(); diff --git a/src/routers/overlay.js b/src/routers/overlay.js index 824d653..6c1421f 100644 --- a/src/routers/overlay.js +++ b/src/routers/overlay.js @@ -18,10 +18,21 @@ function partsFrom(q) { return asked.length ? asked : PARTS; } +// ?chat=left,top,width,height chat box in px of the 1920x1080 page (e.g. Intermission panel: 130,640,700,360) +// ?chatflow=up|down up = newest at the bottom (normal chat); down (default) = newest on top, under the camera +function chatBoxFrom(q) { + const n = String(q || '').split(',').map(Number); + if (n.length !== 4 || n.some(x => !isFinite(x))) return null; + const [l, t, w, h] = n; + if (w < 50 || h < 50 || l < -1920 || t < -1080 || l > 1920 || t > 1080 || w > 1920 || h > 1080) return null; + return { left: Math.round(l), top: Math.round(t), width: Math.round(w), height: Math.round(h) }; +} + router.get('/:uuid', (req, res) => { - const settings = db.getSettings(); + const settings = db.getOverlaySettings(); if (req.params.uuid !== settings.overlay_id) return res.status(404).send('Overlay not found'); - res.render('overlay', { layout: false, settings, parts: partsFrom(req.query.parts) }); + res.render('overlay', { layout: false, settings, parts: partsFrom(req.query.parts), + chatBox: chatBoxFrom(req.query.chat), chatFlow: req.query.chatflow === 'up' ? 'up' : 'down' }); }); module.exports = router; diff --git a/src/routers/redeems.js b/src/routers/redeems.js index 504acd0..93eb365 100644 --- a/src/routers/redeems.js +++ b/src/routers/redeems.js @@ -62,6 +62,7 @@ router.get('/', async (req, res) => { res.render('redeems', { groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY, sounds: soundOptions(), + ttsVoices: db.getAllTtsVoices(), stickers: [ ...listDir('alerts/stickers', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/stickers/${f}`, label: f.replace(/\.\w+$/, '') })), ...listDir('alerts/art', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/art/${f}`, label: f.replace('_Contrast', '').replace(/\.\w+$/, '') })), @@ -93,6 +94,7 @@ router.post('/variation/:id', (req, res) => { caption: (b.caption || '').trim() || 'redeemed it! ♡', art: b.art || '', enabled: b.enabled === 'on' ? 1 : 0, + tts_voice_id: db.getTtsVoice(parseInt(b.tts_voice_id, 10)) ? parseInt(b.tts_voice_id, 10) : null, }); back(res, v); }); diff --git a/src/routers/settings.js b/src/routers/settings.js index 4dd2b84..63c2870 100644 --- a/src/routers/settings.js +++ b/src/routers/settings.js @@ -25,12 +25,15 @@ router.post('/', (req, res) => { gap_audio_min_volume: flt(b.gap_audio_min_volume, 0.2), gap_audio_max_volume: flt(b.gap_audio_max_volume, 1.0), gap_audio_loud_after: int(b.gap_audio_loud_after, 3600), + tts_max_chars: Math.max(20, Math.min(300, int(b.tts_max_chars, 200))), + tts_say_name: b.tts_say_name === 'on' ? 1 : 0, + tts_blocklist: String(b.tts_blocklist || '').slice(0, 20000), custom_css: b.custom_css || '', custom_js: b.custom_js || '', }); // Push updated settings to all connected overlays so they don't need a page reload - ws.broadcast({ type: 'settings_update', settings: db.getSettings() }); + ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); console.log(`[settings] Saved — channel: ${b.channel}, gap_audio: ${b.gap_audio_enabled === 'on'}`); res.redirect('/settings'); diff --git a/src/tts.js b/src/tts.js index 2ece907..e20efc5 100644 --- a/src/tts.js +++ b/src/tts.js @@ -83,6 +83,32 @@ function cleanText(text) { return String(text || '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_CHARS); } +// ---------- viewer text (redeems) ---------- +// Returns { text, blocked }. blocked = a blocklist word was found: do not read anything. +const LEET = { 0: 'o', 1: 'i', 3: 'e', 4: 'a', 5: 's', 7: 't', '@': 'a', $: 's', '!': 'i' }; +function parseBlocklist(list) { + return String(list || '').split(/[\n,]/).map(w => w.trim().toLowerCase()).filter(Boolean); +} +function prepareViewerText(input, { maxChars = 200, blocklist = '' } = {}) { + let t = cleanText(input) + .replace(/\b(?:https?:\/\/|www\.)\S+/gi, ' ') // links + .replace(/\b[\w-]+(?:\.[\w-]+)*\.(?:com|net|org|gg|tv|io|ru|xyz|ly|me|co|app|link|sk|ro|de|uk|info|site|shop)\b\S*/gi, ' ') + .replace(/(\S)\1{3,}/g, '$1$1$1') // aaaaaaa -> aaa + .replace(/\b(\w+)(?:\s+\1\b){2,}/gi, '$1 $1') // lol lol lol lol -> lol lol + .replace(/\s+/g, ' ').trim(); + const max = Math.max(20, Math.min(MAX_CHARS, maxChars | 0 || 200)); + if (t.length > max) t = t.slice(0, max).replace(/\s+\S*$/, '') + '…'; + const plain = t.toLowerCase().replace(/[013457@$!]/g, c => LEET[c] || c); + const words = ' ' + plain.replace(/[^a-z0-9\u00c0-\u024f]+/g, ' ') + ' '; + const squashed = plain.replace(/[^a-z\u00c0-\u024f]+/g, ''); + const blocked = parseBlocklist(blocklist).some(w => { + const ww = w.replace(/[013457@$!]/g, c => LEET[c] || c); + return ww.length >= 4 ? squashed.includes(ww.replace(/[^a-z\u00c0-\u024f]+/g, '')) // longer words: also when spaced out + : words.includes(' ' + ww.replace(/[^a-z0-9\u00c0-\u024f]+/g, ' ').trim() + ' '); + }); + return { text: t, blocked }; +} + // ---------- worker ---------- let proc = null, outBuf = '', nextId = 1; const pending = new Map(); @@ -150,6 +176,11 @@ function layerFilter(l, i) { return `[${i}:a]${f.join(',')}[l${i}]`; } +function durationMs(file) { + return new Promise(resolve => execFile('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file], + { timeout: 10000 }, (err, out) => resolve(err ? 0 : Math.round(parseFloat(out) * 1000) || 0))); +} + function prune() { try { const files = fs.readdirSync(OUT_DIR).filter(f => f.endsWith('.mp3')) @@ -158,7 +189,7 @@ function prune() { } catch (e) { console.warn('[tts] prune:', e.message); } } -// Returns { url, file, cached, ms }. Same config + text = same file (cached). +// Returns { url, file, cached, ms, durationMs }. Same config + text = same file (cached). async function synth(configIn, textIn) { const config = normalize(configIn); const text = cleanText(textIn); @@ -166,7 +197,7 @@ async function synth(configIn, textIn) { const hash = crypto.createHash('sha1').update(JSON.stringify([config, text])).digest('hex').slice(0, 20); const file = path.join(OUT_DIR, `${hash}.mp3`); const url = `/tts/${hash}.mp3`; - if (fs.existsSync(file)) return { url, file, cached: true, ms: 0 }; + if (fs.existsSync(file)) return { url, file, cached: true, ms: 0, durationMs: await durationMs(file) }; const t0 = Date.now(); fs.mkdirSync(TMP_DIR, { recursive: true }); @@ -191,7 +222,7 @@ async function synth(configIn, textIn) { for (const w of wavs) fs.rm(w, { force: true }, () => {}); } prune(); - return { url, file, cached: false, ms: Date.now() - t0 }; + return { url, file, cached: false, ms: Date.now() - t0, durationMs: await durationMs(file) }; } -module.exports = { voices, synth, normalize, cleanText, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS }; +module.exports = { voices, synth, normalize, cleanText, prepareViewerText, parseBlocklist, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS }; diff --git a/views/dashboard.ejs b/views/dashboard.ejs index 7e05b53..c630c52 100644 --- a/views/dashboard.ejs +++ b/views/dashboard.ejs @@ -11,11 +11,27 @@ <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat
      Everything except chat (alerts, redeems, poll, Hype Train bar, raid send-off):
      <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=nochat
      + Chat somewhere else, e.g. in the Intermission panel (left,top,width,height in px of the 1920×1080 page; up = newest at the bottom):
      + <%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %>?parts=chat&chat=130,640,700,360&chatflow=up
      Other combinations: hover for help · everything in one source: /overlay/<%= settings.overlay_id %>
    +
    + + +
    + +

    Twitch connection

    <% if (eventsubStatus.connected) { %> diff --git a/views/overlay.ejs b/views/overlay.ejs index b7469ba..694be44 100644 --- a/views/overlay.ejs +++ b/views/overlay.ejs @@ -67,7 +67,7 @@ - <% if (has('chat')) { %>

    <% } %> + <% if (has('chat')) { %>
    style="--chat-left:<%= chatBox.left %>px; --chat-top:<%= chatBox.top %>px; --chat-width:<%= chatBox.width %>px; --chat-height:<%= chatBox.height %>px;"<% } %>>
    <% } %> <% if (has('alerts')) { %>
    <% } %> @@ -161,6 +161,7 @@ // NOWPLAYING: if (msg.type === 'nowplaying') { if (PARTS.has('nowplaying')) NowPlaying.update(msg.np); return; } if (msg.type === 'nowplaying') return; if (msg.type === 'raid_card') { if (PARTS.has('raid')) RaidCard.update(msg.phase, msg.raid); return; } + if (msg.type === 'alert_skip') { if (PARTS.has('alerts')) PolaroidAlerts.skip(); return; } if (!PARTS.has('alerts')) return; // alerts and legacy actions below if (msg.type === 'alert') { // test buttons: replace other test alerts at once, but never cut off a real alert diff --git a/views/redeems.ejs b/views/redeems.ejs index 3b5912f..6dc2aab 100644 --- a/views/redeems.ejs +++ b/views/redeems.ejs @@ -40,6 +40,7 @@ <% if (t.cost != null) { %><%= t.cost %> pts<% } %> <% if (t.missing) { %>not on Twitch anymore<% } %> <% if (t.live === false) { %>paused on Twitch<% } %> + <% if (t.variations.some(v => v.tts_voice_id)) { %>TTS<% } %> <%= t.variations.length ? `${on.length}/${t.variations.length} variation${t.variations.length === 1 ? '' : 's'} on` : 'no alert' %> @@ -72,6 +73,10 @@ <% for (const st of stickers) { %><% } %> + @@ -122,6 +127,17 @@ post('/redeems/trigger/test', { kind: b.dataset.kind, key: b.dataset.key }); })); + // TTS on = no sound: grey out the sound picker (the server ignores it too) + document.querySelectorAll('[data-tts]').forEach(sel => { + const form = sel.closest('form'), snd = form.querySelector('[data-sound]'); + const sync = () => { + snd.disabled = !!sel.value; + snd.title = sel.value ? 'TTS is on: the voice replaces the sound' : ''; + }; + sel.addEventListener('change', sync); sync(); + form.addEventListener('submit', () => { snd.disabled = false; }); // still submit it, so turning TTS off brings the sound back + }); + // two-step delete, no browser dialog document.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => { const c = b.parentElement.querySelector('[data-del-confirm]'); diff --git a/views/settings.ejs b/views/settings.ejs index d54e29c..f653c79 100644 --- a/views/settings.ejs +++ b/views/settings.ejs @@ -58,6 +58,25 @@ e.g. 3600 = 1 hour of silence → max volume +

    TTS redeems

    +

    For redeem variations with a TTS voice (set on the Redeems page; voices are made on the TTS page).

    +
    + + +
    + +

    Custom CSS / JS