From f07489750cc3942df8c8a4b45ce04e080a71d283 Mon Sep 17 00:00:00 2001 From: Bashy Date: Sun, 26 Apr 2026 23:00:55 +0300 Subject: [PATCH] rework --- .env.example | 11 +- .github/workflows/ci.yml | 36 +- CLAUDE.md | 224 +++- INSTRUCTIONS.md | 274 ---- README.md | 78 -- SPEC.md | 95 -- app/__init__.py | 0 app/auth.py | 64 - app/cooldowns.py | 15 - app/database.py | 48 - app/dispatch.py | 109 -- app/eventsub.py | 141 -- app/main.py | 60 - app/models.py | 79 -- app/routers/__init__.py | 0 app/routers/actions.py | 140 -- app/routers/auth.py | 75 -- app/routers/dashboard.py | 28 - app/routers/layout.py | 91 -- app/routers/media.py | 79 -- app/routers/overlay.py | 57 - app/routers/settings.py | 64 - app/templates.py | 3 - app/ws.py | 28 - deploy.sh | 89 +- package-lock.json | 1981 ++++++++++++++++++++++++++++ package.json | 24 + {static => public}/media/.gitkeep | 0 requirements.txt | 9 - src/app.js | 58 + src/cooldowns.js | 18 + src/db.js | 252 ++++ src/dispatch.js | 37 + src/eventsub.js | 118 ++ src/routers/actions.js | 45 + src/routers/auth.js | 101 ++ src/routers/dashboard.js | 11 + src/routers/layout.js | 29 + src/routers/media.js | 42 + src/routers/overlay.js | 18 + src/routers/settings.js | 40 + src/server.js | 21 + src/ws.js | 26 + static/overlay.css | 74 -- static/style.css | 87 -- templates/actions.html | 71 - templates/base.html | 31 - templates/dashboard.html | 50 - templates/layout.html | 200 --- templates/login.html | 19 - templates/media.html | 35 - templates/overlay.html | 162 --- templates/overlay_preview.html | 54 - templates/partials/action_row.html | 42 - templates/partials/media_item.html | 18 - templates/settings.html | 65 - views/actions.ejs | 88 ++ views/dashboard.ejs | 46 + views/layout.ejs | 38 + views/layout_editor.ejs | 91 ++ views/login.ejs | 33 + views/media.ejs | 53 + views/overlay.ejs | 193 +++ views/overlay_preview.ejs | 87 ++ views/settings.ejs | 79 ++ 65 files changed, 3727 insertions(+), 2607 deletions(-) delete mode 100644 INSTRUCTIONS.md delete mode 100644 README.md delete mode 100644 SPEC.md delete mode 100644 app/__init__.py delete mode 100644 app/auth.py delete mode 100644 app/cooldowns.py delete mode 100644 app/database.py delete mode 100644 app/dispatch.py delete mode 100644 app/eventsub.py delete mode 100644 app/main.py delete mode 100644 app/models.py delete mode 100644 app/routers/__init__.py delete mode 100644 app/routers/actions.py delete mode 100644 app/routers/auth.py delete mode 100644 app/routers/dashboard.py delete mode 100644 app/routers/layout.py delete mode 100644 app/routers/media.py delete mode 100644 app/routers/overlay.py delete mode 100644 app/routers/settings.py delete mode 100644 app/templates.py delete mode 100644 app/ws.py create mode 100644 package-lock.json create mode 100644 package.json rename {static => public}/media/.gitkeep (100%) delete mode 100644 requirements.txt create mode 100644 src/app.js create mode 100644 src/cooldowns.js create mode 100644 src/db.js create mode 100644 src/dispatch.js create mode 100644 src/eventsub.js create mode 100644 src/routers/actions.js create mode 100644 src/routers/auth.js create mode 100644 src/routers/dashboard.js create mode 100644 src/routers/layout.js create mode 100644 src/routers/media.js create mode 100644 src/routers/overlay.js create mode 100644 src/routers/settings.js create mode 100644 src/server.js create mode 100644 src/ws.js delete mode 100644 static/overlay.css delete mode 100644 static/style.css delete mode 100644 templates/actions.html delete mode 100644 templates/base.html delete mode 100644 templates/dashboard.html delete mode 100644 templates/layout.html delete mode 100644 templates/login.html delete mode 100644 templates/media.html delete mode 100644 templates/overlay.html delete mode 100644 templates/overlay_preview.html delete mode 100644 templates/partials/action_row.html delete mode 100644 templates/partials/media_item.html delete mode 100644 templates/settings.html create mode 100644 views/actions.ejs create mode 100644 views/dashboard.ejs create mode 100644 views/layout.ejs create mode 100644 views/layout_editor.ejs create mode 100644 views/login.ejs create mode 100644 views/media.ejs create mode 100644 views/overlay.ejs create mode 100644 views/overlay_preview.ejs create mode 100644 views/settings.ejs diff --git a/.env.example b/.env.example index c846531..1158885 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,12 @@ TWITCH_CLIENT_ID=your_client_id TWITCH_CLIENT_SECRET=your_client_secret -TWITCH_REDIRECT_URI=http://localhost:8000/auth/callback + +# Local dev: +# TWITCH_REDIRECT_URI=http://localhost:3000/auth/callback +# Production: +TWITCH_REDIRECT_URI=https://overlay.example.com/auth/callback SECRET_KEY=change_this_to_a_random_string -APP_BASE_URL=http://localhost:8000 -DATABASE_URL=sqlite:///./heystreamer.db +APP_BASE_URL=https://overlay.example.com +DB_PATH=./heystreamer.db +PORT=3000 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ab6d37..45ce070 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,38 +13,24 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/setup-node@v4 with: - python-version: '3.11' + node-version: '20' + cache: 'npm' - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install -r requirements.txt + run: npm ci - name: Syntax check - run: | - python3 -c " - import ast, sys, pathlib - errors = [] - for f in pathlib.Path('app').rglob('*.py'): - try: - ast.parse(f.read_text()) - except SyntaxError as e: - errors.append(f'{f}: {e}') - if errors: - for e in errors: print('SYNTAX ERROR:', e) - sys.exit(1) - files = list(pathlib.Path('app').rglob('*.py')) - print(f'All {len(files)} Python files OK') - " + run: node --check src/app.js src/server.js src/db.js src/eventsub.js src/dispatch.js src/ws.js src/cooldowns.js src/routers/*.js - name: Import check - run: python -c "from app.main import app; print('App import OK')" + run: node -e "require('./src/app')" env: - DATABASE_URL: sqlite:///./test.db - SECRET_KEY: ci-test-secret-not-real TWITCH_CLIENT_ID: ci-placeholder TWITCH_CLIENT_SECRET: ci-placeholder - TWITCH_REDIRECT_URI: http://localhost:8000/auth/callback - APP_BASE_URL: http://localhost:8000 + TWITCH_REDIRECT_URI: http://localhost:3000/auth/callback + SECRET_KEY: ci-test-secret-not-real + APP_BASE_URL: http://localhost:3000 + DB_PATH: ./test.db + PORT: 3000 diff --git a/CLAUDE.md b/CLAUDE.md index a614b16..06b7e62 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,128 +3,214 @@ ## Running the app ```bash -source .venv/bin/activate -uvicorn app.main:app --reload +npm install +npm run dev # development (nodemon) +npm start # production ``` -Requires `.env` — copy from `.env.example`. Database is created automatically on startup (`SQLModel.metadata.create_all`). +Requires `.env` — copy from `.env.example`. Database is created automatically on startup (better-sqlite3 runs migrations on init). + +## Stack + +- **Node.js** · Express · EJS templates +- **better-sqlite3** — SQLite, synchronous, simple +- **ws** — WebSocket server for pushing alerts to overlay clients +- **tmi.js** — Twitch IRC, runs in the browser on the overlay page (no server-side IRC) +- **multer** — file uploads +- **uuid** — UUID generation +- **dotenv** — env vars +- **express-session** — session management (signed cookie) ## Architecture ``` -Twitch ──EventSub WebSocket──► app/eventsub.py ──► dispatch.py ──► ws.py ──► OBS overlay -Twitch ──IRC (tmi.js)────────────────────────────────────────────────────► OBS overlay +Twitch ──EventSub WebSocket──► src/eventsub.js ──► dispatch.js ──► ws.js ──► OBS overlay +Twitch ──IRC (tmi.js in browser) ────────────────────────────────────────► OBS overlay ``` -- `eventsub.py` runs as an asyncio background task started in `main.py` lifespan -- When it receives a notification, it calls `dispatch.dispatch_event()` -- `dispatch_event()` opens its own DB session (not request-scoped), resolves matching `EventAction` rows, checks cooldowns, logs to `ActivityLog`, and calls `ws.manager.broadcast()` -- `ws.manager` holds a list of active WebSocket connections from `/ws/overlay` +- `eventsub.js` opens a WebSocket to Twitch on startup, managed as a module-level singleton +- On notification it calls `dispatch.dispatchEvent()` +- `dispatch.dispatchEvent()` queries matching `event_actions` rows, checks cooldowns, logs to `activity_log`, calls `wss.broadcast()` +- `wss` (ws.js) holds all active WebSocket connections from `/ws/overlay` - The overlay JS receives the broadcast and plays the action +- Chat messages come directly from tmi.js running in the browser — no server relay + +## Project structure + +``` +src/ + app.js — Express app setup, middleware, router mounting + server.js — HTTP server + WebSocket server startup, EventSub init + db.js — better-sqlite3 setup, migrations, singleton helpers + eventsub.js — Twitch EventSub WebSocket client (module singleton) + dispatch.js — event → action resolution, cooldowns, DB log, broadcast + ws.js — WebSocket connection manager + cooldowns.js — in-memory cooldown tracking + routers/ + auth.js — /auth/* (Twitch OAuth) + dashboard.js — / (activity log, EventSub status) + overlay.js — /overlay/:uuid, /overlay/:uuid/preview, /ws/overlay + actions.js — /actions CRUD + media.js — /media upload/delete + layout.js — /layout editor + /layout/positions + settings.js — /settings +views/ + layout.ejs — base shell (nav, Pico CSS) + login.ejs + dashboard.ejs + overlay.ejs — OBS browser source + overlay_preview.ejs + layout_editor.ejs + actions.ejs + media.ejs + settings.ejs +public/ + media/ — uploaded files (gitignored) +``` ## Key conventions -**No passwords anywhere.** Auth is Twitch OAuth only. Session is a signed cookie via `SessionMiddleware`. `request.session["user_id"]` stores the DB user ID after login. +**No passwords anywhere.** Auth is Twitch OAuth only. Session stored via `express-session` with a signed cookie. `req.session.userId` stores the DB user ID after login. -**Singleton tables.** `Settings` and `OverlayLayout` each have one row. `database.get_settings()` and `database.get_layout()` create the row on first call. Both return detached objects (safe to use after session close — no lazy relationships). +**Singleton tables.** `settings` and `overlay_layout` each have one row (id=1). `db.getSettings()` and `db.getLayout()` create the row on first call if missing. -**Background DB sessions.** `eventsub.py` and `dispatch.py` use `with Session(engine) as session` directly — not FastAPI's `Depends(get_session)` which is request-scoped. Never pass a request-scoped session to a background task. +**Cooldowns are in-memory.** `cooldowns.js` tracks `{ actionId: triggeredAt }`. Restarting the server resets all cooldowns. Intentional — DB cooldowns not worth the complexity. -**Cooldowns are in-memory.** `app/cooldowns.py` tracks `{action_id: (triggered_at, duration)}`. Restarting the server resets all cooldowns. This is intentional — keeping them in the DB is not worth the complexity for this use case. - -**Multiple actions per event.** `dispatch_event()` loops through ALL matching `EventAction` rows for the event type and fires each one (subject to its own cooldown). There is no "first match wins" logic. +**Multiple actions per event.** `dispatchEvent()` loops through ALL matching `event_actions` rows and fires each one (subject to its own cooldown). No "first match wins". **Event matching rules:** -- `event_type="command"`: `event_detail` must match the command name (case-insensitive, required) -- `event_type="bits"`: if `event_detail` is set, it's treated as a minimum bits threshold (`bits_amount >= int(event_detail)`) -- `event_type="channel_points"`: `event_detail` is the reward ID; None matches any reward -- `event_type="sub"/"gift_sub"`: `event_detail` is the tier ("1000", "2000", "3000"); None matches any tier -- `event_type="follow"/"raid"`: `event_detail` not used for matching +- `event_type="command"`: `event_detail` must match the command name (case-insensitive) +- `event_type="bits"`: if `event_detail` set, treat as minimum bits threshold +- `event_type="channel_points"`: `event_detail` is the reward ID; null matches any reward +- `event_type="sub"/"gift_sub"`: `event_detail` is tier ("1000", "2000", "3000"); null matches any +- `event_type="follow"/"raid"`: `event_detail` not used + +**UUID overlays.** `settings.overlay_id` is a UUID generated on first run. OBS browser source URL is `/overlay/:uuid`. Future multi-user support creates multiple settings rows. ## Route map | Method | Path | File | Notes | |---|---|---|---| -| GET | `/` | routers/dashboard.py | Activity log, EventSub status | -| GET | `/auth/login` | routers/auth.py | Login page | -| GET | `/auth/twitch` | routers/auth.py | Redirect to Twitch OAuth | -| GET | `/auth/callback` | routers/auth.py | Exchange code, save user, start EventSub | -| GET | `/auth/logout` | routers/auth.py | Clear session | -| GET | `/overlay` | routers/overlay.py | Live OBS browser source | -| GET | `/overlay/preview` | routers/overlay.py | Mock preview for layout editor | -| WS | `/ws/overlay` | routers/overlay.py | Bidirectional: commands up, actions down | -| GET/POST | `/actions` | routers/actions.py | List and create actions (HTMX) | -| POST | `/actions/{id}/test` | routers/actions.py | Fire action immediately, skip cooldown | -| POST | `/actions/{id}/toggle` | routers/actions.py | Enable/disable (HTMX) | -| DELETE | `/actions/{id}` | routers/actions.py | Delete (HTMX) | -| GET/POST | `/media` | routers/media.py | Upload list (HTMX) | -| DELETE | `/media/{id}` | routers/media.py | Delete file from disk and DB | -| GET/POST | `/layout` | routers/layout.py | Style form | -| POST | `/layout/positions` | routers/layout.py | JSON endpoint called by drag JS | -| GET/POST | `/settings` | routers/settings.py | Channel, gap audio, custom CSS/JS | -| POST | `/settings/reconnect` | routers/settings.py | Restart EventSub task | +| GET | `/` | routers/dashboard.js | Activity log, EventSub status | +| GET | `/auth/login` | routers/auth.js | Login page | +| GET | `/auth/twitch` | routers/auth.js | Redirect to Twitch OAuth | +| GET | `/auth/callback` | routers/auth.js | Exchange code, save user, start EventSub | +| GET | `/auth/logout` | routers/auth.js | Clear session | +| GET | `/overlay/:uuid` | routers/overlay.js | Live OBS browser source | +| GET | `/overlay/:uuid/preview` | routers/overlay.js | Mock preview for layout editor | +| WS | `/ws/overlay` | routers/overlay.js | Bidirectional: commands up, actions down | +| GET/POST | `/actions` | routers/actions.js | List and create actions | +| POST | `/actions/:id/test` | routers/actions.js | Fire immediately, skip cooldown | +| POST | `/actions/:id/toggle` | routers/actions.js | Enable/disable | +| DELETE | `/actions/:id` | routers/actions.js | Delete | +| GET/POST | `/media` | routers/media.js | Upload, list | +| DELETE | `/media/:id` | routers/media.js | Delete file + DB row | +| GET/POST | `/layout` | routers/layout.js | 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 | ## Overlay CSS variable system -All overlay positioning and styling is driven by CSS custom properties injected into `overlay.html` and `overlay_preview.html` from `OverlayLayout`: +All overlay positioning and styling uses CSS custom properties rendered into `overlay.ejs` and `overlay_preview.ejs` from the `overlay_layout` row: | Variable | Controls | |---|---| | `--chat-left`, `--chat-top` | Chat box position (%) | | `--chat-width`, `--chat-height` | Chat box size (%) | | `--chat-font-size` | Chat font size (px) | +| `--chat-font-family` | Chat font family | | `--chat-bg-opacity` | Chat message background opacity | -| `--chat-text-color` | Chat message text color | +| `--chat-text-color` | Chat message text colour | +| `--chat-border-radius` | Message border radius (px) | | `--alert-left`, `--alert-top` | Alert position (%, centered via transform) | | `--alert-font-size` | Alert font size (px) | | `--alert-bg-opacity` | Alert background opacity | -| `--alert-text-color` | Alert text color | +| `--alert-text-color` | Alert text colour | -The layout editor (`/layout`) has drag handles in the parent document overlaid on an iframe pointing to `/overlay/preview`. Since both are same-origin, the editor updates the iframe's CSS variables directly via `iframe.contentDocument.documentElement.style.setProperty(...)` for live preview. Positions are persisted via `POST /layout/positions` (JSON) on drag end. +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`. + +## Gap / new-message audio + +Configured in `settings`. When a chat message arrives in the overlay, tmi.js checks: +1. Is `gap_audio_enabled` true and `gap_audio_url` set? +2. Has at least `gap_audio_min_silence` seconds passed since the last message? +3. If yes: play the audio. Volume = linear interpolation between `gap_audio_min_volume` and `gap_audio_max_volume` based on silence duration vs `gap_audio_loud_after`. + +All logic runs in the browser. The server only serves the config. ## Custom events dispatched to overlay JS -When the overlay WebSocket receives an `execute` message, it dispatches a `CustomEvent` on `document` before playing the alert: +When the overlay WebSocket receives an action broadcast: ```javascript document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg })); ``` -Available event types: `sub`, `gift_sub`, `bits`, `channel_points`, `command`, `follow`, `raid`. +Available: `sub`, `gift_sub`, `bits`, `channel_points`, `command`, `follow`, `raid`. -`msg.detail` contains `{ event_type, action_type, media_url, alert_text }`. +`msg` shape: `{ event_type, action_type, media_url, alert_text, username }`. -## Data model +## Database schema +```sql +users — Twitch OAuth user (twitch_id unique) +settings — singleton id=1: overlay_id, channel, gap audio, message_timeout, custom_css/js +overlay_layout — singleton id=1: widget positions and styles +media_files — uploaded sounds/videos +event_actions — event → action mapping (media_file_id FK) +activity_log — append-only event log ``` -User ──────────────────────────────── Twitch OAuth user (one per login) -Settings ──────────────────────────── Singleton: channel, gap audio, custom CSS/JS -OverlayLayout ─────────────────────── Singleton: widget positions and styles -MediaFile ──────────────────────────── Uploaded sound or video file -EventAction ──── media_file (FK) ───── Event → action mapping -ActivityLog ────────────────────────── Append-only event log -``` - -`Claim` unique constraint on `(item_id, attendee_id)` prevents double-claiming — wait, that's IllBring. HeyStreamer has no Claim model. `EventAction` has no unique constraints; multiple rows with the same `event_type` are allowed and all fire. ## EventSub subscriptions -| Twitch event | Condition | Scope required | -|---|---|---| -| `channel.subscribe` v1 | `broadcaster_user_id` | `channel:read:subscriptions` | -| `channel.subscription.message` v1 | `broadcaster_user_id` | `channel:read:subscriptions` | -| `channel.subscription.gift` v1 | `broadcaster_user_id` | `channel:read:subscriptions` | -| `channel.cheer` v1 | `broadcaster_user_id` | `bits:read` | -| `channel.channel_points_custom_reward_redemption.add` v1 | `broadcaster_user_id` | `channel:read:redemptions` | -| `channel.follow` v2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | -| `channel.raid` v1 | `to_broadcaster_user_id` | none | +| Twitch event | Version | Condition | Scope | +|---|---|---|---| +| `channel.subscribe` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | +| `channel.subscription.message` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | +| `channel.subscription.gift` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` | +| `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` | +| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` | +| `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` | +| `channel.raid` | 1 | `to_broadcaster_user_id` | none | -Token refresh is handled in `eventsub._refresh_token()` — triggered on 401 during subscription. +Token refresh triggered on 401 during subscription. + +## Production deployment + +Runs behind Apache on the VPS as a reverse proxy to Node on port 3000. +Production domain: `https://overlay.example.com` + +Minimal Apache vhost config (requires `mod_proxy`, `mod_proxy_http`, `mod_proxy_wstunnel`): +```apache + + ServerName overlay.example.com + + ProxyPreserveHost On + ProxyPass /ws/overlay ws://127.0.0.1:3000/ws/overlay + ProxyPassReverse /ws/overlay ws://127.0.0.1:3000/ws/overlay + ProxyPass / http://127.0.0.1:3000/ + ProxyPassReverse / http://127.0.0.1:3000/ + + # SSL config here (certbot/Let's Encrypt) + +``` + +The `/ws/overlay` must be proxied separately with `ws://` via `mod_proxy_wstunnel` — if it's not listed before the catch-all `/`, WebSocket connections will fail. Enable the required modules with: +```bash +sudo a2enmod proxy proxy_http proxy_wstunnel +sudo systemctl reload apache2 +``` + +Twitch requires HTTPS for OAuth redirect URIs in production. Register both in the Twitch dev console: +- `http://localhost:3000/auth/callback` (dev) +- `https://overlay.example.com/auth/callback` (production) ## Not yet implemented - Alert variable interpolation (`{username}` in alert text) -- Mod access (currently streamer-only login) -- Blerp / HudFX integrations -- Crypto payment notifications -- Morning-of reminder emails (IllBring feature, not applicable here) +- Mod access (streamer-only login for now) +- Chat commands triggering actions +- Stripe / PayPal / ETH payment notifications +- Multiple overlays (multi-user; UUID foundation is in place) +- HudFX integration diff --git a/INSTRUCTIONS.md b/INSTRUCTIONS.md deleted file mode 100644 index ae9f3e6..0000000 --- a/INSTRUCTIONS.md +++ /dev/null @@ -1,274 +0,0 @@ -# Deployment & Git Instructions - -## Prerequisites - -- Python 3.10 or higher -- A Twitch account (the channel you stream on) -- Git - ---- - -## Initial Deploy - -### 1. Register a Twitch application - -1. Go to [dev.twitch.tv/console/apps](https://dev.twitch.tv/console/apps) -2. Click **Register Your Application** -3. Fill in: - - **Name:** anything (e.g. `HeyStreamer`) - - **OAuth Redirect URLs:** `http://localhost:8000/auth/callback` - - **Category:** Application Integration -4. Click **Create** -5. On the next screen, click **Manage** to see your app -6. Copy the **Client ID** -7. Click **New Secret** and copy the **Client Secret** - -Keep both — you will need them in the next step. - ---- - -### 2. Clone the repository - -```bash -git clone https://example.com/heystreamer.git -cd HeyStreamer -``` - ---- - -### 3. Configure environment variables - -```bash -cp .env.example .env -``` - -Open `.env` and fill in: - -```env -TWITCH_CLIENT_ID=paste_your_client_id_here -TWITCH_CLIENT_SECRET=paste_your_client_secret_here -TWITCH_REDIRECT_URI=http://localhost:8000/auth/callback - -SECRET_KEY=paste_a_random_string_here -APP_BASE_URL=http://localhost:8000 -DATABASE_URL=sqlite:///./heystreamer.db -``` - -Generate a `SECRET_KEY` with: - -```bash -python3 -c "import secrets; print(secrets.token_hex(32))" -``` - ---- - -### 4. Run the deploy script - -```bash -chmod +x deploy.sh -./deploy.sh -``` - -The script will: -- Check that Python 3.10+ is installed -- Create a `.venv` virtual environment -- Install all Python dependencies -- Verify `.env` is filled in -- Create the `static/media/` directory -- Start the server at `http://localhost:8000` - -To stop the server: `Ctrl+C` - -To start again without the setup steps: - -```bash -source .venv/bin/activate -uvicorn app.main:app --reload -``` - ---- - -### 5. Log in with Twitch - -1. Open `http://localhost:8000` in your browser -2. Click **Login with Twitch** -3. Authorise the app — you will be asked to grant permissions for subscriptions, bits, channel points, and follower data -4. You are redirected to the dashboard; EventSub connects automatically - -**Bookmark the dashboard URL.** There are no accounts or passwords — the session cookie keeps you logged in. - ---- - -### 6. Configure OBS browser source - -1. In OBS, go to **Sources → + → Browser** -2. Set the URL to the value shown on the Settings page (default: `http://localhost:8000/overlay`) -3. Set **Width** and **Height** to match your stream resolution (typically `1920` × `1080`) -4. Check **Shutdown source when not visible** -5. In the **Custom CSS** box paste: - ```css - body { background: transparent !important; } - ``` -6. Click OK - -The overlay will appear transparent in OBS. Chat messages and alerts show on top of your game/content. - ---- - -### 7. Upload media - -1. Go to **Media** in the management UI -2. Click **Choose File** and upload sounds (MP3, OGG, WAV) and/or videos (MP4, WebM) -3. Preview them in the browser before assigning them to actions - ---- - -### 8. Configure actions - -1. Go to **Actions** -2. For each event you want to react to, fill in the **Add action** form: - - **Event type:** `sub`, `gift_sub`, `bits`, `channel_points`, `command`, `follow`, or `raid` - - **Event detail:** command name (for commands), minimum bits (for bits), reward ID (for channel points), tier (for subs) — leave blank to match any - - **Action type:** `sound`, `video`, or `alert` - - **Media file:** pick an uploaded file (for sound/video) - - **Alert text:** message shown on screen (for alert type) - - **Cooldown:** seconds before this action can fire again -3. Click **Test** on each action to verify it fires before going live - -To find a channel point reward ID: open your Twitch dashboard, go to Channel Points → Manage Rewards, then click a reward. The ID is in the page URL. - ---- - -### 9. Configure the layout - -1. Go to **Layout** -2. Drag the **Chat** handle to where you want chat to appear on screen -3. Drag the bottom-right corner of the Chat handle to resize it -4. Drag the **Alert** handle to where you want alerts to appear -5. Adjust font size, opacity, and text color in the form below the canvas -6. Click **▶ Preview alert** to see the animation with your current settings -7. Click **Save styles** when done -8. **Refresh the OBS browser source** (`Right-click source → Refresh`) to apply layout changes - ---- - -### 10. Optional: Custom CSS and JS - -Go to **Settings** and scroll to the bottom. - -**Custom CSS example** — glow effect on alerts: -```css -#alert { - box-shadow: 0 0 30px #9146ff; - border: 2px solid #9146ff; -} -.chat-msg { - border-left: 3px solid; -} -``` - -**Custom JS example** — react to a raid: -```javascript -document.addEventListener('heystreamer:raid', (e) => { - console.log('Raided!', e.detail.alert_text); -}); -``` - -Available events: `heystreamer:sub`, `heystreamer:gift_sub`, `heystreamer:bits`, `heystreamer:channel_points`, `heystreamer:command`, `heystreamer:follow`, `heystreamer:raid`. - -Click **Save settings** then refresh the OBS browser source. - ---- - -## Git Actions - -### First push to GitHub - -After creating a new empty repository on GitHub: - -```bash -git remote add origin https://example.com/heystreamer.git -git branch -M main -git push -u origin main -``` - ---- - -### Day-to-day workflow - -```bash -# Check what has changed -git status -git diff - -# Stage and commit changes -git add app/routers/actions.py templates/actions.html -git commit -m "add sub tier filtering to action matching" - -# Push to remote -git push -``` - ---- - -### GitHub Actions CI - -The repository includes `.github/workflows/ci.yml`. It runs automatically on every push and pull request and does the following: - -1. Installs Python 3.11 -2. Installs all dependencies from `requirements.txt` -3. Syntax-checks every Python file under `app/` -4. Verifies the FastAPI app imports without error - -No secrets are required for CI — it uses placeholder values for Twitch credentials. - -To view CI results: go to your repository on GitHub → **Actions** tab. - ---- - -### Adding GitHub repository secrets (for future CD) - -If you later want to deploy automatically, add secrets in GitHub: - -1. Go to your repository → **Settings → Secrets and variables → Actions** -2. Click **New repository secret** -3. Add: - - `TWITCH_CLIENT_ID` - - `TWITCH_CLIENT_SECRET` - - `SECRET_KEY` - -Reference them in a workflow step with `${{ secrets.TWITCH_CLIENT_ID }}`. - ---- - -### Branches - -```bash -# Create a feature branch -git checkout -b feature/alert-interpolation - -# Work, commit, push -git push -u origin feature/alert-interpolation - -# Merge back to main when done (on GitHub via pull request, or locally) -git checkout main -git merge feature/alert-interpolation -git push -``` - ---- - -### Updating a deployment - -If HeyStreamer is running on another machine or you pull in new changes: - -```bash -git pull -source .venv/bin/activate -pip install -r requirements.txt # in case dependencies changed -uvicorn app.main:app --reload -``` - -The SQLite database is updated automatically on startup — new tables and columns are created by `SQLModel.metadata.create_all`. Existing data is preserved. - -> **Note:** `create_all` only adds new tables and columns — it does not handle column renames or deletions. If a migration requires dropping a column, do it manually with `sqlite3 heystreamer.db "ALTER TABLE ..."` before restarting. diff --git a/README.md b/README.md deleted file mode 100644 index 2726408..0000000 --- a/README.md +++ /dev/null @@ -1,78 +0,0 @@ -# HeyStreamer - -Self-hosted Twitch stream alert and overlay platform. Subs, bits, channel points, follows, raids, and chat commands trigger configurable sound and video reactions — all running locally on your machine, no third-party alert service required. - -## Features - -- **OBS browser source overlay** — transparent chat display with gap audio (tone plays when chat goes quiet, volume and pitch scale with silence duration) -- **Twitch EventSub** — real-time events for subs, gift subs, bits, channel points, follows, and raids -- **Chat commands** — `!command` triggers via tmi.js, no bot account needed for public channels -- **Action system** — map any event to a sound, video clip, or on-screen alert; multiple actions per event; per-action cooldowns and enable/disable toggle -- **Test button** — fire any action instantly from the management UI without waiting for a real event -- **Self-hosted media library** — upload your own MP3s and MP4s -- **Layout editor** — WYSIWYG iframe editor; drag chat and alert widgets, resize chat, live style preview -- **Custom CSS / JS** — inject code directly into the overlay; hook into `heystreamer:sub`, `heystreamer:raid`, etc. -- **Management UI** — dashboard with activity log, EventSub status, action config, media library -- **Twitch OAuth** — login with your Twitch account; no passwords anywhere - -## Stack - -- Python 3.10+ · FastAPI · SQLModel · SQLite -- Jinja2 · HTMX · Pico CSS (dark theme) -- tmi.js · Twitch EventSub WebSocket -- interact.js (layout editor drag and resize) - -## Quick start - -See **[INSTRUCTIONS.md](INSTRUCTIONS.md)** for the full setup guide including Twitch app registration and OBS configuration. - -```bash -cp .env.example .env -# fill in your Twitch credentials and a SECRET_KEY -./deploy.sh -``` - -## Project structure - -``` -app/ - main.py — FastAPI app, lifespan, EventSub startup - models.py — SQLModel table definitions - database.py — engine, session dependency, singleton helpers - auth.py — Twitch OAuth helpers, session dependency - eventsub.py — EventSub WebSocket background task, token refresh - dispatch.py — event → action resolution, cooldowns, DB log, broadcast - ws.py — WebSocket connection manager for overlay clients - cooldowns.py — in-memory cooldown tracking per action - routers/ - auth.py — /auth/login, /auth/callback, /auth/logout - dashboard.py — / dashboard with activity log - overlay.py — /overlay (live), /overlay/preview, /ws/overlay - actions.py — /actions CRUD, test, toggle - media.py — /media upload and delete - layout.py — /layout editor, /layout/positions (drag save) - settings.py — /settings -templates/ - overlay.html — OBS browser source (live tmi.js + WebSocket) - overlay_preview.html — layout editor preview (mock data, no live connections) - layout.html — iframe-based drag-and-drop layout editor - base.html — management UI shell - dashboard.html — activity log - actions.html — action configuration - media.html — media library - settings.html — settings including custom CSS/JS - login.html — Twitch OAuth login page - partials/ — HTMX response fragments -static/ - overlay.css — overlay styles using CSS custom properties - style.css — management UI styles - media/ — uploaded sounds and videos (gitignored) -``` - -## Deferred / upcoming - -- Blerp sound library integration -- HudFX video library integration -- Crypto payment notifications (Base/ETH wallet watching) -- Alert variable interpolation (`{username}` in alert text) -- Mod access (currently streamer-only login) diff --git a/SPEC.md b/SPEC.md deleted file mode 100644 index 1bf1417..0000000 --- a/SPEC.md +++ /dev/null @@ -1,95 +0,0 @@ -# HeyStreamer — spec - -Self-hosted Twitch stream event platform. Subs, bits, channel points, and chat commands trigger configurable sound and video reactions. Think StreamElements/Streamlabs alerts, but owned and customisable. - -No smart lights. - -## Event sources - -| Source | How | -|---|---| -| Chat commands (`!name`) | tmi.js IRC WebSocket — no auth needed for public chat | -| Subs, bits, channel points | Twitch EventSub WebSocket — requires OAuth token | - -## Action types - -| Action | Notes | -|---|---| -| Play a sound | From Blerp library — see open questions | -| Play a video/clip overlay | From HudFX library — see open questions | -| On-screen alert | Text, image, or animation shown in the OBS browser source | - -## Media libraries - -- **Sounds — Blerp.** Meme/clip sound platform. Has Twitch integration history. API details need confirming before building — check developer docs for programmatic library access and licensing. -- **Videos — HudFX.** Overlay video/animation library. API access and terms need confirming before building. - -Both are external dependencies. If their APIs aren't open enough, fallback is a self-hosted media library (upload your own files via the management UI). - -## The overlay - -OBS browser source pointed at the local management server. Receives events from the backend via WebSocket and plays the configured reaction. - -### Chat gap audio - -Passive audio notification for slow chat — not tied to a command, just fires when a new message arrives after a long silence: -- **Under 30 seconds** — no sound -- **30s to ~2 minutes** — volume scales up with gap -- **2+ minutes** — full volume + pitch scales up (caps ~5 min) - -Thresholds configurable in management UI. - -## Architecture - -``` -Twitch ──EventSub WebSocket──► Backend ──WebSocket──► OBS Browser Source -Twitch ──IRC (tmi.js)────────────────────────────────► OBS Browser Source -``` - -The overlay holds the tmi.js connection directly. The backend holds the EventSub connection and relays events to the overlay. - -## Management platform - -Local web app running on the streamer's machine. - -**Stack:** FastAPI + SQLite + Jinja2 + HTMX (same as IllBring) - -**Features:** -- Configure actions per event type (sub, bits tier, channel point reward, chat command) -- Search and preview Blerp sounds -- Browse and preview HudFX videos -- Upload custom sounds/videos as fallback -- Configure gap-audio thresholds -- Activity log / dashboard -- User access via Twitch OAuth — mods verified against channel mod list, no separate user table - -## Authentication - -Twitch OAuth throughout: -- Streamer logs in → full admin access -- Mods log in → access if verified as mod of the channel via Twitch API -- Token used for EventSub subscriptions - -## Deferred - -- **Crypto payment notifications** — watch a wallet address for incoming transactions via a blockchain API (Alchemy, Moralis, etc.), fire an overlay event on receipt. Which chains to support and whether to use raw wallet watching vs a payment processor (BTCPay Server, etc.) TBD. - -## Estimated effort - -| Piece | Effort | -|---|---| -| OBS overlay + gap audio | 1–2 hours | -| Twitch OAuth | half day | -| EventSub WebSocket + subscriptions | half–1 day | -| Event → action mapping + management UI | 1 day | -| Blerp integration | half day (pending API review) | -| HudFX integration | half day (pending API review) | -| Dashboard / activity log | half day | -| **Total v1** | **~3–4 days** | - -## Open questions before building - -- Does Blerp have a public API with library search + programmatic playback? -- Does HudFX expose a video library via API? -- If either doesn't — self-hosted media library, or a different provider? -- Crypto: which chains, wallet watching vs payment processor? diff --git a/app/__init__.py b/app/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/app/auth.py b/app/auth.py deleted file mode 100644 index 3c8bda0..0000000 --- a/app/auth.py +++ /dev/null @@ -1,64 +0,0 @@ -import os -from typing import Optional - -import httpx -from fastapi import Depends, HTTPException, Request -from fastapi.responses import RedirectResponse -from sqlmodel import Session, select - -from app.database import get_session -from app.models import User - -TWITCH_CLIENT_ID = os.getenv("TWITCH_CLIENT_ID", "") -TWITCH_CLIENT_SECRET = os.getenv("TWITCH_CLIENT_SECRET", "") -TWITCH_REDIRECT_URI = os.getenv("TWITCH_REDIRECT_URI", "http://localhost:8000/auth/callback") - -SCOPES = "channel:read:subscriptions bits:read channel:read:redemptions moderator:read:followers" - -TWITCH_AUTH_URL = ( - "https://id.twitch.tv/oauth2/authorize" - f"?client_id={TWITCH_CLIENT_ID}" - f"&redirect_uri={TWITCH_REDIRECT_URI}" - "&response_type=code" - f"&scope={SCOPES.replace(' ', '+')}" -) - - -async def exchange_code(code: str) -> dict: - async with httpx.AsyncClient() as client: - r = await client.post("https://id.twitch.tv/oauth2/token", data={ - "client_id": TWITCH_CLIENT_ID, - "client_secret": TWITCH_CLIENT_SECRET, - "code": code, - "grant_type": "authorization_code", - "redirect_uri": TWITCH_REDIRECT_URI, - }) - r.raise_for_status() - return r.json() - - -async def get_twitch_user(access_token: str) -> dict: - async with httpx.AsyncClient() as client: - r = await client.get( - "https://api.twitch.tv/helix/users", - headers={"Authorization": f"Bearer {access_token}", "Client-Id": TWITCH_CLIENT_ID}, - ) - r.raise_for_status() - return r.json()["data"][0] - - -def get_current_user(request: Request, session: Session = Depends(get_session)) -> Optional[User]: - user_id = request.session.get("user_id") - if not user_id: - return None - return session.get(User, user_id) - - -def require_user(request: Request, session: Session = Depends(get_session)) -> User: - user_id = request.session.get("user_id") - if not user_id: - raise HTTPException(status_code=307, headers={"Location": "/auth/login"}) - user = session.get(User, user_id) - if not user: - raise HTTPException(status_code=307, headers={"Location": "/auth/login"}) - return user diff --git a/app/cooldowns.py b/app/cooldowns.py deleted file mode 100644 index 87ac74e..0000000 --- a/app/cooldowns.py +++ /dev/null @@ -1,15 +0,0 @@ -from datetime import datetime - -_store: dict[int, tuple[datetime, int]] = {} - - -def is_on_cooldown(action_id: int) -> bool: - if action_id not in _store: - return False - triggered_at, duration = _store[action_id] - return (datetime.utcnow() - triggered_at).total_seconds() < duration - - -def set_cooldown(action_id: int, duration_seconds: int) -> None: - if duration_seconds > 0: - _store[action_id] = (datetime.utcnow(), duration_seconds) diff --git a/app/database.py b/app/database.py deleted file mode 100644 index bc151ec..0000000 --- a/app/database.py +++ /dev/null @@ -1,48 +0,0 @@ -import os - -from dotenv import load_dotenv -from sqlmodel import Session, SQLModel, create_engine, select - -load_dotenv() - -DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./heystreamer.db") -engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) - - -def create_db() -> None: - SQLModel.metadata.create_all(engine) - - -def get_session(): - with Session(engine) as session: - yield session - - -def get_settings(): - from app.models import Settings - with Session(engine) as session: - s = session.exec(select(Settings)).first() - if not s: - s = Settings() - session.add(s) - session.commit() - session.refresh(s) - return s - - -def get_layout(): - from app.models import OverlayLayout - with Session(engine) as session: - layout = session.exec(select(OverlayLayout)).first() - if not layout: - layout = OverlayLayout() - session.add(layout) - session.commit() - session.refresh(layout) - return layout - - -def get_admin_user(): - from app.models import User - with Session(engine) as session: - return session.exec(select(User).where(User.is_admin == True)).first() diff --git a/app/dispatch.py b/app/dispatch.py deleted file mode 100644 index f2b52f0..0000000 --- a/app/dispatch.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Optional - -from sqlmodel import Session, select - -from app.cooldowns import is_on_cooldown, set_cooldown -from app.database import engine -from app.models import ActivityLog, EventAction, MediaFile -from app.ws import manager - - -async def dispatch_event( - event_type: str, - username: Optional[str] = None, - event_detail: Optional[str] = None, - bits_amount: Optional[int] = None, -) -> None: - with Session(engine) as session: - actions = session.exec( - select(EventAction) - .where(EventAction.event_type == event_type) - .where(EventAction.enabled == True) - ).all() - - fired = [] - for action in actions: - if not _matches(action, event_detail, bits_amount): - continue - if is_on_cooldown(action.id): - continue - - payload = _resolve_payload(action, session) - alert_text = action.alert_text or _default_alert(event_type, username, event_detail, bits_amount) - - set_cooldown(action.id, action.cooldown_seconds) - await manager.broadcast({ - "type": "execute", - "event_type": event_type, - "action_type": action.action_type, - "media_url": payload.get("media_url"), - "alert_text": alert_text, - }) - fired.append(f"{action.action_type}: {payload.get('media_url') or alert_text or ''}") - - action_taken = ", ".join(fired) if fired else None - _log(session, event_type, username, event_detail, bits_amount, action_taken) - - session.commit() - - -def _matches(action: EventAction, event_detail: Optional[str], bits_amount: Optional[int]) -> bool: - if not action.event_detail: - return True - if action.event_type == "bits" and bits_amount is not None: - try: - return bits_amount >= int(action.event_detail) - except ValueError: - return False - if action.event_type == "command": - return action.event_detail.lower() == (event_detail or "").lower() - return action.event_detail == event_detail - - -def _resolve_payload(action: EventAction, session: Session) -> dict: - if action.media_file_id: - media = session.get(MediaFile, action.media_file_id) - if media: - return {"media_url": f"/static/media/{media.filename}"} - return {} - - -def _log(session, event_type, username, event_detail, bits_amount, action_taken): - session.add(ActivityLog( - event_type=event_type, - username=username, - detail=_detail_str(event_type, event_detail, bits_amount), - action_taken=action_taken, - )) - - -def _detail_str(event_type, event_detail, bits_amount) -> Optional[str]: - if event_type == "sub": - return f"tier {event_detail}" if event_detail else None - if event_type == "bits": - return f"{bits_amount} bits" if bits_amount else None - if event_type == "channel_points": - return event_detail - if event_type == "command": - return f"!{event_detail}" if event_detail else None - if event_type == "raid": - return f"{event_detail} viewers" if event_detail else None - return None - - -def _default_alert(event_type, username, event_detail, bits_amount) -> Optional[str]: - u = username or "Someone" - if event_type == "sub": - return f"{u} just subscribed!" - if event_type == "gift_sub": - return f"{u} gifted a sub!" - if event_type == "bits": - return f"{u} cheered {bits_amount} bits!" - if event_type == "channel_points": - return f"{u} redeemed channel points!" - if event_type == "follow": - return f"{u} just followed!" - if event_type == "raid": - viewers = f" with {event_detail} viewers" if event_detail else "" - return f"{u} is raiding{viewers}!" - return None diff --git a/app/eventsub.py b/app/eventsub.py deleted file mode 100644 index 97d1d7e..0000000 --- a/app/eventsub.py +++ /dev/null @@ -1,141 +0,0 @@ -import asyncio -import json -import logging -import os - -import httpx -import websockets - -from app.dispatch import dispatch_event - -logger = logging.getLogger(__name__) - -EVENTSUB_WS_URL = "wss://eventsub.wss.twitch.tv/ws" -TWITCH_CLIENT_ID = os.getenv("TWITCH_CLIENT_ID", "") -TWITCH_CLIENT_SECRET = os.getenv("TWITCH_CLIENT_SECRET", "") - -SUBSCRIPTIONS = [ - ("channel.subscribe", "1", lambda bid: {"broadcaster_user_id": bid}), - ("channel.subscription.message", "1", lambda bid: {"broadcaster_user_id": bid}), - ("channel.subscription.gift", "1", lambda bid: {"broadcaster_user_id": bid}), - ("channel.cheer", "1", lambda bid: {"broadcaster_user_id": bid}), - ("channel.channel_points_custom_reward_redemption.add", "1", lambda bid: {"broadcaster_user_id": bid}), - ("channel.follow", "2", lambda bid: {"broadcaster_user_id": bid, "moderator_user_id": bid}), - ("channel.raid", "1", lambda bid: {"to_broadcaster_user_id": bid}), -] - - -async def run_eventsub(broadcaster_id: str, access_token: str) -> None: - while True: - try: - async with websockets.connect(EVENTSUB_WS_URL) as ws: - logger.info("EventSub connected") - async for raw in ws: - msg = json.loads(raw) - msg_type = msg.get("metadata", {}).get("message_type") - - if msg_type == "session_welcome": - session_id = msg["payload"]["session"]["id"] - token = await _subscribe_all(session_id, broadcaster_id, access_token) - if token: - access_token = token - - elif msg_type == "notification": - await _handle_notification(msg["payload"]) - - elif msg_type == "session_reconnect": - reconnect_url = msg["payload"]["session"]["reconnect_url"] - logger.info("EventSub reconnect requested") - break - - except asyncio.CancelledError: - logger.info("EventSub task cancelled") - return - except Exception as e: - logger.warning(f"EventSub error: {e}, reconnecting in 10s") - await asyncio.sleep(10) - - -async def _subscribe_all(session_id: str, broadcaster_id: str, access_token: str) -> str | None: - transport = {"method": "websocket", "session_id": session_id} - condition = {"broadcaster_user_id": broadcaster_id} - headers = { - "Authorization": f"Bearer {access_token}", - "Client-Id": TWITCH_CLIENT_ID, - "Content-Type": "application/json", - } - - async with httpx.AsyncClient() as client: - for sub_type, version, condition_fn in SUBSCRIPTIONS: - condition = condition_fn(broadcaster_id) - r = await client.post( - "https://api.twitch.tv/helix/eventsub/subscriptions", - headers=headers, - json={"type": sub_type, "version": version, "condition": condition, "transport": transport}, - ) - if r.status_code == 401: - new_token = await _refresh_token(access_token) - if new_token: - headers["Authorization"] = f"Bearer {new_token}" - await client.post( - "https://api.twitch.tv/helix/eventsub/subscriptions", - headers=headers, - json={"type": sub_type, "version": version, "condition": condition, "transport": transport}, - ) - return new_token - elif r.status_code not in (200, 202, 409): - logger.warning(f"Failed to subscribe to {sub_type}: {r.status_code} {r.text}") - return None - - -async def _refresh_token(old_token: str) -> str | None: - from app.database import engine - from app.models import User - from sqlmodel import Session, select - - with Session(engine) as session: - user = session.exec(select(User).where(User.access_token == old_token)).first() - if not user: - return None - async with httpx.AsyncClient() as client: - r = await client.post("https://id.twitch.tv/oauth2/token", data={ - "client_id": TWITCH_CLIENT_ID, - "client_secret": TWITCH_CLIENT_SECRET, - "grant_type": "refresh_token", - "refresh_token": user.refresh_token, - }) - if r.status_code != 200: - return None - data = r.json() - user.access_token = data["access_token"] - user.refresh_token = data.get("refresh_token", user.refresh_token) - session.add(user) - session.commit() - return user.access_token - - -async def _handle_notification(payload: dict) -> None: - sub_type = payload["subscription"]["type"] - event = payload["event"] - username = event.get("user_name") or event.get("user_login") - - if sub_type in ("channel.subscribe", "channel.subscription.message"): - await dispatch_event("sub", username=username, event_detail=event.get("tier", "1000")) - - elif sub_type == "channel.subscription.gift": - await dispatch_event("gift_sub", username=username, event_detail=event.get("tier", "1000")) - - elif sub_type == "channel.cheer": - await dispatch_event("bits", username=username, bits_amount=event.get("bits", 0)) - - elif sub_type == "channel.channel_points_custom_reward_redemption.add": - reward_id = event.get("reward", {}).get("id") - await dispatch_event("channel_points", username=username, event_detail=reward_id) - - elif sub_type == "channel.follow": - await dispatch_event("follow", username=username) - - elif sub_type == "channel.raid": - raider = event.get("from_broadcaster_user_name") or event.get("from_broadcaster_user_login") - viewers = str(event.get("viewers", "")) - await dispatch_event("raid", username=raider, event_detail=viewers) diff --git a/app/main.py b/app/main.py deleted file mode 100644 index 13d3f70..0000000 --- a/app/main.py +++ /dev/null @@ -1,60 +0,0 @@ -import asyncio -import os -from contextlib import asynccontextmanager -from typing import Optional - -from dotenv import load_dotenv -from fastapi import FastAPI -from fastapi.staticfiles import StaticFiles -from starlette.middleware.sessions import SessionMiddleware - -from app.database import create_db, get_admin_user -from app.routers import actions, auth, dashboard, layout, media, overlay, settings - -load_dotenv() - -_eventsub_task: Optional[asyncio.Task] = None - - -def get_eventsub_task() -> Optional[asyncio.Task]: - return _eventsub_task - - -async def start_eventsub() -> None: - global _eventsub_task - from app.eventsub import run_eventsub - - admin = get_admin_user() - if not admin: - return - - if _eventsub_task and not _eventsub_task.done(): - _eventsub_task.cancel() - try: - await _eventsub_task - except asyncio.CancelledError: - pass - - _eventsub_task = asyncio.create_task(run_eventsub(admin.broadcaster_id, admin.access_token)) - - -@asynccontextmanager -async def lifespan(app: FastAPI): - create_db() - await start_eventsub() - yield - if _eventsub_task and not _eventsub_task.done(): - _eventsub_task.cancel() - - -app = FastAPI(title="HeyStreamer", lifespan=lifespan) -app.add_middleware(SessionMiddleware, secret_key=os.getenv("SECRET_KEY", "dev-secret-change-me")) -app.mount("/static", StaticFiles(directory="static"), name="static") - -app.include_router(auth.router) -app.include_router(dashboard.router) -app.include_router(overlay.router) -app.include_router(actions.router) -app.include_router(media.router) -app.include_router(layout.router) -app.include_router(settings.router) diff --git a/app/models.py b/app/models.py deleted file mode 100644 index 12c2a8c..0000000 --- a/app/models.py +++ /dev/null @@ -1,79 +0,0 @@ -from datetime import datetime -from typing import List, Optional - -from sqlmodel import Field, Relationship, SQLModel - - -class User(SQLModel, table=True): - id: Optional[int] = Field(default=None, primary_key=True) - twitch_id: str = Field(unique=True, index=True) - twitch_login: str - twitch_display_name: str - broadcaster_id: str - access_token: str - refresh_token: str - is_admin: bool = False - created_at: datetime = Field(default_factory=datetime.utcnow) - - -class MediaFile(SQLModel, table=True): - id: Optional[int] = Field(default=None, primary_key=True) - filename: str - original_name: str - file_type: str # "audio" | "video" - created_at: datetime = Field(default_factory=datetime.utcnow) - - actions: List["EventAction"] = Relationship(back_populates="media_file") - - -class EventAction(SQLModel, table=True): - id: Optional[int] = Field(default=None, primary_key=True) - event_type: str # "sub" | "gift_sub" | "bits" | "channel_points" | "command" - event_detail: Optional[str] = None # command name, reward ID, sub tier, bits minimum - action_type: str # "sound" | "video" | "alert" - media_file_id: Optional[int] = Field(default=None, foreign_key="mediafile.id") - alert_text: Optional[str] = None - cooldown_seconds: int = 0 - enabled: bool = True - created_at: datetime = Field(default_factory=datetime.utcnow) - - media_file: Optional["MediaFile"] = Relationship(back_populates="actions") - - -class ActivityLog(SQLModel, table=True): - id: Optional[int] = Field(default=None, primary_key=True) - event_type: str - username: Optional[str] = None - detail: Optional[str] = None - action_taken: Optional[str] = None - triggered_at: datetime = Field(default_factory=datetime.utcnow) - - -class Settings(SQLModel, table=True): - id: Optional[int] = Field(default=None, primary_key=True) - twitch_channel: str = "" - gap_silence_threshold: int = 30 - gap_scale_end: int = 120 - gap_pitch_scale_end: int = 300 - custom_css: str = "" - custom_js: str = "" - - -class OverlayLayout(SQLModel, table=True): - id: Optional[int] = Field(default=None, primary_key=True) - # Chat widget — position/size as % of canvas - chat_left: float = 72.0 - chat_top: float = 5.0 - chat_width: float = 27.0 - chat_height: float = 88.0 - chat_font_size: int = 14 - chat_bg_opacity: float = 0.55 - chat_text_color: str = "#ffffff" - chat_max_messages: int = 20 - # Alert widget — position as % of canvas (centered via transform) - alert_left: float = 50.0 - alert_top: float = 40.0 - alert_font_size: int = 24 - alert_bg_opacity: float = 0.8 - alert_text_color: str = "#ffffff" - alert_duration: int = 4 diff --git a/app/routers/__init__.py b/app/routers/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/app/routers/actions.py b/app/routers/actions.py deleted file mode 100644 index 3e22342..0000000 --- a/app/routers/actions.py +++ /dev/null @@ -1,140 +0,0 @@ -from typing import Optional - -from fastapi import APIRouter, Depends, Form, HTTPException, Request -from fastapi.responses import HTMLResponse -from sqlmodel import Session, select - -from app.auth import require_user -from app.database import get_session -from app.models import ActivityLog, EventAction, MediaFile -from app.templates import templates -from app.ws import manager - -router = APIRouter(prefix="/actions") - -EVENT_TYPES = ["sub", "gift_sub", "bits", "channel_points", "command", "follow", "raid"] -ACTION_TYPES = ["sound", "video", "alert"] - - -@router.get("", response_class=HTMLResponse) -async def actions_page(request: Request, session: Session = Depends(get_session), user=Depends(require_user)): - actions = session.exec(select(EventAction)).all() - media_files = session.exec(select(MediaFile)).all() - return templates.TemplateResponse("actions.html", { - "request": request, - "user": user, - "actions": actions, - "media_files": media_files, - "event_types": EVENT_TYPES, - "action_types": ACTION_TYPES, - }) - - -@router.post("", response_class=HTMLResponse) -async def create_action( - request: Request, - event_type: str = Form(...), - event_detail: Optional[str] = Form(default=None), - action_type: str = Form(...), - media_file_id: Optional[int] = Form(default=None), - alert_text: Optional[str] = Form(default=None), - cooldown_seconds: int = Form(default=0), - session: Session = Depends(get_session), - user=Depends(require_user), -): - action = EventAction( - event_type=event_type, - event_detail=event_detail.strip() if event_detail and event_detail.strip() else None, - action_type=action_type, - media_file_id=media_file_id or None, - alert_text=alert_text.strip() if alert_text and alert_text.strip() else None, - cooldown_seconds=max(0, cooldown_seconds), - ) - session.add(action) - session.commit() - session.refresh(action) - - media_files = session.exec(select(MediaFile)).all() - return templates.TemplateResponse("partials/action_row.html", { - "request": request, - "action": action, - "media_files": media_files, - }) - - -@router.post("/{action_id}/test", response_class=HTMLResponse) -async def test_action( - request: Request, - action_id: int, - session: Session = Depends(get_session), - user=Depends(require_user), -): - action = session.get(EventAction, action_id) - if not action: - raise HTTPException(status_code=404) - - media_url = None - if action.media_file_id: - media = session.get(MediaFile, action.media_file_id) - if media: - media_url = f"/static/media/{media.filename}" - - await manager.broadcast({ - "type": "execute", - "action_type": action.action_type, - "media_url": media_url, - "alert_text": action.alert_text or "Test!", - }) - - session.add(ActivityLog( - event_type="test", - username=user.twitch_display_name, - detail=f"{action.event_type}:{action.event_detail or 'any'}", - action_taken=f"{action.action_type}: {media_url or action.alert_text or ''}", - )) - session.commit() - - media_files = session.exec(select(MediaFile)).all() - return templates.TemplateResponse("partials/action_row.html", { - "request": request, - "action": action, - "media_files": media_files, - "just_tested": True, - }) - - -@router.delete("/{action_id}", response_class=HTMLResponse) -async def delete_action( - action_id: int, - session: Session = Depends(get_session), - user=Depends(require_user), -): - action = session.get(EventAction, action_id) - if not action: - raise HTTPException(status_code=404) - session.delete(action) - session.commit() - return HTMLResponse("") - - -@router.post("/{action_id}/toggle", response_class=HTMLResponse) -async def toggle_action( - request: Request, - action_id: int, - session: Session = Depends(get_session), - user=Depends(require_user), -): - action = session.get(EventAction, action_id) - if not action: - raise HTTPException(status_code=404) - action.enabled = not action.enabled - session.add(action) - session.commit() - session.refresh(action) - - media_files = session.exec(select(MediaFile)).all() - return templates.TemplateResponse("partials/action_row.html", { - "request": request, - "action": action, - "media_files": media_files, - }) diff --git a/app/routers/auth.py b/app/routers/auth.py deleted file mode 100644 index 1210380..0000000 --- a/app/routers/auth.py +++ /dev/null @@ -1,75 +0,0 @@ -from fastapi import APIRouter, Depends, HTTPException, Request -from fastapi.responses import HTMLResponse, RedirectResponse -from sqlmodel import Session, select - -from app.auth import TWITCH_AUTH_URL, exchange_code, get_twitch_user, get_current_user -from app.database import get_session -from app.models import Settings, User -from app.templates import templates - -router = APIRouter(prefix="/auth") - - -@router.get("/login", response_class=HTMLResponse) -async def login_page(request: Request, user=Depends(get_current_user)): - if user: - return RedirectResponse(url="/") - return templates.TemplateResponse("login.html", {"request": request}) - - -@router.get("/twitch") -async def twitch_redirect(): - return RedirectResponse(url=TWITCH_AUTH_URL) - - -@router.get("/callback") -async def twitch_callback(request: Request, code: str, session: Session = Depends(get_session)): - try: - tokens = await exchange_code(code) - twitch_user = await get_twitch_user(tokens["access_token"]) - except Exception: - raise HTTPException(status_code=400, detail="OAuth failed") - - user = session.exec(select(User).where(User.twitch_id == twitch_user["id"])).first() - is_first = user is None - - if not user: - user = User( - twitch_id=twitch_user["id"], - twitch_login=twitch_user["login"], - twitch_display_name=twitch_user["display_name"], - broadcaster_id=twitch_user["id"], - access_token=tokens["access_token"], - refresh_token=tokens.get("refresh_token", ""), - is_admin=True, - ) - else: - user.access_token = tokens["access_token"] - user.refresh_token = tokens.get("refresh_token", user.refresh_token) - user.twitch_display_name = twitch_user["display_name"] - - session.add(user) - - if is_first: - settings = session.exec(select(Settings)).first() - if not settings: - settings = Settings() - settings.twitch_channel = twitch_user["login"] - session.add(settings) - - session.commit() - session.refresh(user) - request.session["user_id"] = user.id - - if is_first: - from app.main import start_eventsub - import asyncio - asyncio.create_task(start_eventsub()) - - return RedirectResponse(url="/", status_code=303) - - -@router.get("/logout") -async def logout(request: Request): - request.session.clear() - return RedirectResponse(url="/auth/login") diff --git a/app/routers/dashboard.py b/app/routers/dashboard.py deleted file mode 100644 index 23477a8..0000000 --- a/app/routers/dashboard.py +++ /dev/null @@ -1,28 +0,0 @@ -from fastapi import APIRouter, Depends, Request -from fastapi.responses import HTMLResponse -from sqlmodel import Session, select, desc - -from app.auth import require_user -from app.database import get_session -from app.models import ActivityLog -from app.templates import templates - -router = APIRouter() - - -@router.get("/", response_class=HTMLResponse) -async def dashboard(request: Request, session: Session = Depends(get_session), user=Depends(require_user)): - from app.main import get_eventsub_task - task = get_eventsub_task() - eventsub_connected = task is not None and not task.done() - - logs = session.exec( - select(ActivityLog).order_by(desc(ActivityLog.triggered_at)).limit(50) - ).all() - - return templates.TemplateResponse("dashboard.html", { - "request": request, - "user": user, - "eventsub_connected": eventsub_connected, - "logs": logs, - }) diff --git a/app/routers/layout.py b/app/routers/layout.py deleted file mode 100644 index 061e099..0000000 --- a/app/routers/layout.py +++ /dev/null @@ -1,91 +0,0 @@ -from typing import Optional - -from fastapi import APIRouter, Depends, Form, Request -from fastapi.responses import HTMLResponse -from pydantic import BaseModel -from sqlmodel import Session, select - -from app.auth import require_user -from app.database import get_session -from app.models import OverlayLayout -from app.templates import templates - -router = APIRouter(prefix="/layout") - - -def _get_or_create(session: Session) -> OverlayLayout: - layout = session.exec(select(OverlayLayout)).first() - if not layout: - layout = OverlayLayout() - session.add(layout) - session.commit() - session.refresh(layout) - return layout - - -@router.get("", response_class=HTMLResponse) -async def layout_page(request: Request, session: Session = Depends(get_session), user=Depends(require_user)): - layout = _get_or_create(session) - return templates.TemplateResponse("layout.html", {"request": request, "user": user, "layout": layout}) - - -@router.post("", response_class=HTMLResponse) -async def save_styles( - request: Request, - chat_font_size: int = Form(default=14), - chat_bg_opacity: float = Form(default=0.55), - chat_text_color: str = Form(default="#ffffff"), - chat_max_messages: int = Form(default=20), - alert_font_size: int = Form(default=24), - alert_bg_opacity: float = Form(default=0.8), - alert_text_color: str = Form(default="#ffffff"), - alert_duration: int = Form(default=4), - session: Session = Depends(get_session), - user=Depends(require_user), -): - layout = _get_or_create(session) - layout.chat_font_size = max(8, min(48, chat_font_size)) - layout.chat_bg_opacity = max(0.0, min(1.0, chat_bg_opacity)) - layout.chat_text_color = chat_text_color - layout.chat_max_messages = max(1, min(50, chat_max_messages)) - layout.alert_font_size = max(8, min(72, alert_font_size)) - layout.alert_bg_opacity = max(0.0, min(1.0, alert_bg_opacity)) - layout.alert_text_color = alert_text_color - layout.alert_duration = max(1, min(30, alert_duration)) - session.add(layout) - session.commit() - session.refresh(layout) - return templates.TemplateResponse("layout.html", { - "request": request, - "user": user, - "layout": layout, - "saved": True, - }) - - -class PositionUpdate(BaseModel): - widget: str - left: float - top: float - width: Optional[float] = None - height: Optional[float] = None - - -@router.post("/positions") -async def save_positions( - data: PositionUpdate, - session: Session = Depends(get_session), - user=Depends(require_user), -): - layout = _get_or_create(session) - if data.widget == "chat": - layout.chat_left = round(max(0.0, min(95.0, data.left)), 2) - layout.chat_top = round(max(0.0, min(95.0, data.top)), 2) - if data.width is not None: layout.chat_width = round(max(5.0, min(100.0, data.width)), 2) - if data.height is not None: layout.chat_height = round(max(5.0, min(100.0, data.height)), 2) - elif data.widget == "alert": - layout.alert_left = round(max(0.0, min(100.0, data.left)), 2) - layout.alert_top = round(max(0.0, min(100.0, data.top)), 2) - session.add(layout) - session.commit() - return {"ok": True} diff --git a/app/routers/media.py b/app/routers/media.py deleted file mode 100644 index 5595479..0000000 --- a/app/routers/media.py +++ /dev/null @@ -1,79 +0,0 @@ -import os -import uuid - -from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile -from fastapi.responses import HTMLResponse -from sqlmodel import Session, select - -from app.auth import require_user -from app.database import get_session -from app.models import MediaFile -from app.templates import templates - -router = APIRouter(prefix="/media") - -MEDIA_DIR = "static/media" -AUDIO_EXTENSIONS = {".mp3", ".ogg", ".wav", ".m4a"} -VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov"} - - -@router.get("", response_class=HTMLResponse) -async def media_page(request: Request, session: Session = Depends(get_session), user=Depends(require_user)): - files = session.exec(select(MediaFile)).all() - return templates.TemplateResponse("media.html", { - "request": request, - "user": user, - "files": files, - }) - - -@router.post("", response_class=HTMLResponse) -async def upload_file( - request: Request, - file: UploadFile, - session: Session = Depends(get_session), - user=Depends(require_user), -): - ext = os.path.splitext(file.filename)[1].lower() - if ext in AUDIO_EXTENSIONS: - file_type = "audio" - elif ext in VIDEO_EXTENSIONS: - file_type = "video" - else: - raise HTTPException(status_code=400, detail="Unsupported file type") - - filename = f"{uuid.uuid4().hex}{ext}" - path = os.path.join(MEDIA_DIR, filename) - - content = await file.read() - with open(path, "wb") as f: - f.write(content) - - media = MediaFile(filename=filename, original_name=file.filename, file_type=file_type) - session.add(media) - session.commit() - session.refresh(media) - - return templates.TemplateResponse("partials/media_item.html", { - "request": request, - "file": media, - }) - - -@router.delete("/{file_id}", response_class=HTMLResponse) -async def delete_file( - file_id: int, - session: Session = Depends(get_session), - user=Depends(require_user), -): - media = session.get(MediaFile, file_id) - if not media: - raise HTTPException(status_code=404) - - path = os.path.join(MEDIA_DIR, media.filename) - if os.path.exists(path): - os.remove(path) - - session.delete(media) - session.commit() - return HTMLResponse("") diff --git a/app/routers/overlay.py b/app/routers/overlay.py deleted file mode 100644 index 4e79c0b..0000000 --- a/app/routers/overlay.py +++ /dev/null @@ -1,57 +0,0 @@ -from fastapi import APIRouter, WebSocket, WebSocketDisconnect -from fastapi.requests import Request -from fastapi.responses import HTMLResponse - -from app.database import get_layout, get_settings -from app.dispatch import dispatch_event -from app.templates import templates -from app.ws import manager - -router = APIRouter() - - -@router.get("/overlay", response_class=HTMLResponse) -async def overlay_page(request: Request): - settings = get_settings() - layout = get_layout() - return templates.TemplateResponse("overlay.html", { - "request": request, - "channel": settings.twitch_channel, - "gap_silence": settings.gap_silence_threshold, - "gap_scale_end": settings.gap_scale_end, - "gap_pitch_end": settings.gap_pitch_scale_end, - "layout": layout, - "custom_css": settings.custom_css, - "custom_js": settings.custom_js, - }) - - -@router.get("/overlay/preview", response_class=HTMLResponse) -async def overlay_preview(request: Request): - settings = get_settings() - layout = get_layout() - return templates.TemplateResponse("overlay_preview.html", { - "request": request, - "layout": layout, - "custom_css": settings.custom_css, - "custom_js": settings.custom_js, - "alert_duration_ms": layout.alert_duration * 1000, - }) - - -@router.websocket("/ws/overlay") -async def overlay_ws(websocket: WebSocket): - await manager.connect(websocket) - try: - while True: - data = await websocket.receive_json() - if data.get("type") == "command": - await dispatch_event( - "command", - username=data.get("user"), - event_detail=data.get("name"), - ) - except WebSocketDisconnect: - manager.disconnect(websocket) - except Exception: - manager.disconnect(websocket) diff --git a/app/routers/settings.py b/app/routers/settings.py deleted file mode 100644 index 25aec27..0000000 --- a/app/routers/settings.py +++ /dev/null @@ -1,64 +0,0 @@ -from fastapi import APIRouter, Depends, Form, Request -from fastapi.responses import HTMLResponse, RedirectResponse -from sqlmodel import Session, select - -from app.auth import require_user -from app.database import get_session -from app.models import Settings -from app.templates import templates - -router = APIRouter(prefix="/settings") - - -@router.get("", response_class=HTMLResponse) -async def settings_page(request: Request, session: Session = Depends(get_session), user=Depends(require_user)): - settings = session.exec(select(Settings)).first() or Settings() - return templates.TemplateResponse("settings.html", { - "request": request, - "user": user, - "settings": settings, - "overlay_url": str(request.base_url) + "overlay", - }) - - -@router.post("", response_class=HTMLResponse) -async def save_settings( - request: Request, - twitch_channel: str = Form(...), - gap_silence_threshold: int = Form(default=30), - gap_scale_end: int = Form(default=120), - gap_pitch_scale_end: int = Form(default=300), - custom_css: str = Form(default=""), - custom_js: str = Form(default=""), - session: Session = Depends(get_session), - user=Depends(require_user), -): - settings = session.exec(select(Settings)).first() - if not settings: - settings = Settings() - - settings.twitch_channel = twitch_channel.strip().lstrip("#") - settings.gap_silence_threshold = max(0, gap_silence_threshold) - settings.gap_scale_end = max(settings.gap_silence_threshold + 1, gap_scale_end) - settings.gap_pitch_scale_end = max(settings.gap_scale_end + 1, gap_pitch_scale_end) - settings.custom_css = custom_css - settings.custom_js = custom_js - - session.add(settings) - session.commit() - - return templates.TemplateResponse("settings.html", { - "request": request, - "user": user, - "settings": settings, - "overlay_url": str(request.base_url) + "overlay", - "saved": True, - }) - - -@router.post("/reconnect") -async def reconnect_eventsub(user=Depends(require_user)): - from app.main import start_eventsub - import asyncio - asyncio.create_task(start_eventsub()) - return RedirectResponse(url="/settings", status_code=303) diff --git a/app/templates.py b/app/templates.py deleted file mode 100644 index 6176130..0000000 --- a/app/templates.py +++ /dev/null @@ -1,3 +0,0 @@ -from fastapi.templating import Jinja2Templates - -templates = Jinja2Templates(directory="templates") diff --git a/app/ws.py b/app/ws.py deleted file mode 100644 index 4344045..0000000 --- a/app/ws.py +++ /dev/null @@ -1,28 +0,0 @@ -from fastapi import WebSocket - - -class ConnectionManager: - def __init__(self): - self.active: list[WebSocket] = [] - - async def connect(self, ws: WebSocket) -> None: - await ws.accept() - self.active.append(ws) - - def disconnect(self, ws: WebSocket) -> None: - self.active.discard(ws) if hasattr(self.active, "discard") else None - if ws in self.active: - self.active.remove(ws) - - async def broadcast(self, message: dict) -> None: - dead = [] - for ws in self.active: - try: - await ws.send_json(message) - except Exception: - dead.append(ws) - for ws in dead: - self.disconnect(ws) - - -manager = ConnectionManager() diff --git a/deploy.sh b/deploy.sh index 5b97610..9af0581 100755 --- a/deploy.sh +++ b/deploy.sh @@ -1,72 +1,31 @@ #!/usr/bin/env bash -set -euo pipefail +set -e -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' - -info() { echo -e "${GREEN}[HeyStreamer]${NC} $1"; } -warn() { echo -e "${YELLOW}[HeyStreamer]${NC} $1"; } -error() { echo -e "${RED}[HeyStreamer]${NC} $1"; exit 1; } - -# ── Python version check ────────────────────────────────────────────────────── -PYTHON=$(command -v python3 || command -v python || error "Python not found") -PY_VER=$($PYTHON -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")') -PY_MAJOR=$($PYTHON -c 'import sys; print(sys.version_info.major)') -PY_MINOR=$($PYTHON -c 'import sys; print(sys.version_info.minor)') - -if [ "$PY_MAJOR" -lt 3 ] || { [ "$PY_MAJOR" -eq 3 ] && [ "$PY_MINOR" -lt 10 ]; }; then - error "Python 3.10+ required (found $PY_VER)" +echo "==> Checking Node.js..." +node_version=$(node -v 2>/dev/null | cut -c2- | cut -d. -f1) +if [ -z "$node_version" ] || [ "$node_version" -lt 18 ]; then + echo "ERROR: Node.js 18+ required. Install via: https://nodejs.org" + exit 1 fi -info "Python $PY_VER OK" +echo " Node $(node -v) OK" -# ── Virtual environment ─────────────────────────────────────────────────────── -if [ ! -d ".venv" ]; then - info "Creating virtual environment..." - $PYTHON -m venv .venv +echo "==> Installing dependencies..." +npm install --production + +echo "==> Checking .env..." +if [ ! -f .env ]; then + echo "ERROR: .env not found. Copy .env.example and fill in your values." + exit 1 fi -source .venv/bin/activate -info "Virtual environment active" +for var in TWITCH_CLIENT_ID TWITCH_CLIENT_SECRET SECRET_KEY APP_BASE_URL; do + val=$(grep "^${var}=" .env | cut -d= -f2-) + if [ -z "$val" ] || echo "$val" | grep -q "your_\|change_this"; then + echo "ERROR: $var is not set in .env" + exit 1 + fi +done +echo " .env OK" -# ── Dependencies ────────────────────────────────────────────────────────────── -info "Installing dependencies..." -pip install -q --upgrade pip -pip install -q -r requirements.txt -info "Dependencies installed" - -# ── .env ────────────────────────────────────────────────────────────────────── -if [ ! -f ".env" ]; then - cp .env.example .env - warn ".env created from .env.example" - warn "Edit .env with your Twitch credentials before continuing." - warn "" - warn " TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET:" - warn " Register an app at https://dev.twitch.tv/console/apps" - warn " Set OAuth Redirect URL to: http://localhost:8000/auth/callback" - warn "" - echo -n "Have you filled in .env? [y/N] " - read -r answer - if [[ ! "$answer" =~ ^[Yy]$ ]]; then - warn "Edit .env and run deploy.sh again." - exit 0 - fi -fi - -# ── Media directory ─────────────────────────────────────────────────────────── -mkdir -p static/media -info "Media directory ready" - -# ── Launch ──────────────────────────────────────────────────────────────────── -HOST="${HOST:-0.0.0.0}" -PORT="${PORT:-8000}" - -info "Starting HeyStreamer at http://localhost:${PORT}" -info "Open that URL in your browser to log in with Twitch." -info "OBS browser source URL: http://localhost:${PORT}/overlay" -info "" -info "Press Ctrl+C to stop." -echo "" - -exec uvicorn app.main:app --host "$HOST" --port "$PORT" --reload +echo "==> Starting HeyStreamer..." +node src/server.js diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..2aff27a --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1981 @@ +{ + "name": "heystreamer", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "heystreamer", + "version": "1.0.0", + "dependencies": { + "better-sqlite3": "^11.0.0", + "dotenv": "^16.4.5", + "ejs": "^3.1.10", + "express": "^4.19.2", + "express-ejs-layouts": "^2.5.1", + "express-session": "^1.18.0", + "multer": "^1.4.5-lts.1", + "uuid": "^9.0.1", + "ws": "^8.17.0" + }, + "devDependencies": { + "nodemon": "^3.1.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "11.10.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz", + "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/body-parser": { + "version": "1.20.5", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz", + "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.15.1", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/brace-expansion": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz", + "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-ejs-layouts": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/express-ejs-layouts/-/express-ejs-layouts-2.5.1.tgz", + "integrity": "sha512-IXROv9n3xKga7FowT06n1Qn927JR8ZWDn5Dc9CJQoiiaaDqbhW5PDmWShzbpAa2wjWT1vJqaIM1S6vJwwX11gA==" + }, + "node_modules/express-session": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.19.0.tgz", + "integrity": "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA==", + "license": "MIT", + "dependencies": { + "cookie": "~0.7.2", + "cookie-signature": "~1.0.7", + "debug": "~2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.1.0", + "parseurl": "~1.3.3", + "safe-buffer": "~5.2.1", + "uid-safe": "~2.1.5" + }, + "engines": { + "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/filelist": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz", + "integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", + "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true, + "license": "ISC" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/jake": { + "version": "10.9.4", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", + "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "1.4.5-lts.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz", + "integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==", + "deprecated": "Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "3.89.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz", + "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/nodemon": { + "version": "3.1.14", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz", + "integrity": "sha512-jakjZi93UtB3jHMWsXL68FXSAosbLfY0In5gtKq3niLSkrWznrVBzXFNOEMJUfc9+Ke7SHWoAZsiMkNP3vq6Jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^10.2.1", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/nodemon/node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/nodemon/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/nodemon/node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/nodemon/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/qs": { + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", + "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar-stream/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "license": "MIT", + "dependencies": { + "random-bytes": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", + "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..5bfb41f --- /dev/null +++ b/package.json @@ -0,0 +1,24 @@ +{ + "name": "heystreamer", + "version": "1.0.0", + "description": "Self-hosted Twitch overlay platform", + "main": "src/server.js", + "scripts": { + "start": "node src/server.js", + "dev": "nodemon src/server.js" + }, + "dependencies": { + "better-sqlite3": "^11.0.0", + "dotenv": "^16.4.5", + "ejs": "^3.1.10", + "express": "^4.19.2", + "express-ejs-layouts": "^2.5.1", + "express-session": "^1.18.0", + "multer": "^1.4.5-lts.1", + "uuid": "^9.0.1", + "ws": "^8.17.0" + }, + "devDependencies": { + "nodemon": "^3.1.0" + } +} diff --git a/static/media/.gitkeep b/public/media/.gitkeep similarity index 100% rename from static/media/.gitkeep rename to public/media/.gitkeep diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 834259f..0000000 --- a/requirements.txt +++ /dev/null @@ -1,9 +0,0 @@ -fastapi>=0.115.0 -uvicorn[standard]>=0.30.0 -sqlmodel>=0.0.21 -jinja2>=3.1.4 -python-dotenv>=1.0.1 -httpx>=0.27.0 -python-multipart>=0.0.9 -websockets>=12.0 -itsdangerous>=2.1.0 diff --git a/src/app.js b/src/app.js new file mode 100644 index 0000000..73b2691 --- /dev/null +++ b/src/app.js @@ -0,0 +1,58 @@ +const express = require('express'); +const expressLayouts = require('express-ejs-layouts'); +const session = require('express-session'); +const path = require('path'); +require('dotenv').config(); + +const app = express(); + +app.set('trust proxy', 1); + +app.set('view engine', 'ejs'); +app.set('views', path.join(__dirname, '../views')); +app.use(expressLayouts); +app.set('layout', 'layout'); + +app.use((req, res, next) => { + const start = Date.now(); + res.on('finish', () => { + const ms = Date.now() - start; + console.log(`[http] ${req.method} ${req.path} ${res.statusCode} ${ms}ms — ip:${req.ip} secure:${req.secure}`); + }); + next(); +}); + +app.use(express.static(path.join(__dirname, '../public'))); +app.use(express.urlencoded({ extended: true })); +app.use(express.json()); + +app.use(session({ + secret: process.env.SECRET_KEY || 'dev-secret', + resave: false, + saveUninitialized: false, + cookie: { + secure: process.env.APP_BASE_URL?.startsWith('https'), + httpOnly: true, + maxAge: 7 * 24 * 60 * 60 * 1000, + }, +})); + +app.use((req, res, next) => { + res.locals.user = req.session.user || null; + next(); +}); + +function requireAuth(req, res, next) { + if (!req.session.userId) return res.redirect('/auth/login'); + next(); +} + +app.use('/auth', require('./routers/auth')); +app.use('/overlay', require('./routers/overlay')); +app.use('/actions', requireAuth, require('./routers/actions')); +app.use('/media', requireAuth, require('./routers/media')); +app.use('/layout', requireAuth, require('./routers/layout')); +app.use('/settings', requireAuth, require('./routers/settings')); +app.use('/', requireAuth, require('./routers/dashboard')); + +module.exports = app; diff --git a/src/cooldowns.js b/src/cooldowns.js new file mode 100644 index 0000000..10b68a1 --- /dev/null +++ b/src/cooldowns.js @@ -0,0 +1,18 @@ +const cooldowns = new Map(); + +function isOnCooldown(actionId, cooldownSeconds) { + if (!cooldownSeconds) return false; + const last = cooldowns.get(actionId); + if (!last) return false; + return (Date.now() - last) < cooldownSeconds * 1000; +} + +function setCooldown(actionId) { + cooldowns.set(actionId, Date.now()); +} + +function resetCooldown(actionId) { + cooldowns.delete(actionId); +} + +module.exports = { isOnCooldown, setCooldown, resetCooldown }; diff --git a/src/db.js b/src/db.js new file mode 100644 index 0000000..46464d6 --- /dev/null +++ b/src/db.js @@ -0,0 +1,252 @@ +const Database = require('better-sqlite3'); +const { v4: uuidv4 } = require('uuid'); +require('dotenv').config(); + +const DB_PATH = process.env.DB_PATH || './heystreamer.db'; +let db; + +function init() { + db = new Database(DB_PATH); + db.pragma('journal_mode = WAL'); + db.pragma('foreign_keys = ON'); + createSchema(); + seedSettings(); + seedLayout(); + console.log(`[db] Initialised — path: ${DB_PATH}`); +} + +function createSchema() { + db.exec(` + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + twitch_id TEXT UNIQUE NOT NULL, + login TEXT NOT NULL, + display_name TEXT NOT NULL, + access_token TEXT NOT NULL, + refresh_token TEXT NOT NULL, + created_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS settings ( + id INTEGER PRIMARY KEY CHECK(id = 1), + overlay_id TEXT NOT NULL, + channel TEXT DEFAULT '', + message_timeout INTEGER DEFAULT 30, + max_messages INTEGER DEFAULT 20, + gap_audio_enabled INTEGER DEFAULT 0, + gap_audio_url TEXT DEFAULT '', + gap_audio_min_silence INTEGER DEFAULT 60, + gap_audio_min_volume REAL DEFAULT 0.2, + gap_audio_max_volume REAL DEFAULT 1.0, + gap_audio_loud_after INTEGER DEFAULT 3600, + custom_css TEXT DEFAULT '', + custom_js TEXT DEFAULT '' + ); + + CREATE TABLE IF NOT EXISTS overlay_layout ( + id INTEGER PRIMARY KEY CHECK(id = 1), + chat_left REAL DEFAULT 2.0, + chat_top REAL DEFAULT 60.0, + chat_width REAL DEFAULT 25.0, + chat_height REAL DEFAULT 35.0, + chat_font_size INTEGER DEFAULT 15, + chat_font_family TEXT DEFAULT 'Inter, sans-serif', + chat_bg_opacity REAL DEFAULT 0.45, + chat_text_color TEXT DEFAULT '#ffffff', + chat_border_radius INTEGER DEFAULT 8, + alert_left REAL DEFAULT 50.0, + alert_top REAL DEFAULT 40.0, + alert_font_size INTEGER DEFAULT 32, + alert_bg_opacity REAL DEFAULT 0.7, + alert_text_color TEXT DEFAULT '#ffffff' + ); + + CREATE TABLE IF NOT EXISTS media_files ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + filename TEXT NOT NULL, + original_name TEXT NOT NULL, + media_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + uploaded_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS event_actions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + event_type TEXT NOT NULL, + event_detail TEXT, + action_type TEXT NOT NULL, + media_file_id INTEGER REFERENCES media_files(id) ON DELETE SET NULL, + alert_text TEXT, + cooldown_seconds INTEGER DEFAULT 0, + enabled INTEGER DEFAULT 1, + created_at TEXT DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS activity_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + event_type TEXT NOT NULL, + event_detail TEXT, + username TEXT, + data_json TEXT, + actions_fired INTEGER DEFAULT 0, + created_at TEXT DEFAULT (datetime('now')) + ); + `); +} + +function seedSettings() { + const row = db.prepare('SELECT id FROM settings WHERE id = 1').get(); + if (!row) { + const id = uuidv4(); + db.prepare('INSERT INTO settings (id, overlay_id) VALUES (1, ?)').run(id); + console.log(`[db] Created default settings — overlay_id: ${id}`); + } +} + +function seedLayout() { + const row = db.prepare('SELECT id FROM overlay_layout WHERE id = 1').get(); + if (!row) { + db.prepare('INSERT INTO overlay_layout (id) VALUES (1)').run(); + console.log('[db] Created default layout row'); + } +} + +// Users +function upsertUser({ twitch_id, login, display_name, access_token, refresh_token }) { + db.prepare(` + INSERT INTO users (twitch_id, login, display_name, access_token, refresh_token) + VALUES (@twitch_id, @login, @display_name, @access_token, @refresh_token) + ON CONFLICT(twitch_id) DO UPDATE SET + login = excluded.login, + display_name = excluded.display_name, + access_token = excluded.access_token, + refresh_token = excluded.refresh_token + `).run({ twitch_id, login, display_name, access_token, refresh_token }); + return db.prepare('SELECT * FROM users WHERE twitch_id = ?').get(twitch_id); +} + +function getUserById(id) { + return db.prepare('SELECT * FROM users WHERE id = ?').get(id); +} + +// Settings +function getSettings() { + return db.prepare('SELECT * FROM settings WHERE id = 1').get(); +} + +function updateSettings(fields) { + const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', '); + db.prepare(`UPDATE settings SET ${cols} WHERE id = 1`).run(fields); +} + +// Layout +function getLayout() { + return db.prepare('SELECT * FROM overlay_layout WHERE id = 1').get(); +} + +function updateLayout(fields) { + const cols = Object.keys(fields).map(k => `${k} = @${k}`).join(', '); + db.prepare(`UPDATE overlay_layout SET ${cols} WHERE id = 1`).run(fields); +} + +function updateLayoutPositions(fields) { + db.prepare(` + UPDATE overlay_layout SET + chat_left = @chat_left, chat_top = @chat_top, + chat_width = @chat_width, chat_height = @chat_height, + alert_left = @alert_left, alert_top = @alert_top + WHERE id = 1 + `).run(fields); +} + +// Media +function getAllMedia() { + return db.prepare('SELECT * FROM media_files ORDER BY uploaded_at DESC').all(); +} + +function getMediaFile(id) { + return db.prepare('SELECT * FROM media_files WHERE id = ?').get(id); +} + +function createMedia(fields) { + return db.prepare(` + INSERT INTO media_files (filename, original_name, media_type, size_bytes) + VALUES (@filename, @original_name, @media_type, @size_bytes) + `).run(fields); +} + +function deleteMedia(id) { + db.prepare('DELETE FROM media_files WHERE id = ?').run(id); +} + +// Actions +function getAllActions() { + return db.prepare('SELECT * FROM event_actions ORDER BY created_at DESC').all(); +} + +function getAction(id) { + return db.prepare('SELECT * FROM event_actions WHERE id = ?').get(id); +} + +function createAction(fields) { + db.prepare(` + INSERT INTO event_actions (name, event_type, event_detail, action_type, media_file_id, alert_text, cooldown_seconds) + VALUES (@name, @event_type, @event_detail, @action_type, @media_file_id, @alert_text, @cooldown_seconds) + `).run(fields); +} + +function toggleAction(id) { + db.prepare('UPDATE event_actions SET enabled = NOT enabled WHERE id = ?').run(id); +} + +function deleteAction(id) { + db.prepare('DELETE FROM event_actions WHERE id = ?').run(id); +} + +function getMatchingActions(eventType, eventDetail) { + const rows = db.prepare('SELECT * FROM event_actions WHERE event_type = ? AND enabled = 1').all(eventType); + return rows.filter(a => { + if (eventType === 'command') { + return a.event_detail && a.event_detail.toLowerCase() === (eventDetail || '').toLowerCase(); + } + if (eventType === 'bits' && a.event_detail) { + return parseInt(eventDetail || 0) >= parseInt(a.event_detail); + } + if (eventType === 'channel_points' && a.event_detail) { + return a.event_detail === eventDetail; + } + if ((eventType === 'sub' || eventType === 'gift_sub') && a.event_detail) { + return a.event_detail === eventDetail; + } + return true; + }); +} + +// Activity log +function logActivity(eventType, eventDetail, username, data, actionsFired) { + db.prepare(` + INSERT INTO activity_log (event_type, event_detail, username, data_json, actions_fired) + VALUES (@event_type, @event_detail, @username, @data_json, @actions_fired) + `).run({ + event_type: eventType, + event_detail: eventDetail || null, + username: username || null, + data_json: data ? JSON.stringify(data) : null, + actions_fired: actionsFired, + }); +} + +function getActivityLog(limit = 50) { + return db.prepare('SELECT * FROM activity_log ORDER BY created_at DESC LIMIT ?').all(limit); +} + +module.exports = { + init, + upsertUser, getUserById, + getSettings, updateSettings, + getLayout, updateLayout, updateLayoutPositions, + getAllMedia, getMediaFile, createMedia, deleteMedia, + getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions, + logActivity, getActivityLog, +}; diff --git a/src/dispatch.js b/src/dispatch.js new file mode 100644 index 0000000..3d3003a --- /dev/null +++ b/src/dispatch.js @@ -0,0 +1,37 @@ +const db = require('./db'); +const ws = require('./ws'); +const { isOnCooldown, setCooldown } = require('./cooldowns'); + +function dispatchEvent(eventType, eventDetail = null, username = null, data = null) { + const actions = db.getMatchingActions(eventType, eventDetail); + let fired = 0; + + for (const action of actions) { + if (isOnCooldown(action.id, action.cooldown_seconds)) { + console.log(`[dispatch] Action ${action.id} on cooldown — skipping`); + continue; + } + + let mediaUrl = null; + if (action.media_file_id) { + const media = db.getMediaFile(action.media_file_id); + if (media) mediaUrl = `/media/${media.filename}`; + } + + ws.broadcast({ + event_type: eventType, + action_type: action.action_type, + media_url: mediaUrl, + alert_text: action.alert_text, + username, + }); + + setCooldown(action.id); + fired++; + console.log(`[dispatch] Fired action ${action.id} (${action.name}) — event: ${eventType}, user: ${username}`); + } + + db.logActivity(eventType, eventDetail, username, data, fired); +} + +module.exports = { dispatchEvent }; diff --git a/src/eventsub.js b/src/eventsub.js new file mode 100644 index 0000000..faeae1c --- /dev/null +++ b/src/eventsub.js @@ -0,0 +1,118 @@ +const { WebSocket } = require('ws'); +const dispatch = require('./dispatch'); + +const EVENTSUB_URL = 'wss://eventsub.wss.twitch.tv/ws'; +const CLIENT_ID = process.env.TWITCH_CLIENT_ID; + +let ws = null; +let shouldRun = false; +let sessionId = null; +let _accessToken = null; +let _broadcasterId = null; + +function start(accessToken, broadcasterId) { + _accessToken = accessToken; + _broadcasterId = broadcasterId; + shouldRun = true; + connect(); + console.log(`[eventsub] Starting — broadcaster: ${broadcasterId}, base_url: ${process.env.APP_BASE_URL}`); +} + +function stop() { + shouldRun = false; + if (ws) ws.close(); + console.log('[eventsub] Stopped'); +} + +function connect() { + console.log('[eventsub] Connecting...'); + ws = new WebSocket(EVENTSUB_URL); + + ws.on('open', () => console.log('[eventsub] Connected to Twitch EventSub')); + ws.on('message', (raw) => handleMessage(JSON.parse(raw))); + ws.on('close', () => { + console.log('[eventsub] Disconnected'); + if (shouldRun) setTimeout(connect, 10_000); + }); + ws.on('error', (e) => console.error('[eventsub] Error:', e.message)); +} + +async function handleMessage(msg) { + const type = msg.metadata?.message_type; + if (type === 'session_welcome') { + sessionId = msg.payload.session.id; + console.log('[eventsub] Session established:', sessionId); + await subscribeAll(); + } else if (type === 'session_reconnect') { + console.log('[eventsub] Reconnect requested'); + ws.close(); + } else if (type === 'notification') { + handleNotification(msg.payload); + } +} + +async function subscribeAll() { + const subs = [ + { type: 'channel.subscribe', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, + { type: 'channel.subscription.message', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, + { type: 'channel.subscription.gift', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, + { type: 'channel.cheer', version: '1', condition: { broadcaster_user_id: _broadcasterId } }, + { type: 'channel.channel_points_custom_reward_redemption.add',version: '1', condition: { broadcaster_user_id: _broadcasterId } }, + { type: 'channel.follow', version: '2', condition: { broadcaster_user_id: _broadcasterId, moderator_user_id: _broadcasterId } }, + { type: 'channel.raid', version: '1', condition: { to_broadcaster_user_id: _broadcasterId } }, + ]; + + for (const sub of subs) { + try { + const res = await fetch('https://api.twitch.tv/helix/eventsub/subscriptions', { + method: 'POST', + headers: { + 'Authorization': `Bearer ${_accessToken}`, + 'Client-Id': CLIENT_ID, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ ...sub, transport: { method: 'websocket', session_id: sessionId } }), + }); + if (res.status === 202) { + console.log(`[eventsub] Subscribed: ${sub.type}`); + } else { + const body = await res.text(); + console.warn(`[eventsub] Subscribe ${sub.type} → ${res.status}: ${body}`); + } + } catch (e) { + console.error(`[eventsub] Subscribe ${sub.type} failed:`, e.message); + } + } +} + +function handleNotification(payload) { + const sub = payload.subscription; + const event = payload.event; + const username = event.user_login || event.from_broadcaster_user_login || null; + + console.log(`[eventsub] Notification: ${sub.type} — user: ${username}`); + + switch (sub.type) { + case 'channel.subscribe': + case 'channel.subscription.message': + dispatch.dispatchEvent('sub', event.tier, username, event); + break; + case 'channel.subscription.gift': + dispatch.dispatchEvent('gift_sub', event.tier, username, event); + break; + case 'channel.cheer': + dispatch.dispatchEvent('bits', String(event.bits), username, event); + break; + case 'channel.channel_points_custom_reward_redemption.add': + dispatch.dispatchEvent('channel_points', event.reward?.id, username, event); + break; + case 'channel.follow': + dispatch.dispatchEvent('follow', null, username, event); + break; + case 'channel.raid': + dispatch.dispatchEvent('raid', null, username, event); + break; + } +} + +module.exports = { start, stop }; diff --git a/src/routers/actions.js b/src/routers/actions.js new file mode 100644 index 0000000..1d32b1b --- /dev/null +++ b/src/routers/actions.js @@ -0,0 +1,45 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); +const dispatch = require('../dispatch'); +const { resetCooldown } = require('../cooldowns'); + +router.get('/', (req, res) => { + const actions = db.getAllActions(); + const media = db.getAllMedia(); + res.render('actions', { actions, media }); +}); + +router.post('/', (req, res) => { + const { name, event_type, event_detail, action_type, media_file_id, alert_text, cooldown_seconds } = req.body; + db.createAction({ + name, + event_type, + event_detail: event_detail || null, + action_type, + media_file_id: media_file_id ? parseInt(media_file_id) : null, + alert_text: alert_text || null, + cooldown_seconds: parseInt(cooldown_seconds) || 0, + }); + res.redirect('/actions'); +}); + +router.post('/:id/test', (req, res) => { + const action = db.getAction(parseInt(req.params.id)); + if (!action) return res.status(404).send('Not found'); + resetCooldown(action.id); + dispatch.dispatchEvent(action.event_type, action.event_detail, 'test'); + res.redirect('/actions'); +}); + +router.post('/:id/toggle', (req, res) => { + db.toggleAction(parseInt(req.params.id)); + res.redirect('/actions'); +}); + +router.post('/:id/delete', (req, res) => { + db.deleteAction(parseInt(req.params.id)); + res.redirect('/actions'); +}); + +module.exports = router; diff --git a/src/routers/auth.js b/src/routers/auth.js new file mode 100644 index 0000000..4168e65 --- /dev/null +++ b/src/routers/auth.js @@ -0,0 +1,101 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); +const eventsub = require('../eventsub'); + +const CLIENT_ID = process.env.TWITCH_CLIENT_ID; +const CLIENT_SECRET = process.env.TWITCH_CLIENT_SECRET; +const REDIRECT_URI = process.env.TWITCH_REDIRECT_URI; +const SCOPES = [ + 'channel:read:subscriptions', + 'bits:read', + 'channel:read:redemptions', + 'moderator:read:followers', +].join(' '); + +router.get('/login', (req, res) => { + if (req.session.userId) return res.redirect('/'); + res.render('login', { layout: false }); +}); + +router.get('/twitch', (req, res) => { + const state = Math.random().toString(36).slice(2); + req.session.oauthState = state; + console.log(`[auth] OAuth init — sessionID:${req.sessionID} secure:${req.secure} redirect_uri:${REDIRECT_URI}`); + const url = new URL('https://id.twitch.tv/oauth2/authorize'); + url.searchParams.set('client_id', CLIENT_ID); + url.searchParams.set('redirect_uri', REDIRECT_URI); + url.searchParams.set('response_type', 'code'); + url.searchParams.set('scope', SCOPES); + url.searchParams.set('state', state); + res.redirect(url.toString()); +}); + +router.get('/callback', async (req, res) => { + const { code, state, error, error_description } = req.query; + + if (error) { + console.error(`[auth] Twitch denied OAuth — ${error}: ${error_description}`); + return res.redirect('/auth/login'); + } + + console.log(`[auth] Callback — sessionID:${req.sessionID} secure:${req.secure} hasSession:${!!req.session.oauthState}`); + + if (state !== req.session.oauthState) { + console.warn(`[auth] State mismatch — got:${state} expected:${req.session.oauthState} sessionID:${req.sessionID}`); + return res.redirect('/auth/login'); + } + + try { + const tokenRes = await fetch('https://id.twitch.tv/oauth2/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code, grant_type: 'authorization_code', redirect_uri: REDIRECT_URI }), + }); + const tokens = await tokenRes.json(); + + if (!tokenRes.ok || tokens.error) { + console.error(`[auth] Token exchange failed — ${tokenRes.status}: ${tokens.message || tokens.error}`); + return res.redirect('/auth/login'); + } + + const userRes = await fetch('https://api.twitch.tv/helix/users', { + headers: { 'Authorization': `Bearer ${tokens.access_token}`, 'Client-Id': CLIENT_ID }, + }); + const userData = await userRes.json(); + + if (!userRes.ok || !userData.data?.[0]) { + console.error(`[auth] Twitch user fetch failed — ${userRes.status}:`, userData); + return res.redirect('/auth/login'); + } + + const twitchUser = userData.data[0]; + const user = db.upsertUser({ + twitch_id: twitchUser.id, + login: twitchUser.login, + display_name: twitchUser.display_name, + access_token: tokens.access_token, + refresh_token: tokens.refresh_token, + }); + + req.session.userId = user.id; + req.session.user = { login: user.login, display_name: user.display_name }; + + eventsub.start(tokens.access_token, twitchUser.id); + + console.log(`[auth] Login OK — ${twitchUser.login} (twitch_id:${twitchUser.id})`); + res.redirect('/'); + } catch (e) { + console.error('[auth] OAuth error:', e.message, e.stack); + res.redirect('/auth/login'); + } +}); + +router.get('/logout', (req, res) => { + console.log(`[auth] Logout: ${req.session.user?.login}`); + req.session.destroy(); + eventsub.stop(); + res.redirect('/auth/login'); +}); + +module.exports = router; diff --git a/src/routers/dashboard.js b/src/routers/dashboard.js new file mode 100644 index 0000000..b7b6fb8 --- /dev/null +++ b/src/routers/dashboard.js @@ -0,0 +1,11 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); + +router.get('/', (req, res) => { + const logs = db.getActivityLog(50); + const settings = db.getSettings(); + res.render('dashboard', { logs, settings }); +}); + +module.exports = router; diff --git a/src/routers/layout.js b/src/routers/layout.js new file mode 100644 index 0000000..c33c878 --- /dev/null +++ b/src/routers/layout.js @@ -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; diff --git a/src/routers/media.js b/src/routers/media.js new file mode 100644 index 0000000..42159c4 --- /dev/null +++ b/src/routers/media.js @@ -0,0 +1,42 @@ +const express = require('express'); +const router = express.Router(); +const multer = require('multer'); +const path = require('path'); +const fs = require('fs'); +const { v4: uuidv4 } = require('uuid'); +const db = require('../db'); + +const storage = multer.diskStorage({ + destination: path.join(__dirname, '../../public/media'), + filename: (req, file, cb) => cb(null, uuidv4() + path.extname(file.originalname)), +}); +const upload = multer({ storage, limits: { fileSize: 50 * 1024 * 1024 } }); + +router.get('/', (req, res) => { + res.render('media', { files: db.getAllMedia() }); +}); + +router.post('/upload', upload.single('file'), (req, res) => { + if (!req.file) return res.redirect('/media'); + db.createMedia({ + filename: req.file.filename, + original_name: req.file.originalname, + media_type: req.file.mimetype.startsWith('video') ? 'video' : 'audio', + size_bytes: req.file.size, + }); + console.log(`[media] Uploaded: ${req.file.originalname} (${req.file.size} bytes)`); + res.redirect('/media'); +}); + +router.post('/:id/delete', (req, res) => { + const file = db.getMediaFile(parseInt(req.params.id)); + if (file) { + const filePath = path.join(__dirname, '../../public/media', file.filename); + if (fs.existsSync(filePath)) fs.unlinkSync(filePath); + db.deleteMedia(file.id); + console.log(`[media] Deleted: ${file.original_name}`); + } + res.redirect('/media'); +}); + +module.exports = router; diff --git a/src/routers/overlay.js b/src/routers/overlay.js new file mode 100644 index 0000000..af015e6 --- /dev/null +++ b/src/routers/overlay.js @@ -0,0 +1,18 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); + +router.get('/:uuid', (req, res) => { + const settings = db.getSettings(); + if (req.params.uuid !== settings.overlay_id) return res.status(404).send('Overlay not found'); + const layout = db.getLayout(); + res.render('overlay', { layout: false, settings, layout }); +}); + +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; diff --git a/src/routers/settings.js b/src/routers/settings.js new file mode 100644 index 0000000..ec33efc --- /dev/null +++ b/src/routers/settings.js @@ -0,0 +1,40 @@ +const express = require('express'); +const router = express.Router(); +const db = require('../db'); +const eventsub = require('../eventsub'); + +router.get('/', (req, res) => { + const settings = db.getSettings(); + const baseUrl = process.env.APP_BASE_URL; + res.render('settings', { settings, baseUrl }); +}); + +router.post('/', (req, res) => { + const b = req.body; + db.updateSettings({ + channel: b.channel || '', + message_timeout: 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'); + } + res.redirect('/settings'); +}); + +module.exports = router; diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..b680599 --- /dev/null +++ b/src/server.js @@ -0,0 +1,21 @@ +require('dotenv').config(); +const http = require('http'); +const { WebSocketServer } = require('ws'); + +const db = require('./db'); +const ws = require('./ws'); +const app = require('./app'); + +const PORT = process.env.PORT || 3000; + +db.init(); + +const server = http.createServer(app); +const wss = new WebSocketServer({ server, path: '/ws/overlay' }); +ws.init(wss); + +server.listen(PORT, () => { + console.log(`[server] HeyStreamer running on port ${PORT}`); + console.log(`[server] APP_BASE_URL: ${process.env.APP_BASE_URL}`); + console.log(`[server] DB_PATH: ${process.env.DB_PATH}`); +}); diff --git a/src/ws.js b/src/ws.js new file mode 100644 index 0000000..4d7531d --- /dev/null +++ b/src/ws.js @@ -0,0 +1,26 @@ +const { WebSocket } = require('ws'); + +const clients = new Set(); + +function init(wss) { + wss.on('connection', (ws) => { + clients.add(ws); + console.log(`[ws] Client connected — total: ${clients.size}`); + ws.on('close', () => { + clients.delete(ws); + console.log(`[ws] Client disconnected — total: ${clients.size}`); + }); + ws.on('error', () => clients.delete(ws)); + }); +} + +function broadcast(data) { + const msg = JSON.stringify(data); + for (const client of clients) { + if (client.readyState === WebSocket.OPEN) { + client.send(msg); + } + } +} + +module.exports = { init, broadcast }; diff --git a/static/overlay.css b/static/overlay.css deleted file mode 100644 index aa874a3..0000000 --- a/static/overlay.css +++ /dev/null @@ -1,74 +0,0 @@ -* { margin: 0; padding: 0; box-sizing: border-box; } - -body { - background: transparent; - overflow: hidden; - font-family: 'Segoe UI', Arial, sans-serif; -} - -#chat { - position: fixed; - left: var(--chat-left, 72%); - top: var(--chat-top, 5%); - width: var(--chat-width, 27%); - height: var(--chat-height, 88%); - font-size: var(--chat-font-size, 14px); - overflow: hidden; - display: flex; - flex-direction: column; - justify-content: flex-end; - padding: 8px; - gap: 4px; -} - -.chat-msg { - background: rgba(0, 0, 0, var(--chat-bg-opacity, 0.55)); - border-radius: 6px; - padding: 5px 8px; - color: var(--chat-text-color, #fff); - line-height: 1.4; - word-break: break-word; - animation: fadein 0.2s ease; -} - -.uname { font-weight: bold; } - -#alert { - position: fixed; - left: var(--alert-left, 50%); - top: var(--alert-top, 40%); - transform: translate(-50%, -50%); - background: rgba(0, 0, 0, var(--alert-bg-opacity, 0.8)); - color: var(--alert-text-color, #fff); - padding: 1rem 2rem; - border-radius: 12px; - font-size: var(--alert-font-size, 24px); - font-weight: bold; - text-align: center; - max-width: 80vw; - animation: popin 0.3s ease; -} - -#alert-video-wrap { - position: fixed; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - z-index: 100; -} - -#alert-video { - max-width: 80vw; - max-height: 80vh; - border-radius: 8px; -} - -@keyframes fadein { - from { opacity: 0; transform: translateY(6px); } - to { opacity: 1; transform: translateY(0); } -} - -@keyframes popin { - from { opacity: 0; transform: translate(-50%, -50%) scale(0.8); } - to { opacity: 1; transform: translate(-50%, -50%) scale(1); } -} diff --git a/static/style.css b/static/style.css deleted file mode 100644 index 161991e..0000000 --- a/static/style.css +++ /dev/null @@ -1,87 +0,0 @@ -/* Management UI */ -.login-page { display: flex; align-items: center; justify-content: center; min-height: 80vh; } -.login-card { text-align: center; max-width: 360px; } -.twitch-btn { background: #9146ff; border-color: #9146ff; color: #fff; display: inline-block; } -.twitch-btn:hover { background: #772ce8; border-color: #772ce8; } - -.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; } -@media (max-width: 768px) { .form-grid { grid-template-columns: 1fr; } } - -.status-bar { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1.5rem; padding: 0.5rem 1rem; border-radius: var(--pico-border-radius); background: var(--pico-card-background-color); } -.status-dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; } -.status-dot.connected { background: #2ecc71; } -.status-dot.disconnected { background: #e74c3c; } - -.action-row { display: flex; align-items: center; justify-content: space-between; padding: 0.6rem 0; border-bottom: 1px solid var(--pico-table-border-color); gap: 1rem; } -.action-info { flex: 1; display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; } -.action-controls { display: flex; gap: 0.5rem; flex-shrink: 0; } - -.media-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 1rem; } -.media-item { background: var(--pico-card-background-color); border-radius: var(--pico-border-radius); padding: 0.75rem; display: flex; flex-direction: column; gap: 0.5rem; } -.media-info { display: flex; align-items: center; gap: 0.5rem; } -.media-type-badge { font-size: 0.7rem; padding: 0.1rem 0.4rem; border-radius: 999px; font-weight: bold; text-transform: uppercase; } -.media-type-badge.audio { background: #2980b9; color: #fff; } -.media-type-badge.video { background: #8e44ad; color: #fff; } -.media-item audio, .media-item video { width: 100%; } - -.small-btn { padding: 0.25rem 0.6rem; font-size: 0.8rem; margin-bottom: 0; } -.tested-badge { color: #2ecc71; font-size: 0.85rem; animation: fadeout 2s ease 1s forwards; } -@keyframes fadeout { from { opacity: 1; } to { opacity: 0; } } -.muted { color: var(--pico-muted-color); } -section { margin-bottom: 2rem; } -.url-input { font-family: monospace; font-size: 0.85em; } -.code-textarea { font-family: 'Fira Code', 'Consolas', 'Monaco', monospace; font-size: 0.82rem; resize: vertical; } -.notice-success { background: #1a3a1a; border: 1px solid #2ecc71; border-radius: var(--pico-border-radius); padding: 0.75rem 1rem; margin-bottom: 1rem; } - -/* Layout editor */ -.editor-wrap { - position: relative; - width: 100%; - aspect-ratio: 16 / 9; - border-radius: 8px; - overflow: hidden; - border: 1px solid var(--pico-table-border-color); - background: #000; -} -.drag-handle { - position: absolute; - border: 2px dashed rgba(145, 70, 255, 0.7); - border-radius: 4px; - cursor: move; - user-select: none; - z-index: 10; - box-sizing: border-box; - transition: border-color 0.1s; -} -.drag-handle:hover { border-color: rgba(145, 70, 255, 1); background: rgba(145,70,255,0.08); } -.handle-label { - font-size: 0.6rem; - font-weight: bold; - text-transform: uppercase; - letter-spacing: 0.06em; - color: rgba(145, 70, 255, 0.9); - padding: 2px 5px; - background: rgba(0,0,0,0.6); - border-radius: 2px; - width: fit-content; -} -.resize-corner { - position: absolute; - bottom: 0; - right: 0; - width: 14px; - height: 14px; - background: rgba(145, 70, 255, 0.8); - border-top-left-radius: 4px; - cursor: se-resize; -} -.canvas-footer { display: flex; justify-content: space-between; align-items: center; margin: 0.4rem 0 1rem; } -.style-form { margin-top: 0.5rem; } -.props-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem; } -@media (max-width: 768px) { .props-grid { grid-template-columns: 1fr; } } -.props-row { display: flex; flex-wrap: wrap; gap: 0.75rem; } -.props-row label { display: flex; flex-direction: column; gap: 0.25rem; font-size: 0.85rem; } -.props-row input[type="number"] { width: 70px; margin-bottom: 0; padding: 0.3rem; } -.props-row input[type="range"] { width: 100px; margin-bottom: 0; } -.props-row input[type="color"] { width: 48px; height: 36px; padding: 2px; border-radius: 4px; cursor: pointer; margin-bottom: 0; } -.props-row span { font-size: 0.75rem; color: var(--pico-muted-color); } diff --git a/templates/actions.html b/templates/actions.html deleted file mode 100644 index dafe0c4..0000000 --- a/templates/actions.html +++ /dev/null @@ -1,71 +0,0 @@ -{% extends "base.html" %} -{% block title %}Actions — HeyStreamer{% endblock %} -{% block content %} -
-

