273 lines
8.3 KiB
JavaScript
273 lines
8.3 KiB
JavaScript
// Хаб реального времени: глобальные клиенты, комнаты, сессии, переменные и аудио-состояние
|
|
const store = require('./store');
|
|
const cdp = require('./cdp');
|
|
|
|
const clients = new Set();
|
|
const rooms = new Map(); // presentationId -> Set<ws>
|
|
const clientRooms = new WeakMap();
|
|
const clientRoles = new WeakMap();
|
|
const startedAt = new Map();
|
|
const roomVars = new Map(); // presentationId -> переменные сессии
|
|
const audioState = new Map(); // presentationId -> музыка/громкости
|
|
const mediaState = new Map(); // presentationId -> Map<elementId, media command>
|
|
const windowState = new Map(); // presentationId -> Map<elementId, состояние окна>
|
|
const windowFrames = new Map(); // presentationId -> Map<elementId, последний кадр>
|
|
|
|
const clamp01 = (v, d = 0) => Math.max(0, Math.min(1, Number.isFinite(Number(v)) ? Number(v) : d));
|
|
|
|
function send(ws, payload) {
|
|
if (ws.readyState === 1) ws.send(JSON.stringify(payload));
|
|
}
|
|
|
|
function broadcastAll(payload) {
|
|
const data = JSON.stringify(payload);
|
|
clients.forEach((ws) => {
|
|
if (ws.readyState === 1) ws.send(data);
|
|
});
|
|
}
|
|
|
|
function presentationsSnapshot() {
|
|
return { type: 'presentations', presentations: store.listPresentations() };
|
|
}
|
|
|
|
function sessionsSnapshot() {
|
|
const sessions = [];
|
|
for (const [presentationId, room] of rooms) {
|
|
if (room.size === 0) continue;
|
|
const p = store.getPresentation(presentationId);
|
|
let viewers = 0;
|
|
let presenters = 0;
|
|
room.forEach((client) => {
|
|
if (clientRoles.get(client) === 'speaker') presenters += 1;
|
|
else viewers += 1;
|
|
});
|
|
sessions.push({
|
|
presentationId,
|
|
title: p ? p.title : 'Без названия',
|
|
currentSlide: p ? p.currentSlide : 0,
|
|
slidesCount: p ? p.slides.length : 0,
|
|
viewers,
|
|
presenters,
|
|
startedAt: startedAt.get(presentationId) || Date.now(),
|
|
});
|
|
}
|
|
return { type: 'sessions', sessions };
|
|
}
|
|
|
|
function broadcastPresentations() {
|
|
broadcastAll(presentationsSnapshot());
|
|
}
|
|
|
|
function broadcastSessions() {
|
|
broadcastAll(sessionsSnapshot());
|
|
}
|
|
|
|
function registerClient(ws) {
|
|
clients.add(ws);
|
|
send(ws, presentationsSnapshot());
|
|
send(ws, sessionsSnapshot());
|
|
}
|
|
|
|
function cleanupRoom(presentationId) {
|
|
rooms.delete(presentationId);
|
|
startedAt.delete(presentationId);
|
|
roomVars.delete(presentationId);
|
|
audioState.delete(presentationId);
|
|
mediaState.delete(presentationId);
|
|
windowState.delete(presentationId);
|
|
windowFrames.delete(presentationId);
|
|
cdp.stopPresentation(presentationId);
|
|
// Эфир завершился: следующий зритель начинает с первого слайда.
|
|
const pres = store.getPresentation(presentationId);
|
|
if (pres && pres.currentSlide !== 0) {
|
|
pres.currentSlide = 0;
|
|
store.savePresentation(pres);
|
|
}
|
|
}
|
|
|
|
function unregisterClient(ws) {
|
|
clients.delete(ws);
|
|
const presentationId = clientRooms.get(ws);
|
|
if (!presentationId) return;
|
|
clientRooms.delete(ws);
|
|
clientRoles.delete(ws);
|
|
|
|
const room = rooms.get(presentationId);
|
|
if (!room) return;
|
|
room.delete(ws);
|
|
if (room.size === 0) cleanupRoom(presentationId);
|
|
broadcastSessions();
|
|
}
|
|
|
|
function joinRoom(presentationId, ws, role = 'audience') {
|
|
if (!rooms.has(presentationId)) {
|
|
rooms.set(presentationId, new Set());
|
|
startedAt.set(presentationId, Date.now());
|
|
}
|
|
rooms.get(presentationId).add(ws);
|
|
clientRooms.set(ws, presentationId);
|
|
clientRoles.set(ws, role === 'speaker' ? 'speaker' : 'audience');
|
|
broadcastSessions();
|
|
}
|
|
|
|
function broadcastRoom(presentationId, payload, exclude = null) {
|
|
const room = rooms.get(presentationId);
|
|
if (!room) return;
|
|
const data = JSON.stringify(payload);
|
|
room.forEach((ws) => {
|
|
if (ws !== exclude && ws.readyState === 1) ws.send(data);
|
|
});
|
|
}
|
|
|
|
function endSession(presentationId, reason = 'stopped') {
|
|
const room = rooms.get(presentationId);
|
|
if (!room) return false;
|
|
const payload = JSON.stringify({ type: 'session-ended', reason });
|
|
room.forEach((ws) => {
|
|
if (ws.readyState === 1) ws.send(payload);
|
|
clientRooms.delete(ws);
|
|
clientRoles.delete(ws);
|
|
});
|
|
cleanupRoom(presentationId);
|
|
broadcastSessions();
|
|
return true;
|
|
}
|
|
|
|
function listSessions() {
|
|
return sessionsSnapshot().sessions;
|
|
}
|
|
|
|
// ---- Переменные сессии ----
|
|
|
|
function setRoomVars(presentationId, vars) {
|
|
if (vars && typeof vars === 'object') roomVars.set(presentationId, vars);
|
|
}
|
|
|
|
function getRoomVars(presentationId) {
|
|
return roomVars.get(presentationId) || null;
|
|
}
|
|
|
|
// ---- Аудио-состояние сессии ----
|
|
|
|
const DEFAULT_AUDIO = { musicSrc: '', musicPlaying: false, bgm: 0.5, sfx: 0.8 };
|
|
|
|
function getAudioState(presentationId) {
|
|
return audioState.get(presentationId) || { ...DEFAULT_AUDIO };
|
|
}
|
|
|
|
function hasAudioState(presentationId) {
|
|
return audioState.has(presentationId);
|
|
}
|
|
|
|
// ---- Медиа (видео на слайде) ----
|
|
|
|
function applyMediaCommand(presentationId, command) {
|
|
if (!command || typeof command !== 'object' || !command.elementId) return;
|
|
const map = mediaState.get(presentationId) || new Map();
|
|
map.set(command.elementId, { ...command, at: Date.now() });
|
|
mediaState.set(presentationId, map);
|
|
}
|
|
|
|
function getMediaStates(presentationId) {
|
|
const map = mediaState.get(presentationId);
|
|
return map ? [...map.values()] : [];
|
|
}
|
|
|
|
// ---- Трансляция окна Chrome ----
|
|
|
|
function setWindowState(presentationId, elementId, patch = {}) {
|
|
const map = windowState.get(presentationId) || new Map();
|
|
const current = map.get(elementId) || {
|
|
elementId,
|
|
active: false,
|
|
targetId: '',
|
|
targetTitle: '',
|
|
error: '',
|
|
};
|
|
const next = { ...current, ...patch, elementId };
|
|
map.set(elementId, next);
|
|
windowState.set(presentationId, map);
|
|
return next;
|
|
}
|
|
|
|
function getWindowStates(presentationId) {
|
|
const map = windowState.get(presentationId);
|
|
return map ? [...map.values()] : [];
|
|
}
|
|
|
|
function clearWindowState(presentationId, elementId) {
|
|
const map = windowState.get(presentationId);
|
|
if (map) {
|
|
if (elementId) map.delete(elementId);
|
|
else map.clear();
|
|
if (!map.size) windowState.delete(presentationId);
|
|
}
|
|
const frames = windowFrames.get(presentationId);
|
|
if (frames) {
|
|
if (elementId) frames.delete(elementId);
|
|
else frames.clear();
|
|
if (!frames.size) windowFrames.delete(presentationId);
|
|
}
|
|
}
|
|
|
|
// Последний кадр трансляции: нужен зрителям, которые подключились позже,
|
|
// потому что CDP присылает новый кадр только при изменении страницы.
|
|
function setWindowFrame(presentationId, elementId, data) {
|
|
if (!data || typeof data !== 'string') return;
|
|
const map = windowFrames.get(presentationId) || new Map();
|
|
map.set(elementId, { data, at: Date.now() });
|
|
windowFrames.set(presentationId, map);
|
|
}
|
|
|
|
function getWindowFrames(presentationId) {
|
|
const map = windowFrames.get(presentationId);
|
|
if (!map) return [];
|
|
return [...map.entries()].map(([elementId, item]) => ({ elementId, data: item.data, at: item.at }));
|
|
}
|
|
|
|
function applyAudioCommand(presentationId, command) {
|
|
if (!command || typeof command !== 'object') return;
|
|
let state = audioState.get(presentationId);
|
|
if (!state) {
|
|
const presentation = store.getPresentation(presentationId);
|
|
const initialVolume = presentation && presentation.music ? presentation.music.volume : DEFAULT_AUDIO.bgm;
|
|
state = { ...DEFAULT_AUDIO, bgm: clamp01(initialVolume, DEFAULT_AUDIO.bgm) };
|
|
} else {
|
|
state = { ...state };
|
|
}
|
|
if (command.action === 'music') {
|
|
if (typeof command.src === 'string') state.musicSrc = command.src;
|
|
state.musicPlaying = command.play !== false;
|
|
}
|
|
if (command.action === 'musicStop') state.musicPlaying = false;
|
|
if (command.action === 'volumes') {
|
|
state.bgm = clamp01(command.bgm, state.bgm);
|
|
state.sfx = clamp01(command.sfx, state.sfx);
|
|
}
|
|
audioState.set(presentationId, state);
|
|
}
|
|
|
|
module.exports = {
|
|
registerClient,
|
|
unregisterClient,
|
|
joinRoom,
|
|
broadcastRoom,
|
|
broadcastAll,
|
|
broadcastPresentations,
|
|
broadcastSessions,
|
|
endSession,
|
|
listSessions,
|
|
setRoomVars,
|
|
getRoomVars,
|
|
getAudioState,
|
|
hasAudioState,
|
|
applyAudioCommand,
|
|
applyMediaCommand,
|
|
getMediaStates,
|
|
setWindowState,
|
|
getWindowStates,
|
|
setWindowFrame,
|
|
getWindowFrames,
|
|
clearWindowState,
|
|
};
|