parent
c5462e9790
commit
f07489750c
65 changed files with 3727 additions and 2607 deletions
11
.env.example
11
.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
|
||||
|
|
|
|||
36
.github/workflows/ci.yml
vendored
36
.github/workflows/ci.yml
vendored
|
|
@ -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
|
||||
|
|
|
|||
224
CLAUDE.md
224
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
|
||||
<VirtualHost *:443>
|
||||
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)
|
||||
</VirtualHost>
|
||||
```
|
||||
|
||||
The `/ws/overlay` must be proxied separately with `ws://` via `mod_proxy_wstunnel` — if it's not listed before the catch-all `/`, WebSocket connections will fail. Enable the required modules with:
|
||||
```bash
|
||||
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
|
||||
|
|
|
|||
274
INSTRUCTIONS.md
274
INSTRUCTIONS.md
|
|
@ -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.
|
||||
78
README.md
78
README.md
|
|
@ -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)
|
||||
95
SPEC.md
95
SPEC.md
|
|
@ -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?
|
||||
64
app/auth.py
64
app/auth.py
|
|
@ -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
|
||||
|
|
@ -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)
|
||||
|
|
@ -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()
|
||||
109
app/dispatch.py
109
app/dispatch.py
|
|
@ -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
|
||||
141
app/eventsub.py
141
app/eventsub.py
|
|
@ -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)
|
||||
60
app/main.py
60
app/main.py
|
|
@ -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)
|
||||
|
|
@ -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
|
||||
|
|
@ -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,
|
||||
})
|
||||
|
|
@ -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")
|
||||
|
|
@ -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,
|
||||
})
|
||||
|
|
@ -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}
|
||||
|
|
@ -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("")
|
||||
|
|
@ -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)
|
||||
|
|
@ -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)
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
from fastapi.templating import Jinja2Templates
|
||||
|
||||
templates = Jinja2Templates(directory="templates")
|
||||
28
app/ws.py
28
app/ws.py
|
|
@ -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()
|
||||
87
deploy.sh
87
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"
|
||||
|
||||
# ── 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
|
||||
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"
|
||||
|
||||
# ── 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
|
||||
|
|
|
|||
1981
package-lock.json
generated
Normal file
1981
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
24
package.json
Normal file
24
package.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
58
src/app.js
Normal file
58
src/app.js
Normal file
|
|
@ -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;
|
||||
18
src/cooldowns.js
Normal file
18
src/cooldowns.js
Normal file
|
|
@ -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 };
|
||||
252
src/db.js
Normal file
252
src/db.js
Normal file
|
|
@ -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,
|
||||
};
|
||||
37
src/dispatch.js
Normal file
37
src/dispatch.js
Normal file
|
|
@ -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 };
|
||||
118
src/eventsub.js
Normal file
118
src/eventsub.js
Normal file
|
|
@ -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 };
|
||||
45
src/routers/actions.js
Normal file
45
src/routers/actions.js
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const db = require('../db');
|
||||
const dispatch = require('../dispatch');
|
||||
const { resetCooldown } = require('../cooldowns');
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
const actions = db.getAllActions();
|
||||
const media = db.getAllMedia();
|
||||
res.render('actions', { actions, media });
|
||||
});
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
const { name, event_type, event_detail, action_type, media_file_id, alert_text, cooldown_seconds } = req.body;
|
||||
db.createAction({
|
||||
name,
|
||||
event_type,
|
||||
event_detail: event_detail || null,
|
||||
action_type,
|
||||
media_file_id: media_file_id ? parseInt(media_file_id) : null,
|
||||
alert_text: alert_text || null,
|
||||
cooldown_seconds: parseInt(cooldown_seconds) || 0,
|
||||
});
|
||||
res.redirect('/actions');
|
||||
});
|
||||
|
||||
router.post('/:id/test', (req, res) => {
|
||||
const action = db.getAction(parseInt(req.params.id));
|
||||
if (!action) return res.status(404).send('Not found');
|
||||
resetCooldown(action.id);
|
||||
dispatch.dispatchEvent(action.event_type, action.event_detail, 'test');
|
||||
res.redirect('/actions');
|
||||
});
|
||||
|
||||
router.post('/:id/toggle', (req, res) => {
|
||||
db.toggleAction(parseInt(req.params.id));
|
||||
res.redirect('/actions');
|
||||
});
|
||||
|
||||
router.post('/:id/delete', (req, res) => {
|
||||
db.deleteAction(parseInt(req.params.id));
|
||||
res.redirect('/actions');
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
101
src/routers/auth.js
Normal file
101
src/routers/auth.js
Normal file
|
|
@ -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;
|
||||
11
src/routers/dashboard.js
Normal file
11
src/routers/dashboard.js
Normal file
|
|
@ -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;
|
||||
29
src/routers/layout.js
Normal file
29
src/routers/layout.js
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const db = require('../db');
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
res.render('layout_editor', { layout: db.getLayout(), settings: db.getSettings() });
|
||||
});
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
const b = req.body;
|
||||
db.updateLayout({
|
||||
chat_font_size: parseInt(b.chat_font_size) || 15,
|
||||
chat_font_family: b.chat_font_family || 'Inter, sans-serif',
|
||||
chat_bg_opacity: parseFloat(b.chat_bg_opacity) || 0.45,
|
||||
chat_text_color: b.chat_text_color || '#ffffff',
|
||||
chat_border_radius: parseInt(b.chat_border_radius) || 8,
|
||||
alert_font_size: parseInt(b.alert_font_size) || 32,
|
||||
alert_bg_opacity: parseFloat(b.alert_bg_opacity) || 0.7,
|
||||
alert_text_color: b.alert_text_color || '#ffffff',
|
||||
});
|
||||
res.redirect('/layout');
|
||||
});
|
||||
|
||||
router.post('/positions', (req, res) => {
|
||||
db.updateLayoutPositions(req.body);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
42
src/routers/media.js
Normal file
42
src/routers/media.js
Normal file
|
|
@ -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;
|
||||
18
src/routers/overlay.js
Normal file
18
src/routers/overlay.js
Normal file
|
|
@ -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;
|
||||
40
src/routers/settings.js
Normal file
40
src/routers/settings.js
Normal file
|
|
@ -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;
|
||||
21
src/server.js
Normal file
21
src/server.js
Normal file
|
|
@ -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}`);
|
||||
});
|
||||
26
src/ws.js
Normal file
26
src/ws.js
Normal file
|
|
@ -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 };
|
||||
|
|
@ -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); }
|
||||
}
|
||||
|
|
@ -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); }
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
{% extends "base.html" %}
|
||||
{% block title %}Actions — HeyStreamer{% endblock %}
|
||||
{% block content %}
|
||||
<hgroup>
|
||||
<h1>Actions</h1>
|
||||
<p>Configure what happens when each event fires.</p>
|
||||
</hgroup>
|
||||
|
||||
<section>
|
||||
<h2>Add action</h2>
|
||||
<form hx-post="/actions"
|
||||
hx-target="#actions-list"
|
||||
hx-swap="beforeend"
|
||||
hx-on::after-request="this.reset()">
|
||||
<div class="form-grid">
|
||||
<label>
|
||||
Event type
|
||||
<select name="event_type" required>
|
||||
{% for et in event_types %}
|
||||
<option value="{{ et }}">{{ et }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Event detail
|
||||
<input type="text" name="event_detail" placeholder="command name / reward ID / bits min / sub tier">
|
||||
<small>Leave blank to match any. For commands: the name without !. For bits: minimum amount.</small>
|
||||
</label>
|
||||
<label>
|
||||
Action type
|
||||
<select name="action_type" required>
|
||||
{% for at in action_types %}
|
||||
<option value="{{ at }}">{{ at }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Media file <small>(for sound/video)</small>
|
||||
<select name="media_file_id">
|
||||
<option value="">— none —</option>
|
||||
{% for f in media_files %}
|
||||
<option value="{{ f.id }}">[{{ f.file_type }}] {{ f.original_name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Alert text <small>(shown on screen)</small>
|
||||
<input type="text" name="alert_text" placeholder="e.g. {{ '{{username}} just subscribed!' }}">
|
||||
</label>
|
||||
<label>
|
||||
Cooldown (seconds)
|
||||
<input type="number" name="cooldown_seconds" value="0" min="0">
|
||||
</label>
|
||||
</div>
|
||||
<button type="submit">Add action</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Configured actions</h2>
|
||||
<div id="actions-list">
|
||||
{% for action in actions %}
|
||||
{% set _ = namespace(media_files=media_files) %}
|
||||
{% include "partials/action_row.html" %}
|
||||
{% endfor %}
|
||||
{% if not actions %}
|
||||
<p><em>No actions configured yet.</em></p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}HeyStreamer{% endblock %}</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2.0.6/css/pico.min.css">
|
||||
<script src="https://unpkg.com/htmx.org@2.0.3/dist/htmx.min.js"></script>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="container-fluid">
|
||||
<nav>
|
||||
<ul>
|
||||
<li><strong><a href="/" class="contrast">HeyStreamer</a></strong></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="/">Dashboard</a></li>
|
||||
<li><a href="/actions">Actions</a></li>
|
||||
<li><a href="/media">Media</a></li>
|
||||
<li><a href="/layout">Layout</a></li>
|
||||
<li><a href="/settings">Settings</a></li>
|
||||
<li><a href="/auth/logout" class="secondary">Logout</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
</header>
|
||||
<main class="container">
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
{% extends "base.html" %}
|
||||
{% block title %}Dashboard — HeyStreamer{% endblock %}
|
||||
{% block content %}
|
||||
<hgroup>
|
||||
<h1>Dashboard</h1>
|
||||
<p>Welcome, {{ user.twitch_display_name }}</p>
|
||||
</hgroup>
|
||||
|
||||
<div class="status-bar">
|
||||
<span class="status-dot {% if eventsub_connected %}connected{% else %}disconnected{% endif %}"></span>
|
||||
EventSub: <strong>{% if eventsub_connected %}connected{% else %}disconnected{% endif %}</strong>
|
||||
{% if not eventsub_connected %}
|
||||
<form method="post" action="/settings/reconnect" style="display:inline">
|
||||
<button type="submit" class="outline small-btn">Reconnect</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h2>Recent activity</h2>
|
||||
{% if logs %}
|
||||
<figure>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Time</th>
|
||||
<th>Event</th>
|
||||
<th>User</th>
|
||||
<th>Detail</th>
|
||||
<th>Action taken</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for log in logs %}
|
||||
<tr>
|
||||
<td><small>{{ log.triggered_at.strftime('%H:%M:%S') }}</small></td>
|
||||
<td><code>{{ log.event_type }}</code></td>
|
||||
<td>{{ log.username or '—' }}</td>
|
||||
<td>{{ log.detail or '—' }}</td>
|
||||
<td>{{ log.action_taken or '<span class="muted">none configured</span>' | safe }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</figure>
|
||||
{% else %}
|
||||
<p><em>No activity yet. Events will appear here as they come in.</em></p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
|
@ -1,200 +0,0 @@
|
|||
{% extends "base.html" %}
|
||||
{% block title %}Layout Editor — HeyStreamer{% endblock %}
|
||||
{% block content %}
|
||||
<hgroup>
|
||||
<h1>Layout Editor</h1>
|
||||
<p>Drag handles to reposition. Resize chat from the bottom-right corner. Changes to styles preview live.</p>
|
||||
</hgroup>
|
||||
|
||||
{% if saved %}
|
||||
<div class="notice-success">Styles saved. Refresh your OBS browser source to apply.</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="editor-wrap" id="editor-wrap">
|
||||
<iframe id="preview-frame"
|
||||
src="/overlay/preview"
|
||||
scrolling="no"
|
||||
style="position:absolute;top:0;left:0;width:100%;height:100%;border:none;pointer-events:none;">
|
||||
</iframe>
|
||||
|
||||
<div class="drag-handle handle-chat"
|
||||
id="handle-chat"
|
||||
data-target="chat"
|
||||
data-left="{{ layout.chat_left }}"
|
||||
data-top="{{ layout.chat_top }}"
|
||||
data-width="{{ layout.chat_width }}"
|
||||
data-height="{{ layout.chat_height }}"
|
||||
style="left:{{ layout.chat_left }}%;top:{{ layout.chat_top }}%;width:{{ layout.chat_width }}%;height:{{ layout.chat_height }}%">
|
||||
<div class="handle-label">Chat</div>
|
||||
<div class="resize-corner"></div>
|
||||
</div>
|
||||
|
||||
<div class="drag-handle handle-alert"
|
||||
id="handle-alert"
|
||||
data-target="alert"
|
||||
data-left="{{ layout.alert_left }}"
|
||||
data-top="{{ layout.alert_top }}"
|
||||
style="left:{{ layout.alert_left }}%;top:{{ layout.alert_top }}%;transform:translate(-50%,-50%)">
|
||||
<div class="handle-label">Alert</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="canvas-footer">
|
||||
<small class="muted">Positions save on drag end. Refresh OBS browser source after repositioning.</small>
|
||||
<button type="button" id="preview-alert-btn" class="outline small-btn">▶ Preview alert</button>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/layout" class="style-form">
|
||||
<div class="props-grid">
|
||||
<fieldset>
|
||||
<legend><strong>Chat</strong></legend>
|
||||
<div class="props-row">
|
||||
<label>
|
||||
Font size (px)
|
||||
<input type="number" name="chat_font_size" value="{{ layout.chat_font_size }}" min="8" max="48">
|
||||
</label>
|
||||
<label>
|
||||
BG opacity
|
||||
<input type="range" name="chat_bg_opacity" value="{{ layout.chat_bg_opacity }}"
|
||||
min="0" max="1" step="0.05"
|
||||
oninput="this.nextElementSibling.textContent = (+this.value).toFixed(2)">
|
||||
<span>{{ layout.chat_bg_opacity }}</span>
|
||||
</label>
|
||||
<label>
|
||||
Text color
|
||||
<input type="color" name="chat_text_color" value="{{ layout.chat_text_color }}">
|
||||
</label>
|
||||
<label>
|
||||
Max messages
|
||||
<input type="number" name="chat_max_messages" value="{{ layout.chat_max_messages }}" min="1" max="50">
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend><strong>Alert</strong></legend>
|
||||
<div class="props-row">
|
||||
<label>
|
||||
Font size (px)
|
||||
<input type="number" name="alert_font_size" value="{{ layout.alert_font_size }}" min="8" max="72">
|
||||
</label>
|
||||
<label>
|
||||
BG opacity
|
||||
<input type="range" name="alert_bg_opacity" value="{{ layout.alert_bg_opacity }}"
|
||||
min="0" max="1" step="0.05"
|
||||
oninput="this.nextElementSibling.textContent = (+this.value).toFixed(2)">
|
||||
<span>{{ layout.alert_bg_opacity }}</span>
|
||||
</label>
|
||||
<label>
|
||||
Text color
|
||||
<input type="color" name="alert_text_color" value="{{ layout.alert_text_color }}">
|
||||
</label>
|
||||
<label>
|
||||
Duration (sec)
|
||||
<input type="number" name="alert_duration" value="{{ layout.alert_duration }}" min="1" max="30">
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<button type="submit">Save styles</button>
|
||||
</form>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/interactjs@1.10.27/dist/interact.min.js"></script>
|
||||
<script>
|
||||
const wrap = document.getElementById('editor-wrap');
|
||||
const iframe = document.getElementById('preview-frame');
|
||||
|
||||
function iframeDoc() { return iframe.contentDocument || iframe.contentWindow?.document; }
|
||||
|
||||
function iframeVar(cssVar, value) {
|
||||
const doc = iframeDoc();
|
||||
if (doc) doc.documentElement.style.setProperty(cssVar, value);
|
||||
}
|
||||
|
||||
// ── Live style preview ────────────────────────────────────────────────────
|
||||
function bind(name, cssVar, transform = v => v) {
|
||||
const el = document.querySelector(`[name="${name}"]`);
|
||||
if (!el) return;
|
||||
el.addEventListener('input', () => iframeVar(cssVar, transform(el.value)));
|
||||
}
|
||||
|
||||
bind('chat_font_size', '--chat-font-size', v => v + 'px');
|
||||
bind('chat_bg_opacity', '--chat-bg-opacity');
|
||||
bind('chat_text_color', '--chat-text-color');
|
||||
bind('alert_font_size', '--alert-font-size', v => v + 'px');
|
||||
bind('alert_bg_opacity', '--alert-bg-opacity');
|
||||
bind('alert_text_color', '--alert-text-color');
|
||||
|
||||
// ── Preview alert button ──────────────────────────────────────────────────
|
||||
document.getElementById('preview-alert-btn').addEventListener('click', () => {
|
||||
iframe.contentWindow?.postMessage({ type: 'preview-alert' }, '*');
|
||||
});
|
||||
|
||||
// ── Drag ──────────────────────────────────────────────────────────────────
|
||||
interact('.drag-handle').draggable({
|
||||
listeners: {
|
||||
move(event) {
|
||||
const el = event.target;
|
||||
const ww = wrap.offsetWidth;
|
||||
const wh = wrap.offsetHeight;
|
||||
let left = parseFloat(el.dataset.left || 0);
|
||||
let top = parseFloat(el.dataset.top || 0);
|
||||
left = Math.max(0, Math.min(95, left + event.dx / ww * 100));
|
||||
top = Math.max(0, Math.min(95, top + event.dy / wh * 100));
|
||||
el.style.left = left + '%';
|
||||
el.style.top = top + '%';
|
||||
el.dataset.left = left;
|
||||
el.dataset.top = top;
|
||||
const t = el.dataset.target;
|
||||
iframeVar(`--${t}-left`, left + '%');
|
||||
iframeVar(`--${t}-top`, top + '%');
|
||||
},
|
||||
end(event) {
|
||||
const el = event.target;
|
||||
savePos(el.dataset.target,
|
||||
parseFloat(el.dataset.left),
|
||||
parseFloat(el.dataset.top),
|
||||
parseFloat(el.dataset.width || 0),
|
||||
parseFloat(el.dataset.height || 0));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ── Resize (chat only) ────────────────────────────────────────────────────
|
||||
interact('#handle-chat').resizable({
|
||||
edges: { right: true, bottom: true },
|
||||
modifiers: [interact.modifiers.restrictSize({ min: { width: 30, height: 30 } })],
|
||||
listeners: {
|
||||
move(event) {
|
||||
const el = event.target;
|
||||
const ww = wrap.offsetWidth;
|
||||
const wh = wrap.offsetHeight;
|
||||
const w = Math.max(5, Math.min(100, event.rect.width / ww * 100));
|
||||
const h = Math.max(5, Math.min(100, event.rect.height / wh * 100));
|
||||
el.style.width = w + '%';
|
||||
el.style.height = h + '%';
|
||||
el.dataset.width = w;
|
||||
el.dataset.height = h;
|
||||
iframeVar('--chat-width', w + '%');
|
||||
iframeVar('--chat-height', h + '%');
|
||||
},
|
||||
end(event) {
|
||||
const el = event.target;
|
||||
savePos('chat',
|
||||
parseFloat(el.dataset.left),
|
||||
parseFloat(el.dataset.top),
|
||||
parseFloat(el.dataset.width),
|
||||
parseFloat(el.dataset.height));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function savePos(target, left, top, width, height) {
|
||||
await fetch('/layout/positions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ widget: target, left, top, width, height })
|
||||
});
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Login — HeyStreamer</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2.0.6/css/pico.min.css">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<main class="container login-page">
|
||||
<article class="login-card">
|
||||
<h1>HeyStreamer</h1>
|
||||
<p>Twitch stream event platform.</p>
|
||||
<a href="/auth/twitch" role="button" class="twitch-btn">Login with Twitch</a>
|
||||
</article>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
{% extends "base.html" %}
|
||||
{% block title %}Media — HeyStreamer{% endblock %}
|
||||
{% block content %}
|
||||
<hgroup>
|
||||
<h1>Media</h1>
|
||||
<p>Upload sounds and videos for your actions.</p>
|
||||
</hgroup>
|
||||
|
||||
<section>
|
||||
<h2>Upload</h2>
|
||||
<form hx-post="/media"
|
||||
hx-target="#media-list"
|
||||
hx-swap="beforeend"
|
||||
hx-encoding="multipart/form-data"
|
||||
hx-on::after-request="this.reset()">
|
||||
<label>
|
||||
File <small>(mp3, ogg, wav, m4a, mp4, webm)</small>
|
||||
<input type="file" name="file" accept="audio/*,video/*" required>
|
||||
</label>
|
||||
<button type="submit">Upload</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Library</h2>
|
||||
<div id="media-list" class="media-grid">
|
||||
{% for file in files %}
|
||||
{% include "partials/media_item.html" %}
|
||||
{% endfor %}
|
||||
{% if not files %}
|
||||
<p><em>No files uploaded yet.</em></p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
|
@ -1,162 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Overlay</title>
|
||||
<link rel="stylesheet" href="/static/overlay.css">
|
||||
{% if custom_css %}<style>{{ custom_css | safe }}</style>{% endif %}
|
||||
<style>
|
||||
:root {
|
||||
--chat-left: {{ layout.chat_left }}%;
|
||||
--chat-top: {{ layout.chat_top }}%;
|
||||
--chat-width: {{ layout.chat_width }}%;
|
||||
--chat-height: {{ layout.chat_height }}%;
|
||||
--chat-font-size: {{ layout.chat_font_size }}px;
|
||||
--chat-bg-opacity: {{ layout.chat_bg_opacity }};
|
||||
--chat-text-color: {{ layout.chat_text_color }};
|
||||
--alert-left: {{ layout.alert_left }}%;
|
||||
--alert-top: {{ layout.alert_top }}%;
|
||||
--alert-font-size: {{ layout.alert_font_size }}px;
|
||||
--alert-bg-opacity: {{ layout.alert_bg_opacity }};
|
||||
--alert-text-color: {{ layout.alert_text_color }};
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="alert-video-wrap" style="display:none">
|
||||
<video id="alert-video" playsinline></video>
|
||||
</div>
|
||||
<div id="alert" style="display:none"></div>
|
||||
<div id="chat"></div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/tmi.js@1.8.5/build/tmi.min.js"></script>
|
||||
<script>
|
||||
const CHANNEL = {{ channel | tojson }};
|
||||
const GAP_SIL = {{ gap_silence }};
|
||||
const GAP_VOL = {{ gap_scale_end }};
|
||||
const GAP_PITCH = {{ gap_pitch_end }};
|
||||
const MAX_MSG = {{ layout.chat_max_messages }};
|
||||
const ALERT_DURATION = {{ layout.alert_duration * 1000 }};
|
||||
|
||||
let lastMsgTime = Date.now();
|
||||
let alertQueue = [];
|
||||
let alertBusy = false;
|
||||
|
||||
// ── WebSocket to backend ──────────────────────────────────────────────
|
||||
let ws;
|
||||
function connectWS() {
|
||||
ws = new WebSocket(`ws://${location.host}/ws/overlay`);
|
||||
ws.onmessage = e => {
|
||||
const msg = JSON.parse(e.data);
|
||||
if (msg.type === 'execute') {
|
||||
document.dispatchEvent(new CustomEvent(
|
||||
`heystreamer:${msg.event_type || 'event'}`,
|
||||
{ detail: msg }
|
||||
));
|
||||
enqueueAlert(msg);
|
||||
}
|
||||
};
|
||||
ws.onclose = () => setTimeout(connectWS, 3000);
|
||||
}
|
||||
connectWS();
|
||||
|
||||
// ── Gap audio (Web Audio API — no file needed) ────────────────────────
|
||||
function playGapBeep(gapSec) {
|
||||
if (gapSec < GAP_SIL) return;
|
||||
const vol = Math.min(1, (gapSec - GAP_SIL) / Math.max(1, GAP_VOL - GAP_SIL));
|
||||
const pitch = 1 + Math.min(1, Math.max(0, (gapSec - GAP_VOL) / Math.max(1, GAP_PITCH - GAP_VOL)));
|
||||
const ctx = new AudioContext();
|
||||
const osc = ctx.createOscillator();
|
||||
const gain = ctx.createGain();
|
||||
osc.connect(gain);
|
||||
gain.connect(ctx.destination);
|
||||
osc.frequency.value = 440 * pitch;
|
||||
gain.gain.value = vol * 0.35;
|
||||
osc.start();
|
||||
osc.stop(ctx.currentTime + 0.25);
|
||||
setTimeout(() => ctx.close(), 500);
|
||||
}
|
||||
|
||||
// ── tmi.js chat ───────────────────────────────────────────────────────
|
||||
const client = new tmi.Client({ channels: [CHANNEL] });
|
||||
client.connect().catch(console.error);
|
||||
|
||||
client.on('message', (channel, tags, message, self) => {
|
||||
const now = Date.now();
|
||||
playGapBeep((now - lastMsgTime) / 1000);
|
||||
lastMsgTime = now;
|
||||
|
||||
addChatMsg(tags['display-name'] || tags.username, message, tags.color);
|
||||
|
||||
if (message.startsWith('!') && ws.readyState === WebSocket.OPEN) {
|
||||
const name = message.split(' ')[0].slice(1).toLowerCase();
|
||||
if (name) ws.send(JSON.stringify({ type: 'command', name, user: tags['display-name'] || tags.username }));
|
||||
}
|
||||
});
|
||||
|
||||
// ── Chat display ──────────────────────────────────────────────────────
|
||||
const chatEl = document.getElementById('chat');
|
||||
|
||||
function addChatMsg(username, message, color) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'chat-msg';
|
||||
el.innerHTML = `<span class="uname" style="color:${color || '#9b59b6'}">${esc(username)}</span>: ${esc(message)}`;
|
||||
chatEl.appendChild(el);
|
||||
while (chatEl.children.length > MAX_MSG) chatEl.firstChild.remove();
|
||||
}
|
||||
|
||||
function esc(s) {
|
||||
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||
}
|
||||
|
||||
// ── Alert queue ───────────────────────────────────────────────────────
|
||||
function enqueueAlert(msg) {
|
||||
alertQueue.push(msg);
|
||||
if (!alertBusy) nextAlert();
|
||||
}
|
||||
|
||||
function nextAlert() {
|
||||
if (!alertQueue.length) { alertBusy = false; return; }
|
||||
alertBusy = true;
|
||||
playAlert(alertQueue.shift());
|
||||
}
|
||||
|
||||
function playAlert(msg) {
|
||||
const alertEl = document.getElementById('alert');
|
||||
const videoWrap = document.getElementById('alert-video-wrap');
|
||||
const videoEl = document.getElementById('alert-video');
|
||||
|
||||
if (msg.alert_text) {
|
||||
alertEl.textContent = msg.alert_text;
|
||||
alertEl.style.display = 'block';
|
||||
}
|
||||
|
||||
if (msg.action_type === 'sound' && msg.media_url) {
|
||||
new Audio(msg.media_url).play().catch(() => {});
|
||||
}
|
||||
|
||||
if (msg.action_type === 'video' && msg.media_url) {
|
||||
videoEl.src = msg.media_url;
|
||||
videoWrap.style.display = 'block';
|
||||
videoEl.play().catch(() => {});
|
||||
videoEl.onended = () => {
|
||||
videoWrap.style.display = 'none';
|
||||
videoEl.src = '';
|
||||
alertEl.style.display = 'none';
|
||||
alertEl.textContent = '';
|
||||
nextAlert();
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
alertEl.style.display = 'none';
|
||||
alertEl.textContent = '';
|
||||
nextAlert();
|
||||
}, ALERT_DURATION);
|
||||
}
|
||||
</script>
|
||||
{% if custom_js %}<script>{{ custom_js | safe }}</script>{% endif %}
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="stylesheet" href="/static/overlay.css">
|
||||
{% if custom_css %}<style>{{ custom_css | safe }}</style>{% endif %}
|
||||
<style>
|
||||
:root {
|
||||
--chat-left: {{ layout.chat_left }}%;
|
||||
--chat-top: {{ layout.chat_top }}%;
|
||||
--chat-width: {{ layout.chat_width }}%;
|
||||
--chat-height: {{ layout.chat_height }}%;
|
||||
--chat-font-size: {{ layout.chat_font_size }}px;
|
||||
--chat-bg-opacity: {{ layout.chat_bg_opacity }};
|
||||
--chat-text-color: {{ layout.chat_text_color }};
|
||||
--alert-left: {{ layout.alert_left }}%;
|
||||
--alert-top: {{ layout.alert_top }}%;
|
||||
--alert-font-size: {{ layout.alert_font_size }}px;
|
||||
--alert-bg-opacity: {{ layout.alert_bg_opacity }};
|
||||
--alert-text-color: {{ layout.alert_text_color }};
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="alert" style="display:none"></div>
|
||||
<div id="alert-video-wrap" style="display:none"><video id="alert-video" playsinline></video></div>
|
||||
<div id="chat">
|
||||
<div class="chat-msg"><span class="uname" style="color:#9b59b6">StreamFriend</span>: Let's goooo! 🎉</div>
|
||||
<div class="chat-msg"><span class="uname" style="color:#e74c3c">Viewer42</span>: PogChamp PogChamp</div>
|
||||
<div class="chat-msg"><span class="uname" style="color:#2ecc71">ChatUser</span>: great stream today!</div>
|
||||
<div class="chat-msg"><span class="uname" style="color:#f39c12">AnotherFan</span>: !airhorn</div>
|
||||
<div class="chat-msg"><span class="uname" style="color:#3498db">NewViewer</span>: first time here!</div>
|
||||
</div>
|
||||
<script>
|
||||
const ALERT_DURATION = {{ alert_duration_ms }};
|
||||
let alertTimer = null;
|
||||
|
||||
function showMockAlert(text) {
|
||||
const el = document.getElementById('alert');
|
||||
el.style.display = 'none';
|
||||
void el.offsetWidth;
|
||||
el.textContent = text || 'StreamFan just subscribed! 🎉';
|
||||
el.style.display = 'block';
|
||||
if (alertTimer) clearTimeout(alertTimer);
|
||||
alertTimer = setTimeout(() => { el.style.display = 'none'; }, ALERT_DURATION);
|
||||
}
|
||||
|
||||
window.addEventListener('message', (e) => {
|
||||
if (e.data?.type === 'preview-alert') showMockAlert(e.data.text);
|
||||
});
|
||||
</script>
|
||||
{% if custom_js %}<script>{{ custom_js | safe }}</script>{% endif %}
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
<div class="action-row" id="action-{{ action.id }}">
|
||||
<div class="action-info">
|
||||
<code>{{ action.event_type }}{% if action.event_detail %}:{{ action.event_detail }}{% endif %}</code>
|
||||
→
|
||||
<strong>{{ action.action_type }}</strong>
|
||||
{% if action.media_file %}
|
||||
<span class="muted">{{ action.media_file.original_name }}</span>
|
||||
{% endif %}
|
||||
{% if action.alert_text %}
|
||||
<span class="muted">"{{ action.alert_text }}"</span>
|
||||
{% endif %}
|
||||
{% if action.cooldown_seconds %}
|
||||
<small class="muted">{{ action.cooldown_seconds }}s cooldown</small>
|
||||
{% endif %}
|
||||
{% if just_tested %}
|
||||
<span class="tested-badge">✓ fired</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="action-controls">
|
||||
<form hx-post="/actions/{{ action.id }}/test"
|
||||
hx-target="#action-{{ action.id }}"
|
||||
hx-swap="outerHTML"
|
||||
style="display:inline">
|
||||
<button type="submit" class="outline small-btn">Test</button>
|
||||
</form>
|
||||
<form hx-post="/actions/{{ action.id }}/toggle"
|
||||
hx-target="#action-{{ action.id }}"
|
||||
hx-swap="outerHTML"
|
||||
style="display:inline">
|
||||
<button type="submit" class="outline small-btn {% if not action.enabled %}secondary{% endif %}">
|
||||
{{ 'on' if action.enabled else 'off' }}
|
||||
</button>
|
||||
</form>
|
||||
<button hx-delete="/actions/{{ action.id }}"
|
||||
hx-target="#action-{{ action.id }}"
|
||||
hx-swap="outerHTML"
|
||||
hx-confirm="Delete this action?"
|
||||
class="outline secondary small-btn">
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
<div class="media-item" id="media-{{ file.id }}">
|
||||
<div class="media-info">
|
||||
<span class="media-type-badge {{ file.file_type }}">{{ file.file_type }}</span>
|
||||
<strong>{{ file.original_name }}</strong>
|
||||
</div>
|
||||
{% if file.file_type == "audio" %}
|
||||
<audio controls src="/static/media/{{ file.filename }}" preload="none"></audio>
|
||||
{% else %}
|
||||
<video controls src="/static/media/{{ file.filename }}" preload="none" style="max-width:200px;max-height:120px"></video>
|
||||
{% endif %}
|
||||
<button hx-delete="/media/{{ file.id }}"
|
||||
hx-target="#media-{{ file.id }}"
|
||||
hx-swap="outerHTML"
|
||||
hx-confirm="Delete {{ file.original_name }}?"
|
||||
class="outline secondary small-btn">
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
{% extends "base.html" %}
|
||||
{% block title %}Settings — HeyStreamer{% endblock %}
|
||||
{% block content %}
|
||||
<hgroup>
|
||||
<h1>Settings</h1>
|
||||
</hgroup>
|
||||
|
||||
{% if saved %}
|
||||
<div class="notice-success">Settings saved.</div>
|
||||
{% endif %}
|
||||
|
||||
<section>
|
||||
<h2>OBS browser source URL</h2>
|
||||
<p>Add this as a browser source in OBS:</p>
|
||||
<input type="text" value="{{ overlay_url }}" readonly onclick="this.select()" class="url-input">
|
||||
<small>Refresh the browser source in OBS after changing settings.</small>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<form method="post" action="/settings">
|
||||
<h2>Channel</h2>
|
||||
<label>
|
||||
Twitch channel name
|
||||
<input type="text" name="twitch_channel" value="{{ settings.twitch_channel }}" required placeholder="your_channel">
|
||||
</label>
|
||||
|
||||
<h2>Gap audio thresholds</h2>
|
||||
<p><small>A tone plays when a new message arrives after a silence. These control how the volume and pitch scale with the gap length.</small></p>
|
||||
<div class="form-grid">
|
||||
<label>
|
||||
Silence threshold (seconds)
|
||||
<input type="number" name="gap_silence_threshold" value="{{ settings.gap_silence_threshold }}" min="0">
|
||||
<small>No sound if gap is shorter than this.</small>
|
||||
</label>
|
||||
<label>
|
||||
Full volume at (seconds)
|
||||
<input type="number" name="gap_scale_end" value="{{ settings.gap_scale_end }}" min="1">
|
||||
<small>Volume reaches 100% at this gap length.</small>
|
||||
</label>
|
||||
<label>
|
||||
Max pitch at (seconds)
|
||||
<input type="number" name="gap_pitch_scale_end" value="{{ settings.gap_pitch_scale_end }}" min="1">
|
||||
<small>Pitch stops scaling up after this gap length.</small>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<h2>Custom CSS</h2>
|
||||
<p><small>Injected into the overlay after the default styles. Overrides anything. Use <code>#chat</code>, <code>.chat-msg</code>, <code>#alert</code>.</small></p>
|
||||
<textarea name="custom_css" class="code-textarea" rows="10" placeholder="/* example */ #alert { border: 2px solid #9146ff; box-shadow: 0 0 20px #9146ff; } .chat-msg { border-left: 3px solid; }">{{ settings.custom_css }}</textarea>
|
||||
|
||||
<h2>Custom JS</h2>
|
||||
<p><small>Injected after the overlay scripts. Hook into events with <code>document.addEventListener('heystreamer:sub', e => ...)</code>. Available events: <code>sub</code>, <code>gift_sub</code>, <code>bits</code>, <code>channel_points</code>, <code>command</code>, <code>follow</code>, <code>raid</code>.</small></p>
|
||||
<textarea name="custom_js" class="code-textarea" rows="10" placeholder="// example document.addEventListener('heystreamer:raid', e => { console.log('Raid from', e.detail.alert_text); });">{{ settings.custom_js }}</textarea>
|
||||
|
||||
<button type="submit">Save settings</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>EventSub</h2>
|
||||
<form method="post" action="/settings/reconnect">
|
||||
<button type="submit" class="outline">Reconnect EventSub</button>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
88
views/actions.ejs
Normal file
88
views/actions.ejs
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
<h2>Actions</h2>
|
||||
<p><small>Map Twitch events to sounds, videos, or on-screen alerts.</small></p>
|
||||
|
||||
<details>
|
||||
<summary>Add new action</summary>
|
||||
<form method="POST" action="/actions" style="margin-top:1rem;">
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
|
||||
<label>Name <input type="text" name="name" required placeholder="e.g. Sub sound"></label>
|
||||
<label>
|
||||
Event type
|
||||
<select name="event_type" required>
|
||||
<option value="sub">Sub</option>
|
||||
<option value="gift_sub">Gift sub</option>
|
||||
<option value="bits">Bits</option>
|
||||
<option value="channel_points">Channel points</option>
|
||||
<option value="command">Chat command</option>
|
||||
<option value="follow">Follow</option>
|
||||
<option value="raid">Raid</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Event detail <small>(tier / min bits / command name / reward ID)</small>
|
||||
<input type="text" name="event_detail" placeholder="Optional">
|
||||
</label>
|
||||
<label>
|
||||
Action type
|
||||
<select name="action_type" required>
|
||||
<option value="sound">Sound</option>
|
||||
<option value="video">Video</option>
|
||||
<option value="alert">Alert text</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Media file
|
||||
<select name="media_file_id">
|
||||
<option value="">— none —</option>
|
||||
<% for (const f of media) { %>
|
||||
<option value="<%= f.id %>"><%= f.original_name %> (<%= f.media_type %>)</option>
|
||||
<% } %>
|
||||
</select>
|
||||
</label>
|
||||
<label>Alert text <input type="text" name="alert_text" placeholder="{username} just subbed!"></label>
|
||||
<label>Cooldown (seconds) <input type="number" name="cooldown_seconds" value="0" min="0"></label>
|
||||
</div>
|
||||
<button type="submit">Add action</button>
|
||||
</form>
|
||||
</details>
|
||||
|
||||
<% if (actions.length === 0) { %>
|
||||
<p><em>No actions yet.</em></p>
|
||||
<% } else { %>
|
||||
<figure>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Event</th>
|
||||
<th>Detail</th>
|
||||
<th>Action</th>
|
||||
<th>Cooldown</th>
|
||||
<th>Status</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% for (const a of actions) { %>
|
||||
<tr>
|
||||
<td><%= a.name %></td>
|
||||
<td><code><%= a.event_type %></code></td>
|
||||
<td><%= a.event_detail || '—' %></td>
|
||||
<td><code><%= a.action_type %></code></td>
|
||||
<td><%= a.cooldown_seconds %>s</td>
|
||||
<td>
|
||||
<span class="badge <%= a.enabled ? 'badge-green' : 'badge-grey' %>">
|
||||
<%= a.enabled ? 'on' : 'off' %>
|
||||
</span>
|
||||
</td>
|
||||
<td style="display:flex; gap:0.5rem;">
|
||||
<form method="POST" action="/actions/<%= a.id %>/test"><button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem;">Test</button></form>
|
||||
<form method="POST" action="/actions/<%= a.id %>/toggle"><button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem;"><%= a.enabled ? 'Disable' : 'Enable' %></button></form>
|
||||
<form method="POST" action="/actions/<%= a.id %>/delete" onsubmit="return confirm('Delete this action?')"><button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem; color:#f88;">Delete</button></form>
|
||||
</td>
|
||||
</tr>
|
||||
<% } %>
|
||||
</tbody>
|
||||
</table>
|
||||
</figure>
|
||||
<% } %>
|
||||
46
views/dashboard.ejs
Normal file
46
views/dashboard.ejs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
<h2>Dashboard</h2>
|
||||
|
||||
<div style="display:flex; gap:1rem; margin-bottom:1.5rem; flex-wrap:wrap;">
|
||||
<div>
|
||||
<strong>Channel:</strong>
|
||||
<%= settings.channel || '<em>not set</em>' %>
|
||||
</div>
|
||||
<div>
|
||||
<strong>Overlay URL:</strong>
|
||||
<code><%= process.env.APP_BASE_URL %>/overlay/<%= settings.overlay_id %></code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>Recent activity</h3>
|
||||
<% if (logs.length === 0) { %>
|
||||
<p><em>No activity yet. Events will appear here once your overlay is connected and Twitch fires events.</em></p>
|
||||
<% } else { %>
|
||||
<figure>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Time</th>
|
||||
<th>Event</th>
|
||||
<th>User</th>
|
||||
<th>Detail</th>
|
||||
<th>Actions fired</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% for (const log of logs) { %>
|
||||
<tr>
|
||||
<td><small><%= log.created_at %></small></td>
|
||||
<td><code><%= log.event_type %></code></td>
|
||||
<td><%= log.username || '—' %></td>
|
||||
<td><%= log.event_detail || '—' %></td>
|
||||
<td>
|
||||
<span class="badge <%= log.actions_fired > 0 ? 'badge-green' : 'badge-grey' %>">
|
||||
<%= log.actions_fired %>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<% } %>
|
||||
</tbody>
|
||||
</table>
|
||||
</figure>
|
||||
<% } %>
|
||||
38
views/layout.ejs
Normal file
38
views/layout.ejs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>HeyStreamer</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
|
||||
<style>
|
||||
nav.container-fluid { padding-block: 0.5rem; }
|
||||
.nav-brand { font-weight: 700; font-size: 1.1rem; text-decoration: none; color: inherit; }
|
||||
nav ul li a { font-size: 0.9rem; }
|
||||
.badge { display: inline-block; padding: 0.15em 0.5em; border-radius: 999px; font-size: 0.75rem; font-weight: 600; }
|
||||
.badge-green { background: #1a7a1a; color: #a8f0a8; }
|
||||
.badge-red { background: #7a1a1a; color: #f0a8a8; }
|
||||
.badge-grey { background: #333; color: #aaa; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="container-fluid">
|
||||
<ul>
|
||||
<li><a class="nav-brand" href="/">HeyStreamer</a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li><a href="/">Dashboard</a></li>
|
||||
<li><a href="/actions">Actions</a></li>
|
||||
<li><a href="/media">Media</a></li>
|
||||
<li><a href="/layout">Layout</a></li>
|
||||
<li><a href="/settings">Settings</a></li>
|
||||
<% if (locals.user) { %>
|
||||
<li><a href="/auth/logout">Logout (<%= user.login %>)</a></li>
|
||||
<% } %>
|
||||
</ul>
|
||||
</nav>
|
||||
<main class="container">
|
||||
<%- body %>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
91
views/layout_editor.ejs
Normal file
91
views/layout_editor.ejs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
<h2>Layout editor</h2>
|
||||
<p><small>Drag the handles in the preview to reposition widgets. Use the form below to adjust style.</small></p>
|
||||
|
||||
<div style="position:relative; width:100%; padding-bottom:56.25%; border:1px solid #333; border-radius:8px; overflow:hidden; margin-bottom:1.5rem;">
|
||||
<iframe
|
||||
id="preview"
|
||||
src="/overlay/<%= settings.overlay_id %>/preview"
|
||||
style="position:absolute; top:0; left:0; width:1920px; height:1080px; border:none; transform-origin:top left;"
|
||||
scrolling="no"
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="/layout">
|
||||
<h3>Chat style</h3>
|
||||
<div style="display:grid; grid-template-columns:repeat(3,1fr); gap:1rem;">
|
||||
<label>Font size (px) <input type="number" name="chat_font_size" value="<%= layout.chat_font_size %>" min="8" max="64"></label>
|
||||
<label>Font family <input type="text" name="chat_font_family" value="<%= layout.chat_font_family %>"></label>
|
||||
<label>Text colour <input type="color" name="chat_text_color" value="<%= layout.chat_text_color %>"></label>
|
||||
<label>Background opacity (0–1) <input type="number" name="chat_bg_opacity" value="<%= layout.chat_bg_opacity %>" min="0" max="1" step="0.05"></label>
|
||||
<label>Border radius (px) <input type="number" name="chat_border_radius" value="<%= layout.chat_border_radius %>" min="0" max="32"></label>
|
||||
</div>
|
||||
|
||||
<h3>Alert style</h3>
|
||||
<div style="display:grid; grid-template-columns:repeat(3,1fr); gap:1rem;">
|
||||
<label>Font size (px) <input type="number" name="alert_font_size" value="<%= layout.alert_font_size %>" min="12" max="96"></label>
|
||||
<label>Text colour <input type="color" name="alert_text_color" value="<%= layout.alert_text_color %>"></label>
|
||||
<label>Background opacity (0–1) <input type="number" name="alert_bg_opacity" value="<%= layout.alert_bg_opacity %>" min="0" max="1" step="0.05"></label>
|
||||
</div>
|
||||
|
||||
<button type="submit">Save style</button>
|
||||
</form>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/interact.js@1.10.27/dist/interact.min.js"></script>
|
||||
<script>
|
||||
const iframe = document.getElementById('preview');
|
||||
|
||||
function applyScale() {
|
||||
const scale = iframe.parentElement.offsetWidth / 1920;
|
||||
iframe.style.transform = `scale(${scale})`;
|
||||
}
|
||||
applyScale();
|
||||
window.addEventListener('resize', applyScale);
|
||||
|
||||
iframe.addEventListener('load', () => {
|
||||
const iDoc = iframe.contentDocument;
|
||||
const scale = iframe.parentElement.offsetWidth / 1920;
|
||||
|
||||
['chat', 'alert'].forEach(widget => {
|
||||
const handle = iDoc.getElementById(`${widget}-handle`);
|
||||
if (!handle) return;
|
||||
|
||||
interact(handle).draggable({
|
||||
listeners: {
|
||||
move(event) {
|
||||
const rect = iDoc.documentElement;
|
||||
const x = parseFloat(getComputedStyle(handle).left) + event.dx / scale;
|
||||
const y = parseFloat(getComputedStyle(handle).top) + event.dy / scale;
|
||||
const left = Math.max(0, Math.min(x / 1920 * 100, 95));
|
||||
const top = Math.max(0, Math.min(y / 1080 * 100, 95));
|
||||
|
||||
if (widget === 'chat') {
|
||||
iDoc.documentElement.style.setProperty('--chat-left', `${left}%`);
|
||||
iDoc.documentElement.style.setProperty('--chat-top', `${top}%`);
|
||||
} else {
|
||||
iDoc.documentElement.style.setProperty('--alert-left', `${left}%`);
|
||||
iDoc.documentElement.style.setProperty('--alert-top', `${top}%`);
|
||||
}
|
||||
},
|
||||
end() { savePositions(); }
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function savePositions() {
|
||||
const iDoc = iframe.contentDocument;
|
||||
const get = (v) => parseFloat(getComputedStyle(iDoc.documentElement).getPropertyValue(v));
|
||||
fetch('/layout/positions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
chat_left: get('--chat-left') || <%= layout.chat_left %>,
|
||||
chat_top: get('--chat-top') || <%= layout.chat_top %>,
|
||||
chat_width: <%= layout.chat_width %>,
|
||||
chat_height: <%= layout.chat_height %>,
|
||||
alert_left: get('--alert-left') || <%= layout.alert_left %>,
|
||||
alert_top: get('--alert-top') || <%= layout.alert_top %>,
|
||||
}),
|
||||
});
|
||||
}
|
||||
</script>
|
||||
33
views/login.ejs
Normal file
33
views/login.ejs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>HeyStreamer — Login</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
|
||||
<style>
|
||||
body { display: flex; align-items: center; justify-content: center; min-height: 100vh; }
|
||||
.login-box { width: 100%; max-width: 380px; text-align: center; }
|
||||
.login-box h1 { margin-bottom: 0.25rem; }
|
||||
.login-box p { color: var(--pico-muted-color); margin-bottom: 2rem; }
|
||||
.twitch-btn {
|
||||
display: inline-flex; align-items: center; gap: 0.5rem;
|
||||
background: #9146ff; color: #fff; border: none;
|
||||
padding: 0.75rem 1.5rem; border-radius: 6px;
|
||||
font-size: 1rem; font-weight: 600; cursor: pointer;
|
||||
text-decoration: none;
|
||||
}
|
||||
.twitch-btn:hover { background: #7c2ff5; color: #fff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-box">
|
||||
<h1>HeyStreamer</h1>
|
||||
<p>Self-hosted Twitch stream overlay</p>
|
||||
<a class="twitch-btn" href="/auth/twitch">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M11.571 4.714h1.715v5.143H11.57zm4.715 0H18v5.143h-1.714zM6 0L1.714 4.286v15.428h5.143V24l4.286-4.286h3.428L22.286 12V0zm14.571 11.143l-3.428 3.428h-3.429l-3 3v-3H6.857V1.714h13.714z"/></svg>
|
||||
Login with Twitch
|
||||
</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
53
views/media.ejs
Normal file
53
views/media.ejs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
<h2>Media library</h2>
|
||||
<p><small>Upload audio (MP3, WAV, OGG) or video (MP4, WebM) files to use in actions. Max 50 MB.</small></p>
|
||||
|
||||
<form method="POST" action="/media/upload" enctype="multipart/form-data">
|
||||
<div style="display:flex; gap:1rem; align-items:flex-end;">
|
||||
<label style="flex:1;">
|
||||
File
|
||||
<input type="file" name="file" accept="audio/*,video/*" required>
|
||||
</label>
|
||||
<button type="submit">Upload</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<% if (files.length === 0) { %>
|
||||
<p><em>No files uploaded yet.</em></p>
|
||||
<% } else { %>
|
||||
<figure>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Size</th>
|
||||
<th>Uploaded</th>
|
||||
<th>Preview</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% for (const f of files) { %>
|
||||
<tr>
|
||||
<td><%= f.original_name %></td>
|
||||
<td><code><%= f.media_type %></code></td>
|
||||
<td><%= (f.size_bytes / 1024).toFixed(0) %> KB</td>
|
||||
<td><small><%= f.uploaded_at %></small></td>
|
||||
<td>
|
||||
<% if (f.media_type === 'audio') { %>
|
||||
<audio controls src="/media/<%= f.filename %>" style="height:28px; width:160px;"></audio>
|
||||
<% } else { %>
|
||||
<video controls src="/media/<%= f.filename %>" style="height:40px; width:80px;"></video>
|
||||
<% } %>
|
||||
</td>
|
||||
<td>
|
||||
<form method="POST" action="/media/<%= f.id %>/delete" onsubmit="return confirm('Delete this file?')">
|
||||
<button type="submit" class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem; color:#f88;">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<% } %>
|
||||
</tbody>
|
||||
</table>
|
||||
</figure>
|
||||
<% } %>
|
||||
193
views/overlay.ejs
Normal file
193
views/overlay.ejs
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
:root {
|
||||
--chat-left: <%= layout.chat_left %>%;
|
||||
--chat-top: <%= layout.chat_top %>%;
|
||||
--chat-width: <%= layout.chat_width %>%;
|
||||
--chat-height: <%= layout.chat_height %>%;
|
||||
--chat-font-size: <%= layout.chat_font_size %>px;
|
||||
--chat-font-family: <%= layout.chat_font_family %>;
|
||||
--chat-bg-opacity: <%= layout.chat_bg_opacity %>;
|
||||
--chat-text-color: <%= layout.chat_text_color %>;
|
||||
--chat-border-radius: <%= layout.chat_border_radius %>px;
|
||||
--alert-left: <%= layout.alert_left %>%;
|
||||
--alert-top: <%= layout.alert_top %>%;
|
||||
--alert-font-size: <%= layout.alert_font_size %>px;
|
||||
--alert-bg-opacity: <%= layout.alert_bg_opacity %>;
|
||||
--alert-text-color: <%= layout.alert_text_color %>;
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { background: transparent; overflow: hidden; width: 1920px; height: 1080px; }
|
||||
|
||||
#chat {
|
||||
position: fixed;
|
||||
left: var(--chat-left);
|
||||
top: var(--chat-top);
|
||||
width: var(--chat-width);
|
||||
max-height: var(--chat-height);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-family: var(--chat-font-family);
|
||||
font-size: var(--chat-font-size);
|
||||
color: var(--chat-text-color);
|
||||
}
|
||||
.chat-msg {
|
||||
background: rgba(0, 0, 0, var(--chat-bg-opacity));
|
||||
border-radius: var(--chat-border-radius);
|
||||
padding: 5px 10px;
|
||||
word-break: break-word;
|
||||
animation: fadeIn 0.25s ease;
|
||||
transition: opacity 0.5s ease;
|
||||
}
|
||||
.chat-msg .username { font-weight: 700; margin-right: 4px; }
|
||||
|
||||
#alert-box {
|
||||
position: fixed;
|
||||
left: var(--alert-left);
|
||||
top: var(--alert-top);
|
||||
transform: translate(-50%, -50%);
|
||||
font-family: var(--chat-font-family);
|
||||
font-size: var(--alert-font-size);
|
||||
color: var(--alert-text-color);
|
||||
background: rgba(0, 0, 0, var(--alert-bg-opacity));
|
||||
border-radius: 12px;
|
||||
padding: 16px 28px;
|
||||
text-align: center;
|
||||
display: none;
|
||||
}
|
||||
#alert-video {
|
||||
position: fixed;
|
||||
left: var(--alert-left);
|
||||
top: var(--alert-top);
|
||||
transform: translate(-50%, -50%);
|
||||
max-width: 640px;
|
||||
max-height: 480px;
|
||||
border-radius: 12px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(6px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
<%- settings.custom_css %>
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="chat"></div>
|
||||
<div id="alert-box"></div>
|
||||
<video id="alert-video" autoplay></video>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/tmi.js@1.8.5/build/tmi.min.js"></script>
|
||||
<script>
|
||||
const S = <%- JSON.stringify(settings) %>;
|
||||
const chat = document.getElementById('chat');
|
||||
const alertBox = document.getElementById('alert-box');
|
||||
const alertVideo = document.getElementById('alert-video');
|
||||
|
||||
let lastMsgTime = 0;
|
||||
|
||||
// --- Chat via tmi.js ---
|
||||
if (S.channel) {
|
||||
const client = new tmi.Client({ channels: [S.channel] });
|
||||
client.connect().catch(console.error);
|
||||
|
||||
client.on('message', (channel, tags, message) => {
|
||||
const now = Date.now();
|
||||
const silence = (now - lastMsgTime) / 1000;
|
||||
|
||||
if (S.gap_audio_enabled && S.gap_audio_url && lastMsgTime > 0 && silence >= S.gap_audio_min_silence) {
|
||||
const t = Math.min(
|
||||
(silence - S.gap_audio_min_silence) / Math.max(S.gap_audio_loud_after - S.gap_audio_min_silence, 1),
|
||||
1
|
||||
);
|
||||
const vol = S.gap_audio_min_volume + t * (S.gap_audio_max_volume - S.gap_audio_min_volume);
|
||||
playAudio(S.gap_audio_url, vol);
|
||||
}
|
||||
|
||||
lastMsgTime = now;
|
||||
addMessage(tags['display-name'] || tags.username, tags.color || '#b4a0d4', message);
|
||||
});
|
||||
}
|
||||
|
||||
function addMessage(username, color, text) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'chat-msg';
|
||||
div.innerHTML = `<span class="username" style="color:${esc(color)}">${esc(username)}</span>: ${esc(text)}`;
|
||||
chat.appendChild(div);
|
||||
|
||||
while (chat.children.length > S.max_messages) chat.removeChild(chat.firstChild);
|
||||
|
||||
if (S.message_timeout > 0) {
|
||||
setTimeout(() => {
|
||||
div.style.opacity = '0';
|
||||
setTimeout(() => div.remove(), 500);
|
||||
}, S.message_timeout * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Alert WebSocket ---
|
||||
function connectWS() {
|
||||
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
const ws = new WebSocket(`${proto}://${location.host}/ws/overlay`);
|
||||
|
||||
ws.onmessage = (e) => {
|
||||
const msg = JSON.parse(e.data);
|
||||
document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }));
|
||||
handleAction(msg);
|
||||
};
|
||||
|
||||
ws.onclose = () => setTimeout(connectWS, 3000);
|
||||
}
|
||||
connectWS();
|
||||
|
||||
function handleAction(msg) {
|
||||
if (msg.action_type === 'sound' && msg.media_url) {
|
||||
playAudio(msg.media_url, 1.0);
|
||||
} else if (msg.action_type === 'video' && msg.media_url) {
|
||||
showVideo(msg.media_url);
|
||||
} else if (msg.action_type === 'alert') {
|
||||
showAlert(msg.alert_text || '', msg.username);
|
||||
}
|
||||
}
|
||||
|
||||
function playAudio(url, volume) {
|
||||
const a = new Audio(url);
|
||||
a.volume = Math.max(0, Math.min(1, volume));
|
||||
a.play().catch(() => {});
|
||||
}
|
||||
|
||||
function showAlert(text, username) {
|
||||
alertBox.textContent = text.replace('{username}', username || '');
|
||||
alertBox.style.display = 'block';
|
||||
setTimeout(() => { alertBox.style.display = 'none'; }, 5000);
|
||||
}
|
||||
|
||||
function showVideo(url) {
|
||||
alertVideo.src = url;
|
||||
alertVideo.style.display = 'block';
|
||||
alertVideo.play();
|
||||
alertVideo.onended = () => {
|
||||
alertVideo.style.display = 'none';
|
||||
alertVideo.src = '';
|
||||
};
|
||||
}
|
||||
|
||||
function esc(str) {
|
||||
return String(str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
<%- settings.custom_js %>
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
87
views/overlay_preview.ejs
Normal file
87
views/overlay_preview.ejs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
:root {
|
||||
--chat-left: <%= layout.chat_left %>%;
|
||||
--chat-top: <%= layout.chat_top %>%;
|
||||
--chat-width: <%= layout.chat_width %>%;
|
||||
--chat-height: <%= layout.chat_height %>%;
|
||||
--chat-font-size: <%= layout.chat_font_size %>px;
|
||||
--chat-font-family: <%= layout.chat_font_family %>;
|
||||
--chat-bg-opacity: <%= layout.chat_bg_opacity %>;
|
||||
--chat-text-color: <%= layout.chat_text_color %>;
|
||||
--chat-border-radius: <%= layout.chat_border_radius %>px;
|
||||
--alert-left: <%= layout.alert_left %>%;
|
||||
--alert-top: <%= layout.alert_top %>%;
|
||||
--alert-font-size: <%= layout.alert_font_size %>px;
|
||||
--alert-bg-opacity: <%= layout.alert_bg_opacity %>;
|
||||
--alert-text-color: <%= layout.alert_text_color %>;
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { background: rgba(30,30,30,0.6); overflow: hidden; width: 1920px; height: 1080px; }
|
||||
|
||||
#chat {
|
||||
position: fixed;
|
||||
left: var(--chat-left);
|
||||
top: var(--chat-top);
|
||||
width: var(--chat-width);
|
||||
max-height: var(--chat-height);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-family: var(--chat-font-family);
|
||||
font-size: var(--chat-font-size);
|
||||
color: var(--chat-text-color);
|
||||
}
|
||||
.chat-msg {
|
||||
background: rgba(0, 0, 0, var(--chat-bg-opacity));
|
||||
border-radius: var(--chat-border-radius);
|
||||
padding: 5px 10px;
|
||||
word-break: break-word;
|
||||
}
|
||||
.chat-msg .username { font-weight: 700; margin-right: 4px; }
|
||||
|
||||
#alert-box {
|
||||
position: fixed;
|
||||
left: var(--alert-left);
|
||||
top: var(--alert-top);
|
||||
transform: translate(-50%, -50%);
|
||||
font-family: var(--chat-font-family);
|
||||
font-size: var(--alert-font-size);
|
||||
color: var(--alert-text-color);
|
||||
background: rgba(0, 0, 0, var(--alert-bg-opacity));
|
||||
border-radius: 12px;
|
||||
padding: 16px 28px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#chat-handle, #alert-handle {
|
||||
position: fixed;
|
||||
border: 2px dashed rgba(255,255,255,0.5);
|
||||
cursor: move;
|
||||
background: rgba(255,255,255,0.05);
|
||||
}
|
||||
#chat-handle {
|
||||
left: var(--chat-left); top: var(--chat-top);
|
||||
width: var(--chat-width); height: var(--chat-height);
|
||||
}
|
||||
#alert-handle {
|
||||
left: calc(var(--alert-left) - 80px); top: calc(var(--alert-top) - 20px);
|
||||
width: 160px; height: 40px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="chat">
|
||||
<div class="chat-msg"><span class="username" style="color:#9146ff">channel</span>: This is a preview message</div>
|
||||
<div class="chat-msg"><span class="username" style="color:#ff6b6b">someviewer</span>: Looking great!</div>
|
||||
<div class="chat-msg"><span class="username" style="color:#6bcbff">anotheruser</span>: pog pog pog</div>
|
||||
</div>
|
||||
<div id="alert-box">Alert preview</div>
|
||||
<div id="chat-handle" data-widget="chat"></div>
|
||||
<div id="alert-handle" data-widget="alert"></div>
|
||||
</body>
|
||||
</html>
|
||||
79
views/settings.ejs
Normal file
79
views/settings.ejs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
<h2>Settings</h2>
|
||||
|
||||
<article>
|
||||
<header><strong>Overlay URL</strong></header>
|
||||
<p>Add this as a <strong>Browser Source</strong> in OBS (1920×1080, transparent background):</p>
|
||||
<code><%= baseUrl %>/overlay/<%= settings.overlay_id %></code>
|
||||
</article>
|
||||
|
||||
<form method="POST" action="/settings">
|
||||
|
||||
<h3>Chat</h3>
|
||||
<label>
|
||||
Twitch channel
|
||||
<input type="text" name="channel" value="<%= settings.channel %>" placeholder="yourchannel">
|
||||
</label>
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
|
||||
<label>
|
||||
Message timeout (seconds)
|
||||
<input type="number" name="message_timeout" value="<%= settings.message_timeout %>" min="0" max="600">
|
||||
<small>0 = messages stay forever</small>
|
||||
</label>
|
||||
<label>
|
||||
Max messages shown
|
||||
<input type="number" name="max_messages" value="<%= settings.max_messages %>" min="1" max="100">
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<h3>Gap audio</h3>
|
||||
<p><small>Plays a sound when a new message arrives after a period of silence.</small></p>
|
||||
<label>
|
||||
<input type="checkbox" name="gap_audio_enabled" role="switch" <%= settings.gap_audio_enabled ? 'checked' : '' %>>
|
||||
Enable gap audio
|
||||
</label>
|
||||
<label>
|
||||
Sound URL
|
||||
<input type="text" name="gap_audio_url" value="<%= settings.gap_audio_url %>" placeholder="https://... or /media/filename.mp3">
|
||||
</label>
|
||||
<div style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:1rem;">
|
||||
<label>
|
||||
Min silence before triggering (s)
|
||||
<input type="number" name="gap_audio_min_silence" value="<%= settings.gap_audio_min_silence %>" min="0">
|
||||
<small>Sound won't play if chat was more recent than this</small>
|
||||
</label>
|
||||
<label>
|
||||
Min volume (0–1)
|
||||
<input type="number" name="gap_audio_min_volume" value="<%= settings.gap_audio_min_volume %>" min="0" max="1" step="0.05">
|
||||
<small>Volume right after min silence</small>
|
||||
</label>
|
||||
<label>
|
||||
Max volume (0–1)
|
||||
<input type="number" name="gap_audio_max_volume" value="<%= settings.gap_audio_max_volume %>" min="0" max="1" step="0.05">
|
||||
<small>Volume after long silence</small>
|
||||
</label>
|
||||
</div>
|
||||
<label>
|
||||
Full volume after silence of (seconds)
|
||||
<input type="number" name="gap_audio_loud_after" value="<%= settings.gap_audio_loud_after %>" min="0">
|
||||
<small>e.g. 3600 = 1 hour of silence → max volume</small>
|
||||
</label>
|
||||
|
||||
<h3>Custom CSS / JS</h3>
|
||||
<label>
|
||||
Custom CSS (injected into the overlay)
|
||||
<textarea name="custom_css" rows="6" style="font-family:monospace"><%= settings.custom_css %></textarea>
|
||||
</label>
|
||||
<label>
|
||||
Custom JS (injected into the overlay, runs after init)
|
||||
<textarea name="custom_js" rows="6" style="font-family:monospace"><%= settings.custom_js %></textarea>
|
||||
</label>
|
||||
|
||||
<button type="submit">Save settings</button>
|
||||
</form>
|
||||
|
||||
<hr>
|
||||
<h3>EventSub</h3>
|
||||
<form method="POST" action="/settings/reconnect" style="display:inline;">
|
||||
<button type="submit" class="outline">Reconnect EventSub</button>
|
||||
</form>
|
||||
<small style="margin-left:1rem;">Use this if Twitch alerts stop working after a token refresh.</small>
|
||||
Loading…
Add table
Add a link
Reference in a new issue