-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1476 lines (1310 loc) · 53.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
/* NODE JS MODULES */
var fs = require('fs'),
ejs = require('ejs'),
express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
nconf = require('nconf'),
mysql = require('mysql'),
app = express(),
http = require('http'),
shortId = require('shortid');
/* ROUTES */
var general = require('./routes/general.js'),
character = require('./routes/character.js'),
adventure = require('./routes/adventure.js'),
userContent = require('./routes/userContent.js');
/* CONFIGURATIONS */
nconf.argv()
.env()
.file({ file: nconf.get('config') || 'config.json' });
/* CREATE HTTP SERVER */
var httpServer = http.createServer(app).listen(nconf.get('httpPort'));
console.log('Http listen on port '+nconf.get('httpPort'));
/* WEB SOCKETS - SOCKET.IO */
var io = require('socket.io')(httpServer);
/* APP CONFIGURATIONS */
app.engine('html', ejs.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname+'/public');
app.use(express.static(__dirname+'/public'));
app.use(bodyParser.urlencoded({extended:true, limit:'5mb'}));
app.use(cookieParser());
/* FILE PATHS */
app.get('*.css', function(req, res){
var filename = req.path.slice(req.path.lastIndexOf("/"));
res.sendFile(__dirname+'/public/css/'+filename);
});
app.get('*.js', function(req, res){
var filename = req.path.slice(req.path.lastIndexOf("/"));
res.sendFile(__dirname+'/public/js/'+filename);
});
app.get('*.png', function(req, res){
var filename = req.path.slice(req.path.lastIndexOf("/"));
res.sendFile(__dirname+'/public/'+filename);
});
/* CONNECT TO MYSQL DATABASE */
var connection = mysql.createConnection(nconf.get('connection'));
connection.connect(function(err){
if(err){
console.log('could not connect to mysql database');
}
});
/* SESSIONS */
var MemoryStore = session.MemoryStore,
sessionStore = new MemoryStore();
app.use(session({
secret:nconf.get('sessionSecret'),
store: sessionStore,
key: 'sessionID',
saveUninitialized: false,
resave: false
}));
/* GAME ROOMS */
// initalize var to remember conntected users in rooms
// gamemasters in rooms are saved with username, socket id and connection status
// players in rooms are saved with username, user id, session id, socket id, connection status, readyForPlay status, charactername and character id
// adventureStatus - 0=connecting - 1=prepare start scene and characters - 2=in game
// startLevel defines the startLevel for the player characters
var rooms = {};
/* CLEAN UP */
// clean up sessions
var sessionCleanup = function() {
sessionStore.all(function(err, sessions){
for(var i=sessions.length-1; i>=0; i--){
sessionStore.get(sessions[i], function(){});
}
});
}
var sessionCleanUpInterval = setInterval(sessionCleanup, 600000);
// cleanup rooms
var roomCleanup = function() {
var sessionWithKey, sessionsToGo;
// get all room keys
var roomKeys = Object.keys(rooms);
// get all sessions
sessionStore.all(function(err, sessions){
// check if there is at least one session for each room key
for(var i=0; i<roomKeys.length; i++){
sessionWithKey = false;
sessionsToGo = Object.keys(sessions).length;
// go through all sessions to compare the session rooms with the room key
for(var sid in sessions){
compareRoomKeys(sid, roomKeys[i], function (result){
if(result) sessionWithKey = true;
// check if this was the last session for this key
if(--sessionsToGo === 0){
// delete room if no session with room key was found
if(!sessionWithKey) delete rooms[roomKeys[i]];
}
});
}
}
});
}
function compareRoomKeys (sid, roomKey, callback){
getSessionRoomId(sid, roomKey, function (roomID, key){
// compare room key with session room key
if(roomID === key) return callback(true);
return callback(false);
});
}
function getSessionRoomId (sid, key, callback){
// get room id from session
sessionStore.get(sid, function (error, session){
return callback(session.roomID, key);
});
}
// clean up every 5 minutes = 300 000 milliseconds
var roomCleanUpInterval = setInterval(roomCleanup, 300000);
/* -------------------------------- ROUTING -------------------------------- */
/* INDEX */
app.get('/', function (req, res) { sendIndexPage(req, res, false, false); });
/* ERRORS */
app.get('/error', function (req, res) { sendErrorPage(res, 'Not found'); });
/* REGISTRATION, LOGIN AND LOGOUT */
app.post('/registrate', function (req, res){ registrate(req, res); });
app.post('/login', function (req, res){ login(req, res); });
app.get('/logout', function (req, res){ logout(req, res); });
/* GET DATA FROM DATABASE */
app.post('/selectFromDB', function (req, res){ if(req.session.loggedin===true) selectAllFromTable(req, res); else res.send({error:'Not found'}); });
app.post('/selectContent', function (req, res){ if(req.session.loggedin===true) selectContent(req, res); else res.send({error:'Not found'}); });
/* MANAGE USER CONTENT */
app.get('/manage/:contentType', function (req, res){ if(req.session.loggedin===true) manageUserContent(req, res); else res.redirect('/'); });
app.get('/create/:contentType', function (req, res){ if(req.session.loggedin===true) createUserContent(req, res); else res.redirect('/'); });
app.get('/edit/:contentType/:contentID/:roomID', function (req, res){ if(req.session.loggedin===true) editUserContent(req, res); else res.redirect('/'); });
app.post('/save/:contentType', function (req, res){ if(req.session.loggedin===true) saveUserContent(req, res); else res.send({error:'Not found'}); });
app.put('/save/:contentType', function (req, res){ if(req.session.loggedin===true) updateUserContent(req, res); else res.send({error:'Not found'}); });
app.delete('/delete/:contentType', function (req, res){ if(req.session.loggedin===true) deleteUserContent(req, res); else res.send({error:'Not found'}); });
app.post('/draw/saveImage', function (req, res){ if(req.session.loggedin===true) saveDrawing(req, res); else res.send({error:'Not found'}); });
/* HOST AND JOIN GAME */
app.get('/host', function (req, res){ if(req.session.loggedin===true) connectHost(req, res); else res.redirect('/'); });
app.get('/join', function (req, res){ if(req.session.loggedin===true) connectJoin(req, res); else res.redirect('/'); });
app.get('/connect', function (req, res){ if(req.session.loggedin===true) connectingPage(req, res); else res.redirect('/'); });
app.post('/host', function (req, res){ if(req.session.loggedin===true) hostGame(req, res); });
app.get('/join/:roomID', function (req, res){ if(req.session.loggedin===true) joinGame(req, res); else res.redirect('/'); });
/* PREPARE GAME AND INTRODUCE USERS */
app.get('/prepare/:roomID', function (req, res){ if(req.session.loggedin===true) introduction(req, res); else res.redirect('/'); });
app.post('/prepare/:roomID', function (req, res){ if(req.session.loggedin===true) prepareCharacter(req, res); else res.send({error:'Not found'}); });
app.post('/getReady', function (req, res){ if(req.session.loggedin===true) getReady(req, res); else res.send({error:'Not found'}); });
app.post('/saveGame', function (req, res){ if(req.session.loggedin===true) saveGame(req, res); else res.send({error:'Not found'}); });
/* START THE ADVENTURE */
app.get('/play/:roomID/:scene', function (req, res){ if(req.session.loggedin===true) adventureGM(req, res); else res.redirect('/'); });
app.get('/play/:roomID', function (req, res){ if(req.session.loggedin===true) adventureP(req, res); else res.redirect('/'); });
/* CLOSE THE ADVENTURE */
app.get('/close/:roomID', function (req, res){ if(req.session.loggedin===true) closeAdventure(req, res); else res.redirect('/'); });
/* RETURN TO THE ADVENTURE */
app.get('/returnTo/:roomID', function (req, res){ if(req.session.loggedin===true) returnToAdventure(req, res); else res.redirect('/'); });
/* IN GAME */
app.post('/nextScene', function (req, res){ if(req.session.loggedin===true) nextScene(req, res); else res.send({error:'Not found'}); });
app.put('/saveInventory', function (req, res){ if(req.session.loggedin===true) saveInventory(req, res); else res.send({error:'Not found'}); });
app.post('/selectPlayerContent', function (req, res){ if(req.session.loggedin===true) selectPlayerContent(req, res); else res.send({error:'Not found'}); });
app.put('/saveEnemies', function (req, res){ if(req.session.loggedin===true) saveEnemies(req, res); else res.send({error:'Not found'}); });
app.delete('/deleteEnemies', function (req, res){ if(req.session.loggedin===true) deleteEnemies(req, res); else res.send({error:'Not found'}); });
app.post('/selectDices', function (req, res){ if(req.session.loggedin===true) selectDices(req, res); else res.send({error:'Not found'}); });
app.post('/saveCharacterInfo', function (req, res){ if(req.session.loggedin===true) updateCharacterInfo(req, res); else res.send({error:'Not found'}); });
app.post('/toggleTutorial', function (req, res){ if(req.session.loggedin===true) toggleTutorial(req, res); else res.send({error:'Not found'}); });
/* SOCKET CONNECTIONS */
io.on('connection', function (socket){ socketConnections(socket); });
/* ------------------------------- FUNCTIONS ------------------------------- */
/* BASIC ERROR PAGE */
var sendErrorPage = function (res, err){
// render error page, if an error occured
console.log('ERROR PAGE - res: '+res+' err: '+err);
res.sendFile(__dirname+'/public/error.html');
};
/* INDEX PAGE */
var sendIndexPage = function (req, res, regiError, loginError){
console.log('User with IP '+req.connection.remoteAddress+' connected.');
if(req.session.loggedin!==true){
res.render(__dirname+'/index.html', {
registrate: regiError,
login: loginError,
userdata: {username:req.body.username, email:req.body.email}
});
}
else sendMainPage(req, res, req.session.username, req.session.userID);
};
/* MAIN PAGE */
var sendMainPage = function (req, res, username, userID){
console.log('SERVER - main page user '+userID+' '+username);
var userRoomID = null;
// check if there is still a game running but the room does not exist anymore or user is player
if(req.session.currentGame){
if(!rooms[req.session.roomID] || req.session.role === 'player'){
// delete current game variables
req.session.currentGame = null;
req.session.roomID = null;
req.session.role = null;
if(req.session.role === 'player'){
req.session.characterID = null;
req.session.ready = false;
}
}
else{
// remember room id of current game for gamemaster to reconnect
userRoomID = req.session.roomID;
}
}
// select preview of user created characters, scenes, enemies and items from database and send back to user
userContent.selectPreviewForAll(userID, function (err, response){
if(err) return sendErrorPage(res, err);
if(response) {
res.render(__dirname+'/public/main.html', {
username: username,
characters: response.characters,
scenes: response.scenes,
enemies: response.enemies,
items: response.items,
roomID: userRoomID
});
}
});
};
/* REGISTRATION, LOGIN AND LOGOUT */
var registrate = function (req, res){
var username = req.body.username,
email = req.body.email,
password = req.body.password;
// save new user account in database
general.registrate(req, username, email, password, function (err, response){
if(err==='409') return sendIndexPage(req, res, 'Der Benutzername existiert bereits. Bitte verwende einen anderen Namen.', false);
if(err) return sendErrorPage(res, err);
if(response) res.redirect('/');
});
};
var login = function (req, res){
var username = req.body.username,
password = req.body.password;
// try to login user with entered username and password
general.login(req, username, password, function (err, response){
if(err) return sendIndexPage(req, res, false, 'Der Benutzername oder das Passwort waren falsch.');
if(response) res.redirect('/');
});
};
var logout = function (req, res){
// logout the user and show index page
general.logout(req, function (err, response){
if(err) return sendErrorPage(res, err);
res.redirect('/');
});
};
/* GET DATA FROM DATABASE */
var selectAllFromTable = function (req, res){
// select all data from database table and return the selected json data to sender
var table = req.body.table;
general.selectAllFromTable(table, function (err, response){
if(err) return sendErrorPage(res, err);
res.status(200).json({data:response});
});
};
var selectContent = function (req, res){
// get all user ids from group
var userIDs = [req.session.userID];
for(var i=0; i<rooms[req.session.roomID].players.length; i++){
userIDs.push(rooms[req.session.roomID].players[i].userID);
}
// select all data from database table and return the selected json data to sender
adventure.selectContent(req.body.table, req.body.userTable, req.body.categoryTable, userIDs, function (err, response){
if(err) return sendErrorPage(res, err);
res.status(200).json(response);
});
};
var selectPlayerContent = function (req, res){
userContent.selectById(req.session.characterID, req.session.userID, 'characters', function (err, response){
// send character sheet data to player
res.status(200).json({
err: err,
character: {
attributeValues: response.attributeValues[0],
skillValues: response.skillValues[0],
advanValues: response.advanValues[0],
disadvanValues: response.disadvanValues[0]
}
});
});
};
/* MANAGE USER CONTENT */
var manageUserContent = function (req, res){
// select preview of content for user
userContent.selectByUser(req.session.userID, req.params.contentType, function (err, response){
if(err) return sendErrorPage(res, err);
general.selectCategories(req.params.contentType, function (err2, categories){
if(err2) return sendErrorPage(res, err2);
res.render(__dirname+'/public/manageContent.html', {
username: req.session.username,
contentType: req.params.contentType,
categories: categories,
response: response.rows
});
});
});
};
var createUserContent = function (req, res){
// get character sheet parameters for creating a character
var attributes, skills, characteristics;
if(req.params.contentType==='characters'){
var jsonData = require(__dirname+'/json/characterSheet.json');
attributes = jsonData.attributes;
skills = jsonData.skills;
characteristics = jsonData.characteristics;
}
// show empty character sheet, item-, scene- or enemie-card
general.selectCategories(req.params.contentType, function (err, categories){
if(err) return sendErrorPage(res, err);
var colorsData = require(__dirname+'/json/drawingColors.json');
res.render(__dirname+'/public/contentEditor.html', {
username: req.session.username,
newContent: true,
contentType: req.params.contentType,
contentID: false,
response: false,
startLevel: false,
categories: categories,
attributes: attributes,
skills: skills,
characteristics: characteristics,
colors: colorsData.colors,
ingame: false
});
});
};
var editUserContent = function (req, res){
// select user content
userContent.selectById(req.params.contentID, req.session.userID, req.params.contentType, function (err, response){
if(err) return sendErrorPage(res, err);
if(response.rows.length<=0) return sendErrorPage(res, 'access denied');
var colorsData = require(__dirname+'/json/drawingColors.json');
var roomID = false;
if(req.params.roomID != '0') roomID = req.params.roomID;
// show character sheet of selected user character
if(req.params.contentType==='characters'){
var jsonData = require(__dirname+'/json/characterSheet.json');
res.render(__dirname+'/public/contentEditor.html', {
username: req.session.username,
newContent: false,
contentType: req.params.contentType,
contentID: req.params.contentID,
response: {
attributeValues: response.attributeValues[0],
skillValues: response.skillValues[0],
advanValues: response.advanValues[0],
disadvanValues: response.disadvanValues[0],
informations: response.rows[0]
},
startLevel: response.rows[0].startLevel,
attributes: jsonData.attributes,
skills: jsonData.skills,
characteristics: jsonData.characteristics,
colors: colorsData.colors,
ingame: roomID
});
}
// show selected item-, scene- or enemie-card
else{
res.render(__dirname+'/public/contentEditor.html', {
username: req.session.username,
newContent: false,
contentType: req.params.contentType,
contentID: req.params.contentID,
response: response.rows[0],
categories: response.categories,
colors: colorsData.colors,
ingame: roomID
});
}
});
};
var saveUserContent = function (req, res){
// check if content is character sheet
if(req.params.contentType === 'characters') return saveCharacter(req, res);
// save new item-, scene- or enemie-card
userContent.insert(req.session.userID, req.params.contentType, req.body.data, function (err, response){
res.status(200).json({ err:err, savedContentID:response.insertId });
});
};
var updateUserContent = function (req, res){
// check if content is character sheet
if(req.params.contentType === 'characters') return updateCharacter(req, res);
// save changes in item-, scene- or enemie-card
userContent.update(req.body.contentID, req.session.userID, req.params.contentType, req.body.data, function (err, response){
res.status(200).json({ err:err });
});
};
var deleteUserContent = function (req, res){
// check if content is character sheet
if(req.params.contentType === 'characters') return deleteCharacter(req, res);
// delete selected item, scene or enemie
userContent.delete(req.body.contentID, req.session.userID, req.params.contentType, function (err, response){
res.status(200).json({ err:err });
});
};
/* USER CHARACTERS */
var saveCharacter = function (req, res){
console.log('SERVER - character should be saved');
character.insert(req.session.userID, req.body.data, function (err, response){
// check if character creation was part of an adventure
if(!err && req.session.roomID){
//save status of completed character creation and character id in session
req.session.ready = true;
req.session.characterID = response.insertId;
}
res.status(200).json({ err:err, savedCharacterID:response.insertId });
});
};
var updateCharacter = function (req, res){
console.log('SERVER - character should be updated');
character.updateComplete(req.body.contentID, req.session.userID, req.body.data, function (err){
res.status(200).json({ err:err });
});
};
var updateCharacterInfo = function (req, res){
console.log('SERVER - character informations should be updated');
character.updateOptions(req.body.options, function (err){
res.status(200).json({ err:err });
});
};
var deleteCharacter = function (req, res){
console.log('SERVER - character should be deleted');
character.delete(req.body.contentID, req.session.userID, function (err){
res.status(200).json({ err:err });
});
};
/* SAVE USER IMAGES */
var saveDrawing = function (req, res) {
// get image data
var imgData = req.body.imageData;
var data = imgData.replace(/^data:image\/\w+;base64,/, "");
// get name of directory where user created images are saved
var dirName = 'u'+('00000000000'+req.session.userID).slice(-11);
// create directory if it doesn't already exist
makeDirectory(dirName, function (err) { if(err){ console.log(err); } });
// check if imagepath is already set
var imageName;
if(req.body.imagepath){
// get existing image name
var filename = req.body.imagepath.split('/')[3];
imageName = filename.replace('.png', '');
// save image file in directory
saveImageInDirectory(dirName, imageName, data, function (err) {
if(err){
console.log('ERROR saveImage - saveImageInDirectory');
console.log(err);
res.status(200).json({ err:err });
}
else{
// save image data in database
console.log('saveImage - image successfully saved');
res.status(200).json({ err:false, imagepath:'/uploads/'+dirName+'/'+imageName+'.png' });
}
});
}
else{
// create unique name for image
imageName = 'img_'+Date.now();
// try to open image file
fs.exists(__dirname+'/public/uploads/'+dirName+'/'+imageName+'.png', function (err) {
// check if image file exits
if(!err) {
// save image file in directory
saveImageInDirectory(dirName, imageName, data, function (err) {
if(err){
console.log('ERROR saveImage - saveImageInDirectory');
console.log(err);
}
else{
// save image data in database
console.log('saveImage - image successfully saved');
res.status(200).json({ err:false, imagepath:'/uploads/'+dirName+'/'+imageName+'.png' });
}
});
}
else {
console.log('ERROR saveImage - image file already exists');
res.status(200).json({ err:'Es existiert bereits eine Datei mir Namen '+imageName+'.'});
}
});
}
};
function makeDirectory (dirName, callback) {
fs.mkdir(__dirname+'/public/uploads/'+dirName, function (err) {
if(err){
if(err.code == 'EEXIST'){
// folder already exists - ignore error
callback(false);
}
else callback(err);
}
else callback(false);
});
}
function saveImageInDirectory (dirName, imageName, data, callback) {
var buf = new Buffer(data, 'base64');
fs.writeFile(__dirname+'/public/uploads/'+dirName+'/'+imageName+'.png', buf, function (err){
callback(err);
});
}
/* HOST AND JOIN GAME */
var connectHost = function (req, res){
// remember user as gamemaster in session
setRoleTo(req, 'gamemaster', function (){
// redirect to connecting page for having the same url for host and join
res.redirect('/connect');
});
};
var connectJoin = function (req, res){
// remember user as player in session
setRoleTo(req, 'player', function (){
// redirect to connecting page for having the same url for host and join
res.redirect('/connect');
});
};
var setRoleTo = function (req, newRole, callback){
req.session.role = newRole;
callback();
};
var connectingPage = function (req, res){
// check if user wants to host (gamemaster) or join (player)
if(req.session.role === 'gamemaster'){
console.log('SERVER - gamemaster in connection room');
// select saved games for gamemaster to load
general.selectSavegames(req.session.userID, function (err, response){
if(err) return sendErrorPage(res, err);
if(response) {
// render connecting page for gamemaster
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
// check if room was already created
if(req.session.roomID) res.render(__dirname+'/public/connectGM.html', {username:req.session.username, savegames:response, players:rooms[req.session.roomID].players, roomID:req.session.roomID});
else res.render(__dirname+'/public/connectGM.html', {username:req.session.username, savegames:response, players:false, roomID:false});
}
});
}
else if(req.session.role === 'player'){
console.log('SERVER - player in connection room');
// render connecting page for player
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
// check if user already joined
console.log(req.session.roomID);
if(req.session.roomID) res.render(__dirname+'/public/connectP.html', {username:req.session.username, roomID:req.session.roomID, sessionID:req.session.id, userID:req.session.userID});
else res.render(__dirname+'/public/connectP.html', {username:req.session.username, roomID:null, sessionID:null, userID:null});
}
else{
// render main page, if user didn't choose a role (gamemaster or player)
res.redirect('/');
}
};
var hostGame = function (req, res){
console.log('SERVER - gamemaster host game');
// check for existing session room
if(typeof req.session.roomID === 'undefined' || !req.session.roomID){
// generate new room id
var roomID = shortId.generate();
// check if the generated room id already exists
while(rooms[roomID]){
// if the generated room id already exists generate a new one until it is unique
roomID = shortId.generate();
}
// save new unique room id in session
req.session.roomID = roomID;
// create a new room for the adventure
rooms[roomID] = { adventureStatus:0 };
console.log('room '+roomID+' generated');
}
// check if gamemaster wants to start a new game or load a saved one
if(req.body.savegame){
console.log('SERVER - gamemaster load savegame '+req.body.savegame);
// remember game in session and room
req.session.currentGame = req.body.savegame;
rooms[req.session.roomID].currentGame = req.body.savegame;
// load savegame
general.loadGameCharacters(req.body.savegame, function (err, response){
// send room id and savegame characters back to host
console.log('SERVER - in savegame allowed characters...');
res.status(200).json({err:err, roomID:req.session.roomID, characterIDs:response});
});
}
else{
console.log('SERVER - no savegame selected, start new one');
// send room id back to host
res.status(200).json({err:null, roomID:req.session.roomID, characterIDs:false});
}
};
var joinGame = function (req, res){
console.log('SERVER - player join game '+req.params.roomID);
// get room id
var roomID = req.params.roomID;
// check if room id currently exists
if(rooms[roomID]){
// save room id and role in session
req.session.roomID = roomID;
req.session.role = 'player';
// let the user join the room
res.redirect('/connect');
}
else{
// send back an error, if the room id doesn't currently exist
return sendErrorPage(res, 'Es wurde kein Spiel mit dem Code '+roomID+' gefunden.');
}
};
/* PREPARE GAME AND INTRODUCE USERS */
var introduction = function (req, res){
// render introduction file for gamemaster
if(req.session.role === 'gamemaster'){
console.log('SERVER - introduce gamemaster with scenes selection');
// select all scenes the gamemaster can choose from as start scene
adventure.selectScenesPreview(req.session.userID, function (err, response){
if(err) return sendErrorPage(res, err);
general.getTutorialValue(req.session.userID, function (err, tutorialMode){
if(err) return sendErrorPage(res, err);
res.render(__dirname+'/public/introGM.html', {
username: req.session.username,
roomID: req.params.roomID,
scenesData: response,
tutorial: tutorialMode
});
});
});
}
// render introduction file for player
else if(req.session.role === 'player'){
console.log('SERVER - introduce player with character sheet');
var jsonData = require(__dirname+'/json/characterSheet.json');
// select predefined characters and prepared user characters
console.log(rooms[req.params.roomID].startLevel);
character.selectCharacterList(rooms[req.params.roomID].startLevel, req.session.userID, function (err, response){
if(err) return sendErrorPage(res, err);
if(response) {
res.render(__dirname+'/public/introP.html', {
username: req.session.username,
roomID: req.params.roomID,
sessionID: req.session.id,
ready: req.session.ready,
contentType: 'characters',
response: false,
newContent: true,
startLevel: rooms[req.params.roomID].startLevel,
characters: response.characters,
userCharacters: response.userCharacters,
attributes: jsonData.attributes,
skills: jsonData.skills,
characteristics: jsonData.characteristics
});
}
});
}
// error handling if user role is not defined
else res.redirect('/');
};
var prepareCharacter = function (req, res){
console.log('SERVER - load character data');
// check if character is user created or not
var cid, table;
if(req.body.characterID.indexOf('u') > -1) {
cid = req.body.characterID.split('u')[1];
table = 'UserCharacters';
}
else{
cid = req.body.characterID;
table = 'Characters';
}
// select character sheet data of predefined character
character.selectCharactersets(cid, table, function (err, response){
if(err) return sendErrorPage(res, err);
if(response) res.status(200).json(response);
});
};
var getReady = function (req, res){
console.log('SERVER - loaded user character is ready');
req.session.ready = true;
res.status(200).json(true);
};
var saveGame = function (req, res){
console.log('SERVER - save new game with characters');
// get characters of game
var characters = [];
for(var i=0; i<rooms[req.body.roomID].players.length; i++) {
characters.push(rooms[req.body.roomID].players[i].characterID);
}
// create new savegame
general.saveGame(req.body.gamename, characters, req.session.userID, function (err, savegameID){
if(err) res.status(200).json({ err:err });
// remember currently running game in session and room
req.session.currentGame = savegameID;
rooms[req.body.roomID].currentGame = savegameID;
res.status(200).json({ err:false });
});
};
/* START THE ADVENTURE */
var adventureGM = function (req, res){
if(req.session.role === 'gamemaster'){
console.log('SERVER - gamemaster is in game');
// load savegame start scenes
general.loadGameContent(req.session.currentGame, function (err, savegame){
if(err) return sendErrorPage(res, err);
general.getTutorialValue(req.session.userID, function (err2, tutorialMode){
if(err2) return sendErrorPage(res, err2);
// check if start scene was already set
console.log('SERVER - savegame sceneHistory');
console.log(savegame.sceneHistory);
if(savegame.sceneHistory){
console.log('SERVER - load sceneHistory');
adventure.selectStartScenes(savegame.sceneHistory, function (err3, scenes){
if(err3) return sendErrorPage(res, err3);
// select informations about players characters
character.selectOptions(rooms[req.session.roomID].players, function (err4, playerOptions){
if(err4) return sendErrorPage(res, err4);
// check if game was saved in battle
if(savegame.currentEnemies){
console.log('SERVER - load gamemaster game with start scenes and enemies');
// prepare enemies data for database
var currentEnemies = savegame.currentEnemies.replace(new RegExp('},{', 'g'), '}//SPLIT//{');
var enemiesData = currentEnemies.split('//SPLIT//');
for(var i=0; i<enemiesData.length; i++){
enemiesData[i] = JSON.parse(enemiesData[i]);
}
// get enemies from database
adventure.selectContents('Enemies', enemiesData, function (err5, enemiesContent){
if(err5) return sendErrorPage(res, err5);
// render adventure file for gamemaster with enemies
res.render(__dirname+'/public/adventureGM.html', {
username: req.session.username,
roomID: req.params.roomID,
scenes: scenes,
players: rooms[req.session.roomID].players,
playerOptions: playerOptions,
inBattle: true,
enemies: {content:enemiesContent, data:enemiesData},
tutorial: tutorialMode
});
});
}
else{
console.log('SERVER - load gamemaster game start scenes');
// render adventure file for gamemaster without enemies
res.render(__dirname+'/public/adventureGM.html', {
username: req.session.username,
roomID: req.params.roomID,
scenes: scenes,
players: rooms[req.session.roomID].players,
playerOptions: playerOptions,
inBattle: false,
tutorial: tutorialMode
});
}
});
});
}
else if(req.params.scene){
console.log('SERVER - save start scene in new game');
// update savegame with start scenes
general.updateGameScenes(req.params.scene, req.session.currentGame, req.session.userID, function (err3, savegameID){
if(err3) return sendErrorPage(res, err3);
// select scene from database
adventure.selectStartScenes(req.params.scene, function (err4, scenes){
if(err4) return sendErrorPage(res, err4);
// select informations about players characters
character.selectOptions(rooms[req.params.roomID].players, function (err5, playerOptions){
if(err5) return sendErrorPage(res, err5);
//render adventure file for gamemaster
res.render(__dirname+'/public/adventureGM.html', {
username: req.session.username,
roomID: req.params.roomID,
scenes: scenes,
players: rooms[req.params.roomID].players,
playerOptions: playerOptions,
inBattle: false,
tutorial: tutorialMode
});
});
});
});
}
else return sendErrorPage(res, 'No scenes for game found.');
});
});
}
// if user is no gamemaster
else if(req.session.role === 'player') res.redirect('/play/'+req.params.roomID);
else res.redirect('/');
};
var adventureP = function (req, res){
// select character data for player
if(req.session.role === 'player'){
// save game id in player session if not done yet
if(!req.session.currentGame){
req.session.currentGame = rooms[req.session.roomID].currentGame;
}
// get character id for player if it is not set yet
if(!req.session.characterID){
var characterID;
if(typeof rooms[req.session.roomID] !== 'undefined'){
for (var i=0; i<rooms[req.session.roomID].players.length; i++) {
if(rooms[req.session.roomID].players[i].name.toLowerCase() === req.session.username.toLowerCase()){
characterID = rooms[req.session.roomID].players[i].characterID;
}
}
}
if(!characterID) return sendErrorPage(res, 'No character for player found.');
req.session.characterID = characterID;
req.session.ready = true;
}
// get character and inventory data for plyer
userContent.selectCharacterInformations(req.session.characterID, req.session.userID, function (err, response){
if(err) return sendErrorPage(res, err);
general.getTutorialValue(req.session.userID, function (err2, tutorialMode){
if(err2) return sendErrorPage(res, err2);
character.getInventory(req.session.characterID, req.session.userID, function (err3, inventory){
if(err3) return sendErrorPage(res, err3);
// load savegame
general.loadGameContent(req.session.currentGame, function (err4, savegame){
if(err4) return sendErrorPage(res, err4);
console.log('SERVER - savegame for player loadad');
var jsonData = require(__dirname+'/json/characterSheet.json');
// check if game was saved in battle
if(savegame.currentEnemies){
console.log('SERVER - load player game with enemies');
// prepare enemies data for database
var currentEnemies = savegame.currentEnemies.replace(new RegExp('},{', 'g'), '}//SPLIT//{');
var enemiesData = currentEnemies.split('//SPLIT//');
for(var i=0; i<enemiesData.length; i++){
enemiesData[i] = JSON.parse(enemiesData[i]);
}
// get enemies from database
adventure.selectContents('Enemies', enemiesData, function (err3, enemiesContent){
// render adventure file for player with enemies
res.render(__dirname+'/public/adventureP.html', {
username: req.session.username,
roomID: req.params.roomID,
sessionID: req.session.id,
inventory: inventory,
inventoryOrder: response.rows[0].inventory.split(','),
response: { informations: response.rows[0] },
inBattle: true,
enemies: {content:enemiesContent, data:enemiesData},
startLevel: false,
attributes: jsonData.attributes,
skills: jsonData.skills,
characteristics: jsonData.characteristics,
tutorial: tutorialMode
});
});
}
else{
console.log('SERVER - render adventure file for player');
// render adventure file for player without enemies
res.render(__dirname+'/public/adventureP.html', {
username: req.session.username,
roomID: req.params.roomID,
sessionID: req.session.id,
inventory: inventory,
inventoryOrder: response.rows[0].inventory.split(','),
response: { informations: response.rows[0] },
inBattle: false,
startLevel: false,
attributes: jsonData.attributes,
skills: jsonData.skills,
characteristics: jsonData.characteristics,
tutorial: tutorialMode
});
}
});
});
});
});
}
// if user is no player
else if(req.session.role === 'gamemaster') adventureGM(req, res);
else res.redirect('/');
};
/* CLOSE THE ADVENTURE */
var closeAdventure = function (req, res){
console.log('SERVER - user quit game');
// forget current game variables
if(req.session.role === 'player'){
req.session.characterID = null;
req.session.ready = false;
}
req.session.roomID = null;
req.session.currentGame = null;
req.session.role = null;
res.redirect('/');
};