forked from LandonPowell/SeaFour
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1027 lines (854 loc) · 34.3 KB
/
server.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
// Initializer.
var express = require('express');
var app = express();
var http = require('http');
var https = require('https');
var webServer = http.Server(app);
var imageMagick = require('imagemagick');
var serverData = {};
process.on('uncaughtException', function(err) { // I don't like killing the process when one of my libraries fucks up.
console.log("UNCAUGHT EXCEPTION\n" + err);
});
// Cryptography intializers.
var crypto = require('crypto');
var sjcl = require('sjcl');
var ECDH = require('elliptic').ec;
var ec = new ECDH('curve25519');
serverData.keyPair = ec.genKeyPair();
serverData.tokens = {};
// User database initializers.
var mongodb = require('mongodb').MongoClient;
var collection; // Make 'collection' a global variable.
mongodb.connect("mongodb://localhost:27017/c4", function(err, db) {
// If mongo is acting up, this might not connect, meaning 'collection' is left undefined.
if (err) throw "I wasn't able to connect to Mongo.";
collection = db.collection('users');
console.log("I've connected to Mongo.");
});
// WebSockets Settings
var webSocketServer = require('ws').Server;
var socketServer = new webSocketServer({ server: webServer });
function delimit() {
return Array.from(arguments).join("\u0004");
}
socketServer.broadcast = function() {
var args = Array.from(arguments);
socketServer.clients.forEach(function(client) {
client.send(args.join("\u0004"));
});
};
serverData.rooms = {
'main' : { // By default, we have a 'main' room.
clients : [], // Connected sockets.
posts : 0, // Posts made so far.
topic : "Highly Explosive", // The current topic.
messages : [], // Last few messages posted.
logLimit : 10 // How many messages should the log store. Lower if you're 'noided.
},
};
serverData.roomUsers = function(room) {
var nameList = [];
if (serverData.rooms[room] == undefined) return nameList;
var clients = serverData.rooms[room].clients;
for (var client in clients) {
nameList.push( clients[client].nick );
}
return nameList;
};
socketServer.roomBroadcast = function(room) {
var args = Array.from(arguments).slice(1);
var clients = serverData.rooms[room].clients;
clients.forEach(function(client) {
if (client.readyState == 1) client.send(args.join("\u0004"));
});
};
// Functions used to wrap long statements in a more readable form.
function usableVar(variable) { // Checks if a variable won't fuck something up.
return typeof( variable ) === "string" && variable;
}
function nameSanitize(nick) { // Changes unimportant chars to dashes.
return nick.toLowerCase()
.replace(/[^a-z\d]+/gi, "-")
.replace(/-?([\w]+(?:-[\w]+)*)-?/g, "$1");
}
function checkValidName(nick) { // Checks if a name contains no strange chars or is taken.
if (
['www', 'main', 'server', 'http'] // Reserved and possibly malicious names.
.indexOf(nameSanitize(nick)) + 1
) return false; // It's an array so I can put more in it later without doing much. 'Maintainability.'
return nick.replace(/[^\u0020-\u007e]/gi, "") == nick &&
nick.indexOf("\n") < 0 &&
nick.length < 30 && nick.length > 2;
}
// Functions dedicated to achievements and points.
function onlineIPs(clients) {
// To-do
var ipList = [];
for ( var user in clients ) {
var ip = moderatorSettings.ipLog[nameSanitize(clients[user])];
if (ipList.indexOf(ip) < 0) ipList.push(ip);
}
return ipList.length;
}
var achievable = {
drumpf : {
keywords: ['trump', 'drumpf', 'make america great again'],
limit: 3, // The 'limit' is the amount of messsages needed to make it go off.
value: 300, // The 'value' is the amount of XP given upon completion.
},
pol : {
keywords: ['9/11', 'jews', 'adolf', 'hitler'],
limit: 6,
value: 911,
},
autism : {
keywords: ['fursona', 'call of duty', 'vidya', 'weed', 'xdd', '420'],
limit: 3,
value: 420,
}
};
function achievementHandler(message, username, result) { // Distributes achievements based on messages.
// To-do
// The following code should calculate points gained and achievements earned,
// then update the database accordingly.
username = nameSanitize(username);
var news = [];
collection.updateOne({
'name' : username,
},
{ $set : { 'points' :
result.points +
message.substr(0,150).length
},});
return news;
}
// Moderation and antispam related variables, functions, and calls.
var moderatorSettings = {
quiet : false, // Disallows unregistered from posting; they can watch.
ipLog : [],
banList : [], // List of banned IPs.
superBanList : [] // List of IPs that aren't even allowed to see the chat. NSA goes here. :^)
};
/*\
* Humans have been shit at timekeeping since we first looked at the sky and
* used our sun's position to find out how long we had until nightfall. Now,
* I shall carry on that tradition by assuming 24 * 60 * 60 * 1000 is the length
* of a day in milliseconds, and I'll completely ignore that leap seconds and
* DST are real things.
\*/
setTimeout(function() {
setInterval(function() {
moderatorSettings.banList = [];
serverData.keyPair = ec.genKeyPair(); // Reset keypair every night.
}, 86400000);
}, ( 24 - new Date().getHours() ));
var ipEmits = {}; // Stores the number of emits made by any IP.
setInterval(function() { ipEmits = {}; }, 3000); // Every 3 seconds, clear.
function addEmit(ipAddress, socket) {
if (ipEmits[ipAddress]) ipEmits[ipAddress] += 1;
else ipEmits[ipAddress] = 1;
if (ipEmits[ipAddress] > 6) { // Limits normal emits.
moderatorSettings.banList.push(ipAddress);
console.log(ipAddress + " has been banned.");
socket.close();
}
if (ipEmits[ipAddress] > 10) { // Limits spam emits.
moderatorSettings.superBanList.push(ipAddress);
console.log(ipAddress + " has been super banned.");
if ( socket.readyState == 1 ) {
socket.close();
}
}
}
var commands = {
// Simple messages.
'roomMessage' : {
function(socket, message) {
serverData.rooms[socket.room].posts++;
var username = nameSanitize(socket.nick);
var flair;
collection.findOne({'name' : username},
function(err, result) {
if ( !err && result ) {
flair = result.flair;
if (! usableVar(flair) ) flair = false; // If the flair isn't usable, set it to a boolean false;
var achievementNews = achievementHandler(
message, username, result
);
for (var i = 0; i < achievementNews.length; i++) {
socket.send(delimit( 'systemMessage', achievementNews[i] ));
}
socket.send(delimit( 'pointsUpdate', result.points ));
}
var room = serverData.rooms[socket.room];
if (room.logLimit != 0) {
room.messages.push({
nick: socket.nick,
message: message.substr(0,3000), // Lower because muh data usage.
number: serverData.rooms[socket.room].posts.toString(36),
flair: flair,
});
}
if (room.messages.length > room.logLimit) {
room.messages = room.messages.slice(room.messages.length - room.logLimit);
}
socketServer.roomBroadcast(socket.room,
'roomMessage',
socket.nick,
message.substr(0,6000),
serverData.rooms[socket.room].posts.toString(36),
flair
);
});
},
},
'giveRecent' : {
function(socket, message) {
var recentMessages = serverData.rooms[socket.room].messages;
for (var x = 0; x < recentMessages.length; x++) {
var currentMessage = recentMessages[x];
socket.send(delimit(
'roomMessage',
currentMessage.nick,
currentMessage.message,
currentMessage.number,
currentMessage.flair
));
}
}
},
'me' : {
function(socket, message) {
socketServer.roomBroadcast(socket.room,
'me', socket.nick+" "+message.substr(0,2048));
}
},
'specialMessage' : {
function(socket, type, message) {
var approvedTypes = ["term", "carbonite", "badOS"]; // Default approved types.
collection.findOne({'name' : socket.nick},
function(err, result) {
if ( !err && result ) {
var achievements = result.achievements;
for (var achievement in achievements) {
if (achievements[achievement] == "done") {
approvedTypes.push(result.achievements);
}
}
}
if ( approvedTypes.indexOf(type) + 1 ) {
socketServer.roomBroadcast(socket.room,
'specialMessage', type, socket.nick, message.substr(0,2048) );
}
else {
socket.send(delimit( 'systemMessage', "I can't let you do that, Dave." ));
}
});
},
},
// Get an encrypted private key.
'getEncryptedPrivateKey' : {
function(socket, nick) {
collection.findOne({'name' : nameSanitize(nick)},
function(err, result) {
if (err || !result) {
socket.send(delimit( 'systemMessage', "That user doesn't exist." ));
socket.send(delimit( 'encryptedPrivateKey', nameSanitize(nick), "" ));
return false;
}
socket.send(delimit( 'encryptedPrivateKey',
nameSanitize(nick),
result.encryptedPrivateKey
));
});
},
},
// Registering, logging in, and changing names.
'register' : {
function(socket, nick, publicKey, encryptedPrivateKey) {
if ( !checkValidName(nick) ) {
socket.send(delimit( 'systemMessage', "You're not able to use " + nick + "."));
socket.send('badLogin');
return false;
}
collection.findOne({'name' : nameSanitize(nick)},
function(err, result) {
if (err || result) { // If this is true, someone else already registered.
socket.send(delimit( 'systemMessage', "That's someone else."));
socket.send('badLogin');
return false;
}
collection.insert({
'name' : nameSanitize(nick),
'role' : 0,
'publicKey' : publicKey,
'encryptedPrivateKey' : encryptedPrivateKey,
'points' : 0,
'renown' : 0,
'achievements' : {},
},
function(err, result) {
if (err) { console.log(err); return false; }
socket.send(delimit( 'systemMessage', "You are now registered, " + nick + "."));
socket.send(delimit( 'nickRefresh', nick ));
socket.nick = nick;
socket.role = 0;
socketServer.roomBroadcast(socket.room,
'listRefresh', serverData.roomUsers(socket.room).join("\u0004"));
moderatorSettings.ipLog[nameSanitize( socket.nick )] = socket._socket.remoteAddress;
});
});
},
},
'createToken' : { // Token is created for later authentication.
// In order to create a token
function(socket, nick) {
collection.findOne({'name' : nameSanitize(nick)},
function(err, result) {
if (err || !result) return false;
var plainToken = crypto.randomBytes(666).toString('hex'); // Firstly, create a random string. The end user will need to determine this.
var sharedKey = serverData.keyPair.derive( // Nextly, we find the sharedKey between the server and our user.
ec.keyFromPublic(result.publicKey, 'hex').pub
).toString(36);
var cryptoToken = sjcl.encrypt(sharedKey, plainToken); // Cryptographically secured token. We give this to the end user, who then decrypts it.
serverData.tokens[plainToken] = { // We use the plainToken as a key, so we'll be able to easily access it.
userName : nameSanitize(nick), // Username is stored for later confirmation.
role : result.role,
};
setTimeout(function() { // Delete the token after 2 seconds for obvious reasons.
delete serverData.tokens[plainToken];
}, 2000);
socket.send(delimit('cryptoToken', cryptoToken)); // Send the user the encryptedToken so he can decrypt it and send it back.
});
},
},
'authenticate' : { // Authenticate based upon a token.
function(socket, nick, token) {
if ( !serverData.tokens[token] ) {
socket.send(delimit('systemMessage',
"You weren't able to authenticate as " + nameSanitize(nick) + "."
));
return false;
}
var tokenObject = serverData.tokens[token];
if ( tokenObject.userName == nameSanitize(nick) ) {
socket.send(delimit( 'systemMessage', "You are now authenticated, " + nick + "."));
socket.send(delimit( 'nickRefresh', nick ));
socket.nick = nick;
socket.role = tokenObject.role;
socketServer.roomBroadcast(socket.room,
'listRefresh', serverData.roomUsers(socket.room).join("\u0004"));
moderatorSettings.ipLog[nameSanitize( socket.nick )] = socket._socket.remoteAddress;
}
else {
socket.send(delimit('systemMessage',
"You weren't able to authenticate as " + nameSanitize(nick) + "."
));
socket.send('badLogin');
}
},
},
'changeNick' : {
function(socket, nick) {
if ( !checkValidName(nick) ) {
socket.send(delimit( 'systemMessage', "That user is already registered." ));
return false;
}
socketServer.roomBroadcast(socket.room,
'systemMessage', socket.nick + " is now known as " + nick);
socket.send(delimit( 'nickRefresh', nick ));
socket.nick = nick;
moderatorSettings.ipLog[nameSanitize(nick)] = socket._socket.remoteAddress;
socketServer.roomBroadcast(socket.room,
'listRefresh', serverData.roomUsers(socket.room).join("\u0004"));
}
},
// Room management.
'join' : {
function(socket, room) {
// To-do. Maybe clean this up?
socket.room = room;
var index = serverData.rooms[socket.room].clients.indexOf(socket);
if (index + 1) serverData.rooms[socket.room].clients.splice(index, 1);
socketServer.roomBroadcast(socket.room,
'listRefresh', serverData.roomUsers(socket.room).join("\u0004"));
function joinBroadcast(room) {
serverData.rooms[room].clients.push(socket);
socket.send(delimit( 'topic', serverData.rooms[room].topic ));
socketServer.roomBroadcast(room,
'systemMessage', socket.nick + ' has joined.');
socketServer.roomBroadcast(room,
'listRefresh', serverData.roomUsers(room).join("\u0004"));
}
if (serverData.rooms[room]) {
socket.room = room;
joinBroadcast(socket.room);
return true;
}
collection.findOne({'name' : nameSanitize(room) },
function(err, result) {
if (err || !result) {
socket.send('badRoom');
socket.room = "main";
return false;
}
socket.room = room;
joinBroadcast(socket.room);
});
}
},
// Whispering.
'directMessage' : {
function(socket, userTo, message) {
var wasSent = false;
socketServer.clients.forEach(function(client) {
if ( client.nick == userTo ) {
client.send(delimit('directMessage', "from",
nameSanitize(socket.nick),
message.substr(0,1000)));
wasSent = true;
}
});
if ( !wasSent ) {
socket.send(delimit( 'systemMessage', "That user isn't online right now." ));
return false;
}
socket.send(delimit( 'directMessage', "to",
nameSanitize(userTo),
message.substr(0,1000)) );
}
},
// Check user details.
'who' : {
function(socket, userName) {
userName = nameSanitize(userName);
collection.findOne({'name' : nameSanitize(userName)},
function(err, result) {
if (err || !result) {
socket.send(delimit('systemMessage',
userName + " isn't registered."
));
return false;
}
socket.send(delimit('systemMessage',
userName + " is role " + result.role + "."
));
});
}
},
'getPublicKey' : {
function(socket, nick) {
if (nick == "server") {
socket.send(delimit( 'publicKey',
'server',
serverData.keyPair.getPublic('hex')
));
return true;
}
collection.findOne({'name' : nameSanitize(nick)},
function(err, result) {
if (err || !result) {
socket.send(delimit( 'systemMessage', "That user doesn't exist." ));
socket.send(delimit( 'publicKey', nameSanitize(nick), "" ));
return false;
}
socket.send(delimit( 'publicKey',
nameSanitize(nick),
result.publicKey
));
});
},
},
// Registered exclusive commands.
'flair' : {
role : 0,
function(socket, flair) {
collection.updateOne({'name' : nameSanitize(socket.nick)},
{ $set : { 'flair' : flair } }
);
socket.send(delimit('systemMessage', "Your flair has been updated."));
},
},
'bio' : {
role : 0,
function(socket, bio) {
collection.updateOne({'name' : nameSanitize(socket.nick)},
{ $set : { 'bio' : bio } }
);
socket.send(delimit('systemMessage', "Your bio has been updated."));
},
},
'website' : {
role : 0,
function(socket, link) {
collection.updateOne({'name' : nameSanitize(socket.nick)},
{ $set : { 'website' : link } }
);
socket.send(delimit('systemMessage', "Your website has been updated."));
},
},
// Room settings.
'topic' : {
role: 0,
function(socket, newTopic) {
var room = socket.room;
var mods = serverData.rooms[room].mods;
if (mods && mods.indexOf(nameSanitize(socket.nick)) < 0 ) {
socket.send(delimit('systemMessage', "You aren't an approved moderator here."));
return false;
}
serverData.rooms[room].topic = newTopic.substr(0, 27);
socketServer.roomBroadcast(room,
'topic', newTopic.substr(0, 27));
}
},
// Global moderator exclusive commands.
'fistOfRemoval' : {
role: 1,
function(socket, removedUser) {
removedUser = nameSanitize(removedUser);
collection.findOne({'name' : removedUser},
function(err, result) {
if (err || !result || socket.role > result.role) {
var clients = serverData.rooms[socket.room].clients;
for (var client in clients) {
if (nameSanitize(clients[client].nick) == removedUser) {
clients[client].close();
return true;
}
}
socket.send(delimit('systemMessage', "That user isn't in this room."));
return false;
}
socket.send(delimit('systemMessage', "That user seems to have a level too high for you to kick."));
});
},
},
'getIP' : {
role: 2,
function(socket, searchedUser) {
socket.send(delimit('systemMessage',
moderatorSettings.ipLog[ nameSanitize(searchedUser) ] || "no-ip-available"
));
},
},
'roleChange' : {
role: 2,
function(socket, changedUser, role) {
changedUser = nameSanitize(changedUser);
role = parseInt(role, 10);
if (socket.role < role && false) {
socket.send(delimit('systemMessage', "Your role is too low."));
return false;
}
collection.findOne({
'name' : changedUser,
'role' : { $lt : socket.role },
},
function(err, result) {
if (err || !result) {
socket.send(delimit('systemMessage', changedUser + " does not exist or is too highly ranked."));
}
else {
socket.send(delimit('systemMessage', changedUser + "'s role is now " + role + "."));
}
});
collection.updateOne({
'name' : changedUser,
'role' : { $lt : socket.role },
},
{
$set : { 'role' : role },
});
},
},
'ban' : {
role: 2,
function(socket, maliciousUser) {
var userIP = moderatorSettings.ipLog[ nameSanitize(maliciousUser) ] || maliciousUser;
moderatorSettings.banList.push( userIP );
socket.send(delimit('systemMessage', userIP + " has been banned."));
},
},
'superBan' : {
role: 3,
function(socket, maliciousUser) {
var userIP = moderatorSettings.ipLog[ nameSanitize(maliciousUser) ] || maliciousUser;
moderatorSettings.superBanList.push( userIP );
socket.send(delimit( 'systemMessage', userIP + " has been super banned." ));
},
},
'clearBans' : {
role: 2,
function(socket) {
moderatorSettings.banList = [];
socketServer.broadcast('systemMessage', "The ban list has been cleared.");
},
},
'clearSuperBans' : {
role: 2,
function(socket) {
moderatorSettings.superBanList = [];
socketServer.broadcast('systemMessage', "The super ban list has been cleared.");
},
},
'quiet' : {
role: 2,
function(socket) {
moderatorSettings.quiet = !moderatorSettings.quiet;
socketServer.broadcast('systemMessage', "Quiet mode set to " + moderatorSettings.quiet);
},
},
'genocide' : {
role: 3,
function(socket) {
socketServer.broadcast('systemMessage', "There is much talk, and I have " +
"listened, through rock and metal " +
"and time. Now I shall talk, and you " +
"shall listen.");
socketServer.clients.forEach(function(client) {
client.close();
});
},
},
// WIP COMMANDS BELOW THIS LINE.
'banRange' : {
role: 3,
function(socket, maliciousUser) {
var userIP = moderatorSettings.ipLog[ nameSanitize(maliciousUser) ] || maliciousUser;
moderatorSettings.banList.push( userIP.substr(0, 14) );
socket.send(delimit( 'systemMessage', userIP + " has been banned." ));
},
},
// Low-level only commands. Not to be sent upon user request.
'ping' : { // This is basically the 'keepAlive' of SeaFour.
function(socket) {
socket.send('pong');
}
}
};
// RTC server using Web Sockets. Wew lad, we're in the future now.
socketServer.on('connection', function(socket) {
addEmit( socket._socket.remoteAddress, socket );
// Handles banned users. Basically the asshole bouncer of SeaFour.
if ( ipEmits[socket._socket.remoteAddress] > 6 ||
moderatorSettings.superBanList.indexOf(socket._socket.remoteAddress) + 1 ||
collection === undefined ) { // If the collection is undefined, they've joined so quickly the server couldn't even startup.
console.log("Spammer detected at " + socket._socket.remoteAddress);
socket.close();
return false;
}
// Handlng the more 'front end' aspect of joining.
socket.nick = Math.random().toString(16).substr(2,6);
socket.send(delimit( 'nickRefresh', socket.nick ));
moderatorSettings.ipLog[nameSanitize( socket.nick )] = socket._socket.remoteAddress;
socket.on('message', function(data) {
addEmit( socket._socket.remoteAddress, socket );
var parameters = data.split("\u0004");
var command = commands[ parameters[0] ];
if ( command == undefined ) { // If a dumbass sends a command that isn't real.
socket.send(delimit( 'systemMessage', parameters[0] + ' is not a command.' ));
return false;
}
if ( (moderatorSettings.quiet && !users[ nameSanitize(socket.nick) ]) || // If the mute applies.
moderatorSettings.banList.indexOf( socket._socket.remoteAddress ) + 1 ) { // If the user is banned.
return false;
}
for (var x = 1; x <= 2; x++) {
if ( !usableVar(parameters[x]) ) {
parameters[x] = "I'm a stupid idiot."; // Funniest solution of the century.
}
}
if ( command.role != undefined &&
( socket.role == undefined || socket.role < command.role ) ) {
if (command.role == 0) {
socket.send(delimit( 'systemMessage', parameters[0] + ' requires you to be registered.' ));
}
else {
socket.send(delimit( 'systemMessage', parameters[0] + ' requires at least role ' + command.role + '.' ));
}
return false;
}
parameters[0] = socket;
command.function.apply(this, parameters);
});
//Listener for Disconnects.
socket.on('close', function() {
// To-do : Fix double-call
console.log (socket.room);
socketServer.roomBroadcast(socket.room,
'systemMessage', socket.nick + ' has left.');
var index = serverData.rooms[socket.room].clients.indexOf(socket);
if (index + 1) serverData.rooms[socket.room].clients.splice(index, 1);
socketServer.roomBroadcast(socket.room,
'listRefresh', serverData.roomUsers(socket.room).join("\u0004"));
});
});
// Webapp Settings
app.set('view engine', 'pug');
app.use("/=:room/", function(request, response, giveClient) {
if (request.url != '/' && request.url != '/index.html') {
giveClient(); // Gives client assets.
return true;
}
var room = nameSanitize(request.params.room);
if (serverData.rooms[room]) {
giveClient();
return true;
}
collection.findOne({ 'name' : room },
function(err, result) {
if (err || !result) {
response.render('errorPage', {
error: "That room doesn't seem to be available."
});
return false;
}
if (!result.room) {
result.room = {
topic : "Highly Explosive", // The current topic.
posts : 0, // Posts that have been made so far.
mods : [room], // List of people with moderator permissions.
messages : [],
logLimit : 10
};
}
serverData.rooms[room] = result.room;
serverData.rooms[room].clients = [];
giveClient(); // Gives client assets.
});
}, express.static(__dirname + '/client/') );
// User account pages.
app.get('/[\\w-]+', function(request, response) {
var userName = nameSanitize( request.url.substr(1) );
collection.findOne({ 'name' : nameSanitize(userName) },
function(err, result) {
if (err || !result) {
response.render('errorPage', {
error: "That user doesn't seem to exist."
});
return false;
}
// Heads up: Pug auto-sanitizes HTML for you, so you
// don't have to worry too hard about it; however, stay frosty.
response.render('userPage', {
user: userName,
flair: result.flair || "This user has not set a flair yet.",
role: result.role || "This user has not been given a role yet.",
website: result.website || "This user has not set a website yet.",
bio: result.bio || "This user has not set a bio yet.",
renown: result.renown,
});
});
});
app.get('/api/[\\w]+', function(request, response) {
var userName = request.url.substr(5);
if (userName == "server") {
return response.send(JSON.stringify({
publicKey : serverData.keyPair.getPublic('hex')
}, null, 4 ));
}
collection.findOne({'name' : nameSanitize(userName) },
function(err, result) {
if (err || !result) {
response.send("{}");
return false;
}
response.send(JSON.stringify(
result, ["name", "publicKey", "encryptedPrivateKey", "_id"], 4
));
});
});
var lastImage = { // Defined globally so multiple uses of the function below can modify it.
url: "",
data: "",
};
// Image link to 100x100 thumbnail.
app.get('/img/[^\\s#]+', function(request, response) {
var imageSource = request.url.substr(5).replace(/^[^:]*/, "https"); // This cures autism. Some idiots ACTUALLY use http.
if ( imageSource == lastImage.url ) { // Checks for consecutive requests to the same image.
response.writeHead(200, {'Content-Type' : 'image/jpeg'});
response.end(lastImage.data, 'binary');
return true;
}
https.get(imageSource, function(imageResponse) {
var body = '';
imageResponse.setEncoding('binary');
imageResponse.on('data', function(data) {
body += data;
});
imageResponse.on('end', function() {
imageMagick.crop({
srcData : body,
format : 'jpg',
width : 100,
height : 100,
progressive : true,
}, function(err, imageData){
if (err) {
console.log(err);
return false;
}
lastImage.url = imageSource;
lastImage.data = imageData;
response.writeHead(200, {'Content-Type' : 'image/jpeg'});
response.end(imageData, 'binary');
});
});
}).on('error', function(err) {
console.log(err);
});
});
app.get("/", function(request, response, giveClient) {
// Warning: The following section is full of reasons why JavaScript is a broken language and ECMA is full of retards.
// I'll fill it with comments so you can understand why.
var topRooms = [];
// We duplicate the object so we can remove rooms every run.
// If you just do var rooms = serverData.rooms, changing 'rooms' will change serverData.
// "Could you use a function's scope to solve that?" Nope. Modifying a function's argument's keys will modify the input.
var rooms = Object.assign({}, serverData.rooms);
// {} == {} simply doesn't work in JS.
// {} != {} doesn't either.
// You simply can't compare objects in JS and get non-retarded results.
function hasRooms(rooms) {
for (var room in rooms) return true || room;
return false;
}
// This is just a selection algorithm that gets the 20 most important rooms.
// It's obvious what this does.
for (var x = 0; x < 20 && hasRooms(rooms); x++) {
var maxRoom = {
name: "Err: Sorting reaching non-max room.",
posts: -1,
users: -1
};
for (var roomName in rooms) {
var room = rooms[roomName];
if (room.clients.length > maxRoom.users) {
maxRoom = {
name: roomName,
topic: room.topic,
posts: room.posts,