-
-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathindex.ts
2508 lines (2119 loc) · 83.8 KB
/
index.ts
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Tally Arbiter */
//Protocol, Network, Socket, Server libraries/variables
import fs from 'fs-extra';
import findPackageJson from "find-package-json";
import path from 'path';
import express from 'express';
import compression from 'compression';
import { RateLimiterMemory } from 'rate-limiter-flexible';
import bodyParser from 'body-parser';
import http from 'http';
import socketio from 'socket.io';
import ioClient from 'socket.io-client';
import { BehaviorSubject } from 'rxjs';
import { default as dotenv } from 'dotenv';
dotenv.config();
//TypeScript models
import { TallyInput } from './sources/_Source';
import { CloudClient } from "./_models/CloudClient";
import { FlashListenerClientResponse } from "./_models/FlashListenerClientResponse";
import { MessageListenerClientResponse } from "./_models/MessageListenerClientResponse";
import { ManageResponse } from './_models/ManageResponse';
import { LogItem } from "./_models/LogItem";
import { Source } from './_models/Source';
import { SourceType } from './_models/SourceType';
import { SourceTypeDataFields } from './_models/SourceTypeDataFields';
import { BusOption } from './_models/BusOption';
import { DeviceSource } from './_models/DeviceSource';
import { DeviceAction } from './_models/DeviceAction';
import { Device } from './_models/Device';
import { AddressTallyData, DeviceTallyData, SourceTallyData } from './_models/TallyData';
import { OutputType } from './_models/OutputType';
import { TSLClient } from './_models/TSLClient';
import { OutputTypeDataFields } from './_models/OutputTypeDataFields';
import { ListenerClientConnect } from './_models/ListenerClientConnect';
import { Manage } from './_models/Manage';
import { Addresses } from './_models/Addresses';
import { CloudListenerSocketData } from './_models/CloudListenerSocketData';
import { CloudDestination } from './_models/CloudDestination';
import { CloudDestinationSocket } from './_models/CloudDestinationSocket';
import { ListenerClient } from './_models/ListenerClient';
//TypeScript globals
import { TallyInputs } from './_globals/TallyInputs';
import { PortsInUse } from './_globals/PortsInUse';
import { RegisteredNetworkDiscoveryServices } from './_globals/RegisteredNetworkDiscoveryServices';
import { Actions } from './_globals/Actions';
// Helpers
import { uuidv4 } from './_helpers/uuid';
import { logFilePath, Logs, serverLogger, tallyDataFile } from './_helpers/logger';
import { getNetworkInterfaces } from './_helpers/networkInterfaces';
import { loadClassesFromFolder } from './_helpers/fileLoader';
import { UsePort } from './_decorators/UsesPort.decorator';
import { secondsToHms } from './_helpers/time';
import { currentConfig, getConfigRedacted, readConfig, SaveConfig, replaceConfig } from './_helpers/config';
import { validateConfig } from './_helpers/configValidator';
import { deleteEveryErrorReport, generateErrorReport, getErrorReport, getErrorReportsList, getUnreadErrorReportsList, markErrorReportAsRead, markErrorReportsAsRead } from './_helpers/errorReports';
import { DeviceState } from './_models/DeviceState';
import { VMixEmulator } from './_modules/VMix';
import { TSLListenerProvider } from './_modules/TSL';
import { ListenerProvider } from './_modules/_ListenerProvider';
import { InternalTestModeSource } from './sources/InternalTestMode';
import { authenticate, validateAccessToken, getUsersList, addUser, editUser, deleteUser } from './_helpers/auth';
import { Config } from './_models/Config';
import { bonjour } from './_helpers/mdns';
const version = findPackageJson(__dirname).next()?.value?.version || "unknown";
const devmode = process.argv.includes('--dev') || process.env.NODE_ENV === 'development';
if(devmode) logger('TallyArbiter running in Development Mode.', 'info');
//Rate limiter configurations
const maxWrongAttemptsByIPperDay = 1000;
const maxConsecutiveFailsByUsernameAndIP = 200;
const maxPageRequestPerMinute = 1000;
const limiterSlowBruteByIP = new RateLimiterMemory({
keyPrefix: 'login_fail_ip_per_day',
points: maxWrongAttemptsByIPperDay,
duration: 60 * 60 * 24, // Store number for 1 day since first fail
blockDuration: 60 * 60 * 24, // Block for 1 day
});
const limiterConsecutiveFailsByUsernameAndIP = new RateLimiterMemory({
keyPrefix: 'login_fail_consecutive_username_and_ip',
points: maxConsecutiveFailsByUsernameAndIP,
duration: 60 * 60 * 24, // Store number for 1 day since first fail
blockDuration: 60 * 60 * 2, // Block for 2 hours
});
const limiterServeUI = new RateLimiterMemory({
keyPrefix: 'UI_serve',
points: maxPageRequestPerMinute,
duration: 60, // Store number for 1 minute
blockDuration: 60 * 10, // Block for 10 minutes
});
//Tally Arbiter variables
var uiDistPath = path.join(__dirname, 'ui-dist');
if (!fs.existsSync(uiDistPath)) {
uiDistPath = path.join(__dirname, '..', 'ui-dist');
}
//Imported Sentry lib (imported only if prod and enabled from config)
var Sentry: any = undefined;
const listenPort: number = parseInt(process.env.PORT) || 4455;
const app = express();
const httpServer = new http.Server(app);
const io = new socketio.Server(httpServer, { allowEIO3: true });
const socketupdates_Settings: string[] = ['sources', 'devices', 'device_sources', 'device_states', 'listener_clients', 'tsl_clients', 'cloud_destinations', 'cloud_keys', 'cloud_clients', 'PortsInUse', 'networkDiscovery', 'vmix_clients', "addresses"];
const socketupdates_Producer: string[] = ['sources', 'devices', 'device_sources', 'device_states', 'listener_clients'];
const socketupdates_Companion: string[] = ['sources', 'devices', 'device_sources', 'device_states', 'listener_clients', 'tsl_clients', 'cloud_destinations'];
var listener_clients = []; //array of connected listener clients (web, python, relay, etc.)
let vMixEmulator: VMixEmulator;
export let tslListenerProvider: TSLListenerProvider;
let tsl_clients_interval: NodeJS.Timer | null = null;
var cloud_destinations: CloudDestination[] = []; //array of Tally Arbiter Cloud Destinations (host, port, key)
var cloud_destinations_sockets: CloudDestinationSocket[] = []; //array of actual socket connections
var cloud_keys: string[] = []; //array of Tally Arbiter Cloud Sources (key only)
var cloud_clients: CloudClient[] = []; //array of Tally Arbiter Cloud Clients that have connected with a key
var TestMode = false; //if the system is in test mode or not
const SourceClients: Record<string, TallyInput> = {};
UsePort(listenPort, "reserved");
UsePort(80, "reserved");
UsePort(443, "reserved");
const addresses = new BehaviorSubject<Addresses>({});
addresses.subscribe(() => {
UpdateSockets("addresses");
});
PortsInUse.subscribe(() => {
UpdateSockets('PortsInUse');
})
RegisteredNetworkDiscoveryServices.subscribe(() => {
UpdateSockets('networkDiscovery');
})
var sources: Source[] = []; // the configured tally sources
export var devices: Device[] = []; // the configured tally devices
export var device_sources: DeviceSource[] = []; // the configured tally device-source mappings
var device_actions: DeviceAction[] = []; // the configured device output actions
var currentDeviceTallyData: DeviceTallyData = {}; // tally data (=bus array) per device id (linked busses taken into account)
var currentSourceTallyData: SourceTallyData = {}; // tally data (=bus array) per device source id
function startUp() {
loadClassesFromFolder("actions");
loadClassesFromFolder("sources");
loadConfig();
initialSetup();
DeleteInactiveListenerClients();
process.on('uncaughtException', (err: Error) => {
if (!process.versions.hasOwnProperty('electron')) {
generateAndSendErrorReport(err);
}
});
}
//Sentry Monitoring Setup
if (
process.env.SENTRY_ENABLED &&
!devmode &&
currentConfig.remoteErrorReporting == true
) {
import("@sentry/node").then((ImportedSentry) => {
Sentry = ImportedSentry;
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampleRate: 1.0,
release: "TallyArbiter@" + process.env.npm_package_version,
environment: 'production'
});
});
}
//sets up the REST API and GUI pages and starts the Express server that will listen for incoming requests
function initialSetup() {
logger('Setting up the Main HTTP Server.', 'info-quiet');
app.disable('x-powered-by');
app.use(bodyParser.json({ type: 'application/json' }));
app.use(compression());
//about the author, this program, etc.
app.get('/', (req, res) => {
limiterServeUI.consume(req.ip).then((data) => {
res.sendFile('index.html', { root: uiDistPath });
}).catch((data) => {
res.status(429).send('Too Many Requests');
});
});
//serve up any files in the ui-dist folder
app.use(express.static(uiDistPath));
app.use((req, res) => {
res.status(404).send({error: true, url: req.originalUrl + ' not found.'});
});
logger('Main HTTP Server Complete.', 'info-quiet');
bonjour.publish({
name: 'tallyarbiter-'+(currentConfig["uuid"] || "unknown"),
type: 'tally-arbiter',
port: 4455,
txt: {
version: version,
uuid: (currentConfig["uuid"] || "unknown")
}
});
logger('TallyArbiter advertised over MDNS.', 'info-quiet');
logger('Starting socket.IO Setup.', 'info-quiet');
let tmpSocketAccessTokens: string[] = [];
io.sockets.on('connection', (socket) => {
const ipAddr = socket.handshake.address;
const requireRole = (role: string) => {
return new Promise((resolve, reject) => {
if(typeof(tmpSocketAccessTokens[socket.id]) === undefined) {
let error_msg = "Access token required. Please login to use this feature.";
socket.emit('error', error_msg);
reject(error_msg);
}
let access_token = tmpSocketAccessTokens[socket.id];
validateAccessToken(access_token).then((user) => {
if(user.roles.includes(role) || user.roles.includes("admin")) {
resolve(user);
} else {
let error_msg = "Access denied. You are not authorized to do this.";
socket.emit('error', error_msg);
reject(error_msg);
}
}).catch((err) => {
socket.emit('error', err.message);
reject(err.message);
});
});
}
socket.on('login', (username: string, password: string) => {
authenticate(username, password).then((result) => {
socket.emit('login_response', { loginOk: true, message: "", accessToken: result.access_token });
}).catch((error) => {
logger(`User ${username} (ip addr ${ipAddr}) has attempted a login (${error})`);
//wrong credentials
Promise.all([
limiterConsecutiveFailsByUsernameAndIP.consume(ipAddr),
limiterSlowBruteByIP.consume(`${username}_${ipAddr}`)
]).then((values) => {
//rate limits not exceeded
let points = values[0].remainingPoints;
let message = "Wrong username or password!";
if(points < 10) {
message += " Remaining attemps:"+points;
}
socket.emit('login_response', { loginOk: false, message: message, access_token: "" });
}).catch((error) => {
//rate limits exceeded
let retrySecs = 1;
try{
retrySecs = Math.round(error.msBeforeNext / 1000) || 1;
} catch(e) {
retrySecs = Math.round(error[0].msBeforeNext / 1000) || 1;
}
socket.emit('login_response', { loginOk: false, message: "Too many attemps! Please try "+secondsToHms(retrySecs)+" later.", access_token: "" });
});
});
});
socket.on('access_token', (access_token: string) => {
tmpSocketAccessTokens[socket.id] = access_token;
});
socket.on('version', () => {
socket.emit('version', version);
});
socket.on('externalAddress', () => {
socket.emit('externalAddress', currentConfig.externalAddress);
});
/*socket.on('get_remote_error_opt', () => {
socket.emit('get_', currentConfig.remoteErrorReporting);
})*/
socket.on('interfaces', () => {
socket.emit('interfaces', getNetworkInterfaces());
});
socket.on('sources', () => { // sends the configured Sources to the socket
socket.emit('sources', getSources());
});
socket.on('devices', () => { // sends the configured Devices to the socket
socket.emit('devices', devices);
});
socket.on('device_sources', () => { // sends the configured Device Sources to the socket
socket.emit('device_sources', device_sources);
});
socket.on('device_actions', () => { // sends the configured Device Actions to the socket
socket.emit('device_actions', device_actions);
});
socket.on('bus_options', () => { // sends the Bus Options (preview, program) to the socket
socket.emit('bus_options', currentConfig.bus_options);
});
socket.on('listenerclient_connect', function(obj: ListenerClientConnect) {
/*
This is the new listener client API, all clients should connect and send a JSON object with these properties:
deviceId
internalId (string used internally in your software, passed as parameter on flash and reassign). This is optional. If you don't pass this, it will be assigned to the id used internally by TallyArbiter
listenerType (string to be displayed)
canBeReassigned (bool)
canBeFlashed (bool)
supportsChat (bool)
*/
if(typeof obj !== 'object' && obj !== null) {
logger(`Received JSON object: ${obj}`, 'info-quiet'); //Log the raw JSON to console
obj = JSON.parse(String(obj)); //Re-parse JSON
}
let deviceId = obj.deviceId;
let device = GetDeviceByDeviceId(deviceId);
let oldDeviceId = null;
if ((deviceId === 'null') || (device.id === 'unassigned')) {
if (devices.length > 0) {
oldDeviceId = deviceId;
deviceId = devices[0].id;
socket.emit('error', 'Invalid Device Id specified. Reassigning to the first Device on the server.');
}
else {
//send error state
socket.emit('error', 'No Devices are configured in Tally Arbiter.');
}
}
let listenerType = obj.listenerType ? obj.listenerType : 'client';
let canBeReassigned = obj.canBeReassigned ? obj.canBeReassigned : false;
let canBeFlashed = obj.canBeFlashed ? obj.canBeFlashed : false;
let supportsChat = obj.supportsChat ? obj.supportsChat : false;
socket.join('device-' + deviceId);
let deviceName = GetDeviceByDeviceId(deviceId).name;
logger(`Listener Client Connected. Type: ${listenerType} Device: ${deviceName}`, 'info');
let ipAddress = socket.handshake.address;
let datetimeConnected = new Date().getTime();
let clientId = AddListenerClient(socket.id, deviceId, obj.internalId, listenerType, ipAddress, datetimeConnected, canBeReassigned, canBeFlashed, supportsChat);
if (supportsChat) {
socket.join('messaging');
}
else {
socket.leave('messaging');
}
socket.emit('bus_options', currentConfig.bus_options);
socket.emit('devices', devices);
socket.emit('device_states', getDeviceStates(deviceId));
if (oldDeviceId !== null) {
//sends a reassign command to officially reassign the listener client to the new device ID since the first one was invalid
ReassignListenerClient(clientId, oldDeviceId, deviceId);
}
});
socket.on('device_states', (deviceId: string) => {
socket.emit('device_states', getDeviceStates(deviceId));
});
socket.on('settings', () => {
requireRole("settings").then((user) => {
socket.join('settings');
socket.join('messaging');
socket.emit('initialdata', getSourceTypes(), getSourceTypeDataFields(), addresses.value, getOutputTypes(), getOutputTypeDataFields(), currentConfig.bus_options, getSources(), devices, device_sources, device_actions, getDeviceStates(), tslListenerProvider.tsl_clients, cloud_destinations, cloud_keys, cloud_clients);
socket.emit('listener_clients', listener_clients);
socket.emit('logs', Logs);
socket.emit('PortsInUse', PortsInUse.value);
socket.emit('networkDiscovery', RegisteredNetworkDiscoveryServices.value);
socket.emit('tslclients_1secupdate', currentConfig.tsl_clients_1secupdate);
}).catch((e) => {console.error(e);});
});
socket.on('producer', () => {
requireRole("producer").then((user) => {
socket.join('producer');
socket.join('messaging');
socket.emit('sources', getSources());
socket.emit('devices', devices);
socket.emit('bus_options', currentConfig.bus_options);
socket.emit('listener_clients', listener_clients);
socket.emit('device_states', getDeviceStates());
}).catch((e) => {console.error(e);});
});
socket.on('companion', () => {
socket.join('companion');
socket.emit('sources', getSources());
socket.emit('devices', devices);
socket.emit('bus_options', currentConfig.bus_options);
socket.emit('device_sources', device_sources);
socket.emit('device_states', getDeviceStates());
socket.emit('listener_clients', listener_clients);
socket.emit('tsl_clients', tslListenerProvider.tsl_clients);
socket.emit('cloud_destinations', cloud_destinations);
});
socket.on('flash', (clientId) => {
FlashListenerClient(clientId);
});
socket.on('messaging_client', (clientId: {
relayGroupId?: string;
gpoGroupId?: string;
}, type: string, socketid: string, message: string) => {
MessageListenerClient(clientId, type, socketid, message);
});
socket.on('reassign', (clientId: string, oldDeviceId: string, deviceId: string) => {
ReassignListenerClient(clientId, oldDeviceId, deviceId);
});
socket.on('listener_reassign', (oldDeviceId: string, deviceId: string) => {
socket.leave('device-' + oldDeviceId);
socket.join('device-' + deviceId);
for (let i = 0; i < listener_clients.length; i++) {
if (listener_clients[i].socketId === socket.id) {
listener_clients[i].deviceId = deviceId;
listener_clients[i].inactive = false;
break;
}
}
let oldDeviceName = GetDeviceByDeviceId(oldDeviceId).name;
let deviceName = GetDeviceByDeviceId(deviceId).name;
logger(`Listener Client reassigned from ${oldDeviceName} to ${deviceName}`, 'info');
UpdateSockets('listener_clients');
UpdateCloud('listener_clients');
socket.emit('device_states', getDeviceStates());
});
socket.on('listener_reassign_relay', (relayGroupId, oldDeviceId, deviceId) => {
let canRemove = true;
for (let i = 0; i < listener_clients.length; i++) {
if (listener_clients[i].socketId === socket.id) {
if (listener_clients[i].deviceId === oldDeviceId) {
if (listener_clients[i].relayGroupId !== relayGroupId) {
canRemove = false;
break;
}
}
}
}
if (canRemove) {
//no other relay groups on this socket are using the old device ID, so we can safely leave that room
socket.leave('device-' + oldDeviceId);
}
socket.join('device-' + deviceId);
for (let i = 0; i < listener_clients.length; i++) {
if (listener_clients[i].relayGroupId === relayGroupId) {
listener_clients[i].deviceId = deviceId;
}
}
let oldDeviceName = GetDeviceByDeviceId(oldDeviceId).name;
let deviceName = GetDeviceByDeviceId(deviceId).name;
logger(`Listener Client reassigned from ${oldDeviceName} to ${deviceName}`, 'info');
UpdateSockets('listener_clients');
UpdateCloud('listener_clients');
});
socket.on('listener_reassign_gpo', (gpoGroupId, oldDeviceId, deviceId) => {
let canRemove = true;
for (let i = 0; i < listener_clients.length; i++) {
if (listener_clients[i].socketId === socket.id) {
if (listener_clients[i].deviceId === oldDeviceId) {
if (listener_clients[i].gpoGroupId !== gpoGroupId) {
canRemove = false;
break;
}
}
}
}
if (canRemove) {
//no other gpo groups on this socket are using the old device ID, so we can safely leave that room
socket.leave('device-' + oldDeviceId);
}
socket.join('device-' + deviceId);
for (let i = 0; i < listener_clients.length; i++) {
if (listener_clients[i].gpoGroupId === gpoGroupId) {
listener_clients[i].deviceId = deviceId;
}
}
let oldDeviceName = GetDeviceByDeviceId(oldDeviceId).name;
let deviceName = GetDeviceByDeviceId(deviceId).name;
logger(`Listener Client reassigned from ${oldDeviceName} to ${deviceName}`, 'info');
UpdateSockets('listener_clients');
UpdateCloud('listener_clients');
});
socket.on('listener_reassign_object', (reassignObj) => {
socket.leave('device-' + reassignObj.oldDeviceId);
socket.join('device-' + reassignObj.newDeviceId);
for (let i = 0; i < listener_clients.length; i++) {
if (listener_clients[i].socketId === socket.id) {
listener_clients[i].deviceId = reassignObj.newDeviceId;
listener_clients[i].inactive = false;
break;
}
}
let oldDeviceName = GetDeviceByDeviceId(reassignObj.oldDeviceId).name;
let deviceName = GetDeviceByDeviceId(reassignObj.newDeviceId).name;
logger(`Listener Client reassigned from ${oldDeviceName} to ${deviceName}`, 'info');
UpdateSockets('listener_clients');
UpdateCloud('listener_clients');
socket.emit('device_states', getDeviceStates());
});
socket.on('listener_delete', (clientId) => { // emitted by the Settings page when an inactive client is being removed manually
requireRole("settings:listeners").then((user) => {
for (let i = listener_clients.length - 1; i >= 0; i--) {
if (listener_clients[i].id === clientId) {
logger(`Inactive Client removed: ${listener_clients[i].id}`, 'info');
listener_clients.splice(i, 1);
break;
}
}
UpdateSockets('listener_clients');
UpdateCloud('listener_clients');
}).catch((e) => {console.error(e);});
});
socket.on('cloud_destination_reconnect', (cloudDestinationId) => {
StartCloudDestination(cloudDestinationId);
});
socket.on('cloud_destination_disconnect', (cloudDestinationId) => {
StopCloudDestination(cloudDestinationId);
});
socket.on('cloud_client', (key) => {
let ipAddress = socket.handshake.address;
if (cloud_keys.includes(key)) {
let datetimeConnected = new Date().getTime();
logger(`Cloud Client Connected: ${ipAddress}`, 'info');
AddCloudClient(socket.id, key, ipAddress, datetimeConnected);
}
else {
socket.emit('invalidkey');
logger(`Cloud Client ${ipAddress} attempted connection with an invalid key: ${key}`, 'info');
socket.disconnect();
}
});
socket.on('cloud_sources', (key, data) => {
let cloudClientId = GetCloudClientBySocketId(socket.id).id;
//loop through the received array and if an item in the array isn't already in the sources array, add it, and attach the cloud ID as a property
if (cloud_keys.includes(key)) {
for (let i = 0; i < data.length; i++) {
let found = false;
for (let j = 0; j < sources.length; j++) {
if (data[i].id === sources[j].id) {
found = true;
sources[j].sourceTypeId = data[i].sourceTypeId;
sources[j].name = data[i].name;
sources[j].connected = data[i].connected;
sources[j].cloudConnection = true;
sources[j].cloudClientId = cloudClientId;
break;
}
}
if (!found) {
data[i].cloudConnection = true;
data[i].cloudClientId = cloudClientId;
sources.push(data[i]);
}
}
for (let i = 0; i < sources.length; i++) {
let found = false;
if (sources[i].cloudClientId === cloudClientId) {
for (let j = 0; j < data.length; j++) {
if (sources[i].id === data[j].id) {
found = true;
break;
}
}
if (!found) {
//the client was deleted on the local source, so we should delete it here as well
sources.splice(i, 1);
}
}
}
UpdateSockets('sources');
}
else {
socket.emit('invalidkey');
socket.disconnect();
}
});
socket.on('cloud_devices', (key, data) => {
let cloudClientId = GetCloudClientBySocketId(socket.id).id;
//loop through the received array and if an item in the array isn't already in the devices array, add it, and attach the cloud ID as a property
if (cloud_keys.includes(key)) {
for (let i = 0; i < data.length; i++) {
let found = false;
for (let j = 0; j < devices.length; j++) {
if (data[i].id === devices[j].id) {
found = true;
devices[j].name = data[j].name;
devices[j].description = data[j].description;
devices[j].tslAddress = data[j].tslAddress;
devices[j].enabled = data[j].enabled;
devices[j].cloudConnection = true;
devices[j].cloudClientId = cloudClientId;
break;
}
}
if (!found) {
data[i].cloudConnection = true;
data[i].cloudClientId = cloudClientId;
devices.push(data[i]);
}
}
for (let i = 0; i < devices.length; i++) {
let found = false;
if (devices[i].cloudClientId === cloudClientId) {
for (let j = 0; j < data.length; j++) {
if (devices[i].id === data[j].id) {
found = true;
break;
}
}
if (!found) {
//the client was deleted on the local source, so we should delete it here as well
devices.splice(i, 1);
}
}
}
UpdateSockets('devices');
}
else {
socket.emit('invalidkey');
socket.disconnect();
}
});
socket.on('cloud_device_sources', (key, data) => {
let cloudClientId = GetCloudClientBySocketId(socket.id).id;
//loop through the received array and if an item in the array isn't already in the device sources array, add it, and attach the cloud ID as a property
if (cloud_keys.includes(key)) {
for (let i = 0; i < data.length; i++) {
let found = false;
for (let j = 0; j < device_sources.length; j++) {
if (data[i].id === device_sources[j].id) {
found = true;
break;
}
}
if (!found) {
data[i].cloudConnection = true;
data[i].cloudClientId = cloudClientId;
device_sources.push(data[i]);
}
}
for (let i = 0; i < device_sources.length; i++) {
let found = false;
if (device_sources[i].cloudClientId === cloudClientId) {
for (let j = 0; j < data.length; j++) {
if (device_sources[i].id === data[j].id) {
found = true;
break;
}
}
if (!found) {
//the client was deleted on the local source, so we should delete it here as well
device_sources.splice(i, 1);
}
}
}
}
else {
socket.emit('invalidkey');
socket.disconnect();
}
});
socket.on('cloud_listeners', (key: string, data: CloudListenerSocketData[]) => {
let cloudClientId = GetCloudClientBySocketId(socket.id).id;
//loop through the received array and if an item in the array isn't already in the listener_clients array, add it, and attach the cloud ID as a property
if (cloud_keys.includes(key)) {
for (let i = 0; i < data.length; i++) {
let found = false;
for (let j = 0; j < listener_clients.length; j++) {
if (data[i].id === listener_clients[j].id) {
found = true;
listener_clients[j].socketId = data[i].socketId;
listener_clients[j].deviceId = data[i].deviceId;
listener_clients[j].internalId = data[i].id;
listener_clients[j].listenerType = data[i].listenerType;
listener_clients[j].ipAddress = data[i].ipAddress;
listener_clients[j].datetimeConnected = data[i].datetimeConnected;
listener_clients[j].inactive = data[i].inactive;
listener_clients[j].cloudConnection = true;
listener_clients[j].cloudClientId = cloudClientId;
break;
}
}
if (!found) {
data[i].cloudConnection = true;
data[i].cloudClientId = cloudClientId;
listener_clients.push(data[i]);
}
}
for (let i = 0; i < listener_clients.length; i++) {
let found = false;
if (listener_clients[i].cloudClientId === cloudClientId) {
for (let j = 0; j < data.length; j++) {
if (listener_clients[i].id === data[j].id) {
found = true;
break;
}
}
if (!found) {
//the client was deleted on the local source, so we should delete it here as well
listener_clients.splice(i, 1);
}
}
}
UpdateSockets('listener_clients');
}
else {
socket.emit('invalidkey');
socket.disconnect();
}
});
socket.on('cloud_data', (key: string, sourceId: string, tallyObj: SourceTallyData) => {
if (cloud_keys.includes(key)) {
processSourceTallyData(sourceId, tallyObj);
}
else {
socket.emit('invalidkey');
socket.disconnect();
}
});
socket.on('manage', (arbiterObj: Manage) => {
requireRole("settings").then((user) => {
TallyArbiter_Manage(arbiterObj, tmpSocketAccessTokens[socket.id]).then((response) => {
io.to('settings').emit('manage_response', response);
});
}).catch((e) => {console.error(e);});
});
socket.on('reconnect_source', (sourceId: string) => {
SourceClients[sourceId]?.reconnect();
});
socket.on('listener_clients', () => {
socket.emit('listener_clients', listener_clients);
});
socket.on('tsl_clients', () => {
socket.emit('tsl_clients', tslListenerProvider.tsl_clients);
});
socket.on('cloud_destinations', () => {
socket.emit('cloud_destinations', cloud_destinations);
});
socket.on('cloud_keys', () => {
socket.emit('cloud_keys', cloud_keys);
});
socket.on('cloud_clients', () => {
socket.emit('cloud_clients', cloud_clients);
});
socket.on('testmode', (value: boolean) => {
requireRole("settings:testing").then((user) => {
ToggleTestMode(value);
}).catch((err) => { console.error(err); });
});
socket.on('tslclients_1secupdate', (value: boolean) => {
requireRole("settings:listeners").then((user) => {
currentConfig.tsl_clients_1secupdate = value;
SaveConfig();
TSLClients_1SecUpdate(value);
}).catch((err) => { console.error(err); });
})
socket.on('messaging', (type: string, message: string) => {
SendMessage(type, socket.id, message);
});
socket.on('get_error_reports', () => {
socket.emit('error_reports', getErrorReportsList());
});
socket.on('get_unread_error_reports', () => {
requireRole("admin").then((user) => {
socket.emit('unread_error_reports', getUnreadErrorReportsList());
}).catch((err) => { console.error(err); });
});
socket.on('get_error_report', (errorReportId: string) => {
requireRole("admin").then((user) => {
markErrorReportAsRead(errorReportId);
socket.emit('error_report', getErrorReport(errorReportId));
}).catch((err) => { console.error(err); });
});
socket.on('mark_error_reports_as_read', () => {
requireRole("admin").then((user) => {
markErrorReportsAsRead();
}).catch((err) => { console.error(err); });
});
socket.on('delete_every_error_report', () => {
requireRole("admin").then((user) => {
deleteEveryErrorReport();
}).catch((err) => { console.error(err); });
});
socket.on('users', () => {
requireRole("settings:users").then((user) => {
socket.emit('users', getUsersList());
}).catch((err) => { console.error(err); });
});
socket.on('get_config', () => {
requireRole("settings:config").then((user) => {
socket.emit('config', currentConfig);
}).catch((err) => { console.error(err); });
});
socket.on('set_config', (config: Config) => {
requireRole("settings:config").then((user) => {
validateConfig(config).then((config) => {
replaceConfig(config);
}).catch((error) => {
socket.emit('error', "Config is not valid");
});
}).catch((err) => { console.error(err); });
});
socket.on('disconnect', () => { // emitted when any socket.io client disconnects from the server
DeactivateListenerClient(socket.id);
CheckCloudClients(socket.id);
});
socket.on('remote_error_opt', (optStatus: boolean) => {
currentConfig.remoteErrorReporting = optStatus;
SaveConfig();
socket.emit('remote_error_opt', currentConfig.remoteErrorReporting);
})
});
logger('Socket.IO Setup Complete.', 'info-quiet');
logger('Starting Listener Providers.', 'info-quiet');
vMixEmulator = new VMixEmulator();
tslListenerProvider = new TSLListenerProvider();
const providers = [vMixEmulator, tslListenerProvider];
for (const provider of providers as ListenerProvider[]) {
provider.on("chatMessage", (type, socketId, message) => SendMessage(type, socketId, message));
provider.on("updateSockets", (type) => {
UpdateSockets(type);
UpdateCloud(type);
});
provider.start();
}
if (cloud_destinations.length > 0) {
logger(`Initiating ${cloud_destinations.length} Cloud Destination Connections.`, 'info');
for (let i = 0; i < cloud_destinations.length; i++) {
logger(`Cloud Destination: ${cloud_destinations[i].host}:${cloud_destinations[i].port}`, 'info-quiet');
cloud_destinations[i].connected = false;
StartCloudDestination(cloud_destinations[i].id);
}
logger(`Finished Cloud Destinations.`, 'info');
}
logger('Starting HTTP Server.', 'info-quiet');
httpServer.listen(listenPort, () => { // start up http server
logger(`Tally Arbiter running on port ${listenPort}`, 'info');
});
}
function getSources(): Source[] {
return sources.map((s) => {
s.connected = SourceClients[s.id]?.connected?.value || false;
return s;
});
}
function TSLClients_1SecUpdate(value) {
if (tsl_clients_interval !== null) {
clearInterval(tsl_clients_interval);
}
logger(`TSL Clients 1 Second Updates are turned ${(value ? 'on' : 'off')}.`, 'info');
if (value) {
logger('Starting TSL Clients 1 Second Interval.', 'info');
tsl_clients_interval = setInterval(TSLClients_UpdateAll, 1000);
}
}
function TSLClients_UpdateAll() {
//loops through all devices and sends out the state, 1 per second
for (const device of devices) {
tslListenerProvider.updateListenerClientsForDevice(currentDeviceTallyData, device);
}
}
function getDeviceStates(deviceId?: string): DeviceState[] {
return devices.filter((d) => deviceId ? d.id == deviceId : true).flatMap((d) => currentConfig.bus_options.map((b) => {
const deviceSources = device_sources.filter((s) => s.deviceId == d.id);
return {
busId: b.id,
deviceId: d.id,
sources: deviceSources.filter(
(s) => Object.entries(SourceClients[s.sourceId]?.tally?.value || [])
.filter(([address, busses]) => address == s.address)
.findIndex(([address, busses]: [string, string[]]) => busses.includes(b.type)) !== -1).map((s) => s.id),
}
}));
}
function getSourceTypeDataFields(): SourceTypeDataFields[] {
return Object.entries(TallyInputs).map(([id, data]) => ({
sourceTypeId: id,
fields: data.configFields,
} as SourceTypeDataFields));
}
function getOutputTypeDataFields(): OutputTypeDataFields[] {