-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
1184 lines (1082 loc) · 39.7 KB
/
server.js
File metadata and controls
1184 lines (1082 loc) · 39.7 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
const express = require("express");
const cors = require("cors");
const multer = require("multer");
const fs = require("fs");
const cookieParser = require("cookie-parser");
const MongoClient = require("mongodb").MongoClient;
const app = express();
const cookie = require("cookie");
const http = require("http").createServer(app);
http.listen(4000, "localhost", () => {
console.log("Running on port 4000 , 0.0.0.0");
});
const io = require("socket.io").listen(http);
io.origins(['http://localhost:4000']);
const gameEngine = require(__dirname + "/game-logic/gameEngine.js");
const gameData = require(__dirname + "/game-logic/DATA.js");
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ PATHS ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
const upload = multer({ dest: __dirname + "/assets/" }); // Set file upload destination
const imagePath = "/assets/";
const url =
"mongodb+srv://admin:admin@samurai-murit.mongodb.net/test?retryWrites=true"; // URI for remote database!
app.use(cors())
app.use("/assets", express.static(__dirname + "/assets"));
app.use(cookieParser());
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ STORAGE ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
let usersCollection;
let sessionsCollection;
let lobbiesCollection;
let gamesCollection;
let chatsCollection;
let gameIdAssociation; // in database as collection "GameIdAssociation"
let newsCollection;
//Connection to DB, do not close!
(async function initDB() {
await MongoClient.connect(url, { useNewUrlParser: true }, (err, allDbs) => {
console.log(
"-----------------------Database Initialised-----------------------"
);
// Add option useNewUrlParser to get rid of console warning message
if (err) throw err;
finalProjectDB = allDbs.db("FinalProject-DB");
usersCollection = finalProjectDB.collection("Users");
sessionsCollection = finalProjectDB.collection("Sessions");
lobbiesCollection = finalProjectDB.collection("Lobbies");
chatsCollection = finalProjectDB.collection("Chats");
newsCollection = finalProjectDB.collection("News");
});
})();
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ GENERAL FUNCTIONS ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
//Generates random Id
const generateId = () => {
return "" + Math.floor(Math.random() * 100000000000);
};
const lobbyPurge = (username, newLobbyId) => {
try {
console.log("OLD LOBBY PURGE FOR: " + username);
lobbiesCollection.deleteMany({
$or: [{ playerOne: username }, { playerTwo: username }],
_id: { $not: { $eq: newLobbyId } }
});
} catch (e) {
console.log("ERROR IN LOBBY PURGE FOR: " + username);
console.log(e);
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ SIGNUP, LOGIN, LOGOUT & AUTOLOGIN ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ SIGNUP ************//
app.post("/signup", upload.none(), function (req, res) {
//Check user collection in remote database to see if username already exists
usersCollection
.find({ username: req.body.username })
.toArray((err, result) => {
if (result[0] !== undefined) {
// If database return any entry, user exists already!
console.log("DB: Be yourself! Try something original...");
res.send(JSON.stringify({ success: false }));
return;
}
const newUser = {
//userId: generateId(), use _id instead
username: req.body.username,
password: req.body.password,
country: req.body.country,
wins: 0,
losses: 0,
points: 0,
isAdmin: false,
currentLobby: "",
profilePic: "/assets/default-user.jpg",
status: "playing Super Chess II",
bio: "Super Chess II player",
army: gameData.defaultArmy,
joinedDate: req.body.joinedDate
};
usersCollection.insertOne(newUser, (err, result) => {
//Add new user to remote database
if (err) throw err;
console.log(
`DB: Successfully inserted user ${
req.body.username
} into Users collection`
);
const newSessionId = generateId();
sessionsCollection.insertOne(
{ sessionId: newSessionId, user: req.body.username },
(err, result) => {
if (err) throw err;
console.log("DB: Successfully added entry to Sessions collection");
res.cookie("sid", newSessionId);
res.send(
JSON.stringify({ success: true, username: req.body.username })
);
}
);
});
});
});
//************ LOGIN ************//
app.post("/login", upload.none(), function (req, res) {
const { username: enteredName, password: enteredPass } = req.body;
// Check remote users collection in db
usersCollection.find({ username: enteredName }).toArray((err, result) => {
console.log("DB: Retrieving expected password for user");
if (err) throw err;
if (result[0] === undefined) {
console.log("DB: User not found");
res.send(JSON.stringify({ success: false }));
return;
}
const expectedPass = result[0].password;
if (enteredPass !== expectedPass) {
// Check that password matches
console.log("Passwords did not match!");
res.send(JSON.stringify({ success: false }));
return;
}
const newSessionId = generateId(); // Generate random number for sid cookie
sessionsCollection.insertOne(
{ sessionId: newSessionId, user: enteredName },
(err, result) => {
if (err) throw err;
console.log("DB: Successfully added entry to Sessions collection");
}
);
console.log(`Logging in user ${enteredName}`);
res.cookie("sid", newSessionId); // Send back set-cookie and successful response
res.send(JSON.stringify({ success: true, username: enteredName }));
});
});
//************ LOGOUT ************//
app.get("/logout", upload.none(), function (req, res) {
console.log("Logging out...");
sessionsCollection.deleteOne(
{ sessionId: req.cookies.sid },
(err, result) => {
// Remove from remote database
if (err) throw err;
console.log("DB: Successfully removed entry from sessions collection!");
}
);
res.send(JSON.stringify({ success: true }));
});
//************ AUTOLOGIN ************//
app.get("/verify-cookie", function (req, res) {
if (sessionsCollection === undefined) {
return;
}
sessionsCollection
.find({ sessionId: req.cookies.sid })
.toArray((err, result) => {
if (err) throw err;
//result is an array, we must check it elements with [ ]
if (result[0] === undefined || result.length === 0) {
//MUST send back success: false is username is not defined
res.send(JSON.stringify({ success: false }));
return;
}
// console.log("Username found in db from sessionId: ", result[0].user)
res.send(JSON.stringify({ success: true, username: result[0].user }));
});
});
//***************************GET USER PROFILE*************************************8 */
app.post("/get-user-profile", upload.none(), function (req, res) {
if (req.body.username === undefined) {
res.send({ success: false });
}
if (usersCollection === undefined) {
res.send({ success: false });
}
let reqUsername = req.body.username;
usersCollection.find({ username: reqUsername }).toArray((err, result) => {
console.log("user profile lookup");
console.log(result);
let userProfile = {
username: result[0].username,
statusMessage: result[0].statusMessage,
bio: result[0].bio,
profilePic: result[0].profilePic
};
if (userProfile.profilePic === undefined) {
userProfile.profilePic = "/assets/default-user.png";
}
if (userProfile.statusMessage === undefined) {
userProfile.statusMessage = "";
}
if (userProfile.bio === undefined) {
userProfile.bio = "";
}
console.log("user profile lookup");
console.log(userProfile);
userProfile = JSON.stringify(userProfile);
res.send(userProfile);
});
});
//***************************CHANGE USER PROFILE**************************************/
app.post("/change-user-profile", upload.none(), function (req, res) {
console.log(req.cookies.sid);
if (req.cookies.sid === undefined) {
return { success: false };
}
let newInfo = req.body;
sessionsCollection
.find({ sessionId: req.cookies.sid })
.toArray((err, result) => {
console.log(result[0]);
usersCollection
.find({ username: result[0].user })
.toArray((err, result) => {
console.log(result[0]);
usersCollection.updateOne(
{ _id: result[0]._id },
{
$set: {
statusMessage: newInfo.statusMessage,
bio: newInfo.bio,
profilePic: newInfo.profilePic
}
},
(err, result) => {
if (err) throw err;
console.log(`DB: editing user information: ${"username"}`);
res.send(JSON.stringify({ success: true }));
}
);
});
});
});
app.get("/get-user-score", function (req, res) {
sessionsCollection
.find({ sessionId: req.cookies.sid })
.toArray((err, result) => {
if (err || result.length === 0) {
res.send(JSON.stringify({ wins: 0, losses: 0 }));
}
usersCollection
.find({ username: result[0].user })
.toArray((err, result) => {
console.log("Wins ", result[0].wins);
res.send(
JSON.stringify({ wins: result[0].wins, losses: result[0].losses })
);
});
});
});
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ NEWS AND NEWS POSTING ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
app.get("/get-news", upload.none(), (req, res) => {
newsCollection.find({}).toArray((err, result) => {
if (err) {
res.send(JSON.stringify({ success: false }));
return;
}
console.log("Getting news -> results: ", result);
res.send(JSON.stringify({ newsList: result, success: true }));
});
});
app.post("/add-news", upload.none(), (req, res) => {
let text = req.body.newsText;
if (
req.cookies.sid === undefined ||
text === undefined ||
text.trim() === ""
) {
res.send({ success: false, err: "not logged in" });
}
sessionsCollection
.find({ sessionId: req.cookies.sid })
.toArray((err, result) => {
if (err) {
res.send(JSON.stringify({ success: false }));
return;
}
usersCollection
.find({ username: result[0].user })
.toArray((err, result) => {
if (err) {
res.send(JSON.stringify({ success: false }));
return;
}
if (!result[0].isAdmin) {
res.send(JSON.stringify({ success: false }));
return;
}
let iso = new Date().toISOString();
let newPost = {
date: iso,
text
};
newsCollection.insertOne(newPost, (err, result) => {
if (err) {
res.send(JSON.stringify({ success: false }));
return;
}
console.log("Created new News post.");
res.send(JSON.stringify({ success: true }));
});
});
});
});
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ ARMY AND MAP EDITOR ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
app.get("/get-player-army", upload.none(), (req, res) => {
if (req.cookies.sid === undefined) {
res.send({ success: false, err: "not logged in" });
}
sessionsCollection
.find({ sessionId: req.cookies.sid })
.toArray((err, result) => {
if (!result[0]) {
res.send(JSON.stringify({ success: false }))
return
}
usersCollection
.find({ username: result[0].user })
.toArray((err, result) => {
res.send(JSON.stringify(result[0].army));
});
});
});
app.post("/set-army", upload.none(), (req, res) => {
if (req.cookies.sid === undefined) {
res.send({ success: false, err: "not logged in" });
}
let newArmy = req.body.armyString;
newArmy = newArmy;
if (typeof newArmy === "string") {
newArmy = newArmy.split("_");
if (newArmy.length === 3) {
newArmy = newArmy.map(row => {
return row.split(" ");
});
}
}
console.log(newArmy);
let setNewArmy = [];
for (let row = 0; row < 3; row++) {
let arrRow = [];
for (let col = 0; col < 8; col++) {
if (newArmy[row]) arrRow.push(newArmy[row][col]);
}
setNewArmy.push(arrRow);
}
console.log(setNewArmy);
sessionsCollection
.find({ sessionId: req.cookies.sid })
.toArray((err, result) => {
if (result !== undefined) {
usersCollection
.find({ username: result[0].user })
.toArray((err, result) => {
usersCollection.updateOne(
{ _id: result[0]._id },
{
$set: {
army: setNewArmy
}
},
(err, result) => {
if (err) throw err;
console.log(`DB: editing user information: ${"username"}`);
res.send(JSON.stringify({ success: true }));
}
);
});
}
});
});
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ LEADERBOARD & LOBBY RELATED ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ GET LEADERBOARD ************//
app.get("/get-leaderboard", upload.none(), function (req, res) {
console.log("Getting leaderboard...");
usersCollection
.find()
.sort({ wins: -1, losses: 1 })
.toArray((err, result) => {
if (err) throw err;
// console.log("Leaderboard:", result);
res.send(JSON.stringify(result));
});
});
//************ CREATE LOBBY ************//
app.post("/create-lobby", upload.none(), function (req, res) {
//Lobby to be inserted
let newLobbyId = generateId();
const newLobby = {
_id: newLobbyId,
playerOne: req.body.currentUser,
playerTwo: "",
readyPlayerOne: false,
readyPlayerTwo: false,
creationTime: new Date().toLocaleString()
};
lobbyPurge(req.body.currentUser, newLobbyId);
//Insert lobby into the database
lobbiesCollection.insertOne(newLobby, (err, result) => {
if (err) {
res.send(JSON.stringify({ success: false }));
throw err;
}
console.log(
`DB: Successfully added lobby for ${
newLobby.playerOne
} into lobby collection`
);
console.log(`New LobbyId: ${newLobbyId}`);
usersCollection
.find({ username: req.body.currentUser })
.toArray((err, result) => {
usersCollection.updateOne(
//bookmark
{ _id: result[0]._id },
{ $set: { currentLobby: newLobbyId } },
(err, result) => {
if (err) throw err;
console.log(`DB: Setting users currentLobby to: ${newLobbyId}`);
//res.send(JSON.stringify({ success: true }));
}
);
});
//We are now creating the lobby chat right after creating the lobby.
const newLobbyChat = {
_id: newLobbyId,
messageList: [],
creationTime: new Date().toLocaleString()
};
//Insert lobby chat into the database
chatsCollection.insertOne(newLobbyChat, (err, result) => {
if (err) {
res.send(JSON.stringify({ success: false }));
throw err;
}
console.log(
`DB: Successfully added lobby chat created by ${
req.body.currentUser
} into lobby chat collection`
);
console.log(
`The added chats ID, ${
newLobbyChat._id
}, is the same as the LobbyId, ${newLobbyId}.`
);
//The newLobby._id will also be used for the LobbyChat id
res.send(JSON.stringify({ success: true, lobbyId: newLobby._id }));
});
});
});
//************ GET LOBBIES ************//
app.get("/get-lobbies", upload.none(), function (req, res) {
if (lobbiesCollection === undefined) {
res.send(JSON.stringify({ success: false }));
return;
}
console.log("Getting lobbies...");
lobbiesCollection.find({}).toArray((err, result) => {
if (err) throw err;
// console.log("Lobbies:", result);
res.send(JSON.stringify(result));
});
});
//************ JOIN LOBBY ************//
app.post("/join-lobby", upload.none(), function (req, res) {
const { lobbyId, currentUser } = req.body;
lobbyPurge(currentUser, lobbyId);
console.log("Trying to join lobby with id ", lobbyId);
lobbiesCollection.find({ _id: lobbyId }).toArray((err, result) => {
if (result[0] === undefined) {
console.log("Error joining lobby!");
res.send(JSON.stringify({ success: false }));
return;
}
if (result[0].playerTwo !== "") {
console.log("No space in this lobby!");
res.send(JSON.stringify({ success: false }));
return;
}
lobbiesCollection.updateOne(
{ _id: lobbyId },
{ $set: { playerTwo: currentUser } },
(err, result) => {
if (err) throw err;
console.log(`DB: Adding user to lobbyId: ${lobbyId}`);
//res.send(JSON.stringify({ success: true }));
usersCollection
.find({ username: req.body.currentUser })
.toArray((err, result) => {
usersCollection.updateOne(
//bookmark
{ _id: result[0]._id },
{ $set: { currentLobby: lobbyId } },
(err, result) => {
if (err) throw err;
console.log(`DB: Setting users currentLobby to: ${lobbyId}`);
res.send(JSON.stringify({ success: true }));
}
);
});
}
);
refreshLobbyChat(lobbyId);
});
});
//************ USER READY ************//
app.post("/user-ready", upload.none(), function (req, res) {
const { lobbyId, currentUser } = req.body;
console.log(
`|Ready| button pressed by "${currentUser}" for lobby with id ${lobbyId}`
);
lobbiesCollection.find({ _id: lobbyId }).toArray((err, result) => {
if (
result[0].playerTwo !== currentUser &&
result[0].playerOne !== currentUser
) {
console.log(
`Error: "${currentUser}" is not registered as playerOne or playerTwo`
);
res.send(JSON.stringify({ success: false }));
return;
}
let ready;
switch (currentUser) {
case result[0].playerOne:
console.log(`User "${currentUser}" is registered as playerOne`);
ready = !result[0].readyPlayerOne;
lobbiesCollection.updateOne(
{ _id: lobbyId },
{ $set: { readyPlayerOne: ready } },
(err, result) => {
if (err) throw err;
console.log(`DB: Updating playerOne ready to ${ready}`);
res.send(JSON.stringify({ success: true, user: 1 }));
}
);
break;
case result[0].playerTwo:
console.log(`User "` + currentUser + `" is registered as playerTwo`);
ready = !result[0].readyPlayerTwo;
lobbiesCollection.updateOne(
{ _id: lobbyId },
{ $set: { readyPlayerTwo: ready } },
(err, result) => {
if (err) throw err;
console.log(`DB: Updating playerTwo ready to ${ready}`);
res.send(JSON.stringify({ success: true, user: 2 }));
}
);
break;
default:
console.log(
"Error, current user is not registered as playerOne or playerTwo"
);
res.send(JSON.stringify({ success: false }));
}
});
});
//************ GET CURRENT LOBBY ************//
app.post("/get-current-lobby", upload.none(), function (req, res) {
const currentLobbyId = req.body.currentLobbyId;
lobbiesCollection.find({ _id: currentLobbyId }).toArray((err, result) => {
if (err) throw err;
if (result[0] === undefined) {
res.send(JSON.stringify({ success: false }));
return;
}
//Send back lobby object in response
res.send(JSON.stringify(result[0]));
});
});
//_____________GAME TEST CODE____________________-
let UserGameAssoc = {};
let army = [
[
"knight",
"knight",
"archer",
"catapult",
"catapult",
"archer",
"knight",
"knight"
],
[
"legionary",
"pawn",
"legionary",
"pawn",
"pawn",
"legionary",
"pawn",
"legionary"
]
];
//____________END OF GAME TEST CODE___________________
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ SOCKET IO STUFF ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
//____________FUNCTIONS FOR SOCKET STUFF____________
//Refresh the lobby chat
let refreshLobbyChat = lobbyId => {
if (chatsCollection == undefined) {
return;
}
chatsCollection.find({ _id: lobbyId }).toArray((err, result) => {
if (err) throw err;
if (result[0] === undefined) {
return;
}
console.log("REFRESHING LOBBYCHAT.");
//result[0] is a chat object that has messageList
io.in(lobbyId).emit("lobby-chat", result[0].messageList);
});
};
//Reset the lobby chat
let resetLobbyChat = lobbyId => {
console.log("Resetting lobby chat for chat id: ", lobbyId);
chatsCollection.updateOne(
{ _id: lobbyId },
{ $set: { messageList: [] } },
(err, result) => {
if (err) throw err;
console.log(`DB: Resetting message list for chat id: ${lobbyId}`);
}
);
refreshLobbyChat(lobbyId);
};
let refreshLobby = lobbyId => {
console.log("Socket: Refresh lobby listener called");
lobbiesCollection.find({ _id: lobbyId }).toArray((err, result) => {
if (err) throw err;
if (result[0] === undefined) {
return;
}
//Send back lobby object in socket
io.in(lobbyId).emit("lobby-data", result[0]);
});
};
let refreshLobbyList = () => {
if (lobbiesCollection === undefined) {
return;
}
console.log("REFRESHING LOBBY LIST");
lobbiesCollection.find().toArray((err, result) => {
let lobbyCount = 0;
let fullLobbies = 0;
result.forEach(lobby => {
lobbyCount++;
if (lobby.playerOne !== "" && lobby.playerTwo !== "") {
fullLobbies++;
}
});
let data = {
lobbies: result,
lobbyCount,
fullLobbies
};
// console.log("Lobbies from socket: ", result)
io.emit("lobby-list-data", data);
});
};
//____________END|FUNCTIONS FOR SOCKET STUFF____________
io.on("connection", socket => {
console.log("Connected to socket");
socket.on("join", currentLobbyId => {
//After receiving join event with lobbyId, set the room for the client
console.log("Connecting client to socket room: ", currentLobbyId);
socket.join(currentLobbyId);
});
socket.on("disconnect", () => {
let usercookie = cookie.parse(socket.request.headers.cookie);
var currentLobbyId = "";
sessionsCollection
.find({ sessionId: usercookie.sid })
.toArray((err, result) => {
if (err) throw err;
//result is an array, we must check it elements with [ ]
if (result[0] === undefined || result.length === 0) {
//MUST send back success: false is username is not defined
return;
}
usersCollection
.find({ username: result[0].user })
.toArray((err, result) => {
currentLobbyId = result[0].currentLobby;
lobbiesCollection
.find({ _id: currentLobbyId })
.toArray((err, result) => {
if (err) throw err;
if (result[0] === undefined) {
return;
}
if (result[0].readyPlayerOne && result[0].readyPlayerTwo) {
return;
} else {
usersCollection.updateOne(
//bookmark
{ _id: result[0]._id },
{ $set: { currentLobby: "" } },
(err, result) => {
if (err) throw err;
console.log(`DB: Removed users currentLobby...`);
lobbiesCollection.deleteOne({ _id: currentLobbyId });
refreshLobbyList();
refreshLobby(currentLobbyId);
}
);
}
//Send back lobby object in socket
io.in(currentLobbyId).emit("lobby-data", result[0]);
});
});
});
//bookmark
io.emit("lobby-disconnect");
});
socket.on("refresh-lobby", currentLobbyId => {
refreshLobby(currentLobbyId);
});
socket.on("refresh-leaderboard-data", () => {
console.log("REFRESHING LEADERBOARD");
usersCollection
.find()
.sort({ wins: -1, losses: 1 })
.toArray((err, result) => {
if (err) throw err;
console.log("Leaderboard:", result);
io.emit("leaderboard-data", result);
});
});
socket.on("refresh-lobby-list", () => {
refreshLobbyList();
});
socket.on("refresh-lobby-chat", lobbyId => {
refreshLobbyChat(lobbyId);
});
socket.on("sent-message", data => {
console.log("Sent message data", data);
console.log(Object.values(data));
let messageToBeAdded = data.message;
chatsCollection.updateOne(
{ _id: data.lobbyId },
{ $push: { messageList: { ...messageToBeAdded } } },
(err, result) => {
if (err) throw err;
console.log(`DB: Updating message list for chat id: ${data.lobbyId}`);
refreshLobbyChat(data.lobbyId);
}
);
});
socket.on("leave-lobby", data => {
if (
data.lobbyId === undefined ||
data.lobbyId === null ||
data.lobbyId == ""
) {
return;
}
lobbiesCollection.find({ _id: data.lobbyId }).toArray((err, result) => {
if (err) throw err;
if (result[0] == undefined) {
return;
}
//If playerOne is alone in lobby, remove it from db!
if (
result[0].playerOne === data.currentUser &&
result[0].playerTwo === ""
) {
lobbiesCollection.deleteOne({ _id: data.lobbyId });
}
//If playerTwo is alone in lobby, remove it as well!
if (
result[0].playerTwo === data.currentUser &&
result[0].playerOne === ""
) {
lobbiesCollection.deleteOne({ _id: data.lobbyId });
}
//If playerOne leaves and is not alone, update lobby and emit!
if (
result[0].playerOne === data.currentUser &&
result[0].playerTwo !== ""
) {
lobbiesCollection.updateOne(
{ _id: data.lobbyId },
//PlayerTwo will become playerOne
{
$set: {
playerOne: result[0].playerTwo,
playerTwo: "",
readyPlayerOne: result[0].readyPlayerTwo,
readyPlayerTwo: false
}
},
(err, result) => {
if (err) throw err;
console.log(`DB: Removing player1 from lobbyId: ${data.lobbyId}`);
lobbiesCollection
.find({ _id: data.lobbyId })
.toArray((err, result) => {
io.in(data.lobbyId).emit("lobby-data", result[0]);
lobbiesCollection.find().toArray((err, result) => {
io.emit("lobby-list-data", result);
resetLobbyChat(data.lobbyId);
});
});
}
);
}
//If playerTwo leaves and is not alone, also update lobby and emit!
if (
result[0].playerTwo === data.currentUser &&
result[0].playerOne !== ""
) {
lobbiesCollection.updateOne(
{ _id: data.lobbyId },
{ $set: { playerTwo: "" } },
(err, result) => {
if (err) throw err;
console.log(`DB: Removing player2 from lobbyId: ${data.lobbyId}`);
lobbiesCollection
.find({ _id: data.lobbyId })
.toArray((err, result) => {
io.in(data.lobbyId).emit("lobby-data", result[0]);
lobbiesCollection.find().toArray((err, result) => {
io.emit("lobby-list-data", result);
resetLobbyChat(data.lobbyId);
});
});
}
);
refreshLobby(data.lobbyId);
}
});
io.emit("refresh-lobby-chat", data.lobbyId);
});
//_______________________GAME________________________________________________
socket.on("join-game", lobbyId => {
console.log(
"_________________________________________________________________________________"
);
console.log("join game recieved: ", lobbyId);
socket.join(lobbyId);
if (gameEngine.getGameInst(lobbyId) === undefined) {
console.log("creating game instance: ", lobbyId);
if (lobbyId === undefined) {
console.log("no lobby id");
return;
}
//_________________________
if (lobbiesCollection === undefined) {
console.log("db not created");
return;
}
lobbiesCollection.find({ _id: lobbyId }).toArray((err, result) => {
let originLobby = result[0];
usersCollection
.find({ username: originLobby.playerOne })
.toArray((err, result) => {
let userOne = result[0];
usersCollection
.find({ username: originLobby.playerTwo })
.toArray((err, result) => {
let userTwo = result[0];
let newGameId = gameEngine.createGameInst(
userOne.username,
userTwo.username,
userOne.army,
userTwo.army,
lobbyId
);
UserGameAssoc[userOne.username] = newGameId;
UserGameAssoc[userTwo.username] = newGameId;
console.log("new Game Id: ", newGameId);
io.in(lobbyId).emit("game-created", "game started");
});
});
});
} else {
io.in(lobbyId).emit("game-created", "game started");
}
});