Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
699 lines (615 loc) · 30.4 KB
/
Copy pathserver.ts
File metadata and controls
699 lines (615 loc) · 30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
import "./app/lib/nodeVersionCheck"; // must stay first: exits on a too-old Node.js before anything else loads
import { createServer as createHttpServer, IncomingMessage, ServerResponse } from "http";
import { createServer as createHttpsServer } from "https";
import { readFileSync, existsSync } from "fs";
import { styleText } from "util";
import next from "next";
import { Server as SocketIOServer } from "socket.io";
import { bundleManager } from "./app/lib/BundleManager";
import { getDisplayConfigs, ensureDisplayId, setDisplayConfigs, DisplayConfig } from "./app/lib/displayState";
import { resolveTransition, TransitionConfig } from "./app/lib/transitions";
import { setContentChangedListener } from "./app/lib/contentEvents";
import { isAllowedOrigin, resolveSocketIdentity, SocketRole } from "./app/lib/socketAuth";
import { CLIENT_ADDRESS_HEADER, getTrustedProxyHops, resolveClientAddress } from "./app/lib/clientAddress";
import { getAllUsers } from "./app/lib/auth";
import { getOrCreateSetupCode } from "./app/lib/setupCode";
import { isHttpsDisabled, resolveServerTlsFiles } from "./app/lib/tlsFiles";
const dev = process.env.NODE_ENV !== "production";
const port = parseInt(process.env.PORT ?? "3000", 10);
const hostname = process.env.HOST ?? "0.0.0.0";
let memoryStart = process.memoryUsage.rss();
const startStamp = Date.now();
const tls = resolveServerTlsFiles();
const httpsDisabled = isHttpsDisabled();
const useHttps = !httpsDisabled && existsSync(tls.key) && existsSync(tls.cert);
// Shared server state
interface ActiveSlide {
bundle: string;
slide: string;
duration: number; // seconds, <=0 = manual
}
interface ServerState {
activeSlide: ActiveSlide | null;
connectedDisplays: number;
isCycling: boolean;
displayConfigs: DisplayConfig[];
displayStates: Record<string, ActiveSlide | null>;
displayConnections: Record<string, number>;
displayCycling: Record<string, boolean>;
displayQueuedNext: Record<string, string | null>;
displayAnnouncements: Record<string, { line1: string; line2: string; color: string } | null>;
displayStreams: Record<string, string[]>;
streams: StreamInfo[];
}
interface CycleSlide {
id: string;
duration?: number;
}
let connectedDisplays = 0;
let displayConfigs: DisplayConfig[] = getDisplayConfigs();
const displayStates: Record<string, ActiveSlide | null> = {};
const displayConnections: Record<string, number> = {};
const displayCycleTimers: Record<string, ReturnType<typeof setTimeout> | null> = {};
const displayCycleSlides: Record<string, CycleSlide[]> = {};
const displayCycleIndex: Record<string, number> = {};
const displayQueuedNext: Record<string, string | null> = {};
let io: SocketIOServer | null = null;
// Lower-third announcements
interface DisplayAnnouncement {
line1: string;
line2: string;
color: string;
}
const displayAnnouncements: Record<string, DisplayAnnouncement | null> = {};
// WebRTC streaming state
interface StreamInfo {
streamId: string;
name: string;
socketId: string;
}
const streams = new Map<string, StreamInfo>(); // streamId → info
const socketToStream = new Map<string, string>(); // socketId → streamId
const displayStreams = new Map<string, string[]>(); // displayId → streamIds shown, oldest first
const socketToWatchedStreams = new Map<string, Set<string>>(); // viewerSocketId → streamIds it watches
const streamOwners = new Map<string, string>(); // streamId → username of the streamer
/** Formats a duration in milliseconds as hours, minutes and seconds, e.g. "26h 03m 07s". */
function formatDuration(ms: number): string {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const pad = (value: number) => String(value).padStart(2, "0");
return `${hours}h ${pad(minutes)}m ${pad(seconds)}s`;
}
function showMemory() {
if (dev) {
const now = process.memoryUsage.rss();
const diff = now - memoryStart;
const uptime = formatDuration(Date.now() - startStamp);
// Live JS objects; unlike RSS, it drops back after garbage collection, so a steady rise points to a leak.
const heapUsed = process.memoryUsage().heapUsed;
const toMb = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(2)}mb`;
const uptimeLabel = styleText("cyan", "Uptime:");
const memoryLabel = styleText("green", "Memory now:");
const diffLabel = styleText("yellow", "Diff:");
const heapLabel = styleText("magenta", "Heap used:");
console.log(`${uptimeLabel} ${uptime} | ${memoryLabel} ${toMb(now)} | ${diffLabel} ${toMb(diff)} | ${heapLabel} ${toMb(heapUsed)}`);
}
}
function emitAdminStreams() {
if (!io) return;
io.to("admins").emit("streams:update", [...streams.values()]);
}
function getServerState(): ServerState {
return {
activeSlide: null,
connectedDisplays,
isCycling: Object.values(displayCycleTimers).some((timer) => timer !== null),
displayConfigs,
displayStates: { ...displayStates },
displayConnections: { ...displayConnections },
displayCycling: Object.fromEntries(
Object.entries(displayCycleTimers).map(([displayId, timer]) => [displayId, timer !== null])
),
displayQueuedNext: { ...displayQueuedNext },
displayAnnouncements: { ...displayAnnouncements },
displayStreams: Object.fromEntries(displayStreams),
streams: [...streams.values()],
};
}
interface EnrichedSlide extends ActiveSlide {
json?: object | null;
bundleMeta?: unknown;
transition?: TransitionConfig;
}
function resolveSlideTransition(bundle: string, slideId: string): TransitionConfig {
const meta = bundleManager.getMeta(bundle);
const entry = meta.slides?.find((s) => s.id === slideId);
return resolveTransition(entry?.transition, meta.defaultTransition);
}
function enrichSlideData(slide: ActiveSlide): EnrichedSlide {
return {
...slide,
json: bundleManager.getSlideJson(slide.bundle, slide.slide),
bundleMeta: bundleManager.getMeta(slide.bundle),
transition: resolveSlideTransition(slide.bundle, slide.slide),
};
}
function getBundleSlides(bundle: string): CycleSlide[] {
return bundleManager.getOrderedSlides(bundle, { activeOnly: true });
}
const FALLBACK_SLIDE_DURATION = 10; // seconds, for bundles without a default duration
/** The bundle's default slide duration in seconds (<=0 = manual); slides may override it. */
function getBundleBaseDuration(bundle: string): number {
const duration = bundleManager.getMeta(bundle).defaultDuration;
return typeof duration === "number" && Number.isFinite(duration) ? duration : FALLBACK_SLIDE_DURATION;
}
function resolveSlideDuration(slide: CycleSlide | undefined, fallbackDuration: number): number {
const override = slide?.duration;
if (typeof override === "number" && Number.isFinite(override) && override >= 0) return override;
return fallbackDuration;
}
function displayRoom(displayId: string) {
return `display:${displayId}`;
}
function normalizeDisplayKeys() {
const validIds = new Set(displayConfigs.map((conf) => conf.id));
for (const key of Object.keys(displayStates)) {
if (!validIds.has(key)) {
delete displayStates[key];
}
}
for (const key of Object.keys(displayConnections)) {
if (!validIds.has(key)) {
delete displayConnections[key];
}
}
for (const key of Object.keys(displayCycleTimers)) {
if (!validIds.has(key)) {
if (displayCycleTimers[key]) clearTimeout(displayCycleTimers[key]!);
delete displayCycleTimers[key];
delete displayCycleSlides[key];
delete displayCycleIndex[key];
delete displayQueuedNext[key];
}
}
for (const key of Object.keys(displayAnnouncements)) {
if (!validIds.has(key)) delete displayAnnouncements[key];
}
for (const conf of displayConfigs) {
if (!(conf.id in displayStates)) displayStates[conf.id] = null;
if (!(conf.id in displayConnections)) displayConnections[conf.id] = 0;
if (!(conf.id in displayCycleTimers)) displayCycleTimers[conf.id] = null;
}
}
function emitAdminState() {
if (!io) return;
io.to("admins").emit("state:sync", getServerState());
}
function emitDisplayState(displayId: string) {
if (!io) return;
io.to(displayRoom(displayId)).emit("display:state:sync", {
activeSlide: displayStates[displayId] ?? null,
connectedDisplays,
isCycling: displayCycleTimers[displayId] !== null,
displayConfigs,
displayStates: { [displayId]: displayStates[displayId] ?? null },
displayConnections: { [displayId]: displayConnections[displayId] ?? 0 },
});
}
/**
* Shows the display's current slide on its screens and sends the same content to the
* admins, so their live preview doesn't need to fetch it over HTTP.
*/
function broadcastActiveSlide(displayId: string) {
const active = displayStates[displayId];
if (!io || !active) return;
const slide = enrichSlideData(active);
io.to(displayRoom(displayId)).emit("slide:show", slide);
io.to("admins").emit("display:slide", { displayId, slide });
}
function emitDisplayStatesToAll() {
for (const conf of displayConfigs) {
emitDisplayState(conf.id);
}
}
// The active bundle is restored on server start, so it follows whatever bundle is put on air.
function persistActiveBundle(displayId: string, bundle: string) {
const confIndex = displayConfigs.findIndex((c) => c.id === displayId);
if (confIndex === -1 || displayConfigs[confIndex].activeBundle === bundle) return;
displayConfigs[confIndex] = { ...displayConfigs[confIndex], activeBundle: bundle };
setDisplayConfigs(displayConfigs);
}
function stopCycle(displayId: string) {
const timer = displayCycleTimers[displayId];
if (timer) {
clearTimeout(timer);
displayCycleTimers[displayId] = null;
}
}
/**
* Shows the display's current slide (`initial`) and, when it has a duration, cycles on
* through its bundle from there. The only place a newly chosen slide is broadcast, so
* displays load it once.
*/
function startCycle(displayId: string, initial: ActiveSlide) {
stopCycle(displayId);
if (initial.duration <= 0) {
broadcastActiveSlide(displayId);
return;
}
displayCycleSlides[displayId] = getBundleSlides(initial.bundle);
displayCycleIndex[displayId] = displayCycleSlides[displayId].findIndex((s) => s.id === initial.slide);
if (displayCycleIndex[displayId] < 0) displayCycleIndex[displayId] = 0;
const initialEntry = displayCycleSlides[displayId][displayCycleIndex[displayId]];
const initialDelay = resolveSlideDuration(initialEntry, initial.duration);
if (displayStates[displayId]) {
displayStates[displayId] = { ...displayStates[displayId]!, duration: initialDelay };
}
broadcastActiveSlide(displayId);
emitAdminState();
if (initialDelay <= 0) return;
const endCycle = () => {
stopCycle(displayId);
emitAdminState();
};
const tick = () => {
showMemory();
if (!displayStates[displayId]) return endCycle();
const currentActive = displayStates[displayId]!;
const bundle = currentActive.bundle;
displayCycleSlides[displayId] = getBundleSlides(bundle);
if (displayCycleSlides[displayId].length === 0) return endCycle();
const currentIdx = displayCycleSlides[displayId].findIndex((s) => s.id === currentActive.slide);
const queuedId = displayQueuedNext[displayId];
let nextIdx = currentIdx < 0 ? 0 : (currentIdx + 1) % displayCycleSlides[displayId].length;
if (queuedId) {
const queuedIdx = displayCycleSlides[displayId].findIndex((s) => s.id === queuedId);
if (queuedIdx >= 0) nextIdx = queuedIdx;
displayQueuedNext[displayId] = null;
}
displayCycleIndex[displayId] = nextIdx;
const nextEntry = displayCycleSlides[displayId][displayCycleIndex[displayId]];
const nextDelay = resolveSlideDuration(nextEntry, getBundleBaseDuration(bundle));
displayStates[displayId] = { bundle, slide: nextEntry.id, duration: nextDelay };
broadcastActiveSlide(displayId);
if (nextDelay <= 0) return endCycle();
emitAdminState();
displayCycleTimers[displayId] = setTimeout(tick, nextDelay * 1000);
};
displayCycleTimers[displayId] = setTimeout(tick, initialDelay * 1000);
}
function isMultiview(displayId: string): boolean {
return displayConfigs.some((conf) => conf.id === displayId && conf.streamMultiview);
}
/** The streams a display should show, in the form display clients connect with. */
function getAssignedStreams(displayId: string) {
return (displayStreams.get(displayId) ?? [])
.map((streamId) => streams.get(streamId))
.filter((stream): stream is StreamInfo => !!stream)
.map((stream) => ({ streamId: stream.streamId, streamName: stream.name, streamSocketId: stream.socketId }));
}
function emitAssignedStreams(displayId: string) {
io?.to(displayRoom(displayId)).emit("streams:assigned", { streams: getAssignedStreams(displayId) });
}
function setDisplayStreams(displayId: string, streamIds: string[]) {
if (streamIds.length > 0) displayStreams.set(displayId, streamIds);
else displayStreams.delete(displayId);
emitAssignedStreams(displayId);
}
/** In multiview the stream joins the grid; otherwise it replaces the one showing. */
function showStreamOnDisplay(displayId: string, streamId: string) {
const current = displayStreams.get(displayId) ?? [];
if (!isMultiview(displayId)) return setDisplayStreams(displayId, [streamId]);
if (!current.includes(streamId)) setDisplayStreams(displayId, [...current, streamId]);
}
function removeStreamFromDisplay(displayId: string, streamId: string) {
const current = displayStreams.get(displayId) ?? [];
if (current.includes(streamId)) setDisplayStreams(displayId, current.filter((id) => id !== streamId));
}
/** Without multiview a display keeps only its newest stream. */
function fitStreamsToLayout(displayId: string) {
const current = displayStreams.get(displayId) ?? [];
if (current.length > 1 && !isMultiview(displayId)) setDisplayStreams(displayId, current.slice(-1));
}
/** A new stream goes straight onto every display set to auto-show incoming streams. */
function autoShowStream(streamId: string) {
const targets = displayConfigs.filter((conf) => conf.autoShowStreams);
for (const conf of targets) showStreamOnDisplay(conf.id, streamId);
if (targets.length > 0) emitAdminState();
}
/** A stream moved to a new streamer socket; displays showing it reconnect to the new one. */
function reannounceStreamToDisplays(streamId: string) {
for (const [displayId, streamIds] of displayStreams.entries()) {
if (streamIds.includes(streamId)) emitAssignedStreams(displayId);
}
}
function cleanupStream(streamId: string, streamerSocketId: string) {
streams.delete(streamId);
streamOwners.delete(streamId);
socketToStream.delete(streamerSocketId);
for (const watched of socketToWatchedStreams.values()) watched.delete(streamId);
for (const displayId of [...displayStreams.keys()]) removeStreamFromDisplay(displayId, streamId);
io?.emit("stream:ended", { streamId });
emitAdminStreams();
emitAdminState();
}
/** Admins may preview any stream; a display may only watch the streams assigned to it. */
function canWatchStream(role: SocketRole, displayId: string, streamId: string): boolean {
if (role === "admin") return true;
if (role === "display") return displayStreams.get(displayId)?.includes(streamId) ?? false;
return false;
}
function isWatching(viewerSocketId: string, streamId: string): boolean {
return socketToWatchedStreams.get(viewerSocketId)?.has(streamId) ?? false;
}
/** Signals may only flow between a streamer and a viewer watching that streamer's stream. */
function canSignal(fromSocketId: string, toSocketId: string): boolean {
const toStreamId = socketToStream.get(toSocketId);
if (toStreamId && isWatching(fromSocketId, toStreamId)) return true;
const ownStreamId = socketToStream.get(fromSocketId);
return !!ownStreamId && isWatching(toSocketId, ownStreamId);
}
const app = next({ dev, turbopack: dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const trustedProxyHops = getTrustedProxyHops();
const handleWithClientAddress = (req: IncomingMessage, res: ServerResponse) => {
req.headers[CLIENT_ADDRESS_HEADER] = resolveClientAddress(req, trustedProxyHops);
return handle(req, res);
};
const httpServer = useHttps
? createHttpsServer(
{ key: readFileSync(tls.key), cert: readFileSync(tls.cert) },
handleWithClientAddress
)
: createHttpServer(handleWithClientAddress);
io = new SocketIOServer(httpServer, {
allowRequest: (req, callback) => callback(null, isAllowedOrigin(req)),
});
io.use(async (socket, next) => {
const identity = await resolveSocketIdentity(socket);
if (!identity) return next(new Error("unauthorized"));
socket.data.role = identity.role;
socket.data.username = identity.username;
next();
});
setContentChangedListener(() => io?.to("admins").emit("content:changed"));
io.on("connection", (socket) => {
const role: SocketRole = socket.data.role;
const requestedDisplayId = (socket.handshake.query.displayId as string) ?? "1";
const displayId = ensureDisplayId(requestedDisplayId);
if (role === "display") {
socket.join(displayRoom(displayId));
socket.join("displays");
displayConnections[displayId] = (displayConnections[displayId] ?? 0) + 1;
connectedDisplays++;
emitAdminState();
emitDisplayState(displayId);
if (displayStates[displayId]) {
socket.emit("slide:show", enrichSlideData(displayStates[displayId]!));
}
socket.emit("streams:assigned", { streams: getAssignedStreams(displayId) });
const announcement = displayAnnouncements[displayId];
if (announcement) {
socket.emit("announce:show", announcement);
}
socket.on("disconnect", () => {
displayConnections[displayId] = Math.max(0, (displayConnections[displayId] ?? 1) - 1);
connectedDisplays = Math.max(0, connectedDisplays - 1);
emitAdminState();
});
}
if (role === "admin") {
socket.join("admins");
for (const [id, active] of Object.entries(displayStates)) {
if (active) socket.emit("display:slide", { displayId: id, slide: enrichSlideData(active) });
}
socket.emit("state:sync", getServerState());
socket.on("slide:show", (data: ActiveSlide & { displayId: string }) => {
const targetId = ensureDisplayId(data.displayId);
displayStates[targetId] = { bundle: data.bundle, slide: data.slide, duration: data.duration };
displayQueuedNext[targetId] = null;
persistActiveBundle(targetId, data.bundle);
startCycle(targetId, displayStates[targetId]!);
emitAdminState();
});
socket.on("slide:clear", (data: { displayId: string }) => {
const targetId = ensureDisplayId(data.displayId);
stopCycle(targetId);
displayStates[targetId] = null;
displayQueuedNext[targetId] = null;
if (io) {
io.to(displayRoom(targetId)).emit("slide:clear");
}
emitAdminState();
});
socket.on("cycle:stop", (data: { displayId: string }) => {
const targetId = ensureDisplayId(data.displayId);
stopCycle(targetId);
emitAdminState();
});
socket.on("cycle:queueNext", (data: { displayId: string; slideId: string | null }) => {
const targetId = ensureDisplayId(data.displayId);
displayQueuedNext[targetId] = data.slideId ?? null;
emitAdminState();
});
socket.on("announce:show", (data: { displayId: string; line1: string; line2: string; color: string }) => {
const targetId = ensureDisplayId(data.displayId);
const payload: DisplayAnnouncement = {
line1: data.line1 ?? "",
line2: data.line2 ?? "",
color: data.color || "#d32f2f",
};
displayAnnouncements[targetId] = payload;
io?.to(displayRoom(targetId)).emit("announce:show", payload);
emitAdminState();
});
socket.on("announce:showAll", (data: { line1: string; line2: string; color: string }) => {
const payload: DisplayAnnouncement = {
line1: data.line1 ?? "",
line2: data.line2 ?? "",
color: data.color || "#d32f2f",
};
for (const conf of displayConfigs) {
displayAnnouncements[conf.id] = payload;
}
io?.to("displays").emit("announce:show", payload);
emitAdminState();
});
socket.on("announce:clearAll", () => {
for (const conf of displayConfigs) {
displayAnnouncements[conf.id] = null;
}
io?.to("displays").emit("announce:clear");
emitAdminState();
});
socket.on("bundle:meta", (data: { bundle: string; meta: Record<string, unknown>; displayId?: string }) => {
if (io) {
io.emit("bundle:meta", { bundle: data.bundle, meta: data.meta });
}
emitAdminState();
});
socket.on("bundle:activate", (data: { bundle: string; displayId: string }) => {
const targetId = ensureDisplayId(data.displayId);
const bundle = data?.bundle;
if (typeof bundle !== "string" || !bundle) return;
displayQueuedNext[targetId] = null;
const slides = getBundleSlides(bundle);
if (slides.length > 0) {
// startCycle applies the first slide's own duration on top of the bundle default.
displayStates[targetId] = { bundle, slide: slides[0].id, duration: getBundleBaseDuration(bundle) };
startCycle(targetId, displayStates[targetId]!);
}
persistActiveBundle(targetId, bundle);
emitAdminState();
});
socket.on("display:config", (data: { configs: DisplayConfig[] }) => {
const uniqueConfigs: DisplayConfig[] = [];
const seenIds = new Set<string>();
for (const config of data.configs) {
const id = config.id.trim() || `display-${uniqueConfigs.length + 1}`;
if (!seenIds.has(id)) {
seenIds.add(id);
// Preserve existing activeBundle if available
const existing = displayConfigs.find(c => c.id === id);
uniqueConfigs.push({
id,
name: config.name || `Display ${id}`,
activeBundle: existing?.activeBundle,
autoShowStreams: config.autoShowStreams === true,
streamMultiview: config.streamMultiview === true,
});
}
}
displayConfigs = uniqueConfigs.length > 0 ? uniqueConfigs : [{ id: "1", name: "Display 1" }];
setDisplayConfigs(displayConfigs);
normalizeDisplayKeys();
for (const conf of displayConfigs) fitStreamsToLayout(conf.id);
emitAdminState();
emitDisplayStatesToAll();
});
}
// --- WebRTC streaming signaling ---
if (role === "streamer") {
socket.on("stream:register", (data: { streamId: string; name: string }) => {
const existing = streams.get(data.streamId);
const isTakeover = !!existing && existing.socketId !== socket.id;
if (isTakeover) {
// Only the stream's own user may take it over — a streamer that reconnected
// before the server noticed its old connection dropped.
if (streamOwners.get(data.streamId) !== socket.data.username) return;
socketToStream.delete(existing.socketId);
}
// A socket owns one stream; drop its previous one instead of orphaning it.
const previousStreamId = socketToStream.get(socket.id);
if (previousStreamId && previousStreamId !== data.streamId) cleanupStream(previousStreamId, socket.id);
const isNew = !existing;
const info: StreamInfo = { streamId: data.streamId, name: data.name, socketId: socket.id };
streams.set(data.streamId, info);
streamOwners.set(data.streamId, socket.data.username);
socketToStream.set(socket.id, data.streamId);
if (isTakeover) reannounceStreamToDisplays(info.streamId);
emitAdminStreams();
if (isNew) autoShowStream(info.streamId);
});
socket.on("stream:unregister", (data: { streamId: string }) => {
if (streams.get(data.streamId)?.socketId !== socket.id) return;
cleanupStream(data.streamId, socket.id);
});
socket.on("disconnect", () => {
const streamId = socketToStream.get(socket.id);
if (streamId) cleanupStream(streamId, socket.id);
});
}
// Signal relay between a streamer and its viewers
socket.on("stream:watch", (data: { streamId: string }) => {
const stream = streams.get(data.streamId);
if (!stream) return;
if (!canWatchStream(role, displayId, data.streamId)) return;
const watched = socketToWatchedStreams.get(socket.id) ?? new Set<string>();
watched.add(data.streamId);
socketToWatchedStreams.set(socket.id, watched);
io?.to(stream.socketId).emit("stream:viewer:joined", { viewerSocketId: socket.id });
});
socket.on("stream:unwatch", (data: { streamId: string }) => {
const stream = streams.get(data.streamId);
socketToWatchedStreams.get(socket.id)?.delete(data.streamId);
if (!stream) return;
io?.to(stream.socketId).emit("stream:viewer:left", { viewerSocketId: socket.id });
});
socket.on("stream:signal", (data: { to: string; data: unknown }) => {
if (typeof data?.to !== "string" || !canSignal(socket.id, data.to)) return;
io?.to(data.to).emit("stream:signal", { from: socket.id, data: data.data });
});
if (role === "admin") {
socket.on("stream:show", (data: { streamId: string; displayId: string }) => {
const stream = streams.get(data.streamId);
if (!stream) return;
showStreamOnDisplay(ensureDisplayId(data.displayId), stream.streamId);
emitAdminState();
});
// Without a streamId every stream leaves the display.
socket.on("stream:clear", (data: { displayId: string; streamId?: string }) => {
const targetId = ensureDisplayId(data.displayId);
if (data.streamId) removeStreamFromDisplay(targetId, data.streamId);
else setDisplayStreams(targetId, []);
emitAdminState();
});
}
socket.on("disconnect", () => {
const watched = socketToWatchedStreams.get(socket.id);
if (!watched) return;
socketToWatchedStreams.delete(socket.id);
for (const streamId of watched) {
const stream = streams.get(streamId);
if (stream) io?.to(stream.socketId).emit("stream:viewer:left", { viewerSocketId: socket.id });
}
});
});
httpServer.listen(port, hostname, () => {
const proto = useHttps ? "https" : "http";
console.log(`> Ready on ${proto}://${hostname}:${port} [${dev ? "dev" : "production"}]`);
if (httpsDisabled) {
console.log(`> HTTPS disabled by DISABLE_HTTPS — terminate TLS in the reverse proxy in front of this server.`);
} else if (!useHttps) {
console.log(`> Running HTTP only — WebRTC screen/camera capture requires HTTPS on non-localhost origins.`);
console.log(`> To enable HTTPS, run "pnpm run gen-cert" (creates ${tls.cert} + ${tls.key}) and restart.`);
}
getAllUsers().then((users) => {
if (users.length === 0) getOrCreateSetupCode();
});
memoryStart = process.memoryUsage.rss();
// Boot active bundles for all displays
for (const config of displayConfigs) {
if (config.activeBundle) {
const slides = getBundleSlides(config.activeBundle);
if (slides.length > 0) {
const state = { bundle: config.activeBundle, slide: slides[0].id, duration: getBundleBaseDuration(config.activeBundle) };
displayStates[config.id] = state;
startCycle(config.id, state);
}
}
}
});
});