-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtestServer2.js
529 lines (478 loc) · 16.6 KB
/
testServer2.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
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 http = require("http").createServer(app);
const io = require("socket.io")(http);
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:[email protected]/test?retryWrites=true"; // URI for remote database!
app.use("/assets", express.static(__dirname + "/assets"));
app.use(cookieParser());
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ STORAGE ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
let usersCollection;
let sessionsCollection;
let lobbiesCollection;
let gamesCollection;
//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");
});
})();
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ GENERAL FUNCTIONS ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
//Generates random Id
const generateId = () => {
return "" + Math.floor(Math.random() * 100000000000);
};
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ 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,
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 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 }));
});
});
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ 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
const newLobby = {
_id: generateId(),
playerOne: req.body.currentUser,
playerTwo: "",
readyPlayerOne: false,
readyPlayerTwo: false,
creationTime: new Date().toLocaleString()
};
//Insert lobby into the database
lobbiesCollection.insertOne(newLobby, (err, result) => {
//Add new user to remote database
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: ${newLobby._id}`);
//use this result to get the _Id from the lobby object
// console.log(result);
res.send(JSON.stringify({ success: true, lobbyId: newLobby._id }));
//res.send(JSON.stringify(result));
});
});
//************ 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;
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.update(
{ _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 }));
}
);
});
});
//************ 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.update(
{ _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 }));
}
);
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 }));
}
);
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]));
});
});
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ SOCKET IO STUFF ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
//_____________GAME TEST CODE____________________-
let army = ["pawn", "knight", "catapult", "legionary", "archer"];
gameEngine.createTestGameInst("user1", "user2", army, army);
/*
gameEngine.getGameInst("test").map.forEach(char => {
if (char.actorType !== "char") {
return;
}
console.log(char.actorId);
console.log(char.charType);
console.log(char.pos);
});
let mres = gameEngine.handlerUserInput({
gameId: "test",
action: {
type: "move",
actorId: "29",
dest: { x: 3, y: 2 }
},
team: "user1"
});
console.log(mres);
console.log("action");
mres.changes.forEach(change => {
console.log(change);
});
console.log("______________________");
gameEngine.getGameInst("test").map.forEach(char => {
if (char.actorType !== "char") {
return;
}
console.log(char.actorId);
console.log(char.pos);
});
//console.log(gameEngine.getGameInst("test")["points"]);
//console.log("_______________________________________________________________");
//console.log("_______________________________________________________________");
//console.log(gameEngine.getGameInst("test"));
*/
//____________END OF GAME TEST CODE___________________
io.on("connection", socket => {
console.log("Connected to socket");
console.log(socket.request.headers.cookie);
socket.on("playerOneReady", () => {
console.log("Socket: Player one is ready!");
socket.emit("setStatePlayerOneReady");
});
socket.on("playerTwoReady", () => {
console.log("Socket: Player two is ready!");
//
socket.emit("setStatePlayerTwoReady");
});
socket.on("login", () => {
console.log("Socket: Logging in");
});
socket.on("lobby-update", () => {
//Refreshes lobby page for both users
socket.emit("refresh-lobby");
});
//_______________________GAME________________________________________________
socket.on("get-game-data", message => {
socket.emit("game-data", gameEngine.getGameInst("test"));
});
socket.on("game-input", input => {
console.log("here");
let result = gameEngine.handlerUserInput({
gameId: "test",
action: input,
team: "user1"
});
if (
result["changes"][0] !== undefined &&
result["changes"][0]["type"] === "game-over"
) {
socket.emit("game-over", {
type: "game-over",
winner: result.changes[0]["winner"]
});
} else {
socket.emit("game-state-change", {
success: result.success,
changes: result.changes
});
}
});
//_______________________END OF GAME________________________________________________
});
///////////////////////////////////////////////////////////////////////////////////////////////////////
//************ JAQUES STUFF ************//
///////////////////////////////////////////////////////////////////////////////////////////////////////
const { spawn } = require("child_process");
const chokidar = require("chokidar");
let pollServer = `let __version = undefined
let delay = t => new Promise((res, rej) => setTimeout(() => res(), t))
let checkVersion = async () => {
await fetch('/__version')
.then(x => x.text())
.then(v => {
__version = v
})
while (true) {
await delay(300)
try {
let x = await fetch('/__version')
let newVersion = await x.text()
if (__version !== newVersion) {
location.reload();
}
} catch (err) { }
}
}
checkVersion()`;
//let generateId = () => "" + Math.floor(Math.random() * 10000000000);
let __version = generateId();
app.get("/__version", (req, res) => {
res.send(__version);
});
chokidar
.watch(__dirname + "/build", { ignored: /(^|[\/\\])\../ })
.on("all", (event, path) => {
webpackError = undefined;
__version = generateId();
});
let webpackError = undefined;
app.all("/*", (req, res, next) => {
if (webpackError) {
res.send(
"<h4>" + webpackError + "</h4><script>" + pollServer + "</script>"
);
} else {
next();
}
});
app.use("/", express.static("build"));
app.all("/*", (req, res) => {
res.sendFile(__dirname + "/build/index.html");
});
let counter = 0;
let setup = async () => {
const cmd = /^win/.test(process.platform) ? "npx.cmd" : "npx";
let webpack = spawn(cmd, ["webpack", "--watch", "--display", "errors-only"]);
webpack.stdout.on("data", data => {
webpackError = data.toString();
});
http.listen(4000, "0.0.0.0", () => {
console.log("Running on port 4000 , 0.0.0.0");
});
};
setup();