1const { WebSocketServer } = require('ws');
2const hub = require('./hub');
3const store = require('./store');
4const cdp = require('./cdp');
5
6function setupWebSocket(server) {
7 const wss = new WebSocketServer({ server });
8
9 // Heartbeat: прокси и NAT рвут «тихие» соединения — пингуем и убиваем мёртвых.
10 const heartbeat = setInterval(() => {
11 wss.clients.forEach((ws) => {
12 if (ws.isAlive === false) {
13 try { ws.terminate(); } catch { /* noop */ }
14 return;
15 }
16 ws.isAlive = false;
17 try { ws.ping(); } catch { /* noop */ }
18 });
19 }, 25000);
20 wss.on('close', () => clearInterval(heartbeat));
21
22 wss.on('connection', (ws, req) => {
23 ws.isAlive = true;
24 ws.on('pong', () => { ws.isAlive = true; });
25
26 const { searchParams } = new URL(req.url, 'http://localhost');
27 const presentationId = searchParams.get('id');
28 const role = searchParams.get('role') === 'speaker' ? 'speaker' : 'audience';
29
30 hub.registerClient(ws);
31
32 // Глобальный клиент (дашборд/редактор)
33 if (!presentationId) {
34 ws.on('close', () => hub.unregisterClient(ws));
35 return;
36 }
37
38 const presentation = store.getPresentation(presentationId);
39 if (!presentation) {
40 ws.send(JSON.stringify({ type: 'error', error: 'not_found' }));
41 ws.close(4004, 'presentation not found');
42 return;
43 }
44
45 hub.joinRoom(presentationId, ws, role);
46 ws._presentationId = presentationId;
47
48 const syncPayload = () => ({
49 type: 'sync',
50 presentationId,
51 title: presentation.title,
52 slides: presentation.slides,
53 slideIndex: presentation.currentSlide,
54 variables: presentation.variables,
55 music: presentation.music,
56 lua: presentation.lua,
57 commands: presentation.commands,
58 graph: presentation.graph,
59 });
60
61 ws.send(JSON.stringify(syncPayload()));
62
63 const roomVars = hub.getRoomVars(presentationId);
64 if (roomVars) ws.send(JSON.stringify({ type: 'vars', vars: roomVars }));
65
66 const audioState = hub.getAudioState(presentationId);
67 if (hub.hasAudioState(presentationId)) {
68 ws.send(JSON.stringify({ type: 'audio-state', state: audioState }));
69 }
70
71 const mediaStates = hub.getMediaStates(presentationId);
72 if (mediaStates.length) ws.send(JSON.stringify({ type: 'media-state', states: mediaStates }));
73
74 hub.getWindowStates(presentationId).forEach((state) => {
75 ws.send(JSON.stringify({ type: 'window-state', state }));
76 });
77 hub.getWindowFrames(presentationId).forEach((frame) => {
78 ws.send(JSON.stringify({ type: 'window-frame', elementId: frame.elementId, data: frame.data, cached: true }));
79 });
80
81 function sendWindowError(elementId, message) {
82 if (ws.readyState === 1) {
83 ws.send(JSON.stringify({ type: 'window-error', elementId, message }));
84 }
85 }
86
87 function findWindowElement(elementId) {
88 const fresh = store.getPresentation(presentationId) || presentation;
89 for (const slide of fresh.slides) {
90 const found = (slide.elements || []).find((element) => element.id === elementId && element.type === 'window');
91 if (found) return found;
92 }
93 return null;
94 }
95
96 async function startWindow(elementId, targetId) {
97 const element = findWindowElement(elementId);
98 if (!element) {
99 sendWindowError(elementId, 'Элемент окна не найден на слайдах');
100 return;
101 }
102 const wanted = String(targetId || element.targetId || '');
103 let lastFrameAt = 0;
104 hub.setWindowState(presentationId, elementId, {
105 active: true,
106 targetId: wanted,
107 targetTitle: element.targetTitle || '',
108 error: '',
109 });
110 ws.send(JSON.stringify({ type: 'window-starting', elementId, targetId: wanted }));
111 hub.broadcastRoom(presentationId, {
112 type: 'window-state',
113 state: hub.getWindowStates(presentationId).find((item) => item.elementId === elementId) || { elementId, active: true, targetId: wanted },
114 });
115 try {
116 await cdp.start(`${presentationId}::${elementId}`, presentationId, elementId, wanted, {
117 onStart({ target, viewport }) {
118 const state = hub.setWindowState(presentationId, elementId, {
119 active: true,
120 targetId: target.id,
121 targetTitle: target.title,
122 error: '',
123 width: viewport.width,
124 height: viewport.height,
125 });
126 hub.broadcastRoom(presentationId, { type: 'window-state', state });
127 },
128 onFrame({ data }) {
129 hub.setWindowFrame(presentationId, elementId, data);
130 const now = Date.now();
131 if (now - lastFrameAt < 55) return;
132 lastFrameAt = now;
133 hub.broadcastRoom(presentationId, { type: 'window-frame', elementId, data });
134 },
135 onError(error) {
136 const message = String(error && error.message ? error.message : error);
137 hub.setWindowState(presentationId, elementId, { active: false, error: message });
138 hub.broadcastRoom(presentationId, { type: 'window-error', elementId, message });
139 },
140 onClose() {
141 const states = hub.getWindowStates(presentationId);
142 const current = states.find((item) => item.elementId === elementId);
143 if (current && current.active) {
144 hub.setWindowState(presentationId, elementId, { active: false });
145 hub.broadcastRoom(presentationId, { type: 'window-stop', elementId });
146 }
147 },
148 });
149 } catch (error) {
150 const message = String(error && error.message ? error.message : error);
151 hub.setWindowState(presentationId, elementId, { active: false, error: message });
152 sendWindowError(elementId, message);
153 }
154 }
155
156 ws.on('message', (raw) => {
157 let msg;
158 try {
159 msg = JSON.parse(raw);
160 } catch (e) {
161 return;
162 }
163
164 const current = store.getPresentation(presentationId);
165 if (!current) return;
166
167 if (msg.type === 'navigate') {
168 const slideIndex = Math.max(
169 0,
170 Math.min(Number(msg.slideIndex) || 0, Math.max(current.slides.length - 1, 0))
171 );
172 current.currentSlide = slideIndex;
173 store.savePresentation(current);
174 hub.broadcastRoom(presentationId, {
175 type: 'sync',
176 presentationId,
177 title: current.title,
178 slides: current.slides,
179 slideIndex,
180 variables: current.variables,
181 music: current.music,
182 lua: current.lua,
183 commands: current.commands,
184 graph: current.graph,
185 });
186 hub.broadcastSessions();
187 }
188
189 if (msg.type === 'audio' && msg.command) {
190 if (role !== 'speaker') return;
191 hub.applyAudioCommand(presentationId, msg.command);
192 hub.broadcastRoom(presentationId, { type: 'audio', command: msg.command }, ws);
193 }
194
195 if (msg.type === 'vars' && msg.vars && typeof msg.vars === 'object') {
196 if (role !== 'speaker') return;
197 hub.setRoomVars(presentationId, msg.vars);
198 hub.broadcastRoom(presentationId, { type: 'vars', vars: msg.vars }, ws);
199 }
200
201 if (msg.type === 'media' && msg.command) {
202 if (role !== 'speaker') return;
203 hub.applyMediaCommand(presentationId, msg.command);
204 hub.broadcastRoom(presentationId, { type: 'media', command: msg.command }, ws);
205 }
206
207 if (msg.type === 'window-start') {
208 if (role !== 'speaker' || !msg.elementId) return;
209 startWindow(String(msg.elementId), msg.targetId);
210 }
211
212 if (msg.type === 'window-stop') {
213 if (role !== 'speaker' || !msg.elementId) return;
214 cdp.stop(`${presentationId}::${msg.elementId}`);
215 hub.clearWindowState(presentationId, String(msg.elementId));
216 hub.broadcastRoom(presentationId, { type: 'window-stop', elementId: String(msg.elementId) });
217 }
218
219 if (msg.type === 'window-input') {
220 if (role !== 'speaker' || !msg.elementId) return;
221 cdp
222 .input(`${presentationId}::${msg.elementId}`, msg.input)
223 .catch((error) => sendWindowError(String(msg.elementId), String(error.message || error)));
224 }
225
226 if (msg.type === 'window-targets') {
227 cdp.listTargets(true).then((targets) => {
228 if (ws.readyState === 1) {
229 ws.send(JSON.stringify({
230 type: 'window-targets',
231 targets: targets.map(({ id, title, url }) => ({ id, title, url })),
232 endpoint: cdp.ENDPOINT,
233 }));
234 }
235 });
236 }
237 });
238
239 ws.on('close', () => hub.unregisterClient(ws));
240 });
241
242 return wss;
243}
244
245module.exports = { setupWebSocket };