const { WebSocketServer } = require('ws'); const hub = require('./hub'); const store = require('./store'); const cdp = require('./cdp'); function setupWebSocket(server) { const wss = new WebSocketServer({ server }); // Heartbeat: прокси и NAT рвут «тихие» соединения — пингуем и убиваем мёртвых. const heartbeat = setInterval(() => { wss.clients.forEach((ws) => { if (ws.isAlive === false) { try { ws.terminate(); } catch { /* noop */ } return; } ws.isAlive = false; try { ws.ping(); } catch { /* noop */ } }); }, 25000); wss.on('close', () => clearInterval(heartbeat)); wss.on('connection', (ws, req) => { ws.isAlive = true; ws.on('pong', () => { ws.isAlive = true; }); const { searchParams } = new URL(req.url, 'http://localhost'); const presentationId = searchParams.get('id'); const role = searchParams.get('role') === 'speaker' ? 'speaker' : 'audience'; hub.registerClient(ws); // Глобальный клиент (дашборд/редактор) if (!presentationId) { ws.on('close', () => hub.unregisterClient(ws)); return; } const presentation = store.getPresentation(presentationId); if (!presentation) { ws.send(JSON.stringify({ type: 'error', error: 'not_found' })); ws.close(4004, 'presentation not found'); return; } hub.joinRoom(presentationId, ws, role); ws._presentationId = presentationId; const syncPayload = () => ({ type: 'sync', presentationId, title: presentation.title, slides: presentation.slides, slideIndex: presentation.currentSlide, variables: presentation.variables, music: presentation.music, lua: presentation.lua, commands: presentation.commands, graph: presentation.graph, }); ws.send(JSON.stringify(syncPayload())); const roomVars = hub.getRoomVars(presentationId); if (roomVars) ws.send(JSON.stringify({ type: 'vars', vars: roomVars })); const audioState = hub.getAudioState(presentationId); if (hub.hasAudioState(presentationId)) { ws.send(JSON.stringify({ type: 'audio-state', state: audioState })); } const mediaStates = hub.getMediaStates(presentationId); if (mediaStates.length) ws.send(JSON.stringify({ type: 'media-state', states: mediaStates })); hub.getWindowStates(presentationId).forEach((state) => { ws.send(JSON.stringify({ type: 'window-state', state })); }); hub.getWindowFrames(presentationId).forEach((frame) => { ws.send(JSON.stringify({ type: 'window-frame', elementId: frame.elementId, data: frame.data, cached: true })); }); function sendWindowError(elementId, message) { if (ws.readyState === 1) { ws.send(JSON.stringify({ type: 'window-error', elementId, message })); } } function findWindowElement(elementId) { const fresh = store.getPresentation(presentationId) || presentation; for (const slide of fresh.slides) { const found = (slide.elements || []).find((element) => element.id === elementId && element.type === 'window'); if (found) return found; } return null; } async function startWindow(elementId, targetId) { const element = findWindowElement(elementId); if (!element) { sendWindowError(elementId, 'Элемент окна не найден на слайдах'); return; } const wanted = String(targetId || element.targetId || ''); let lastFrameAt = 0; hub.setWindowState(presentationId, elementId, { active: true, targetId: wanted, targetTitle: element.targetTitle || '', error: '', }); ws.send(JSON.stringify({ type: 'window-starting', elementId, targetId: wanted })); hub.broadcastRoom(presentationId, { type: 'window-state', state: hub.getWindowStates(presentationId).find((item) => item.elementId === elementId) || { elementId, active: true, targetId: wanted }, }); try { await cdp.start(`${presentationId}::${elementId}`, presentationId, elementId, wanted, { onStart({ target, viewport }) { const state = hub.setWindowState(presentationId, elementId, { active: true, targetId: target.id, targetTitle: target.title, error: '', width: viewport.width, height: viewport.height, }); hub.broadcastRoom(presentationId, { type: 'window-state', state }); }, onFrame({ data }) { hub.setWindowFrame(presentationId, elementId, data); const now = Date.now(); if (now - lastFrameAt < 55) return; lastFrameAt = now; hub.broadcastRoom(presentationId, { type: 'window-frame', elementId, data }); }, onError(error) { const message = String(error && error.message ? error.message : error); hub.setWindowState(presentationId, elementId, { active: false, error: message }); hub.broadcastRoom(presentationId, { type: 'window-error', elementId, message }); }, onClose() { const states = hub.getWindowStates(presentationId); const current = states.find((item) => item.elementId === elementId); if (current && current.active) { hub.setWindowState(presentationId, elementId, { active: false }); hub.broadcastRoom(presentationId, { type: 'window-stop', elementId }); } }, }); } catch (error) { const message = String(error && error.message ? error.message : error); hub.setWindowState(presentationId, elementId, { active: false, error: message }); sendWindowError(elementId, message); } } ws.on('message', (raw) => { let msg; try { msg = JSON.parse(raw); } catch (e) { return; } const current = store.getPresentation(presentationId); if (!current) return; if (msg.type === 'navigate') { const slideIndex = Math.max( 0, Math.min(Number(msg.slideIndex) || 0, Math.max(current.slides.length - 1, 0)) ); current.currentSlide = slideIndex; store.savePresentation(current); hub.broadcastRoom(presentationId, { type: 'sync', presentationId, title: current.title, slides: current.slides, slideIndex, variables: current.variables, music: current.music, lua: current.lua, commands: current.commands, graph: current.graph, }); hub.broadcastSessions(); } if (msg.type === 'audio' && msg.command) { if (role !== 'speaker') return; hub.applyAudioCommand(presentationId, msg.command); hub.broadcastRoom(presentationId, { type: 'audio', command: msg.command }, ws); } if (msg.type === 'vars' && msg.vars && typeof msg.vars === 'object') { if (role !== 'speaker') return; hub.setRoomVars(presentationId, msg.vars); hub.broadcastRoom(presentationId, { type: 'vars', vars: msg.vars }, ws); } if (msg.type === 'media' && msg.command) { if (role !== 'speaker') return; hub.applyMediaCommand(presentationId, msg.command); hub.broadcastRoom(presentationId, { type: 'media', command: msg.command }, ws); } if (msg.type === 'window-start') { if (role !== 'speaker' || !msg.elementId) return; startWindow(String(msg.elementId), msg.targetId); } if (msg.type === 'window-stop') { if (role !== 'speaker' || !msg.elementId) return; cdp.stop(`${presentationId}::${msg.elementId}`); hub.clearWindowState(presentationId, String(msg.elementId)); hub.broadcastRoom(presentationId, { type: 'window-stop', elementId: String(msg.elementId) }); } if (msg.type === 'window-input') { if (role !== 'speaker' || !msg.elementId) return; cdp .input(`${presentationId}::${msg.elementId}`, msg.input) .catch((error) => sendWindowError(String(msg.elementId), String(error.message || error))); } if (msg.type === 'window-targets') { cdp.listTargets(true).then((targets) => { if (ws.readyState === 1) { ws.send(JSON.stringify({ type: 'window-targets', targets: targets.map(({ id, title, url }) => ({ id, title, url })), endpoint: cdp.ENDPOINT, })); } }); } }); ws.on('close', () => hub.unregisterClient(ws)); }); return wss; } module.exports = { setupWebSocket };