Update gitignore

This commit is contained in:
Bashy 2026-11-20 18:53:12 +01:00
commit 9e0ddb8182
32 changed files with 3863 additions and 0 deletions

12
.env.example Normal file
View file

@ -0,0 +1,12 @@
TWITCH_CLIENT_ID=your_client_id
TWITCH_CLIENT_SECRET=your_client_secret
# Local dev:
# TWITCH_REDIRECT_URI=http://localhost:3000/auth/callback
# Production:
TWITCH_REDIRECT_URI=https://overlay.example.com/auth/callback
SECRET_KEY=change_this_to_a_random_string
APP_BASE_URL=https://overlay.example.com
DB_PATH=./heystreamer.db
PORT=3000

36
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,36 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Syntax check
run: node --check src/app.js src/server.js src/db.js src/eventsub.js src/dispatch.js src/ws.js src/cooldowns.js src/routers/*.js
- name: Import check
run: node -e "require('./src/app')"
env:
TWITCH_CLIENT_ID: ci-placeholder
TWITCH_CLIENT_SECRET: ci-placeholder
TWITCH_REDIRECT_URI: http://localhost:3000/auth/callback
SECRET_KEY: ci-test-secret-not-real
APP_BASE_URL: http://localhost:3000
DB_PATH: ./test.db
PORT: 3000

13
.gitignore vendored Normal file
View file

@ -0,0 +1,13 @@
*.db
*.pyc
__pycache__/
.env
.venv/
venv/
static/media/*
!static/media/.gitkeep
node_modules/
*.db-shm
*.db-wal
public/media/*

221
CLAUDE.md Normal file
View file

@ -0,0 +1,221 @@
# CLAUDE.md
## Running the app
```bash
npm install
npm run dev # development (nodemon)
npm start # production
```
Requires `.env` — copy from `.env.example`. Database is created automatically on startup (better-sqlite3 runs migrations on init).
## Stack
- **Node.js** · Express · EJS templates
- **better-sqlite3** — SQLite, synchronous, simple
- **ws** — WebSocket server for pushing alerts and settings to overlay clients
- **tmi.js** — Twitch IRC, runs in the browser on the overlay page (no server-side IRC). Self-hosted at `public/vendor/tmi.min.js` — the npm package has no browser build, downloaded from GitHub release
- **multer** — file uploads
- **uuid** — UUID generation
- **dotenv** — env vars
- **express-session** — session management (signed cookie)
## Architecture
```
Twitch ──EventSub WebSocket──► src/eventsub.js ──► dispatch.js ──► ws.js ──► OBS overlay
Twitch ──IRC (tmi.js in browser) ────────────────────────────────────────► OBS overlay
Dashboard /settings save ────────────────────────────────────────────────► ws.js ──► OBS overlay (settings_update)
```
- `eventsub.js` opens a WebSocket to Twitch on startup, managed as a module-level singleton
- On notification it calls `dispatch.dispatchEvent()`
- `dispatch.dispatchEvent()` queries matching `event_actions` rows, checks cooldowns, logs to `activity_log`, calls `wss.broadcast()`
- `wss` (ws.js) holds all active WebSocket connections from `/ws/overlay`
- The overlay JS receives the broadcast and plays the action
- Chat messages come directly from tmi.js running in the browser — no server relay
- When settings are saved, the server broadcasts `{ type: 'settings_update', settings }` to all overlay clients — overlay updates `S` in place, no OBS reload needed
## Project structure
```
src/
app.js — Express app setup, middleware, router mounting
server.js — HTTP server + WebSocket server startup, EventSub init
db.js — better-sqlite3 setup, migrations, singleton helpers
eventsub.js — Twitch EventSub WebSocket client (module singleton)
dispatch.js — event → action resolution, cooldowns, DB log, broadcast
ws.js — WebSocket connection manager
cooldowns.js — in-memory cooldown tracking
routers/
auth.js — /auth/* (Twitch OAuth)
dashboard.js — / (activity log, EventSub status)
overlay.js — /overlay/:uuid, /overlay/:uuid/preview, /ws/overlay
actions.js — /actions CRUD
media.js — /media upload/delete
layout.js — /layout editor + /layout/positions
settings.js — /settings
views/
layout.ejs — base shell (nav, Pico CSS)
login.ejs
dashboard.ejs
overlay.ejs — OBS browser source
overlay_preview.ejs
layout_editor.ejs
actions.ejs
media.ejs
settings.ejs
public/
media/ — uploaded files (gitignored)
vendor/
tmi.min.js — self-hosted tmi.js browser build
```
## Key conventions
**No passwords anywhere.** Auth is Twitch OAuth only. Session stored via `express-session` with a signed cookie. `req.session.userId` stores the DB user ID after login.
**Singleton tables.** `settings` and `overlay_layout` each have one row (id=1). `db.getSettings()` and `db.getLayout()` create the row on first call if missing.
**Cooldowns are in-memory.** `cooldowns.js` tracks `{ actionId: triggeredAt }`. Restarting the server resets all cooldowns. Intentional — DB cooldowns not worth the complexity.
**Multiple actions per event.** `dispatchEvent()` loops through ALL matching `event_actions` rows and fires each one (subject to its own cooldown). No "first match wins".
**Event matching rules:**
- `event_type="command"`: `event_detail` must match the command name (case-insensitive)
- `event_type="bits"`: if `event_detail` set, treat as minimum bits threshold
- `event_type="channel_points"`: `event_detail` is the reward ID; null matches any reward
- `event_type="sub"/"gift_sub"`: `event_detail` is tier ("1000", "2000", "3000"); null matches any
- `event_type="follow"/"raid"`: `event_detail` not used
**UUID overlays.** `settings.overlay_id` is a UUID generated on first run. OBS browser source URL is `/overlay/:uuid`. Future multi-user support creates multiple settings rows.
**`layout` is a reserved render variable.** `express-ejs-layouts` uses the `layout` local to pick the wrapper template. Never pass `layout` as a template variable — it will override the layout selection and cause a 500. The DB `overlay_layout` row is passed as `overlayLayout` in all render calls.
**Form value parsing.** Never use `parseInt(val) || default` — it overwrites valid `0` values. Use:
```javascript
const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; };
const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
```
## Route map
| Method | Path | File | Notes |
|---|---|---|---|
| GET | `/` | routers/dashboard.js | Activity log, EventSub status |
| GET | `/auth/login` | routers/auth.js | Login page |
| GET | `/auth/twitch` | routers/auth.js | Redirect to Twitch OAuth |
| GET | `/auth/callback` | routers/auth.js | Exchange code, save user, start EventSub |
| GET | `/auth/logout` | routers/auth.js | Clear session |
| GET | `/overlay/:uuid` | routers/overlay.js | Live OBS browser source |
| GET | `/overlay/:uuid/preview` | routers/overlay.js | Mock preview for layout editor |
| WS | `/ws/overlay` | routers/overlay.js | Bidirectional: commands up, actions down |
| GET/POST | `/actions` | routers/actions.js | List and create actions |
| POST | `/actions/:id/test` | routers/actions.js | Fire immediately, skip cooldown |
| POST | `/actions/:id/toggle` | routers/actions.js | Enable/disable |
| DELETE | `/actions/:id` | routers/actions.js | Delete |
| GET/POST | `/media` | routers/media.js | Upload, list |
| DELETE | `/media/:id` | routers/media.js | Delete file + DB row |
| GET/POST | `/layout` | routers/layout.js | Position + style form (saves all layout fields) |
| POST | `/layout/positions` | routers/layout.js | JSON position update (legacy, kept for future drag) |
| GET/POST | `/settings` | routers/settings.js | Channel, gap audio, custom CSS/JS; broadcasts settings_update on save |
| POST | `/settings/reconnect` | routers/settings.js | Restart EventSub |
## Overlay CSS variable system
All overlay positioning and styling uses CSS custom properties rendered into `overlay.ejs` and `overlay_preview.ejs` from the `overlay_layout` row:
| Variable | Controls |
|---|---|
| `--chat-left`, `--chat-top` | Chat box position (%) |
| `--chat-width`, `--chat-height` | Chat box size (%) |
| `--chat-font-size` | Chat font size (px) |
| `--chat-font-family` | Chat font family |
| `--chat-bg-opacity` | Chat message background opacity |
| `--chat-text-color` | Chat message text colour |
| `--chat-border-radius` | Message border radius (px) |
| `--alert-left`, `--alert-top` | Alert position (%, centered via transform) |
| `--alert-font-size` | Alert font size (px) |
| `--alert-bg-opacity` | Alert background opacity |
| `--alert-text-color` | Alert text colour |
The layout editor (`/layout`) shows position and style inputs, with a scaled iframe preview of `/overlay/:uuid/preview`. Position inputs update CSS variables in the iframe live on `input` event. All fields (position + style) are saved via `POST /layout`.
## Gap / new-message audio
Configured in `settings`. When a chat message arrives in the overlay, tmi.js checks:
1. Is `gap_audio_enabled` true and `gap_audio_url` set?
2. Has at least `gap_audio_min_silence` seconds passed since the last message?
3. If yes: play the audio. Volume = linear interpolation between `gap_audio_min_volume` and `gap_audio_max_volume` based on silence duration vs `gap_audio_loud_after`.
All logic runs in the browser. The server pushes updated settings to the overlay via WebSocket on save — no OBS reload needed. Gap audio has `[gap]` debug logging in the browser console.
## Custom events dispatched to overlay JS
When the overlay WebSocket receives a message:
- **Action broadcast:** `document.dispatchEvent(new CustomEvent(`heystreamer:${msg.event_type}`, { detail: msg }))`
Available types: `sub`, `gift_sub`, `bits`, `channel_points`, `command`, `follow`, `raid`.
`msg` shape: `{ event_type, action_type, media_url, alert_text, username }`.
- **Settings update:** `{ type: 'settings_update', settings }` — overlay does `Object.assign(S, msg.settings)` to update live.
Alert text supports `{username}` interpolation.
## Database schema
```sql
users — Twitch OAuth user (twitch_id unique)
settings — singleton id=1: overlay_id, channel, gap audio, message_timeout, custom_css/js
overlay_layout — singleton id=1: widget positions and styles
media_files — uploaded sounds/videos
event_actions — event → action mapping (media_file_id FK)
activity_log — append-only event log
```
## EventSub subscriptions
| Twitch event | Version | Condition | Scope |
|---|---|---|---|
| `channel.subscribe` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` |
| `channel.subscription.message` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` |
| `channel.subscription.gift` | 1 | `broadcaster_user_id` | `channel:read:subscriptions` |
| `channel.cheer` | 1 | `broadcaster_user_id` | `bits:read` |
| `channel.channel_points_custom_reward_redemption.add` | 1 | `broadcaster_user_id` | `channel:read:redemptions` |
| `channel.follow` | 2 | `broadcaster_user_id` + `moderator_user_id` | `moderator:read:followers` |
| `channel.raid` | 1 | `to_broadcaster_user_id` | none |
Token refresh triggered on 401 during subscription.
## Production deployment
Runs behind Apache on the VPS as a reverse proxy to Node on port 3000.
Production domain: `https://overlay.example.com`
Apache vhost config is managed by `~/projects/apache.sh` (run on the VPS). Key requirements:
- `RequestHeader set X-Forwarded-Proto "https"` must be in the **443 vhost** — without it Express sees the connection as HTTP, `req.secure` is false, and the session cookie is never sent (OAuth login breaks)
- `app.set('trust proxy', 1)` is set in `app.js` before all middleware
- `/ws/overlay` must be proxied with `ws://` via `mod_proxy_wstunnel` before the catch-all `/`
- Required modules: `proxy`, `proxy_http`, `proxy_wstunnel`, `headers`, `rewrite`
Deploy from Linux Mint:
```bash
rsync -avzO --exclude='node_modules' --exclude='.env' --exclude='public/media' \
~/projects/heystreamer/ user@your-server:/opt/heystreamer/
ssh user@your-server "cd /opt/heystreamer && npm install --production && sudo systemctl restart heystreamer"
```
Twitch requires HTTPS for OAuth redirect URIs in production. Register both in the Twitch dev console:
- `http://localhost:3000/auth/callback` (dev)
- `https://overlay.example.com/auth/callback` (production)
## Not yet implemented
- Mod access (streamer-only login for now)
- Chat commands triggering actions
- Stripe / PayPal / ETH payment notifications
- Multiple overlays (multi-user; UUID foundation is in place)
- HudFX integration
- Drag-to-reposition in layout editor (removed — CSS transform + interact.js coordinate mismatch; use the position inputs instead)

31
deploy.sh Executable file
View file

@ -0,0 +1,31 @@
#!/usr/bin/env bash
set -e
echo "==> Checking Node.js..."
node_version=$(node -v 2>/dev/null | cut -c2- | cut -d. -f1)
if [ -z "$node_version" ] || [ "$node_version" -lt 18 ]; then
echo "ERROR: Node.js 18+ required. Install via: https://nodejs.org"
exit 1
fi
echo " Node $(node -v) OK"
echo "==> Installing dependencies..."
npm install --production
echo "==> Checking .env..."
if [ ! -f .env ]; then
echo "ERROR: .env not found. Copy .env.example and fill in your values."
exit 1
fi
for var in TWITCH_CLIENT_ID TWITCH_CLIENT_SECRET SECRET_KEY APP_BASE_URL; do
val=$(grep "^${var}=" .env | cut -d= -f2-)
if [ -z "$val" ] || echo "$val" | grep -q "your_\|change_this"; then
echo "ERROR: $var is not set in .env"
exit 1
fi
done
echo " .env OK"
echo "==> Starting HeyStreamer..."
node src/server.js

1981
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

24
package.json Normal file
View 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"
}
}

14
public/favicon.svg Normal file
View file

@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<!-- Background circle -->
<circle cx="16" cy="16" r="15" fill="#9146ff"/>
<!-- Speech bubble body -->
<rect x="7" y="8" width="18" height="13" rx="3" fill="white"/>
<!-- Bubble tail -->
<polygon points="10,21 7,26 14,21" fill="white"/>
<!-- Screen/monitor lines (chat lines) -->
<rect x="10" y="11" width="12" height="2" rx="1" fill="#9146ff"/>
<rect x="10" y="14.5" width="9" height="2" rx="1" fill="#9146ff"/>
<!-- Star / sparkle top-right -->
<circle cx="23" cy="9" r="2.5" fill="#ffcc00"/>
<polygon points="23,6 23.7,8.3 26,8.3 24.2,9.7 24.8,12 23,10.6 21.2,12 21.8,9.7 20,8.3 22.3,8.3" fill="#ffaa00"/>
</svg>

After

Width:  |  Height:  |  Size: 701 B

1
public/vendor/tmi.min.js vendored Normal file

File diff suppressed because one or more lines are too long

58
src/app.js Normal file
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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;

37
src/routers/layout.js Normal file
View file

@ -0,0 +1,37 @@
const express = require('express');
const router = express.Router();
const db = require('../db');
router.get('/', (req, res) => {
res.render('layout_editor', { overlayLayout: db.getLayout(), settings: db.getSettings() });
});
router.post('/', (req, res) => {
const b = req.body;
const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; };
const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
db.updateLayout({
chat_left: flt(b.chat_left, 2.0),
chat_top: flt(b.chat_top, 60.0),
chat_width: flt(b.chat_width, 25.0),
chat_height: flt(b.chat_height, 35.0),
alert_left: flt(b.alert_left, 50.0),
alert_top: flt(b.alert_top, 40.0),
chat_font_size: int(b.chat_font_size, 15),
chat_font_family: b.chat_font_family || 'Inter, sans-serif',
chat_bg_opacity: flt(b.chat_bg_opacity, 0.45),
chat_text_color: b.chat_text_color || '#ffffff',
chat_border_radius: int(b.chat_border_radius, 8),
alert_font_size: int(b.alert_font_size, 32),
alert_bg_opacity: flt(b.alert_bg_opacity, 0.7),
alert_text_color: b.alert_text_color || '#ffffff',
});
res.redirect('/layout');
});
router.post('/positions', (req, res) => {
db.updateLayoutPositions(req.body);
res.json({ ok: true });
});
module.exports = router;

42
src/routers/media.js Normal file
View 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
View 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 overlayLayout = db.getLayout();
res.render('overlay', { layout: false, settings, overlayLayout });
});
router.get('/:uuid/preview', (req, res) => {
const settings = db.getSettings();
const overlayLayout = db.getLayout();
res.render('overlay_preview', { layout: false, settings, overlayLayout });
});
module.exports = router;

48
src/routers/settings.js Normal file
View file

@ -0,0 +1,48 @@
const express = require('express');
const router = express.Router();
const db = require('../db');
const eventsub = require('../eventsub');
const ws = require('../ws');
const int = (v, d) => { const n = parseInt(v, 10); return isNaN(n) ? d : n; };
const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
router.get('/', (req, res) => {
const settings = db.getSettings();
const baseUrl = process.env.APP_BASE_URL;
res.render('settings', { settings, baseUrl });
});
router.post('/', (req, res) => {
const b = req.body;
db.updateSettings({
channel: b.channel || '',
message_timeout: int(b.message_timeout, 30),
max_messages: int(b.max_messages, 20),
gap_audio_enabled: b.gap_audio_enabled === 'on' ? 1 : 0,
gap_audio_url: b.gap_audio_url || '',
gap_audio_min_silence: int(b.gap_audio_min_silence, 60),
gap_audio_min_volume: flt(b.gap_audio_min_volume, 0.2),
gap_audio_max_volume: flt(b.gap_audio_max_volume, 1.0),
gap_audio_loud_after: int(b.gap_audio_loud_after, 3600),
custom_css: b.custom_css || '',
custom_js: b.custom_js || '',
});
// Push updated settings to all connected overlays so they don't need a page reload
ws.broadcast({ type: 'settings_update', settings: db.getSettings() });
console.log(`[settings] Saved — channel: ${b.channel}, gap_audio: ${b.gap_audio_enabled === 'on'}`);
res.redirect('/settings');
});
router.post('/reconnect', (req, res) => {
const user = db.getUserById(req.session.userId);
if (user) {
eventsub.start(user.access_token, user.twitch_id);
console.log('[settings] EventSub reconnect triggered');
}
res.redirect('/settings');
});
module.exports = router;

21
src/server.js Normal file
View 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
View 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 };

88
views/actions.ejs Normal file
View 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
View 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>
<% } %>

39
views/layout.ejs Normal file
View file

@ -0,0 +1,39 @@
<!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="icon" type="image/svg+xml" href="/favicon.svg">
<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>

73
views/layout_editor.ejs Normal file
View file

@ -0,0 +1,73 @@
<h2>Layout editor</h2>
<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 position &amp; size</h3>
<div style="display:grid; grid-template-columns:repeat(4,1fr); gap:1rem;">
<label>Left (%) <input type="number" name="chat_left" id="chat_left" value="<%= overlayLayout.chat_left %>" min="0" max="95" step="0.5"></label>
<label>Top (%) <input type="number" name="chat_top" id="chat_top" value="<%= overlayLayout.chat_top %>" min="0" max="95" step="0.5"></label>
<label>Width (%) <input type="number" name="chat_width" value="<%= overlayLayout.chat_width %>" min="1" max="100" step="0.5"></label>
<label>Height (%) <input type="number" name="chat_height" value="<%= overlayLayout.chat_height %>" min="1" max="100" step="0.5"></label>
</div>
<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="<%= overlayLayout.chat_font_size %>" min="8" max="64"></label>
<label>Font family <input type="text" name="chat_font_family" value="<%= overlayLayout.chat_font_family %>"></label>
<label>Text colour <input type="color" name="chat_text_color" value="<%= overlayLayout.chat_text_color %>"></label>
<label>Background opacity (0–1) <input type="number" name="chat_bg_opacity" value="<%= overlayLayout.chat_bg_opacity %>" min="0" max="1" step="0.05"></label>
<label>Border radius (px) <input type="number" name="chat_border_radius" value="<%= overlayLayout.chat_border_radius %>" min="0" max="32"></label>
</div>
<h3>Alert position</h3>
<div style="display:grid; grid-template-columns:repeat(2,1fr); gap:1rem;">
<label>Left (%) <input type="number" name="alert_left" id="alert_left" value="<%= overlayLayout.alert_left %>" min="0" max="100" step="0.5"></label>
<label>Top (%) <input type="number" name="alert_top" id="alert_top" value="<%= overlayLayout.alert_top %>" min="0" max="100" step="0.5"></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="<%= overlayLayout.alert_font_size %>" min="12" max="96"></label>
<label>Text colour <input type="color" name="alert_text_color" value="<%= overlayLayout.alert_text_color %>"></label>
<label>Background opacity (0–1) <input type="number" name="alert_bg_opacity" value="<%= overlayLayout.alert_bg_opacity %>" min="0" max="1" step="0.05"></label>
</div>
<button type="submit" style="margin-top:1rem;">Save layout</button>
</form>
<script>
const iframe = document.getElementById('preview');
function applyScale() {
const scale = iframe.parentElement.offsetWidth / 1920;
iframe.style.transform = `scale(${scale})`;
}
applyScale();
window.addEventListener('resize', applyScale);
// Live-update CSS variables in the preview iframe as inputs change
const varMap = {
chat_left: '--chat-left',
chat_top: '--chat-top',
alert_left: '--alert-left',
alert_top: '--alert-top',
};
Object.entries(varMap).forEach(([id, cssVar]) => {
const input = document.getElementById(id);
if (!input) return;
input.addEventListener('input', () => {
if (!iframe.contentDocument) return;
iframe.contentDocument.documentElement.style.setProperty(cssVar, `${input.value}%`);
});
});
</script>

34
views/login.ejs Normal file
View file

@ -0,0 +1,34 @@
<!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="icon" type="image/svg+xml" href="/favicon.svg">
<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
View 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>
<% } %>

199
views/overlay.ejs Normal file
View file

@ -0,0 +1,199 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
:root {
--chat-left: <%= overlayLayout.chat_left %>%;
--chat-top: <%= overlayLayout.chat_top %>%;
--chat-width: <%= overlayLayout.chat_width %>%;
--chat-height: <%= overlayLayout.chat_height %>%;
--chat-font-size: <%= overlayLayout.chat_font_size %>px;
--chat-font-family: <%= overlayLayout.chat_font_family %>;
--chat-bg-opacity: <%= overlayLayout.chat_bg_opacity %>;
--chat-text-color: <%= overlayLayout.chat_text_color %>;
--chat-border-radius: <%= overlayLayout.chat_border_radius %>px;
--alert-left: <%= overlayLayout.alert_left %>%;
--alert-top: <%= overlayLayout.alert_top %>%;
--alert-font-size: <%= overlayLayout.alert_font_size %>px;
--alert-bg-opacity: <%= overlayLayout.alert_bg_opacity %>;
--alert-text-color: <%= overlayLayout.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="/vendor/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;
console.log(`[gap] silence=${silence.toFixed(1)}s threshold=${S.gap_audio_min_silence}s enabled=${S.gap_audio_enabled} url=${!!S.gap_audio_url} lastMsg=${lastMsgTime>0}`);
if (S.gap_audio_enabled && S.gap_audio_url && lastMsgTime > 0 && silence >= S.gap_audio_min_silence) {
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);
console.log(`[gap] PLAY — t=${t.toFixed(2)} vol=${vol.toFixed(2)} min=${S.gap_audio_min_volume} max=${S.gap_audio_max_volume}`);
playAudio(S.gap_audio_url, vol);
}
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);
if (msg.type === 'settings_update') {
Object.assign(S, msg.settings);
return;
}
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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
<%- settings.custom_js %>
</script>
</body>
</html>

87
views/overlay_preview.ejs Normal file
View file

@ -0,0 +1,87 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
:root {
--chat-left: <%= overlayLayout.chat_left %>%;
--chat-top: <%= overlayLayout.chat_top %>%;
--chat-width: <%= overlayLayout.chat_width %>%;
--chat-height: <%= overlayLayout.chat_height %>%;
--chat-font-size: <%= overlayLayout.chat_font_size %>px;
--chat-font-family: <%= overlayLayout.chat_font_family %>;
--chat-bg-opacity: <%= overlayLayout.chat_bg_opacity %>;
--chat-text-color: <%= overlayLayout.chat_text_color %>;
--chat-border-radius: <%= overlayLayout.chat_border_radius %>px;
--alert-left: <%= overlayLayout.alert_left %>%;
--alert-top: <%= overlayLayout.alert_top %>%;
--alert-font-size: <%= overlayLayout.alert_font_size %>px;
--alert-bg-opacity: <%= overlayLayout.alert_bg_opacity %>;
--alert-text-color: <%= overlayLayout.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
View 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>