forked from infinite-options/Caption-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
caption_api.py
3025 lines (2581 loc) · 128 KB
/
caption_api.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
# To run program: python3 io_api.py
# README: if conn error make sure password is set properly in RDS PASSWORD section
# README: Debug Mode may need to be set to False when deploying live (although it seems to be working through Zappa)
# README: if there are errors, make sure you have all requirements are loaded
from contextlib import nullcontext
import os
import uuid
import boto3
import json
import math
from datetime import time, date, datetime, timedelta
import calendar
import time
from pytz import timezone
import random
import string
import stripe
from flask import Flask, request, render_template
from flask_restful import Resource, Api
from flask_cors import CORS
from flask_mail import Mail, Message
# used for serializer email and error handling
# from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadTimeSignature
# from flask_cors import CORS
from werkzeug.exceptions import BadRequest, NotFound, InternalServerError
from werkzeug.security import generate_password_hash, check_password_hash
# NEED TO SOLVE THIS
# from NotificationHub import Notification
# from NotificationHub import NotificationHub
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup
from twilio.rest import Client
from dateutil.relativedelta import *
from decimal import Decimal
from datetime import datetime, date, timedelta
from hashlib import sha512
from math import ceil
import string
# BING API KEY
# Import Bing API key into bing_api_key.py
# NEED TO SOLVE THIS
# from env_keys import BING_API_KEY, RDS_PW
import decimal
import sys
import json
import pytz
import pymysql
import requests
from random import randint
RDS_HOST = "io-mysqldb8.cxjnrciilyjq.us-west-1.rds.amazonaws.com"
RDS_PORT = 3306
RDS_USER = "admin"
RDS_DB = "captions"
# app = Flask(__name__)
app = Flask(__name__, template_folder="assets")
# --------------- Stripe Variables ------------------
# these key are using for testing. Customer should use their stripe account's keys instead
import stripe
# STRIPE AND PAYPAL KEYS
paypal_secret_test_key = os.environ.get('paypal_secret_key_test')
paypal_secret_live_key = os.environ.get('paypal_secret_key_live')
paypal_client_test_key = os.environ.get('paypal_client_test_key')
paypal_client_live_key = os.environ.get('paypal_client_live_key')
stripe_public_test_key = os.environ.get('stripe_public_test_key')
stripe_secret_test_key = os.environ.get('stripe_secret_test_key')
stripe_public_live_key = os.environ.get('stripe_public_live_key')
stripe_secret_live_key = os.environ.get('stripe_secret_live_key')
stripe.api_key = stripe_secret_test_key
# use below for local testing
# stripe.api_key = ""sk_test_51J0UzOLGBFAvIBPFAm7Y5XGQ5APR...WTenXV4Q9ANpztS7Y7ghtwb007quqRPZ3""
CORS(app)
# --------------- Mail Variables ------------------
#This should be on Github -- should work wth environmental variables
app.config["MAIL_USERNAME"] = os.environ.get("SUPPORT_EMAIL")
app.config["MAIL_PASSWORD"] = os.environ.get("SUPPORT_PASSWORD")
#This should not be on Github -- should work on localhost
# app.config['MAIL_USERNAME'] = "support@mealsfor..."
# app.config['MAIL_USERNAME'] = "support@capshnz..."
# app.config['MAIL_PASSWORD'] = "Support..."
# Setting for mydomain.com
app.config["MAIL_SERVER"] = "smtp.mydomain.com"
app.config["MAIL_PORT"] = 465
# Setting for gmail
# app.config['MAIL_SERVER'] = 'smtp.gmail.com'
# app.config['MAIL_PORT'] = 465
app.config["MAIL_USE_TLS"] = False
app.config["MAIL_USE_SSL"] = True
# Set this to false when deploying to live application
# app.config['DEBUG'] = True
app.config["DEBUG"] = False
app.config["STRIPE_SECRET_KEY"] = os.environ.get("STRIPE_SECRET_KEY")
mail = Mail(app)
# API
api = Api(app)
# convert to UTC time zone when testing in local time zone
utc = pytz.utc
# # These statment return Day and Time in GMT
# def getToday(): return datetime.strftime(datetime.now(utc), "%Y-%m-%d")
# def getNow(): return datetime.strftime(datetime.now(utc), "%Y-%m-%d %H:%M:%S")
# # These statment return Day and Time in Local Time - Not sure about PST vs PDT
def getToday(): return datetime.strftime(datetime.now(), "%Y-%m-%d")
def getNow(): return datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
# Not sure what these statments do
# getToday = lambda: datetime.strftime(date.today(), "%Y-%m-%d")
# print(getToday)
# getNow = lambda: datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
# print(getNow)
# Get RDS password from command line argument
def RdsPw():
if len(sys.argv) == 2:
return str(sys.argv[1])
return ""
# RDS PASSWORD
# When deploying to Zappa, set RDS_PW equal to the password as a string
# When pushing to GitHub, set RDS_PW equal to RdsPw()
RDS_PW = "prashant"
# RDS_PW = RdsPw()
s3 = boto3.client('s3')
s3_res = boto3.resource('s3')
s3_cl = boto3.client('s3')
# aws s3 bucket where the image is stored
# BUCKET_NAME = os.environ.get('MEAL_IMAGES_BUCKET')
BUCKET_NAME = 'iocaptions'
# allowed extensions for uploading a profile photo file
ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg"])
def allowed_file(filename):
"""Checks if the file is allowed to upload"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def helper_upload_user_img(file, key):
print("uploading image to s3 bucket.")
bucket = 'iocaptions'
if file and allowed_file(file.filename):
# filename = 'https://' + bucket+ '.s3.us-west-1.amazonaws.com/' \
# + str(bucket) + '/' + str(key)
filename = 'https://' + bucket+ '.s3.us-west-1.amazonaws.com/' + str(key)
upload_file = s3.put_object(
Bucket=bucket,
Body=file,
Key=key,
ACL='public-read',
ContentType='image/jpeg'
)
return filename
return None
# For Push notification
isDebug = False
NOTIFICATION_HUB_KEY = os.environ.get("NOTIFICATION_HUB_KEY")
NOTIFICATION_HUB_NAME = os.environ.get("NOTIFICATION_HUB_NAME")
TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN")
# Connect to MySQL database (API v2)
def connect():
global RDS_PW
global RDS_HOST
global RDS_PORT
global RDS_USER
global RDS_DB
print("Trying to connect to RDS (API v2)...")
try:
conn = pymysql.connect(
host=RDS_HOST,
user=RDS_USER,
port=RDS_PORT,
passwd=RDS_PW,
db=RDS_DB,
cursorclass=pymysql.cursors.DictCursor,
)
print("Successfully connected to RDS. (API v2)")
return conn
except:
print("Could not connect to RDS. (API v2)")
raise Exception("RDS Connection failed. (API v2)")
# Disconnect from MySQL database (API v2)
def disconnect(conn):
try:
conn.close()
print("Successfully disconnected from MySQL database. (API v2)")
except:
print("Could not properly disconnect from MySQL database. (API v2)")
raise Exception("Failure disconnecting from MySQL database. (API v2)")
# Serialize JSON
def serializeResponse(response):
try:
# print("In Serialize JSON")
for row in response:
for key in row:
if type(row[key]) is Decimal:
row[key] = float(row[key])
elif type(row[key]) is date or type(row[key]) is datetime:
row[key] = row[key].strftime("%Y-%m-%d")
# print("In Serialize JSON response", response)
return response
except:
raise Exception("Bad query JSON")
# Execute an SQL command (API v2)
# Set cmd parameter to 'get' or 'post'
# Set conn parameter to connection object
# OPTIONAL: Set skipSerialization to True to skip default JSON response serialization
def execute(sql, cmd, conn, skipSerialization=False):
response = {}
print("in Execute")
print(cmd)
try:
with conn.cursor() as cur:
print("before query")
cur.execute(sql)
print("after query")
if cmd == "get":
result = cur.fetchall()
response["message"] = "Successfully executed SQL query."
# Return status code of 280 for successful GET request
response["code"] = 280
if not skipSerialization:
result = serializeResponse(result)
response["result"] = result
elif cmd == "post":
print("in POST")
conn.commit()
print("after commit")
response["message"] = "Successfully committed SQL command."
# Return status code of 281 for successful POST request
response["code"] = 281
else:
response["message"] = "Request failed. Unknown or ambiguous instruction given for MySQL command."
# Return status code of 480 for unknown HTTP method
response["code"] = 480
except:
response["message"] = "Request failed, could not execute MySQL command."
# Return status code of 490 for unsuccessful HTTP request
response["code"] = 490
finally:
response["sql"] = sql
return response
# Close RDS connection
def closeRdsConn(cur, conn):
try:
cur.close()
conn.close()
print("Successfully closed RDS connection.")
except:
print("Could not close RDS connection.")
# Runs a select query with the SQL query string and pymysql cursor as arguments
# Returns a list of Python tuples
def runSelectQuery(query, cur):
try:
cur.execute(query)
queriedData = cur.fetchall()
return queriedData
except:
raise Exception("Could not run select query and/or return data")
# -- Stored Procedures start here -------------------------------------------------------------------------------
# RUN STORED PROCEDURES
def get_new_gameUID(conn):
newGameQuery = execute("CALL captions.new_game_uid()", 'get', conn)
if newGameQuery['code'] == 280:
return newGameQuery['result'][0]['new_id']
return "Could not generate new game UID", 500
def get_new_roundUID(conn):
newRoundQuery = execute("CALL captions.new_round_uid()", 'get', conn)
if newRoundQuery['code'] == 280:
return newRoundQuery['result'][0]['new_id']
return "Could not generate new game UID", 500
def get_new_userUID(conn):
newPurchaseQuery = execute("CALL captions.new_user_uid()", 'get', conn)
if newPurchaseQuery['code'] == 280:
return newPurchaseQuery['result'][0]['new_id']
return "Could not generate new user UID", 500
def get_new_historyUID(conn):
newHistoryQuery = execute("CALL captions.new_history_uid()", 'get', conn)
if newHistoryQuery['code'] == 280:
return newHistoryQuery['result'][0]['new_id']
return "Could not generate new history UID", 500
def get_new_imageUID(conn):
# print("getting new image")
newImageQuery = execute("CALL captions.new_image_uid()", 'get', conn)
# print(newImageQuery)
if newImageQuery['code'] == 280:
return newImageQuery['result'][0]['new_id']
return "Could not generate new image UID", 500
def get_new_deckUID(conn):
# print("getting new image")
newImageQuery = execute("CALL captions.new_deck_uid()", 'get', conn)
# print(newImageQuery)
if newImageQuery['code'] == 280:
return newImageQuery['result'][0]['new_id']
return "Could not generate new deck UID", 500
# --Caption Queries start here -------------------------------------------------------------------------------
# CHECK IF USER EXISTS
# def checkUser(self, user_name, user_alias, user_email, user_zip):
# print("In checkUser")
# response = {}
# try:
# conn = connect()
# # print Received data to Terminal
# print("In checkUser:", user_name, user_alias, user_email, user_zip)
# message = "Email Verification Code Sent"
# # CHECK IF EMAIL EXISTS IN DB
# check_email = '''
# SELECT * FROM captions.user
# WHERE user_email= \'''' + user_email + '''\'
# '''
# userinfo = execute(check_email, "get", conn)
# print(userinfo, type(userinfo))
# print("User Info returned: ", userinfo['result'])
# # CHECK IF USER EXISTS
# if userinfo['result'] != ():
# # if len(userinfo['result'][0]['user_uid']) > 0:
# response["user_uid"] = userinfo['result'][0]['user_uid']
# # CHECK IF VALIDATION CODE IS TRUE
# if userinfo['result'][0]["email_validated"] != "TRUE":
# print("Not Validated")
# response["user_status"] = "User NOT Validated"
# response["user_code"] = userinfo["result"][0]["email_validated"]
# SendEmail.get(self, user_name, user_email, userinfo["result"][0]["email_validated"], message)
# # return response
# # CHECK IF ZIP CODE IS IN LIST
# if user_zip not in userinfo['result'][0]['user_zip_code']:
# print("Zip code not in list")
# response["user_zip"] = "Zip code not in list"
# query = '''
# UPDATE captions.user
# SET user_zip_code = JSON_ARRAY_APPEND(user_zip_code, '$', \'''' + user_zip + '''\')
# WHERE user_email = \'''' + user_email + '''\';
# '''
# addzip = execute(query, "post", conn)
# print("items: ", addzip)
# if addzip["code"] == 281:
# response["user_zip_added"] = "Zip code added"
# # CHECK IF ALIAS HAS CHANGED
# if user_alias != userinfo['result'][0]['user_alias']:
# print("Alias changed")
# response["user_alias"] = "Alias changed"
# query = '''
# UPDATE captions.user
# SET user_alias = \'''' + user_alias + '''\'
# WHERE user_email = \'''' + user_email + '''\';
# '''
# update_alias = execute(query, "post", conn)
# print("items: ", update_alias)
# if update_alias["code"] == 281:
# response["user_alias_added"] = "Alias updated"
# # CHECK IF USER NAME HAS CHANGED
# if user_name != userinfo['result'][0]['user_name']:
# print("Name changed")
# response["user_name"] = "Name Changed"
# query = '''
# UPDATE captions.user
# SET user_name = \'''' + user_name + '''\'
# WHERE user_email = \'''' + user_email + '''\';
# '''
# update_name = execute(query, "post", conn)
# print("items: ", update_name)
# if update_name["code"] == 281:
# response["user_name_updated"] = "Name updated"
# # USER DOES NOT EXIST
# else:
# # Create Validation Code FOR NEW USER
# code = str(randint(100,999))
# print("Email validation code will be set to: ", code)
# new_user_uid = get_new_userUID(conn)
# print(new_user_uid)
# print(getNow())
# query = '''
# INSERT INTO captions.user
# SET user_uid = \'''' + new_user_uid + '''\',
# user_created_at = \'''' + getNow() + '''\',
# user_name = \'''' + user_name + '''\',
# user_alias = \'''' + user_alias + '''\',
# user_email = \'''' + user_email + '''\',
# user_zip_code = \'''' + user_zip + '''\',
# email_validated = \'''' + code + '''\',
# user_purchases = NULL
# '''
# items = execute(query, "post", conn)
# print("items: ", items)
# if items["code"] == 281:
# response["message"] = "Create User successful"
# response["user_uid"] = new_user_uid
# response["email_validated"] = code
# # Send Code to User
# SendEmail.get(self, user_name, user_email, code, message)
# print(response)
# return response, 200
# print(response)
# return response, 200
# except:
# raise BadRequest("Create User Request failed")
# finally:
# disconnect(conn)
# class createUser(Resource):
# def post(self):
# response = {}
# items = {}
# try:
# conn = connect()
# data = request.get_json(force=True)
# # print to Received data to Terminal
# print("Received:", data)
# user_name = data["user_name"]
# user_alias = data["user_alias"] if data.get("user_alias") is not None else data["user_name"].split[0]
# user_email = data["user_email"]
# user_zip = data["user_zip"]
# # print(user_zip)
# response = checkUser(self, user_name, user_alias, user_email, user_zip)
# # print("after CheckEmail call")
# return response, 200
# except:
# raise BadRequest("Create User Request failed")
# finally:
# disconnect(conn)
class addUserByEmail(Resource):
def post(self):
response = {}
message = "Email Verification Code Sent"
try:
conn = connect()
data = request.get_json()
email = data["email"]
query = """SELECT * FROM captions.user
WHERE user_email= \'""" + email + """\'
"""
user = execute(query, "get", conn)
if user['result'] != ():
response["user_uid"] = user['result'][0]['user_uid']
response["user_code"] = user["result"][0]["email_validated"]
response["name"] = user["result"][0]["user_name"]
response["alias"] = user["result"][0]["user_alias"]
if user['result'][0]["email_validated"] != "TRUE":
response["user_status"] = "User NOT Validated"
SendEmail.get(self, "User", email,
user["result"][0]["email_validated"], message)
else:
code = str(randint(100,999))
new_user_uid = get_new_userUID(conn)
query = '''
INSERT INTO captions.user
SET user_uid = \'''' + new_user_uid + '''\',
user_created_at = \'''' + getNow() + '''\',
user_email = \'''' + email + '''\',
email_validated = \'''' + code + '''\',
user_purchases = NULL
'''
items = execute(query, "post", conn)
if items["code"] == 281:
response["message"] = "Create User successful"
response["user_uid"] = new_user_uid
response["email_validated"] = code
SendEmail.get(self, "User", email, code, message)
return response, 200
except Exception as e:
raise InternalServerError("An unknown error occurred") from e
finally:
disconnect(conn)
return response, 200
class addUser(Resource):
def post(self):
response = {}
items = {}
try:
conn = connect()
data = request.get_json(force=True)
# print to Received data to Terminal
print("Received:", data)
user_name = data["user_name"]
user_alias = data["user_alias"] if data.get("user_alias") is not None else data["user_name"].split[0]
user_email = data["user_email"]
# user_zip = data["user_zip"]
# print(data)
message = "Email Verification Code Sent"
# Use statements below if we want to use def
# user = CheckEmail(user_email)
# print("after CheckEmail call")
# CHECK IF EMAIL EXISTS IN DB
check_user = '''SELECT * FROM captions.user
WHERE user_email= \'''' + user_email + '''\'
'''
user = execute(check_user, "get", conn)
print(user)
# CHECK IF USER EXISTS
if user['result'] != ():
# if len(user['result'][0]['user_uid']) > 0:
response["user_uid"] = user['result'][0]['user_uid']
response["user_code"] = user["result"][0]["email_validated"]
# CHECK IF VALIDATION CODE IS TRUE
if user['result'][0]["email_validated"] != "TRUE":
print("Not Validated")
response["user_status"] = "User NOT Validated"
SendEmail.get(self, user_name, user_email, user["result"][0]["email_validated"], message)
# return response
# CHECK IF ZIP CODE IS IN LIST
# if user_zip not in user['result'][0]['user_zip_code']:
# print("Zip code not in list")
# response["user_zip"] = "Zip code not in list"
# query = '''
# UPDATE captions.user
# SET user_zip_code = JSON_ARRAY_APPEND(user_zip_code, '$', \'''' + user_zip + '''\')
# WHERE user_email = \'''' + user_email + '''\';
# '''
# addzip = execute(query, "post", conn)
# print("items: ", addzip)
# if addzip["code"] == 281:
# response["user_zip"] = "Zip code added"
# CHECK IF ALIAS HAS CHANGED
if user_alias != user['result'][0]['user_alias']:
print("Alias changed")
response["user_alias"] = "Alias changed"
query = '''
UPDATE captions.user
SET user_alias = \'''' + user_alias + '''\'
WHERE user_email = \'''' + user_email + '''\';
'''
update_alias = execute(query, "post", conn)
print("items: ", update_alias)
if update_alias["code"] == 281:
response["user_alias"] = "Alias updated"
# CHECK IF USER NAME HAS CHANGED
if user_name != user['result'][0]['user_name']:
print("Name changed")
response["user_name"] = "Name Changed"
query = '''
UPDATE captions.user
SET user_name = \'''' + user_name + '''\'
WHERE user_email = \'''' + user_email + '''\';
'''
update_name = execute(query, "post", conn)
print("items: ", update_name)
if update_name["code"] == 281:
response["user_name"] = "Name updated"
# USER DOES NOT EXIST
else:
# Create Validation Code FOR NEW USER
code = str(randint(100,999))
print("Email validation code will be set to: ", code)
new_user_uid = get_new_userUID(conn)
print(new_user_uid)
print(getNow())
query = '''
INSERT INTO captions.user
SET user_uid = \'''' + new_user_uid + '''\',
user_created_at = \'''' + getNow() + '''\',
user_name = \'''' + user_name + '''\',
user_alias = \'''' + user_alias + '''\',
user_email = \'''' + user_email + '''\',
email_validated = \'''' + code + '''\',
user_purchases = NULL
'''
items = execute(query, "post", conn)
print("items: ", items)
if items["code"] == 281:
response["message"] = "Create User successful"
response["user_uid"] = new_user_uid
response["email_validated"] = code
# Send Code to User
SendEmail.get(self, user_name, user_email, code, message)
return response, 200
return response, 200
except:
raise BadRequest("Create User Request failed")
finally:
disconnect(conn)
class createGame(Resource):
def post(self):
response = {}
items = {}
try:
conn = connect()
data = request.get_json(force=True)
# print to Received data to Terminal
print("Received:", data)
user_uid = data["user_uid"]
num_rounds = data["rounds"]
time_limit = data["round_time"]
scoring = data["scoring_scheme"]
print(user_uid)
new_game_uid = get_new_gameUID(conn)
print(new_game_uid)
print(getNow())
game_code = random.randint(10000000, 99999999)
print(game_code)
query = '''
INSERT INTO captions.game
SET game_uid = \'''' + new_game_uid + '''\',
game_created_at = \'''' + getNow() + '''\',
game_code = \'''' + str(game_code) + '''\',
num_rounds = \'''' + num_rounds + '''\',
time_limit = \'''' + time_limit + '''\',
game_host_uid = \'''' + user_uid + '''\',
scoring_scheme = \'''' + scoring + '''\'
'''
items = execute(query, "post", conn)
print("items: ", items)
if items["code"] == 281:
response["message"] = "Create Game successful"
response["game_code"] = str(game_code)
response["game_uid"] = str(new_game_uid)
return response, 200
except:
raise BadRequest("Create Game Request failed")
finally:
disconnect(conn)
class joinGame(Resource):
print("In joinGame")
def post(self):
response = {}
returning_user = {}
new_user = {}
game_info = {}
try:
conn = connect()
data = request.get_json(force=True)
# print to Received data to Terminal
print("Received:", data)
# player data
user_uid = data["user_uid"]
game_code = data["game_code"]
# Check if game code exists and get game_uid
check_game_code_query = '''
SELECT * FROM captions.game
WHERE game_code=\'''' + game_code + '''\'
'''
game_info = execute(check_game_code_query, "get", conn)
print(game_info)
if game_info["code"] == 280 and len(game_info["result"]) == 1:
game_uid = game_info["result"][0]["game_uid"]
print(game_uid)
response["num_rounds"] = game_info["result"][0]["num_rounds"]
print(game_info["result"][0]["num_rounds"])
response["round_duration"] = game_info["result"][0]["time_limit"]
print(game_info["result"][0]["time_limit"])
# Check if user is already in the game
check_user_in_game_query = '''
SELECT round_user_uid FROM captions.round
WHERE round_game_uid = \'''' + game_uid + '''\'
AND round_user_uid = \'''' + user_uid + '''\';
'''
existing_player = execute(check_user_in_game_query, "get", conn)
print("player_info: ", existing_player)
if existing_player["code"] == 280 and existing_player["result"] != ():
response["message"] = "280, Player has already joined the game."
response["user_uid"] = user_uid
return response, 409
else:
# User has entered and existing game code and is not in the game
print("in else clause")
new_round_uid = get_new_roundUID(conn)
add_user_to_round_query = '''
INSERT INTO captions.round
SET round_uid = \'''' + new_round_uid + '''\',
round_game_uid = \'''' + game_uid + '''\',
round_user_uid = \'''' + user_uid + '''\',
round_number = 1,
round_deck_uid = NULL,
round_image_uid = NULL ,
caption = NULL,
votes = 0,
score = 0,
round_started_at = NULL'''
add_user = execute(add_user_to_round_query, "post", conn)
print("add_user_response: ", add_user)
if add_user["code"] == 281:
response["message"] = "Player added to the game."
response["game_uid"] = game_uid
response["user_uid"] = user_uid
return response, 200
else:
response["warning"] = "Invalid game code."
return response
except:
raise BadRequest("Join Game Request failed")
finally:
disconnect(conn)
class selectDeck(Resource):
def post(self):
response = {}
items = {}
try:
conn = connect()
data = request.get_json(force=True)
# print to Received data to Terminal
print("Received:", data)
deck_uid = data["deck_uid"]
game_code = data["game_code"]
select_deck_query = '''
UPDATE captions.game
SET game_deck = \'''' + deck_uid + '''\'
WHERE game_code = \'''' + game_code + '''\';
'''
selected_deck = execute(select_deck_query, "post", conn)
print("selected deck info: ", selected_deck)
if selected_deck["code"] == 281:
response["message"] = "281, Deck successfully submitted."
return response, 200
except:
raise BadRequest("Select deck Request failed")
finally:
disconnect(conn)
class assignDeck(Resource):
def post(self):
response = {}
items = {}
try:
conn = connect()
data = request.get_json(force=True)
# print to Received data to Terminal
print("Received:", data)
deck_uid = data["deck_uid"]
game_code = data["game_code"]
assign_deck_query = '''
UPDATE captions.round
SET round_deck_uid = \'''' + deck_uid + '''\'
WHERE round_game_uid = (
SELECT game_uid
FROM captions.game
WHERE game_code = \'''' + game_code + '''\');
'''
assign_deck = execute(assign_deck_query, "post", conn)
print("selected deck info: ", assign_deck)
if assign_deck["code"] == 281:
response["message"] = "281, Deck assigned successfully."
return response, 200
except:
raise BadRequest("Assign deck Request failed")
finally:
disconnect(conn)
class checkGame(Resource):
def get(self, game_code):
print(game_code)
response = {}
items = {}
try:
conn = connect()
query = '''
SELECT game_uid FROM captions.game
WHERE game_code = \'''' + game_code + '''\';
'''
items = execute(query, "get", conn)
print("items: ", items)
if items["code"] == 280:
response["message"] = "280, Check Game successful"
if len(items["result"]) > 0:
response["game_uid"] = items["result"][0]["game_uid"]
else:
response["warning"] = "Invalid game code"
return response, 200
except:
raise BadRequest("Create Game Request failed")
finally:
disconnect(conn)
class getPlayers(Resource):
def get(self, game_code):
print("requested game_uid: ", game_code)
response = {}
items = {}
try:
conn = connect()
get_players_query = '''
SELECT DISTINCT user_uid, user_alias FROM captions.user
INNER JOIN captions.round
ON user.user_uid = round.round_user_uid
WHERE round_game_uid= (SELECT game_uid FROM captions.game
WHERE game_code=\'''' + game_code + '''\') AND user.email_validated = "TRUE"
'''
players = execute(get_players_query, "get", conn)
print("players info: ", players)
if players["code"] == 280:
response["message"] = "280, Get players request successful."
response["players_list"] = players["result"]
return response, 200
except:
raise BadRequest("Get players in the game request failed")
finally:
disconnect(conn)
class decks(Resource):
def get(self, user_uid, public_decks):
print(user_uid)
print(public_decks)
response = {}
try:
conn = connect()
# data = request.get_json(force=True)
# print("Received: ", data)
#
#user_uid = data["user_uid"] #public => "" or personal => "xxx-xxxxxx"
#we need to know user_uid
#if it matches or anything that is public (user_uid is provided, match it with that or
get_all_decks_query = '''
SELECT deck_uid, deck_title, deck_thumbnail_url, deck_description FROM captions.deck
'''
get_all_decks_query1 = '''
SELECT deck_uid, deck_title, deck_thumbnail_url, deck_description