Update gitignore
This commit is contained in:
commit
9e0ddb8182
32 changed files with 3863 additions and 0 deletions
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;
|
||||
37
src/routers/layout.js
Normal file
37
src/routers/layout.js
Normal 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
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 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
48
src/routers/settings.js
Normal 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
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 };
|
||||
Loading…
Add table
Add a link
Reference in a new issue