forked from KieronDowie/TestingGrounds
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
3972 lines (3950 loc) · 136 KB
/
server.js
File metadata and controls
3972 lines (3950 loc) · 136 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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var http = require('http');
var url = require('url');
var fs = require('fs');
var roles = require('./roleinfo');
var ws = require('ws');
var crypto = require('crypto');
var storage = require('./storage.js');
var verified = []; //List of ips that are verified to use the MCP.
var createdList = [];
var gm = require('./gm.js');
var request = require('request');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded',
};
var commandList = {
all: {
help: 'Displays this message.',
whisper: 'Whisper to another player. This is silent during Pregame, but once in-game other players will know that you are whispering. Usage: /w name message',
mod: 'Send a message directly to the mod. Usage: /mod message',
target: 'Target a player with a night action. Usage: /target player or /target player1 player2',
vote: 'Command for voting, should only be used if there is a problem with the voting interface. Usage: /vote name',
role: 'View your current rolecard, or use /role name to view another rolecard. Usage /role to view your role, /role rolename to view a rolecard.',
rolelist: 'Display the current rolelist.',
confirm: 'Use during the roles phase to confirm you have your role. Usage: /confirm',
ping: 'Show your ping. Usage: /ping',
afk: 'Go afk. Only usable in pregame. Usage: /afk',
back: 'Return. Usage /back, after using /afk',
music: 'Tells you what music each phase is set to. Usage: /music',
tmk: 'Describes what Tactical Mafia Killing does. Usage: /tmk',
},
mod: {
givemod: 'Pass the mod onto another person. Usage: /givemod name',
a: 'Send a public message to everyone (outside of Pregame). Usage: /a message',
d: 'Send a public death message to everyone (outside of Pregame). Example: /d WW - Usage: /d message',
win: 'Send a public message to everyone stating who won the game. Example: /win town 1 4 5 8 12 13 14 15 - Usage: /win faction playernumbers',
random: 'Choose a random player. Usage: /random',
roll: 'Roll a dice. Usage /roll or /roll sides',
msg: 'Send a message to a player. <span class="mod">From</span> <b>Mod:</b> <span class="mod">This looks like this</span>. Usage: /msg name message',
sys: 'Send a system message to a player. <b>This looks like this</b>',
clean: "Set a player's will to not show upon death.",
forcevote: 'Forces a player to vote for a particular person. Usage: /forcevote person1 person2',
lockvote: "Locks the player's vote. They will be unable to vote or cancel their vote after you use this command, except through /forcevote. Usage: /lockvote person",
unlockvote: "Unlocks the player's vote. They will be able to vote and cancel their vote once more after you use this command. /unlockvote person",
settrial: 'Forces a trial on a player. They will automatically be voted to the stand.',
},
dev: {
dev: 'Activate developer powers.',
setspectate: 'Toggle someone\'s spectator setting. Usage: /setspectate name',
alert: 'Send an audio alert to a player.',
kick: 'Kick a player.',
ban: 'Ban an ip.',
silence: 'Silence a player until the end of the current phase. This effects all messages that are shown to other players.',
},
fun: {
me: 'Do something. Eg. <em>Player waves!</emY. Only usable during Pregame.',
hug: 'Send a hug to a person. Only usable during Pregame.',
},
};
//Enums and other code shared between client and server
var {
Type,
Phase,
sanitize,
msgToHTML,
} = require('./common.js');
//Game variables
var autoLevel = 1;
var phase = Phase.PREGAME;
var mod = undefined;
var ontrial = undefined;
var apass;
loadPassword();
loadBanlist();
var prev_rolled;
var testTime = new Date();
loadDate();
//Banlist
var banlist = [];
var server = http.createServer(function (req, res) {
var path = url.parse(req.url).pathname;
//Routing
switch (path) {
case '/':
if (apass) {
fs.readFile(__dirname + '/index.html', function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data, 'utf8');
res.end();
}
});
} else {
res.write('<h1>Server is busy loading... Please wait a few minutes then refresh the page.</h1>');
res.end();
}
break;
case '/gamelogs':
var filename = url.parse(req.url, true).query.filename;
if(filename) {
storage.load(filename).then(function(data) {
res.writeHead(200);
res.write('<!DOCTYPE html><html><head><meta charset="utf-8" /><link href="playstyle.css" rel="stylesheet" type="text/css" /></head><body id="main">');
res.write(data);
res.write('</body></html>');
res.end();
}, function() {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
});
} else {
storage.list().then(function(data) {
res.writeHead(200);
data.map(function({ Key: filename, Size: filesize }) {
res.write('<a href="/gamelogs?filename='+filename+'">'+filename+'</a> ('+filesize+' bytes)<br>');
});
res.end();
}, function(e) {
res.writeHead(500);
res.write('Failed to load list of gamelogs: '+e.message);
res.end();
})
}
break;
case '/MCP':
if (req.method == 'POST') {
var pass;
req.on('data', function (p) {
pass = p.toString();
pass = pass.substring(5, pass.length); //Drop the preceding 'pass='
});
req.on('end', function () {
//Check the password.
if (pass == apass) {
var ip = getIpReq(req);
if (!verified[ip]) {
verified[ip] = setTimeout(function () {
//Connection expired.
expireVerification(ip);
}, 5 * 60 * 1000);
}
fs.readFile(__dirname + '/MCP/mod.html', function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data, 'utf8');
res.end();
}
});
} else {
fs.readFile(__dirname + '/modpass.html', function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data, 'utf8');
res.end();
}
});
}
});
} else {
fs.readFile(__dirname + '/modpass.html', function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data, 'utf8');
res.end();
}
});
}
break;
case '/MCP/Admin':
case '/MCP/Players':
case '/MCP/Roles':
case '/MCP/Banlist':
if (isVerified(getIpReq(req))) {
fs.readFile(__dirname + path + '.html', 'utf-8', function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
data = formatData(data);
res.write(data, 'utf8');
res.end();
}
});
} else {
res.write('You do not have permission to access this page.');
res.end();
}
break;
case '/MCP/setPass':
{
res.write('You do not have permission to access this page.');
res.end();
}
break;
case '/MCP/setDate':
if (isVerified(getIpReq(req))) {
var datetime = url.parse(req.url).query;
//Make sure the date is in the correct format.
var sides = datetime.split('-');
var date = sides[0].split('/');
var time = sides[1];
var valid = true;
var error = '';
for (i in date) {
if (isNaN(date[i]) || !(date[i].length == 2 || (i == 2 && date[i].length == 4))) {
valid = false;
error = date[i];
break;
}
}
if (!/\d\d:\d\d/.test(time)) {
valid = false;
error = time;
}
res.write(error + ' is not formatted correctly.');
res.end();
} else {
res.write('You do not have permission to access this page.');
res.end();
}
break;
case '/MCP/playerList':
res.write('You do not have permission to access this page.');
res.end();
break;
case '/play':
var name = url.parse(req.url, true).query.name;
if(!name) {
res.writeHead(302, { Location: '/' }); //Send em home
res.end();
break;
}
//Serve the page.
fs.readFile(__dirname + path + '.html', function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data, 'utf8');
res.end();
}
});
break;
case '/time':
//Calculate time until the test.
var now = new Date().getTime();
var timeToTest = testTime.getTime() - now;
timeToTest = timeToTest / 1000; //To seconds.
if (timeToTest > 0) {
res.write(timeToTest + '');
} else {
res.write('now');
}
res.end();
break;
case '/namecheck':
var name = url.parse(req.url).query;
if (name && typeof name == 'string') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (nameTaken(name, getIpReq(req))) {
res.write('taken');
} else if (name.length == 0) {
res.write('empty');
} else if (name.toLowerCase() == 'empty') {
res.write('lol');
} else if (name.length > 20) {
res.write('toolong');
} else if (!/[a-z]/i.test(name)) {
res.write('noletters');
} else if (/^[a-z0-9-_]+$/i.test(name)) {
res.write('good');
} else {
res.write('invalid');
}
} else {
res.write('empty');
}
res.end();
break;
case '/common.js':
case '/socketstuff.js':
case '/script.js':
case '/playscript.js':
case '/themes.js':
case '/MCP/modscript.js':
case '/MCP/passscript.js':
case '/jquery-2.1.4.min.js':
case '/glDatePicker.min.js':
case '/snowstorm.js':
fs.readFile(__dirname + path, function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/js' });
res.write(data, 'utf8');
res.end();
}
});
break;
case '/style.css':
case '/playstyle.css':
case '/MCP/modstyle.css':
case '/MCP/calstyles/glDatePicker.default.css':
case '/MCP/calstyles/glDatePicker.darkneon.css':
case '/MCP/calstyles/glDatePicker.flatwhite.css':
fs.readFile(__dirname + path, function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/css' });
res.write(data, 'utf8');
res.end();
}
});
break;
case '/invest.png':
case '/sheriff.png':
case '/moon.png':
case '/maf.png':
case '/cov.png':
case '/mayor.png':
case '/med.png':
case '/jailor.png':
case '/blackmailer.png':
case '/will.png':
case '/willicon.png':
case '/notes.png':
case '/notesicon.png':
case '/button.png':
case '/list.png':
case '/settings.png':
case '/edit.png':
case '/accept.png':
case '/roll.png':
case '/back1.png':
case '/back2.png':
case '/back3.png':
case '/Unity_Innocent.png':
case '/Unity_Guilty.png':
case '/lastwillbutton.png':
case '/paste.png':
case '/notesbutton.png':
case '/notesclose.png':
case '/music.png':
case '/nomusic.png':
case '/Snowback1.png':
fs.readFile(__dirname + '/images/' + path, function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/png' });
res.write(data, 'utf8');
res.end();
}
});
break;
case '/dancingkitteh.gif':
fs.readFile(__dirname + '/images/' + path, function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/gif' });
res.write(data, 'utf8');
res.end();
}
});
break;
case '/ping.wav':
case '/Giratina.wav':
fs.readFile(__dirname + '/sounds/' + path, function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/wav' });
res.write(data, 'utf8');
res.end();
}
});
break;
case '/6ballStart.mp3':
case '/6ball.mp3':
case '/Agari.mp3':
case '/Alfheim.mp3':
case '/Aquabatics.mp3':
case '/AutumnMountain.mp3':
case '/Bewitching.mp3':
case '/CalmBeforeTheStorm.mp3':
case '/CareFree.mp3':
case '/Cascades.mp3':
case '/Cauldron.mp3':
case '/Chaos.mp3':
case '/CosmicCove.mp3':
case '/DarkAlley.mp3':
case '/DarkHolidays.mp3':
case '/Deceitful.mp3':
case '/GardenGridlock.mp3':
case '/GreenMeadows.mp3':
case '/Heated.mp3':
case '/Homecoming.mp3':
case '/Inevitable.mp3':
case '/Innocence.mp3':
case '/KakarikoNight.mp3':
case '/KakarikoSaved.mp3':
case '/LittleItaly.mp3':
case '/LonghornStartup.mp3':
case '/Magmic.mp3':
case '/MilkyWay.mp3':
case '/MountHylia.mp3':
case '/PeaceAndTranquility.mp3':
case '/Piglets.mp3':
case '/Remembrance.mp3':
case '/Riverside.mp3':
case '/Searching.mp3':
case '/ShockAndAwe.mp3':
case '/Skyworld.mp3':
case '/StarlitSky.mp3':
case '/Suspicion.mp3':
case '/Touchstone.mp3':
case '/ToyPuzzle.mp3':
case '/Truth.mp3':
case '/Valkyrie.mp3':
case '/Vampiric.mp3':
case '/WhatLurksInTheNight.mp3':
case '/WhoAmI.mp3':
case '/WLITN.mp3':
fs.readFile(__dirname + '/sounds/' + path, function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'audio/mpeg' });
res.write(data, 'utf8');
res.end();
}
});
break;
case '/Spinwheel.m4a':
fs.readFile(__dirname + '/sounds/' + path, function (error, data) {
if (error) {
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'audio/m4a' });
res.write(data, 'utf8');
res.end();
}
});
break;
default:
res.writeHead(404);
res.write("<h1>Oops! This page doesn't seem to exist! 404</h1>");
res.end();
break;
}
});
var port = process.env.PORT || 8080;
server.listen(port, function () {
console.log('Listening on port ' + port + '...');
});
//Server variables
//List of player objects.
var players = [];
//To store the order of players.
var playernums = [];
//List of names with their socket.id's. Needed to provide quick access to the player objects.
var playernames = [];
//Record of what happened in the game for future reference
var gamelog = [];
var io = new ws.WebSocketServer({ server: server });
//Start the timer.
var timer = Timer();
timer.tick();
timer.ping();
//Let the pinging begin
ping();
function addLogMessage() {
if(phase <= Phase.ROLES) {
return;
}
var [type, ...args] = arguments;
var html = msgToHTML(type, args);
if(html) {
gamelog.push(html);
}
}
function sendPublicMessage() {
addLogMessage.apply(this, arguments);
for(var i in players) {
players[i].s.sendMessage.apply(players[i].s, arguments);
}
}
function playerToReference(player) {
return {
num: playernums.indexOf(player.s.id),
name: player.name,
};
}
io.on('connection', function (socket, req) {
socket.id = crypto.randomBytes(16).toString("hex");
var listeners = {};
function addSocketListener(type, callback) {
listeners[type] = callback;
}
socket.addEventListener('message', function(event) {
try {
var [type, ...args] = JSON.parse(event.data);
} catch(err) {
socket.sendMessage(Type.SYSTEM, ''+err);
return;
}
if(type !== Type.JOIN && !players[socket.id]) {
return;
}
if(listeners[type]) { try {
listeners[type].apply(socket, args);
} catch(err) {
console.error(err);
addLogMessage(Type.SYSTEM, sanitize(err.stack).replace(/\n/g, '<br>'));
socket.sendMessage(Type.SYSTEM, 'That command caused an error: '+err);
} }
});
socket.sendMessage = function() {
this.send(JSON.stringify(Array.prototype.slice.call(arguments)));
}
var ip = getIpReq(req);
addSocketListener(Type.JOIN, function(connecting_as_name, simple_resume) {
var banned = false;
var reason = '';
for (i in banlist) {
if (banlist[i].ip == ip) {
banned = true;
reason = banlist[i].reason;
}
}
if (banned) {
socket.sendMessage(
Type.SYSTEM,
'This IP has been banned. Reason: ' +
reason +
'.<br>If you believe this was a mistake, bring it up on the <a href="https://discord.gg/EVS55Zb">Testing Grounds Discord Server</a>.'
);
socket.sendMessage(Type.KICK);
console.log('Connection attempt from banned ip: ' + ip);
socket.close();
} else if (!nameCheck(connecting_as_name)) {
socket.sendMessage(Type.SYSTEM, 'Invalid name!');
socket.sendMessage(Type.KICK);
socket.close();
} else {
//Check if the person is reconnecting or an alt.
var reconnecting = null;
var alts = [];
for (i in players) {
if (ip == players[i].ip) {
if(connecting_as_name == players[i].name) {
reconnecting = players[i];
} else {
alts.push(players[i].name);
}
}
}
//If reconnecting, give them their old slot back
if(reconnecting) {
//Rejoining after a dc
//If the player is a mod who disconnected, set them as the mod.
if (reconnecting.s.id == mod) {
mod = socket.id;
}
//If the player was on trial, update the ontrial variable
if (reconnecting.s.id == ontrial) {
ontrial = socket.id;
}
if (reconnecting.s.readyState == ws.OPEN) {
//The player might have duplicated the tab. Disconnect the old one in a non-confusing way.
reconnecting.s.sendMessage(Type.SYSTEM, 'You have been disconnected because you connected again elsewhere.');
reconnecting.s.sendMessage(Type.KICK);
reconnecting.s.close();
}
//Welcome back!
delete players[reconnecting.s.id];
players[socket.id] = reconnecting;
playernums[playernums.indexOf(reconnecting.s.id)] = socket.id;
playernames[players[socket.id].name] = socket.id;
//Replace the old socket.
players[socket.id].s = socket;
//Reset ping.
players[socket.id].ping = 0;
socket.sendMessage(Type.ACCEPT);
if(mod == socket.id) {
socket.sendMessage(Type.SETMOD, true);
} else {
socket.sendMessage(Type.SETMOD, false);
}
if(simple_resume && !players[socket.id].visibly_disconnected) {
return;
}
socket.sendMessage(Type.PAUSEPHASE, timer.paused);
socket.sendMessage(Type.SETDAYNUMBER, gm.getDay());
socket.sendMessage(Type.SYSTEM, 'You have reconnected. Welcome back!');
var name = players[socket.id].name;
//Inform everyone of the new arrival.
sendPublicMessage(Type.RECONNECT, name);
players[socket.id].visibly_disconnected = false;
//Tell the new arrival what phase it is.
socket.sendMessage(Type.SETPHASE, phase, true, timer.time);
if (players[mod] && mod != socket.id) {
var send = {};
for (i in players[socket.id].chats) {
if (players[socket.id].chats[i]) {
send[i] = players[socket.id].chats[i];
}
}
//Exceptions
send.name = players[socket.id].name;
send.alive = players[socket.id].alive;
send.blackmailer = players[socket.id].hearwhispers;
send.mayor = players[socket.id].mayor !== undefined;
send.gardenia = players[socket.id].gardenia !== undefined;
send.role = players[socket.id].role;
players[mod].s.sendMessage(Type.ROLEUPDATE, send);
}
//Resend the list.
sendRoomlist(socket);
//Set the rejoining player's will.
socket.sendMessage(Type.GETWILL, undefined, players[socket.id].will);
//Set the rejoining player's notes.
socket.sendMessage(Type.GETNOTES, undefined, players[socket.id].notes);
//Inform the new arrival of their targeting options, if any.
sendPlayerTargetingOptions(players[socket.id]);
//If the mod is reconnecting, send the role data for all players
if(mod == socket.id) {
sendPlayerInfo();
}
} else if (!nameTaken(connecting_as_name)) { //Second check for the name being taken
if (connecting_as_name) {
socket.sendMessage(Type.PAUSEPHASE, timer.paused);
socket.sendMessage(Type.SETDAYNUMBER, gm.getDay());
//If the player is first, set them as the mod.
if (Object.keys(players).length == 0) {
mod = socket.id;
}
//Send the list of names in the game to the new arrival
sendRoomlist(socket);
socket.sendMessage(Type.ACCEPT);
players[socket.id] = Player(socket, connecting_as_name, ip);
//Inform everyone of the new arrival.
sendPublicMessage(Type.JOIN, connecting_as_name);
if(mod == socket.id) {
socket.sendMessage(Type.SETMOD, true);
} else {
socket.sendMessage(Type.SETMOD, false);
}
if (phase != 0) {
for (i in players) {
if (connecting_as_name == players[i].name) {
players[i].spectate = true;
players[i].setRole('Spectator');
}
}
sendPublicMessage(Type.SETSPEC, connecting_as_name);
}
if (alts.length > 0) {
//Inform everyone of the alt.
sendPublicMessage(Type.HIGHLIGHT, 'Note: ' + connecting_as_name + ' is an alt of ' + gm.grammarList(alts) + '.');
}
//Tell the new arrival what phase it is.
socket.sendMessage(Type.SETPHASE, phase, true, timer.time);
//Inform the new arrival of any devs and spectators present.
for (i in players) {
if (players[i].spectate) {
socket.sendMessage(Type.SETSPEC, players[i].name);
}
if (players[i].dev) {
socket.sendMessage(Type.SETDEV, players[i].name);
}
}
//Inform the new arrival of their targeting options, if any.
sendPlayerTargetingOptions(players[socket.id]);
}
} else {
socket.sendMessage(Type.DENY, 'Sorry, this name is taken.');
socket.close();
}
}
});
addSocketListener(Type.AUTOLEVEL, function (lvl) {
if (socket.id == mod) {
autoLevel = lvl;
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can set the level of automation.');
}
});
addSocketListener(Type.GUARDIAN_ANGEL, function (name) {
sendPublicMessage(Type.GUARDIAN_ANGEL, name);
});
addSocketListener(Type.PHLOX, function (name) {
sendPublicMessage(Type.PHLOX, name);
});
addSocketListener(Type.REMOVE_EMOJI, function (emojiId) {
sendPublicMessage(Type.REMOVE_EMOJI, emojiId);
});
addSocketListener(Type.MSG, function (msg) {
if (msg.length > 512) {
socket.sendMessage(Type.SYSTEM, 'Your message sent was over 512 characters.');
} else if (msg.trim() == '') {
socket.sendMessage(Type.SYSTEM, 'You cannot send an empty message.');
} else if (msg[0] == '/') {
players[socket.id].command(msg.substring(1, msg.length));
} else {
players[socket.id].message(msg);
}
});
addSocketListener(Type.CUSTOMROLES, function (bool) {
roles.setCustomRoles(bool);
});
addSocketListener(Type.PRENOT, function (name, prenot) {
if (socket.id == mod) {
var player = getPlayerByName(name);
var modmessage = '';
switch (prenot) {
case 'HEAL':
modmessage = name + ' was attacked and healed.';
break;
case 'SAVED_BY_BG':
modmessage = name + ' was attacked and saved by a Bodyguard.';
break;
case 'PROTECTED':
modmessage = name + ' was attacked and protected.';
break;
case 'SAVED_BY_TRAP':
modmessage = name + ' was attacked and saved by a trap.';
break;
case 'DEAD':
modmessage = name + ' was killed.';
break;
case 'TARGET_ATTACKED':
modmessage = name + '\'s target was attacked.';
break;
case 'DOUSE':
modmessage = name + ' was doused.';
break;
case 'BLACKMAIL':
modmessage = name + ' was blackmailed.';
break;
case 'TARGETIMMUNE':
modmessage = name + ' attacked someone with too strong of a defense.';
break;
case 'IMMUNE':
modmessage = name + ' was attacked but immune.';
break;
case 'SHOTVET':
modmessage = name + ' was shot by a Veteran.';
break;
case 'VETSHOT':
modmessage = name + ' shot one of their visitors.';
break;
case 'RB':
modmessage = name + ' was roleblocked.';
break;
case 'WITCHED':
modmessage = name + ' was controlled.';
break;
case 'REVIVE':
modmessage = name + ' was revived.';
break;
case 'JAILED':
modmessage = name + ' was hauled off to Jail.';
break;
case 'ENTANGLED':
modmessage = name + ' was locked away in the Garden.';
break;
case 'GUARDIAN_ANGEL':
modmessage = name + ' was watched by their Guardian Angel.';
break;
case 'PHLOX':
modmessage = name + ' was purified by a Phlox.';
break;
case 'SAVED_BY_GA':
modmessage = name + ' was attacked but their Guardian Angel saved them.';
break;
case 'POISON_CURABLE':
modmessage = name + ' was poisoned. They will die unless they are cured.';
break;
case 'POISON_UNCURABLE':
modmessage = name + ' was poisoned.';
break;
case 'MEDUSA_STONE':
modmessage = name + ' stoned someone.';
break;
case 'TRANSPORT':
modmessage = name + ' was transported.';
break;
case 'TARGET_ATTACKED':
modmessage = name + '\'s target was attacked.';
break;
case 'INNO':
modmessage = name + '\'s target was innocent.';
break;
case 'SUS':
modmessage = name + '\'s target was suspicious.';
break;
}
addLogMessage(Type.SYSTEM, modmessage);
players[mod].s.sendMessage(Type.SYSTEM, modmessage);
player.s.sendMessage(Type.PRENOT, prenot);
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can do that.');
}
});
addSocketListener(Type.ROLL, function (rolelist, custom, exceptions) {
if (socket.id == mod) {
var result = roles.sortRoles(rolelist, custom, exceptions);
createdList = rolelist;
var names = Object.keys(playernames);
names.splice(names.indexOf(players[mod].name), 1); //Get rid of the mod.
for (i in players) {
if (players[i].spectate) {
names.splice(names.indexOf(players[i].name), 1);
}
}
shuffleArray(names);
//Format the roles
for (i in result) {
result[i] = roles.formatRolename(result[i]);
}
socket.sendMessage(Type.ROLL, result, names, []);
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can do that.');
}
});
addSocketListener(Type.SETROLE, function (name, role) {
if (socket.id == mod) {
if (role.length > 80) {
socket.sendMessage(Type.SYSTEM, 'Role name cannot be more than 80 characters.');
} else {
var p = getPlayerByName(name);
if (p) {
p.setRole(role);
} else {
socket.sendMessage(Type.SYSTEM, 'Invalid name "' + name + '", did you break something?');
}
}
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can do that.');
}
});
addSocketListener(Type.SETROLESBYLIST, function (roles, names) {
if (socket.id == mod) {
prev_rolled = roles;
for (i in names) {
if (roles[i].length > 80) {
socket.sendMessage(Type.SYSTEM, 'Invalid rolelist! Role name cannot be more than 80 characters: ' + roles[i]);
break;
}
var p = getPlayerByName(names[i]);
if (p) {
p.setRole(roles[i]);
} else {
socket.sendMessage(Type.SYSTEM, 'Invalid rolelist! Could not find player: ' + names[i]);
break;
}
}
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can do that.');
}
});
addSocketListener(Type.GETWILL, function (num) {
var p = getPlayerByNumber(num);
if (!p) {
socket.sendMessage(Type.SYSTEM, 'Invalid player number: ' + num);
} else if (socket.id == mod) {
socket.sendMessage(Type.GETWILL, p.name, p.will);
} else if (p.publicwill) {
socket.sendMessage(Type.GETWILL, p.name, p.publicwill);
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can do that.');
}
});
addSocketListener(Type.GETNOTES, function (num) {
if (socket.id == mod) {
var p = getPlayerByNumber(num);
if (p) {
socket.sendMessage(Type.GETNOTES, p.name, p.notes);
} else {
socket.sendMessage(Type.SYSTEM, 'Invalid player number: ' + num);
}
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can do that.');
}
});
addSocketListener(Type.SHOWLIST, function (list) {
if (socket.id == mod) {
createdList = list;
if (!players[socket.id].silenced) {
sendPublicMessage(Type.SHOWLIST, createdList.map(function(roleslot) {
return roles.formatAlignment(sanitize(roleslot));
}));
}
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can do that.');
}
});
addSocketListener(Type.SHOWALLROLES, function () {
if (socket.id == mod) {
var c = 0;
var list = [];
for (i in players) {
if (players[i].s.id != mod) {
list.push({ name: players[i].name, role: roles.formatRolename(players[i].role) });
c++;
}
}
if (players[socket.id]) {
sendPublicMessage(Type.SHOWALLROLES, list);
}
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can do that.');
}
});
addSocketListener(Type.SETPHASE, function (p) {
if (mod == socket.id && p >= 0 && p < Object.keys(Phase).length) {
setPhase(p);
}
});
addSocketListener(Type.SETDAYNUMBER, function (num) {
if (socket.id == mod) {
gm.setDay(num);
sendPublicMessage(Type.SETDAYNUMBER, gm.getDay());
} else {
socket.sendMessage(Type.SYSTEM, 'Only the mod can set the day number.');
}
});
addSocketListener(Type.PAUSEPHASE, function () {
if (mod == socket.id) {
timer.paused = !timer.paused;
sendPublicMessage(Type.PAUSEPHASE, timer.paused);
} else {
socket.sendMessage(Type.SYSTEM, 'You need to be the mod to pause or unpause.');
}
});
addSocketListener(Type.WILL, function (will, name) {
if (will !== undefined && will !== null) {
if (name) {
if (mod == socket.id) {
var p = getPlayerByName(name);
if (p) {
p.will = will;
} else {
socket.sendMessage(Type.SYSTEM, 'Invalid player name:' + name);
}
} else {