const { WebSocket } = require('ws'); const clients = new Set(); // Overlay -> server messages. Only accepted from connections that present the overlay UUID // (?overlay=, the same secret as the OBS URL), so strangers cannot inject alerts. function handleIncoming(raw) { let msg; try { msg = JSON.parse(raw); } catch { return; } if (msg?.type === 'chat_notice') { const alerts = require('./alerts'); // lazy: alerts.js requires this module alerts.send(alerts.fromOverlayNotice(msg)); } } function init(wss) { wss.on('connection', (ws, req) => { clients.add(ws); const db = require('./db'); const overlayId = new URL(req.url, 'http://x').searchParams.get('overlay'); const trusted = !!overlayId && overlayId === db.getSettings().overlay_id; console.log(`[ws] Client connected${trusted ? ' (overlay)' : ''} — total: ${clients.size}`); if (trusted) ws.on('message', data => handleIncoming(String(data).slice(0, 2000))); // a freshly loaded overlay gets the current song right away const np = require('./nowplaying').get(); if (np) ws.send(JSON.stringify({ type: 'nowplaying', np })); const raid = require('./alerts').getPendingRaid(); // overlay reloaded during a raid countdown if (raid) ws.send(JSON.stringify({ type: 'raid_card', phase: 'start', raid })); ws.on('close', () => { 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 };