-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathskala_api.py
2172 lines (1603 loc) · 72.5 KB
/
skala_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
# Copyright (C) 2023 David Mossakowski
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import json
import os
import io
import glob
import random
import uuid
from datetime import datetime, date, time, timedelta
import competitionsEngine
import csv
from functools import wraps
from dataclasses import dataclass
from flask import Flask, redirect, url_for, session, request, render_template, send_file, send_from_directory, jsonify, Response, \
stream_with_context, copy_current_request_context, g
import logging
from flask import Blueprint
import activities_db as activities_db
import skala_db
from io import BytesIO
from flask import send_file
from collections import defaultdict
#import Activity
#from flask_openapi3 import APIBlueprint, OpenAPI, Tag
#book_tag = Tag(name="book", description="Some Book")
#comp_tag = Tag(name="competition", description="""
# Some competition
# with multiple lines
# #header also
# """)
# Third party libraries
from flask import Flask, redirect, request, url_for
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from oauthlib.oauth2 import WebApplicationClient
import requests
from pydantic import BaseModel
#skala_api_app = Blueprint('skala_api_app', __name__)
from authlib.integrations.flask_client import OAuth
from authlib.integrations.flask_client import OAuthError
languages = {}
grades = ['?', '1', '2', '3', '4a', '4b', '4c', '5a','5a+', '5b', '5b+', '5c','5c+', '6a', '6a+', '6b', '6b+', '6c', '6c+', '7a', '7a+', '7b', '7b+', '7c', '7c+', '8a', '8a+', '8b', '8b+', '8c', '8c+', '9a', '9a+', '9b', '9b+', '9c']
DATA_DIRECTORY = os.getenv('DATA_DIRECTORY')
if DATA_DIRECTORY is None:
DATA_DIRECTORY = os.getcwd()
COMPETITIONS_DB = DATA_DIRECTORY + "/db/competitions.sqlite"
# ID, date, name, location
COMPETITIONS_TABLE = "competitions"
# ID, name, club, m/f, list of climbs
CLIMBERS_TABLE = "climbers"
FSGT_APP_ID = os.getenv('FSGT_APP_ID')
FSGT_APP_SECRET = os.getenv('FSGT_APP_SECRET')
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
#skala_api_app = APIBlueprint('skala_api', __name__, url_prefix='/api1', doc_ui=True, abp_tags= [book_tag, comp_tag])
skala_api_app = Blueprint('skala_api', __name__, url_prefix='/api1')
skala_api_app.debug = True
skala_api_app.secret_key = 'development'
oauth = OAuth(skala_api_app)
genres = {"test": "1"}
authenticated = False
# Third party libraries
from flask import Flask, redirect, request, url_for
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from oauthlib.oauth2 import WebApplicationClient
import requests
# Internal imports
# Flask app setup
skala_api_app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)
UPLOAD_FOLDER = os.path.join(DATA_DIRECTORY,'uploads')
ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg', 'gif'])
# skala_api_app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#from flask_openapi3 import Info, Tag
#from flask_openapi3 import OpenAPI
#info = Info(title="book API", version="1.0.0")
#book_tag = Tag(name="book", description="Some Book")
class Activity1(BaseModel):
activity_name: str
gym_id: str
date: datetime
# User session management setup
# https://flask-login.readthedocs.io/en/latest
@skala_api_app.before_request
def x(*args, **kwargs):
#logging.debug('api before request '+str(session.get('language'))+ ' accepted languages='+str(request.accept_languages))
if not session.get('language'):
#kk = competitionsEngine.supported_languages.keys()
language = request.accept_languages.best_match(competitionsEngine.supported_languages.keys())
if language is None:
language = 'fr_FR'
session['language'] = language
#logging.debug ("api setting language to session language="+str(session['language']))
langpack = competitionsEngine.reference_data['languages'][session['language']]
competitionsEngine.reference_data['current_language'] = langpack
@skala_api_app.route('/api/language/<language>')
def set_language(language=None):
if language is None:
language = 'fr_FR'
session['language'] = language
logging.debug('api setting language requested to '+str(language))
langpack = competitionsEngine.reference_data['languages'][language]
competitionsEngine.reference_data['current_language'] = langpack
return language
@skala_api_app.route('/language')
def get_language():
if not session.get('language'):
return json.dumps({'language': 'fr_FR'})
else:
return json.dumps({'language': session['language']})
@skala_api_app.route('/langpack')
def get_langpack():
if not session.get('language'):
return json.dumps(competitionsEngine.reference_data['languages']['fr_FR'])
else:
return json.dumps(competitionsEngine.reference_data['languages'][session.get('language')])
def is_logged_in():
if session is not None and session.get('expires_at') is not None:
return True
else:
session["wants_url"] = request.url
return False
def login_required(fn):
@wraps(fn)
def decorated_function(*args, **kwargs):
if is_logged_in():
return fn(*args, **kwargs)
else:
return redirect(url_for("skala_api_app.fsgtlogin"))
return decorated_function
def admin_required(fn):
@wraps(fn)
def decorated_function(*args, **kwargs):
if session != None:
user = competitionsEngine.get_user_by_email(session['email'])
if user is not None:
permissions = user.get('permissions')
if 'create_gym' in permissions['general'] or permissions['godmode'] == True:
return fn(*args, **kwargs)
if session.get('name') == 'David Mossakowski' or session.get('name') == 'Sebastiao Correia':
return fn(*args, **kwargs)
else:
session["wants_url"] = request.url
return redirect(url_for("app_ui.fsgtlogin"))
return decorated_function
#@skala_api_app.get('/apitest', tags=[book_tag, comp_tag])
def testapi():
return {"code": 0, "message": "ok"}
@skala_api_app.post('/competitionRawAdmin')
@login_required
def fsgtadmin():
edittype = request.form.get('edittype')
id = request.form.get('id')
action = request.form.get('action')
jsondata = request.form.get('jsondata')
comp = {}
jsonobject = None
if jsondata is not None and len(jsondata) > 2:
jsonobject = json.loads(jsondata)
if edittype == 'user':
if jsonobject is not None and action == 'update':
competitionsEngine.upsert_user(jsonobject)
if id is not None and action == 'find':
jsonobject = competitionsEngine.get_user_by_email(id)
if id is not None and action == 'findall':
jsonobject = competitionsEngine.get_all_user_emails()
elif edittype == 'competition':
if jsonobject is not None and action == 'update':
#jsonobject = {"success": "competition updated"}
competitionsEngine._update_competition(jsonobject['id'],jsonobject)
if id is not None and action == 'delete':
#jsonobject = {"success": "competition updated"}
competitionsEngine.delete_competition(id)
if id is not None and action == 'find':
jsonobject = competitionsEngine.getCompetition(id)
if id is not None and action == 'findall':
jsonobject = competitionsEngine.get_all_competition_ids()
elif edittype == 'gym':
if jsonobject is not None and action == 'update':
#jsonobject = {"success": "competition updated"}
competitionsEngine.update_gym(jsonobject['id'], jsonobject)
if id is not None and action == 'find':
jsonobject = competitionsEngine.get_gym(id)
if id is not None and action == 'findall':
jsonobject = competitionsEngine.get_gyms()
elif edittype == 'routes':
if jsonobject is not None and action == 'update':
#jsonobject = {"success": "competition updated"}
# None is gymid but this is ok as the routes id will be found
competitionsEngine.upsert_routes(id, None, jsonobject)
if id is not None and action == 'find':
jsonobject = competitionsEngine.get_routes(id)
if id is not None and action == 'findall':
jsonobject = competitionsEngine.get_all_routes_ids()
else:
jsonobject = {"error": "choose edit type" }
return render_template('competitionRawAdmin.html',
jsondata=json.dumps(jsonobject),
reference_data=competitionsEngine.reference_data,
id=id)
@skala_api_app.route('/competition_admin/<competition_id>', methods=['POST'])
@login_required
def competition_admin_post(competition_id):
remove_climber = request.form.get('remove_climber')
update_status = request.form.get('update_status')
permission_user = request.form.get('permission_user')
competition_update_button = request.form.get('competition_update_button')
edittype = request.form.get('edittype')
permissioned_user = request.form.get('permissioned_user')
id = request.form.get('id')
action = request.form.get('action')
competition_status = request.form.get('competition_status')
instructions = request.form.get('instructions')
jsondata = request.form.get('jsondata')
comp = {}
jsonobject = None
user = competitionsEngine.get_user_by_email(session['email'])
competition = competitionsEngine.getCompetition(competition_id)
if user is None or competition is None or not competitionsEngine.can_edit_competition(user,competition):
session["wants_url"] = request.url
return redirect(url_for("skala_api_app.fsgtlogin"))
# add this competition to another user's permissions
# remove this competition from another users permissions
# change the state of a competition
# remove climber from a competition
if permission_user is not None:
user2 = competitionsEngine.get_user_by_email(permissioned_user)
competitionsEngine.modify_user_permissions_to_competition(user, competition_id)
if update_status is not None:
competition['status'] = int(competition_status)
competitionsEngine.update_competition(competition_id, competition)
if remove_climber is not None:
competition['climbers'].pop(remove_climber)
competitionsEngine.update_competition(competition['id'], competition)
if competition_update_button is not None:
competition_name = request.form.get('competition_name')
competition_date = request.form.get('competition_date')
competition_routes = request.form.get('competition_routes')
competitionsEngine.update_competition_details(competition, competition_name, competition_date, competition_routes, instructions)
user_list = competitionsEngine.get_all_user_emails()
all_routes = competitionsEngine.get_routes_by_gym_id(competition['gym_id'])
return render_template('competitionAdmin.html',
jsondata=json.dumps(jsonobject),
user=user,
competition=competition,
user_list=user_list,
competitionId=competition_id,
all_routes = all_routes,
reference_data=competitionsEngine.reference_data,
id=id)
@skala_api_app.get('/activities')
@login_required
def get_activities():
user = competitionsEngine.get_user_by_email(session['email'])
activitiesA = activities_db.get_activities(user.get('id'))
allActivities = activities_db.get_activities_all_anonymous()
activities = {}
activities['activities'] = activitiesA
avg_stats = []
user_stats = []
user_activities_stats = calculate_activities_stats(activitiesA)
all_activities_stats = calculate_activities_stats(allActivities)
combined_dates = sorted(set(user_activities_stats['dates'] + all_activities_stats['dates']), reverse=False)
# Limit the combined_dates list to only the last 26 items
combined_dates = combined_dates[-25:]
# Create a dictionary for all_activities_stats for quick lookups
all_activities_dict = {date: count for date, count in zip(all_activities_stats['dates'], all_activities_stats['routes_done'])}
# Loop through user_activities_stats and check if the date exists in all_activities_stats
for date in combined_dates:
if date in all_activities_dict:
avg_stats.append(all_activities_dict[date])
else:
avg_stats.append(0)
if date in user_activities_stats['dates']:
user_stats.append(user_activities_stats['routes_done'][user_activities_stats['dates'].index(date)])
else:
user_stats.append(0)
activities['stats'] = {}
activities['stats']['dates'] = combined_dates
activities['stats']['routes_done'] = user_stats
activities['stats']['routes_avg'] = avg_stats
return json.dumps(activities)
#calculates number of routes done per day
def calculate_activities_stats_per_day(activities):
# Get today's date
today = datetime.today().date()
stats = {}
# Create a dictionary with dates 30 days back from today as keys and 0 as initial values
routes_done = {(today - timedelta(days=i)).strftime('%Y-%m-%d'): 0 for i in range(160, -1, -1)}
for activity in activities:
if activity.get('date') is None:
continue
# Parse the 'date' into a date object
activity_date = activity['date']
# If the activity date is in the routes_done dictionary, add the number of routes
if activity_date in routes_done:
routes_done[activity_date] += len(activity['routes'])
# Convert the dictionary to a list of values
routes_done_list = list(routes_done.values())
stats['dates'] = list(routes_done.keys())
stats['routes_done'] = routes_done_list
return stats
# calculates number of activities per day
def calculate_activities_stats(activities):
# Initialize a dictionary to store the count of routes done per week
weekly_stats = defaultdict(int)
for activity in activities:
# Parse the date of the activity
activity_date = datetime.strptime(activity['date'], '%Y-%m-%d')
# Find the Monday of the week for the activity date
start_of_week = activity_date - timedelta(days=activity_date.weekday())
# Increment the count of routes done for that week
weekly_stats[start_of_week] += len(activity['routes'])
# Convert the weekly_stats dictionary to a sorted list of tuples
sorted_weekly_stats = sorted(weekly_stats.items())
# Initialize the result dictionary with dates and routes_done lists
result = {'dates': [], 'routes_done': []}
# Populate the result dictionary
for week_start, count in sorted_weekly_stats:
result['dates'].append(week_start.strftime('%Y-%m-%d'))
result['routes_done'].append(count)
return result
@skala_api_app.get('/activities/all')
def get_activities_all():
activities = activities_db.get_activities_all_anonymous()
#return json.dumps(activities)
return activities
@skala_api_app.post('/activity')
@login_required
def journey_add():
user = competitionsEngine.get_user_by_email(session['email'])
data = request.get_json()
#data = request.get_data()
# get the data from the body of the request
date = data.get('date')
gym_id = data.get('gym_id')
name = data.get('activity_name')
comp = {}
gym = competitionsEngine.get_gym(gym_id)
routesid = gym.get('routesid')
#a = Activity1(**data)
activity_id = activities_db.add_activity(user, gym, routesid, name, date)
activity = activities_db.get_activity(activity_id)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return json.dumps(activity)
@skala_api_app.delete('/activity/<activity_id>')
@login_required
def delete_activity(activity_id):
user = competitionsEngine.get_user_by_email(session['email'])
activity = activities_db.get_activity(activity_id)
if (activity is None):
return {"error":"activity not found"}
#a = Activity1(**data)
activities_db.delete_activity(activity_id)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return {}
@skala_api_app.get('/activity/<activity_id>')
@login_required
def get_activity(activity_id):
user = competitionsEngine.get_user_by_email(session['email'])
activity = activities_db.get_activity(activity_id)
if (activity is None):
return {"error":"activity not found"}
#a = Activity1(**data)
activity = activities_db.get_activity(activity_id)
#activity = calculate_activity_stats(activity)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return json.dumps(activity)
# add a route to an activity
@skala_api_app.post('/activity/<activity_id>')
@login_required
def add_activity_route(activity_id):
user = competitionsEngine.get_user_by_email(session['email'])
data = request.get_json()
#data = request.get_data()
# get the data from the body of the request
gym_id = data.get('gym_id')
routes_id = data.get('routes_id')
routes = competitionsEngine.get_routes(routes_id)
route_id = data.get('route_id')
note = data.get('note')
route_finish_status = data.get('route_finish_status')
grade = data.get('grade')
user_grade = data.get('route-grade-user')
route = competitionsEngine.get_route(routes_id, route_id)
activity = activities_db.add_activity_entry(activity_id, route, route_finish_status, note, user_grade)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return json.dumps(activity)
@skala_api_app.get('/activity/user/<user_id>')
@login_required
def get_activities_by_user(user_id):
user = competitionsEngine.get_user_by_email(session['email'])
activity = activities_db.get_activities_by_gym_routes(activity_id)
if (activity is None):
return {"error":"activity not found"}
#a = Activity1(**data)
# journey_id = user.get('journey_id')
# calculate_activity_stats(activity)
#journeys = activities_db.get_activities(user.get('id'))
return {}
@skala_api_app.get('/activity/gym/<gym_id>/routes/<routes_id>')
def get_activities_by_gym_by_routes(gym_id, routes_id):
activities = activities_db.get_activities_by_gym_routes(gym_id, routes_id)
if (activities is None or len(activities) == 0):
return {"error":"activity not found"}
#a = Activity1(**data)
# journey_id = user.get('journey_id')
# calculate_activity_stats(activity)
#journeys = activities_db.get_activities(user.get('id'))
return json.dumps(activities)
@skala_api_app.route('/journey/<journey_id>', methods=['GET'])
@login_required
def journey_session(journey_id):
journey = activities_db.get_journey_session(journey_id)
return journey
@skala_api_app.delete('/activity/<activity_id>/route/<route_id>')
@login_required
def delete_activity_route(activity_id, route_id):
user = competitionsEngine.get_user_by_email(session['email'])
activity = activities_db.get_activity(activity_id)
if (activity is None):
return {"error":"activity not found"}
#a = Activity1(**data)
activity = activities_db.delete_activity_route(activity_id, route_id)
# journey_id = user.get('journey_id')
#journeys = activities_db.get_activities(user.get('id'))
return activity
def calculate_activity_stats(activity):
routes = activity.get('routes')
routes_count = len(routes)
grades_climbed = []
for route in routes:
route['grade_index'] = grades.index(route['grade'])
#route['grade_points'] = np.exp(-((route['grade_index'] - mean) / std_dev) ** 2 / 2)
if route['status'] == 'climbed' or route['status'] == 'flashed':
grades_climbed.append(route['grade'])
avg_grade_climbed = avg_grade(routes)
activity['stats'] = {}
activity['stats']['routes_count'] = routes_count
activity['stats']['avg_grade_climbed'] = avg_grade_climbed
return activity
def avg_grade(routes, flash_weight=2, climb_weight=1, attempt_weight=0.1):
if not routes:
return None
# Convert grades to indices and apply weights
weighted_indices = []
for route in routes:
grade = route['grade']
status = route['status']
if status == 'flashed':
weight = flash_weight
elif status == 'climbed':
weight = climb_weight
else: # status is 'attempted' or anything else
weight = attempt_weight
weighted_indices.append(grades.index(grade) * weight)
# Calculate average index
average_index = sum(weighted_indices) / sum(flash_weight if route['status'] == 'flashed' else climb_weight if route['status'] == 'climbed' else attempt_weight for route in routes)
# Round to nearest integer
average_index = round(average_index)
# Convert index back to grade
average_grade = grades[average_index]
return average_grade
@skala_api_app.route('/journey/<journey_id>/add', methods=['POST'])
@login_required
def journey_session_entry_add(journey_id):
user = competitionsEngine.get_user_by_email(session['email'])
route_finish_status = request.form.get('route_finish_status')
route_id = request.form.get('route')
notes = request.form.get('notes')
comp = {}
journey = activities_db.get_journey_session(journey_id)
journey = activities_db.add_journey_session_entry(journey_id,route_id, route_finish_status, notes)
routes = competitionsEngine.get_routes(journey.get('routes_id'))
return render_template('skala-journey-session.html',
user=user,
journey=journey,
routes=routes,
reference_data=competitionsEngine.reference_data,
)
@skala_api_app.route('/journey/<journey_id>/<route_id>/remove', methods=['GET'])
@login_required
def journey_session_remove(journey_id, route_id):
user = competitionsEngine.get_user_by_email(session['email'])
journey = activities_db.get_journey_session(journey_id)
testid = request.args.get('testid')
if journey is None:
return {}
activities_db.remove_journey_session(journey_id, route_id)
routes = competitionsEngine.get_routes(journey.get('routes_id'))
return {}
@skala_api_app.route('/competition/list')
def getCompetitionDashboard():
comps = competitionsEngine.getCompetitions()
compsreturnd = []
language = session.get('language', 'fr')[:2]
# for each competition remove object climbers
for compid in comps:
c={}
comps[compid]['climbers'] = None
comps[compid]['routes'] = None
c['title'] = comps[compid]['name']
c['id'] = comps[compid]['gym_id']
#c['start'] = comps[compid]['date']+ "T11:00:00"
#c['end'] = comps[compid]['date']+ "T15:59:59"
c['date'] = comps[compid]['date']
c['extendedProps'] = comps[compid]
c['url'] = '/competitionDetails/'+compid
c['text'] = {}
c['text']['status'] = competitionsEngine.reference_data['current_language'].get('competition_status_'+str(comps[compid]['status']))
compsreturnd.append(c)
logging.debug('setting language of competitions to '+str(language)+' session language='+str(session.get('language')))
return json.dumps(compsreturnd)
@skala_api_app.route('/competition/<competition_id>')
def get_competition_by_id(competition_id):
competition = competitionsEngine.getCompetition(competition_id)
if competition is None:
return {}
for climber in competition.get('climbers').values():
climber.pop('email', None)
if competition is None:
return {"error": "competition not found"}
return competition
@skala_api_app.route('/competition/year/<year>')
def competitions_by_year(year):
username = session.get('username')
#if username:
# return 'logged in '+str(username)
#print(username)
#username = request.args.get('username')
name = request.args.get('name')
date = request.args.get('date')
gym = request.args.get('gym')
comp = {}
competitionId=None
if not year.isdigit():
year = datetime.now().year
user = competitionsEngine.get_user_by_email(session.get('email'))
subheader_message = request.accept_languages
langs = competitionsEngine.reference_data['languages']
competitions = competitionsEngine.getCompetitions()
#test_list = [datetime(year, 1, 1), datetime(year, 12, 31)]
date_strt, date_end = datetime(int(year), 1, 1), datetime(int(year), 12, 31)
input_format = "%Y-%m-%d"
competitions2 = {}
for competition_id in competitions:
competition = competitions.get(competition_id)
competition_date = competition.get('date')
try:
parsered_date = datetime.strptime(competition_date, input_format)
if parsered_date >= date_strt and parsered_date <= date_end:
res = True
competitions2[competition['id']] = competition
except ValueError:
print("This is the incorrect date string format.")
return competitions2
@skala_api_app.route('/competition/create', methods=['POST'])
@login_required
def new_competition_post():
username = session.get('username')
routedata = request.get_json()
routedata = json.loads(routedata)
#username = request.args.get('username')
name = request.form.get('name')
date = request.form.get('date')
#gym = request.form.get('gym')
routesid = request.form.get('routes')
comp = {}
competitionId = None
user = competitionsEngine.get_user_by_email(session.get('email'))
if user is None or not competitionsEngine.can_create_competition(user):
return "{ 'error'; 'Not authorized'}"
if name is not None and date is not None and routesid is not None:
competitionId = competitionsEngine.addCompetition(None, name, date, routesid)
competitionsEngine.modify_user_permissions_to_competition(user, competitionId, "ADD")
comp = competitionsEngine.getCompetition(competitionId)
return comp
return "{ 'error'; 'Not created. Something missing'}"
@skala_api_app.route('/competition/<competitionId>/register')
#@login_required
def addCompetitionClimber(competitionId):
return None
# Statistics for a competition
@skala_api_app.route('/competition/<competitionId>/stats')
#@login_required
def getCompetitionStats(competitionId):
competition = None
if competitionId is not None:
competition = competitionsEngine.recalculate(competitionId)
if competition is None:
return render_template('competitionDashboard.html', sortedA=None,
subheader_message="No competition found",
**session)
elif competition is LookupError:
return render_template('index.html', sortedA=None,
getPlaylistError="Playlist was not found",
library={},
**session)
elif len(competition) == 0:
return render_template('index.html', sortedA=None,
getPlaylistError="Playlist has no tracks or it was not found",
library={},
**session)
routesid = competition.get('routesid')
routesDict = competitionsEngine.get_routes(routesid)
routes = routesDict['routes']
#rankings = competitionsEngine.get_sorted_rankings(competition)
# we need 6 categories:
categories = ["F0","F1","F2","M0","M1","M2"]
#category_names = [reference_data['current_language'].ranking_diament_women,
# reference_data['current_language'].ranking_titan_women,
# reference_data['current_language'].ranking_senior_women,
# reference_data['current_language'].ranking_diament_men,
# reference_data['current_language'].ranking_titan_men,
# reference_data['current_language'].ranking_senior_men]
statistics = {}
for category in categories:
repeatArray = [0]*len(routes)
statistics[str(category)]=repeatArray
for climber in competition['climbers'].values():
key = str(climber.get('sex'))+str(climber.get('category'))
stats = statistics.get(key)
for routenum in climber.get('routesClimbed'):
if climber.get('sex') == 'M':
stats[routenum-1]=stats[routenum-1]+1
else:
stats[routenum-1]=stats[routenum-1]+1 # can make -1 to have a stacked chart with males and females
statout = []
for category in categories:
statout.append( { #"name":category,
"data": statistics.get(category)})
statresponse = { "chartdata": statout,
"routedata" : routes}
return json.dumps(statresponse)
### USER
@skala_api_app.route('/user')
def get_user():
if session is None or session.get('email') is None:
return {}
user = competitionsEngine.get_user_by_email(session['email'])
if user is None:
return {}
return json.dumps(user)
@skala_api_app.route('/user/email')
@admin_required
def get_users():
if session is None or session.get('email') is None:
return {}
user = competitionsEngine.get_user_by_email(session['email'])
if user is None:
return {}
if competitionsEngine.can_edit_users(user):
users = skala_db.get_all_user_emails()
return json.dumps(users)
return json.dumps(user)
@skala_api_app.route('/user/email/<email>')
@admin_required
def get_user_by_email(email):
climber = competitionsEngine.get_user_by_email(email)
if climber is None:
#return "{'error_code':'No such user'}", 400
return {}
return climber
@skala_api_app.route('/gym/<gym_id>/users')
def get_users_by_gym(gym_id):
users= skala_db.get_users_by_gym_id(gym_id)
# remove email and permissions from the response
for user in users:
user.pop('email', None)
#user.pop('permissions', None)
user.pop('isgod',None)
if user.get('fpictureurl') is not None:
user['pictureurl'] = user.get('fpictureurl')
if user.get('gpictureurl') is not None:
user['pictureurl'] = user.get('gpictureurl')
if user.get('fpictureurl') is None and user.get('gpictureurl') is None:
#user['pictureurl'] = '/public/images/sentiment_satisfied_FILL0_wght600_GRAD200_opsz48.png'
user['pictureurl'] = '/public/images/favicon.png'
if user.get('firstname') is None:
user['firstname'] = user.get('name')
return users
@skala_api_app.route('/users/search/')
def get_all_users():
search_string = request.args.get('q')
if search_string is None or len(search_string) < 2 or not search_string.isalnum():
return []
users= skala_db.search_all_users(search_string=search_string)
# remove email and permissions from the response
for user in users:
user.pop('email', None)
#user.pop('permissions', None)
user.pop('isgod',None)
if user.get('fpictureurl') is not None:
user['pictureurl'] = user.get('fpictureurl')
if user.get('gpictureurl') is not None:
user['pictureurl'] = user.get('gpictureurl')
if user.get('fpictureurl') is None and user.get('gpictureurl') is None:
#user['pictureurl'] = '/public/images/sentiment_satisfied_FILL0_wght600_GRAD200_opsz48.png'
user['pictureurl'] = '/public/images/favicon.png'
if user.get('firstname') is None:
user['firstname'] = user.get('name')
#json.dumps(users)
return json.dumps(users)
@skala_api_app.route('/updateuser')
def update_user():
if session.get('email') is None:
return render_template('competitionDashboard.html', sortedA=None,
subheader_message="No competition found",
**session)
climber = competitionsEngine.get_user_by_email(session.get('email'))