-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
3740 lines (3134 loc) · 147 KB
/
app.py
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
from ast import alias
from flask import Flask, flash, redirect, render_template, request, session, url_for, Markup, send_file
from flask_session import Session
from werkzeug.utils import secure_filename
#from flask.ext.session import Session
import logging
import requests
from passlib.apps import custom_app_context as pwd_context
import sys
import random
import json
import config ## moved to db_accessor
from db_accessor.db_accessor import db, db2
import sched, time
from collections import OrderedDict, defaultdict
from datetime import datetime, timedelta, date
import re
import os
from operator import itemgetter, attrgetter
from functools import wraps
from espnapi import get_espn_scores, get_espn_score_by_qtr, get_espn_summary_single_game, get_ncaab_games
from espn_every_minute.get_espn_score import get_espn_every_min_scores
from funnel_helper import elimination_check
from email_helper import send_email
from gd_email_helper import send_gd_email
from email_validator import validate_email, EmailNotValidError
UPLOAD_FOLDER = 'static'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
path = '/home/dheslin/dailybox'
dev_path = '/home/dheslin/bygtech/dailybox'
print(f"OS instance PATH {os.path.dirname(app.instance_path)}")
print(f"OS root PATH {os.path.dirname(app.root_path)}")
print(f"OS CWD {os.getcwd()}")
if config.env == 'prod' and os.getcwd() != path:
os.chdir(path)
elif config.env == 'dev' and os.getcwd() != dev_path:
os.chdir(dev_path)
print(f"OS CWD after: {os.getcwd()}")
logging.basicConfig(filename="byg.log", format="%(asctime)s %(levelname)-8s %(message)s", level=logging.DEBUG, datefmt="%Y-%m-%d %H:%M:%S")
logging.info(f"OS instance PATH {os.path.dirname(app.instance_path)}")
logging.info(f"OS root PATH {os.path.dirname(app.root_path)}")
logging.info(f"OS CWD {os.getcwd()}")
# ensure responses aren't caches
if app.config["DEBUG"]:
print("in app.config debug")
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# configure session to use filesystem (instead of signed cookies)
app.config["SESSION_PERMANENT"] = True
app.config["SESSION_TYPE"] = "filesystem"
app.permanent_session_lifetime = timedelta(days=7)
Session(app)
# Global variables
PAY_TYPE_ID = {
'four_qtr' : 1,
'single' : 2,
'every_score' : 3,
'touch' : 4,
'ten_man' : 5,
'satellite' : 6,
'ten_man_final_reverse': 7,
'every_minute': 8,
'ten_man_final_half': 9
}
BOX_TYPE_ID = {
'dailybox' : 1,
'custom' : 2,
'nutcracker' : 3,
'private' : 4
}
EMOJIS = {
'thumbs_up': '\uD83D\uDC4D'.encode('utf-16', 'surrogatepass').decode('utf-16'),
'thumbs_down': '\uD83D\uDC4E'.encode('utf-16', 'surrogatepass').decode('utf-16'),
'middle_finger': '\uD83D\uDD95'.encode('utf-16', 'surrogatepass').decode('utf-16'),
'check': '\u2714',
'ex': '\u274c',
'crown': '\uD83C\uDFC6'.encode('utf-16', 'surrogatepass').decode('utf-16')
}
# mysql> select * from pay_type;
# +-------------+--------------------------+
# | pay_type_id | description |
# +-------------+--------------------------+
# | 1 | 4 Qtr Payout 10/30/10/50 |
# | 2 | Single Payout |
# | 3 | Every Score |
# | 4 | Touch Box |
# | 5 | 10-Man |
# | 6 | Satellite
# | 7 | 10-Man Final/Reverse 75/25
# | 8 | Every Minute |
# | 9 | 10-Man Final/Half 75/2 |
# +-------------+--------------------------+
def apology(message, code=400):
"""Renders message as an apology to user."""
return render_template("apology.html", top=code, bottom=message, code=code)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("userid") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("is_admin") == 0:
return redirect("/")
return f(*args, **kwargs)
return decorated_function
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route("/remove_image", methods=["POST", "GET"])
@login_required
def remove_image():
userid = request.args['userid']
remove_query = "UPDATE users SET image = NULL WHERE userid = %s;"
db2(remove_query, (userid,))
return redirect(url_for('user_details'))
@app.route('/upload_file', methods=["POST", "GET"])
@login_required
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
user = int(request.form.get('user'))
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
user_query = "UPDATE users SET image = %s WHERE userid = %s;"
db2(user_query, (file.filename, user))
return redirect(url_for('user_details', name=filename))
userid = request.args['userid']
print(userid)
return '''
<!doctype html>
<title>Upload new image to display in BOX selection</title>
<h1>Upload new File</h1>
<p>All of your boxes will display this image if you upload</p>
<p>Only .png, .jpg, .jpeg, .gif filetypes are supported</p>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
<input type=hidden value=''' + userid + ''' name=user>
</form>
'''
def box_string():
s = ''
for x in range(100):
s += 'box' + str(x) + ", "
s = s[:-2] # chop last space and ,
return s
def assign_xy():
n = [x for x in range(10)]
random.shuffle(n)
return(n)
# create json string of assigned x/y numbers
def assign_numbers(boxid):
x_nums = assign_xy()
y_nums = assign_xy()
x_string = '{'
y_string = '{'
for i in range(10):
x_string += '"' + str(i) + '"' + ':' + str(x_nums[i]) + ','
y_string += '"' + str(i) + '"' + ':' + str(y_nums[i]) + ','
x_string = x_string[:-1] # chop off last ,
y_string = y_string[:-1]
x_string += '}'
y_string += '}'
s = "INSERT INTO boxnums(boxid, x, y) VALUES({}, '{}', '{}');".format(boxid, x_string, y_string)
db(s)
def count_avail(boxid):
s = "SELECT * FROM boxes WHERE boxid = {};".format(boxid)
boxes = db(s)[0]
count = 0
for x in boxes[:len(boxes)-101:-1]:
if x == 1 or x == 0:
count += 1
return count
def payout_calc(pay_type, fee):
'''
mysql> select * from pay_type;
+-------------+--------------------------+
| pay_type_id | description |
+-------------+--------------------------+
| 1 | 4 Qtr Payout 10/30/10/50 |
| 2 | Single Payout |
| 3 | Every Score |
| 4 | Touch Box |
| 5 | 10-Man |
| 6 | Satellite
| 7 | 10-Man Final/Reverse 75/25
| 8 | Every Minute |
| 9 | 10-man Final/Half 75/25 |
+-------------+--------------------------+
'''
if pay_type == PAY_TYPE_ID['four_qtr']:
a = fee * 10
b = fee * 20
c = fee * 60
s = '1st {} / 2nd {} / 3rd {} / Final {}'.format(a, b, a, c)
elif pay_type == PAY_TYPE_ID['single']:
s = 'Single Winner: {}'.format(fee * 100)
elif pay_type == PAY_TYPE_ID['ten_man']:
s = 'Single Winner 10 Man: {}'.format(fee * 10)
elif pay_type == PAY_TYPE_ID['satellite']:
s = 'Satellite'
elif pay_type == PAY_TYPE_ID['ten_man_final_reverse']:
s = 'Final: {} / Reverse Final: {}'.format(int((fee * 10) *.75), int((fee * 10) *.25))
elif pay_type == PAY_TYPE_ID['ten_man_final_half']:
s = 'Final: {} / Half: {}'.format(int((fee * 10) *.75), int((fee * 10) *.25))
elif pay_type == PAY_TYPE_ID['every_score']:
s = Markup('Every score wins {} up to 27 scores. Final gets remainder after all payouts, min {}. <br>Reverse final wins min {} / max {} (see TW email). Anything touching reverse or final wins {}.'.format(fee * 3, fee * 10, fee, fee * 10, fee))
elif pay_type == PAY_TYPE_ID['every_minute']:
s = Markup(f'Every minute you are winning {int(fee*1.5)} - Final and Reverse Final {int(fee*5)}')
else:
s = 'Payouts for Game Type not yet supported' # will add later date
return s
def calc_winner(boxid): # all this does is strip all beginning digits from the scores
# find pay_type
pt = "SELECT pay_type FROM boxes WHERE boxid = {};".format(boxid)
pay_type = db(pt)[0][0]
print(pay_type)
winner_list = []
if pay_type == PAY_TYPE_ID['single'] or pay_type == PAY_TYPE_ID['ten_man'] or pay_type == PAY_TYPE_ID['satellite'] or pay_type == PAY_TYPE_ID['ten_man_final_reverse']: # final only
s = "SELECT x4, y4 FROM scores WHERE boxid = {};".format(boxid)
scores = db(s)# [-1:][0] # always take the last in list
if len(scores) == 0:
return winner_list
print(scores[-1:][0])
score = scores[-1:][0]
if score[0] > 9:
winner_list.append(str(score[0])[-1:])
else:
winner_list.append(str(score[0]))
if score[1] > 9:
winner_list.append(str(score[1])[-1:])
else:
winner_list.append(str(score[1]))
elif pay_type == PAY_TYPE_ID['four_qtr']: # all 4 qtrs
s = "SELECT x1, y1, x2, y2, x3, y3, x4, y4 FROM scores WHERE boxid = {};".format(boxid)
scores = db(s)
if len(scores) == 0:
return winner_list
else:
for score in scores[-1:][0]:
print(f"score in calc {score}")
if score is not None:
if score > 9:
winner_list.append(str(score)[-1:])
else:
winner_list.append(str(score))
# pay_type == 3 or 8: # will do this elsewhere
print(winner_list)
return winner_list
# returns a list of winning userids for a given boxid.
# if each quarter has winner, will be [q1, q2, q3, f]
# if single winner, [f]
# if final/reverse final [TODO NUTX]
def find_winning_user(boxid):
s = "SELECT * FROM scores WHERE boxid = {} ORDER BY score_id DESC LIMIT 1;".format(boxid)
print(s)
scores = db(s)[0]
score_list = []
for score in scores[3:]:
if score != None:
score_list.append(str(score)[-1:])
else:
score_list.append(None)
print(score_list)
xy = "SELECT x, y FROM boxnums WHERE boxid = {};".format(boxid)
xy_list = db(xy)
x = json.loads(xy_list[0][0])
y = json.loads(xy_list[0][1])
box_x = []
box_y = []
# go thru each score, find in grid
for score in score_list[::2]: # only look at the x's
if score != None:
# box_x = [n for n in x if x[n] == int(score)]
for n in x:
if x[n] == int(score):
box_x.append(n)
for score in score_list[1::2]: # look at y's
if score != None:
#box_y = [n for n in y if y[n] == int(score)]
for n in y:
if y[n] == int(score):
box_y.append(n)
print(box_x, box_y)
winner_list = []
for n in range(len(box_x)):
boxnum = "box"
if box_y[n] != '0':
boxnum += box_y[n]
boxnum += box_x[n]
w = "SELECT {} FROM boxes WHERE boxid = {};".format(boxnum, boxid)
winner = db(w)[0][0]
winner_list.append(winner)
print(winner)
print(winner_list)
return(winner_list)
def check_box_limit(userid):
box_list = ['box' + str(x) + ' ,' for x in range(100)]
box_string = ''
for _ in box_list:
box_string += _
box_string = box_string[:-2]
box = "SELECT {} FROM boxes WHERE active = 1 or boxid between 26 and 36;".format(box_string)
all_boxes = db(box)
count = 0
for game in all_boxes:
for box in game:
if box == session['userid']:
count += 1
s = "SELECT max_boxes FROM max_boxes WHERE userid = {};".format(session['userid'])
mb = db(s)
if len(mb) == 0:
return True
elif count < mb[0][0]:
return False
else:
return True
def create_new_game(box_type, pay_type, fee, box_name=None, home=None, away=None, espn_id=None):
if box_name == None:
s = "SELECT max(boxid) from boxes;"
max_box = db(s)[0][0]
box_name = "db" + str(max_box + 1)
# builds the string of box## to create
c = ''
for x in range(100):
c += 'box' + str(x) + ", "
c = c[:-2] # chop last space and ,
# create string of v = values to add
v = "{}, 1, {}, '{}', '{}', '{}', ".format(fee, box_type, box_name, pay_type, espn_id) # sets column active to Y
for x in range(100):
v += str(1) + ", " # 1 is place holder value for box entry
v = v[:-2] # chop last space and ,
s = "INSERT INTO boxes(fee, active, box_type, box_name, pay_type, espn_id, {}) VALUES({});".format(c,v)
db(s)
b = "SELECT max(boxid) FROM boxes;"
boxid = db(b)[0][0]
t = "INSERT INTO teams(boxid, home, away) VALUES('{}', '{}', '{}');".format(boxid, home, away)
db(t)
@app.route("/start_game", methods=["POST", "GET"])
def start_game():
boxid = request.form.get('boxid')
# check if we've already assigned numbers first
check_sql_string = "SELECT boxid FROM boxnums WHERE boxid = %s"
already_has_numbers = db2(check_sql_string, (boxid, ))
if already_has_numbers:
return apology("Escalate with tech support, this game has already drawn numbers")
avail = count_avail(boxid)
s = "SELECT box_type, pay_type from boxes WHERE boxid = {};".format(boxid)
box = db(s)
box_type = box[0][0]
pay_type = box[0][1]
print("boxtype in start game {}".format(box_type))
if avail == 0:
assign_numbers(boxid) # this assigns the row/col numbers
if box_type == BOX_TYPE_ID['dailybox']: # this is a dailybox, so generate the winning numbers as well
winning_col = random.randint(0,9)
winning_row = random.randint(0,9)
scores = "INSERT INTO scores(boxid, x4, y4) VALUES('{}', '{}', '{}');".format(boxid, winning_col, winning_row)
db(scores)
# and... mark the game inactive in database
inactivate = "UPDATE boxes SET active = 0 WHERE boxid = {};".format(boxid)
db(inactivate)
# and... update the db with winner - in scores
w = "UPDATE scores SET winner = {} WHERE boxid = {};".format(find_winning_user(boxid)[0], boxid)
db(w)
if pay_type == PAY_TYPE_ID['every_score'] or PAY_TYPE_ID['every_minute']: # this is everyscore or everymin pool, so set 0, 0 as initial winning score
winner = find_winning_box(boxid, 0, 0)
win_box = winner[0]
win_uid = winner[1]
s = "INSERT INTO everyscore(score_num, score_type, boxid, x_score, y_score, winner, winning_box) VALUES('1', '0/0 Start Game', {}, '0', '0', '{}', '{}');".format(boxid, win_uid, win_box)
db(s)
return redirect(url_for("display_box", boxid=boxid))
else:
print("tried to start game, but boxes still available")
return apology("Cannot start game - still boxes available")
# takes [box_type, box_type, ...]
def get_games(box_type, active = 1):
box_string = ''
for b in box_type:
box_string += str(b) + ', '
box_string = box_string[:-2] # chop last ', '
if active == 0:
s = "SELECT b.boxid, b.box_name, b.fee, pt.description, s.winner FROM boxes b LEFT JOIN pay_type pt ON b.pay_type = pt.pay_type_id LEFT JOIN scores s ON s.boxid = b.boxid WHERE b.active = {} and b.box_type in ({});".format(active, box_string)
games = db(s)
game_list = [list(game) for game in games]
u = "SELECT userid, username FROM users;"
user_dict = dict(db2(u))
print(user_dict)
for game in game_list:
if game[4] is not None:
#w = "SELECT username FROM users WHERE userid = {};".format(game[4])
#username = db(w)[0][0]
# game[4] = username
game[4] = user_dict[int(game[4])]
else:
game[4] = "N/A"
elif box_type[0] == 4:
priv_boxid_string = "SELECT boxid FROM privategames WHERE userid = %s;"
priv_boxes = db2(priv_boxid_string, (session['userid'], ))
if priv_boxes:
priv_boxids = []
for box in priv_boxes:
priv_boxids.append(box[0])
#priv_boxids = priv_boxes[0][0]
print(f"private boxids {priv_boxids}")
boxid_string = ""
for bs in priv_boxids:
boxid_string += str(bs) + ", "
boxid_string = boxid_string[:-2]
s = f"SELECT b.boxid, b.box_name, b.fee, pt.description FROM boxes b LEFT JOIN pay_type pt ON b.pay_type = pt.pay_type_id WHERE b.active = {active} and b.boxid in ({boxid_string}) and b.box_type in ({box_type[0]});"
games = db2(s)
game_list = [list(game) for game in games]
else:
return []
else:
s = "SELECT b.boxid, b.box_name, b.fee, pt.description FROM boxes b LEFT JOIN pay_type pt ON b.pay_type = pt.pay_type_id WHERE b.active = {} and b.box_type in ({});".format(active, box_string)
games = db(s)
game_list = [list(game) for game in games]
print(game_list)
if active == 1:
a = "SELECT * FROM boxes WHERE active = {};".format(active)
avail = db(a)
available = {}
for game in avail:
count = 0
for x in game[:len(game)-101:-1]:
if x == 1 or x == 0:
count += 1
available[game[0]] = count
# add the avail spots to the list that is passed to display game list
#if active == 1:
for game in game_list:
game.append(available[game[0]])
print(game_list)
return game_list
def auto_check_lines():
print("checking espn lines automatically")
pass
@app.route("/init_box_db")
@login_required
def init_box_db():
b = ['box' + str(x) + " INT," for x in range(100)]
s = "CREATE TABLE IF NOT EXISTS boxes(boxid INT AUTO_INCREMENT PRIMARY KEY, active, box_type, box_name, fee int, "
for _ in b:
s += _
s = s[:-1]
s += ")"
db(s)
return redirect(url_for("index"))
@app.route("/create_game", methods=["POST", "GET"])
def create_game():
fee = request.form.get('fee')
espn_id = request.form.get('espn_id')
if not request.form.get('box_name'):
s = "SELECT max(boxid) from boxes;"
max_box = db(s)[0][0]
box_name = "db" + str(max_box + 1)
else:
box_name = request.form.get('box_name')
box_type = request.form.get('box_type')
pay_type = request.form.get('pay_type')
# create string of c = columns to update
home = request.form.get('home')
away = request.form.get('away')
create_new_game(box_type, pay_type, fee, box_name, home, away, espn_id)
return redirect(url_for("index"))
@app.route("/gobble_games", methods=["POST", "GET"])
def gobble_games():
boxid_1 = request.form.get('boxid_1')
boxid_2 = request.form.get('boxid_2')
boxid_3 = request.form.get('boxid_3')
print(boxid_1, boxid_2, boxid_3)
g = "SELECT max(gobbler_id) from boxes;"
max_g = db(g)[0][0]
g_id = max_g + 1
s = "UPDATE boxes SET gobbler_id = {} WHERE boxid IN ({}, {}, {});".format(g_id, int(boxid_1), int(boxid_2), int(boxid_3))
db(s)
return redirect(url_for("admin_summary"))
@app.route("/my_games", methods=["POST", "GET"])
@login_required
def my_games():
show_active = request.form.get("active")
print("activeactive")
print(show_active)
s = "SELECT * FROM boxes;"
games = db(s)
g_list = [list(game) for game in games]
pt = "SELECT pay_type_id, description from pay_type;"
payout_types = dict(db(pt))
game_list = []
completed_game_list = []
available = {}
user_nums = []
#### dict of boxid:winner ####
bw = "SELECT boxid, winner FROM scores ORDER BY score_id ASC;"
win_dict = dict(db(bw))
#### dict of box x,y if box is full ####
bn = "SELECT * FROM boxnums;"
boxnums = db(bn)
#print(boxnums)
u = "SELECT userid, username FROM users;"
user_dict = dict(db2(u))
alias_string = "SELECT userid, alias_of_userid FROM users WHERE alias_of_userid IS NOT NULL;"
aliases = dict(db2(alias_string))
t = "SELECT boxid, home, away from teams;"
teams_list = db2(t)
teams_dict = {}
for t_boxid, t_home, t_away in teams_list:
teams_dict[t_boxid] = {"home": t_home, "away": t_away}
# create dict of boxid:{x:{json}, y:{json}}
boxnum_x = {}
boxnum_y = {}
for b_id in boxnums:
boxnum_x[b_id[0]] = json.loads(b_id[1])
boxnum_y[b_id[0]] = json.loads(b_id[2])
for game in g_list:
count = 0
gameid = game[0]
active = game[1]
box_type = ''
b_type = game[2]
if b_type == 1:
box_type = 'Daily Box'
elif b_type == 2:
box_type = 'Custom Box'
elif b_type == 3:
box_type = 'Nutcracker'
elif b_type == None:
box_type = 'Daily Box'
box_name = game[3]
fee = game[4]
pay_type = payout_types[game[5]]
gobbler_id = game[6]
espn_id = game[7]
box_index = 0
if active == 0:
# find who won
#w = "SELECT username FROM users WHERE userid = {};".format(find_winning_user(gameid)[0])
#winner = db(w)[0][0]
if gameid not in win_dict:
winner = "multi" # these are cxl'd or every score
else:
#print(f"GAMEID before crash {gameid}")
# total hack, check if string is json format, then it's multi
if not win_dict[gameid]:
winner = "none - game canceled"
elif win_dict[gameid][:1] == "{":
winner = "multi" # will parse this later...
else:
#w = "SELECT username FROM users WHERE userid = {};".format(win_dict[gameid])
#winner = db(w)[0][0]
winner = user_dict[int(win_dict[gameid])]
for b in game[8:]: # BOX DB Change if schema change here
if b in aliases:
box = aliases[b]
alias = user_dict[b]
else:
box = b
alias = ''
if box == session['userid'] and active == 1:
if gameid in boxnum_x:
h_num = teams_dict.get(gameid).get("home") + " " + str(boxnum_x[gameid][str(box_index % 10)])
a_num = teams_dict.get(gameid).get("away") + " " + str(boxnum_y[gameid][str(box_index // 10)])
else:
h_num = "TBD"
a_num = "TBD"
game_list.append((gameid,box_name,box_index + 1,alias,fee,pay_type,h_num,a_num))
elif box == session['userid'] and active == 0:
completed_game_list.append((gameid,box_type,box_name,box_index + 1,alias,fee,pay_type,winner))
if box == 1 or box == 0:
count += 1
box_index += 1
available[game[0]] = count
hover_text_1 = "Click on cell in this column to re-label"
hover_text_2 = "box to something other than your username"
total = len(game_list)
if show_active == 'True' or show_active == None:
return render_template("my_games.html", game_list = game_list, available = available, total=total, hover_text_1=hover_text_1, hover_text_2=hover_text_2)
else:
print("got to my completed list")
return render_template("my_completed_games.html", game_list = completed_game_list)
@app.route("/create_alias", methods=["POST", "GET"])
@login_required
def create_alias():
r = request.form.get('alias_boxnum')
print(f"alias boxnum: {r}")
box_tuple = eval(r)
boxid = box_tuple[0]
boxnum = box_tuple[1]
ud_string = "SELECT userid, username FROM users;"
user_dict = dict(db2(ud_string))
alias_string = "SELECT userid FROM users WHERE alias_of_userid = {} and active = 1".format(session['userid'])
aliases_result = db2(alias_string)
user_aliases = []
if aliases_result:
for alias in aliases_result:
user_aliases.append((user_dict[alias[0]], alias[0]))
print(f"user_aliases: {user_aliases}")
return render_template("create_alias.html", boxid=boxid, boxnum=boxnum, user_aliases=user_aliases)
@app.route("/assign_alias", methods=["POST", "GET"])
@login_required
def assign_alias():
boxid = str(request.form.get('boxid'))
boxnum = str(int(request.form.get('boxnum')) - 1) #boxes displayed start at 1. boxes in db start at 0.
user_aliases = eval(request.form.get('user_aliases'))
user_alias_dict = dict(user_aliases)
print(f"user_alias_dict: {user_alias_dict}")
if request.form.get('existingAlias'):
existing_alias = eval(request.form.get('existingAlias'))
else:
existing_alias = None
new_alias = request.form.get('newAliasName')
print(f"box info: {boxid} {boxnum} {new_alias} {type(existing_alias)} {existing_alias}")
if existing_alias:
query = "UPDATE boxes SET box%s = %s WHERE boxid = %s;"
db2(query, (int(boxnum), existing_alias[1], int(boxid)))
elif new_alias in user_alias_dict:
query = "UPDATE boxes SET box%s = %s WHERE boxid = %s;"
db2(query, (int(boxnum), user_alias_dict[new_alias], int(boxid)))
elif new_alias:
new_user_q = "INSERT INTO users (username, password, first_name, last_name, active, alias_of_userid) values (%s, 'x', 'alias', %s, 1, %s);"
db2(new_user_q, (new_alias, session['username'], session['userid']))
get_new_user_q = "SELECT userid FROM users WHERE username = %s;"
new_userid = db2(get_new_user_q, (new_alias,))[0][0]
print(f"new userid for alias: {new_userid}")
assign_alias_q = "UPDATE boxes SET box%s = %s WHERE boxid = %s;"
db2(assign_alias_q, (int(boxnum), int(new_userid), int(boxid)))
return redirect(url_for("my_games"))
@app.route("/completed_games")
@login_required
def completed_games():
#game_list_d = get_games(1, 0)
game_list_c = get_games([2,3], 0)
#game_list = game_list_d + game_list_c
game_list_pre = game_list_c
game_list_pre.sort(key=lambda x: x[0])
# dedupe - if corrections were made in score entry a game can have multiple
game_list = []
seen = set()
for game in game_list_pre:
if game[0] not in seen: # unique game, mark as seen and add to gl
game_list.append(game)
seen.add(game[0])
else: # seen this one already.. replace it with a new one
del game_list[-1]
game_list.append(game)
return render_template("completed_games.html", game_list = game_list)
@app.route("/completed_private_games")
@login_required
def completed_private_games():
#game_list_d = get_games(1, 0)
game_list_c = get_games([4], 0)
#game_list = game_list_d + game_list_c
game_list_pre = game_list_c
game_list_pre.sort(key=lambda x: x[0])
# dedupe - if corrections were made in score entry a game can have multiple
game_list = []
seen = set()
for game in game_list_pre:
if game[0] not in seen: # unique game, mark as seen and add to gl
game_list.append(game)
seen.add(game[0])
else: # seen this one already.. replace it with a new one
del game_list[-1]
game_list.append(game)
return render_template("completed_private_games.html", game_list = game_list)
@app.route("/game_list")
def game_list():
game_list = get_games([1])
return render_template("game_list.html", game_list = game_list)
@app.route("/custom_game_list")
@login_required
def custom_game_list():
game_list = get_games([2,3]) # pass a list of box types..
no_active_games_string = ''
if not game_list:
no_active_games_string = 'No Active Games'
# sorted(game_list, key=itemgetter(0))
game_list.sort(key=lambda x: x[0])
return render_template("custom_game_list.html", game_list = game_list, no_active_games_string = no_active_games_string)
@app.route("/private_game_list")
@login_required
def private_game_list():
game_list = get_games([4]) # takes a list of box_types.. only 4 for private here
no_active_games_string = ''
if not game_list:
no_active_games_string = 'You have no active private games'
else:
game_list.sort(key=lambda x: x[0])
return render_template("private_game_list.html", game_list = game_list, no_active_games_string = no_active_games_string)
@app.route("/private_pswd", methods=["POST", "GET"])
@login_required
def private_pswd():
if request.method == "POST":
pswd = request.form.get('priv_password')
# first check if this is valid#
p = "SELECT boxid FROM privatepass WHERE pswd = %s;"
box = db2(p, (pswd, ))
print(f"BOXBOX {box}")
if box:
print(f"privpswd BOX {box}")
s = "INSERT INTO privategames (userid, boxid, paid) values (%s, %s, 0) ON DUPLICATE KEY UPDATE userid = %s, boxid=%s;"
db2(s, (session['userid'], box[0][0], session['userid'], box[0][0]))
else:
display_error = "Invalid code - please try again or contact the game admin."
return render_template("private_pswd.html", display_error=display_error)
# for now
return redirect("private_game_list")
else:
return render_template("private_pswd.html")
@app.route("/display_box", methods=["GET", "POST"])
@login_required
def display_box():
if request.method == "POST":
boxid = request.form.get('boxid')
else:
boxid = request.args['boxid']
logging.info("user {} just ran display_box for boxid {}".format(session['username'], boxid))
s = "SELECT * FROM boxes where boxid = {};".format(boxid)
box = list(db(s))[0]
box_type = box[2]
if box_type == 4:
private_game_payment_link = "Click here for this game's payment status"
else:
private_game_payment_link = ""
box_name = box[3]
fee = box[4]
ptype = box[5]
for p in PAY_TYPE_ID:
if ptype == PAY_TYPE_ID[p]:
pay_type = p # human form of a pay type
gobbler_id = box[6]
espn_id = box[7]
payout = payout_calc(ptype, fee)
rev_payout = 0
#current_user = Session['userid']
# if ptype != 2 and ptype != 5:
if ptype == PAY_TYPE_ID['four_qtr']:
final_payout = fee * 60
elif ptype == PAY_TYPE_ID['single']:
final_payout = fee * 100
elif ptype == PAY_TYPE_ID['ten_man']:
final_payout = fee * 10
elif ptype == PAY_TYPE_ID['satellite']:
final_payout = "Satellite"
else:
final_payout = None
if box_type != BOX_TYPE_ID['dailybox']:
t = "SELECT home, away FROM teams WHERE boxid = {};".format(boxid)
teams = db(t)
home = teams[0][0]
away = teams[0][1]
else:
home = 'XXX'
away = 'YYY'
game_status = get_espn_summary_single_game(espn_id)
live_quarter = int(game_status['quarter'])
status = game_status['game_status']
game_clock = game_status['game_clock']
kickoff_time = game_status['kickoff_time']
team_scores = get_espn_score_by_qtr(espn_id) # team_scpre[abbr] = current_score, qtr_scores, name, nickname, logo
print(f"team scores: {team_scores}")
game_dict = get_espn_score_by_qtr(espn_id)
away_team = {}
for i in range(10):
away_team[str(i)] = ''
if len(away) == 3:
# away_team['2'] = team_scores[away]['logo']
away_team['2'] = team_scores[away].get('logo', "TBD")
away_team['3'] = away[0]
away_team['4'] = away[1]
away_team['5'] = away[2]
# away_team['6'] = team_scores[away]['logo']
away_team['6'] = team_scores[away].get('logo', "TBD")
print(f"LEN AWAY TEAM {len(away_team)}")
else:
# away_team['3'] = team_scores[away]['logo']
away_team['3'] = team_scores[away].get('logo', "TBD")
away_team['4'] = away[0]
away_team['5'] = away[1]
# away_team['6'] = team_scores[away]['logo']
away_team['6'] = team_scores[away].get('logo', "TBD")
print(f"paytype: {pay_type}")
# check for final scores only
if pay_type == 'single' or pay_type == 'ten_man' or pay_type == 'sattelite':
if 'current_score' in team_scores[home]:
home_digit = team_scores[home]['current_score'][-1]
away_digit = team_scores[away]['current_score'][-1]
else:
home_digit = str(0)
away_digit = str(0)
# DH 11/25/22 - changing..
# team_scores_digit = get_espn_scores(espnid = '')['team']
# #game_dict = get_espn_score_by_qtr(espn_id)
# print(f"team scores: {team_scores_digit}")
# print(f"home and away: {home} {away}")
# home_digit = str(0)
# away_digit = str(0)
# if home in team_scores_digit and away in team_scores_digit:
# print(f"home: {home}:{team_scores_digit[home]} away: {away}:{team_scores_digit[away]}")
# home_digit = team_scores_digit[home][-1]
# away_digit = team_scores_digit[away][-1]
# print(home_digit, away_digit)
# else:
# print("one team is most likely on bye")
elif pay_type == 'four_qtr':
home_digit = str(0)
away_digit = str(0)
#game_dict = get_espn_score_by_qtr(espn_id)
print(f"game_dict in display box {game_dict}")
# create a dict of userid:username
u = "SELECT userid, username FROM users;"
user_dict = dict(db(u))
alias_query = "SELECT userid, alias_of_userid FROM users WHERE alias_of_userid IS NOT NULL;"
alias_dict = dict(db2(alias_query))
grid = []
box_num = 0
row = 0
avail = 0