-
Notifications
You must be signed in to change notification settings - Fork 3
/
AppDatabase.py
2902 lines (2482 loc) · 120 KB
/
AppDatabase.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.
"""Database implementation"""
import json
import re
import sys
import traceback
import uuid
from bson.objectid import ObjectId
import pymongo
import time
import Database
import DatabaseException
import InputChecker
import Keys
import Perf
import Workout
def insert_into_collection(collection, doc):
"""Handles differences in document insertion between pymongo 3 and 4."""
if int(pymongo.__version__[0]) < 4:
result = collection.insert(doc)
else:
result = collection.insert_one(doc)
return result is not None and result.inserted_id is not None
def update_collection(collection, doc):
"""Handles differences in document updates between pymongo 3 and 4."""
if int(pymongo.__version__[0]) < 4:
collection.save(doc)
return True
else:
query = { Keys.DATABASE_ID_KEY: doc[Keys.DATABASE_ID_KEY] }
new_values = { "$set" : doc }
result = collection.update_one(query, new_values)
return result.matched_count > 0
def update_activities_collection(self, activity):
"""Handles differences in document updates between pymongo 3 and 4 with activities collection-specific logic."""
activity[Keys.ACTIVITY_LAST_UPDATED_KEY] = time.time()
return update_collection(self.activities_collection, activity)
def retrieve_time_from_location(location):
"""Used with the sort function."""
return location['time']
def retrieve_time_from_time_value_pair(value):
"""Used with the sort function."""
return list(value.keys())[0]
class Device(object):
def __init__(self):
self.id = 0
self.name = ""
self.description = ""
super(Device, self).__init__()
class MongoDatabase(Database.Database):
"""Mongo DB implementation of the application database."""
conn = None
database = None
users_collection = None
activities_collection = None
workouts_collection = None
tasks_collectoin = None
uploads_collection = None
sessions_collection = None
def __init__(self):
Database.Database.__init__(self)
def connect(self, config):
"""Connects/creates the database"""
try:
# If we weren't given a database URL then assume localhost and default port.
database_url = config.get_database_url()
self.conn = pymongo.MongoClient('mongodb://' + database_url + '/?uuidRepresentation=pythonLegacy')
# Database.
self.database = self.conn['openworkoutdb']
if self.database is None:
raise DatabaseException.DatabaseException("Could not connect to MongoDB.")
# Handles to the various collections.
self.users_collection = self.database['users']
self.activities_collection = self.database['activities']
self.records_collection = self.database['records']
self.workouts_collection = self.database['workouts']
self.tasks_collection = self.database['tasks']
self.uploads_collection = self.database['uploads']
self.sessions_collection = self.database['sessions']
# Create indexes.
self.activities_collection.create_index(Keys.ACTIVITY_ID_KEY)
except pymongo.errors.ConnectionFailure as e:
raise DatabaseException.DatabaseException("Could not connect to MongoDB: %s" % e)
def total_users_count(self):
"""Returns the number of users in the database."""
try:
if int(pymongo.__version__[0]) < 4:
return self.users_collection.count()
return self.users_collection.count_documents({})
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return 0
def total_activities_count(self):
"""Returns the number of activities in the database."""
try:
if int(pymongo.__version__[0]) < 4:
return self.activities_collection.count()
return self.activities_collection.count_documents({})
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return 0
def list_excluded_activity_keys(self):
"""This is the list of stuff we don't need to return when we're summarizing activities."""
exclude_keys = {}
exclude_keys[Keys.APP_LOCATIONS_KEY] = False
exclude_keys[Keys.APP_ACCELEROMETER_KEY] = False
exclude_keys[Keys.APP_CURRENT_SPEED_KEY] = False
exclude_keys[Keys.APP_HEART_RATE_KEY] = False
exclude_keys[Keys.APP_CADENCE_KEY] = False
exclude_keys[Keys.APP_POWER_KEY] = False
return exclude_keys
#
# User management methods
#
def create_user(self, username, realname, passhash):
"""Create method for a user."""
if username is None:
raise Exception("Unexpected empty object: username")
if realname is None:
raise Exception("Unexpected empty object: realname")
if passhash is None:
raise Exception("Unexpected empty object: passhash")
if len(username) == 0:
raise Exception("username too short")
if len(realname) == 0:
raise Exception("realname too short")
if len(passhash) == 0:
raise Exception("hash too short")
try:
post = { Keys.USERNAME_KEY: username, Keys.REALNAME_KEY: realname, Keys.HASH_KEY: passhash, Keys.DEVICES_KEY: [], Keys.FRIENDS_KEY: [], Keys.DEFAULT_PRIVACY_KEY: Keys.ACTIVITY_VISIBILITY_PUBLIC }
return insert_into_collection(self.users_collection, post)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def retrieve_user_details(self, username):
"""Retrieve method for a user."""
if username is None:
raise Exception("Unexpected empty object: username")
if len(username) == 0:
raise Exception("username is empty")
try:
return self.users_collection.find_one({ Keys.USERNAME_KEY: username })
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return None
def retrieve_user(self, username):
"""Retrieve method for a user."""
if username is None:
raise Exception("Unexpected empty object: username")
if len(username) == 0:
raise Exception("username is empty")
try:
# Find the user.
result_keys = { Keys.DATABASE_ID_KEY: 1, Keys.HASH_KEY: 1, Keys.REALNAME_KEY: 1 }
user = self.users_collection.find_one({ Keys.USERNAME_KEY: username }, result_keys)
# If the user was found.
if user is not None:
return str(user[Keys.DATABASE_ID_KEY]), user[Keys.HASH_KEY], str(user[Keys.REALNAME_KEY])
return None, None, None
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return None, None, None
def retrieve_user_doc_from_id(self, user_id):
"""Retrieve method for a user."""
user_id_obj = ObjectId(str(user_id))
return self.users_collection.find_one({ Keys.DATABASE_ID_KEY: user_id_obj })
def retrieve_user_from_id(self, user_id):
"""Retrieve method for a user."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
try:
# Find the user.
user_id_obj = ObjectId(str(user_id))
result_keys = { Keys.USERNAME_KEY: 1, Keys.REALNAME_KEY: 1 }
user = self.users_collection.find_one({ Keys.DATABASE_ID_KEY: user_id_obj }, result_keys)
# If the user was found.
if user is not None:
return user[Keys.USERNAME_KEY], user[Keys.REALNAME_KEY]
return None, None
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return None, None
def retrieve_user_from_api_key(self, api_key):
"""Retrieve method for a user."""
if api_key is None:
raise Exception("Unexpected empty object: api_key")
try:
# Find the user.
rate = 100
query = { Keys.API_KEYS: { Keys.API_KEY: str(api_key), Keys.API_KEY_RATE : rate } }
result_keys = { Keys.DATABASE_ID_KEY: 1, Keys.HASH_KEY: 1, Keys.REALNAME_KEY: 1 }
user = self.users_collection.find_one(query, result_keys)
# If the user was found.
if user is not None:
return str(user[Keys.DATABASE_ID_KEY]), user[Keys.HASH_KEY], user[Keys.REALNAME_KEY], rate
return None, None, None, rate
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return None, None, None, None
def update_user_doc(self, doc):
"""Update method for a user."""
return update_collection(self.users_collection, doc)
def update_user(self, user_id, username, realname, passhash):
"""Update method for a user."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if username is None:
raise Exception("Unexpected empty object: username")
if realname is None:
raise Exception("Unexpected empty object: realname")
if len(username) == 0:
raise Exception("username too short")
if len(realname) == 0:
raise Exception("realname too short")
try:
# Find the user.
user = self.retrieve_user_doc_from_id(user_id)
# If the user was found.
if user is not None:
user[Keys.USERNAME_KEY] = username
user[Keys.REALNAME_KEY] = realname
if passhash is not None:
user[Keys.HASH_KEY] = passhash
return self.update_user_doc(user)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def delete_user(self, user_id):
"""Delete method for a user."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
try:
user_id_obj = ObjectId(str(user_id))
deleted_result = self.users_collection.delete_one({ Keys.DATABASE_ID_KEY: user_id_obj })
if deleted_result is not None:
return True
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def retrieve_matched_users(self, username):
"""Returns a list of user names for users that match the specified regex."""
user_list = []
if username is None:
raise Exception("Unexpected empty object: username")
if len(username) == 0:
raise Exception("username is empty")
try:
# Match on usernames.
matched_usernames = self.users_collection.find({ Keys.USERNAME_KEY: { "$regex": username } })
if matched_usernames is not None:
for matched_user in matched_usernames:
user_list.append(matched_user[Keys.USERNAME_KEY])
# Match real names too.
matched_realnames = self.users_collection.find({ Keys.REALNAME_KEY: { "$regex": username } })
if matched_realnames is not None:
for matched_user in matched_realnames:
username = matched_user[Keys.USERNAME_KEY]
if username not in user_list:
user_list.append(username)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return user_list
def retrieve_random_user(self):
"""Returns a random user id and name from the database."""
random_user = self.users_collection.aggregate([{ "$sample": { "size": 1 } }])
for user in random_user:
return str(user[Keys.DATABASE_ID_KEY]), user[Keys.USERNAME_KEY]
return None, None
#
# Device management methods
#
def create_user_device(self, user_id, device_str):
"""Create method for a device."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if device_str is None:
raise Exception("Unexpected empty object: device_str")
try:
# Find the user.
user = self.retrieve_user_doc_from_id(user_id)
if user is None:
return False
# Read the devices list.
devices = []
if Keys.DEVICES_KEY in user:
devices = user[Keys.DEVICES_KEY]
# Append the device to the devices list, if it is not already there.
if device_str not in devices:
devices.append(device_str)
user[Keys.DEVICES_KEY] = devices
return self.update_user_doc(user)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return True
def retrieve_user_devices(self, user_id):
"""Retrieve method for a device."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
try:
# Find the user.
user_id_obj = ObjectId(str(user_id))
result_keys = { Keys.DEVICES_KEY: 1 }
user = self.users_collection.find_one({ Keys.DATABASE_ID_KEY: user_id_obj }, result_keys)
# Read the devices list.
if user is not None and Keys.DEVICES_KEY in user:
return user[Keys.DEVICES_KEY]
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return []
def retrieve_user_from_device(self, device_str):
"""Finds the user associated with the device."""
if device_str is None:
raise Exception("Unexpected empty object: device_str")
if len(device_str) == 0:
raise Exception("Device string not provided")
try:
return self.users_collection.find_one({ Keys.DEVICES_KEY: device_str })
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return None
def delete_user_device(self, device_str):
"""Deletes method for a device."""
if device_str is None:
raise Exception("Unexpected empty object: device_str")
if len(device_str) == 0:
raise Exception("Device string not provided")
try:
self.activities_collection.remove({ Keys.ACTIVITY_DEVICE_STR_KEY: device_str })
return True
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
#
# Friend management methods
#
def create_pending_friend_request(self, user_id, target_id):
"""Appends a user to the friends list of the user with the specified id."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if target_id is None:
raise Exception("Unexpected empty object: target_id")
try:
# Find the user whose friendship is being requested.
user = self.retrieve_user_doc_from_id(target_id)
if user is None:
return False
# If the user was found then add the target user to the pending friends list.
pending_friends_list = []
if Keys.FRIEND_REQUESTS_KEY in user:
pending_friends_list = user[Keys.FRIEND_REQUESTS_KEY]
if user_id not in pending_friends_list:
pending_friends_list.append(user_id)
user[Keys.FRIEND_REQUESTS_KEY] = pending_friends_list
return self.update_user_doc(user)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def retrieve_pending_friends(self, user_id):
"""Returns the user ids for all users that are pending confirmation as friends of the specified user."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
try:
# Only return these keys.
result_keys = { Keys.USERNAME_KEY: 1, Keys.REALNAME_KEY: 1, Keys.REQUESTING_USER_KEY: 1 }
# Find the users whose friendship we have requested.
pending_friends_list = []
pending_friends = self.users_collection.find({ Keys.FRIEND_REQUESTS_KEY: user_id }, result_keys)
for pending_friend in pending_friends:
pending_friend[Keys.DATABASE_ID_KEY] = str(pending_friend[Keys.DATABASE_ID_KEY])
pending_friend[Keys.REQUESTING_USER_KEY] = "self"
pending_friends_list.append(pending_friend)
# Find the users who have requested our friendship.
user = self.retrieve_user_doc_from_id(user_id)
# If we found ourselves.
if user is not None:
temp_friend_id_list = []
if Keys.FRIEND_REQUESTS_KEY in user:
temp_friend_id_list = user[Keys.FRIEND_REQUESTS_KEY]
for temp_friend_id in temp_friend_id_list:
temp_friend_id_obj = ObjectId(str(temp_friend_id))
pending_friend = self.users_collection.find_one({ Keys.DATABASE_ID_KEY: temp_friend_id_obj }, result_keys)
if pending_friend is not None:
pending_friend[Keys.DATABASE_ID_KEY] = str(pending_friend[Keys.DATABASE_ID_KEY])
pending_friend[Keys.REQUESTING_USER_KEY] = str(pending_friend[Keys.DATABASE_ID_KEY])
pending_friends_list.append(pending_friend)
return pending_friends_list
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return []
def delete_pending_friend_request(self, user_id, target_id):
"""Appends a user to the friends list of the user with the specified id."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if target_id is None:
raise Exception("Unexpected empty object: target_id")
try:
# Find the user whose friendship is being requested.
user = self.retrieve_user_doc_from_id(user_id)
if user is None:
return False
# If the user was found then add the target user to the pending friends list.
pending_friends_list = []
if Keys.FRIEND_REQUESTS_KEY in user:
pending_friends_list = user[Keys.FRIEND_REQUESTS_KEY]
if target_id in pending_friends_list:
pending_friends_list.remove(target_id)
user[Keys.FRIEND_REQUESTS_KEY] = pending_friends_list
return self.update_user_doc(user)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def create_friend(self, user_id, target_id):
"""Appends a user to the friends list of the user with the specified id."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if target_id is None:
raise Exception("Unexpected empty object: target_id")
try:
# Find the user.
user = self.retrieve_user_doc_from_id(user_id)
# Find the target user.
target_user = self.retrieve_user_doc_from_id(target_id)
# If the users were found then add each other to their friends lists.
if user is not None and target_user is not None:
# Update the user's friends list.
friends_list = []
if Keys.FRIENDS_KEY in user:
friends_list = user[Keys.FRIENDS_KEY]
if target_id not in friends_list:
friends_list.append(target_id)
user[Keys.FRIENDS_KEY] = friends_list
self.update_user_doc(user)
# Update the target user's friends list.
friends_list = []
if Keys.FRIENDS_KEY in target_user:
friends_list = target_user[Keys.FRIENDS_KEY]
if user_id not in friends_list:
friends_list.append(user_id)
target_user[Keys.FRIENDS_KEY] = friends_list
self.update_user_doc(target_user)
return True
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def retrieve_friends(self, user_id):
"""Returns the user ids for all users that are friends with the user who has the specified id."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
try:
# Only return these keys.
result_keys = { Keys.USERNAME_KEY: 1, Keys.REALNAME_KEY: 1 }
# Find the user's friends list.
friends_list = []
friends = self.users_collection.find({ Keys.FRIENDS_KEY: user_id }, result_keys)
for friend in friends:
friend[Keys.DATABASE_ID_KEY] = str(friend[Keys.DATABASE_ID_KEY])
friends_list.append(friend)
return friends_list
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return []
def delete_friend(self, user_id, target_id):
"""Removes the users from each other's friends lists."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if target_id is None:
raise Exception("Unexpected empty object: target_id")
try:
# Find the user.
user = self.retrieve_user_doc_from_id(user_id)
# Find the target user.
target_user = self.retrieve_user_doc_from_id(target_id)
# If the users were found then add each other to their friends lists.
if user is not None and target_user is not None:
# Update the user's friends list.
friends_list = []
if Keys.FRIENDS_KEY in user:
friends_list = user[Keys.FRIENDS_KEY]
if target_id in friends_list:
friends_list.remove(target_id)
user[Keys.FRIENDS_KEY] = friends_list
self.update_user_doc(user)
# Update the target user's friends list.
friends_list = []
if Keys.FRIENDS_KEY in target_user:
friends_list = target_user[Keys.FRIENDS_KEY]
if user_id in friends_list:
friends_list.remove(user_id)
target_user[Keys.FRIENDS_KEY] = friends_list
self.update_user_doc(target_user)
return True
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
#
# User settings methods
#
def update_user_setting(self, user_id, key, value, update_time):
"""Create/update method for user preferences."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if key is None:
raise Exception("Unexpected empty object: key")
if value is None:
raise Exception("Unexpected empty object: value")
if update_time is None:
raise Exception("Unexpected empty object: update_time")
try:
# Find the user.
user = self.retrieve_user_doc_from_id(user_id)
if user is None:
return False
# Do not replace a newer value with an older value.
if Keys.USER_SETTINGS_LAST_UPDATED_KEY not in user:
user[Keys.USER_SETTINGS_LAST_UPDATED_KEY] = {}
elif key in user[Keys.USER_SETTINGS_LAST_UPDATED_KEY] and user[Keys.USER_SETTINGS_LAST_UPDATED_KEY][key] > update_time:
return False
# Update.
user[Keys.USER_SETTINGS_LAST_UPDATED_KEY][key] = update_time
user[key] = value
return self.update_user_doc(user)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def retrieve_user_setting(self, user_id, key):
"""Retrieve method for user preferences."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if key is None:
raise Exception("Unexpected empty object: key")
try:
# Find the user.
user = self.retrieve_user_doc_from_id(user_id)
if user is None:
return None
# We want to search for keys in a case insensitive manner.
user_lower = { k.lower():v for k,v in user.items() }
key_lower = key.lower()
valid_settings = set(k.lower() for k in Keys.USER_SETTINGS)
# Find the setting.
if user_lower is not None and key_lower in user_lower and key_lower in valid_settings:
return user_lower[key_lower]
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return None
def retrieve_user_settings(self, user_id, keys):
"""Retrieve method for user preferences."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if keys is None:
raise Exception("Unexpected empty object: keys")
try:
# Find the user.
user = self.retrieve_user_doc_from_id(user_id)
if user is None:
return []
# We want to search for keys in a case insensitive manner.
user_lower = { k.lower():v for k,v in user.items() }
keys_lower = set(k.lower() for k in keys)
valid_settings = set(k.lower() for k in Keys.USER_SETTINGS)
# Find the settings.
results = []
for key in keys_lower:
if key in user_lower and key in valid_settings:
results.append({key: user_lower[key]})
return results
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return []
#
# Personal record management methods
#
def create_user_personal_records(self, user_id, records):
"""Create method for a user's personal record."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if records is None:
raise Exception("Unexpected empty object: records")
try:
# Find the user's records collection.
user_id_str = str(user_id)
user_records = self.records_collection.find_one({ Keys.USER_ID_KEY: user_id_str })
# If the collection was found.
if user_records is None:
post = { Keys.USER_ID_KEY: user_id_str, Keys.PERSONAL_RECORDS_KEY: records }
return insert_into_collection(self.records_collection, post)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def update_user_personal_records(self, user_id, records):
"""Create method for a user's personal record. These are the bests across all activities. Activity records are the bests for individual activities."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if records is None or len(records) == 0:
raise Exception("Unexpected empty object: records")
try:
# Find the user's records collection.
user_id_str = str(user_id)
user_records = self.records_collection.find_one({ Keys.USER_ID_KEY: user_id_str })
# If the collection was found.
if user_records is not None:
user_records[Keys.PERSONAL_RECORDS_KEY] = records
return update_collection(self.records_collection, user_records)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def delete_all_user_personal_records(self, user_id):
"""Delete method for a user's personal record. Deletes the entire personal record cache."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
try:
# Delete the user's records collection.
user_id_str = str(user_id)
deleted_result = self.records_collection.delete_one({ Keys.USER_ID_KEY: user_id_str })
if deleted_result is not None:
return True
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
#
# Activity bests management methods
#
def create_activity_bests(self, user_id, activity_id, activity_type, activity_time, bests):
"""Create method for a user's personal records for a given activity."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if activity_id is None:
raise Exception("Unexpected empty object: activity_id")
if not InputChecker.is_uuid(activity_id):
raise Exception("Invalid object: activity_id " + str(activity_id))
if activity_type is None:
raise Exception("Unexpected empty object: activity_type")
if activity_time is None:
raise Exception("Unexpected empty object: activity_time")
if bests is None:
raise Exception("Unexpected empty object: bests")
try:
# Find the user's records collection.
user_records = self.records_collection.find_one({ Keys.USER_ID_KEY: user_id })
if user_records is not None:
bests[Keys.ACTIVITY_TYPE_KEY] = activity_type
bests[Keys.ACTIVITY_START_TIME_KEY] = activity_time
user_records[activity_id] = bests
return update_collection(self.records_collection, user_records)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
def retrieve_activity_bests_for_user(self, user_id):
"""Retrieve method for a user's activity records."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
try:
user_records = self.records_collection.find_one({ Keys.USER_ID_KEY: user_id })
if user_records is None:
return {}
# Each record is named using the activity ID of the corresponding activity.
bests = {}
for activity_id in user_records:
if InputChecker.is_uuid(activity_id):
activity_bests = user_records[activity_id]
bests[activity_id] = activity_bests
return bests
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return {}
def retrieve_bounded_activity_bests_for_user(self, user_id, cutoff_time_lower, cutoff_time_higher):
"""Retrieve method for a user's activity records. Only activities more recent than the specified cutoff time will be returned."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if cutoff_time_lower is None:
raise Exception("Unexpected empty object: cutoff_time_lower")
if cutoff_time_higher is None:
raise Exception("Unexpected empty object: cutoff_time_higher")
try:
user_records = self.records_collection.find_one({ Keys.USER_ID_KEY: user_id })
if user_records is None:
return {}
# Each record is named using the activity ID of the corresponding activity.
bests = {}
for activity_id in user_records:
if InputChecker.is_uuid(activity_id):
activity_bests = user_records[activity_id]
if Keys.ACTIVITY_START_TIME_KEY in activity_bests:
activity_time = activity_bests[Keys.ACTIVITY_START_TIME_KEY]
if activity_time >= cutoff_time_lower and activity_time < cutoff_time_higher:
bests[activity_id] = activity_bests
return bests
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return {}
def delete_activity_best_for_user(self, user_id, activity_id):
"""Delete method for a user's personal records for a given activity."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if activity_id is None:
raise Exception("Unexpected empty object: activity_id")
if not InputChecker.is_uuid(activity_id):
raise Exception("Invalid object: activity_id " + str(activity_id))
try:
user_records = self.records_collection.find_one({ Keys.USER_ID_KEY: user_id })
if user_records is not None:
user_records[activity_id] = {}
return update_collection(self.records_collection, user_records)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
#
# Activity management methods
#
@Perf.statistics
def retrieve_user_activity_list(self, user_id, start_time, end_time, return_all_data):
"""Retrieves the list of activities associated with the specified user."""
"""If return_all_data is False then only metadata is returned."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
try:
# Things we don't need.
if return_all_data:
exclude_keys = None
else:
exclude_keys = self.list_excluded_activity_keys()
if start_time is None or end_time is None:
return list(self.activities_collection.find({ "$and": [ { Keys.ACTIVITY_USER_ID_KEY: { '$eq': user_id } } ]}, exclude_keys))
return list(self.activities_collection.find({ "$and": [ { Keys.ACTIVITY_USER_ID_KEY: { '$eq': user_id }}, { Keys.ACTIVITY_START_TIME_KEY: { '$gt': start_time } }, { Keys.ACTIVITY_START_TIME_KEY: { '$lt': end_time } } ]}, exclude_keys))
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return []
@Perf.statistics
def retrieve_each_user_activity(self, user_id, context, callback_func, start_time, end_time, return_all_data):
"""Retrieves each user activity and calls the callback function for each one."""
"""Returns TRUE on success, FALSE if an error was encountered."""
"""If return_all_data is False then only metadata is returned."""
if user_id is None:
raise Exception("Unexpected empty object: user_id")
if callback_func is None:
raise Exception("Unexpected empty object: callback_func")
try:
# Things we don't need.
if return_all_data:
exclude_keys = None
else:
exclude_keys = self.list_excluded_activity_keys()
# Get an iterator to the activities.
if start_time is None or end_time is None:
activities_cursor = self.activities_collection.find({ Keys.ACTIVITY_USER_ID_KEY: user_id }, exclude_keys)
activities_cursor = self.activities_collection.find({ "$and": [ { Keys.ACTIVITY_START_TIME_KEY: { '$gt': start_time } }, { Keys.ACTIVITY_START_TIME_KEY: { '$lt': end_time } } ]}, exclude_keys)
# Iterate over the results, triggering the callback for each.
if activities_cursor is not None:
try:
while activities_cursor.alive:
activity = activities_cursor.next()
callback_func(context, activity, user_id)
except StopIteration:
pass
return True
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return False
@Perf.statistics
def retrieve_devices_activity_list(self, devices, start_time, end_time, return_all_data):
"""Retrieves the list of activities associated with the specified devices."""
if devices is None:
raise Exception("Unexpected empty object: devices")
try:
# Things we don't need.
if return_all_data:
exclude_keys = None
else:
exclude_keys = self.list_excluded_activity_keys()
# Build part of the exptression while sanity checking the input.
device_list = []
for device_str in devices:
if InputChecker.is_uuid(device_str):
device_list.append( { Keys.ACTIVITY_DEVICE_STR_KEY: {'$eq': device_str} } )
# If the device list is empty then just return as there's nothing to do and we'll just get a db error.
if not device_list:
return []
if start_time is None or end_time is None:
return list(self.activities_collection.find({ "$or": device_list }, exclude_keys))
return list(self.activities_collection.find({ "$and": [ { "$or": device_list }, { Keys.ACTIVITY_START_TIME_KEY: { '$gt': start_time } }, { Keys.ACTIVITY_START_TIME_KEY: { '$lt': end_time } } ] }, exclude_keys))
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
return []
@Perf.statistics
def retrieve_each_device_activity(self, user_id, device_str, context, callback_func, start_time, end_time, return_all_data):
"""Retrieves each device activity and calls the callback function for each one."""
"""If return_all_data is False then only metadata is returned."""
if user_id is None:
raise Exception("Unexpected empty object: device_str")
if device_str is None:
raise Exception("Unexpected empty object: device_str")
if callback_func is None:
raise Exception("Unexpected empty object: device_str")
try:
# Things we don't need.
if return_all_data:
exclude_keys = None
else:
exclude_keys = self.list_excluded_activity_keys()
# Get an iterator to the activities.
if start_time is None or end_time is None:
activities_cursor = self.activities_collection.find({ Keys.ACTIVITY_DEVICE_STR_KEY: device_str }, exclude_keys)
activities_cursor = self.activities_collection.find({ "$and": [ { Keys.ACTIVITY_DEVICE_STR_KEY: { '$eq': device_str } }, { Keys.ACTIVITY_START_TIME_KEY: { '$gt': start_time } }, { Keys.ACTIVITY_START_TIME_KEY: { '$lt': end_time } } ]}, exclude_keys)
# Iterate over the results, triggering the callback for each.
if activities_cursor is not None:
try:
while activities_cursor.alive:
activity = activities_cursor.next()
callback_func(context, activity, user_id)