-
Notifications
You must be signed in to change notification settings - Fork 3
/
Api.py
3023 lines (2488 loc) · 142 KB
/
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
# -*- coding: utf-8 -*-
#
# # MIT License
#
# Copyright (c) 2017 Michael J Simms
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""API request handlers"""
import calendar
import datetime
import json
import logging
import time
import uuid
import ApiException
import Exporter
import InputChecker
import Keys
import Units
import TrainingPaceCalculator
import Workout
from urllib.parse import unquote_plus
from distutils.util import strtobool
class Api(object):
"""Class for managing API messages."""
def __init__(self, config, user_mgr, data_mgr, user_id, root_url):
super(Api, self).__init__()
self.config = config
self.user_mgr = user_mgr
self.data_mgr = data_mgr
self.user_id = user_id
self.root_url = root_url
def log_api_call(self, request, values):
"""Writes an info message to the log file."""
log_str = request + json.dumps(values)
logger = logging.getLogger()
logger.debug(log_str)
def log_error(self, log_str):
"""Writes an error message to the log file."""
logger = logging.getLogger()
logger.error(log_str)
def activity_belongs_to_logged_in_user(self, activity):
"""Returns True if the specified activity belongs to the logged in user."""
if self.user_id is None:
return False
activity_user_id, _, _ = self.data_mgr.get_activity_user(activity)
belongs_to_current_user = str(activity_user_id) == str(self.user_id)
return belongs_to_current_user
def activity_can_be_viewed(self, activity):
"""Determine if the requesting user can view the activity."""
if self.user_id is None:
return self.data_mgr.is_activity_public(activity)
activity_user_id, _, _ = self.data_mgr.get_activity_user(activity)
belongs_to_current_user = belongs_to_current_user = str(activity_user_id) == str(self.user_id)
return self.data_mgr.is_activity_public(activity) or belongs_to_current_user
def activity_id_can_be_viewed(self, activity_id):
"""Determine if the requesting user can view the activity."""
if self.user_id is None:
return self.data_mgr.is_activity_id_public(activity_id)
activity_user_id, _, _ = self.data_mgr.get_activity_id_from_user(activity_id)
belongs_to_current_user = belongs_to_current_user = str(activity_user_id) == str(self.user_id)
return self.data_mgr.is_activity_id_public(activity_id) or belongs_to_current_user
def parse_json_loc_obj(self, json_obj, sensor_readings_dict, metadata_list_dict):
"""Helper function that parses the JSON object, which contains location data, and updates the database."""
location = []
try:
# Parse the metadata for the timestamp.
if Keys.APP_TIME_KEY in json_obj:
time_str = json_obj[Keys.APP_TIME_KEY]
date_time = int(time_str)
else:
date_time = int(time.time() * 1000)
# Parse the location data.
try:
lat = json_obj[Keys.APP_LOCATION_LAT_KEY]
lon = json_obj[Keys.APP_LOCATION_LON_KEY]
alt = json_obj[Keys.APP_LOCATION_ALT_KEY]
horizontal_accuracy = json_obj[Keys.APP_HORIZONTAL_ACCURACY_KEY]
vertical_accuracy = json_obj[Keys.APP_VERTICAL_ACCURACY_KEY]
location = [ date_time, lat, lon, alt, horizontal_accuracy, vertical_accuracy ]
except ValueError as e:
self.log_error("ValueError in JSON location data - reason " + str(e) + ". JSON str = " + str(json_obj))
except KeyError as e:
self.log_error("KeyError in JSON location data - reason " + str(e) + ". JSON str = " + str(json_obj))
except:
self.log_error("Error parsing JSON location data. JSON object = " + str(json_obj))
# Parse the rest of the data, which will be a combination of metadata and sensor data.
for item in json_obj.items():
key = item[0]
time_value_pair = []
time_value_pair.append(date_time)
time_value_pair.append(float(item[1]))
if key in [ Keys.APP_CADENCE_KEY, Keys.APP_HEART_RATE_KEY, Keys.APP_POWER_KEY, Keys.APP_THREAT_COUNT_KEY ]:
if key not in sensor_readings_dict:
sensor_readings_dict[key] = []
value_list = sensor_readings_dict[key]
value_list.append(time_value_pair)
elif key in [ Keys.APP_CURRENT_SPEED_KEY, Keys.APP_CURRENT_PACE_KEY ]:
if key not in metadata_list_dict:
metadata_list_dict[key] = []
value_list = metadata_list_dict[key]
value_list.append(time_value_pair)
except ValueError as e:
self.log_error("ValueError in JSON meta and sensor data - reason " + str(e) + ". JSON str = " + str(json_obj))
except KeyError as e:
self.log_error("KeyError in JSON meta and sensor data - reason " + str(e) + ". JSON str = " + str(json_obj))
except:
self.log_error("Error parsing JSON meta and sensor data. JSON object = " + str(json_obj))
return location
def parse_json_accel_obj(self, json_obj):
"""Helper function that parses the JSON object, which contains accelerometer data, and updates the database."""
accel = []
try:
# Parse the metadata for the timestamp.
date_time = int(time.time() * 1000)
if Keys.APP_TIME_KEY in json_obj:
time_str = json_obj[Keys.APP_TIME_KEY]
date_time = int(time_str)
x = json_obj[Keys.APP_AXIS_NAME_X]
y = json_obj[Keys.APP_AXIS_NAME_Y]
z = json_obj[Keys.APP_AXIS_NAME_Z]
accel = [ date_time, x, y, z ]
except ValueError as e:
self.log_error("ValueError in JSON accelerometer data - reason " + str(e) + ". JSON str = " + str(json_obj))
except KeyError as e:
self.log_error("KeyError in JSON accelerometer data - reason " + str(e) + ". JSON str = " + str(json_obj))
except:
self.log_error("Error parsing JSON accelerometer data. JSON object = " + str(json_obj))
return accel
def handle_update_status(self, values):
"""Called when an API message to update the status of a device is received."""
device_str = ""
activity_id = ""
activity_type = ""
username = ""
battery_level = None
locations = []
sensor_readings_dict = {}
metadata_list_dict = {}
# Parse required identifiers.
device_str = values[Keys.APP_DEVICE_ID_KEY]
activity_id = values[Keys.APP_ID_KEY]
# Parse optional identifiers.
if Keys.APP_TYPE_KEY in values:
activity_type = values[Keys.APP_TYPE_KEY]
if Keys.APP_USERNAME_KEY in values:
username = values[Keys.APP_USERNAME_KEY]
if Keys.APP_BATTERY_LEVEL_KEY in values:
battery_level = values[Keys.APP_BATTERY_LEVEL_KEY]
if Keys.APP_LOCATIONS_KEY in values:
# Parse each of the location objects. Check for invalid data.
encoded_locations = values[Keys.APP_LOCATIONS_KEY]
for location_obj in encoded_locations:
location = self.parse_json_loc_obj(location_obj, sensor_readings_dict, metadata_list_dict)
# Ignore invalid readings. Invalid lat/lon are indicated as -1, but extremely high values should be ignored too. Units are meters.
if InputChecker.is_valid_location(location[1], location[2], location[4]):
locations.append(location)
# Update the activity.
if locations:
self.data_mgr.update_moving_activity(device_str, activity_id, locations, sensor_readings_dict, metadata_list_dict)
if Keys.APP_ACCELEROMETER_KEY in values:
# Parse each of the accelerometer objects.
accels = []
encoded_accel = values[Keys.APP_ACCELEROMETER_KEY]
for accel_obj in encoded_accel:
accel = self.parse_json_accel_obj(accel_obj)
accels.append(accel)
# Update the accelerometer readings.
if accels:
self.data_mgr.create_activity_accelerometer_reading(device_str, activity_id, accels)
# Update the activity type.
activity_type_updated = False
if len(activity_type) > 0:
# If the activity type was updated then set the default gear (will be done later after user id validation).
activity_type_updated = self.data_mgr.create_activity_metadata(activity_id, 0, Keys.ACTIVITY_TYPE_KEY, activity_type, False)
# Valid user?
if len(username) > 0:
temp_user_id, _, _ = self.user_mgr.retrieve_user(username)
if temp_user_id == self.user_id:
# Update the user device association.
user_devices = self.user_mgr.retrieve_user_devices(self.user_id)
if user_devices is not None and device_str not in user_devices:
self.user_mgr.create_user_device_for_user_id(self.user_id, device_str)
# Set the default gear.
if activity_type_updated:
self.data_mgr.create_default_tags_on_activity(self.user_id, activity_type, activity_id)
# Battery level?
if battery_level is not None:
self.data_mgr.create_activity_battery_level_reading(activity_id, battery_level)
# Analysis is now obsolete, so delete it.
self.data_mgr.delete_activity_summary(activity_id)
return True, ""
def handle_retrieve_activity_track(self, values):
"""Called when an API message to get the activity track is received. Result is a JSON string."""
# Required parameters.
if Keys.ACTIVITY_ID_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity ID not specified.")
if Keys.ACTIVITY_NUM_POINTS not in values:
raise ApiException.ApiMalformedRequestException("Number of datapoints not specified.")
# Get the device and activity IDs from the request.
activity_id = values[Keys.ACTIVITY_ID_KEY]
if not InputChecker.is_uuid(activity_id):
raise ApiException.ApiMalformedRequestException("Invalid activity ID.")
# Validate the number of points to retrieve.
num_points = values[Keys.ACTIVITY_NUM_POINTS]
if not InputChecker.is_unsigned_integer(num_points):
raise ApiException.ApiMalformedRequestException("Invalid number of points.")
num_points = int(num_points)
# Get the activity from the database.
activity = self.data_mgr.retrieve_activity(activity_id)
# Determine if the requesting user can view the activity.
if not self.activity_can_be_viewed(activity):
raise ApiException.ApiMalformedRequestException("The requested activity is not viewable to this user.")
# Format the locations track as JSON.
response = ""
if Keys.APP_LOCATIONS_KEY in activity:
locations = activity[Keys.APP_LOCATIONS_KEY]
response += json.dumps(locations[num_points:])
return True, response
def handle_retrieve_activity_metadata(self, values):
"""Called when an API message to get the activity metadata. Result is a JSON string."""
# Required parameters.
if Keys.ACTIVITY_ID_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity ID not specified.")
# Get the activity ID from the request.
activity_id = values[Keys.ACTIVITY_ID_KEY]
if not InputChecker.is_uuid(activity_id):
raise ApiException.ApiMalformedRequestException("Invalid activity ID.")
# Get the activity from the database.
activity = self.data_mgr.retrieve_activity(activity_id)
if activity is None:
raise ApiException.ApiMalformedRequestException("Invalid activity.")
# Determine if the requesting user can view the activity.
if not self.activity_can_be_viewed(activity):
raise ApiException.ApiMalformedRequestException("The requested activity is not viewable to this user.")
# Is this is a foot based activity? Need to know so we can display steps per minute instead of revs per minute.
is_foot_based = False
response_dict = {}
response_dict[Keys.ACTIVITY_ID_KEY] = activity_id
if Keys.ACTIVITY_NAME_KEY in activity:
activity_name = activity[Keys.ACTIVITY_NAME_KEY]
if activity_name is not None and len(activity_name) > 0:
response_dict[Keys.ACTIVITY_NAME_KEY] = activity_name
if Keys.ACTIVITY_TYPE_KEY in activity:
activity_type = activity[Keys.ACTIVITY_TYPE_KEY]
if activity_type is not None and len(activity_type) > 0:
is_foot_based = activity_type in Keys.FOOT_BASED_ACTIVITIES
response_dict["Type"] = activity_type
if Keys.ACTIVITY_DESCRIPTION_KEY in activity:
activity_description = activity[Keys.ACTIVITY_DESCRIPTION_KEY]
if activity_description is not None and len(activity_description) > 0:
response_dict[Keys.ACTIVITY_DESCRIPTION_KEY] = activity_description
if Keys.ACTIVITY_START_TIME_KEY in activity:
activity_time = activity[Keys.ACTIVITY_START_TIME_KEY]
if activity_time is not None:
response_dict["Time"] = activity_time
if Keys.ACTIVITY_TAGS_KEY in activity:
tags = activity[Keys.ACTIVITY_TAGS_KEY]
response_dict[Keys.ACTIVITY_TAGS_KEY] = tags
if Keys.APP_DISTANCE_KEY in activity:
distances = activity[Keys.APP_DISTANCE_KEY]
if distances is not None and len(distances) > 0:
distance = distances[-1]
value = float(list(distance.values())[0])
response_dict[Keys.APP_DISTANCE_KEY] = value
if Keys.APP_AVG_SPEED_KEY in activity:
avg_speeds = activity[Keys.APP_AVG_SPEED_KEY]
if avg_speeds is not None and len(avg_speeds) > 0:
speed = avg_speeds[-1]
value = float(list(speed.values())[0])
response_dict[Keys.APP_AVG_SPEED_KEY] = value
if Keys.APP_MOVING_SPEED_KEY in activity:
moving_speeds = activity[Keys.APP_MOVING_SPEED_KEY]
if moving_speeds is not None and len(moving_speeds) > 0:
speed = moving_speeds[-1]
value = float(list(speed.values())[0])
response_dict[Keys.APP_MOVING_SPEED_KEY] = value
if Keys.APP_HEART_RATE_KEY in activity:
heart_rates = activity[Keys.APP_HEART_RATE_KEY]
if heart_rates is not None and len(heart_rates) > 0:
heart_rate = heart_rates[-1]
value = float(list(heart_rate.values())[0])
response_dict[Keys.APP_HEART_RATE_KEY] = value
if Keys.APP_CADENCE_KEY in activity:
cadences = activity[Keys.APP_CADENCE_KEY]
if cadences is not None and len(cadences) > 0:
cadence = cadences[-1]
value = float(list(cadence.values())[0])
if is_foot_based:
value = value * 2.0
response_dict[Keys.APP_CADENCE_KEY] = value
if Keys.APP_POWER_KEY in activity:
powers = activity[Keys.APP_POWER_KEY]
if powers is not None and len(powers) > 0:
power = powers[-1]
value = float(list(power.values())[0])
response_dict[Keys.APP_POWER_KEY] = value
response = json.dumps(response_dict)
return True, response
def handle_retrieve_activity_sensordata(self, values):
"""Called when an API message to get the activity sensordata. Result is a JSON string."""
# Required parameters.
if Keys.ACTIVITY_ID_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity ID not specified.")
if Keys.SENSOR_LIST_KEY not in values:
raise ApiException.ApiMalformedRequestException("Sensor list not specified.")
# Get the activity ID from the request.
activity_id = values[Keys.ACTIVITY_ID_KEY]
if not InputChecker.is_uuid(activity_id):
raise ApiException.ApiMalformedRequestException("Invalid activity ID.")
# Get the activity from the database.
activity = self.data_mgr.retrieve_activity(activity_id)
if activity is None:
raise ApiException.ApiMalformedRequestException("Activity not found.")
# Determine if the requesting user can view the activity.
if not self.activity_can_be_viewed(activity):
raise ApiException.ApiMalformedRequestException("The requested activity is not viewable to this user.")
response = {}
for sensor_name in values[Keys.SENSOR_LIST_KEY].split(','):
if sensor_name in activity:
# Need to fix up the datetime item for each event.
if sensor_name == 'Events':
events = activity[sensor_name]
for event in events:
if 'timestamp' in event:
dt_tuple = event['timestamp'].timetuple()
dt_unix = calendar.timegm(dt_tuple)
event['timestamp'] = dt_unix
if 'start_time' in event:
dt_tuple = event['start_time'].timetuple()
dt_unix = calendar.timegm(dt_tuple)
event['start_time'] = dt_unix
if 'local_timestamp' in event:
dt_tuple = event['local_timestamp'].timetuple()
dt_unix = calendar.timegm(dt_tuple)
event['local_timestamp'] = dt_unix
response[sensor_name] = events
else:
response[sensor_name] = activity[sensor_name]
return True, json.dumps(response)
def handle_retrieve_activity_summarydata(self, values):
"""Called when an API message to get the interval segments computed from the activity is received. Result is a JSON string."""
# Required parameters.
if Keys.ACTIVITY_ID_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity ID not specified.")
if Keys.SUMMARY_ITEMS_LIST_KEY not in values:
raise ApiException.ApiMalformedRequestException("Summary item list not specified.")
# Get the activity ID from the request.
activity_id = values[Keys.ACTIVITY_ID_KEY]
if not InputChecker.is_uuid(activity_id):
raise ApiException.ApiMalformedRequestException("Invalid activity ID.")
# Determine if the requesting user can view the activity.
if not self.activity_id_can_be_viewed(activity_id):
raise ApiException.ApiMalformedRequestException("The requested activity is not viewable to this user.")
# Get the activity summary from the database.
activity_summary = self.data_mgr.retrieve_activity_summary(activity_id)
response = {}
if activity_summary is not None:
for summary_item in values[Keys.SUMMARY_ITEMS_LIST_KEY].split(','):
if summary_item in activity_summary:
response[summary_item] = activity_summary[summary_item]
return True, json.dumps(response)
def handle_update_activity_metadata(self, values):
"""Called when an API message to update the activity metadata."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.ACTIVITY_ID_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity ID not specified.")
# Get the activity ID from the request.
activity_id = values[Keys.ACTIVITY_ID_KEY]
if not InputChecker.is_uuid(activity_id):
raise ApiException.ApiMalformedRequestException("Invalid activity ID.")
# Get the activity from the database.
activity = self.data_mgr.retrieve_activity(activity_id)
if not activity:
raise ApiException.ApiMalformedRequestException("Activity not found.")
# Get the ID of the user that owns the activity and make sure it's the current user.
if not self.activity_belongs_to_logged_in_user(activity):
raise ApiException.ApiAuthenticationException("Not activity owner.")
if Keys.ACTIVITY_NAME_KEY in values:
activity_name = values[Keys.ACTIVITY_NAME_KEY].strip()
if not self.data_mgr.create_activity_metadata(activity_id, 0, Keys.ACTIVITY_NAME_KEY, activity_name, False):
raise Exception("Failed to update activity name.")
if Keys.ACTIVITY_TYPE_KEY in values:
if not self.data_mgr.create_activity_metadata(activity_id, 0, Keys.ACTIVITY_TYPE_KEY, values[Keys.ACTIVITY_TYPE_KEY], False):
raise Exception("Failed to update activity type.")
if Keys.ACTIVITY_DESCRIPTION_KEY in values:
activity_description = values[Keys.ACTIVITY_DESCRIPTION_KEY].strip()
if not self.data_mgr.create_activity_metadata(activity_id, 0, Keys.ACTIVITY_DESCRIPTION_KEY, activity_description, False):
raise Exception("Failed to update activity description.")
return True, ""
def handle_create_new_lap(self, values):
"""Called when an API message to create a new lap is received."""
"""This typically happens when the user presses the lap button while live streaming an activity."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.ACTIVITY_ID_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity ID not specified.")
if Keys.ACTIVITY_LAP_START_TIME not in values:
raise ApiException.ApiMalformedRequestException("Lap start time not specified.")
# Get the activity ID from the request.
activity_id = values[Keys.ACTIVITY_ID_KEY]
if not InputChecker.is_uuid(activity_id):
raise ApiException.ApiMalformedRequestException("Invalid activity ID.")
# Get the lap start time from the request.
lap_start_time = values[Keys.ACTIVITY_LAP_START_TIME]
if not InputChecker.is_unsigned_integer(lap_start_time):
raise ApiException.ApiMalformedRequestException("Invalid lap start time.")
# Get the activity from the database.
activity = self.data_mgr.retrieve_activity(activity_id)
if not activity:
raise ApiException.ApiMalformedRequestException("Activity not found.")
# Get the ID of the user that owns the activity and make sure it's the current user.
if not self.activity_belongs_to_logged_in_user(activity):
raise ApiException.ApiAuthenticationException("Not activity owner.")
if not self.data_mgr.create_activity_lap(activity_id, lap_start_time):
raise Exception("Failed to create a lap on an activity.")
return True, ""
def handle_login(self, values):
"""Called when an API message to login is received."""
if self.user_id is not None:
return True, ""
# Required parameters.
if Keys.USERNAME_KEY not in values:
raise ApiException.ApiAuthenticationException("Username not specified.")
if Keys.PASSWORD_KEY not in values:
raise ApiException.ApiAuthenticationException("Password not specified.")
# Decode and validate the required parameters.
email = unquote_plus(values[Keys.USERNAME_KEY])
if not InputChecker.is_email_address(email):
raise ApiException.ApiAuthenticationException("Invalid email address.")
password = unquote_plus(values[Keys.PASSWORD_KEY])
# Validate the credentials.
try:
if not self.user_mgr.authenticate_user(email, password):
raise ApiException.ApiAuthenticationException("Authentication failed.")
except Exception as e:
raise ApiException.ApiAuthenticationException(str(e))
# Make sure the device the user is using is registered to this user.
if Keys.DEVICE_KEY in values:
device_str = unquote_plus(values[Keys.DEVICE_KEY])
result = self.user_mgr.create_user_device(email, device_str)
else:
result = True
# Create session information for this new login.
cookie, expiry = self.user_mgr.create_new_session(email)
if not cookie:
raise ApiException.ApiAuthenticationException("Session cookie not generated.")
if not expiry:
raise ApiException.ApiAuthenticationException("Session expiry not generated.")
# Encode the session info.
session_data = {}
session_data[Keys.SESSION_TOKEN_KEY] = cookie
session_data[Keys.SESSION_EXPIRY_KEY] = expiry
session_data[Keys.USER_ID_KEY] = str(self.user_mgr.get_logged_in_user_id())
json_result = json.dumps(session_data, ensure_ascii=False)
return result, json_result
def handle_create_login(self, values):
"""Called when an API message to create an account is received."""
if self.user_id is not None:
raise Exception("Already logged in.")
# Make sure this is allowed.
# Creating a new login can be disabled for security reasons, testing, etc.
if self.config.is_create_login_disabled():
raise ApiException.ApiAuthenticationException("Creating a new login is currently disabled.")
# Required parameters.
if Keys.USERNAME_KEY not in values:
raise ApiException.ApiAuthenticationException("Username not specified.")
if Keys.REALNAME_KEY not in values:
raise ApiException.ApiAuthenticationException("Real name not specified.")
if Keys.PASSWORD1_KEY not in values:
raise ApiException.ApiAuthenticationException("Password not specified.")
if Keys.PASSWORD2_KEY not in values:
raise ApiException.ApiAuthenticationException("Password confirmation not specified.")
# Decode and validate the required parameters.
email = unquote_plus(values[Keys.USERNAME_KEY])
if not InputChecker.is_email_address(email):
raise ApiException.ApiMalformedRequestException("Invalid email address.")
realname = unquote_plus(values[Keys.REALNAME_KEY])
if not InputChecker.is_valid_decoded_str(realname):
raise ApiException.ApiMalformedRequestException("Invalid name.")
password1 = unquote_plus(values[Keys.PASSWORD1_KEY])
password2 = unquote_plus(values[Keys.PASSWORD2_KEY])
if Keys.DEVICE_KEY in values:
device_str = unquote_plus(values[Keys.DEVICE_KEY])
else:
device_str = ""
# Add the user to the database, should fail if the user already exists.
try:
if not self.user_mgr.create_user(email, realname, password1, password2, device_str):
raise Exception("User creation failed.")
except:
raise Exception("User creation failed.")
# The new user should start in a logged-in state, so generate session info.
cookie, expiry = self.user_mgr.create_new_session(email)
if not cookie:
raise ApiException.ApiAuthenticationException("Session cookie not generated.")
if not expiry:
raise ApiException.ApiAuthenticationException("Session expiry not generated.")
# Encode the session info.
session_data = {}
session_data[Keys.SESSION_TOKEN_KEY] = cookie
session_data[Keys.SESSION_EXPIRY_KEY] = expiry
session_data[Keys.USER_ID_KEY] = str(self.user_mgr.get_logged_in_user_id())
json_result = json.dumps(session_data, ensure_ascii=False)
return True, json_result
def handle_login_status(self, values):
"""Called when an API message to check the login status in is received."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
return True, "Logged In"
def handle_logout(self, values):
"""Ends the session for the specified user."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# End the session
self.user_mgr.clear_current_session()
self.user_id = None
return True, "Logged Out"
def handle_update_email(self, values):
"""Updates the user's email address."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.EMAIL_KEY not in values:
raise ApiException.ApiMalformedRequestException("Email not specified.")
# Get the logged in user.
current_username = self.user_mgr.get_logged_in_username()
if current_username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# Decode the parameter.
new_username = unquote_plus(values[Keys.EMAIL_KEY])
# Get the user details.
user_id, _, user_realname = self.user_mgr.retrieve_user(current_username)
# Update the user's password in the database.
if not self.user_mgr.update_user_email(user_id, new_username, user_realname):
raise Exception("Update failed.")
return True, ""
def handle_update_password(self, values):
"""Updates the user's password."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if 'old_password' not in values:
raise ApiException.ApiMalformedRequestException("Old password not specified.")
if 'new_password1' not in values:
raise ApiException.ApiMalformedRequestException("New password not specified.")
if 'new_password2' not in values:
raise ApiException.ApiMalformedRequestException("New password confirmation not specified.")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# Get the user details.
user_id, _, user_realname = self.user_mgr.retrieve_user(username)
# The the old and new passwords from the request.
old_password = unquote_plus(values["old_password"])
new_password1 = unquote_plus(values["new_password1"])
new_password2 = unquote_plus(values["new_password2"])
# Reauthenticate the user.
if not self.user_mgr.authenticate_user(username, old_password):
raise Exception("Authentication failed.")
# Update the user's password in the database.
if not self.user_mgr.update_user_password(user_id, username, user_realname, new_password1, new_password2):
raise Exception("Update failed.")
return True, ""
def handle_delete_users_gear(self, values):
"""Removes the current user's gear data."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.PASSWORD_KEY not in values:
raise ApiException.ApiMalformedRequestException("Password not specified.")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# Reauthenticate the user.
password = unquote_plus(values[Keys.PASSWORD_KEY])
if not self.user_mgr.authenticate_user(username, password):
raise Exception("Authentication failed.")
# Delete all the user's gear.
self.data_mgr.delete_user_gear(self.user_id)
return True, ""
def handle_delete_users_activities(self, values):
"""Removes the current user's activity data."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.PASSWORD_KEY not in values:
raise ApiException.ApiMalformedRequestException("Password not specified.")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# Reauthenticate the user.
password = unquote_plus(values[Keys.PASSWORD_KEY])
if not self.user_mgr.authenticate_user(username, password):
raise Exception("Authentication failed.")
# Delete all the user's activities.
self.data_mgr.delete_user_activities(self.user_id)
# Delete the cache of the user's personal records.
self.data_mgr.delete_all_user_personal_records(self.user_id)
return True, ""
def handle_delete_user(self, values):
"""Removes the current user and all associated data."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.PASSWORD_KEY not in values:
raise ApiException.ApiMalformedRequestException("Password not specified.")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# Reauthenticate the user.
password = unquote_plus(values[Keys.PASSWORD_KEY])
if not self.user_mgr.authenticate_user(username, password):
raise Exception("Authentication failed.")
# Delete all of the user's activities.
self.data_mgr.delete_user_activities(self.user_id)
# Delete the user.
self.user_mgr.delete_user(self.user_id)
return True, ""
def handle_list_devices(self, values):
"""Returns a JSON string describing all of the user's devices."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# List the devices.
user_device_ids = self.user_mgr.retrieve_user_devices(self.user_id)
# Get the time each device was last heard from.
devices = []
for device_id in user_device_ids:
device_info = {}
device_info[Keys.APP_DEVICE_ID_KEY] = device_id
activity = self.data_mgr.retrieve_most_recent_activity_for_device(device_id)
if activity is not None:
device_info[Keys.DEVICE_LAST_HEARD_FROM_KEY] = activity[Keys.ACTIVITY_START_TIME_KEY]
else:
device_info[Keys.DEVICE_LAST_HEARD_FROM_KEY] = 0
devices.append(device_info)
json_result = json.dumps(devices, ensure_ascii=False)
return True, json_result
def handle_list_activities(self, values, include_friends):
"""Returns a JSON string describing all of the user's activities."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Fetch and validate the activity start and end times (optional).
start_time = None
end_time = None
if Keys.START_DATE_KEY in values:
start_time = int(datetime.datetime.strptime(values[Keys.START_DATE_KEY], '%Y-%m-%d').strftime("%s"))
if Keys.END_DATE_KEY in values:
end_time = int(datetime.datetime.strptime(values[Keys.END_DATE_KEY], '%Y-%m-%d').strftime("%s"))
if Keys.START_TIME_KEY in values:
start_time = values[Keys.START_TIME_KEY]
if InputChecker.is_unsigned_integer(start_time):
start_time = int(start_time)
else:
raise ApiException.ApiMalformedRequestException("Invalid start time.")
if Keys.END_TIME_KEY in values:
end_time = values[Keys.END_TIME_KEY]
if InputChecker.is_unsigned_integer(end_time):
end_time = int(end_time)
else:
raise ApiException.ApiMalformedRequestException("Invalid ending time.")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# Get the user details.
_, _, user_realname = self.user_mgr.retrieve_user(username)
# Get the activities that belong to the logged in user.
matched_activities = []
if include_friends:
activities = self.data_mgr.retrieve_all_activities_visible_to_user(self.user_id, user_realname, start_time, end_time, None)
else:
activities = self.data_mgr.retrieve_user_activity_list(self.user_id, user_realname, start_time, end_time, None)
# Convert the activities list to an array of JSON objects for return to the client.
if activities is not None and isinstance(activities, list):
for activity in activities:
activity_type = Keys.TYPE_UNSPECIFIED_ACTIVITY_KEY
activity_name = Keys.UNNAMED_ACTIVITY_TITLE
activity_tags = []
activity_id = ""
if Keys.ACTIVITY_TYPE_KEY in activity:
activity_type = activity[Keys.ACTIVITY_TYPE_KEY]
if Keys.ACTIVITY_NAME_KEY in activity:
activity_name = activity[Keys.ACTIVITY_NAME_KEY]
if Keys.ACTIVITY_TAGS_KEY in activity:
activity_tags = activity[Keys.ACTIVITY_TAGS_KEY]
if Keys.ACTIVITY_ID_KEY in activity:
activity_id = activity[Keys.ACTIVITY_ID_KEY]
if Keys.ACTIVITY_START_TIME_KEY in activity and Keys.ACTIVITY_ID_KEY in activity:
url = self.root_url + "/activity/" + activity[Keys.ACTIVITY_ID_KEY]
temp_activity = {'title':'[' + activity_type + '] ' + activity_name, 'url': url, 'time': int(activity[Keys.ACTIVITY_START_TIME_KEY]), Keys.ACTIVITY_TAGS_KEY: activity_tags, Keys.ACTIVITY_ID_KEY: activity_id}
matched_activities.append(temp_activity)
json_result = json.dumps(matched_activities, ensure_ascii=False)
return True, json_result
def handle_delete_activity(self, values):
"""Removes the specified activity."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.ACTIVITY_ID_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity ID not specified.")
# Get the device and activity IDs from the request.
activity_id = values[Keys.ACTIVITY_ID_KEY]
if not InputChecker.is_uuid(activity_id):
raise ApiException.ApiMalformedRequestException("Invalid activity ID.")
# Only the activity's owner should be able to do this.
activity = self.data_mgr.retrieve_activity(activity_id)
if not self.activity_belongs_to_logged_in_user(activity):
raise ApiException.ApiAuthenticationException("Not activity owner.")
# Delete the activity.
deleted = self.data_mgr.delete_activity(self.user_id, activity_id)
# Did we find it?
if not deleted:
raise Exception("An error occurred. Nothing was deleted.")
return deleted, ""
def handle_add_time_and_distance_activity(self, values):
"""Called when an API message to add a new activity based on time and distance is received."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.APP_DISTANCE_KEY not in values:
raise ApiException.ApiMalformedRequestException("Distance not specified.")
if Keys.APP_DURATION_KEY not in values:
raise ApiException.ApiMalformedRequestException("Duration not specified.")
if Keys.ACTIVITY_START_TIME_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity start time not specified.")
if Keys.ACTIVITY_TYPE_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity type not specified.")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# Validate the activity start time.
start_time = values[Keys.ACTIVITY_START_TIME_KEY]
if not InputChecker.is_unsigned_integer(start_time):
raise ApiException.ApiMalformedRequestException("Invalid start time.")
# Validate the activity type.
activity_type = values[Keys.ACTIVITY_TYPE_KEY]
if not InputChecker.is_valid_activity_type(activity_type):
raise ApiException.ApiMalformedRequestException("Invalid parameter.")
# Add the activity to the database.
_, activity_id = self.data_mgr.create_activity(username, self.user_id, "", "", activity_type, int(start_time), None)
# Add the activity data to the database.
self.data_mgr.create_activity_metadata(activity_id, 0, Keys.APP_DISTANCE_KEY, float(values[Keys.APP_DISTANCE_KEY]), False)
self.data_mgr.create_activity_metadata(activity_id, 0, Keys.APP_DURATION_KEY, float(values[Keys.APP_DURATION_KEY]), False)
return ""
def handle_add_sets_and_reps_activity(self, values):
"""Called when an API message to add a new activity based on sets and reps is received."""
if self.user_id is None:
raise ApiException.ApiNotLoggedInException()
# Required parameters.
if Keys.APP_SETS_KEY not in values:
raise ApiException.ApiMalformedRequestException("Sets not specified.")
if Keys.ACTIVITY_START_TIME_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity start time not specified.")
if Keys.ACTIVITY_TYPE_KEY not in values:
raise ApiException.ApiMalformedRequestException("Activity type not specified.")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise ApiException.ApiMalformedRequestException("Empty username.")
# Convert the array string to an actual array (note: I realize I could use eval for this, but that seems dangerous)
sets = values[Keys.APP_SETS_KEY]
if len(sets) <= 2:
raise ApiException.ApiMalformedRequestException("Malformed set data.")
sets = sets[1:-1] # Remove the brackets
sets = sets.split(',')
if len(sets) == 0:
raise ApiException.ApiMalformedRequestException("Set data was not specified.")
# Make sure everything is a number.
new_sets = []
for current_set in sets:
rep_count = int(current_set)
if rep_count > 0:
new_sets.append(rep_count)
# Make sure we got at least one valid set.
if len(new_sets) == 0:
raise ApiException.ApiMalformedRequestException("Set data was not specified.")
# Validate the activity start time.
start_time = values[Keys.ACTIVITY_START_TIME_KEY]
if not InputChecker.is_unsigned_integer(start_time):
raise ApiException.ApiMalformedRequestException("Invalid start time.")
# Validate the activity type.
activity_type = values[Keys.ACTIVITY_TYPE_KEY]
if not InputChecker.is_valid_activity_type(activity_type):
raise ApiException.ApiMalformedRequestException("Invalid parameter.")
# Add the activity to the database.
_, activity_id = self.data_mgr.create_activity(username, self.user_id, "", "", activity_type, int(start_time), None)
self.data_mgr.create_activity_sets_and_reps_data(activity_id, new_sets)