Compare commits
No commits in common. "3fe1443e42b7aa3e460727de62411b4ad974ef37" and "f07489750cc3942df8c8a4b45ce04e080a71d283" have entirely different histories.
3fe1443e42
...
f07489750c
103 changed files with 803 additions and 9132 deletions
|
|
@ -10,9 +10,3 @@ SECRET_KEY=change_this_to_a_random_string
|
||||||
APP_BASE_URL=https://overlay.example.com
|
APP_BASE_URL=https://overlay.example.com
|
||||||
DB_PATH=./heystreamer.db
|
DB_PATH=./heystreamer.db
|
||||||
PORT=3000
|
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=
|
|
||||||
|
|
|
||||||
26
.gitignore
vendored
26
.gitignore
vendored
|
|
@ -6,29 +6,3 @@ __pycache__/
|
||||||
venv/
|
venv/
|
||||||
static/media/*
|
static/media/*
|
||||||
!static/media/.gitkeep
|
!static/media/.gitkeep
|
||||||
|
|
||||||
# Node
|
|
||||||
node_modules/
|
|
||||||
*.db-shm
|
|
||||||
*.db-wal
|
|
||||||
public/media/*
|
|
||||||
!public/media/.gitkeep
|
|
||||||
|
|
||||||
# TTS: generated audio, Piper install and voice models (tools/tts/setup.sh)
|
|
||||||
public/tts/
|
|
||||||
tools/tts/venv/
|
|
||||||
tools/tts/voices/
|
|
||||||
|
|
||||||
# Twitch analytics exports (channel data, revenue): import them on the Stats page, never commit them
|
|
||||||
*.csv
|
|
||||||
|
|
||||||
# The channel's own media library (pictures, stickers, sounds, videos picked on Actions → Alerts / Redeems):
|
|
||||||
# stays on disk and travels with the rsync deploy, never in git. Everything else is set in the dashboard (database).
|
|
||||||
public/alerts/art/*
|
|
||||||
!public/alerts/art/placeholder.svg
|
|
||||||
public/alerts/stickers/
|
|
||||||
public/alerts/sounds/
|
|
||||||
public/alerts/videos/*
|
|
||||||
!public/alerts/videos/.gitkeep
|
|
||||||
# this channel's deployment notes for Claude Code (hosts, server user)
|
|
||||||
CLAUDE.local.md
|
|
||||||
|
|
|
||||||
292
CLAUDE.md
292
CLAUDE.md
|
|
@ -14,8 +14,8 @@ Requires `.env` — copy from `.env.example`. Database is created automatically
|
||||||
|
|
||||||
- **Node.js** · Express · EJS templates
|
- **Node.js** · Express · EJS templates
|
||||||
- **better-sqlite3** — SQLite, synchronous, simple
|
- **better-sqlite3** — SQLite, synchronous, simple
|
||||||
- **ws** — WebSocket server for pushing alerts and settings to overlay clients
|
- **ws** — WebSocket server for pushing alerts to overlay clients
|
||||||
- **tmi.js** — Twitch IRC, runs in the browser on the overlay page (no server-side IRC). Self-hosted at `public/vendor/tmi.min.js` — the npm package has no browser build, downloaded from GitHub release
|
- **tmi.js** — Twitch IRC, runs in the browser on the overlay page (no server-side IRC)
|
||||||
- **multer** — file uploads
|
- **multer** — file uploads
|
||||||
- **uuid** — UUID generation
|
- **uuid** — UUID generation
|
||||||
- **dotenv** — env vars
|
- **dotenv** — env vars
|
||||||
|
|
@ -26,7 +26,6 @@ Requires `.env` — copy from `.env.example`. Database is created automatically
|
||||||
```
|
```
|
||||||
Twitch ──EventSub WebSocket──► src/eventsub.js ──► dispatch.js ──► ws.js ──► OBS overlay
|
Twitch ──EventSub WebSocket──► src/eventsub.js ──► dispatch.js ──► ws.js ──► OBS overlay
|
||||||
Twitch ──IRC (tmi.js in browser) ────────────────────────────────────────► 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
|
- `eventsub.js` opens a WebSocket to Twitch on startup, managed as a module-level singleton
|
||||||
|
|
@ -35,7 +34,6 @@ Dashboard /settings save ──────────────────
|
||||||
- `wss` (ws.js) holds all active WebSocket connections from `/ws/overlay`
|
- `wss` (ws.js) holds all active WebSocket connections from `/ws/overlay`
|
||||||
- The overlay JS receives the broadcast and plays the action
|
- The overlay JS receives the broadcast and plays the action
|
||||||
- Chat messages come directly from tmi.js running in the browser — no server relay
|
- 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
|
## Project structure
|
||||||
|
|
||||||
|
|
@ -51,22 +49,23 @@ src/
|
||||||
routers/
|
routers/
|
||||||
auth.js — /auth/* (Twitch OAuth)
|
auth.js — /auth/* (Twitch OAuth)
|
||||||
dashboard.js — / (activity log, EventSub status)
|
dashboard.js — / (activity log, EventSub status)
|
||||||
overlay.js — /overlay/:uuid, /ws/overlay
|
overlay.js — /overlay/:uuid, /overlay/:uuid/preview, /ws/overlay
|
||||||
actions.js — /actions CRUD
|
actions.js — /actions CRUD
|
||||||
media.js — /media upload/delete
|
media.js — /media upload/delete
|
||||||
|
layout.js — /layout editor + /layout/positions
|
||||||
settings.js — /settings
|
settings.js — /settings
|
||||||
views/
|
views/
|
||||||
layout.ejs — base shell (nav, Pico CSS)
|
layout.ejs — base shell (nav, Pico CSS)
|
||||||
login.ejs
|
login.ejs
|
||||||
dashboard.ejs
|
dashboard.ejs
|
||||||
overlay.ejs — OBS browser source
|
overlay.ejs — OBS browser source
|
||||||
|
overlay_preview.ejs
|
||||||
|
layout_editor.ejs
|
||||||
actions.ejs
|
actions.ejs
|
||||||
media.ejs
|
media.ejs
|
||||||
settings.ejs
|
settings.ejs
|
||||||
public/
|
public/
|
||||||
media/ — uploaded files (gitignored)
|
media/ — uploaded files (gitignored)
|
||||||
vendor/
|
|
||||||
tmi.min.js — self-hosted tmi.js browser build
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Key conventions
|
## Key conventions
|
||||||
|
|
@ -88,14 +87,6 @@ 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.
|
**UUID overlays.** `settings.overlay_id` is a UUID generated on first run. OBS browser source URL is `/overlay/:uuid`. Future multi-user support creates multiple settings rows.
|
||||||
|
|
||||||
**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. Pass `layout: false` to render without the shell (overlay, `_activity` partial).
|
|
||||||
|
|
||||||
**Form value parsing.** Never use `parseInt(val) || default` — it overwrites valid `0` values. Use:
|
|
||||||
```javascript
|
|
||||||
const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; };
|
|
||||||
const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
|
|
||||||
```
|
|
||||||
|
|
||||||
## Route map
|
## Route map
|
||||||
|
|
||||||
| Method | Path | File | Notes |
|
| Method | Path | File | Notes |
|
||||||
|
|
@ -106,6 +97,7 @@ 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/callback` | routers/auth.js | Exchange code, save user, start EventSub |
|
||||||
| GET | `/auth/logout` | routers/auth.js | Clear session |
|
| GET | `/auth/logout` | routers/auth.js | Clear session |
|
||||||
| GET | `/overlay/:uuid` | routers/overlay.js | Live OBS browser source |
|
| 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 |
|
| WS | `/ws/overlay` | routers/overlay.js | Bidirectional: commands up, actions down |
|
||||||
| GET/POST | `/actions` | routers/actions.js | List and create actions |
|
| GET/POST | `/actions` | routers/actions.js | List and create actions |
|
||||||
| POST | `/actions/:id/test` | routers/actions.js | Fire immediately, skip cooldown |
|
| POST | `/actions/:id/test` | routers/actions.js | Fire immediately, skip cooldown |
|
||||||
|
|
@ -113,61 +105,30 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
|
||||||
| DELETE | `/actions/:id` | routers/actions.js | Delete |
|
| DELETE | `/actions/:id` | routers/actions.js | Delete |
|
||||||
| GET/POST | `/media` | routers/media.js | Upload, list |
|
| GET/POST | `/media` | routers/media.js | Upload, list |
|
||||||
| DELETE | `/media/:id` | routers/media.js | Delete file + DB row |
|
| DELETE | `/media/:id` | routers/media.js | Delete file + DB row |
|
||||||
| GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS; broadcasts settings_update on save |
|
| GET/POST | `/layout` | routers/layout.js | Style form |
|
||||||
|
| POST | `/layout/positions` | routers/layout.js | JSON, called by drag JS |
|
||||||
|
| GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS |
|
||||||
| POST | `/settings/reconnect` | routers/settings.js | Restart EventSub |
|
| POST | `/settings/reconnect` | routers/settings.js | Restart EventSub |
|
||||||
| GET | `/activity` | routers/dashboard.js | Activity table partial (dashboard Reload / auto-refresh) |
|
|
||||||
| POST | `/alerts/test/:key` | routers/alerts.js | Send a sample polaroid alert to the overlay |
|
|
||||||
|
|
||||||
## Overlay chat position and style
|
## Overlay CSS variable system
|
||||||
|
|
||||||
The layout editor was removed (2026-11-20); the `overlay_layout` table is still created but unused, so old data is kept.
|
All overlay positioning and styling uses CSS custom properties rendered into `overlay.ejs` and `overlay_preview.ejs` from the `overlay_layout` row:
|
||||||
The legacy text/video action alert position lives in the `:root` block of `views/overlay.ejs`.
|
|
||||||
|
|
||||||
Chat (`?parts=chat`) is `public/chat/chat.css` + `public/chat/chat.js` (window.HSChat), fed by tmi.js in overlay.ejs:
|
| Variable | Controls |
|
||||||
- Look: cream paper slips, name on a washi-tape label tinted with the chatter's Twitch colour, slight random tilt.
|
|---|---|
|
||||||
- Flow: the box sits under the webcam (Game scene camera group 1920,600 640x360 on the 2560 canvas), newest on top;
|
| `--chat-left`, `--chat-top` | Chat box position (%) |
|
||||||
a new message slides out from under the camera, the rest glide down (FLIP with the `translate` property) and the
|
| `--chat-width`, `--chat-height` | Chat box size (%) |
|
||||||
oldest dissolve at the bottom (mask-image fade). Expire after `message_timeout` s, cap `max_messages`.
|
| `--chat-font-size` | Chat font size (px) |
|
||||||
- Move/resize with Custom CSS: `#chat { --chat-top: 63%; --chat-right: 2%; --chat-width: 20%; --chat-height: 34%; }`.
|
| `--chat-font-family` | Chat font family |
|
||||||
- Emotes: Twitch (from `tags.emotes`, code-point ranges) + 7TV global and channel sets (`7tv.io/v3`, channel by
|
| `--chat-bg-opacity` | Chat message background opacity |
|
||||||
`room-id` from ROOMSTATE, refreshed every 10 min). 7TV zero-width emotes (data flag 256) stack on the emote before.
|
| `--chat-text-color` | Chat message text colour |
|
||||||
Emote-only messages (up to 3 emotes) get bigger emotes.
|
| `--chat-border-radius` | Message border radius (px) |
|
||||||
- Moderation: deleted messages, timeouts, bans and /clear remove the matching slips at once.
|
| `--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 |
|
||||||
|
|
||||||
## Overlay updates after a deploy
|
The layout editor (`/layout`) overlays drag handles on an iframe pointing to `/overlay/:uuid/preview`. Same-origin, so the editor sets CSS variables directly on the iframe's document for live preview. Saved via `POST /layout/positions`.
|
||||||
|
|
||||||
OBS keeps an overlay page running for hours, so after a deploy it would keep the old alert code. `src/ws.js` has a
|
|
||||||
`BOOT_ID` (new on every server start); the overlay page is rendered with it, and the server sends
|
|
||||||
`{type:'hello', boot}` on every WebSocket connect. When the overlay reconnects after a restart and the ID differs, it
|
|
||||||
reloads itself (1.5 s later). Asset URLs in overlay.ejs carry `?v=<BOOT_ID>` so the reload never uses cached files.
|
|
||||||
|
|
||||||
## TTS voices (/tts)
|
|
||||||
|
|
||||||
Builder page to make named TTS voices, used by redeem variations (Redeems page: "TTS: <voice>" per variation).
|
|
||||||
- Redeem with a TTS voice + viewer text: `redeems.addSpeech()` cleans the text (`tts.prepareViewerText`: links out,
|
|
||||||
repeats collapsed, cut to `settings.tts_max_chars` at a word, `settings.tts_blocklist` -> nothing read, letter says
|
|
||||||
"(message removed)"; whole-word matching with plurals, look-alike swaps and spaced-out letters; starter list
|
|
||||||
`src/tts-blocklist.txt` is merged into the setting once, `tts_blocklist_seeded`), synthesizes "<user> says: <text>" (`tts_say_name`), and only then sends the alert with
|
|
||||||
`tts` (URL), `tts_ms`, `tts_env` (loudness per 40 ms, `tts.loudness()`) and `tts_prefix` (words said before the message).
|
|
||||||
Shown as the envelope letter (style `tts`, `public/alerts/fx.js` envelope(), CSS in fx.css): flap opens, the letter rises
|
|
||||||
out and settles in front ~80px from the top, words ink in as spoken (timing estimated from tts_env; if the voice
|
|
||||||
does not start, the whole text shows). Design preview: `~/Desktop/Stream/tts-alerts/`. TTS on = the variation's
|
|
||||||
sound is not sent (the voice replaces it; the Redeems page greys the picker out). Synthesis errors: the note still shows, silent.
|
|
||||||
- Dashboard "Skip current alert" -> POST `/alerts/skip` -> WS `{type:'alert_skip'}` -> `PolaroidAlerts.skip()`.
|
|
||||||
- `tts_blocklist` never goes to overlay pages: they get `db.getOverlaySettings()` (render and settings_update).
|
|
||||||
- New columns on existing DBs are added by `db.migrate()` (`addColumn`, ALTER only when missing).
|
|
||||||
- `src/tts.js`: `synth(config, text)` -> cached mp3 in `public/tts/<sha1>.mp3` (gitignored, newest 300 kept).
|
|
||||||
Config = up to 3 `layers` (engine `piper`|`espeak`, voice, speaker, speed, pitch in semitones, volume, delay ms)
|
|
||||||
+ `effects` {stadium, echo, crush, radio, robot, chorus, flanger, tremolo: 0..1}. `normalize()` clamps everything
|
|
||||||
and only accepts plain voice/speaker names (no paths). Pitch = asetrate+atempo (formants shift too: the demon sound).
|
|
||||||
ffmpeg: per-layer pitch/volume/delay -> amix -> effects -> loudnorm -> mono mp3.
|
|
||||||
- `tools/tts/worker.py`: long-running Python process (JSON lines over stdin/stdout), started on first use. Piper
|
|
||||||
models stay loaded (LRU, `TTS_MAX_LOADED`=4, ~100 MB each); espeak-ng via libespeak-ng + ctypes (no binary needed).
|
|
||||||
- Setup (server): `sudo apt install python3-venv ffmpeg espeak-ng`, then `tools/tts/setup.sh` (venv + default voices
|
|
||||||
into `tools/tts/voices/`, both gitignored). Extra voices: `tools/tts/setup.sh en_US-amy-medium ...`.
|
|
||||||
Env overrides: `TTS_PYTHON`, `TTS_VOICES_DIR`.
|
|
||||||
- Table `tts_voices` (name, config JSON). Routes: GET `/tts`, POST `/tts/preview`, POST `/tts/voices`, POST `/tts/voices/:id/delete`.
|
|
||||||
- SAM (C64 voice) was left out on purpose: the only JS port has no licence (abandonware).
|
|
||||||
|
|
||||||
## Gap / new-message audio
|
## Gap / new-message audio
|
||||||
|
|
||||||
|
|
@ -176,20 +137,20 @@ Configured in `settings`. When a chat message arrives in the overlay, tmi.js che
|
||||||
2. Has at least `gap_audio_min_silence` seconds passed since the last message?
|
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`.
|
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.
|
All logic runs in the browser. The server only serves the config.
|
||||||
|
|
||||||
## Custom events dispatched to overlay JS
|
## Custom events dispatched to overlay JS
|
||||||
|
|
||||||
When the overlay WebSocket receives a message:
|
When the overlay WebSocket receives an action broadcast:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }));
|
||||||
|
```
|
||||||
|
|
||||||
|
Available: `sub`, `gift_sub`, `bits`, `channel_points`, `command`, `follow`, `raid`.
|
||||||
|
|
||||||
- **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 }`.
|
`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
|
## Database schema
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
|
|
@ -203,176 +164,51 @@ activity_log — append-only event log
|
||||||
|
|
||||||
## EventSub subscriptions
|
## EventSub subscriptions
|
||||||
|
|
||||||
| Twitch event | Version | Condition | Scope | Used for |
|
| Twitch event | Version | Condition | Scope |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | follow alert |
|
| `channel.subscribe` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` |
|
||||||
| `channel.bits.use` | 1 | `broadcaster_user_id` | `bits:read` | cheers (bits alert) **and** Power-ups (`type: power_up` → Redeems); replaced `channel.cheer` |
|
| `channel.subscription.message` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` |
|
||||||
| `channel.chat.notification` | 1 | `broadcaster_user_id` + `user_id` | `user:read:chat` | subs, resubs, Prime, multi-month, gifts, community gifts, raids |
|
| `channel.subscription.gift` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` |
|
||||||
| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | channel point rewards → Redeems |
|
| `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` |
|
||||||
| `channel.channel_points_automatic_reward_redemption.add` | 2 | `broadcaster_user_id` | `channel:read:redemptions` | built-in rewards (highlight message, emote unlocks) → Redeems |
|
| `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 |
|
||||||
|
|
||||||
`channel.chat.notification` replaced `channel.subscribe` / `subscription.message` / `subscription.gift` / `channel.raid`:
|
Token refresh triggered on 401 during subscription.
|
||||||
one event carries `is_prime`, `duration_months` (months bought at once), `cumulative_months`, the gift recipient,
|
|
||||||
community gift totals and the resub message. `sub_gift` notices with a `community_gift_id` are skipped (the
|
|
||||||
`community_sub_gift` notice covers the whole bomb), so a gift bomb is one alert.
|
|
||||||
|
|
||||||
**Lifecycle (src/eventsub.js, src/twitch.js):**
|
|
||||||
- Started on boot from the stored login (`db.getPrimaryUser()`), and again after OAuth login. `EVENTSUB_DISABLED=1` skips it (local UI work).
|
|
||||||
- Token: validated hourly and before subscribing; refreshed when it expires or on any 401 (`twitch.helix()`), new tokens saved to `users`.
|
|
||||||
- `session_reconnect`: connects to the given URL (subscriptions carry over), swaps sockets on its welcome.
|
|
||||||
- Keepalive watchdog: no message for `keepalive_timeout_seconds + 10s` → reconnect.
|
|
||||||
- Status (connected / subscribed / failed / last event) shown on the dashboard.
|
|
||||||
|
|
||||||
## Redeems (channel points, built-in rewards, bits Power-ups)
|
|
||||||
|
|
||||||
Page `/redeems` (src/routers/redeems.js, views/redeems.ejs, logic in src/redeems.js), table `reward_variations`.
|
|
||||||
|
|
||||||
- A trigger is `kind` + `key`: `reward` + Twitch reward id, `auto_reward` + built-in type, `power_up` + Power-up type.
|
|
||||||
- Each trigger has variations (name, rarity, sound, volume, polaroid on/off, caption, art, enabled). On a redemption
|
|
||||||
ONE enabled variation is picked at random, weighted by rarity (`RARITY` in src/redeems.js: weights Common 50 / Uncommon 25 / Rare 12 / Ultra Rare 3 (Twitch's Super Rare merged into Ultra Rare); chance = weight ÷ sum of the trigger's enabled weights), like
|
|
||||||
Twitch alert variations. No enabled variation → only logged (and legacy actions run).
|
|
||||||
- Custom rewards are listed live from Helix `GET /channel_points/custom_rewards` (title, cost, icon); built-in rewards
|
|
||||||
and Power-ups are fixed lists. Titles are refreshed when a redemption arrives with a new name.
|
|
||||||
- Shown as a cassette tape (`public/alerts/cassette.js` + `.css`, called from polaroid.js so it shares the queue):
|
|
||||||
rarity = shell colour (Ultra Rare: gold, glow, foil, sparkles), reels spin over the sound's length, label =
|
|
||||||
variation name + reward, paper strip = viewer + caption + typed message, sticker in the corner = the variation's
|
|
||||||
`art` (URL; '' = the theme's default sticker). `polaroid` column = "show cassette" (0 = sound only).
|
|
||||||
- Special styles instead of the cassette (`STYLE` in src/redeems.js, drawn by `public/alerts/fx.js` + `.css`):
|
|
||||||
Gigantify Power-up → the viewer's emote grows giant; On-Screen Celebration → 14 copies of the emote bounce around
|
|
||||||
the whole screen for the sound's length; Highlight my message and the Message Effect Power-up → big taped paper note, taller than wide (stays ~2 s + 70 ms/char).
|
|
||||||
Emote image = `https://static-cdn.jtvnw.net/emoticons/v2/<id>/default/dark/3.0` from `event.power_up.emote.id`
|
|
||||||
(fallback: heart). Default caption becomes "gigantified an emote!" / "is celebrating!" / "highlighted:".
|
|
||||||
- Sound picker = `public/alerts/sounds/redeems/` (redeem clips, loudness-normalized to -16 LUFS with ffmpeg
|
|
||||||
two-pass loudnorm, so volume stays 0.8), `public/alerts/sounds/` (alert sounds + library) and audio uploaded on
|
|
||||||
the Media page (`/media/<file>`). Stickers: `public/alerts/stickers/` (cut out with rembg / hand masks).
|
|
||||||
- polaroid off = sound only: it still waits its turn in the overlay queue and holds it for the sound's length.
|
|
||||||
- First run: `src/redeems-seed.json` (Twitch's built-in rewards / Power-ups, silent, Card look) is loaded when the table is
|
|
||||||
empty. After that the dashboard is the source of truth; the seed file is never re-applied.
|
|
||||||
- Test buttons: per variation, and "Test random" per trigger (`POST /redeems/variation/:id/test`, `/redeems/trigger/test`).
|
|
||||||
- Power-up payload field names (`event.type === 'power_up'`, `event.power_up.type`) follow Twitch's docs but were not
|
|
||||||
yet seen live; check `activity_log.data_json` of the first real Power-up.
|
|
||||||
|
|
||||||
## Raid send-off and Hype Train bar
|
|
||||||
|
|
||||||
- Outgoing raid send-off: Twitch has no "raid started" event, so raids are started from the dashboard Raid box
|
|
||||||
(`POST /alerts/raid/start` → Helix `POST /raids`, scope `channel:manage:raids`; `/alerts/raid/cancel` → `DELETE /raids`).
|
|
||||||
The silent card (`public/alerts/raidcard.js`, top-centre polaroid with the target's Twitch avatar, "raiding X / with N
|
|
||||||
of you, be nice! ♡", 90 s countdown) stays until `channel.raid` (`from_broadcaster_user_id` = us) arrives, then
|
|
||||||
shows "raid sent!" and leaves. Raid started on Twitch directly: card shows only at that moment. Test: `raid-card-test`.
|
|
||||||
- Hype Train bar: every `channel.hype_train.*` event also goes out as `{type:'hype_bar', phase, train}`;
|
|
||||||
`public/alerts/hypebar.js` shows a slim taped strip top-left (LV, progress/goal bar, time left; gold for Golden
|
|
||||||
Kappa), outside the queue; on end it shows the final level for 5 s and slides away. Test: dashboard `hype-bar-test`.
|
|
||||||
|
|
||||||
## Overlay parts (two OBS sources)
|
|
||||||
|
|
||||||
`/overlay/:uuid?parts=` picks what a browser source shows: `chat` (chat box + gap audio), `alerts` (polaroid queue,
|
|
||||||
redeems, legacy actions), `poll`, `hypebar`, `raid`. List parts (`?parts=chat,raid`) or exclude them with `no<part>`
|
|
||||||
(`?parts=nochat`, `?parts=nochat,noraid`). No `?parts=` = all. Recommended: `?parts=chat` as a source with audio
|
|
||||||
"Monitor Only (mute output)" (chat sounds stay off stream) and `?parts=nochat` as the main source. Every source receives every WebSocket message and ignores the parts it does not show, so nothing plays twice.
|
|
||||||
Every source still listens to chat for watch streaks; the server dedupes the reports by message id.
|
|
||||||
|
|
||||||
## Now playing (Feishin) — SWITCHED OFF for now
|
|
||||||
|
|
||||||
Kept in the repo but disabled: the `/nowplaying` route is commented out in `src/app.js`, `nowplaying` is not in
|
|
||||||
`PARTS` (src/routers/overlay.js) and the overlay lines are commented (marked NOWPLAYING in views/overlay.ejs).
|
|
||||||
To re-enable: undo those three. Description of how it works when enabled:
|
|
||||||
|
|
||||||
|
|
||||||
- `tools/nowplaying/feishin_nowplaying.py` runs on the streaming PC: watches Feishin over MPRIS (D-Bus, PyGObject),
|
|
||||||
POSTs `{status,title,artist,album,length,cover}` to `/nowplaying` with `Authorization: Bearer NOWPLAYING_KEY`
|
|
||||||
on every change + every 30 s. Config `~/.config/heystreamer-nowplaying.env` (HEYSTREAMER_URL, NOWPLAYING_KEY);
|
|
||||||
systemd user unit next to the script.
|
|
||||||
- Feishin's `mpris:artUrl` points at Navidrome on the LAN and carries the Subsonic token: the helper downloads the
|
|
||||||
cover itself and sends a 160 px JPEG data URL, so no URL/credential ever leaves the PC.
|
|
||||||
- Server: `src/routers/nowplaying.js` (key check, sanitised fields, data-URL-only cover) → `src/nowplaying.js` keeps
|
|
||||||
the current song and broadcasts `{type:'nowplaying', np}`; new overlay connections get it on connect.
|
|
||||||
- Overlay: `public/alerts/nowplaying.js` small taped paper slip (cover, title, artist) top-right, visible only while
|
|
||||||
`playing`; hides 1.5 s after pause/stop (grace so track changes do not flicker). Chat position unchanged.
|
|
||||||
|
|
||||||
## StreamElements tips
|
|
||||||
|
|
||||||
- `src/streamelements.js`: Astro websocket (`wss://astro.streamelements.com`, override `SE_URL` for tests). Off unless
|
|
||||||
`SE_JWT` is set in `.env` (StreamElements dashboard → avatar → channel → JWT token; secret, never commit).
|
|
||||||
- welcome → subscribe `{topic:'channel.tips', token, token_type:'jwt'}` → `message` on `channel.tips`; tip fields in
|
|
||||||
`data.donation` (`user.username`, `amount`, `currency`, `message`). Only `approved: 'allowed'` + `status: 'success'`
|
|
||||||
alert; deduped by `data._id`. `reconnect` message → reconnect with `?reconnect_token=` (no re-subscribe). Server
|
|
||||||
PINGs every 30 s (ws answers). Status on the dashboard.
|
|
||||||
- Alert: tip polaroid (art + sound from the theme, amount via Intl currency format, badge, +1/2/3 hearts at 10/25/50).
|
|
||||||
Turn off StreamElements' own tip alert in its overlay to avoid doubles.
|
|
||||||
|
|
||||||
## Polls and Hype Train
|
|
||||||
|
|
||||||
- Polls (`channel.poll.begin/progress/end` v1, scope `channel:read:polls`): `alerts.sendPoll()` broadcasts
|
|
||||||
`{type:'poll', phase, poll}`; `public/alerts/poll.js` shows a live taped-paper card (left, below the alert corner,
|
|
||||||
NOT in the alert queue): bars + votes + countdown; on `completed` the winner gets a heart + WINNER stamp, then it
|
|
||||||
drops away after 9 s (archived/terminated: away after 1.5 s). Begin/end are logged. Test: dashboard `poll-test`.
|
|
||||||
- Hype Train (`channel.hype_train.*` v2, scope `channel:read:hype_train`): `alerts.fromHypeTrain()` → queued polaroid
|
|
||||||
alerts on start, on each NEW level (progress fires per contribution) and at the end (top contributors). theme art
|
|
||||||
art; sounds pro-gamer / toad-ya-hoo / tadaaa (in `describe()` case 'hype'). Golden Kappa / Treasure trains named.
|
|
||||||
|
|
||||||
## Polaroid alerts
|
|
||||||
|
|
||||||
```
|
|
||||||
Twitch EventSub ─► eventsub.js ─► alerts.js (fromFollow / fromCheer / fromChatNotification) ─► alerts.send()
|
|
||||||
Overlay chat (tmi.js USERNOTICE viewermilestone) ─► WS up {type:'chat_notice'} ─► alerts.fromOverlayNotice() ─┘
|
|
||||||
alerts.send() ─► ws.broadcast({type:'alert', alert}) ─► overlay ─► public/alerts/polaroid.js (queue + animation + sound)
|
|
||||||
└─► dispatch.dispatchEvent() (activity log + legacy actions keep working)
|
|
||||||
```
|
|
||||||
|
|
||||||
- Alert shape and per-event look (art, caption, tape colour, badge, sound, bits tiers) live in `public/alerts/polaroid.js` (`describe()` + CONFIG block). Art in `public/alerts/art/`, sounds in `public/alerts/sounds/`. Sound lengths come from `SOUND_MS` or are measured in the browser (redeem sounds picked in the UI), so the alert holds for the whole sound. Redeem alerts carry their own sound URL, volume, art and caption.
|
|
||||||
- Watch streaks only exist in chat. The overlay reports them; the server only accepts `chat_notice` from WS connections that pass `?overlay=<overlay_id>` and dedupes by message id (several overlays may report the same notice).
|
|
||||||
- Test buttons on the dashboard: `POST /alerts/test/:key` (keys = `alerts.TEST_KEYS`). 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
|
## Production deployment
|
||||||
|
|
||||||
Runs behind Apache (or any reverse proxy) as a proxy to Node on port 3000. This channel's real hosts, server user and
|
Runs behind Apache on the VPS as a reverse proxy to Node on port 3000.
|
||||||
deploy command are in `CLAUDE.local.md` (not in git; Claude Code loads it automatically).
|
Production domain: `https://overlay.example.com`
|
||||||
|
|
||||||
Apache vhost: `apache.example.sh` is a template (copy it outside the repo, fill in your hosts, run it on the server).
|
Minimal Apache vhost config (requires `mod_proxy`, `mod_proxy_http`, `mod_proxy_wstunnel`):
|
||||||
Key requirements:
|
```apache
|
||||||
- `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)
|
<VirtualHost *:443>
|
||||||
- `app.set('trust proxy', 1)` is set in `app.js` before all middleware
|
ServerName overlay.example.com
|
||||||
- `/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 by copying the working folder (rsync), not by git: the channel's media library is not in git and must travel too.
|
ProxyPreserveHost On
|
||||||
|
ProxyPass /ws/overlay ws://127.0.0.1:3000/ws/overlay
|
||||||
|
ProxyPassReverse /ws/overlay ws://127.0.0.1:3000/ws/overlay
|
||||||
|
ProxyPass / http://127.0.0.1:3000/
|
||||||
|
ProxyPassReverse / http://127.0.0.1:3000/
|
||||||
|
|
||||||
|
# SSL config here (certbot/Let's Encrypt)
|
||||||
|
</VirtualHost>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `/ws/overlay` must be proxied separately with `ws://` via `mod_proxy_wstunnel` — if it's not listed before the catch-all `/`, WebSocket connections will fail. Enable the required modules with:
|
||||||
```bash
|
```bash
|
||||||
rsync -avzO --exclude='node_modules' --exclude='.env' --exclude='public/media' --exclude='*.db*' \
|
sudo a2enmod proxy proxy_http proxy_wstunnel
|
||||||
./ user@your-server:/opt/heystreamer/
|
sudo systemctl reload apache2
|
||||||
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:
|
Twitch requires HTTPS for OAuth redirect URIs in production. Register both in the Twitch dev console:
|
||||||
- `http://localhost:3000/auth/callback` (dev)
|
- `http://localhost:3000/auth/callback` (dev)
|
||||||
- `https://overlay.example.com/auth/callback` (production)
|
- `https://overlay.example.com/auth/callback` (production)
|
||||||
|
|
||||||
## Channel setup lives in the database, not in files
|
|
||||||
|
|
||||||
Everything a channel customises is set in the dashboard and stored in the database, so the repo holds no channel
|
|
||||||
data and `git pull` never touches a channel's setup:
|
|
||||||
|
|
||||||
| Where in the dashboard | Stored in |
|
|
||||||
|---|---|
|
|
||||||
| Actions → Alerts: style (Card / Polaroid), pictures, sounds, bits tiers, card colours (`src/theme.js`) | `settings.alert_theme` (JSON) |
|
|
||||||
| Actions → Redeems: variations, look (Card / Cassette / Sound only / Video), TTS voice | `reward_variations` |
|
|
||||||
| Actions → TTS voices, Media (uploads in `public/media/`, not in git) | `tts_voices`, `media_files` |
|
|
||||||
| Settings → General, Connections (StreamElements token), Chat, TTS, Stats, Advanced | `settings` |
|
|
||||||
| Settings → Backup: export / import all of the above as one JSON file | — |
|
|
||||||
|
|
||||||
Alert styles: **Card** (`public/alerts/card.js`, the plain default) for everyone; **Polaroid**, **Cassette** and the
|
|
||||||
**Letter** (TTS) are optional looks anyone can pick. The overlay receives the merged theme with its settings
|
|
||||||
(`S.alert_theme`) and reads it per alert, so saving in the dashboard needs no OBS reload. An old file-based
|
|
||||||
`public/alerts/theme.js` is imported once at startup (`theme.importLegacyFile()`).
|
|
||||||
|
|
||||||
Not in git (`.gitignore`): the database, `.env`, uploads (`public/media`), TTS clips, analytics CSV exports, the
|
|
||||||
channel's media library under `public/alerts/{art,stickers,sounds,videos}` (picked like uploads on Actions → Alerts /
|
|
||||||
Redeems), and `CLAUDE.local.md` (this channel's hosts / deploy notes). Never commit viewer names, stats, revenue,
|
|
||||||
reward ids or the channel's hosts.
|
|
||||||
|
|
||||||
## Not yet implemented
|
## Not yet implemented
|
||||||
|
|
||||||
|
- Alert variable interpolation (`{username}` in alert text)
|
||||||
- Mod access (streamer-only login for now)
|
- Mod access (streamer-only login for now)
|
||||||
- Chat commands triggering actions
|
- Chat commands triggering actions
|
||||||
- Stripe / PayPal / ETH payment notifications
|
- Stripe / PayPal / ETH payment notifications
|
||||||
|
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Template (copy to apache.sh, not in git, and use your own hosts). Writes /etc/apache2/sites-available/overlay.example.conf and reloads Apache.
|
|
||||||
# Run on the VPS: bash apache.sh
|
|
||||||
set -e
|
|
||||||
|
|
||||||
CONF=/etc/apache2/sites-available/overlay.example.conf
|
|
||||||
|
|
||||||
sudo tee "$CONF" > /dev/null << 'EOF'
|
|
||||||
# ── overlay.example.com + heystreamer.example.com + stats.example.com ───────
|
|
||||||
# stats.example.com = the public stats page (the app serves ONLY that page on this host).
|
|
||||||
# Its certificate: sudo certbot certonly --apache --cert-name example.com --expand -d <every name already on it> -d stats.example.com
|
|
||||||
# HTTP: redirect everything to HTTPS
|
|
||||||
<VirtualHost *:80>
|
|
||||||
ServerName overlay.example.com
|
|
||||||
ServerAlias heystreamer.example.com stats.example.com
|
|
||||||
|
|
||||||
RewriteEngine on
|
|
||||||
RewriteCond %{SERVER_NAME} =heystreamer.example.com [OR]
|
|
||||||
RewriteCond %{SERVER_NAME} =stats.example.com [OR]
|
|
||||||
RewriteCond %{SERVER_NAME} =overlay.example.com
|
|
||||||
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
|
|
||||||
|
|
||||||
ErrorLog ${APACHE_LOG_DIR}/example.com/overlay.error.log
|
|
||||||
CustomLog ${APACHE_LOG_DIR}/example.com/overlay.access.log combined
|
|
||||||
</VirtualHost>
|
|
||||||
|
|
||||||
# HTTPS: proxy to Node on port 3000
|
|
||||||
<IfModule mod_ssl.c>
|
|
||||||
<VirtualHost *:443>
|
|
||||||
ServerName overlay.example.com
|
|
||||||
ServerAlias heystreamer.example.com stats.example.com
|
|
||||||
|
|
||||||
ProxyPreserveHost On
|
|
||||||
|
|
||||||
# Tell Express it's behind HTTPS so secure session cookies work
|
|
||||||
RequestHeader set X-Forwarded-Proto "https"
|
|
||||||
|
|
||||||
Header always unset Content-Security-Policy
|
|
||||||
Header always set Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' https: wss: data:;"
|
|
||||||
|
|
||||||
# WebSocket must be listed before the catch-all
|
|
||||||
ProxyPass /ws/overlay ws://127.0.0.1:3000/ws/overlay
|
|
||||||
ProxyPassReverse /ws/overlay ws://127.0.0.1:3000/ws/overlay
|
|
||||||
|
|
||||||
ProxyPass / http://127.0.0.1:3000/
|
|
||||||
ProxyPassReverse / http://127.0.0.1:3000/
|
|
||||||
|
|
||||||
ErrorLog ${APACHE_LOG_DIR}/example.com/overlay.error.log
|
|
||||||
CustomLog ${APACHE_LOG_DIR}/example.com/overlay.access.log combined
|
|
||||||
|
|
||||||
Include /etc/letsencrypt/options-ssl-apache.conf
|
|
||||||
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
|
|
||||||
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
|
|
||||||
</VirtualHost>
|
|
||||||
</IfModule>
|
|
||||||
EOF
|
|
||||||
|
|
||||||
echo "==> Enabling required modules..."
|
|
||||||
sudo a2enmod proxy proxy_http proxy_wstunnel headers rewrite
|
|
||||||
|
|
||||||
echo "==> Enabling site..."
|
|
||||||
sudo a2ensite overlay.example.conf
|
|
||||||
|
|
||||||
echo "==> Testing config..."
|
|
||||||
sudo apachectl configtest
|
|
||||||
|
|
||||||
echo "==> Reloading Apache..."
|
|
||||||
sudo systemctl reload apache2
|
|
||||||
|
|
||||||
echo "Done. Try logging in at https://overlay.example.com"
|
|
||||||
106
docs/PLANS.md
106
docs/PLANS.md
|
|
@ -1,106 +0,0 @@
|
||||||
# HeyStreamer plans
|
|
||||||
|
|
||||||
Ideas agreed on but not built yet. Newest first. (Started 2026-11-22.)
|
|
||||||
|
|
||||||
## 4. Point system (draft, 2026-11-22)
|
|
||||||
|
|
||||||
Loyalty points calculated from the per-viewer statistics (src/chatlog.js), so values can change later and
|
|
||||||
everyone's points recalculate. Name to be decided (e.g. "<channel> points").
|
|
||||||
|
|
||||||
| Action | Points | Notes |
|
|
||||||
|---|---|---|
|
|
||||||
| Chat message | 10 | max 1 per 5 min per viewer (counted at ingestion: chat_user.scored / chat_user_day.scored) |
|
|
||||||
| First message in a stream (check-in) | 25 | once per stream (stream_checkin, built with watch time) |
|
|
||||||
| First message ever on the channel | 50 | Twitch's first-time chatter flag, kept in chat_user.intro |
|
|
||||||
| Follow | 50 | once |
|
|
||||||
| Watch streak | 5 x streak | max 100 |
|
|
||||||
| Channel point redeem | 1 per 100 points spent | |
|
|
||||||
| Cheer / Power-up / Custom Power-up | 1 per bit | |
|
|
||||||
| Sub Tier 1 / Prime | 500 per month | resubs: their months |
|
|
||||||
| Sub Tier 2 / Tier 3 | 1000 / 2500 per month | |
|
|
||||||
| Gift sub | as a sub, per gifted sub | to the gifter |
|
|
||||||
| Tip | 100 per 1 EUR | |
|
|
||||||
| Incoming raid | 100 flat | no reward for raid size |
|
|
||||||
| Emotes, commands | 0 | stats only, no farming |
|
|
||||||
| Watch time | 5 per 5 min live (one tick updates watch time and points together; built: src/watchtime.js) | needs moderator:read:chatters (chatter list); import StreamElements' watch time once (SE key already in .env) so viewers keep their history when our bot takes over `!watchtime` |
|
|
||||||
|
|
||||||
Levels by watch time (ours + StreamElements import), decided: Viewer, Regular (50 h), Loyal (200 h), Veteran (1000 h).
|
|
||||||
Points only rank the leaderboard; bits/subs do not buy a level.
|
|
||||||
Balance: lurker 60/h, active chatter up to 180/h; Tier 1 sub (500) ~ 8 h watching.
|
|
||||||
Uses: `!points`, on-stream leaderboard, level next to names in the overlay chat, spending on free Power-up uses (1).
|
|
||||||
Rule: points earned from bits must never be exchanged for things with money value (Bits Acceptable Use Policy).
|
|
||||||
Activity log stays (decided: records of support, like Twitch keeps); forget-a-viewer removes theirs.
|
|
||||||
|
|
||||||
## 1. Free uses of Custom Power-ups ("refund")
|
|
||||||
|
|
||||||
**Why:** when a viewer paid for a Power-up but it did not show (overlay was off, OBS crashed, server down),
|
|
||||||
give them one free use to trigger it again.
|
|
||||||
|
|
||||||
**How it would work**
|
|
||||||
- Granting: on the **Redeems page**, a small "Give a free use" control (viewer name + Power-up + count) next to
|
|
||||||
the page's reload/save controls. Later maybe also a mod chat command (`!giveuse @viewer jumpscare`).
|
|
||||||
- Using: the viewer types the Power-up's command, made from its name (`Jump Scare` → `!jumpscare`, renameable).
|
|
||||||
With a free use left it plays like a bits Power-up (random variation, video + box), the box says
|
|
||||||
**free use** instead of the bits amount. Without one: nothing happens.
|
|
||||||
- Storage: table `power_up_credits (user_id, user_login, power_up_id, uses, granted_by, granted_at)`.
|
|
||||||
- Recent activity logs grants and uses (with Replay).
|
|
||||||
|
|
||||||
**Needs:** chat read on the server (see 3), credits table, Redeems UI, command handling.
|
|
||||||
Estimate: about half a day once chat is read server-side.
|
|
||||||
|
|
||||||
## 2. Own chat bot in HeyStreamer (instead of StreamElements' bot)
|
|
||||||
|
|
||||||
**Why:** one place for alerts, redeems, commands and replies; no third-party bot.
|
|
||||||
|
|
||||||
**Rough shape**
|
|
||||||
- Bot account: the channel's own bot account logs in to HeyStreamer once (Twitch scopes `user:read:chat`, `user:write:chat`;
|
|
||||||
the bot also needs to be a mod/VIP in the channel for reliable sending).
|
|
||||||
- Reads chat via EventSub `channel.chat.message`, sends via Helix `POST /chat/messages`.
|
|
||||||
- Commands page: custom text commands (`!discord`, `!socials`, …) with cooldowns and permission levels
|
|
||||||
(everyone / sub / VIP / mod), variables like `{user}`, `{uptime}`, `{count}`.
|
|
||||||
- Timers (repeating messages while live), shoutouts, free-use replies (see 1).
|
|
||||||
- Move StreamElements' commands over, then turn its bot off. StreamElements stays for tips until replaced.
|
|
||||||
|
|
||||||
## 3. Chat log for statistics
|
|
||||||
|
|
||||||
**Why:** advanced statistics later (activity over time, regulars, first-time chatters, emote use, peak moments).
|
|
||||||
|
|
||||||
**Rules (GDPR, Twitch developer rules)**
|
|
||||||
- Log on the server via EventSub `channel.chat.message` (works without OBS, no duplicates).
|
|
||||||
- Store only: message id, time, user id + login + display name, text, badges, emotes, first-message / reply flags.
|
|
||||||
- Honour moderation: `channel.chat.message_delete`, `channel.chat.clear_user_messages` (timeouts/bans) and
|
|
||||||
`channel.chat.clear` remove or blank the stored messages.
|
|
||||||
- Retention: raw messages 30 days (then deleted), aggregated statistics kept.
|
|
||||||
- "Delete this user's messages" control for removal requests; a line in the Twitch panels that chat is logged
|
|
||||||
for stream statistics.
|
|
||||||
- Size: a few MB per month in SQLite.
|
|
||||||
|
|
||||||
Status: **logging built 2026-11-22** (src/chatlog.js), with these choices: per-viewer counts (messages, per day,
|
|
||||||
emotes incl. 7TV, !commands, first/last seen) parsed as messages arrive; raw messages kept **30 days** only;
|
|
||||||
moderation removes stored text; hidden chatters (bots) are counted but must be left out of shown
|
|
||||||
statistics and leaderboards (filter at display time with chatlog.isHidden()). Viewer actions are counted too
|
|
||||||
(chat_action: rewards + points, Power-ups + bits, cheers, subs, gifts, follows, raids, watch streaks, tips). Still to do: a statistics page, and a
|
|
||||||
"forget this viewer" button for removal requests (`chatlog.forgetUser()` exists).
|
|
||||||
|
|
||||||
**2026-11-23: per-stream and period statistics + public page.** `src/periodstats.js` keeps one generic table,
|
|
||||||
`stat_day` (day x stream x viewer x kind x item), fed by chatlog.js (messages, first messages, emotes, commands,
|
|
||||||
actions) and watchtime.js (watch ticks); backfilled once from the older tables. A new statistic = a new `kind`,
|
|
||||||
then a section in `views/_statsbody.ejs` (shared by the admin Stats page and the public page). Streams keep title,
|
|
||||||
game, peak + average viewers. Public page: Settings → Public stats page (its own host name; on that
|
|
||||||
host nothing else answers; `/public` on the admin host is a preview). It never shows message text, bots, the
|
|
||||||
streamer on leaderboards, or viewers who typed `!hideme` (`!showme` undoes it; also a button on the viewer page).
|
|
||||||
The StreamElements watch-time importer is removed; the minutes imported on 2026-11-22 stay as a fixed baseline
|
|
||||||
(watch_import: All time, points, levels).
|
|
||||||
|
|
||||||
**2026-11-23 (2): data from Twitch** (`src/twitchsync.js`, every 6 h, after each stream, "Sync with Twitch" button):
|
|
||||||
followers with follow dates (whole history), current subs, mods (`moderation:read`), VIPs (`channel:read:vips`; both
|
|
||||||
scopes need one new login), all-time bits top 100, the channel's emotes, past streams from VODs (7/60 days only).
|
|
||||||
Per stream: viewer count every 5 min (`stream_viewers`) and every title/category change (`stream_change`, EventSub
|
|
||||||
`channel.update`). Not on Twitch's API at all: past viewer counts, past titles, emote use outside this channel.
|
|
||||||
The old /actions page (event → sound rules, unused) is gone; "Actions" is now the nav group Redeems / TTS / Media.
|
|
||||||
|
|
||||||
**2026-11-23 (3): Twitch analytics CSV** (`src/twitchcsv.js`, Stats → "Import Twitch analytics (CSV)"): the Creator
|
|
||||||
Dashboard export "Analytics and Revenue by day". No API offers this: export by hand now and then and import again (per day, safe).
|
|
||||||
Before the cutoff (first day HeyStreamer counted) it supplies messages, watch time, follows, streamed days/hours;
|
|
||||||
for every day it supplies what only Twitch measures (unique / engaged viewers, clips, live views, average + peak
|
|
||||||
viewers, revenue). Revenue: admin page only, never public.
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 260"><path d="M150 236C70 180 22 136 22 84c0-34 26-60 60-60 28 0 50 16 68 40 18-24 40-40 68-40 34 0 60 26 60 60 0 52-48 96-128 152z" fill="#f4a0a8" stroke="#fffdf7" stroke-width="10"/><text x="150" y="122" text-anchor="middle" font-family="sans-serif" font-size="26" font-weight="700" fill="#fffdf7">your art</text><text x="150" y="152" text-anchor="middle" font-family="sans-serif" font-size="16" fill="#fffdf7">public/alerts/art</text></svg>
|
|
||||||
|
Before Width: | Height: | Size: 501 B |
|
|
@ -1,23 +0,0 @@
|
||||||
/* Card alerts (card.js): the plain style every channel gets. Colours come from Actions → Alerts (theme.card). */
|
|
||||||
#card-alert { position:fixed; left:60px; top:60px; width:600px; visibility:hidden; z-index:50; font-family:'Nunito', system-ui, sans-serif;
|
|
||||||
--accent:#9146ff; --bg:#ffffff; --fg:#1f1f23; }
|
|
||||||
#card-alert .card { position:relative; display:flex; gap:18px; align-items:center; background:var(--bg); color:var(--fg);
|
|
||||||
border-radius:20px; padding:16px 24px 18px 16px; box-shadow:0 14px 34px rgba(0,0,0,.35); overflow:hidden; }
|
|
||||||
#card-alert .card::before { content:''; position:absolute; left:0; top:0; bottom:0; width:8px; background:var(--accent); }
|
|
||||||
#card-alert .pic { width:104px; height:104px; flex:none; border-radius:16px; margin-left:6px; display:grid; place-items:center; overflow:hidden;
|
|
||||||
background:color-mix(in srgb, var(--accent) 16%, var(--bg)); }
|
|
||||||
#card-alert .pic img { width:100%; height:100%; object-fit:contain; }
|
|
||||||
#card-alert .pic .ini { font:900 50px/1 'Nunito', sans-serif; color:var(--accent); }
|
|
||||||
#card-alert .txt { min-width:0; flex:1; }
|
|
||||||
#card-alert .tag { font:800 14px/1.2 'Nunito', sans-serif; text-transform:uppercase; letter-spacing:.08em; color:var(--accent); opacity:.9; margin-bottom:2px;
|
|
||||||
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
|
||||||
#card-alert .name { font:900 32px/1.1 'Nunito', sans-serif; color:var(--accent); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
|
||||||
#card-alert .line { font:800 23px/1.2 'Nunito', sans-serif; margin-top:2px; }
|
|
||||||
#card-alert .msg { font:800 19px/1.3 'Nunito', sans-serif; opacity:.72; margin-top:6px; overflow:hidden; display:-webkit-box; -webkit-line-clamp:4; -webkit-box-orient:vertical; }
|
|
||||||
#card-alert .msg .w { opacity:.25; transition:opacity .15s; }
|
|
||||||
#card-alert .msg .w.on { opacity:1; }
|
|
||||||
#card-alert .badge { position:absolute; right:16px; top:14px; background:var(--badge, var(--accent)); color:#fff; border-radius:99px;
|
|
||||||
padding:3px 13px; font:900 20px/1.3 'Nunito', sans-serif; box-shadow:0 3px 8px rgba(0,0,0,.2); }
|
|
||||||
#card-alert .badge small { font-size:13px; margin-left:4px; opacity:.9; }
|
|
||||||
#card-alert .card.has-badge .txt { padding-right:90px; }
|
|
||||||
#card-alert .bar { position:absolute; left:0; right:0; bottom:0; height:5px; background:var(--accent); opacity:.55; transform-origin:left center; }
|
|
||||||
|
|
@ -1,78 +0,0 @@
|
||||||
/*
|
|
||||||
Card alerts: the plain style (Actions → Alerts: style "Card"). Used for events (follow, sub, gift, raid, bits, tip,
|
|
||||||
Hype Train) and for redeem variations / read-aloud redeems set to Card. Called by polaroid.js (shared queue):
|
|
||||||
window.CardAlert.show(d, cur, { url, len, volume }) -> Promise (resolves when it has left)
|
|
||||||
d: { art|sticker|emote (picture URL), name, line, msg, badge {big, small, color}, tag (small label above the name),
|
|
||||||
tts (voice URL instead of the sound), ttsEnv (loudness for word timing) }
|
|
||||||
cur: { anims, timer, audio } from polaroid.js, so reset / skip can stop it.
|
|
||||||
Timeline: slides in (0.6 s), sound starts, stays until the sound / voice ends (at least 4 s), slides out.
|
|
||||||
*/
|
|
||||||
(function () {
|
|
||||||
const MIN_SHOW = 4000, SOUND_LEAD = 350, ENV_STEP = 0.04;
|
|
||||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c]));
|
|
||||||
let el = null;
|
|
||||||
function root() {
|
|
||||||
if (!el) { el = document.createElement('div'); el.id = 'card-alert'; document.body.appendChild(el); }
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
const theme = () => (window.S && window.S.alert_theme) || {};
|
|
||||||
|
|
||||||
function show(d, cur, { url, len, volume }) {
|
|
||||||
const el = root(), c = theme().card || {};
|
|
||||||
if (c.accent) el.style.setProperty('--accent', c.accent);
|
|
||||||
if (c.bg) el.style.setProperty('--bg', c.bg);
|
|
||||||
if (c.text) el.style.setProperty('--fg', c.text);
|
|
||||||
const pic = d.emote || d.sticker || d.art || '';
|
|
||||||
const name = d.name || 'Someone';
|
|
||||||
const words = d.tts && d.msg ? String(d.msg).split(/\s+/).filter(Boolean) : null;
|
|
||||||
el.innerHTML = `<div class="card${d.badge ? ' has-badge' : ''}">
|
|
||||||
<div class="pic">${pic ? `<img src="${esc(pic)}" alt="">` : `<span class="ini">${esc(name.trim()[0] || '♥').toUpperCase()}</span>`}</div>
|
|
||||||
<div class="txt">
|
|
||||||
${d.tag ? `<div class="tag">${esc(d.tag)}</div>` : ''}
|
|
||||||
<div class="name">${esc(name)}</div>
|
|
||||||
<div class="line">${esc(d.line || '')}</div>
|
|
||||||
${d.msg ? `<div class="msg">${words ? words.map(w => `<span class="w">${esc(w)}</span>`).join(' ') : `“${esc(d.msg)}”`}</div>` : ''}
|
|
||||||
</div>
|
|
||||||
${d.badge ? `<div class="badge"${d.badge.color ? ` style="--badge:${esc(d.badge.color)}"` : ''}>${esc(d.badge.big)}<small>${esc(d.badge.small || '')}</small></div>` : ''}
|
|
||||||
<div class="bar"></div>
|
|
||||||
</div>`;
|
|
||||||
el.style.visibility = 'visible';
|
|
||||||
const card = el.querySelector('.card');
|
|
||||||
const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; };
|
|
||||||
|
|
||||||
A(card, [
|
|
||||||
{ transform:'translateX(-700px)', opacity:0 },
|
|
||||||
{ transform:'translateX(14px)', opacity:1, offset:.75 },
|
|
||||||
{ transform:'translateX(0)', opacity:1 },
|
|
||||||
], { duration:600, easing:'cubic-bezier(.2,.8,.3,1)' });
|
|
||||||
A(el.querySelector('.pic'), [{ transform:'scale(.6) rotate(-8deg)' }, { transform:'scale(1.08) rotate(3deg)', offset:.6 }, { transform:'scale(1) rotate(0)' }],
|
|
||||||
{ delay:350, duration:450, easing:'ease-out' });
|
|
||||||
|
|
||||||
// the voice (read-aloud redeems) or the sound
|
|
||||||
const voice = d.tts || null;
|
|
||||||
const playUrl = voice || url;
|
|
||||||
const playLen = voice ? (d.ttsMs || 0) : len;
|
|
||||||
if (playUrl) {
|
|
||||||
const a = new Audio(playUrl); a.volume = volume;
|
|
||||||
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD);
|
|
||||||
// words light up roughly as they are spoken
|
|
||||||
if (words) {
|
|
||||||
const spans = [...el.querySelectorAll('.msg .w')];
|
|
||||||
const total = Math.max(playLen, 1000), step = total / Math.max(spans.length, 1);
|
|
||||||
spans.forEach((s, i) => setTimeout(() => s.classList.add('on'), SOUND_LEAD + i * step));
|
|
||||||
}
|
|
||||||
} else if (words) el.querySelectorAll('.msg .w').forEach(s => s.classList.add('on'));
|
|
||||||
|
|
||||||
const stay = Math.max(MIN_SHOW, playUrl ? SOUND_LEAD + playLen + 600 : 0);
|
|
||||||
A(el.querySelector('.bar'), [{ transform:'scaleX(1)' }, { transform:'scaleX(0)' }], { delay:600, duration:Math.max(stay - 600, 500), easing:'linear' });
|
|
||||||
const exit = A(card, [
|
|
||||||
{ transform:'translateX(0)', opacity:1 },
|
|
||||||
{ transform:'translateX(18px)', opacity:1, offset:.25 },
|
|
||||||
{ transform:'translateX(-720px)', opacity:0 },
|
|
||||||
], { delay:stay, duration:550, easing:'cubic-bezier(.5,0,.8,.4)' });
|
|
||||||
return exit.finished.then(() => { el.style.visibility = 'hidden'; cur.anims.forEach(a => a.cancel()); }).catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
function hide() { if (el) el.style.visibility = 'hidden'; }
|
|
||||||
window.CardAlert = { show, hide };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,45 +0,0 @@
|
||||||
/* Cassette tape alert for redeems (see cassette.js). Same corner as the polaroid; they share one queue. */
|
|
||||||
#cassette-alert { --ink:#3a2a20; --red:#b74347; position:fixed; left:85px; top:110px; width:440px; visibility:hidden; z-index:50; }
|
|
||||||
#cassette-alert * { box-sizing:border-box; }
|
|
||||||
|
|
||||||
#cassette-alert.r-common { --shell:#f3ead9; --shell2:#e6dac3; --edge:#8a7558; --band:#f4a0a8; --bandtxt:#7a2f3a; }
|
|
||||||
#cassette-alert.r-uncommon { --shell:#cdeedd; --shell2:#b5e2cb; --edge:#4f8a6b; --band:#7fcfa6; --bandtxt:#1f5a3c; }
|
|
||||||
#cassette-alert.r-rare { --shell:#ddd0f4; --shell2:#cbb9ee; --edge:#6b54a8; --band:#a88be0; --bandtxt:#ffffff; }
|
|
||||||
#cassette-alert.r-ultra { --shell:#f6d77a; --shell2:#eec456; --edge:#9a6a10; --band:#3c2006; --bandtxt:#f6d77a; }
|
|
||||||
|
|
||||||
#cassette-alert .tape-wrap { position:relative; width:440px; height:282px; filter:drop-shadow(0 14px 22px rgba(0,0,0,.45)); }
|
|
||||||
#cassette-alert.r-ultra .tape-wrap { filter:drop-shadow(0 0 16px #ffd76a) drop-shadow(0 0 4px #fff2c0) drop-shadow(0 14px 22px rgba(0,0,0,.45)); }
|
|
||||||
#cassette-alert svg { position:absolute; inset:0; width:100%; height:100%; overflow:visible; }
|
|
||||||
#cassette-alert .reel-hub, #cassette-alert .wound { transform-box:fill-box; transform-origin:center; }
|
|
||||||
|
|
||||||
#cassette-alert .band { position:absolute; left:34px; right:34px; top:24px; height:32px; display:flex; align-items:center;
|
|
||||||
justify-content:space-between; padding:0 14px; font:900 15px 'Nunito', sans-serif; letter-spacing:2px; color:var(--bandtxt); }
|
|
||||||
#cassette-alert .title { position:absolute; left:40px; right:40px; top:58px; text-align:center; font:700 40px/1 'Caveat', cursive;
|
|
||||||
color:var(--ink); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
|
||||||
#cassette-alert .sub { position:absolute; left:40px; right:40px; top:156px; text-align:center; font:700 22px/1 'Caveat', cursive;
|
|
||||||
color:#7a6656; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
|
||||||
|
|
||||||
/* per-redeem sticker, bottom-right corner; any shape fits inside 150x125 */
|
|
||||||
#cassette-alert .stk { position:absolute; right:-50px; top:150px; width:175px; height:150px; display:flex; align-items:center; justify-content:center; }
|
|
||||||
#cassette-alert .stk img { max-width:175px; max-height:150px; transform:rotate(10deg);
|
|
||||||
filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 5px 8px rgba(0,0,0,.35)); }
|
|
||||||
|
|
||||||
#cassette-alert .foil { position:absolute; inset:0; border-radius:20px; pointer-events:none; opacity:0;
|
|
||||||
background:linear-gradient(115deg,#0000 35%,#fff9 48%,#fff3 52%,#0000 62%); mix-blend-mode:screen; }
|
|
||||||
#cassette-alert .spark { position:absolute; width:44px; height:44px; opacity:0; pointer-events:none; background:#fffbe6;
|
|
||||||
clip-path:polygon(50% 0,60% 40%,100% 50%,60% 60%,50% 100%,40% 60%,0 50%,40% 40%); filter:drop-shadow(0 0 6px #fff4b0); }
|
|
||||||
|
|
||||||
#cassette-alert .strip { position:relative; margin:-6px 0 0 30px; display:inline-block; max-width:400px; padding:8px 22px 10px;
|
|
||||||
background:#fffdf7; transform:rotate(-2deg); box-shadow:0 6px 14px rgba(0,0,0,.35); font:700 30px/1.05 'Caveat', cursive; color:var(--ink); }
|
|
||||||
#cassette-alert .strip .u { color:var(--red); }
|
|
||||||
#cassette-alert .strip .msg { display:block; font-size:22px; color:#7a6656; margin-top:4px;
|
|
||||||
overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
|
|
||||||
#cassette-alert .strip:before, #cassette-alert .strip:after { content:''; position:absolute; top:-10px; width:70px; height:24px;
|
|
||||||
background:rgba(201,182,228,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 7px,#0000 7px 14px); }
|
|
||||||
#cassette-alert .strip:before { left:-22px; transform:rotate(-28deg); }
|
|
||||||
#cassette-alert .strip:after { right:-22px; transform:rotate(24deg); }
|
|
||||||
|
|
||||||
/* the reward's / Power-up's Twitch icon as a small sticker on the top-left corner (only when Twitch has one) */
|
|
||||||
#cassette-alert .ico { position:absolute; left:-30px; top:-28px; width:76px; height:76px; display:flex; align-items:center; justify-content:center; z-index:2; }
|
|
||||||
#cassette-alert .ico img { max-width:76px; max-height:76px;
|
|
||||||
filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 5px 8px rgba(0,0,0,.35)); }
|
|
||||||
|
|
@ -1,130 +0,0 @@
|
||||||
/*
|
|
||||||
Cassette tape renderer for redeem alerts. Called by polaroid.js (shared queue):
|
|
||||||
window.CassetteAlert.show(d, cur, { url, len, volume }) -> Promise (resolves when ejected)
|
|
||||||
d: { title (variation), sub (reward), rarity, sticker (URL), name (user), line (strip text), msg (viewer input) }
|
|
||||||
cur: { anims, timer, audio } from polaroid.js, so reset/skip can stop it.
|
|
||||||
Timeline: slides in (0.7 s), sticker + strip pop on, reels spin and tape winds over the sound's length,
|
|
||||||
stays animation + 3 s or until the sound ends, then ejects upward.
|
|
||||||
*/
|
|
||||||
(function () {
|
|
||||||
const AFTER_ANIM = 3000, SOUND_LEAD = 600, ANIM_END = 1200;
|
|
||||||
// sticker when a variation has none: Actions → Alerts → Default redeem sticker (else a plain shape)
|
|
||||||
const defaultSticker = () => (window.S && window.S.alert_theme && window.S.alert_theme.defaultSticker) || (window.ALERTS_BASE || '/alerts/') + 'art/placeholder.svg';
|
|
||||||
const RAR = { common:['r-common','COMMON'], uncommon:['r-uncommon','UNCOMMON'], rare:['r-rare','★ RARE'], ultra_rare:['r-ultra','★ ULTRA RARE ★'] };
|
|
||||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c]));
|
|
||||||
const between = (a, b) => a + Math.random() * (b - a);
|
|
||||||
|
|
||||||
let el = null;
|
|
||||||
function root() {
|
|
||||||
if (!el) { el = document.createElement('div'); el.id = 'cassette-alert'; document.body.appendChild(el); }
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
|
|
||||||
function reel(cx, id) {
|
|
||||||
const teeth = Array.from({ length: 6 }, (_, i) =>
|
|
||||||
`<rect x="${cx - 3}" y="109" width="6" height="8" rx="1.5" fill="#cfc6bb" transform="rotate(${i * 60} ${cx} 126)"/>`).join('');
|
|
||||||
return `<circle class="wound" data-id="${id}-tape" cx="${cx}" cy="126" r="44" fill="#4a3426"/>
|
|
||||||
<g class="reel-hub" data-id="${id}"><circle cx="${cx}" cy="126" r="19" fill="#fffdf7" stroke="#bdb3a6" stroke-width="2"/>${teeth}
|
|
||||||
<circle cx="${cx}" cy="126" r="5" fill="#bdb3a6"/></g>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function svg() {
|
|
||||||
const uid = 'c' + Math.random().toString(36).slice(2, 8);
|
|
||||||
return `<svg viewBox="0 0 440 282" xmlns="http://www.w3.org/2000/svg">
|
|
||||||
<defs><clipPath id="${uid}w"><rect x="112" y="98" width="216" height="56" rx="28"/></clipPath>
|
|
||||||
<pattern id="${uid}l" width="10" height="16" patternUnits="userSpaceOnUse"><rect y="15" width="10" height="1" fill="#0000001a"/></pattern></defs>
|
|
||||||
<rect x="3" y="3" width="434" height="276" rx="20" fill="var(--shell)" stroke="var(--edge)" stroke-width="3"/>
|
|
||||||
<rect x="14" y="14" width="412" height="200" rx="12" fill="none" stroke="var(--edge)" stroke-opacity=".25" stroke-width="2"/>
|
|
||||||
${[[22,22],[418,22],[22,260],[418,260]].map(([x, y]) => `<circle cx="${x}" cy="${y}" r="6" fill="var(--shell2)" stroke="var(--edge)" stroke-width="1.5"/><path d="M${x-3} ${y}h6M${x} ${y-3}v6" stroke="var(--edge)" stroke-width="1.4"/>`).join('')}
|
|
||||||
<rect x="30" y="22" width="380" height="166" rx="8" fill="#fffdf7"/>
|
|
||||||
<rect x="30" y="22" width="380" height="166" rx="8" fill="url(#${uid}l)"/>
|
|
||||||
<rect x="30" y="22" width="380" height="36" rx="8" fill="var(--band)"/><rect x="30" y="46" width="380" height="12" fill="var(--band)"/>
|
|
||||||
<rect x="108" y="94" width="224" height="64" rx="32" fill="#2b2230" stroke="var(--edge)" stroke-width="2"/>
|
|
||||||
<g clip-path="url(#${uid}w)"><rect x="112" y="98" width="216" height="56" fill="#3a2f40"/>
|
|
||||||
${reel(160, 'reelL')}${reel(280, 'reelR')}
|
|
||||||
<rect x="150" y="150" width="140" height="4" fill="#4a3426"/><rect x="112" y="98" width="216" height="20" fill="#ffffff10"/></g>
|
|
||||||
<path d="M96 279 L118 220 H322 L344 279 Z" fill="var(--shell2)" stroke="var(--edge)" stroke-width="2.5" stroke-linejoin="round"/>
|
|
||||||
${[148,180,260,292].map(x => `<circle cx="${x}" cy="252" r="7" fill="#2b2230"/>`).join('')}
|
|
||||||
<rect x="206" y="240" width="28" height="22" rx="4" fill="#2b2230"/>
|
|
||||||
</svg>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
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 = `
|
|
||||||
<div class="tape-wrap">${svg()}
|
|
||||||
<div class="band"><span>SIDE A</span><span>${label}</span></div>
|
|
||||||
<div class="title">${esc(d.title)}</div>
|
|
||||||
<div class="sub">${d.sub && d.sub !== d.title ? esc(d.sub) : ''}</div>
|
|
||||||
<div class="stk"><img src="${esc(d.sticker || defaultSticker())}" alt=""></div>
|
|
||||||
${d.icon ? `<div class="ico"><img src="${esc(d.icon)}" alt=""></div>` : ''}
|
|
||||||
${ultra ? '<div class="foil"></div>' + '<div class="spark"></div>'.repeat(6) : ''}
|
|
||||||
</div>
|
|
||||||
<div class="strip"><span class="u">${esc(d.name)}</span> ${esc(d.line)}${d.msg ? `<span class="msg">“${esc(d.msg)}”</span>` : ''}</div>`;
|
|
||||||
el.style.visibility = 'visible';
|
|
||||||
|
|
||||||
const q = s => el.querySelector(s);
|
|
||||||
const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; };
|
|
||||||
const tilt = between(-4, 4);
|
|
||||||
|
|
||||||
A(q('.tape-wrap'), [
|
|
||||||
{ transform:'translateX(-620px) rotate(-14deg)', opacity:0 },
|
|
||||||
{ transform:`translateX(18px) rotate(${tilt + 2}deg)`, opacity:1, offset:.72 },
|
|
||||||
{ transform:`translateX(-4px) rotate(${tilt - .6}deg)`, offset:.88 },
|
|
||||||
{ transform:`translateX(0) rotate(${tilt}deg)`, opacity:1 },
|
|
||||||
], { duration:700, easing:'cubic-bezier(.2,.8,.3,1)' });
|
|
||||||
if (q('.ico')) A(q('.ico'), [ // the reward's / Power-up's Twitch icon, top-left corner
|
|
||||||
{ transform:'rotate(10deg) scale(0)', opacity:0 },
|
|
||||||
{ transform:'rotate(-18deg) scale(1.2)', opacity:1, offset:.6 },
|
|
||||||
{ transform:'rotate(-10deg) scale(1)', opacity:1 },
|
|
||||||
], { delay:560, duration:360, easing:'ease-out' });
|
|
||||||
A(q('.stk'), [
|
|
||||||
{ transform:'rotate(-30deg) scale(0)', opacity:0 },
|
|
||||||
{ transform:'rotate(8deg) scale(1.2)', opacity:1, offset:.6 },
|
|
||||||
{ transform:'rotate(0deg) scale(1)', opacity:1 },
|
|
||||||
], { delay:650, duration:380, easing:'ease-out' });
|
|
||||||
A(q('.strip'), [
|
|
||||||
{ transform:'translateY(-20px) rotate(-6deg) scale(1.1)', opacity:0 },
|
|
||||||
{ transform:'translateY(0) rotate(-2deg) scale(1)', opacity:1 },
|
|
||||||
], { delay:850, duration:320, easing:'cubic-bezier(.3,.7,.4,1)' });
|
|
||||||
|
|
||||||
// reels spin and tape winds while the sound plays
|
|
||||||
const playMs = Math.max(len, 600);
|
|
||||||
const turns = Math.round(playMs / 1000 * 540);
|
|
||||||
['reelL', 'reelR'].forEach(id => A(q(`[data-id="${id}"]`), [{ transform:'rotate(0deg)' }, { transform:`rotate(${turns}deg)` }],
|
|
||||||
{ delay:SOUND_LEAD, duration:playMs, easing:'linear', fill:'none' }));
|
|
||||||
A(q('[data-id="reelL-tape"]'), [{ transform:'scale(1)' }, { transform:'scale(.55)' }], { delay:SOUND_LEAD, duration:playMs, easing:'linear' });
|
|
||||||
A(q('[data-id="reelR-tape"]'), [{ transform:'scale(.55)' }, { transform:'scale(1)' }], { delay:SOUND_LEAD, duration:playMs, easing:'linear' });
|
|
||||||
A(q('.tape-wrap'), [{ translate:'0 0' }, { translate:'0 -2px' }, { translate:'0 0' }],
|
|
||||||
{ delay:SOUND_LEAD, duration:420, iterations:Math.ceil(playMs / 420), easing:'ease-in-out', fill:'none', composite:'add' });
|
|
||||||
|
|
||||||
if (ultra) {
|
|
||||||
A(q('.foil'), [{ opacity:0 }, { opacity:1, offset:.2 }, { opacity:1, offset:.8 }, { opacity:0 }],
|
|
||||||
{ delay:700, duration:1400, iterations:3, easing:'ease-in-out', fill:'none' });
|
|
||||||
el.querySelectorAll('.spark').forEach((s, i) => {
|
|
||||||
s.style.left = `${between(10, 410)}px`; s.style.top = `${between(-10, 250)}px`;
|
|
||||||
A(s, [{ opacity:0, transform:'scale(0) rotate(0deg)' }, { opacity:1, transform:'scale(1) rotate(45deg)', offset:.5 }, { opacity:0, transform:'scale(0) rotate(90deg)' }],
|
|
||||||
{ delay:800 + i * 230, duration:900, iterations:4, fill:'none' });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url) {
|
|
||||||
const a = new Audio(url); a.volume = volume;
|
|
||||||
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD);
|
|
||||||
}
|
|
||||||
|
|
||||||
const exitAt = Math.max(ANIM_END + AFTER_ANIM, url ? SOUND_LEAD + len : 0);
|
|
||||||
const exit = A(el, [
|
|
||||||
{ transform:'translateY(0)', opacity:1 },
|
|
||||||
{ transform:'translateY(14px)', opacity:1, offset:.2 },
|
|
||||||
{ transform:'translateY(-420px) rotate(-8deg)', opacity:0 },
|
|
||||||
], { delay:exitAt, duration:600, easing:'cubic-bezier(.5,0,.8,.4)' });
|
|
||||||
return exit.finished.then(() => { el.style.visibility = 'hidden'; cur.anims.forEach(a => a.cancel()); }).catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
function hide() { if (el) el.style.visibility = 'hidden'; }
|
|
||||||
window.CassetteAlert = { show, hide };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,68 +0,0 @@
|
||||||
/* Special redeem visuals (see fx.js): giant emote, bouncing emote celebration, highlighted message. */
|
|
||||||
#fx-alert { --ink:#3a2a20; --red:#b74347; position:fixed; inset:0; pointer-events:none; visibility:hidden; z-index:55; }
|
|
||||||
#fx-alert * { box-sizing:border-box; }
|
|
||||||
|
|
||||||
/* name strip, same paper + tape look as the cassette */
|
|
||||||
#fx-alert .strip { position:absolute; display:inline-block; max-width:520px; padding:8px 22px 10px; background:#fffdf7;
|
|
||||||
box-shadow:0 6px 14px rgba(0,0,0,.35); font:700 30px/1.05 'Caveat', cursive; color:var(--ink); }
|
|
||||||
#fx-alert .strip .u { color:var(--red); }
|
|
||||||
#fx-alert .strip:before, #fx-alert .strip:after { content:''; position:absolute; top:-10px; width:70px; height:24px;
|
|
||||||
background:rgba(190,160,240,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 7px,#0000 7px 14px); }
|
|
||||||
#fx-alert .strip:before { left:-22px; transform:rotate(-28deg); }
|
|
||||||
#fx-alert .strip:after { right:-22px; transform:rotate(24deg); }
|
|
||||||
|
|
||||||
/* gigantify */
|
|
||||||
#fx-alert .giant { position:absolute; left:85px; top:70px; width:380px; height:380px; display:flex; align-items:center; justify-content:center; }
|
|
||||||
#fx-alert .giant img { width:100%; height:100%; object-fit:contain; filter:drop-shadow(0 12px 24px rgba(0,0,0,.5)); }
|
|
||||||
|
|
||||||
/* celebration */
|
|
||||||
#fx-alert .bounce { position:absolute; left:0; top:0; will-change:transform; filter:drop-shadow(0 6px 10px rgba(0,0,0,.4)); }
|
|
||||||
|
|
||||||
/* highlighted message / message effect: big taped paper note, tall rather than wide */
|
|
||||||
#fx-alert .note { position:absolute; left:90px; top:90px; width:440px; min-height:300px; padding:30px 32px 34px; background:#fffdf7;
|
|
||||||
box-shadow:0 14px 30px rgba(0,0,0,.45); transform-origin:50% 0;
|
|
||||||
background-image:repeating-linear-gradient(#0000 0 51px, #0000001a 51px 52px); background-position:0 79px; }
|
|
||||||
#fx-alert .note:before, #fx-alert .note:after { content:''; position:absolute; top:-14px; width:120px; height:34px;
|
|
||||||
background:rgba(190,160,240,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px);
|
|
||||||
box-shadow:0 1px 2px rgba(0,0,0,.15); }
|
|
||||||
#fx-alert .note:before { left:-34px; transform:rotate(-32deg); }
|
|
||||||
#fx-alert .note:after { right:-34px; transform:rotate(28deg); }
|
|
||||||
#fx-alert .note .who { font:700 34px/1.1 'Caveat', cursive; color:var(--ink); margin-bottom:10px; }
|
|
||||||
#fx-alert .note .who .u { color:var(--red); }
|
|
||||||
#fx-alert .note .text { font:700 46px/52px 'Caveat', cursive; color:var(--ink); word-wrap:break-word;
|
|
||||||
overflow:hidden; display:-webkit-box; -webkit-line-clamp:9; -webkit-box-orient:vertical; }
|
|
||||||
|
|
||||||
/* TTS redeems: envelope letter (fx.js envelope()). The flap opens, the letter rises all the way out (its peak may
|
|
||||||
leave the screen), then comes down in front of the envelope and ends ~80px from the top; words ink in as spoken.
|
|
||||||
Coordinates are bottom-up inside .envl (360x560); the letter's slot is clipped at the envelope's bottom edge. */
|
|
||||||
#fx-alert .envl { position:absolute; left:90px; top:-146px; width:360px; height:560px; }
|
|
||||||
#fx-alert .envl .env { position:absolute; left:0; bottom:0; width:360px; height:216px; z-index:3; background:#e9d3b0; border-radius:6px;
|
|
||||||
box-shadow:0 10px 20px rgba(0,0,0,.45); }
|
|
||||||
#fx-alert .envl .env:before { content:''; position:absolute; inset:0; border-radius:6px; z-index:3;
|
|
||||||
background:linear-gradient(32deg, #dcc39b 50%, transparent 50%) left/50% 100% no-repeat,
|
|
||||||
linear-gradient(-32deg, #dcc39b 50%, transparent 50%) right/50% 100% no-repeat; }
|
|
||||||
#fx-alert .envl .flap { position:absolute; left:0; bottom:216px; width:360px; height:122px; transform-origin:bottom; z-index:1;
|
|
||||||
background:#d8bd93; clip-path:polygon(0 100%, 50% 0, 100% 100%); animation:fx-flap .6s .35s ease-out both; }
|
|
||||||
@keyframes fx-flap { from { transform:rotateX(180deg); z-index:4; } }
|
|
||||||
#fx-alert .envl .slot { position:absolute; left:-40px; right:-40px; bottom:0; top:-400px; overflow:hidden; z-index:2; animation:fx-zswap 1.6s .8s both; }
|
|
||||||
@keyframes fx-zswap { 0%, 54% { z-index:2; } 55%, 100% { z-index:6; } }
|
|
||||||
#fx-alert .envl .letter { --fs:24px; --lh:30px; position:absolute; left:62px; bottom:30px; width:316px; min-height:290px; background:#fffdf7; padding:18px 22px 22px;
|
|
||||||
box-shadow:0 4px 12px rgba(0,0,0,.3); animation:fx-rise 1.6s .8s both;
|
|
||||||
background-image:repeating-linear-gradient(transparent 0 calc(var(--lh) - 1px), rgba(110,150,200,.3) calc(var(--lh) - 1px) var(--lh));
|
|
||||||
background-position:0 calc(22px + var(--lh) - 6px); }
|
|
||||||
/* longer messages: smaller handwriting, the ruled lines follow */
|
|
||||||
#fx-alert .envl .letter.long { --fs:20px; --lh:25px; }
|
|
||||||
#fx-alert .envl .letter.longer { --fs:17px; --lh:21px; width:340px; }
|
|
||||||
#fx-alert .envl .letter.huge { --fs:15px; --lh:18px; width:356px; }
|
|
||||||
@keyframes fx-rise {
|
|
||||||
0% { transform:translateY(110px); animation-timing-function:cubic-bezier(.3,.7,.4,1); }
|
|
||||||
45% { transform:translateY(-200px) rotate(-1deg); }
|
|
||||||
55% { transform:translateY(-200px) rotate(-1deg); animation-timing-function:cubic-bezier(.4,0,.3,1.2); }
|
|
||||||
100% { transform:translateY(-14px) rotate(-2deg); }
|
|
||||||
}
|
|
||||||
#fx-alert .envl .to { font:700 22px/1 Caveat, cursive; color:var(--red); margin-bottom:6px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
|
||||||
#fx-alert .envl .tx { font:700 var(--fs)/var(--lh) Caveat, cursive; color:var(--ink); word-wrap:break-word; }
|
|
||||||
#fx-alert .envl .w { opacity:.12; transition:opacity .25s; }
|
|
||||||
#fx-alert .envl .w.on { opacity:1; }
|
|
||||||
#fx-alert .envl .seal { position:absolute; left:157px; bottom:86px; width:46px; height:46px; z-index:5; border-radius:50%; background:#b74347;
|
|
||||||
box-shadow:inset 0 -3px 0 rgba(0,0,0,.2), 0 3px 6px rgba(0,0,0,.35); color:#ffd9d4; font:22px/46px sans-serif; text-align:center; }
|
|
||||||
|
|
@ -1,196 +0,0 @@
|
||||||
/*
|
|
||||||
Special redeem visuals, called by polaroid.js (shared queue). Each returns a Promise that resolves when done.
|
|
||||||
FxAlert.giant(d, cur, snd) Gigantify Power-up: the viewer's emote grows huge, pulses while the sound plays
|
|
||||||
FxAlert.rain(d, cur, snd) On-Screen Celebration Power-up: copies of the emote bounce around the screen
|
|
||||||
FxAlert.message(d, cur, snd) Highlight my message / Message Effect: big taped paper note with the message
|
|
||||||
FxAlert.envelope(d, cur, snd) TTS redeems: envelope opens, the letter rises out and settles in front, words ink in as
|
|
||||||
they are spoken (d.tts URL, d.ttsMs length, d.ttsEnv loudness per 40 ms, d.ttsPrefix
|
|
||||||
= words said before the message, e.g. "<name> says:")
|
|
||||||
d: { name (user), line, msg, emote (image URL or null) }; snd: { url, len, volume }
|
|
||||||
cur: { anims, timer, audio } so reset/skip can stop it (anything with cancel() can go in anims).
|
|
||||||
*/
|
|
||||||
(function () {
|
|
||||||
const AFTER_ANIM = 3000, SOUND_LEAD = 300;
|
|
||||||
// when Twitch sends no emote: the corner sticker from Actions → Alerts, else a plain shape
|
|
||||||
const fallback = () => window.FX_FALLBACK || (window.S && window.S.alert_theme && window.S.alert_theme.heart) || (window.ALERTS_BASE || '/alerts/') + 'art/placeholder.svg';
|
|
||||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c]));
|
|
||||||
const between = (a, b) => a + Math.random() * (b - a);
|
|
||||||
|
|
||||||
let el = null;
|
|
||||||
function root() {
|
|
||||||
if (!el) { el = document.createElement('div'); el.id = 'fx-alert'; document.body.appendChild(el); }
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
function hide() { if (el) { el.style.visibility = 'hidden'; el.innerHTML = ''; } }
|
|
||||||
|
|
||||||
function playSound(cur, { url, volume }) {
|
|
||||||
if (!url) return;
|
|
||||||
const a = new Audio(url); a.volume = volume;
|
|
||||||
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD);
|
|
||||||
}
|
|
||||||
const imgTag = (src, cls = '') => `<img class="${cls}" src="${esc(src || fallback())}" alt="" onerror="this.onerror=null;this.src='${fallback()}'">`;
|
|
||||||
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 = `<div class="giant">${imgTag(d.emote)}</div>
|
|
||||||
<div class="strip" style="left:110px; top:470px; transform:rotate(-2deg)"><span class="u">${esc(d.name)}</span> ${esc(d.line)}</div>`;
|
|
||||||
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('') +
|
|
||||||
`<div class="strip" style="left:110px; top:90px; transform:rotate(-2deg)"><span class="u">${esc(d.name)}</span> ${esc(d.line)}</div>`;
|
|
||||||
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 = `<div class="note"><div class="who"><span class="u">${esc(d.name)}</span> ${esc(d.line)}</div>
|
|
||||||
<div class="text">${esc(text)}</div></div>`;
|
|
||||||
el.style.visibility = 'visible';
|
|
||||||
const n = el.querySelector('.note');
|
|
||||||
A(cur, n, [
|
|
||||||
{ transform:`translateY(-140px) rotate(${tilt * -3}deg) scale(1.12)`, opacity:0 },
|
|
||||||
{ transform:`translateY(8px) rotate(${tilt + 1}deg) scale(.99)`, opacity:1, offset:.7 },
|
|
||||||
{ transform:`translateY(0) rotate(${tilt}deg) scale(1)`, opacity:1 },
|
|
||||||
], { duration:650, easing:'cubic-bezier(.2,.8,.3,1)' });
|
|
||||||
A(cur, n.querySelector('.text'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }],
|
|
||||||
{ delay:550, duration:Math.min(1600, 300 + 18 * text.length), easing:'ease-in-out' });
|
|
||||||
playSound(cur, snd);
|
|
||||||
const read = 2000 + 70 * text.length; // time to read it
|
|
||||||
let exitAt = Math.max(650 + AFTER_ANIM, 650 + read, SOUND_LEAD + snd.len);
|
|
||||||
if (d.tts) { // TTS: after the intro sound, keep the note up until it is said
|
|
||||||
const ttsAt = SOUND_LEAD + (snd.url ? snd.len + 250 : 300);
|
|
||||||
const a = new Audio(d.tts); a.volume = snd.volume;
|
|
||||||
const t = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] TTS blocked:', err.message)); }, ttsAt);
|
|
||||||
cur.anims.push({ cancel: () => { clearTimeout(t); a.pause(); } }); // skip/reset stop the voice too
|
|
||||||
exitAt = Math.max(exitAt, ttsAt + (d.ttsMs || 4000) + 900);
|
|
||||||
}
|
|
||||||
return done(cur, A(cur, el, [{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(140px) rotate(8deg)', opacity:0 }],
|
|
||||||
{ delay:exitAt, duration:500, easing:'ease-in' }));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- TTS redeems: envelope letter ----
|
|
||||||
const VOICE_AT = 1300; // ms: the voice starts while the letter comes back down
|
|
||||||
const ENV_STEP = 0.04; // s per loudness value (src/tts.js ENV_STEP_MS)
|
|
||||||
|
|
||||||
// when each shown word starts (s), spread over the voiced part of the clip, longer words and pauses after
|
|
||||||
// punctuation get more time. The first `prefix` spoken words ("<name> says:") are not on the letter.
|
|
||||||
function wordStarts(env, prefixWords, words) {
|
|
||||||
let s = 0, e = env.length - 1;
|
|
||||||
while (s < e && env[s] < .08) s++;
|
|
||||||
while (e > s && env[e] < .08) e--;
|
|
||||||
const all = [...prefixWords, ...words];
|
|
||||||
const weight = all.map(x => x.length + 2 + (/[.!?,:]$/.test(x) ? 5 : 0));
|
|
||||||
const total = weight.reduce((a, b) => a + b, 0) || 1;
|
|
||||||
let acc = 0;
|
|
||||||
const starts = all.map((_, i) => { const t = (s + (e - s + 1) * acc / total) * ENV_STEP; acc += weight[i]; return t; });
|
|
||||||
return starts.slice(prefixWords.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
function envelope(d, cur, snd) {
|
|
||||||
const el = root();
|
|
||||||
const text = d.msg || '';
|
|
||||||
const words = text.split(/\s+/).filter(Boolean);
|
|
||||||
el.innerHTML = `<div class="envl"><div class="flap"></div>
|
|
||||||
<div class="slot"><div class="letter ${text.length > 340 ? 'huge' : text.length > 230 ? 'longer' : text.length > 140 ? 'long' : ''}"><div class="to">from ${esc(d.name)} ♡</div>
|
|
||||||
<div class="tx">${words.map(w => `<span class="w">${esc(w)}</span>`).join(' ')}</div></div></div>
|
|
||||||
<div class="env"></div><div class="seal">♥</div></div>`;
|
|
||||||
el.style.visibility = 'visible';
|
|
||||||
const box = el.querySelector('.envl');
|
|
||||||
const spans = [...box.querySelectorAll('.w')];
|
|
||||||
A(cur, box, [{ transform:'translateY(-40px) scale(.92) rotate(-3deg)', opacity:0 }, { transform:'none', opacity:1 }],
|
|
||||||
{ duration:600, easing:'cubic-bezier(.2,1.25,.4,1)' });
|
|
||||||
|
|
||||||
let exitAt;
|
|
||||||
if (d.tts) {
|
|
||||||
const prefix = d.ttsPrefix ? [d.name, 'says:'].slice(0, d.ttsPrefix) : [];
|
|
||||||
const starts = d.ttsEnv && d.ttsEnv.length ? wordStarts(d.ttsEnv, prefix, words) : null;
|
|
||||||
const a = new Audio(d.tts); a.volume = snd.volume;
|
|
||||||
const t = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] TTS blocked:', err.message)); }, VOICE_AT);
|
|
||||||
let raf = 0, failed = false;
|
|
||||||
const fail = () => { failed = true; }; // voice missing/blocked: show the whole text anyway
|
|
||||||
a.addEventListener('error', fail, { once:true });
|
|
||||||
const t2 = setTimeout(() => { if (!a.currentTime) fail(); }, VOICE_AT + 1500);
|
|
||||||
const tick = () => { // ink in each word as it is said
|
|
||||||
const now = a.ended ? Infinity : a.currentTime + .05;
|
|
||||||
spans.forEach((w, i) => w.classList.toggle('on', failed || a.ended || (!a.paused || a.currentTime > 0) && (!starts || now >= starts[i])));
|
|
||||||
raf = requestAnimationFrame(tick);
|
|
||||||
};
|
|
||||||
raf = requestAnimationFrame(tick);
|
|
||||||
cur.anims.push({ cancel: () => { clearTimeout(t); clearTimeout(t2); cancelAnimationFrame(raf); a.pause(); } });
|
|
||||||
exitAt = VOICE_AT + (d.ttsMs || 4000) + 1400;
|
|
||||||
} else { // blocked or no voice: just show the letter
|
|
||||||
spans.forEach(w => w.classList.add('on'));
|
|
||||||
exitAt = 2400 + 2000 + 60 * text.length;
|
|
||||||
}
|
|
||||||
return done(cur, A(cur, box, [{ transform:'none', opacity:1 }, { transform:'translateY(40px) scale(.95) rotate(4deg)', opacity:0 }],
|
|
||||||
{ delay:exitAt, duration:500, easing:'ease-in' }));
|
|
||||||
}
|
|
||||||
|
|
||||||
window.FxAlert = { giant, rain, message, envelope, hide };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
/* 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); }
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
/*
|
|
||||||
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 = '<div class="top"><span class="name"></span><span class="time"></span></div><div class="track"><div class="fill"></div></div>'; }
|
|
||||||
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} · <span class="lv">ENDED AT LV ${t.level}</span> ♡`;
|
|
||||||
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} · <span class="lv">LV ${t.level}</span>`;
|
|
||||||
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 };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
/* "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; }
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
||||||
/*
|
|
||||||
"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 = `<div class="slip"><div class="cover"></div><div class="txt"><div class="t"></div><div class="a"></div></div></div>`;
|
|
||||||
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 };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
/* Polaroid alerts (see polaroid.js). Fonts: Caveat (loaded by overlay.ejs). */
|
|
||||||
#polaroid-alert { --red:#b74347; --ink:#3a2a20;
|
|
||||||
position:fixed; left:85px; top:90px; width:340px; visibility:hidden; z-index:50; }
|
|
||||||
|
|
||||||
#polaroid-alert .photo { position:absolute; left:0; top:0; width:340px; padding:18px 18px 0; background:#fffdf7;
|
|
||||||
box-shadow:0 14px 30px rgba(0,0,0,.45); transform-origin:50% 40%; box-sizing:content-box; }
|
|
||||||
#polaroid-alert .photo.main { position:relative; }
|
|
||||||
#polaroid-alert .ph { height:290px; background:var(--phbg, linear-gradient(#ffd9e0,#f8c3cf)); position:relative; overflow:hidden; }
|
|
||||||
#polaroid-alert .ph img { position:absolute; bottom:0; left:50%; transform:translateX(-50%); width:300px; display:block; }
|
|
||||||
#polaroid-alert .back .blank { height:70px; }
|
|
||||||
|
|
||||||
#polaroid-alert .cap { font:700 34px/1.05 'Caveat', cursive; color:var(--ink); text-align:center; padding:14px 34px 20px; }
|
|
||||||
#polaroid-alert .cap .u { color:var(--red); display:block; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
|
||||||
#polaroid-alert .cap .msg { font-size:24px; line-height:1.1; color:#7a6656; margin-top:6px;
|
|
||||||
overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
|
|
||||||
|
|
||||||
#polaroid-alert .tape { position:absolute; z-index:3; width:130px; height:36px; top:-16px; opacity:0;
|
|
||||||
background-color:var(--tape, rgba(201,182,228,.85));
|
|
||||||
background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px);
|
|
||||||
box-shadow:0 1px 2px rgba(0,0,0,.15); }
|
|
||||||
#polaroid-alert .t1 { left:-30px; }
|
|
||||||
#polaroid-alert .t2 { right:-30px; }
|
|
||||||
|
|
||||||
#polaroid-alert .sticker { filter:drop-shadow(4px 0 0 #fff) drop-shadow(-4px 0 0 #fff) drop-shadow(0 4px 0 #fff)
|
|
||||||
drop-shadow(0 -4px 0 #fff) drop-shadow(0 6px 10px rgba(0,0,0,.35)); }
|
|
||||||
#polaroid-alert .heart { position:absolute; z-index:4; right:-66px; bottom:-34px; width:104px; opacity:0; }
|
|
||||||
#polaroid-alert .heart.extra { width:70px; bottom:30px; }
|
|
||||||
|
|
||||||
#polaroid-alert .badge { position:absolute; z-index:5; right:-34px; top:40px; width:96px; height:96px; border-radius:50%;
|
|
||||||
background:var(--badge, #f6c75b); border:5px solid #fff; box-shadow:0 6px 10px rgba(0,0,0,.35); box-sizing:content-box;
|
|
||||||
display:flex; flex-direction:column; align-items:center; justify-content:center; opacity:0;
|
|
||||||
font:700 40px/0.9 'Caveat', cursive; color:#fff; text-shadow:0 2px 0 rgba(0,0,0,.25); }
|
|
||||||
#polaroid-alert .badge small { font-size:19px; line-height:1; }
|
|
||||||
|
|
||||||
/* variation name on a paper label (redeems) */
|
|
||||||
#polaroid-alert .tag { position:absolute; left:10px; bottom:10px; max-width:85%; padding:2px 12px; background:#fffdf7;
|
|
||||||
font:700 26px/1.2 'Caveat', cursive; color:var(--ink); transform:rotate(-3deg); box-shadow:0 2px 4px rgba(0,0,0,.25);
|
|
||||||
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; box-sizing:border-box; }
|
|
||||||
|
|
||||||
/* raid send-off: square Twitch avatar fills the photo instead of standing on the bottom edge */
|
|
||||||
#polaroid-alert .ph.avatar img { width:100%; height:100%; bottom:0; object-fit:cover; }
|
|
||||||
|
|
||||||
/* no picture set (Actions → Alerts): the first letter of the name, handwritten */
|
|
||||||
#polaroid-alert .ph .ini { position:absolute; inset:0; display:grid; place-items:center; font:700 170px/1 'Caveat', cursive; color:rgba(255,255,255,.9); text-shadow:0 4px 12px rgba(0,0,0,.12); }
|
|
||||||
|
|
@ -1,374 +0,0 @@
|
||||||
/*
|
|
||||||
Polaroid alerts for the OBS overlay.
|
|
||||||
|
|
||||||
window.PolaroidAlerts.play(alert) queue an alert (never overlaps)
|
|
||||||
window.PolaroidAlerts.playTest(alert) test alert: replaces a showing/queued TEST alert at once,
|
|
||||||
but never interrupts or drops a real one (it queues behind it).
|
|
||||||
A real alert cuts off a test that is showing.
|
|
||||||
window.PolaroidAlerts.reset() stop the current alert and clear the queue
|
|
||||||
window.PolaroidAlerts.skip() stop the current alert (e.g. a TTS message), carry on with the queue
|
|
||||||
|
|
||||||
Alert shapes come from src/alerts.js:
|
|
||||||
{ type:'follow', user }
|
|
||||||
{ type:'sub', user, tier, prime, months, duration, message }
|
|
||||||
{ type:'gift', user|null, total, recipient, tier }
|
|
||||||
{ type:'streak', user, streak }
|
|
||||||
{ type:'raid', user, viewers }
|
|
||||||
{ type:'bits', user|null, bits, message }
|
|
||||||
{ type:'tip', user, amount, currency, message } (StreamElements)
|
|
||||||
{ type:'hype', phase:'begin'|'level'|'end', level, golden, treasure, top } (Hype Train v2)
|
|
||||||
{ type:'redeem', kind, key, user, reward, variation, rarity, input, caption, sound (URL), volume, polaroid, art }
|
|
||||||
channel point rewards / Power-ups, configured on the dashboard Redeems page; drawn as a
|
|
||||||
cassette tape by cassette.js (polaroid:false = sound only, art = sticker URL)
|
|
||||||
Everything per event (art, caption, tape colour, badge, sound) is in describe() below.
|
|
||||||
*/
|
|
||||||
(function () {
|
|
||||||
// ===================== CONFIG =====================
|
|
||||||
const BASE = window.ALERTS_BASE || '/alerts/'; // ALERTS_BASE: only set by offline test pages
|
|
||||||
const rebase = u => (u && u.startsWith('/alerts/') && BASE !== '/alerts/') ? BASE + u.slice(8) : u;
|
|
||||||
// pictures and sounds are URLs from the Media library (Actions → Alerts); bare names = old files in public/alerts/art|sounds
|
|
||||||
const ART = n => !n ? '' : /^(https?:)?\/\//.test(n) ? n : n.startsWith('/') ? rebase(n) : `${BASE}art/${n}`;
|
|
||||||
const SND = n => `${BASE}sounds/${n}`;
|
|
||||||
const DEFAULT_VOLUME = 0.8;
|
|
||||||
|
|
||||||
const TAPE = {
|
|
||||||
follow:'rgba(201,182,228,.88)', sub:'rgba(244,160,168,.88)', prime:'rgba(140,200,240,.88)',
|
|
||||||
gift:'rgba(150,215,180,.88)', streak:'rgba(246,206,110,.9)', raid:'rgba(250,170,120,.88)',
|
|
||||||
bits:'rgba(190,160,240,.88)', redeem:'rgba(140,215,215,.88)',
|
|
||||||
};
|
|
||||||
|
|
||||||
// The channel's alert theme (src/theme.js, edited on Actions → Alerts) arrives with the overlay settings and is read
|
|
||||||
// per alert, so a save in the dashboard is used by the next alert without reloading OBS.
|
|
||||||
const TH = () => (window.S && window.S.alert_theme) || {};
|
|
||||||
const SOUND_MS = {}; // sound lengths are measured in the browser once (soundLength)
|
|
||||||
|
|
||||||
const RANGES = { photoTilt:[2,7], tape1:[-42,-18], tape2:[18,42], tapeX:[-12,12], tapeY:[-6,6],
|
|
||||||
heart:[-8,26], heartX:[-10,6], heartY:[-14,8], badge:[-18,14] };
|
|
||||||
const AFTER_ANIM = 3000; // ms the finished polaroid stays up after its entrance animation
|
|
||||||
const SOUND_LEAD = 400; // ms after the photo starts dropping that the sound starts
|
|
||||||
const GAP = 600; // ms between queued alerts
|
|
||||||
|
|
||||||
// Event -> what the polaroid shows. null = no alert.
|
|
||||||
function describe(e) {
|
|
||||||
const th = TH(), THA = th.art || {}, THS = th.sounds || {};
|
|
||||||
const BITS_MIN = th.bitsMin ?? 1, BITS_TIERS = th.bitsTiers || [];
|
|
||||||
const who = e.user || (e.type === 'gift' ? 'An anonymous gifter' : 'Someone');
|
|
||||||
switch (e.type) {
|
|
||||||
case 'follow':
|
|
||||||
return { art:THA.follow, name:who, line:'just followed! ♡', tape:TAPE.follow, sound:THS.follow };
|
|
||||||
case 'sub': {
|
|
||||||
const months = e.months || 1, dur = e.duration || 1, multi = dur > 1;
|
|
||||||
const tier = e.prime ? '' : ({ '2000':'Tier 2', '3000':'Tier 3' }[e.tier] || '');
|
|
||||||
const atTier = tier ? ` at ${tier}` : '';
|
|
||||||
let line;
|
|
||||||
if (multi) line = `subscribed${atTier} for ${dur} months at once! ♡`;
|
|
||||||
else if (e.prime) line = months > 1 ? `resubscribed with Prime for ${months} months! ♛` : 'subscribed with Prime! ♛';
|
|
||||||
else if (months > 1) line = `resubscribed${atTier} for ${months} months! ♡`;
|
|
||||||
else line = `just subscribed${atTier}! ♡`;
|
|
||||||
const art = e.prime ? THA.prime : (months > 1 || multi ? THA.resub : THA.sub);
|
|
||||||
return { art, name:who, line, msg:e.message, tape:e.prime ? TAPE.prime : TAPE.sub, sound:THS.sub,
|
|
||||||
stack: multi ? Math.min(dur - 1, 5) : 0,
|
|
||||||
badge: multi ? { big:`${dur}×`, small:'months' } : months > 1 ? { big:months, small:'months' } : null,
|
|
||||||
phbg: e.prime ? 'linear-gradient(#e3f2ff,#bcdcf5)' : null };
|
|
||||||
}
|
|
||||||
case 'gift': {
|
|
||||||
const n = e.total || 1;
|
|
||||||
return { art:THA.gift, name:who,
|
|
||||||
line: n > 1 ? `gifted ${n} subs to the community! ♡`
|
|
||||||
: (e.recipient ? `gifted a sub to ${e.recipient}! ♡` : 'gifted a sub! ♡'),
|
|
||||||
tape:TAPE.gift, sound:THS.gift, stack: n > 1 ? Math.min(n - 1, 3) : 0,
|
|
||||||
badge: n > 1 ? { big:`×${n}`, small:'subs' } : null, phbg:'linear-gradient(#e2f6ea,#bfe6cf)' };
|
|
||||||
}
|
|
||||||
case 'streak':
|
|
||||||
return { art:THA.streak, name:who, line:`is on a ${e.streak}-stream watch streak!`,
|
|
||||||
tape:TAPE.streak, sound:THS.streak, badge:{ big:e.streak, small:'streams' }, phbg:'linear-gradient(#fff4d6,#f7deb0)' };
|
|
||||||
case 'raid':
|
|
||||||
return { art:THA.raid, name:who, line:`is raiding with ${e.viewers} viewers!`,
|
|
||||||
tape:TAPE.raid, sound:THS.raid, badge:{ big:e.viewers, small:'raiders' },
|
|
||||||
phbg:'linear-gradient(#ffe6d6,#f8c8a8)', stack:2 };
|
|
||||||
case 'tip': {
|
|
||||||
// StreamElements tip: amount in its own currency, extra hearts for bigger tips
|
|
||||||
let money;
|
|
||||||
try { money = new Intl.NumberFormat('en', { style:'currency', currency:e.currency || 'USD', maximumFractionDigits: e.amount % 1 ? 2 : 0 }).format(e.amount); }
|
|
||||||
catch { money = `${e.amount} ${e.currency || ''}`.trim(); }
|
|
||||||
const hearts = e.amount >= 50 ? 3 : e.amount >= 25 ? 2 : e.amount >= 10 ? 1 : 0;
|
|
||||||
return { art:THA.tip, name:who, line:`tipped ${money}! ♡`, msg:e.message, sound:THS.tip,
|
|
||||||
tape:'rgba(246,206,110,.9)', badge:{ big:money, small:'tip', color:'#e0a21b' }, hearts,
|
|
||||||
phbg:'linear-gradient(#fff6dc,#fbe0a8)' };
|
|
||||||
}
|
|
||||||
case 'hype': {
|
|
||||||
// Hype Train: start / level up / end (art + sounds from the theme)
|
|
||||||
const name = e.golden ? 'Golden Kappa Train' : e.treasure ? 'Treasure Train' : 'Hype Train';
|
|
||||||
const line = e.phase === 'begin' ? 'is leaving the station! choo choo 🚂'
|
|
||||||
: e.phase === 'level' ? `reached level ${e.level}!` : `ended at level ${e.level}! ♡`;
|
|
||||||
const sound = { begin:THS.hypeBegin, level:THS.hypeLevel, end:THS.hypeEnd }[e.phase];
|
|
||||||
return { art:THA.hype, name, line, tape: e.golden ? 'rgba(246,206,110,.95)' : TAPE.raid, sound,
|
|
||||||
msg: e.phase === 'end' && e.top?.length ? `thank you ${e.top.join(', ')}!` : null,
|
|
||||||
badge:{ big:e.level, small:'level', color: e.golden ? '#d4a017' : '#e0457b' }, hearts: e.phase === 'end' ? 2 : 0,
|
|
||||||
stack: e.phase === 'end' ? 2 : 0, phbg: e.golden ? 'linear-gradient(#fff4d0,#f6d77a)' : 'linear-gradient(#ffe6d6,#f8c8a8)' };
|
|
||||||
}
|
|
||||||
case 'redeem': {
|
|
||||||
// shown as a cassette tape (cassette.js); polaroid:false = sound only
|
|
||||||
const fill = t => String(t || '').replace(/\{reward\}/g, e.reward || '').replace(/\{variation\}/g, e.variation || '');
|
|
||||||
return { cassette: true, style: e.style || 'cassette', emote: e.emote || null, sticker: rebase(e.art) || null, icon: e.icon || null,
|
|
||||||
name: e.user || 'Someone', line: fill(e.caption || 'redeemed it! ♡'), msg: e.input,
|
|
||||||
title: e.variation || e.reward, sub: e.reward, rarity: e.rarity,
|
|
||||||
sound: e.sound || null, volume: e.volume, soundOnly: e.polaroid === false && !e.tts,
|
|
||||||
tts: e.tts ? rebase(e.tts) : null, ttsMs: e.tts_ms || 0, ttsEnv: e.tts_env || [], ttsPrefix: e.tts_prefix || 0 };
|
|
||||||
}
|
|
||||||
case 'bits': {
|
|
||||||
if (!(e.bits >= BITS_MIN)) return null;
|
|
||||||
const t = BITS_TIERS.find(t => e.bits >= t.min) || BITS_TIERS[BITS_TIERS.length - 1] || { art:THA.follow, badge:'#8a8aa8', hearts:0 };
|
|
||||||
return { art:t.art, name:who, line:`cheered ${e.bits} bits!`, msg:e.message, tape:TAPE.bits, sound:t.sound,
|
|
||||||
badge:{ big:e.bits, small:'bits', color:t.badge }, hearts:t.hearts, volume:t.volume, phbg:'linear-gradient(#efe6ff,#d7c6f5)' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===================== ENGINE =====================
|
|
||||||
const rnd = Math.random;
|
|
||||||
const between = ([a, b]) => a + rnd() * (b - a);
|
|
||||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c]));
|
|
||||||
|
|
||||||
let el = null;
|
|
||||||
function root() {
|
|
||||||
if (!el) { el = document.createElement('div'); el.id = 'polaroid-alert'; document.body.appendChild(el); }
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
|
|
||||||
// preload images and sounds so the first alert of the stream is not blank or late
|
|
||||||
function preload() {
|
|
||||||
const th = TH();
|
|
||||||
const imgs = new Set([...(th.back || []), ...Object.values(th.art || {}), th.heart, ...(th.bitsTiers || []).map(t => t.art)].filter(Boolean));
|
|
||||||
imgs.forEach(n => { new Image().src = ART(n); });
|
|
||||||
Object.keys(SOUND_MS).forEach(n => { const a = new Audio(); a.preload = 'auto'; a.src = SND(n); });
|
|
||||||
}
|
|
||||||
|
|
||||||
// built-in sounds are file names, redeem sounds are URLs
|
|
||||||
const soundUrl = s => !s ? null : (s.startsWith('/') ? rebase(s) : SND(s));
|
|
||||||
const lengths = {};
|
|
||||||
// sound length in ms: known table, else measured once in the browser (max 3 s wait)
|
|
||||||
function soundLength(url) {
|
|
||||||
const base = decodeURIComponent(url.split('/').pop());
|
|
||||||
if (SOUND_MS[base]) return Promise.resolve(SOUND_MS[base]);
|
|
||||||
if (lengths[url] != null) return Promise.resolve(lengths[url]);
|
|
||||||
return new Promise(res => {
|
|
||||||
const a = new Audio(); a.preload = 'metadata';
|
|
||||||
const done = ms => { clearTimeout(t); res(lengths[url] = ms); };
|
|
||||||
const t = setTimeout(() => done(0), 3000);
|
|
||||||
a.addEventListener('loadedmetadata', () => done(isFinite(a.duration) ? a.duration * 1000 : 0), { once:true });
|
|
||||||
a.addEventListener('error', () => done(0), { once:true });
|
|
||||||
a.src = url;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const queue = [];
|
|
||||||
let busy = false, current = null, gen = 0;
|
|
||||||
|
|
||||||
function play(alert) {
|
|
||||||
const d = describe(alert);
|
|
||||||
if (!d) { console.log('[alerts] skipped', alert); return; }
|
|
||||||
d.test = !!alert.test;
|
|
||||||
if (!d.test) {
|
|
||||||
// a real alert is never delayed by tests: drop queued tests, cut a test that is on screen
|
|
||||||
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1);
|
|
||||||
if (current && current.test) skipCurrent();
|
|
||||||
}
|
|
||||||
queue.push(d);
|
|
||||||
if (!busy) next();
|
|
||||||
}
|
|
||||||
|
|
||||||
// stop what is on screen and carry on with the queue
|
|
||||||
function skipCurrent() {
|
|
||||||
gen++;
|
|
||||||
clearTimeout(current.timer);
|
|
||||||
if (current.audio) { current.audio.pause(); current.audio.currentTime = 0; }
|
|
||||||
current.anims.forEach(a => a.cancel());
|
|
||||||
current = null;
|
|
||||||
if (el) el.style.visibility = 'hidden';
|
|
||||||
window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide();
|
|
||||||
busy = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function playTest(alert) {
|
|
||||||
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1); // older tests: gone
|
|
||||||
if (current && current.test) skipCurrent(); // a test on screen: cut it
|
|
||||||
play({ ...alert, test: true }); // a real one on screen: wait
|
|
||||||
}
|
|
||||||
|
|
||||||
// dashboard Skip button: cut what is on screen (sound/TTS too), then play the next queued alert
|
|
||||||
function skip() {
|
|
||||||
if (!current) return;
|
|
||||||
skipCurrent();
|
|
||||||
setTimeout(() => { if (!busy) next(); }, GAP);
|
|
||||||
}
|
|
||||||
|
|
||||||
function reset() {
|
|
||||||
gen++;
|
|
||||||
queue.length = 0;
|
|
||||||
if (current) {
|
|
||||||
clearTimeout(current.timer);
|
|
||||||
if (current.audio) { current.audio.pause(); current.audio.currentTime = 0; }
|
|
||||||
current.anims.forEach(a => a.cancel());
|
|
||||||
current = null;
|
|
||||||
}
|
|
||||||
if (el) el.style.visibility = 'hidden';
|
|
||||||
window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide();
|
|
||||||
busy = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function next() {
|
|
||||||
const d = queue.shift();
|
|
||||||
if (!d) { busy = false; return; }
|
|
||||||
busy = true;
|
|
||||||
const my = gen;
|
|
||||||
await show(d);
|
|
||||||
if (my !== gen) return;
|
|
||||||
setTimeout(() => { if (my === gen) next(); }, GAP);
|
|
||||||
}
|
|
||||||
|
|
||||||
function photoHTML(cls, art, inner) {
|
|
||||||
return `<div class="photo ${cls}"><div class="ph">${art ? `<img src="${ART(art)}" alt="">` : ''}</div>${inner}</div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function show(d) {
|
|
||||||
const el = root();
|
|
||||||
const cur = current = { anims:[], timer:null, audio:null, test:!!d.test };
|
|
||||||
const url = soundUrl(d.sound);
|
|
||||||
const len = url ? await soundLength(url) : 0;
|
|
||||||
if (cur !== current) return; // skipped while measuring the sound
|
|
||||||
|
|
||||||
// which look: Card (plain, everyone) or the optional Polaroid / Cassette / Letter (Actions → Alerts, Redeems)
|
|
||||||
const th = TH();
|
|
||||||
const asCard = window.CardAlert && !d.soundOnly && (
|
|
||||||
d.style === 'card' || // redeem variation set to Card
|
|
||||||
(d.style === 'tts' && th.ttsStyle !== 'letter') || // read-aloud redeem
|
|
||||||
(!d.cassette && !d.style && th.style !== 'polaroid')); // follow / sub / gift / raid / bits / tip / Hype Train
|
|
||||||
if (asCard) {
|
|
||||||
if (d.cassette) d.tag = d.title && d.sub && d.title !== d.sub ? `${d.sub} · ${d.title}` : (d.sub || d.title || '');
|
|
||||||
if (!d.sticker && d.cassette) d.sticker = ART(th.defaultSticker) || null;
|
|
||||||
return window.CardAlert.show(d, cur, { url, len, volume: d.volume ?? (th.volume ?? DEFAULT_VOLUME) })
|
|
||||||
.then(() => { if (current === cur) current = null; });
|
|
||||||
}
|
|
||||||
const fx = { emote: 'giant', emote_rain: 'rain', message: 'message', tts: 'envelope' }[d.style];
|
|
||||||
if (fx && !d.soundOnly && window.FxAlert) {
|
|
||||||
return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? (TH().volume ?? DEFAULT_VOLUME) })
|
|
||||||
.then(() => { if (current === cur) current = null; });
|
|
||||||
}
|
|
||||||
if (d.cassette && !d.soundOnly && window.CassetteAlert) {
|
|
||||||
return window.CassetteAlert.show(d, cur, { url, len, volume: d.volume ?? (TH().volume ?? DEFAULT_VOLUME) })
|
|
||||||
.then(() => { if (current === cur) current = null; });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (d.soundOnly) { // no picture: play the sound, hold the queue for its length
|
|
||||||
if (!url) return;
|
|
||||||
const a = cur.audio = new Audio(url); a.volume = d.volume ?? (TH().volume ?? DEFAULT_VOLUME);
|
|
||||||
a.play().catch(err => console.warn('[alerts] sound blocked:', err.message));
|
|
||||||
const wait = el.animate([{}, {}], { duration: Math.max(len, 500) });
|
|
||||||
cur.anims.push(wait);
|
|
||||||
return wait.finished.then(() => { if (current === cur) current = null; }).catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
const nameSize = d.name.length > 18 ? 32 : d.name.length > 14 ? 36 : 40;
|
|
||||||
const backArt = th.back && th.back.length ? th.back : [d.art]; // photos fanned out behind (theme), else the same one
|
|
||||||
const backs = Array.from({ length: d.stack || 0 }, (_, i) =>
|
|
||||||
photoHTML('back', backArt[i % backArt.length], '<div class="blank"></div>')).join('');
|
|
||||||
const heart = ART(th.heart); // corner sticker; none set = no stickers
|
|
||||||
const extraHearts = heart ? Array.from({ length: d.hearts || 0 }, () =>
|
|
||||||
`<img class="heart extra sticker" src="${heart}" alt="">`).join('') : '';
|
|
||||||
el.innerHTML = backs + `
|
|
||||||
<div class="photo main" style="--tape:${d.tape}${d.phbg ? ';--phbg:' + d.phbg : ''}">
|
|
||||||
<div class="tape t1"></div><div class="tape t2"></div>
|
|
||||||
<div class="ph${d.avatar ? ' avatar' : ''}">${d.art ? `<img src="${ART(d.art)}" alt="">` : `<span class="ini">${esc((d.name || '♥').trim()[0] || '♥').toUpperCase()}</span>`}${d.tag ? `<span class="tag">${esc(d.tag)}</span>` : ''}</div>
|
|
||||||
<div class="cap"><span class="u" style="font-size:${nameSize}px">${esc(d.name)}</span>${esc(d.line)}${d.msg ? `<span class="msg">“${esc(d.msg)}”</span>` : ''}</div>
|
|
||||||
${heart ? `<img class="heart sticker" src="${heart}" alt="">` : ''}
|
|
||||||
${extraHearts}
|
|
||||||
${d.badge ? `<div class="badge" style="${d.badge.color ? '--badge:' + d.badge.color : ''}">${esc(d.badge.big)}<small>${esc(d.badge.small)}</small></div>` : ''}
|
|
||||||
</div>`;
|
|
||||||
el.style.visibility = 'visible';
|
|
||||||
|
|
||||||
const q = s => el.querySelector(s);
|
|
||||||
const main = q('.photo.main');
|
|
||||||
const tilt = between(RANGES.photoTilt) * (rnd() < .5 ? -1 : 1);
|
|
||||||
const rot = dd => `rotate(${tilt + dd}deg)`;
|
|
||||||
const anims = cur.anims;
|
|
||||||
const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); anims.push(a); return a; };
|
|
||||||
|
|
||||||
// fanned stack behind the main photo (multi-month subs, community gifts, raids)
|
|
||||||
const backEls = [...el.querySelectorAll('.photo.back')];
|
|
||||||
const t0 = backEls.length ? 120 * backEls.length + 150 : 0;
|
|
||||||
backEls.forEach((b, i) => {
|
|
||||||
const ang = 4 + i * 4 + between([-2, 2]), dx = 24 + i * 26 + between([-4, 4]), dy = i * 5 + between([-4, 4]);
|
|
||||||
A(b, [
|
|
||||||
{ transform:`translate(${dx}px,${dy - 150}px) rotate(${ang * 2}deg)`, opacity:0 },
|
|
||||||
{ transform:`translate(${dx}px,${dy}px) rotate(${ang}deg)`, opacity:1 },
|
|
||||||
], { delay:i * 120, duration:450, easing:'cubic-bezier(.2,.8,.3,1)' });
|
|
||||||
});
|
|
||||||
|
|
||||||
// 1. photo drops in
|
|
||||||
A(main, [
|
|
||||||
{ transform:`translateY(-160px) rotate(${tilt * -2.5}deg) scale(1.15)`, opacity:0 },
|
|
||||||
{ transform:`translateY(10px) ${rot(tilt > 0 ? 1.5 : -1.5)} scale(.99)`, opacity:1, offset:.7 },
|
|
||||||
{ transform:`translateY(0) ${rot(0)} scale(1)`, opacity:1 },
|
|
||||||
], { delay:t0, duration:750, easing:'cubic-bezier(.2,.8,.3,1)' });
|
|
||||||
|
|
||||||
const nudge = (at, dx) => A(main, [
|
|
||||||
{ transform:`translateY(0) ${rot(0)}` }, { transform:`translateY(3px) ${rot(dx)}` }, { transform:`translateY(0) ${rot(0)}` },
|
|
||||||
], { delay:at, duration:220, easing:'ease-out', fill:'none' });
|
|
||||||
|
|
||||||
// 2. tapes press on
|
|
||||||
const tapeT = (x, y, a, s) => `translate(${x}px,${y}px) rotate(${a}deg) scale(${s})`;
|
|
||||||
const stick = (node, a, at) => {
|
|
||||||
const x = between(RANGES.tapeX), y = between(RANGES.tapeY);
|
|
||||||
A(node, [
|
|
||||||
{ transform:tapeT(x, y - 30, a - 8, 1.35), opacity:0 },
|
|
||||||
{ transform:tapeT(x, y, a, .94), opacity:1, offset:.75 },
|
|
||||||
{ transform:tapeT(x, y, a, 1), opacity:1 },
|
|
||||||
], { delay:at, duration:260, easing:'cubic-bezier(.3,.7,.4,1)' });
|
|
||||||
};
|
|
||||||
stick(q('.t1'), between(RANGES.tape1), t0 + 800); nudge(t0 + 1000, -.6);
|
|
||||||
stick(q('.t2'), between(RANGES.tape2), t0 + 1080); nudge(t0 + 1280, .6);
|
|
||||||
|
|
||||||
// 3. stickers slap on
|
|
||||||
const slap = (node, at, x, y, a) => A(node, [
|
|
||||||
{ transform:`translate(${x}px,${y}px) rotate(${a - 40}deg) scale(0)`, opacity:0 },
|
|
||||||
{ transform:`translate(${x}px,${y}px) rotate(${a + 6}deg) scale(1.25)`, opacity:1, offset:.6 },
|
|
||||||
{ transform:`translate(${x}px,${y}px) rotate(${a - 2}deg) scale(.92)`, opacity:1, offset:.82 },
|
|
||||||
{ transform:`translate(${x}px,${y}px) rotate(${a}deg) scale(1)`, opacity:1 },
|
|
||||||
], { delay:at, duration:420, easing:'ease-out' });
|
|
||||||
if (q('.heart:not(.extra)')) slap(q('.heart:not(.extra)'), t0 + 1450, between(RANGES.heartX), between(RANGES.heartY), between(RANGES.heart));
|
|
||||||
nudge(t0 + 1650, tilt > 0 ? .8 : -.8);
|
|
||||||
[...el.querySelectorAll('.heart.extra')].forEach((h, i) =>
|
|
||||||
slap(h, t0 + 1600 + i * 160, between([-20, 10]), -110 - i * 95 + between([-15, 15]), between([-25, 25])));
|
|
||||||
const badge = q('.badge');
|
|
||||||
if (badge) slap(badge, t0 + 1250, 0, 0, between(RANGES.badge));
|
|
||||||
|
|
||||||
// 4. caption writes in
|
|
||||||
A(q('.cap'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }],
|
|
||||||
{ delay:t0 + 1700, duration:700, easing:'ease-in-out' });
|
|
||||||
|
|
||||||
// stays up: entrance animation + 3 s, or until the sound has finished if that is later
|
|
||||||
const animEnd = t0 + 2400; // caption done writing
|
|
||||||
const soundEnd = url ? t0 + SOUND_LEAD + len : 0;
|
|
||||||
if (url) {
|
|
||||||
const a = new Audio(url); a.volume = d.volume ?? (TH().volume ?? DEFAULT_VOLUME);
|
|
||||||
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + SOUND_LEAD);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. exit: lift and drop away
|
|
||||||
const exitAt = Math.max(animEnd + AFTER_ANIM, soundEnd);
|
|
||||||
const exit = A(el, [
|
|
||||||
{ transform:'translateY(0) rotate(0) scale(1)', opacity:1 },
|
|
||||||
{ transform:'translateY(-20px) rotate(0deg) scale(1.04)', opacity:1, offset:.25 },
|
|
||||||
{ transform:`translateY(140px) rotate(${tilt > 0 ? 14 : -14}deg) scale(.9)`, opacity:0 },
|
|
||||||
], { delay:exitAt, duration:650, easing:'ease-in' });
|
|
||||||
|
|
||||||
return exit.finished
|
|
||||||
.then(() => { el.style.visibility = 'hidden'; anims.forEach(a => a.cancel()); if (current === cur) current = null; })
|
|
||||||
.catch(() => {}); // cancelled by reset()
|
|
||||||
}
|
|
||||||
|
|
||||||
window.PolaroidAlerts = { play, playTest, reset, skip, describe };
|
|
||||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload();
|
|
||||||
})();
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
/* 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; }
|
|
||||||
|
|
@ -1,92 +0,0 @@
|
||||||
/*
|
|
||||||
Live poll card for the overlay. Not part of the alert queue: it stays up while the poll runs.
|
|
||||||
PollCard.update(phase, poll) phase: begin | progress | end
|
|
||||||
poll: { id, title, choices:[{ id, title, votes }], ends_at, status } (status on end: completed | archived | terminated)
|
|
||||||
Votes animate live; on 'completed' the winner(s) get a heart and a WINNER stamp, then the card drops away.
|
|
||||||
*/
|
|
||||||
(function () {
|
|
||||||
const COLORS = ['#f4a0a8', '#a88be0', '#7fcfa6', '#f6c75b', '#8cc8f0'];
|
|
||||||
// heart on the winning option: the corner sticker from Actions → Alerts, else a plain shape
|
|
||||||
const heart = () => (window.S && window.S.alert_theme && window.S.alert_theme.heart) || (window.ALERTS_BASE || '/alerts/') + 'art/placeholder.svg';
|
|
||||||
const SHOW_RESULT_MS = 9000;
|
|
||||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c]));
|
|
||||||
let el = null, pollId = null, timer = null, hideTimer = null, endsAt = 0;
|
|
||||||
|
|
||||||
function root() {
|
|
||||||
if (!el) { el = document.createElement('div'); el.id = 'poll-card'; document.body.appendChild(el); }
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
|
|
||||||
function build(poll) {
|
|
||||||
const el = root();
|
|
||||||
clearTimeout(hideTimer); el.getAnimations().forEach(a => a.cancel());
|
|
||||||
pollId = poll.id;
|
|
||||||
el.innerHTML = `<div class="head"><span>POLL</span><span class="timer"></span></div>
|
|
||||||
<div class="q">${esc(poll.title)}</div>
|
|
||||||
${poll.choices.map((c, i) => `<div class="c" data-id="${esc(c.id)}">
|
|
||||||
<div class="row"><span class="t">${esc(c.title)}</span><span class="n">0</span></div>
|
|
||||||
<div class="track"><div class="fill" style="background-color:${COLORS[i % COLORS.length]}"></div></div>
|
|
||||||
<img class="heart" src="${heart()}" alt=""></div>`).join('')}
|
|
||||||
<div class="stamp">WINNER</div>`;
|
|
||||||
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 };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
/* 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; }
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
/*
|
|
||||||
Outgoing raid send-off card. Silent, outside the alert queue.
|
|
||||||
RaidCard.update(phase, raid) phase: start | done | cancel
|
|
||||||
raid: { target, avatar (Twitch profile picture URL or null), viewers, started_at }
|
|
||||||
start: appears and stays with a countdown (Twitch raids wait up to 90 s); done: "raid sent!" then leaves; cancel: leaves.
|
|
||||||
*/
|
|
||||||
(function () {
|
|
||||||
const COUNTDOWN_S = 90;
|
|
||||||
const BASE = window.ALERTS_BASE || '/alerts/';
|
|
||||||
// picture when the raided channel has none: Actions → Alerts → Raid send-off picture
|
|
||||||
const fallback = () => (window.S && window.S.alert_theme && window.S.alert_theme.raidFallback) || BASE + 'art/placeholder.svg';
|
|
||||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c]));
|
|
||||||
let el = null, timer = null, hideTimer = null, startedAt = 0, shown = false;
|
|
||||||
|
|
||||||
function root() { if (!el) { el = document.createElement('div'); el.id = 'raid-card'; document.body.appendChild(el); } return el; }
|
|
||||||
|
|
||||||
function render(raid, line, badge) {
|
|
||||||
const img = raid.avatar ? `<img src="${esc(raid.avatar)}" alt="" onerror="this.onerror=null;this.className='fallback';this.src='${fallback()}'">`
|
|
||||||
: `<img class="fallback" src="${fallback()}" alt="">`;
|
|
||||||
el.innerHTML = `<div class="ph">${img}</div>
|
|
||||||
<div class="cap"><span class="u">raiding ${esc(raid.target)}</span>${esc(line)}</div>
|
|
||||||
<div class="when">${esc(badge)}</div>`;
|
|
||||||
}
|
|
||||||
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 };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
/* Video redeems (?parts=video, see video.js): full-screen video + a camcorder notification box,
|
|
||||||
the HUDFX box's look in yellow, in the alert corner (85,110, 440px wide on 1920x1080; video.js zooms the box
|
|
||||||
to the page width, so a 2560x1440 source looks the same, only sharper). */
|
|
||||||
@import url('https://fonts.googleapis.com/css2?family=VT323&display=swap');
|
|
||||||
|
|
||||||
#vfx-video { position:fixed; inset:0; width:100vw; height:100vh; object-fit:contain; background:transparent;
|
|
||||||
visibility:hidden; pointer-events:none; z-index:40; }
|
|
||||||
|
|
||||||
#vfx-box {
|
|
||||||
--yellow:#eeb434; --pale:#ffe7a3; --screen:#241e12;
|
|
||||||
position:fixed; left:85px; top:110px; width:440px; box-sizing:border-box; z-index:41; visibility:hidden;
|
|
||||||
padding:46px 22px 26px; border:5px solid var(--yellow); border-radius:12px;
|
|
||||||
box-shadow:0 0 0 3px #15110a, 0 0 22px rgba(238,180,52,.55), 0 14px 26px rgba(0,0,0,.5);
|
|
||||||
background:
|
|
||||||
linear-gradient(#fff,#fff) 12px 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) 12px 12px / 4px 26px no-repeat,
|
|
||||||
linear-gradient(#fff,#fff) right 12px top 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) right 12px top 12px / 4px 26px no-repeat,
|
|
||||||
linear-gradient(#fff,#fff) left 12px bottom 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) left 12px bottom 12px / 4px 26px no-repeat,
|
|
||||||
linear-gradient(#fff,#fff) right 12px bottom 12px / 26px 4px no-repeat, linear-gradient(#fff,#fff) right 12px bottom 12px / 4px 26px no-repeat,
|
|
||||||
repeating-linear-gradient(0deg, rgba(255,255,255,.045) 0 2px, transparent 2px 4px),
|
|
||||||
radial-gradient(ellipse at 50% 45%, #43361a 0%, var(--screen) 70%) #241e12;
|
|
||||||
font-family:'VT323', monospace; color:#fff; text-align:center;
|
|
||||||
}
|
|
||||||
#vfx-box .rec { position:absolute; left:58px; top:16px; font-size:26px; color:#ff3b4e; text-shadow:0 0 6px rgba(255,59,78,.7);
|
|
||||||
animation:vfx-blink 1s steps(1) infinite; }
|
|
||||||
#vfx-box .tc { position:absolute; right:24px; top:16px; font-size:24px; opacity:.85; }
|
|
||||||
#vfx-box .title { font-size:36px; line-height:1; text-transform:uppercase; overflow-wrap:anywhere;
|
|
||||||
text-shadow:2px 0 rgba(255,59,120,.75), -2px 0 rgba(80,220,255,.75); }
|
|
||||||
#vfx-box .who { font-size:32px; line-height:1; margin-top:10px; color:var(--pale); text-transform:uppercase; overflow-wrap:anywhere;
|
|
||||||
text-shadow:2px 0 rgba(255,59,120,.6), -2px 0 rgba(80,220,255,.6); }
|
|
||||||
#vfx-box .amt { display:inline-block; margin-top:16px; padding:2px 16px; background:var(--yellow); color:#241e12; font-size:28px;
|
|
||||||
border-radius:4px; text-transform:uppercase; box-shadow:0 0 12px rgba(238,180,52,.7); }
|
|
||||||
#vfx-box .amt:empty { display:none; }
|
|
||||||
#vfx-box .brand { position:absolute; right:46px; bottom:14px; font:900 13px/1 'Nunito', sans-serif; letter-spacing:1.5px;
|
|
||||||
color:var(--yellow); opacity:.8; }
|
|
||||||
@keyframes vfx-blink { 0% { opacity:1; } 50% { opacity:0; } }
|
|
||||||
|
|
||||||
/* the Power-up's / reward's Twitch icon as a sticker on the box's top-left corner */
|
|
||||||
#vfx-box .ico { position:absolute; left:-30px; top:-30px; width:72px; height:72px; object-fit:contain; transform:rotate(-10deg); z-index:2;
|
|
||||||
filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 5px 8px rgba(0,0,0,.35)); }
|
|
||||||
#vfx-box .ico[hidden] { display:none; }
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
/*
|
|
||||||
Video redeems, for the ?parts=video overlay (an OBS source of its own, e.g. instead of HUDFX).
|
|
||||||
Any source size works; 2560x1440 like HUDFX gives sharper video. The box is laid out for 1920x1080 and
|
|
||||||
zoomed to the page width, so it always lands in the alert corner.
|
|
||||||
Redeem variations with a video (style 'video', see src/redeems.js) play here full-screen, one at a time,
|
|
||||||
with a camcorder notification box (video.css) while the video runs.
|
|
||||||
VideoFX.play(alert) queue it
|
|
||||||
VideoFX.playTest(alert) test: replaces a playing/queued test at once
|
|
||||||
VideoFX.skip() stop the current one, carry on with the queue
|
|
||||||
alert: { video, volume, user, reward, variation, bits, test }
|
|
||||||
*/
|
|
||||||
(() => {
|
|
||||||
const queue = [];
|
|
||||||
let cur = null, vid = null, box = null, tcTimer = null;
|
|
||||||
|
|
||||||
function els() {
|
|
||||||
if (vid) return;
|
|
||||||
vid = document.createElement('video'); vid.id = 'vfx-video'; vid.playsInline = true; document.body.appendChild(vid);
|
|
||||||
box = document.createElement('div'); box.id = 'vfx-box';
|
|
||||||
box.innerHTML = '<img class="ico" alt=""><div class="rec">● REC</div><div class="tc"></div><div class="title"></div><div class="who"></div><div class="amt"></div><div class="brand">POWER-UP</div>';
|
|
||||||
document.body.appendChild(box);
|
|
||||||
fit(); addEventListener('resize', fit);
|
|
||||||
}
|
|
||||||
function fit() { if (box) box.style.zoom = innerWidth / 1920; }
|
|
||||||
const fmt = s => { s = Math.max(0, Math.floor(s)); return `▶ ${Math.floor(s / 3600)}:${String(Math.floor(s / 60) % 60).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`; };
|
|
||||||
|
|
||||||
function show(a) {
|
|
||||||
els();
|
|
||||||
const name = a.variation && a.variation !== a.reward ? a.variation : (a.reward || 'Power-up');
|
|
||||||
box.querySelector('.title').textContent = `Triggered ${name}`;
|
|
||||||
box.querySelector('.who').textContent = a.user || '';
|
|
||||||
box.querySelector('.amt').textContent = a.bits ? `◆ ${a.bits} bits ◆` : '';
|
|
||||||
box.querySelector('.tc').textContent = fmt(0);
|
|
||||||
const ico = box.querySelector('.ico'); // the Power-up's / reward's Twitch icon, top-left corner
|
|
||||||
if (a.icon) { ico.src = a.icon; ico.hidden = false; } else { ico.removeAttribute('src'); ico.hidden = true; }
|
|
||||||
box.style.visibility = 'visible';
|
|
||||||
box.animate([{ opacity: 0, transform: 'translateY(-12px)' }, { opacity: 1, transform: 'none' }], { duration: 400, easing: 'ease-out', fill: 'both' });
|
|
||||||
clearInterval(tcTimer); tcTimer = setInterval(() => { box.querySelector('.tc').textContent = fmt(vid.currentTime); }, 250);
|
|
||||||
}
|
|
||||||
function hideBox() {
|
|
||||||
clearInterval(tcTimer);
|
|
||||||
if (!box || box.style.visibility !== 'visible') return;
|
|
||||||
box.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 500, fill: 'both' }).finished
|
|
||||||
.then(() => { if (!cur) box.style.visibility = 'hidden'; }).catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
function finish(a) {
|
|
||||||
if (cur !== a) return;
|
|
||||||
clearTimeout(a._guard);
|
|
||||||
vid.pause(); vid.removeAttribute('src'); vid.load(); vid.style.visibility = 'hidden';
|
|
||||||
cur = null;
|
|
||||||
hideBox();
|
|
||||||
setTimeout(next, 600);
|
|
||||||
}
|
|
||||||
function next() {
|
|
||||||
if (cur || !queue.length) return;
|
|
||||||
const a = cur = queue.shift();
|
|
||||||
show(a);
|
|
||||||
vid.src = a.video; vid.volume = Math.max(0, Math.min(1, a.volume ?? 0.8)); vid.currentTime = 0;
|
|
||||||
vid.style.visibility = 'visible';
|
|
||||||
vid.onended = () => finish(a);
|
|
||||||
vid.onerror = () => { console.warn('[video] could not play', a.video); setTimeout(() => finish(a), 2500); };
|
|
||||||
vid.play().catch(e => { console.warn('[video] play:', e.message); setTimeout(() => finish(a), 2500); });
|
|
||||||
a._guard = setTimeout(() => finish(a), 120000); // never block the queue on a broken/endless file
|
|
||||||
}
|
|
||||||
|
|
||||||
function play(a) { if (!a?.video) return; queue.push(a); next(); }
|
|
||||||
function playTest(a) {
|
|
||||||
if (!a?.video) return;
|
|
||||||
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1);
|
|
||||||
if (cur?.test) { queue.unshift({ ...a, test: true }); finish(cur); }
|
|
||||||
else play({ ...a, test: true });
|
|
||||||
}
|
|
||||||
function skip() { if (cur) finish(cur); }
|
|
||||||
|
|
||||||
window.VideoFX = { play, playTest, skip };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,82 +0,0 @@
|
||||||
/* Chat: cream paper slips with the name on a washi-tape label ("style 5" from the chat preview).
|
|
||||||
The box sits under the webcam (Game scene: camera group at 1920,600, 640x360 on the 2560 canvas
|
|
||||||
= 1440,450 480x270 on this 1920x1080 page). Newest message on top, slides out from under the camera,
|
|
||||||
older ones are pushed down and dissolve at the bottom edge.
|
|
||||||
Per browser source: ?chat=left,top,width,height (px of the 1920x1080 page) and ?chatflow=up (newest at the bottom),
|
|
||||||
e.g. the Intermission panel: ?parts=chat&chat=130,640,700,360&chatflow=up. Default (no ?chat): under the camera, flowing down. */
|
|
||||||
#chat {
|
|
||||||
--chat-left: 78%;
|
|
||||||
--chat-top: 63%; /* 680px: just above the bottom of the camera ring, so messages come out from under it */
|
|
||||||
--chat-width: 20%;
|
|
||||||
--chat-height: 34%; /* down to the bottom edge */
|
|
||||||
--ink: #3a2a20;
|
|
||||||
--cream: #fffdf7;
|
|
||||||
position: fixed;
|
|
||||||
left: var(--chat-left);
|
|
||||||
top: var(--chat-top);
|
|
||||||
width: var(--chat-width);
|
|
||||||
height: var(--chat-height);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
justify-content: flex-start;
|
|
||||||
gap: 8px;
|
|
||||||
padding: 26px 8px 0;
|
|
||||||
overflow: hidden;
|
|
||||||
-webkit-mask-image: linear-gradient(transparent 0, #000 30px, #000 calc(100% - 60px), transparent);
|
|
||||||
mask-image: linear-gradient(transparent 0, #000 30px, #000 calc(100% - 60px), transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* up: like a normal chat, newest at the bottom, the oldest fade out at the top */
|
|
||||||
#chat.up {
|
|
||||||
justify-content: flex-end;
|
|
||||||
padding: 14px 8px 8px;
|
|
||||||
-webkit-mask-image: linear-gradient(transparent 0, #000 50px);
|
|
||||||
mask-image: linear-gradient(transparent 0, #000 50px);
|
|
||||||
}
|
|
||||||
#chat.up .msg.in { animation-name: chat-in-up; }
|
|
||||||
@keyframes chat-in-up { from { opacity: 0; transform: translateY(24px) rotate(calc(var(--tilt, 0deg) * -3)) scale(.95); } }
|
|
||||||
|
|
||||||
#chat .msg {
|
|
||||||
position: relative;
|
|
||||||
flex: none;
|
|
||||||
margin: 9px 6px 0;
|
|
||||||
padding: 19px 14px 9px;
|
|
||||||
border-radius: 2px;
|
|
||||||
background: var(--cream);
|
|
||||||
color: var(--ink);
|
|
||||||
font: 800 17px/1.3 Nunito, sans-serif;
|
|
||||||
word-break: break-word;
|
|
||||||
box-shadow: 0 3px 8px rgba(0, 0, 0, .35);
|
|
||||||
transform: rotate(var(--tilt, 0deg));
|
|
||||||
}
|
|
||||||
#chat .msg.action { font-style: italic; }
|
|
||||||
|
|
||||||
/* the name on a strip of washi tape, tinted with the chatter's Twitch colour */
|
|
||||||
#chat .msg .u {
|
|
||||||
position: absolute;
|
|
||||||
top: -12px;
|
|
||||||
left: 10px;
|
|
||||||
max-width: 85%;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
padding: 1px 12px 2px;
|
|
||||||
font: 700 23px/1 Caveat, cursive;
|
|
||||||
color: var(--ink);
|
|
||||||
background-color: var(--tape, rgba(201, 182, 228, .92));
|
|
||||||
background-image: repeating-linear-gradient(45deg, #fff5 0 6px, #0000 6px 12px);
|
|
||||||
transform: rotate(calc(var(--tilt, 0deg) * -2));
|
|
||||||
box-shadow: 0 1px 2px rgba(0, 0, 0, .2);
|
|
||||||
clip-path: polygon(0 8%, 3% 0, 97% 4%, 100% 0, 98% 100%, 2% 94%);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* emotes (Twitch + 7TV). Zero-width 7TV emotes (RainTime, PETPET...) stack on the emote before them. */
|
|
||||||
#chat .em { position: relative; display: inline-grid; vertical-align: -0.45em; margin: 0 1px; }
|
|
||||||
#chat .em > img { grid-area: 1 / 1; height: 1.6em; width: auto; justify-self: center; align-self: center;
|
|
||||||
filter: drop-shadow(0 0 1px rgba(58, 42, 32, .55)); } /* white emotes (Clap...) stay visible on cream */
|
|
||||||
#chat .msg.big .em > img { height: 2.6em; } /* emote-only messages: bigger emotes */
|
|
||||||
|
|
||||||
#chat .msg.in { animation: chat-in .45s cubic-bezier(.2, 1.3, .4, 1) both; }
|
|
||||||
#chat .msg.out { animation: chat-out .6s ease-in both; }
|
|
||||||
@keyframes chat-in { from { opacity: 0; transform: translateY(-24px) rotate(calc(var(--tilt, 0deg) * -3)) scale(.95); } }
|
|
||||||
@keyframes chat-out { to { opacity: 0; transform: translate(40px, 30px) rotate(calc(var(--tilt, 0deg) + 12deg)); } }
|
|
||||||
|
|
@ -1,165 +0,0 @@
|
||||||
/* Chat messages for the overlay (?parts=chat). tmi.js in overlay.ejs feeds them in via HSChat.add().
|
|
||||||
Look: public/chat/chat.css. Emotes: Twitch (from the message tags) + 7TV channel and global sets.
|
|
||||||
Settings used: S.message_timeout (seconds, 0 = never fade) and S.max_messages. */
|
|
||||||
(function () {
|
|
||||||
const box = document.getElementById('chat');
|
|
||||||
if (!box) return;
|
|
||||||
|
|
||||||
const TWITCH_EMOTE = id => `https://static-cdn.jtvnw.net/emoticons/v2/${id}/default/dark/2.0`;
|
|
||||||
const SEVENTV = 'https://7tv.io/v3';
|
|
||||||
const ZERO_WIDTH = 256; // 7TV emote data flag: overlays the emote before it
|
|
||||||
const REFRESH_MS = 10 * 60 * 1000; // pick up newly added 7TV emotes without an OBS refresh
|
|
||||||
|
|
||||||
let emotes7tv = new Map(); // name -> { url, zw }
|
|
||||||
let roomId = null, seq = 0;
|
|
||||||
|
|
||||||
// ---------- 7TV ----------
|
|
||||||
function setFrom(list, into) {
|
|
||||||
for (const e of list || []) {
|
|
||||||
const host = e.data && e.data.host;
|
|
||||||
if (!host || !host.url) continue;
|
|
||||||
const file = (host.files || []).find(f => f.name === '2x.webp') || (host.files || []).find(f => /\.webp$/.test(f.name));
|
|
||||||
if (!file) continue;
|
|
||||||
into.set(e.name, { url: 'https:' + host.url + '/' + file.name, zw: ((e.data.flags || 0) & ZERO_WIDTH) !== 0 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function getJSON(url) {
|
|
||||||
const r = await fetch(url);
|
|
||||||
if (!r.ok) throw new Error(url + ' -> ' + r.status);
|
|
||||||
return r.json();
|
|
||||||
}
|
|
||||||
async function load7tv() {
|
|
||||||
const next = new Map();
|
|
||||||
try { setFrom((await getJSON(`${SEVENTV}/emote-sets/global`)).emotes, next); }
|
|
||||||
catch (e) { console.warn('[chat] 7TV global emotes:', e.message); }
|
|
||||||
if (roomId) {
|
|
||||||
try { setFrom(((await getJSON(`${SEVENTV}/users/twitch/${roomId}`)).emote_set || {}).emotes, next); } // channel wins over global
|
|
||||||
catch (e) { console.warn('[chat] 7TV channel emotes:', e.message); }
|
|
||||||
}
|
|
||||||
if (next.size) emotes7tv = next;
|
|
||||||
console.log(`[chat] 7TV emotes loaded: ${next.size}`);
|
|
||||||
}
|
|
||||||
function setRoom(id) {
|
|
||||||
if (!id || id === roomId) return;
|
|
||||||
roomId = id;
|
|
||||||
load7tv();
|
|
||||||
}
|
|
||||||
load7tv();
|
|
||||||
setInterval(load7tv, REFRESH_MS);
|
|
||||||
|
|
||||||
// ---------- message -> HTML ----------
|
|
||||||
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
||||||
const img = (url, name) => `<img src="${esc(url)}" alt="${esc(name)}" title="${esc(name)}">`;
|
|
||||||
|
|
||||||
// Returns { html, emoteOnly, emoteCount }.
|
|
||||||
function render(text, twitchEmotes) {
|
|
||||||
// Twitch emote positions are in code points, so work on an array of characters
|
|
||||||
const chars = Array.from(text);
|
|
||||||
const ranges = [];
|
|
||||||
for (const [id, list] of Object.entries(twitchEmotes || {})) {
|
|
||||||
for (const r of list) { const [a, b] = r.split('-').map(Number); ranges.push({ a, b, id }); }
|
|
||||||
}
|
|
||||||
ranges.sort((x, y) => x.a - y.a);
|
|
||||||
|
|
||||||
const tokens = []; // { t:'text', s } | { t:'em', url, name, zw }
|
|
||||||
let i = 0;
|
|
||||||
for (const r of ranges) {
|
|
||||||
if (r.a > i) tokens.push({ t: 'text', s: chars.slice(i, r.a).join('') });
|
|
||||||
tokens.push({ t: 'em', url: TWITCH_EMOTE(r.id), name: chars.slice(r.a, r.b + 1).join(''), zw: false });
|
|
||||||
i = r.b + 1;
|
|
||||||
}
|
|
||||||
if (i < chars.length) tokens.push({ t: 'text', s: chars.slice(i).join('') });
|
|
||||||
|
|
||||||
// 7TV: whole words inside the text parts
|
|
||||||
const out = [];
|
|
||||||
for (const tk of tokens) {
|
|
||||||
if (tk.t !== 'text') { out.push(tk); continue; }
|
|
||||||
for (const part of tk.s.split(/(\s+)/)) {
|
|
||||||
const e = part && emotes7tv.get(part);
|
|
||||||
out.push(e ? { t: 'em', url: e.url, name: part, zw: e.zw } : { t: 'text', s: part });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// build HTML; a zero-width emote joins the emote stack before it (skipping whitespace)
|
|
||||||
let html = '', open = false, count = 0, words = 0;
|
|
||||||
for (let k = 0; k < out.length; k++) {
|
|
||||||
const tk = out[k];
|
|
||||||
if (tk.t === 'text') {
|
|
||||||
if (/^\s*$/.test(tk.s)) {
|
|
||||||
const nx = out.slice(k + 1).find(x => !(x.t === 'text' && /^\s*$/.test(x.s)));
|
|
||||||
if (open && nx && nx.t === 'em' && nx.zw) continue; // keep the stack open for the overlay emote
|
|
||||||
if (open) { html += '</span>'; open = false; }
|
|
||||||
html += esc(tk.s);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (open) { html += '</span>'; open = false; }
|
|
||||||
html += esc(tk.s); words++;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
count++;
|
|
||||||
if (tk.zw && open) { html += img(tk.url, tk.name); continue; }
|
|
||||||
if (open) html += '</span>';
|
|
||||||
html += '<span class="em">' + img(tk.url, tk.name); open = true;
|
|
||||||
}
|
|
||||||
if (open) html += '</span>';
|
|
||||||
return { html, emoteOnly: count > 0 && words === 0, emoteCount: count };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- add / remove ----------
|
|
||||||
function tapeFrom(hex) {
|
|
||||||
const m = /^#?([0-9a-f]{6})$/i.exec(hex || '');
|
|
||||||
const n = m ? parseInt(m[1], 16) : 0xc9b6e4;
|
|
||||||
const c = [n >> 16, (n >> 8) & 255, n & 255].map(v => Math.round(v * .55 + 255 * .45));
|
|
||||||
return `rgba(${c[0]},${c[1]},${c[2]},.92)`;
|
|
||||||
}
|
|
||||||
const S = () => window.S || {};
|
|
||||||
|
|
||||||
function add(tags, text, isAction) {
|
|
||||||
if (tags && tags['room-id']) setRoom(tags['room-id']);
|
|
||||||
const name = (tags && (tags['display-name'] || tags.username)) || '?';
|
|
||||||
const r = render(text, tags && tags.emotes);
|
|
||||||
|
|
||||||
const d = document.createElement('div');
|
|
||||||
d.className = 'msg in' + (r.emoteOnly && r.emoteCount <= 3 ? ' big' : '') + (isAction ? ' action' : '');
|
|
||||||
d.dataset.id = (tags && tags.id) || '';
|
|
||||||
d.dataset.user = ((tags && tags.username) || '').toLowerCase();
|
|
||||||
d.style.setProperty('--tilt', (Math.random() * 3.2 - 1.6).toFixed(2) + 'deg');
|
|
||||||
d.style.setProperty('--tape', tapeFrom(tags && tags.color));
|
|
||||||
d.innerHTML = `<span class="u">${esc(name)}</span>${r.html}`;
|
|
||||||
d._n = ++seq;
|
|
||||||
|
|
||||||
// FLIP: remember where the others are, add the new one (on top, or at the bottom for ?chatflow=up),
|
|
||||||
// then glide the others from their old spot
|
|
||||||
const before = new Map([...box.children].map(m => [m, m.getBoundingClientRect().top]));
|
|
||||||
if (box.classList.contains('up')) box.append(d); else box.prepend(d);
|
|
||||||
before.forEach((top, m) => {
|
|
||||||
const dy = top - m.getBoundingClientRect().top;
|
|
||||||
if (dy && m.animate) m.animate([{ translate: `0 ${dy}px` }, { translate: '0 0' }], { duration: 320, easing: 'cubic-bezier(.2,.8,.3,1)' });
|
|
||||||
});
|
|
||||||
d.addEventListener('animationend', () => d.classList.remove('in'), { once: true });
|
|
||||||
|
|
||||||
// over the cap: the oldest leave with their exit animation
|
|
||||||
const live = [...box.children].filter(m => !m.classList.contains('out')).sort((a, b) => a._n - b._n);
|
|
||||||
const max = Number(S().max_messages) || 10;
|
|
||||||
live.slice(0, Math.max(0, live.length - max)).forEach(leave);
|
|
||||||
|
|
||||||
const t = Number(S().message_timeout);
|
|
||||||
if (t > 0) d._t = setTimeout(() => leave(d), t * 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
function leave(d) {
|
|
||||||
if (d.classList.contains('out')) return;
|
|
||||||
clearTimeout(d._t);
|
|
||||||
d.classList.remove('in');
|
|
||||||
d.classList.add('out');
|
|
||||||
d.addEventListener('animationend', () => d.remove(), { once: true });
|
|
||||||
setTimeout(() => d.remove(), 1200); // in case the animation never ends (hidden source)
|
|
||||||
}
|
|
||||||
|
|
||||||
// moderation: a deleted message, or everything from a user who got timed out / banned, leaves at once
|
|
||||||
function removeId(id) { [...box.children].filter(m => id && m.dataset.id === id).forEach(leave); }
|
|
||||||
function removeUser(user) { const u = String(user || '').toLowerCase(); [...box.children].filter(m => u && m.dataset.user === u).forEach(leave); }
|
|
||||||
function clear() { [...box.children].forEach(leave); }
|
|
||||||
|
|
||||||
window.HSChat = { add, removeId, removeUser, clear, setRoom, reload7tv: load7tv, render };
|
|
||||||
})();
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
|
||||||
<!-- Background circle -->
|
|
||||||
<circle cx="16" cy="16" r="15" fill="#9146ff"/>
|
|
||||||
<!-- Speech bubble body -->
|
|
||||||
<rect x="7" y="8" width="18" height="13" rx="3" fill="white"/>
|
|
||||||
<!-- Bubble tail -->
|
|
||||||
<polygon points="10,21 7,26 14,21" fill="white"/>
|
|
||||||
<!-- Screen/monitor lines (chat lines) -->
|
|
||||||
<rect x="10" y="11" width="12" height="2" rx="1" fill="#9146ff"/>
|
|
||||||
<rect x="10" y="14.5" width="9" height="2" rx="1" fill="#9146ff"/>
|
|
||||||
<!-- Star / sparkle top-right -->
|
|
||||||
<circle cx="23" cy="9" r="2.5" fill="#ffcc00"/>
|
|
||||||
<polygon points="23,6 23.7,8.3 26,8.3 24.2,9.7 24.8,12 23,10.6 21.2,12 21.8,9.7 20,8.3 22.3,8.3" fill="#ffaa00"/>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 701 B |
1
public/vendor/tmi.min.js
vendored
1
public/vendor/tmi.min.js
vendored
File diff suppressed because one or more lines are too long
128
src/activity.js
128
src/activity.js
|
|
@ -1,128 +0,0 @@
|
||||||
// Dashboard "Recent activity": readable labels for a log row, and Replay (play the row on the overlay again).
|
|
||||||
//
|
|
||||||
// Rows logged since replay_json exists carry the exact overlay message that was shown.
|
|
||||||
// Older rows only have the raw Twitch event (data_json): redeems and outgoing raids are rebuilt from it,
|
|
||||||
// other old rows cannot be replayed.
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
const TIERS = { 1000: 'Tier 1', 2000: 'Tier 2', 3000: 'Tier 3' };
|
|
||||||
const RARITY = { common: 'Common', uncommon: 'Uncommon', rare: 'Rare', ultra_rare: 'Ultra Rare' };
|
|
||||||
|
|
||||||
const LABEL = {
|
|
||||||
follow: 'Follow', sub: 'Sub', gift_sub: 'Gift sub', bits: 'Bits', watch_streak: 'Watch streak',
|
|
||||||
raid: 'Raid in', raid_out: 'Raid out', hype_train: 'Hype Train', tip: 'Tip',
|
|
||||||
channel_points: 'Channel points', auto_reward: 'Built-in reward', power_up: 'Power-up', custom_power_up: 'Custom Power-up',
|
|
||||||
poll_begin: 'Poll started', poll_end: 'Poll ended', command: 'Command',
|
|
||||||
};
|
|
||||||
|
|
||||||
const REDEEM_KIND = { channel_points: 'reward', auto_reward: 'auto_reward', power_up: 'power_up', custom_power_up: 'custom_power_up' };
|
|
||||||
|
|
||||||
function parse(json) { try { return json ? JSON.parse(json) : null; } catch { return null; } }
|
|
||||||
|
|
||||||
// Twitch's own reward name from the raw event (also for rows without a stored alert)
|
|
||||||
function rewardTitle(type, raw, alert) {
|
|
||||||
const { AUTO_REWARDS, POWER_UPS } = require('./redeems');
|
|
||||||
if (alert?.reward) return alert.reward;
|
|
||||||
if (type === 'channel_points') return raw?.reward?.title || null;
|
|
||||||
if (type === 'auto_reward') return AUTO_REWARDS[raw?.reward?.type] || raw?.reward?.type || null;
|
|
||||||
if (type === 'power_up') return POWER_UPS[raw?.power_up?.type] || raw?.power_up?.type || null;
|
|
||||||
if (type === 'custom_power_up') return raw?.custom_power_up?.title || null;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// -> { label, title, tags: [string], message }
|
|
||||||
function describe(log) {
|
|
||||||
const raw = parse(log.data_json);
|
|
||||||
const replay = parse(log.replay_json);
|
|
||||||
const a = replay?.type === 'alert' ? replay.alert : null;
|
|
||||||
const t = log.event_type;
|
|
||||||
const out = { label: LABEL[t] || t, title: null, tags: [], message: null };
|
|
||||||
|
|
||||||
if (REDEEM_KIND[t]) {
|
|
||||||
out.title = rewardTitle(t, raw, a) || log.event_detail;
|
|
||||||
if (raw?.reward?.cost) out.tags.push(`${raw.reward.cost} points`);
|
|
||||||
else if (raw?.reward?.channel_points) out.tags.push(`${raw.reward.channel_points} points`);
|
|
||||||
else if (raw?.bits) out.tags.push(`${raw.bits} bits`);
|
|
||||||
else if (raw?.custom_power_up?.bits) out.tags.push(`${raw.custom_power_up.bits} bits`);
|
|
||||||
if (a) {
|
|
||||||
if (a.variation && a.variation !== a.reward) out.tags.push(`played: ${a.variation}`);
|
|
||||||
if (a.rarity && a.rarity !== 'common') out.tags.push(RARITY[a.rarity] || a.rarity);
|
|
||||||
if (a.tts) out.tags.push('TTS');
|
|
||||||
if (a.video) out.tags.push('video');
|
|
||||||
}
|
|
||||||
out.message = a?.input || raw?.user_input || raw?.message?.text || null;
|
|
||||||
} else if (a) {
|
|
||||||
switch (a.type) {
|
|
||||||
case 'sub':
|
|
||||||
out.title = a.prime ? 'Prime' : TIERS[a.tier] || a.tier;
|
|
||||||
if (a.months > 1) out.tags.push(`${a.months} months`);
|
|
||||||
if (a.duration > 1) out.tags.push(`${a.duration} months at once`);
|
|
||||||
out.message = a.message || null; break;
|
|
||||||
case 'gift':
|
|
||||||
out.title = a.total > 1 ? `${a.total} gift subs` : `gift to ${a.recipient || 'someone'}`;
|
|
||||||
if (TIERS[a.tier]) out.tags.push(TIERS[a.tier]);
|
|
||||||
if (!a.user) out.tags.push('anonymous'); break;
|
|
||||||
case 'bits': out.title = `${a.bits} bits`; out.message = a.message || null; break;
|
|
||||||
case 'streak': out.title = `${a.streak} streams in a row`; break;
|
|
||||||
case 'raid': out.title = `${a.viewers} viewers`; break;
|
|
||||||
case 'hype':
|
|
||||||
out.title = a.phase === 'begin' ? 'started' : a.phase === 'level' ? `level ${a.level}` : `ended at level ${a.level}`;
|
|
||||||
if (a.golden) out.tags.push('Golden Kappa'); if (a.treasure) out.tags.push('Treasure');
|
|
||||||
if (a.top?.length) out.message = `top: ${a.top.join(', ')}`; break;
|
|
||||||
case 'tip': out.title = `${a.amount} ${a.currency}`; out.message = a.message || null; break;
|
|
||||||
}
|
|
||||||
} else if (t === 'raid_out') {
|
|
||||||
out.title = `to ${raw?.to_broadcaster_user_name || log.username || '?'}`;
|
|
||||||
if (raw?.viewers != null) out.tags.push(`${raw.viewers} viewers`);
|
|
||||||
} else if (t === 'poll_begin' || t === 'poll_end') {
|
|
||||||
out.title = raw?.title || null;
|
|
||||||
if (t === 'poll_end' && raw?.choices?.length) {
|
|
||||||
const sorted = [...raw.choices].sort((x, y) => (y.votes || 0) - (x.votes || 0));
|
|
||||||
out.message = sorted.map(c => `${c.title}: ${c.votes ?? 0}`).join(' · ');
|
|
||||||
}
|
|
||||||
} else if (log.event_detail) {
|
|
||||||
out.title = log.event_detail;
|
|
||||||
}
|
|
||||||
if (t === 'raid_out' && replay?.raid) {
|
|
||||||
out.title = `to ${replay.raid.target}`;
|
|
||||||
out.tags = [`${replay.raid.viewers} viewers`];
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Can this row be replayed? (cheap check for the table; replay() does the real work)
|
|
||||||
function canReplay(log) {
|
|
||||||
if (log.replay_json) return true;
|
|
||||||
return !!log.data_json && (!!REDEEM_KIND[log.event_type] || log.event_type === 'raid_out');
|
|
||||||
}
|
|
||||||
|
|
||||||
const PUBLIC = path.join(__dirname, '..', 'public');
|
|
||||||
const fileGone = url => !url || !fs.existsSync(path.join(PUBLIC, url.replace(/^\/+/, '').split('?')[0]));
|
|
||||||
|
|
||||||
// -> the overlay message to broadcast, or null
|
|
||||||
async function replayMessage(log) {
|
|
||||||
const stored = parse(log.replay_json);
|
|
||||||
if (stored) {
|
|
||||||
if (stored.type === 'alert' && stored.alert.tts && fileGone(stored.alert.tts)) await require('./redeems').respeak(stored.alert);
|
|
||||||
return stored;
|
|
||||||
}
|
|
||||||
const raw = parse(log.data_json);
|
|
||||||
if (!raw) return null;
|
|
||||||
if (REDEEM_KIND[log.event_type]) {
|
|
||||||
const kind = REDEEM_KIND[log.event_type];
|
|
||||||
const key = log.event_detail;
|
|
||||||
const input = raw.user_input || raw.message?.text || null;
|
|
||||||
const emote = raw.reward?.emote?.id || raw.power_up?.emote?.id || null;
|
|
||||||
const bits = raw.custom_power_up?.bits ?? null;
|
|
||||||
const alert = await require('./redeems').rebuild(kind, key, { user: raw.user_name || raw.user_login || log.username, input, emote, bits });
|
|
||||||
return alert ? { type: 'alert', alert } : null;
|
|
||||||
}
|
|
||||||
if (log.event_type === 'raid_out') {
|
|
||||||
const raid = await require('./alerts').raidTarget(raw);
|
|
||||||
return { type: 'raid_card', phase: 'done', raid: { ...raid, viewers: raw.viewers } };
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { describe, canReplay, replayMessage };
|
|
||||||
258
src/alerts.js
258
src/alerts.js
|
|
@ -1,258 +0,0 @@
|
||||||
// Turns Twitch events into polaroid alerts and pushes them to the overlay.
|
|
||||||
//
|
|
||||||
// Alert shape (what public/alerts/polaroid.js renders):
|
|
||||||
// { type:'follow', user }
|
|
||||||
// { type:'sub', user, tier:'1000'|'2000'|'3000', prime, months, duration, message }
|
|
||||||
// { type:'gift', user|null (anonymous), total, recipient, tier } total>1 = community gift
|
|
||||||
// { type:'streak', user, streak }
|
|
||||||
// { type:'raid', user, viewers }
|
|
||||||
// { type:'bits', user|null (anonymous), bits, message }
|
|
||||||
//
|
|
||||||
// Every alert also goes through dispatch.dispatchEvent() so the existing actions system
|
|
||||||
// (sounds/videos per event) and the dashboard activity log keep working.
|
|
||||||
const ws = require('./ws');
|
|
||||||
const dispatch = require('./dispatch');
|
|
||||||
|
|
||||||
// legacy action event types + detail, so existing action matching rules still apply
|
|
||||||
function legacy(alert) {
|
|
||||||
switch (alert.type) {
|
|
||||||
case 'sub': return ['sub', alert.tier];
|
|
||||||
case 'gift': return ['gift_sub', alert.tier];
|
|
||||||
case 'bits': return ['bits', String(alert.bits)];
|
|
||||||
case 'streak': return ['watch_streak', String(alert.streak)];
|
|
||||||
case 'hype': return ['hype_train', alert.phase];
|
|
||||||
case 'tip': return ['tip', `${alert.amount} ${alert.currency}`];
|
|
||||||
case 'redeem': return [{ reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up', custom_power_up: 'custom_power_up' }[alert.kind] || 'redeem', alert.key];
|
|
||||||
default: return [alert.type || 'alert', null];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function send(alert, raw = null) {
|
|
||||||
if (!alert) return;
|
|
||||||
console.log(`[alerts] ${alert.type} — ${alert.user ?? 'anonymous'} ${JSON.stringify({ ...alert, type: undefined, user: undefined })}`);
|
|
||||||
const msg = { type: 'alert', alert };
|
|
||||||
ws.broadcast(msg);
|
|
||||||
const [eventType, detail] = legacy(alert);
|
|
||||||
dispatch.dispatchEvent(eventType, detail, alert.user, raw || alert, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
const text = m => (m && typeof m.text === 'string' && m.text.trim()) ? m.text.trim() : null;
|
|
||||||
|
|
||||||
// --- EventSub mappers ---
|
|
||||||
|
|
||||||
function fromFollow(e) {
|
|
||||||
return { type: 'follow', user: e.user_name || e.user_login };
|
|
||||||
}
|
|
||||||
|
|
||||||
function fromCheer(e) {
|
|
||||||
return { type: 'bits', user: e.is_anonymous ? null : (e.user_name || e.user_login), bits: e.bits, message: e.message || null };
|
|
||||||
}
|
|
||||||
|
|
||||||
// channel.bits.use with type 'cheer' (Power-ups are handled by redeems.js)
|
|
||||||
function fromBitsUse(e) {
|
|
||||||
return { type: 'bits', user: e.user_name || e.user_login || null, bits: e.bits, message: text(e.message) };
|
|
||||||
}
|
|
||||||
|
|
||||||
// channel.chat.notification: one event type that carries all sub/gift/raid details
|
|
||||||
// (Prime flag, months bought at once, gift recipient, resub message, community gift totals).
|
|
||||||
function fromChatNotification(e) {
|
|
||||||
const user = e.chatter_is_anonymous ? null : (e.chatter_user_name || e.chatter_user_login);
|
|
||||||
switch (e.notice_type) {
|
|
||||||
case 'sub':
|
|
||||||
return { type: 'sub', user, tier: e.sub.sub_tier, prime: !!e.sub.is_prime, months: 1,
|
|
||||||
duration: e.sub.duration_months || 1, message: text(e.message) };
|
|
||||||
case 'resub':
|
|
||||||
return { type: 'sub', user, tier: e.resub.sub_tier, prime: !!e.resub.is_prime,
|
|
||||||
months: e.resub.cumulative_months || 1, duration: e.resub.duration_months || 1, message: text(e.message) };
|
|
||||||
case 'gift_paid_upgrade':
|
|
||||||
case 'prime_paid_upgrade':
|
|
||||||
// gifted/Prime sub continued as a paid sub: show as a sub
|
|
||||||
return { type: 'sub', user, tier: e.prime_paid_upgrade?.sub_tier || '1000', prime: false, months: 1, duration: 1, message: null };
|
|
||||||
case 'sub_gift':
|
|
||||||
// part of a community gift: the community_sub_gift notice already covers it (no alert per recipient)
|
|
||||||
if (e.sub_gift.community_gift_id) return null;
|
|
||||||
return { type: 'gift', user, total: 1, recipient: e.sub_gift.recipient_user_name, tier: e.sub_gift.sub_tier };
|
|
||||||
case 'community_sub_gift':
|
|
||||||
return { type: 'gift', user, total: e.community_sub_gift.total, tier: e.community_sub_gift.sub_tier };
|
|
||||||
case 'raid':
|
|
||||||
return { type: 'raid', user: e.raid.user_name || e.raid.user_login, viewers: e.raid.viewer_count };
|
|
||||||
default:
|
|
||||||
return null; // announcements, pay-it-forward, bits badge tiers, ...: no alert
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- StreamElements tip (Astro channel.tips message data) ---
|
|
||||||
function fromTip(d) {
|
|
||||||
const t = d.donation || {};
|
|
||||||
return { type: 'tip', user: t.user?.username || 'Someone', amount: Number(t.amount) || 0, currency: t.currency || 'USD',
|
|
||||||
message: (t.message || '').trim() || null };
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Hype Train (v2): alert on start, on each NEW level, and at the end ---
|
|
||||||
const hypeLevels = new Map(); // train id -> last announced level
|
|
||||||
function fromHypeTrain(phase, e) {
|
|
||||||
const base = { type: 'hype', golden: e.type === 'golden_kappa', treasure: e.type === 'treasure', shared: !!e.is_shared_train, level: e.level };
|
|
||||||
if (phase === 'begin') {
|
|
||||||
hypeLevels.set(e.id, e.level);
|
|
||||||
return { ...base, phase: 'begin' };
|
|
||||||
}
|
|
||||||
if (phase === 'progress') {
|
|
||||||
if ((hypeLevels.get(e.id) || 0) >= e.level) return null; // every contribution sends progress: only level-ups alert
|
|
||||||
hypeLevels.set(e.id, e.level);
|
|
||||||
return { ...base, phase: 'level' };
|
|
||||||
}
|
|
||||||
hypeLevels.delete(e.id);
|
|
||||||
const top = (e.top_contributions || []).map(c => c.user_name || c.user_login).filter(Boolean);
|
|
||||||
return { ...base, phase: 'end', top: [...new Set(top)].slice(0, 3) };
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Hype Train progress bar (persistent while the train runs, outside the queue) ---
|
|
||||||
function sendHypeBar(phase, e) {
|
|
||||||
ws.broadcast({ type: 'hype_bar', phase, train: {
|
|
||||||
id: e.id, level: e.level, progress: e.progress ?? null, goal: e.goal ?? null, total: e.total,
|
|
||||||
expires_at: e.expires_at || null, golden: e.type === 'golden_kappa', treasure: e.type === 'treasure' } });
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- outgoing raid send-off card (persistent, silent, outside the queue) ---
|
|
||||||
// Twitch has no "raid started" event: the card appears when the raid is started from the dashboard
|
|
||||||
// (routers/alerts.js -> Helix POST /raids) and stays until channel.raid reports the raid happened.
|
|
||||||
let pendingRaid = null; // { target, avatar, viewers, started_at }
|
|
||||||
function raidCard(phase, raid) { ws.broadcast({ type: 'raid_card', phase, raid }); }
|
|
||||||
function raidStarted(raid) { pendingRaid = { ...raid, started_at: new Date().toISOString() }; raidCard('start', pendingRaid); }
|
|
||||||
function raidCancelled() { if (pendingRaid) raidCard('cancel', pendingRaid); pendingRaid = null; }
|
|
||||||
function getPendingRaid() { return pendingRaid; }
|
|
||||||
// channel.raid from us: the raid happened (started from the dashboard or straight on Twitch)
|
|
||||||
async function raidTarget(e) {
|
|
||||||
let avatar = null;
|
|
||||||
try {
|
|
||||||
const res = await require('./twitch').helix(`/users?id=${encodeURIComponent(e.to_broadcaster_user_id)}`);
|
|
||||||
if (res.ok) avatar = (await res.json()).data?.[0]?.profile_image_url || null;
|
|
||||||
} catch { /* fallback art */ }
|
|
||||||
return { target: e.to_broadcaster_user_name || e.to_broadcaster_user_login, avatar };
|
|
||||||
}
|
|
||||||
async function raidHappened(e) {
|
|
||||||
const raid = pendingRaid || await raidTarget(e); // started on Twitch directly: show the card briefly
|
|
||||||
const msg = { type: 'raid_card', phase: 'done', raid: { ...raid, viewers: e.viewers } };
|
|
||||||
ws.broadcast(msg);
|
|
||||||
pendingRaid = null;
|
|
||||||
console.log(`[alerts] raid out — ${msg.raid.target} with ${e.viewers}`);
|
|
||||||
dispatch.dispatchEvent('raid_out', String(e.viewers), e.to_broadcaster_user_name, e, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- polls: a live card on the overlay, outside the alert queue ---
|
|
||||||
function pollShape(phase, e) {
|
|
||||||
return {
|
|
||||||
id: e.id, title: e.title, status: e.status || null, ends_at: e.ends_at || null,
|
|
||||||
choices: (e.choices || []).map(c => ({ id: c.id, title: c.title, votes: c.votes || 0 })),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function sendPoll(phase, e) {
|
|
||||||
ws.broadcast({ type: 'poll', phase, poll: pollShape(phase, e) });
|
|
||||||
if (phase !== 'progress') {
|
|
||||||
const detail = phase === 'end' ? e.status : null;
|
|
||||||
dispatch.dispatchEvent(`poll_${phase}`, detail, null, e); // activity log (begin + end only)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- watch streaks, reported by the overlay (they only exist as a chat USERNOTICE) ---
|
|
||||||
const seenNotices = new Map(); // message id -> time; several overlays may report the same notice
|
|
||||||
function fromOverlayNotice(n) {
|
|
||||||
if (n.kind !== 'watch_streak') return null;
|
|
||||||
const streak = parseInt(n.streak, 10);
|
|
||||||
if (!n.id || !n.user || !(streak > 0)) return null;
|
|
||||||
const now = Date.now();
|
|
||||||
for (const [id, t] of seenNotices) if (now - t > 10 * 60 * 1000) seenNotices.delete(id);
|
|
||||||
if (seenNotices.has(n.id)) return null;
|
|
||||||
seenNotices.set(n.id, now);
|
|
||||||
return { type: 'streak', user: String(n.user).slice(0, 40), streak };
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- test alerts (dashboard buttons) ---
|
|
||||||
const SAMPLES = {
|
|
||||||
'follow': { type: 'follow', user: 'ChickenWhisperer' },
|
|
||||||
'sub-new': { type: 'sub', user: 'PixelPotato', tier: '1000', prime: false, months: 1, duration: 1 },
|
|
||||||
'sub-prime': { type: 'sub', user: 'LurkingLynx', tier: '1000', prime: true, months: 1, duration: 1 },
|
|
||||||
'sub-resub': { type: 'sub', user: 'ChickenWhisperer', tier: '1000', prime: false, months: 14, duration: 1, message: 'still here for the chickens and the chaos' },
|
|
||||||
'sub-3': { type: 'sub', user: 'BobTheBuilder99', tier: '1000', prime: false, months: 3, duration: 3 },
|
|
||||||
'sub-6': { type: 'sub', user: 'xX_Lurker_Xx', tier: '1000', prime: false, months: 6, duration: 6 },
|
|
||||||
'gift-1': { type: 'gift', user: 'PixelPotato', total: 1, recipient: 'ChickenWhisperer', tier: '1000' },
|
|
||||||
'gift-10': { type: 'gift', user: 'BobTheBuilder99', total: 10, tier: '1000' },
|
|
||||||
'gift-anon': { type: 'gift', user: null, total: 5, tier: '1000' },
|
|
||||||
'streak': { type: 'streak', user: 'LurkingLynx', streak: 5 },
|
|
||||||
'raid': { type: 'raid', user: 'CozyStreamer', viewers: 42 },
|
|
||||||
'bits-3': { type: 'bits', user: 'PixelPotato', bits: 3 },
|
|
||||||
'bits-20': { type: 'bits', user: 'PixelPotato', bits: 20 },
|
|
||||||
'bits-60': { type: 'bits', user: 'ChickenWhisperer', bits: 60 },
|
|
||||||
'bits-80': { type: 'bits', user: 'BobTheBuilder99', bits: 80, message: 'we do a little trolling' },
|
|
||||||
'bits-120': { type: 'bits', user: 'LurkingLynx', bits: 120 },
|
|
||||||
'bits-200': { type: 'bits', user: 'xX_Lurker_Xx', bits: 200, message: 'RUN' },
|
|
||||||
'bits-500': { type: 'bits', user: 'BobTheBuilder99', bits: 500, message: 'Tom da Tank says hi' },
|
|
||||||
'hype-begin':{ type: 'hype', phase: 'begin', level: 1, golden: false },
|
|
||||||
'hype-level':{ type: 'hype', phase: 'level', level: 3, golden: false },
|
|
||||||
'hype-end': { type: 'hype', phase: 'end', level: 4, golden: false, top: ['ChickenWhisperer', 'PixelPotato', 'LurkingLynx'] },
|
|
||||||
'hype-golden':{ type: 'hype', phase: 'begin', level: 1, golden: true },
|
|
||||||
'tip-5': { type: 'tip', user: 'PixelPotato', amount: 5, currency: 'EUR', message: 'for the hydration fund' },
|
|
||||||
'tip-25': { type: 'tip', user: 'ChickenWhisperer', amount: 25, currency: 'EUR', message: 'great stream today, have a coffee on me ♡' },
|
|
||||||
'tip-100': { type: 'tip', user: 'BobTheBuilder99', amount: 100, currency: 'USD', message: null },
|
|
||||||
};
|
|
||||||
|
|
||||||
const TEST_KEYS = [...Object.keys(SAMPLES), 'queue-test', 'poll-test', 'hype-bar-test', 'raid-card-test'];
|
|
||||||
|
|
||||||
// fake Hype Train bar: starts at level 1, fills up, levels up twice, ends
|
|
||||||
let hypeTimers = [];
|
|
||||||
function testHypeBar() {
|
|
||||||
hypeTimers.forEach(clearTimeout); hypeTimers = [];
|
|
||||||
const t = { id: 'test-' + Date.now(), level: 1, progress: 0, goal: 1000, total: 0, type: 'regular' };
|
|
||||||
const send = phase => sendHypeBar(phase, { ...t, expires_at: new Date(Date.now() + 300000).toISOString() });
|
|
||||||
send('begin');
|
|
||||||
for (let i = 1; i <= 12; i++) hypeTimers.push(setTimeout(() => {
|
|
||||||
t.progress += 300; t.total += 300;
|
|
||||||
if (t.progress >= t.goal) { t.progress -= t.goal; t.level++; t.goal += 500; }
|
|
||||||
send('progress');
|
|
||||||
}, i * 800));
|
|
||||||
hypeTimers.push(setTimeout(() => send('end'), 11000));
|
|
||||||
}
|
|
||||||
|
|
||||||
// fake poll: begins, votes come in over ~9 s, then it ends with a winner
|
|
||||||
let pollTimers = [];
|
|
||||||
function testPoll() {
|
|
||||||
pollTimers.forEach(clearTimeout); pollTimers = [];
|
|
||||||
const ends = new Date(Date.now() + 10000).toISOString();
|
|
||||||
const poll = { id: 'test-' + Date.now(), title: 'Which map next?', ends_at: ends, status: null,
|
|
||||||
choices: [{ id: 'a', title: 'Customs', votes: 0 }, { id: 'b', title: 'Woods', votes: 0 }, { id: 'c', title: 'Reserve', votes: 0 }, { id: 'd', title: 'Factory (chaos)', votes: 0 }] };
|
|
||||||
const send = phase => ws.broadcast({ type: 'poll', phase, poll: JSON.parse(JSON.stringify(poll)) });
|
|
||||||
send('begin');
|
|
||||||
for (let i = 1; i <= 8; i++) pollTimers.push(setTimeout(() => {
|
|
||||||
poll.choices.forEach((c, k) => { c.votes += Math.floor(Math.random() * (k === 2 ? 6 : 4)); });
|
|
||||||
send('progress');
|
|
||||||
}, i * 1000));
|
|
||||||
pollTimers.push(setTimeout(() => { poll.status = 'completed'; send('end'); }, 10000));
|
|
||||||
}
|
|
||||||
|
|
||||||
function sendTestAlert(alert) {
|
|
||||||
ws.broadcast({ type: 'alert', alert: { ...alert, test: true } });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test alerts go straight to the overlay; they are not logged and do not fire actions.
|
|
||||||
// test:true replaces another test alert at once (fast checking) but never cuts off a real alert;
|
|
||||||
// 'queue-test' sends four alerts that queue like real ones.
|
|
||||||
function sendTest(key) {
|
|
||||||
if (key === 'poll-test') { testPoll(); return true; }
|
|
||||||
if (key === 'hype-bar-test') { testHypeBar(); return true; }
|
|
||||||
if (key === 'raid-card-test') { // countdown card, then "raid sent" after 12 s
|
|
||||||
raidCard('start', { target: 'CozyStreamer', avatar: null, viewers: 42, started_at: new Date().toISOString() });
|
|
||||||
setTimeout(() => raidCard('done', { target: 'CozyStreamer', avatar: null, viewers: 42 }), 12000);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (key === 'queue-test') {
|
|
||||||
ws.broadcast({ type: 'alert', alert: { ...SAMPLES['follow'], test: true } });
|
|
||||||
for (const k of ['bits-60', 'gift-10', 'streak']) ws.broadcast({ type: 'alert', alert: { ...SAMPLES[k], test: 'queue' } });
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
const alert = SAMPLES[key];
|
|
||||||
if (!alert) return false;
|
|
||||||
ws.broadcast({ type: 'alert', alert: { ...alert, test: true } });
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { raidTarget, send, sendTest, sendTestAlert, sendPoll, sendHypeBar, raidStarted, raidCancelled, raidHappened, getPendingRaid, fromHypeTrain, fromTip, SAMPLES, TEST_KEYS, fromFollow, fromCheer, fromBitsUse, fromChatNotification, fromOverlayNotice };
|
|
||||||
34
src/app.js
34
src/app.js
|
|
@ -22,8 +22,7 @@ app.use((req, res, next) => {
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
// redirect:false: /media (the uploads folder) must not bounce to /media/ before the Media page route
|
app.use(express.static(path.join(__dirname, '../public')));
|
||||||
app.use(express.static(path.join(__dirname, '../public'), { redirect: false }));
|
|
||||||
app.use(express.urlencoded({ extended: true }));
|
app.use(express.urlencoded({ extended: true }));
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
|
|
@ -48,33 +47,12 @@ function requireAuth(req, res, next) {
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Public stats page: on its own host (Settings → Public stats page) ONLY that page is served (anything else 404s,
|
|
||||||
// the admin pages never answer there); on the admin host it is at /public as well.
|
|
||||||
const publicStats = require('./routers/public');
|
|
||||||
const db = require('./db');
|
|
||||||
const adminHost = (() => { try { return new URL(process.env.APP_BASE_URL).hostname; } catch { return ''; } })();
|
|
||||||
app.use((req, res, next) => {
|
|
||||||
const host = String(db.getSettings()?.public_stats_host || '').toLowerCase();
|
|
||||||
if (!host || req.hostname !== host || host === adminHost) return next(); // never lock the admin host out
|
|
||||||
publicStats(req, res, () => res.status(404).send('Not found'));
|
|
||||||
});
|
|
||||||
app.use('/public', publicStats);
|
|
||||||
|
|
||||||
app.use('/auth', require('./routers/auth'));
|
app.use('/auth', require('./routers/auth'));
|
||||||
app.use('/overlay', require('./routers/overlay'));
|
app.use('/overlay', require('./routers/overlay'));
|
||||||
app.use('/ext', require('./routers/ext').router); // HUDFX / Blerp pages served inside the overlay (public, under the overlay id)
|
app.use('/actions', requireAuth, require('./routers/actions'));
|
||||||
// Now playing (Feishin) is switched off for now; uncomment to bring it back (see views/overlay.ejs).
|
app.use('/media', requireAuth, require('./routers/media'));
|
||||||
// app.use('/nowplaying', require('./routers/nowplaying')); // key-protected push from the PC helper
|
app.use('/layout', requireAuth, require('./routers/layout'));
|
||||||
// sections with a left sidebar (src/nav.js): Actions = Redeems / Alerts / TTS voices / Media, and Settings
|
app.use('/settings', requireAuth, require('./routers/settings'));
|
||||||
const { section } = require('./nav');
|
app.use('/', requireAuth, require('./routers/dashboard'));
|
||||||
app.get('/actions', requireAuth, (req, res) => res.redirect('/redeems'));
|
|
||||||
app.use('/actions/alerts', requireAuth, section('actions'), require('./routers/alertsetup'));
|
|
||||||
app.use('/redeems', requireAuth, section('actions'), require('./routers/redeems'));
|
|
||||||
app.use('/tts', requireAuth, section('actions'), require('./routers/tts'));
|
|
||||||
app.use('/media', requireAuth, section('actions'), require('./routers/media'));
|
|
||||||
app.use('/settings', requireAuth, section('settings'), require('./routers/settings'));
|
|
||||||
app.use('/stats', requireAuth, (req, res, next) => { res.locals.navActive = 'stats'; next(); }, require('./routers/stats'));
|
|
||||||
app.use('/alerts', requireAuth, require('./routers/alerts')); // test / skip / raid (POST)
|
|
||||||
app.use('/', requireAuth, (req, res, next) => { res.locals.navActive = 'dashboard'; next(); }, require('./routers/dashboard'));
|
|
||||||
|
|
||||||
module.exports = app;
|
module.exports = app;
|
||||||
|
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
// Settings → Backup: the whole setup as one JSON file (settings, alert theme, redeem variations, TTS voices).
|
|
||||||
// Not included: media files, statistics, secrets (Twitch tokens live in users; se_jwt is left out).
|
|
||||||
const db = require('./db');
|
|
||||||
|
|
||||||
const VERSION = 1;
|
|
||||||
const SKIP_SETTINGS = ['id', 'overlay_id', 'se_jwt', 'tts_blocklist_seeded'];
|
|
||||||
|
|
||||||
function exportAll() {
|
|
||||||
const d = db.raw();
|
|
||||||
const settings = { ...db.getSettings() };
|
|
||||||
for (const k of SKIP_SETTINGS) delete settings[k];
|
|
||||||
return {
|
|
||||||
heystreamer_backup: VERSION, exported_at: new Date().toISOString(),
|
|
||||||
settings,
|
|
||||||
variations: d.prepare('SELECT * FROM reward_variations ORDER BY id').all().map(({ id, created_at, ...v }) => v),
|
|
||||||
tts_voices: d.prepare('SELECT id, name, config FROM tts_voices ORDER BY id').all(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// replaces settings (known columns only), variations and TTS voices; keeps statistics, users, media rows
|
|
||||||
function importAll(data) {
|
|
||||||
if (!data || data.heystreamer_backup !== VERSION) throw new Error('not a HeyStreamer backup file');
|
|
||||||
const d = db.raw();
|
|
||||||
const cols = new Set(d.prepare('PRAGMA table_info(settings)').all().map(c => c.name));
|
|
||||||
const vcols = new Set(d.prepare('PRAGMA table_info(reward_variations)').all().map(c => c.name));
|
|
||||||
const settings = Object.fromEntries(Object.entries(data.settings || {}).filter(([k]) => cols.has(k) && !SKIP_SETTINGS.includes(k)));
|
|
||||||
d.transaction(() => {
|
|
||||||
if (Object.keys(settings).length) db.updateSettings(settings);
|
|
||||||
// TTS voices keep their ids, so variations still point at the right voice
|
|
||||||
d.prepare('DELETE FROM tts_voices').run();
|
|
||||||
const tv = d.prepare('INSERT INTO tts_voices (id, name, config) VALUES (?, ?, ?)');
|
|
||||||
for (const v of data.tts_voices || []) tv.run(v.id, String(v.name || 'voice'), typeof v.config === 'string' ? v.config : JSON.stringify(v.config || {}));
|
|
||||||
d.prepare('DELETE FROM reward_variations').run();
|
|
||||||
for (const v of data.variations || []) {
|
|
||||||
const row = Object.fromEntries(Object.entries(v).filter(([k]) => vcols.has(k) && k !== 'id'));
|
|
||||||
const keys = Object.keys(row);
|
|
||||||
if (!keys.length) continue;
|
|
||||||
d.prepare(`INSERT INTO reward_variations (${keys.join(', ')}) VALUES (${keys.map(k => '@' + k).join(', ')})`).run(row);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
return { settings: Object.keys(settings).length, variations: (data.variations || []).length, voices: (data.tts_voices || []).length };
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { exportAll, importAll };
|
|
||||||
225
src/chatlog.js
225
src/chatlog.js
|
|
@ -1,225 +0,0 @@
|
||||||
// Chat statistics. Every chat message (EventSub channel.chat.message, read on the server) is counted right away
|
|
||||||
// into per-viewer totals; the raw message is only a 30-day buffer.
|
|
||||||
//
|
|
||||||
// chat_user per viewer: messages, first/last seen
|
|
||||||
// chat_user_day per viewer per day: messages (activity over time)
|
|
||||||
// chat_emote per viewer per emote: uses (Twitch emotes from the message, 7TV channel + global by name)
|
|
||||||
// chat_command per viewer per !command: uses, last used
|
|
||||||
// chat_raw the messages themselves, deleted after RAW_DAYS
|
|
||||||
// chat_action per viewer per action + item: uses, total spent (points / bits / subs / viewers / tip money),
|
|
||||||
// from every event that goes through dispatch.js (rewards, Power-ups, cheers, subs, gifts,
|
|
||||||
// follows, raids, watch streaks, tips). Keyed by Twitch user id, or 'name:<login>' when the
|
|
||||||
// event has none (StreamElements tips, watch streaks).
|
|
||||||
// These are lifetime totals (points and levels come from them). The same events also go to periodstats.js per day
|
|
||||||
// and per stream, for the stream / week / month / year views. !hideme / !showme toggle the public-page opt-out.
|
|
||||||
//
|
|
||||||
// Moderation: a deleted message, a timeout/ban (clear_user_messages) or a chat clear removes the stored text at
|
|
||||||
// once (Twitch developer rules); the counts stay, they hold no message content.
|
|
||||||
// Accounts in Settings → Hidden chatters (bots) ARE counted, but statistics pages / leaderboards must leave them
|
|
||||||
// out when showing data: use isHidden(login) / hiddenUsers() there (changing the list then applies at once).
|
|
||||||
const db = require('./db');
|
|
||||||
|
|
||||||
const RAW_DAYS = 30;
|
|
||||||
const SCORE_GAP_MS = 5 * 60 * 1000; // point system: a message earns points only 5 min after the viewer's last one that did
|
|
||||||
let ready = false;
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
if (ready) return;
|
|
||||||
db.raw().exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_raw (
|
|
||||||
id TEXT PRIMARY KEY, -- Twitch message id
|
|
||||||
at TEXT NOT NULL, -- ISO time
|
|
||||||
user_id TEXT NOT NULL, user_login TEXT, user_name TEXT,
|
|
||||||
text TEXT, emotes TEXT, -- emotes: JSON [name, ...] as counted
|
|
||||||
command TEXT,
|
|
||||||
first_msg INTEGER DEFAULT 0
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS chat_raw_at ON chat_raw(at);
|
|
||||||
CREATE INDEX IF NOT EXISTS chat_raw_user ON chat_raw(user_id);
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_user (
|
|
||||||
user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT,
|
|
||||||
messages INTEGER DEFAULT 0, first_seen TEXT, last_seen TEXT
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_user_day (
|
|
||||||
user_id TEXT NOT NULL, day TEXT NOT NULL, messages INTEGER DEFAULT 0,
|
|
||||||
PRIMARY KEY (user_id, day)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_emote (
|
|
||||||
user_id TEXT NOT NULL, emote TEXT NOT NULL, -- emote name as typed
|
|
||||||
source TEXT, emote_id TEXT, uses INTEGER DEFAULT 0, last_used TEXT,
|
|
||||||
PRIMARY KEY (user_id, emote)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_action (
|
|
||||||
user_key TEXT NOT NULL, -- Twitch user id, or 'name:<login>'
|
|
||||||
user_login TEXT, user_name TEXT,
|
|
||||||
action TEXT NOT NULL, -- channel_points, custom_power_up, bits, sub, gift_sub, follow, raid, tip, ...
|
|
||||||
item TEXT NOT NULL DEFAULT '', -- reward / Power-up title, sub tier, ...
|
|
||||||
uses INTEGER DEFAULT 0, amount REAL DEFAULT 0, unit TEXT,
|
|
||||||
first_at TEXT, last_at TEXT,
|
|
||||||
PRIMARY KEY (user_key, action, item)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_badges ( -- latest chat badges per viewer (roles, sub months), from their last message
|
|
||||||
user_id TEXT PRIMARY KEY, badges TEXT, sub_months INTEGER, at TEXT
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS chat_command (
|
|
||||||
user_id TEXT NOT NULL, command TEXT NOT NULL, uses INTEGER DEFAULT 0, last_used TEXT,
|
|
||||||
PRIMARY KEY (user_id, command)
|
|
||||||
);
|
|
||||||
`);
|
|
||||||
// point-system columns (added after the first version): points-eligible messages, first-ever-message flag
|
|
||||||
const cols = db.raw().prepare('PRAGMA table_info(chat_user)').all().map(c => c.name);
|
|
||||||
for (const [c, def] of [['scored', 'INTEGER DEFAULT 0'], ['last_scored', 'TEXT'], ['intro', 'INTEGER DEFAULT 0']]) {
|
|
||||||
if (!cols.includes(c)) db.raw().exec(`ALTER TABLE chat_user ADD COLUMN ${c} ${def}`);
|
|
||||||
}
|
|
||||||
const dcols = db.raw().prepare('PRAGMA table_info(chat_user_day)').all().map(c => c.name);
|
|
||||||
if (!dcols.includes('scored')) db.raw().exec('ALTER TABLE chat_user_day ADD COLUMN scored INTEGER DEFAULT 0');
|
|
||||||
ready = true;
|
|
||||||
setInterval(prune, 60 * 60 * 1000).unref();
|
|
||||||
prune();
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 7TV emotes (channel set + global), refreshed every hour; Twitch emotes come marked in the message ---
|
|
||||||
let seventv = new Map(), seventvAt = 0;
|
|
||||||
async function load7tv(twitchId) {
|
|
||||||
if (Date.now() - seventvAt < 60 * 60 * 1000) return;
|
|
||||||
seventvAt = Date.now();
|
|
||||||
const next = new Map();
|
|
||||||
const add = set => { for (const e of set?.emotes || []) next.set(e.name, e.id); };
|
|
||||||
try { const r = await fetch('https://7tv.io/v3/emote-sets/global'); if (r.ok) add(await r.json()); } catch {}
|
|
||||||
try { const r = await fetch(`https://7tv.io/v3/users/twitch/${encodeURIComponent(twitchId)}`); if (r.ok) add((await r.json()).emote_set); } catch {}
|
|
||||||
if (next.size) seventv = next;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Settings → Hidden chatters: counted, but left out of shown statistics and leaderboards
|
|
||||||
function hiddenUsers() {
|
|
||||||
return String(db.getSettings().chat_hidden_users || '').toLowerCase().split(/[\s,]+/).filter(Boolean);
|
|
||||||
}
|
|
||||||
const isHidden = login => hiddenUsers().includes(String(login || '').toLowerCase());
|
|
||||||
|
|
||||||
// one chat message: count it, keep the raw copy
|
|
||||||
function onMessage(e) {
|
|
||||||
init();
|
|
||||||
if (e.broadcaster_user_id) load7tv(e.broadcaster_user_id).catch(() => {});
|
|
||||||
const login = String(e.chatter_user_login || '').toLowerCase();
|
|
||||||
if (!e.chatter_user_id) return;
|
|
||||||
const text = String(e.message?.text || '');
|
|
||||||
const at = new Date().toISOString(), day = at.slice(0, 10);
|
|
||||||
|
|
||||||
// emotes: Twitch ones are marked by Twitch; any other word that is a 7TV emote counts too
|
|
||||||
const emotes = [];
|
|
||||||
for (const f of e.message?.fragments || []) {
|
|
||||||
if (f.type === 'emote') emotes.push({ name: f.text, source: 'twitch', id: f.emote?.id || null });
|
|
||||||
else if (f.type === 'text') for (const w of f.text.split(/\s+/)) if (w && seventv.has(w)) emotes.push({ name: w, source: '7tv', id: seventv.get(w) });
|
|
||||||
}
|
|
||||||
const m = /^\s*!(\w[\w-]{0,30})/.exec(text);
|
|
||||||
const command = m ? '!' + m[1].toLowerCase() : null;
|
|
||||||
|
|
||||||
const d = db.raw();
|
|
||||||
d.transaction(() => {
|
|
||||||
d.prepare(`INSERT OR IGNORE INTO chat_raw (id, at, user_id, user_login, user_name, text, emotes, command, first_msg)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
||||||
.run(e.message_id, at, e.chatter_user_id, login, e.chatter_user_name || login, text,
|
|
||||||
JSON.stringify(emotes.map(x => x.name)), command, e.message_type === 'user_intro' ? 1 : 0);
|
|
||||||
d.prepare(`INSERT INTO chat_user (user_id, user_login, user_name, messages, first_seen, last_seen) VALUES (?, ?, ?, 1, ?, ?)
|
|
||||||
ON CONFLICT(user_id) DO UPDATE SET messages = messages + 1, user_login = excluded.user_login,
|
|
||||||
user_name = excluded.user_name, last_seen = excluded.last_seen`)
|
|
||||||
.run(e.chatter_user_id, login, e.chatter_user_name || login, at, at);
|
|
||||||
// points-eligible: at least SCORE_GAP_MS since this viewer's last eligible message
|
|
||||||
const prev = d.prepare('SELECT last_scored FROM chat_user WHERE user_id = ?').get(e.chatter_user_id);
|
|
||||||
const scored = !prev?.last_scored || Date.parse(at) - Date.parse(prev.last_scored) >= SCORE_GAP_MS ? 1 : 0;
|
|
||||||
if (scored) d.prepare('UPDATE chat_user SET scored = scored + 1, last_scored = ? WHERE user_id = ?').run(at, e.chatter_user_id);
|
|
||||||
if (e.message_type === 'user_intro') d.prepare('UPDATE chat_user SET intro = 1 WHERE user_id = ?').run(e.chatter_user_id);
|
|
||||||
require('./watchtime').checkin(e.chatter_user_id); // first message of this stream = check-in
|
|
||||||
// badges: moderator / vip / subscriber (info = months) / founder / artist-badge / ...
|
|
||||||
const badges = (e.badges || []).map(b => ({ set: b.set_id, id: b.id, info: b.info || '' }));
|
|
||||||
const subB = badges.find(b => b.set === 'subscriber' || b.set === 'founder');
|
|
||||||
d.prepare('INSERT OR REPLACE INTO chat_badges (user_id, badges, sub_months, at) VALUES (?, ?, ?, ?)')
|
|
||||||
.run(e.chatter_user_id, JSON.stringify(badges), subB && /^\d+$/.test(subB.info) ? +subB.info : null, at);
|
|
||||||
d.prepare(`INSERT INTO chat_user_day (user_id, day, messages, scored) VALUES (?, ?, 1, ?)
|
|
||||||
ON CONFLICT(user_id, day) DO UPDATE SET messages = messages + 1, scored = scored + excluded.scored`).run(e.chatter_user_id, day, scored);
|
|
||||||
const em = d.prepare(`INSERT INTO chat_emote (user_id, emote, source, emote_id, uses, last_used) VALUES (?, ?, ?, ?, 1, ?)
|
|
||||||
ON CONFLICT(user_id, emote) DO UPDATE SET uses = uses + 1, last_used = excluded.last_used`);
|
|
||||||
for (const x of emotes) em.run(e.chatter_user_id, x.name, x.source, x.id, at);
|
|
||||||
if (command) d.prepare(`INSERT INTO chat_command (user_id, command, uses, last_used) VALUES (?, ?, 1, ?)
|
|
||||||
ON CONFLICT(user_id, command) DO UPDATE SET uses = uses + 1, last_used = excluded.last_used`)
|
|
||||||
.run(e.chatter_user_id, command, at);
|
|
||||||
|
|
||||||
// per day + per stream (periodstats.js: stream / week / month / year statistics)
|
|
||||||
const ps = require('./periodstats');
|
|
||||||
const who = { key: e.chatter_user_id, login, name: e.chatter_user_name || login };
|
|
||||||
const rows = [{ ...who, kind: 'message', amount: scored }];
|
|
||||||
if (e.message_type === 'user_intro') rows.push({ ...who, kind: 'intro' });
|
|
||||||
for (const x of emotes) { rows.push({ ...who, kind: 'emote', item: x.name }); ps.emoteSeen(x.name, x.source, x.id); }
|
|
||||||
if (command) rows.push({ ...who, kind: 'command', item: command });
|
|
||||||
ps.add(rows, at);
|
|
||||||
// public stats page: viewers can leave it (still counted, never named) and come back
|
|
||||||
if (command === '!hideme' || command === '!showme') ps.setOptout(e.chatter_user_id, login, command === '!hideme');
|
|
||||||
})();
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- viewer actions (called by dispatch.js for every logged event) ---
|
|
||||||
const TIER = { 1000: 'Tier 1', 2000: 'Tier 2', 3000: 'Tier 3' };
|
|
||||||
function actionOf(eventType, detail, data, a) {
|
|
||||||
const { AUTO_REWARDS, POWER_UPS } = require('./redeems');
|
|
||||||
const d = data || {};
|
|
||||||
switch (eventType) {
|
|
||||||
case 'channel_points': return { item: d.reward?.title || detail, amount: d.reward?.cost, unit: 'points' };
|
|
||||||
case 'auto_reward': return { item: AUTO_REWARDS[d.reward?.type] || d.reward?.type || detail, amount: d.reward?.channel_points, unit: 'points' };
|
|
||||||
case 'power_up': return { item: POWER_UPS[d.power_up?.type] || d.power_up?.type || detail, amount: d.bits, unit: 'bits' };
|
|
||||||
case 'custom_power_up': return { item: d.custom_power_up?.title || detail, amount: d.custom_power_up?.bits, unit: 'bits' };
|
|
||||||
case 'bits': return { item: 'cheer', amount: d.bits ?? a?.bits, unit: 'bits' };
|
|
||||||
case 'sub': return { item: a?.prime ? 'Prime' : TIER[a?.tier] || 'sub', amount: a?.duration || 1, unit: 'months' };
|
|
||||||
case 'gift_sub': return { item: TIER[a?.tier] || 'gift subs', amount: a?.total || 1, unit: 'subs' };
|
|
||||||
case 'follow': return { item: 'follow', amount: 0, unit: null };
|
|
||||||
case 'raid': return { item: 'raid', amount: a?.viewers, unit: 'viewers' };
|
|
||||||
case 'watch_streak': return { item: 'watch streak', amount: a?.streak, unit: 'streak', max: true };
|
|
||||||
case 'tip': return { item: 'tip', amount: a?.amount, unit: a?.currency || null };
|
|
||||||
default: return null; // polls, hype train, raid out, legacy commands: no single viewer
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function onAction(eventType, detail, username, data, replay) {
|
|
||||||
init();
|
|
||||||
const a = replay?.type === 'alert' ? replay.alert : null;
|
|
||||||
const act = actionOf(eventType, detail, data, a);
|
|
||||||
if (!act) return;
|
|
||||||
const d = data || {};
|
|
||||||
const id = d.user_id || d.chatter_user_id || null;
|
|
||||||
const login = String(d.user_login || d.chatter_user_login || username || a?.user || '').toLowerCase();
|
|
||||||
if (!id && !login) return; // anonymous gifts / cheers
|
|
||||||
const key = id ? String(id) : `name:${login}`;
|
|
||||||
const amount = Number(act.amount) || 0, at = new Date().toISOString();
|
|
||||||
db.raw().prepare(`INSERT INTO chat_action (user_key, user_login, user_name, action, item, uses, amount, unit, first_at, last_at)
|
|
||||||
VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?)
|
|
||||||
ON CONFLICT(user_key, action, item) DO UPDATE SET uses = uses + 1,
|
|
||||||
amount = ${act.max ? 'MAX(amount, excluded.amount)' : 'amount + excluded.amount'},
|
|
||||||
user_login = excluded.user_login, user_name = excluded.user_name, last_at = excluded.last_at`)
|
|
||||||
.run(key, login, d.user_name || d.chatter_user_name || username || login, eventType, String(act.item || ''), amount, act.unit, at, at);
|
|
||||||
require('./periodstats').add([{ key, login, name: d.user_name || d.chatter_user_name || username || login,
|
|
||||||
kind: 'action:' + eventType, item: act.item || '', amount, unit: act.unit }], at);
|
|
||||||
}
|
|
||||||
|
|
||||||
// moderation: remove stored message text (counts stay)
|
|
||||||
function onDelete(e) { init(); db.raw().prepare('DELETE FROM chat_raw WHERE id = ?').run(e.message_id); }
|
|
||||||
function onClearUser(e) { init(); db.raw().prepare('DELETE FROM chat_raw WHERE user_id = ?').run(e.target_user_id); }
|
|
||||||
function onClear() { init(); db.raw().prepare(`DELETE FROM chat_raw WHERE at >= ?`).run(new Date(Date.now() - 24 * 3600e3).toISOString()); }
|
|
||||||
|
|
||||||
function prune() {
|
|
||||||
const cut = new Date(Date.now() - RAW_DAYS * 24 * 3600e3).toISOString();
|
|
||||||
const n = db.raw().prepare('DELETE FROM chat_raw WHERE at < ?').run(cut).changes;
|
|
||||||
if (n) console.log(`[chatlog] pruned ${n} raw message(s) older than ${RAW_DAYS} days`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// removal request: forget a viewer completely (raw + counts)
|
|
||||||
function forgetUser(userIdOrLogin) {
|
|
||||||
init();
|
|
||||||
const d = db.raw();
|
|
||||||
const u = d.prepare('SELECT user_id FROM chat_user WHERE user_id = ? OR user_login = ?').get(String(userIdOrLogin), String(userIdOrLogin).toLowerCase());
|
|
||||||
const login = String(userIdOrLogin).toLowerCase();
|
|
||||||
if (u) require('./watchtime').forgetUser(u.user_id);
|
|
||||||
if (u) for (const t of ['chat_raw', 'chat_user', 'chat_user_day', 'chat_emote', 'chat_command', 'chat_badges']) d.prepare(`DELETE FROM ${t} WHERE user_id = ?`).run(u.user_id);
|
|
||||||
const n = d.prepare('DELETE FROM chat_action WHERE user_key = ? OR user_key = ? OR user_login = ?').run(u ? u.user_id : '-', `name:${login}`, login).changes;
|
|
||||||
require('./periodstats').forgetUser(u ? u.user_id : null, login);
|
|
||||||
return u || n ? 1 : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init, onMessage, onAction, onDelete, onClearUser, onClear, prune, forgetUser, hiddenUsers, isHidden, RAW_DAYS };
|
|
||||||
205
src/db.js
205
src/db.js
|
|
@ -10,10 +10,8 @@ function init() {
|
||||||
db.pragma('journal_mode = WAL');
|
db.pragma('journal_mode = WAL');
|
||||||
db.pragma('foreign_keys = ON');
|
db.pragma('foreign_keys = ON');
|
||||||
createSchema();
|
createSchema();
|
||||||
migrate();
|
|
||||||
seedSettings();
|
seedSettings();
|
||||||
seedTtsBlocklist();
|
seedLayout();
|
||||||
seedVariations();
|
|
||||||
console.log(`[db] Initialised — path: ${DB_PATH}`);
|
console.log(`[db] Initialised — path: ${DB_PATH}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -45,7 +43,6 @@ function createSchema() {
|
||||||
custom_js TEXT DEFAULT ''
|
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 (
|
CREATE TABLE IF NOT EXISTS overlay_layout (
|
||||||
id INTEGER PRIMARY KEY CHECK(id = 1),
|
id INTEGER PRIMARY KEY CHECK(id = 1),
|
||||||
chat_left REAL DEFAULT 2.0,
|
chat_left REAL DEFAULT 2.0,
|
||||||
|
|
@ -86,32 +83,6 @@ function createSchema() {
|
||||||
created_at TEXT DEFAULT (datetime('now'))
|
created_at TEXT DEFAULT (datetime('now'))
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Channel point rewards / built-in rewards / bits Power-ups: each trigger has variations,
|
|
||||||
-- one is picked at random weighted by rarity (like Twitch alert variations).
|
|
||||||
-- TTS voices built on the /tts page: config is JSON (layers + effects, see src/tts.js normalize()).
|
|
||||||
CREATE TABLE IF NOT EXISTS tts_voices (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
config TEXT NOT NULL,
|
|
||||||
created_at TEXT DEFAULT (datetime('now'))
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS reward_variations (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
kind TEXT NOT NULL, -- reward | auto_reward | power_up | custom_power_up
|
|
||||||
key TEXT NOT NULL, -- reward id / built-in reward type / power-up type
|
|
||||||
title TEXT NOT NULL, -- trigger name shown in the UI (last known)
|
|
||||||
name TEXT NOT NULL, -- variation name, shown on the polaroid
|
|
||||||
rarity TEXT NOT NULL DEFAULT 'common',
|
|
||||||
sound TEXT DEFAULT '', -- URL path under /public, '' = silent
|
|
||||||
volume REAL DEFAULT 0.8,
|
|
||||||
polaroid INTEGER DEFAULT 1, -- 0 = sound only
|
|
||||||
caption TEXT DEFAULT 'redeemed it! ♡', -- text after the viewer's name on the cassette strip
|
|
||||||
art TEXT DEFAULT '', -- file in /alerts/art, '' = default
|
|
||||||
enabled INTEGER DEFAULT 1,
|
|
||||||
created_at TEXT DEFAULT (datetime('now'))
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS activity_log (
|
CREATE TABLE IF NOT EXISTS activity_log (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
event_type TEXT NOT NULL,
|
event_type TEXT NOT NULL,
|
||||||
|
|
@ -124,46 +95,6 @@ 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'); // "<name> says: ..." before the message
|
|
||||||
addColumn('settings', 'tts_blocklist_seeded', 'INTEGER DEFAULT 0'); // starter list copied in once
|
|
||||||
addColumn('activity_log', 'replay_json', 'TEXT');
|
|
||||||
addColumn('settings', 'hudfx_overlay_url', "TEXT DEFAULT ''");
|
|
||||||
addColumn('settings', 'chat_hidden_users', "TEXT DEFAULT 'streamelements, nightbot, blerp, blerpbot, hudfx, hudfxbot, lumiastream'"); // never shown in the on-screen chat
|
|
||||||
addColumn('settings', 'chat_hide_commands', 'INTEGER DEFAULT 1'); // hide messages starting with !
|
|
||||||
addColumn('settings', 'alert_theme', "TEXT DEFAULT ''"); // Actions → Alerts (src/theme.js), JSON
|
|
||||||
addColumn('settings', 'se_jwt', "TEXT DEFAULT ''"); // StreamElements JWT (Settings → Connections); secret
|
|
||||||
addColumn('settings', 'timezone', "TEXT DEFAULT 'UTC'"); // times on the stats pages
|
|
||||||
addColumn('reward_variations', 'look', "TEXT DEFAULT ''"); // card | cassette ('' = cassette, older rows)
|
|
||||||
addColumn('settings', 'public_stats_enabled', 'INTEGER DEFAULT 0'); // public stats page on/off
|
|
||||||
addColumn('settings', 'public_stats_host', "TEXT DEFAULT ''"); // its own host name (DNS + certificate needed)
|
|
||||||
addColumn('reward_variations', 'video', "TEXT DEFAULT ''"); // URL of a video: full-screen on the ?parts=video overlay // HUDFX browser source URL, embedded with ?ext=hudfx // the overlay message that was shown (dashboard Replay)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put the starter TTS blocklist (src/tts-blocklist.txt) into the settings ONCE; after that it is the user's list
|
|
||||||
// (clearing or editing it in Settings is respected).
|
|
||||||
function seedTtsBlocklist() {
|
|
||||||
const s = db.prepare('SELECT tts_blocklist, tts_blocklist_seeded FROM settings WHERE id = 1').get();
|
|
||||||
if (!s || s.tts_blocklist_seeded) return;
|
|
||||||
const starter = require('fs').readFileSync(require('path').join(__dirname, 'tts-blocklist.txt'), 'utf8')
|
|
||||||
.split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
|
|
||||||
const mine = String(s.tts_blocklist || '').split(/[\n,]/).map(w => w.trim()).filter(Boolean);
|
|
||||||
const merged = [...mine, ...starter.filter(w => !mine.some(m => m.toLowerCase() === w.toLowerCase()))];
|
|
||||||
db.prepare('UPDATE settings SET tts_blocklist = ?, tts_blocklist_seeded = 1 WHERE id = 1').run(merged.join('\n'));
|
|
||||||
console.log(`[db] TTS blocklist: added ${merged.length - mine.length} starter words`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function seedSettings() {
|
function seedSettings() {
|
||||||
const row = db.prepare('SELECT id FROM settings WHERE id = 1').get();
|
const row = db.prepare('SELECT id FROM settings WHERE id = 1').get();
|
||||||
if (!row) {
|
if (!row) {
|
||||||
|
|
@ -173,13 +104,12 @@ function seedSettings() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function seedVariations() {
|
function seedLayout() {
|
||||||
if (db.prepare('SELECT COUNT(*) n FROM reward_variations').get().n > 0) return;
|
const row = db.prepare('SELECT id FROM overlay_layout WHERE id = 1').get();
|
||||||
const seed = require('./redeems-seed.json').variations; // Twitch's built-in rewards; the rest is made on Redeems
|
if (!row) {
|
||||||
const ins = db.prepare(`INSERT INTO reward_variations (kind, key, title, name, rarity, sound, volume, art, enabled, look)
|
db.prepare('INSERT INTO overlay_layout (id) VALUES (1)').run();
|
||||||
VALUES (@kind, @key, @title, @name, @rarity, @sound, @volume, @art, @enabled, @look)`);
|
console.log('[db] Created default layout row');
|
||||||
db.transaction(() => seed.forEach(v => ins.run({ ...v, volume: v.volume ?? 0.8, art: v.art || '', enabled: v.enabled === false ? 0 : 1, look: v.look || 'card' })))();
|
}
|
||||||
console.log(`[db] Loaded ${seed.length} default redeem variations`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Users
|
// Users
|
||||||
|
|
@ -200,31 +130,36 @@ function getUserById(id) {
|
||||||
return db.prepare('SELECT * FROM users WHERE id = ?').get(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
|
// Settings
|
||||||
function getSettings() {
|
function getSettings() {
|
||||||
return db.prepare('SELECT * FROM settings WHERE id = 1').get();
|
return db.prepare('SELECT * FROM settings WHERE id = 1').get();
|
||||||
}
|
}
|
||||||
|
|
||||||
// what overlay pages get: everything except server-only values (the overlay URL is public)
|
|
||||||
function getOverlaySettings() {
|
|
||||||
const { tts_blocklist, tts_blocklist_seeded, hudfx_overlay_url, se_jwt, alert_theme, ...rest } = getSettings();
|
|
||||||
return { ...rest, alert_theme: require('./theme').get() }; // the overlay gets the merged theme, never secrets
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateSettings(fields) {
|
function updateSettings(fields) {
|
||||||
const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', ');
|
const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', ');
|
||||||
db.prepare(`UPDATE settings SET ${cols} WHERE id = 1`).run(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
|
// Media
|
||||||
function getAllMedia() {
|
function getAllMedia() {
|
||||||
return db.prepare('SELECT * FROM media_files ORDER BY uploaded_at DESC').all();
|
return db.prepare('SELECT * FROM media_files ORDER BY uploaded_at DESC').all();
|
||||||
|
|
@ -288,76 +223,12 @@ function getMatchingActions(eventType, eventDetail) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Redeem variations
|
|
||||||
const VARIATION_FIELDS = ['name', 'rarity', 'sound', 'volume', 'polaroid', 'caption', 'art', 'enabled', 'tts_voice_id', 'video', 'look'];
|
|
||||||
|
|
||||||
function getAllVariations() {
|
|
||||||
return db.prepare('SELECT * FROM reward_variations ORDER BY kind, title, id').all();
|
|
||||||
}
|
|
||||||
|
|
||||||
function getVariationsFor(kind, key) {
|
|
||||||
return db.prepare('SELECT * FROM reward_variations WHERE kind = ? AND key = ? ORDER BY id').all(kind, key);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getVariation(id) {
|
|
||||||
return db.prepare('SELECT * FROM reward_variations WHERE id = ?').get(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createVariation({ kind, key, title, name, look = '' }) {
|
|
||||||
const r = db.prepare('INSERT INTO reward_variations (kind, key, title, name, look) VALUES (?, ?, ?, ?, ?)').run(kind, key, title, name, look);
|
|
||||||
return getVariation(r.lastInsertRowid);
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateVariation(id, fields) {
|
|
||||||
const f = Object.fromEntries(Object.entries(fields).filter(([k]) => VARIATION_FIELDS.includes(k)));
|
|
||||||
if (!Object.keys(f).length) return;
|
|
||||||
const cols = Object.keys(f).map(k => `${k} = @${k}`).join(', ');
|
|
||||||
db.prepare(`UPDATE reward_variations SET ${cols} WHERE id = @id`).run({ ...f, id });
|
|
||||||
}
|
|
||||||
|
|
||||||
// keep the trigger name current when Twitch reports a renamed reward
|
|
||||||
function renameTrigger(kind, key, title) {
|
|
||||||
db.prepare('UPDATE reward_variations SET title = ? WHERE kind = ? AND key = ? AND title != ?').run(title, kind, key, title);
|
|
||||||
}
|
|
||||||
|
|
||||||
function deleteVariation(id) {
|
|
||||||
db.prepare('DELETE FROM reward_variations WHERE id = ?').run(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
// TTS voices (config is stored as JSON text, returned parsed)
|
|
||||||
const ttsRow = r => r && { ...r, config: JSON.parse(r.config) };
|
|
||||||
|
|
||||||
function getAllTtsVoices() {
|
|
||||||
return db.prepare('SELECT * FROM tts_voices ORDER BY name COLLATE NOCASE, id').all().map(ttsRow);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getTtsVoice(id) {
|
|
||||||
return ttsRow(db.prepare('SELECT * FROM tts_voices WHERE id = ?').get(id));
|
|
||||||
}
|
|
||||||
|
|
||||||
function createTtsVoice(name, config) {
|
|
||||||
const r = db.prepare('INSERT INTO tts_voices (name, config) VALUES (?, ?)').run(name, JSON.stringify(config));
|
|
||||||
return getTtsVoice(r.lastInsertRowid);
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateTtsVoice(id, name, config) {
|
|
||||||
db.prepare('UPDATE tts_voices SET name = ?, config = ? WHERE id = ?').run(name, JSON.stringify(config), id);
|
|
||||||
}
|
|
||||||
|
|
||||||
function deleteTtsVoice(id) {
|
|
||||||
db.transaction(() => {
|
|
||||||
db.prepare('UPDATE reward_variations SET tts_voice_id = NULL WHERE tts_voice_id = ?').run(id);
|
|
||||||
db.prepare('DELETE FROM tts_voices WHERE id = ?').run(id);
|
|
||||||
})();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Activity log
|
// Activity log
|
||||||
function logActivity(eventType, eventDetail, username, data, actionsFired, replay = null) {
|
function logActivity(eventType, eventDetail, username, data, actionsFired) {
|
||||||
db.prepare(`
|
db.prepare(`
|
||||||
INSERT INTO activity_log (event_type, event_detail, username, data_json, actions_fired, replay_json)
|
INSERT INTO activity_log (event_type, event_detail, username, data_json, actions_fired)
|
||||||
VALUES (@event_type, @event_detail, @username, @data_json, @actions_fired, @replay_json)
|
VALUES (@event_type, @event_detail, @username, @data_json, @actions_fired)
|
||||||
`).run({
|
`).run({
|
||||||
replay_json: replay ? JSON.stringify(replay) : null,
|
|
||||||
event_type: eventType,
|
event_type: eventType,
|
||||||
event_detail: eventDetail || null,
|
event_detail: eventDetail || null,
|
||||||
username: username || null,
|
username: username || null,
|
||||||
|
|
@ -367,21 +238,15 @@ function logActivity(eventType, eventDetail, username, data, actionsFired, repla
|
||||||
}
|
}
|
||||||
|
|
||||||
function getActivityLog(limit = 50) {
|
function getActivityLog(limit = 50) {
|
||||||
return db.prepare('SELECT * FROM activity_log ORDER BY created_at DESC, id DESC LIMIT ?').all(limit);
|
return db.prepare('SELECT * FROM activity_log ORDER BY created_at DESC LIMIT ?').all(limit);
|
||||||
}
|
|
||||||
|
|
||||||
function getActivity(id) {
|
|
||||||
return db.prepare('SELECT * FROM activity_log WHERE id = ?').get(id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
init,
|
init,
|
||||||
upsertUser, getUserById, getPrimaryUser, updateUserTokens,
|
upsertUser, getUserById,
|
||||||
getSettings, getOverlaySettings, updateSettings,
|
getSettings, updateSettings,
|
||||||
|
getLayout, updateLayout, updateLayoutPositions,
|
||||||
getAllMedia, getMediaFile, createMedia, deleteMedia,
|
getAllMedia, getMediaFile, createMedia, deleteMedia,
|
||||||
getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions,
|
getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions,
|
||||||
getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation,
|
logActivity, getActivityLog,
|
||||||
getAllTtsVoices, getTtsVoice, createTtsVoice, updateTtsVoice, deleteTtsVoice,
|
|
||||||
logActivity, getActivityLog, getActivity,
|
|
||||||
raw: () => db, // for modules that keep their own tables (chatlog.js)
|
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,7 @@ const db = require('./db');
|
||||||
const ws = require('./ws');
|
const ws = require('./ws');
|
||||||
const { isOnCooldown, setCooldown } = require('./cooldowns');
|
const { isOnCooldown, setCooldown } = require('./cooldowns');
|
||||||
|
|
||||||
// replay: the overlay message that was shown for this event, stored so the dashboard can play it again
|
function dispatchEvent(eventType, eventDetail = null, username = null, data = null) {
|
||||||
function dispatchEvent(eventType, eventDetail = null, username = null, data = null, replay = null) {
|
|
||||||
const actions = db.getMatchingActions(eventType, eventDetail);
|
const actions = db.getMatchingActions(eventType, eventDetail);
|
||||||
let fired = 0;
|
let fired = 0;
|
||||||
|
|
||||||
|
|
@ -32,12 +31,7 @@ function dispatchEvent(eventType, eventDetail = null, username = null, data = nu
|
||||||
console.log(`[dispatch] Fired action ${action.id} (${action.name}) — event: ${eventType}, user: ${username}`);
|
console.log(`[dispatch] Fired action ${action.id} (${action.name}) — event: ${eventType}, user: ${username}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// the log must never take the server down (a bad row once crashed it mid-stream)
|
db.logActivity(eventType, eventDetail, username, data, fired);
|
||||||
try { db.logActivity(eventType || 'unknown', eventDetail, username, data, fired, replay); }
|
|
||||||
catch (e) { console.error(`[dispatch] activity log failed (${eventType}):`, e.message); }
|
|
||||||
// per-viewer action statistics (chatlog.js)
|
|
||||||
try { require('./chatlog').onAction(eventType, eventDetail, username, data, replay); }
|
|
||||||
catch (e) { console.error(`[dispatch] action stats failed (${eventType}):`, e.message); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { dispatchEvent };
|
module.exports = { dispatchEvent };
|
||||||
|
|
|
||||||
271
src/eventsub.js
271
src/eventsub.js
|
|
@ -1,267 +1,118 @@
|
||||||
// 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 { WebSocket } = require('ws');
|
||||||
const twitch = require('./twitch');
|
const dispatch = require('./dispatch');
|
||||||
const alerts = require('./alerts');
|
|
||||||
const redeems = require('./redeems');
|
|
||||||
const chatlog = require('./chatlog');
|
|
||||||
const watchtime = require('./watchtime');
|
|
||||||
|
|
||||||
const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws';
|
const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws';
|
||||||
|
const CLIENT_ID = process.env.TWITCH_CLIENT_ID;
|
||||||
|
|
||||||
let ws = null;
|
let ws = null;
|
||||||
let shouldRun = false;
|
let shouldRun = false;
|
||||||
let broadcasterId = null;
|
let sessionId = null;
|
||||||
let keepaliveMs = 30_000;
|
let _accessToken = null;
|
||||||
let watchdog = null;
|
let _broadcasterId = null;
|
||||||
let reconnectTimer = null;
|
|
||||||
const status = { connected: false, sessionId: null, subscribed: [], failed: [], lastEventAt: null };
|
|
||||||
|
|
||||||
function start(user) {
|
function start(accessToken, broadcasterId) {
|
||||||
twitch.setUser(user);
|
_accessToken = accessToken;
|
||||||
broadcasterId = user.twitch_id;
|
_broadcasterId = broadcasterId;
|
||||||
shouldRun = true;
|
shouldRun = true;
|
||||||
console.log(`[eventsub] Starting — broadcaster: ${user.login} (${broadcasterId})`);
|
connect();
|
||||||
closeSocket(ws);
|
console.log(`[eventsub] Starting — broadcaster: ${broadcasterId}, base_url: ${process.env.APP_BASE_URL}`);
|
||||||
connect(EVENTSUB_URL, true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function stop() {
|
function stop() {
|
||||||
shouldRun = false;
|
shouldRun = false;
|
||||||
clearTimeout(reconnectTimer);
|
if (ws) ws.close();
|
||||||
clearTimeout(watchdog);
|
|
||||||
closeSocket(ws);
|
|
||||||
ws = null;
|
|
||||||
status.connected = false;
|
|
||||||
console.log('[eventsub] Stopped');
|
console.log('[eventsub] Stopped');
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeSocket(sock) {
|
function connect() {
|
||||||
if (!sock) return;
|
console.log('[eventsub] Connecting...');
|
||||||
sock.removeAllListeners('close'); // a deliberate close must not trigger the auto-reconnect
|
ws = new WebSocket(EVENTSUB_URL);
|
||||||
sock.on('error', () => {});
|
|
||||||
try { sock.close(); } catch { /* already closed */ }
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleReconnect(delay = 10_000) {
|
ws.on('open', () => console.log('[eventsub] Connected to Twitch EventSub'));
|
||||||
clearTimeout(reconnectTimer);
|
ws.on('message', (raw) => handleMessage(JSON.parse(raw)));
|
||||||
if (!shouldRun) return;
|
ws.on('close', () => {
|
||||||
reconnectTimer = setTimeout(() => connect(EVENTSUB_URL, true), delay);
|
console.log('[eventsub] Disconnected');
|
||||||
}
|
if (shouldRun) setTimeout(connect, 10_000);
|
||||||
|
|
||||||
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 => {
|
ws.on('error', (e) => console.error('[eventsub] Error:', e.message));
|
||||||
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) {
|
async function handleMessage(msg) {
|
||||||
const type = msg.metadata?.message_type;
|
const type = msg.metadata?.message_type;
|
||||||
if (sock === ws || type === 'session_welcome') armWatchdog();
|
if (type === 'session_welcome') {
|
||||||
|
sessionId = msg.payload.session.id;
|
||||||
switch (type) {
|
console.log('[eventsub] Session established:', sessionId);
|
||||||
case 'session_welcome': {
|
await subscribeAll();
|
||||||
const s = msg.payload.session;
|
} else if (type === 'session_reconnect') {
|
||||||
keepaliveMs = (s.keepalive_timeout_seconds || 10) * 1000;
|
console.log('[eventsub] Reconnect requested');
|
||||||
if (!fresh) { // handover from session_reconnect: swap sockets
|
ws.close();
|
||||||
const old = ws;
|
} else if (type === 'notification') {
|
||||||
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);
|
handleNotification(msg.payload);
|
||||||
break;
|
|
||||||
case 'revocation':
|
|
||||||
console.warn(`[eventsub] Subscription revoked: ${msg.payload.subscription.type} (${msg.payload.subscription.status})`);
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function subscribeAll(sessionId) {
|
async function subscribeAll() {
|
||||||
const b = broadcasterId;
|
|
||||||
const subs = [
|
const subs = [
|
||||||
{ type: 'channel.follow', version: '2', condition: { broadcaster_user_id: b, moderator_user_id: b } },
|
{ type: 'channel.subscribe', version: '1', condition: { broadcaster_user_id: _broadcasterId } },
|
||||||
// cheers AND bits Power-ups (message effect, celebration, gigantify); replaces channel.cheer
|
{ type: 'channel.subscription.message', version: '1', condition: { broadcaster_user_id: _broadcasterId } },
|
||||||
{ type: 'channel.bits.use', version: '1', condition: { broadcaster_user_id: b } },
|
{ type: 'channel.subscription.gift', version: '1', condition: { broadcaster_user_id: _broadcasterId } },
|
||||||
// Custom Power-ups (bits, made on Twitch): redeem variations, e.g. full-screen videos
|
{ type: 'channel.cheer', version: '1', condition: { broadcaster_user_id: _broadcasterId } },
|
||||||
{ type: 'channel.custom_power_up_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
|
{ type: 'channel.channel_points_custom_reward_redemption.add',version: '1', condition: { broadcaster_user_id: _broadcasterId } },
|
||||||
// subs, resubs, gifts, community gifts, raids, with Prime/multi-month/recipient/message details
|
{ type: 'channel.follow', version: '2', condition: { broadcaster_user_id: _broadcasterId, moderator_user_id: _broadcasterId } },
|
||||||
{ type: 'channel.chat.notification', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
{ type: 'channel.raid', version: '1', condition: { to_broadcaster_user_id: _broadcasterId } },
|
||||||
// watch time (watchtime.js): live state for the 5-minute ticks and per-stream check-ins
|
|
||||||
{ type: 'stream.online', version: '1', condition: { broadcaster_user_id: b } },
|
|
||||||
{ type: 'stream.offline', version: '1', condition: { broadcaster_user_id: b } },
|
|
||||||
// title / category changes (stream history, viewer graph markers); no scope needed
|
|
||||||
{ type: 'channel.update', version: '2', condition: { broadcaster_user_id: b } },
|
|
||||||
// chat statistics (chatlog.js): every message, plus deletes / timeouts+bans / clears to drop stored text
|
|
||||||
{ type: 'channel.chat.message', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
|
||||||
{ type: 'channel.chat.message_delete', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
|
||||||
{ type: 'channel.chat.clear_user_messages', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
|
||||||
{ type: 'channel.chat.clear', version: '1', condition: { broadcaster_user_id: b, user_id: b } },
|
|
||||||
{ type: 'channel.channel_points_custom_reward_redemption.add', version: '1', condition: { broadcaster_user_id: b } },
|
|
||||||
// built-in rewards: highlight message, unlock emote, ...
|
|
||||||
{ type: 'channel.channel_points_automatic_reward_redemption.add', version: '2', condition: { broadcaster_user_id: b } },
|
|
||||||
// live poll card on the overlay
|
|
||||||
{ type: 'channel.poll.begin', version: '1', condition: { broadcaster_user_id: b } },
|
|
||||||
{ type: 'channel.poll.progress', version: '1', condition: { broadcaster_user_id: b } },
|
|
||||||
{ type: 'channel.poll.end', version: '1', condition: { broadcaster_user_id: b } },
|
|
||||||
// outgoing raid: send-off card (incoming raids come through channel.chat.notification)
|
|
||||||
{ type: 'channel.raid', version: '1', condition: { from_broadcaster_user_id: b } },
|
|
||||||
// Hype Train alerts (start, level up, end)
|
|
||||||
{ type: 'channel.hype_train.begin', version: '2', condition: { broadcaster_user_id: b } },
|
|
||||||
{ type: 'channel.hype_train.progress', version: '2', condition: { broadcaster_user_id: b } },
|
|
||||||
{ type: 'channel.hype_train.end', version: '2', condition: { broadcaster_user_id: b } },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
try { await twitch.validate(); } catch (e) { console.error('[eventsub]', e.message); }
|
|
||||||
|
|
||||||
watchtime.checkLive(); // restarted mid-stream: pick up the running stream
|
|
||||||
|
|
||||||
status.subscribed = [];
|
|
||||||
status.failed = [];
|
|
||||||
for (const sub of subs) {
|
for (const sub of subs) {
|
||||||
try {
|
try {
|
||||||
const res = await twitch.helix('/eventsub/subscriptions', {
|
const res = await fetch('https://api.twitch.tv/helix/eventsub/subscriptions', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: { ...sub, transport: { method: 'websocket', session_id: sessionId } },
|
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) {
|
if (res.status === 202) {
|
||||||
status.subscribed.push(sub.type);
|
|
||||||
console.log(`[eventsub] Subscribed: ${sub.type}`);
|
console.log(`[eventsub] Subscribed: ${sub.type}`);
|
||||||
} else {
|
} else {
|
||||||
const body = await res.text();
|
const body = await res.text();
|
||||||
status.failed.push(`${sub.type} (${res.status})`);
|
|
||||||
console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`);
|
console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
status.failed.push(`${sub.type} (${e.message})`);
|
|
||||||
console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message);
|
console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleNotification(payload) {
|
function handleNotification(payload) {
|
||||||
const type = payload.subscription.type;
|
const sub = payload.subscription;
|
||||||
const event = payload.event;
|
const event = payload.event;
|
||||||
|
const username = event.user_login || event.from_broadcaster_user_login || null;
|
||||||
|
|
||||||
switch (type) {
|
console.log(`[eventsub] Notification: ${sub.type} — user: ${username}`);
|
||||||
case 'channel.follow':
|
|
||||||
alerts.send(alerts.fromFollow(event), event);
|
switch (sub.type) {
|
||||||
|
case 'channel.subscribe':
|
||||||
|
case 'channel.subscription.message':
|
||||||
|
dispatch.dispatchEvent('sub', event.tier, username, event);
|
||||||
break;
|
break;
|
||||||
case 'channel.bits.use':
|
case 'channel.subscription.gift':
|
||||||
if (event.type === 'power_up' && event.power_up?.type) {
|
dispatch.dispatchEvent('gift_sub', event.tier, username, event);
|
||||||
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;
|
break;
|
||||||
case 'channel.chat.notification': {
|
case 'channel.cheer':
|
||||||
const alert = alerts.fromChatNotification(event);
|
dispatch.dispatchEvent('bits', String(event.bits), username, event);
|
||||||
if (alert) alerts.send(alert, event);
|
|
||||||
else console.log(`[eventsub] chat notification ${event.notice_type} — no alert`);
|
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
case 'channel.channel_points_custom_reward_redemption.add':
|
case 'channel.channel_points_custom_reward_redemption.add':
|
||||||
redeems.handle('reward', event.reward.id, event.reward.title,
|
dispatch.dispatchEvent('channel_points', event.reward?.id, username, event);
|
||||||
{ user: event.user_name || event.user_login, input: event.user_input || null }, event);
|
|
||||||
break;
|
break;
|
||||||
case 'channel.poll.begin':
|
case 'channel.follow':
|
||||||
case 'channel.poll.progress':
|
dispatch.dispatchEvent('follow', null, username, event);
|
||||||
case 'channel.poll.end':
|
|
||||||
alerts.sendPoll(type.split('.').pop(), event);
|
|
||||||
break;
|
break;
|
||||||
case 'channel.hype_train.begin':
|
|
||||||
case 'channel.hype_train.progress':
|
|
||||||
case 'channel.hype_train.end': {
|
|
||||||
const phase = type.split('.').pop();
|
|
||||||
alerts.sendHypeBar(phase, event); // persistent progress bar
|
|
||||||
const alert = alerts.fromHypeTrain(phase, event); // queued alert on start / new level / end
|
|
||||||
if (alert) alerts.send(alert, event);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'stream.online':
|
|
||||||
watchtime.online(event.id, event.started_at);
|
|
||||||
break;
|
|
||||||
case 'stream.offline':
|
|
||||||
watchtime.offline();
|
|
||||||
break;
|
|
||||||
case 'channel.update':
|
|
||||||
try { watchtime.channelUpdate(event.title, event.category_name); } catch (e) { console.error('[watchtime]', e.message); }
|
|
||||||
break;
|
|
||||||
case 'channel.chat.message':
|
|
||||||
try { chatlog.onMessage(event); } catch (e) { console.error('[chatlog]', e.message); }
|
|
||||||
break;
|
|
||||||
case 'channel.chat.message_delete':
|
|
||||||
try { chatlog.onDelete(event); } catch (e) { console.error('[chatlog]', e.message); }
|
|
||||||
break;
|
|
||||||
case 'channel.chat.clear_user_messages':
|
|
||||||
try { chatlog.onClearUser(event); } catch (e) { console.error('[chatlog]', e.message); }
|
|
||||||
break;
|
|
||||||
case 'channel.chat.clear':
|
|
||||||
try { chatlog.onClear(event); } catch (e) { console.error('[chatlog]', e.message); }
|
|
||||||
break;
|
|
||||||
case 'channel.custom_power_up_redemption.add': {
|
|
||||||
const p = event.custom_power_up || {};
|
|
||||||
if (p.id) redeems.handle('custom_power_up', p.id, p.title || 'Custom Power-up',
|
|
||||||
{ user: event.user_name || event.user_login, input: event.user_input || null, bits: p.bits ?? null }, event);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'channel.raid':
|
case 'channel.raid':
|
||||||
if (event.from_broadcaster_user_id === broadcasterId) alerts.raidHappened(event).catch(e => console.error('[alerts] raid out:', e.message));
|
dispatch.dispatchEvent('raid', null, username, event);
|
||||||
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;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
function getStatus() { return { ...status, running: shouldRun }; }
|
module.exports = { start, stop };
|
||||||
|
|
||||||
module.exports = { start, stop, getStatus };
|
|
||||||
|
|
|
||||||
|
|
@ -1,157 +0,0 @@
|
||||||
/* Blerp: OBS browser source → Properties → Custom CSS (source 1920x1080, covering the whole canvas in OBS).
|
|
||||||
Looks like HeyStreamer's redeem tapes: pastel shell with screws, lined label with a SIDE A band, handwritten
|
|
||||||
title, reel window, a paper strip underneath ("<name> shared!") and the Blerp logo as the sticker.
|
|
||||||
The sound's own picture sits in the reel window. Built only from Blerp's own elements; its swing-in stays. */
|
|
||||||
@import url('https://fonts.googleapis.com/css2?family=Caveat:wght@600;700&family=Nunito:wght@800;900&display=swap');
|
|
||||||
|
|
||||||
body { background-color: rgba(0, 0, 0, 0); margin: 0 auto; overflow: hidden; }
|
|
||||||
|
|
||||||
/* --- position: top-left corner 85,110, 440px wide (same spot and size as the other alerts) --- */
|
|
||||||
#blerp-alert-wrapper { justify-content: flex-start !important; align-items: flex-start !important; }
|
|
||||||
#blerp-generic-template {
|
|
||||||
width: auto !important; min-height: 0 !important; overflow: visible !important;
|
|
||||||
margin: 110px 0 0 85px !important; transform-origin: left top !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --- the shell (drawn at 540x346, zoomed to 440 wide) --- */
|
|
||||||
.blerpOuterBackground {
|
|
||||||
--shell: #ffd3dc; --shell2: #ffc1cd; --edge: #c8284f; --band: #fe295c; --bandtxt: #ffffff;
|
|
||||||
--ink: #3a2a20; --red: #b74347; --window: #3b2f45;
|
|
||||||
zoom: 0.815;
|
|
||||||
position: relative !important; width: 540px !important; height: 346px !important;
|
|
||||||
border: 3px solid var(--edge) !important; border-radius: 24px !important; overflow: visible !important;
|
|
||||||
box-shadow: 0 14px 22px rgba(0, 0, 0, .45) !important;
|
|
||||||
background:
|
|
||||||
/* screws */
|
|
||||||
radial-gradient(circle at 20px 20px, #fff 0 3px, var(--edge) 3px 5px, #0000 6px),
|
|
||||||
radial-gradient(circle at 514px 20px, #fff 0 3px, var(--edge) 3px 5px, #0000 6px),
|
|
||||||
radial-gradient(circle at 20px 318px, #fff 0 3px, var(--edge) 3px 5px, #0000 6px),
|
|
||||||
radial-gradient(circle at 514px 318px, #fff 0 3px, var(--edge) 3px 5px, #0000 6px),
|
|
||||||
/* lined label */
|
|
||||||
repeating-linear-gradient(#0000 0 25px, rgba(110, 130, 170, .22) 25px 26px) 42px 70px / 454px 160px no-repeat,
|
|
||||||
linear-gradient(#fffdf6, #fffdf6) 42px 30px / 454px 200px no-repeat,
|
|
||||||
linear-gradient(var(--shell), var(--shell2)) !important;
|
|
||||||
}
|
|
||||||
/* bottom part with the drive holes */
|
|
||||||
.blerpOuterBackground::before {
|
|
||||||
content: ""; position: absolute; left: 118px; right: 118px; bottom: -3px; height: 86px;
|
|
||||||
clip-path: polygon(9% 0, 91% 0, 100% 100%, 0 100%);
|
|
||||||
background:
|
|
||||||
radial-gradient(circle at 22% 55%, var(--window) 0 8px, #0000 9px),
|
|
||||||
radial-gradient(circle at 34% 55%, var(--window) 0 8px, #0000 9px),
|
|
||||||
linear-gradient(var(--window), var(--window)) 50% 52% / 28px 24px no-repeat,
|
|
||||||
radial-gradient(circle at 66% 55%, var(--window) 0 8px, #0000 9px),
|
|
||||||
radial-gradient(circle at 78% 55%, var(--window) 0 8px, #0000 9px),
|
|
||||||
#ffadbf;
|
|
||||||
}
|
|
||||||
/* Blerp logo sticker, top-right corner, white outline like the redeem stickers */
|
|
||||||
.blerpOuterBackground::after {
|
|
||||||
content: ""; position: absolute; right: -44px; top: -40px; width: 112px; height: 104px; z-index: 3;
|
|
||||||
background: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2244.716%22%20height%3D%2241.642%22%20viewBox%3D%220%200%2044.716%2041.642%22%3E%20%20%20%3Cg%20id%3D%22BlerpIconRed%22%20transform%3D%22translate%28-145.998%20-27%29%22%3E%20%20%20%20%20%3Cpath%20id%3D%22Path_1731%22%20data-name%3D%22Path%201731%22%20d%3D%22M37.36%2C17.914c-.91-4.766%2C3.258-8.281.4-11.831-3.881-4.815-8.637%2C1.76-12.993-.133C21.935%2C4.718%2C19.1.565%2C14.924%2C2.083s-3.683%2C6.526-5.038%2C9.285C7.751%2C15.62-.12%2C13.642%2C0%2C19.827c.094%2C4.558%2C5.542%2C4.573%2C7.91%2C8.805S4.814%2C38%2C9.728%2C42.05c5.953%2C4.914%2C11.974-5.072%2C17.2-6.986h0c5.211-1.9%2C16.266%2C1.913%2C17.67-5.705C45.745%2C23.1%2C38.25%2C22.606%2C37.36%2C17.914ZM24.021%2C27.09a9.068%2C9.068%2C0%2C0%2C1-10.308-3.461%2C1.483%2C1.483%2C0%2C0%2C1%2C1.043-2.358%2C29.169%2C29.169%2C0%2C0%2C0%2C6.556-1.587%2C29.342%2C29.342%2C0%2C0%2C0%2C6.046-3%2C1.483%2C1.483%2C0%2C0%2C1%2C2.3%2C1.1A9.062%2C9.062%2C0%2C0%2C1%2C24.021%2C27.09Z%22%20transform%3D%22translate%28146.001%2025.246%29%22%20fill%3D%22%23fe295c%22%2F%3E%20%20%20%3C%2Fg%3E%20%3C%2Fsvg%3E%20") center / contain no-repeat;
|
|
||||||
transform: rotate(10deg);
|
|
||||||
filter: drop-shadow(4px 0 0 #fff) drop-shadow(-4px 0 0 #fff) drop-shadow(0 4px 0 #fff) drop-shadow(0 -4px 0 #fff) drop-shadow(0 6px 9px rgba(0,0,0,.35));
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --- the label (holds everything else) --- */
|
|
||||||
.alertNewPill {
|
|
||||||
position: absolute !important; left: 42px; top: 30px; width: 454px !important; height: 200px !important;
|
|
||||||
box-sizing: border-box !important; padding: 0 !important; display: block !important;
|
|
||||||
background: transparent !important; overflow: visible !important;
|
|
||||||
}
|
|
||||||
/* SIDE A band */
|
|
||||||
.alertNewPill::before, .alertNewPill::after {
|
|
||||||
position: absolute; top: 0; height: 40px; font: 900 19px/40px 'Nunito', sans-serif; letter-spacing: 2.5px; color: var(--bandtxt);
|
|
||||||
}
|
|
||||||
.alertNewPill::before { content: "SIDE A"; left: 0; right: 0; padding-left: 20px; background: var(--band); border-radius: 6px 6px 0 0; }
|
|
||||||
.alertNewPill::after { content: "★ BLERP"; right: 70px; }
|
|
||||||
|
|
||||||
.innerBackgroundText { position: absolute !important; inset: 0; display: block !important; overflow: visible !important; padding: 0 !important; }
|
|
||||||
/* reel window with two white reels */
|
|
||||||
.innerBackgroundText::before {
|
|
||||||
content: ""; position: absolute; left: 82px; top: 92px; width: 290px; height: 82px; border-radius: 41px;
|
|
||||||
border: 3px solid var(--edge); box-sizing: border-box;
|
|
||||||
background:
|
|
||||||
radial-gradient(circle at 62px 38px, var(--window) 0 6px, #fff 7px 13px, #d9d2ca 13px 16px, #fff 16px 25px, #cfc6bd 25px 27px, #5a4036 28px 33px, #0000 34px),
|
|
||||||
radial-gradient(circle at 222px 38px, var(--window) 0 6px, #fff 7px 13px, #d9d2ca 13px 16px, #fff 16px 25px, #cfc6bd 25px 27px, #5a4036 28px 33px, #0000 34px),
|
|
||||||
var(--window);
|
|
||||||
}
|
|
||||||
/* small caption under the window */
|
|
||||||
.innerBackgroundText::after {
|
|
||||||
content: "Blerp sound"; position: absolute; left: 0; right: 0; top: 176px; text-align: center;
|
|
||||||
font: 700 27px/1 'Caveat', cursive; color: #7a6656;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* the sound's picture: a sticker in the bottom-right corner (where the redeem tapes have theirs):
|
|
||||||
thick white border, softly rounded, one corner curling up */
|
|
||||||
#innerBackgroundImage {
|
|
||||||
position: absolute !important; left: 392px; top: 188px; z-index: 5;
|
|
||||||
width: 150px !important; height: 150px !important; margin: 0 !important; padding: 8px !important;
|
|
||||||
border: none !important; border-radius: 16px 16px 26px 16px !important; background: #fff !important; box-sizing: border-box !important;
|
|
||||||
box-shadow: 0 7px 12px rgba(0, 0, 0, .35), 0 1px 2px rgba(0, 0, 0, .25) !important;
|
|
||||||
overflow: hidden !important;
|
|
||||||
}
|
|
||||||
#innerBackgroundImageReal { width: 134px !important; height: 134px !important; border-radius: 10px 10px 18px 10px !important; object-fit: cover; }
|
|
||||||
/* curled corner, bottom right */
|
|
||||||
#innerBackgroundImage::after {
|
|
||||||
content: ""; position: absolute; right: 0; bottom: 0; width: 34px; height: 34px;
|
|
||||||
background: linear-gradient(135deg, rgba(0, 0, 0, .18) 0%, #f4f0ea 46%, #fff 50%, #0000 51%);
|
|
||||||
border-top-left-radius: 10px; box-shadow: -2px -2px 4px rgba(0, 0, 0, .12);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* title: the sound name, handwritten on the label */
|
|
||||||
#secondary-alert-text {
|
|
||||||
position: absolute !important; left: 24px; right: 24px; top: 42px; width: auto !important; height: auto !important;
|
|
||||||
text-align: center !important; font-family: 'Caveat', cursive !important; font-weight: 700 !important;
|
|
||||||
font-size: 48px !important; line-height: 1 !important; color: var(--ink) !important;
|
|
||||||
white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* "<name> shared!" on a taped paper strip under the tape */
|
|
||||||
#main-alert-text {
|
|
||||||
position: absolute !important; left: -6px; top: 318px; width: auto !important; height: auto !important; max-width: 470px;
|
|
||||||
padding: 10px 28px 12px !important; background: #fffdf7; transform: rotate(-2deg);
|
|
||||||
box-shadow: 0 6px 14px rgba(0, 0, 0, .35); z-index: 4;
|
|
||||||
font-family: 'Caveat', cursive !important; font-weight: 700 !important; font-size: 38px !important; line-height: 1.05 !important;
|
|
||||||
color: var(--red) !important; white-space: nowrap !important; overflow: visible !important; margin: 0 !important; min-width: 0 !important;
|
|
||||||
}
|
|
||||||
#main-alert-text::before, #main-alert-text::after {
|
|
||||||
content: ""; position: absolute; top: -12px; width: 86px; height: 28px;
|
|
||||||
background: rgba(201, 182, 228, .85); background-image: repeating-linear-gradient(45deg, #fff6 0 8px, #0000 8px 16px);
|
|
||||||
}
|
|
||||||
#main-alert-text::before { left: -26px; transform: rotate(-28deg); }
|
|
||||||
#main-alert-text::after { right: -26px; transform: rotate(24deg); }
|
|
||||||
|
|
||||||
/* --- motion: same as HeyStreamer's tapes (public/alerts/cassette.js) --- */
|
|
||||||
/* Blerp's own entrance ("swing") off; its exit animation stays */
|
|
||||||
@keyframes swing { from { transform: none; } to { transform: none; } }
|
|
||||||
/* Blerp fades the text in after a delay: show it with the tape */
|
|
||||||
.innerBackgroundText { opacity: 1 !important; transition: none !important; }
|
|
||||||
|
|
||||||
/* tape slides in from the left with a little overshoot, settles tilted; then bobs while the sound plays */
|
|
||||||
.blerpOuterBackground { animation: hs-tape-in 700ms cubic-bezier(.2, .8, .3, 1) both, hs-bob 420ms ease-in-out 700ms 12; }
|
|
||||||
@keyframes hs-tape-in {
|
|
||||||
0% { transform: translateX(-620px) rotate(-14deg); opacity: 0; }
|
|
||||||
72% { transform: translateX(18px) rotate(0deg); opacity: 1; }
|
|
||||||
88% { transform: translateX(-4px) rotate(-2.6deg); }
|
|
||||||
100% { transform: translateX(0) rotate(-2deg); opacity: 1; }
|
|
||||||
}
|
|
||||||
@keyframes hs-bob { 0%, 100% { translate: 0 0; } 50% { translate: 0 -2px; } }
|
|
||||||
/* stickers pop in: the picture like the redeem sticker, the logo just after */
|
|
||||||
#innerBackgroundImage { animation: hs-img-in 380ms ease-out 650ms both; }
|
|
||||||
@keyframes hs-img-in {
|
|
||||||
0% { transform: rotate(-22deg) scale(0); opacity: 0; }
|
|
||||||
60% { transform: rotate(14deg) scale(1.2); opacity: 1; }
|
|
||||||
100% { transform: rotate(7deg) scale(1); opacity: 1; }
|
|
||||||
}
|
|
||||||
.blerpOuterBackground::after { animation: hs-stk-in 380ms ease-out 780ms both; }
|
|
||||||
@keyframes hs-stk-in {
|
|
||||||
0% { transform: rotate(-30deg) scale(0); opacity: 0; }
|
|
||||||
60% { transform: rotate(18deg) scale(1.2); opacity: 1; }
|
|
||||||
100% { transform: rotate(10deg) scale(1); opacity: 1; }
|
|
||||||
}
|
|
||||||
/* paper strip drops in */
|
|
||||||
#main-alert-text { animation: hs-strip-in 320ms cubic-bezier(.3, .7, .4, 1) 850ms both; }
|
|
||||||
@keyframes hs-strip-in {
|
|
||||||
0% { transform: translateY(-20px) rotate(-6deg) scale(1.1); opacity: 0; }
|
|
||||||
100% { transform: translateY(0) rotate(-2deg) scale(1); opacity: 1; }
|
|
||||||
}
|
|
||||||
|
|
@ -1,68 +0,0 @@
|
||||||
/* HUDFX: OBS browser source → Properties → Custom CSS (source 2560x1440).
|
|
||||||
The notification as a camcorder viewfinder in HUDFX colours: scanlines, corner brackets, ● REC, timecode, VCR text.
|
|
||||||
Built only from HUDFX's own elements (.alert-inner-container …); full-screen effect videos are untouched. */
|
|
||||||
@import url('https://fonts.googleapis.com/css2?family=VT323&display=swap');
|
|
||||||
|
|
||||||
body { background-color: rgba(0, 0, 0, 0); margin: 0 auto; overflow: hidden; }
|
|
||||||
|
|
||||||
div.alert-contain > div.alert-inner-container.branded {
|
|
||||||
--purple: #734ffe; --lilac: #b9a6ff; --navy: #1c1f2f;
|
|
||||||
width: 440px !important; height: auto !important; min-height: 250px !important;
|
|
||||||
padding: 58px 26px 30px !important;
|
|
||||||
border: 6px solid var(--purple) !important; border-radius: 14px !important;
|
|
||||||
box-shadow: 0 0 0 3px #0e0f18, 0 0 26px rgba(115, 79, 254, .6), 0 14px 26px rgba(0, 0, 0, .5) !important;
|
|
||||||
background:
|
|
||||||
/* corner brackets */
|
|
||||||
linear-gradient(#fff, #fff) 14px 14px / 30px 4px no-repeat, linear-gradient(#fff, #fff) 14px 14px / 4px 30px no-repeat,
|
|
||||||
linear-gradient(#fff, #fff) right 14px top 14px / 30px 4px no-repeat, linear-gradient(#fff, #fff) right 14px top 14px / 4px 30px no-repeat,
|
|
||||||
linear-gradient(#fff, #fff) left 14px bottom 14px / 30px 4px no-repeat, linear-gradient(#fff, #fff) left 14px bottom 14px / 4px 30px no-repeat,
|
|
||||||
linear-gradient(#fff, #fff) right 14px bottom 14px / 30px 4px no-repeat, linear-gradient(#fff, #fff) right 14px bottom 14px / 4px 30px no-repeat,
|
|
||||||
/* scanlines + a soft purple glow on the screen */
|
|
||||||
repeating-linear-gradient(0deg, rgba(255, 255, 255, .045) 0 2px, transparent 2px 4px),
|
|
||||||
radial-gradient(ellipse at 50% 45%, #2b2550 0%, #1c1f2f 70%) #1c1f2f !important;
|
|
||||||
background-color: #1c1f2f !important; /* solid screen, never see-through */
|
|
||||||
animation: hfx-jitter 3.2s steps(1) infinite;
|
|
||||||
}
|
|
||||||
/* ● REC (blinking) and timecode */
|
|
||||||
div.alert-contain > div.alert-inner-container.branded::before {
|
|
||||||
content: "● REC"; position: absolute; left: 28px; top: 20px;
|
|
||||||
font: 30px/1 'VT323', monospace; color: #ff3b4e; letter-spacing: 1px; text-shadow: 0 0 6px rgba(255, 59, 78, .7);
|
|
||||||
animation: hfx-blink 1s steps(1) infinite;
|
|
||||||
}
|
|
||||||
div.alert-contain > div.alert-inner-container.branded::after {
|
|
||||||
content: "▶ 0:00:13"; position: absolute; right: 28px; top: 20px;
|
|
||||||
font: 26px/1 'VT323', monospace; color: #fff; opacity: .85;
|
|
||||||
}
|
|
||||||
|
|
||||||
.alert-media-contain { display: none !important; } /* little avatar badge on the top edge */
|
|
||||||
|
|
||||||
/* "Triggered <effect>" + viewer name: VCR text with a slight colour split */
|
|
||||||
.alert-text-contain pre {
|
|
||||||
font-family: 'VT323', monospace !important; font-weight: 400 !important;
|
|
||||||
font-size: 40px !important; line-height: 1 !important; text-transform: uppercase;
|
|
||||||
color: #fff !important; white-space: pre-wrap !important; text-align: center !important; margin: 0 !important;
|
|
||||||
text-shadow: 2px 0 rgba(255, 59, 120, .75), -2px 0 rgba(80, 220, 255, .75) !important;
|
|
||||||
}
|
|
||||||
.alert-text-contain .animate__pulse pre { color: var(--lilac) !important; font-size: 36px !important; margin-top: 10px !important; }
|
|
||||||
|
|
||||||
/* "50 bits" as the tape label strip */
|
|
||||||
.alert-amount-contain {
|
|
||||||
background: var(--purple) !important; border-radius: 4px !important; height: auto !important;
|
|
||||||
padding: 4px 18px !important; margin-top: 18px !important; box-shadow: 0 0 12px rgba(115, 79, 254, .7) !important;
|
|
||||||
}
|
|
||||||
.alert-amount-contain pre { font-family: 'VT323', monospace !important; font-size: 30px !important; color: #fff !important; text-transform: uppercase; }
|
|
||||||
|
|
||||||
.branded-logo-contain { opacity: .6; transform: translate(-30px, -12px); }
|
|
||||||
|
|
||||||
@keyframes hfx-blink { 0% { opacity: 1; } 50% { opacity: 0; } }
|
|
||||||
@keyframes hfx-jitter { 0%, 100% { transform: none; } 92% { transform: translateX(2px) skewX(-1deg); } 94% { transform: translateX(-2px); } 96% { transform: none; } }
|
|
||||||
|
|
||||||
/* Put the box where HeyStreamer's own alerts appear (top left: 85,110 on the 1920x1080 overlay, 440px wide).
|
|
||||||
This page is 2560x1440 shown at 75%, so: scale 1.45 makes the box ~440px wide on the overlay, and the layer
|
|
||||||
position puts its top-left corner at 85,110. #BCOvP… is the alert layer's id in this HUDFX overlay's settings;
|
|
||||||
:has() catches it if that id ever changes. */
|
|
||||||
#BCOvPCnfVtwksnH8vmgmm,
|
|
||||||
.overlay-layer:has(.alert-contain) {
|
|
||||||
left: 44px !important; top: 46px !important;
|
|
||||||
transform: scale(1.45) !important; transform-origin: 0 0 !important;
|
|
||||||
}
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
// Every media file HeyStreamer can use, in one list: the built-in library under public/alerts (shipped with
|
|
||||||
// the code) and uploads from the Media page (public/media, kept only on the server, listed in media_files).
|
|
||||||
// Used by the Media page and by the Redeems pickers, so both always show the same files.
|
|
||||||
// { url, label, type: 'audio' | 'video' | 'image', source: 'library' | 'upload', id?, size, file }
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const db = require('./db');
|
|
||||||
|
|
||||||
const PUBLIC = path.join(__dirname, '..', 'public');
|
|
||||||
const RE = { audio: /\.(mp3|wav|ogg|m4a)$/i, video: /\.(webm|mp4|mov)$/i, image: /\.(png|webp|gif|jpe?g)$/i };
|
|
||||||
|
|
||||||
// built-in folders, in the order they are listed
|
|
||||||
const DIRS = [
|
|
||||||
{ dir: 'alerts/videos', type: 'video' },
|
|
||||||
{ dir: 'alerts/sounds/redeems', type: 'audio', note: 'normalized' },
|
|
||||||
{ dir: 'alerts/sounds', type: 'audio' },
|
|
||||||
{ dir: 'alerts/stickers', type: 'image' },
|
|
||||||
{ dir: 'alerts/art', type: 'image' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const pretty = f => f.replace(/\.\w+$/, '').replace(/_Contrast$/, '').replace(/[_]+/g, ' ');
|
|
||||||
|
|
||||||
function typeOf(mime, name) {
|
|
||||||
if (/^video\//.test(mime) || RE.video.test(name)) return 'video';
|
|
||||||
if (/^audio\//.test(mime) || RE.audio.test(name)) return 'audio';
|
|
||||||
if (/^image\/(png|webp|gif|jpeg)$/.test(mime) || RE.image.test(name)) return 'image';
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function list() {
|
|
||||||
const out = [];
|
|
||||||
for (const d of DIRS) {
|
|
||||||
let files = [];
|
|
||||||
try { files = fs.readdirSync(path.join(PUBLIC, d.dir)).filter(f => RE[d.type].test(f)).sort(); } catch { /* folder missing */ }
|
|
||||||
for (const f of files) {
|
|
||||||
let size = 0;
|
|
||||||
try { size = fs.statSync(path.join(PUBLIC, d.dir, f)).size; } catch {}
|
|
||||||
out.push({ url: `/${d.dir}/${f}`, label: pretty(f), file: f, type: d.type, source: 'library', size, note: d.note || null });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const m of db.getAllMedia()) {
|
|
||||||
const type = m.media_type === 'image' ? 'image' : m.media_type === 'video' ? 'video' : 'audio';
|
|
||||||
out.push({ url: `/media/${m.filename}`, label: pretty(m.original_name), file: m.original_name, type, source: 'upload',
|
|
||||||
id: m.id, size: m.size_bytes, uploaded_at: m.uploaded_at });
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ofType = type => list().filter(i => i.type === type);
|
|
||||||
|
|
||||||
// how many redeem variations use each URL (as sound, video or sticker)
|
|
||||||
function usage() {
|
|
||||||
const n = new Map();
|
|
||||||
for (const v of db.getAllVariations()) for (const u of [v.sound, v.video, v.art]) if (u) n.set(u, (n.get(u) || 0) + 1);
|
|
||||||
return n;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { list, ofType, usage, typeOf, PUBLIC };
|
|
||||||
35
src/nav.js
35
src/nav.js
|
|
@ -1,35 +0,0 @@
|
||||||
// Left sidebars of the dashboard sections. app.js mounts section('actions') / section('settings') in front of the
|
|
||||||
// pages of that section; views/layout.ejs draws the sidebar and marks the page that is open.
|
|
||||||
const SECTIONS = {
|
|
||||||
actions: {
|
|
||||||
title: 'Actions',
|
|
||||||
items: [
|
|
||||||
{ href: '/redeems', label: 'Redeems', hint: 'Channel point rewards and Power-ups: variations, sounds, looks' },
|
|
||||||
{ href: '/actions/alerts', label: 'Alerts', hint: 'Follows, subs, gifts, raids, bits, tips, Hype Train: style, pictures, sounds' },
|
|
||||||
{ href: '/tts', label: 'TTS voices', hint: 'Voices for redeems that read the viewer\'s text aloud' },
|
|
||||||
{ href: '/media', label: 'Media', hint: 'Every picture, sound and video you can pick' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
settings: {
|
|
||||||
title: 'Settings',
|
|
||||||
items: [
|
|
||||||
{ href: '/settings/general', label: 'General' },
|
|
||||||
{ href: '/settings/connections', label: 'Connections', hint: 'Twitch, StreamElements, HUDFX' },
|
|
||||||
{ href: '/settings/obs', label: 'OBS sources', hint: 'Browser source links for OBS' },
|
|
||||||
{ href: '/settings/chat', label: 'Chat', hint: 'On-screen chat, hidden chatters, gap sound' },
|
|
||||||
{ href: '/settings/tts', label: 'Text to speech', hint: 'Length, blocked words' },
|
|
||||||
{ href: '/settings/stats', label: 'Stats and data', hint: 'Public stats page, Twitch sync, analytics import' },
|
|
||||||
{ href: '/settings/backup', label: 'Backup', hint: 'Export / import the whole setup' },
|
|
||||||
{ href: '/settings/advanced', label: 'Advanced', hint: 'Custom CSS / JS for the overlay' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const section = name => (req, res, next) => {
|
|
||||||
const s = SECTIONS[name];
|
|
||||||
const here = req.baseUrl + req.path;
|
|
||||||
res.locals.sidebar = { name, title: s.title, items: s.items.map(i => ({ ...i, on: here === i.href || here.startsWith(i.href + '/') })) };
|
|
||||||
next();
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = { SECTIONS, section };
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
// "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 };
|
|
||||||
|
|
@ -1,493 +0,0 @@
|
||||||
// Period statistics: what happened per day and per stream, so the Stats pages (admin and public) can show one
|
|
||||||
// stream, a week, a month, a year or all time. ONE generic table: a new kind of statistic is a new `kind`
|
|
||||||
// value, not a new table (e.g. bot commands later: kind 'command', or a kind of their own).
|
|
||||||
//
|
|
||||||
// stat_day day (UTC YYYY-MM-DD) x stream_id ('' = chat while offline) x viewer x kind x item -> uses, amount
|
|
||||||
// kind 'message' item '' uses = messages, amount = points-eligible messages
|
|
||||||
// kind 'intro' item '' Twitch "first message ever in this channel"
|
|
||||||
// kind 'emote' item emote name uses
|
|
||||||
// kind 'command' item '!cmd' uses
|
|
||||||
// kind 'watch' item '' uses = 5-minute watch ticks
|
|
||||||
// kind 'action:<event>' item reward / tier uses, amount + unit (points, bits, months, viewers, EUR...)
|
|
||||||
// stat_emote emote name -> source (twitch / 7tv) + id, for pictures
|
|
||||||
// public_optout viewers who typed !hideme: counted, but never named on the public page
|
|
||||||
// stat_meta one-time jobs (backfill)
|
|
||||||
//
|
|
||||||
// The lifetime tables in chatlog.js / watchtime.js stay as they are (points and levels are calculated from them).
|
|
||||||
// Viewer key = Twitch user id, or 'name:<login>' when an event has no id (StreamElements tips, watch streaks).
|
|
||||||
const db = require('./db');
|
|
||||||
|
|
||||||
let ready = false;
|
|
||||||
const d = () => db.raw();
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
if (ready) return;
|
|
||||||
d().exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS stat_day (
|
|
||||||
day TEXT NOT NULL, stream_id TEXT NOT NULL DEFAULT '',
|
|
||||||
user_key TEXT NOT NULL, user_login TEXT, user_name TEXT,
|
|
||||||
kind TEXT NOT NULL, item TEXT NOT NULL DEFAULT '',
|
|
||||||
uses INTEGER DEFAULT 0, amount REAL DEFAULT 0, max_amount REAL DEFAULT 0, unit TEXT,
|
|
||||||
PRIMARY KEY (day, stream_id, user_key, kind, item)
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS stat_day_stream ON stat_day(stream_id);
|
|
||||||
CREATE INDEX IF NOT EXISTS stat_day_user ON stat_day(user_key);
|
|
||||||
CREATE TABLE IF NOT EXISTS stat_emote (emote TEXT PRIMARY KEY, source TEXT, emote_id TEXT);
|
|
||||||
CREATE TABLE IF NOT EXISTS public_optout (user_key TEXT PRIMARY KEY, user_login TEXT, at TEXT);
|
|
||||||
CREATE TABLE IF NOT EXISTS stat_meta (key TEXT PRIMARY KEY, value TEXT);
|
|
||||||
`);
|
|
||||||
ready = true;
|
|
||||||
try { backfill(); } catch (e) { console.error('[periodstats] backfill failed:', e.message); }
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentStream = () => require('./watchtime').currentStreamId() || '';
|
|
||||||
|
|
||||||
// rows: [{ key, login, name, kind, item, uses, amount, unit, max }]; at = ISO time (default now), stream = id or ''
|
|
||||||
function add(rows, at = new Date().toISOString(), stream = currentStream()) {
|
|
||||||
init();
|
|
||||||
const ins = d().prepare(`INSERT INTO stat_day (day, stream_id, user_key, user_login, user_name, kind, item, uses, amount, max_amount, unit)
|
|
||||||
VALUES (@day, @stream, @key, @login, @name, @kind, @item, @uses, @amount, @amount, @unit)
|
|
||||||
ON CONFLICT(day, stream_id, user_key, kind, item) DO UPDATE SET
|
|
||||||
uses = uses + excluded.uses, amount = amount + excluded.amount,
|
|
||||||
max_amount = MAX(max_amount, excluded.max_amount),
|
|
||||||
user_login = COALESCE(excluded.user_login, user_login), user_name = COALESCE(excluded.user_name, user_name),
|
|
||||||
unit = COALESCE(excluded.unit, unit)`);
|
|
||||||
const day = at.slice(0, 10);
|
|
||||||
for (const r of rows) {
|
|
||||||
if (!r.key || !r.kind) continue;
|
|
||||||
ins.run({ day, stream: stream || '', key: String(r.key), login: r.login || null, name: r.name || r.login || null,
|
|
||||||
kind: r.kind, item: String(r.item ?? ''), uses: r.uses ?? 1, amount: Number(r.amount) || 0, unit: r.unit || null });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function emoteSeen(name, source, id) {
|
|
||||||
init();
|
|
||||||
d().prepare('INSERT INTO stat_emote (emote, source, emote_id) VALUES (?, ?, ?) ON CONFLICT(emote) DO UPDATE SET source = excluded.source, emote_id = COALESCE(excluded.emote_id, emote_id)')
|
|
||||||
.run(name, source || null, id || null);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- public page opt-out (!hideme / !showme in chat, or the button on the admin viewer page) ---
|
|
||||||
function setOptout(key, login, hide) {
|
|
||||||
init();
|
|
||||||
if (hide) d().prepare('INSERT OR REPLACE INTO public_optout (user_key, user_login, at) VALUES (?, ?, ?)').run(String(key), login || null, new Date().toISOString());
|
|
||||||
else d().prepare('DELETE FROM public_optout WHERE user_key = ? OR (user_login IS NOT NULL AND user_login = ?)').run(String(key), login || '-');
|
|
||||||
}
|
|
||||||
function optedOut() {
|
|
||||||
init();
|
|
||||||
const rows = d().prepare('SELECT user_key, user_login FROM public_optout').all();
|
|
||||||
return { keys: new Set(rows.map(r => r.user_key)), logins: new Set(rows.map(r => r.user_login).filter(Boolean)) };
|
|
||||||
}
|
|
||||||
const isOptedOut = (key, login) => { const o = optedOut(); return o.keys.has(String(key)) || o.logins.has(String(login || '').toLowerCase()); };
|
|
||||||
|
|
||||||
function forgetUser(key, login) {
|
|
||||||
init();
|
|
||||||
d().prepare('DELETE FROM stat_day WHERE user_key = ? OR user_key = ? OR user_login = ?').run(String(key || '-'), `name:${login || '-'}`, login || '-');
|
|
||||||
d().prepare('DELETE FROM public_optout WHERE user_key = ? OR user_login = ?').run(String(key || '-'), login || '-');
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- one-time backfill from the tables that existed before (raw chat is kept 30 days) ---
|
|
||||||
function backfill() {
|
|
||||||
if (d().prepare("SELECT 1 FROM stat_meta WHERE key = 'backfill_v1'").get()) return;
|
|
||||||
const has = t => !!d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t);
|
|
||||||
const streams = has('stream_session') ? d().prepare('SELECT id, started_at, ended_at FROM stream_session').all() : [];
|
|
||||||
const at = iso => { const t = Date.parse(iso); return streams.find(s => t >= Date.parse(s.started_at) && t <= Date.parse(s.ended_at || new Date().toISOString()))?.id || ''; };
|
|
||||||
const onDay = day => streams.find(s => s.started_at.slice(0, 10) <= day && (s.ended_at || new Date().toISOString()).slice(0, 10) >= day)?.id || '';
|
|
||||||
let n = 0;
|
|
||||||
d().transaction(() => {
|
|
||||||
// chat from the raw buffer: exact time -> exact stream. Points-eligible = same 5-minute rule as chatlog.js.
|
|
||||||
const rawCount = new Map(); // user|day -> messages found in raw
|
|
||||||
if (has('chat_raw')) {
|
|
||||||
const lastScored = new Map();
|
|
||||||
for (const m of d().prepare('SELECT * FROM chat_raw ORDER BY at').all()) {
|
|
||||||
const t = Date.parse(m.at), prev = lastScored.get(m.user_id);
|
|
||||||
const scored = prev == null || t - prev >= 5 * 60 * 1000 ? 1 : 0;
|
|
||||||
if (scored) lastScored.set(m.user_id, t);
|
|
||||||
const who = { key: m.user_id, login: m.user_login, name: m.user_name };
|
|
||||||
const rows = [{ ...who, kind: 'message', amount: scored }];
|
|
||||||
if (m.first_msg) rows.push({ ...who, kind: 'intro' });
|
|
||||||
for (const e of JSON.parse(m.emotes || '[]')) rows.push({ ...who, kind: 'emote', item: e });
|
|
||||||
if (m.command) rows.push({ ...who, kind: 'command', item: m.command });
|
|
||||||
add(rows, m.at, at(m.at)); n++;
|
|
||||||
const k = `${m.user_id}|${m.at.slice(0, 10)}`; rawCount.set(k, (rawCount.get(k) || 0) + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// messages counted but no longer in the raw buffer (deleted by moderation, or older than 30 days)
|
|
||||||
if (has('chat_user_day')) for (const r of d().prepare('SELECT c.user_id, c.day, c.messages, u.user_login, u.user_name FROM chat_user_day c LEFT JOIN chat_user u USING (user_id)').all()) {
|
|
||||||
const rest = r.messages - (rawCount.get(`${r.user_id}|${r.day}`) || 0);
|
|
||||||
if (rest > 0) add([{ key: r.user_id, login: r.user_login, name: r.user_name, kind: 'message', uses: rest }], r.day + 'T12:00:00.000Z', onDay(r.day));
|
|
||||||
}
|
|
||||||
// watch ticks only happen while live: the stream of that day
|
|
||||||
if (has('watch_user_day')) for (const r of d().prepare('SELECT w.user_id, w.day, w.ticks, u.user_login, u.user_name FROM watch_user_day w LEFT JOIN watch_user u USING (user_id)').all())
|
|
||||||
add([{ key: r.user_id, login: r.user_login, name: r.user_name, kind: 'watch', uses: r.ticks }], r.day + 'T12:00:00.000Z', onDay(r.day));
|
|
||||||
// actions: a single use has its exact time; repeated ones are put on the last use
|
|
||||||
if (has('chat_action')) for (const r of d().prepare('SELECT * FROM chat_action').all()) {
|
|
||||||
const when = r.uses === 1 ? r.first_at : r.last_at;
|
|
||||||
add([{ key: r.user_key, login: r.user_login, name: r.user_name, kind: 'action:' + r.action, item: r.item, uses: r.uses, amount: r.amount, unit: r.unit }], when, at(when));
|
|
||||||
}
|
|
||||||
if (has('chat_emote')) for (const r of d().prepare('SELECT emote, source, emote_id FROM chat_emote GROUP BY emote').all()) emoteSeen(r.emote, r.source, r.emote_id);
|
|
||||||
d().prepare("INSERT INTO stat_meta (key, value) VALUES ('backfill_v1', ?)").run(new Date().toISOString());
|
|
||||||
})();
|
|
||||||
console.log(`[periodstats] backfilled from existing statistics (${n} raw messages)`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===================== ranges =====================
|
|
||||||
// ?p=stream&s=<id> | week | month | year | all, anchored on ?d=YYYY-MM-DD (default today). Days are UTC.
|
|
||||||
const iso = t => new Date(t).toISOString().slice(0, 10);
|
|
||||||
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
|
||||||
const nice = day => { const [y, m, dd] = day.split('-'); return `${+dd} ${MONTHS[+m - 1].slice(0, 3)} ${y}`; };
|
|
||||||
|
|
||||||
function streams() {
|
|
||||||
init();
|
|
||||||
return d().prepare('SELECT * FROM stream_session ORDER BY started_at DESC').all();
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseRange(q = {}, fallback = 'all') {
|
|
||||||
let p = ['stream', 'week', 'month', 'year', 'all'].includes(q.p) ? q.p : fallback;
|
|
||||||
const anchor = /^\d{4}-\d{2}-\d{2}$/.test(q.d || '') ? q.d : iso(Date.now());
|
|
||||||
const a = new Date(anchor + 'T00:00:00Z');
|
|
||||||
if (p === 'stream') {
|
|
||||||
const list = streams();
|
|
||||||
const s = list.find(x => x.id === String(q.s || '')) || list[0];
|
|
||||||
if (!s) p = 'all';
|
|
||||||
else {
|
|
||||||
const i = list.indexOf(s);
|
|
||||||
return { p, stream: s, label: `Stream · ${nice(s.started_at.slice(0, 10))}`, sub: s.title || '',
|
|
||||||
prev: list[i + 1] ? { p, s: list[i + 1].id } : null, next: list[i - 1] ? { p, s: list[i - 1].id } : null };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (p === 'week') {
|
|
||||||
const mon = new Date(a); mon.setUTCDate(a.getUTCDate() - ((a.getUTCDay() + 6) % 7));
|
|
||||||
const from = iso(mon), to = iso(mon.getTime() + 6 * 864e5);
|
|
||||||
return { p, from, to, label: `Week of ${nice(from)}`, sub: `${nice(from)} – ${nice(to)}`,
|
|
||||||
prev: { p, d: iso(mon.getTime() - 7 * 864e5) }, next: to < iso(Date.now()) ? { p, d: iso(mon.getTime() + 7 * 864e5) } : null };
|
|
||||||
}
|
|
||||||
if (p === 'month') {
|
|
||||||
const y = a.getUTCFullYear(), m = a.getUTCMonth();
|
|
||||||
const from = iso(Date.UTC(y, m, 1)), to = iso(Date.UTC(y, m + 1, 0));
|
|
||||||
return { p, from, to, label: `${MONTHS[m]} ${y}`, prev: { p, d: iso(Date.UTC(y, m - 1, 1)) },
|
|
||||||
next: to < iso(Date.now()) ? { p, d: iso(Date.UTC(y, m + 1, 1)) } : null };
|
|
||||||
}
|
|
||||||
if (p === 'year') {
|
|
||||||
const y = a.getUTCFullYear();
|
|
||||||
return { p, from: `${y}-01-01`, to: `${y}-12-31`, label: String(y), prev: { p, d: `${y - 1}-01-01` },
|
|
||||||
next: `${y}-12-31` < iso(Date.now()) ? { p, d: `${y + 1}-01-01` } : null };
|
|
||||||
}
|
|
||||||
return { p: 'all', label: 'All time' };
|
|
||||||
}
|
|
||||||
|
|
||||||
// query string for a range link (prev / next / tabs)
|
|
||||||
const rangeQuery = r => '?' + Object.entries(r).filter(([, v]) => v != null).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&');
|
|
||||||
|
|
||||||
function whereOf(r) {
|
|
||||||
if (r.p === 'stream') return { sql: 'stream_id = ?', args: [r.stream.id] };
|
|
||||||
if (r.from) return { sql: 'day BETWEEN ? AND ?', args: [r.from, r.to] };
|
|
||||||
return { sql: '1 = 1', args: [] };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===================== the summary both Stats pages show =====================
|
|
||||||
// opts.hidden: logins left out completely (bots); opts.anonymous: { keys, logins } counted in totals but never
|
|
||||||
// named (public page: !hideme); opts.baseline: add StreamElements' watch time from before our tracking ('all' only).
|
|
||||||
function summary(r, { hidden = [], anonymous = null, baseline = true, top = 10, revenue = false } = {}) {
|
|
||||||
init();
|
|
||||||
const hide = new Set(hidden.map(x => String(x).toLowerCase()));
|
|
||||||
const anon = (key, login) => anonymous && (anonymous.keys.has(key) || anonymous.logins.has(String(login || '').toLowerCase()));
|
|
||||||
const w = whereOf(r);
|
|
||||||
|
|
||||||
const names = new Map(); // latest login / name per viewer (bare columns come from the MAX(day) row)
|
|
||||||
for (const x of d().prepare(`SELECT user_key, user_login, user_name, MAX(day) FROM stat_day GROUP BY user_key`).all()) names.set(x.user_key, x);
|
|
||||||
const rows = d().prepare(`SELECT user_key, kind, item, SUM(uses) uses, SUM(amount) amount, MAX(max_amount) max_amount, MAX(unit) unit
|
|
||||||
FROM stat_day WHERE ${w.sql} GROUP BY user_key, kind, item`).all(...w.args)
|
|
||||||
.filter(x => !hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase()));
|
|
||||||
|
|
||||||
const per = new Map(); // viewer -> { key, login, name, messages, ticks, ... }
|
|
||||||
const who = k => {
|
|
||||||
if (!per.has(k)) { const n = names.get(k) || {}; per.set(k, { key: k, login: n.user_login, name: n.user_name || n.user_login, messages: 0, ticks: 0, bits: 0, subs: 0, gifts: 0, points: 0, tips: 0 }); }
|
|
||||||
return per.get(k);
|
|
||||||
};
|
|
||||||
const emotes = new Map(), commands = new Map(), rewards = new Map(), tipsByUnit = new Map();
|
|
||||||
const t = { messages: 0, scored: 0, intros: 0, ticks: 0, emotes: 0, commands: 0, follows: 0, subs: 0, giftSubs: 0, bits: 0, raids: 0, raidViewers: 0, redeems: 0, channelPoints: 0, powerUps: 0, tips: 0 };
|
|
||||||
for (const x of rows) {
|
|
||||||
const v = who(x.user_key);
|
|
||||||
switch (x.kind) {
|
|
||||||
case 'message': v.messages += x.uses; t.messages += x.uses; t.scored += x.amount; break;
|
|
||||||
case 'intro': t.intros += x.uses; break;
|
|
||||||
case 'watch': v.ticks += x.uses; t.ticks += x.uses; break;
|
|
||||||
case 'emote': t.emotes += x.uses; emotes.set(x.item, (emotes.get(x.item) || 0) + x.uses); break;
|
|
||||||
case 'command': t.commands += x.uses; commands.set(x.item, (commands.get(x.item) || 0) + x.uses); break;
|
|
||||||
case 'action:follow': t.follows += x.uses; break;
|
|
||||||
case 'action:sub': t.subs += x.uses; v.subs += x.uses; break;
|
|
||||||
case 'action:gift_sub': t.giftSubs += x.amount; v.gifts += x.amount; break;
|
|
||||||
case 'action:bits': t.bits += x.amount; v.bits += x.amount; break;
|
|
||||||
case 'action:power_up': case 'action:custom_power_up':
|
|
||||||
t.bits += x.amount; v.bits += x.amount; t.powerUps += x.uses;
|
|
||||||
rewards.set(x.item, (rewards.get(x.item) || 0) + x.uses); break;
|
|
||||||
case 'action:channel_points': case 'action:auto_reward':
|
|
||||||
t.redeems += x.uses; t.channelPoints += x.amount; v.points += x.amount;
|
|
||||||
rewards.set(x.item, (rewards.get(x.item) || 0) + x.uses); break;
|
|
||||||
case 'action:raid': t.raids += x.uses; t.raidViewers += x.amount; break;
|
|
||||||
case 'action:tip': t.tips += x.uses; v.tips += x.amount; tipsByUnit.set(x.unit || '', (tipsByUnit.get(x.unit || '') || 0) + x.amount); break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasT = t => !!d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t);
|
|
||||||
const synced = t => hasT(t) && !!d().prepare(`SELECT 1 FROM ${t} LIMIT 1`).get();
|
|
||||||
// new followers: Twitch's follower list has every follow date (also before HeyStreamer); our events otherwise
|
|
||||||
const followWindow = r.p === 'stream' ? [r.stream.started_at, r.stream.ended_at || new Date().toISOString()]
|
|
||||||
: r.from ? [r.from, r.to + 'T23:59:59.999Z'] : null;
|
|
||||||
if (synced('tw_follower') && (!synced('tw_daily') || r.p === 'stream')) {
|
|
||||||
t.follows = followWindow ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE followed_at BETWEEN ? AND ?').get(...followWindow).n
|
|
||||||
: d().prepare('SELECT COUNT(*) n FROM tw_follower').get().n;
|
|
||||||
}
|
|
||||||
|
|
||||||
// StreamElements watch time from before our own tracking: no dates, so it only belongs to "all time"
|
|
||||||
let baselineMinutes = 0;
|
|
||||||
if (r.p === 'all' && baseline && d().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='watch_import'").get()) {
|
|
||||||
const byLogin = new Map([...per.values()].filter(v => v.login).map(v => [v.login, v]));
|
|
||||||
for (const b of d().prepare('SELECT user_login, minutes FROM watch_import').all()) {
|
|
||||||
if (hide.has(b.user_login)) continue;
|
|
||||||
const v = byLogin.get(b.user_login) || who(`name:${b.user_login}`);
|
|
||||||
if (!v.login) { v.login = b.user_login; v.name = b.user_login; }
|
|
||||||
v.extraMinutes = (v.extraMinutes || 0) + b.minutes; baselineMinutes += b.minutes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const people = [...per.values()];
|
|
||||||
const named = people.filter(v => !anon(v.key, v.login));
|
|
||||||
const board = (f, n = top) => named.map(v => ({ key: v.key, login: v.login, name: v.name, n: f(v) })).filter(x => x.n > 0).sort((a, b) => b.n - a.n).slice(0, n);
|
|
||||||
// Twitch's daily export (twitchcsv.js). Things we also count ourselves (messages, watch time, follows, streamed days)
|
|
||||||
// come from it only for days before our own counting started (cutoff); things only Twitch measures (unique /
|
|
||||||
// engaged viewers, clips, live views, revenue, average + peak viewers) come from it for every day.
|
|
||||||
const hist = { days: 0, streamedDays: 0, minutesStreamed: 0, minutesWatched: 0, messages: 0, follows: 0, viewerMinutes: 0,
|
|
||||||
maxViewers: 0, uniqueSum: 0, newEngaged: 0, returningEngaged: 0, clips: 0, clipViews: 0, liveViews: 0, revenue: 0, revenueByType: {} };
|
|
||||||
const cutoff = d().prepare("SELECT MIN(day) d FROM stat_day WHERE kind IN ('message', 'watch')").get().d || '9999-12-31';
|
|
||||||
let dailyRows = [];
|
|
||||||
if (r.p !== 'stream' && synced('tw_daily')) {
|
|
||||||
dailyRows = d().prepare(`SELECT * FROM tw_daily ${r.from ? 'WHERE day BETWEEN ? AND ?' : ''} ORDER BY day`).all(...(r.from ? [r.from, r.to] : []));
|
|
||||||
for (const x of dailyRows) {
|
|
||||||
const before = x.day < cutoff;
|
|
||||||
if (before) {
|
|
||||||
hist.messages += x.chat_messages; hist.minutesWatched += x.minutes_watched; hist.follows += x.follows;
|
|
||||||
if (x.minutes_streamed > 0) { hist.streamedDays++; hist.minutesStreamed += x.minutes_streamed; }
|
|
||||||
}
|
|
||||||
if (x.minutes_streamed > 0) { hist.viewerMinutes += x.avg_viewers * x.minutes_streamed; hist.days++; hist.uniqueSum += x.unique_viewers; }
|
|
||||||
hist.maxViewers = Math.max(hist.maxViewers, x.max_viewers);
|
|
||||||
hist.newEngaged += x.new_engaged; hist.returningEngaged += x.returning_engaged;
|
|
||||||
hist.clips += x.clips_created; hist.clipViews += x.clip_views; hist.liveViews += x.live_views;
|
|
||||||
if (revenue) {
|
|
||||||
hist.revenue += x.revenue;
|
|
||||||
for (const [k, v] of Object.entries(JSON.parse(x.revenue_json || '{}'))) hist.revenueByType[k] = (hist.revenueByType[k] || 0) + v;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
t.messages += hist.messages;
|
|
||||||
if (synced('tw_follower') && r.p !== 'all') { // from the cutoff on: the follower list (CSV before it)
|
|
||||||
const [a, b] = followWindow;
|
|
||||||
const from = a > cutoff ? a : cutoff;
|
|
||||||
t.follows = from <= b ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE followed_at BETWEEN ? AND ?').get(from, b).n : 0;
|
|
||||||
} else if (synced('tw_follower')) t.follows = d().prepare('SELECT COUNT(*) n FROM tw_follower').get().n;
|
|
||||||
if (!synced('tw_follower') || r.p !== 'all') t.follows += hist.follows; // all time: the follower list already counts everyone
|
|
||||||
}
|
|
||||||
|
|
||||||
let bitsBoard = board(v => v.bits), bitsSource = 'heystreamer';
|
|
||||||
if (r.p === 'all' && synced('tw_bits')) {
|
|
||||||
bitsSource = 'twitch';
|
|
||||||
bitsBoard = d().prepare('SELECT user_id, user_login, user_name, score FROM tw_bits ORDER BY score DESC').all()
|
|
||||||
.filter(x => !hide.has(String(x.user_login).toLowerCase()) && !anon(x.user_id, x.user_login))
|
|
||||||
.slice(0, top).map(x => ({ key: x.user_id, login: x.user_login, name: x.user_name, n: x.score }));
|
|
||||||
t.bits = Math.max(t.bits, d().prepare('SELECT COALESCE(SUM(score), 0) n FROM tw_bits').get().n);
|
|
||||||
}
|
|
||||||
const meta = new Map(d().prepare('SELECT * FROM stat_emote').all().map(e => [e.emote, e]));
|
|
||||||
|
|
||||||
// the channel's own emotes (Twitch list) with how often they were used in chat in this range
|
|
||||||
let channelEmotes = [];
|
|
||||||
if (synced('tw_emote')) {
|
|
||||||
const byName = new Map();
|
|
||||||
for (const [name, uses] of emotes) byName.set(name, uses);
|
|
||||||
const idToNames = new Map();
|
|
||||||
for (const e of meta.values()) if (e.emote_id) idToNames.set(e.emote_id, [...(idToNames.get(e.emote_id) || []), e.emote]);
|
|
||||||
channelEmotes = d().prepare('SELECT * FROM tw_emote').all().map(e => {
|
|
||||||
const names = new Set([e.name, ...(idToNames.get(e.id) || [])]);
|
|
||||||
return { id: e.id, name: e.name, image: e.image, tier: e.tier, type: e.emote_type, gone: !!e.gone,
|
|
||||||
uses: [...names].reduce((n, x) => n + (byName.get(x) || 0), 0) };
|
|
||||||
}).filter(e => !e.gone || e.uses).sort((a, b) => b.uses - a.uses || a.name.localeCompare(b.name));
|
|
||||||
}
|
|
||||||
const sorted = (m, n) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, n);
|
|
||||||
|
|
||||||
// streams in this range, with their own numbers
|
|
||||||
const streamRows = r.p === 'stream' ? [r.stream]
|
|
||||||
: streams().filter(s => !r.from || (s.started_at.slice(0, 10) >= r.from && s.started_at.slice(0, 10) <= r.to));
|
|
||||||
const perStream = new Map();
|
|
||||||
if (streamRows.length) {
|
|
||||||
const ids = streamRows.map(s => s.id);
|
|
||||||
for (const x of d().prepare(`SELECT stream_id, kind, user_key, SUM(uses) uses FROM stat_day WHERE stream_id IN (${ids.map(() => '?').join(',')})
|
|
||||||
AND kind IN ('message', 'watch') GROUP BY stream_id, kind, user_key`).all(...ids)) {
|
|
||||||
if (hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase())) continue;
|
|
||||||
const s = perStream.get(x.stream_id) || { messages: 0, chatters: 0, viewers: 0 };
|
|
||||||
if (x.kind === 'message') { s.messages += x.uses; s.chatters++; } else s.viewers++;
|
|
||||||
perStream.set(x.stream_id, s);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const checkins = streamRows.length ? d().prepare(`SELECT COUNT(*) n FROM stream_checkin WHERE stream_id IN (${streamRows.map(() => '?').join(',')})`).get(...streamRows.map(s => s.id)).n : 0;
|
|
||||||
|
|
||||||
// activity over the range: per day (week / month), per month (year / all); none for one stream
|
|
||||||
let series = null;
|
|
||||||
if (r.p !== 'stream') {
|
|
||||||
const byMonth = r.p === 'year' || r.p === 'all';
|
|
||||||
const buckets = new Map();
|
|
||||||
if (r.from && !byMonth) for (let x = Date.parse(r.from + 'T00:00:00Z'); iso(x) <= r.to; x += 864e5) buckets.set(iso(x), { messages: 0, ticks: 0 });
|
|
||||||
if (r.p === 'year') for (let m = 1; m <= 12; m++) buckets.set(`${r.from.slice(0, 4)}-${String(m).padStart(2, '0')}`, { messages: 0, ticks: 0 });
|
|
||||||
const blank = () => ({ messages: 0, ticks: 0, follows: 0 });
|
|
||||||
for (const b of buckets.values()) b.follows = 0;
|
|
||||||
const fFrom = synced('tw_daily') ? (r.from && r.from > cutoff ? r.from : cutoff) : (r.from || '0000-00-00');
|
|
||||||
if (synced('tw_follower')) for (const x of d().prepare(`SELECT substr(followed_at, 1, 10) day, COUNT(*) n FROM tw_follower
|
|
||||||
WHERE followed_at >= ? ${r.from ? 'AND followed_at <= ?' : ''} GROUP BY day`).all(...[fFrom, ...(r.from ? [r.to + 'T23:59:59.999Z'] : [])])) {
|
|
||||||
const k = byMonth ? x.day.slice(0, 7) : x.day;
|
|
||||||
const b = buckets.get(k) || blank(); b.follows += x.n; buckets.set(k, b);
|
|
||||||
}
|
|
||||||
for (const x of dailyRows) {
|
|
||||||
const k = byMonth ? x.day.slice(0, 7) : x.day;
|
|
||||||
const b = buckets.get(k) || blank();
|
|
||||||
if (x.day < cutoff) {
|
|
||||||
b.messages += x.chat_messages; b.ticks += x.minutes_watched / 5; b.streamMin = (b.streamMin || 0) + x.minutes_streamed;
|
|
||||||
b.follows += x.follows;
|
|
||||||
}
|
|
||||||
if (x.minutes_streamed > 0) { b.vMin = (b.vMin || 0) + x.avg_viewers * x.minutes_streamed; b.vW = (b.vW || 0) + x.minutes_streamed; }
|
|
||||||
buckets.set(k, b);
|
|
||||||
}
|
|
||||||
for (const x of d().prepare(`SELECT day, user_key, kind, SUM(uses) uses FROM stat_day WHERE ${w.sql} AND kind IN ('message', 'watch') GROUP BY day, user_key, kind`).all(...w.args)) {
|
|
||||||
if (hide.has(String(names.get(x.user_key)?.user_login || '').toLowerCase())) continue;
|
|
||||||
const k = byMonth ? x.day.slice(0, 7) : x.day;
|
|
||||||
const b = buckets.get(k) || blank();
|
|
||||||
if (x.kind === 'message') b.messages += x.uses; else b.ticks += x.uses;
|
|
||||||
buckets.set(k, b);
|
|
||||||
}
|
|
||||||
for (const st of (r.p === 'stream' ? [] : streams())) {
|
|
||||||
const sd = st.started_at.slice(0, 10);
|
|
||||||
if (sd < cutoff || (r.from && (sd < r.from || sd > r.to))) continue;
|
|
||||||
const k = byMonth ? sd.slice(0, 7) : sd, b = buckets.get(k) || blank();
|
|
||||||
const mins = (Date.parse(st.ended_at || new Date().toISOString()) - Date.parse(st.started_at)) / 60000;
|
|
||||||
b.streamMin = (b.streamMin || 0) + mins;
|
|
||||||
buckets.set(k, b);
|
|
||||||
}
|
|
||||||
if (r.p === 'all' && buckets.size) { // every month from the first one with data until now, gaps included
|
|
||||||
const ks = [...buckets.keys()].sort();
|
|
||||||
for (let [y, m] = ks[0].split('-').map(Number), end = new Date().toISOString().slice(0, 7); ; m++) {
|
|
||||||
if (m > 12) { y++; m = 1; }
|
|
||||||
const k = `${y}-${String(m).padStart(2, '0')}`;
|
|
||||||
if (k > end) break;
|
|
||||||
if (!buckets.has(k)) buckets.set(k, blank());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const keys = [...buckets.keys()].sort();
|
|
||||||
series = { unit: byMonth ? 'month' : 'day', rows: keys.map(k => ({ key: k, label: byMonth ? `${MONTHS[+k.slice(5, 7) - 1].slice(0, 3)} ${k.slice(2, 4)}` : k.slice(5),
|
|
||||||
messages: buckets.get(k).messages, watchHours: +(buckets.get(k).ticks * 5 / 60).toFixed(1), follows: buckets.get(k).follows || 0,
|
|
||||||
streamHours: +((buckets.get(k).streamMin || 0) / 60).toFixed(1),
|
|
||||||
avgViewers: buckets.get(k).vW ? +(buckets.get(k).vMin / buckets.get(k).vW).toFixed(1) : 0 })) };
|
|
||||||
}
|
|
||||||
|
|
||||||
// games: time per category from the title / category changes (HeyStreamer-era streams; Twitch keeps no history of it)
|
|
||||||
const gameMin = new Map(), gamesOf = new Map();
|
|
||||||
if (hasT('stream_change')) {
|
|
||||||
const prevQ = d().prepare('SELECT at, game FROM stream_change WHERE at < ? ORDER BY at DESC LIMIT 1');
|
|
||||||
const inQ = d().prepare('SELECT at, game FROM stream_change WHERE at BETWEEN ? AND ? ORDER BY at');
|
|
||||||
for (const st of streamRows) {
|
|
||||||
const end = st.ended_at || new Date().toISOString();
|
|
||||||
const before = prevQ.get(st.started_at);
|
|
||||||
const segs = [...(before ? [{ at: st.started_at, game: before.game }] : []), ...inQ.all(st.started_at, end)];
|
|
||||||
if (!segs.length && st.game) segs.push({ at: st.started_at, game: st.game });
|
|
||||||
const list = [];
|
|
||||||
segs.forEach((c, i) => {
|
|
||||||
const a = Date.parse(c.at < st.started_at ? st.started_at : c.at), b = Date.parse(segs[i + 1]?.at || end);
|
|
||||||
const mins = Math.max(0, (b - a) / 60000);
|
|
||||||
if (!c.game || mins < 1) return;
|
|
||||||
gameMin.set(c.game, (gameMin.get(c.game) || 0) + mins);
|
|
||||||
if (!list.includes(c.game)) list.push(c.game);
|
|
||||||
});
|
|
||||||
gamesOf.set(st.id, list);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// community: who raided, who supported (named only when not hidden / opted out)
|
|
||||||
const showName = (key, login) => !hide.has(String(login || '').toLowerCase()) && !anon(key, login);
|
|
||||||
// (deliberately no list of new followers / first-time chatters: nobody is singled out just for showing up)
|
|
||||||
const community = { raiders: [], supporters: [] };
|
|
||||||
for (const x of rows) {
|
|
||||||
const v = per.get(x.user_key); if (!v || !showName(v.key, v.login)) continue;
|
|
||||||
if (x.kind === 'action:raid') community.raiders.push({ login: v.login, name: v.name, raids: x.uses, viewers: x.amount });
|
|
||||||
}
|
|
||||||
community.raiders.sort((a, b) => b.viewers - a.viewers);
|
|
||||||
community.supporters = people.filter(v => showName(v.key, v.login) && (v.bits || v.subs || v.gifts || v.tips))
|
|
||||||
.map(v => ({ login: v.login, name: v.name, bits: v.bits, subs: v.subs, gifts: v.gifts, tips: v.tips }))
|
|
||||||
.sort((a, b) => (b.bits / 100 + (b.subs + b.gifts) * 5 + b.tips) - (a.bits / 100 + (a.subs + a.gifts) * 5 + a.tips));
|
|
||||||
|
|
||||||
// one stream: viewer count every 5 minutes + title / category changes (with what was set when it started)
|
|
||||||
let timeline = null;
|
|
||||||
if (r.p === 'stream' && hasT('stream_viewers')) {
|
|
||||||
const st = r.stream, end = st.ended_at || new Date().toISOString();
|
|
||||||
const samples = d().prepare('SELECT at, viewers FROM stream_viewers WHERE stream_id = ? ORDER BY at').all(st.id);
|
|
||||||
const before = d().prepare('SELECT at, title, game FROM stream_change WHERE at < ? ORDER BY at DESC LIMIT 1').get(st.started_at);
|
|
||||||
const during = d().prepare('SELECT at, title, game FROM stream_change WHERE at BETWEEN ? AND ? ORDER BY at').all(st.started_at, end);
|
|
||||||
const changes = [...(before ? [{ ...before, at: st.started_at, start: true }] : []), ...during];
|
|
||||||
timeline = { start: st.started_at, end, samples, changes };
|
|
||||||
}
|
|
||||||
// across streams: peak and average viewers (streams with samples only)
|
|
||||||
const sampled = streamRows.filter(x => x.viewer_samples);
|
|
||||||
let peak = sampled.length ? Math.max(...sampled.map(x => x.peak_viewers || 0)) : null;
|
|
||||||
let avg = sampled.length ? Math.round(sampled.reduce((a, x) => a + x.viewer_sum / x.viewer_samples, 0) / sampled.length) : null;
|
|
||||||
if (hist.days) { // Twitch's daily numbers cover every streamed day (weighted by minutes streamed)
|
|
||||||
peak = Math.max(peak || 0, hist.maxViewers);
|
|
||||||
avg = Math.round(hist.viewerMinutes / dailyRows.reduce((a, x) => a + (x.minutes_streamed > 0 ? x.minutes_streamed : 0), 0) * 10) / 10;
|
|
||||||
}
|
|
||||||
const ownMinutes = streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff)
|
|
||||||
.reduce((a, x) => a + (Date.parse(x.ended_at || new Date().toISOString()) - Date.parse(x.started_at)) / 60000, 0);
|
|
||||||
const followers = synced('tw_follower') ? d().prepare('SELECT COUNT(*) n FROM tw_follower WHERE unfollowed_at IS NULL').get().n : null;
|
|
||||||
const user = db.getPrimaryUser();
|
|
||||||
const subsNow = synced('tw_sub') ? d().prepare('SELECT COUNT(*) n FROM tw_sub WHERE user_id != ?').get(String(user?.twitch_id || '')).n : null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
range: r, timeline, channelEmotes, bitsSource, community,
|
|
||||||
games: [...gameMin.entries()].map(([game, minutes]) => ({ game, minutes: Math.round(minutes) })).sort((a, b) => b.minutes - a.minutes),
|
|
||||||
channel: { followers, subsNow, peak, avg },
|
|
||||||
twitch: hist.days || dailyRows.length ? {
|
|
||||||
cutoff, streamedDays: hist.streamedDays, hoursStreamed: Math.round((hist.minutesStreamed + ownMinutes) / 60),
|
|
||||||
uniquePerDay: hist.days ? Math.round(hist.uniqueSum / hist.days) : null, newEngaged: hist.newEngaged, returningEngaged: hist.returningEngaged,
|
|
||||||
clips: hist.clips, clipViews: hist.clipViews, liveViews: hist.liveViews,
|
|
||||||
revenue: revenue ? +hist.revenue.toFixed(2) : null,
|
|
||||||
revenueByType: revenue ? Object.entries(hist.revenueByType).filter(([, v]) => v).map(([k, v]) => [k, +v.toFixed(2)]) : null,
|
|
||||||
} : null,
|
|
||||||
totals: {
|
|
||||||
...t,
|
|
||||||
chatters: people.filter(v => v.messages).length,
|
|
||||||
viewers: people.filter(v => v.ticks || v.extraMinutes).length,
|
|
||||||
// watch time before our counting: Twitch's channel total if imported (then the StreamElements per-viewer
|
|
||||||
// minutes only feed the leaderboards), else the StreamElements baseline
|
|
||||||
watchHours: Math.round((t.ticks * 5 + (hist.minutesWatched ? hist.minutesWatched : baselineMinutes)) / 60),
|
|
||||||
baselineHours: hist.minutesWatched ? 0 : Math.round(baselineMinutes / 60),
|
|
||||||
historyWatchHours: Math.round(hist.minutesWatched / 60),
|
|
||||||
hoursStreamed: Math.round((hist.minutesStreamed + streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff || !hist.streamedDays)
|
|
||||||
.reduce((a, x) => a + (Date.parse(x.ended_at || new Date().toISOString()) - Date.parse(x.started_at)) / 60000, 0)) / 60),
|
|
||||||
viewersFromBaseline: people.filter(v => !v.ticks && v.extraMinutes).length,
|
|
||||||
streams: streamRows.filter(x => x.started_at.slice(0, 10) >= cutoff || !hist.streamedDays).length + hist.streamedDays, checkins,
|
|
||||||
tipsByUnit: [...tipsByUnit.entries()].map(([unit, amount]) => ({ unit, amount: +amount.toFixed(2) })),
|
|
||||||
},
|
|
||||||
streams: streamRows.map(s => {
|
|
||||||
const n = perStream.get(s.id) || {};
|
|
||||||
const mins = Math.round((Date.parse(s.ended_at || new Date().toISOString()) - Date.parse(s.started_at)) / 60000);
|
|
||||||
return { id: s.id, started_at: s.started_at, ended_at: s.ended_at, live: !s.ended_at, title: s.title || '', game: s.game || '',
|
|
||||||
minutes: mins, peak: s.peak_viewers || null, source: s.source || 'live', games: gamesOf.get(s.id) || (s.game ? [s.game] : []), avg: s.viewer_samples ? Math.round(s.viewer_sum / s.viewer_samples) : null,
|
|
||||||
messages: n.messages || 0, chatters: n.chatters || 0, viewers: n.viewers || 0 };
|
|
||||||
}),
|
|
||||||
boards: {
|
|
||||||
chat: board(v => v.messages),
|
|
||||||
watch: board(v => v.ticks * 5 + (v.extraMinutes || 0)),
|
|
||||||
bits: bitsBoard,
|
|
||||||
subs: board(v => v.subs + v.gifts),
|
|
||||||
channelPoints: board(v => v.points),
|
|
||||||
},
|
|
||||||
emotes: sorted(emotes, 24).map(([emote, uses]) => ({ emote, uses, source: meta.get(emote)?.source || null, id: meta.get(emote)?.emote_id || null })),
|
|
||||||
commands: sorted(commands, 24).map(([command, uses]) => ({ command, uses })),
|
|
||||||
rewards: sorted(rewards, 15).map(([item, uses]) => ({ item, uses })),
|
|
||||||
series,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init, add, emoteSeen, setOptout, optedOut, isOptedOut, forgetUser, parseRange, rangeQuery, streams, summary, backfill };
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
// Points (point system, values in docs/PLANS.md), calculated from the statistics
|
|
||||||
// tables, so changing a value here recalculates everyone. Also used by the Stats page; later by !points.
|
|
||||||
const db = require('./db');
|
|
||||||
|
|
||||||
const VALUE = {
|
|
||||||
watchTick: 5, // per 5-minute watch tick
|
|
||||||
chat: 10, // per points-eligible message (max 1 per 5 min, counted in chatlog.js)
|
|
||||||
checkin: 25, // first message of a stream
|
|
||||||
intro: 50, // first message ever on the channel
|
|
||||||
follow: 50, // once
|
|
||||||
bit: 1, // cheers, Power-ups, Custom Power-ups
|
|
||||||
per100ChannelPoints: 1,
|
|
||||||
subMonth: { 'Tier 1': 500, Prime: 500, 'Tier 2': 1000, 'Tier 3': 2500 },
|
|
||||||
tipPerUnit: 100, // per 1 EUR (or whatever currency the tip was in)
|
|
||||||
raid: 100, // flat, no reward for raid size
|
|
||||||
streakPer: 5, streakMax: 100,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Levels by watch time (our ticks + the StreamElements baseline), not points: bits/subs do not buy a level.
|
|
||||||
const LEVELS = [
|
|
||||||
{ minHours: 0, name: 'Viewer' }, { minHours: 50, name: 'Regular' }, { minHours: 200, name: 'Loyal' }, { minHours: 1000, name: 'Veteran' },
|
|
||||||
];
|
|
||||||
const levelOf = watchMinutes => [...LEVELS].reverse().find(l => watchMinutes >= l.minHours * 60);
|
|
||||||
|
|
||||||
const has = t => !!db.raw().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t);
|
|
||||||
const all = (sql, ...a) => db.raw().prepare(sql).all(...a);
|
|
||||||
|
|
||||||
// -> Map key -> viewer { key, user_id, login, name, parts: {watch, chat, ...}, total, level }
|
|
||||||
// key = Twitch user id; viewers known only by name (tips, watch streaks) are merged by login when possible
|
|
||||||
function everyone() {
|
|
||||||
const v = new Map(), byLogin = new Map();
|
|
||||||
const get = (id, login, name) => {
|
|
||||||
let key = id ? String(id) : null;
|
|
||||||
if (!key && login && byLogin.has(login)) key = byLogin.get(login);
|
|
||||||
if (!key) key = `name:${login}`;
|
|
||||||
if (!v.has(key)) v.set(key, { key, user_id: id || null, login, name: name || login, parts: {}, total: 0 });
|
|
||||||
const x = v.get(key);
|
|
||||||
if (login) { byLogin.set(login, key); x.login = x.login || login; }
|
|
||||||
if (name) x.name = name;
|
|
||||||
return x;
|
|
||||||
};
|
|
||||||
const add = (x, part, pts) => { if (!pts) return; x.parts[part] = (x.parts[part] || 0) + pts; x.total += pts; };
|
|
||||||
|
|
||||||
if (has('chat_user')) for (const r of all('SELECT user_id, user_login, user_name, scored, intro FROM chat_user')) {
|
|
||||||
const x = get(r.user_id, r.user_login, r.user_name);
|
|
||||||
add(x, 'chat', (r.scored || 0) * VALUE.chat); add(x, 'first message', r.intro ? VALUE.intro : 0);
|
|
||||||
}
|
|
||||||
if (has('watch_user')) for (const r of all('SELECT user_id, user_login, user_name, ticks FROM watch_user')) {
|
|
||||||
const x = get(r.user_id, r.user_login, r.user_name);
|
|
||||||
x.watchMinutes = (x.watchMinutes || 0) + (r.ticks || 0) * 5;
|
|
||||||
add(x, 'watching', (r.ticks || 0) * VALUE.watchTick);
|
|
||||||
}
|
|
||||||
// StreamElements watch time from before our tracking (imported once, see watchtime.js): counted like our ticks
|
|
||||||
if (has('watch_import')) for (const r of all('SELECT user_login, minutes FROM watch_import')) {
|
|
||||||
const x = get(null, r.user_login, null);
|
|
||||||
x.importedMinutes = (x.importedMinutes || 0) + r.minutes;
|
|
||||||
x.watchMinutes = (x.watchMinutes || 0) + r.minutes;
|
|
||||||
add(x, 'watching (StreamElements)', Math.floor(r.minutes / 5) * VALUE.watchTick);
|
|
||||||
}
|
|
||||||
if (has('stream_checkin')) for (const r of all('SELECT user_id, COUNT(*) n FROM stream_checkin GROUP BY user_id')) {
|
|
||||||
add(get(r.user_id, null, null), 'check-ins', r.n * VALUE.checkin);
|
|
||||||
}
|
|
||||||
if (has('chat_action')) for (const r of all('SELECT * FROM chat_action ORDER BY user_key LIKE \'name:%\'')) {
|
|
||||||
const id = r.user_key.startsWith('name:') ? null : r.user_key;
|
|
||||||
const x = get(id, r.user_login, r.user_name);
|
|
||||||
switch (r.action) {
|
|
||||||
case 'follow': add(x, 'follow', VALUE.follow); break;
|
|
||||||
case 'bits': case 'power_up': case 'custom_power_up': add(x, 'bits', Math.round(r.amount * VALUE.bit)); break;
|
|
||||||
case 'channel_points': case 'auto_reward': add(x, 'channel points', Math.floor(r.amount / 100) * VALUE.per100ChannelPoints); break;
|
|
||||||
case 'sub': add(x, 'subs', Math.round(r.amount * (VALUE.subMonth[r.item] || VALUE.subMonth['Tier 1']))); break;
|
|
||||||
case 'gift_sub': add(x, 'gift subs', Math.round(r.amount * (VALUE.subMonth[r.item] || VALUE.subMonth['Tier 1']))); break;
|
|
||||||
case 'tip': add(x, 'tips', Math.round(r.amount * VALUE.tipPerUnit)); break;
|
|
||||||
case 'raid': add(x, 'raids', r.uses * VALUE.raid); break;
|
|
||||||
case 'watch_streak': add(x, 'watch streak', Math.min(VALUE.streakMax, r.amount * VALUE.streakPer)); break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const x of v.values()) x.level = levelOf(x.watchMinutes || 0);
|
|
||||||
return v;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { VALUE, LEVELS, levelOf, everyone };
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
{
|
|
||||||
"_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": ""
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
185
src/redeems.js
185
src/redeems.js
|
|
@ -1,185 +0,0 @@
|
||||||
// Channel point rewards, built-in channel point rewards and bits Power-ups.
|
|
||||||
// Each trigger (kind + key) has variations; one enabled variation is picked at random,
|
|
||||||
// weighted by rarity (like Twitch alert variations), and played as a polaroid or sound-only alert.
|
|
||||||
const db = require('./db');
|
|
||||||
const alerts = require('./alerts');
|
|
||||||
const dispatch = require('./dispatch');
|
|
||||||
const tts = require('./tts');
|
|
||||||
|
|
||||||
// relative weight per rarity (Twitch does not publish its numbers; tune here).
|
|
||||||
// chance of a variation = its weight / sum of the weights of the trigger's ENABLED variations
|
|
||||||
const RARITY = {
|
|
||||||
common: { label: 'Common', weight: 50 },
|
|
||||||
uncommon: { label: 'Uncommon', weight: 25 },
|
|
||||||
rare: { label: 'Rare', weight: 12 },
|
|
||||||
ultra_rare: { label: 'Ultra Rare', weight: 3 },
|
|
||||||
};
|
|
||||||
|
|
||||||
// built-in (automatic) channel point rewards, channel.channel_points_automatic_reward_redemption.add v2
|
|
||||||
const AUTO_REWARDS = {
|
|
||||||
send_highlighted_message: 'Highlight my message',
|
|
||||||
single_message_bypass_sub_mode: 'Send a message in sub-only mode',
|
|
||||||
random_sub_emote_unlock: 'Unlock a random sub emote',
|
|
||||||
chosen_sub_emote_unlock: 'Choose an emote to unlock',
|
|
||||||
chosen_modified_sub_emote_unlock: 'Modify a single emote',
|
|
||||||
};
|
|
||||||
|
|
||||||
// bits Power-ups, channel.bits.use with type = power_up
|
|
||||||
const POWER_UPS = {
|
|
||||||
message_effect: 'Power-up: Message Effect',
|
|
||||||
celebration: 'Power-up: On-Screen Celebration',
|
|
||||||
gigantify_an_emote: 'Power-up: Gigantify an Emote',
|
|
||||||
};
|
|
||||||
|
|
||||||
// Custom Power-ups (bits, made by the streamer on Twitch): kind 'custom_power_up', key = power-up id
|
|
||||||
|
|
||||||
// how a trigger is drawn on the overlay (everything else: cassette tape)
|
|
||||||
const STYLE = {
|
|
||||||
'power_up:gigantify_an_emote': 'emote', // the viewer's emote, giant
|
|
||||||
'power_up:celebration': 'emote_rain', // copies of the emote bouncing around the screen
|
|
||||||
'auto_reward:send_highlighted_message': 'message', // big taped paper note with the message
|
|
||||||
'power_up:message_effect': 'message', // same as highlight
|
|
||||||
};
|
|
||||||
const LINE = { emote: 'gigantified an emote!', emote_rain: 'is celebrating!', message: 'highlighted:', tts: 'says:' };
|
|
||||||
const emoteUrl = id => id ? `https://static-cdn.jtvnw.net/emoticons/v2/${encodeURIComponent(id)}/default/dark/3.0` : null;
|
|
||||||
|
|
||||||
function pick(variations) {
|
|
||||||
const pool = variations.filter(v => v.enabled);
|
|
||||||
const total = pool.reduce((s, v) => s + (RARITY[v.rarity]?.weight || 1), 0);
|
|
||||||
let r = Math.random() * total;
|
|
||||||
for (const v of pool) { r -= RARITY[v.rarity]?.weight || 1; if (r < 0) return v; }
|
|
||||||
return pool[pool.length - 1] || null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function toAlert(v, { user, input, emote, bits }) {
|
|
||||||
const spoken = !!(v.tts_voice_id && input); // TTS variations: envelope letter (fx.js envelope())
|
|
||||||
// video variations play full-screen on the ?parts=video overlay (public/alerts/video.js)
|
|
||||||
// look: the variation's Card / Cassette (older rows: cassette); read-aloud ones: Card or Letter (Actions → Alerts)
|
|
||||||
const style = v.video ? 'video' : spoken ? 'tts' : (STYLE[`${v.kind}:${v.key}`] || (v.look === 'card' ? 'card' : 'cassette'));
|
|
||||||
const line = spoken ? LINE.tts : LINE[style];
|
|
||||||
return {
|
|
||||||
type: 'redeem', kind: v.kind, key: v.key, style, vid: v.id, // vid: re-speak on replay if the mp3 was pruned
|
|
||||||
user, reward: v.title, variation: v.name, rarity: v.rarity, input: input || null,
|
|
||||||
// special styles have their own wording unless the caption was customised
|
|
||||||
caption: style !== 'cassette' && style !== 'card' && v.caption === 'redeemed it! ♡' ? line : v.caption,
|
|
||||||
sound: spoken ? null : (v.sound || null), volume: v.volume, // TTS on: the voice replaces the sound
|
|
||||||
polaroid: !!v.polaroid, art: v.art || null, emote: emoteUrl(emote),
|
|
||||||
video: v.video || null, bits: bits ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// TTS: clean the viewer's text, speak it with the variation's saved voice, attach { tts, tts_ms }.
|
|
||||||
// Never throws: on any problem the alert still goes out, just without speech.
|
|
||||||
async function addSpeech(v, alert) {
|
|
||||||
try {
|
|
||||||
const voice = db.getTtsVoice(v.tts_voice_id);
|
|
||||||
if (!voice || !alert.input) return;
|
|
||||||
const s = db.getSettings();
|
|
||||||
const { text, blocked } = tts.prepareViewerText(alert.input, { maxChars: s.tts_max_chars, blocklist: s.tts_blocklist });
|
|
||||||
if (blocked) {
|
|
||||||
console.log(`[tts] blocked message from ${alert.user}`);
|
|
||||||
alert.input = '(message removed)';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
alert.input = text; // the note shows what is read
|
|
||||||
if (!text) return;
|
|
||||||
const say = s.tts_say_name && alert.user ? `${alert.user} says: ${text}` : text;
|
|
||||||
const out = await tts.synth(voice.config, say);
|
|
||||||
alert.tts = out.url;
|
|
||||||
alert.tts_ms = out.durationMs;
|
|
||||||
alert.tts_env = await tts.loudness(out.file); // word timing on the overlay
|
|
||||||
alert.tts_prefix = say === text ? 0 : 2; // words spoken before the message ("<name> says:")
|
|
||||||
} catch (e) {
|
|
||||||
console.warn(`[tts] ${alert.user}: ${e.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Twitch icons of channel point rewards (custom images only) and Custom Power-ups.
|
|
||||||
// alert.icon -> top-left sticker on the cassette (cassette.js) and the video box (video.js).
|
|
||||||
// Cached; reloaded every 10 min, or (at most every 30 s) when an unknown trigger comes in.
|
|
||||||
const icons = new Map();
|
|
||||||
let iconsAt = 0, iconsLoading = null;
|
|
||||||
const bestImg = i => (i && (i.url_4x || i.url_2x || i.url_1x)) || null;
|
|
||||||
async function loadIcons() {
|
|
||||||
const twitch = require('./twitch');
|
|
||||||
const u = twitch.getUser();
|
|
||||||
if (!u) return;
|
|
||||||
const next = new Map();
|
|
||||||
try {
|
|
||||||
const r = await twitch.helix(`/channel_points/custom_rewards?broadcaster_id=${u.twitch_id}`);
|
|
||||||
if (r.ok) for (const x of (await r.json()).data || []) { const img = bestImg(x.image); if (img) next.set(`reward|${x.id}`, img); }
|
|
||||||
} catch (e) { console.warn('[redeems] reward icons:', e.message); }
|
|
||||||
try {
|
|
||||||
const r = await twitch.helix(`/bits/custom_power_ups?broadcaster_id=${u.twitch_id}`);
|
|
||||||
if (r.ok) for (const x of (await r.json()).data || []) {
|
|
||||||
const img = bestImg(x.image) || bestImg(x.icon) || bestImg(x.default_image) || x.image_url || null;
|
|
||||||
if (img) next.set(`custom_power_up|${x.id}`, img);
|
|
||||||
}
|
|
||||||
} catch (e) { console.warn('[redeems] power-up icons:', e.message); }
|
|
||||||
if (next.size || !icons.size) { icons.clear(); for (const [k, v] of next) icons.set(k, v); }
|
|
||||||
iconsAt = Date.now();
|
|
||||||
}
|
|
||||||
async function iconFor(kind, key) {
|
|
||||||
if (kind !== 'reward' && kind !== 'custom_power_up') return null;
|
|
||||||
const age = Date.now() - iconsAt;
|
|
||||||
if (age > 10 * 60000 || (!icons.has(`${kind}|${key}`) && age > 30000)) {
|
|
||||||
iconsLoading = iconsLoading || loadIcons().finally(() => { iconsLoading = null; });
|
|
||||||
await Promise.race([iconsLoading, new Promise(r => setTimeout(r, 2000))]); // never hold an alert long
|
|
||||||
}
|
|
||||||
return icons.get(`${kind}|${key}`) || null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// legacy action event type for the actions system / activity log
|
|
||||||
const LEGACY = { reward: 'channel_points', auto_reward: 'auto_reward', power_up: 'power_up', custom_power_up: 'custom_power_up' };
|
|
||||||
|
|
||||||
// A redemption arrived from Twitch.
|
|
||||||
function handle(kind, key, title, { user, input, emote, bits }, raw) {
|
|
||||||
if (title) db.renameTrigger(kind, key, title);
|
|
||||||
const v = pick(db.getVariationsFor(kind, key));
|
|
||||||
if (!v) {
|
|
||||||
// nothing configured (or all off): still log it and run legacy actions
|
|
||||||
dispatch.dispatchEvent(LEGACY[kind], key, user, raw);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const alert = toAlert(v, { user, input, emote, bits });
|
|
||||||
const ready = iconFor(kind, key).then(icon => { alert.icon = icon; });
|
|
||||||
if (v.tts_voice_id && input && !v.video) ready.then(() => addSpeech(v, alert)).then(() => alerts.send(alert, raw)); // speech first, then the alert
|
|
||||||
else ready.then(() => alerts.send(alert, raw));
|
|
||||||
return alert;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dashboard Replay of an old activity row that has no stored alert: a fresh pick for the trigger,
|
|
||||||
// with the viewer's original name and text. Resolves to the alert, or null if nothing is configured.
|
|
||||||
async function rebuild(kind, key, { user, input, emote, bits }) {
|
|
||||||
const v = pick(db.getVariationsFor(kind, key));
|
|
||||||
if (!v) return null;
|
|
||||||
const alert = toAlert(v, { user, input, emote, bits });
|
|
||||||
alert.icon = await iconFor(kind, key);
|
|
||||||
if (v.tts_voice_id && input && !v.video) await addSpeech(v, alert);
|
|
||||||
return alert;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Replay of a stored TTS alert whose mp3 was pruned: speak it again with the same variation's voice.
|
|
||||||
async function respeak(alert) {
|
|
||||||
const v = alert.vid && db.getVariation(alert.vid);
|
|
||||||
for (const k of ['tts', 'tts_ms', 'tts_env', 'tts_prefix']) delete alert[k];
|
|
||||||
if (v && v.tts_voice_id && alert.input) await addSpeech(v, alert);
|
|
||||||
return alert;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dashboard test: one specific variation, or a random pick for the whole trigger.
|
|
||||||
function test({ id, kind, key }) {
|
|
||||||
const v = id ? db.getVariation(id) : pick(db.getVariationsFor(kind, key));
|
|
||||||
if (!v) return false;
|
|
||||||
const input = v.tts_voice_id ? 'Hydrate check! Also, nice shot, I was totally not camping that container.'
|
|
||||||
: ['send_highlighted_message', 'message_effect'].includes(v.key) ? 'this is what a highlighted message looks like on stream!'
|
|
||||||
: v.kind === 'reward' ? 'test input' : null;
|
|
||||||
const alert = toAlert({ ...v, enabled: 1 }, { user: 'ChickenWhisperer', input, emote: v.kind === 'power_up' ? '25' : null,
|
|
||||||
bits: v.kind === 'custom_power_up' ? 50 : null }); // 25 = Kappa
|
|
||||||
const ready = iconFor(v.kind, v.key).then(icon => { alert.icon = icon; });
|
|
||||||
if (v.tts_voice_id && !v.video) ready.then(() => addSpeech(v, alert)).then(() => alerts.sendTestAlert(alert));
|
|
||||||
else ready.then(() => alerts.sendTestAlert(alert));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { RARITY, AUTO_REWARDS, POWER_UPS, STYLE, LEGACY, pick, handle, test, rebuild, respeak };
|
|
||||||
45
src/routers/actions.js
Normal file
45
src/routers/actions.js
Normal file
|
|
@ -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;
|
||||||
|
|
@ -1,52 +0,0 @@
|
||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const alerts = require('../alerts');
|
|
||||||
const twitch = require('../twitch');
|
|
||||||
const ws = require('../ws');
|
|
||||||
|
|
||||||
// POST /alerts/test/:key: send a sample alert to every connected overlay (dashboard test buttons)
|
|
||||||
router.post('/test/:key', (req, res) => {
|
|
||||||
const ok = alerts.sendTest(req.params.key);
|
|
||||||
res.status(ok ? 200 : 404).json({ ok });
|
|
||||||
});
|
|
||||||
|
|
||||||
// POST /alerts/skip: stop the alert on screen right now (e.g. a TTS message), the queue carries on
|
|
||||||
router.post('/skip', (req, res) => {
|
|
||||||
ws.broadcast({ type: 'alert_skip' });
|
|
||||||
console.log('[alerts] skip requested from the dashboard');
|
|
||||||
res.json({ ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
// POST /alerts/raid/start {target}: start a raid on Twitch and show the send-off card until it happens
|
|
||||||
router.post('/raid/start', async (req, res) => {
|
|
||||||
const me = twitch.getUser();
|
|
||||||
const login = String(req.body.target || '').trim().replace(/^@/, '').toLowerCase();
|
|
||||||
if (!me) return res.status(400).json({ ok: false, error: 'not connected to Twitch' });
|
|
||||||
if (!/^[a-z0-9_]{2,25}$/.test(login)) return res.status(400).json({ ok: false, error: 'invalid channel name' });
|
|
||||||
try {
|
|
||||||
const u = await twitch.helix(`/users?login=${encodeURIComponent(login)}`);
|
|
||||||
const target = u.ok ? (await u.json()).data?.[0] : null;
|
|
||||||
if (!target) return res.status(404).json({ ok: false, error: 'channel not found' });
|
|
||||||
const r = await twitch.helix(`/raids?from_broadcaster_id=${me.twitch_id}&to_broadcaster_id=${target.id}`, { method: 'POST' });
|
|
||||||
if (!r.ok) {
|
|
||||||
const body = await r.json().catch(() => ({}));
|
|
||||||
return res.status(r.status).json({ ok: false, error: body.message || `Twitch said ${r.status}` });
|
|
||||||
}
|
|
||||||
let viewers = null;
|
|
||||||
const s = await twitch.helix(`/streams?user_id=${me.twitch_id}`);
|
|
||||||
if (s.ok) viewers = (await s.json()).data?.[0]?.viewer_count ?? null;
|
|
||||||
alerts.raidStarted({ target: target.display_name, avatar: target.profile_image_url || null, viewers });
|
|
||||||
res.json({ ok: true, target: target.display_name, viewers });
|
|
||||||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
// POST /alerts/raid/cancel: cancel the pending raid on Twitch and remove the card
|
|
||||||
router.post('/raid/cancel', async (req, res) => {
|
|
||||||
const me = twitch.getUser();
|
|
||||||
if (!me) return res.status(400).json({ ok: false, error: 'not connected to Twitch' });
|
|
||||||
const r = await twitch.helix(`/raids?broadcaster_id=${me.twitch_id}`, { method: 'DELETE' }).catch(e => ({ ok: false, status: 500, e }));
|
|
||||||
alerts.raidCancelled();
|
|
||||||
res.status(r.ok || r.status === 404 ? 200 : r.status).json({ ok: r.ok || r.status === 404 });
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
// Actions → Alerts: how follows, subs, gifts, raids, bits, tips and the Hype Train look and sound (src/theme.js).
|
|
||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const db = require('../db');
|
|
||||||
const ws = require('../ws');
|
|
||||||
const theme = require('../theme');
|
|
||||||
const library = require('../library');
|
|
||||||
|
|
||||||
router.get('/', (req, res) => {
|
|
||||||
const media = library.list();
|
|
||||||
res.render('alerts_setup', {
|
|
||||||
theme: theme.get(),
|
|
||||||
images: media.filter(m => m.type === 'image'),
|
|
||||||
sounds: media.filter(m => m.type === 'audio'),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// preview: the real overlay code with a button per alert; looks: the defaults, the optional styles, this channel's own
|
|
||||||
function previewThemes() {
|
|
||||||
const optional = theme.merge(theme.DEFAULT, { style: 'polaroid', redeemStyle: 'cassette', ttsStyle: 'letter' });
|
|
||||||
return {
|
|
||||||
mine: { label: 'Your alerts', theme: theme.get() },
|
|
||||||
defaults: { label: 'Defaults (Card)', theme: theme.DEFAULT },
|
|
||||||
optional: { label: 'Polaroid / Cassette / Letter', theme: optional },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
router.get('/preview', (req, res) => {
|
|
||||||
res.render('alerts_preview', { layout: false, base: '/alerts/', themes: previewThemes(), start: req.query.look || 'mine', samples: require('../alerts').SAMPLES });
|
|
||||||
});
|
|
||||||
|
|
||||||
// whole theme as JSON from the editor
|
|
||||||
router.post('/', express.json({ limit: '200kb' }), (req, res) => {
|
|
||||||
try {
|
|
||||||
const t = theme.save(req.body || {});
|
|
||||||
ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); // overlays use it at once
|
|
||||||
res.json({ ok: true, theme: t });
|
|
||||||
} catch (e) { res.status(400).json({ ok: false, error: e.message }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
|
|
@ -11,13 +11,6 @@ const SCOPES = [
|
||||||
'bits:read',
|
'bits:read',
|
||||||
'channel:read:redemptions',
|
'channel:read:redemptions',
|
||||||
'moderator:read:followers',
|
'moderator:read:followers',
|
||||||
'user:read:chat', // channel.chat.notification (sub/gift/raid details)
|
|
||||||
'channel:read:polls', // channel.poll.* (poll card on the overlay)
|
|
||||||
'channel:read:hype_train', // channel.hype_train.* (Hype Train alerts)
|
|
||||||
'channel:manage:raids', // start/cancel raids from the dashboard (send-off card stays during the countdown)
|
|
||||||
'moderator:read:chatters', // watch time: chatter list every 5 min while live (watchtime.js)
|
|
||||||
'moderation:read', // stats: who is a moderator (twitchsync.js)
|
|
||||||
'channel:read:vips', // stats: who is a VIP (twitchsync.js)
|
|
||||||
].join(' ');
|
].join(' ');
|
||||||
|
|
||||||
router.get('/login', (req, res) => {
|
router.get('/login', (req, res) => {
|
||||||
|
|
@ -88,7 +81,7 @@ router.get('/callback', async (req, res) => {
|
||||||
req.session.userId = user.id;
|
req.session.userId = user.id;
|
||||||
req.session.user = { login: user.login, display_name: user.display_name };
|
req.session.user = { login: user.login, display_name: user.display_name };
|
||||||
|
|
||||||
eventsub.start(user);
|
eventsub.start(tokens.access_token, twitchUser.id);
|
||||||
|
|
||||||
console.log(`[auth] Login OK — ${twitchUser.login} (twitch_id:${twitchUser.id})`);
|
console.log(`[auth] Login OK — ${twitchUser.login} (twitch_id:${twitchUser.id})`);
|
||||||
res.redirect('/');
|
res.redirect('/');
|
||||||
|
|
|
||||||
|
|
@ -1,36 +1,11 @@
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const db = require('../db');
|
const db = require('../db');
|
||||||
const eventsub = require('../eventsub');
|
|
||||||
const alerts = require('../alerts');
|
|
||||||
const streamelements = require('../streamelements');
|
|
||||||
const activity = require('../activity');
|
|
||||||
const ws = require('../ws');
|
|
||||||
|
|
||||||
router.get('/', (req, res) => {
|
router.get('/', (req, res) => {
|
||||||
const logs = db.getActivityLog(50);
|
const logs = db.getActivityLog(50);
|
||||||
const settings = db.getSettings();
|
const settings = db.getSettings();
|
||||||
res.render('dashboard', { logs, activity, settings, eventsubStatus: eventsub.getStatus(), seStatus: streamelements.getStatus(), testKeys: alerts.TEST_KEYS });
|
res.render('dashboard', { logs, settings });
|
||||||
});
|
|
||||||
|
|
||||||
// Activity table only (dashboard Reload button / auto-refresh)
|
|
||||||
router.get('/activity', (req, res) => {
|
|
||||||
res.render('_activity', { layout: false, logs: db.getActivityLog(50), activity });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Replay: play a logged event on the overlay again (queued like a real alert; not logged again, no actions fired)
|
|
||||||
router.post('/activity/:id/replay', async (req, res) => {
|
|
||||||
const log = db.getActivity(parseInt(req.params.id, 10));
|
|
||||||
if (!log) return res.status(404).json({ ok: false, error: 'not found' });
|
|
||||||
try {
|
|
||||||
const msg = await activity.replayMessage(log);
|
|
||||||
if (!msg) return res.json({ ok: false, error: 'nothing to replay for this event' });
|
|
||||||
ws.broadcast(msg);
|
|
||||||
res.json({ ok: true });
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[activity] replay:', e.message);
|
|
||||||
res.status(500).json({ ok: false, error: e.message });
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|
|
||||||
|
|
@ -1,146 +0,0 @@
|
||||||
// HUDFX and Blerp inside our overlay (one OBS source, one audio fader, our CSS).
|
|
||||||
//
|
|
||||||
// Their overlay pages are fetched here and served from our domain with a few things injected:
|
|
||||||
// <base> their own files and APIs still load from their sites
|
|
||||||
// page address their apps read the overlay id from location.pathname, so it is set back to theirs
|
|
||||||
// API redirect HUDFX's settings API refuses other sites (CORS), so those calls go through /hudfx-api here
|
|
||||||
// volume every <audio>/<video> and Howler (Blerp) plays at ?vol= (0..1)
|
|
||||||
// CSS src/ext/<name>.css (paper/cassette/camcorder look)
|
|
||||||
// Blerp's main script refuses to load from other sites (module scripts need CORS), so /blerp-assets serves it.
|
|
||||||
//
|
|
||||||
// Config: Settings page → HUDFX overlay URL. Blerp is not embedded: its realtime server only accepts its own site.
|
|
||||||
// Routes live under the overlay id, like the overlay itself: /ext/<overlay id>/hudfx, /ext/<overlay id>/blerp
|
|
||||||
const express = require('express');
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const db = require('../db');
|
|
||||||
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
const EXT = {
|
|
||||||
hudfx: { css: 'hudfx.css', api: { from: 'https://api.hudfx.io/', to: 'hudfx-api/' } },
|
|
||||||
// Blerp picks its servers from the hostname (anything else = its developers' localhost); ?env=prod forces the real ones
|
|
||||||
blerp: { css: 'blerp.css', assets: true, query: { env: 'prod' } },
|
|
||||||
};
|
|
||||||
|
|
||||||
// HUDFX: Settings page (settings.hudfx_overlay_url). Blerp: not embeddable (see above), no setting.
|
|
||||||
function target(name) {
|
|
||||||
const raw = name === 'hudfx' ? db.getSettings().hudfx_overlay_url : null;
|
|
||||||
if (!raw) return null;
|
|
||||||
try { const u = new URL(raw); return u.protocol === 'https:' ? u : null; } catch { return null; }
|
|
||||||
}
|
|
||||||
function configured() { return Object.keys(EXT).filter(target); }
|
|
||||||
|
|
||||||
// only for our overlay id
|
|
||||||
router.use('/:uuid', (req, res, next) => {
|
|
||||||
if (req.params.uuid !== db.getOverlaySettings().overlay_id) return res.status(404).send('Not found');
|
|
||||||
next();
|
|
||||||
});
|
|
||||||
|
|
||||||
const esc = s => JSON.stringify(s).replace(/</g, '\\u003c');
|
|
||||||
|
|
||||||
router.get('/:uuid/:name(hudfx|blerp)', async (req, res) => {
|
|
||||||
const name = req.params.name, ext = EXT[name], u = target(name);
|
|
||||||
if (!u) return res.status(404).send(`${name}: not configured (Settings)`);
|
|
||||||
try {
|
|
||||||
const r = await fetch(u, { headers: { 'User-Agent': req.get('User-Agent') || 'Mozilla/5.0', 'Accept': 'text/html' } });
|
|
||||||
if (!r.ok) return res.status(502).send(`${name}: ${r.status}`);
|
|
||||||
let html = await r.text();
|
|
||||||
const ours = `${req.protocol}://${req.get('host')}/ext/${req.params.uuid}/`;
|
|
||||||
const vol = Math.min(1, Math.max(0, parseFloat(req.query.vol)));
|
|
||||||
const volume = isFinite(vol) ? vol : 1;
|
|
||||||
|
|
||||||
html = html.replace(/<script>\s*\(function\(\)\{function c\(\)[\s\S]*?<\/script>/, ''); // Cloudflare beacon (Blerp)
|
|
||||||
if (ext.assets) html = html.replace(/(src|href)="\/assets\//g, `$1="${ours}${name}-assets/`);
|
|
||||||
|
|
||||||
const addr = new URL(u);
|
|
||||||
for (const [k, v] of Object.entries(ext.query || {})) addr.searchParams.set(k, v);
|
|
||||||
const head = `<base href="${u.origin}/">
|
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
// their router reads the overlay id from the address: put their path back (same origin, so allowed)
|
|
||||||
history.replaceState(null, '', location.origin + ${esc(addr.pathname + addr.search)});
|
|
||||||
${ext.api ? `
|
|
||||||
const FROM = ${esc(ext.api.from)}, TO = ${esc(ours + ext.api.to)};
|
|
||||||
const fix = x => (typeof x === 'string' && x.startsWith(FROM)) ? TO + x.slice(FROM.length) : x;
|
|
||||||
const xo = XMLHttpRequest.prototype.open;
|
|
||||||
XMLHttpRequest.prototype.open = function (m, url, ...rest) { return xo.call(this, m, fix(String(url)), ...rest); };
|
|
||||||
const fo = window.fetch;
|
|
||||||
window.fetch = (i, o) => fo((typeof i === 'string' || i instanceof URL) ? fix(String(i)) : i, o);` : ''}
|
|
||||||
// Workers must come from the page's own origin; theirs live on their site (HUDFX's alert box uses a
|
|
||||||
// chromakey worker, and without it the box never renders). Start them from our /worker.js, which imports
|
|
||||||
// their script (their files allow cross-site loading; a blob: worker would break our Content-Security-Policy).
|
|
||||||
const NativeWorker = window.Worker;
|
|
||||||
window.Worker = function (url, opts) {
|
|
||||||
const u = new URL(String(url), document.baseURI);
|
|
||||||
if (u.origin !== location.origin) {
|
|
||||||
url = ${esc(ours + 'worker.js')} + '?type=' + (opts && opts.type === 'module' ? 'module' : 'classic') + '&src=' + encodeURIComponent(u.href);
|
|
||||||
}
|
|
||||||
return new NativeWorker(url, opts);
|
|
||||||
};
|
|
||||||
window.Worker.prototype = NativeWorker.prototype;
|
|
||||||
// one volume for everything this page plays
|
|
||||||
const VOL = ${volume};
|
|
||||||
const play = HTMLMediaElement.prototype.play;
|
|
||||||
HTMLMediaElement.prototype.play = function () { this.volume = VOL; return play.apply(this, arguments); };
|
|
||||||
addEventListener('load', () => { if (window.Howler) window.Howler.volume(VOL); });
|
|
||||||
})();
|
|
||||||
</script>`;
|
|
||||||
const css = fs.readFileSync(path.join(__dirname, '..', 'ext', ext.css), 'utf8');
|
|
||||||
html = html.replace(/<head([^>]*)>/i, `<head$1>${head}`).replace(/<\/head>/i, `<style id="heystreamer-css">${css}</style></head>`);
|
|
||||||
res.set('Cache-Control', 'no-store').type('html').send(html);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`[ext] ${name}:`, e.message);
|
|
||||||
res.status(502).send(`${name}: ${e.message}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// HUDFX settings API (GET/POST), forwarded as is
|
|
||||||
router.all('/:uuid/hudfx-api/*', express.raw({ type: '*/*', limit: '1mb' }), async (req, res) => {
|
|
||||||
if (!['GET', 'POST', 'OPTIONS'].includes(req.method)) return res.sendStatus(405);
|
|
||||||
if (req.method === 'OPTIONS') return res.sendStatus(204); // same origin: only sent if something adds custom headers
|
|
||||||
try {
|
|
||||||
const up = new URL(req.params[0] + (req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''), EXT.hudfx.api.from);
|
|
||||||
if (up.origin !== new URL(EXT.hudfx.api.from).origin) return res.sendStatus(400);
|
|
||||||
const headers = {};
|
|
||||||
for (const h of ['content-type', 'authorization', 'accept']) if (req.get(h)) headers[h] = req.get(h);
|
|
||||||
const r = await fetch(up, { method: req.method, headers, body: req.method === 'POST' && req.body?.length ? req.body : undefined });
|
|
||||||
res.status(r.status);
|
|
||||||
if (r.headers.get('content-type')) res.type(r.headers.get('content-type'));
|
|
||||||
res.send(Buffer.from(await r.arrayBuffer()));
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[ext] hudfx-api:', e.message);
|
|
||||||
res.sendStatus(502);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Same-origin stand-in for their Web Workers (see the Worker patch above): imports their worker script.
|
|
||||||
// Only scripts from the embedded sites' own origins.
|
|
||||||
router.get('/:uuid/worker.js', (req, res) => {
|
|
||||||
let src;
|
|
||||||
try { src = new URL(String(req.query.src || '')); } catch { return res.sendStatus(400); }
|
|
||||||
const allowed = Object.keys(EXT).map(target).filter(Boolean).map(u => u.origin);
|
|
||||||
if (src.protocol !== 'https:' || !allowed.includes(src.origin)) return res.sendStatus(400);
|
|
||||||
const code = req.query.type === 'module' ? `import ${JSON.stringify(src.href)};` : `importScripts(${JSON.stringify(src.href)});`;
|
|
||||||
res.set('Cache-Control', 'no-store').type('text/javascript').send(code);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Blerp's /assets/* (main module + its chunks, CSS)
|
|
||||||
router.get('/:uuid/blerp-assets/*', async (req, res) => {
|
|
||||||
const u = target('blerp');
|
|
||||||
if (!u) return res.sendStatus(404);
|
|
||||||
try {
|
|
||||||
const up = new URL('/assets/' + req.params[0], u.origin);
|
|
||||||
if (up.origin !== u.origin || !up.pathname.startsWith('/assets/')) return res.sendStatus(400);
|
|
||||||
const r = await fetch(up);
|
|
||||||
if (!r.ok) return res.sendStatus(r.status);
|
|
||||||
res.set('Cache-Control', 'public, max-age=3600');
|
|
||||||
if (r.headers.get('content-type')) res.type(r.headers.get('content-type'));
|
|
||||||
res.send(Buffer.from(await r.arrayBuffer()));
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[ext] blerp-assets:', e.message);
|
|
||||||
res.sendStatus(502);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = { router, configured };
|
|
||||||
29
src/routers/layout.js
Normal file
29
src/routers/layout.js
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
const express = require('express');
|
||||||
|
const router = express.Router();
|
||||||
|
const db = require('../db');
|
||||||
|
|
||||||
|
router.get('/', (req, res) => {
|
||||||
|
res.render('layout_editor', { layout: db.getLayout(), settings: db.getSettings() });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/', (req, res) => {
|
||||||
|
const b = req.body;
|
||||||
|
db.updateLayout({
|
||||||
|
chat_font_size: parseInt(b.chat_font_size) || 15,
|
||||||
|
chat_font_family: b.chat_font_family || 'Inter, sans-serif',
|
||||||
|
chat_bg_opacity: parseFloat(b.chat_bg_opacity) || 0.45,
|
||||||
|
chat_text_color: b.chat_text_color || '#ffffff',
|
||||||
|
chat_border_radius: parseInt(b.chat_border_radius) || 8,
|
||||||
|
alert_font_size: parseInt(b.alert_font_size) || 32,
|
||||||
|
alert_bg_opacity: parseFloat(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;
|
||||||
|
|
@ -5,47 +5,27 @@ const path = require('path');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const { v4: uuidv4 } = require('uuid');
|
const { v4: uuidv4 } = require('uuid');
|
||||||
const db = require('../db');
|
const db = require('../db');
|
||||||
const library = require('../library');
|
|
||||||
|
|
||||||
// uploads go to public/media (not in git, never touched by deploys); audio, video and images (stickers)
|
|
||||||
const storage = multer.diskStorage({
|
const storage = multer.diskStorage({
|
||||||
destination: path.join(__dirname, '../../public/media'),
|
destination: path.join(__dirname, '../../public/media'),
|
||||||
filename: (req, file, cb) => cb(null, uuidv4() + path.extname(file.originalname).toLowerCase()),
|
filename: (req, file, cb) => cb(null, uuidv4() + path.extname(file.originalname)),
|
||||||
});
|
|
||||||
const upload = multer({
|
|
||||||
storage, limits: { fileSize: 50 * 1024 * 1024, files: 20 },
|
|
||||||
fileFilter: (req, file, cb) => cb(null, !!library.typeOf(file.mimetype, file.originalname)),
|
|
||||||
});
|
});
|
||||||
|
const upload = multer({ storage, limits: { fileSize: 50 * 1024 * 1024 } });
|
||||||
|
|
||||||
router.get('/', (req, res) => {
|
router.get('/', (req, res) => {
|
||||||
const items = library.list();
|
res.render('media', { files: db.getAllMedia() });
|
||||||
const used = library.usage();
|
|
||||||
for (const i of items) i.used = used.get(i.url) || 0;
|
|
||||||
res.render('media', {
|
|
||||||
groups: [
|
|
||||||
{ type: 'video', name: 'Videos', items: items.filter(i => i.type === 'video') },
|
|
||||||
{ type: 'audio', name: 'Sounds', items: items.filter(i => i.type === 'audio') },
|
|
||||||
{ type: 'image', name: 'Stickers & art', items: items.filter(i => i.type === 'image') },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// several files at once; answers JSON for the page's upload (progress bar), redirects for a plain form post
|
router.post('/upload', upload.single('file'), (req, res) => {
|
||||||
router.post('/upload', (req, res) => {
|
if (!req.file) return res.redirect('/media');
|
||||||
upload.array('files', 20)(req, res, err => {
|
db.createMedia({
|
||||||
const json = (req.get('Accept') || '').includes('application/json');
|
filename: req.file.filename,
|
||||||
if (err) {
|
original_name: req.file.originalname,
|
||||||
const msg = err.code === 'LIMIT_FILE_SIZE' ? 'File too big (max 50 MB)' : err.message;
|
media_type: req.file.mimetype.startsWith('video') ? 'video' : 'audio',
|
||||||
return json ? res.status(400).json({ ok: false, error: msg }) : res.status(400).send(msg);
|
size_bytes: req.file.size,
|
||||||
}
|
|
||||||
const files = req.files || [];
|
|
||||||
for (const f of files) {
|
|
||||||
db.createMedia({ filename: f.filename, original_name: f.originalname, media_type: library.typeOf(f.mimetype, f.originalname), size_bytes: f.size });
|
|
||||||
console.log(`[media] Uploaded: ${f.originalname} (${f.size} bytes)`);
|
|
||||||
}
|
|
||||||
if (json) return res.json({ ok: true, saved: files.length, skipped: Math.max(0, (req.headers['x-file-count'] | 0) - files.length) });
|
|
||||||
res.redirect('/media');
|
|
||||||
});
|
});
|
||||||
|
console.log(`[media] Uploaded: ${req.file.originalname} (${req.file.size} bytes)`);
|
||||||
|
res.redirect('/media');
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/:id/delete', (req, res) => {
|
router.post('/:id/delete', (req, res) => {
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
const express = require('express');
|
|
||||||
const crypto = require('crypto');
|
|
||||||
const router = express.Router();
|
|
||||||
const nowplaying = require('../nowplaying');
|
|
||||||
|
|
||||||
// POST /nowplaying (Authorization: Bearer <NOWPLAYING_KEY>) 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;
|
|
||||||
|
|
@ -1,56 +1,18 @@
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const db = require('../db');
|
const db = require('../db');
|
||||||
const ws = require('../ws');
|
|
||||||
const ext = require('./ext');
|
|
||||||
|
|
||||||
// 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)
|
|
||||||
// ?ext=hudfx also embed HUDFX's own overlay page (src/routers/ext.js; needs HUDFX_OVERLAY_URL in .env).
|
|
||||||
// Opt-in, so an OBS that still has its own HUDFX source does not play effects twice.
|
|
||||||
// ?parts=chat,raid only those parts
|
|
||||||
// ?parts=nochat everything except chat (no<part>, several allowed: nochat,noraid)
|
|
||||||
// no ?parts / nothing valid: everything
|
|
||||||
// ?parts=video full-screen video redeems + their notification box (public/alerts/video.js).
|
|
||||||
// Opt-in only (never part of "everything"), so it lives in its own OBS source.
|
|
||||||
const OPT_IN = ['video'];
|
|
||||||
function partsFrom(q) {
|
|
||||||
if (!q) return PARTS;
|
|
||||||
const tokens = String(q).split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
|
|
||||||
const optIn = tokens.filter(t => OPT_IN.includes(t));
|
|
||||||
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)), ...optIn];
|
|
||||||
const asked = tokens.filter(p => PARTS.includes(p) || OPT_IN.includes(p));
|
|
||||||
return asked.length ? asked : PARTS;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ?hudfxvol=0..1 / ?blerpvol=0..1 volume of everything that page plays (default 1)
|
|
||||||
// ?blerp=cx,cy,scale where Blerp's card goes: its centre in px of the 1920x1080 page + size
|
|
||||||
const vol = v => { const n = parseFloat(v); return isFinite(n) ? Math.min(1, Math.max(0, n)) : 1; };
|
|
||||||
function blerpPlace(q) {
|
|
||||||
const n = String(q || '').split(',').map(Number);
|
|
||||||
if (n.length === 3 && n.every(isFinite) && n[2] > 0.1 && n[2] <= 2) return { cx: n[0], cy: n[1], s: n[2] };
|
|
||||||
return { cx: 1725, cy: 365, s: 0.5 }; // under the HUDFX box, above the camera (Game scene)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ?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) => {
|
router.get('/:uuid', (req, res) => {
|
||||||
const settings = db.getOverlaySettings();
|
const settings = db.getSettings();
|
||||||
if (req.params.uuid !== settings.overlay_id) return res.status(404).send('Overlay not found');
|
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),
|
const layout = db.getLayout();
|
||||||
chatBox: chatBoxFrom(req.query.chat), chatFlow: req.query.chatflow === 'up' ? 'up' : 'down', boot: ws.BOOT_ID,
|
res.render('overlay', { layout: false, settings, layout });
|
||||||
ext: { on: ext.configured().filter(n => String(req.query.ext || '').split(',').includes(n)), hudfxVol: vol(req.query.hudfxvol), blerpVol: vol(req.query.blerpvol), blerp: blerpPlace(req.query.blerp) } });
|
});
|
||||||
|
|
||||||
|
router.get('/:uuid/preview', (req, res) => {
|
||||||
|
const settings = db.getSettings();
|
||||||
|
const layout = db.getLayout();
|
||||||
|
res.render('overlay_preview', { layout: false, settings, layout });
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
// Public stats page (no login): stream / week / month / year / all time, the same numbers as the admin Stats page
|
|
||||||
// (periodstats.js + views/_statsbody.ejs). Served at the host in Settings → Public stats page (e.g.
|
|
||||||
// stats.example.com, routed in app.js) and at /public on the admin host (works while logged in even when off).
|
|
||||||
// Never shown here: message text, bots (Settings → Hidden chatters), names of viewers who typed !hideme.
|
|
||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const db = require('../db');
|
|
||||||
const chatlog = require('../chatlog');
|
|
||||||
const watchtime = require('../watchtime');
|
|
||||||
const periodstats = require('../periodstats');
|
|
||||||
const points = require('../points');
|
|
||||||
|
|
||||||
router.get('/', (req, res) => {
|
|
||||||
const st = db.getSettings();
|
|
||||||
if (!st.public_stats_enabled && !req.session?.userId) return res.status(404).send('Not found');
|
|
||||||
chatlog.init(); watchtime.init(); periodstats.init();
|
|
||||||
const range = periodstats.parseRange(req.query, 'all');
|
|
||||||
const user = db.getPrimaryUser();
|
|
||||||
// the streamer herself is counted in the totals but not on the public leaderboards
|
|
||||||
const anonymous = periodstats.optedOut();
|
|
||||||
if (user) { anonymous.keys.add(String(user.twitch_id)); if (user.login) anonymous.logins.add(user.login.toLowerCase()); }
|
|
||||||
const s = periodstats.summary(range, { hidden: chatlog.hiddenUsers(), anonymous });
|
|
||||||
const channel = (st.channel || user?.login || '').replace(/^#/, '');
|
|
||||||
// community ranks (Regular and up, all time), without bots, the streamer and !hideme viewers
|
|
||||||
const hidden = new Set(chatlog.hiddenUsers());
|
|
||||||
const ranks = [...points.everyone().values()]
|
|
||||||
.filter(x => x.level.name !== 'Viewer' && !hidden.has(String(x.login || '').toLowerCase())
|
|
||||||
&& !anonymous.logins.has(String(x.login || '').toLowerCase()) && !anonymous.keys.has(String(x.user_id || x.key)))
|
|
||||||
.sort((a, b) => (b.watchMinutes || 0) - (a.watchMinutes || 0)).map(x => ({ login: x.login, name: x.name, level: x.level.name }));
|
|
||||||
res.set('Cache-Control', 'public, max-age=60');
|
|
||||||
res.render('public_stats', {
|
|
||||||
layout: false, s, q: periodstats.rangeQuery, base: req.baseUrl || '', ranks, view: req.query.v === 'streams' ? 'streams' : 'community', tz: st.timezone || 'UTC',
|
|
||||||
channel, displayName: user?.display_name || channel, live: watchtime.isLive(),
|
|
||||||
preview: !st.public_stats_enabled,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
|
|
@ -1,153 +0,0 @@
|
||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const db = require('../db');
|
|
||||||
const twitch = require('../twitch');
|
|
||||||
const redeems = require('../redeems');
|
|
||||||
|
|
||||||
|
|
||||||
// pickers: the same files the Media page lists (src/library.js)
|
|
||||||
const library = require('../library');
|
|
||||||
const soundOptions = () => library.ofType('audio').map(i => ({ url: i.url, label: i.label, note: i.source === 'upload' ? 'uploaded' : i.note }));
|
|
||||||
const videoOptions = () => library.ofType('video').map(i => ({ url: i.url, label: i.label, note: i.source === 'upload' ? 'uploaded' : null }));
|
|
||||||
const stickerOptions = () => library.ofType('image').map(i => ({ url: i.url, label: i.label, note: i.source === 'upload' ? 'uploaded' : null }));
|
|
||||||
|
|
||||||
// live list of the channel's Custom Power-ups (bits); null when Twitch is not reachable
|
|
||||||
let loggedPowerUps = false;
|
|
||||||
async function twitchPowerUps() {
|
|
||||||
const u = twitch.getUser();
|
|
||||||
if (!u) return null;
|
|
||||||
try {
|
|
||||||
const res = await twitch.helix(`/bits/custom_power_ups?broadcaster_id=${u.twitch_id}`);
|
|
||||||
if (!res.ok) { console.warn(`[redeems] custom power-ups: ${res.status} ${await res.text()}`); return null; }
|
|
||||||
const data = (await res.json()).data || [];
|
|
||||||
if (!loggedPowerUps) { loggedPowerUps = true; console.log(`[redeems] custom power-ups (first load): ${JSON.stringify(data).slice(0, 1500)}`); }
|
|
||||||
return data.map(p => ({
|
|
||||||
kind: 'custom_power_up', key: p.id, title: p.title, bits: p.bits ?? p.cost ?? null,
|
|
||||||
live: p.is_enabled ?? p.enabled ?? true, image: p.image?.url_1x || p.default_image?.url_1x || null,
|
|
||||||
}));
|
|
||||||
} catch (e) { console.warn('[redeems] custom power-ups:', e.message); return null; }
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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 fromTwitchPU = await twitchPowerUps();
|
|
||||||
const powerUps = fromTwitchPU ? [...fromTwitchPU] : [];
|
|
||||||
for (const v of variations) {
|
|
||||||
if (v.kind === 'custom_power_up' && !powerUps.some(p => p.key === v.key)) {
|
|
||||||
powerUps.push({ kind: 'custom_power_up', key: v.key, title: v.title, bits: null, missing: !!fromTwitchPU });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const uniq = (list) => list.filter((r, i) => list.findIndex(x => x.key === r.key) === i);
|
|
||||||
const groups = [
|
|
||||||
{ name: 'Custom Power-ups (bits)', id: 'custom-power-ups', items: uniq(powerUps).sort((a, b) => (a.bits ?? 1e9) - (b.bits ?? 1e9)),
|
|
||||||
empty: fromTwitchPU ? 'No Custom Power-ups yet: create them on Twitch (Creator Dashboard → Viewer Rewards → Power-ups).' : 'Could not load your Custom Power-ups from Twitch right now.' },
|
|
||||||
{ 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', {
|
|
||||||
theme: require('../theme').get(),
|
|
||||||
groups, twitchOk: !!fromTwitch, rarity: redeems.RARITY,
|
|
||||||
sounds: soundOptions(),
|
|
||||||
videos: videoOptions(),
|
|
||||||
ttsVoices: db.getAllTtsVoices(),
|
|
||||||
stickers: stickerOptions(),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
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', 'custom_power_up'].includes(kind) || !key) return res.status(400).send('bad trigger');
|
|
||||||
const n = db.getVariationsFor(kind, key).length;
|
|
||||||
const look = require('../theme').get().redeemStyle === 'cassette' ? 'cassette' : 'card'; // Actions → Alerts: look of new variations
|
|
||||||
const v = db.createVariation({ kind, key, title: title || key, name: n ? `${title} ${n + 1}` : (title || key), look });
|
|
||||||
back(res, v);
|
|
||||||
});
|
|
||||||
|
|
||||||
// one variation's fields from the editor. display: card | cassette | sound (sound only) | video
|
|
||||||
function cleanVariation(v, b) {
|
|
||||||
const vol = parseFloat(b.volume);
|
|
||||||
const was = v.video ? 'video' : !v.polaroid ? 'sound' : v.look === 'card' ? 'card' : 'cassette';
|
|
||||||
const display = ['card', 'cassette', 'sound', 'video'].includes(b.display) ? b.display : was;
|
|
||||||
const videos = new Set(videoOptions().map(o => o.url));
|
|
||||||
const video = display === 'video' && videos.has(b.video) ? b.video : '';
|
|
||||||
const on = x => x === true || x === 'on' || x === 1 || x === '1';
|
|
||||||
return {
|
|
||||||
name: String(b.name || '').trim().slice(0, 80) || v.name,
|
|
||||||
rarity: redeems.RARITY[b.rarity] ? b.rarity : v.rarity,
|
|
||||||
sound: String(b.sound || ''),
|
|
||||||
volume: isNaN(vol) ? v.volume : Math.max(0, Math.min(1, vol)),
|
|
||||||
polaroid: display === 'cassette' || display === 'card' ? 1 : 0,
|
|
||||||
look: display === 'card' ? 'card' : display === 'cassette' ? 'cassette' : v.look || '',
|
|
||||||
video,
|
|
||||||
caption: String(b.caption || '').trim().slice(0, 120) || 'redeemed it! ♡',
|
|
||||||
art: String(b.art || ''),
|
|
||||||
enabled: on(b.enabled) ? 1 : 0,
|
|
||||||
tts_voice_id: db.getTtsVoice(parseInt(b.tts_voice_id, 10)) ? parseInt(b.tts_voice_id, 10) : null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save all: { variations: [{ id, ...fields }] } from the editor (one Save button / Ctrl+S)
|
|
||||||
router.post('/save', express.json({ limit: '1mb' }), (req, res) => {
|
|
||||||
const list = Array.isArray(req.body?.variations) ? req.body.variations : [];
|
|
||||||
let saved = 0;
|
|
||||||
for (const b of list) {
|
|
||||||
const v = db.getVariation(parseInt(b.id, 10));
|
|
||||||
if (!v) continue;
|
|
||||||
db.updateVariation(v.id, cleanVariation(v, b));
|
|
||||||
saved++;
|
|
||||||
}
|
|
||||||
res.json({ ok: true, saved });
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/variation/:id', (req, res) => {
|
|
||||||
const v = db.getVariation(req.params.id);
|
|
||||||
if (!v) return res.status(404).send('not found');
|
|
||||||
db.updateVariation(v.id, cleanVariation(v, req.body));
|
|
||||||
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;
|
|
||||||
|
|
@ -1,112 +1,40 @@
|
||||||
// Settings: one page per category (sidebar in views/layout.ejs, list in src/nav.js). Each page saves only its own
|
|
||||||
// fields, so saving one page never resets another. Views: views/settings/<section>.ejs.
|
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const db = require('../db');
|
const db = require('../db');
|
||||||
const ws = require('../ws');
|
const eventsub = require('../eventsub');
|
||||||
|
|
||||||
const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; };
|
router.get('/', (req, res) => {
|
||||||
const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
|
|
||||||
const on = v => v === 'on' ? 1 : 0;
|
|
||||||
const logins = v => String(v || '').split(/[\s,]+/).map(s => s.replace(/^@/, '').toLowerCase()).filter(Boolean).join(', ').slice(0, 2000);
|
|
||||||
const validTz = tz => { try { new Intl.DateTimeFormat('en', { timeZone: tz }); return true; } catch { return false; } };
|
|
||||||
|
|
||||||
// only a real HUDFX overlay link (https://overlays.hudfx.io/overlay/<id>), anything else clears it
|
|
||||||
function hudfxUrl(v) {
|
|
||||||
try {
|
|
||||||
const u = new URL(String(v || '').trim());
|
|
||||||
return u.protocol === 'https:' && u.hostname === 'overlays.hudfx.io' && /^\/overlay\/[\w-]+$/.test(u.pathname) ? u.origin + u.pathname : '';
|
|
||||||
} catch { return ''; }
|
|
||||||
}
|
|
||||||
|
|
||||||
// section -> fields it owns (parsed from the form)
|
|
||||||
const FIELDS = {
|
|
||||||
general: b => ({
|
|
||||||
channel: String(b.channel || '').trim().replace(/^#/, '').toLowerCase().slice(0, 25),
|
|
||||||
timezone: validTz(b.timezone) ? b.timezone : (db.getSettings().timezone || 'UTC'), // invalid: keep the old one
|
|
||||||
}),
|
|
||||||
chat: b => ({
|
|
||||||
message_timeout: int(b.message_timeout, 30), max_messages: int(b.max_messages, 20),
|
|
||||||
chat_hidden_users: logins(b.chat_hidden_users), chat_hide_commands: on(b.chat_hide_commands),
|
|
||||||
gap_audio_enabled: on(b.gap_audio_enabled), gap_audio_url: String(b.gap_audio_url || '').trim(),
|
|
||||||
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),
|
|
||||||
}),
|
|
||||||
tts: b => ({
|
|
||||||
tts_max_chars: Math.max(20, Math.min(500, int(b.tts_max_chars, 200))), tts_say_name: on(b.tts_say_name),
|
|
||||||
tts_blocklist: String(b.tts_blocklist || '').slice(0, 20000),
|
|
||||||
}),
|
|
||||||
stats: b => ({
|
|
||||||
public_stats_enabled: on(b.public_stats_enabled),
|
|
||||||
public_stats_host: String(b.public_stats_host || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '').replace(/[^a-z0-9.-]/g, '').slice(0, 200),
|
|
||||||
}),
|
|
||||||
advanced: b => ({ custom_css: b.custom_css || '', custom_js: b.custom_js || '' }),
|
|
||||||
hudfx: b => ({ hudfx_overlay_url: hudfxUrl(b.hudfx_overlay_url) }),
|
|
||||||
};
|
|
||||||
const PAGES = ['general', 'connections', 'obs', 'chat', 'tts', 'stats', 'backup', 'advanced'];
|
|
||||||
|
|
||||||
function locals(section, req) {
|
|
||||||
const settings = db.getSettings();
|
const settings = db.getSettings();
|
||||||
const base = (process.env.APP_BASE_URL || '').replace(/\/$/, '');
|
const baseUrl = process.env.APP_BASE_URL;
|
||||||
const out = { section, settings, base, overlayUrl: `${base}/overlay/${settings.overlay_id}`, msg: req.query.msg || null, err: req.query.err || null };
|
res.render('settings', { settings, baseUrl });
|
||||||
if (section === 'connections') {
|
});
|
||||||
out.eventsub = require('../eventsub').getStatus();
|
|
||||||
out.se = require('../streamelements').getStatus();
|
router.post('/', (req, res) => {
|
||||||
out.user = db.getPrimaryUser();
|
const b = req.body;
|
||||||
|
db.updateSettings({
|
||||||
|
channel: b.channel || '',
|
||||||
|
message_timeout: parseInt(b.message_timeout) || 30,
|
||||||
|
max_messages: parseInt(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: parseInt(b.gap_audio_min_silence) || 60,
|
||||||
|
gap_audio_min_volume: parseFloat(b.gap_audio_min_volume) || 0.2,
|
||||||
|
gap_audio_max_volume: parseFloat(b.gap_audio_max_volume) || 1.0,
|
||||||
|
gap_audio_loud_after: parseInt(b.gap_audio_loud_after) || 3600,
|
||||||
|
custom_css: b.custom_css || '',
|
||||||
|
custom_js: b.custom_js || '',
|
||||||
|
});
|
||||||
|
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');
|
||||||
}
|
}
|
||||||
if (section === 'chat') out.sounds = require('../library').list().filter(m => m.type === 'audio');
|
res.redirect('/settings');
|
||||||
if (section === 'stats') {
|
|
||||||
out.sync = require('../twitchsync').lastStatus();
|
|
||||||
out.csv = require('../twitchcsv').status();
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
router.get('/', (req, res) => res.redirect('/settings/general'));
|
|
||||||
|
|
||||||
router.get('/:section', (req, res, next) => {
|
|
||||||
const s = req.params.section;
|
|
||||||
if (!PAGES.includes(s)) return next();
|
|
||||||
res.render(`settings/${s}`, locals(s, req));
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/:section', (req, res, next) => {
|
|
||||||
const s = req.params.section;
|
|
||||||
if (!FIELDS[s]) return next();
|
|
||||||
db.updateSettings(FIELDS[s](req.body));
|
|
||||||
ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() }); // overlays update without a reload
|
|
||||||
const page = s === 'hudfx' ? 'connections' : s;
|
|
||||||
res.redirect(`/settings/${page}?msg=` + encodeURIComponent('Saved'));
|
|
||||||
});
|
|
||||||
|
|
||||||
// Connections: StreamElements token (secret: never sent back to the page, only "set / not set")
|
|
||||||
router.post('/connections/se', (req, res) => {
|
|
||||||
const token = String(req.body.se_jwt || '').trim();
|
|
||||||
if (req.body.clear === '1') db.updateSettings({ se_jwt: '' });
|
|
||||||
else if (token) db.updateSettings({ se_jwt: token.slice(0, 4000) });
|
|
||||||
require('../streamelements').restart();
|
|
||||||
res.redirect('/settings/connections?msg=' + encodeURIComponent(req.body.clear === '1' ? 'StreamElements token removed' : token ? 'StreamElements token saved, connecting…' : 'Reconnecting to StreamElements…'));
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/connections/reconnect', (req, res) => {
|
|
||||||
const user = db.getUserById(req.session.userId) || db.getPrimaryUser();
|
|
||||||
if (user) require('../eventsub').start(user);
|
|
||||||
res.redirect('/settings/connections?msg=' + encodeURIComponent('Reconnecting to Twitch…'));
|
|
||||||
});
|
|
||||||
|
|
||||||
// Backup: download / restore the whole setup (src/backup.js)
|
|
||||||
router.get('/backup/export', (req, res) => {
|
|
||||||
const day = new Date().toISOString().slice(0, 10);
|
|
||||||
res.set('Content-Disposition', `attachment; filename="heystreamer-backup-${day}.json"`);
|
|
||||||
res.json(require('../backup').exportAll());
|
|
||||||
});
|
|
||||||
const upload = require('multer')({ storage: require('multer').memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } });
|
|
||||||
router.post('/backup/import', upload.single('file'), (req, res) => {
|
|
||||||
try {
|
|
||||||
const r = require('../backup').importAll(JSON.parse(req.file?.buffer?.toString('utf8') || 'null'));
|
|
||||||
ws.broadcast({ type: 'settings_update', settings: db.getOverlaySettings() });
|
|
||||||
res.redirect('/settings/backup?msg=' + encodeURIComponent(`Imported ${r.variations} redeem variations, ${r.voices} TTS voices and the settings`));
|
|
||||||
} catch (e) { res.redirect('/settings/backup?err=' + encodeURIComponent('Import failed: ' + e.message)); }
|
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|
|
||||||
|
|
@ -1,127 +0,0 @@
|
||||||
// Stats page: one stream / week / month / year / all time (periodstats.js, shared with the public page in
|
|
||||||
// routers/public.js), all-time points board, viewer lookup, public-page opt-out, forget a viewer.
|
|
||||||
// Bots (Settings → Hidden chatters) are counted but left out of everything shown here.
|
|
||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const db = require('../db');
|
|
||||||
const chatlog = require('../chatlog');
|
|
||||||
const watchtime = require('../watchtime');
|
|
||||||
const points = require('../points');
|
|
||||||
const periodstats = require('../periodstats');
|
|
||||||
const twitchsync = require('../twitchsync');
|
|
||||||
const twitchcsv = require('../twitchcsv');
|
|
||||||
const upload = require('multer')({ storage: require('multer').memoryStorage(), limits: { fileSize: 5 * 1024 * 1024, files: 30 } });
|
|
||||||
|
|
||||||
const has = t => !!db.raw().prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t);
|
|
||||||
const all = (sql, ...a) => (has(sql.match(/FROM (\w+)/)[1]) ? db.raw().prepare(sql).all(...a) : []);
|
|
||||||
const one = (sql, ...a) => (has(sql.match(/FROM (\w+)/)[1]) ? db.raw().prepare(sql).get(...a) : null) || {};
|
|
||||||
|
|
||||||
router.get('/', (req, res) => {
|
|
||||||
chatlog.init(); watchtime.init(); periodstats.init();
|
|
||||||
const hidden = chatlog.hiddenUsers();
|
|
||||||
const range = periodstats.parseRange(req.query, 'all');
|
|
||||||
const summary = periodstats.summary(range, { hidden, revenue: true });
|
|
||||||
const viewers = [...points.everyone().values()].filter(x => !hidden.includes(String(x.login || '').toLowerCase()));
|
|
||||||
res.render('stats', {
|
|
||||||
live: watchtime.isLive(),
|
|
||||||
hiddenCount: hidden.length,
|
|
||||||
since: one('SELECT MIN(day) t FROM stat_day').t || null,
|
|
||||||
s: summary, q: periodstats.rangeQuery,
|
|
||||||
pointsBoard: [...viewers].sort((a, b) => b.total - a.total).slice(0, 10).map(x => ({ login: x.login, name: x.name, n: x.total, level: x.level.name })),
|
|
||||||
ranks: viewers.filter(x => x.level.name !== 'Viewer').sort((a, b) => (b.watchMinutes || 0) - (a.watchMinutes || 0)).map(x => ({ login: x.login, name: x.name, level: x.level.name })),
|
|
||||||
view: req.query.v === 'streams' ? 'streams' : 'community',
|
|
||||||
tz: db.getSettings().timezone || 'UTC',
|
|
||||||
publicUrl: publicUrl(),
|
|
||||||
sync: twitchsync.lastStatus(),
|
|
||||||
csv: twitchcsv.status(),
|
|
||||||
msg: req.query.msg || null,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
function publicUrl() {
|
|
||||||
const st = db.getSettings();
|
|
||||||
return st.public_stats_enabled && st.public_stats_host ? `https://${st.public_stats_host}/` : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// one viewer: /stats/viewer?q=<login>
|
|
||||||
router.get('/viewer', (req, res) => {
|
|
||||||
chatlog.init(); watchtime.init();
|
|
||||||
const q = String(req.query.q || '').trim().replace(/^@/, '').toLowerCase();
|
|
||||||
if (!q) return res.redirect('/stats');
|
|
||||||
const v = [...points.everyone().values()].find(x => x.login === q || x.key === q);
|
|
||||||
if (!v) return res.render('stats_viewer', { q, viewer: null });
|
|
||||||
const id = v.user_id;
|
|
||||||
res.render('stats_viewer', {
|
|
||||||
q,
|
|
||||||
viewer: {
|
|
||||||
...v,
|
|
||||||
hidden: chatlog.isHidden(v.login),
|
|
||||||
chat: id ? one('SELECT * FROM chat_user WHERE user_id = ?', id) : {},
|
|
||||||
watch: id ? one('SELECT * FROM watch_user WHERE user_id = ?', id) : {},
|
|
||||||
importedMinutes: watchtime.baselineMinutes(v.login),
|
|
||||||
publicHidden: periodstats.isOptedOut(v.user_id || v.key, v.login),
|
|
||||||
twitch: twitchsync.viewer(id, v.login),
|
|
||||||
badges: (() => { const b = id ? one('SELECT badges, sub_months, at FROM chat_badges WHERE user_id = ?', id) : {}; return { list: JSON.parse(b.badges || '[]'), subMonths: b.sub_months || null, at: b.at || null }; })(),
|
|
||||||
given: (() => {
|
|
||||||
const rows = all('SELECT action, uses, amount FROM chat_action WHERE user_key = ? OR user_login = ?', v.key, v.login);
|
|
||||||
const sum = (types, f) => rows.filter(r => types.includes(r.action)).reduce((a, r) => a + f(r), 0);
|
|
||||||
return { bits: sum(['bits', 'power_up', 'custom_power_up'], r => r.amount), subs: sum(['sub'], r => r.uses),
|
|
||||||
subMonths: sum(['sub'], r => r.amount), gifts: sum(['gift_sub'], r => r.amount) };
|
|
||||||
})(),
|
|
||||||
checkins: id ? one('SELECT COUNT(*) n FROM stream_checkin WHERE user_id = ?', id).n || 0 : 0,
|
|
||||||
emotes: id ? all('SELECT emote, source, emote_id, uses FROM chat_emote WHERE user_id = ? ORDER BY uses DESC LIMIT 20', id) : [],
|
|
||||||
commands: id ? all('SELECT command, uses, last_used FROM chat_command WHERE user_id = ? ORDER BY uses DESC LIMIT 20', id) : [],
|
|
||||||
actions: all('SELECT action, item, uses, amount, unit, last_at FROM chat_action WHERE user_key = ? OR user_login = ? ORDER BY last_at DESC', v.key, v.login),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// pull followers, subs, roles, bits, emotes, VODs from Twitch now
|
|
||||||
router.post('/sync', async (req, res) => {
|
|
||||||
const st = await twitchsync.sync();
|
|
||||||
const bad = Object.entries(st.parts || {}).filter(([, v]) => !String(v).startsWith('ok'));
|
|
||||||
const text = bad.length ? `Sync with Twitch: ${bad.map(([k, v]) => `${k} failed (${v})`).join('; ')}` : 'Synced with Twitch';
|
|
||||||
res.redirect(req.query.back === 'settings' ? `/settings/stats?${bad.length ? 'err' : 'msg'}=` + encodeURIComponent(text) : '/stats?msg=' + encodeURIComponent(text));
|
|
||||||
});
|
|
||||||
|
|
||||||
// Twitch Creator Dashboard "Analytics and Revenue by day" CSV exports (several at once; importing again is safe)
|
|
||||||
router.post('/import-twitch', upload.array('files'), (req, res) => {
|
|
||||||
const done = [], bad = [];
|
|
||||||
for (const f of req.files || []) {
|
|
||||||
try { const r = twitchcsv.importCsv(f.buffer.toString('utf8')); done.push(r); }
|
|
||||||
catch (e) { bad.push(`${f.originalname}: ${e.message}`); }
|
|
||||||
}
|
|
||||||
const days = done.reduce((a, r) => a + r.days, 0);
|
|
||||||
const from = done.map(r => r.from).filter(Boolean).sort()[0], to = done.map(r => r.to).filter(Boolean).sort().pop();
|
|
||||||
const msg = (done.length ? `Imported ${days} days of Twitch analytics${from ? ` (${from} – ${to})` : ''} from ${done.length} file${done.length === 1 ? '' : 's'}.` : '')
|
|
||||||
+ (bad.length ? ` Import failed: ${bad.join('; ')}` : '');
|
|
||||||
res.redirect((req.query.back === 'settings' ? '/settings/stats?msg=' : '/stats?msg=') + encodeURIComponent(msg || 'No files chosen'));
|
|
||||||
});
|
|
||||||
|
|
||||||
// renamed on Twitch: move a viewer's StreamElements watch time (from before our tracking) to the new name
|
|
||||||
router.post('/viewer/rename', (req, res) => {
|
|
||||||
try {
|
|
||||||
const to = watchtime.renameBaseline(req.body.from, req.body.to);
|
|
||||||
res.redirect('/stats/viewer?q=' + encodeURIComponent(to));
|
|
||||||
} catch (e) { res.redirect('/stats?msg=' + encodeURIComponent('Rename failed: ' + e.message)); }
|
|
||||||
});
|
|
||||||
|
|
||||||
// public stats page: leave out / show again (same as the viewer typing !hideme / !showme)
|
|
||||||
router.post('/viewer/public', (req, res) => {
|
|
||||||
const login = String(req.body.login || '').toLowerCase(), key = String(req.body.user_id || '') || `name:${login}`;
|
|
||||||
periodstats.setOptout(key, login, req.body.hide === '1');
|
|
||||||
res.redirect('/stats/viewer?q=' + encodeURIComponent(login));
|
|
||||||
});
|
|
||||||
|
|
||||||
// removal request: forget a viewer completely (stats, watch time, raw chat; activity log entries too)
|
|
||||||
router.post('/viewer/forget', (req, res) => {
|
|
||||||
const login = String(req.body.login || '').toLowerCase(), id = String(req.body.user_id || '');
|
|
||||||
if (id) { chatlog.forgetUser(id); watchtime.forgetUser(id); } else if (login) chatlog.forgetUser(login);
|
|
||||||
periodstats.forgetUser(id || null, login || null); // also the rows keyed by name (tips, watch streaks)
|
|
||||||
if (login) db.raw().prepare('DELETE FROM activity_log WHERE lower(username) = ?').run(login);
|
|
||||||
if (login && has('watch_import')) db.raw().prepare('DELETE FROM watch_import WHERE user_login = ?').run(login); // StreamElements minutes too
|
|
||||||
console.log(`[stats] forgot viewer ${login || id}`);
|
|
||||||
res.redirect('/stats');
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
// /tts — TTS voice builder: combine engines, voices, pitch/speed, layers and effects, test, save as named voices.
|
|
||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
const db = require('../db');
|
|
||||||
const tts = require('../tts');
|
|
||||||
|
|
||||||
router.get('/', async (req, res) => {
|
|
||||||
let voices = null, error = null;
|
|
||||||
try { voices = await tts.voices(); }
|
|
||||||
catch (e) { error = e.message; }
|
|
||||||
res.render('tts', {
|
|
||||||
voices, error, saved: db.getAllTtsVoices(),
|
|
||||||
effects: Object.fromEntries(Object.entries(tts.EFFECTS).map(([k, e]) => [k, { label: e.label, hint: e.hint }])),
|
|
||||||
limits: tts.LIMITS, defaults: tts.DEFAULT_CONFIG, maxChars: tts.MAX_CHARS,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// play: { config, text } -> { url, ms, cached }
|
|
||||||
router.post('/preview', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const out = await tts.synth(req.body.config, req.body.text);
|
|
||||||
res.json({ ok: true, url: out.url, ms: out.ms, cached: out.cached });
|
|
||||||
} catch (e) {
|
|
||||||
res.status(400).json({ ok: false, error: e.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// save: { id?, name, config } -> { voice }
|
|
||||||
router.post('/voices', (req, res) => {
|
|
||||||
try {
|
|
||||||
const name = String(req.body.name || '').trim().slice(0, 60);
|
|
||||||
if (!name) throw new Error('give the voice a name');
|
|
||||||
const config = tts.normalize(req.body.config);
|
|
||||||
const id = parseInt(req.body.id, 10);
|
|
||||||
if (!isNaN(id) && db.getTtsVoice(id)) db.updateTtsVoice(id, name, config);
|
|
||||||
const voice = !isNaN(id) && db.getTtsVoice(id) ? db.getTtsVoice(id) : db.createTtsVoice(name, config);
|
|
||||||
res.json({ ok: true, voice });
|
|
||||||
} catch (e) {
|
|
||||||
res.status(400).json({ ok: false, error: e.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post('/voices/:id/delete', (req, res) => {
|
|
||||||
db.deleteTtsVoice(req.params.id);
|
|
||||||
res.json({ ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
|
|
@ -9,7 +9,6 @@ const app = require('./app');
|
||||||
const PORT = process.env.PORT || 3000;
|
const PORT = process.env.PORT || 3000;
|
||||||
|
|
||||||
db.init();
|
db.init();
|
||||||
require('./theme').importLegacyFile(); // once: an old public/alerts/theme.js moves into Actions → Alerts
|
|
||||||
|
|
||||||
const server = http.createServer(app);
|
const server = http.createServer(app);
|
||||||
const wss = new WebSocketServer({ server, path: '/ws/overlay' });
|
const wss = new WebSocketServer({ server, path: '/ws/overlay' });
|
||||||
|
|
@ -19,22 +18,4 @@ server.listen(PORT, () => {
|
||||||
console.log(`[server] HeyStreamer running on port ${PORT}`);
|
console.log(`[server] HeyStreamer running on port ${PORT}`);
|
||||||
console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`);
|
console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`);
|
||||||
console.log(`[server] DB_PATH: ${process.env.DB_PATH}`);
|
console.log(`[server] DB_PATH: ${process.env.DB_PATH}`);
|
||||||
|
|
||||||
require('./chatlog').init(); // chat statistics tables + hourly 30-day cleanup of raw messages
|
|
||||||
require('./watchtime').init(); // watch time tables (ticks start when the stream goes live)
|
|
||||||
require('./periodstats').init(); // per day + per stream statistics (backfills once from the tables above)
|
|
||||||
require('./twitchcsv').init(); // Twitch daily analytics imported from CSV (Stats page)
|
|
||||||
if (process.env.EVENTSUB_DISABLED !== '1') require('./twitchsync').start(); // followers, subs, roles, bits, emotes, VODs from Twitch
|
|
||||||
|
|
||||||
// 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');
|
|
||||||
}
|
|
||||||
if (process.env.EVENTSUB_DISABLED !== '1') require('./streamelements').start();
|
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,79 +0,0 @@
|
||||||
// StreamElements tips via the Astro websocket (https://docs.streamelements.com/websockets).
|
|
||||||
// JWT token: Settings → Connections (StreamElements dashboard -> avatar -> channel -> copy JWT token); SE_JWT in .env
|
|
||||||
// still works as a fallback. Empty = off. Saving the token restarts the connection (restart()).
|
|
||||||
// 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
|
|
||||||
|
|
||||||
const jwt = () => (require('./db').getSettings()?.se_jwt || process.env.SE_JWT || '').trim();
|
|
||||||
|
|
||||||
function start() {
|
|
||||||
if (!jwt()) { status.enabled = false; console.log('[se] no StreamElements token: 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: 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, source: require('./db').getSettings()?.se_jwt ? 'settings' : process.env.SE_JWT ? 'env' : null }; }
|
|
||||||
function restart() { stop(); status.error = null; start(); }
|
|
||||||
module.exports = { start, stop, restart, getStatus };
|
|
||||||
102
src/theme.js
102
src/theme.js
|
|
@ -1,102 +0,0 @@
|
||||||
// Alert theme: how alerts look and sound, edited on Actions → Alerts and saved in the database (settings.alert_theme,
|
|
||||||
// JSON). Nothing channel-specific lives in the code or in files: a fresh install uses DEFAULT below (the plain Card
|
|
||||||
// style, no pictures, no sounds); each channel picks its own pictures and sounds from the Media library.
|
|
||||||
// The overlay gets the merged theme through the settings it already receives (S.alert_theme) and reads it per alert,
|
|
||||||
// so a save shows up without reloading OBS.
|
|
||||||
//
|
|
||||||
// style events (follow, sub, ...): 'card' (plain, for everyone) | 'polaroid' (taped photo)
|
|
||||||
// redeemStyle default look of new redeem variations: 'card' | 'cassette'
|
|
||||||
// ttsStyle redeems with a TTS voice: 'card' | 'letter' (envelope letter)
|
|
||||||
// card colours of the Card style
|
|
||||||
// art / sounds per event: media URLs ('' = none). bitsTiers: highest matching min wins, under bitsMin no alert.
|
|
||||||
const db = require('./db');
|
|
||||||
|
|
||||||
const EVENTS = ['follow', 'sub', 'resub', 'prime', 'gift', 'streak', 'raid', 'tip', 'hype'];
|
|
||||||
const DEFAULT = {
|
|
||||||
style: 'card', redeemStyle: 'card', ttsStyle: 'card',
|
|
||||||
card: { accent: '#9146ff', bg: '#ffffff', text: '#1f1f23' },
|
|
||||||
art: Object.fromEntries(EVENTS.map(e => [e, ''])),
|
|
||||||
sounds: { follow: '', sub: '', gift: '', streak: '', raid: '', tip: '', hypeBegin: '', hypeLevel: '', hypeEnd: '' },
|
|
||||||
volume: 0.8,
|
|
||||||
heart: '', raidFallback: '', back: [], // polaroid extras: corner sticker, raid card fallback, photos stacked behind
|
|
||||||
defaultSticker: '', // cassette sticker when a variation has none
|
|
||||||
bitsMin: 1,
|
|
||||||
bitsTiers: [
|
|
||||||
{ min: 1000, art: '', sound: '', volume: null, badge: '#e0457b', hearts: 3 },
|
|
||||||
{ min: 100, art: '', sound: '', volume: null, badge: '#9b6bdc', hearts: 1 },
|
|
||||||
{ min: 1, art: '', sound: '', volume: null, badge: '#8a8aa8', hearts: 0 },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const isObj = x => x && typeof x === 'object' && !Array.isArray(x);
|
|
||||||
function merge(base, over) {
|
|
||||||
if (!isObj(over)) return base;
|
|
||||||
const out = { ...base };
|
|
||||||
for (const [k, v] of Object.entries(over)) out[k] = isObj(base[k]) && isObj(v) ? merge(base[k], v) : v;
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
function get() {
|
|
||||||
let saved = {};
|
|
||||||
try { saved = JSON.parse(db.getSettings()?.alert_theme || '{}'); } catch {}
|
|
||||||
return merge(DEFAULT, saved);
|
|
||||||
}
|
|
||||||
|
|
||||||
// clean a theme coming from the editor: only known keys, URLs as strings, numbers in range
|
|
||||||
function clean(t) {
|
|
||||||
const url = v => typeof v === 'string' && /^(\/[\w\-./%]*|https:\/\/[^\s"'<>]+)$/.test(v.trim()) ? v.trim() : '';
|
|
||||||
const col = (v, d) => /^#[0-9a-f]{6}$/i.test(String(v || '')) ? v : d;
|
|
||||||
const vol = v => { const n = parseFloat(v); return isNaN(n) ? null : Math.max(0, Math.min(1, n)); };
|
|
||||||
const pick = (v, ok, d) => ok.includes(v) ? v : d;
|
|
||||||
return {
|
|
||||||
style: pick(t.style, ['card', 'polaroid'], DEFAULT.style),
|
|
||||||
redeemStyle: pick(t.redeemStyle, ['card', 'cassette'], DEFAULT.redeemStyle),
|
|
||||||
ttsStyle: pick(t.ttsStyle, ['card', 'letter'], DEFAULT.ttsStyle),
|
|
||||||
card: { accent: col(t.card?.accent, DEFAULT.card.accent), bg: col(t.card?.bg, DEFAULT.card.bg), text: col(t.card?.text, DEFAULT.card.text) },
|
|
||||||
art: Object.fromEntries(EVENTS.map(e => [e, url(t.art?.[e])])),
|
|
||||||
sounds: Object.fromEntries(Object.keys(DEFAULT.sounds).map(k => [k, url(t.sounds?.[k])])),
|
|
||||||
volume: vol(t.volume) ?? DEFAULT.volume,
|
|
||||||
heart: url(t.heart), raidFallback: url(t.raidFallback), defaultSticker: url(t.defaultSticker),
|
|
||||||
back: (Array.isArray(t.back) ? t.back : []).map(url).filter(Boolean).slice(0, 12),
|
|
||||||
bitsMin: Math.max(1, parseInt(t.bitsMin, 10) || 1),
|
|
||||||
bitsTiers: (Array.isArray(t.bitsTiers) ? t.bitsTiers : []).map(x => ({
|
|
||||||
min: Math.max(1, parseInt(x.min, 10) || 1), art: url(x.art), sound: url(x.sound), volume: vol(x.volume),
|
|
||||||
badge: col(x.badge, '#8a8aa8'), hearts: Math.max(0, Math.min(3, parseInt(x.hearts, 10) || 0)),
|
|
||||||
})).sort((a, b) => b.min - a.min).slice(0, 12),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function save(t) {
|
|
||||||
const c = clean(t || {});
|
|
||||||
db.updateSettings({ alert_theme: JSON.stringify(c) });
|
|
||||||
return merge(DEFAULT, c);
|
|
||||||
}
|
|
||||||
|
|
||||||
// One-time import of the old public/alerts/theme.js (file-based theme, before the theme moved into the database).
|
|
||||||
// File names there are relative to public/alerts/art and public/alerts/sounds; here they become URLs.
|
|
||||||
function importLegacyFile() {
|
|
||||||
const fs = require('fs'), path = require('path'), vm = require('vm');
|
|
||||||
const file = path.join(__dirname, '..', 'public', 'alerts', 'theme.js');
|
|
||||||
if (!fs.existsSync(file) || (db.getSettings()?.alert_theme || '')) return false;
|
|
||||||
try {
|
|
||||||
const box = { window: {} };
|
|
||||||
vm.runInNewContext(fs.readFileSync(file, 'utf8'), box, { timeout: 500 });
|
|
||||||
const o = box.window.ALERT_THEME || {};
|
|
||||||
const art = n => !n ? '' : /^(\/|https:)/.test(n) ? n : `/alerts/art/${n}`;
|
|
||||||
const snd = n => !n ? '' : /^(\/|https:)/.test(n) ? n : `/alerts/sounds/${n}`;
|
|
||||||
const a = o.art || {}, s = o.sounds || {};
|
|
||||||
save({
|
|
||||||
style: 'polaroid', redeemStyle: 'cassette', ttsStyle: 'letter', card: DEFAULT.card,
|
|
||||||
art: Object.fromEntries(EVENTS.map(e => [e, art(a[e])])),
|
|
||||||
sounds: Object.fromEntries(Object.keys(DEFAULT.sounds).map(k => [k, snd(s[k])])),
|
|
||||||
volume: 0.8, heart: art(a.heart), raidFallback: art(a.raidFallback), back: (a.back || []).map(art),
|
|
||||||
defaultSticker: o.defaultSticker?.path ? `/alerts/${o.defaultSticker.path}` : '',
|
|
||||||
bitsMin: o.bitsMin || 5,
|
|
||||||
bitsTiers: (o.bitsTiers || []).map(t => ({ ...t, art: art(t.art), sound: snd(t.sound), volume: t.volume ?? null })),
|
|
||||||
});
|
|
||||||
console.log('[theme] imported public/alerts/theme.js into the database (Actions → Alerts); the file is no longer used');
|
|
||||||
return true;
|
|
||||||
} catch (e) { console.error('[theme] could not import public/alerts/theme.js:', e.message); return false; }
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { DEFAULT, EVENTS, get, save, clean, merge, importLegacyFile };
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
# Starter TTS blocklist: slurs and phrases that can get a channel in trouble under Twitch's rules when read aloud.
|
|
||||||
# Copied ONCE into Settings -> TTS redeems -> Blocked words (on first start after this was added); edit it there.
|
|
||||||
# Matching (src/tts.js prepareViewerText): whole words, not case-sensitive, plurals (-s/-es/-z) included,
|
|
||||||
# simple swaps (0->o 1->i 3->e 4->a 5->s 7->t @->a $->s) and spaced-out letters (k y s) caught.
|
|
||||||
# Normal swearing is deliberately not here.
|
|
||||||
|
|
||||||
# racial / ethnic slurs
|
|
||||||
nigger
|
|
||||||
nigga
|
|
||||||
sandnigger
|
|
||||||
chink
|
|
||||||
gook
|
|
||||||
spic
|
|
||||||
wetback
|
|
||||||
beaner
|
|
||||||
kike
|
|
||||||
raghead
|
|
||||||
towelhead
|
|
||||||
coon
|
|
||||||
jigaboo
|
|
||||||
porch monkey
|
|
||||||
paki
|
|
||||||
|
|
||||||
# homophobic / transphobic
|
|
||||||
faggot
|
|
||||||
fag
|
|
||||||
dyke
|
|
||||||
tranny
|
|
||||||
shemale
|
|
||||||
|
|
||||||
# ableist
|
|
||||||
retard
|
|
||||||
retarded
|
|
||||||
|
|
||||||
# self-harm / threats
|
|
||||||
kys
|
|
||||||
kill yourself
|
|
||||||
kill urself
|
|
||||||
kill your self
|
|
||||||
neck yourself
|
|
||||||
hang yourself
|
|
||||||
go die
|
|
||||||
|
|
||||||
# sexual violence / minors
|
|
||||||
rape
|
|
||||||
rapist
|
|
||||||
pedo
|
|
||||||
pedophile
|
|
||||||
child porn
|
|
||||||
|
|
||||||
# hate slogans
|
|
||||||
heil hitler
|
|
||||||
sieg heil
|
|
||||||
1488
|
|
||||||
white power
|
|
||||||
gas the jews
|
|
||||||
253
src/tts.js
253
src/tts.js
|
|
@ -1,253 +0,0 @@
|
||||||
// Text-to-speech: engines (Piper, espeak-ng) via the Python worker in tools/tts/worker.py, then ffmpeg for
|
|
||||||
// pitch/speed per layer, mixing up to 3 layers, effects and loudness. Output: cached mp3 in public/tts/.
|
|
||||||
//
|
|
||||||
// A voice config (stored in tts_voices.config, edited on the /tts page):
|
|
||||||
// { layers: [ { engine: 'piper'|'espeak', voice, speaker, speed, pitch, volume, delay } ... up to 3 ],
|
|
||||||
// effects: { stadium: 0..1, echo: 0..1, crush: 0..1, radio: 0..1, robot: 0..1, chorus: 0..1, flanger: 0..1, tremolo: 0..1 } }
|
|
||||||
// pitch is in semitones (changes the voice's character, like the "deep demon"), speed 1 = normal.
|
|
||||||
//
|
|
||||||
// Env: TTS_PYTHON (python with piper-tts, default tools/tts/venv/bin/python), TTS_VOICES_DIR (Piper models,
|
|
||||||
// default tools/tts/voices). See tools/tts/setup.sh.
|
|
||||||
const { spawn, execFile } = require('child_process');
|
|
||||||
const crypto = require('crypto');
|
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
const ROOT = path.join(__dirname, '..');
|
|
||||||
const PY = process.env.TTS_PYTHON || path.join(ROOT, 'tools/tts/venv/bin/python');
|
|
||||||
const WORKER = path.join(ROOT, 'tools/tts/worker.py');
|
|
||||||
const VOICES_DIR = process.env.TTS_VOICES_DIR || path.join(ROOT, 'tools/tts/voices');
|
|
||||||
const OUT_DIR = path.join(ROOT, 'public/tts');
|
|
||||||
const TMP_DIR = path.join(OUT_DIR, 'tmp');
|
|
||||||
const KEEP_FILES = 300; // cached mp3s kept in public/tts (oldest deleted first)
|
|
||||||
const MAX_CHARS = 500; // Twitch chat messages are max 500 characters
|
|
||||||
const SR = 44100;
|
|
||||||
|
|
||||||
const LIMITS = {
|
|
||||||
layers: 3,
|
|
||||||
speed: [0.5, 2], pitch: [-12, 12], volume: [0, 1.5], delay: [0, 1000],
|
|
||||||
};
|
|
||||||
|
|
||||||
// effect key -> label, hint and the ffmpeg filter for amount a (0 < a <= 1)
|
|
||||||
const EFFECTS = {
|
|
||||||
stadium: { label: 'Stadium', hint: 'big hall: long double echo',
|
|
||||||
f: a => `aecho=0.8:0.9:${r(60 + 60 * a)}|${r(120 + 120 * a)}:${n(0.25 + 0.25 * a)}|${n(0.15 + 0.2 * a)}` },
|
|
||||||
echo: { label: 'Echo', hint: 'short cave echo (the demon uses this)',
|
|
||||||
f: a => `aecho=0.8:0.85:${r(40 + 60 * a)}:${n(0.15 + 0.35 * a)}` },
|
|
||||||
crush: { label: '8-bit', hint: 'bit-crushed, glitchy',
|
|
||||||
f: a => `acrusher=bits=${r(8 - 5 * a)}:samples=${r(1 + 6 * a)}:mix=${n(0.4 + 0.5 * a)}` },
|
|
||||||
radio: { label: 'Radio', hint: 'thin, crackly walkie-talkie',
|
|
||||||
f: a => `highpass=f=${r(300 + 300 * a)},lowpass=f=${r(3500 - 1200 * a)},acrusher=bits=8:mix=${n(0.1 + 0.3 * a)},volume=1.5` },
|
|
||||||
robot: { label: 'Robot', hint: 'metallic ring modulation',
|
|
||||||
f: a => `aeval='val(0)*(${n(1 - a)}+${n(a)}*sin(2*PI*${r(30 + 30 * a)}*t))':c=same` },
|
|
||||||
chorus: { label: 'Choir', hint: 'several voices at once',
|
|
||||||
f: a => `chorus=0.6:0.9:50|60|40:${n(0.4 * a)}|${n(0.32 * a)}|${n(0.3 * a)}:0.25|0.4|0.3:2|2.3|1.3` },
|
|
||||||
flanger: { label: 'Warp', hint: 'swooshy jet flanger',
|
|
||||||
f: a => `flanger=delay=${n(2 * a)}:depth=${n(2 + 6 * a)}` },
|
|
||||||
tremolo: { label: 'Shaky', hint: 'wobbling volume',
|
|
||||||
f: a => `tremolo=f=${n(4 + 6 * a)}:d=${n(0.2 + 0.6 * a)}` },
|
|
||||||
};
|
|
||||||
function r(x) { return Math.round(x); }
|
|
||||||
function n(x) { return Number(x.toFixed(3)); }
|
|
||||||
|
|
||||||
const DEFAULT_CONFIG = {
|
|
||||||
layers: [{ engine: 'piper', voice: 'en_GB-alan-medium', speaker: '', speed: 1, pitch: 0, volume: 1, delay: 0 }],
|
|
||||||
effects: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
// ---------- validation ----------
|
|
||||||
const SAFE_NAME = /^[A-Za-z0-9_+-][A-Za-z0-9_.+-]{0,119}$/;
|
|
||||||
const clamp = (v, [lo, hi], d) => { const x = parseFloat(v); return isNaN(x) ? d : Math.max(lo, Math.min(hi, x)); };
|
|
||||||
|
|
||||||
function normalize(input) {
|
|
||||||
const c = typeof input === 'string' ? JSON.parse(input) : (input || {});
|
|
||||||
const layers = (Array.isArray(c.layers) ? c.layers : []).slice(0, LIMITS.layers).map(l => ({
|
|
||||||
engine: l.engine === 'espeak' ? 'espeak' : 'piper',
|
|
||||||
voice: SAFE_NAME.test(l.voice || '') ? l.voice : '', // plain names only: no paths
|
|
||||||
speaker: SAFE_NAME.test(l.speaker ?? '') ? String(l.speaker) : '',
|
|
||||||
speed: clamp(l.speed, LIMITS.speed, 1),
|
|
||||||
pitch: clamp(l.pitch, LIMITS.pitch, 0),
|
|
||||||
volume: clamp(l.volume, LIMITS.volume, 1),
|
|
||||||
delay: Math.round(clamp(l.delay, LIMITS.delay, 0)),
|
|
||||||
})).filter(l => l.voice);
|
|
||||||
if (!layers.length) throw new Error('a voice needs at least one layer');
|
|
||||||
const effects = {};
|
|
||||||
for (const k of Object.keys(EFFECTS)) {
|
|
||||||
const a = clamp(c.effects?.[k], [0, 1], 0);
|
|
||||||
if (a > 0) effects[k] = n(a);
|
|
||||||
}
|
|
||||||
return { layers, effects };
|
|
||||||
}
|
|
||||||
|
|
||||||
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(w => w && !w.startsWith('#'));
|
|
||||||
}
|
|
||||||
// lowercase, look-alike swaps, spaced-out letters joined ("k y s" -> "kys"), only letters/digits, single spaces
|
|
||||||
function normalizeForMatch(text) {
|
|
||||||
return ' ' + String(text).toLowerCase()
|
|
||||||
.replace(/[013457@$!]/g, c => LEET[c] || c)
|
|
||||||
.replace(/(^|[^a-z0-9\u00c0-\u024f])((?:[a-z][\s.\-_*]+){2,}[a-z])(?![a-z])/g, (_, pre, letters) => pre + letters.replace(/[^a-z]/g, ''))
|
|
||||||
.replace(/([a-z])\1{2,}/g, '$1') // niiiice -> nice
|
|
||||||
.replace(/[^a-z0-9\u00c0-\u024f]+/g, ' ').trim() + ' ';
|
|
||||||
}
|
|
||||||
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*$/, '') + '…';
|
|
||||||
// whole words/phrases only (so "raccoon", "spicy", "therapist" are fine), plurals included
|
|
||||||
const hay = normalizeForMatch(t);
|
|
||||||
const blocked = parseBlocklist(blocklist).some(w => {
|
|
||||||
const term = normalizeForMatch(w).trim();
|
|
||||||
if (!term) return false;
|
|
||||||
return new RegExp(` ${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:s|es|z)? `).test(hay);
|
|
||||||
});
|
|
||||||
return { text: t, blocked };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- worker ----------
|
|
||||||
let proc = null, outBuf = '', nextId = 1;
|
|
||||||
const pending = new Map();
|
|
||||||
|
|
||||||
function failAll(err) {
|
|
||||||
for (const p of pending.values()) { clearTimeout(p.timer); p.reject(err); }
|
|
||||||
pending.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
function worker() {
|
|
||||||
if (proc) return proc;
|
|
||||||
proc = spawn(PY, [WORKER], { env: { ...process.env, TTS_VOICES_DIR: VOICES_DIR }, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
||||||
outBuf = '';
|
|
||||||
proc.stdout.on('data', d => {
|
|
||||||
outBuf += d;
|
|
||||||
let i;
|
|
||||||
while ((i = outBuf.indexOf('\n')) >= 0) {
|
|
||||||
const line = outBuf.slice(0, i); outBuf = outBuf.slice(i + 1);
|
|
||||||
let msg; try { msg = JSON.parse(line); } catch { continue; } // ignore stray library output
|
|
||||||
const p = pending.get(msg.id);
|
|
||||||
if (!p) continue;
|
|
||||||
pending.delete(msg.id); clearTimeout(p.timer);
|
|
||||||
msg.ok ? p.resolve(msg) : p.reject(new Error(msg.error || 'TTS failed'));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
proc.stderr.on('data', d => { const s = String(d).trim(); if (s) console.log('[tts-worker]', s.slice(0, 500)); });
|
|
||||||
proc.on('error', e => { console.error('[tts] worker failed to start:', e.message, `(TTS_PYTHON=${PY})`); proc = null; failAll(e); });
|
|
||||||
proc.on('exit', code => { if (proc) console.log(`[tts] worker exited (${code})`); proc = null; failAll(new Error('TTS worker exited')); });
|
|
||||||
return proc;
|
|
||||||
}
|
|
||||||
|
|
||||||
function call(req, timeoutMs = 30000) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const id = nextId++;
|
|
||||||
const timer = setTimeout(() => { pending.delete(id); reject(new Error('TTS worker timed out')); }, timeoutMs);
|
|
||||||
pending.set(id, { resolve, reject, timer });
|
|
||||||
try { worker().stdin.write(JSON.stringify({ ...req, id }) + '\n'); }
|
|
||||||
catch (e) { pending.delete(id); clearTimeout(timer); reject(e); }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let voiceCache = null, voiceCacheAt = 0;
|
|
||||||
async function voices() {
|
|
||||||
if (voiceCache && Date.now() - voiceCacheAt < 60000) return voiceCache;
|
|
||||||
const v = await call({ op: 'voices' }, 60000);
|
|
||||||
voiceCache = { piper: v.piper || [], espeak: v.espeak || [] };
|
|
||||||
voiceCacheAt = Date.now();
|
|
||||||
return voiceCache;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- synthesis ----------
|
|
||||||
function ffmpeg(args) {
|
|
||||||
return new Promise((resolve, reject) => execFile('ffmpeg', args, { timeout: 60000 }, (err, _o, stderr) =>
|
|
||||||
err ? reject(new Error('ffmpeg: ' + String(stderr || err.message).trim().split('\n').slice(-3).join(' '))) : resolve()));
|
|
||||||
}
|
|
||||||
|
|
||||||
function layerFilter(l, i) {
|
|
||||||
const f = [`aresample=${SR}`];
|
|
||||||
if (l.pitch) {
|
|
||||||
const k = Math.pow(2, l.pitch / 12); // shift pitch + formants, keep the length
|
|
||||||
f.push(`asetrate=${r(SR * k)}`, `aresample=${SR}`, `atempo=${n(1 / k)}`);
|
|
||||||
}
|
|
||||||
if (l.volume !== 1) f.push(`volume=${l.volume}`);
|
|
||||||
if (l.delay) f.push(`adelay=${l.delay}|${l.delay}`);
|
|
||||||
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)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Loudness curve: one value 0..1 per 40 ms (peak = 1). The overlay uses it to time the words of the
|
|
||||||
// envelope letter (ink in as they are spoken). ~25 numbers per second of speech.
|
|
||||||
const ENV_STEP_MS = 40;
|
|
||||||
function loudness(file) {
|
|
||||||
return new Promise(resolve => execFile('ffmpeg', ['-loglevel', 'error', '-i', file, '-ac', '1', '-ar', '8000', '-f', 's16le', '-'],
|
|
||||||
{ encoding: 'buffer', maxBuffer: 16 * 1024 * 1024, timeout: 15000 }, (err, out) => {
|
|
||||||
if (err || !out.length) return resolve([]);
|
|
||||||
const step = 8 * ENV_STEP_MS, env = [];
|
|
||||||
for (let i = 0; i + 1 < out.length / 2; i += step) {
|
|
||||||
let sum = 0, n = 0;
|
|
||||||
for (let j = i; j < Math.min(i + step, out.length / 2); j++) { const v = out.readInt16LE(j * 2) / 32768; sum += v * v; n++; }
|
|
||||||
env.push(Math.sqrt(sum / n));
|
|
||||||
}
|
|
||||||
const max = Math.max(...env) || 1;
|
|
||||||
resolve(env.map(v => Math.round(100 * v / max) / 100));
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
function prune() {
|
|
||||||
try {
|
|
||||||
const files = fs.readdirSync(OUT_DIR).filter(f => f.endsWith('.mp3'))
|
|
||||||
.map(f => ({ f, t: fs.statSync(path.join(OUT_DIR, f)).mtimeMs })).sort((a, b) => b.t - a.t);
|
|
||||||
for (const x of files.slice(KEEP_FILES)) fs.unlinkSync(path.join(OUT_DIR, x.f));
|
|
||||||
} catch (e) { console.warn('[tts] prune:', e.message); }
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
if (!text) throw new Error('nothing to say');
|
|
||||||
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, durationMs: await durationMs(file) };
|
|
||||||
|
|
||||||
const t0 = Date.now();
|
|
||||||
fs.mkdirSync(TMP_DIR, { recursive: true });
|
|
||||||
const wavs = config.layers.map((_, i) => path.join(TMP_DIR, `${hash}-${i}.wav`));
|
|
||||||
try {
|
|
||||||
await Promise.all(config.layers.map((l, i) => call(l.engine === 'piper'
|
|
||||||
? { op: 'say', engine: 'piper', voice: l.voice, speaker: l.speaker || null, length_scale: n(1 / l.speed), text, out: wavs[i] }
|
|
||||||
: { op: 'say', engine: 'espeak', voice: l.voice, rate: r(160 * l.speed), text, out: wavs[i] })));
|
|
||||||
|
|
||||||
const parts = config.layers.map(layerFilter);
|
|
||||||
const mixIn = config.layers.map((_, i) => `[l${i}]`).join('');
|
|
||||||
const fx = Object.entries(config.effects).map(([k, a]) => EFFECTS[k].f(a));
|
|
||||||
const chain = [
|
|
||||||
config.layers.length > 1 ? `${mixIn}amix=inputs=${config.layers.length}:duration=longest:normalize=0` : `[l0]anull`,
|
|
||||||
...fx,
|
|
||||||
'loudnorm=I=-16:TP=-1.5',
|
|
||||||
].join(',');
|
|
||||||
await ffmpeg(['-loglevel', 'error', '-y', ...wavs.flatMap(w => ['-i', w]),
|
|
||||||
'-filter_complex', `${parts.join(';')};${chain}[out]`, '-map', '[out]',
|
|
||||||
'-ac', '1', '-ar', String(SR), '-codec:a', 'libmp3lame', '-q:a', '3', file]);
|
|
||||||
} finally {
|
|
||||||
for (const w of wavs) fs.rm(w, { force: true }, () => {});
|
|
||||||
}
|
|
||||||
prune();
|
|
||||||
return { url, file, cached: false, ms: Date.now() - t0, durationMs: await durationMs(file) };
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { voices, synth, loudness, ENV_STEP_MS, normalize, cleanText, prepareViewerText, parseBlocklist, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS };
|
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
// 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 };
|
|
||||||
|
|
@ -1,97 +0,0 @@
|
||||||
// Twitch Creator Dashboard export "Analytics and Revenue by day" (CSV, one row per day, the whole channel), uploaded
|
|
||||||
// on the Stats page. Twitch keeps this history for years; the API does not offer it.
|
|
||||||
// Used for the days BEFORE HeyStreamer counted itself (periodstats.js cutoff): streamed days, hours streamed and
|
|
||||||
// watched, average / peak viewers, follows, chat messages; revenue only on the admin page, never public.
|
|
||||||
// Importing again is safe: rows are per day, a day in two files keeps the more complete row (an export's last
|
|
||||||
// day is often still empty).
|
|
||||||
const db = require('./db');
|
|
||||||
|
|
||||||
// CSV column -> our column
|
|
||||||
const COLS = {
|
|
||||||
'Average Viewers': 'avg_viewers', 'Follows': 'follows', 'Minutes Streamed': 'minutes_streamed', 'Minutes Watched': 'minutes_watched',
|
|
||||||
'Live Views': 'live_views', 'Max Viewers': 'max_viewers', 'Unique Viewers': 'unique_viewers', 'Engaged Viewers': 'engaged_viewers',
|
|
||||||
'Chatters': 'chatters', 'Chat Messages': 'chat_messages', 'Clips Created': 'clips_created', 'Clip Views': 'clip_views',
|
|
||||||
'Ad Breaks (Minutes)': 'ad_minutes', 'Prime Subs': 'prime_subs', 'Total Paid Subs': 'paid_subs', 'Total Gifted Subs': 'gifted_subs',
|
|
||||||
'New Engaged Viewers': 'new_engaged', 'Returning Engaged Viewers': 'returning_engaged',
|
|
||||||
};
|
|
||||||
const REVENUE = ['Sub Revenue', 'Prime Revenue', 'Gifted Subs Revenue', 'Multi-Month Gifted Subs Revenue', 'Bits Revenue', 'Ad Revenue',
|
|
||||||
'Turbo Revenue', 'Game Sales Revenue', 'Extensions Revenue', 'Bounties Revenue', 'Other Bits Interactions Revenue'];
|
|
||||||
|
|
||||||
let ready = false;
|
|
||||||
function init() {
|
|
||||||
if (ready) return;
|
|
||||||
db.raw().exec(`CREATE TABLE IF NOT EXISTS tw_daily (
|
|
||||||
day TEXT PRIMARY KEY,
|
|
||||||
${Object.values(COLS).map(c => `${c} REAL DEFAULT 0`).join(', ')},
|
|
||||||
revenue REAL DEFAULT 0, -- sum of all revenue columns (USD)
|
|
||||||
revenue_json TEXT, -- per type
|
|
||||||
raw_json TEXT, imported_at TEXT
|
|
||||||
)`);
|
|
||||||
ready = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// minimal CSV: quoted fields with "" escapes, , separators, \n or \r\n lines
|
|
||||||
function parseCsv(text) {
|
|
||||||
const rows = [];
|
|
||||||
let row = [], f = '', q = false;
|
|
||||||
for (let i = 0; i < text.length; i++) {
|
|
||||||
const c = text[i];
|
|
||||||
if (q) { if (c === '"') { if (text[i + 1] === '"') { f += '"'; i++; } else q = false; } else f += c; continue; }
|
|
||||||
if (c === '"') q = true;
|
|
||||||
else if (c === ',') { row.push(f); f = ''; }
|
|
||||||
else if (c === '\n') { row.push(f); rows.push(row); row = []; f = ''; }
|
|
||||||
else if (c !== '\r') f += c;
|
|
||||||
}
|
|
||||||
if (f || row.length) { row.push(f); rows.push(row); }
|
|
||||||
return rows.filter(r => r.some(x => x !== ''));
|
|
||||||
}
|
|
||||||
|
|
||||||
const MON = { Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6, Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12 };
|
|
||||||
function dayOf(s) { // "Mon Apr 01 2024" (also accepts 2024-04-01)
|
|
||||||
const m = /([A-Z][a-z]{2}) (\d{1,2}) (\d{4})/.exec(s);
|
|
||||||
if (m && MON[m[1]]) return `${m[3]}-${String(MON[m[1]]).padStart(2, '0')}-${m[2].padStart(2, '0')}`;
|
|
||||||
return /^\d{4}-\d{2}-\d{2}/.test(s) ? s.slice(0, 10) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// -> { days, from, to, replaced, kept }
|
|
||||||
function importCsv(text) {
|
|
||||||
init();
|
|
||||||
const rows = parseCsv(String(text).replace(/^/, ''));
|
|
||||||
if (rows.length < 2) throw new Error('empty file');
|
|
||||||
const head = rows[0].map(h => h.trim());
|
|
||||||
if (head[0] !== 'Date' || !head.includes('Minutes Streamed')) throw new Error('not a Twitch "Analytics and Revenue by day" export');
|
|
||||||
const d = db.raw(), at = new Date().toISOString();
|
|
||||||
const cols = Object.values(COLS);
|
|
||||||
const up = d.prepare(`INSERT OR REPLACE INTO tw_daily (day, ${cols.join(', ')}, revenue, revenue_json, raw_json, imported_at)
|
|
||||||
VALUES (@day, ${cols.map(c => '@' + c).join(', ')}, @revenue, @revenue_json, @raw_json, @imported_at)`);
|
|
||||||
const old = d.prepare('SELECT raw_json FROM tw_daily WHERE day = ?');
|
|
||||||
const weight = obj => Object.values(obj).reduce((a, v) => a + (v === '' ? 0 : 1) + (Math.abs(parseFloat(v)) || 0), 0);
|
|
||||||
let days = 0, kept = 0, from = null, to = null;
|
|
||||||
d.transaction(() => {
|
|
||||||
for (const r of rows.slice(1)) {
|
|
||||||
const raw = Object.fromEntries(head.map((h, i) => [h, (r[i] ?? '').trim()]));
|
|
||||||
const day = dayOf(raw.Date);
|
|
||||||
if (!day) continue;
|
|
||||||
delete raw.Date;
|
|
||||||
const prev = old.get(day);
|
|
||||||
if (prev && weight(JSON.parse(prev.raw_json || '{}')) > weight(raw)) { kept++; continue; } // keep the more complete copy
|
|
||||||
const rec = { day, raw_json: JSON.stringify(raw), imported_at: at };
|
|
||||||
for (const [csv, col] of Object.entries(COLS)) rec[col] = parseFloat(raw[csv]) || 0;
|
|
||||||
const rev = Object.fromEntries(REVENUE.filter(k => raw[k] !== undefined && raw[k] !== '').map(k => [k.replace(/ Revenue$/, ''), parseFloat(raw[k]) || 0]));
|
|
||||||
rec.revenue = +Object.values(rev).reduce((a, v) => a + v, 0).toFixed(2);
|
|
||||||
rec.revenue_json = JSON.stringify(rev);
|
|
||||||
up.run(rec);
|
|
||||||
days++;
|
|
||||||
if (!from || day < from) from = day;
|
|
||||||
if (!to || day > to) to = day;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
return { days, kept, from, to };
|
|
||||||
}
|
|
||||||
|
|
||||||
function status() {
|
|
||||||
init();
|
|
||||||
return db.raw().prepare('SELECT COUNT(*) days, MIN(day) from_day, MAX(day) to_day, SUM(minutes_streamed > 0) streamed FROM tw_daily').get();
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init, importCsv, status, parseCsv, dayOf };
|
|
||||||
|
|
@ -1,190 +0,0 @@
|
||||||
// What Twitch itself knows, copied into the database for the Stats pages. Runs at start, every 6 hours, after each
|
|
||||||
// stream, and from the "Sync with Twitch" button on the Stats page. Each part is independent: a missing scope or a
|
|
||||||
// failed call skips that part (logged once) and keeps the last good copy.
|
|
||||||
//
|
|
||||||
// tw_follower every follower with followed_at (Twitch keeps the whole history: follower growth for all time);
|
|
||||||
// unfollowed_at is set when a sync no longer lists them
|
|
||||||
// tw_sub current subscribers: tier, gift + gifter (no history on Twitch: past subs only from our events)
|
|
||||||
// tw_role moderators (moderation:read), VIPs (channel:read:vips); chat badges add founder / artist etc.
|
|
||||||
// tw_bits all-time bits leaderboard (top 100; includes everything before HeyStreamer)
|
|
||||||
// tw_emote the channel's own emotes (usage is counted by us in chat: periodstats kind 'emote')
|
|
||||||
// stream_session past broadcasts from VODs (title, start, length) that HeyStreamer did not see live.
|
|
||||||
// Twitch keeps VODs 7 days (affiliate) / 60 days (partner): older streams cannot be recovered.
|
|
||||||
//
|
|
||||||
// Not available from Twitch at all: past viewer counts, past titles, emote use outside this channel.
|
|
||||||
const db = require('./db');
|
|
||||||
const twitch = require('./twitch');
|
|
||||||
|
|
||||||
const EVERY_MS = 6 * 60 * 60 * 1000;
|
|
||||||
let timer = null, ready = false, running = null;
|
|
||||||
const status = { at: null, parts: {} }; // part -> 'ok (n)' | 'error message'
|
|
||||||
const warned = new Set();
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
if (ready) return;
|
|
||||||
db.raw().exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS tw_follower (user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, followed_at TEXT, seen_at TEXT, unfollowed_at TEXT);
|
|
||||||
CREATE INDEX IF NOT EXISTS tw_follower_at ON tw_follower(followed_at);
|
|
||||||
CREATE TABLE IF NOT EXISTS tw_sub (user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, tier TEXT, is_gift INTEGER, gifter_login TEXT, gifter_name TEXT, seen_at TEXT);
|
|
||||||
CREATE TABLE IF NOT EXISTS tw_role (user_id TEXT NOT NULL, role TEXT NOT NULL, user_login TEXT, user_name TEXT, seen_at TEXT, PRIMARY KEY (user_id, role));
|
|
||||||
CREATE TABLE IF NOT EXISTS tw_bits (user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, score INTEGER, rank INTEGER, seen_at TEXT);
|
|
||||||
CREATE TABLE IF NOT EXISTS tw_emote (id TEXT PRIMARY KEY, name TEXT, tier TEXT, emote_type TEXT, set_id TEXT, image TEXT, seen_at TEXT, gone INTEGER DEFAULT 0);
|
|
||||||
CREATE TABLE IF NOT EXISTS tw_meta (key TEXT PRIMARY KEY, value TEXT);
|
|
||||||
`);
|
|
||||||
const cols = db.raw().prepare('PRAGMA table_info(stream_session)').all().map(c => c.name);
|
|
||||||
if (cols.length && !cols.includes('source')) db.raw().exec("ALTER TABLE stream_session ADD COLUMN source TEXT DEFAULT 'live'"); // live | vod
|
|
||||||
ready = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function start() {
|
|
||||||
init();
|
|
||||||
clearInterval(timer);
|
|
||||||
timer = setInterval(() => sync().catch(() => {}), EVERY_MS);
|
|
||||||
timer.unref?.();
|
|
||||||
setTimeout(() => sync().catch(() => {}), 20 * 1000).unref?.(); // after EventSub has validated the token
|
|
||||||
}
|
|
||||||
|
|
||||||
// all pages of a Helix list
|
|
||||||
async function pages(path, max = 200) {
|
|
||||||
const out = [];
|
|
||||||
let after = '';
|
|
||||||
for (let i = 0; i < max; i++) {
|
|
||||||
const r = await twitch.helix(path + (after ? `&after=${encodeURIComponent(after)}` : ''));
|
|
||||||
if (r.status === 401 || r.status === 403) { const e = new Error(`no permission (${r.status}): log in again on the dashboard`); e.scope = true; throw e; }
|
|
||||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
||||||
const j = await r.json();
|
|
||||||
out.push(...(j.data || []));
|
|
||||||
after = j.pagination?.cursor;
|
|
||||||
if (!after || !(j.data || []).length) break;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = () => new Date().toISOString();
|
|
||||||
|
|
||||||
const PARTS = {
|
|
||||||
async followers(b) {
|
|
||||||
const list = await pages(`/channels/followers?broadcaster_id=${b}&first=100`);
|
|
||||||
const at = now(), d = db.raw();
|
|
||||||
d.transaction(() => {
|
|
||||||
const up = d.prepare(`INSERT INTO tw_follower (user_id, user_login, user_name, followed_at, seen_at, unfollowed_at) VALUES (?, ?, ?, ?, ?, NULL)
|
|
||||||
ON CONFLICT(user_id) DO UPDATE SET user_login = excluded.user_login, user_name = excluded.user_name,
|
|
||||||
followed_at = excluded.followed_at, seen_at = excluded.seen_at, unfollowed_at = NULL`);
|
|
||||||
for (const f of list) up.run(f.user_id, f.user_login, f.user_name, f.followed_at, at);
|
|
||||||
d.prepare('UPDATE tw_follower SET unfollowed_at = ? WHERE seen_at < ? AND unfollowed_at IS NULL').run(at, at);
|
|
||||||
})();
|
|
||||||
return list.length;
|
|
||||||
},
|
|
||||||
async subs(b) {
|
|
||||||
const list = await pages(`/subscriptions?broadcaster_id=${b}&first=100`);
|
|
||||||
const at = now(), d = db.raw();
|
|
||||||
d.transaction(() => {
|
|
||||||
d.prepare('DELETE FROM tw_sub').run();
|
|
||||||
const ins = d.prepare('INSERT OR REPLACE INTO tw_sub (user_id, user_login, user_name, tier, is_gift, gifter_login, gifter_name, seen_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
|
|
||||||
for (const s of list) ins.run(s.user_id, s.user_login, s.user_name, s.tier, s.is_gift ? 1 : 0, s.gifter_login || null, s.gifter_name || null, at);
|
|
||||||
})();
|
|
||||||
return list.length;
|
|
||||||
},
|
|
||||||
async mods(b) { return roles(b, 'moderator', `/moderation/moderators?broadcaster_id=${b}&first=100`); },
|
|
||||||
async vips(b) { return roles(b, 'vip', `/channels/vips?broadcaster_id=${b}&first=100`); },
|
|
||||||
async bits() {
|
|
||||||
const r = await twitch.helix('/bits/leaderboard?count=100&period=all');
|
|
||||||
if (r.status === 401 || r.status === 403) { const e = new Error(`no permission (${r.status})`); e.scope = true; throw e; }
|
|
||||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
||||||
const list = (await r.json()).data || [];
|
|
||||||
const at = now(), d = db.raw();
|
|
||||||
d.transaction(() => {
|
|
||||||
d.prepare('DELETE FROM tw_bits').run();
|
|
||||||
const ins = d.prepare('INSERT INTO tw_bits (user_id, user_login, user_name, score, rank, seen_at) VALUES (?, ?, ?, ?, ?, ?)');
|
|
||||||
for (const x of list) ins.run(x.user_id, x.user_login, x.user_name, x.score, x.rank, at);
|
|
||||||
})();
|
|
||||||
return list.length;
|
|
||||||
},
|
|
||||||
async emotes(b) {
|
|
||||||
const r = await twitch.helix(`/chat/emotes?broadcaster_id=${b}`);
|
|
||||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
||||||
const list = (await r.json()).data || [];
|
|
||||||
const at = now(), d = db.raw();
|
|
||||||
d.transaction(() => {
|
|
||||||
const up = d.prepare(`INSERT INTO tw_emote (id, name, tier, emote_type, set_id, image, seen_at, gone) VALUES (?, ?, ?, ?, ?, ?, ?, 0)
|
|
||||||
ON CONFLICT(id) DO UPDATE SET name = excluded.name, tier = excluded.tier, emote_type = excluded.emote_type,
|
|
||||||
set_id = excluded.set_id, image = excluded.image, seen_at = excluded.seen_at, gone = 0`);
|
|
||||||
for (const e of list) up.run(e.id, e.name, e.tier || null, e.emote_type || null, e.emote_set_id || null, e.images?.url_2x || e.images?.url_1x || null, at);
|
|
||||||
d.prepare('UPDATE tw_emote SET gone = 1 WHERE seen_at < ?').run(at); // removed from the channel: kept for history
|
|
||||||
})();
|
|
||||||
return list.length;
|
|
||||||
},
|
|
||||||
async vods(b) {
|
|
||||||
const list = await pages(`/videos?user_id=${b}&type=archive&first=100`, 5);
|
|
||||||
const d = db.raw();
|
|
||||||
let added = 0;
|
|
||||||
const secs = s => { const m = /(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/.exec(s || '') || []; return (+m[1] || 0) * 3600 + (+m[2] || 0) * 60 + (+m[3] || 0); };
|
|
||||||
d.transaction(() => {
|
|
||||||
for (const v of list) {
|
|
||||||
if (!v.stream_id) continue;
|
|
||||||
const start = v.created_at, end = new Date(Date.parse(v.created_at) + secs(v.duration) * 1000).toISOString();
|
|
||||||
const known = d.prepare('SELECT id FROM stream_session WHERE id = ?').get(String(v.stream_id));
|
|
||||||
if (known) { d.prepare('UPDATE stream_session SET title = COALESCE(title, ?) WHERE id = ?').run(v.title || null, String(v.stream_id)); continue; }
|
|
||||||
d.prepare("INSERT INTO stream_session (id, started_at, ended_at, ticks, title, source) VALUES (?, ?, ?, 0, ?, 'vod')").run(String(v.stream_id), start, end, v.title || null);
|
|
||||||
added++;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
return `${list.length} VODs, ${added} new`;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
async function roles(b, role, path) {
|
|
||||||
const list = await pages(path);
|
|
||||||
const at = now(), d = db.raw();
|
|
||||||
d.transaction(() => {
|
|
||||||
d.prepare('DELETE FROM tw_role WHERE role = ?').run(role);
|
|
||||||
const ins = d.prepare('INSERT OR REPLACE INTO tw_role (user_id, role, user_login, user_name, seen_at) VALUES (?, ?, ?, ?, ?)');
|
|
||||||
for (const x of list) ins.run(x.user_id, role, x.user_login, x.user_name, at);
|
|
||||||
})();
|
|
||||||
return list.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
// only = list of part names (default: all)
|
|
||||||
function sync(only) {
|
|
||||||
if (running) return running;
|
|
||||||
init();
|
|
||||||
const u = twitch.getUser();
|
|
||||||
if (!u) return Promise.resolve(status);
|
|
||||||
require('./watchtime').init();
|
|
||||||
running = (async () => {
|
|
||||||
for (const [name, fn] of Object.entries(PARTS)) {
|
|
||||||
if (only && !only.includes(name)) continue;
|
|
||||||
try { status.parts[name] = `ok (${await fn(u.twitch_id)})`; warned.delete(name); }
|
|
||||||
catch (e) {
|
|
||||||
status.parts[name] = e.message;
|
|
||||||
if (!warned.has(name)) { warned.add(name); console.warn(`[twitchsync] ${name}: ${e.message}`); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
status.at = now();
|
|
||||||
db.raw().prepare("INSERT OR REPLACE INTO tw_meta (key, value) VALUES ('last_sync', ?)").run(JSON.stringify(status));
|
|
||||||
console.log('[twitchsync] done:', Object.entries(status.parts).map(([k, v]) => `${k} ${v}`).join(', '));
|
|
||||||
return status;
|
|
||||||
})().finally(() => { running = null; });
|
|
||||||
return running;
|
|
||||||
}
|
|
||||||
|
|
||||||
function lastStatus() {
|
|
||||||
init();
|
|
||||||
if (status.at) return status;
|
|
||||||
try { return JSON.parse(db.raw().prepare("SELECT value FROM tw_meta WHERE key = 'last_sync'").get()?.value || 'null') || status; } catch { return status; }
|
|
||||||
}
|
|
||||||
|
|
||||||
// one viewer, from the synced tables (the viewer page)
|
|
||||||
function viewer(userId, login) {
|
|
||||||
init();
|
|
||||||
const d = db.raw(), id = String(userId || ''), lg = String(login || '').toLowerCase();
|
|
||||||
const by = t => d.prepare(`SELECT * FROM ${t} WHERE user_id = ? OR lower(user_login) = ?`).get(id, lg) || null;
|
|
||||||
return {
|
|
||||||
follower: by('tw_follower'),
|
|
||||||
sub: by('tw_sub'),
|
|
||||||
roles: d.prepare('SELECT role FROM tw_role WHERE user_id = ? OR lower(user_login) = ?').all(id, lg).map(r => r.role),
|
|
||||||
bits: by('tw_bits'),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init, start, sync, lastStatus, viewer };
|
|
||||||
204
src/watchtime.js
204
src/watchtime.js
|
|
@ -1,204 +0,0 @@
|
||||||
// Watch time. While the channel is live, one tick every 5 minutes: the chatter list (Helix GET /chat/chatters,
|
|
||||||
// lurkers included) gets +1 tick = 5 minutes. Watch time and watch points come from the same tick
|
|
||||||
// (points = ticks x 5), so they can never drift apart.
|
|
||||||
//
|
|
||||||
// stream_session one row per stream (Twitch stream id, start, end)
|
|
||||||
// watch_user per viewer: ticks (x5 = minutes and points), first/last seen watching
|
|
||||||
// watch_user_day per viewer per day: ticks
|
|
||||||
// stream_checkin per viewer per stream: first chat message time (point system check-in)
|
|
||||||
// stream_session also keeps the stream's title, game, peak + average viewer count (Helix /streams, every tick)
|
|
||||||
// stream_viewers viewer count every 5 minutes while live (the viewer graph of a stream)
|
|
||||||
// stream_change every title / category change, live or not (EventSub channel.update + the /streams check)
|
|
||||||
// watch_import StreamElements watch time from before our own tracking (imported once before HeyStreamer counted; the
|
|
||||||
// importer is gone, the minutes stay as a fixed baseline for watch time, points and levels)
|
|
||||||
//
|
|
||||||
// Every tick also goes to periodstats.js (per day + per stream).
|
|
||||||
// Live state: EventSub stream.online / stream.offline, plus a Helix /streams check at start (server restarted
|
|
||||||
// mid-stream). Needs the moderator:read:chatters scope; without it the tick logs once and skips.
|
|
||||||
// Bots are counted (statistics hide Settings → Hidden chatters when showing data, see chatlog.js).
|
|
||||||
const db = require('./db');
|
|
||||||
const twitch = require('./twitch');
|
|
||||||
|
|
||||||
const TICK_MS = 5 * 60 * 1000;
|
|
||||||
let live = null; // { id, started_at } of the current stream
|
|
||||||
let timer = null, ready = false, warnedScope = false;
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
if (ready) return;
|
|
||||||
db.raw().exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS stream_session (id TEXT PRIMARY KEY, started_at TEXT, ended_at TEXT, ticks INTEGER DEFAULT 0);
|
|
||||||
CREATE TABLE IF NOT EXISTS watch_user (
|
|
||||||
user_id TEXT PRIMARY KEY, user_login TEXT, user_name TEXT, ticks INTEGER DEFAULT 0, first_seen TEXT, last_seen TEXT
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS watch_user_day (
|
|
||||||
user_id TEXT NOT NULL, day TEXT NOT NULL, ticks INTEGER DEFAULT 0, PRIMARY KEY (user_id, day)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS stream_checkin (
|
|
||||||
stream_id TEXT NOT NULL, user_id TEXT NOT NULL, at TEXT, PRIMARY KEY (stream_id, user_id)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS stream_viewers (stream_id TEXT NOT NULL, at TEXT NOT NULL, viewers INTEGER, PRIMARY KEY (stream_id, at));
|
|
||||||
CREATE TABLE IF NOT EXISTS stream_change ( -- every title / category change (channel.update + the /streams check)
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT, stream_id TEXT DEFAULT '', at TEXT NOT NULL, title TEXT, game TEXT
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS stream_change_stream ON stream_change(stream_id);
|
|
||||||
CREATE TABLE IF NOT EXISTS watch_import (
|
|
||||||
user_login TEXT PRIMARY KEY, minutes INTEGER NOT NULL, source TEXT, imported_at TEXT
|
|
||||||
);
|
|
||||||
`);
|
|
||||||
const cols = db.raw().prepare('PRAGMA table_info(stream_session)').all().map(c => c.name);
|
|
||||||
for (const [c, def] of [['title', 'TEXT'], ['game', 'TEXT'], ['peak_viewers', 'INTEGER'], ['viewer_sum', 'INTEGER DEFAULT 0'], ['viewer_samples', 'INTEGER DEFAULT 0']]) {
|
|
||||||
if (!cols.includes(c)) db.raw().exec(`ALTER TABLE stream_session ADD COLUMN ${c} ${def}`);
|
|
||||||
}
|
|
||||||
ready = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// title, game and viewer count of the running stream (Helix /streams); count = also sample the viewer count
|
|
||||||
async function refreshStream(count) {
|
|
||||||
if (!live) return;
|
|
||||||
const u = twitch.getUser();
|
|
||||||
if (!u) return;
|
|
||||||
try {
|
|
||||||
const r = await twitch.helix(`/streams?user_id=${u.twitch_id}`);
|
|
||||||
if (!r.ok) return;
|
|
||||||
const s = (await r.json()).data?.[0];
|
|
||||||
if (!s || !live || String(s.id) !== live.id) return;
|
|
||||||
channelUpdate(s.title, s.game_name);
|
|
||||||
if (count) db.raw().prepare('INSERT OR IGNORE INTO stream_viewers (stream_id, at, viewers) VALUES (?, ?, ?)').run(live.id, new Date().toISOString(), s.viewer_count || 0);
|
|
||||||
db.raw().prepare(`UPDATE stream_session SET title = ?, game = ?, peak_viewers = MAX(COALESCE(peak_viewers, 0), ?),
|
|
||||||
viewer_sum = viewer_sum + ?, viewer_samples = viewer_samples + ? WHERE id = ?`)
|
|
||||||
.run(s.title || null, s.game_name || null, s.viewer_count || 0, count ? s.viewer_count || 0 : 0, count ? 1 : 0, live.id);
|
|
||||||
} catch (e) { console.warn('[watchtime] stream info:', e.message); }
|
|
||||||
}
|
|
||||||
|
|
||||||
function startTicking() {
|
|
||||||
clearInterval(timer);
|
|
||||||
timer = setInterval(() => tick().catch(e => console.warn('[watchtime] tick:', e.message)), TICK_MS);
|
|
||||||
timer.unref?.();
|
|
||||||
}
|
|
||||||
|
|
||||||
function online(id, startedAt) {
|
|
||||||
init();
|
|
||||||
if (live?.id === id) return;
|
|
||||||
live = { id: String(id), started_at: startedAt || new Date().toISOString() };
|
|
||||||
db.raw().prepare('INSERT OR IGNORE INTO stream_session (id, started_at) VALUES (?, ?)').run(live.id, live.started_at);
|
|
||||||
console.log(`[watchtime] live (stream ${live.id}) — counting every 5 min`);
|
|
||||||
startTicking();
|
|
||||||
setTimeout(() => refreshStream(false), 60 * 1000).unref?.(); // /streams lists a new stream with a short delay
|
|
||||||
}
|
|
||||||
|
|
||||||
function offline() {
|
|
||||||
init();
|
|
||||||
if (!live) return;
|
|
||||||
db.raw().prepare('UPDATE stream_session SET ended_at = ? WHERE id = ?').run(new Date().toISOString(), live.id);
|
|
||||||
console.log(`[watchtime] offline (stream ${live.id})`);
|
|
||||||
live = null;
|
|
||||||
clearInterval(timer); timer = null;
|
|
||||||
setTimeout(() => require('./twitchsync').sync().catch(() => {}), 2 * 60 * 1000).unref?.(); // new followers / subs / the VOD
|
|
||||||
}
|
|
||||||
|
|
||||||
// server (re)started: are we live right now?
|
|
||||||
async function checkLive() {
|
|
||||||
init();
|
|
||||||
const u = twitch.getUser();
|
|
||||||
if (!u) return;
|
|
||||||
try {
|
|
||||||
const r = await twitch.helix(`/streams?user_id=${u.twitch_id}`);
|
|
||||||
if (!r.ok) return;
|
|
||||||
const s = (await r.json()).data?.[0];
|
|
||||||
if (s) online(s.id, s.started_at); else offline();
|
|
||||||
} catch (e) { console.warn('[watchtime] live check:', e.message); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function chatters() {
|
|
||||||
const u = twitch.getUser();
|
|
||||||
const out = [];
|
|
||||||
let after = '';
|
|
||||||
for (let page = 0; page < 20; page++) {
|
|
||||||
const r = await twitch.helix(`/chat/chatters?broadcaster_id=${u.twitch_id}&moderator_id=${u.twitch_id}&first=1000${after ? `&after=${after}` : ''}`);
|
|
||||||
if (r.status === 401 || r.status === 403) {
|
|
||||||
if (!warnedScope) { warnedScope = true; console.warn('[watchtime] no permission to read the chatter list: log in again on the dashboard (moderator:read:chatters)'); }
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (!r.ok) throw new Error(`chatters ${r.status}`);
|
|
||||||
const j = await r.json();
|
|
||||||
out.push(...(j.data || []));
|
|
||||||
after = j.pagination?.cursor;
|
|
||||||
if (!after) break;
|
|
||||||
}
|
|
||||||
warnedScope = false;
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function tick() {
|
|
||||||
if (!live) return;
|
|
||||||
const list = await chatters();
|
|
||||||
if (!list) return;
|
|
||||||
const at = new Date().toISOString(), day = at.slice(0, 10);
|
|
||||||
const d = db.raw();
|
|
||||||
d.transaction(() => {
|
|
||||||
const w = d.prepare(`INSERT INTO watch_user (user_id, user_login, user_name, ticks, first_seen, last_seen) VALUES (?, ?, ?, 1, ?, ?)
|
|
||||||
ON CONFLICT(user_id) DO UPDATE SET ticks = ticks + 1, user_login = excluded.user_login,
|
|
||||||
user_name = excluded.user_name, last_seen = excluded.last_seen`);
|
|
||||||
const wd = d.prepare(`INSERT INTO watch_user_day (user_id, day, ticks) VALUES (?, ?, 1)
|
|
||||||
ON CONFLICT(user_id, day) DO UPDATE SET ticks = ticks + 1`);
|
|
||||||
for (const c of list) { w.run(c.user_id, c.user_login, c.user_name, at, at); wd.run(c.user_id, day); }
|
|
||||||
d.prepare('UPDATE stream_session SET ticks = ticks + 1 WHERE id = ?').run(live.id);
|
|
||||||
require('./periodstats').add(list.map(c => ({ key: c.user_id, login: c.user_login, name: c.user_name, kind: 'watch' })), at, live.id);
|
|
||||||
})();
|
|
||||||
refreshStream(true);
|
|
||||||
console.log(`[watchtime] tick: ${list.length} watching`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// chatlog.js: first message of this viewer in the current stream = check-in
|
|
||||||
function checkin(userId) {
|
|
||||||
if (!live || !userId) return false;
|
|
||||||
init();
|
|
||||||
return db.raw().prepare('INSERT OR IGNORE INTO stream_checkin (stream_id, user_id, at) VALUES (?, ?, ?)')
|
|
||||||
.run(live.id, String(userId), new Date().toISOString()).changes > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function forgetUser(userId) {
|
|
||||||
init();
|
|
||||||
for (const t of ['watch_user', 'watch_user_day', 'stream_checkin']) db.raw().prepare(`DELETE FROM ${t} WHERE user_id = ?`).run(String(userId));
|
|
||||||
}
|
|
||||||
|
|
||||||
// title / category changed (EventSub channel.update, or noticed by refreshStream): one row per real change
|
|
||||||
function channelUpdate(title, game) {
|
|
||||||
init();
|
|
||||||
const sid = live?.id || '';
|
|
||||||
const last = db.raw().prepare('SELECT title, game FROM stream_change ORDER BY id DESC LIMIT 1').get();
|
|
||||||
if (last && last.title === (title || null) && last.game === (game || null)) return false;
|
|
||||||
db.raw().prepare('INSERT INTO stream_change (stream_id, at, title, game) VALUES (?, ?, ?, ?)').run(sid, new Date().toISOString(), title || null, game || null);
|
|
||||||
if (sid) db.raw().prepare('UPDATE stream_session SET title = ?, game = ? WHERE id = ?').run(title || null, game || null, sid);
|
|
||||||
console.log(`[watchtime] title/category: ${title} · ${game}`);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isLive = () => !!live;
|
|
||||||
const currentStreamId = () => live?.id || null;
|
|
||||||
|
|
||||||
// StreamElements baseline: minutes of a viewer by login (0 when none)
|
|
||||||
function baselineMinutes(login) {
|
|
||||||
init();
|
|
||||||
return db.raw().prepare('SELECT minutes FROM watch_import WHERE user_login = ?').get(String(login || '').toLowerCase())?.minutes || 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// a viewer known only from the StreamElements baseline renamed on Twitch: move their minutes to the new login
|
|
||||||
function renameBaseline(fromLogin, toLogin) {
|
|
||||||
init();
|
|
||||||
const clean = v => String(v || '').trim().replace(/^@/, '').toLowerCase();
|
|
||||||
const from = clean(fromLogin), to = clean(toLogin);
|
|
||||||
if (!/^\w{2,25}$/.test(from) || !/^\w{2,25}$/.test(to) || from === to) throw new Error('invalid name');
|
|
||||||
const d = db.raw();
|
|
||||||
d.transaction(() => {
|
|
||||||
const old = d.prepare('SELECT minutes, source, imported_at FROM watch_import WHERE user_login = ?').get(from);
|
|
||||||
if (!old) return;
|
|
||||||
d.prepare(`INSERT INTO watch_import (user_login, minutes, source, imported_at) VALUES (?, ?, ?, ?)
|
|
||||||
ON CONFLICT(user_login) DO UPDATE SET minutes = minutes + excluded.minutes`).run(to, old.minutes, old.source, old.imported_at);
|
|
||||||
d.prepare('DELETE FROM watch_import WHERE user_login = ?').run(from);
|
|
||||||
})();
|
|
||||||
console.log(`[watchtime] StreamElements baseline: renamed ${from} -> ${to}`);
|
|
||||||
return to;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { init, online, offline, checkLive, tick, checkin, forgetUser, isLive, currentStreamId, channelUpdate, baselineMinutes, renameBaseline, TICK_MS };
|
|
||||||
30
src/ws.js
30
src/ws.js
|
|
@ -1,35 +1,11 @@
|
||||||
const { WebSocket } = require('ws');
|
const { WebSocket } = require('ws');
|
||||||
|
|
||||||
const clients = new Set();
|
const clients = new Set();
|
||||||
// changes every server start (= every deploy): overlays compare it with the one their page was built with
|
|
||||||
// and reload themselves when it differs, so OBS never keeps running old alert code after an update
|
|
||||||
const BOOT_ID = Date.now().toString(36);
|
|
||||||
|
|
||||||
// Overlay -> server messages. Only accepted from connections that present the overlay UUID
|
|
||||||
// (?overlay=<uuid>, 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) {
|
function init(wss) {
|
||||||
wss.on('connection', (ws, req) => {
|
wss.on('connection', (ws) => {
|
||||||
clients.add(ws);
|
clients.add(ws);
|
||||||
const db = require('./db');
|
console.log(`[ws] Client connected — total: ${clients.size}`);
|
||||||
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}`);
|
|
||||||
ws.send(JSON.stringify({ type: 'hello', boot: BOOT_ID }));
|
|
||||||
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', () => {
|
ws.on('close', () => {
|
||||||
clients.delete(ws);
|
clients.delete(ws);
|
||||||
console.log(`[ws] Client disconnected — total: ${clients.size}`);
|
console.log(`[ws] Client disconnected — total: ${clients.size}`);
|
||||||
|
|
@ -47,4 +23,4 @@ function broadcast(data) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { BOOT_ID, init, broadcast };
|
module.exports = { init, broadcast };
|
||||||
|
|
|
||||||
|
|
@ -1,119 +0,0 @@
|
||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Feishin -> HeyStreamer "now playing".
|
|
||||||
|
|
||||||
Watches Feishin over MPRIS (D-Bus) and POSTs {status, title, artist, album, length, cover} to
|
|
||||||
<HEYSTREAMER_URL>/nowplaying with "Authorization: Bearer <NOWPLAYING_KEY>".
|
|
||||||
|
|
||||||
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()
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
// Static copy of the alert preview (views/alerts_preview.ejs) with the default looks, for viewing without a server:
|
|
||||||
// node tools/preview/export.js <out-dir>
|
|
||||||
// Writes <out-dir>/index.html plus the overlay code under <out-dir>/alerts/. No channel data: defaults only.
|
|
||||||
const fs = require('fs'), path = require('path'), ejs = require('ejs');
|
|
||||||
const root = path.join(__dirname, '..', '..');
|
|
||||||
const out = path.resolve(process.argv[2] || 'alert-preview');
|
|
||||||
const theme = require(path.join(root, 'src', 'theme.js')); // DEFAULT only (no database needed)
|
|
||||||
const SAMPLES = require(path.join(root, 'src', 'alerts.js')).SAMPLES;
|
|
||||||
const themes = {
|
|
||||||
defaults: { label: 'Defaults (Card)', theme: theme.DEFAULT },
|
|
||||||
optional: { label: 'Polaroid / Cassette / Letter', theme: theme.merge(theme.DEFAULT, { style: 'polaroid', redeemStyle: 'cassette', ttsStyle: 'letter' }) },
|
|
||||||
};
|
|
||||||
fs.mkdirSync(path.join(out, 'alerts', 'art'), { recursive: true });
|
|
||||||
for (const f of ['card', 'polaroid', 'cassette', 'fx']) for (const ext of ['js', 'css'])
|
|
||||||
fs.copyFileSync(path.join(root, 'public', 'alerts', `${f}.${ext}`), path.join(out, 'alerts', `${f}.${ext}`));
|
|
||||||
fs.copyFileSync(path.join(root, 'public', 'alerts', 'art', 'placeholder.svg'), path.join(out, 'alerts', 'art', 'placeholder.svg'));
|
|
||||||
const html = ejs.render(fs.readFileSync(path.join(root, 'views', 'alerts_preview.ejs'), 'utf8'), { base: 'alerts/', themes, start: 'defaults', samples: SAMPLES });
|
|
||||||
fs.writeFileSync(path.join(out, 'index.html'), html);
|
|
||||||
console.log(`alert preview written to ${out}/index.html`);
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# One-time TTS setup for HeyStreamer. Run on the server (or dev PC) from anywhere:
|
|
||||||
# tools/tts/setup.sh -> installs Piper into tools/tts/venv and downloads the default voices
|
|
||||||
# tools/tts/setup.sh en_US-amy-medium ... -> downloads extra voices (names: https://huggingface.co/rhasspy/piper-voices)
|
|
||||||
# Needs: python3-venv, ffmpeg, espeak-ng (sudo apt install python3-venv ffmpeg espeak-ng). Restart HeyStreamer afterwards.
|
|
||||||
set -euo pipefail
|
|
||||||
cd "$(dirname "$0")"
|
|
||||||
|
|
||||||
missing=()
|
|
||||||
command -v ffmpeg >/dev/null || missing+=(ffmpeg)
|
|
||||||
# libespeak-ng (comes with espeak-ng). Look for the file: ldconfig is in /sbin, not on a normal user's PATH
|
|
||||||
has_espeak() {
|
|
||||||
compgen -G '/usr/lib/*/libespeak-ng.so*' >/dev/null || compgen -G '/usr/lib*/libespeak-ng.so*' >/dev/null ||
|
|
||||||
/sbin/ldconfig -p 2>/dev/null | grep -q libespeak-ng
|
|
||||||
}
|
|
||||||
has_espeak || missing+=(espeak-ng)
|
|
||||||
python3 -c 'import venv, ensurepip' 2>/dev/null || missing+=(python3-venv)
|
|
||||||
if ((${#missing[@]})); then echo "First install: sudo apt install ${missing[*]}"; exit 1; fi
|
|
||||||
|
|
||||||
[ -x venv/bin/python ] || python3 -m venv venv
|
|
||||||
venv/bin/pip install -q --upgrade pip piper-tts
|
|
||||||
|
|
||||||
# default set (~65 MB each): male-heavy English picks + a few female voices
|
|
||||||
DEFAULT=(
|
|
||||||
en_GB-alan-medium en_GB-northern_english_male-medium en_GB-semaine-medium en_GB-vctk-medium
|
|
||||||
en_US-ryan-high en_US-joe-medium en_US-john-medium en_US-norman-medium en_US-bryce-medium
|
|
||||||
en_US-kusal-medium en_US-mike-medium en_US-hfc_male-medium en_US-arctic-medium
|
|
||||||
en_US-lessac-medium en_US-kristin-medium en_GB-cori-medium
|
|
||||||
)
|
|
||||||
venv/bin/python -m piper.download_voices --download-dir voices "${@:-${DEFAULT[@]}}"
|
|
||||||
echo "Voices in $(pwd)/voices:"; ls voices/*.onnx | sed 's|.*/||; s|\.onnx$||'
|
|
||||||
|
|
@ -1,171 +0,0 @@
|
||||||
#!/usr/bin/env python3
|
|
||||||
"""HeyStreamer TTS worker: one long-running process, started by src/tts.js.
|
|
||||||
|
|
||||||
Reads one JSON request per line on stdin, writes one JSON reply per line on stdout.
|
|
||||||
{"id": 1, "op": "voices"} -> {"id": 1, "ok": true, "piper": [...], "espeak": [...]}
|
|
||||||
{"id": 2, "op": "say", "engine": "piper", "voice": "en_GB-alan-medium", "speaker": null,
|
|
||||||
"length_scale": 1.0, "text": "...", "out": "/path/x.wav"} -> {"id": 2, "ok": true}
|
|
||||||
{"id": 3, "op": "say", "engine": "espeak", "voice": "en-us+klatt", "rate": 160, "pitch": 50,
|
|
||||||
"text": "...", "out": "/path/y.wav"} -> {"id": 3, "ok": true}
|
|
||||||
Errors come back as {"id": n, "ok": false, "error": "..."}.
|
|
||||||
|
|
||||||
Piper: `pip install piper-tts` in this script's venv; voice models (*.onnx + *.onnx.json) in the voices dir.
|
|
||||||
espeak: uses libespeak-ng through ctypes (`apt install espeak-ng`), so no espeak binary is needed.
|
|
||||||
"""
|
|
||||||
import ctypes
|
|
||||||
import ctypes.util
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import wave
|
|
||||||
import array
|
|
||||||
import re
|
|
||||||
|
|
||||||
SAFE_NAME = re.compile(r'^[A-Za-z0-9_+-][A-Za-z0-9_.+-]{0,119}$') # plain names only: no paths
|
|
||||||
|
|
||||||
VOICES_DIR = os.environ.get('TTS_VOICES_DIR') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'voices')
|
|
||||||
|
|
||||||
# ---------- piper ----------
|
|
||||||
_piper = {} # model -> PiperVoice, most recently used last
|
|
||||||
MAX_LOADED = int(os.environ.get('TTS_MAX_LOADED', '4')) # each model is ~100 MB of RAM
|
|
||||||
|
|
||||||
|
|
||||||
def piper_voice(model):
|
|
||||||
if model in _piper:
|
|
||||||
_piper[model] = _piper.pop(model) # mark as recently used
|
|
||||||
return _piper[model]
|
|
||||||
from piper import PiperVoice # imported lazily so espeak works without piper installed
|
|
||||||
if not SAFE_NAME.match(model or ''):
|
|
||||||
raise ValueError('bad voice name')
|
|
||||||
path = os.path.join(VOICES_DIR, model + '.onnx')
|
|
||||||
if not os.path.isfile(path):
|
|
||||||
raise ValueError('unknown piper voice: ' + model)
|
|
||||||
while len(_piper) >= MAX_LOADED:
|
|
||||||
_piper.pop(next(iter(_piper)))
|
|
||||||
_piper[model] = PiperVoice.load(path)
|
|
||||||
return _piper[model]
|
|
||||||
|
|
||||||
|
|
||||||
def piper_list():
|
|
||||||
out = []
|
|
||||||
try:
|
|
||||||
names = sorted(f for f in os.listdir(VOICES_DIR) if f.endswith('.onnx'))
|
|
||||||
except FileNotFoundError:
|
|
||||||
return out
|
|
||||||
for f in names:
|
|
||||||
model = f[:-5]
|
|
||||||
try:
|
|
||||||
with open(os.path.join(VOICES_DIR, f + '.json'), encoding='utf-8') as fh:
|
|
||||||
cfg = json.load(fh)
|
|
||||||
except (OSError, ValueError):
|
|
||||||
continue
|
|
||||||
out.append({
|
|
||||||
'model': model,
|
|
||||||
'language': (cfg.get('language') or {}).get('code') or model.split('-')[0],
|
|
||||||
'quality': (cfg.get('audio') or {}).get('quality') or model.rsplit('-', 1)[-1],
|
|
||||||
'speakers': sorted(cfg.get('speaker_id_map') or {}, key=lambda k: cfg['speaker_id_map'][k]),
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def piper_say(req):
|
|
||||||
from piper import SynthesisConfig
|
|
||||||
v = piper_voice(req['voice'])
|
|
||||||
sid = None
|
|
||||||
spk = req.get('speaker')
|
|
||||||
if spk not in (None, ''):
|
|
||||||
sid = v.config.speaker_id_map.get(spk)
|
|
||||||
if sid is None:
|
|
||||||
raise ValueError('unknown speaker: %s' % spk)
|
|
||||||
cfg = SynthesisConfig(speaker_id=sid, length_scale=float(req.get('length_scale') or 1.0))
|
|
||||||
with wave.open(req['out'], 'wb') as w:
|
|
||||||
v.synthesize_wav(req['text'], w, syn_config=cfg)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- espeak-ng (libespeak-ng via ctypes) ----------
|
|
||||||
_es = {'lib': None, 'rate': 0, 'buf': None, 'cb': None}
|
|
||||||
CALLBACK = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(ctypes.c_short), ctypes.c_int, ctypes.c_void_p)
|
|
||||||
|
|
||||||
|
|
||||||
def espeak_lib():
|
|
||||||
if _es['lib'] is None:
|
|
||||||
name = ctypes.util.find_library('espeak-ng') or 'libespeak-ng.so.1'
|
|
||||||
lib = ctypes.CDLL(name)
|
|
||||||
_es['rate'] = lib.espeak_Initialize(2, 0, None, 0) # AUDIO_OUTPUT_SYNCHRONOUS
|
|
||||||
|
|
||||||
def cb(wav, n, _ev):
|
|
||||||
if wav and n > 0:
|
|
||||||
_es['buf'].extend(wav[:n])
|
|
||||||
return 0
|
|
||||||
_es['cb'] = CALLBACK(cb) # keep a reference, or it gets garbage collected
|
|
||||||
lib.espeak_SetSynthCallback(_es['cb'])
|
|
||||||
_es['lib'] = lib
|
|
||||||
return _es['lib']
|
|
||||||
|
|
||||||
|
|
||||||
def espeak_list():
|
|
||||||
"""English voice + the variant files (klatt, Demonic, croak...), as 'en-us+variant' names."""
|
|
||||||
try:
|
|
||||||
espeak_lib()
|
|
||||||
except OSError:
|
|
||||||
return []
|
|
||||||
variants = []
|
|
||||||
for base in ('/usr/lib/x86_64-linux-gnu/espeak-ng-data/voices/!v', '/usr/lib/aarch64-linux-gnu/espeak-ng-data/voices/!v',
|
|
||||||
'/usr/share/espeak-ng-data/voices/!v', '/usr/lib/espeak-ng-data/voices/!v'):
|
|
||||||
if os.path.isdir(base):
|
|
||||||
variants = sorted(os.listdir(base), key=str.lower)
|
|
||||||
break
|
|
||||||
return ['en-us', 'en'] + ['en-us+' + v for v in variants]
|
|
||||||
|
|
||||||
|
|
||||||
def espeak_say(req):
|
|
||||||
lib = espeak_lib()
|
|
||||||
if not SAFE_NAME.match(str(req.get('voice') or '')):
|
|
||||||
raise ValueError('bad voice name')
|
|
||||||
if lib.espeak_SetVoiceByName(str(req['voice']).encode()) != 0:
|
|
||||||
raise ValueError('unknown espeak voice: %s' % req['voice'])
|
|
||||||
lib.espeak_SetParameter(1, int(req.get('rate') or 160), 0) # espeakRATE (words per minute)
|
|
||||||
lib.espeak_SetParameter(3, int(req.get('pitch') or 50), 0) # espeakPITCH (0-100)
|
|
||||||
_es['buf'] = array.array('h')
|
|
||||||
t = req['text'].encode('utf-8') + b'\0'
|
|
||||||
lib.espeak_Synth(t, len(t), 0, 1, 0, 0, None, None)
|
|
||||||
lib.espeak_Synchronize()
|
|
||||||
with wave.open(req['out'], 'wb') as w:
|
|
||||||
w.setnchannels(1)
|
|
||||||
w.setsampwidth(2)
|
|
||||||
w.setframerate(_es['rate'])
|
|
||||||
w.writeframes(_es['buf'].tobytes())
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- loop ----------
|
|
||||||
def handle(req):
|
|
||||||
op = req.get('op')
|
|
||||||
if op == 'voices':
|
|
||||||
return {'piper': piper_list(), 'espeak': espeak_list()}
|
|
||||||
if op == 'say':
|
|
||||||
if not req.get('text') or not req.get('out'):
|
|
||||||
raise ValueError('text and out are required')
|
|
||||||
{'piper': piper_say, 'espeak': espeak_say}[req['engine']](req)
|
|
||||||
return {}
|
|
||||||
raise ValueError('unknown op: %s' % op)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
for line in sys.stdin:
|
|
||||||
line = line.strip()
|
|
||||||
if not line:
|
|
||||||
continue
|
|
||||||
rid = None
|
|
||||||
try:
|
|
||||||
req = json.loads(line)
|
|
||||||
rid = req.get('id')
|
|
||||||
reply = {'id': rid, 'ok': True}
|
|
||||||
reply.update(handle(req))
|
|
||||||
except Exception as e: # one bad request must not kill the worker
|
|
||||||
reply = {'id': rid, 'ok': False, 'error': '%s: %s' % (type(e).__name__, e)}
|
|
||||||
sys.stdout.write(json.dumps(reply) + '\n')
|
|
||||||
sys.stdout.flush()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
<% if (logs.length === 0) { %>
|
|
||||||
<p><em>No activity yet. Events will appear here once your overlay is connected and Twitch fires events.</em></p>
|
|
||||||
<% } else { %>
|
|
||||||
<figure>
|
|
||||||
<table class="activity">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Time</th>
|
|
||||||
<th>Event</th>
|
|
||||||
<th>User</th>
|
|
||||||
<th>Detail</th>
|
|
||||||
<th><span title="Actions (Actions page) that fired for this event">Actions</span></th>
|
|
||||||
<th></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<% for (const log of logs) { const d = activity.describe(log); %>
|
|
||||||
<tr>
|
|
||||||
<td><small><time datetime="<%= String(log.created_at).replace(' ', 'T') %>Z"><%= log.created_at %> UTC</time></small></td>
|
|
||||||
<td><%= d.label %></td>
|
|
||||||
<td><%= log.username || '—' %></td>
|
|
||||||
<td>
|
|
||||||
<% if (d.title) { %><strong><%= d.title %></strong><% } %>
|
|
||||||
<% for (const tag of d.tags) { %> <span class="badge badge-grey"><%= tag %></span><% } %>
|
|
||||||
<% if (d.message) { %><br><small class="activity-msg">“<%= d.message %>”</small><% } %>
|
|
||||||
<% if (!d.title && !d.tags.length && !d.message) { %>—<% } %>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span class="badge <%= log.actions_fired > 0 ? 'badge-green' : 'badge-grey' %>">
|
|
||||||
<%= log.actions_fired %>
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<% if (activity.canReplay(log)) { %>
|
|
||||||
<button type="button" class="outline activity-replay" data-id="<%= log.id %>"
|
|
||||||
title="<%= log.replay_json ? 'Play this again on the overlay (queued like a real alert, not logged again)' : 'Older event: replays with a fresh pick of the reward\'s variations' %>"
|
|
||||||
style="width:auto; padding:.2rem .6rem; margin:0;">Replay</button>
|
|
||||||
<small class="activity-replay-status"></small>
|
|
||||||
<% } %>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<% } %>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</figure>
|
|
||||||
<% } %>
|
|
||||||
|
|
@ -1,411 +0,0 @@
|
||||||
<%#
|
|
||||||
Shared statistics body for the admin Stats page (views/stats.ejs) and the public page (views/public_stats.ejs).
|
|
||||||
Two views (?v=community | streams) x periods (?p=stream|week|month|year|all).
|
|
||||||
Community: supporters, raids, leaderboards, community ranks, emotes, commands, rewards.
|
|
||||||
Streams: numbers, one activity chart (pick what to show), games played, the streams list; one stream: viewer graph.
|
|
||||||
Locals: s = periodstats.summary(), q = rangeQuery helper, base = link prefix ('/stats', '/public' or '/'),
|
|
||||||
view = 'community' | 'streams', mode = 'admin' | 'public', viewerHref = viewer link prefix or null,
|
|
||||||
extraBoards = [{ title, rows, level, wide }], ranks = [{ login, name, level }] (Regular and up, all time).
|
|
||||||
Colours come from the page: --muted, --line, --accent, --accent-hover, --card (and --card-solid for popups).
|
|
||||||
A new section goes here once and appears on both pages; wrap it in `if (admin)` when it is not for the public.
|
|
||||||
%>
|
|
||||||
<%
|
|
||||||
const admin = locals.mode === 'admin';
|
|
||||||
const esc = v => String(v ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
||||||
const num = n => Number(n || 0).toLocaleString('en-US');
|
|
||||||
const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${String(Math.round(m % 60)).padStart(2, '0')} m` : `${Math.round(m)} m`;
|
|
||||||
const r = s.range, T = s.totals, C = s.channel || {}, TW = s.twitch;
|
|
||||||
const v = locals.view === 'streams' ? 'streams' : 'community';
|
|
||||||
const cur = { p: r.p, d: r.from || undefined, s: r.p === 'stream' ? r.stream.id : undefined };
|
|
||||||
const link = (rq, view = v) => base + q({ ...rq, v: view === 'community' ? undefined : view });
|
|
||||||
const TZ = locals.tz || 'UTC'; // Settings → General → Time zone
|
|
||||||
const day = iso => new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', timeZone: TZ });
|
|
||||||
const time = iso => new Date(iso).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: TZ });
|
|
||||||
const emoteSrc = e => e.source === 'twitch' && e.id ? `https://static-cdn.jtvnw.net/emoticons/v2/${e.id}/default/dark/1.0`
|
|
||||||
: e.source === '7tv' && e.id ? `https://cdn.7tv.app/emote/${e.id}/1x.webp` : null;
|
|
||||||
// ⓘ with an instant tooltip (hover, or tap / keyboard focus)
|
|
||||||
const info = text => text ? ` <span class="sb-i" tabindex="0" data-tip="${esc(text)}">ⓘ</span>` : '';
|
|
||||||
const person = x => { const n = esc(x.name || x.login || '?'); return viewerHref && x.login ? `<a href="${viewerHref}${encodeURIComponent(x.login)}">${n}</a>` : n; };
|
|
||||||
const since = TW && TW.streamedDays ? TW.cutoff : null; // period reaches back before HeyStreamer counted
|
|
||||||
%>
|
|
||||||
<style>
|
|
||||||
.sb-nav { display:flex; flex-wrap:wrap; align-items:center; gap:.5rem 1rem; margin:.4rem 0 1rem; }
|
|
||||||
.sb-views { display:flex; gap:1.2rem; border-bottom:1px solid var(--line); margin:.2rem 0 .8rem; }
|
|
||||||
.sb-views a { padding:.4rem .1rem; text-decoration:none; color:var(--muted); font-weight:700; border-bottom:3px solid transparent; margin-bottom:-1px; }
|
|
||||||
.sb-views a.on { color:inherit; border-bottom-color:var(--accent); }
|
|
||||||
.sb-tabs { display:flex; gap:.25rem; flex-wrap:wrap; }
|
|
||||||
.sb-tabs a { padding:.25rem .8rem; border-radius:99px; border:1px solid var(--line); text-decoration:none; color:inherit; font-size:.85rem; }
|
|
||||||
.sb-tabs a.on { background:var(--accent); border-color:var(--accent); color:#fff; }
|
|
||||||
.sb-step { display:flex; align-items:center; gap:.4rem; margin-left:auto; }
|
|
||||||
.sb-step a, .sb-step span.off { padding:.15rem .6rem; border-radius:8px; border:1px solid var(--line); text-decoration:none; color:inherit; }
|
|
||||||
.sb-step span.off { opacity:.35; }
|
|
||||||
.sb-title { font-weight:700; }
|
|
||||||
.sb-sub { color:var(--muted); font-size:.85rem; }
|
|
||||||
.sb-i { position:relative; cursor:help; color:var(--muted); font-size:.85em; outline:none; }
|
|
||||||
.sb-i:hover::after, .sb-i:focus::after { content:attr(data-tip); position:absolute; left:50%; bottom:calc(100% + 6px); transform:translateX(-50%);
|
|
||||||
width:max-content; max-width:260px; white-space:normal; text-align:left; font-size:.78rem; font-weight:400; line-height:1.35; color:inherit;
|
|
||||||
background:var(--card-solid, var(--card)); border:1px solid var(--line); border-radius:8px; padding:.4rem .55rem;
|
|
||||||
box-shadow:0 6px 18px rgba(0,0,0,.3); z-index:30; }
|
|
||||||
.sb-tiles { display:grid; grid-template-columns:repeat(auto-fit, minmax(140px, 1fr)); gap:.6rem; margin:.2rem 0 1.2rem; }
|
|
||||||
.sb-tile { border:1px solid var(--line); border-radius:12px; padding:.65rem .85rem; background:var(--card); }
|
|
||||||
.sb-tile .v { font-size:1.5rem; font-weight:700; line-height:1.1; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
|
||||||
.sb-tile .k { font-size:.8rem; color:var(--muted); }
|
|
||||||
.sb-h { margin:1.4rem 0 .6rem; font-size:1.1rem; }
|
|
||||||
.sb-streams { width:100%; border-collapse:collapse; font-size:.86rem; }
|
|
||||||
.sb-streams th, .sb-streams td { text-align:left; padding:.4rem .5rem; border-bottom:1px solid var(--line); background:none; vertical-align:top; }
|
|
||||||
.sb-streams th { color:var(--muted); font-weight:600; font-size:.78rem; }
|
|
||||||
.sb-streams td.n { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
|
||||||
.sb-streams .t { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; max-width:20rem; display:block; }
|
|
||||||
.sb-streams .g { color:var(--muted); font-size:.78rem; }
|
|
||||||
.sb-scroll { overflow-x:auto; }
|
|
||||||
.sb-chart { border:1px solid var(--line); border-radius:12px; padding:.7rem .9rem; position:relative; background:var(--card); }
|
|
||||||
.sb-chart h4 { margin:0 0 .4rem; font-size:.95rem; }
|
|
||||||
.sb-chart svg { width:100%; height:auto; display:block; }
|
|
||||||
.sb-chart .bar { fill:var(--accent); }
|
|
||||||
.sb-chart .hit:hover + .bar { fill:var(--accent-hover); }
|
|
||||||
.sb-chart .grid { stroke:var(--line); stroke-width:1; }
|
|
||||||
.sb-chart .ax { fill:var(--muted); font-size:10px; }
|
|
||||||
.sb-metrics { display:flex; flex-wrap:wrap; gap:.3rem; margin-bottom:.5rem; }
|
|
||||||
.sb-metrics button { all:unset; cursor:pointer; padding:.2rem .7rem; border-radius:99px; border:1px solid var(--line); font-size:.8rem; }
|
|
||||||
.sb-metrics button.on { background:var(--accent); border-color:var(--accent); color:#fff; }
|
|
||||||
.sb-tip { position:absolute; pointer-events:none; background:var(--card-solid, var(--card)); border:1px solid var(--line);
|
|
||||||
border-radius:8px; padding:.25rem .5rem; font-size:.8rem; box-shadow:0 4px 12px rgba(0,0,0,.35); white-space:nowrap; display:none; z-index:5; }
|
|
||||||
.sb-two { display:grid; grid-template-columns:minmax(0, 2fr) minmax(260px, 1fr); gap:1rem; align-items:start; }
|
|
||||||
@media (max-width: 800px) { .sb-two { grid-template-columns:1fr; } }
|
|
||||||
.sb-games { display:flex; gap:1rem; align-items:center; flex-wrap:wrap; }
|
|
||||||
.sb-games svg { width:150px; height:150px; flex:none; }
|
|
||||||
.sb-games ul { list-style:none; margin:0; padding:0; flex:1; min-width:160px; max-width:440px; font-size:.85rem; }
|
|
||||||
.sb-games li { list-style:none; display:grid; grid-template-columns:.8rem minmax(0, 1fr) auto; gap:.45rem; align-items:center; padding:.15rem 0; }
|
|
||||||
.sb-games .sw { width:.8rem; height:.8rem; border-radius:3px; }
|
|
||||||
.sb-games .nm { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
||||||
.sb-games .hv { color:var(--muted); font-variant-numeric:tabular-nums; white-space:nowrap; }
|
|
||||||
.sb-boards { display:grid; grid-template-columns:repeat(auto-fill, minmax(290px, 1fr)); gap:1rem; }
|
|
||||||
.sb-board { border:1px solid var(--line); border-radius:12px; padding:.6rem .8rem; background:var(--card); }
|
|
||||||
.sb-board h4 { margin:0 0 .3rem; font-size:.95rem; }
|
|
||||||
.sb-board ol { list-style:none; margin:0; padding:0; }
|
|
||||||
.sb-board li { list-style:none; display:grid; grid-template-columns:1.6rem minmax(0, 1fr) var(--nw, 4.6rem); align-items:center; gap:.5rem;
|
|
||||||
height:2rem; margin:0; padding:0 .2rem; border-bottom:1px solid var(--line); font-size:.88rem; }
|
|
||||||
.sb-board li:last-child { border-bottom:0; }
|
|
||||||
.sb-board .r { color:var(--muted); text-align:right; font-variant-numeric:tabular-nums; }
|
|
||||||
.sb-board .who { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0; }
|
|
||||||
.sb-board .who a { text-decoration:none; }
|
|
||||||
.sb-board .lvl { font-size:.66rem; padding:.02rem .45rem; border-radius:99px; border:1px solid var(--line); color:var(--muted); white-space:nowrap; justify-self:start; }
|
|
||||||
.sb-board .n { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
|
||||||
.sb-board.wide { grid-column:span 2; }
|
|
||||||
.sb-board.wide li { grid-template-columns:1.6rem minmax(0, 1fr) 5.5rem var(--nw, 4.6rem); }
|
|
||||||
@media (max-width: 700px) { .sb-board.wide { grid-column:auto; } }
|
|
||||||
.sb-pills { display:flex; flex-wrap:wrap; gap:.45rem; }
|
|
||||||
.sb-pill { display:flex; align-items:center; gap:.35rem; border:1px solid var(--line); border-radius:99px; padding:.15rem .6rem .15rem .3rem; font-size:.82rem; background:var(--card); }
|
|
||||||
.sb-pill.txt { padding-left:.6rem; }
|
|
||||||
.sb-pill img { width:26px; height:26px; object-fit:contain; }
|
|
||||||
.sb-pill a { text-decoration:none; }
|
|
||||||
.sb-pill .what { color:var(--muted); font-size:.75rem; }
|
|
||||||
.sb-pill.zero { opacity:.5; }
|
|
||||||
.sb-empty { color:var(--muted); font-size:.85rem; font-style:italic; }
|
|
||||||
.sb-note { color:var(--muted); font-size:.8rem; }
|
|
||||||
.sb-ranks { display:grid; grid-template-columns:repeat(auto-fill, minmax(220px, 1fr)); gap:1rem; }
|
|
||||||
.sb-rank { border:1px solid var(--line); border-radius:12px; padding:.6rem .8rem; background:var(--card); }
|
|
||||||
.sb-rank h4 { margin:0 0 .45rem; font-size:.95rem; }
|
|
||||||
.sb-timeline .area { fill:var(--accent); opacity:.18; }
|
|
||||||
.sb-timeline .line { fill:none; stroke:var(--accent); stroke-width:2.5; stroke-linejoin:round; }
|
|
||||||
.sb-timeline .dot { fill:transparent; }
|
|
||||||
.sb-timeline .dot:hover { fill:var(--accent); }
|
|
||||||
.sb-timeline .mark { stroke:var(--muted); stroke-dasharray:4 4; }
|
|
||||||
.sb-timeline .markdot { fill:var(--muted); }
|
|
||||||
.sb-changes { list-style:none; padding:0; margin:.6rem 0 0; font-size:.86rem; }
|
|
||||||
.sb-changes li { list-style:none; padding:.2rem 0; border-bottom:1px dashed var(--line); }
|
|
||||||
.sb-changes .when { display:inline-block; min-width:3.4rem; color:var(--muted); font-variant-numeric:tabular-nums; }
|
|
||||||
.sb-changes .game { color:var(--muted); font-size:.8rem; margin-left:.4rem; }
|
|
||||||
.sb-vod { font-size:.65rem; border:1px solid var(--line); border-radius:99px; padding:0 .35rem; color:var(--muted); }
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<div class="sb-views" role="tablist">
|
|
||||||
<a href="<%= link(cur, 'community') %>" class="<%= v === 'community' ? 'on' : '' %>">Community</a>
|
|
||||||
<a href="<%= link(cur, 'streams') %>" class="<%= v === 'streams' ? 'on' : '' %>">Streams</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="sb-nav">
|
|
||||||
<div class="sb-tabs">
|
|
||||||
<% for (const [p, label] of [['stream', 'Stream'], ['week', 'Week'], ['month', 'Month'], ['year', 'Year'], ['all', 'All time']]) { %>
|
|
||||||
<a href="<%= link(p === 'all' ? { p } : { p, ...(p === 'stream' ? {} : { d: r.from || undefined }) }) %>" class="<%= r.p === p ? 'on' : '' %>"><%= label %></a>
|
|
||||||
<% } %>
|
|
||||||
</div>
|
|
||||||
<div class="sb-step">
|
|
||||||
<% if (r.p !== 'all') { %>
|
|
||||||
<% if (r.prev) { %><a href="<%= link(r.prev) %>" title="<%= r.p === 'stream' ? 'Older stream' : 'Earlier' %>">‹</a><% } else { %><span class="off">‹</span><% } %>
|
|
||||||
<% } %>
|
|
||||||
<span><span class="sb-title"><%= r.label %></span><% if (r.sub) { %> <span class="sb-sub">· <%= r.sub %></span><% } %></span>
|
|
||||||
<% if (r.p !== 'all') { %>
|
|
||||||
<% if (r.next) { %><a href="<%= link(r.next) %>" title="<%= r.p === 'stream' ? 'Newer stream' : 'Later' %>">›</a><% } else { %><span class="off">›</span><% } %>
|
|
||||||
<% } %>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<%
|
|
||||||
// ---- number tiles. Public: a short, friendly set; admin: everything ----
|
|
||||||
const T_ = {}; // id -> [value, label, tooltip]
|
|
||||||
T_.messages = [num(T.messages), 'chat messages', since ? `Before ${since} from Twitch's daily analytics, after that counted by HeyStreamer` : ''];
|
|
||||||
T_.watch = [num(T.watchHours), 'hours watched', T.historyWatchHours ? `${num(T.historyWatchHours)} h from Twitch's daily analytics (before ${since}), the rest counted by HeyStreamer` : T.baselineHours ? `Includes ${num(T.baselineHours)} h counted by StreamElements before HeyStreamer counted itself` : ''];
|
|
||||||
if (r.p !== 'stream') T_.streams = [num(T.streams), T.streams === 1 ? 'stream' : 'streams', since ? `Before ${since} every day with a stream counts as one stream (Twitch's daily analytics)` : ''];
|
|
||||||
T_.streamed = r.p === 'stream' && s.streams[0] ? [hm(s.streams[0].minutes), s.streams[0].live ? 'live for' : 'streamed'] : [num(T.hoursStreamed), 'hours streamed'];
|
|
||||||
T_.emotes = [num(T.emotes), 'emotes used', since ? `Counted by HeyStreamer since ${since}` : ''];
|
|
||||||
if (TW && TW.clips) T_.clips = [num(TW.clips), 'clips created', `${num(TW.clipViews)} clip views (Twitch's daily analytics)`];
|
|
||||||
T_.redeems = [num(T.redeems), 'rewards redeemed', `${num(T.channelPoints)} channel points spent${since ? `; counted since ${since}` : ''}`];
|
|
||||||
if (admin) {
|
|
||||||
if (r.p === 'all' && C.followers != null) T_.followers = [num(C.followers), 'followers', 'Following the channel right now (from Twitch)'];
|
|
||||||
if (r.p === 'all' && C.subsNow != null) T_.subsNow = [num(C.subsNow), 'subscribers', 'Subscribed right now (from Twitch, without the streamer)'];
|
|
||||||
T_.chatters = [num(T.chatters), since ? `chatters since ${since}` : 'chatters', 'Different people who chatted. Twitch\'s export has no names, so this only counts from HeyStreamer\'s start'];
|
|
||||||
T_.viewers = [num(T.viewers), since ? `viewers since ${since}` : 'viewers', `Different people in the chatter list while live, lurkers included${T.viewersFromBaseline ? `. Includes ${num(T.viewersFromBaseline)} viewers known only from StreamElements' watch time (from before HeyStreamer counted), which is why All time is higher than the other tabs` : ''}`];
|
|
||||||
const pk = r.p === 'stream' ? s.streams[0] : C;
|
|
||||||
if (pk && pk.peak != null) T_.peak = [num(pk.peak), 'peak viewers', pk.avg != null ? `About ${num(pk.avg)} on average` : ''];
|
|
||||||
if (TW && TW.uniquePerDay != null) T_.unique = [num(TW.uniquePerDay), 'unique viewers / stream day', 'Twitch\'s count of different people who watched, averaged over the days you streamed'];
|
|
||||||
if (TW && (TW.newEngaged || TW.returningEngaged)) T_.engaged = [num(TW.newEngaged), 'new engaged viewers', `${num(TW.returningEngaged)} returning engaged viewer-days. Engaged = watched 5+ minutes and chatted or followed (Twitch)`];
|
|
||||||
if (TW && TW.revenue) T_.revenue = [`$${TW.revenue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`, 'revenue · admin only',
|
|
||||||
TW.revenueByType.map(([k, x]) => `${k} $${x.toFixed(2)}`).join(', ') + ' (Twitch export, before payout fees and taxes)'];
|
|
||||||
if (T.follows && !T_.followers) T_.follows = [num(T.follows), 'new followers'];
|
|
||||||
if (T.intros) T_.intros = [num(T.intros), 'first-time chatters'];
|
|
||||||
if (T.subs || T.giftSubs) T_.subs = [num(T.subs + T.giftSubs), 'subs', `${num(T.subs)} subs and resubs, ${num(T.giftSubs)} gifted`];
|
|
||||||
if (T.bits) T_.bits = [num(T.bits), 'bits', s.bitsSource === 'twitch' ? 'All time, from Twitch (top 100 cheerers)' : T.powerUps ? `${num(T.powerUps)} Power-ups included` : ''];
|
|
||||||
if (T.raids) T_.raids = [num(T.raids), T.raids === 1 ? 'raid' : 'raids', `${num(T.raidViewers)} viewers brought in`];
|
|
||||||
if (T.checkins) T_.checkins = [num(T.checkins), 'check-ins', 'First message of a stream'];
|
|
||||||
}
|
|
||||||
const order = admin
|
|
||||||
? ['followers', 'subsNow', 'messages', 'chatters', 'viewers', 'watch', 'streams', 'streamed', 'peak', 'unique', 'engaged', 'clips', 'revenue', 'follows', 'intros', 'emotes', 'subs', 'bits', 'redeems', 'raids', 'checkins']
|
|
||||||
: ['messages', 'watch', 'streams', 'streamed', 'emotes', 'clips', 'redeems'];
|
|
||||||
const tiles = order.filter(k => T_[k]).map(k => T_[k]);
|
|
||||||
%>
|
|
||||||
<% if (admin || v === 'streams') { %>
|
|
||||||
<div class="sb-tiles">
|
|
||||||
<% for (const [val, k, tip] of tiles) { %><div class="sb-tile"><div class="v"><%= val %></div><div class="k"><%= k %><%- info(tip) %></div></div><% } %>
|
|
||||||
</div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if (v === 'streams') { %>
|
|
||||||
<%# ===================== STREAMS ===================== %>
|
|
||||||
<% if (r.p === 'stream' && s.streams[0]) { const x = s.streams[0]; %>
|
|
||||||
<p class="sb-sub" style="margin-top:-.6rem;">
|
|
||||||
<%= day(x.started_at) %>, <%= time(x.started_at) %>–<%= x.ended_at ? time(x.ended_at) : 'now' %><%= x.games.length ? ` · ${x.games.join(', ')}` : '' %>
|
|
||||||
<% if (x.live) { %> · <strong>live now</strong><% } %>
|
|
||||||
<% if (x.source === 'vod') { %> · from the VOD (HeyStreamer was not counting)<% } %>
|
|
||||||
</p>
|
|
||||||
<%
|
|
||||||
// viewers every 5 minutes as an area line; title / category changes as dashed markers
|
|
||||||
const tl = s.timeline;
|
|
||||||
if (tl && (tl.samples.length || tl.changes.length)) {
|
|
||||||
const W = 900, H = 200, L = 34, B = 20, TOP = 10;
|
|
||||||
const t0 = Date.parse(tl.start), t1 = Math.max(Date.parse(tl.end), t0 + 60000);
|
|
||||||
const max = Math.max(1, ...tl.samples.map(p => p.viewers));
|
|
||||||
const top = (() => { const p = Math.pow(10, Math.floor(Math.log10(max))); return [1, 2, 2.5, 5, 10].map(m => m * p).find(x => x >= max); })();
|
|
||||||
const X = t => L + (W - L) * (Date.parse(t) - t0) / (t1 - t0), Y = n => TOP + (H - TOP - B) * (1 - n / top);
|
|
||||||
let svg = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Viewers during the stream">`;
|
|
||||||
for (const g of [0, top / 2, top]) svg += `<line class="grid" x1="${L}" x2="${W}" y1="${Y(g)}" y2="${Y(g)}"/><text class="ax" x="${L - 4}" y="${Y(g) + 3}" text-anchor="end">${g}</text>`;
|
|
||||||
for (let h = 0; h <= (t1 - t0) / 36e5; h++) { const tt = new Date(t0 + h * 36e5).toISOString(); svg += `<text class="ax" x="${X(tt)}" y="${H - 5}" text-anchor="middle">${time(tt)}</text>`; }
|
|
||||||
if (tl.samples.length) {
|
|
||||||
const pts = tl.samples.map(p => `${X(p.at).toFixed(1)},${Y(p.viewers).toFixed(1)}`);
|
|
||||||
svg += `<path class="area" d="M${X(tl.samples[0].at).toFixed(1)},${H - B} L${pts.join(' L')} L${X(tl.samples.at(-1).at).toFixed(1)},${H - B} Z"/>`;
|
|
||||||
svg += `<polyline class="line" points="${pts.join(' ')}"/>`;
|
|
||||||
for (const p of tl.samples) svg += `<circle class="dot hit" cx="${X(p.at).toFixed(1)}" cy="${Y(p.viewers).toFixed(1)}" r="6" data-tip="${time(p.at)} · ${p.viewers} viewers"/>`;
|
|
||||||
}
|
|
||||||
for (const c of tl.changes) {
|
|
||||||
if (c.start) continue;
|
|
||||||
const x = X(c.at).toFixed(1);
|
|
||||||
svg += `<line class="mark" x1="${x}" x2="${x}" y1="${TOP}" y2="${H - B}"/><circle class="markdot hit" cx="${x}" cy="${TOP + 4}" r="5" data-tip="${time(c.at)} · ${esc(c.title || '')}${c.game ? ' · ' + esc(c.game) : ''}"/>`;
|
|
||||||
}
|
|
||||||
%>
|
|
||||||
<h3 class="sb-h">Viewers</h3>
|
|
||||||
<div class="sb-chart sb-timeline"><%- svg %></svg><div class="sb-tip"></div></div>
|
|
||||||
<% if (!tl.samples.length) { %><p class="sb-note">No viewer counts were recorded for this stream.</p><% } %>
|
|
||||||
<% if (tl.changes.length) { %>
|
|
||||||
<ol class="sb-changes">
|
|
||||||
<% for (const c of tl.changes) { %><li><span class="when"><%= c.start ? 'start' : time(c.at) %></span> <span><%= c.title || '—' %></span><% if (c.game) { %> <span class="game"><%= c.game %></span><% } %></li><% } %>
|
|
||||||
</ol>
|
|
||||||
<% } %>
|
|
||||||
<% } %>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<%
|
|
||||||
// one activity chart, like Twitch's: pick what it shows
|
|
||||||
const METRICS = [['messages', 'Chat messages', ''], ['watchHours', 'Hours watched', 'h'], ['streamHours', 'Hours streamed', 'h'],
|
|
||||||
['avgViewers', 'Average viewers', ''], ['follows', 'New followers', '']];
|
|
||||||
const rows = s.series ? s.series.rows : [];
|
|
||||||
const shown = METRICS.filter(([k]) => rows.some(x => x[k]));
|
|
||||||
%>
|
|
||||||
<% if (rows.length && shown.length) { %>
|
|
||||||
<h3 class="sb-h">Activity <span class="sb-sub">per <%= s.series.unit %></span></h3>
|
|
||||||
<div class="sb-chart" id="sb-activity">
|
|
||||||
<div class="sb-metrics"><% shown.forEach(([k, label], i) => { %><button type="button" data-k="<%= k %>" class="<%= i ? '' : 'on' %>"><%= label %></button><% }) %></div>
|
|
||||||
<div class="plot"></div><div class="sb-tip"></div>
|
|
||||||
</div>
|
|
||||||
<script>
|
|
||||||
(function () {
|
|
||||||
const rows = <%- JSON.stringify(rows.map(x => ({ label: x.label, messages: x.messages, watchHours: x.watchHours, streamHours: x.streamHours, avgViewers: x.avgViewers, follows: x.follows }))).replace(/</g, '\\u003c') %>;
|
|
||||||
const units = <%- JSON.stringify(Object.fromEntries(METRICS.map(([k, l, u]) => [k, { label: l, unit: u }]))) %>;
|
|
||||||
const box = document.getElementById('sb-activity'), plot = box.querySelector('.plot');
|
|
||||||
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
||||||
function draw(key) {
|
|
||||||
const W = 900, H = 200, L = 38, B = 20, TOP = 8, n = rows.length, max = Math.max(1, ...rows.map(d => d[key] || 0));
|
|
||||||
const p = Math.pow(10, Math.floor(Math.log10(max))), top = [1, 2, 2.5, 5, 10].map(m => m * p).find(x => x >= max);
|
|
||||||
const slot = (W - L) / n, bw = Math.max(2, Math.min(slot - 2, 44)), pad = (slot - bw) / 2, y = x => TOP + (H - TOP - B) * (1 - x / top);
|
|
||||||
const every = Math.ceil(n / 12);
|
|
||||||
let out = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(units[key].label)}">`;
|
|
||||||
for (const g of [0, top / 2, top]) out += `<line class="grid" x1="${L}" x2="${W}" y1="${y(g)}" y2="${y(g)}"/><text class="ax" x="${L - 4}" y="${y(g) + 3}" text-anchor="end">${+g.toFixed(1)}</text>`;
|
|
||||||
rows.forEach((d, i) => {
|
|
||||||
const x = L + i * slot + pad, val = d[key] || 0, tp = y(val), h = (H - B) - tp, rr = Math.min(4, bw / 2, h);
|
|
||||||
out += `<rect class="hit" x="${L + i * slot}" y="${TOP}" width="${slot}" height="${H - TOP - B}" fill="transparent" data-tip="${esc(d.label)} · ${val}${units[key].unit ? ' ' + units[key].unit : ''}"/>`;
|
|
||||||
if (val > 0) out += `<path class="bar" d="M${x},${H - B} V${tp + rr} Q${x},${tp} ${x + rr},${tp} H${x + bw - rr} Q${x + bw},${tp} ${x + bw},${tp + rr} V${H - B} Z"/>`;
|
|
||||||
if (i % every === 0) out += `<text class="ax" x="${x + bw / 2}" y="${H - 4}" text-anchor="middle">${esc(d.label)}</text>`;
|
|
||||||
});
|
|
||||||
plot.innerHTML = out + '</svg>';
|
|
||||||
window.sbHoverTips && window.sbHoverTips(box);
|
|
||||||
}
|
|
||||||
box.querySelectorAll('.sb-metrics button').forEach(b => b.addEventListener('click', () => {
|
|
||||||
box.querySelectorAll('.sb-metrics button').forEach(x => x.classList.toggle('on', x === b));
|
|
||||||
draw(b.dataset.k);
|
|
||||||
}));
|
|
||||||
draw(box.querySelector('.sb-metrics button.on').dataset.k);
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<%
|
|
||||||
// games played: donut of streamed time per category (from HeyStreamer's title / category history)
|
|
||||||
const PAL = ['#b74347', '#5b8fc7', '#d39b3a', '#4f9a68', '#8c6bb1', '#c76f9a', '#3fa3a1', '#9a8a5a'];
|
|
||||||
const games = s.games || [];
|
|
||||||
const totalMin = games.reduce((a, g) => a + g.minutes, 0);
|
|
||||||
const slices = games.length > 8 ? [...games.slice(0, 7), { game: `${games.length - 7} more`, minutes: games.slice(7).reduce((a, g) => a + g.minutes, 0), other: true }] : games;
|
|
||||||
%>
|
|
||||||
<% if (r.p !== 'stream' || slices.length > 1) { %>
|
|
||||||
<h3 class="sb-h">Games<%- info('Time per category, from every title / category change HeyStreamer saw. Twitch keeps no history of categories, so streams from before HeyStreamer recorded them have no game.') %></h3>
|
|
||||||
<% if (!totalMin) { %><p class="sb-empty">no categories recorded in this period yet</p><% } else { %>
|
|
||||||
<div class="sb-chart sb-games">
|
|
||||||
<svg viewBox="-1 -1 2 2" role="img" aria-label="Time per game">
|
|
||||||
<% let acc = 0; slices.forEach((g, i) => {
|
|
||||||
const a0 = acc / totalMin * 2 * Math.PI, a1 = (acc + g.minutes) / totalMin * 2 * Math.PI; acc += g.minutes;
|
|
||||||
const big = a1 - a0 > Math.PI ? 1 : 0, P = a => `${(Math.sin(a) * .95).toFixed(4)} ${(-Math.cos(a) * .95).toFixed(4)}`, Q = a => `${(Math.sin(a) * .55).toFixed(4)} ${(-Math.cos(a) * .55).toFixed(4)}`;
|
|
||||||
const d = slices.length === 1 ? 'M0 -.95 A.95 .95 0 1 1 0 .95 A.95 .95 0 1 1 0 -.95 Z M0 -.55 A.55 .55 0 1 0 0 .55 A.55 .55 0 1 0 0 -.55 Z'
|
|
||||||
: `M${P(a0)} A.95 .95 0 ${big} 1 ${P(a1)} L${Q(a1)} A.55 .55 0 ${big} 0 ${Q(a0)} Z`; %>
|
|
||||||
<path d="<%= d %>" fill="<%= g.other ? '#8a8a8a' : PAL[i % PAL.length] %>" fill-rule="evenodd" stroke="var(--card-solid, #fff)" stroke-width=".02"><title><%= g.game %> · <%= hm(g.minutes) %></title></path>
|
|
||||||
<% }) %>
|
|
||||||
</svg>
|
|
||||||
<ul>
|
|
||||||
<% slices.forEach((g, i) => { %>
|
|
||||||
<li><span class="sw" style="background:<%= g.other ? '#8a8a8a' : PAL[i % PAL.length] %>"></span><span class="nm" title="<%= g.game %>"><%= g.game %></span>
|
|
||||||
<span class="hv"><%= hm(g.minutes) %> · <%= Math.round(g.minutes / totalMin * 100) %>%</span></li>
|
|
||||||
<% }) %>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
<% } %>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if (r.p !== 'stream' && s.streams.length) { %>
|
|
||||||
<h3 class="sb-h"><%= r.p === 'all' ? 'Recent streams' : 'Streams' %></h3>
|
|
||||||
<div class="sb-scroll"><table class="sb-streams">
|
|
||||||
<thead><tr><th>Date</th><th>Title · games</th><th style="text-align:right">Length</th><th style="text-align:right">Peak</th><th style="text-align:right">Viewers</th><th style="text-align:right">Chatters</th><th style="text-align:right">Messages</th></tr></thead>
|
|
||||||
<tbody>
|
|
||||||
<% for (const x of s.streams.slice(0, r.p === 'all' ? 15 : 100)) { %>
|
|
||||||
<tr>
|
|
||||||
<td style="white-space:nowrap"><a href="<%= link({ p: 'stream', s: x.id }) %>"><%= day(x.started_at) %></a><%= x.live ? ' · live' : '' %><% if (x.source === 'vod') { %> <span class="sb-vod" title="Known from the Twitch VOD only: HeyStreamer was not counting during this stream">VOD</span><% } %></td>
|
|
||||||
<td><span class="t" title="<%= x.title %>"><%= x.title || '—' %></span><% if (x.games.length) { %><span class="g"><%= x.games.join(' · ') %></span><% } %></td>
|
|
||||||
<td class="n"><%= hm(x.minutes) %></td><td class="n"><%= x.peak != null ? num(x.peak) : '—' %></td>
|
|
||||||
<td class="n"><%= num(x.viewers) %></td><td class="n"><%= num(x.chatters) %></td><td class="n"><%= num(x.messages) %></td>
|
|
||||||
</tr>
|
|
||||||
<% } %>
|
|
||||||
</tbody>
|
|
||||||
</table></div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% } else { %>
|
|
||||||
<%# ===================== COMMUNITY ===================== %>
|
|
||||||
<% const cm = s.community || {}; %>
|
|
||||||
<% if ((cm.supporters || []).length) { %>
|
|
||||||
<h3 class="sb-h">Thank you for the support</h3>
|
|
||||||
<div class="sb-pills">
|
|
||||||
<% for (const x of cm.supporters.slice(0, 40)) {
|
|
||||||
const what = [x.bits ? `${num(x.bits)} bits` : '', x.subs ? (x.subs === 1 ? 'sub' : `${x.subs} subs`) : '', x.gifts ? `${num(x.gifts)} gifted` : '', admin && x.tips ? 'tip' : ''].filter(Boolean).join(' · '); %>
|
|
||||||
<span class="sb-pill txt"><%- person(x) %> <span class="what"><%= what %></span></span>
|
|
||||||
<% } %>
|
|
||||||
</div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if ((cm.raiders || []).length) { %>
|
|
||||||
<h3 class="sb-h">Raids</h3>
|
|
||||||
<div class="sb-pills"><% for (const x of cm.raiders) { %><span class="sb-pill txt"><%- person(x) %> <span class="what"><%= x.raids > 1 ? `${x.raids} raids · ` : '' %><%= num(x.viewers) %> viewers</span></span><% } %></div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<%
|
|
||||||
const board = b => {
|
|
||||||
const nw = b.nw ? ` style="--nw:${b.nw}"` : '';
|
|
||||||
let out = `<div class="sb-board${b.wide ? ' wide' : ''}"${nw}><h4>${esc(b.title)}</h4>`;
|
|
||||||
if (!b.rows.length) return out + '<p class="sb-empty">nothing yet</p></div>';
|
|
||||||
out += '<ol>';
|
|
||||||
b.rows.forEach((x, i) => {
|
|
||||||
out += `<li><span class="r">${i + 1}</span><span class="who" title="${esc(x.name || x.login)}">${person(x)}</span>${b.level ? `<span class="lvl">${esc(b.level(x))}</span>` : ''}<span class="n">${(b.fmt || num)(x.n)}</span></li>`;
|
|
||||||
});
|
|
||||||
return out + '</ol></div>';
|
|
||||||
};
|
|
||||||
const boards = [
|
|
||||||
...(locals.extraBoards || []),
|
|
||||||
{ title: 'Most active in chat', rows: s.boards.chat },
|
|
||||||
{ title: 'Watch time', rows: s.boards.watch, fmt: hm, nw: '6.4rem' },
|
|
||||||
{ title: 'Channel points spent', rows: s.boards.channelPoints, optional: true },
|
|
||||||
...(admin ? [{ title: 'Bits', rows: s.boards.bits, optional: true }, { title: 'Subs and gifts', rows: s.boards.subs, optional: true }] : []),
|
|
||||||
].filter(b => !(b.optional && !b.rows.length));
|
|
||||||
%>
|
|
||||||
<h3 class="sb-h">Leaderboards</h3>
|
|
||||||
<div class="sb-boards"><% for (const b of boards) { %><%- board(b) %><% } %></div>
|
|
||||||
|
|
||||||
<% if ((locals.ranks || []).length) {
|
|
||||||
const LV = ['Veteran', 'Loyal', 'Regular']; %>
|
|
||||||
<h3 class="sb-h">Community ranks<%- info('Levels by total watch time: Regular from 50 h, Loyal from 200 h, Veteran from 1000 h. All time.') %></h3>
|
|
||||||
<div class="sb-ranks">
|
|
||||||
<% for (const lv of LV) { const list = ranks.filter(x => x.level === lv); if (!list.length) continue; %>
|
|
||||||
<div class="sb-rank"><h4><%= lv %> <span class="sb-sub"><%= list.length %></span></h4>
|
|
||||||
<div class="sb-pills"><% for (const x of list) { %><span class="sb-pill txt"><%- person(x) %></span><% } %></div></div>
|
|
||||||
<% } %>
|
|
||||||
</div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if (s.channelEmotes && s.channelEmotes.length) { %>
|
|
||||||
<h3 class="sb-h">Channel emotes<%- info('The channel\'s own emotes and how often they were used in this chat in this period. Twitch does not tell how often they are used in other channels.') %></h3>
|
|
||||||
<div class="sb-pills">
|
|
||||||
<% for (const e of s.channelEmotes) { %>
|
|
||||||
<span class="sb-pill<%= e.uses ? '' : ' zero' %>" title="<%= e.name %><%= e.tier ? ` · Tier ${String(e.tier).slice(0, 1)}` : '' %><%= e.type === 'follower' ? ' · follower emote' : e.type === 'bitstier' ? ' · bits emote' : '' %><%= e.gone ? ' · removed from the channel' : '' %>"><% if (e.image) { %><img src="<%= e.image %>" alt="" loading="lazy"><% } %><%= e.name %> <strong><%= num(e.uses) %></strong></span>
|
|
||||||
<% } %>
|
|
||||||
</div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<h3 class="sb-h">Top emotes</h3>
|
|
||||||
<% if (!s.emotes.length) { %><p class="sb-empty">nothing yet</p><% } else { %>
|
|
||||||
<div class="sb-pills">
|
|
||||||
<% for (const e of s.emotes) { const src = emoteSrc(e); %>
|
|
||||||
<span class="sb-pill" title="<%= e.emote %><%= e.source ? ` · ${e.source === '7tv' ? '7TV' : 'Twitch'}` : '' %>"><% if (src) { %><img src="<%= src %>" alt="" loading="lazy"><% } %><%= e.emote %> <strong><%= num(e.uses) %></strong></span>
|
|
||||||
<% } %>
|
|
||||||
</div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if (s.commands.length) { %>
|
|
||||||
<h3 class="sb-h">Top commands</h3>
|
|
||||||
<div class="sb-pills"><% for (const c of s.commands) { %><span class="sb-pill txt"><code><%= c.command %></code> <strong><%= num(c.uses) %></strong></span><% } %></div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if (s.rewards.length) { %>
|
|
||||||
<h3 class="sb-h">Rewards and Power-ups</h3>
|
|
||||||
<div class="sb-pills"><% for (const x of s.rewards) { %><span class="sb-pill txt"><%= x.item %> <strong><%= num(x.uses) %></strong></span><% } %></div>
|
|
||||||
<% } %>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
// chart hover tooltips (bars, viewer dots, title-change markers)
|
|
||||||
window.sbHoverTips = function (scope) {
|
|
||||||
(scope ? [scope] : document.querySelectorAll('.sb-chart')).forEach(ch => {
|
|
||||||
const tip = ch.querySelector('.sb-tip');
|
|
||||||
if (!tip) return;
|
|
||||||
ch.querySelectorAll('.hit').forEach(h => {
|
|
||||||
h.addEventListener('mouseenter', () => { tip.textContent = h.dataset.tip; tip.style.display = 'block'; });
|
|
||||||
h.addEventListener('mousemove', e => { const r = ch.getBoundingClientRect(); tip.style.left = (e.clientX - r.left + 12) + 'px'; tip.style.top = (e.clientY - r.top - 28) + 'px'; });
|
|
||||||
h.addEventListener('mouseleave', () => { tip.style.display = 'none'; });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
|
||||||
window.sbHoverTips();
|
|
||||||
</script>
|
|
||||||
88
views/actions.ejs
Normal file
88
views/actions.ejs
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
<h2>Actions</h2>
|
||||||
|
<p><small>Map Twitch events to sounds, videos, or on-screen alerts.</small></p>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Add new action</summary>
|
||||||
|
<form method="POST" action="/actions" style="margin-top:1rem;">
|
||||||
|
<div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
|
||||||
|
<label>Name <input type="text" name="name" required placeholder="e.g. Sub sound"></label>
|
||||||
|
<label>
|
||||||
|
Event type
|
||||||
|
<select name="event_type" required>
|
||||||
|
<option value="sub">Sub</option>
|
||||||
|
<option value="gift_sub">Gift sub</option>
|
||||||
|
<option value="bits">Bits</option>
|
||||||
|
<option value="channel_points">Channel points</option>
|
||||||
|
<option value="command">Chat command</option>
|
||||||
|
<option value="follow">Follow</option>
|
||||||
|
<option value="raid">Raid</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Event detail <small>(tier / min bits / command name / reward ID)</small>
|
||||||
|
<input type="text" name="event_detail" placeholder="Optional">
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Action type
|
||||||
|
<select name="action_type" required>
|
||||||
|
<option value="sound">Sound</option>
|
||||||
|
<option value="video">Video</option>
|
||||||
|
<option value="alert">Alert text</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Media file
|
||||||
|
<select name="media_file_id">
|
||||||
|
<option value="">— none —</option>
|
||||||
|
<% for (const f of media) { %>
|
||||||
|
<option value="<%= f.id %>"><%= f.original_name %> (<%= f.media_type %>)</option>
|
||||||
|
<% } %>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>Alert text <input type="text" name="alert_text" placeholder="{username} just subbed!"></label>
|
||||||
|
<label>Cooldown (seconds) <input type="number" name="cooldown_seconds" value="0" min="0"></label>
|
||||||
|
</div>
|
||||||
|
<button type="submit">Add action</button>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<% if (actions.length === 0) { %>
|
||||||
|
<p><em>No actions yet.</em></p>
|
||||||
|
<% } else { %>
|
||||||
|
<figure>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Event</th>
|
||||||
|
<th>Detail</th>
|
||||||
|
<th>Action</th>
|
||||||
|
<th>Cooldown</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% for (const a of actions) { %>
|
||||||
|
<tr>
|
||||||
|
<td><%= a.name %></td>
|
||||||
|
<td><code><%= a.event_type %></code></td>
|
||||||
|
<td><%= a.event_detail || '—' %></td>
|
||||||
|
<td><code><%= a.action_type %></code></td>
|
||||||
|
<td><%= a.cooldown_seconds %>s</td>
|
||||||
|
<td>
|
||||||
|
<span class="badge <%= a.enabled ? 'badge-green' : 'badge-grey' %>">
|
||||||
|
<%= a.enabled ? 'on' : 'off' %>
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td style="display:flex; gap:0.5rem;">
|
||||||
|
<form method="POST" action="/actions/<%= a.id %>/test"><button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem;">Test</button></form>
|
||||||
|
<form method="POST" action="/actions/<%= a.id %>/toggle"><button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem;"><%= a.enabled ? 'Disable' : 'Enable' %></button></form>
|
||||||
|
<form method="POST" action="/actions/<%= a.id %>/delete" onsubmit="return confirm('Delete this action?')"><button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem; color:#f88;">Delete</button></form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</figure>
|
||||||
|
<% } %>
|
||||||
|
|
@ -1,133 +0,0 @@
|
||||||
<!doctype html>
|
|
||||||
<%#
|
|
||||||
Alert preview: the real overlay code on a 1920x1080 stage, with a button for every alert. Served at
|
|
||||||
/actions/alerts/preview (logged in) and exported as a static page by tools/export-preview.js.
|
|
||||||
Locals: base ('/alerts/' or 'alerts/'), themes { key: { label, theme } }, start (theme key), samples (src/alerts.js SAMPLES).
|
|
||||||
%>
|
|
||||||
<html lang="en"><head><meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<title>Alert preview</title>
|
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Caveat:wght@700&family=Nunito:wght@700;800;900&display=block">
|
|
||||||
<% for (const f of ['card', 'polaroid', 'cassette', 'fx']) { %><link rel="stylesheet" href="<%= base %><%= f %>.css"><% } %>
|
|
||||||
<style>
|
|
||||||
* { box-sizing:border-box; }
|
|
||||||
html, body { margin:0; height:100%; background:#101014; color:#f1edf7; font-family:'Nunito', system-ui, sans-serif; }
|
|
||||||
.wrap { display:grid; grid-template-columns:minmax(0, 1fr) 380px; height:100vh; }
|
|
||||||
@media (max-width: 1000px) { .wrap { grid-template-columns:1fr; height:auto; } }
|
|
||||||
.viewport { position:relative; overflow:hidden; display:grid; place-items:center; padding:16px; }
|
|
||||||
.stage-box { position:relative; width:100%; aspect-ratio:16 / 9; max-height:calc(100vh - 32px); }
|
|
||||||
#stage { position:absolute; left:0; top:0; width:1920px; height:1080px; transform-origin:0 0; overflow:hidden; border-radius:10px;
|
|
||||||
background:var(--bg); box-shadow:0 10px 40px rgba(0,0,0,.5); }
|
|
||||||
/* the alert elements are position:fixed in the overlay; inside the scaled stage they must follow the stage */
|
|
||||||
#stage { contain:layout paint; transform-style:flat; }
|
|
||||||
.bg-game { --bg:radial-gradient(1200px 700px at 30% 40%, #3a5f4f, #16261f 70%), #16261f; }
|
|
||||||
.bg-dark { --bg:#1b1b22; }
|
|
||||||
.bg-light { --bg:#e9e6ef; }
|
|
||||||
.bg-check { --bg:repeating-conic-gradient(#2a2a33 0 25%, #22222a 0 50%) 0 0 / 40px 40px; }
|
|
||||||
.scene { position:absolute; inset:0; pointer-events:none; }
|
|
||||||
.scene .cam { position:absolute; right:60px; bottom:60px; width:480px; height:270px; border-radius:18px; background:rgba(255,255,255,.08);
|
|
||||||
border:2px dashed rgba(255,255,255,.18); display:grid; place-items:center; color:rgba(255,255,255,.35); font:800 26px Nunito; }
|
|
||||||
.panel { overflow:auto; background:#191720; border-left:1px solid #2b2836; padding:16px 18px 30px; }
|
|
||||||
.panel h1 { font-size:20px; margin:0 0 4px; }
|
|
||||||
.note { font-size:13px; color:#b9b0cc; margin:0 0 10px; line-height:1.4; }
|
|
||||||
h3 { font-size:12px; letter-spacing:.12em; color:#b9a3ec; margin:16px 0 7px; text-transform:uppercase; }
|
|
||||||
.row { display:flex; flex-wrap:wrap; gap:6px; }
|
|
||||||
button { font:800 13px 'Nunito'; border:0; border-radius:14px; padding:6px 12px; cursor:pointer; background:#2c2838; color:#f1edf7; }
|
|
||||||
button:hover { background:#3b3550; }
|
|
||||||
button.on { background:#9146ff; color:#fff; }
|
|
||||||
button.alt { background:#efe6ff; color:#2a1d40; }
|
|
||||||
.colors { display:flex; gap:12px; flex-wrap:wrap; font-size:13px; align-items:center; }
|
|
||||||
.colors label { display:flex; gap:6px; align-items:center; }
|
|
||||||
.colors input { width:34px; height:26px; border:0; padding:0; background:none; }
|
|
||||||
#log { font:700 12px monospace; color:#c9ffd8; margin-top:14px; min-height:1.2em; }
|
|
||||||
</style></head><body>
|
|
||||||
<div class="wrap">
|
|
||||||
<div class="viewport"><div class="stage-box" id="box"><div id="stage" class="bg-game"><div class="scene"><div class="cam">camera</div></div></div></div></div>
|
|
||||||
<div class="panel">
|
|
||||||
<h1>Alert preview</h1>
|
|
||||||
<p class="note">The real overlay code. Click a button to play an alert; a click replaces the one showing. Click anywhere once first so the browser allows sound.</p>
|
|
||||||
|
|
||||||
<h3>Look</h3>
|
|
||||||
<div class="row" id="themes"><% for (const [k, t] of Object.entries(themes)) { %><button data-theme="<%= k %>"><%= t.label %></button><% } %></div>
|
|
||||||
<div class="row" style="margin-top:6px;" id="styles">
|
|
||||||
<button data-style="card">Alerts: Card</button><button data-style="polaroid">Alerts: Polaroid</button>
|
|
||||||
</div>
|
|
||||||
<div class="colors" style="margin-top:8px;">
|
|
||||||
<label><input type="color" data-c="accent"> accent</label><label><input type="color" data-c="bg"> card</label><label><input type="color" data-c="text"> text</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h3>Background</h3>
|
|
||||||
<div class="row" id="bgs"><button data-bg="bg-game" class="on">Game</button><button data-bg="bg-dark">Dark</button><button data-bg="bg-light">Light</button><button data-bg="bg-check">Transparent</button></div>
|
|
||||||
|
|
||||||
<h3>Follows and subs</h3>
|
|
||||||
<div class="row"><% for (const [k, l] of [['follow', 'Follow'], ['sub-new', 'New sub'], ['sub-prime', 'Prime'], ['sub-resub', 'Resub 14 months'], ['sub-6', '6 months at once'], ['gift-1', 'Gift 1'], ['gift-10', 'Gift 10'], ['gift-anon', 'Anonymous gift']]) { %><button data-k="<%= k %>"><%= l %></button><% } %></div>
|
|
||||||
<h3>Bits, tips, raids</h3>
|
|
||||||
<div class="row"><% for (const [k, l] of [['bits-20', '20 bits'], ['bits-120', '120 bits'], ['bits-500', '500 bits'], ['tip-5', 'Tip 5'], ['tip-100', 'Tip 100'], ['raid', 'Raid'], ['streak', 'Watch streak']]) { %><button data-k="<%= k %>"><%= l %></button><% } %></div>
|
|
||||||
<h3>Hype Train</h3>
|
|
||||||
<div class="row"><% for (const [k, l] of [['hype-begin', 'Start'], ['hype-level', 'Level up'], ['hype-end', 'End'], ['hype-golden', 'Golden Kappa']]) { %><button data-k="<%= k %>"><%= l %></button><% } %></div>
|
|
||||||
<h3>Redeems</h3>
|
|
||||||
<div class="row">
|
|
||||||
<button data-r="card">Card</button><button data-r="cassette">Cassette</button><button data-r="cassette-rare">Cassette rare</button><button data-r="cassette-ultra">Cassette ultra rare</button>
|
|
||||||
<button data-r="tts">Read aloud</button><button data-r="message">Highlight message</button><button data-r="emote">Gigantify emote</button><button data-r="rain">Celebration</button>
|
|
||||||
</div>
|
|
||||||
<h3>Queue</h3>
|
|
||||||
<div class="row"><button data-queue class="alt">4 alerts at once</button><button data-reset>Stop</button></div>
|
|
||||||
<div id="log">ready</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
window.ALERTS_BASE = <%- JSON.stringify(base) %>;
|
|
||||||
const THEMES = <%- JSON.stringify(Object.fromEntries(Object.entries(themes).map(([k, t]) => [k, t.theme]))).replace(/</g, '\\u003c') %>;
|
|
||||||
window.S = { alert_theme: JSON.parse(JSON.stringify(THEMES[<%- JSON.stringify(start) %>])) };
|
|
||||||
</script>
|
|
||||||
<% for (const f of ['card', 'cassette', 'fx', 'polaroid']) { %><script src="<%= base %><%= f %>.js"></script><% } %>
|
|
||||||
<script>
|
|
||||||
const SAMPLES = <%- JSON.stringify(samples).replace(/</g, '\\u003c') %>;
|
|
||||||
const REDEEMS = {
|
|
||||||
card: { style: 'card', user: 'LurkingLynx', reward: 'Hydrate!', variation: 'Water break', rarity: 'common', caption: 'redeemed it! ♡' },
|
|
||||||
cassette: { style: 'cassette', user: 'PixelPotato', reward: 'Posture check', variation: 'Sit up straight', rarity: 'common', caption: 'redeemed it! ♡' },
|
|
||||||
'cassette-rare': { style: 'cassette', user: 'ChickenWhisperer', reward: 'Random sound', variation: 'Chicken dance', rarity: 'rare', caption: 'redeemed it! ♡' },
|
|
||||||
'cassette-ultra': { style: 'cassette', user: 'BobTheBuilder99', reward: 'Random sound', variation: 'The legendary one', rarity: 'ultra_rare', caption: 'redeemed it! ♡' },
|
|
||||||
tts: { style: 'tts', user: 'Chatty', reward: 'Read my message', variation: 'Robot voice', caption: 'says:', input: 'hello there streamer, that was a very nice shot and I was totally not camping that corner' },
|
|
||||||
message: { style: 'message', user: 'PixelPotato', reward: 'Highlight my message', caption: 'highlighted:', input: 'this stream is the coziest place on the internet' },
|
|
||||||
emote: { style: 'emote', user: 'LurkingLynx', reward: 'Gigantify an Emote', caption: 'gigantified an emote!', emote: 'https://static-cdn.jtvnw.net/emoticons/v2/25/default/dark/3.0' },
|
|
||||||
rain: { style: 'emote_rain', user: 'BobTheBuilder99', reward: 'On-Screen Celebration', caption: 'is celebrating!', emote: 'https://static-cdn.jtvnw.net/emoticons/v2/25/default/dark/3.0' },
|
|
||||||
};
|
|
||||||
const log = t => { document.getElementById('log').textContent = t; };
|
|
||||||
|
|
||||||
// scale the 1920x1080 stage to its box; fixed-position alerts are kept inside it by moving them into the stage
|
|
||||||
const stage = document.getElementById('stage'), box = document.getElementById('box');
|
|
||||||
const fit = () => { stage.style.transform = `scale(${box.clientWidth / 1920})`; };
|
|
||||||
new ResizeObserver(fit).observe(box); fit();
|
|
||||||
new MutationObserver(() => {
|
|
||||||
for (const id of ['card-alert', 'polaroid-alert', 'cassette-alert', 'fx-alert']) {
|
|
||||||
const el = document.getElementById(id);
|
|
||||||
if (el && el.parentElement !== stage) stage.appendChild(el);
|
|
||||||
}
|
|
||||||
}).observe(document.body, { childList: true });
|
|
||||||
|
|
||||||
const mark = (sel, attr, v) => document.querySelectorAll(sel).forEach(b => b.classList.toggle('on', b.dataset[attr] === v));
|
|
||||||
function useTheme(k) {
|
|
||||||
window.S.alert_theme = JSON.parse(JSON.stringify(THEMES[k]));
|
|
||||||
mark('#themes button', 'theme', k); mark('#styles button', 'style', window.S.alert_theme.style);
|
|
||||||
document.querySelectorAll('[data-c]').forEach(i => { i.value = window.S.alert_theme.card[i.dataset.c]; });
|
|
||||||
PolaroidAlerts.reset(); log('look: ' + document.querySelector(`[data-theme="${k}"]`).textContent);
|
|
||||||
}
|
|
||||||
document.querySelectorAll('[data-theme]').forEach(b => b.addEventListener('click', () => useTheme(b.dataset.theme)));
|
|
||||||
document.querySelectorAll('[data-style]').forEach(b => b.addEventListener('click', () => { window.S.alert_theme.style = b.dataset.style; mark('#styles button', 'style', b.dataset.style); }));
|
|
||||||
document.querySelectorAll('[data-c]').forEach(i => i.addEventListener('input', () => { window.S.alert_theme.card[i.dataset.c] = i.value; }));
|
|
||||||
document.querySelectorAll('[data-bg]').forEach(b => b.addEventListener('click', () => { stage.className = b.dataset.bg; mark('#bgs button', 'bg', b.dataset.bg); }));
|
|
||||||
document.querySelectorAll('[data-k]').forEach(b => b.addEventListener('click', () => { PolaroidAlerts.playTest({ ...SAMPLES[b.dataset.k], test: true }); log(b.textContent); }));
|
|
||||||
document.querySelectorAll('[data-r]').forEach(b => b.addEventListener('click', () => {
|
|
||||||
const r = REDEEMS[b.dataset.r];
|
|
||||||
PolaroidAlerts.playTest({ type: 'redeem', kind: 'reward', key: 'preview', volume: .8, polaroid: true, test: true, ...r }); log('redeem: ' + b.textContent);
|
|
||||||
}));
|
|
||||||
document.querySelector('[data-queue]').addEventListener('click', () => {
|
|
||||||
PolaroidAlerts.reset(); ['follow', 'bits-120', 'gift-10', 'hype-level'].forEach(k => PolaroidAlerts.play(SAMPLES[k]));
|
|
||||||
log('queued: follow, 120 bits, gift 10, hype level');
|
|
||||||
});
|
|
||||||
document.querySelector('[data-reset]').addEventListener('click', () => { PolaroidAlerts.reset(); log('stopped'); });
|
|
||||||
useTheme(<%- JSON.stringify(start) %>);
|
|
||||||
</script>
|
|
||||||
</body></html>
|
|
||||||
|
|
@ -1,233 +0,0 @@
|
||||||
<% const J = x => JSON.stringify(x).replace(/</g, '\\u003c'); %>
|
|
||||||
<style>
|
|
||||||
.al-grid { display:grid; grid-template-columns:minmax(150px, 200px) minmax(0, 1fr) minmax(0, 1fr) auto; gap:.5rem 1rem; align-items:center; }
|
|
||||||
.al-grid .hd { font-size:.75rem; color:var(--pico-muted-color); text-transform:uppercase; letter-spacing:.06em; }
|
|
||||||
.al-grid select { margin:0; font-size:.88rem; padding:.3rem .5rem; height:auto; }
|
|
||||||
.al-name { font-weight:600; font-size:.92rem; }
|
|
||||||
.al-name small { display:block; font-weight:400; color:var(--pico-muted-color); font-size:.78rem; }
|
|
||||||
.pk { display:flex; align-items:center; gap:.4rem; }
|
|
||||||
.pk img { width:34px; height:34px; object-fit:contain; border-radius:6px; background:rgba(255,255,255,.06); flex:none; }
|
|
||||||
.pk img[src=""] { visibility:hidden; }
|
|
||||||
.pk button, .btn-xs { width:auto; margin:0; padding:.2rem .55rem; font-size:.78rem; }
|
|
||||||
@media (max-width: 900px) { .al-grid { grid-template-columns:1fr 1fr; } .al-grid .hd { display:none; } }
|
|
||||||
.set-row > .seg { justify-self:start; }
|
|
||||||
.set-row.stack { grid-template-columns:1fr; }
|
|
||||||
.tiers .pk select { min-width:200px; }
|
|
||||||
.seg { display:inline-flex; border:1px solid var(--pico-muted-border-color); border-radius:8px; overflow:hidden; }
|
|
||||||
.seg label { margin:0; padding:.35rem .9rem; cursor:pointer; font-size:.88rem; border-left:1px solid var(--pico-muted-border-color); }
|
|
||||||
.seg label:first-child { border-left:0; }
|
|
||||||
.seg input { display:none; }
|
|
||||||
.seg label:has(input:checked) { background:var(--pico-primary-background); color:#fff; }
|
|
||||||
.tiers { width:100%; font-size:.86rem; }
|
|
||||||
.tiers td, .tiers th { padding:.3rem .4rem; vertical-align:middle; }
|
|
||||||
.tiers input, .tiers select { margin:0; padding:.25rem .4rem; font-size:.85rem; height:auto; }
|
|
||||||
.savebar-al { position:sticky; bottom:0; display:flex; gap:.8rem; align-items:center; padding:.7rem 0; background:var(--pico-background-color);
|
|
||||||
border-top:1px solid var(--pico-muted-border-color); z-index:5; }
|
|
||||||
.savebar-al button { width:auto; margin:0; }
|
|
||||||
.dirty { color:#e6b800; font-weight:600; }
|
|
||||||
.backs { display:flex; flex-wrap:wrap; gap:.4rem; align-items:center; }
|
|
||||||
.backs .b { display:flex; align-items:center; gap:.2rem; border:1px solid var(--pico-muted-border-color); border-radius:8px; padding:.15rem .3rem; }
|
|
||||||
.backs .b img { width:30px; height:30px; object-fit:contain; }
|
|
||||||
.colors { display:flex; gap:1rem; flex-wrap:wrap; align-items:center; }
|
|
||||||
.colors label { display:flex; gap:.4rem; align-items:center; margin:0; font-size:.88rem; }
|
|
||||||
.colors input[type=color] { width:2.6rem; height:2rem; padding:0; margin:0; }
|
|
||||||
.hint { color:var(--pico-muted-color); font-size:.8rem; }
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<h2 class="set-h">Alerts</h2>
|
|
||||||
<p class="set-intro"><a href="/actions/alerts/preview" target="_blank" rel="noopener" style="float:right; margin-left:1rem;">Open the preview ↗</a>What follows, subs, gifts, raids, bits, tips and the Hype Train look and sound like. Pictures and sounds come from
|
|
||||||
<a href="/media">Media</a> (upload your own there). Changes reach OBS as soon as you save; use Test to see them.</p>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Style</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Alerts<small>Follows, subs, gifts, raids, bits, tips, Hype Train.</small></div>
|
|
||||||
<span class="seg"><% for (const [v, l] of [['card', 'Card'], ['polaroid', 'Polaroid']]) { %><label><input type="radio" name="style" value="<%= v %>"><%= l %></label><% } %></span>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">New redeem variations<small>Look of variations you add on Redeems (each variation can still be changed there).</small></div>
|
|
||||||
<span class="seg"><% for (const [v, l] of [['card', 'Card'], ['cassette', 'Cassette']]) { %><label><input type="radio" name="redeemStyle" value="<%= v %>"><%= l %></label><% } %></span>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Read-aloud redeems<small>Variations with a TTS voice.</small></div>
|
|
||||||
<span class="seg"><% for (const [v, l] of [['card', 'Card'], ['letter', 'Letter']]) { %><label><input type="radio" name="ttsStyle" value="<%= v %>"><%= l %></label><% } %></span>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Card colours</div>
|
|
||||||
<div class="colors">
|
|
||||||
<label><input type="color" data-k="card.accent"> accent</label>
|
|
||||||
<label><input type="color" data-k="card.bg"> background</label>
|
|
||||||
<label><input type="color" data-k="card.text"> text</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Volume<small>Alert sounds (a bits tier can have its own).</small></div>
|
|
||||||
<div class="set-inline"><input type="range" min="0" max="1" step="0.05" data-k="volume" style="max-width:240px;"><span id="vol-out" class="hint"></span></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Events</h3>
|
|
||||||
<div class="al-grid" id="events">
|
|
||||||
<span class="hd">Event</span><span class="hd">Picture</span><span class="hd">Sound</span><span class="hd"></span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Bits</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">No alert under</div>
|
|
||||||
<div class="set-inline"><input type="number" min="1" data-k="bitsMin" style="max-width:7rem;"> <span class="hint">bits</span></div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row stack">
|
|
||||||
<div class="lbl">Tiers<small>The highest tier the cheer reaches is used.</small></div>
|
|
||||||
<div>
|
|
||||||
<div style="overflow-x:auto;"><table class="tiers"><thead><tr><th>From</th><th>Picture</th><th>Sound</th><th>Volume</th><th>Badge</th><th>Hearts</th><th></th></tr></thead><tbody id="tiers"></tbody></table></div>
|
|
||||||
<div class="set-inline"><button type="button" class="outline btn-xs" id="tier-add">+ Add tier</button>
|
|
||||||
<button type="button" class="outline btn-xs" data-test="bits-120">Test 120 bits</button><button type="button" class="outline btn-xs" data-test="bits-500">Test 500 bits</button></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Extras</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Corner sticker<small>Polaroid: sticker on the photo's corner (and the extra ones for big alerts).</small></div>
|
|
||||||
<div class="pk" data-pick="heart" data-type="image"></div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Photos behind<small>Polaroid: photos fanned out behind multi-month subs, gift bombs and raids.</small></div>
|
|
||||||
<div class="backs" id="backs"></div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Raid send-off picture<small>When the raided channel has no picture.</small></div>
|
|
||||||
<div class="pk" data-pick="raidFallback" data-type="image"></div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Default redeem sticker<small>Card and Cassette redeems whose variation has no picture.</small></div>
|
|
||||||
<div class="pk" data-pick="defaultSticker" data-type="image"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="savebar-al">
|
|
||||||
<button type="button" id="save">Save</button>
|
|
||||||
<span id="state" class="hint">No changes</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
let T = <%- J(theme) %>;
|
|
||||||
const IMAGES = <%- J(images.map(m => ({ url: m.url, label: m.label }))) %>;
|
|
||||||
const SOUNDS = <%- J(sounds.map(m => ({ url: m.url, label: m.label }))) %>;
|
|
||||||
const EVENTS = [
|
|
||||||
['follow', 'Follow', '', 'follow', 'follow'], ['sub', 'New sub', '', 'sub', 'sub-new'], ['resub', 'Resub', 'sound: same as New sub', null, 'sub-resub'],
|
|
||||||
['prime', 'Prime sub', 'sound: same as New sub', null, 'sub-prime'], ['gift', 'Gift subs', '', 'gift', 'gift-10'],
|
|
||||||
['streak', 'Watch streak', '', 'streak', 'streak'], ['raid', 'Raid', '', 'raid', 'raid'], ['tip', 'Tip', 'StreamElements', 'tip', 'tip-25'],
|
|
||||||
['hype', 'Hype Train', 'start sound', 'hypeBegin', 'hype-begin'],
|
|
||||||
[null, 'Hype Train level up', '', 'hypeLevel', 'hype-level'], [null, 'Hype Train end', '', 'hypeEnd', 'hype-end'],
|
|
||||||
];
|
|
||||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
||||||
const get = k => k.split('.').reduce((o, p) => o?.[p], T);
|
|
||||||
const set = (k, v) => { const ps = k.split('.'); let o = T; ps.slice(0, -1).forEach(p => { o = o[p] = o[p] || {}; }); o[ps.at(-1)] = v; dirty(); };
|
|
||||||
const state = document.getElementById('state');
|
|
||||||
const dirty = () => { state.textContent = 'Unsaved changes'; state.className = 'dirty'; };
|
|
||||||
|
|
||||||
// a picker: select from the media library (+ thumbnail / play button); onChange(url)
|
|
||||||
let audio = null;
|
|
||||||
function picker(type, value, onChange) {
|
|
||||||
const list = type === 'image' ? IMAGES : SOUNDS;
|
|
||||||
const w = document.createElement('span'); w.className = 'pk';
|
|
||||||
const opts = ['<option value="">— none —</option>', ...list.map(m => `<option value="${esc(m.url)}">${esc(m.label)}</option>`)];
|
|
||||||
if (value && !list.some(m => m.url === value)) opts.push(`<option value="${esc(value)}">${esc(value.split('/').pop())} (missing)</option>`);
|
|
||||||
w.innerHTML = (type === 'image' ? `<img src="${esc(value || '')}" alt="">` : '') + `<select>${opts.join('')}</select>` + (type === 'audio' ? '<button type="button" class="outline" title="Play">▶</button>' : '');
|
|
||||||
const sel = w.querySelector('select'); sel.value = value || '';
|
|
||||||
sel.addEventListener('change', () => { if (type === 'image') w.querySelector('img').src = sel.value; onChange(sel.value); });
|
|
||||||
if (type === 'audio') w.querySelector('button').addEventListener('click', () => { audio?.pause(); if (sel.value) { audio = new Audio(sel.value); audio.volume = T.volume ?? .8; audio.play(); } });
|
|
||||||
return w;
|
|
||||||
}
|
|
||||||
const testBtn = key => { const b = document.createElement('button'); b.type = 'button'; b.className = 'outline btn-xs'; b.textContent = 'Test'; b.dataset.test = key; return b; };
|
|
||||||
|
|
||||||
function render() {
|
|
||||||
// style radios, colours, numbers
|
|
||||||
for (const n of ['style', 'redeemStyle', 'ttsStyle']) document.querySelectorAll(`input[name=${n}]`).forEach(r => { r.checked = r.value === T[n]; });
|
|
||||||
document.querySelectorAll('[data-k]').forEach(i => { i.value = get(i.dataset.k) ?? ''; });
|
|
||||||
document.getElementById('vol-out').textContent = Math.round((T.volume ?? .8) * 100) + '%';
|
|
||||||
// events grid
|
|
||||||
const g = document.getElementById('events');
|
|
||||||
g.querySelectorAll(':scope > :not(.hd)').forEach(x => x.remove());
|
|
||||||
for (const [artKey, label, sub, soundKey, test] of EVENTS) {
|
|
||||||
const name = document.createElement('div'); name.className = 'al-name'; name.innerHTML = esc(label) + (sub ? `<small>${esc(sub)}</small>` : '');
|
|
||||||
g.append(name,
|
|
||||||
artKey ? picker('image', T.art[artKey], v => { T.art[artKey] = v; dirty(); }) : document.createElement('span'),
|
|
||||||
soundKey ? picker('audio', T.sounds[soundKey], v => { T.sounds[soundKey] = v; dirty(); }) : Object.assign(document.createElement('span'), { className: 'hint', textContent: '' }),
|
|
||||||
testBtn(test));
|
|
||||||
}
|
|
||||||
// bits tiers
|
|
||||||
const tb = document.getElementById('tiers'); tb.innerHTML = '';
|
|
||||||
T.bitsTiers.forEach((t, i) => {
|
|
||||||
const tr = document.createElement('tr');
|
|
||||||
tr.innerHTML = `<td><input type="number" min="1" value="${t.min}" style="width:6rem"></td><td></td><td></td>
|
|
||||||
<td><input type="number" min="0" max="1" step="0.05" value="${t.volume ?? ''}" placeholder="default" style="width:6rem"></td>
|
|
||||||
<td><input type="color" value="${esc(t.badge || '#8a8aa8')}" style="width:2.4rem; height:1.8rem; padding:0"></td>
|
|
||||||
<td><select style="width:4rem">${[0, 1, 2, 3].map(h => `<option ${h === t.hearts ? 'selected' : ''}>${h}</option>`).join('')}</select></td>
|
|
||||||
<td><button type="button" class="outline btn-xs" title="Remove tier">✕</button></td>`;
|
|
||||||
tr.children[1].append(picker('image', t.art, v => { t.art = v; dirty(); }));
|
|
||||||
tr.children[2].append(picker('audio', t.sound, v => { t.sound = v; dirty(); }));
|
|
||||||
const [min, , , vol, badge, hearts] = [...tr.children].map(td => td.querySelector('input, select'));
|
|
||||||
min.addEventListener('input', () => { t.min = +min.value || 1; dirty(); });
|
|
||||||
vol.addEventListener('input', () => { t.volume = vol.value === '' ? null : +vol.value; dirty(); });
|
|
||||||
badge.addEventListener('input', () => { t.badge = badge.value; dirty(); });
|
|
||||||
hearts.addEventListener('change', () => { t.hearts = +hearts.value; dirty(); });
|
|
||||||
tr.querySelector('button').addEventListener('click', () => { T.bitsTiers.splice(i, 1); dirty(); render(); });
|
|
||||||
tb.append(tr);
|
|
||||||
});
|
|
||||||
// single pickers
|
|
||||||
document.querySelectorAll('[data-pick]').forEach(el => {
|
|
||||||
const key = el.dataset.pick, type = el.dataset.type;
|
|
||||||
const w = picker(type, T[key], v => { T[key] = v; dirty(); });
|
|
||||||
w.dataset.pick = key; w.dataset.type = type;
|
|
||||||
el.replaceWith(w);
|
|
||||||
});
|
|
||||||
// photos behind
|
|
||||||
const bk = document.getElementById('backs'); bk.innerHTML = '';
|
|
||||||
T.back.forEach((u, i) => {
|
|
||||||
const b = document.createElement('span'); b.className = 'b';
|
|
||||||
b.innerHTML = `<img src="${esc(u)}" alt="" title="${esc(u.split('/').pop())}"><button type="button" class="outline btn-xs" title="Remove">✕</button>`;
|
|
||||||
b.querySelector('button').addEventListener('click', () => { T.back.splice(i, 1); dirty(); render(); });
|
|
||||||
bk.append(b);
|
|
||||||
});
|
|
||||||
const add = picker('image', '', v => { if (v) { T.back.push(v); dirty(); render(); } });
|
|
||||||
add.querySelector('select').options[0].textContent = '+ add a photo';
|
|
||||||
bk.append(add);
|
|
||||||
}
|
|
||||||
|
|
||||||
document.querySelectorAll('input[name=style], input[name=redeemStyle], input[name=ttsStyle]').forEach(r => r.addEventListener('change', () => { T[r.name] = r.value; dirty(); }));
|
|
||||||
document.querySelectorAll('[data-k]').forEach(i => i.addEventListener('input', () => {
|
|
||||||
set(i.dataset.k, i.type === 'number' || i.type === 'range' ? +i.value : i.value);
|
|
||||||
if (i.dataset.k === 'volume') document.getElementById('vol-out').textContent = Math.round(i.value * 100) + '%';
|
|
||||||
}));
|
|
||||||
document.getElementById('tier-add').addEventListener('click', () => { T.bitsTiers.push({ min: 1, art: '', sound: '', volume: null, badge: '#8a8aa8', hearts: 0 }); dirty(); render(); });
|
|
||||||
|
|
||||||
async function save() {
|
|
||||||
state.textContent = 'Saving…'; state.className = 'hint';
|
|
||||||
try {
|
|
||||||
const r = await fetch('/actions/alerts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(T) });
|
|
||||||
const j = await r.json();
|
|
||||||
if (!j.ok) throw new Error(j.error || r.status);
|
|
||||||
T = j.theme; render();
|
|
||||||
state.textContent = 'Saved'; state.className = 'hint';
|
|
||||||
} catch (e) { state.textContent = 'Save failed: ' + e.message; state.className = 'dirty'; }
|
|
||||||
}
|
|
||||||
document.getElementById('save').addEventListener('click', save);
|
|
||||||
document.addEventListener('keydown', e => { if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); save(); } });
|
|
||||||
window.addEventListener('beforeunload', e => { if (state.classList.contains('dirty')) { e.preventDefault(); e.returnValue = ''; } });
|
|
||||||
// test buttons: save first, then play the sample on the overlay
|
|
||||||
document.addEventListener('click', async e => {
|
|
||||||
const b = e.target.closest('[data-test]'); if (!b) return;
|
|
||||||
if (state.classList.contains('dirty')) await save();
|
|
||||||
const r = await fetch('/alerts/test/' + encodeURIComponent(b.dataset.test), { method: 'POST' });
|
|
||||||
const l = b.textContent; b.textContent = r.ok ? 'Sent' : 'Failed'; setTimeout(() => { b.textContent = l; }, 1200);
|
|
||||||
});
|
|
||||||
render();
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
|
|
@ -1,126 +1,46 @@
|
||||||
<h2>Dashboard</h2>
|
<h2>Dashboard</h2>
|
||||||
|
|
||||||
<div class="dash-status">
|
<div style="display:flex; gap:1rem; margin-bottom:1.5rem; flex-wrap:wrap;">
|
||||||
<a href="/settings/connections" title="Settings → Connections">
|
<div>
|
||||||
Twitch <% if (eventsubStatus.connected) { %><span class="badge badge-green">connected</span><% } else if (eventsubStatus.running) { %><span class="badge badge-grey">connecting…</span><% } else { %><span class="badge badge-red">not running</span><% } %>
|
<strong>Channel:</strong>
|
||||||
</a>
|
<%= settings.channel || '<em>not set</em>' %>
|
||||||
<a href="/settings/connections" title="Settings → Connections">
|
|
||||||
StreamElements <% if (!seStatus.enabled) { %><span class="badge badge-grey">off</span><% } else if (seStatus.subscribed) { %><span class="badge badge-green">connected</span><% } else { %><span class="badge badge-grey">connecting…</span><% } %>
|
|
||||||
</a>
|
|
||||||
<a href="/settings/obs" title="Browser source links for OBS">OBS links →</a>
|
|
||||||
<% if (eventsubStatus.failed.length) { %><a href="/settings/connections" style="color:#f88">Some Twitch permissions are missing: log in again</a><% } %>
|
|
||||||
</div>
|
</div>
|
||||||
<style>
|
<div>
|
||||||
.dash-status { display:flex; gap:1.4rem; flex-wrap:wrap; align-items:center; margin:0 0 1.4rem; padding:.6rem .9rem;
|
<strong>Overlay URL:</strong>
|
||||||
border:1px solid var(--pico-muted-border-color); border-radius:12px; }
|
<code><%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %></code>
|
||||||
.dash-status a { text-decoration:none; font-size:.92rem; }
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<div style="display:flex; gap:.8rem; align-items:center; margin-bottom:1.5rem;">
|
|
||||||
<button type="button" id="skip-alert" class="outline" style="width:auto; margin:0;"
|
|
||||||
title="Stops the alert that is on screen right now (sound and TTS voice too). Queued alerts carry on.">⏭ Skip current alert</button>
|
|
||||||
<small id="skip-status"></small>
|
|
||||||
</div>
|
</div>
|
||||||
<script>
|
|
||||||
document.getElementById('skip-alert').addEventListener('click', async () => {
|
|
||||||
const st = document.getElementById('skip-status');
|
|
||||||
try { const r = await fetch('/alerts/skip', { method: 'POST' }); st.textContent = r.ok ? 'Skipped' : `Failed (${r.status})`; }
|
|
||||||
catch (e) { st.textContent = 'Failed: ' + e.message; }
|
|
||||||
setTimeout(() => { st.textContent = ''; }, 3000);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<h3>Raid</h3>
|
|
||||||
<p><small>Start the raid here and the send-off card stays on stream (silent) until the raid happens. Same as Twitch's Raid button.</small></p>
|
|
||||||
<div style="display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-bottom:.4rem;">
|
|
||||||
<input id="raid-target" placeholder="channel name" style="width:16rem; margin:0;">
|
|
||||||
<button type="button" id="raid-start" style="width:auto; margin:0;">Start raid</button>
|
|
||||||
<button type="button" id="raid-cancel" class="outline" style="width:auto; margin:0;">Cancel raid</button>
|
|
||||||
<small id="raid-status"></small>
|
|
||||||
</div>
|
</div>
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
const out = document.getElementById('raid-status');
|
|
||||||
const call = async (url, body) => {
|
|
||||||
try {
|
|
||||||
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
|
|
||||||
const j = await r.json().catch(() => ({}));
|
|
||||||
out.textContent = j.ok ? (j.target ? `Raiding ${j.target}${j.viewers != null ? ' with ' + j.viewers : ''}…` : 'Raid cancelled') : `Failed: ${j.error || r.status}`;
|
|
||||||
} catch (e) { out.textContent = 'Failed: ' + e.message; }
|
|
||||||
};
|
|
||||||
document.getElementById('raid-start').addEventListener('click', () => call('/alerts/raid/start', { target: document.getElementById('raid-target').value }));
|
|
||||||
document.getElementById('raid-cancel').addEventListener('click', () => call('/alerts/raid/cancel'));
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<h3>Test alerts</h3>
|
<h3>Recent activity</h3>
|
||||||
<p><small>Sends a sample alert to the overlay (OBS). Not logged, no actions fired. Looks and sounds: <a href="/actions/alerts">Actions → Alerts</a>.</small></p>
|
<% if (logs.length === 0) { %>
|
||||||
<div id="test-alerts" style="display:flex; flex-wrap:wrap; gap:.4rem; margin-bottom:.5rem;">
|
<p><em>No activity yet. Events will appear here once your overlay is connected and Twitch fires events.</em></p>
|
||||||
<% for (const key of testKeys) { %>
|
<% } else { %>
|
||||||
<button type="button" class="outline" data-key="<%= key %>" style="width:auto; padding:.3rem .8rem; margin:0;"><%= key %></button>
|
<figure>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Time</th>
|
||||||
|
<th>Event</th>
|
||||||
|
<th>User</th>
|
||||||
|
<th>Detail</th>
|
||||||
|
<th>Actions fired</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% for (const log of logs) { %>
|
||||||
|
<tr>
|
||||||
|
<td><small><%= log.created_at %></small></td>
|
||||||
|
<td><code><%= log.event_type %></code></td>
|
||||||
|
<td><%= log.username || '—' %></td>
|
||||||
|
<td><%= log.event_detail || '—' %></td>
|
||||||
|
<td>
|
||||||
|
<span class="badge <%= log.actions_fired > 0 ? 'badge-green' : 'badge-grey' %>">
|
||||||
|
<%= log.actions_fired %>
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</figure>
|
||||||
<% } %>
|
<% } %>
|
||||||
</div>
|
|
||||||
<p><small id="test-status"></small></p>
|
|
||||||
<script>
|
|
||||||
document.querySelectorAll('#test-alerts button').forEach(b => b.addEventListener('click', async () => {
|
|
||||||
const out = document.getElementById('test-status');
|
|
||||||
try {
|
|
||||||
const r = await fetch('/alerts/test/' + encodeURIComponent(b.dataset.key), { method: 'POST' });
|
|
||||||
out.textContent = r.ok ? `Sent: ${b.dataset.key}` : `Failed (${r.status})`;
|
|
||||||
} catch (e) { out.textContent = 'Failed: ' + e.message; }
|
|
||||||
}));
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div style="display:flex; align-items:center; gap:1rem; flex-wrap:wrap;">
|
|
||||||
<h3 style="margin:0;">Recent activity</h3>
|
|
||||||
<button type="button" id="activity-reload" class="outline" style="width:auto; padding:.3rem .8rem; margin:0;">Reload</button>
|
|
||||||
<label style="margin:0;"><input type="checkbox" id="activity-auto"> auto-refresh (15 s)</label>
|
|
||||||
<small id="activity-updated"></small>
|
|
||||||
</div>
|
|
||||||
<div id="activity"><%- include('_activity') %></div>
|
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
const box = document.getElementById('activity');
|
|
||||||
const stamp = document.getElementById('activity-updated');
|
|
||||||
const auto = document.getElementById('activity-auto');
|
|
||||||
let timer = null;
|
|
||||||
// times are stored in UTC: show them in this browser's time zone
|
|
||||||
function localTimes() {
|
|
||||||
box.querySelectorAll('time[datetime]').forEach(t => {
|
|
||||||
const d = new Date(t.getAttribute('datetime'));
|
|
||||||
if (!isNaN(d)) { t.title = t.textContent; t.textContent = d.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }); }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Replay buttons (the table is re-rendered on reload, so listen on the box)
|
|
||||||
box.addEventListener('click', async ev => {
|
|
||||||
const b = ev.target.closest('.activity-replay'); if (!b) return;
|
|
||||||
const st = b.parentElement.querySelector('.activity-replay-status');
|
|
||||||
b.disabled = true; st.textContent = '…';
|
|
||||||
try {
|
|
||||||
const r = await fetch('/activity/' + encodeURIComponent(b.dataset.id) + '/replay', { method: 'POST' });
|
|
||||||
const j = await r.json().catch(() => ({}));
|
|
||||||
st.textContent = j.ok ? 'sent' : (j.error || `failed (${r.status})`);
|
|
||||||
} catch (e) { st.textContent = 'failed: ' + e.message; }
|
|
||||||
b.disabled = false;
|
|
||||||
});
|
|
||||||
localTimes();
|
|
||||||
async function reload() {
|
|
||||||
try {
|
|
||||||
const r = await fetch('/activity', { headers: { 'Accept': 'text/html' } });
|
|
||||||
if (r.redirected || !r.ok) { stamp.textContent = 'Reload failed (logged out?)'; return; }
|
|
||||||
box.innerHTML = await r.text();
|
|
||||||
localTimes();
|
|
||||||
stamp.textContent = 'Updated ' + new Date().toLocaleTimeString();
|
|
||||||
} catch (e) { stamp.textContent = 'Reload failed: ' + e.message; }
|
|
||||||
}
|
|
||||||
function setAuto(on) {
|
|
||||||
clearInterval(timer);
|
|
||||||
if (on) timer = setInterval(reload, 15000);
|
|
||||||
try { localStorage.setItem('activityAuto', on ? '1' : '0'); } catch {}
|
|
||||||
}
|
|
||||||
document.getElementById('activity-reload').addEventListener('click', reload);
|
|
||||||
auto.addEventListener('change', () => setAuto(auto.checked));
|
|
||||||
try { auto.checked = localStorage.getItem('activityAuto') === '1'; } catch {}
|
|
||||||
setAuto(auto.checked);
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>HeyStreamer</title>
|
<title>HeyStreamer</title>
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
|
||||||
<style>
|
<style>
|
||||||
nav.container-fluid { padding-block: 0.5rem; }
|
nav.container-fluid { padding-block: 0.5rem; }
|
||||||
|
|
@ -14,45 +13,6 @@
|
||||||
.badge-green { background: #1a7a1a; color: #a8f0a8; }
|
.badge-green { background: #1a7a1a; color: #a8f0a8; }
|
||||||
.badge-red { background: #7a1a1a; color: #f0a8a8; }
|
.badge-red { background: #7a1a1a; color: #f0a8a8; }
|
||||||
.badge-grey { background: #333; color: #aaa; }
|
.badge-grey { background: #333; color: #aaa; }
|
||||||
nav ul li a.on { color: var(--pico-color); font-weight: 700; }
|
|
||||||
/* left sidebar of Actions / Settings */
|
|
||||||
main.with-side { max-width: 1400px; margin: 0 auto; }
|
|
||||||
.shell { display: grid; grid-template-columns: 210px minmax(0, 1fr); gap: 2rem; align-items: start; }
|
|
||||||
.side { position: sticky; top: 1rem; display: flex; flex-direction: column; gap: .15rem; }
|
|
||||||
.side-title { font-size: .75rem; text-transform: uppercase; letter-spacing: .08em; color: var(--pico-muted-color); margin: 0 0 .4rem .75rem; }
|
|
||||||
.side a { display: block; padding: .45rem .75rem; border-radius: 8px; text-decoration: none; color: var(--pico-muted-color); font-size: .95rem; }
|
|
||||||
.side a:hover { background: var(--pico-card-background-color); color: var(--pico-color); }
|
|
||||||
.side a.on { background: var(--pico-primary-background); color: #fff; font-weight: 600; }
|
|
||||||
@media (max-width: 800px) {
|
|
||||||
.shell { grid-template-columns: 1fr; gap: 1rem; }
|
|
||||||
.side { position: static; flex-direction: row; flex-wrap: wrap; }
|
|
||||||
.side-title { display: none; }
|
|
||||||
}
|
|
||||||
/* settings pages: one card per group, label left, control right */
|
|
||||||
.set-h { margin: 0 0 .3rem; }
|
|
||||||
.set-intro { color: var(--pico-muted-color); margin: 0 0 1.2rem; }
|
|
||||||
.set-card { border: 1px solid var(--pico-muted-border-color); border-radius: 12px; padding: 1rem 1.2rem; margin-bottom: 1.2rem; }
|
|
||||||
.set-card > h3 { font-size: 1.05rem; margin: 0 0 .8rem; }
|
|
||||||
.set-row { display: grid; grid-template-columns: minmax(180px, 280px) minmax(0, 1fr); gap: .4rem 1.4rem; align-items: start; padding: .7rem 0; border-top: 1px solid var(--pico-muted-border-color); }
|
|
||||||
.set-card > h3 + .set-row, .set-card > .set-row:first-child { border-top: 0; padding-top: 0; }
|
|
||||||
.set-row > .lbl { font-weight: 600; font-size: .92rem; }
|
|
||||||
.set-row > .lbl small { display: block; font-weight: 400; color: var(--pico-muted-color); font-size: .8rem; margin-top: .15rem; }
|
|
||||||
.set-row input:not([type=checkbox]):not([type=radio]), .set-row select, .set-row textarea { margin: 0; }
|
|
||||||
.set-row label { margin: 0; }
|
|
||||||
@media (max-width: 700px) { .set-row { grid-template-columns: 1fr; } }
|
|
||||||
.set-inline { display: flex; gap: .6rem; flex-wrap: wrap; align-items: center; }
|
|
||||||
.set-inline > * { margin: 0 !important; }
|
|
||||||
.btn-auto { width: auto !important; }
|
|
||||||
.savebar-set { position: sticky; bottom: 0; display: flex; gap: .8rem; align-items: center; padding: .7rem 0; background: var(--pico-background-color); border-top: 1px solid var(--pico-muted-border-color); margin-top: .5rem; z-index: 5; }
|
|
||||||
.savebar-set button { width: auto; margin: 0; }
|
|
||||||
.flash { padding: .5rem .8rem; border-radius: 8px; margin: 0 0 1rem; background: rgba(63,185,80,.15); border: 1px solid rgba(63,185,80,.5); }
|
|
||||||
.flash.err { background: rgba(248,136,136,.12); border-color: #f88; }
|
|
||||||
.copy { display: flex; gap: .4rem; align-items: center; }
|
|
||||||
.copy code { flex: 1; overflow-x: auto; white-space: nowrap; padding: .35rem .55rem; }
|
|
||||||
.copy button { width: auto; margin: 0; padding: .25rem .7rem; font-size: .8rem; }
|
|
||||||
/* sensitive values (OBS links, HUDFX link, tokens): blurred until the eye is clicked; Copy still copies them */
|
|
||||||
.secret:not(.shown) { filter: blur(6px); user-select: none; pointer-events: none; }
|
|
||||||
.eye { width: auto !important; margin: 0 !important; padding: .25rem .55rem !important; font-size: .9rem !important; line-height: 1; }
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
@ -61,59 +21,18 @@
|
||||||
<li><a class="nav-brand" href="/">HeyStreamer</a></li>
|
<li><a class="nav-brand" href="/">HeyStreamer</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
<ul>
|
<ul>
|
||||||
<% const top = locals.sidebar ? locals.sidebar.name : ''; %>
|
<li><a href="/">Dashboard</a></li>
|
||||||
<li><a href="/" class="<%= !top && locals.navActive === 'dashboard' ? 'on' : '' %>">Dashboard</a></li>
|
<li><a href="/actions">Actions</a></li>
|
||||||
<li><a href="/redeems" class="<%= top === 'actions' ? 'on' : '' %>">Actions</a></li>
|
<li><a href="/media">Media</a></li>
|
||||||
<li><a href="/stats" class="<%= locals.navActive === 'stats' ? 'on' : '' %>">Stats</a></li>
|
<li><a href="/layout">Layout</a></li>
|
||||||
<li><a href="/settings" class="<%= top === 'settings' ? 'on' : '' %>">Settings</a></li>
|
<li><a href="/settings">Settings</a></li>
|
||||||
<% if (locals.user) { %>
|
<% if (locals.user) { %>
|
||||||
<li><a href="/auth/logout">Logout (<%= user.login %>)</a></li>
|
<li><a href="/auth/logout">Logout (<%= user.login %>)</a></li>
|
||||||
<% } %>
|
<% } %>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
<main class="container<%= locals.sidebar ? '-fluid with-side' : '' %>">
|
<main class="container">
|
||||||
<% if (locals.sidebar) { %>
|
|
||||||
<div class="shell">
|
|
||||||
<aside class="side">
|
|
||||||
<div class="side-title"><%= sidebar.title %></div>
|
|
||||||
<% for (const i of sidebar.items) { %>
|
|
||||||
<a href="<%= i.href %>" class="<%= i.on ? 'on' : '' %>"<% if (i.hint) { %> title="<%= i.hint %>"<% } %>><%= i.label %></a>
|
|
||||||
<% } %>
|
|
||||||
</aside>
|
|
||||||
<section class="pane"><%- body %></section>
|
|
||||||
</div>
|
|
||||||
<% } else { %>
|
|
||||||
<%- body %>
|
<%- body %>
|
||||||
<% } %>
|
|
||||||
</main>
|
</main>
|
||||||
<script>
|
|
||||||
// eye buttons: <button data-reveal="#id"> shows / hides a blurred .secret element or a password input
|
|
||||||
document.addEventListener('click', e => {
|
|
||||||
const b = e.target.closest('[data-reveal]');
|
|
||||||
if (!b) return;
|
|
||||||
const t = document.querySelector(b.dataset.reveal);
|
|
||||||
if (!t) return;
|
|
||||||
const show = t.tagName === 'INPUT' ? t.type === 'password' : !t.classList.contains('shown');
|
|
||||||
if (t.tagName === 'INPUT') t.type = show ? 'text' : 'password'; else t.classList.toggle('shown', show);
|
|
||||||
b.textContent = show ? '🙈' : '👁'; b.title = show ? 'Hide' : 'Show';
|
|
||||||
});
|
|
||||||
// copy buttons: <button data-copy="text"> or data-copy-from="#id"
|
|
||||||
document.addEventListener('click', e => {
|
|
||||||
const b = e.target.closest('[data-copy],[data-copy-from]');
|
|
||||||
if (!b) return;
|
|
||||||
const text = b.dataset.copy ?? document.querySelector(b.dataset.copyFrom)?.textContent ?? '';
|
|
||||||
navigator.clipboard?.writeText(text).then(() => { const l = b.textContent; b.textContent = 'Copied'; setTimeout(() => { b.textContent = l; }, 1200); });
|
|
||||||
});
|
|
||||||
// Two-click delete instead of a browser confirm() dialog: first click arms the button, second submits.
|
|
||||||
document.addEventListener('click', e => {
|
|
||||||
const b = e.target.closest('button[data-confirm]');
|
|
||||||
if (!b) return;
|
|
||||||
if (b.dataset.armed) { if (b.type !== 'submit') b.form.requestSubmit(); return; } // armed submit button: let it submit
|
|
||||||
e.preventDefault();
|
|
||||||
b.dataset.armed = '1'; b.dataset.label = b.textContent; b.textContent = b.dataset.confirm || 'Really delete?';
|
|
||||||
b.style.fontWeight = '700';
|
|
||||||
setTimeout(() => { delete b.dataset.armed; b.textContent = b.dataset.label; b.style.fontWeight = ''; }, 4000);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
91
views/layout_editor.ejs
Normal file
91
views/layout_editor.ejs
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
<h2>Layout editor</h2>
|
||||||
|
<p><small>Drag the handles in the preview to reposition widgets. Use the form below to adjust style.</small></p>
|
||||||
|
|
||||||
|
<div style="position:relative; width:100%; padding-bottom:56.25%; border:1px solid #333; border-radius:8px; overflow:hidden; margin-bottom:1.5rem;">
|
||||||
|
<iframe
|
||||||
|
id="preview"
|
||||||
|
src="/overlay/<%= settings.overlay_id %>/preview"
|
||||||
|
style="position:absolute; top:0; left:0; width:1920px; height:1080px; border:none; transform-origin:top left;"
|
||||||
|
scrolling="no"
|
||||||
|
></iframe>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form method="POST" action="/layout">
|
||||||
|
<h3>Chat style</h3>
|
||||||
|
<div style="display:grid; grid-template-columns:repeat(3,1fr); gap:1rem;">
|
||||||
|
<label>Font size (px) <input type="number" name="chat_font_size" value="<%= layout.chat_font_size %>" min="8" max="64"></label>
|
||||||
|
<label>Font family <input type="text" name="chat_font_family" value="<%= layout.chat_font_family %>"></label>
|
||||||
|
<label>Text colour <input type="color" name="chat_text_color" value="<%= layout.chat_text_color %>"></label>
|
||||||
|
<label>Background opacity (0–1) <input type="number" name="chat_bg_opacity" value="<%= layout.chat_bg_opacity %>" min="0" max="1" step="0.05"></label>
|
||||||
|
<label>Border radius (px) <input type="number" name="chat_border_radius" value="<%= layout.chat_border_radius %>" min="0" max="32"></label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>Alert style</h3>
|
||||||
|
<div style="display:grid; grid-template-columns:repeat(3,1fr); gap:1rem;">
|
||||||
|
<label>Font size (px) <input type="number" name="alert_font_size" value="<%= layout.alert_font_size %>" min="12" max="96"></label>
|
||||||
|
<label>Text colour <input type="color" name="alert_text_color" value="<%= layout.alert_text_color %>"></label>
|
||||||
|
<label>Background opacity (0–1) <input type="number" name="alert_bg_opacity" value="<%= layout.alert_bg_opacity %>" min="0" max="1" step="0.05"></label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit">Save style</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/interact.js@1.10.27/dist/interact.min.js"></script>
|
||||||
|
<script>
|
||||||
|
const iframe = document.getElementById('preview');
|
||||||
|
|
||||||
|
function applyScale() {
|
||||||
|
const scale = iframe.parentElement.offsetWidth / 1920;
|
||||||
|
iframe.style.transform = `scale(${scale})`;
|
||||||
|
}
|
||||||
|
applyScale();
|
||||||
|
window.addEventListener('resize', applyScale);
|
||||||
|
|
||||||
|
iframe.addEventListener('load', () => {
|
||||||
|
const iDoc = iframe.contentDocument;
|
||||||
|
const scale = iframe.parentElement.offsetWidth / 1920;
|
||||||
|
|
||||||
|
['chat', 'alert'].forEach(widget => {
|
||||||
|
const handle = iDoc.getElementById(`${widget}-handle`);
|
||||||
|
if (!handle) return;
|
||||||
|
|
||||||
|
interact(handle).draggable({
|
||||||
|
listeners: {
|
||||||
|
move(event) {
|
||||||
|
const rect = iDoc.documentElement;
|
||||||
|
const x = parseFloat(getComputedStyle(handle).left) + event.dx / scale;
|
||||||
|
const y = parseFloat(getComputedStyle(handle).top) + event.dy / scale;
|
||||||
|
const left = Math.max(0, Math.min(x / 1920 * 100, 95));
|
||||||
|
const top = Math.max(0, Math.min(y / 1080 * 100, 95));
|
||||||
|
|
||||||
|
if (widget === 'chat') {
|
||||||
|
iDoc.documentElement.style.setProperty('--chat-left', `${left}%`);
|
||||||
|
iDoc.documentElement.style.setProperty('--chat-top', `${top}%`);
|
||||||
|
} else {
|
||||||
|
iDoc.documentElement.style.setProperty('--alert-left', `${left}%`);
|
||||||
|
iDoc.documentElement.style.setProperty('--alert-top', `${top}%`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
end() { savePositions(); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function savePositions() {
|
||||||
|
const iDoc = iframe.contentDocument;
|
||||||
|
const get = (v) => parseFloat(getComputedStyle(iDoc.documentElement).getPropertyValue(v));
|
||||||
|
fetch('/layout/positions', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
chat_left: get('--chat-left') || <%= layout.chat_left %>,
|
||||||
|
chat_top: get('--chat-top') || <%= layout.chat_top %>,
|
||||||
|
chat_width: <%= layout.chat_width %>,
|
||||||
|
chat_height: <%= layout.chat_height %>,
|
||||||
|
alert_left: get('--alert-left') || <%= layout.alert_left %>,
|
||||||
|
alert_top: get('--alert-top') || <%= layout.alert_top %>,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
@ -4,7 +4,6 @@
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>HeyStreamer — Login</title>
|
<title>HeyStreamer — Login</title>
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
|
||||||
<style>
|
<style>
|
||||||
body { display: flex; align-items: center; justify-content: center; min-height: 100vh; }
|
body { display: flex; align-items: center; justify-content: center; min-height: 100vh; }
|
||||||
|
|
|
||||||
163
views/media.ejs
163
views/media.ejs
|
|
@ -1,124 +1,53 @@
|
||||||
<style>
|
|
||||||
.drop { border:2px dashed var(--pico-muted-border-color); border-radius:12px; padding:1.2rem; text-align:center; cursor:pointer;
|
|
||||||
transition:border-color .15s, background .15s; margin-bottom:.6rem; }
|
|
||||||
.drop.over { border-color:var(--pico-primary); background:rgba(1, 114, 173, .12); }
|
|
||||||
.drop strong { display:block; margin-bottom:.2rem; }
|
|
||||||
.drop input { display:none; }
|
|
||||||
.upbar { height:6px; border-radius:3px; background:var(--pico-muted-border-color); overflow:hidden; margin:.4rem 0; }
|
|
||||||
.upbar > div { height:100%; width:0; background:var(--pico-primary); transition:width .1s; }
|
|
||||||
.tools { display:flex; gap:.8rem; align-items:center; flex-wrap:wrap; margin:1rem 0 .4rem; }
|
|
||||||
.tools input { margin:0; max-width:320px; }
|
|
||||||
.tools .meta, .meta { color:var(--pico-muted-color); font-size:.85rem; }
|
|
||||||
.lib-h { margin:1.4rem 0 .5rem; display:flex; align-items:baseline; gap:.6rem; }
|
|
||||||
.grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(210px, 1fr)); gap:.6rem; }
|
|
||||||
.item { border:1px solid var(--pico-muted-border-color); border-radius:10px; padding:.5rem; display:flex; flex-direction:column; gap:.35rem; }
|
|
||||||
.item .pv { height:110px; border-radius:6px; background:#0004; display:flex; align-items:center; justify-content:center; overflow:hidden; }
|
|
||||||
.item .pv img { max-width:100%; max-height:100%; object-fit:contain; }
|
|
||||||
.item .pv video { max-width:100%; max-height:100%; }
|
|
||||||
.item .name { font-weight:600; font-size:.88rem; overflow-wrap:anywhere; }
|
|
||||||
.item .row { display:flex; gap:.35rem; align-items:center; flex-wrap:wrap; font-size:.75rem; color:var(--pico-muted-color); }
|
|
||||||
.pill { font-size:.7rem; padding:.02rem .45rem; border-radius:99px; border:1px solid var(--pico-muted-border-color); }
|
|
||||||
.pill.up { border-color:#3fb950; color:#7ee08f; }
|
|
||||||
.pill.used { border-color:#a970ff; color:#c9a8ff; }
|
|
||||||
.item button, .item audio { margin:0; }
|
|
||||||
.item audio { width:100%; height:30px; }
|
|
||||||
.btn-sm { margin:0; padding:.2rem .6rem; font-size:.75rem; width:auto; }
|
|
||||||
.item form { margin:0 0 0 auto; }
|
|
||||||
.hidden-by-filter { display:none !important; }
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<h2>Media library</h2>
|
<h2>Media library</h2>
|
||||||
|
<p><small>Upload audio (MP3, WAV, OGG) or video (MP4, WebM) files to use in actions. Max 50 MB.</small></p>
|
||||||
|
|
||||||
<div class="drop" id="drop" title="Audio: MP3, WAV, OGG, M4A. Video: WebM (transparent looks best over the game), MP4. Images (stickers): PNG, WebP, GIF, JPG. Max 50 MB per file, up to 20 at once.">
|
<form method="POST" action="/media/upload" enctype="multipart/form-data">
|
||||||
<strong>Drop files here, or click to choose</strong>
|
<div style="display:flex; gap:1rem; align-items:flex-end;">
|
||||||
<span class="meta">sounds, videos or sticker images · several at once</span>
|
<label style="flex:1;">
|
||||||
<input type="file" id="files" multiple accept="audio/*,video/*,image/png,image/webp,image/gif,image/jpeg">
|
File
|
||||||
|
<input type="file" name="file" accept="audio/*,video/*" required>
|
||||||
|
</label>
|
||||||
|
<button type="submit">Upload</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="up" hidden><div class="upbar"><div id="upfill"></div></div><span class="meta" id="upmsg"></span></div>
|
|
||||||
|
|
||||||
<div class="tools">
|
|
||||||
<input type="search" id="filter" placeholder="Filter by name…">
|
|
||||||
<span class="meta" title="Built-in files ship with HeyStreamer (public/alerts) and are changed in the code. Uploads live only on the server and can be deleted here.">
|
|
||||||
<span class="pill">built-in</span> <span class="pill up">uploaded</span> <span class="pill used">used by N</span> ⓘ
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<% for (const g of groups) { %>
|
|
||||||
<h3 class="lib-h" data-group><%= g.name %> <span class="meta"><%= g.items.length %></span></h3>
|
|
||||||
<% if (!g.items.length) { %><p class="meta"><%= g.type === 'video' ? 'No videos yet: drop some above.' : 'Nothing here yet.' %></p><% } %>
|
|
||||||
<div class="grid">
|
|
||||||
<% for (const i of g.items) { %>
|
|
||||||
<div class="item" data-name="<%= (i.label + ' ' + i.file).toLowerCase() %>">
|
|
||||||
<div class="pv">
|
|
||||||
<% if (i.type === 'image') { %><img src="<%= i.url %>" alt="" loading="lazy">
|
|
||||||
<% } else if (i.type === 'video') { %><video src="<%= i.url %>#t=0.5" preload="metadata" muted playsinline data-hoverplay title="Hover to play (muted). Click for sound."></video>
|
|
||||||
<% } else { %><span style="font-size:2rem;">🔊</span><% } %>
|
|
||||||
</div>
|
|
||||||
<div class="name" title="<%= i.url %>"><%= i.label %></div>
|
|
||||||
<% if (i.type === 'audio') { %><audio controls preload="none" src="<%= i.url %>"></audio><% } %>
|
|
||||||
<div class="row">
|
|
||||||
<span class="pill <%= i.source === 'upload' ? 'up' : '' %>"><%= i.source === 'upload' ? 'uploaded' : 'built-in' %></span>
|
|
||||||
<% if (i.note) { %><span class="pill" title="Loudness-matched sound"><%= i.note %></span><% } %>
|
|
||||||
<% if (i.used) { %><span class="pill used" title="Used by <%= i.used %> redeem variation<%= i.used === 1 ? '' : 's' %>">used by <%= i.used %></span><% } %>
|
|
||||||
<span><%= i.size > 1048576 ? (i.size / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(i.size / 1024)) + ' KB' %></span>
|
|
||||||
<% if (i.source === 'upload') { %>
|
|
||||||
<form method="POST" action="/media/<%= i.id %>/delete">
|
|
||||||
<button type="button" data-confirm class="outline btn-sm" style="color:#f88; border-color:#f88;"
|
|
||||||
title="<%= i.used ? `Used by ${i.used} variation(s): they will play nothing until you pick another file` : 'Delete this upload' %>">Delete</button>
|
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<% if (files.length === 0) { %>
|
||||||
|
<p><em>No files uploaded yet.</em></p>
|
||||||
|
<% } else { %>
|
||||||
|
<figure>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Size</th>
|
||||||
|
<th>Uploaded</th>
|
||||||
|
<th>Preview</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% for (const f of files) { %>
|
||||||
|
<tr>
|
||||||
|
<td><%= f.original_name %></td>
|
||||||
|
<td><code><%= f.media_type %></code></td>
|
||||||
|
<td><%= (f.size_bytes / 1024).toFixed(0) %> KB</td>
|
||||||
|
<td><small><%= f.uploaded_at %></small></td>
|
||||||
|
<td>
|
||||||
|
<% if (f.media_type === 'audio') { %>
|
||||||
|
<audio controls src="/media/<%= f.filename %>" style="height:28px; width:160px;"></audio>
|
||||||
|
<% } else { %>
|
||||||
|
<video controls src="/media/<%= f.filename %>" style="height:40px; width:80px;"></video>
|
||||||
<% } %>
|
<% } %>
|
||||||
</div>
|
</td>
|
||||||
</div>
|
<td>
|
||||||
|
<form method="POST" action="/media/<%= f.id %>/delete" onsubmit="return confirm('Delete this file?')">
|
||||||
|
<button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem; color:#f88;">Delete</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
<% } %>
|
<% } %>
|
||||||
</div>
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</figure>
|
||||||
<% } %>
|
<% } %>
|
||||||
|
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
// upload: drag & drop or click, several files, progress bar, then reload the list
|
|
||||||
const drop = document.getElementById('drop'), input = document.getElementById('files');
|
|
||||||
const up = document.getElementById('up'), fill = document.getElementById('upfill'), msg = document.getElementById('upmsg');
|
|
||||||
drop.addEventListener('click', () => input.click());
|
|
||||||
['dragenter', 'dragover'].forEach(t => drop.addEventListener(t, e => { e.preventDefault(); drop.classList.add('over'); }));
|
|
||||||
['dragleave', 'drop'].forEach(t => drop.addEventListener(t, e => { e.preventDefault(); drop.classList.remove('over'); }));
|
|
||||||
drop.addEventListener('drop', e => send(e.dataTransfer.files));
|
|
||||||
input.addEventListener('change', () => send(input.files));
|
|
||||||
|
|
||||||
function send(files) {
|
|
||||||
if (!files || !files.length) return;
|
|
||||||
const fd = new FormData(); for (const f of files) fd.append('files', f);
|
|
||||||
const x = new XMLHttpRequest();
|
|
||||||
x.open('POST', '/media/upload'); x.setRequestHeader('Accept', 'application/json'); x.setRequestHeader('X-File-Count', files.length);
|
|
||||||
up.hidden = false; fill.style.width = '0'; msg.textContent = `Uploading ${files.length} file${files.length === 1 ? '' : 's'}…`;
|
|
||||||
x.upload.onprogress = e => { if (e.lengthComputable) fill.style.width = (100 * e.loaded / e.total) + '%'; };
|
|
||||||
x.onload = () => {
|
|
||||||
let j = {}; try { j = JSON.parse(x.responseText); } catch {}
|
|
||||||
if (x.status === 200 && j.ok) {
|
|
||||||
msg.textContent = `Uploaded ${j.saved}` + (j.skipped ? ` · skipped ${j.skipped} (not audio, video or image)` : '') + ' · refreshing…';
|
|
||||||
setTimeout(() => location.reload(), 600);
|
|
||||||
} else msg.textContent = 'Upload failed: ' + (j.error || x.status);
|
|
||||||
};
|
|
||||||
x.onerror = () => { msg.textContent = 'Upload failed (connection)'; };
|
|
||||||
x.send(fd);
|
|
||||||
}
|
|
||||||
|
|
||||||
// filter
|
|
||||||
document.getElementById('filter').addEventListener('input', e => {
|
|
||||||
const q = e.target.value.trim().toLowerCase();
|
|
||||||
document.querySelectorAll('.item').forEach(i => i.classList.toggle('hidden-by-filter', !!q && !i.dataset.name.includes(q)));
|
|
||||||
// hide sections with nothing left
|
|
||||||
document.querySelectorAll('h3[data-group]').forEach(h => {
|
|
||||||
const grid = h.nextElementSibling?.classList.contains('grid') ? h.nextElementSibling : h.nextElementSibling?.nextElementSibling;
|
|
||||||
const any = !!grid?.querySelector('.item:not(.hidden-by-filter)');
|
|
||||||
h.classList.toggle('hidden-by-filter', !!q && !any);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// videos: play muted on hover, with sound on click
|
|
||||||
document.querySelectorAll('[data-hoverplay]').forEach(v => {
|
|
||||||
v.addEventListener('mouseenter', () => { v.play().catch(() => {}); });
|
|
||||||
v.addEventListener('mouseleave', () => { v.pause(); v.currentTime = 0.5; v.muted = true; });
|
|
||||||
v.addEventListener('click', () => { v.muted = false; v.currentTime = 0; v.play().catch(() => {}); });
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
|
|
|
||||||
|
|
@ -2,39 +2,50 @@
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Caveat:wght@700&family=Nunito:wght@800;900&display=swap">
|
|
||||||
<% const has = p => parts.includes(p); %>
|
|
||||||
<% if (has('alerts')) { %>
|
|
||||||
<link rel="stylesheet" href="/alerts/card.css?v=<%= boot %>">
|
|
||||||
<link rel="stylesheet" href="/alerts/polaroid.css?v=<%= boot %>">
|
|
||||||
<link rel="stylesheet" href="/alerts/cassette.css?v=<%= boot %>">
|
|
||||||
<link rel="stylesheet" href="/alerts/fx.css?v=<%= boot %>">
|
|
||||||
<% } %>
|
|
||||||
<% if (has('chat')) { %><link rel="stylesheet" href="/chat/chat.css?v=<%= boot %>"><% } %>
|
|
||||||
<% if (has('poll')) { %><link rel="stylesheet" href="/alerts/poll.css?v=<%= boot %>"><% } %>
|
|
||||||
<% if (has('hypebar')) { %><link rel="stylesheet" href="/alerts/hypebar.css?v=<%= boot %>"><% } %>
|
|
||||||
<% if (has('raid')) { %><link rel="stylesheet" href="/alerts/raidcard.css?v=<%= boot %>"><% } %>
|
|
||||||
<% if (has('video')) { %><link rel="stylesheet" href="/alerts/video.css?v=<%= boot %>"><% } %>
|
|
||||||
<%# 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:
|
|
||||||
<link rel="stylesheet" href="/alerts/nowplaying.css"> (inside an if (has('nowplaying')))
|
|
||||||
<script src="/alerts/nowplaying.js"></script> (same)
|
|
||||||
the nowplaying line in ws.onmessage below %>
|
|
||||||
<style>
|
<style>
|
||||||
/* Legacy text/video action alerts. Values were taken from the layout editor (removed 2026-11-20);
|
|
||||||
change them here, or override with Custom CSS in Settings. The chat has its own /chat/chat.css. */
|
|
||||||
:root {
|
:root {
|
||||||
--chat-font-family: Inter, sans-serif;
|
--chat-left: <%= layout.chat_left %>%;
|
||||||
--alert-left: 50%;
|
--chat-top: <%= layout.chat_top %>%;
|
||||||
--alert-top: 40%;
|
--chat-width: <%= layout.chat_width %>%;
|
||||||
--alert-font-size: 32px;
|
--chat-height: <%= layout.chat_height %>%;
|
||||||
--alert-bg-opacity: 0.7;
|
--chat-font-size: <%= layout.chat_font_size %>px;
|
||||||
--alert-text-color: #ffffff;
|
--chat-font-family: <%= layout.chat_font_family %>;
|
||||||
|
--chat-bg-opacity: <%= layout.chat_bg_opacity %>;
|
||||||
|
--chat-text-color: <%= layout.chat_text_color %>;
|
||||||
|
--chat-border-radius: <%= layout.chat_border_radius %>px;
|
||||||
|
--alert-left: <%= layout.alert_left %>%;
|
||||||
|
--alert-top: <%= layout.alert_top %>%;
|
||||||
|
--alert-font-size: <%= layout.alert_font_size %>px;
|
||||||
|
--alert-bg-opacity: <%= layout.alert_bg_opacity %>;
|
||||||
|
--alert-text-color: <%= layout.alert_text_color %>;
|
||||||
}
|
}
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
body { background: transparent; overflow: hidden; width: 1920px; height: 1080px; }
|
body { background: transparent; overflow: hidden; width: 1920px; height: 1080px; }
|
||||||
|
|
||||||
|
#chat {
|
||||||
|
position: fixed;
|
||||||
|
left: var(--chat-left);
|
||||||
|
top: var(--chat-top);
|
||||||
|
width: var(--chat-width);
|
||||||
|
max-height: var(--chat-height);
|
||||||
|
overflow: hidden;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
font-family: var(--chat-font-family);
|
||||||
|
font-size: var(--chat-font-size);
|
||||||
|
color: var(--chat-text-color);
|
||||||
|
}
|
||||||
|
.chat-msg {
|
||||||
|
background: rgba(0, 0, 0, var(--chat-bg-opacity));
|
||||||
|
border-radius: var(--chat-border-radius);
|
||||||
|
padding: 5px 10px;
|
||||||
|
word-break: break-word;
|
||||||
|
animation: fadeIn 0.25s ease;
|
||||||
|
transition: opacity 0.5s ease;
|
||||||
|
}
|
||||||
|
.chat-msg .username { font-weight: 700; margin-right: 4px; }
|
||||||
|
|
||||||
#alert-box {
|
#alert-box {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
left: var(--alert-left);
|
left: var(--alert-left);
|
||||||
|
|
@ -67,36 +78,16 @@
|
||||||
|
|
||||||
<%- settings.custom_css %>
|
<%- settings.custom_css %>
|
||||||
</style>
|
</style>
|
||||||
<style>
|
|
||||||
/* HUDFX / Blerp pages (src/routers/ext.js). HUDFX's page is 2560x1440: scaled to this 1920x1080 page. */
|
|
||||||
.ext-frame { position:fixed; left:0; top:0; border:0; background:transparent; pointer-events:none; transform-origin:0 0; z-index:5; }
|
|
||||||
#ext-hudfx { width:2560px; height:1440px; transform:scale(.75); }
|
|
||||||
#ext-blerp { width:1920px; height:1080px; }
|
|
||||||
</style>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<% if (has('chat')) { %><div id="chat" class="<%= chatFlow %>"<% if (chatBox) { %> style="--chat-left:<%= chatBox.left %>px; --chat-top:<%= chatBox.top %>px; --chat-width:<%= chatBox.width %>px; --chat-height:<%= chatBox.height %>px;"<% } %>></div><% } %>
|
<div id="chat"></div>
|
||||||
<% if (has('alerts')) { %><div id="alert-box"></div>
|
<div id="alert-box"></div>
|
||||||
<video id="alert-video" autoplay></video><% } %>
|
<video id="alert-video" autoplay></video>
|
||||||
|
|
||||||
<script src="/vendor/tmi.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/tmi.js@1.8.5/build/tmi.min.js"></script>
|
||||||
<% if (has('chat')) { %><script src="/chat/chat.js?v=<%= boot %>"></script><% } %>
|
|
||||||
<% if (has('alerts')) { %>
|
|
||||||
<script src="/alerts/card.js?v=<%= boot %>"></script>
|
|
||||||
<script src="/alerts/cassette.js?v=<%= boot %>"></script>
|
|
||||||
<script src="/alerts/fx.js?v=<%= boot %>"></script>
|
|
||||||
<script src="/alerts/polaroid.js?v=<%= boot %>"></script>
|
|
||||||
<% } %>
|
|
||||||
<% if (has('poll')) { %><script src="/alerts/poll.js?v=<%= boot %>"></script><% } %>
|
|
||||||
<% if (has('hypebar')) { %><script src="/alerts/hypebar.js?v=<%= boot %>"></script><% } %>
|
|
||||||
<% if (has('raid')) { %><script src="/alerts/raidcard.js?v=<%= boot %>"></script><% } %>
|
|
||||||
<% if (has('video')) { %><script src="/alerts/video.js?v=<%= boot %>"></script><% } %>
|
|
||||||
<script>
|
<script>
|
||||||
const S = <%- JSON.stringify(settings) %>;
|
const S = <%- JSON.stringify(settings) %>;
|
||||||
window.S = S; // chat.js reads message_timeout / max_messages from here (settings_update keeps it current)
|
const chat = document.getElementById('chat');
|
||||||
// which parts this browser source shows (?parts=chat / ?parts=nochat / ?parts=chat,raid / nothing = all)
|
|
||||||
const PARTS = new Set(<%- JSON.stringify(parts) %>);
|
|
||||||
const chat = document.getElementById('chat'); // null when this source has no chat part
|
|
||||||
const alertBox = document.getElementById('alert-box');
|
const alertBox = document.getElementById('alert-box');
|
||||||
const alertVideo = document.getElementById('alert-video');
|
const alertVideo = document.getElementById('alert-video');
|
||||||
|
|
||||||
|
|
@ -107,89 +98,47 @@
|
||||||
const client = new tmi.Client({ channels: [S.channel] });
|
const client = new tmi.Client({ channels: [S.channel] });
|
||||||
client.connect().catch(console.error);
|
client.connect().catch(console.error);
|
||||||
|
|
||||||
// Watch streaks only exist as a chat USERNOTICE (msg-id=viewermilestone).
|
|
||||||
// Report them to the server, which logs them and sends the alert back to every overlay.
|
|
||||||
client.on('raw_message', (_copy, m) => {
|
|
||||||
const t = m.tags || {};
|
|
||||||
if (m.command !== 'USERNOTICE' || t['msg-id'] !== 'viewermilestone' || t['msg-param-category'] !== 'watch-streak') return;
|
|
||||||
sendUp({ type: 'chat_notice', kind: 'watch_streak', id: t.id,
|
|
||||||
user: t['display-name'] || t.login, streak: t['msg-param-value'] });
|
|
||||||
});
|
|
||||||
|
|
||||||
// channel id for the 7TV channel emotes, and moderation: deleted messages / timeouts / bans leave the screen
|
|
||||||
if (PARTS.has('chat')) {
|
|
||||||
client.on('roomstate', (_ch, state) => HSChat.setRoom(state['room-id']));
|
|
||||||
client.on('messagedeleted', (_ch, _user, _msg, tags) => HSChat.removeId(tags['target-msg-id']));
|
|
||||||
client.on('timeout', (_ch, user) => HSChat.removeUser(user));
|
|
||||||
client.on('ban', (_ch, user) => HSChat.removeUser(user));
|
|
||||||
client.on('clearchat', () => HSChat.clear());
|
|
||||||
}
|
|
||||||
|
|
||||||
client.on('message', (channel, tags, message) => {
|
client.on('message', (channel, tags, message) => {
|
||||||
if (!PARTS.has('chat')) return; // other sources only listen to chat for watch streaks
|
|
||||||
// Settings → Chat: hidden chatters (bots, alert services) and ! commands never reach the screen
|
|
||||||
const hidden = String(S.chat_hidden_users || '').toLowerCase().split(/[\s,]+/).filter(Boolean);
|
|
||||||
if (hidden.includes(String(tags.username || '').toLowerCase())) return;
|
|
||||||
if (S.chat_hide_commands && /^\s*!/.test(message)) return;
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const silence = (now - lastMsgTime) / 1000;
|
const silence = (now - lastMsgTime) / 1000;
|
||||||
|
|
||||||
console.log(`[gap] silence=${silence.toFixed(1)}s threshold=${S.gap_audio_min_silence}s enabled=${S.gap_audio_enabled} url=${!!S.gap_audio_url} lastMsg=${lastMsgTime>0}`);
|
|
||||||
if (S.gap_audio_enabled && S.gap_audio_url && lastMsgTime > 0 && silence >= S.gap_audio_min_silence) {
|
if (S.gap_audio_enabled && S.gap_audio_url && lastMsgTime > 0 && silence >= S.gap_audio_min_silence) {
|
||||||
const t = Math.min(
|
const t = Math.min(
|
||||||
(silence - S.gap_audio_min_silence) / Math.max(S.gap_audio_loud_after - S.gap_audio_min_silence, 1),
|
(silence - S.gap_audio_min_silence) / Math.max(S.gap_audio_loud_after - S.gap_audio_min_silence, 1),
|
||||||
1
|
1
|
||||||
);
|
);
|
||||||
const vol = S.gap_audio_min_volume + t * (S.gap_audio_max_volume - S.gap_audio_min_volume);
|
const vol = S.gap_audio_min_volume + t * (S.gap_audio_max_volume - S.gap_audio_min_volume);
|
||||||
console.log(`[gap] PLAY — t=${t.toFixed(2)} vol=${vol.toFixed(2)} min=${S.gap_audio_min_volume} max=${S.gap_audio_max_volume}`);
|
|
||||||
playAudio(S.gap_audio_url, vol);
|
playAudio(S.gap_audio_url, vol);
|
||||||
}
|
}
|
||||||
|
|
||||||
lastMsgTime = now;
|
lastMsgTime = now;
|
||||||
HSChat.add(tags, message, tags['message-type'] === 'action');
|
addMessage(tags['display-name'] || tags.username, tags.color || '#b4a0d4', message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Alert WebSocket ---
|
function addMessage(username, color, text) {
|
||||||
// ?overlay=<id> marks this page as the real overlay, so the server accepts chat_notice messages from it
|
const div = document.createElement('div');
|
||||||
let ws = null;
|
div.className = 'chat-msg';
|
||||||
const pending = [];
|
div.innerHTML = `<span class="username" style="color:${esc(color)}">${esc(username)}</span>: ${esc(text)}`;
|
||||||
function sendUp(obj) {
|
chat.appendChild(div);
|
||||||
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(obj));
|
|
||||||
else pending.push(obj);
|
while (chat.children.length > S.max_messages) chat.removeChild(chat.firstChild);
|
||||||
|
|
||||||
|
if (S.message_timeout > 0) {
|
||||||
|
setTimeout(() => {
|
||||||
|
div.style.opacity = '0';
|
||||||
|
setTimeout(() => div.remove(), 500);
|
||||||
|
}, S.message_timeout * 1000);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Alert WebSocket ---
|
||||||
function connectWS() {
|
function connectWS() {
|
||||||
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||||
ws = new WebSocket(`${proto}://${location.host}/ws/overlay?overlay=${encodeURIComponent(S.overlay_id)}`);
|
const ws = new WebSocket(`${proto}://${location.host}/ws/overlay`);
|
||||||
ws.onopen = () => { while (pending.length) ws.send(JSON.stringify(pending.shift())); };
|
|
||||||
|
|
||||||
ws.onmessage = (e) => {
|
ws.onmessage = (e) => {
|
||||||
const msg = JSON.parse(e.data);
|
const msg = JSON.parse(e.data);
|
||||||
// server restarted with (possibly) new code: reload this page so OBS runs the current alerts
|
|
||||||
if (msg.type === 'hello') { if (msg.boot !== '<%= boot %>') setTimeout(() => location.reload(), 1500); return; }
|
|
||||||
if (msg.type === 'settings_update') {
|
|
||||||
Object.assign(S, msg.settings);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// every source gets every message; each one only reacts to its own parts (so nothing plays twice)
|
|
||||||
if (msg.type === 'poll') { if (PARTS.has('poll')) PollCard.update(msg.phase, msg.poll); return; }
|
|
||||||
if (msg.type === 'hype_bar') { if (PARTS.has('hypebar')) HypeBar.update(msg.phase, msg.train); return; }
|
|
||||||
// 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(); if (PARTS.has('video')) VideoFX.skip(); return; }
|
|
||||||
// video redeems only play on the ?parts=video source
|
|
||||||
if (msg.type === 'alert' && msg.alert.style === 'video') {
|
|
||||||
if (PARTS.has('video')) msg.alert.test === true ? VideoFX.playTest(msg.alert) : VideoFX.play(msg.alert);
|
|
||||||
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
|
|
||||||
if (msg.alert.test === true) PolaroidAlerts.playTest(msg.alert);
|
|
||||||
else PolaroidAlerts.play(msg.alert);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }));
|
document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }));
|
||||||
handleAction(msg);
|
handleAction(msg);
|
||||||
};
|
};
|
||||||
|
|
@ -240,13 +189,5 @@
|
||||||
|
|
||||||
<%- settings.custom_js %>
|
<%- settings.custom_js %>
|
||||||
</script>
|
</script>
|
||||||
<% const extSrc = (n, v) => `/ext/${settings.overlay_id}/${n}?vol=${v}`; %>
|
|
||||||
<% if (ext.on.includes('hudfx')) { %>
|
|
||||||
<iframe id="ext-hudfx" class="ext-frame" src="<%= extSrc('hudfx', ext.hudfxVol) %>" allow="autoplay" scrolling="no"></iframe>
|
|
||||||
<% } %>
|
|
||||||
<% if (ext.on.includes('blerp')) { const b = ext.blerp; %>
|
|
||||||
<iframe id="ext-blerp" class="ext-frame" src="<%= extSrc('blerp', ext.blerpVol) %>" allow="autoplay" scrolling="no"
|
|
||||||
style="transform:translate(<%= b.cx - 960 * b.s %>px, <%= b.cy - 540 * b.s %>px) scale(<%= b.s %>)"></iframe>
|
|
||||||
<% } %>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
87
views/overlay_preview.ejs
Normal file
87
views/overlay_preview.ejs
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--chat-left: <%= layout.chat_left %>%;
|
||||||
|
--chat-top: <%= layout.chat_top %>%;
|
||||||
|
--chat-width: <%= layout.chat_width %>%;
|
||||||
|
--chat-height: <%= layout.chat_height %>%;
|
||||||
|
--chat-font-size: <%= layout.chat_font_size %>px;
|
||||||
|
--chat-font-family: <%= layout.chat_font_family %>;
|
||||||
|
--chat-bg-opacity: <%= layout.chat_bg_opacity %>;
|
||||||
|
--chat-text-color: <%= layout.chat_text_color %>;
|
||||||
|
--chat-border-radius: <%= layout.chat_border_radius %>px;
|
||||||
|
--alert-left: <%= layout.alert_left %>%;
|
||||||
|
--alert-top: <%= layout.alert_top %>%;
|
||||||
|
--alert-font-size: <%= layout.alert_font_size %>px;
|
||||||
|
--alert-bg-opacity: <%= layout.alert_bg_opacity %>;
|
||||||
|
--alert-text-color: <%= layout.alert_text_color %>;
|
||||||
|
}
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
body { background: rgba(30,30,30,0.6); overflow: hidden; width: 1920px; height: 1080px; }
|
||||||
|
|
||||||
|
#chat {
|
||||||
|
position: fixed;
|
||||||
|
left: var(--chat-left);
|
||||||
|
top: var(--chat-top);
|
||||||
|
width: var(--chat-width);
|
||||||
|
max-height: var(--chat-height);
|
||||||
|
overflow: hidden;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
font-family: var(--chat-font-family);
|
||||||
|
font-size: var(--chat-font-size);
|
||||||
|
color: var(--chat-text-color);
|
||||||
|
}
|
||||||
|
.chat-msg {
|
||||||
|
background: rgba(0, 0, 0, var(--chat-bg-opacity));
|
||||||
|
border-radius: var(--chat-border-radius);
|
||||||
|
padding: 5px 10px;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.chat-msg .username { font-weight: 700; margin-right: 4px; }
|
||||||
|
|
||||||
|
#alert-box {
|
||||||
|
position: fixed;
|
||||||
|
left: var(--alert-left);
|
||||||
|
top: var(--alert-top);
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
font-family: var(--chat-font-family);
|
||||||
|
font-size: var(--alert-font-size);
|
||||||
|
color: var(--alert-text-color);
|
||||||
|
background: rgba(0, 0, 0, var(--alert-bg-opacity));
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 16px 28px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-handle, #alert-handle {
|
||||||
|
position: fixed;
|
||||||
|
border: 2px dashed rgba(255,255,255,0.5);
|
||||||
|
cursor: move;
|
||||||
|
background: rgba(255,255,255,0.05);
|
||||||
|
}
|
||||||
|
#chat-handle {
|
||||||
|
left: var(--chat-left); top: var(--chat-top);
|
||||||
|
width: var(--chat-width); height: var(--chat-height);
|
||||||
|
}
|
||||||
|
#alert-handle {
|
||||||
|
left: calc(var(--alert-left) - 80px); top: calc(var(--alert-top) - 20px);
|
||||||
|
width: 160px; height: 40px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="chat">
|
||||||
|
<div class="chat-msg"><span class="username" style="color:#9146ff">channel</span>: This is a preview message</div>
|
||||||
|
<div class="chat-msg"><span class="username" style="color:#ff6b6b">someviewer</span>: Looking great!</div>
|
||||||
|
<div class="chat-msg"><span class="username" style="color:#6bcbff">anotheruser</span>: pog pog pog</div>
|
||||||
|
</div>
|
||||||
|
<div id="alert-box">Alert preview</div>
|
||||||
|
<div id="chat-handle" data-widget="chat"></div>
|
||||||
|
<div id="alert-handle" data-widget="alert"></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -1,72 +0,0 @@
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<title><%= displayName %> · Stream stats</title>
|
|
||||||
<meta name="description" content="Stream statistics for <%= displayName %> on Twitch: streams, chat, emotes, leaderboards.">
|
|
||||||
<%# viewer names are listed: keep the page out of search engines (remove this line to allow indexing) %>
|
|
||||||
<meta name="robots" content="noindex">
|
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Caveat:wght@700&family=Nunito:wght@400;600;700;800;900&display=swap">
|
|
||||||
<style>
|
|
||||||
/* paper look of the overlay alerts (polaroid / letter): cream paper, ink, red, lilac washi tape */
|
|
||||||
:root { --bg:#f3ece2; --paper:#fffdf7; --ink:#3a2a20; --muted:#8a7565; --line:#e4d9cb; --accent:#b74347; --accent-hover:#9a3539;
|
|
||||||
--card:var(--paper); --card-solid:var(--paper); --tape:rgba(201,182,228,.85); --link:#b74347; }
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
:root { --bg:#1d1916; --paper:#2a2420; --ink:#f1e7da; --muted:#b09d8b; --line:#3d342d; --accent:#d0626a; --accent-hover:#e07a82;
|
|
||||||
--card:var(--paper); --card-solid:var(--paper); --tape:rgba(155,130,195,.7); --link:#e58b91; }
|
|
||||||
}
|
|
||||||
* { box-sizing:border-box; }
|
|
||||||
html, body { margin:0; background:var(--bg); color:var(--ink); }
|
|
||||||
body { font:400 15px/1.45 'Nunito', system-ui, sans-serif; }
|
|
||||||
a { color:var(--link); }
|
|
||||||
.wrap { max-width:1100px; margin:0 auto; padding:24px 16px 48px; }
|
|
||||||
header.hero { position:relative; background:var(--paper); padding:22px 24px 18px; margin:14px 0 22px; box-shadow:0 10px 24px rgba(0,0,0,.12);
|
|
||||||
transform:rotate(-.4deg); display:flex; flex-wrap:wrap; align-items:center; gap:.5rem 1.2rem; }
|
|
||||||
header.hero:before, header.hero:after { content:''; position:absolute; top:-14px; width:120px; height:32px; background-color:var(--tape);
|
|
||||||
background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px); box-shadow:0 1px 2px rgba(0,0,0,.15); }
|
|
||||||
header.hero:before { left:-18px; transform:rotate(-8deg); }
|
|
||||||
header.hero:after { right:-18px; transform:rotate(7deg); }
|
|
||||||
header.hero h1 { font:700 46px/1 'Caveat', cursive; margin:0; }
|
|
||||||
header.hero h1 span { color:var(--accent); }
|
|
||||||
header.hero .sub { color:var(--muted); font-weight:600; }
|
|
||||||
.live { display:inline-flex; align-items:center; gap:.4rem; background:var(--accent); color:#fff; border-radius:99px; padding:.2rem .8rem;
|
|
||||||
font-weight:800; font-size:.85rem; text-decoration:none; margin-left:auto; }
|
|
||||||
.live:before { content:''; width:8px; height:8px; border-radius:50%; background:#fff; animation:blink 1.4s infinite; }
|
|
||||||
.watch { margin-left:auto; font-weight:700; text-decoration:none; }
|
|
||||||
@keyframes blink { 50% { opacity:.3; } }
|
|
||||||
.preview { background:#e6b800; color:#221a00; padding:.4rem .8rem; border-radius:8px; font-weight:700; font-size:.85rem; margin-bottom:.6rem; }
|
|
||||||
h3.sb-h { font:700 30px/1 'Caveat', cursive; margin:1.8rem 0 .7rem; }
|
|
||||||
.sb-tile .v { font-weight:900; }
|
|
||||||
.sb-board h4, .sb-chart h4 { font-weight:800; }
|
|
||||||
.sb-tabs a.on { color:#fff; }
|
|
||||||
code { font-family:ui-monospace, monospace; font-size:.9em; }
|
|
||||||
footer { margin-top:2.4rem; color:var(--muted); font-size:.85rem; border-top:1px dashed var(--line); padding-top:1rem; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="wrap">
|
|
||||||
<% if (preview) { %><div class="preview">Preview: the public page is off (Settings → Public stats page). Only you can see this.</div><% } %>
|
|
||||||
<header class="hero">
|
|
||||||
<h1><span><%= displayName %></span>'s stream stats</h1>
|
|
||||||
<span class="sub">the people who make the streams fun ♡</span>
|
|
||||||
<% if (live) { %>
|
|
||||||
<a class="live" href="https://twitch.tv/<%= encodeURIComponent(channel) %>" target="_blank" rel="noopener">live now</a>
|
|
||||||
<% } else if (channel) { %>
|
|
||||||
<a class="watch" href="https://twitch.tv/<%= encodeURIComponent(channel) %>" target="_blank" rel="noopener">twitch.tv/<%= channel %> ↗</a>
|
|
||||||
<% } %>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<%- include('_statsbody', { s, q, base: base || '/', viewerHref: null, mode: 'public', view, ranks, tz }) %>
|
|
||||||
|
|
||||||
<footer>
|
|
||||||
Chat activity and watch time are counted for these statistics; message text is never shown here.
|
|
||||||
Don't want your name on this page? Type <code>!hideme</code> in chat (you still count in the totals, unnamed);
|
|
||||||
<code>!showme</code> brings it back. To have your data deleted completely, ask in chat or whisper the streamer.
|
|
||||||
Days are UTC; numbers update every few minutes.
|
|
||||||
</footer>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
|
|
@ -1,405 +0,0 @@
|
||||||
<style>
|
|
||||||
/* save bar */
|
|
||||||
.savebar { position:sticky; top:0; z-index:20; display:flex; align-items:center; gap:.8rem; flex-wrap:wrap;
|
|
||||||
padding:.55rem .9rem; margin:0 0 1rem; border-radius:10px; background:var(--pico-card-background-color);
|
|
||||||
border:1px solid var(--pico-muted-border-color); box-shadow:0 4px 14px rgba(0,0,0,.25); }
|
|
||||||
.savebar .state { font-size:.9rem; }
|
|
||||||
.savebar .state.dirty { color:#e6b800; font-weight:600; }
|
|
||||||
.savebar .state.ok { color:#3fb950; }
|
|
||||||
.savebar .state.err { color:#f88; }
|
|
||||||
.savebar button { margin:0; width:auto; padding:.35rem 1.1rem; }
|
|
||||||
.savebar kbd { font-size:.7rem; }
|
|
||||||
.draftbar { display:flex; gap:.6rem; align-items:center; flex-wrap:wrap; padding:.5rem .9rem; margin:-.4rem 0 1rem;
|
|
||||||
border:1px dashed #e6b800; border-radius:10px; font-size:.9rem; }
|
|
||||||
.draftbar button { margin:0; width:auto; padding:.25rem .8rem; font-size:.85rem; }
|
|
||||||
|
|
||||||
/* triggers */
|
|
||||||
.group-h { margin:1.6rem 0 .6rem; }
|
|
||||||
.trig { border:1px solid var(--pico-muted-border-color); border-radius:12px; padding:.45rem .9rem; margin-bottom:.6rem; }
|
|
||||||
.trig[open] { padding-bottom:.8rem; }
|
|
||||||
.trig > summary { display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; cursor:pointer; }
|
|
||||||
.trig > summary img { width:24px; height:24px; border-radius:4px; }
|
|
||||||
.meta { color:var(--pico-muted-color); font-size:.85rem; }
|
|
||||||
.pill { font-size:.75rem; padding:.05rem .5rem; border-radius:99px; border:1px solid var(--pico-muted-border-color); color:var(--pico-muted-color); }
|
|
||||||
.pill.bits { border-color:#a970ff; color:#c9a8ff; }
|
|
||||||
.pill.pts { border-color:#3fb950; color:#7ee08f; }
|
|
||||||
.btn-sm { margin:0; padding:.25rem .7rem; font-size:.8rem; width:auto; }
|
|
||||||
.danger { color:#f88; border-color:#f88; }
|
|
||||||
.warn { color:#e6b800; }
|
|
||||||
|
|
||||||
/* variation cards */
|
|
||||||
.vcard { border:1px solid var(--pico-muted-border-color); border-left:4px solid var(--pico-muted-border-color);
|
|
||||||
border-radius:10px; padding:.6rem .8rem; margin:.6rem 0; }
|
|
||||||
.vcard.dirty { border-left-color:#e6b800; }
|
|
||||||
.vcard.off { opacity:.55; }
|
|
||||||
.vrow { display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; }
|
|
||||||
.vrow + .vrow { margin-top:.55rem; }
|
|
||||||
.vcard input, .vcard select { margin:0; padding:.3rem .5rem; font-size:.85rem; height:auto; }
|
|
||||||
.vcard input[type=checkbox] { margin:0; }
|
|
||||||
.vcard input[type=range] { padding:0; width:110px; }
|
|
||||||
.vname { flex:1 1 180px; font-weight:600; }
|
|
||||||
.chance { font-size:.8rem; color:var(--pico-muted-color); min-width:5.5em; }
|
|
||||||
.field { display:flex; align-items:center; gap:.4rem; }
|
|
||||||
.field > span:first-child { font-size:.75rem; color:var(--pico-muted-color); }
|
|
||||||
.grow { flex:1 1 220px; }
|
|
||||||
.grow > input, .grow > select { width:100%; }
|
|
||||||
.seg { display:inline-flex; border:1px solid var(--pico-muted-border-color); border-radius:8px; overflow:hidden; }
|
|
||||||
.seg label { margin:0; padding:.25rem .8rem; font-size:.8rem; cursor:pointer; user-select:none; }
|
|
||||||
.seg input { display:none; }
|
|
||||||
.seg label:has(input:checked) { background:var(--pico-primary-background); color:var(--pico-primary-inverse); }
|
|
||||||
.thumb { width:34px; height:34px; object-fit:contain; }
|
|
||||||
.vol-out { font-size:.75rem; color:var(--pico-muted-color); width:2.6em; }
|
|
||||||
.preview { margin-top:.5rem; max-width:320px; border-radius:8px; background:#0006; }
|
|
||||||
/* pickers: a pill with the current choice (click to change, x to clear) or "+ …"; typing filters */
|
|
||||||
.pick { position:relative; display:inline-flex; align-items:center; }
|
|
||||||
.chip { display:inline-flex; align-items:center; gap:.35rem; padding:.18rem .3rem .18rem .6rem; border-radius:99px; font-size:.82rem;
|
|
||||||
background:rgba(1,114,173,.18); border:1px solid rgba(1,114,173,.55); cursor:pointer; max-width:340px; }
|
|
||||||
.chip .lbl { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
||||||
.chip img { width:22px; height:22px; object-fit:contain; }
|
|
||||||
.chip .x { border:0; background:none; color:inherit; padding:0 .3rem; margin:0; width:auto; font-size:.95rem; line-height:1; opacity:.7; cursor:pointer; }
|
|
||||||
.chip .x:hover { opacity:1; }
|
|
||||||
.chip .tag { font-size:.65rem; opacity:.7; }
|
|
||||||
.chip.add { background:none; border-style:dashed; color:var(--pico-muted-color); padding-right:.6rem; }
|
|
||||||
.pick.disabled .chip { opacity:.45; }
|
|
||||||
.pick input.q { margin:0; padding:.25rem .6rem; font-size:.82rem; height:auto; width:260px; border-radius:99px; }
|
|
||||||
.pick ul.opts { position:absolute; top:100%; left:0; z-index:30; list-style:none; margin:.2rem 0 0; padding:.25rem; min-width:260px; max-height:260px; overflow:auto;
|
|
||||||
background:var(--pico-card-background-color); border:1px solid var(--pico-muted-border-color); border-radius:10px; box-shadow:0 8px 20px rgba(0,0,0,.4); }
|
|
||||||
.pick ul.opts li { list-style:none; padding:.25rem .5rem; border-radius:6px; font-size:.82rem; cursor:pointer; display:flex; align-items:center; gap:.4rem; }
|
|
||||||
.pick ul.opts li img { width:22px; height:22px; object-fit:contain; }
|
|
||||||
.pick ul.opts li .tag { margin-left:auto; font-size:.68rem; color:var(--pico-muted-color); }
|
|
||||||
.pick ul.opts li.on { background:rgba(1,114,173,.3); }
|
|
||||||
.pick ul.opts li.none { color:var(--pico-muted-color); cursor:default; }
|
|
||||||
[data-show] { display:none !important; }
|
|
||||||
.vcard[data-display="cassette"] [data-show~="cassette"],
|
|
||||||
.vcard[data-display="card"] [data-show~="cassette"],
|
|
||||||
.vcard[data-display="sound"] [data-show~="sound"],
|
|
||||||
.vcard[data-display="video"] [data-show~="video"] { display:flex !important; }
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<h2>Redeems</h2>
|
|
||||||
|
|
||||||
<div class="savebar">
|
|
||||||
<button type="button" id="save-all" title="Save every change on this page (Ctrl+S)">Save</button>
|
|
||||||
<span class="state ok" id="save-state">All saved</span>
|
|
||||||
<span class="meta" style="margin-left:auto;" title="Each redeem plays ONE of its enabled variations, picked at random by rarity (relative weights). Sounds: built-in library or uploads on the Media page. Videos: uploads on the Media page (transparent WebM looks best); they play on the overlay URL with ?parts=video.">
|
|
||||||
How it works ⓘ · <kbd>Ctrl</kbd>+<kbd>S</kbd> saves
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="draftbar" id="draftbar" hidden>
|
|
||||||
<span>Unsaved changes from <strong id="draft-when"></strong> were kept in this browser.</span>
|
|
||||||
<button type="button" id="draft-restore">Restore them</button>
|
|
||||||
<button type="button" class="outline" id="draft-discard">Discard</button>
|
|
||||||
</div>
|
|
||||||
<% if (!twitchOk) { %><p class="warn">Could not load your channel point rewards from Twitch right now, so only rewards that already have variations are listed.</p><% } %>
|
|
||||||
|
|
||||||
<% for (const g of groups) { %>
|
|
||||||
<h3 class="group-h" <%= g.id ? `id=${g.id}` : '' %>><%= g.name %></h3>
|
|
||||||
<% if (!g.items.length && g.empty) { %><p class="meta"><%= g.empty %></p><% } %>
|
|
||||||
<% for (const t of g.items) {
|
|
||||||
const on = t.variations.filter(v => v.enabled);
|
|
||||||
const anchor = `t-${t.kind}-${t.key}`; %>
|
|
||||||
<details class="trig" id="<%= anchor %>" data-trigger>
|
|
||||||
<summary>
|
|
||||||
<% if (t.image) { %><img src="<%= t.image %>" alt=""><% } %>
|
|
||||||
<strong><%= t.title %></strong>
|
|
||||||
<% if (t.cost != null) { %><span class="pill pts"><%= t.cost %> pts</span><% } %>
|
|
||||||
<% if (t.bits != null) { %><span class="pill bits"><%= t.bits %> bits</span><% } %>
|
|
||||||
<% if (t.missing) { %><span class="badge badge-red">not on Twitch anymore</span><% } %>
|
|
||||||
<% if (t.live === false) { %><span class="badge badge-grey">paused on Twitch</span><% } %>
|
|
||||||
<% if (t.variations.some(v => v.video)) { %><span class="pill" title="At least one variation plays a full-screen video (?parts=video overlay)">video</span><% } %>
|
|
||||||
<% if (t.variations.some(v => v.tts_voice_id)) { %><span class="pill" title="At least one variation reads the viewer's text aloud">TTS</span><% } %>
|
|
||||||
<span class="meta" data-count><%= t.variations.length ? `${on.length}/${t.variations.length} on` : 'no alert yet' %></span>
|
|
||||||
<% if (on.length) { %>
|
|
||||||
<button type="button" class="outline btn-sm" data-test-trigger data-kind="<%= t.kind %>" data-key="<%= t.key %>" title="Play a random enabled variation on the overlay (saves first)">Test random</button>
|
|
||||||
<% } %>
|
|
||||||
</summary>
|
|
||||||
|
|
||||||
<% for (const v of t.variations) {
|
|
||||||
const display = v.video ? 'video' : !v.polaroid ? 'sound' : v.look === 'card' ? 'card' : 'cassette'; %>
|
|
||||||
<div class="vcard<%= v.enabled ? '' : ' off' %>" data-id="<%= v.id %>" data-display="<%= display %>">
|
|
||||||
<div class="vrow">
|
|
||||||
<input type="checkbox" role="switch" data-f="enabled" <%= v.enabled ? 'checked' : '' %> title="On: this variation can play">
|
|
||||||
<input class="vname" data-f="name" value="<%= v.name %>" title="Variation name (shown on the cassette / video box)">
|
|
||||||
<select data-f="rarity" style="width:auto;" title="Rarity: how often it is picked compared to the other enabled variations">
|
|
||||||
<% for (const [k, r] of Object.entries(rarity)) { %><option value="<%= k %>" <%= v.rarity === k ? 'selected' : '' %>><%= r.label %></option><% } %>
|
|
||||||
</select>
|
|
||||||
<span class="chance" data-chance></span>
|
|
||||||
<button type="button" class="outline btn-sm" data-test title="Show it on the overlay (saves first)">Test</button>
|
|
||||||
<button type="button" class="outline btn-sm danger" data-del title="Delete this variation">Delete</button>
|
|
||||||
<button type="button" class="btn-sm danger" data-del-confirm hidden>Really delete</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="vrow">
|
|
||||||
<span class="seg" title="Card: plain alert card with sound. Cassette: tape alert with sound. Sound only: just the sound. Video: full-screen video on the ?parts=video overlay">
|
|
||||||
<% for (const [val, lbl] of [['card', 'Card'], ['cassette', 'Cassette'], ['sound', 'Sound only'], ['video', 'Video']]) { %>
|
|
||||||
<label><input type="radio" name="display-<%= v.id %>" data-f="display" value="<%= val %>" <%= display === val ? 'checked' : '' %>><%= lbl %></label>
|
|
||||||
<% } %>
|
|
||||||
</span>
|
|
||||||
<span class="field" title="Volume of the sound / video">
|
|
||||||
<input type="range" min="0" max="1" step="0.05" data-f="volume" value="<%= v.volume %>"><span class="vol-out" data-vol></span>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="vrow" data-show="cassette sound">
|
|
||||||
<input type="hidden" data-f="sound" value="<%= v.sound || '' %>">
|
|
||||||
<span class="pick" data-pick="sound" title="Sound that plays (TTS on: the voice replaces it)"></span>
|
|
||||||
<button type="button" class="outline btn-sm" data-play-sound title="Play the sound here in the browser">▶</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="vrow" data-show="cassette">
|
|
||||||
<input type="hidden" data-f="art" value="<%= v.art || '' %>">
|
|
||||||
<span class="pick" data-pick="art" title="Picture on the card / sticker in the cassette's corner"></span>
|
|
||||||
<span class="field grow"><input data-f="caption" value="<%= v.caption %>" title="Text after the viewer's name on the paper strip. {reward} = reward name, {variation} = this variation's name. The viewer's typed message is added automatically."></span>
|
|
||||||
<input type="hidden" data-f="tts_voice_id" value="<%= v.tts_voice_id || '' %>">
|
|
||||||
<span class="pick" data-pick="tts_voice_id" title="Read the viewer's typed text aloud (voice from the TTS page), shown as a big paper note. The voice replaces the sound. The reward needs 'Require Viewer to Enter Text' on Twitch."></span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="vrow" data-show="video">
|
|
||||||
<input type="hidden" data-f="video" value="<%= v.video || '' %>">
|
|
||||||
<span class="pick" data-pick="video" title="Video file: built-in or uploaded on the Media page (transparent WebM looks best)"></span>
|
|
||||||
<button type="button" class="outline btn-sm" data-play-video title="Preview the video here">▶</button>
|
|
||||||
<% if (!videos.length) { %><a href="/media" class="meta">upload a video on Media</a><% } %>
|
|
||||||
</div>
|
|
||||||
<video class="preview" data-preview hidden controls playsinline></video>
|
|
||||||
</div>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<form method="POST" action="/redeems/variation" data-add style="margin:.6rem 0 0;">
|
|
||||||
<input type="hidden" name="kind" value="<%= t.kind %>">
|
|
||||||
<input type="hidden" name="key" value="<%= t.key %>">
|
|
||||||
<input type="hidden" name="title" value="<%= t.title %>">
|
|
||||||
<button type="submit" class="outline btn-sm" title="Add a variation (saves your changes first)">+ Add variation</button>
|
|
||||||
</form>
|
|
||||||
</details>
|
|
||||||
<% } %>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
const RARITY = <%- JSON.stringify(rarity) %>;
|
|
||||||
// picker options (same files as the Media page)
|
|
||||||
const OPTS = {
|
|
||||||
sound: <%- JSON.stringify(sounds) %>,
|
|
||||||
video: <%- JSON.stringify(videos) %>,
|
|
||||||
art: <%- JSON.stringify(stickers) %>,
|
|
||||||
tts_voice_id: <%- JSON.stringify(ttsVoices.map(t => ({ url: String(t.id), label: t.name }))) %>,
|
|
||||||
};
|
|
||||||
const ADD = { sound: '+ sound', video: '+ video', art: '+ sticker', tts_voice_id: '+ TTS voice' };
|
|
||||||
const THEME_STICKER = <%- JSON.stringify(theme.defaultSticker || '') %>; // Actions → Alerts → Default redeem sticker
|
|
||||||
const DEFAULT_STICKER = { url: '', label: 'default picture', img: THEME_STICKER || '/alerts/art/placeholder.svg' };
|
|
||||||
const DRAFT_KEY = 'redeemsDraft', OPEN_KEY = 'redeemsOpen';
|
|
||||||
const stateEl = document.getElementById('save-state');
|
|
||||||
const dirty = new Set();
|
|
||||||
const cards = () => [...document.querySelectorAll('.vcard')];
|
|
||||||
const card = id => document.querySelector(`.vcard[data-id="${id}"]`);
|
|
||||||
const store = { get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } },
|
|
||||||
set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },
|
|
||||||
del(k) { try { localStorage.removeItem(k); } catch {} } };
|
|
||||||
|
|
||||||
function state(text, cls) { stateEl.textContent = text; stateEl.className = 'state ' + cls; }
|
|
||||||
function refreshState() { dirty.size ? state(`${dirty.size} unsaved change${dirty.size === 1 ? '' : 's'}`, 'dirty') : state('All saved', 'ok'); }
|
|
||||||
|
|
||||||
// read one card's values
|
|
||||||
function collect(c) {
|
|
||||||
const o = { id: c.dataset.id };
|
|
||||||
c.querySelectorAll('[data-f]').forEach(el => {
|
|
||||||
const f = el.dataset.f;
|
|
||||||
if (el.type === 'radio') { if (el.checked) o[f] = el.value; }
|
|
||||||
else if (el.type === 'checkbox') o[f] = el.checked;
|
|
||||||
else o[f] = el.value;
|
|
||||||
});
|
|
||||||
return o;
|
|
||||||
}
|
|
||||||
function apply(c, o) {
|
|
||||||
c.querySelectorAll('[data-f]').forEach(el => {
|
|
||||||
const f = el.dataset.f; if (!(f in o)) return;
|
|
||||||
if (el.type === 'radio') el.checked = el.value === o[f];
|
|
||||||
else if (el.type === 'checkbox') el.checked = !!o[f];
|
|
||||||
else el.value = o[f];
|
|
||||||
});
|
|
||||||
sync(c);
|
|
||||||
}
|
|
||||||
|
|
||||||
// card look: display mode, off, volume, sticker thumbnail; chances for the whole trigger
|
|
||||||
function sync(c) {
|
|
||||||
const o = collect(c);
|
|
||||||
c.dataset.display = o.display;
|
|
||||||
c.classList.toggle('off', !o.enabled);
|
|
||||||
c.querySelector('[data-vol]').textContent = Math.round(o.volume * 100) + '%';
|
|
||||||
const ttsOn = !!o.tts_voice_id && (o.display === 'cassette' || o.display === 'card');
|
|
||||||
c.querySelector('[data-pick="sound"]').classList.toggle('disabled', ttsOn);
|
|
||||||
c.querySelectorAll('[data-pick]').forEach(renderPick);
|
|
||||||
chances(c.closest('[data-trigger]'));
|
|
||||||
}
|
|
||||||
function chances(t) {
|
|
||||||
const cs = [...t.querySelectorAll('.vcard')].map(c => [c, collect(c)]);
|
|
||||||
const total = cs.filter(([, o]) => o.enabled).reduce((s, [, o]) => s + (RARITY[o.rarity]?.weight || 1), 0);
|
|
||||||
for (const [c, o] of cs) c.querySelector('[data-chance]').textContent = o.enabled && total ? Math.round(100 * (RARITY[o.rarity]?.weight || 1) / total) + '% chance' : 'off';
|
|
||||||
const n = cs.filter(([, o]) => o.enabled).length, el = t.querySelector('[data-count]');
|
|
||||||
if (el && cs.length) el.textContent = `${n}/${cs.length} on`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- pickers ---
|
|
||||||
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[ch]));
|
|
||||||
const field = el => el.closest('.vcard').querySelector(`[data-f="${el.dataset.pick}"]`);
|
|
||||||
function setVal(el, val) {
|
|
||||||
const h = field(el); h.value = val;
|
|
||||||
h.dispatchEvent(new Event('change', { bubbles: true })); // -> sync + unsaved change
|
|
||||||
}
|
|
||||||
function renderPick(el) {
|
|
||||||
if (el.querySelector('input.q')) return; // editing right now
|
|
||||||
const f = el.dataset.pick, val = field(el).value;
|
|
||||||
let o = OPTS[f].find(x => String(x.url) === String(val));
|
|
||||||
if (!o && val) o = { url: val, label: val.split('/').pop() + ' (missing)' };
|
|
||||||
if (!o && f === 'art') o = DEFAULT_STICKER;
|
|
||||||
if (!o) { el.innerHTML = `<span class="chip add" tabindex="0">${ADD[f]}</span>`; return; }
|
|
||||||
const img = f === 'art' ? `<img src="${esc(o.img || o.url)}" alt="">` : '';
|
|
||||||
const clear = val ? '<button type="button" class="x" title="Remove">×</button>' : '';
|
|
||||||
el.innerHTML = `<span class="chip" tabindex="0" title="Click to change">${img}<span class="lbl">${esc(o.label)}</span>${o.note ? `<span class="tag">${esc(o.note)}</span>` : ''}${clear}</span>`;
|
|
||||||
}
|
|
||||||
function openPick(el) {
|
|
||||||
if (el.querySelector('input.q')) return;
|
|
||||||
const f = el.dataset.pick, list = OPTS[f];
|
|
||||||
el.innerHTML = '<input class="q" placeholder="type to search…" autocomplete="off"><ul class="opts"></ul>';
|
|
||||||
const q = el.querySelector('input.q'), ul = el.querySelector('ul.opts');
|
|
||||||
let hits = [], at = 0;
|
|
||||||
const draw = () => {
|
|
||||||
const s = q.value.trim().toLowerCase();
|
|
||||||
hits = list.filter(o => !s || o.label.toLowerCase().includes(s) || String(o.url).toLowerCase().includes(s)).slice(0, 80);
|
|
||||||
at = Math.min(at, Math.max(0, hits.length - 1));
|
|
||||||
ul.innerHTML = hits.length ? hits.map((o, i) => `<li data-i="${i}" class="${i === at ? 'on' : ''}">${f === 'art' ? `<img src="${esc(o.url)}" alt="">` : ''}${esc(o.label)}${o.note ? `<span class="tag">${esc(o.note)}</span>` : ''}</li>`).join('')
|
|
||||||
: '<li class="none">nothing matches</li>';
|
|
||||||
ul.querySelector('li.on')?.scrollIntoView({ block: 'nearest' });
|
|
||||||
};
|
|
||||||
const close = () => { el.innerHTML = ''; renderPick(el); };
|
|
||||||
const choose = i => { const o = hits[i]; if (!o) return; el.innerHTML = ''; setVal(el, String(o.url)); renderPick(el); };
|
|
||||||
q.addEventListener('input', () => { at = 0; draw(); });
|
|
||||||
q.addEventListener('keydown', e => {
|
|
||||||
if (e.key === 'ArrowDown') { e.preventDefault(); at = Math.min(at + 1, hits.length - 1); draw(); }
|
|
||||||
else if (e.key === 'ArrowUp') { e.preventDefault(); at = Math.max(at - 1, 0); draw(); }
|
|
||||||
else if (e.key === 'Enter') { e.preventDefault(); choose(at); }
|
|
||||||
else if (e.key === 'Escape') { e.preventDefault(); close(); }
|
|
||||||
});
|
|
||||||
ul.addEventListener('mousedown', e => { const li = e.target.closest('li[data-i]'); if (li) { e.preventDefault(); choose(+li.dataset.i); } });
|
|
||||||
q.addEventListener('blur', () => setTimeout(() => { if (el.contains(q)) close(); }, 120));
|
|
||||||
draw(); q.focus();
|
|
||||||
}
|
|
||||||
document.addEventListener('click', e => {
|
|
||||||
const x = e.target.closest('.pick .x');
|
|
||||||
if (x) { e.stopPropagation(); const el = x.closest('.pick'); setVal(el, ''); renderPick(el); return; }
|
|
||||||
const chip = e.target.closest('.pick .chip');
|
|
||||||
if (chip) openPick(chip.closest('.pick'));
|
|
||||||
});
|
|
||||||
document.addEventListener('keydown', e => {
|
|
||||||
const chip = e.target.closest?.('.pick .chip');
|
|
||||||
if (chip && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); openPick(chip.closest('.pick')); }
|
|
||||||
});
|
|
||||||
|
|
||||||
function markDirty(c) {
|
|
||||||
dirty.add(c.dataset.id); c.classList.add('dirty');
|
|
||||||
const d = store.get(DRAFT_KEY) || { at: Date.now(), cards: {} };
|
|
||||||
d.at = Date.now(); d.cards[c.dataset.id] = collect(c); store.set(DRAFT_KEY, d);
|
|
||||||
refreshState();
|
|
||||||
}
|
|
||||||
|
|
||||||
cards().forEach(c => {
|
|
||||||
sync(c);
|
|
||||||
c.addEventListener('input', e => { if (e.target.dataset.f) { sync(c); markDirty(c); } });
|
|
||||||
c.addEventListener('change', e => { if (e.target.dataset.f) { sync(c); markDirty(c); } });
|
|
||||||
});
|
|
||||||
|
|
||||||
// --- save (button, Ctrl+S, and before anything that reloads the page) ---
|
|
||||||
let saving = null;
|
|
||||||
async function save() {
|
|
||||||
if (saving) return saving;
|
|
||||||
if (!dirty.size) return true;
|
|
||||||
const ids = [...dirty];
|
|
||||||
state('Saving…', 'dirty');
|
|
||||||
saving = (async () => {
|
|
||||||
try {
|
|
||||||
const r = await fetch('/redeems/save', { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ variations: ids.map(id => collect(card(id))) }) });
|
|
||||||
const j = await r.json().catch(() => ({}));
|
|
||||||
if (!r.ok || !j.ok) throw new Error(j.error || r.status);
|
|
||||||
ids.forEach(id => { dirty.delete(id); card(id)?.classList.remove('dirty'); });
|
|
||||||
if (!dirty.size) store.del(DRAFT_KEY);
|
|
||||||
state(`Saved ✓ ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`, 'ok');
|
|
||||||
return true;
|
|
||||||
} catch (e) { state('Save failed: ' + e.message + ' (your changes are kept)', 'err'); return false; }
|
|
||||||
finally { saving = null; }
|
|
||||||
})();
|
|
||||||
return saving;
|
|
||||||
}
|
|
||||||
document.getElementById('save-all').addEventListener('click', save);
|
|
||||||
document.addEventListener('keydown', e => {
|
|
||||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); save(); }
|
|
||||||
});
|
|
||||||
|
|
||||||
// add variation: save first, then the normal form post (reloads the page)
|
|
||||||
document.querySelectorAll('[data-add]').forEach(f => f.addEventListener('submit', async e => {
|
|
||||||
e.preventDefault(); if (await save()) { rememberOpen(f.closest('[data-trigger]').id, true); f.submit(); }
|
|
||||||
}));
|
|
||||||
|
|
||||||
// delete: two steps, no browser dialog; saves other changes first
|
|
||||||
document.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => {
|
|
||||||
const c = b.parentElement.querySelector('[data-del-confirm]');
|
|
||||||
b.hidden = true; c.hidden = false;
|
|
||||||
setTimeout(() => { b.hidden = false; c.hidden = true; }, 4000);
|
|
||||||
}));
|
|
||||||
document.querySelectorAll('[data-del-confirm]').forEach(b => b.addEventListener('click', async () => {
|
|
||||||
const c = b.closest('.vcard'); dirty.delete(c.dataset.id);
|
|
||||||
const d = store.get(DRAFT_KEY); if (d) { delete d.cards[c.dataset.id]; store.set(DRAFT_KEY, d); }
|
|
||||||
if (!(await save())) return;
|
|
||||||
const f = document.createElement('form'); f.method = 'POST'; f.action = `/redeems/variation/${c.dataset.id}/delete`;
|
|
||||||
document.body.appendChild(f); f.submit();
|
|
||||||
}));
|
|
||||||
|
|
||||||
// tests: save first so the overlay shows what you see
|
|
||||||
const post = async (url, body) => {
|
|
||||||
if (!(await save())) return;
|
|
||||||
try {
|
|
||||||
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
|
|
||||||
state(r.ok ? 'Sent to the overlay' : `Test failed (${r.status})`, r.ok ? 'ok' : 'err');
|
|
||||||
} catch (e) { state('Test failed: ' + e.message, 'err'); }
|
|
||||||
};
|
|
||||||
document.querySelectorAll('[data-test]').forEach(b => b.addEventListener('click', () => post(`/redeems/variation/${b.closest('.vcard').dataset.id}/test`)));
|
|
||||||
document.querySelectorAll('[data-test-trigger]').forEach(b => b.addEventListener('click', e => {
|
|
||||||
e.preventDefault(); post('/redeems/trigger/test', { kind: b.dataset.kind, key: b.dataset.key });
|
|
||||||
}));
|
|
||||||
|
|
||||||
// previews in the browser
|
|
||||||
let player = null;
|
|
||||||
document.querySelectorAll('[data-play-sound]').forEach(b => b.addEventListener('click', () => {
|
|
||||||
const c = b.closest('.vcard'), o = collect(c);
|
|
||||||
if (player) player.pause();
|
|
||||||
if (!o.sound) return state('No sound selected', 'err');
|
|
||||||
player = new Audio(o.sound); player.volume = parseFloat(o.volume) || 0.8;
|
|
||||||
player.play().catch(e => state('Could not play: ' + e.message, 'err'));
|
|
||||||
}));
|
|
||||||
document.querySelectorAll('[data-play-video]').forEach(b => b.addEventListener('click', () => {
|
|
||||||
const c = b.closest('.vcard'), o = collect(c), v = c.querySelector('[data-preview]');
|
|
||||||
if (!o.video) return state('No video selected', 'err');
|
|
||||||
if (!v.hidden && v.getAttribute('src') === o.video) { v.pause(); v.hidden = true; return; }
|
|
||||||
v.src = o.video; v.volume = parseFloat(o.volume) || 0.8; v.hidden = false; v.play().catch(() => {});
|
|
||||||
}));
|
|
||||||
|
|
||||||
// remember which triggers are open (survives the reload after add/delete)
|
|
||||||
function rememberOpen(id, open) { const s = new Set(store.get(OPEN_KEY) || []); open ? s.add(id) : s.delete(id); store.set(OPEN_KEY, [...s]); }
|
|
||||||
for (const id of store.get(OPEN_KEY) || []) { const d = document.getElementById(id); if (d) d.open = true; }
|
|
||||||
if (location.hash) { const d = document.getElementById(decodeURIComponent(location.hash.slice(1))); if (d) d.open = true; }
|
|
||||||
document.querySelectorAll('[data-trigger]').forEach(d => d.addEventListener('toggle', () => rememberOpen(d.id, d.open)));
|
|
||||||
|
|
||||||
// unsaved changes from a closed tab / crash: offer to restore (inline, no dialog)
|
|
||||||
const draft = store.get(DRAFT_KEY);
|
|
||||||
if (draft && draft.cards && Object.keys(draft.cards).some(id => card(id) && JSON.stringify(collect(card(id))) !== JSON.stringify(draft.cards[id]))) {
|
|
||||||
const bar = document.getElementById('draftbar');
|
|
||||||
document.getElementById('draft-when').textContent = new Date(draft.at).toLocaleString();
|
|
||||||
bar.hidden = false;
|
|
||||||
document.getElementById('draft-restore').onclick = () => {
|
|
||||||
for (const [id, o] of Object.entries(draft.cards)) { const c = card(id); if (c) { apply(c, o); markDirty(c); c.closest('[data-trigger]').open = true; } }
|
|
||||||
bar.hidden = true; state(`${dirty.size} restored change${dirty.size === 1 ? '' : 's'}: Save to keep them`, 'dirty');
|
|
||||||
};
|
|
||||||
document.getElementById('draft-discard').onclick = () => { store.del(DRAFT_KEY); bar.hidden = true; };
|
|
||||||
} else store.del(DRAFT_KEY);
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
79
views/settings.ejs
Normal file
79
views/settings.ejs
Normal file
|
|
@ -0,0 +1,79 @@
|
||||||
|
<h2>Settings</h2>
|
||||||
|
|
||||||
|
<article>
|
||||||
|
<header><strong>Overlay URL</strong></header>
|
||||||
|
<p>Add this as a <strong>Browser Source</strong> in OBS (1920×1080, transparent background):</p>
|
||||||
|
<code><%= baseUrl %>/overlay/<%= settings.overlay_id %></code>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<form method="POST" action="/settings">
|
||||||
|
|
||||||
|
<h3>Chat</h3>
|
||||||
|
<label>
|
||||||
|
Twitch channel
|
||||||
|
<input type="text" name="channel" value="<%= settings.channel %>" placeholder="yourchannel">
|
||||||
|
</label>
|
||||||
|
<div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
|
||||||
|
<label>
|
||||||
|
Message timeout (seconds)
|
||||||
|
<input type="number" name="message_timeout" value="<%= settings.message_timeout %>" min="0" max="600">
|
||||||
|
<small>0 = messages stay forever</small>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Max messages shown
|
||||||
|
<input type="number" name="max_messages" value="<%= settings.max_messages %>" min="1" max="100">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>Gap audio</h3>
|
||||||
|
<p><small>Plays a sound when a new message arrives after a period of silence.</small></p>
|
||||||
|
<label>
|
||||||
|
<input type="checkbox" name="gap_audio_enabled" role="switch" <%= settings.gap_audio_enabled ? 'checked' : '' %>>
|
||||||
|
Enable gap audio
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Sound URL
|
||||||
|
<input type="text" name="gap_audio_url" value="<%= settings.gap_audio_url %>" placeholder="https://... or /media/filename.mp3">
|
||||||
|
</label>
|
||||||
|
<div style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:1rem;">
|
||||||
|
<label>
|
||||||
|
Min silence before triggering (s)
|
||||||
|
<input type="number" name="gap_audio_min_silence" value="<%= settings.gap_audio_min_silence %>" min="0">
|
||||||
|
<small>Sound won't play if chat was more recent than this</small>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Min volume (0–1)
|
||||||
|
<input type="number" name="gap_audio_min_volume" value="<%= settings.gap_audio_min_volume %>" min="0" max="1" step="0.05">
|
||||||
|
<small>Volume right after min silence</small>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Max volume (0–1)
|
||||||
|
<input type="number" name="gap_audio_max_volume" value="<%= settings.gap_audio_max_volume %>" min="0" max="1" step="0.05">
|
||||||
|
<small>Volume after long silence</small>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label>
|
||||||
|
Full volume after silence of (seconds)
|
||||||
|
<input type="number" name="gap_audio_loud_after" value="<%= settings.gap_audio_loud_after %>" min="0">
|
||||||
|
<small>e.g. 3600 = 1 hour of silence → max volume</small>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<h3>Custom CSS / JS</h3>
|
||||||
|
<label>
|
||||||
|
Custom CSS (injected into the overlay)
|
||||||
|
<textarea name="custom_css" rows="6" style="font-family:monospace"><%= settings.custom_css %></textarea>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Custom JS (injected into the overlay, runs after init)
|
||||||
|
<textarea name="custom_js" rows="6" style="font-family:monospace"><%= settings.custom_js %></textarea>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<button type="submit">Save settings</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<hr>
|
||||||
|
<h3>EventSub</h3>
|
||||||
|
<form method="POST" action="/settings/reconnect" style="display:inline;">
|
||||||
|
<button type="submit" class="outline">Reconnect EventSub</button>
|
||||||
|
</form>
|
||||||
|
<small style="margin-left:1rem;">Use this if Twitch alerts stop working after a token refresh.</small>
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
<% if (locals.msg) { %><p class="flash"><%= msg %></p><% } %>
|
|
||||||
<% if (locals.err) { %><p class="flash err"><%= err %></p><% } %>
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
<h2 class="set-h">Advanced</h2>
|
|
||||||
<p class="set-intro">Extra CSS and JavaScript added to every overlay page.</p>
|
|
||||||
<%- include('_flash') %>
|
|
||||||
<form method="POST" action="/settings/advanced">
|
|
||||||
<div class="set-card">
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Custom CSS</div>
|
|
||||||
<textarea name="custom_css" rows="10" style="font-family:monospace"><%= settings.custom_css %></textarea>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Custom JS<small>Runs after the overlay starts.</small></div>
|
|
||||||
<textarea name="custom_js" rows="10" style="font-family:monospace"><%= settings.custom_js %></textarea>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="savebar-set"><button type="submit">Save</button></div>
|
|
||||||
</form>
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
<h2 class="set-h">Backup</h2>
|
|
||||||
<p class="set-intro">Your whole setup in one file: settings, alert theme, redeems and their variations, TTS voices. Not included: the media files themselves (keep a copy of your uploads), statistics, and secrets (Twitch login, StreamElements token).</p>
|
|
||||||
<%- include('_flash') %>
|
|
||||||
<div class="set-card">
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Export<small>Download a .json file.</small></div>
|
|
||||||
<div><a href="/settings/backup/export" role="button" class="btn-auto">Download backup</a></div>
|
|
||||||
</div>
|
|
||||||
<form method="POST" action="/settings/backup/import" enctype="multipart/form-data" class="set-row">
|
|
||||||
<div class="lbl">Import<small>Replaces the current settings, theme, redeems and TTS voices with the ones in the file. Statistics stay.</small></div>
|
|
||||||
<div class="set-inline">
|
|
||||||
<input type="file" name="file" accept=".json,application/json" required>
|
|
||||||
<button type="submit" class="outline btn-auto" data-confirm="Really replace everything?">Import and replace</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
<h2 class="set-h">Chat</h2>
|
|
||||||
<p class="set-intro">The chat shown on the overlay (OBS source with the chat part).</p>
|
|
||||||
<%- include('_flash') %>
|
|
||||||
<form method="POST" action="/settings/chat">
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Messages</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Message timeout<small>Seconds a message stays. 0 = forever.</small></div>
|
|
||||||
<input type="number" name="message_timeout" value="<%= settings.message_timeout %>" min="0" max="600" style="max-width:8rem;">
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Max messages shown</div>
|
|
||||||
<input type="number" name="max_messages" value="<%= settings.max_messages %>" min="1" max="100" style="max-width:8rem;">
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Hidden chatters<small>Bots and alert services: never shown in the on-screen chat and left out of the statistics. Twitch logins, commas or spaces.</small></div>
|
|
||||||
<input type="text" name="chat_hidden_users" value="<%= settings.chat_hidden_users || '' %>" placeholder="streamelements, nightbot, …">
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Hide ! commands<small>!discord, !lurk … are not shown. Add the bot to Hidden chatters to hide its answer too.</small></div>
|
|
||||||
<label><input type="checkbox" name="chat_hide_commands" role="switch" <%= settings.chat_hide_commands ? 'checked' : '' %>></label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Gap sound</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Play a sound after silence<small>When a message arrives after chat was quiet for a while.</small></div>
|
|
||||||
<label><input type="checkbox" name="gap_audio_enabled" role="switch" <%= settings.gap_audio_enabled ? 'checked' : '' %>></label>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Sound<small>From your <a href="/media">Media</a> library (upload new sounds there).</small></div>
|
|
||||||
<div class="set-inline">
|
|
||||||
<select name="gap_audio_url" id="gap-sound" style="flex:1; min-width:220px;">
|
|
||||||
<option value="">— none —</option>
|
|
||||||
<% for (const m of sounds) { %><option value="<%= m.url %>" <%= m.url === settings.gap_audio_url ? 'selected' : '' %>><%= m.label %></option><% } %>
|
|
||||||
<% if (settings.gap_audio_url && !sounds.some(m => m.url === settings.gap_audio_url)) { %><option value="<%= settings.gap_audio_url %>" selected>link: <%= settings.gap_audio_url.split('/').pop() %></option><% } %>
|
|
||||||
</select>
|
|
||||||
<button type="button" class="outline btn-auto" id="gap-play" title="Play">▶</button>
|
|
||||||
</div>
|
|
||||||
<script>
|
|
||||||
document.getElementById('gap-play').addEventListener('click', () => {
|
|
||||||
const u = document.getElementById('gap-sound').value;
|
|
||||||
if (u) { const a = new Audio(u); a.volume = parseFloat(document.querySelector('[name=gap_audio_max_volume]').value) || 1; a.play(); }
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Quiet for at least<small>Seconds of silence before the sound plays.</small></div>
|
|
||||||
<input type="number" name="gap_audio_min_silence" value="<%= settings.gap_audio_min_silence %>" min="0" style="max-width:8rem;">
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Volume<small>Quiet right after the minimum silence, louder the longer chat was quiet.</small></div>
|
|
||||||
<div class="set-inline">
|
|
||||||
<label>from <input type="number" name="gap_audio_min_volume" value="<%= settings.gap_audio_min_volume %>" min="0" max="1" step="0.05" style="max-width:6rem;"></label>
|
|
||||||
<label>to <input type="number" name="gap_audio_max_volume" value="<%= settings.gap_audio_max_volume %>" min="0" max="1" step="0.05" style="max-width:6rem;"></label>
|
|
||||||
<label>full after <input type="number" name="gap_audio_loud_after" value="<%= settings.gap_audio_loud_after %>" min="0" style="max-width:7rem;"> s</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="savebar-set"><button type="submit">Save</button></div>
|
|
||||||
</form>
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
<h2 class="set-h">Connections</h2>
|
|
||||||
<p class="set-intro">Services HeyStreamer talks to.</p>
|
|
||||||
<%- include('_flash') %>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Twitch</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Account</div>
|
|
||||||
<div><%= user ? (user.display_name || user.login) : 'not logged in' %></div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Events (EventSub)<small>Follows, subs, bits, rewards, raids, chat, stream on / off.</small></div>
|
|
||||||
<div>
|
|
||||||
<% if (eventsub.connected) { %><span class="badge badge-green">connected</span>
|
|
||||||
<% } else if (eventsub.running) { %><span class="badge badge-grey">connecting…</span>
|
|
||||||
<% } else { %><span class="badge badge-red">not running</span><% } %>
|
|
||||||
<% if (eventsub.lastEventAt) { %> <small>last event <%= eventsub.lastEventAt.slice(0, 16).replace('T', ' ') %> UTC</small><% } %>
|
|
||||||
<% if (eventsub.failed.length) { %><p><small style="color:#f88">Not allowed: <%= eventsub.failed.join(', ') %>. Log in again to give HeyStreamer the missing permission.</small></p><% } %>
|
|
||||||
<% if (eventsub.subscribed.length) { %><details style="margin:.4rem 0 0;"><summary><small>Listening to <%= eventsub.subscribed.length %> events</small></summary><small><%= eventsub.subscribed.join(', ') %></small></details><% } %>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Fix it<small>Log in again after new features ask for more permissions, or reconnect if alerts stop.</small></div>
|
|
||||||
<div class="set-inline">
|
|
||||||
<a href="/auth/twitch" role="button" class="btn-auto">Log in again with Twitch</a>
|
|
||||||
<form method="POST" action="/settings/connections/reconnect"><button type="submit" class="outline btn-auto">Reconnect</button></form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>StreamElements tips</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Status</div>
|
|
||||||
<div>
|
|
||||||
<% if (!se.enabled) { %><span class="badge badge-grey">off</span> <small>no token</small>
|
|
||||||
<% } else if (se.subscribed) { %><span class="badge badge-green">connected</span><% if (se.lastTipAt) { %> <small>last tip <%= se.lastTipAt %></small><% } %>
|
|
||||||
<% } else { %><span class="badge badge-grey">connecting…</span><% } %>
|
|
||||||
<% if (se.error) { %><br><small style="color:#f88"><%= se.error %></small><% } %>
|
|
||||||
<% if (se.source === 'env') { %><br><small>Token comes from <code>.env</code> (SE_JWT). Saving one here replaces it.</small><% } %>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<form method="POST" action="/settings/connections/se" class="set-row">
|
|
||||||
<div class="lbl">JWT token<small>StreamElements → your avatar → Channel settings → Show secrets → JWT Token. Kept secret: it is never shown again here.</small></div>
|
|
||||||
<div class="set-inline">
|
|
||||||
<input type="password" id="se-jwt" name="se_jwt" autocomplete="off" placeholder="<%= settings.se_jwt ? '•••••••• (saved: paste a new one to replace it)' : 'paste the JWT token' %>" style="flex:1; min-width:220px;">
|
|
||||||
<button type="button" class="outline eye" data-reveal="#se-jwt" title="Show what you typed">👁</button>
|
|
||||||
<button type="submit" class="btn-auto">Save and connect</button>
|
|
||||||
<% if (settings.se_jwt) { %><button type="submit" name="clear" value="1" class="outline btn-auto" data-confirm="Really remove?">Remove token</button><% } %>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form method="POST" action="/settings/hudfx" class="set-card">
|
|
||||||
<h3>HUDFX</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">HUDFX overlay URL<small>Then add <code>&ext=hudfx</code> to an OBS source link: HUDFX effects play inside that overlay. Empty = off.</small></div>
|
|
||||||
<div class="set-inline">
|
|
||||||
<input type="password" id="hudfx-url" name="hudfx_overlay_url" value="<%= settings.hudfx_overlay_url || '' %>" placeholder="https://overlays.hudfx.io/overlay/…" autocomplete="off" style="flex:1; min-width:220px;">
|
|
||||||
<button type="button" class="outline eye" data-reveal="#hudfx-url" title="Show">👁</button>
|
|
||||||
<button type="submit" class="btn-auto">Save</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
<h2 class="set-h">General</h2>
|
|
||||||
<p class="set-intro">Basics about your channel.</p>
|
|
||||||
<%- include('_flash') %>
|
|
||||||
<form method="POST" action="/settings/general">
|
|
||||||
<div class="set-card">
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Twitch channel<small>The chat shown on the overlay. Usually your own channel name.</small></div>
|
|
||||||
<input type="text" name="channel" value="<%= settings.channel || '' %>" placeholder="yourchannel" required pattern="#?[A-Za-z0-9_]{2,25}">
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Time zone<small>Used for times and days on the stats pages.</small></div>
|
|
||||||
<div>
|
|
||||||
<input type="text" name="timezone" value="<%= settings.timezone || 'UTC' %>" list="tz-list" placeholder="Europe/London">
|
|
||||||
<datalist id="tz-list">
|
|
||||||
<% let zones = []; try { zones = Intl.supportedValuesOf('timeZone'); } catch {} %>
|
|
||||||
<% for (const z of zones) { %><option value="<%= z %>"><% } %>
|
|
||||||
</datalist>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="savebar-set"><button type="submit">Save</button></div>
|
|
||||||
</form>
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
<h2 class="set-h">OBS sources</h2>
|
|
||||||
<p class="set-intro">The links are hidden (anyone with one can open your overlay): 👁 shows one, Copy copies it either way. Add them as <strong>Browser Source</strong> in OBS (1920 × 1080, transparent). Pick what one source shows, then copy its link.</p>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Ready-made links</h3>
|
|
||||||
<% const links = [
|
|
||||||
['Everything except chat', '?parts=nochat', 'Alerts, redeems, poll, Hype Train bar, raid send-off.'],
|
|
||||||
['Chat only', '?parts=chat', 'Set its audio to “Monitor Only (mute output)” so chat sounds stay off stream.'],
|
|
||||||
['Full-screen videos', '?parts=video', 'Video redeems / Power-ups. 2560 × 1440 source looks sharpest.'],
|
|
||||||
['Everything in one source', '', 'Simplest, but chat and alert sounds share one fader.'],
|
|
||||||
]; %>
|
|
||||||
<% links.forEach(([title, q, hint], i) => { %>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl"><%= title %><small><%= hint %></small></div>
|
|
||||||
<div class="copy"><code id="obs-<%= i %>" class="secret"><%= overlayUrl + q %></code><button type="button" class="outline eye" data-reveal="#obs-<%= i %>" title="Show">👁</button><button type="button" class="outline" data-copy-from="#obs-<%= i %>">Copy</button></div>
|
|
||||||
</div>
|
|
||||||
<% }) %>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Build your own</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Parts</div>
|
|
||||||
<div class="set-inline" id="obs-parts">
|
|
||||||
<% for (const [p, l] of [['alerts', 'Alerts and redeems'], ['chat', 'Chat'], ['poll', 'Poll'], ['hypebar', 'Hype Train bar'], ['raid', 'Raid send-off'], ['video', 'Videos']]) { %>
|
|
||||||
<label><input type="checkbox" value="<%= p %>" <%= p !== 'video' ? 'checked' : '' %>> <%= l %></label>
|
|
||||||
<% } %>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Chat box<small>Optional: left, top, width, height in px of the 1920 × 1080 page. Empty = default place.</small></div>
|
|
||||||
<div class="set-inline">
|
|
||||||
<input type="text" id="obs-box" placeholder="130,640,700,360" style="max-width:12rem;">
|
|
||||||
<label><input type="checkbox" id="obs-up"> newest at the bottom</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Extras</div>
|
|
||||||
<div class="set-inline"><label title="Needs the HUDFX URL in Settings → Connections"><input type="checkbox" id="obs-hudfx"> HUDFX effects</label></div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Link</div>
|
|
||||||
<div class="copy"><code id="obs-built" class="secret"></code><button type="button" class="outline eye" data-reveal="#obs-built" title="Show">👁</button><button type="button" class="outline" data-copy-from="#obs-built">Copy</button></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<script>
|
|
||||||
(() => {
|
|
||||||
const base = <%- JSON.stringify(overlayUrl) %>;
|
|
||||||
const all = ['alerts', 'chat', 'poll', 'hypebar', 'raid'];
|
|
||||||
const build = () => {
|
|
||||||
const picked = [...document.querySelectorAll('#obs-parts input:checked')].map(i => i.value);
|
|
||||||
const std = picked.filter(p => p !== 'video');
|
|
||||||
const q = [];
|
|
||||||
if (!(std.length === all.length && !picked.includes('video'))) q.push('parts=' + picked.join(','));
|
|
||||||
const box = document.getElementById('obs-box').value.trim();
|
|
||||||
if (picked.includes('chat') && /^\d+,\d+,\d+,\d+$/.test(box)) q.push('chat=' + box);
|
|
||||||
if (picked.includes('chat') && document.getElementById('obs-up').checked) q.push('chatflow=up');
|
|
||||||
if (document.getElementById('obs-hudfx').checked) q.push('ext=hudfx');
|
|
||||||
document.getElementById('obs-built').textContent = base + (q.length ? '?' + q.join('&') : '');
|
|
||||||
};
|
|
||||||
document.querySelectorAll('#obs-parts input, #obs-box, #obs-up, #obs-hudfx').forEach(i => i.addEventListener('input', build));
|
|
||||||
build();
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
<h2 class="set-h">Stats and data</h2>
|
|
||||||
<p class="set-intro">The public stats page, and data copied from Twitch.</p>
|
|
||||||
<%- include('_flash') %>
|
|
||||||
<form method="POST" action="/settings/stats" class="set-card">
|
|
||||||
<h3>Public stats page</h3>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Public page on<small>Off: it answers “not found” for everyone except you (preview below). Never shows message text, bots, or viewers who typed !hideme.</small></div>
|
|
||||||
<label><input type="checkbox" name="public_stats_enabled" role="switch" <%= settings.public_stats_enabled ? 'checked' : '' %>></label>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Host name<small>Its own address. Needs a DNS record to this server, a certificate, and the web server sending it to HeyStreamer. On that host only the public page answers.</small></div>
|
|
||||||
<input type="text" name="public_stats_host" value="<%= settings.public_stats_host || '' %>" placeholder="stats.example.com">
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl"></div>
|
|
||||||
<div class="set-inline"><button type="submit" class="btn-auto">Save</button><a href="/public" target="_blank" rel="noopener">Preview ↗</a></div>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<div class="set-card">
|
|
||||||
<h3>Twitch</h3>
|
|
||||||
<% const bad = Object.entries(sync.parts || {}).filter(([, v]) => !String(v).startsWith('ok')); %>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Sync with Twitch<small>Followers with follow dates, current subs, mods, VIPs, all-time bits, your emotes, past streams (VODs). Runs every 6 hours and after each stream.</small></div>
|
|
||||||
<div>
|
|
||||||
<form method="POST" action="/stats/sync?back=settings" class="set-inline"><button type="submit" class="outline btn-auto">Sync now</button>
|
|
||||||
<small><%= sync.at ? `last ${sync.at.slice(0, 16).replace('T', ' ')} UTC` : 'never' %></small></form>
|
|
||||||
<% if (sync.at) { %><small><% for (const [k, v] of Object.entries(sync.parts || {})) { %><%= k %>: <span style="<%= String(v).startsWith('ok') ? '' : 'color:#f88' %>"><%= v %></span> · <% } %></small><% } %>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Twitch analytics (CSV)<small>Creator Dashboard → Analytics → export “Analytics and Revenue by day”. Fills in your history before HeyStreamer, and numbers only Twitch has. Importing again only updates days. Revenue is never public.</small></div>
|
|
||||||
<form method="POST" action="/stats/import-twitch?back=settings" enctype="multipart/form-data" class="set-inline">
|
|
||||||
<label role="button" class="outline btn-auto">Choose CSV files…<input type="file" name="files" accept=".csv,text/csv" multiple hidden onchange="this.form.requestSubmit()"></label>
|
|
||||||
<small><%= csv.days ? `${csv.days} days imported (${csv.from_day} – ${csv.to_day})` : 'none imported yet' %></small>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
<h2 class="set-h">Text to speech</h2>
|
|
||||||
<p class="set-intro">For redeem variations with a TTS voice (set on Actions → Redeems; voices are made on Actions → TTS voices).</p>
|
|
||||||
<%- include('_flash') %>
|
|
||||||
<form method="POST" action="/settings/tts">
|
|
||||||
<div class="set-card">
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Max length<small>Characters. Longer messages are cut at a word.</small></div>
|
|
||||||
<input type="number" name="tts_max_chars" value="<%= settings.tts_max_chars %>" min="20" max="500" style="max-width:8rem;">
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Say the name first<small>“ChickenWhisperer says: …”</small></div>
|
|
||||||
<label><input type="checkbox" name="tts_say_name" role="switch" <%= settings.tts_say_name ? 'checked' : '' %>></label>
|
|
||||||
</div>
|
|
||||||
<div class="set-row">
|
|
||||||
<div class="lbl">Blocked words<small>One per line or comma-separated. A message containing one is not read (“message removed”). Whole words, not case-sensitive, plurals and swaps like 0→o, $→s, k y s included. Links are always removed.</small></div>
|
|
||||||
<textarea name="tts_blocklist" rows="10"><%= settings.tts_blocklist %></textarea>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="savebar-set"><button type="submit">Save</button></div>
|
|
||||||
</form>
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue