This repository has been archived by the owner on Jul 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
1070 lines (935 loc) · 38.7 KB
/
index.js
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
/**
* This file is part of the WhackerLink project.
*
* (c) 2023-2024 Caleb <[email protected]>
*
* For the full copyright and license information, see the
* LICENSE file that was distributed with this source code.
*/
import * as fs from 'fs';
import * as path from 'path';
import createDebug from 'debug';
import configLoader from './src/components/ConfigLoader.js';
import DatabaseManager from './src/components/DatabaseManager.js';
import Logger from './src/components/Logger.js';
import Master from './src/Master.js';
import Peer from './src/Peer.js';
const debug = createDebug('WhackerLink:index');
const configIndex = process.argv.indexOf('-c');
debug('Starting WhackerLink');
let configPath = 'config/config.yaml';
if (configIndex > -1) {
configPath = process.argv[configIndex + 1];
}
const configFilePath = new URL(configPath, import.meta.url);
//new URL(path.join('config', 'google.json'), import.meta.url);
const config = configLoader.loadYaml(configFilePath);
const serviceAccountKeyFile = config.paths.sheetsJson;
import express from 'express';
import session from 'express-session';
import http from 'http';
import { Server as SocketIOServer } from 'socket.io';
import axios from 'axios';
import { google } from 'googleapis';
import * as https from 'https';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
const socketsStatus = {};
const grantedChannels = {};
const grantedRids = {};
const affiliations = [];
let regDenyCount = {};
let activeVoiceChannels = {};
const networkName = config.system.networkName;
const networkBindAddress = config.system.networkBindAddress;
const networkBindPort = config.system.networkBindPort;
const fullPath = config.paths.fullPath;
const logPath = config.paths.logPath;
const logLevel = config.configuration.logLevel;
const debugConfig = config.configuration.debug;
const sheetId = config.configuration.sheetId;
const grantDenyOccurrence = config.configuration.grantDenyOccurrence;
const enableDiscord = config.configuration.discordWebHookEnable;
const discordWebHookUrl = config.configuration.discordWebHookUrl;
const discordVoiceG = config.discord.voiceGrant;
const discordVoiceR = config.discord.voiceRequest;
const discordAffG = config.discord.affiliationGrant;
const discordAffR = config.discord.affiliationRequest;
const discordRegG = config.discord.regGrant;
const discordRegR = config.discord.regRequest;
const discordRegD = config.discord.regDeny;
const discordRegRfs = config.discord.regRefuse;
const discordPage = config.discord.page;
const discordInhibit = config.discord.inhibit;
const discordEmerg = config.discord.emergencyCall;
const discordVoiceD = config.discord.emergencyCall;
const useHttps = config.configuration.httpsEnable || false;
const peers = config.peers;
const controlChannels = config.system.controlChannels;
const voiceChannels = config.system.voiceChannels;
console.log('Network Name:', networkName);
console.log('HTTPS Enable:', useHttps);
console.log('Network Bind Address:', networkBindAddress);
console.log('Network Bind Port:', networkBindPort);
console.log('Full Path:', fullPath);
console.log('Sheets JSON Path:', serviceAccountKeyFile.toString());
console.log('Sheet ID:', sheetId);
console.log('grantDenyOccurrence:', grantDenyOccurrence);
if (grantDenyOccurrence < 3){
console.log("grantDenyOccurrence can not be lower than three");
throw Error;
}
const httpApp = express();
const httpServer = http.createServer(httpApp);
const httpIo = new SocketIOServer(httpServer);
const httpsOptions = {
key: fs.readFileSync(config.paths.fullPath + 'ssl/server.key'),
cert: fs.readFileSync(config.paths.fullPath + '/ssl/server.cert')
};
const httpsApp = express();
const httpsServer = https.createServer(httpsOptions, httpsApp);
const httpsIo = new SocketIOServer(httpsServer);
const app = useHttps ? httpsApp : httpApp;
const server = useHttps ? httpsServer : httpServer;
const io = useHttps ? httpsIo : httpIo;
const googleSheetClient = await getGoogleSheetClient();
app.use(session({
secret: "super_secret_password!2",
resave: false,
saveUninitialized: true,
cookie: { secure: 'auto', maxAge: 3600000 }
}));
app.use(express.urlencoded({ extended: true }));
const logger = new Logger(logLevel, logPath, debugConfig);
const dbManager = new DatabaseManager(`${config.paths.fullPath}db/whackerlink_users.db`, logger);
// Convert all sockets and database stuff to use the master.js module
const masters = null; //Placeholder
if (masters !== null) {
masters.forEach((master) => {
// TODO: Move all socket and db stuff to the module
new Master(
config,
logger
).create();
});
}
// Loop through peers list and attempt to connect
peers.forEach((peer)=>{
// Create new peer
if (peer.enable) {
new Peer(
peer.jwt,
peer.srcId,
peer.dstId,
peer.ignoreCommands,
peer.endPoint,
logger
).create();
}
});
app.set('views', path.join(config.paths.fullPath, 'views'))
app.set("view engine", "ejs");
app.use("/files", express.static(config.paths.fullPath + "public"));
// User interface routes
app.get("/" , async (req , res)=>{
if (!req.session.user) {
res.redirect('/login');
return;
}
res.redirect("/user_dashboard")
});
app.get("/user_dashboard" , async (req , res)=>{
if (!req.session.user) {
res.redirect('/login');
return;
}
try {
const sheetTabs = await getSheetTabs(googleSheetClient, sheetId);
const zoneData = [];
for (const tab of sheetTabs) {
const tabData = await readGoogleSheet(googleSheetClient, sheetId, tab, "A:B");
zoneData.push({zone: tab, content: tabData});
}
res.render("index", {zoneData, networkName, user: req.session.user, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
} catch (error) {
console.error("Error fetching sheet data:", error);
res.status(500).send("Error fetching sheet data");
}
});
app.get('/users', (req, res) => {
if (!req.session.user) {
res.redirect('/login');
return;
}
if (req.session.user.level !== 'admin') {
res.status(404).send();
return;
}
dbManager.db.all('SELECT id, username, password, mainRid FROM users', [], (err, rows) => {
if (err) {
res.status(500).send('Error retrieving users');
console.error(err.message);
} else {
res.render('users', {users: rows, networkName});
}
});
});
app.get('/edit/:id', (req, res) => {
const userId = req.params.id;
if (req.session.user && req.session.user.level === "admin") {
dbManager.db.get('SELECT * FROM users WHERE id = ?', [userId], (err, user) => {
if (err) {
res.status(500).send('Error retrieving user');
logger.error(err.message);
return;
}
res.render('edit.ejs', {user: user, loggedinuser: req.session.user, networkName});
});
} else if(req.session.user.id == userId) {
dbManager.db.get('SELECT * FROM users WHERE id = ?', [userId], (err, user) => {
if (err) {
res.status(500).send('Error retrieving user');
logger.error(err.message);
return;
}
res.render('edit.ejs', {user: user, loggedinuser: req.session.user, networkName});
});
} else {
res.send("Invalid permissions");
}
});
app.get('/delete/:id', (req, res) => {
const userId = req.params.id;
if (req.session.user && req.session.user.level === "admin") {
dbManager.db.get('SELECT * FROM users WHERE id = ?', [userId], (err, user) => {
if (err) {
res.status(500).send('Error retrieving user');
logger.error(err.message);
return;
}
res.render('delete.ejs', {user: user, networkName});
});
} else {
res.send("Invalid permissions");
}
});
app.post('/update/:id', (req, res) => {
const userId = req.params.id;
const { username, mainRid, level } = req.body;
if (req.session.user && req.session.user.level === "admin") {
dbManager.db.run('UPDATE users SET username = ?, mainRid = ?, level = ? WHERE id = ?', [username, mainRid, level, userId], function (err) {
if (err) {
res.status(500).send("Error updating user");
logger.error(err.message);
return;
}
logger.log(`User with ID: ${userId} has been updated.`);
res.redirect('/users');
});
} else if(req.session.user.id === userId) {
dbManager.db.run('UPDATE users SET username = ?, mainRid = ?, level = ? WHERE id = ?', [username, mainRid, level, userId], function (err) {
if (err) {
res.status(500).send("Error updating user");
logger.error(err.message);
return;
}
logger.info(`User with ID: ${userId} has been updated.`);
res.redirect('/user_dashboard');
});
} else {
res.send("Invalid permissions");
}
});
app.post('/delete/:id', (req, res) => {
const userId = req.params.id;
if (req.session.user && req.session.user.level === "admin") {
dbManager.db.run('DELETE FROM users WHERE id = ?', [userId], function (err) {
if (err) {
res.status(500).send("Error updating user");
logger.error(err.message);
return;
}
logger.info(`User with ID: ${userId} has been DELETED.`);
res.redirect('/users');
});
} else {
res.send("Invalid permissions");
}
});
app.get('/register', (req, res) => {
res.render('register', { networkName });
});
app.post('/register', (req, res) => {
let { username, password, mainRid } = req.body;
if (!username || !password) {
return res.status(400).send("Username and password and main rid are required");
} else if(!mainRid){
mainRid = "Not Assigned";
}
let level = "operator";
let saltRounds = 10;
bcrypt.hash(password, saltRounds, function(err, hash) {
if (err) {
logger.error(err.message);
return res.status(500).send("Error hashing password");
}
dbManager.db.get('SELECT id FROM users WHERE username = ?', [username], (err, row) => {
if (row) {
return res.status(409).send("User already exists");
}
dbManager.db.run('INSERT INTO users (username, password, mainRid, level) VALUES (?, ?, ?, ?)', [username, hash, mainRid, level], function(err) {
if (err) {
logger.error(err.message);
return res.status(500).send("Error registering user");
}
logger.debug(level)
logger.info(`A new user has been created with ID: ${this.lastID}`);
const message = 'Registered successfully!';
const redirectUrl = '/login';
res.send(`
<html>
<head>
<title>Registered</title>
Registered. Redirecting to login
<script>
setTimeout(function() {
window.location.href = '${redirectUrl}';
}, 3000);
</script>
</head>
</html>
`);
});
});
});
});
app.get('/login', (req, res) => {
res.render('login', { networkName });
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
dbManager.db.get('SELECT id, username, password, level, mainRid FROM users WHERE username = ?', [username], (err, row) => {
if (err) {
return res.status(500).send('Error on the server.');
}
if (!row) {
return res.status(404).send('User not found.');
}
bcrypt.compare(password, row.password, function(err, result) {
if (result) {
req.session.user = {
id: row.id,
username: row.username,
mainRid: row.mainRid,
level: row.level
};
res.redirect("/user_dashboard")
} else {
res.status(401).send('Password is incorrect.');
}
});
});
});
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.status(500).send('Could not log out try again.');
}
res.redirect('/login');
});
});
app.get("/radio", (req, res) => {
let radio_model = req.query.radioModel;
if (req.session.user) {
// ${req.session.user.username}
switch (radio_model) {
case "apx6000_non_xe_black":
res.render("6k_noxe_black", {networkName, selected_channel: req.query.channel, rid: req.query.rid, mode: req.query.mode, zone: req.query.zone, logged_in_user: req.session.user, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken, controlChannel: controlChannels[0]});
break;
case "apxmobile_o2_green":
res.render("o2_radio", {networkName, selected_channel: req.query.channel, rid: req.query.rid, mode: req.query.mode, zone: req.query.zone, logged_in_user: req.session.user, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken, controlChannel: controlChannels[0]});
break;
case "apx8000_xe_green":
res.render("o2_radio", {networkName, selected_channel: req.query.channel, rid: req.query.rid, mode: req.query.mode, zone: req.query.zone, logged_in_user: req.session.user, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken, controlChannel: controlChannels[0]});
break;
default:
res.send("Invalid radio model");
}
} else {
res.redirect("/login")
}
});
app.get("/unication" , (req , res)=>{
res.render("g5", {selected_channel: req.query.channel, rid: req.query.rid, mode: req.query.mode, zone: req.query.zone, networkName: networkName, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
});
app.get("/g5" , async (req , res)=>{
try {
const sheetTabs = await getSheetTabs(googleSheetClient, sheetId);
const zoneData = [];
for (const tab of sheetTabs) {
const tabData = await readGoogleSheet(googleSheetClient, sheetId, tab, "A:B");
zoneData.push({ zone: tab, content: tabData });
}
res.render("uniLanding", {zoneData, networkName, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
} catch (error) {
logger.error("Error fetching sheet data:", error);
res.status(500).send("Error fetching sheet data");
}
});
app.get("/console", async (req, res) => {
try {
let rid = "502";
const sheetTabs = await getSheetTabs(googleSheetClient, sheetId);
const zoneData = [];
for (const tab of sheetTabs) {
const tabData = await readGoogleSheet(googleSheetClient, sheetId, tab, "A:B");
zoneData.push({ zone: tab, content: tabData });
}
res.render("console", {zoneData, networkName, rid, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
} catch (error) {
logger.error("Error fetching sheet data:", error);
res.status(500).send("Error fetching sheet data");
}
});
app.get("/sys_view" , (req , res)=>{
res.render("systemView", {networkName, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
});
app.get("/sys_view/admin", (req , res)=>{
if (req.session.user && req.session.user.level === "admin") {
res.render("adminView", {networkName, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
} else {
res.send("Invalid permissions");
}
});
app.get("/affiliations" , (req , res)=>{
res.render("affiliations", {affiliations, networkName, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
});
app.get("/tones" , async (req , res)=>{
try {
const sheetTabs = await getSheetTabs(googleSheetClient, sheetId);
const zoneData = [];
for (const tab of sheetTabs) {
const tabData = await readGoogleSheet(googleSheetClient, sheetId, tab, "A:B");
zoneData.push({ zone: tab, content: tabData });
}
res.render("tones", {zoneData, networkName, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
} catch (error) {
logger.error("Error fetching sheet data:", error);
res.status(500).send("Error fetching sheet data");
}
});
app.get("/sysWatch", (req, res) => {
res.render("sysWatch", { networkName: networkName, controlChannels: controlChannels, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken });
});
app.get("/auto" , async (req , res)=>{
try {
const sheetTabs = await getSheetTabs(googleSheetClient, sheetId);
const zoneData = [];
for (const tab of sheetTabs) {
const tabData = await readGoogleSheet(googleSheetClient, sheetId, tab, "A:B");
zoneData.push({ zone: tab, content: tabData });
}
res.render("auto", {zoneData, networkName, endPointForClient: config.configuration.endPointForClient, socketAuthToken: config.configuration.socketAuthToken});
} catch (error) {
logger.error("Error fetching sheet data:", error);
res.status(500).send("Error fetching sheet data");
}
});
// API routes
if (config.configuration.apiEnable) {
app.get("/api/affs", (req, res) => {
const affiliationsJSON = affiliations.map((aff) => {
return {
srcId: aff.srcId,
dstId: aff.dstId
};
});
res.json(JSON.stringify(affiliationsJSON));
});
app.get("/api/channels/voice/list", (req, res) => {
res.json(JSON.stringify(voiceChannels));
});
app.get("/api/channels/voice/active", (req, res) => {
res.json(JSON.stringify(activeVoiceChannels));
});
app.get("/api/aff/remove/:rid", (req, res, ) =>{
let status = removeAffiliation(req.params.rid);
if (status){
res.json(JSON.stringify({"status": 200}));
} else {
res.json(JSON.stringify({"status": 500}));
}
});
app.get("/api/channel/voice/release/all", (req, res, ) =>{
Object.keys(activeVoiceChannels).forEach(channel => {
delete activeVoiceChannels[channel];
});
broadcastChannelUpdates();
res.json(JSON.stringify({"status": 200}))
});
}
async function sendDiscord(message) {
const webhookUrl = discordWebHookUrl;
const embed = {
title: 'Last Heard',
description: message,
color: 0x3498db,
timestamp: new Date().toISOString()
};
const data = {
embeds: [embed]
};
try {
const response = await axios.post(webhookUrl, data);
logger.debug('Webhook sent successfully ' + response.data);
} catch (error) {
logger.error('Error sending webhook:' + error.message);
}
}
function getDaTime(){
const currentDate = new Date();
const cdtOptions = {
timeZone: 'America/Chicago',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
};
return currentDate.toLocaleString('en-US', cdtOptions);
}
function broadcastChannelUpdates() {
const controlChannelMapping = controlChannels.reduce((acc, controlChannel) => {
acc[controlChannel] = {
controlChannel,
voiceChannels: []
};
return acc;
}, {});
for (const [channelName, voiceChannelData] of Object.entries(activeVoiceChannels)) {
const socketId = voiceChannelData.socketId;
const socketInfo = socketsStatus[socketId];
if (!socketInfo || !controlChannels.includes(socketInfo.controlChannel)) {
continue;
}
controlChannelMapping[socketInfo.controlChannel].voiceChannels.push({
voiceChannel: channelName,
dstId: voiceChannelData.dstId,
srcId: voiceChannelData.srcId
});
}
const channelData = Object.values(controlChannelMapping);
io.emit('updateChannels', channelData);
}
function removeAffiliation(rid) {
const index = affiliations.findIndex(affiliation => affiliation.srcId === rid);
if (index !== -1) {
affiliations.splice(index, 1);
}
// affiliations.forEach(affiliation => {
// console.log(affiliation);
// });
io.emit('AFFILIATION_LOOKUP_UPDATE', affiliations);
return true;
}
function addAffiliation(rid, channel){
affiliations.push({ srcId: rid, dstId: channel });
io.emit('AFFILIATION_LOOKUP_UPDATE', affiliations);
}
function getAffiliation(rid) {
const affiliation = affiliations.find(affiliation => affiliation.srcId === rid);
return affiliation ? affiliation.channel : false;
}
function isRadioAffiliated(srcId, dstId) {
return affiliations.some(affiliation => affiliation.srcId === srcId && affiliation.dstId === dstId);
}
function forceGrant(data){
/**
* WARNING: MAY NOT WORK PROPERLY AT THIS TIME
*
* TODO: Fix for new logic
*/
data.stamp = getDaTime();
io.emit("VOICE_CHANNEL_GRANT", data);
logger.info(`FORCED VOICE_CHANNEL_GRANT GIVEN TO: ${data.srcId} ON: ${data.dstId}`);
if (enableDiscord && discordVoiceG) {
sendDiscord(`Voice Transmission from ${data.srcId} on ${data.dstId}`);
}
grantedChannels[data.dstId] = true;
grantedRids[data.srcId] = true;
}
function getAvailableVoiceChannel() {
for (let channel of voiceChannels) {
if (!activeVoiceChannels[channel]) {
return channel;
}
}
return null;
}
function assignVoiceChannel(dstId, socketId, srcId) {
let availableChannel = getAvailableVoiceChannel();
if (availableChannel) {
activeVoiceChannels[availableChannel] = { dstId, socketId, srcId };
return availableChannel;
}
return null;
}
io.use((socket, next) => {
const token = socket.handshake.query.token;
logger.debug("Token Received: " + token);
if (!token) {
logger.debug('No token provided');
return next(new Error('Authentication error'));
}
jwt.verify(token, config.configuration.apiToken, function(err, decoded) {
if (err) {
logger.debug('JWT Verification Error:', err.message);
return next(new Error('Authentication error'));
}
socket.decoded = decoded;
logger.debug('JWT Verified Successfully');
next();
});
})
.on("connection", function (socket) {
const socketId = socket.id;
socketsStatus[socket.id] = {};
broadcastChannelUpdates();
socket.on("REQUEST_CHANNEL_UPDATES", function (data){
broadcastChannelUpdates();
});
socket.on("VOICE_CHANNEL_CONFIRMED", function (data) {
if (data.srcId && grantedChannels[data.dstId]) {
socketsStatus[socketId].voiceChannelActive = true;
logger.debug(`Voice channel confirmed ${data.srcId} on ${data.dstId}`);
}
});
socket.on("JOIN_CONTROL_CHANNEL", (data) => {
if (controlChannels.includes(data.channel)) {
socket.join(data.channel);
socket.emit("CONTROL_CHANNEL_ACK", {
message: "Connected to Control Channel: " + data.channel
});
} else {
socket.emit("CONTROL_CHANNEL_ERROR", {
message: "Invalid Control Channel: " + data.channel
});
}
});
socket.on("voice", function (data) {
var newData = data.split(";");
newData[0] = "data:audio/wav;";
newData = newData.join(";");
const senderDstId = socketsStatus[socketId].dstId;
const activeVoiceChannel = socketsStatus[socketId].voiceChannel;
for (const id in socketsStatus) {
const recipientDstId = socketsStatus[id].dstId;
if (senderDstId === recipientDstId)
if (socketsStatus[socketId].voiceChannelActive) {
socket.to(activeVoiceChannel).emit("send", {
newData: newData,
srcId: socketsStatus[id].srcId,
dstId: socketsStatus[id].dstId,
voiceChannel: socketsStatus[id].voiceChannel,
controlChannel: socketsStatus[id].controlChannel
});
} else {
logger.warn(`srcID: ${socketsStatus[socketId].srcId} not on voice channel; stand by`);
}
}
});
socket.on("userInformation", function (data) {
socketsStatus[socketId] = data;
io.sockets.emit("usersUpdate", socketsStatus);
});
socket.on("AFFILIATION_LIST_REQUEST", function(){
io.emit('AFFILIATION_LOOKUP_UPDATE', affiliations);
});
socket.on("VOICE_CHANNEL_REQUEST", function (data) {
logger.info(`VOICE_CHANNEL_REQUEST FROM: ${data.srcId} TO: ${data.dstId}`);
const cdtDateTime = getDaTime();
data.stamp = cdtDateTime;
if (enableDiscord && discordVoiceR) {
sendDiscord(`Voice Request from ${data.srcId} on ${data.dstId} at ${data.stamp}`);
}
io.emit("VOICE_CHANNEL_REQUEST", data);
setTimeout(function () {
let integerNumber = parseInt(data.srcId);
if (!Number.isInteger(integerNumber)) {
data.stamp = cdtDateTime;
io.emit("VOICE_CHANNEL_DENY", data);
logger.warn("Invalid RID");
return;
}
if (isRadioAffiliated(data.srcId, data.dstId)) {
let assignedChannel = assignVoiceChannel(data.dstId, socket.id, data.srcId);
if (assignedChannel) {
data.newChannel = assignedChannel;
for (const id in socketsStatus) {
if (socketsStatus[id].dstId === data.dstId) {
io.to(socketsStatus[id].controlChannel).emit("VOICE_CHANNEL_GRANT", data);
socket.join(assignedChannel);
}
}
broadcastChannelUpdates();
logger.info(`VOICE_CHANNEL_GRANT GIVEN TO: ${data.srcId} ON: ${data.dstId} AT: ${assignedChannel}`);
if (enableDiscord && discordVoiceG) {
sendDiscord(`Voice Transmission from ${data.srcId} on ${data.dstId} at ${data.stamp}`);
}
grantedChannels[data.dstId] = true;
grantedRids[data.srcId] = true;
} else {
data.stamp = cdtDateTime;
io.emit("VOICE_CHANNEL_DENY", data);
logger.info(`VOICE_CHANNEL_DENY GIVEN TO: ${data.srcId} ON: ${data.dstId}`);
if (enableDiscord && discordVoiceD) {
sendDiscord(`Voice Deny from ${data.srcId} on ${data.dstId} at ${data.stamp}`);
}
}
} else {
io.emit("VOICE_CHANNEL_DENY", data);
logger.info(`VOICE_CHANNEL_DENY GIVEN TO: ${data.srcId} ON: ${data.dstId}`);
logger.warn(data.srcId + " Non affiliated voice request not permitted for " + data.dstId);
}
}, 750);
});
socket.on("RELEASE_VOICE_CHANNEL", function (data){
data.stamp = getDaTime();
logger.info(`RELEASE_VOICE_CHANNEL FROM: ${data.srcId} TO: ${data.dstId}`);
io.emit("VOICE_CHANNEL_RELEASE", data);
grantedRids[data.srcId] = false;
grantedChannels[data.dstId] = false;
let channel = data.newChannel;
Object.keys(activeVoiceChannels).forEach(channel => {
if (activeVoiceChannels[channel].dstId === data.dstId && activeVoiceChannels[channel].socketId === socket.id) {
delete activeVoiceChannels[channel];
}
});
broadcastChannelUpdates();
});
socket.on("disconnect", function (data) {
if (socketsStatus[socketId].srcId) {
removeAffiliation(socketsStatus[socketId].srcId);
}
Object.keys(activeVoiceChannels).forEach(channel => {
if (activeVoiceChannels[channel].socketId === socket.id) {
delete activeVoiceChannels[channel];
}
});
delete socketsStatus[socketId];
});
socket.on("CHANNEL_AFFILIATION_REQUEST", function (data){
data.stamp = getDaTime();
io.emit("CHANNEL_AFFILIATION_REQUEST", data);
if (enableDiscord && discordAffR) {
sendDiscord(`Affiliation Grant to ${data.srcId} on ${data.dstId} at ${data.stamp}`);
}
setTimeout(function (){
io.emit("CHANNEL_AFFILIATION_GRANTED", data);
if (enableDiscord && discordAffG) {
sendDiscord(`Affiliation Grant to ${data.srcId} on ${data.dstId} at ${data.stamp}`);
}
if (!getAffiliation(data.srcId)){
logger.info("AFFILIATION GRANTED TO: " + data.srcId + " ON: " + data.dstId);
addAffiliation(data.srcId, data.dstId, data.stamp = getDaTime());
} else {
logger.info("AFFILIATION GRANTED TO: " + data.srcId + " ON: " + data.dstId + " AND REMOVED OLD AFF");
removeAffiliation(data.srcId);
addAffiliation(data.srcId, data.dstId);
}
},1500);
});
socket.on("REMOVE_AFFILIATION", function (data){
data.stamp = getDaTime();
removeAffiliation(data.srcId);
logger.info("AFFILIATION REMOVED: " + data.srcId + " ON: " + data.dstId);
io.emit("REMOVE_AFFILIATION_GRANTED", data);
});
socket.on("EMERGENCY_CALL", function (data){
if (enableDiscord && discordEmerg) {
sendDiscord(`Affiliation Grant to ${data.srcId} on ${data.dstId} at ${data.stamp}`);
}
data.stamp = getDaTime();
logger.info("EMERGENCY_CALL FROM: " + data.srcId + " ON: " + data.dstId)
io.emit("EMERGENCY_CALL", data);
});
socket.on("RID_INHIBIT", async function(data) {
if (enableDiscord && discordInhibit) {
sendDiscord(`Inhibit sent to ${data.srcId} on ${data.dstId} at ${data.stamp}`);
}
data.stamp = getDaTime();
const ridToInhibit = data.dstId;
const ridAcl = await readGoogleSheet(googleSheetClient, sheetId, "rid_acl", "A:B");
io.emit("RID_INHIBIT", data);
const matchingIndex = ridAcl.findIndex(entry => entry[0] === ridToInhibit);
if (matchingIndex !== -1) {
ridAcl[matchingIndex][1] = '0';
await updateGoogleSheet(googleSheetClient, sheetId, "rid_acl", "A:B", ridAcl);
logger.info(`RID_INHIBIT: ${ridToInhibit}`);
}
});
socket.on("RID_INHIBIT_ACK", function (data){
io.emit("RID_INHIBIT_ACK", data);
});
socket.on("RID_UNINHIBIT_ACK", function (data){
io.emit("RID_UNINHIBIT_ACK", data);
});
socket.on("RID_UNINHIBIT", async function (data){
data.stamp = getDaTime();
const ridToUnInhibit = data.dstId;
const ridAcl = await readGoogleSheet(googleSheetClient, sheetId, "rid_acl", "A:B");
io.emit("RID_UNINHIBIT", data);
const matchingIndex = ridAcl.findIndex(entry => entry[0] === ridToUnInhibit);
if (matchingIndex !== -1) {
ridAcl[matchingIndex][1] = '1';
await updateGoogleSheet(googleSheetClient, sheetId, "rid_acl", "A:B", ridAcl);
logger.info(`RID_UNINHIBIT: ${ridToUnInhibit}`);
}
});
socket.on("INFORMATION_ALERT", function(data){
io.emit("INFORMATION_ALERT", data);
forceGrant(data);
setTimeout(function (){
io.emit("VOICE_CHANNEL_RELEASE", data);
}, 1500);
});
socket.on("AUTO_DISPATCH_CHANNEL_BROADCAST", function(data){
io.emit("AUTO_DISPATCH_CHANNEL_BROADCAST", data);
forceGrant(data);
setTimeout(function (){
io.emit("VOICE_CHANNEL_RELEASE", data);
}, 8000);
});
socket.on("CANCELLATION_ALERT", function(data){
io.emit("CANCELLATION_ALERT", data);
forceGrant(data);
setTimeout(function (){
io.emit("VOICE_CHANNEL_RELEASE", data);
}, 1500);
});
socket.on("REG_REQUEST", async function (rid){
io.emit("REG_REQUEST", rid);
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
let ridAcl = await readGoogleSheet(googleSheetClient, sheetId, "rid_acl", "A:B");
const matchingEntry = ridAcl.find(entry => entry[0] === rid);
const denyCount = regDenyCount[rid] || 0;
if (enableDiscord && discordRegR){
sendDiscord(`Reg Request: ${rid}`);
}
setTimeout(function (){
if (rid.isNumber()) {
if (matchingEntry) {
const inhibit = matchingEntry[1];
if (inhibit === '1') {
if (enableDiscord && discordRegG){
sendDiscord(`Reg grant: ${rid}`);
}
io.emit("REG_GRANTED", rid);
logger.info("REG_GRANTED: " + rid);
} else {
io.emit("RID_INHIBIT", {srcId: rid, dstId: "999999999"});
}
} else {
if (denyCount >= 3){
if (enableDiscord && discordRegRfs){
sendDiscord(`Reg refuse: ${rid}`);
}
io.emit("REG_REFUSE", rid);
} else {
if (enableDiscord && discordRegD){
sendDiscord(`REG_REFUSE: ${rid}`);
}
io.emit("REG_REFUSE", rid);
regDenyCount[rid] = denyCount + 1;
}
}
} else {
if (denyCount >= 3){
if (enableDiscord && discordRegRfs){
sendDiscord(`Reg refuse: ${rid}`);
}
io.emit("REG_REFUSE", rid);
} else {
if (enableDiscord && discordRegD){
sendDiscord(`Reg deny: ${rid}`);
}
io.emit("REG_DENIED", rid);
regDenyCount[rid] = denyCount + 1;
}
}
}, 1500);
});
socket.on("RID_PAGE", function(data){
data.stamp = getDaTime();
logger.info("RID PAGE srcId: ", data.srcId, " dstId: ", data.dstId)
setTimeout(()=>{
io.emit("PAGE_RID", data);
}, 1000);
});
socket.on("RID_PAGE_ACK", function(data){
data.stamp = getDaTime();
setTimeout(()=>{
io.emit("PAGE_RID_ACK", data);
}, 1500);