-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
5334 lines (5270 loc) · 186 KB
/
app.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 ejs = require('ejs');
const crypto = require('crypto');
const path = require('path');
const speakeasy = require('speakeasy');
const useragent = require('express-useragent');
const mysql = require('mysql');
const geoip = require('geoip-lite');
const cookieParser = require('cookie-parser');
const { DateTime } = require('luxon');
const Teams = require('./t.js');
const QRCS = require('./qrcs.js');
const Cred = require('./cred.js');
const Email = require('./email.js');
const QR = require('qrcode');
var busy = false;
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: Cred.sql().p,
database: Cred.sql().d,
multipleStatements: true
});
function request(sql) {
if (!busy) {
busy = true;
return new Promise(function(resolve, reject) {
con.query(sql,function (error,result) {
if (error) {
busy = false;
throw error;
};
resolve(result);
})
}).then(function(result) {
busy = false;
return result;
});
} else {
//console.log('query is busy');
return new Promise(function(resolve, reject) {
setTimeout(() => { resolve(); },100);
}).then(() => {
return request(sql);
});
}
}
function updateTeam(abbr,attrs,vals) {
return update('teams',`abbr = '${abbr}'`,attrs,vals);
}
function update(d,w,attrs,vals) {
//return new Promise(function(resolve, reject) {
//con.connect(function(err) {
var sql = `UPDATE ${d} SET `;
for (let i = 0; i < attrs.length; i++) {
let val = vals[i];
let attr = attrs[i];
if (typeof val == 'number' || val == null) {
sql += `${attr} = ${con.escape(val)}`;
} else if (typeof val == 'boolean') {
sql += `${attr} = ${Number(val)}`;
} else if (typeof val == 'object') {
sql += `${attr} = ${con.escape(JSON.stringify(val))}`;
} else {
sql += `${attr} = ${con.escape(val)}`;
}
if (i != attrs.length - 1) {
sql += ',';
}
}
if (d == 'teams') {
sql += ',activated=true';
}
sql += ` WHERE ${w}`;
return request(sql);
}
const clubs = {};
clubs.getTeamFromAbbr = abbr => {
return request(`SELECT * FROM teams WHERE Abbr = ${con.escape(abbr)}`).then(list => {
return list[0];
});
}
clubs.getTeamFromMascot = (mascot) => request(`SELECT * FROM teams WHERE mascot = ${con.escape(mascot)}`).then(list => {
return list[0];
})
clubs.getAllTeams = () => request('SELECT * FROM teams');
clubs.getAllTeamsByConf = conf => {
var z = con.escape(conf.toUpperCase()).replace("'", '').replace("'", '');
return request(`SELECT * FROM teams WHERE DIVISION LIKE '${z}%'`);
}
clubs.getAccountFromToken = token => request('SELECT * FROM teams').then(list => {
let matches = [];
for (let team of list) {
let tokenSalt = JSON.parse(team.tokenSalt);
let tokenHash = JSON.parse(team.tokenHash);
for (let i = 0; i < tokenSalt.length; i++) {
if (crypto.createHash('sha512').update(token + tokenSalt[i]).digest('hex') == tokenHash[i]) {
matches.push(team);
break;
}
}
}
if (matches.length == 1) {
return matches[0];
} else {
return;
}
});
clubs.deleteToken = token => clubs.getAccountFromToken(token).then(acc => {
if (!acc) {
return false;
}
var allSalts = JSON.parse(acc.tokenSalt);
var allHashes = JSON.parse(acc.tokenHash);
for (let i = 0; i < allHashes.length; i++) {
if (crypto.createHash('sha512').update(token + allSalts[i]).digest('hex') == allHashes[i]) {
allSalts[i] = undefined;
allHashes[i] = undefined;
}
}
allSalts = clean(allSalts);
allHashes = clean(allHashes);
return updateTeam(acc.abbr, ['tokenSalt','tokenHash'], [allSalts,allHashes]).then(function () {
return true;
});
})
clubs.getOpponentsFromGame = game => request('SELECT * FROM teams').then(list => { //has singular game
let exp = {};
for (let team of list) {
if (team.abbr == game.away) {
exp.away = team;
} else if (team.abbr == game.home) {
exp.home = team;
}
}
return exp;
})
clubs.getAttrFromAbbr = (abbr,attr) => {
if (abbr == 'CFC' || abbr == 'NFC') {
return abbr;
}
for (let x of Teams.getTeams()) {
if (x.abbr == abbr) {
return x[attr];
}
}
}
clubs.clean = str => {
if (typeof str == 'object') {
str = str.mascot;
}
return str.toLowerCase().replace(/\s/g,'');
}
clubs.getAssets = abbr => {
return clubs.getTeamFromAbbr(abbr).then(team => {
roster = JSON.parse(team.roster);
return athletes.getAllPlayers().then(players => {
var active = [];
for (let p of players) {
if (roster.includes(p.id)) {
active.push(p);
}
}
return selections.getTeamPicks(abbr).then(picks => {
let unused = [];
for (let p of picks) {
if (p.pick > currentPick) {
unused.push(p);
}
}
return {players:active,picks:unused};
});
});
});
}
clubs.getGamesLeft = abbr => {
return request(`SELECT * FROM games WHERE (away=${con.escape(abbr)} OR home=${con.escape(abbr)}) AND week <> 0 AND week < 21 AND status='upcoming'`).then(list => {
return list.length;
});
}
clubs.getPlayoffs = () => {
return clubs.getAllTeams().then(teams => {
return contests.getAllGames().then(games => {
for (let t of teams) {
t.clean = t.mascot.toLowerCase().replace(/\s/g,'');
}
let confs = {cfc:teams.slice(0,20),nfc:teams.slice(20,40)};
let order = {cfc:[],nfc:[]};
let divs = {};
for (let c in confs) {
for (let t of confs[c]) {
if (t.w + t.l != 0) {
t.record = t.w / (t.w + t.l);
} else {
t.record = 0.01;
}
if (t.dw + t.dl != 0) {
t.divRecord = t.dw / (t.dw + t.dl);
} else {
t.divRecord = 0.01;
}
}
confs[c].sort(sortTeams(games));
let leader = 0;
let index = 5;
for (let t of confs[c]) {
let cd = t.division.toLowerCase().replace(/\s/g,'');
if (!divs[cd]) { //no team yet in div; first in div
order[c][leader] = t;
leader++;
divs[cd] = [];
} else { //div leader already in
order[c][index] = t;
index++;
}
divs[cd].push(t);
}
for (let i = 0; i < order[c].length; i++) {
order[c][i].seed = i + 1;
order[c][i].flag = '';
}
}
for (let n in divs) {
let div = divs[n];
if (checkClinch(div[0],div.slice(1,4),games)) {
div[0].flag = 'xy';
} else if (checkClinch(div[0],confs[n.substring(0,3)].slice(8,20),games)) {
div[0].flag = 'x';
} //end div leader
for (let i = 1; i < 4; i++) {
if (checkClinch(div[i],confs[n.substring(0,3)].slice(8,20),games)) {
div[i].flag = 'x';
} else if (checkElim(div[i],confs[n.substring(0,3)].slice(5,8).concat(div[0]),games)) { //cannot win div and cannot beat current wc's
div[i].flag = 'e';
}
}
}
return {confs:order,divs:divs};
});
});
}
clubs.breakdown = (roster,acc,ws) => {
var spending = 0;
for (let i = 0, p = roster[0]; i < roster.length; i++, p = roster[i]) {
let denom = (roster.length==1)?1:roster.length - 1;
p.color = `hsl(${Math.round(100 + 200 / denom * i)},70%,50%)`;
p.type = 'player';
p.name = `${p.fName} ${p.lName} <span class="num">(${p.pos} #${p.id})</span>`;
spending += p.salary;
}
var investment = 0;
for (let d of JSON.parse(acc.delegates)) {
investment += d.investment;
}
spending += investment;
var dead = acc.dead;
spending += dead;
var space = 200000 - spending;
var breakdown = [{name:'Cap Space',salary:space,color:'#888'}];
breakdown = breakdown.concat(roster);
breakdown.push({name:'Delegate Investment',salary:investment,color:'chocolate'});
breakdown.push({name:'Dead Cap',salary:dead,color:'sienna'});
if (space < 0) {
breakdown[0].color = 'red';
breakdown[0].perc = 1000 / (spending + 1000) * 100;
for (let i = 1; i < breakdown.length; i++) {
breakdown[i].perc = breakdown[i].salary / (spending + 1000) * 100;
}
} else {
for (let b of breakdown) {
b.perc = b.salary / 2000;
}
}
for (let b of breakdown) {
b.frac = b.salary / 2000;
b.render = renderAmount(b.salary);
}
let res = {method:'brokenDown',spending:spending,breakdown:breakdown};
if (ws == 'all') {
return announce(acc.abbr,res);
} else if (ws) {
return ws.send(JSON.stringify(res));
}
return res;
}
clubs.nextGame = abbr => {
return request(`SELECT * FROM games WHERE (away=${con.escape(abbr)} OR home=${con.escape(abbr)}) AND status='upcoming'`).then(list => {
if (list.length == 0) {
return {oppo:'LEA'};
}
list.sort((a,b) => { return new Date(a.schedule).getTime() - new Date(b.schedule).getTime() } );
if (list[0].away == abbr) {
list[0].oppo = list[0].home;
} else {
list[0].oppo = list[0].away;
}
return list[0];
});
}
const athletes = {};
athletes.getPlayers = list => {
if (list.length == 0) {
return new Promise(function(resolve) {
resolve();
}).then(function() {
return [];
});
}
if (typeof list == 'string') {
list = JSON.parse(list);
}
var sql = 'SELECT * FROM players WHERE ';
for (let i = 0, p = list[0]; i < list.length; i++, p = list[i]) {
sql += `id=${con.escape(p)}`;
if (i == list.length - 1) {
sql += ';'
} else {
sql += ' OR ';
}
}
return request(sql);
}
athletes.getAllPlayers = () => {
return request('SELECT * FROM players');
}
athletes.getPlayerFromId = id => {
return request(`SELECT * FROM players where id=${con.escape(id)}`).then(list => {
return list[0];
});
}
athletes.getRosterFromPlayers = (list,abbr) => {
var exp = [];
for (let p of list) {
if (p.team == abbr) {
exp.push(p);
}
}
return exp;
}
athletes.getPlayersByPos = pos => {
return request(`SELECT * FROM players where pos=${con.escape(pos)}`);
}
athletes.getPlayersInDraft = () => {
return request('SELECT * FROM players WHERE draftable=true');
}
athletes.getDraftablePlayers = () => {
return request('SELECT * FROM players WHERE draftable=true AND drafted=false');
}
athletes.getPlayerFromList = (id,list) => {
for (let p of list) {
if (p.id == id) {
return p;
}
}
}
athletes.searchPlayers = (list,pos,id,team,base,guar,name,draftable,a,b,c,d) => {
//return athletes.getAllPlayers().then(players => {
let matches = [];
for (let p of list) {
if (typeof id == 'string') {
if (p.id.toLowerCase().replace(/\s/g,'').indexOf(id.toLowerCase().replace(/\s/g,'')) == -1) {
continue;
}
}
if (pos != p.pos && pos != undefined) {
continue;
}
if (team != p.team && team != undefined && team != 'ANY') {
continue;
}
if (p.base > base && base != undefined) {
continue;
}
if (p.guar > guar && guar != undefined) {
continue;
}
if (typeof name == 'string') {
let n = p.fName + p.lName;
if (n.toLowerCase().replace(/\s/g,'').indexOf(name.toLowerCase().replace(/\s/g,'')) == -1) {
continue;
}
}
if (Number(draftable) != p.draftable && draftable != undefined && draftable != 'ANY') {
continue;
}
let stats = [p.stat1,p.stat2,p.stat3,p.stat4];
for (let s of stats) {
if (typeof s == 'string') {
s = JSON.parse(s);
}
}
let reqs = [a,b,c,d];
let sds = Teams.getStatsByPos()[p.pos];
let match = true;
for (let i = 0, s = stats[0], r = reqs[0]; i < stats.length; i++, s = stats[i], r = reqs[i]) {
if (typeof s == 'string') {
s = JSON.parse(s);
}
if (s == undefined) {
match = false;
break;
}
let mean = s.m;
if (sds[i].flip) {
mean *= -1;
r = -r;
}
if (mean < r) {
match = false;
break;
}
}
if (match) {
matches.push(p);
}
}
return expandPlayers(matches);
//});
}
athletes.signCheapestOfPos = (abbr,pos) => {
return clubs.getTeamFromAbbr(abbr).then(acc => {
return request(`SELECT * FROM players WHERE team='UFA' AND pos='${pos}' AND draftable=0;`).then(players => {
//SELECT * FROM players WHERE team='UFA' AND pos='QB' AND draftable=0;
let w = getCurrentWeek(), wr;
if (w == 0) {
wr = 20;
} else if (w < 21) {
wr = 21 - w;
} else {
wr = 0;
}
for (let p of players) {
p.salary = wr * p.base + p.guar;
}
players.sort((a,b) => { return a.salary - b.salary; });
let cheapPlayers = [];
console.log('cheap pos',pos,players.length);
let cheapSalary = players[0].salary;
for (let p of players) {
if (p.salary > cheapSalary + 200) {
break;
}
cheapPlayers.push(p);
}
let random = cheapPlayers[Math.floor(Math.random() * cheapPlayers.length)];
let roster = JSON.parse(acc.roster).concat(random.id);
let sql = `UPDATE teams SET roster='${JSON.stringify(roster)}' WHERE abbr='${acc.abbr}';`;
return clubs.getGamesLeft(acc.abbr).then(left => {
sql += `UPDATE players SET team='${acc.abbr}',weekSigned=${getCurrentWeek()},duration=${left} WHERE id='${random.id}';`;
console.log(sql);
return request(sql);
});
});
});
}
const messages = {};
messages.getMessages = (user,other) => {
if (other == 'ALE') {
return request('SELECT * FROM chat WHERE sentFrom="ALE"');
}
return request(`SELECT * FROM chat WHERE (sentFrom=${con.escape(user)} AND sentTo=${con.escape(other)}) OR (sentFrom=${con.escape(other)} AND sentTo=${con.escape(user)});`);
}
messages.getAll = abbr => {
return request(`SELECT * FROM chat WHERE sentTo=${con.escape(abbr)} OR sentFrom=${con.escape(abbr)}`);
}
const tiempo = {};
tiempo.getFormatTime = (utc,tz,use) => {
let zone = tiempo.getTime(utc,tz);
if (zone.error) {
return 'Time Error';
}
return `${zone.weekdayShort} ${zone.day} ${zone.monthShort} ${tiempo.getFormatHour(utc,tz,use)}`;
}
tiempo.getFormatDayAndHour = (utc,tz,use) => {
let zone = tiempo.getTime(utc,tz);
if (zone.error) {
return 'Time Error';
}
return `${zone.weekdayShort} ${tiempo.getFormatHour(utc,tz,use)}`;
}
tiempo.getFormatHour = (utc,tz,use) => {
let zone = tiempo.getTime(utc,tz);
if (zone.error) {
return 'XX:XX';
}
var m = zone.minute;
if (m < 10) {
m = `0${m}`;
}
if (zone.hour == 0) {
var h = 12;
var r = 'A';
} else if (zone.hour < 12) {
var h = zone.hour;
var r = 'A';
} else if (zone.hour == 12) {
var h = 12;
var r = 'P';
} else {
var h = zone.hour - 12;
var r = 'P';
}
if (use === false) {
return `${h}${r}`;
}
return `${h}:${m}${r}`;
}
tiempo.getTime = (utc,tz) => {
if (!utc) {
let d = new Date();
utc = d.toISOString();
}
if (typeof utc == 'object') {
utc = utc.toISOString();
}
if (!tz) {
tz = 'utc';
}
var time = DateTime.fromISO(utc, { zone: 'utc' });
if (!time.isValid) {
return {error:true};
}
var zone = time.setZone(tz);
if (!zone.isValid) {
return {error:true};
}
return zone;
}
const contests = {}
contests.getWeek = num => {
return request(`SELECT * FROM games WHERE week=${num}`);
}
contests.getAllGames = () => {
return request('SELECT * FROM games');
}
contests.getPlayoffGames = () => {
return request('SELECT * FROM games WHERE week > 20');
}
contests.getGamesByTeam = abbr => {
return request(`SELECT * FROM games WHERE away=${con.escape(abbr)} OR home=${con.escape(abbr)}`);
}
contests.getTopEight = (games,teams) => {
if (games.length < 9) {
return games;
}
for (let g of games) {
let d = new Date(g.schedule);
g.unix = d.getTime();
}
games.sort((a,b) => { //order by time
return a.unix - b.unix;
});
for (var l = 0; l < games.length; l++) {
if (games[l].status == 'upcoming') {
break;
}
}
for (let i = l; i < games.length; i++) {
games[i].index = i - l;
}
for (let g of games) {
for (let t of teams) {
if (t.abbr == g.away) {
g.awayMascot = t.mascot;
g.awayClean = t.mascot.toLowerCase().replace(/\s/g,'');
g.awayRecord = `(${t.w}-${t.l}) | (${t.dw}-${t.dl})`;
}
if (t.abbr == g.home) {
g.homeMascot = t.mascot;
g.homeClean = t.mascot.toLowerCase().replace(/\s/g,'');
g.homeRecord = `(${t.w}-${t.l}) | (${t.dw}-${t.dl})`;
}
if (g.awayMascot != undefined && g.homeMascot != undefined) {
break;
}
}
if (g.status == 'ongoing') {
g.score = 1000;
} else { //games is upcoming or final
let aRecord;
let hRecord;
for (let t of teams) {
if (t.abbr == g.away) {
if (t.w + t.l == 0) {
aRecord = 0.01;
} else {
aRecord = t.w / (t.w + t.l);
}
}
if (t.abbr == g.home) {
if (t.w + t.l == 0) {
hRecord = 0.01;
} else {
hRecord = t.w / (t.w + t.l);
}
}
if (aRecord != undefined && hRecord != undefined) {
break;
}
}
let mult = 1;
if (aRecord > 0.75 && hRecord > 0.75) {
mult = 1.5;
} else if (aRecord > 0.5 && hRecord > 0.5) {
mult = 1.25;
} else if (aRecord < 0.3 && hRecord < 0.3) {
mult = 0.75;
}
if (g.status == 'upcoming') {
g.score = (100 + (20 - g.index) * 5) * mult;
} else { //final
g.score = (10 - (Math.abs(g.awayScore - g.homeScore) / 5)) * 15 * mult;
}
}
if (g.primetime) {
g.score *= 2.5;
}
}
games.sort((a,b) => {
return b.score - a.score;
});
return games.slice(0,8);
}
const selections = {};
selections.getAllPicks = () => {
return request('SELECT * FROM draft');
}
selections.getNthPick = num => {
return request(`SELECT * FROM draft WHERE pick=${num}`).then(x => {
if (x.length == 1) {
return x[0];
} else {
return {team:'LEA',trades:'[]',player:null,pick:-1};
}
});
}
selections.getNthRound = num => {
return request(`SELECT * FROM draft LIMIT ${num * 40},40`);
}
selections.getNextTwentyFromWhole = sxns => {
let exp = [];
for (let i = currentPick + 1; i < currentPick + 21; i++ ) {
exp.push({abbr:sxns[i].team,index:i + 1});
}
return exp;
}
selections.getTeamPicks = abbr => {
return request(`SELECT * FROM draft WHERE team=${con.escape(abbr)}`);
}
selections.getInvolvedPicks = abbr => {
var a = con.escape(abbr);
a = a.substring(1,a.length - 1);
return request(`SELECT * FROM draft WHERE JSON_CONTAINS(trades,'"${a}"','$');`);
}
selections.getCurrentPick = () => {
return selections.getNthPick(currentPick);
}
selections.getThree = () => {
if (currentPick == -1) {
return new Promise(function(resolve) {
resolve();
}).then(function() {
return ['Trading opens 1 Sep 12:00P MDT','Draft is 3 Sep 6:00P-8:00P MDT','Preseason starts 7 Sep 2:00P MDT'];
});
}
if (currentPick > 319) {
return new Promise(function(resolve) {
resolve();
}).then(function() {
return ['The draft is now over','You will be redirected soon','Good luck in preseason'];
});
}
return selections.getCurrentPick().then(pick => {
return selections.getTeamPicks(pick.team).then(picks => {
let strs = [];
let found = false;
let next;
for (let i = 0, p = picks[0]; i < picks.length; i++, p = picks[i]) {
let f = roundAndPick(p.pick);
if (p.player !== null) {
strs.push(`Drafted ${idToPos(p.player)} #${p.player} at RD ${f.r} PK ${f.p}`);
} else {
if (!found) {
found = true;
next = i;
}
strs.push(`Has RD ${f.r} PK ${f.p} (${ordinal(p.pick + 1)} Overall)`);
}
}
if (next == undefined || next < 2) {
next = 2;
}
return strs.slice(next - 2,next + 1);
});
});
}
selections.getPicks = list => {
if (list.length == 0) {
return new Promise(function(resolve) {
resolve();
}).then(function() {
return [];
});
}
if (typeof list == 'string') {
list = JSON.parse(list);
}
var sql = 'SELECT * FROM draft WHERE ';
for (let i = 0, p = list[0]; i < list.length; i++, p = list[i]) {
sql += `pick=${p}`;
if (i == list.length - 1) {
sql += ';'
} else {
sql += ' OR ';
}
}
return request(sql);
}
const deals = {};
deals.getInvolvedTrades = abbr => {
return request(`SELECT * FROM trades WHERE (fromTeam=${con.escape(abbr)} AND fromShow=true) OR (toTeam=${con.escape(abbr)} AND toShow=true)`);
}
deals.getAll = () => {
return request('SELECT * FROM trades');
}
deals.getTradeFromId = id => {
return request(`SELECT * FROM trades WHERE id=${con.escape(id)}`).then(list => { return list[0]; });
}
const news = {};
news.getInvolvedStories = abbr => {
var a = con.escape(abbr);
a = a.substring(1,a.length - 1);
return request(`SELECT * FROM news WHERE JSON_CONTAINS(teams,'"${a}"','$');`);
}
news.getMostRecent = num => {
return request('SELECT * FROM news').then(list => {
list.sort((a,b) => { return new Date(b.time).getTime() - new Date(a.time).getTime() });
return list.slice(0,num);
});
}
news.newStory = (abbrs,story) => {
let s = new Date().toISOString().replace('T',' ').substring(0,19);
let t = JSON.stringify(abbrs);
console.log('new story',`INSERT INTO news (teams,time,story) VALUES ('${t}','${s}','${story}');`);
request(`INSERT INTO news (teams,time,story) VALUES ('${t}','${s}','${story}');`);
}
const line = {};
line.trade = '2021-11-16T19:00:00Z';
line.draft = '2021-09-04T00:00:00Z';
line.fa = '2021-09-10T18:00:00Z';
line.release = '2022-01-22T19:00:00Z';
line.season = '2021-09-01T18:00:00Z';
line.sign = '2021-12-14T19:00:00Z';
line.firstGame = '2021-09-10T22:00:00Z';
line.championship = '2022-02-05T19:00:00Z';
const span = {};
span.canTrade = () => {
if (new Date(line.trade).getTime() > new Date().getTime()) {
return true;
}
return false;
}
span.canDraft = () => {
if (new Date(line.draft).getTime() > new Date().getTime()) {
return true;
}
return false;
}
span.canRelease = () => {
if (new Date(line.release).getTime() > new Date().getTime()) {
return true;
}
return false;
}
span.canSign = () => {
if (new Date(line.sign).getTime() > new Date().getTime()) {
return true;
}
return false;
}
span.faPeriod = () => {
if (new Date(line.fa).getTime() > new Date().getTime()) {
return true;
}
return false;
}
span.inSeason = () => {
if (new Date(line.season).getTime() < new Date().getTime()) {
return true;
}
return false;
}
//game sim
const passRoutes = {};
passRoutes.go = (player,speed) => {
return {x:speed/10,y:0};
}
passRoutes.post = (player,speed) => {
if (player.x < game.los + 5) {
return {x:speed/10,y:0};
} else {
let v = speed/10/Math.sqrt(2);
if (player.iy < 25) {
return {x:v,y:v};
}
return {x:v,y:-v};
}
}
passRoutes.slant = (player,speed) => {
if (player.x < game.los + 2) {
return {x:speed/10,y:0};
} else {
let v = speed/10;
if (player.iy < 25) {
return {x:v/2,y:v*Math.sqrt(3)/2};
}
return {x:v/2,y:-v*Math.sqrt(3)/2};
}
}
passRoutes.corner = (player,speed) => {
if (player.x < game.los + 5) {
return {x:speed/10,y:0};
} else {
let v = speed/10/Math.sqrt(2);
if (player.iy < 25) {
return {x:v,y:-v};
}
return {x:v,y:v};
}
}
passRoutes.out = (player,speed) => {
if (player.x < game.los + 5) {
return {x:speed/10,y:0};
} else {
if (player.iy < 25) {
return {x:0,y:-speed/10};
}
return {x:0,y:speed/10};
}
}
passRoutes.in = (player,speed) => {
if (player.x < game.los + 5) {
return {x:speed/10,y:0};
} else {
if (player.iy < 25) {
return {x:0,y:speed/10};
}
return {x:0,y:-speed/10};
}
}
const tiring = {recep:0.5,speed:6,elus:0.2};
var game = {};
const match = {};
var gameSockets = [];
var gameActive = false;
match.verifyRoster = (away,home) => {
clubs.getTeamFromAbbr(away).then(awayTeam => {
clubs.getTeamFromAbbr(home).then(homeTeam => {
let valid = true;
let awayPos = {QB:0,RB:0,WR:0,TE:0,OL:0,DL:0,LB:0,CB:0,S:0,K:0,P:0};
let homePos = {QB:0,RB:0,WR:0,TE:0,OL:0,DL:0,LB:0,CB:0,S:0,K:0,P:0};
for (let p of JSON.parse(awayTeam.roster)) {
awayPos[idToPos(p)]++;
}
for (let p of JSON.parse(homeTeam.roster)) {
homePos[idToPos(p)]++;
}
let needed = {QB:1,RB:1,WR:2,TE:1,OL:2,DL:2,LB:1,CB:3,S:1,K:1,P:1};
for (let a in needed) {
if (awayPos[a] < needed[a]) {
valid = false;
athletes.signCheapestOfPos(away,a).then(() => {
match.verifyRoster(away,home);
});
break;
}
}
for (let a in needed) {
if (homePos[a] < needed[a]) {
valid = false;
athletes.signCheapestOfPos(home,a).then(() => {
match.verifyRoster(away,home);
});
break;
}
}
if (valid) {
match.verifyPlays(away,home);
}
});
});
}
match.verifyPlays = (away,home) => {
clubs.getTeamFromAbbr(away).then(awayTeam => {
clubs.getTeamFromAbbr(home).then(homeTeam => {
let awayOffPlays = JSON.parse(awayTeam.offPlays);
let homeOffPlays = JSON.parse(homeTeam.offPlays);
let awayDefPlays = JSON.parse(awayTeam.defPlays);
let homeDefPlays = JSON.parse(homeTeam.defPlays);
let awaySpePlays = JSON.parse(awayTeam.spePlays);
let homeSpePlays = JSON.parse(homeTeam.spePlays);
let awayRoster = JSON.parse(awayTeam.roster);
let homeRoster = JSON.parse(homeTeam.roster);
let awayChange = {off:false,def:false,spe:false};
let homeChange = {off:false,def:false,spe:false};
let awayCase = {'1s':false,'1m':false,'1l':false,'1e':false,'2s':false,'2m':false,'2l':false,'2e':false,'3s':false,'3m':false,'3l':false,'3e':false,'4s':false,'4m':false,'4l':false,'4e':false,'2p':false};
let homeCase = {'1s':false,'1m':false,'1l':false,'1e':false,'2s':false,'2m':false,'2l':false,'2e':false,'3s':false,'3m':false,'3l':false,'3e':false,'4s':false,'4m':false,'4l':false,'4e':false,'2p':false};
let sql = '';
for (let attr in awayOffPlays) {
let playCheck = JSON.stringify(awayOffPlays[attr]);
let play = awayOffPlays[attr];
for (let c of play.cases) {
awayCase[c] = true;
}
if (attr.indexOf('pass') != -1) { //is passing play
for (let a of ['wr1r','wr2r','ter']) {
if (!['go','slant','in','out','post','corner'].includes(play[a])) {
awayChange.off = true;
play[a] = 'go';
}
}
let ordinals = {first:false,second:false,third:false};
let recs = {wr1:false,wr2:false,te:false};
for (let ord in ordinals) {
if (['wr1','wr2','te'].includes(play[ord])) {
ordinals[ord] = true;
}
for (let q of ['wr1','wr2','te']) {
if (play[ord] == q) {
recs[q] = true;
break;
}
}
}
if (JSON.stringify(ordinals).indexOf('false') != -1) {
awayChange.off = true;
for (let ord in ordinals) {
if (ordinals[ord] == false) {
for (let rec in recs) {
if (recs[rec] == false) {
play[ord] = rec;
ordinals[ord] = true;
recs[rec] = true;
}
}
}
}
}
}
for (let o of [{a:'qb',p:'QB'},{a:'rb',p:'RB'},{a:'wr1',p:'WR'},{a:'wr2',p:'WR'},{a:'te',p:'TE'},{a:'ol1',p:'OL'},{a:'ol2',p:'OL'}]) {
playCheck = JSON.stringify(awayOffPlays[attr]);
if (play[o.a] == '' || play[o.a] == undefined || play[o.a] == null || !awayRoster.includes(play[o.a])) {
awayChange.off = true;
for (let id of awayRoster) {
if (idToPos(id) == o.p && playCheck.indexOf(id) == -1) { //player right pos and not in play
play[o.a] = id;
break;
}
}
}
}
}
for (let c in awayCase) {
if (awayCase[c] == false) {
awayChange.off = true;
awayOffPlays.pass1.cases.push(c);
}
}
for (let attr in awayDefPlays) {
let playCheck = JSON.stringify(awayDefPlays[attr]);
let play = awayDefPlays[attr];
for (let o of [{a:'dl1',p:'DL'},{a:'dl2',p:'DL'},{a:'lb',p:'LB'},{a:'cb1',p:'CB'},{a:'cb2',p:'CB'},{a:'cb3',p:'CB'},{a:'s',p:'S'}]) {
playCheck = JSON.stringify(awayDefPlays[attr]);
if (play[o.a] == '' || play[o.a] == undefined || play[o.a] == null || !awayRoster.includes(play[o.a])) {
awayChange.def = true;
for (let id of awayRoster) {
if (idToPos(id) == o.p && playCheck.indexOf(id) == -1) { //player right pos and not in play
play[o.a] = id;
break;
}
}
}
}
}
for (let attr in awaySpePlays) {
let playCheck = JSON.stringify(awaySpePlays[attr]);
let play = awaySpePlays[attr];
for (let pos in play) {
playCheck = JSON.stringify(awaySpePlays[attr]);
console.log(play[pos],'pos',pos);
if (play[pos] == '' || play[pos] == undefined || play[pos] == null || !awayRoster.includes(play[pos])) {
console.log('get',pos);
awayChange.spe = true;
for (let id of awayRoster) {
if (idToPos(id) == pos.toUpperCase() && playCheck.indexOf(id) == -1) { //player right pos and not in play
play[pos] = id;