Actions

-

Configure what happens when each event fires.

-
- -
-

Add action

-
-
- - - - - - -
- -
-
- -
-

Configured actions

-
- {% for action in actions %} - {% set _ = namespace(media_files=media_files) %} - {% include "partials/action_row.html" %} - {% endfor %} - {% if not actions %} -

No actions configured yet.

- {% endif %} -
-
-{% endblock %} diff --git a/templates/base.html b/templates/base.html deleted file mode 100644 index 2997416..0000000 --- a/templates/base.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - {% block title %}HeyStreamer{% endblock %} - - - - - -
- -
-
- {% block content %}{% endblock %} -
- - diff --git a/templates/dashboard.html b/templates/dashboard.html deleted file mode 100644 index 1f392d0..0000000 --- a/templates/dashboard.html +++ /dev/null @@ -1,50 +0,0 @@ -{% extends "base.html" %} -{% block title %}Dashboard — HeyStreamer{% endblock %} -{% block content %} -
-

Dashboard

-

Welcome, {{ user.twitch_display_name }}

-
- -
- - EventSub: {% if eventsub_connected %}connected{% else %}disconnected{% endif %} - {% if not eventsub_connected %} -
- -
- {% endif %} -
- -
-

Recent activity

- {% if logs %} -
- - - - - - - - - - - - {% for log in logs %} - - - - - - - - {% endfor %} - -
TimeEventUserDetailAction taken
{{ log.triggered_at.strftime('%H:%M:%S') }}{{ log.event_type }}{{ log.username or '—' }}{{ log.detail or '—' }}{{ log.action_taken or 'none configured' | safe }}
-
- {% else %} -

