-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1720 lines (1325 loc) · 57.2 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
//check README.md
//load secret config vars
require("dotenv").config();
const GAME = require("./game");
var fs = require('fs');
var numberConverter = require('number-to-words');
var Parser = require('expr-eval').Parser;
//.env content
/*
ADMINS=username1|pass1,username2|pass2
PORT = 3000
*/
var port = process.env.PORT || 3000;
//if loading twee story file
if (GAME.SETTINGS.STORY_FILE != "" && GAME.SETTINGS.STORY_FILE != null) {
fs.readFile(GAME.SETTINGS.STORY_FILE, 'utf8', function (err, data) {
if (err) throw err;
GAME.PASSAGES = parseTwee(data);
});
}
else
console.log("WARNING: NO STORY FILE " + GAME.SETTINGS.STORY_FILE);
//number of emits per second allowed for each player, after that ban the IP.
//over 30 emits in this game means that the client is hacked and the flooding is malicious
//if you change the game logic make sure this limit is still reasonable
var PACKETS_PER_SECONDS = 30;
/*
The client and server version strings MUST be the same!
They can be used to force clients to hard refresh to load the latest client.
If the server gets updated it can be restarted, but if there are active clients (users' open browsers) they could be outdated and create issues.
If the VERSION vars are mismatched they will send all clients in an infinite refresh loop. Make sure you update sketch.js before restarting server.js
*/
var VERSION = "1.0";
//create a web application that uses the express frameworks and socket.io to communicate via http (the web protocol)
var express = require("express");
var app = express();
var http = require("http").createServer(app);
var io = require("socket.io")(http);
var Filter = require("bad-words");
//time before disconnecting (forgot the tab open?)
var ACTIVITY_TIMEOUT = 10 * 60 * 1000;
//should be the same as index maxlength="16"
var MAX_NAME_LENGTH = 16;
//cap the overall players
var MAX_PLAYERS = -1;
//refuse people when a room is full
var MAX_PLAYERS_PER_ROOM = 200;
//views since the server started counts relogs
var visits = 0;
/*
A very rudimentary admin system.
Reserved usernames and admin pass are stored in .env file as
ADMINS=username1|pass1,username2|pass2
Admin logs in as username|password in the normal field
If combo user|password is correct (case insensitive) mark the player as admin on the server side
The "username|password" remains stored on the client as var nickName
and it's never shared to other clients, unlike player.nickName
admins can call admin commands from the chat like /kick nickName
*/
var admins = [];
if (process.env.ADMINS != null)
admins = process.env.ADMINS.split(",");
//We want the server to keep track of the whole game state
//in this case the game state are the attributes of each player
var gameState = {
players: {},
}
//save the server startup time and send it in case the clients need to syncronize something
var START_TIME = Date.now();
//a collection of banned IPs
//not permanent, it lasts until the server restarts
var banned = [];
//when a client connects serve the static files in the public directory ie public/index.html
app.use(express.static("public"));
//when a client connects the socket is established and I set up all the functions listening for events
io.on("connection", function (socket) {
//this bit (middleware?) catches all incoming packets
//I use to make my own lil rate limiter without unleashing 344525 dependencies
//a rate limiter prevents malicious flooding from a hacked client
socket.use((packet, next) => {
if (gameState.players[socket.id] != null) {
var p = gameState.players[socket.id];
p.floodCount++;
if (p.floodCount > PACKETS_PER_SECONDS) {
console.log(socket.id + " is flooding! BAN BAN BAN");
if (p.IP != "") {
//comment this if you don't want to ban the IP
banned.push(p.IP);
socket.emit("errorMessage", "Flooding attempt! You are banned");
socket.disconnect();
}
}
}
next();
});
//this appears in the server terminal
console.log("A user connected");
//send server data to client
socket.emit("serverWelcome", VERSION, START_TIME, GAME.SETTINGS, GAME.TEXT);
//check if the IP is banned and if we reached the maximum number of players on the server
socket.on("join", function () {
//if running locally it's not gonna work
var IP = "";
//oh look at this beautiful socket.io to get an goddamn ip address
if (socket.handshake.headers != null)
if (socket.handshake.headers["x-forwarded-for"] != null) {
IP = socket.handshake.headers["x-forwarded-for"].split(",")[0];
}
var serverPlayers = Object.keys(io.sockets.connected).length + 1;
var isBanned = false;
//prevent banned IPs from joining
if (IP != "") {
var index = banned.indexOf(IP);
//found
if (index > -1) {
isBanned = true;
}
}
if (isBanned) {
console.log("ATTENTION: banned " + IP + " is trying to log in again");
socket.emit("errorMessage", "You have been banned");
socket.disconnect();
}
else if (serverPlayers > MAX_PLAYERS && MAX_PLAYERS > 0) {
console.log("ATTENTION: reached maximum number of players");
socket.emit("errorMessage", "Sorry, the server is full");
socket.disconnect();
}
//prevent a hacked client from duplicating players
else if (gameState.players[socket.id] != null) {
console.log("ATTENTION: there is already a player associated to the socket " + socket.id);
socket.disconnect();
}
});
socket.on("submitName", function (nickName) {
try {
//if client hacked truncate
if (nickName.length > MAX_NAME_LENGTH)
nickName = nickName.substring(0, MAX_NAME_LENGTH);
//if running locally it's not gonna work
var IP = "";
//oh look at this beautiful socket.io to get an goddamn ip address
if (socket.handshake.headers != null)
if (socket.handshake.headers["x-forwarded-for"] != null) {
IP = socket.handshake.headers["x-forwarded-for"].split(",")[0];
}
var val = 1;
val = validateName(nickName);
socket.emit("nameResponse", val);
}
catch (e) {
console.log("Error on submitName from " + socket.id);
console.error(e);
}
});
socket.on("login", function (nickName, pronoun, description) {
try {
//if running locally it's not gonna work
var IP = "";
//oh look at this beautiful socket.io to get an goddamn ip address
if (socket.handshake.headers != null)
if (socket.handshake.headers["x-forwarded-for"] != null) {
IP = socket.handshake.headers["x-forwarded-for"].split(",")[0];
}
//validate again in case of hacks
var val = validateName(nickName);
if (val != 0 && val != 3) {
//if there is an | strip the after so the password remains in the admin client
var combo = nickName.split("|");
nickName = combo[0];
if (val == 2)
console.log(nickName + " joins as admin");
else
print(nickName + " logs in");
var firstPassage = GAME.SETTINGS.firstPassage;
var firstRoom = "";
if (GAME.PASSAGES[firstPassage] != null) {
firstPassage = firstPassage;
}
else if (GAME.PASSAGES["Start"] != null) {
firstPassage = "Start";
}
else if (GAME.PASSAGES["start"] != null) {
firstPassage = "start";
}
else {
print("WARNING: No VALID first passage specified, going with the first: " + Object.keys(GAME.PASSAGES)[0]);
firstPassage = Object.keys(GAME.PASSAGES)[0];
}
if (GAME.PASSAGES[firstPassage].room != null)
firstRoom = GAME.PASSAGES[firstPassage].room;
print("First " + firstPassage);
//create the player object
var p = {};
p.id = socket.id;
p.nickName = filter.clean(nickName);
p.room = firstRoom;
p.privateChannel = "";
p.privateChannelName = "";
p.passage = firstPassage;
p.previousPassage = "";
p.recentAction = "";
p.pronoun = pronoun;
p.description = description;
p.randomSeed = randomInt(0, 100);
//the server keeps track of more variables that are not sent to the client
p.lastMessage = 0;
p.admin = (val == 2) ? true : false;
p.spam = 0;
p.lastActivity = new Date().getTime();
p.muted = false;
p.IP = IP;
p.floodCount = 0;
p.afk = false;
//game custom initialization
if (GAME.initPlayer != null)
GAME.initPlayer(p);
//save the same information in my game state
gameState.players[socket.id] = p;
//send the clients only the useful stuff
var newPlayer = getPlayer(socket.id);
//if passage has a room associated send the user there
if (firstRoom != "") {
socket.join(newPlayer.room, function () { });
//send all OTHER players information about the new player
socket.broadcast.to(newPlayer.room).emit('playerJoined', newPlayer);
var roomPlayers = getRoomPlayers(newPlayer.room);
//send the player the state of the room, current players and such
socket.emit("joinedRoom", newPlayer.room, roomPlayers);
}
//parse text
var html = parseText(GAME.PASSAGES[firstPassage].text, p);
var closeChat = (GAME.PASSAGES[firstPassage].room == "" || GAME.PASSAGES[firstPassage].room == null);
if (GAME.passageFilter != null)
html = GAME.passageFilter(html, newPlayer, firstPassage);
socket.emit("changePassage", html, closeChat);
//socket.emit("changedPassage", GAME.PASSAGES[firstPassage]);
visits++;
console.log("There are now " + Object.keys(gameState.players).length + " players on this server. Total visits " + visits);
}
else
print("Warning: " + socket.id + " attempts login with a hacked client");
}
catch (e) {
console.log("Error on submitName from " + socket.id);
console.error(e);
}
});
//textfield
//language based
socket.on("requestPassage", function (pId, actionMessage) {
try {
if (GAME.PASSAGES[pId] == null) {
print("Error: there is no passage named " + pId);
}
else {
//moving it to a function since it can happen automatically
changePassage(pId, actionMessage, socket);
}
}
catch (e) {
console.log("Error on requestPassage from " + socket.id);
console.error(e);
}
});
//no passage is open just
socket.on("openURL", function (actionMessage) {
try {
var player = gameState.players[socket.id];
var room = gameState.players[socket.id].room;
var passageId = gameState.players[socket.id].passage;
if (actionMessage != "" && room != null) {
//quick check making sure message is not hacked
if (GAME.PASSAGES[passageId].text.indexOf(actionMessage) != -1) {
var msg = adapt(actionMessage, player, false);
socket.broadcast.to(room).emit("actionMessage", msg);
}
}
}
catch (e) {
console.log("Error on openURL from " + socket.id);
console.error(e);
}
});
//a custom description is served
socket.on("requestDescription", function (playerId) {
try {
var target = gameState.players[playerId];
var requester = gameState.players[socket.id];
gameState.players[socket.id].lastActivity = new Date().getTime();
if (target == null || target.room != requester.room) {
//inquiring about a person who is not here anymore?
}
else {
//add a back
var linkBack = "<a class='passageLink' href='#' onclick='requestPassage(\"" + requester.passage + "\"); return false; '>" + GAME.TEXT.descriptionBack + " " + adapt("them", target, target.pronoun) + "</a>";
var afkText = "";
if (target.afk)
afkText = adapt(GAME.TEXT.AFK, [target]);
var description = GAME.TEXT.descriptionIntro + " " + target.nickName + ".<br/>" + target.description + afkText + "<br/>" + linkBack;
if (GAME.descriptionFilter != null)
description = GAME.descriptionFilter(description, target, requester);
//set a private channel if in description without leaving the public one
requester.privateChannel = playerId;
requester.privateChannelName = target.nickName;
socket.emit("descriptionReceived", description, target.nickName);
socket.emit("changeTitle", target.nickName);
var look = adapt(GAME.TEXT.lookDescription, [requester]);
//avoid glance spamming
if (requester.recentAction != look) {
io.sockets.sockets[target.id].emit("actionMessage", look);
requester.recentAction = look;
}
}
}
catch (e) {
console.log("Error on requestDescription from " + socket.id);
console.error(e);
}
});
//this looks for a function in GAME
socket.on("requestFunction", function (aId, arguments) {
try {
if (GAME[aId] != null) {
GAME[aId](socket.id, arguments);
}
else {
print("Error: there is no function called " + aId + " in game.js");
}
}
catch (e) {
console.log("Error on requestFunction from " + socket.id);
console.error(e);
}
});
//when a client disconnects I have to delete its player object
//or I would end up with ghost players
socket.on("disconnect", function () {
try {
console.log("Player disconnected " + socket.id);
var disconnectingPlayer = gameState.players[socket.id];
//player is null when exits before loggin in
if (disconnectingPlayer != null) {
//communicates to all
io.sockets.emit("playerLeft", socket.id, true);
//communicates to the room
if (disconnectingPlayer.room != "") {
var msg = adapt(GAME.TEXT.disconnect, [disconnectingPlayer], true);
socket.broadcast.to(disconnectingPlayer.room).emit("actionMessage", msg);
}
//send the disconnect
//delete the player object
disconnectingPlayer = null;
delete gameState.players[socket.id];
//gameState.players[socket.id] = null;
console.log("There are now " + Object.keys(gameState.players).length + " players on this server");
}
}
catch (e) {
console.log("Error on disconnect from" + socket.id);
console.error(e);
}
});
//when I receive a talk send it to everybody in the room
socket.on("talk", function (message) {
try {
var time = new Date().getTime();
var room = gameState.players[socket.id].room;
//block if spamming
if (room != "" && time - gameState.players[socket.id].lastMessage > GAME.SETTINGS.ANTI_SPAM && !gameState.players[socket.id].muted) {
//Admin commands can be typed as messages
//is this an admin
if (gameState.players[socket.id].admin && message.charAt(0) == "/") {
console.log("Admin " + gameState.players[socket.id].nickName + " attempts command " + message);
adminCommand(socket, message);
}
else {
//normal talk stuff
//aphostrophe
message = message.replace("’", "'");
//replace unmapped characters
message = message.replace(/[^A-Za-z0-9_!$%*()@./#&+-|]*$/g, "");
//replace html tags
message = message.replace(/(<([^>]+)>)/ig, "");
//remove leading and trailing whitespaces
message = message.replace(/^\s+|\s+$/g, "");
//filter bad words
message = filter.clean(message);
//advanced cleaning
//f u c k
var test = message.replace(/\s/g, "");
//fffffuuuuck
var test2 = message.replace(/(.)(?=.*\1)/g, "");
//f*u*c*k
var test3 = message.replace(/\W/g, "");
//spaces
var test4 = message.replace(/\s/g, "");
if (filter.isProfane(test) || filter.isProfane(test2) || filter.isProfane(test3) || test4 == "") {
console.log(socket.id + " is problematic");
}
else {
if (message != "") {
var player = gameState.players[socket.id];
if (GAME.talkFilter != null) {
message = GAME.talkFilter(message, player);
}
if (player.privateChannel == "" || player.privateChannel == null) {
//don't link yourself
var htmlMsgMe = "<span class='nameLink me' >" + player.nickName + "</span>: " + message;
//for others
var htmlMsg = nameLink(player.id) + ": " + message;
//send to everybody else
socket.broadcast.to(room).emit("playerTalked", htmlMsg);
//send to the talker
socket.emit("playerTalked", htmlMsgMe);
//if talking in an empty room
var rp = getRoomPlayers(room, player.id);
if (rp.length == 0) {
var msg = randomIn(GAME.TEXT.talkingAlone);
socket.emit("actionMessage", msg);
}
}
else {
//private talk
//don't link yourself
var htmlMsgMe = "<span class='nameLink me' >" + player.nickName + "</span>: " + "<span class='whisper'>(whispering) " + message + "</span>";
//for others
var htmlMsg = nameLink(player.id) + ": " + "<span class='whisper'>(whispering to you) " + message + "</span>";
if (io.sockets.sockets[player.privateChannel] != null) {
io.sockets.sockets[player.privateChannel].emit("playerTalked", htmlMsg);
//send to the talker
socket.emit("playerTalked", htmlMsgMe);
}
else {
socket.emit("actionMessage", player.privateChannelName + " " + GAME.TEXT.user_left);
}
}
}
}
}
//update the last message time
if (gameState.players[socket.id] != null) {
gameState.players[socket.id].lastMessage = time;
gameState.players[socket.id].lastActivity = time;
}
}
} catch (e) {
console.log("Error on talk from" + socket.id);
console.error(e);
}
});
//when I receive a user name validate it
socket.on("sendName", function (nn) {
try {
var res = validateName(nn);
//send the code 0 no - 1 ok - 2 admin
socket.emit("nameValidation", res);
} catch (e) {
console.log("Error on sendName from " + socket.id);
console.error(e);
}
});
//user afk
socket.on("focus", function () {
try {
var p = gameState.players[socket.id];
if (p != null) {
p.afk = false;
if (p.room != null)
io.to(p.room).emit("playerFocused", p.nickName);
}
} catch (e) {
console.log("Error on playerFocused from " + socket.id);
console.error(e);
}
});
socket.on("blur", function () {
try {
var p = gameState.players[socket.id];
if (p != null) {
p.afk = true;
if (p.room != null)
io.to(p.room).emit("playerBlurred", p.nickName)
}
} catch (e) {
console.log("Error on playerBlurred from " + socket.id);
console.error(e);
}
});
//generic action listener, looks for a function with that id in the mod
socket.on("action", function (aId) {
try {
io.to(obj.room).emit("playerActed", socket.id, aId);
} catch (e) {
console.log("Error on playerActed from " + socket.id);
console.error(e);
}
});
});
//rate limiting - clears the flood count
setInterval(function () {
for (var id in gameState.players) {
if (gameState.players.hasOwnProperty(id)) {
gameState.players[id].floodCount = 0;
}
}
}, 1000);
//custom every second function for
setInterval(function () {
if (GAME.everySecond != null)
GAME.everySecond();
}, 1000);
function changePassage(pId, actionMessage, socket) {
////////////////////////////turn this into a function
var movingPlayer = gameState.players[socket.id];
var fromPassage = movingPlayer.previousPassage = movingPlayer.passage;
movingPlayer.passage = pId;
gameState.players[socket.id].lastActivity = new Date().getTime();
//change room
var toId = GAME.PASSAGES[pId].room || "";
var fromId = gameState.players[socket.id].room || "";
//update the server room
gameState.players[socket.id].room = toId;
//parse text
var html = parseText(GAME.PASSAGES[pId].text, gameState.players[socket.id]);
var closeChat = (GAME.PASSAGES[pId].room == "" || GAME.PASSAGES[pId].room == null);
if (GAME.passageFilter != null)
html = GAME.passageFilter(html, movingPlayer, pId);
socket.emit("changePassage", html, closeChat);
if (GAME.ROOM_TITLES[toId] != null)
socket.emit("changeTitle", GAME.ROOM_TITLES[toId]);
else
socket.emit("changeTitle", "");
//no more on a private channel if any
movingPlayer.privateChannel = "";
movingPlayer.privateChannelName = "";
if (actionMessage != "" && (fromId != "" || toId != "")) {
//quick check making sure message is not hacked
if (GAME.PASSAGES[fromPassage].text.indexOf(actionMessage) != -1) {
var noLink = (toId != fromId);
var msg = adapt(actionMessage, movingPlayer, noLink);
//send it to the room(s) involved if any
if (fromId != "")
socket.broadcast.to(fromId).emit("actionMessage", msg);
if (toId != fromId && toId != "")
socket.broadcast.to(toId).emit("actionMessage", msg);
}
}
//if the passage has a room associated and the room is different than the current one join
if (toId != fromId) {
console.log("Player " + socket.id + " moved from " + fromId + " to " + toId);
//if leaving a room broadcast to the players in the room
if (fromId != "") {
socket.leave(fromId);
//broadcast the change to everybody in the current room
io.to(fromId).emit("playerLeft", socket.id, false);
}
//if joining a room broadcast the changes to the current player and send the state to the moving player
if (toId != "" && toId != fromId) {
socket.join(toId);
//send all OTHER players information about the new player
//upon creation destination and position are the same
socket.broadcast.to(toId).emit('playerJoined', movingPlayer);
//retrieving the state of the current room
var roomPlayers = getRoomPlayers(toId);
//send ONLY the new player the state of the room, current players and such
socket.emit("joinedRoom", toId, roomPlayers);
}
}//changing rooms
}
function parseText(txt, player) {
//1-
//parse the "links" between rooms, it's a twine-like syntax that gets converted into a link that calls a changePassage function
var link = txt.match(/\[\[([\s\S]*?)\]\]/);
var failSafe = 0;
while (link != null && failSafe < 1000) {
//found link
if (link != null) {
var l = link[1].split("|");
var linkText = l[0];
var actionMessage = "";
//parse the actionMessage associated to the link
var actionMessageArr = l[0].split(">>");
if (actionMessageArr.length > 1) {
actionMessage = actionMessageArr[1];
//strip action from link text
linkText = actionMessageArr[0];
//horrible trick to prevent replacement in inner links
actionMessage = actionMessage.replace("$", "@@");
}
if (l.length == 1) {
//passage and link text are the same
var passage = linkText.replace(/^\s+|\s+$/g, "");
var htmlLink = "<a class='passageLink' href='#' onclick='requestPassage(\"" + + "\", \"" + actionMessage + "\"); return false; '>" + linkText + "</a>";
txt = txt.replace(link[0], htmlLink);
}
else if (l.length == 2) {
//passage and link text are not the same
//whitespaces
var passage = l[1].replace(/^\s+|\s+$/g, "");
//is it a link
if (passage.match(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig)) {
var urlString = passage;
var htmlLink = "<a class=\"externalLink\" target=\"_blank\" href=\"" + urlString + "\" onclick='openURL(\"" + actionMessage + "\");'>" + linkText + "</a>";
txt = txt.replace(link[0], htmlLink);
}
else {
var htmlLink = "<a class='passageLink' href='#' onclick='requestPassage(\"" + passage + "\", \"" + actionMessage + "\"); return false; '>" + linkText + "</a>";
txt = txt.replace(link[0], htmlLink);
}
}
else {
print("Error: Link malformed " + link[0]);
failSafe = 1000;
}
}
failSafe++;
if (failSafe > 100) {
print("Error: infinite parsing loop at " + link);
}
//keep replacing until there are no matches
link = txt.match(/\[\[([\s\S]*?)\]\]/);
}
//2-
//parse the macros to narrativize the current dynamic state (if any)
var macro = txt.match(/{([\s\S]*?)}/);
failSafe = 0;
while (macro != null && failSafe < 1000) {
failSafe++;
//found link
if (macro != null) {
var m = macro[1].split("|");
var html = "";
//remove whitespaces
m[0] = m[0].replace(/^\s+|\s+$/g, "");
switch (m[0]) {
//get all players on a particular state and narrativize them
case "passagePlayers":
if (GAME.PASSAGES[m[1]] != null) {
//syntax
//{passagePlayers|passageId|Output if no player found|Output if one player found|Output if multiple found}
if (m.length == 5) {
var playersInPassage = getPlayersByPassage(m[1], player.id);
//names are linked only if we are talking about the same room
var noLinks = true;
//there is a room associated
if (GAME.PASSAGES[m[1]] != null) {
if (GAME.PASSAGES[m[1]].room != null)
noLinks = (GAME.PASSAGES[m[1]].room != player.room);
}
//print("Found " + playersInState.length + " doing " + m[1]);
if (playersInPassage.length == 0)
html = m[2]; //nobody is here
if (playersInPassage.length == 1)
html = adapt(m[3], playersInPassage, noLinks);
if (playersInPassage.length > 1)
html = adapt(m[4], playersInPassage, noLinks);
}
else {
print("Error in macro: " + macro[0]);
}
} else
print("Warning: no passage called " + m[1]);
break;
//estimates the number of people in another room and narrativizes it, mapping the number to the available options
//{roomPlayers|roomId|output for empty|output for one|output for more than one}
case "roomPlayers":
if (m.length == 5) {
//names are linked only if we are talking about the same room
var noLinks = (player.room != m[1]);
var roomPlayers = getRoomPlayers(m[1], player.id);
///print("Found " + player.room + " vs " + m[1]);
if (roomPlayers.length == 0)
html = m[2]; //nobody is here
else if (roomPlayers.length == 1)
html = adapt(m[3], roomPlayers, noLinks); //another person is here
else
html = adapt(m[4], roomPlayers, noLinks);
}
else {
print("Error in macro: " + macro[0]);
}
break;
case "back":
var linkText = GAME.TEXT.goBack;
if (m.length >= 2) {
linkText = m[1];
}
html = "<a class='passageLink' href='#' onclick='requestPassage(\"" + player.previousPassage + "\"); return false; '>" + linkText + "</a>";
break;
//outputs string if the expression is true, variables need to be player properties or prefixed with GLOBAL_ if global
//{playerCondition|expression|output if true|output if false (optional)}
//{playerCondition | GLOBAL_test+example>10 | Yes it is greater than 10| no it isn't bigger than 10}
case "playerCondition":
if (m.length >= 3) {
//get the expression
var expr = Parser.parse(m[1]);
//get the variable names referenced in it
var variables = expr.variables();
//ugly ass way to read global variables
//save them into an object
var prop = {}
//get the corresponding properties of the player
for (var i = 0; i < variables.length; i++) {
if (variables[i].substr(0, "GLOBAL_".length) == "GLOBAL_") {
var name = variables[i].substr("GLOBAL_".length);
//fuck yeah javascript create a property in player why not
player[variables[i]] = GAME.GLOBAL[name];
}
}
try {
if (expr.evaluate(player))
html = m[2];
else if (m[3] != null)
html = m[3];
else
html = "";
}
catch (e) {
print("Syntax error in expression " + m[1]);
html = ""
}
}
else
print("Error on playerCondition " + m.join("|") + " wrong number of parameters");
break;
//performs an expression using player variables. Returns nothing
//It can change player variables but not global ones, it can read global variables with global_ prefix on variable name
//{playerExpression|example=GLOBAL_test+100}
case "playerExpression":
if (m.length == 2) {
//get the expression
var expr = Parser.parse(m[1]);
//get the variable names referenced in it
var variables = expr.variables();
//ugly ass way to read global variables
//save them into an object
var prop = {}
//get the corresponding properties of the player
for (var i = 0; i < variables.length; i++) {
if (variables[i].substr(0, "GLOBAL_".length) == "GLOBAL_") {
var name = variables[i].substr("GLOBAL_".length);
//fuck yeah javascript create a property in player why not
player[variables[i]] = GAME.GLOBAL[name];
}
}
try {
html = expr.evaluate(player);
html = "";
}
catch (e) {
print("Syntax error in expression " + m[1]);
html = ""
}
}
else
print("Error on playerExpression " + m.join("|") + " wrong number of parameters");
break;