-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1069 lines (950 loc) · 46.9 KB
/
index.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
// import the package express for API purposes
const express = require('express');
const app = express();
// Use pg-promise to make connections to the base as previously
const pgp = require('pg-promise')();
const bodyParser = require('body-parser');
// package to help set the session object. USE req.session!
const session = require('express-session');
// Package to hash user passwords (very important!)
const bcrypt = require('bcrypt');
// Package Axios: Make HTTP requests to an external server from our server
const axios = require('axios');
const { homedir } = require('os');
// database configuration
const dbConfig = {
host: 'db',
port: 5432,
database: process.env.POSTGRES_DB,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD
};
// Use pg-promise and make a handy shorthand constant
const db = pgp(dbConfig);
// Database connection test
db.connect()
.then(obj => {
// If the connection is successful, print to the console
console.log('Database connection successful');
// use the done function to close the database connection
obj.done();
})
.catch(error => {
// If there are any errors, print them to the console
console.log('ERROR:', error.message || error);
});
// Set the view engine to EJS
app.set('view engine', 'ejs');
// Initializing Session variables
app.use(
session({
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false,
})
);
// Specify that we are using json to parse the body of a request
app.use(bodyParser.json());
// Necessary code to serve static files such as images
app.use(express.static('resources'));
app.use('/images', express.static('resources/imgs'));
//
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.get('/login', (req, res) => {
res.render('pages/login');
});
app.post('/login', async (req, res) => {
//the logic goes here
//console.log(req.body)
const username = req.body.username;
const query = `SELECT * FROM users WHERE username = $1;`;
const user = await db.any(query, [username]);
db.any(query, [
username,
]).then(async function(user) {
const match = await bcrypt.compare(req.body.password, user[0].password);
if(match){
// If the passwords match, update the session to include information about the user
req.session.user = {
username: username,
tag: user[0].clash_tag,
user_id: user[0].user_id,
//Only used for account page
email: user[0].email,
current_streak: user[0].current_streak,
max_streak: user[0].max_streak,
daily_challenges_completed: user[0].daily_challenges_completed,
random_challenges_completed: user[0].random_challenges_completed,
bad_challenges_completed: user[0].bad_challenges_completed
}
req.session.save();
res.redirect('/home')
}
else{
res.render('pages/register', {
message: `incorrect username or password`,
});
}
})
.catch(err => {
console.log(err);
res.redirect('/register');
})
});
app.get('/register', (req, res) => {
res.render('pages/register');
});
// Register submission
app.post('/register', async (req, res) => {
//the logic goes here
//console.log(req.body)
const username = req.body.username;
const email = req.body.email
const clash_tag = req.body.clashTag
//console.log(clash_tag)
const hash = await bcrypt.hash(req.body.password, 10);
//console.log(hash)
const query = `INSERT INTO users (username, email, clash_tag, password, random_challenges_completed, bad_challenges_completed)
values ($1, $2, $3, $4, 0, 0);`
db.any(query, [
username, email, clash_tag,
hash
]).then(function (data) {
res.redirect('/login');
})
.catch(err => {
console.log(err);
res.redirect('/register');
})
});
// GET request to /random
app.get('/random', async (req, res) => {
// Render the RANDOM CHALLENGE page
// Parse the request headers to see if the user is attempting to render a pre-existing challenge
const challengeID = Number(req.query.randomid);
// Check to see if an id was queried. If not, render the page for just a button
if (challengeID && challengeID != null) {
// If a query was given, we need to now check the database for this challenge
// Create a query for the database
const randomQuery = `SELECT * FROM randchallenges WHERE challenge_id = '${challengeID}'`;
// Query the database with this request in task form for multiple queries
db.task(task => {
// Query the database for the challenge ID
return task.any(randomQuery)
.then(data => {
// We now have the data output, so we need to handle a few cases
let challenge = data[0];
// CASE 1: The data is null. This means that a challenge with this ID does not exist
if(!challenge) {
// Render the new random page with a message stating that the challenge could not be found
// console.log("Could not find a challenge of ID: " + challengeID);
// Deliver a message to the page
// Check if a user is logged in, and if they are, display their completion on this challenge
if(req.session.user && req.session.user != null) {
// Render the page with the users information and the error message
// Fetch the number of challenges completed from the database
return task.any(`SELECT random_challenges_completed FROM users WHERE user_id = ${req.session.user.user_id}`)
.then(data => {
// Set this value into a variable for later user
let numChallengesCompleted = data[0].random_challenges_completed;
// Render the page to create a new random challenge passing the information needed for the header
res.render('pages/newrandom', {
error: true,
message: "A challenge of this ID does not exist.",
username: req.session.user.username,
isLoggedIn: true,
numChallengesCompleted: numChallengesCompleted
})
})
} else {
// Render the page with the error, but without the user's information
res.render('pages/newrandom', {
error: true,
message: "A challenge of this ID does not exist.",
isLoggedIn: false
})
}
}
else {
// CASE 2: we should now attempt to render this challenge
// Call the database with each card's ID to get it's information
const queryImage = `SELECT * FROM cards WHERE card_id IN ($1, $2, $3, $4, $5, $6, $7, $8)`
// Query for each Card with an In statement
return task.any(queryImage, [challenge.card_id_1, challenge.card_id_2, challenge.card_id_3, challenge.card_id_4, challenge.card_id_5, challenge.card_id_6, challenge.card_id_7, challenge.card_id_8])
.then(async data => {
// CASE 3: Bad card data
// If the data is null, something went wrong when trying to find the cards. Render the newrandom page with an error message
if(!data[0]) {
res.render('pages/newrandom', {
error: true,
message: "The challenge could not be properly accessed. Please try again later."
})
}
// CASE 4: It all works out nicely! Great!
let cardData = data;
// Check if a user is logged in, and if they are, display their completion on this challenge
if(req.session.user && req.session.user != null) {
// Get the clash tag from the user session
const clashTag = req.session.user.tag;
const tag = clashTag.replace('#', '%23');
// Check the Clash royale API for completion
const battlelog = await axios({
url: `https://api.clashroyale.com/v1/players/${tag}/battlelog`,
method: 'get',
dataType:'json',
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
}
})
.catch(error => { //If there is an error here it most likely will be with the tag registered in the users account so it sends the appropriate message
console.log(error);
})
// TODO handle bad cases for battlelog
// Get the recent matches for this player
let recentMatches = battlelog.data;
// Loop through each match to check if the correct cards were used
await recentMatches.forEach(match => {
// Pull the cards played
let cards = match.team[0].cards;
// Create a vector of the card IDs from the match data
let cardIDs = [cards[0].id, cards[1].id, cards[2].id, cards[3].id, cards[4].id, cards[5].id, cards[6].id, cards[7].id];
// This will be the clash royale version of the ID. we need to convert it to our IDs first, so do this with a database request
db.task(async task => {
const data = await task.any(`SELECT * FROM cards WHERE clash_id IN ($1, $2, $3, $4, $5, $6, $7, $8) ORDER BY card_id`, cardIDs);
// With the cards, run the hashing algorithm
let newCards = data;
let dotHash = cantorPair(cantorPair(newCards[0].card_id, newCards[1].card_id), newCards[2].card_id);
let dotHash2 = cantorPair(cantorPair(newCards[3].card_id, newCards[4].card_id), newCards[5].card_id);
let dotHash3 = cantorPair(newCards[6].card_id, newCards[7].card_id);
// Check the random challenges database for a match to the hash
const hashquery = `SELECT * FROM randchallenges WHERE (dothash = ${dotHash} AND dothash2 = ${dotHash2} AND dothash3 = ${dotHash3} AND challenge_id = ${challengeID})`;
const data_2 = await task.any(hashquery);
// If there is a return to the data, we have a match in the database!
if (data_2[0]) {
console.log("MATCH found for a deck!");
// Check if the player won
// Verify if the match was won
let win = false;
if (match.team[0].crowns == match.opponent[0].crowns) {
win = false;
} else if (match.team[0].crowns > match.opponent[0].crowns) {
console.log("THEY WON!");
win = true;
} else {
win = false;
}
if (win) {
// If the player won the challenge, we need to mark it as complete and update their total
// Increment the count on this user's table
// Now, verify if they havent already completed this challenge
return task.any(`SELECT is_completed FROM users_to_randoms WHERE (user_id = ${req.session.user.user_id} AND challenge_id = ${challengeID})`)
.then(data => {
// Check if the user has seen this challenge before, just to handle the case of if we have predefined challenges
if(data[0]) {
// Now,Use an if statement to check
if(data[0].is_completed) {
// If we reach here, they have already completed this challenge. nothing else to do
} else {
// If not completed, update the table and increment the challenges completed
// Once is completed is set to true, increment the completions
return task.any(`UPDATE users_to_randoms SET is_completed = true WHERE (user_id = ${req.session.user.user_id} AND challenge_id = ${challengeID}) RETURNING is_completed`)
.then(incrementUserChallengesCompleted(req.session.user.user_id));
}
} else {
// If nothing was returned, create the entry, then increment the challenges value
return task.any(`INSERT INTO users_to_randoms (user_id, challenge_id, is_completed) values (${req.session.user.user_id}, ${challengeID}, true)`)
.then(incrementUserChallengesCompleted(req.session.user.user_id))
}
})
} else {
// If win is false, then they did not win. move along
console.log("They did not win.");
}
} else {
// If there is no return from the query, the challenge was not found in the database
console.log("No return from database, challenge does not match")
}
})
.catch(error => {
// Catch any errors
console.log(error)
})
})
// Get the number of random challenges completed
return task.any(`SELECT random_challenges_completed FROM users WHERE user_id = ${req.session.user.user_id}`)
.then(async data => {
// Set this value into a variable for later user
let numChallengesCompleted = data[0].random_challenges_completed;
// Query the DB to see if the user has attempted this challenge
const queryUserToChl = `SELECT * FROM users_to_randoms WHERE (user_id = ${req.session.user.user_id} AND challenge_id = ${challengeID})`;
const data_1 = await task.any(queryUserToChl);
// Check if a return from the DB was made
if (data_1[0]) {
console.log("Rendering page with return. Iscompleted: " + data_1[0].is_completed);
// If a return was made, render the page with the user's completion progress
res.render('pages/random', {
// Give the card data
data: cardData,
isLoggedIn: true,
username: req.session.user.username,
isCompleted: data_1[0].is_completed,
numChallengesCompleted: numChallengesCompleted,
css: "home.css"
});
} else {
// If nothing was returned from the DB, the user has not attempted this challenge yet. Insert into the DB that they are now attempting this challenge
return task.any(`INSERT INTO users_to_randoms (user_id, challenge_id, is_completed) values (${req.session.user.user_id}, ${challengeID}, false) RETURNING is_completed`)
.then(data_2 => {
console.log("Rendering page with return, User has not seen this challenge. Iscompleted: " + data_2[0].is_completed);
// With the user now linked to the challenge, render the page along with their completion
res.render('pages/random', {
// Give the card data
data: cardData,
isLoggedIn: true,
username: req.session.user.username,
isCompleted: data_2[0].is_completed,
numChallengesCompleted: numChallengesCompleted,
css: "home.css"
});
});
}
})
} else {
// If a user is not logged in, render the page, but give the option to sign in to save challenge progress
// With the data, render the page
res.render('pages/random', {
// Give the card data
data: cardData,
isLoggedIn: false,
css: "home.css"
});
}
})
}
})
})
.catch(error => {
// Handle Errors
console.log(error)
res.render('pages/newrandom', {
isLoggedIn: false,
css: "home.css"
})
})
}
else {
// Check if a user is logged in
if(req.session.user && req.session.user != null) {
// Fetch the number of challenges completed from the database
db.task(task => {
return task.any(`SELECT random_challenges_completed FROM users WHERE user_id = ${req.session.user.user_id}`)
.then(data => {
// Set this value into a variable for later user
let numChallengesCompleted = data[0].random_challenges_completed;
// Render the page to create a new random challenge passing the information needed for the header
res.render('pages/newrandom', {
username: req.session.user.username,
isLoggedIn: true,
numChallengesCompleted: numChallengesCompleted,
css: "home.css"
});
})
})
.catch(error => {
// Handle Errors
console.log(error)
res.render('pages/newrandom', {
isLoggedIn: false,
css: "home.css"
})
});
} else {
// If a challenge ID was not provided, or was given as null, render the page to create a new random challenge without an error
res.render('pages/newrandom', {
isLoggedIn: false,
css: "home.css"
});
}
}
});
// POST Request for random
app.post('/random', (req, res) => {
// A POST request to random will create a new random challenge, save it to the database, and redirect the user to the page of the new challenge
// First, get 8 unique card id's, descending
const cardsquery = `SELECT * FROM (SELECT * FROM cards ORDER BY RANDOM() LIMIT 8) AS randcards ORDER BY card_id;`;
// Query the database to get each of the card ids
db.task(task => {
return task.any(cardsquery)
.then(data => {
// With the data from each of the cards, we need to verify that this is a unique challenge
let newCards = data;
// this can be done by using Cantor's pairing function
let dotHash = cantorPair( cantorPair(newCards[0].card_id, newCards[1].card_id), newCards[2].card_id );
let dotHash2 = cantorPair( cantorPair(newCards[3].card_id, newCards[4].card_id), newCards[5].card_id );
let dotHash3 = cantorPair(newCards[6].card_id, newCards[7].card_id)
// This unique hash can be a quick reference to check if this random deck has been created before
// Before we insert this new value into the dabase, check if this random set is already in the database
// Create a query to check the database's hashed values
// Select all from the database for the purpose of verification, we need to check if this challenge has been created or not
const hashquery = `SELECT * FROM (SELECT * FROM (SELECT * FROM randchallenges WHERE dothash = ${dotHash}) AS hashone WHERE dothash2 = ${dotHash2}) AS hashtwo WHERE dothash3 = ${dotHash3}`;
// Query the db for this hash
return task.any(hashquery)
.then(data => {
// If there is a return from the DB, the random challenge already exists
if(data[0]) {
// Extract the challenge id
let challengeID = data[0].challenge_id;
// Create a log to compare the checked and in-db values to verify that my hashing algorithm works
if(newCards[0].card_id != data[0].card_id_1 && newCards[1].card_id != data[0].card_id_2 && newCards[2].card_id != data[0].card_id_3 && newCards[3].card_id != data[0].card_id_4 && newCards[4].card_id != data[0].card_id_5 && newCards[5].card_id != data[0].card_id_6 && newCards[7].card_id != data[0].card_id_8) {
console.log("Error: Two sets of cards prdouced the same hash!")
console.log("Newly picked cards: " + newCards[0].card_id + " " + newCards[1].card_id + " " + newCards[2].card_id + " " + newCards[3].card_id + " " + newCards[4].card_id + " " + newCards[5].card_id + " " + newCards[6].card_id + " " + newCards[7].card_id + ", Hash: " + dotHash + " " + dotHash2 + " " + dotHash3);
console.log("Cards being compared to: " + data[0].card_id_1 + " " + data[0].card_id_2 + " " + data[0].card_id_3 + " " + data[0].card_id_4 + " " + data[0].card_id_5 + " " + data[0].card_id_6 + " " + data[0].card_id_7 + " " + data[0].card_id_8 + ", Hash: " + data[0].dothash + " " + data[0].dothash2 + " " + data[0].dothash3);
}
// First, check if a user is logged in by checking the session
if(req.session.user && req.session.user != null) {
// Query the database for completion
return task.any(`SELECT * FROM (SELECT * FROM users_to_randoms WHERE user_id = ${req.session.user.user_id}) AS userchallenges WHERE challenge_id = ${data[0].challenge_id}`)
.then(data => {
// Check if anything is returned
if(data[0]) {
// Use the iscompleted boolean to verify if the challenge has been completed by the user
if(data[0].is_completed) {
// TODO: If the challenge is completed, go back to the new random page. Not sure what the best way to handle this case would be
res.redirect(`/random`)
} else {
// If the challenge is not completed, redirect to the challenge page (They have not completed it yet!)
res.redirect(`/random?randomid=${data[0].challenge_id}`)
}
} else {
// If no data is returned, this challenge has not been attempted. Redirect to the challenge page
res.redirect(`/random?randomid=${challengeID}`)
}
})
} else {
// If a user is not logged in, simply redirect to the challenge page
res.redirect(`/random?randomid=${data[0].challenge_id}`)
}
}
else {
// If the data is not found, we can proceed with the creation of a new challenge in the DB
// Make an array of the costs for use
let costArray = [newCards[0].cost, newCards[1].cost, newCards[2].cost, newCards[3].cost, newCards[4].cost, newCards[5].cost, newCards[6].cost, newCards[7].cost];
// FIRST: Find the average cost of the cards that were returned
let newAvgCost = (costArray[0] + costArray[1] + costArray[2] + costArray[3] + costArray[4] + costArray[5] + costArray[6] + costArray[7]) / 8;
// SECOND: Find the 4 cycle value, the sum of the 4 cheapest cards in the deck
// Sort the cost array in ascending order and sum the smallest 4 values
costArray.sort((a,b)=>{return a-b});
// Sum the minimum 4 values
let newFourCycle = costArray[0] + costArray[1] + costArray[2] + costArray[3];
// Query to the database to make a new challenge
return task.any(`INSERT INTO randchallenges (challenge_name, average_cost, fourcycle, card_id_1, card_id_2, card_id_3, card_id_4, card_id_5, card_id_6, card_id_7, card_id_8, dothash, dothash2, dothash3) values ('Test Challenge', ${newAvgCost}, ${newFourCycle}, ${newCards[0].card_id}, ${newCards[1].card_id}, ${newCards[2].card_id}, ${newCards[3].card_id}, ${newCards[4].card_id}, ${newCards[5].card_id}, ${newCards[6].card_id}, ${newCards[7].card_id}, ${dotHash}, ${dotHash2}, ${dotHash3}) RETURNING challenge_id`)
.then(data => {
// With the insert hopefully successful, redirect the user to the page with the newly create challenge
// First, check if a user is logged in by checking the session
if(req.session.user && req.session.user != null) {
// Create an entry in the database to link the user and the challenge
return task.any(`INSERT INTO users_to_randoms (user_id, challenge_id, is_completed) values (${req.session.user.user_id}, ${data[0].challenge_id}, false) RETURNING challenge_id`)
.then(data => {
// With the user now linked to the challenge, we can send them to the challenge page
res.redirect(`/random?randomid=${data[0].challenge_id}`)
})
} else {
// If the user is not logged in, simply redirect them to the challenge page
res.redirect(`/random?randomid=${data[0].challenge_id}`)
}
})
}
})
})
})
.catch(error => {
// Log any errors to the console
console.log(error);
// Catch any errors relating to this database access and show a message on the page
res.render('pages/newrandom', {
error: true,
message: "Sorry, we could not process your request.",
isLoggedIn: false,
})
})
})
app.post('/bad', (req, res) => {
db.task(task => {
//get a random already created bad challenge
return task.any(`SELECT challenge_id FROM badchallenges OFFSET floor(random() * (SELECT COUNT(*) FROM badchallenges)) LIMIT 1`)
.then(data => {
//check if user is logged in
if (req.session.user && req.session.user != null) {
//connect user to the challenge they got
return task.any(`INSERT INTO users_to_bad (user_id, challenge_id, is_completed) values (${req.session.user.user_id}, ${data[0].challenge_id}, false) RETURNING challenge_id`)
.then(data => {
//render the bad page with the challenge they got
res.redirect(`/bad?badid=${data[0].challenge_id}`)
})
} else {
//render the bad page with the challenge they got
res.redirect(`/bad?badid=$${data[0].challenge_id}`)
}
})
//catch errors
.catch(error => {
console.log(error);
res.render('pages/baddecksDefault', {
error: true,
message: "Sorry, we could not process your request.",
isLoggedIn: false,
})
})
})
});
// GET request to /bad
app.get('/bad', async (req, res) => {
// Parse the request headers to see if the user is attempting to render a pre-existing challenge
const badChallID = Number(req.query.badid);
// Check to see if an id was queried. If not, render the page for just a button
if (badChallID && badChallID != null) {
// If a query was given, we need to now check the database for this challenge
// Create a query for the database
const badQuery = `SELECT * FROM badchallenges WHERE challenge_id = '${badChallID}'`;
// Query the database with this request in task form for multiple queries
db.task(task => {
// Query the database for the challenge ID
return task.any(badQuery)
.then(data => {
// We now have the data output, so we need to handle a few cases
let challenge = data[0];
let challName = data[0].challenge_name;
// CASE 1: The data is null. This means that a challenge with this ID does not exist
if (!challenge) {
// Render the new bad page with a message stating that the challenge could not be found
// console.log("Could not find a challenge of ID: " + challengeID);
// Deliver a message to the page
//Check if user is logged in
if (req.session.user && req.session.user != null) {
//Render the pahe with the users information and the error message
//Fetch the number of bad challenges completed
return task.any(`SELECT bad_challenges_completed FROM users WHERE user_id = ${req.session.user.user_id}`)
.then(data => {
//Save number of bad challenges
let numBadChallengesCompleted = data[0].bad_challenges_completed;
//Render the page to get new bad challenge
res.render('pages/baddecksDefault', {
error: true,
message: "A challenge of this ID does not exist.",
username: req.session.use.username,
isLoggedIn: true,
numBadChallengesCompleted: numBadChallengesCompleted,
css: "home.css",
})
})
} else {
//Render the page with the error
res.render('pages/baddecksDefault', {
error: true,
message: "A challenge of this ID does not exist.",
isLoggedIn: false,
css: "home.css",
})
}
}
else {
// CASE 2: we should now attempt to render this challenge
// Call the database with each card's ID to get it's information
const queryImage = `SELECT * FROM cards WHERE card_id IN ($1, $2, $3, $4, $5, $6, $7, $8)`
// Query for each Card with an In statement
return task.any(queryImage, [challenge.card_id_1, challenge.card_id_2, challenge.card_id_3, challenge.card_id_4, challenge.card_id_5, challenge.card_id_6, challenge.card_id_7, challenge.card_id_8])
.then(async data => {
// CASE 3: Bad card data
// If the data is null, something went wrong when trying to find the cards. Render the newrandom page with an error message
if (!data[0]) {
res.render('pages/baddecksDefault', {
error: true,
message: "The challenge could not be properly accessed. Please try again later.",
css: "home.css",
})
}
// CASE 4: It all works out nicely! Great!
let badCardData = data;
//Check if user is logged in
if (req.session.user && req.session.user != null) {
//Get clash tag from user session
const clashTag = req.session.user.tag;
const tag = clashTag.replace('#', '%23');
// Check the Clash royale API for completion
const battleLog = await axios({
url: `https://api.clashroyale.com/v1/players/${tag}/battlelog`,
method: 'get',
dataType: 'json',
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
}
})
.catch(error => {
console.log(error);
})
//Get the recent matches
let recentMatchesForBad = battleLog.data;
recentMatchesForBad.forEach(match => {
//Get the cards they played with
let cards = match.team[0].cards;
//Get all the cardIDs
let cardIDs = [cards[0].id, cards[1].id, cards[2].id, cards[3].id, cards[4].id, cards[5].id, cards[6].id, cards[7].id];
db.task(task => {
return task.any(`SELECT * FROM cards WHERE clash_id IN ($1, $2, $3, $4, $5, $6, $7, $8) ORDER BY card_id`, cardIDs)
.then(data => {
let localCardIDs = [data[0].card_id, data[1].card_id, data[2].card_id, data[3].card_id, data[4].card_id, data[5].card_id, data[6].card_id, data[7].card_id];
const badhashquery = `SELECT * FROM badchallenges WHERE challenge_id = ${badChallID}`;
return task.any(badhashquery)
.then(data => {
if (data[0]) {
let challengeCardIDs = [data[0].card_id_1, data[0].card_id_2, data[0].card_id_3, data[0].card_id_4, data[0].card_id_5, data[0].card_id_6, data[0].card_id_7, data[0].card_id_8];
//console.log(challengeCardIDs);
//console.log(localCardIDs);
if (localCardIDs.sort().join(',') === challengeCardIDs.sort().join(',')) {
//console.log("THE CARDS ARE THE SAME");
let win = false;
if (match.team[0].crowns == match.opponent[0].crowns) {
win = false;
} else if (match.team[0].crowns > match.opponent[0].crowns) {
win = true;
} else {
win = false;
}
if (win) {
//console.log("YOU WON");
return task.any(`SELECT is_completed FROM users_to_bad WHERE (user_id = ${req.session.user.user_id} AND challenge_id = ${badChallID})`)
.then(data => {
if (data[0]) {
if (data[0].is_completed) {
} else {
console.log("Not completed but won, increment wins");
return task.any(`UPDATE users_to_bad SET is_completed = true WHERE (user_id = ${req.session.user.user_id} AND challenge_id = ${badChallID})`)
.then(data => {
incrementBadUserChallengesCompleted(req.session.user.user_id);
})
}
} else {
console.log("Not seen but won, increment wins");
return task.any(`INSERT INTO users_to_bad (user_id, challenge_id, is_completed) values (${req.session.user.user_id}, ${data[0].challenge_id}, true) RETURNING challenge_id`)
.then(data => {
incrementBadUserChallengesCompleted(req.session.user.user_id);
})
}
})
} else {
}
}
} else {
}
})
})
})
.catch(error => {
console.log(error)
})
})
//Get the number of bad challeneges completed
return task.any(`SELECT bad_challenges_completed FROM users WHERE user_id = ${req.session.user.user_id}`)
.then(data => {
//Save this value
let numBadChallengesCompleted = data[0].bad_challenges_completed;
//See if a user has attempted this specific challenge
const badQueryUserToChl = `SELECT * FROM (SELECT * FROM users_to_bad WHERE user_id = ${req.session.user.user_id}) AS userchallenges WHERE challenge_id = ${badChallID}`;
return task.any(badQueryUserToChl)
.then(data => {
//Check if a return from the DB was made
if (data[0]) {
//If there was a return made, render the page with completion progress
res.render('pages/newbaddecks', {
data: badCardData,
challName: challName,
isLoggedIn: true,
username: req.session.user.username,
isCompleted: data[0].is_completed,
numBadChallengesCompleted: numBadChallengesCompleted,
css: "home.css"
});
} else {
//If nothing returnred they havent attempted this yet and we should add into the DB
return task.any(`INSERT INTO users_to_bad (user_id, challenge_id, is_completed) values (${req.sessions.user.user_id}, ${badChallID}, true) RETURNING is_completed`)
.then(data => {
res.render('pages/newbaddecks', {
data: badCardData,
challName: challName,
isLoggedIn: true,
username: req.session.user.username,
isCompleted: data[0].is_completed,
numBadChallengesCompleted: numBadChallengesCompleted,
css: "home.css"
});
})
}
})
})
} else {
res.render('pages/newbaddecks', {
data: badCardData,
challName: challName,
isLoggedIn: false,
css: "home.css",
});
}
})
}
})
})
.catch(error => {
console.log(error)
res.render('pages/baddecksDefault', {
isLoggedIn: false,
css: "home.css",
})
})
}
else {
if (req.session.user && req.session.user != null) {
db.task(task => {
return task.any(`SELECT bad_challenges_completed FROM users WHERE user_id = ${req.session.user.user_id}`)
.then(data => {
let numBadChallengesCompleted = data[0].bad_challenges_completed;
res.render('pages/baddecksDefault', {
username: req.session.user.username,
isLoggedIn: true,
numBadChallengesCompleted: numBadChallengesCompleted,
css: "home.css"
});
})
})
.catch(error => {
console.log(error)
res.render('pages/baddecksDefault', {
isLoggedIn: false,
css: "home.css"
})
});
} else {
res.render('pages/baddecksDefault', {
isLoggedIn: false,
css: "home.css"
});
}
}
});
// Get Request to update and test card database
// TODO: turn into a better form to update card data dynamically
// TODO: add functionality to dynamically add attributes to cards through UI
app.get('/cards', (req, res) => {
console.log("GET/cards");
// Query to list cards
const query = 'SELECT * FROM CARDS';
db.any(query)
.then(cards => {
// console.log(cards);
res.render('pages/cards', {
cards,
title: "Cards",
});
})
.catch(error => {
res.render('pages/cards', {
error: true,
message: error.message,
});
});
});
// Fetch new clash royale cards and card data from the clash royale API.
app.post('/cards/fetch-cards', (req,res) => {
console.log("Fetch Cards");
var insertQuery = "";
axios({
url: 'https://api.clashroyale.com/v1/cards',
method: 'get',
dataType:'json',
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`
}
})
.then(cards => {
// console.log(cards.data.items);
// Fetch Cards from the Clash Royale Database
for (var i=0; i<cards.data.items.length; i++) {
var card = cards.data.items[i];
insertQuery += `INSERT INTO cards (card_name, clash_id, max_level, icon_url, cost) VALUES ('${card.name}', ${card.id}, ${card.maxLevel}, '${card.iconUrls.medium}', 0) ON CONFLICT DO NOTHING;\n`;
}
console.log(insertQuery);
db.any(insertQuery).catch(error => {
console.log("Fetch Cards: Query is invalid");
});
res.redirect('/cards');
})
.catch(error => {
console.log("Fetch Cards Error");
res.redirect('/home');
})
})
// Get Request to view and test attribute database
app.get('/attributes', (req, res) => {
console.log("GET/attributes");
// TODO: Query to get attributes
res.render('pages/attributes');
});
//Authentication Middleware TODO Make this only apply where Authentication is necessary
const auth = (req, res, next) => {
if (!req.session.user) {
// Default to register page.
return res.redirect('/register');
}
next();
};
// Authentication Required
app.use(auth);
// GET Request for /home
app.get('/home', async (req, res) => {
//console.log(req.session.user.api_key);
//console.log(req.session.user.tag);
const clashTag = req.session.user.tag;
//console.log(clashTag);
const tag = clashTag.replace('#', '%23');
let usersRankedQuery = `SELECT username, SUM(random_challenges_completed + bad_challenges_completed) as challenges_completed FROM users
GROUP BY user_id
ORDER BY SUM(random_challenges_completed + bad_challenges_completed);`
const query = `SELECT daily_challenges_completed FROM users;`;
let userRankings = await db.any(usersRankedQuery);
axios({
url: `https://api.clashroyale.com/v1/players/${tag}`,
method: 'get',
dataType:'json',
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
}
})
.then(async (results) => {
//console.log(results); // the results will be displayed on the terminal if the docker containers are running
const battlelog = await axios({
url: `https://api.clashroyale.com/v1/players/${tag}/battlelog`,
method: 'get',
dataType:'json',
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
}
})
.catch(error => { //If there is an error here it most likely will be with the tag registered in the users account so it sends the appropriate message
res.render('pages/home', {
error: error,
message: 'Not able to find player with your clash royale tag. Please check your tag and change it if needed in account page',
username: req.session.user.username,
css: "home.css",
})
})
const clanRankings = await axios({
url: `https://api.clashroyale.com/v1/locations/57000006/rankings/clans`,
method: 'get',
dataType:'json',
headers: {
// Bearer apikey
"Authorization": `Bearer ${process.env.API_KEY}`,
// `Bearer ${req.session.user.api_key} does not work
}
})
.catch(error => {
console.log(error);
res.render('pages/home', { //Error should not happen here unless api_key is not valid so should not really have to worry about this
message: 'Error with retrieving clan rankings',
})
})
var worstClan = clanRankings.data.items[998];
var worstClanTag = worstClan.tag.replace('#', '%23');
const worstClanInfo = await axios({
url: `https://api.clashroyale.com/v1/clans/${worstClanTag}`,
method: 'get',
dataType:'json',
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
}
})
.catch(error => {
console.log(error);
res.render('pages/home', { //Error should not happen here unless api_key is not valid so should not really have to worry about this
message: 'Error retrieving clan rankings info',
})
})
console.log(userRankings);
res.render('pages/home', {
results: results,
battlelog: battlelog,
userRankings: userRankings,
clanRankings: clanRankings,
worstClanInfo: worstClanInfo,
username: req.session.user.username,
title: "Home",
css: "home.css",
});
})
.catch(error => { //an error could occur if the incorrect clash royale tag is associated with the account so the erorr message reflects that
// Handle errors