No activity yet. Events will appear here as they come in.

- {% endif %} -
-{% endblock %} diff --git a/templates/layout.html b/templates/layout.html deleted file mode 100644 index ad098e1..0000000 --- a/templates/layout.html +++ /dev/null @@ -1,200 +0,0 @@ -{% extends "base.html" %} -{% block title %}Layout Editor — HeyStreamer{% endblock %} -{% block content %} -
-

Layout Editor

-

Drag handles to reposition. Resize chat from the bottom-right corner. Changes to styles preview live.

-
- -{% if saved %} -
Styles saved. Refresh your OBS browser source to apply.
-{% endif %} - -
- - -
-
Chat
-
-
- -
-
Alert
-
-
- - - -
-
-
- Chat -
- - - - -
-
- -
- Alert -
- - - - -
-
-
- -
- - - -{% endblock %} diff --git a/templates/login.html b/templates/login.html deleted file mode 100644 index 83372d9..0000000 --- a/templates/login.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - Login — HeyStreamer - - - - -
- -
- - diff --git a/templates/media.html b/templates/media.html deleted file mode 100644 index f638a92..0000000 --- a/templates/media.html +++ /dev/null @@ -1,35 +0,0 @@ -{% extends "base.html" %} -{% block title %}Media — HeyStreamer{% endblock %} -{% block content %} -
-

Media

-

Upload sounds and videos for your actions.

-
- -
-

Upload

-
- - -
-
- -
-

Library

-
- {% for file in files %} - {% include "partials/media_item.html" %} - {% endfor %} - {% if not files %} -

No files uploaded yet.

- {% endif %} -
-
-{% endblock %} diff --git a/templates/overlay.html b/templates/overlay.html deleted file mode 100644 index 3855e83..0000000 --- a/templates/overlay.html +++ /dev/null @@ -1,162 +0,0 @@ - - - - - - Overlay - - {% if custom_css %}{% endif %} - - - - - -
- - - - {% if custom_js %}{% endif %} - - diff --git a/templates/overlay_preview.html b/templates/overlay_preview.html deleted file mode 100644 index 20354bc..0000000 --- a/templates/overlay_preview.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - {% if custom_css %}{% endif %} - - - - - -
-
StreamFriend: Let's goooo! 🎉
-
Viewer42: PogChamp PogChamp
-
ChatUser: great stream today!
-
AnotherFan: !airhorn
-
NewViewer: first time here!
-
- - {% if custom_js %}{% endif %} - - diff --git a/templates/partials/action_row.html b/templates/partials/action_row.html deleted file mode 100644 index 2236296..0000000 --- a/templates/partials/action_row.html +++ /dev/null @@ -1,42 +0,0 @@ -
-
- {{ action.event_type }}{% if action.event_detail %}:{{ action.event_detail }}{% endif %} - → - {{ action.action_type }} - {% if action.media_file %} - {{ action.media_file.original_name }} - {% endif %} - {% if action.alert_text %} - "{{ action.alert_text }}" - {% endif %} - {% if action.cooldown_seconds %} - {{ action.cooldown_seconds }}s cooldown - {% endif %} - {% if just_tested %} - ✓ fired - {% endif %} -
-
-
- -
-
- -
- -
-
diff --git a/templates/partials/media_item.html b/templates/partials/media_item.html deleted file mode 100644 index 74f78c6..0000000 --- a/templates/partials/media_item.html +++ /dev/null @@ -1,18 +0,0 @@ -
-
- {{ file.file_type }} - {{ file.original_name }} -
- {% if file.file_type == "audio" %} - - {% else %} - - {% endif %} - -
diff --git a/templates/settings.html b/templates/settings.html deleted file mode 100644 index 925362a..0000000 --- a/templates/settings.html +++ /dev/null @@ -1,65 +0,0 @@ -{% extends "base.html" %} -{% block title %}Settings — HeyStreamer{% endblock %} -{% block content %} -
-

