-
Notifications
You must be signed in to change notification settings - Fork 3
/
DataMgr.py
1995 lines (1699 loc) · 89.2 KB
/
DataMgr.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-2020 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.
"""Data store abstraction"""
import base64
import datetime
import hashlib
import os
import threading
import time
import uuid
import AppDatabase
import BmiCalculator
import FtpCalculator
import HeartRateCalculator
import Importer
import InputChecker
import Keys
import MapSearch
import MergeTool
import Summarizer
import TrainingPaceCalculator
import Units
import VO2MaxCalculator
import celery
SIX_MONTHS = ((365.25 / 2.0) * 24.0 * 60.0 * 60.0)
ONE_YEAR = (365.25 * 24.0 * 60.0 * 60.0)
ONE_WEEK = (7.0 * 24.0 * 60.0 * 60.0)
FOUR_WEEKS = (28.0 * 24.0 * 60.0 * 60.0)
EIGHT_WEEKS = (56.0 * 24.0 * 60.0 * 60.0)
g_api_key_rate_lock = threading.Lock()
g_api_key_rates = {}
g_last_api_reset = 0 # Timestamp of when g_api_key_rates was last cleared
def get_activities_sort_key(item):
# Was the start time provided? If not, look at the first location.
if Keys.ACTIVITY_START_TIME_KEY in item:
return item[Keys.ACTIVITY_START_TIME_KEY]
return 0
class DataMgr(Importer.ActivityWriter):
"""Data store abstraction"""
def __init__(self, *, config, root_url, analysis_scheduler, import_scheduler):
"""Constructor"""
assert config is not None
self.config = config
self.root_url = root_url
self.analysis_scheduler = analysis_scheduler
self.import_scheduler = import_scheduler
self.database = AppDatabase.MongoDatabase()
self.database.connect(config)
self.map_search = None
self.celery_worker = celery.Celery(Keys.CELERY_PROJECT_NAME)
self.celery_worker.config_from_object('CeleryConfig')
if config is not None:
self.celery_worker.conf.broker_url = config.get_broker_url()
super(Importer.ActivityWriter, self).__init__()
def terminate(self):
"""Destructor"""
self.analysis_scheduler = None
self.import_scheduler = None
self.database = None
def total_users_count(self):
"""Returns the number of users in the database."""
return self.database.total_users_count()
def total_activities_count(self):
"""Returns the number of activities in the database."""
return self.database.total_activities_count()
def create_activity_id(self):
"""Generates a new activity ID."""
return str(uuid.uuid4())
def schedule_activity_analysis(self, activity, activity_user_id):
"""Schedules the specified activity for analysis."""
if activity is None:
raise Exception("No activity object.")
if activity_user_id is None:
raise Exception("No activity user ID.")
if not InputChecker.is_hex_str(activity_user_id):
raise Exception("Invalid activity user ID.")
if self.analysis_scheduler is None:
raise Exception("No analysis scheduler.")
activity[Keys.ACTIVITY_USER_ID_KEY] = activity_user_id
task_id, internal_task_id = self.analysis_scheduler.add_activity_to_analysis_queue(activity)
if [task_id, internal_task_id].count(None) == 0:
self.create_deferred_task(activity_user_id, Keys.ANALYSIS_TASK_KEY, task_id, internal_task_id, None)
def analyze_activity_by_id(self, activity_id, activity_user_id):
"""Schedules the specified activity for analysis."""
if activity_id is None:
raise Exception("No activity ID.")
if activity_user_id is None:
raise Exception("No activity user ID.")
complete_activity_data = self.retrieve_activity(activity_id)
self.schedule_activity_analysis(complete_activity_data, activity_user_id)
def schedule_personal_records_refresh(self, user_id):
"""Schedules the specified activity for analysis."""
if user_id is None:
raise Exception("No user ID.")
if self.analysis_scheduler is None:
raise Exception("No analysis scheduler.")
task_id, internal_task_id = self.analysis_scheduler.add_personal_records_analysis_to_queue(user_id)
if [task_id, internal_task_id].count(None) == 0:
self.create_deferred_task(user_id, Keys.ANALYSIS_TASK_KEY, task_id, internal_task_id, None)
def compute_activity_end_time_ms(self, activity):
"""Examines the activity and computes the time at which the activity ended."""
end_time_ms = None
# Look through activity attributes that have a "time".
search_keys = []
search_keys.append(Keys.APP_LOCATIONS_KEY)
search_keys.append(Keys.APP_ACCELEROMETER_KEY)
for search_key in search_keys:
# Read the last item out of the list since they should be in chronological order.
if search_key in activity and isinstance(activity[search_key], list) and len(activity[search_key]) > 0:
last_list_entry = (activity[search_key])[-1]
if "time" in last_list_entry:
possible_end_time_ms = last_list_entry["time"]
if end_time_ms is None or possible_end_time_ms > end_time_ms:
end_time_ms = possible_end_time_ms
return end_time_ms
def update_activity_end_time_secs(self, activity, end_time_sec):
"""Utility function for updating the activity's ending time in the database."""
if self.database is None:
raise Exception("No database.")
if activity is None:
raise Exception("No activity object.")
if end_time_sec is None:
raise Exception("End time not provided.")
return self.database.create_or_update_activity_metadata(activity[Keys.ACTIVITY_ID_KEY], None, Keys.ACTIVITY_END_TIME_KEY, int(end_time_sec), False)
def compute_and_store_activity_end_time(self, activity):
"""Examines the activity and computes the time at which the activity ended, storing it so we don't have to do this again."""
if self.database is None:
raise Exception("No database.")
end_time_sec = None
# Compute from the activity's raw data.
end_time_ms = self.compute_activity_end_time_ms(activity)
if end_time_ms is not None:
end_time_sec = end_time_ms / 1000
# If we couldn't find anything with a time then just duplicate the start time, assuming it's a manually entered workout or something.
if end_time_sec is None:
end_time_sec = activity[Keys.ACTIVITY_START_TIME_KEY]
# Store the ending time, so we don't have to go through this again.
if end_time_sec is not None:
self.update_activity_end_time_secs(activity, end_time_sec)
return end_time_sec
def get_activity_start_and_end_times(self, activity):
"""Retrieves the start time and end time, computing the ending time, if necessary."""
if activity is None:
raise Exception("No activity object.")
activity_start_time_sec = activity[Keys.ACTIVITY_START_TIME_KEY]
if Keys.ACTIVITY_END_TIME_KEY not in activity:
activity_end_time_sec = self.compute_and_store_activity_end_time(activity)
else:
activity_end_time_sec = activity[Keys.ACTIVITY_END_TIME_KEY]
return activity_start_time_sec, activity_end_time_sec
def is_duplicate_activity(self, user_id, start_time_sec, optional_activity_id):
"""Inherited from ActivityWriter. Returns TRUE if the activity appears to be a duplicate of another activity. Returns FALSE otherwise."""
if self.database is None:
raise Exception("No database.")
# If an activity ID was specified then do any documents already exist with this ID?
if optional_activity_id is not None:
if self.database.retrieve_activity(optional_activity_id) is not None:
return True
# Look through the user's activities for ones that overlap with the given start time.
activities = self.database.retrieve_user_activity_list(user_id, None, None, True)
for activity in activities:
if Keys.ACTIVITY_START_TIME_KEY in activity:
# Get the activity start and end times.
activity_start_time_sec, activity_end_time_sec = self.get_activity_start_and_end_times(activity)
# We're looking for activities that start within the bounds of another activity.
if start_time_sec >= activity_start_time_sec and start_time_sec < activity_end_time_sec:
return True
return False
def create_activity(self, username, user_id, stream_name, stream_description, activity_type, start_time, desired_activity_id):
"""Inherited from ActivityWriter. Called when we start reading an activity file."""
if self.database is None:
raise Exception("No database.")
# Device is unknown.
device_str = ""
# Create the device ID, or use the provided one.
if desired_activity_id is None:
activity_id = self.create_activity_id()
else:
activity_id = desired_activity_id
# Add the activity to the database.
if stream_name is None:
stream_name = ""
if not self.database.create_activity(activity_id, stream_name, start_time, device_str):
return None, None
if activity_type is not None and len(activity_type) > 0:
self.database.create_or_update_activity_metadata(activity_id, 0, Keys.ACTIVITY_TYPE_KEY, activity_type, False)
self.create_default_tags_on_activity(user_id, activity_type, activity_id)
# If given a user ID then associate the activity with the user.
if user_id is not None:
self.database.create_or_update_activity_metadata(activity_id, 0, Keys.ACTIVITY_USER_ID_KEY, user_id, False)
return device_str, activity_id
def create_activity_track(self, device_str, activity_id, track_name, track_description):
"""Inherited from ActivityWriter."""
pass
def create_activity_locations(self, device_str, activity_id, locations):
"""Inherited from ActivityWriter. Adds several locations to the database. 'locations' is an array of arrays in the form [time, lat, lon, alt]."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
return self.database.create_activity_locations(device_str, activity_id, locations)
def create_activity_sensor_reading(self, activity_id, date_time, sensor_type, value):
"""Inherited from ActivityWriter. Create method for sensor data."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
return self.database.create_activity_sensor_reading(activity_id, date_time, sensor_type, value)
def create_activity_sensor_readings(self, activity_id, sensor_type, values):
"""Inherited from ActivityWriter. Adds several sensor readings to the database. 'values' is an array of arrays in the form [time, value]."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
return self.database.create_activity_sensor_readings(activity_id, sensor_type, values)
def create_activity_event(self, activity_id, event):
"""Inherited from ActivityWriter. 'event' is a dictionary describing an event."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
if event is None:
raise Exception("No event.")
return self.database.create_activity_events(activity_id, event)
def create_activity_events(self, activity_id, events):
"""Inherited from ActivityWriter. 'events' is an array of dictionaries in which each dictionary describes an event."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
if events is None:
raise Exception("No events.")
return self.database.create_activity_events(activity_id, events)
def create_activity_metadata(self, activity_id, date_time, key, value, create_list):
"""Create method for activity metadata."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
if date_time is None:
raise Exception("No timestamp.")
if key is None:
raise Exception("No key.")
if value is None:
raise Exception("No value.")
if create_list is None:
raise Exception("Missing parameter.")
return self.database.create_or_update_activity_metadata(activity_id, date_time, key, value, create_list)
def create_activity_metadata_list(self, activity_id, key, values):
"""Create method for activity metadata."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
if key is None:
raise Exception("No key.")
if values is None:
raise Exception("No values.")
return self.database.create_or_update_activity_metadata_list(activity_id, key, values)
def create_activity_lap(self, activity_id, start_time_ms):
"""Create method for a lap on an activity."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
return self.database.create_activity_lap(activity_id, start_time_ms)
def create_activity_sets_and_reps_data(self, activity_id, sets):
"""Create method for activity set and rep data."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
return self.database.create_activity_sets_and_reps_data(activity_id, sets)
def create_activity_accelerometer_reading(self, device_str, activity_id, accels):
"""Adds several accelerometer readings to the database. 'accels' is an array of arrays in the form [time, x, y, z]."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
return self.database.create_activity_accelerometer_reading(device_str, activity_id, accels)
def create_activity_battery_level_reading(self, activity_id, battery_level):
"""Adds the latest battery level reading to the database."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
if battery_level is None:
raise Exception("No battery level.")
values = [time.time() * 1000, battery_level]
return self.database.create_or_update_activity_metadata_list(activity_id, Keys.APP_BATTERY_LEVEL_KEY, [values])
def finish_activity(self, activity_id, end_time_ms):
"""Inherited from ActivityWriter. Called for post-processing."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
if end_time_ms is None:
raise Exception("No timestamp.")
return self.database.create_or_update_activity_metadata(activity_id, int(end_time_ms), Keys.ACTIVITY_END_TIME_KEY, int(end_time_ms / 1000), False)
def create_deferred_task(self, user_id, task_type, celery_task_id, internal_task_id, details):
"""Called by the importer to store data associated with an ongoing import task."""
if self.database is None:
raise Exception("No database.")
if user_id is None:
raise Exception("No user ID.")
if task_type is None:
raise Exception("No task type.")
if celery_task_id is None:
raise Exception("No celery task ID.")
if internal_task_id is None:
raise Exception("No internal task ID.")
return self.database.create_deferred_task(user_id, task_type, celery_task_id, internal_task_id, details, Keys.TASK_STATUS_QUEUED)
def retrieve_deferred_tasks(self, user_id):
"""Returns a list of all incomplete tasks."""
if self.database is None:
raise Exception("No database.")
if user_id is None:
raise Exception("No user ID.")
return self.database.retrieve_deferred_tasks(user_id)
def update_deferred_task(self, user_id, internal_task_id, activity_id, status):
"""Returns a list of all incomplete tasks."""
if self.database is None:
raise Exception("No database.")
if user_id is None:
raise Exception("No user ID.")
if internal_task_id is None:
raise Exception("No internal task ID.")
if status is None:
raise Exception("No status.")
return self.database.update_deferred_task(user_id, internal_task_id, activity_id, status)
def prune_deferred_tasks_list(self):
"""Removes all completed tasks from the list."""
if self.database is None:
raise Exception("No database.")
return self.database.delete_finished_deferred_tasks()
def create_uploaded_file(self, activity_id, file_data):
"""Create method for an uploaded activity file."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity_id")
if file_data is None:
raise Exception("No file data")
return self.database.create_uploaded_file(activity_id, file_data)
def import_activity_from_file(self, username, user_id, uploaded_file_data, uploaded_file_name, desired_activity_id):
"""Imports the contents of a local file into the database. Desired activity ID is optional."""
if self.import_scheduler is None:
raise Exception("No importer.")
if self.config is None:
raise Exception("No configuration object.")
if username is None:
raise Exception("No username.")
if user_id is None:
raise Exception("No user ID.")
if uploaded_file_data is None:
raise Exception("No uploaded file data.")
if uploaded_file_name is None:
raise Exception("No uploaded file name.")
# Check the file size.
if len(uploaded_file_data) > self.config.get_import_max_file_size():
raise Exception("The file is too large.")
return self.import_scheduler.add_file_to_queue(username, user_id, uploaded_file_data, uploaded_file_name, desired_activity_id, self)
def get_user_photos_dir(self, user_id):
"""Calculates the photos dir assigned to the specified user and creates if it does not exist."""
# Where are we storing photos?
photos_dir = self.config.get_photos_dir()
if len(photos_dir) == 0:
raise Exception("No photos directory.")
# Create the directory, if it does not already exist.
user_photos_dir = os.path.join(os.path.normpath(os.path.expanduser(photos_dir)), str(user_id))
if not os.path.exists(user_photos_dir):
os.makedirs(user_photos_dir)
# Sanity check.
if not os.path.exists(user_photos_dir):
raise Exception("Photos directory not created.")
return user_photos_dir
def attach_photo_to_activity(self, user_id, uploaded_file_data, activity_id):
"""Imports a photo and associates it with an activity."""
if self.database is None:
raise Exception("No database.")
if self.config is None:
raise Exception("No configuration object.")
if user_id is None:
raise Exception("No user ID.")
if uploaded_file_data is None:
raise Exception("No uploaded file data.")
if activity_id is None:
raise Exception("No activity ID.")
# Decode the uplaoded data.
uploaded_file_data = uploaded_file_data.replace(" ", "+") # Some JS base64 encoders replace plus with space, so we need to undo that.
decoded_file_data = base64.b64decode(uploaded_file_data)
# Check the file size.
if len(decoded_file_data) > self.config.get_photos_max_file_size():
raise Exception("The file is too large.")
# Hash the photo. This will prevent duplicates as well as give us a unique name.
h = hashlib.sha512()
h.update(str(decoded_file_data).encode('utf-8'))
hash_str = h.hexdigest()
# Where are we storing photos?
user_photos_dir = self.get_user_photos_dir(user_id)
# Save the file to the user's photos directory.
try:
local_file_name = os.path.join(user_photos_dir, hash_str)
if not os.path.isfile(local_file_name):
with open(local_file_name, 'wb') as local_file:
local_file.write(decoded_file_data)
except:
raise Exception("Could not save the photo.")
# Attach the hash to the activity.
return self.database.create_activity_photo(user_id, activity_id, hash_str)
def list_activity_photos(self, activity_id):
"""Lists all photos associated with an activity. Response is a list of identifiers."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
activity = self.database.retrieve_activity_small(activity_id)
if activity is not None and Keys.ACTIVITY_PHOTOS_KEY in activity:
return activity[Keys.ACTIVITY_PHOTOS_KEY]
return None
def delete_activity_photo(self, activity_id, photo_id):
"""Lists all photos associated with an activity. Response is a list of identifiers."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("No activity ID.")
if photo_id is None:
raise Exception("No photo ID.")
return self.database.delete_activity_photo(activity_id, photo_id)
def update_activity_start_time(self, activity):
"""Caches the activity start time, based on the first reported location."""
if Keys.ACTIVITY_START_TIME_KEY in activity:
return activity[Keys.ACTIVITY_START_TIME_KEY]
if Keys.ACTIVITY_LOCATIONS_KEY in activity:
locations = activity[Keys.ACTIVITY_LOCATIONS_KEY]
else:
locations = self.retrieve_activity_locations(activity[Keys.ACTIVITY_ID_KEY])
time_num = 0
if len(locations) > 0:
first_loc = locations[0]
if Keys.LOCATION_TIME_KEY in first_loc:
time_num = first_loc[Keys.LOCATION_TIME_KEY] / 1000 # Milliseconds to seconds
activity_id = activity[Keys.ACTIVITY_ID_KEY]
activity[Keys.ACTIVITY_START_TIME_KEY] = time_num
self.create_activity_metadata(activity_id, time_num, Keys.ACTIVITY_START_TIME_KEY, time_num, False)
return time_num
def update_moving_activity(self, device_str, activity_id, locations, sensor_readings_dict, metadata_list_dict):
"""Updates locations, sensor readings, and metadata associated with a moving activity. Provided as a performance improvement over making several database updates."""
if self.database is None:
raise Exception("No database.")
if device_str is None:
raise Exception("Bad parameter.")
if activity_id is None:
raise Exception("Bad parameter.")
return self.database.update_activity(device_str, activity_id, locations, sensor_readings_dict, metadata_list_dict)
def is_activity_public(self, activity):
"""Helper function for returning whether or not an activity is publically visible."""
if Keys.ACTIVITY_VISIBILITY_KEY in activity:
if activity[Keys.ACTIVITY_VISIBILITY_KEY] == "private":
return False
return True
def is_activity_id_public(self, activity_id):
"""Helper function for returning whether or not an activity is publically visible."""
if activity_id is None:
raise Exception("Bad parameter.")
visibility = self.retrieve_activity_visibility(activity_id)
if visibility is not None:
if visibility == "private":
return False
return True
def retrieve_user_activity_list(self, user_id, user_realname, start_time, end_time, num_results):
"""Returns a list containing all of the user's activities, up to num_results. num_results can be None for all activiites."""
if self.database is None:
raise Exception("No database.")
if user_id is None or len(user_id) == 0:
raise Exception("Bad parameter.")
activities = []
# List activities recorded on devices registered to the user.
devices = self.database.retrieve_user_devices(user_id)
devices = list(set(devices)) # De-duplicate
device_activities = self.database.retrieve_devices_activity_list(devices, start_time, end_time, False)
if device_activities is not None:
for device_activity in device_activities:
device_activity[Keys.REALNAME_KEY] = user_realname
self.update_activity_start_time(device_activity)
activities.extend(device_activities)
# List activities with no device that are associated with the user.
user_activities = self.database.retrieve_user_activity_list(user_id, start_time, end_time, False)
if user_activities is not None:
for user_activity in user_activities:
user_activity[Keys.REALNAME_KEY] = user_realname
activities.extend(user_activities)
# Sort and limit the list.
if len(activities) > 0:
activities = sorted(activities, key=get_activities_sort_key, reverse=True)[:num_results]
return activities
def retrieve_each_user_activity(self, user_id, context, cb_func, start_time, end_time, return_all_data):
"""Fires a callback for all of the user's activities. num_results can be None for all activiites."""
if self.database is None:
raise Exception("No database.")
if user_id is None:
raise Exception("Bad parameter.")
if context is None:
raise Exception("Bad parameter.")
if cb_func is None:
raise Exception("Bad parameter.")
if return_all_data is None:
raise Exception("Bad parameter.")
# List activities recorded on devices registered to the user.
devices = self.database.retrieve_user_devices(user_id)
devices = list(set(devices)) # De-duplicate
for device in devices:
self.database.retrieve_each_device_activity(user_id, device, context, cb_func, start_time, end_time, return_all_data)
# List activities with no device that are associated with the user.
return self.database.retrieve_each_user_activity(user_id, context, cb_func, start_time, end_time, return_all_data)
def retrieve_all_activities_visible_to_user(self, user_id, user_realname, start_time, end_time, num_results):
"""Returns a list containing all of the activities visible to the specified user, up to num_results. num_results can be None for all activiites."""
if self.database is None:
raise Exception("No database.")
if user_id is None or len(user_id) == 0:
raise Exception("Bad parameter.")
# Start with the user's own activities.
activities = self.retrieve_user_activity_list(user_id, user_realname, start_time, end_time, num_results)
# Add the activities of users they follow.
friends = self.database.retrieve_friends(user_id)
for friend in friends:
more_activities = self.retrieve_user_activity_list(friend[Keys.DATABASE_ID_KEY], friend[Keys.REALNAME_KEY], start_time, end_time, num_results)
for another_activity in more_activities:
if self.is_activity_public(another_activity):
activities.append(another_activity)
# Sort and limit the list.
if len(activities) > 0:
activities = sorted(activities, key=get_activities_sort_key, reverse=True)[:num_results]
return activities
def delete_user_gear(self, user_id):
"""Deletes all user gear."""
if self.database is None:
raise Exception("No database.")
if user_id is None or len(user_id) == 0:
raise Exception("Bad parameter.")
# TODO: Remove from each activity
gear_list = self.database.retrieve_gear(user_id)
for gear in gear_list:
pass
# Remove the gear list from the user's profile.
return self.database.delete_all_gear(user_id)
def delete_user_activities(self, user_id):
"""Deletes all user activities."""
if self.database is None:
raise Exception("No database.")
if user_id is None or len(user_id) == 0:
raise Exception("Bad parameter.")
devices = self.database.retrieve_user_devices(user_id)
devices = list(set(devices)) # De-duplicate
if devices is not None:
for device in devices:
self.database.delete_user_device(device)
return True
def retrieve_activity(self, activity_id):
"""Retrieve method for an activity, specified by the activity ID."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("Bad parameter.")
return self.database.retrieve_activity(activity_id)
def delete_activity(self, user_id, activity_id):
"""Delete the activity with the specified object ID."""
if self.database is None:
raise Exception("No database.")
if user_id is None:
raise Exception("Bad parameter.")
if activity_id is None:
raise Exception("Bad parameter.")
# Delete the activity as well as the cache of the PRs performed during that activity.
result = self.database.delete_activity(activity_id)
if result:
# Delete the activity bests (there might not be any), so don't bother checking the return code.
self.database.delete_activity_best_for_user(user_id, activity_id)
# Delete the uploaded file (if any).
self.database.delete_uploaded_file(activity_id)
# Recreate the user's all-time PR list as the previous one could have contained data from the now deleted activity.
result = self.schedule_personal_records_refresh(user_id)
return result
def trim_activity(self, activity, trim_from, num_seconds):
if self.database is None:
raise Exception("No database.")
if activity is None:
raise Exception("Bad parameter.")
if trim_from is None:
raise Exception("Bad parameter.")
if num_seconds is None:
raise Exception("Bad parameter.")
# Make sure the ending time has been computed, compute it if it has not.
trim_before_ms = 0
trim_after_ms = self.compute_activity_end_time_ms(activity)
if trim_after_ms is None:
raise Exception("Cannot compute the ending time for the activity.")
# Compute the new activity start and ending time.
if trim_from == Keys.TRIM_FROM_BEGINNING_VALUE:
if Keys.ACTIVITY_START_TIME_KEY in activity:
trim_before_ms = activity[Keys.ACTIVITY_START_TIME_KEY] * 1000
trim_before_ms = trim_before_ms + (num_seconds * 1000)
if trim_from == Keys.TRIM_FROM_END_VALUE:
trim_after_ms = trim_after_ms - (num_seconds * 1000)
# Trim the location data.
if Keys.APP_LOCATIONS_KEY in activity:
old_locations = activity[Keys.APP_LOCATIONS_KEY]
new_locations = []
for location in old_locations:
ts = location[Keys.LOCATION_TIME_KEY]
if ts >= trim_before_ms and ts <= trim_after_ms:
new_locations.append(location)
activity[Keys.APP_LOCATIONS_KEY] = new_locations
# Trim the sensor data.
for sensor_type in Keys.SENSOR_KEYS:
if sensor_type in activity:
try:
old_sensor_data = activity[sensor_type]
new_sensor_data = []
sensor_iter = iter(old_sensor_data)
sensor_reading = next(sensor_iter)
sensor_time = float(list(sensor_reading.keys())[0])
# Skip over everything before the start time.
while sensor_time < trim_before_ms:
sensor_reading = next(sensor_iter)
sensor_time = float(list(sensor_reading.keys())[0])
# Copy everything up the ending time.
while sensor_time < trim_after_ms:
sensor_reading = next(sensor_iter)
sensor_time = float(list(sensor_reading.keys())[0])
sensor_value = list(sensor_reading.values())[0]
new_sensor_data.append({str(sensor_time): sensor_value})
except StopIteration:
pass
activity[sensor_type] = new_sensor_data
# Write the new, updated activity.
self.database.recreate_activity(activity)
# Activity will need to be reanalyzed.
self.database.delete_activity_summary(activity[Keys.ACTIVITY_ID_KEY])
return True
def activity_exists(self, activity_id):
"""Determines whether or not there is a document corresonding to the activity ID."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("Bad parameter.")
return self.database.activity_exists(activity_id)
def retrieve_activity_visibility(self, activity_id):
"""Returns the visibility setting for the specified activity."""
if self.database is None:
raise Exception("No database.")
if activity_id is None or len(activity_id) == 0:
raise Exception("Bad parameter.")
activity = self.database.retrieve_activity_small(activity_id)
if activity is not None and Keys.ACTIVITY_VISIBILITY_KEY in activity:
return activity[Keys.ACTIVITY_VISIBILITY_KEY]
return None
def update_activity_visibility(self, activity_id, visibility):
"""Changes the visibility setting for the specified activity."""
if self.database is None:
raise Exception("No database.")
if activity_id is None or len(activity_id) == 0:
raise Exception("Bad parameter.")
if visibility is None:
raise Exception("Bad parameter.")
return self.database.create_or_update_activity_metadata(activity_id, None, Keys.ACTIVITY_VISIBILITY_KEY, visibility, False)
def retrieve_activity_locations(self, activity_id):
"""Returns the location list for the specified activity."""
if self.database is None:
raise Exception("No database.")
if activity_id is None or len(activity_id) == 0:
raise Exception("Bad parameter.")
return self.database.retrieve_activity_locations(activity_id)
def delete_activity_sensor_readings(self, key, activity_id):
"""Returns all the sensor data for the specified sensor for the given activity."""
if self.database is None:
raise Exception("No database.")
if key is None or len(key) == 0:
raise Exception("Bad parameter.")
if activity_id is None or len(activity_id) == 0:
raise Exception("Bad parameter.")
return self.database.delete_activity_sensor_readings(key, activity_id)
def retrieve_most_recent_activity_id_for_device(self, device_str):
"""Returns the most recent activity id for the specified device."""
if self.database is None:
raise Exception("No database.")
if device_str is None or len(device_str) == 0:
raise Exception("Bad parameter.")
activity = self.database.retrieve_most_recent_activity_for_device(device_str, False)
if activity is None:
return None
return activity[Keys.ACTIVITY_ID_KEY]
def retrieve_most_recent_activity_for_device(self, device_str):
"""Returns the most recent activity for the specified device."""
if self.database is None:
raise Exception("No database.")
if device_str is None or len(device_str) == 0:
raise Exception("Bad parameter.")
return self.database.retrieve_most_recent_activity_for_device(device_str, False)
def retrieve_most_recent_activity_for_user(self, user_devices):
"""Returns the most recent activity id for the specified user."""
if self.database is None:
raise Exception("No database.")
if user_devices is None:
raise Exception("Bad parameter.")
# Search through each device registered to the user.
most_recent_activity = None
for device_str in user_devices:
# Find the most recent activity for the specified device.
device_activity = self.retrieve_most_recent_activity_for_device(device_str)
if device_activity is not None:
# Is this more recent than our current most recent activity?
if most_recent_activity is None:
most_recent_activity = device_activity
elif Keys.ACTIVITY_START_TIME_KEY in device_activity and Keys.ACTIVITY_START_TIME_KEY in most_recent_activity:
curr_activity_time = device_activity[Keys.ACTIVITY_START_TIME_KEY]
prev_activity_time = most_recent_activity[Keys.ACTIVITY_START_TIME_KEY]
if curr_activity_time > prev_activity_time:
most_recent_activity = device_activity
return most_recent_activity
def create_activity_summary(self, activity_id, summary_data):
"""Create method for activity summary data. Summary data is data computed from the raw data."""
if self.database is None:
raise Exception("No database.")
if activity_id is None or len(activity_id) == 0:
raise Exception("Bad parameter.")
if summary_data is None:
raise Exception("Bad parameter.")
return self.database.create_activity_summary(activity_id, summary_data)
def retrieve_activity_summary(self, activity_id):
"""Retrieve method for activity summary data. Summary data is data computed from the raw data."""
if self.database is None:
raise Exception("No database.")
if activity_id is None or len(activity_id) == 0:
raise Exception("Bad parameter.")
activity = self.database.retrieve_activity_small(activity_id)
if activity is not None and Keys.ACTIVITY_SUMMARY_KEY in activity:
return activity[Keys.ACTIVITY_SUMMARY_KEY]
return None
def delete_activity_summary(self, activity_id):
"""Delete method for activity summary data. Summary data is data computed from the raw data."""
if self.database is None:
raise Exception("No database.")
if activity_id is None or len(activity_id) == 0:
raise Exception("Bad parameter.")
return self.database.delete_activity_summary(activity_id)
def list_default_tags(self):
"""Returns a list of tags that can be used for any activity."""
tags = []
tags.append('Race')
tags.append('Commute')
tags.append('Workout')
tags.append('Interval Workout')
tags.append('Brick Workout')
tags.append('Hot')
tags.append('Humid')
tags.append('Cold')
tags.append('Rainy')
tags.append('Windy')
tags.append('Virtual')
tags.append('Group Activity')
return tags
def list_available_tags_for_activity_type_and_user(self, user_id, activity_type):
"""Returns a list of tags that are valid for a particular activity type and user."""
tags = self.list_default_tags()
gear_list = self.retrieve_gear(user_id)
show_shoes = activity_type in Keys.FOOT_BASED_ACTIVITIES
show_bikes = activity_type in Keys.CYCLING_ACTIVITIES
if activity_type == Keys.TYPE_RUNNING_KEY:
tags.append("Long Run")
for gear in gear_list:
if Keys.GEAR_TYPE_KEY in gear and Keys.GEAR_NAME_KEY in gear:
if (show_shoes and gear[Keys.GEAR_TYPE_KEY] == Keys.GEAR_TYPE_SHOES) or (show_bikes and gear[Keys.GEAR_TYPE_KEY] == Keys.GEAR_TYPE_BIKE):
if gear[Keys.GEAR_RETIRE_TIME_KEY] == 0:
tags.append(gear[Keys.GEAR_NAME_KEY])
return tags
def retrieve_activity_tags(self, activity_id):
"""Returns the most recent 'num' locations for the specified device and activity."""
if self.database is None:
raise Exception("No database.")
if activity_id is None or len(activity_id) == 0:
raise Exception("Bad parameter.")
activity = self.database.retrieve_activity_small(activity_id)
if activity is not None and Keys.ACTIVITY_TAGS_KEY in activity:
return activity[Keys.ACTIVITY_TAGS_KEY]
return []
def create_tags_on_activity(self, activity, tags):
"""Adds tags to an activity."""
if self.database is None:
raise Exception("No database.")
if activity is None:
raise Exception("Bad parameter.")
if tags is None:
raise Exception("Bad parameter.")
return self.database.create_tags_on_activity(activity, tags)
def create_default_tags_on_activity(self, user_id, activity_type, activity_id):
"""Adds tags to an activity."""
if self.database is None:
raise Exception("No database.")
if activity_id is None:
raise Exception("Bad parameter.")
defaults = self.retrieve_gear_defaults(user_id)
for default in defaults:
if Keys.ACTIVITY_TYPE_KEY in default and default[Keys.ACTIVITY_TYPE_KEY] == activity_type:
tags = []
tags.append(default[Keys.GEAR_NAME_KEY])
return self.database.create_tags_on_activity_by_id(activity_id, tags)
return False
def delete_tag_from_activity(self, activity, tag):
"""Delete a tag from an activity."""
if self.database is None:
raise Exception("No database.")
if activity is None:
raise Exception("Bad parameter.")
if tag is None:
raise Exception("Bad parameter.")
return self.database.delete_tag_from_activity(activity, tag)
@staticmethod
def distance_for_activity(activity):
if Keys.APP_DISTANCE_KEY in activity:
return activity[Keys.APP_DISTANCE_KEY]
if Keys.ACTIVITY_SUMMARY_KEY in activity:
summary_data = activity[Keys.ACTIVITY_SUMMARY_KEY]
if Keys.LONGEST_DISTANCE in summary_data:
return summary_data[Keys.LONGEST_DISTANCE]
return 0.0
@staticmethod
def distance_for_tag_cb(tag_distances, activity, user_id):
if tag_distances is None: