-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmlgame.js
717 lines (637 loc) · 20.7 KB
/
mlgame.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
//Loads the config fomr config.env to process.env (turn off prior to deployment)
require("dotenv").config({ path: "./config.env" });
// index.js
/* EXPRESS */
const express = require('express');
const app = express();
const session = require('express-session');
const fs = require('fs');
const http = require('http');
const https = require('https');
const dbo = require("./db/conn");
const cors = require('cors');
var ObjectId = require('mongodb').ObjectID;
app.use(cors());
if (process.env.SSLKEY) {
var privateKey = fs.readFileSync(process.env.SSLKEY, 'utf8');
var certificate = fs.readFileSync(process.env.SSLCERT, 'utf8');
var credentials = {key: privateKey, cert: certificate};
}
app.set('view engine', 'ejs');
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'SECRET'
}));
app.use(express.urlencoded());
app.use(express.json());
//Put the user object in a global veriable so it can be accessed from templates
app.use(function(req, res, next) {
try {
res.locals.user = req.session.passport.user;
next();
} catch (error) {
res.locals.user = req.session.user;
next();
}
});
/* Setup public directory
* Everything in her does not require authentication */
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
if (req.session.passport) {
res.redirect("/profile");
} else {
res.locals.pageTitle ="ODI Template (NodeJS + Express + OAuth)";
res.render('pages/auth');
}
});
/* PASSPORT SETUP */
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'ejs');
app.post('/logout', function(req, res, next){
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
app.get('/error', (req, res) => res.send("error logging in"));
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
/* Google AUTH */
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
const GOOGLE_CALLBACK_URL = "http://" + process.env.HOST + "/auth/google/callback";
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: GOOGLE_CALLBACK_URL
},
function(accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
app.get('/auth/google',
passport.authenticate('google', { scope : ['profile', 'email'] }));
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/error' }),
function(req, res) {
//console.log(req.user);
// Successful authentication, redirect success.
// Redirects to the profile page, CHANGE THIS to redirect to another page, e.g. a tool that is protected
res.redirect('/profile');
});
/* Setup function to handle authentications */
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated())
return next();
else
unauthorised(res);
}
function unauthorised(res) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
}
function badRequest(res,start,end) {
res.locals.pageTitle ="400 Bad Request";
return res.status(400).render("errors/400",{start: start, end: end});
}
function renderGame(req,res,data) {
var sessionId = data._id;
var dbConnect = dbo.getDb();
dbConnect
.collection('Leaderboards')
.findOne({"_id": new ObjectId(data.leaderboardId)},function(err,data2) {
var chosenSet = data2.cardset[Math.floor(Math.random() * data2.cardset.length)];
let tutorMode = false;
if (data.tutorMode == "on") {
tutorMode = true;
}
res.render('pages/game',{session: sessionId, leaderboardId: data.leaderboardId, set: chosenSet, resultId: null, isTutor: data.isTutor, requireEvaluationPin: tutorMode});
});
}
/* Setup private directory, everything in here requires authentication */
app.use('/private', ensureAuthenticated);
app.use('/private', express.static(__dirname + '/private'));
/**
* Methods to allow users to play the game
*
*/
app.get('/game/:id', function(req,res) {
var dbConnect = dbo.getDb();
dbConnect
.collection('Sessions')
.findOne({"_id": new ObjectId(req.params.id)},function(err,data) {
if (req.isAuthenticated()) {
data.isTutor = true;
renderGame(req,res,data);
} else {
if (data.startTime) {
var now = new Date().getTime();
var start = new Date(data.startTime).getTime();
if (now >= start) {
if (data.endTime) {
var end = new Date(data.endTime).getTime();
if (now <= end) {
renderGame(req,res,data);
} else {
badRequest(res,data.startTime,data.endTime);
}
} else {
renderGame(req,res,data);
}
} else {
badRequest(res,data.startTime,data.endTime);
}
} else {
renderGame(req,res,data);
}
}
});
});
app.get('/game/:id/result', function(req,res) {
const playerName = req.query.userId;
if (!req.query.userId) {
res.locals.pageTitle ="400 Bad request";
return res.status(400).render("errors/400");
} else {
var dbConnect = dbo.getDb();
dbConnect
.collection('Results')
.findOne({"sessionId" : req.params.id, "attempt" : 1, "playerName" : playerName}, function(err,data) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(data, null, 4));
});
}
});
app.get('/browse', function(req,res) {
res.render('pages/browse');
});
/**
* Methods to get leaderboard results
*/
app.get('/leaderboard/all/results', async function(req, res) {
type = req.headers.accept.split(',')[0];
if (req.isAuthenticated()) {
if (type == "application/json") {
try {
const dbConnect = dbo.getDb();
// Fetch sessions with hidePublic set to false
const sessions = await dbConnect
.collection("Sessions")
.find({ hidePublic: "off" })
.toArray();
// Extract session IDs
const sessionIds = sessions.map(session => session._id);
const query = { sessionId: { $in: sessionIds.map(id => id.toString()) } };
const results = await dbConnect
.collection("Results")
.find(query)
.project({"id":1,"score":1,"_id":0,"confidences":1,"result":1,"vsHybrid":1,"vsMachine":1,"attempt":1})
.sort({"score": -1})
.toArray();
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(results, null, 4));
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Internal Server Error' });
}
} else {
res.render('pages/leaderboard');
}
} else {
if (type == "application/json") {
try {
const dbConnect = dbo.getDb();
// Fetch sessions with hidePublic set to false
const sessions = await dbConnect
.collection("Sessions")
.find({ hidePublic: "off" })
.toArray();
const sessionIds = sessions.map(session => session._id);
const query = { sessionId: { $in: sessionIds.map(id => id.toString()) } };
const results = await dbConnect
.collection("Results")
.find(query)
.project({"id":1,"score":1,"_id":0,"confidences":1,"result":1,"vsHybrid":1,"vsMachine":1,"attempt":1})
.sort({"score": -1})
.toArray();
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(results, null, 4));
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Internal Server Error' });
}
} else {
res.locals.pageTitle ="Leaderboard";
res.render('pages/leaderboard');
}
}
});
app.get('/leaderboard/:id/results', function(req, res) {
res.locals.pageTitle ="Leaderboard for " + req.params.id;
res.locals.id = req.params.id;
type = req.headers.accept.split(',')[0];
if (req.isAuthenticated()) {
if (type=="application/json") {
var dbConnect = dbo.getDb();
dbConnect
.collection('Sessions')
.find({"leaderboardId" : req.params.id})
.toArray(function(err,data) {
var sessions = [];
for(i=0;i<data.length;i++) {
sessions.push(data[i]._id.toString());
}
dbConnect
.collection("Results")
.find({ sessionId: { $in: sessions} } )
.sort( {"score": -1} )
.toArray(function(err,output) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(output, null, 4));
});
});
} else {
res.render('pages/leaderboard/view', {})
}
} else {
if (type=="application/json") {
var dbConnect = dbo.getDb();
dbConnect
.collection('Sessions')
.find({"leaderboardId" : req.params.id})
.toArray(function(err,data) {
var sessions = [];
for(i=0;i<data.length;i++) {
sessions.push(data[i]._id.toString());
}
dbConnect
.collection("Results")
.find({ sessionId: { $in: sessions} } )
.project({"id":1,"score":1,"attempt":1,"_id":0})
.sort( {"score": -1} )
.toArray(function(err,output) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(output, null, 4));
});
});
} else {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
}
}
});
app.get('/leaderboard/:id/:sessionId/results', function(req, res) {
type = req.headers.accept.split(',')[0];
if (!req.isAuthenticated()) {
if (type=="application/json") {
var dbConnect = dbo.getDb();
dbConnect
.collection('Results')
.find({"sessionId" : req.params.sessionId})
.project({"id":1,"playerName": 1,"attempt":1,"score":1,"_id":0})
.sort( {"score": -1} )
.toArray(function(err,data) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(data, null, 4));
});
} else {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
}
} else {
if (type=="application/json") {
var dbConnect = dbo.getDb();
dbConnect
.collection('Results')
.find({"sessionId" : req.params.sessionId})
.sort( {"score": -1} )
.toArray(function(err,data) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(data, null, 4));
});
} else {
res.locals.pageTitle ="View single session leaderboard";
res.locals.id = req.params.id;
res.locals.sessionId = req.params.sessionId;
res.render('pages/session/view', {})
}
}
});
app.get('/result/:resultId', function(req, res) {
if (!req.isAuthenticated()) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
} else {
var dbConnect = dbo.getDb();
dbConnect
.collection('Results')
.findOne({"id" : req.params.resultId}, function(err,data) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(data, null, 4));
});
}
});
app.get('/result/:resultId/tree', function(req, res) {
if (!req.isAuthenticated()) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
} else {
var dbConnect = dbo.getDb();
dbConnect
.collection('Results')
.findOne({"id" : req.params.resultId}, function(err,data) {
dbConnect
.collection('Sessions')
.findOne({"_id": new ObjectId(data.sessionId)},function(err,lbdata) {
res.render('pages/game',{session: data.sessionId, leaderboardId: lbdata.leaderboardId, set: data.cardSet, resultId: req.params.resultId, isTutor: true, requireEvaluationPin: false});
});
});
}
});
app.get('/evaluationPin', function(req, res) {
if (!req.isAuthenticated()) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
} else {
res.locals.pageTitle ="Evaluation pin";
res.render('pages/pin', {})
}
});
app.post('/result', function(req, res) {
if (!req.body.score) {
return res.status(400).send("Result not accepted");
}
var dbConnect = dbo.getDb();
dbConnect
.collection('Results')
.updateOne({"id":req.body.id},{ $set: req.body},{upsert:true},
function(err,result) {
if (err) {
return res.status(500).send("Result not accepted");
}
return res.status(201).send("Result accepted");
});
});
/**
* Methods to crete, view and edit leaderboards
*
*/
app.get('/leaderboard/create', function(req, res) {
if (!req.isAuthenticated()) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
}
res.locals.pageTitle ="Create leaderboard";
res.render('pages/leaderboard/create', {})
});
app.get('/leaderboard/:id/edit', function(req, res) {
if (!req.isAuthenticated()) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
}
res.locals.pageTitle ="Edit leaderboard";
res.locals.id = req.params.id;
res.render('pages/leaderboard/edit', {})
});
app.get('/leaderboards', function(req, res) {
if (!req.isAuthenticated()) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
}
type = req.headers.accept.split(',')[0];
if (type=="application/json") {
var dbConnect = dbo.getDb();
dbConnect
.collection('Leaderboards')
.find({})
.toArray(function(err,data) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(data, null, 4));
});
} else {
res.locals.pageTitle ="View leaderboards";
res.render('pages/leaderboard/list', {msg: ""})
}
});
app.get('/leaderboard/:id', function(req, res) {
res.locals.pageTitle ="Leaderboard for " + req.params.id;
res.locals.id = req.params.id;
if (req.isAuthenticated()) {
type = req.headers.accept.split(',')[0];
if (type=="application/json") {
var dbConnect = dbo.getDb();
dbConnect
.collection('Leaderboards')
.findOne({"_id": new ObjectId(req.params.id)},function(err,data) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(data, null, 4));
});
} else {
res.render('pages/leaderboard/view', {})
}
} else {
res.render('pages/leaderboard/view', {})
}
});
app.post('/leaderboard', function(req, res) {
var dbConnect = dbo.getDb();
dbConnect
.collection('Leaderboards')
.insertOne(req.body,
function(err,result) {
var msg = "Leaderboard inserted";
if (err) {
var msg = "Error inserting leaderboard";
}
res.locals.pageTitle = "Dashboards";
res.render('pages/leaderboard/list', { msg: msg });
});
});
app.post('/leaderboard/:id', function(req, res) {
var dbConnect = dbo.getDb();
dbConnect
.collection('Leaderboards')
.updateOne({"_id":new ObjectId(req.params.id)},{ $set: req.body},{upset:false},
function(err,result) {
var msg = "Leaderboard updated";
if (err) {
var msg = "Error updating leaderboard";
}
res.redirect("/leaderboards");
});
});
app.delete('/leaderboard/:id', function(req, res) {
res.locals.id = req.params.id;
var dbConnect = dbo.getDb();
dbConnect
.collection('Leaderboards')
.deleteOne({"_id": new ObjectId(req.params.id)},
function(err,result) {
var msg = "Leaderboard deleted";
if (err) {
var msg = "Error deleting leaderboard";
}
res.locals.pageTitle = "Sessions";
res.render('pages/session/list', { msg: msg });
});
});
/**
* Methods to crete, view and edit sessions
*
*/
app.get('/leaderboard/:id/sessions', function(req, res) {
if (!req.isAuthenticated()) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
}
type = req.headers.accept.split(',')[0];
if (type=="application/json") {
var dbConnect = dbo.getDb();
dbConnect
.collection('Sessions')
.find({"leaderboardId" : req.params.id})
.toArray(function(err,data) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(data, null, 4));
});
} else {
res.locals.pageTitle ="View sessions for leaderboard";
res.locals.id = req.params.id;
res.render('pages/session/list', {msg: ""})
}
});
app.get('/leaderboard/:id/session/create', function(req, res) {
res.locals.pageTitle ="Create session for leaderboard";
res.locals.id = req.params.id;
res.render('pages/session/create', {})
});
app.post('/leaderboard/:id/createSession', function(req, res) {
var dbConnect = dbo.getDb();
var data = req.body;
data.leaderboardId = req.params.id;
res.locals.id = req.params.id;
dbConnect
.collection('Sessions')
.insertOne(data,
function(err,result) {
var msg = "Session created";
if (err) {
var msg = "Error creating session";
}
res.redirect("/leaderboard/"+ req.params.id + "/sessions");
});
});
app.put('/leaderboard/:id/:sessionId', function(req, res) {
var dbConnect = dbo.getDb();
var data = req.body;
// Extract the session ID from the URL parameters
var sessionId = req.params.sessionId;
// Update the session data
dbConnect
.collection('Sessions')
.updateOne(
{ _id: ObjectId(sessionId) }, // Use ObjectId to convert sessionId to MongoDB ObjectId
{ $set: data },
function(err, result) {
if (err) {
console.error('Error updating session:', err);
res.status(500).json({ error: 'Internal Server Error' }); // Return a 500 error code to the front end
} else {
if (result.matchedCount === 0) {
res.status(404).json({ error: 'Session not found' }); // Return a 404 error code if the session was not found
} else {
res.status(200).json({ message: 'Session updated' }); // Return a 200 success code to the front end
}
}
}
);
});
app.get('/leaderboard/:id/:sessionId', function(req, res) {
res.locals.pageTitle ="Leaderboard for session " + req.params.sessionId;
res.locals.id = req.params.id;
res.locals.sessionId = req.params.sessionId;
if (req.isAuthenticated()) {
type = req.headers.accept.split(',')[0];
if (type=="application/json") {
var dbConnect = dbo.getDb();
dbConnect
.collection('Sessions')
.findOne({"_id": new ObjectId(req.params.sessionId)},function(err,data) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(data, null, 4));
});
} else {
res.render('pages/session/view', {})
}
} else {
res.render('pages/session/view', {})
}
});
app.get('/leaderboard/:id/:sessionId/edit', function(req, res) {
if (!req.isAuthenticated()) {
res.locals.pageTitle ="401 Unauthorised";
return res.status(401).render("errors/401");
}
res.locals.pageTitle ="Edit session";
res.locals.id = req.params.id;
res.locals.sessionId = req.params.sessionId;
res.render('pages/session/edit', {})
});
app.delete('/leaderboard/:id/:sessionId', function(req, res) {
res.locals.id = req.params.id;
var dbConnect = dbo.getDb();
dbConnect
.collection('Sessions')
.deleteOne({"leaderboardId": req.params.id, "_id": new ObjectId(req.params.sessionId)},
function(err,result) {
var msg = "Session deleted";
if (err) {
var msg = "Error deleting session";
}
res.locals.pageTitle = "Sessions";
res.render('pages/session/list', { msg: msg });
});
});
/* Other methods */
app.get('/profile', function(req, res) {
res.locals.pageTitle ="Profile page";
res.render('pages/profile')
});
app.get('/help', function(req, res) {
res.locals.pageTitle ="Video walkthrough";
res.render('pages/help')
});
//Keep this at the END!
app.get('*', function(req, res){
res.locals.pageTitle ="404 Not Found";
return res.status(404).render("errors/404");
});
/* Run server */
dbo.connectToServer(function (err) {
if (err) {
console.error(err);
process.exit();
}
const port = process.env.PORT || 80;
// start the Express server
var httpServer = http.createServer(app);
httpServer.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
if (process.env.SSLKEY) {
const securePort = process.env.SECUREPORT || 443;
var httpsServer = https.createServer(credentials,app);
httpsServer.listen(securePort, () => {
console.log(`Server is running on port: 443`);
});
}
});