Репозитории /
Promptly /
server/hub.js
hub.js
| 1 | // Хаб реального времени: глобальные клиенты, комнаты, сессии, переменные и аудио-состояние |
| 2 | const store = require('./store'); |
| 3 | const cdp = require('./cdp'); |
| 4 | |
| 5 | const clients = new Set(); |
| 6 | const rooms = new Map(); // presentationId -> Set<ws> |
| 7 | const clientRooms = new WeakMap(); |
| 8 | const clientRoles = new WeakMap(); |
| 9 | const startedAt = new Map(); |
| 10 | const roomVars = new Map(); // presentationId -> переменные сессии |
| 11 | const audioState = new Map(); // presentationId -> музыка/громкости |
| 12 | const mediaState = new Map(); // presentationId -> Map<elementId, media command> |
| 13 | const windowState = new Map(); // presentationId -> Map<elementId, состояние окна> |
| 14 | const windowFrames = new Map(); // presentationId -> Map<elementId, последний кадр> |
| 15 | |
| 16 | const clamp01 = (v, d = 0) => Math.max(0, Math.min(1, Number.isFinite(Number(v)) ? Number(v) : d)); |
| 17 | |
| 18 | function send(ws, payload) { |
| 19 | if (ws.readyState === 1) ws.send(JSON.stringify(payload)); |
| 20 | } |
| 21 | |
| 22 | function broadcastAll(payload) { |
| 23 | const data = JSON.stringify(payload); |
| 24 | clients.forEach((ws) => { |
| 25 | if (ws.readyState === 1) ws.send(data); |
| 26 | }); |
| 27 | } |
| 28 | |
| 29 | function presentationsSnapshot() { |
| 30 | return { type: 'presentations', presentations: store.listPresentations() }; |
| 31 | } |
| 32 | |
| 33 | function sessionsSnapshot() { |
| 34 | const sessions = []; |
| 35 | for (const [presentationId, room] of rooms) { |
| 36 | if (room.size === 0) continue; |
| 37 | const p = store.getPresentation(presentationId); |
| 38 | let viewers = 0; |
| 39 | let presenters = 0; |
| 40 | room.forEach((client) => { |
| 41 | if (clientRoles.get(client) === 'speaker') presenters += 1; |
| 42 | else viewers += 1; |
| 43 | }); |
| 44 | sessions.push({ |
| 45 | presentationId, |
| 46 | title: p ? p.title : 'Без названия', |
| 47 | currentSlide: p ? p.currentSlide : 0, |
| 48 | slidesCount: p ? p.slides.length : 0, |
| 49 | viewers, |
| 50 | presenters, |
| 51 | startedAt: startedAt.get(presentationId) || Date.now(), |
| 52 | }); |
| 53 | } |
| 54 | return { type: 'sessions', sessions }; |
| 55 | } |
| 56 | |
| 57 | function broadcastPresentations() { |
| 58 | broadcastAll(presentationsSnapshot()); |
| 59 | } |
| 60 | |
| 61 | function broadcastSessions() { |
| 62 | broadcastAll(sessionsSnapshot()); |
| 63 | } |
| 64 | |
| 65 | function registerClient(ws) { |
| 66 | clients.add(ws); |
| 67 | send(ws, presentationsSnapshot()); |
| 68 | send(ws, sessionsSnapshot()); |
| 69 | } |
| 70 | |
| 71 | function cleanupRoom(presentationId) { |
| 72 | rooms.delete(presentationId); |
| 73 | startedAt.delete(presentationId); |
| 74 | roomVars.delete(presentationId); |
| 75 | audioState.delete(presentationId); |
| 76 | mediaState.delete(presentationId); |
| 77 | windowState.delete(presentationId); |
| 78 | windowFrames.delete(presentationId); |
| 79 | cdp.stopPresentation(presentationId); |
| 80 | // Эфир завершился: следующий зритель начинает с первого слайда. |
| 81 | const pres = store.getPresentation(presentationId); |
| 82 | if (pres && pres.currentSlide !== 0) { |
| 83 | pres.currentSlide = 0; |
| 84 | store.savePresentation(pres); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | function unregisterClient(ws) { |
| 89 | clients.delete(ws); |
| 90 | const presentationId = clientRooms.get(ws); |
| 91 | if (!presentationId) return; |
| 92 | clientRooms.delete(ws); |
| 93 | clientRoles.delete(ws); |
| 94 | |
| 95 | const room = rooms.get(presentationId); |
| 96 | if (!room) return; |
| 97 | room.delete(ws); |
| 98 | if (room.size === 0) cleanupRoom(presentationId); |
| 99 | broadcastSessions(); |
| 100 | } |
| 101 | |
| 102 | function joinRoom(presentationId, ws, role = 'audience') { |
| 103 | if (!rooms.has(presentationId)) { |
| 104 | rooms.set(presentationId, new Set()); |
| 105 | startedAt.set(presentationId, Date.now()); |
| 106 | } |
| 107 | rooms.get(presentationId).add(ws); |
| 108 | clientRooms.set(ws, presentationId); |
| 109 | clientRoles.set(ws, role === 'speaker' ? 'speaker' : 'audience'); |
| 110 | broadcastSessions(); |
| 111 | } |
| 112 | |
| 113 | function broadcastRoom(presentationId, payload, exclude = null) { |
| 114 | const room = rooms.get(presentationId); |
| 115 | if (!room) return; |
| 116 | const data = JSON.stringify(payload); |
| 117 | room.forEach((ws) => { |
| 118 | if (ws !== exclude && ws.readyState === 1) ws.send(data); |
| 119 | }); |
| 120 | } |
| 121 | |
| 122 | function endSession(presentationId, reason = 'stopped') { |
| 123 | const room = rooms.get(presentationId); |
| 124 | if (!room) return false; |
| 125 | const payload = JSON.stringify({ type: 'session-ended', reason }); |
| 126 | room.forEach((ws) => { |
| 127 | if (ws.readyState === 1) ws.send(payload); |
| 128 | clientRooms.delete(ws); |
| 129 | clientRoles.delete(ws); |
| 130 | }); |
| 131 | cleanupRoom(presentationId); |
| 132 | broadcastSessions(); |
| 133 | return true; |
| 134 | } |
| 135 | |
| 136 | function listSessions() { |
| 137 | return sessionsSnapshot().sessions; |
| 138 | } |
| 139 | |
| 140 | // ---- Переменные сессии ---- |
| 141 | |
| 142 | function setRoomVars(presentationId, vars) { |
| 143 | if (vars && typeof vars === 'object') roomVars.set(presentationId, vars); |
| 144 | } |
| 145 | |
| 146 | function getRoomVars(presentationId) { |
| 147 | return roomVars.get(presentationId) || null; |
| 148 | } |
| 149 | |
| 150 | // ---- Аудио-состояние сессии ---- |
| 151 | |
| 152 | const DEFAULT_AUDIO = { musicSrc: '', musicPlaying: false, bgm: 0.5, sfx: 0.8 }; |
| 153 | |
| 154 | function getAudioState(presentationId) { |
| 155 | return audioState.get(presentationId) || { ...DEFAULT_AUDIO }; |
| 156 | } |
| 157 | |
| 158 | function hasAudioState(presentationId) { |
| 159 | return audioState.has(presentationId); |
| 160 | } |
| 161 | |
| 162 | // ---- Медиа (видео на слайде) ---- |
| 163 | |
| 164 | function applyMediaCommand(presentationId, command) { |
| 165 | if (!command || typeof command !== 'object' || !command.elementId) return; |
| 166 | const map = mediaState.get(presentationId) || new Map(); |
| 167 | map.set(command.elementId, { ...command, at: Date.now() }); |
| 168 | mediaState.set(presentationId, map); |
| 169 | } |
| 170 | |
| 171 | function getMediaStates(presentationId) { |
| 172 | const map = mediaState.get(presentationId); |
| 173 | return map ? [...map.values()] : []; |
| 174 | } |
| 175 | |
| 176 | // ---- Трансляция окна Chrome ---- |
| 177 | |
| 178 | function setWindowState(presentationId, elementId, patch = {}) { |
| 179 | const map = windowState.get(presentationId) || new Map(); |
| 180 | const current = map.get(elementId) || { |
| 181 | elementId, |
| 182 | active: false, |
| 183 | targetId: '', |
| 184 | targetTitle: '', |
| 185 | error: '', |
| 186 | }; |
| 187 | const next = { ...current, ...patch, elementId }; |
| 188 | map.set(elementId, next); |
| 189 | windowState.set(presentationId, map); |
| 190 | return next; |
| 191 | } |
| 192 | |
| 193 | function getWindowStates(presentationId) { |
| 194 | const map = windowState.get(presentationId); |
| 195 | return map ? [...map.values()] : []; |
| 196 | } |
| 197 | |
| 198 | function clearWindowState(presentationId, elementId) { |
| 199 | const map = windowState.get(presentationId); |
| 200 | if (map) { |
| 201 | if (elementId) map.delete(elementId); |
| 202 | else map.clear(); |
| 203 | if (!map.size) windowState.delete(presentationId); |
| 204 | } |
| 205 | const frames = windowFrames.get(presentationId); |
| 206 | if (frames) { |
| 207 | if (elementId) frames.delete(elementId); |
| 208 | else frames.clear(); |
| 209 | if (!frames.size) windowFrames.delete(presentationId); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | // Последний кадр трансляции: нужен зрителям, которые подключились позже, |
| 214 | // потому что CDP присылает новый кадр только при изменении страницы. |
| 215 | function setWindowFrame(presentationId, elementId, data) { |
| 216 | if (!data || typeof data !== 'string') return; |
| 217 | const map = windowFrames.get(presentationId) || new Map(); |
| 218 | map.set(elementId, { data, at: Date.now() }); |
| 219 | windowFrames.set(presentationId, map); |
| 220 | } |
| 221 | |
| 222 | function getWindowFrames(presentationId) { |
| 223 | const map = windowFrames.get(presentationId); |
| 224 | if (!map) return []; |
| 225 | return [...map.entries()].map(([elementId, item]) => ({ elementId, data: item.data, at: item.at })); |
| 226 | } |
| 227 | |
| 228 | function applyAudioCommand(presentationId, command) { |
| 229 | if (!command || typeof command !== 'object') return; |
| 230 | let state = audioState.get(presentationId); |
| 231 | if (!state) { |
| 232 | const presentation = store.getPresentation(presentationId); |
| 233 | const initialVolume = presentation && presentation.music ? presentation.music.volume : DEFAULT_AUDIO.bgm; |
| 234 | state = { ...DEFAULT_AUDIO, bgm: clamp01(initialVolume, DEFAULT_AUDIO.bgm) }; |
| 235 | } else { |
| 236 | state = { ...state }; |
| 237 | } |
| 238 | if (command.action === 'music') { |
| 239 | if (typeof command.src === 'string') state.musicSrc = command.src; |
| 240 | state.musicPlaying = command.play !== false; |
| 241 | } |
| 242 | if (command.action === 'musicStop') state.musicPlaying = false; |
| 243 | if (command.action === 'volumes') { |
| 244 | state.bgm = clamp01(command.bgm, state.bgm); |
| 245 | state.sfx = clamp01(command.sfx, state.sfx); |
| 246 | } |
| 247 | audioState.set(presentationId, state); |
| 248 | } |
| 249 | |
| 250 | module.exports = { |
| 251 | registerClient, |
| 252 | unregisterClient, |
| 253 | joinRoom, |
| 254 | broadcastRoom, |
| 255 | broadcastAll, |
| 256 | broadcastPresentations, |
| 257 | broadcastSessions, |
| 258 | endSession, |
| 259 | listSessions, |
| 260 | setRoomVars, |
| 261 | getRoomVars, |
| 262 | getAudioState, |
| 263 | hasAudioState, |
| 264 | applyAudioCommand, |
| 265 | applyMediaCommand, |
| 266 | getMediaStates, |
| 267 | setWindowState, |
| 268 | getWindowStates, |
| 269 | setWindowFrame, |
| 270 | getWindowFrames, |
| 271 | clearWindowState, |
| 272 | }; |