-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1050 lines (889 loc) · 32.6 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
const express = require('express')
const app = express()
const passport = require('passport')
const session = require('cookie-session')
const JSSoup = require('jssoup').default
const bodyParser = require('body-parser')
const SteamStrategy = require('passport-steam').Strategy
const { gotScraping } = require('got-scraping')
const puppeteer = require('puppeteer-extra')
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
const db = require('./db')
puppeteer.use(StealthPlugin())
app.set('view engine', 'ejs')
app.use(express.static(`${__dirname}/static`))
app.use(express.urlencoded({ extended: false }))
app.use(bodyParser.urlencoded({ extended: true }))
require('dotenv').config()
/* Steam Authentication */
passport.serializeUser(function(user, done) {
done(null, user)
})
passport.deserializeUser(function(obj, done) {
done(null, obj)
})
passport.use(new SteamStrategy({
returnURL: `${process.env.WEBSITE_LINK}auth/steam/return`,
realm: process.env.WEBSITE_LINK,
apiKey: process.env.STEAM_KEY
},
function(identifier, profile, done) {
process.nextTick(function () {
profile.identifier = identifier
return done(null, profile)
})
}
))
app.use(session({
secret: process.env.SESSION_SECRET,
name: 'pog',
resave: true,
saveUninitialized: true
}))
app.use(passport.initialize())
app.use(passport.session())
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) return next()
res.redirect('/')
}
/* End Steam Authentication */
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function getParsedPage(url) {
return new Promise(async function (resolve, reject) {
await delay(1000)
try {
const browser = await puppeteer.launch({
headless: true,
args: [
'--autoplay-policy=user-gesture-required',
'--disable-background-networking',
'--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
'--disable-breakpad',
'--disable-client-side-phishing-detection',
'--disable-component-update',
'--disable-default-apps',
'--disable-dev-shm-usage',
'--disable-domain-reliability',
'--disable-extensions',
'--disable-features=AudioServiceOutOfProcess',
'--disable-hang-monitor',
'--disable-ipc-flooding-protection',
'--disable-notifications',
'--disable-offer-store-unmasked-wallet-cards',
'--disable-popup-blocking',
'--disable-print-preview',
'--disable-prompt-on-repost',
'--disable-renderer-backgrounding',
'--disable-setuid-sandbox',
'--disable-speech-api',
'--disable-sync',
'--hide-scrollbars',
'--ignore-gpu-blacklist',
'--metrics-recording-only',
'--mute-audio',
'--no-default-browser-check',
'--no-first-run',
'--no-pings',
'--no-sandbox',
'--no-zygote',
'--password-store=basic',
'--use-gl=swiftshader',
'--use-mock-keychain',
]
})
const browserPage = await browser.newPage()
await browserPage.setRequestInterception(true)
browserPage.on('request', async request => {
if (request.resourceType() === 'fetch' || request.resourceType() === 'image' || request.resourceType() === 'media' || request.resourceType() === 'font' || request.resourceType() === 'stylesheet' || request.resourceType() === 'websocket' || request.resourceType() === 'manifest' || request.resourceType() === 'other' ||
(request.resourceType() === 'script' && !request.url().includes('hltv.js'))) {
request.abort()
} else {
// console.log(request.url())
request.continue()
}
})
await browserPage.setDefaultNavigationTimeout(60000) // 1 minute
await browserPage.goto(url, { waitUntil: 'networkidle0' })
const fullPage = await browserPage.evaluate(() => document.body.innerHTML)
browser.close()
const page = '<html><body>' + fullPage.substring(fullPage.indexOf('<div class="navbar">')) // reduce page size to only relevant content
// return new JSSoup(page)
resolve(new JSSoup(page))
}
catch (err) {
console.log(err)
// const page = await (await gotScraping.get(url)).body
console.log('repeating parse')
const page = await getParsedPage(url)
// return new JSSoup(page)
resolve(page)
}
})
}
/* Tournament Links */
const TOURNAMENT_URL = 'https://www.hltv.org/events/6973/blast-premier-fall-groups-2023'
const MATCHES_URL = 'https://www.hltv.org/events/6973/matches'
const RESULTS_URL = 'https://www.hltv.org/results?event=6973'
const TOURNAMENT_NAME = 'BLAST Premier Fall Groups 2023'
const TEAM_TO_LOGO = require('./logos')
const TEAM_TO_ID = {}
const ID_TO_TEAM = {}
const all_matches = {}
let leaderboard = []
const recently_completed = new Set()
const MATCHES_SHOWN = 3
const LEADERBOARD_SHOWN = 5
let startup_complete = false
let repeating = false
function calcScore(prob) {
return Math.round((25 - (Math.pow(prob - 100, 2) / 100)) * 10) / 10
}
function toOrdinal(i) {
const j = i % 10
const k = i % 100;
if (j == 1 && k != 11) {
return i + "st"
}
if (j == 2 && k != 12) {
return i + "nd"
}
if (j == 3 && k != 13) {
return i + "rd"
}
return i + "th"
}
function findUserInLeaderboard(user) {
for (let i = 0; i < leaderboard.length; i++) {
if (leaderboard[i].user === user) {
return leaderboard[i]
}
}
}
/* Start Functions */
async function loadTeams() {
return new Promise(async function (resolve, reject) {
const web_data = await getParsedPage(TOURNAMENT_URL)
const all_teams = web_data.findAll('div', {'class': 'team-box'} )
for (let i = 0; i < all_teams.length; i++) {
const team_name = all_teams[i].find('div', {'class': 'team-name'} ).find('div', {'class': 'text'} ).text
TEAM_TO_ID[team_name] = i
ID_TO_TEAM[i] = team_name
}
resolve(1)
})
}
async function loadMatches() {
return new Promise(async function (resolve, reject) {
const match_data = await getParsedPage(MATCHES_URL)
const results_data = await getParsedPage(RESULTS_URL)
const live_matches = match_data.findAll('div', {'class': 'liveMatch'} )
const upcoming_matches = match_data.findAll('div', {'class': 'upcomingMatch'} )
const completed_matches = results_data.findAll('div', {'class': 'result-con'} )
for (let i = 0; i < live_matches.length; i++) {
const match_id = parseInt(live_matches[i].attrs['data-livescore-match'])
const teams = live_matches[i].findAll('div', {'class': 'matchTeamName'} )
const team1 = teams[0].text
const team2 = teams[1].text
const scores = live_matches[i].findAll('div', {'class': 'matchTeamScore'} )
const team1score = scores[0].text.substring(1)
const team2score = scores[1].text.substring(1)
all_matches[match_id] = {
match_id: match_id,
team1: team1,
team2: team2,
team1score: team1score,
team2score: team2score,
startTime: new Date(),
endTime: undefined,
isLive: true,
isComplete: false,
sumPredictions: 0,
numPredictions: 0,
}
}
for (let i = 0; i < upcoming_matches.length; i++) {
const match_id = parseInt(upcoming_matches[i].find('a').attrs['href'].split('/')[2])
if (upcoming_matches[i].find('div', {'class': 'matchInfoEmpty'} ) === undefined) {
const teams = upcoming_matches[i].findAll('div', {'class': 'matchTeamName'} )
if (teams.length != 2) continue // skip matches with a TBD opponent
const team1 = teams[0].text
const team2 = teams[1].text
const match_time = parseInt(upcoming_matches[i].find('div', {'class': 'matchTime'} ).attrs['data-unix'])
all_matches[match_id] = {
match_id: match_id,
team1: team1,
team2: team2,
team1score: 0,
team2score: 0,
startTime: new Date(match_time),
endTime: undefined,
isLive: false,
isComplete: false,
sumPredictions: 0,
numPredictions: 0,
}
}
}
for (let i = 0; i < completed_matches.length; i++) {
const match_id = parseInt(completed_matches[i].find('a').attrs['href'].split('/')[2])
const team1 = completed_matches[i].find('div', {'class': 'team1'} ).text
const team2 = completed_matches[i].find('div', {'class': 'team2'} ).text
const scores = completed_matches[i].find('td', {'class': 'result-score'} ).findAll('span')
const team1score = parseInt(scores[0].text)
const team2score = parseInt(scores[1].text)
const end_time = parseInt(completed_matches[i].attrs['data-zonedgrouping-entry-unix'])
if (end_time + 86400000 > new Date().getTime()) {
recently_completed.add(match_id)
}
all_matches[match_id] = {
match_id: match_id,
team1: team1,
team2: team2,
team1score: team1score,
team2score: team2score,
startTime: new Date(end_time),
endTime: new Date(end_time),
isLive: false,
isComplete: true,
sumPredictions: 0,
numPredictions: 0,
}
}
resolve(1)
})
}
async function loadDatabases() {
// function loads all predictions from database
return new Promise(async function (resolve, reject) {
await db.find().forEach(async function (doc) {
for (const [key, val] of Object.entries(doc)) {
if (!isNaN(key)) { // if key is a number, then this is a valid match id
all_matches[key].numPredictions += 1
all_matches[key].sumPredictions += val
}
}
})
resolve(1)
})
}
async function updateLeaderboard() {
return new Promise(async function (resolve, reject) {
const oldLeaderboard = []
const newLeaderboard = []
await db.find().forEach(async function (doc) {
if (!isNaN(doc._id)) {
let newPrevDay = 0.0
recently_completed.forEach(match_id => {
if (doc[match_id] !== undefined) {
newPrevDay += all_matches[match_id].team1score > all_matches[match_id].team2score ? calcScore(100 - doc[match_id]) : calcScore(doc[match_id])
}
})
newPrevDay = parseFloat(newPrevDay.toFixed(1))
oldLeaderboard.push({
user: doc._id,
score: parseFloat((doc.score - newPrevDay).toFixed(1)),
})
newLeaderboard.push({
user: doc._id,
username: doc.displayName,
steamURL: doc.steamURL,
score: doc.score,
correct: doc.correct,
totalGuesses: doc.correct + doc.incorrect,
prevDay: newPrevDay,
spotsChanged: 0,
})
}
})
oldLeaderboard.sort((a, b) => {
return b.score - a.score || b.correct - a.correct
})
newLeaderboard.sort((a, b) => {
return b.score - a.score || b.correct - a.correct
})
const user_to_rank = {}
for (let i = 0; i < oldLeaderboard.length; i++) {
if (i == 0) {
user_to_rank[oldLeaderboard[i].user] = i
}
else {
if (oldLeaderboard[i].score === oldLeaderboard[i - 1].score && oldLeaderboard[i].correct === oldLeaderboard[i - 1].correct) {
// same score as the person before, so use their rank as well
user_to_rank[oldLeaderboard[i].user] = user_to_rank[oldLeaderboard[i - 1].user]
}
else {
user_to_rank[oldLeaderboard[i].user] = i
}
}
}
for (let i = 0; i < newLeaderboard.length; i++) {
let place = i
if (i !== 0) {
if (newLeaderboard[i].score === newLeaderboard[i - 1].score && newLeaderboard[i].correct === newLeaderboard[i - 1].correct) {
place = newLeaderboard[i - 1].place
}
}
newLeaderboard[i].spotsChanged = user_to_rank[newLeaderboard[i].user] - place
newLeaderboard[i].place = place
}
leaderboard = newLeaderboard
resolve(1)
})
}
async function newCompletedMatch(match_id) {
// function is called when a new match is completed
// update user scores in the database
return new Promise(async function (resolve, reject) {
try {
const team1win = all_matches[match_id].team1score > all_matches[match_id].team2score
await db.find().forEach(async function (doc) {
if (!isNaN(doc._id)) {
const query = { _id: doc._id }
const update = { $set: {} }
if (doc[match_id] !== undefined) {
// user predicted on this match
const userGuess = parseInt(doc[match_id])
if (team1win) {
update.$set.score = parseFloat((calcScore(100 - userGuess) + doc.score).toFixed(1))
if (userGuess > 50) {
// user guessed incorrectly
update.$set.incorrect = doc.incorrect + 1
}
else if (userGuess < 50) {
// user guessed correctly
update.$set.correct = doc.correct + 1
}
}
else {
update.$set.score = parseFloat((calcScore(userGuess) + doc.score).toFixed(1))
if (userGuess > 50) {
// user guessed correctly
update.$set.correct = doc.correct + 1
}
else if (userGuess < 50) {
// user guessed incorrectly
update.$set.incorrect = doc.incorrect + 1
}
}
const updateRes = await db.updateOne(query, update)
}
}
})
// update leaderboard
await delay(1000) // slight delay to help mongodb problems
await updateLeaderboard()
resolve(1)
}
catch (err) {
console.log(`error updating user scores: ${err}, match: ${match_id}`)
}
})
}
async function checkMatches() {
// function that loads all matches to check for new matches (repeats from timer)
const match_data = await getParsedPage(MATCHES_URL)
const results_data = await getParsedPage(RESULTS_URL)
const live_matches = match_data.findAll('div', {'class': 'liveMatch'} )
const upcoming_matches = match_data.findAll('div', {'class': 'upcomingMatch'} )
const completed_matches = results_data.findAll('div', {'class': 'result-con'} )
for (let i = 0; i < live_matches.length; i++) {
const match_id = parseInt(live_matches[i].attrs['data-livescore-match'])
if (all_matches[match_id] === undefined) {
console.log(`new untracked live match: ${match_id}`)
const teams = live_matches[i].findAll('div', {'class': 'matchTeamName'} )
const team1 = teams[0].text
const team2 = teams[1].text
all_matches[match_id] = {
match_id: match_id,
team1: team1,
team2: team2,
team1score: 0,
team2score: 0,
startTime: new Date(),
endTime: undefined,
isLive: true,
isComplete: false,
sumPredictions: 0,
numPredictions: 0,
}
}
else if (!all_matches[match_id].isLive) {
console.log(`now match live: ${match_id}`)
all_matches[match_id].isLive = true
all_matches[match_id].startTime = new Date() < all_matches[match_id].startTime ? new Date() : all_matches[match_id].startTime
}
const scores = live_matches[i].findAll('div', {'class': 'matchTeamScore'} )
const team1score = scores[0].text.substring(1)
const team2score = scores[1].text.substring(1)
all_matches[match_id].team1score = team1score
all_matches[match_id].team2score = team2score
}
for (let i = 0; i < upcoming_matches.length; i++) {
const match_id = parseInt(upcoming_matches[i].find('a').attrs['href'].split('/')[2])
if (all_matches[match_id] === undefined) {
if (upcoming_matches[i].find('div', {'class': 'matchInfoEmpty'} ) === undefined) {
const teams = upcoming_matches[i].findAll('div', {'class': 'matchTeamName'} )
if (teams.length != 2) continue // skip matches with a TBD opponent
console.log(`new upcoming match: ${match_id}`)
const team1 = teams[0].text
const team2 = teams[1].text
const match_time = parseInt(upcoming_matches[i].find('div', {'class': 'matchTime'} ).attrs['data-unix'])
all_matches[match_id] = {
match_id: match_id,
team1: team1,
team2: team2,
team1score: 0,
team2score: 0,
startTime: new Date(match_time),
endTime: undefined,
isLive: false,
isComplete: false,
sumPredictions: 0,
numPredictions: 0,
}
}
}
else {
const match_time = parseInt(upcoming_matches[i].find('div', {'class': 'matchTime'} ).attrs['data-unix'])
all_matches[match_id].startTime = new Date(match_time)
if (all_matches[match_id].isLive) {
console.log(`match unlive: ${match_id}`)
all_matches[match_id].isLive = false
}
}
}
for (let i = 0; i < completed_matches.length; i++) {
const match_id = parseInt(completed_matches[i].find('a').attrs['href'].split('/')[2])
if (all_matches[match_id] === undefined) {
console.log(`untracked match complete: ${match_id}`)
const team1 = completed_matches[i].find('div', {'class': 'team1'} ).text
const team2 = completed_matches[i].find('div', {'class': 'team2'} ).text
const scores = completed_matches[i].find('td', {'class': 'result-score'} ).findAll('span')
const team1score = parseInt(scores[0].text)
const team2score = parseInt(scores[1].text)
const end_time = parseInt(completed_matches[i].attrs['data-zonedgrouping-entry-unix'])
all_matches[match_id] = {
match_id: match_id,
team1: team1,
team2: team2,
team1score: team1score,
team2score: team2score,
startTime: new Date() < new Date(end_time) ? new Date() : new Date(end_time),
endTime: new Date() < new Date(end_time) ? new Date() : new Date(end_time),
isLive: false,
isComplete: true,
sumPredictions: 0,
numPredictions: 0,
}
}
else if (!all_matches[match_id].isComplete) {
console.log(`match complete: ${match_id}`)
const scores = completed_matches[i].find('td', {'class': 'result-score'} ).findAll('span')
const team1score = parseInt(scores[0].text)
const team2score = parseInt(scores[1].text)
const end_time = parseInt(completed_matches[i].attrs['data-zonedgrouping-entry-unix'])
all_matches[match_id].isLive = false
all_matches[match_id].isComplete = true
all_matches[match_id].endTime = new Date() < new Date(end_time) ? new Date() : new Date(end_time)
all_matches[match_id].team1score = team1score
all_matches[match_id].team2score = team2score
recently_completed.add(match_id)
await newCompletedMatch(match_id)
}
}
}
async function updateRecentlyCompleted() {
// update recently completed set
return new Promise(async function (resolve, reject) {
const curr_time = new Date()
let updated = false
recently_completed.forEach(match_id => {
if (all_matches[match_id].endTime.getTime() + 86400000 < curr_time.getTime()) {
recently_completed.delete(match_id)
updated = true
}
})
if (updated) {
// need to update leaderboard with new 24 hr updates
await updateLeaderboard()
}
resolve(1)
})
}
async function repeatedFunctions() {
return new Promise(async function (resolve, reject) {
console.log("repeat - ", new Date().toLocaleString("en-US", { timeZone: "America/New_York" }))
if (repeating) {
console.log("skipped")
resolve(1)
}
else {
repeating = true
await checkMatches()
await updateRecentlyCompleted()
console.log("repeat complete - ", new Date().toLocaleString("en-US", { timeZone: "America/New_York" }))
repeating = false
resolve(1)
}
})
}
async function start() {
try {
console.log('loading teams...')
await loadTeams()
console.log('loading matches...')
await loadMatches()
console.log('loading databases...')
await loadDatabases()
console.log('loading leaderboard...')
await updateLeaderboard()
console.log('startup complete')
startup_complete = true
const repeatTimer = setInterval(repeatedFunctions, 60000)
}
catch (err) {
console.log('error on startup')
console.log(err)
}
}
start()
/* EJS Helper Functions */
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Nov', 'Dec']
app.locals.getDate = function(time) {
const timeString = time.toLocaleString("en-US", { timeZone: "America/New_York" })
const dates = timeString.substring(0, timeString.indexOf(',')).split('/')
return `${MONTHS[parseInt(dates[0]) - 1]} ${dates[1]} ${dates[2]}`
}
app.locals.getTime = function(time) {
const timeString = time.toLocaleString("en-US", { timeZone: "America/New_York" })
const times = timeString.substring(timeString.indexOf(',') + 2, timeString.indexOf(' ', timeString.indexOf(',') + 2)).split(':')
return `${times[0]}:${times[1]} ${timeString.substring(timeString.indexOf(' ', timeString.indexOf(',') + 2)+1)} (EST)`
}
app.locals.setTimer = function(diff) {
if (diff <= 0) return 'SOON'
const days = Math.floor(diff / 86400000)
const hours = Math.floor((diff % 86400000) / 3600000)
const minutes = Math.floor((diff % 3600000) / 60000)
const seconds = Math.floor((diff % 60000) / 1000)
if (days > 0) {
return `${days}d ${hours}h ${minutes}m`
}
else {
if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`
else if (minutes > 0) return `${minutes}m ${seconds}s`
else return `${seconds}s`
}
}
app.locals.calcScore = function(prob) {
return calcScore(prob)
}
/* Middleware */
function getUpcomingMatches(req, res, next) {
if (!startup_complete) next()
else {
res.locals.upcoming_matches = []
for (const match_id in all_matches) {
if (!all_matches[match_id].isComplete && !all_matches[match_id].isLive) {
res.locals.upcoming_matches.push({...all_matches[match_id], userGuess: res.locals.userDoc[match_id], averageGuess: all_matches[match_id].numPredictions === 0 ? 50 : Math.round(all_matches[match_id].sumPredictions / all_matches[match_id].numPredictions)})
}
}
res.locals.upcoming_matches.sort((a, b) => {
return a.startTime - b.startTime
})
next()
}
}
async function checkDocumentExists(req, res, next) {
if (!startup_complete) next()
else {
if (req.user === undefined) {
// user is not logged in
res.locals.userDoc = {}
next()
}
else {
const query = { _id: req.user._json.steamid }
const result = await db.findOne(query)
res.locals.userDoc = result
if (result === null) {
// new user, insert new doc into database
const newDoc = {
_id: req.user._json.steamid,
displayName: req.user._json.personaname,
steamURL: req.user._json.profileurl,
avatar: req.user.photos[2].value,
score: 0.0,
correct: 0,
incorrect: 0,
}
const insRes = await db.insertOne(newDoc)
res.locals.userDoc = newDoc
req.user.points = 0.0
console.log(`new user: ${insRes.insertedId}`)
// update leaderboard with new user
leaderboard.push({
user: req.user._json.steamid,
username: req.user._json.personaname,
steamURL: req.user._json.profileurl,
score: 0.0,
place: leaderboard.length,
correct: 0,
totalGuesses: 0,
prevDay: 0.0,
spotsChanged: 0,
})
await delay(1000) // slight delay to help mongodb problems
await updateLeaderboard()
next()
}
else {
// old user, update user if necessary
req.user.points = result.score
if (result.displayName !== req.user._json.personaname || result.steamURL !== req.user._json.profileurl || result.avatar !== req.user.photos[2].value) {
const query = { _id: req.user._json.steamid }
const update = {
$set: {
displayName: req.user._json.personaname,
steamURL: req.user._json.profileurl,
avatar: req.user.photos[2].value
}
}
const updateRes = await db.updateOne(query, update)
next()
}
else {
// believe this is necessary with the await
next()
}
}
}
}
}
function getCompletedMatches(req, res, next) {
if (!startup_complete) next()
else {
res.locals.completed_matches = []
for (const match_id in all_matches) {
if (all_matches[match_id].isLive || all_matches[match_id].isComplete) {
res.locals.completed_matches.push({...all_matches[match_id], userGuess: res.locals.userDoc[match_id], averageGuess: all_matches[match_id].numPredictions === 0 ? undefined : Math.round(all_matches[match_id].sumPredictions / all_matches[match_id].numPredictions)})
}
}
res.locals.completed_matches.sort((a, b) => {
if (a.isLive && b.isLive) return a.startTime - b.startTime
else if (a.isLive) return -1
else if (b.isLive) return 1
return b.endTime - a.endTime
})
next()
}
}
function getLiveMatches(req, res, next) {
if (!startup_complete) next()
else {
res.locals.live_matches = []
for (const match_id in all_matches) {
if (all_matches[match_id].isLive) {
res.locals.live_matches.push({...all_matches[match_id], userGuess: res.locals.userDoc[match_id], averageGuess: all_matches[match_id].numPredictions === 0 ? undefined : Math.round(all_matches[match_id].sumPredictions / all_matches[match_id].numPredictions)})
}
}
res.locals.live_matches.sort((a, b) => {
return a.startTime - b.startTime
})
next()
}
}
async function insertGuessHelper(req, res, next) {
if (!startup_complete) {
next()
}
else if (req.user === undefined || req.user._json === undefined) {
console.log(`insert guess fail, not logged in`)
next()
}
else if (req.body.match_id === undefined || all_matches[req.body.match_id] === undefined) {
console.log(`insert guess fail, invalid match id: ${req.body.match_id}, user: ${req.user._json.steamid}`)
next()
}
else if (isNaN(req.body.prob) || parseInt(req.body.prob) < 0 || parseInt(req.body.prob) > 100) {
console.log(`insert guess fail, invalid probability: ${req.body.prob}, user: ${req.user._json.steamid}`)
next()
}
else if (all_matches[req.body.match_id].isComplete || all_matches[req.body.match_id].isLive) {
console.log(`insert guess fail, match is complete or live: ${req.body.match_id}, user: ${req.user._json.steamid}`)
next()
}
else {
try {
const query = { _id: req.user._json.steamid }
const results = await db.findOne(query)
if (results[req.body.match_id] !== undefined) {
// user has guessed on this match before
all_matches[req.body.match_id].sumPredictions -= results[req.body.match_id]
}
else {
// new guess for user
all_matches[req.body.match_id].numPredictions += 1
}
all_matches[req.body.match_id].sumPredictions += parseInt(req.body.prob)
const update = { $set: {} }
update.$set[req.body.match_id] = parseInt(req.body.prob)
const updateRes = await db.updateOne(query, update)
next()
}
catch (err) {
console.log(`insert guess fail, error: ${err}, user: ${req.user._json.steamid}`)
next()
}
}
}
function findUserPlace(req, res, next) {
if (!startup_complete) next()
else if (!req.user) next()
else {
for (let i = 0; i < leaderboard.length; i++) {
if (leaderboard[i].user === req.user._json.steamid) {
res.locals.userPlace = leaderboard[i].place + 1
res.locals.userPoints = leaderboard[i].score
break
}
}
next()
}
}
async function getUserInfo(req, res, next) {
if (!startup_complete) next()
else {
const query = { _id: req.params.userID }
const results = await db.findOne(query)
if (results === null) {
// user does not exist
res.locals.userInfo = undefined
next()
}
else {
const userInfo = findUserInLeaderboard(req.params.userID)
res.locals.userInfo = {
displayName: results.displayName,
steamURL: results.steamURL,
avatar: results.avatar,
place: toOrdinal(userInfo.place + 1),
score: userInfo.score,
correct: userInfo.correct,
totalGuesses: userInfo.totalGuesses,
prevDay: userInfo.prevDay,
spotsChanged: userInfo.spotsChanged,
userMatches: []
}
if (req.user && req.user._json.steamid === req.params.userID) {
// user looking at their own profile
for (const match_id in all_matches) {
res.locals.userInfo.userMatches.push({ ...all_matches[match_id], userGuess: results[match_id] })
}
}
else {
// user looking at someone else's profile
for (const match_id in all_matches) {
if (all_matches[match_id].isComplete || all_matches[match_id].isLive) {
res.locals.userInfo.userMatches.push({ ...all_matches[match_id], userGuess: results[match_id] })
}
}
}
res.locals.userInfo.userMatches.sort((a, b) => {
if (!a.isComplete && !b.isComplete) return a.startTime - b.startTime
else if (!a.isComplete) return -1
else if (!b.isComplete) return 1
return b.endTime - a.endTime
})
next()
}
}
}
/* Routes */
app.get('/', [checkDocumentExists, getLiveMatches, getUpcomingMatches, getCompletedMatches], (req, res) => {
if (!startup_complete) {
res.render('loading')
}
else {
req.session.currLink = '/'
const upcomingMatches = res.locals.live_matches.concat(res.locals.upcoming_matches).slice(0, MATCHES_SHOWN)
const completedMatches = res.locals.completed_matches.filter(match => match.isComplete).slice(0, MATCHES_SHOWN)
const leaderboardDisplay = leaderboard.slice(0, LEADERBOARD_SHOWN)
res.render('index', { user: req.user, upcomingMatches: upcomingMatches, completedMatches: completedMatches, leaderboard: leaderboardDisplay, logos: TEAM_TO_LOGO, tournamentName: TOURNAMENT_NAME })
}
})
app.get('/upcomingMatches', [checkDocumentExists, getUpcomingMatches, findUserPlace], (req, res) => {
if (!startup_complete) {
res.render('loading')
}
else {
req.session.currLink = '/upcomingMatches'
res.render('upcoming-matches', { user: req.user, matches: res.locals.upcoming_matches, logos: TEAM_TO_LOGO, userPoints: res.locals.userPoints, userPlace: toOrdinal(res.locals.userPlace), totalUsers: leaderboard.length })
}
})
app.post('/insertGuess', [insertGuessHelper], (req, res) => {
res.send()
})
app.get('/completedMatches', [checkDocumentExists, getCompletedMatches], (req, res) => {
if (!startup_complete) {
res.render('loading')
}
else {
req.session.currLink = '/completedMatches'
res.render('completed-matches', { user: req.user, matches: res.locals.completed_matches, logos: TEAM_TO_LOGO })
}
})
app.get('/leaderboard', [checkDocumentExists], (req, res) => {
if (!startup_complete) {
res.render('loading')
}
else {
req.session.currLink = '/leaderboard'
res.render('leaderboard', { user: req.user, leaderboard: leaderboard })
}
})
app.get('/user/:userID', [checkDocumentExists, getUserInfo], (req, res) => {
if (!startup_complete) {
res.render('loading')