Settings

-
- -{% if saved %} -
Settings saved.
-{% endif %} - -
-

OBS browser source URL

-

Add this as a browser source in OBS:

- - Refresh the browser source in OBS after changing settings. -
- -
-
-

Channel

- - -

Gap audio thresholds

-

A tone plays when a new message arrives after a silence. These control how the volume and pitch scale with the gap length.

-
- - - -
- -

Custom CSS

-

Injected into the overlay after the default styles. Overrides anything. Use #chat, .chat-msg, #alert.

- - -

Custom JS

-

Injected after the overlay scripts. Hook into events with document.addEventListener('heystreamer:sub', e => ...). Available events: sub, gift_sub, bits, channel_points, command, follow, raid.

- - - -
-
- -
-

EventSub

-
- -
-
-{% endblock %} diff --git a/views/actions.ejs b/views/actions.ejs new file mode 100644 index 0000000..8af7df7 --- /dev/null +++ b/views/actions.ejs @@ -0,0 +1,88 @@ +

Actions

+

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

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

No actions yet.

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

Dashboard

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

Recent activity

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

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

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

Layout editor

+

Drag the handles in the preview to reposition widgets. Use the form below to adjust style.

+ +
+ +
+ +
+

Chat style

+
+ + + + + +
+ +

Alert style

+
+ + + +
+ + +
+ + + diff --git a/views/login.ejs b/views/login.ejs new file mode 100644 index 0000000..65a4b13 --- /dev/null +++ b/views/login.ejs @@ -0,0 +1,33 @@ + + + + + + HeyStreamer — Login + + + + +
+

HeyStreamer

+

Self-hosted Twitch stream overlay

+ + + Login with Twitch + +
+ + diff --git a/views/media.ejs b/views/media.ejs new file mode 100644 index 0000000..0d03b66 --- /dev/null +++ b/views/media.ejs @@ -0,0 +1,53 @@ +

Media library

+

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

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

No files uploaded yet.

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

Settings

+ +
+
Overlay URL
+

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

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

Chat

+ +
+ + +
+ +

Gap audio

+

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

+ + +
+ + + +
+ + +

Custom CSS / JS

+ + + + +
+ +
+

EventSub

+
+ +
+Use this if Twitch alerts stop working after a token refresh.