-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathschema.py
More file actions
1586 lines (1210 loc) · 53.8 KB
/
Copy pathschema.py
File metadata and controls
1586 lines (1210 loc) · 53.8 KB
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
import binascii
import graphene
import base64
import gspread
import os
from flask_jwt_extended import create_access_token, create_refresh_token, get_jwt_identity, get_jwt, jwt_required
from functools import wraps
from datetime import datetime, timedelta, time, timezone
from graphene_sqlalchemy import SQLAlchemyObjectType
from graphql import GraphQLError
from src.models.capacity import Capacity as CapacityModel
from src.models.capacity_reminder import CapacityReminder as CapacityReminderModel
from src.models.facility import Facility as FacilityModel
from src.models.gym import Gym as GymModel
from src.models.openhours import OpenHours as OpenHoursModel
from src.models.amenity import Amenity as AmenityModel
from src.models.equipment import Equipment as EquipmentModel
from src.models.activity import Activity as ActivityModel, Price as PriceModel
from src.models.classes import Class as ClassModel
from src.models.classes import ClassInstance as ClassInstanceModel
from src.models.token_blacklist import TokenBlocklist
from src.models.user import User as UserModel
from src.models.friends import Friendship as FriendshipModel
from src.models.enums import DayOfWeekGraphQLEnum, CapacityReminderGymGraphQLEnum
from src.models.giveaway import Giveaway as GiveawayModel
from src.models.giveaway import GiveawayInstance as GiveawayInstanceModel
from src.models.workout import Workout as WorkoutModel
from src.models.report import Report as ReportModel
from src.models.hourly_average_capacity import HourlyAverageCapacity as HourlyAverageCapacityModel
from src.models.user_workout_goal_history import UserWorkoutGoalHistory as UserWorkoutGoalHistoryModel
from src.utils.constants import (
SERVICE_ACCOUNT_PATH,
SHEET_KEY,
SHEET_REPORTS,
get_digital_ocean_s3_endpoint_url,
)
from src.database import db_session
import requests
from firebase_admin import messaging
import logging
from zoneinfo import ZoneInfo
from sqlalchemy import func, cast, Date
import boto3
from botocore.config import Config
# Configure the spreadsheet used to mirror user-submitted reports. SHEET_KEY
# selects the development or production spreadsheet based on FLASK_ENV.
gc = gspread.service_account(filename=SERVICE_ACCOUNT_PATH)
sh = gc.open_by_key(SHEET_KEY)
local_tz = ZoneInfo("America/New_York")
def resolve_enum_value(entry):
"""Return the raw value for Enum objects while leaving plain strings untouched."""
return getattr(entry, "value", entry)
def ensure_utc(dt):
"""
Normalize a datetime to UTC.
- If dt is None, return None.
- If dt is naive, assume it is already in UTC and attach UTC tzinfo.
- If dt is timezone-aware, convert it to UTC.
"""
if dt is None:
return None
if getattr(dt, "tzinfo", None) is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def to_local_time(dt):
"""
Convert a UTC datetime to the server's local timezone for output.
- If dt is None, return None.
- If dt is naive, assume it is UTC first.
- If dt is timezone-aware, convert from UTC to local.
"""
if dt is None:
return None
dt_utc = ensure_utc(dt)
if dt_utc is None:
return None
# Convert to local timezone (server-local)
return dt_utc.astimezone(local_tz)
def goal_at(goal_history, window_start_date):
"""
Determine the workout goal for a given window start date from the goal history.
Parameters:
- `window_start_date` (datetime.date): The start date of the window.
- `goal_history` (list[tuple[int, datetime.datetime]]): The list of workout goal history entries.
Returns:
- The workout goal for the given window start date.
"""
for workout_goal, effective_at in goal_history:
if effective_at.date() <= window_start_date:
return workout_goal
return goal_history[-1][0]
# MARK: - Gym
class Gym(SQLAlchemyObjectType):
class Meta:
model = GymModel
amenities = graphene.List(lambda: Amenity)
facilities = graphene.List(lambda: Facility)
hours = graphene.List(lambda: OpenHours)
activities = graphene.List(lambda: Activity)
def resolve_amenities(self, info):
query = Amenity.get_query(info=info).filter(AmenityModel.gym_id == self.id)
return query
def resolve_facilities(self, info):
query = Facility.get_query(info=info).filter(FacilityModel.gym_id == self.id)
return query
def resolve_hours(self, info):
query = OpenHours.get_query(info=info).filter(OpenHoursModel.gym_id == self.id)
return query
def resolve_activities(self, info):
query = Activity.get_query(info=info).filter(ActivityModel.gym_id == self.id)
return query
# MARK: - Facility
class Facility(SQLAlchemyObjectType):
class Meta:
model = FacilityModel
capacity = graphene.Field(lambda: Capacity)
hours = graphene.List(lambda: OpenHours)
equipment = graphene.List(lambda: Equipment)
activities = graphene.List(lambda: Activity)
def resolve_capacity(self, info):
query = (
Capacity.get_query(info=info)
.filter(CapacityModel.facility_id == self.id)
.order_by(CapacityModel.updated.desc())
.first()
)
return query
def resolve_hours(self, info):
query = OpenHours.get_query(info=info).filter(OpenHoursModel.facility_id == self.id)
return query
def resolve_equipment(self, info):
query = Equipment.get_query(info=info).filter(EquipmentModel.facility_id == self.id)
return query
def resolve_activities(self, info):
query = Activity.get_query(info=info).filter(ActivityModel.facility_id == self.id)
return query
# MARK: - Open Hours
class OpenHours(SQLAlchemyObjectType):
class Meta:
model = OpenHoursModel
# MARK: - Equipment
class Equipment(SQLAlchemyObjectType):
class Meta:
model = EquipmentModel
# MARK: - Amenity
class Amenity(SQLAlchemyObjectType):
class Meta:
model = AmenityModel
# MARK: - Capacity
class Capacity(SQLAlchemyObjectType):
class Meta:
model = CapacityModel
# MARK - Hourly Average Capacity
class HourlyAverageCapacity(SQLAlchemyObjectType):
class Meta:
model = HourlyAverageCapacityModel
day_of_week = graphene.Field(DayOfWeekGraphQLEnum)
# MARK: - Price
class Price(SQLAlchemyObjectType):
class Meta:
model = PriceModel
# MARK: - Class
class Class(SQLAlchemyObjectType):
class Meta:
model = ClassModel
class_instances = graphene.List(lambda: ClassInstance)
def resolve_class_instances(self, info):
query = ClassInstance.get_query(info=info).filter(ClassInstanceModel.class_id == self.id)
return query
# MARK: - Class Instance
class ClassInstance(SQLAlchemyObjectType):
class Meta:
model = ClassInstanceModel
gym = graphene.Field(lambda: Gym)
class_ = graphene.Field(lambda: Class)
def resolve_gym(self, info):
query = Gym.get_query(info=info).filter(GymModel.id == self.gym_id).first()
return query
def resolve_class_(self, info):
query = Class.get_query(info=info).filter(ClassModel.id == self.class_id).first()
return query
# MARK: - Activity
class Activity(SQLAlchemyObjectType):
class Meta:
model = ActivityModel
pricing = graphene.List(lambda: Price)
def resolve_pricing(self, info):
query = Price.get_query(info=info).filter(PriceModel.activity_id == self.id)
return query
class WorkoutGoalHistory(SQLAlchemyObjectType):
class Meta:
model = UserWorkoutGoalHistoryModel
def resolve_effective_at(self, info):
return to_local_time(self.effective_at)
# MARK: - User
class User(SQLAlchemyObjectType):
class Meta:
model = UserModel
friendships = graphene.List(lambda: Friendship)
friends = graphene.List(lambda: User)
total_gym_days = graphene.Int(
required=True, description="Get the total number of gym days (unique workout days) for user."
)
streak_start = graphene.DateTime(
description="The start datetime of the most recent active streak (midnight of the day in local timezone), up until the current date."
)
workout_history = graphene.List(lambda: Workout)
def resolve_workout_history(self, info):
query = Workout.get_query(info).filter(WorkoutModel.user_id == self.id).order_by(WorkoutModel.workout_time.desc())
return query.all()
def resolve_total_gym_days(self, info):
return (
Workout.get_query(info)
.filter(WorkoutModel.user_id == self.id)
.with_entities(
func.count(func.distinct(cast(WorkoutModel.workout_time, Date)))
) # We cast the datetiem object as a Date object to get the unique days
.scalar()
)
def resolve_active_streak(self, info):
user = User.get_query(info).filter(UserModel.id == self.id).first()
if not user:
return self.active_streak
workout_date_rows = (
Workout.get_query(info)
.filter(WorkoutModel.user_id == user.id)
.with_entities(cast(WorkoutModel.workout_time, Date).label("workout_date"))
.distinct()
.order_by(cast(WorkoutModel.workout_time, Date).desc())
.all()
)
if not workout_date_rows:
return 0
workout_dates = [row[0] for row in workout_date_rows]
goal_hist = (
db_session.query(UserWorkoutGoalHistoryModel.workout_goal, UserWorkoutGoalHistoryModel.effective_at)
.filter(UserWorkoutGoalHistoryModel.user_id == user.id)
.order_by(UserWorkoutGoalHistoryModel.effective_at.desc())
.all()
)
if not goal_hist:
if not self.workout_goal:
return 0
goal_hist = [(self.workout_goal, datetime.min)]
today = datetime.now(timezone.utc).date()
day_pointer, total_workout_days = 0, len(workout_dates)
window_end = today
streak = 0
while day_pointer < total_workout_days:
window_start = window_end - timedelta(days=6)
day_iterator = day_pointer
count_in_window = 0
while day_iterator < total_workout_days and workout_dates[day_iterator] >= window_start:
count_in_window += 1
day_iterator += 1
goal_days = goal_at(goal_hist, window_start)
if count_in_window == 0:
break
elif count_in_window >= goal_days:
streak += 1
else:
pass
window_end -= timedelta(days=7)
day_pointer = day_iterator
return streak
def resolve_streak_start(self, info):
user = User.get_query(info).filter(UserModel.id == self.id).first()
if not user:
return None
workout_date_rows = (
Workout.get_query(info)
.filter(WorkoutModel.user_id == user.id)
.with_entities(cast(WorkoutModel.workout_time, Date).label("workout_date"))
.distinct()
.order_by(cast(WorkoutModel.workout_time, Date).desc())
.all()
)
if not workout_date_rows:
return None
workout_dates = [row[0] for row in workout_date_rows]
if not workout_dates:
return None
goal_hist = (
db_session.query(UserWorkoutGoalHistoryModel.workout_goal, UserWorkoutGoalHistoryModel.effective_at)
.filter(UserWorkoutGoalHistoryModel.user_id == user.id)
.order_by(UserWorkoutGoalHistoryModel.effective_at.desc())
.all()
)
if not goal_hist:
return None
goal_values = [goal for goal, _ in goal_hist]
goal_effective_dates = []
for _, eff_at in goal_hist:
if eff_at.tzinfo is None:
eff_at = eff_at.replace(tzinfo=timezone.utc)
goal_effective_dates.append(eff_at.date())
if not goal_effective_dates:
return None
goal_index = 0
def goal_for_window_start(ws_date):
nonlocal goal_index
while goal_index < len(goal_values) - 1 and ws_date < goal_effective_dates[goal_index]:
goal_index += 1
if ws_date < goal_effective_dates[-1]:
return None
return goal_values[goal_index]
today = datetime.now(timezone.utc).date()
window_end = today
day_pointer = 0
total = len(workout_dates)
idx_last_streak_start = None
while day_pointer < total:
while day_pointer < total and workout_dates[day_pointer] > today:
day_pointer += 1
window_start = window_end - timedelta(days=6)
window_goal = goal_for_window_start(window_start)
if window_goal is None:
break
i = day_pointer
while i < total and workout_dates[i] >= window_start:
i += 1
count_in_window = i - day_pointer
if count_in_window == 0:
break
if count_in_window >= window_goal:
if i - 1 >= 0:
idx_last_streak_start = i - 1
window_end -= timedelta(days=7)
day_pointer = i
if idx_last_streak_start is None:
return None
last_streak_start_date = workout_dates[idx_last_streak_start]
local_midnight = datetime.combine(last_streak_start_date, time.min, tzinfo=local_tz)
return local_midnight
def resolve_max_streak(self, info):
user = User.get_query(info).filter(UserModel.id == self.id).first()
if not user:
return self.max_streak
workout_date_rows = (
Workout.get_query(info)
.filter(WorkoutModel.user_id == user.id)
.with_entities(cast(WorkoutModel.workout_time, Date).label("workout_date"))
.distinct()
.order_by(cast(WorkoutModel.workout_time, Date).desc())
.all()
)
if not workout_date_rows:
return 0
workout_dates = [row[0] for row in workout_date_rows]
goal_hist = (
db_session.query(UserWorkoutGoalHistoryModel.workout_goal, UserWorkoutGoalHistoryModel.effective_at)
.filter(UserWorkoutGoalHistoryModel.user_id == user.id)
.order_by(UserWorkoutGoalHistoryModel.effective_at.desc())
.all()
)
if not goal_hist:
if not self.workout_goal:
return 0
goal_hist = [(self.workout_goal, datetime.min)]
today = datetime.now(timezone.utc).date()
day_pointer, total_workout_dates = 0, len(workout_dates)
window_end = today
run_met_goal = 0
max_met_goal = 0
while day_pointer < total_workout_dates:
while day_pointer < total_workout_dates and workout_dates[day_pointer] > today:
day_pointer += 1
window_start = window_end - timedelta(days=6)
day_iterator = day_pointer
count_in_window = 0
while day_iterator < total_workout_dates and workout_dates[day_iterator] >= window_start:
count_in_window += 1
day_iterator += 1
goal_days = goal_at(goal_hist, window_start)
if count_in_window == 0:
max_met_goal = max(max_met_goal, run_met_goal)
run_met_goal = 0
elif goal_days and count_in_window >= goal_days:
run_met_goal += 1
else:
pass
window_end -= timedelta(days=7)
day_pointer = day_iterator
max_met_goal = max(max_met_goal, run_met_goal)
return max_met_goal
def resolve_friendships(self, info):
# Return all friendship relationships for this user
query = Friendship.get_query(info).filter(
(FriendshipModel.user_id == self.id) | (FriendshipModel.friend_id == self.id)
)
return query.all()
def resolve_friends(self, info):
# Return all friend users for this user
direct_friendships = Friendship.get_query(info).filter(FriendshipModel.user_id == self.id).all()
reverse_friendships = Friendship.get_query(info).filter(FriendshipModel.friend_id == self.id).all()
friend_ids = set()
# Add friend_ids from direct friendships
for friendship in direct_friendships:
if friendship.is_accepted: # Only include accepted friendships
friend_ids.add(friendship.friend_id)
# Add user_ids from reverse friendships
for friendship in reverse_friendships:
if friendship.is_accepted: # Only include accepted friendships
friend_ids.add(friendship.user_id)
# Query for all the users at once
return User.get_query(info).filter(UserModel.id.in_(friend_ids)).all()
class UserInput(graphene.InputObjectType):
net_id = graphene.String(required=True)
giveaway_id = graphene.Int(required=True)
# MARK: - Friendship
class Friendship(SQLAlchemyObjectType):
class Meta:
model = FriendshipModel
user = graphene.Field(lambda: User)
friend = graphene.Field(lambda: User)
def resolve_user(self, info):
query = User.get_query(info).filter(UserModel.id == self.user_id).first()
return query
def resolve_friend(self, info):
query = User.get_query(info).filter(UserModel.id == self.friend_id).first()
return query
def resolve_accepted_at(self, info):
return to_local_time(self.accepted_at)
# MARK: - Giveaway
class Giveaway(SQLAlchemyObjectType):
class Meta:
model = GiveawayModel
# MARK: - Giveaway Instance
class GiveawayInstance(SQLAlchemyObjectType):
class Meta:
model = GiveawayInstanceModel
# MARK: - Workout
class Workout(SQLAlchemyObjectType):
class Meta:
model = WorkoutModel
gym_name = graphene.String(required=True)
def resolve_gym_name(self, info):
facility = Facility.get_query(info).filter(FacilityModel.id == self.facility_id).first()
if not facility:
raise GraphQLError("Facility for workout not found.")
gym = Gym.get_query(info).filter(GymModel.id == facility.gym_id).first()
if not gym:
raise GraphQLError("Gym for workout not found.")
return gym.name
def resolve_workout_time(self, info):
return to_local_time(self.workout_time)
# MARK: - Report
class Report(SQLAlchemyObjectType):
class Meta:
model = ReportModel
gym = graphene.Field(lambda: Gym)
def resolve_gym(self, info):
query = Gym.get_query(info).filter(GymModel.id == self.gym_id).first()
return query
def resolve_created_at(self, info):
return to_local_time(self.created_at)
# MARK: - Capacity Reminder
class CapacityReminder(SQLAlchemyObjectType):
class Meta:
model = CapacityReminderModel
exclude_fields = ("fcm_token",)
# MARK: - Query
class Query(graphene.ObjectType):
get_all_gyms = graphene.List(Gym, description="Get all gyms.")
get_user_by_net_id = graphene.List(User, net_id=graphene.String(), description="Get user by Net ID.")
get_users_friends = graphene.List(User, id=graphene.Int(), description="Get all friends of a user by ID.")
get_users_by_giveaway_id = graphene.List(User, id=graphene.Int(), description="Get all users given a giveaway ID.")
get_weekly_workout_days = graphene.List(
graphene.String, id=graphene.Int(), description="Get the days a user worked out for the current week."
)
get_workouts_by_id = graphene.List(Workout, id=graphene.Int(), description="Get all of a user's workouts by ID.")
activities = graphene.List(Activity)
get_all_reports = graphene.List(Report, description="Get all reports.")
get_hourly_average_capacities_by_facility_id = graphene.List(
HourlyAverageCapacity, facility_id=graphene.Int(), description="Get all facility hourly average capacities."
)
get_user_friends = graphene.List(
User, user_id=graphene.Int(required=True), description="Get all friends for a user."
)
get_capacity_reminder_by_id = graphene.Field(
CapacityReminder, id=graphene.Int(required=True), description="Get a specific capacity reminder by its ID."
)
get_all_capacity_reminders = graphene.List(CapacityReminder, description="Get all capacity reminders.")
def resolve_get_all_gyms(self, info):
query = Gym.get_query(info)
return query.all()
def resolve_activities(self, info):
query = Activity.get_query(info)
return query.all()
def resolve_get_user_by_net_id(self, info, net_id):
user = User.get_query(info).filter(UserModel.net_id == net_id).all()
if not user:
raise GraphQLError("User with the given Net ID does not exist.")
return user
def resolve_get_users_friends(self, info, id):
user = User.get_query(info).filter(UserModel.id == id).first()
if not user:
raise GraphQLError("User with the given ID does not exist.")
friends = user.get_friends()
return friends
def resolve_get_users_by_giveaway_id(self, info, id):
entries = GiveawayInstance.get_query(info).filter(GiveawayInstanceModel.giveaway_id == id).all()
users = [User.get_query(info).filter(UserModel.id == entry.user_id).first() for entry in entries]
return users
@jwt_required()
def resolve_get_workouts_by_id(self, info, id):
user = User.get_query(info).filter(UserModel.id == id).first()
if not user:
raise GraphQLError("User with the given ID does not exist.")
workouts = Workout.get_query(info).filter(WorkoutModel.user_id == user.id).all()
return workouts
@jwt_required()
def resolve_get_weekly_workout_days(self, info, id):
user = User.get_query(info).filter(UserModel.id == id).first()
if not user:
raise GraphQLError("User with the given ID does not exist.")
# Get the date 7 days ago in UTC
one_week_ago = datetime.now(timezone.utc) - timedelta(days=7)
# Query distinct workout dates for the user in the past week. Workouts must never be logged for a future date.
workout_days = (
Workout.get_query(info)
.filter(
WorkoutModel.user_id == user.id, WorkoutModel.workout_time >= one_week_ago # Use 'workout_time' here
)
.all()
)
# Extract days of the week from the workout times (use a set to avoid duplicates)
# Convert workout_time to local time so the weekday reflects the user's local date.
workout_days_set = {to_local_time(workout.workout_time).strftime("%A") for workout in workout_days}
return list(workout_days_set)
def resolve_get_all_reports(self, info):
query = ReportModel.query.all()
return query
def resolve_get_hourly_average_capacities_by_facility_id(self, info, facility_id):
valid_facility_ids = [14492437, 8500985, 7169406, 10055021, 2323580, 16099753, 15446768, 12572681]
if facility_id not in valid_facility_ids:
raise GraphQLError("Invalid facility ID.")
query = HourlyAverageCapacity.get_query(info).filter(HourlyAverageCapacityModel.facility_id == facility_id)
return query.all()
@jwt_required()
def resolve_get_user_friends(self, info, user_id):
user = User.get_query(info).filter(UserModel.id == user_id).first()
if not user:
raise GraphQLError("User with the given ID does not exist.")
# Direct friendships where user is the initiator
direct_friendships = (
Friendship.get_query(info)
.filter((FriendshipModel.user_id == user_id) & (FriendshipModel.is_accepted == True))
.all()
)
# Reverse friendships where user is the recipient
reverse_friendships = (
Friendship.get_query(info)
.filter((FriendshipModel.friend_id == user_id) & (FriendshipModel.is_accepted == True))
.all()
)
friend_ids = set()
for friendship in direct_friendships:
friend_ids.add(friendship.friend_id)
for friendship in reverse_friendships:
friend_ids.add(friendship.user_id)
# Query for all friends at once
return User.get_query(info).filter(UserModel.id.in_(friend_ids)).all()
@jwt_required()
def resolve_get_capacity_reminder_by_id(self, info, id):
reminder = CapacityReminder.get_query(info).filter(CapacityReminderModel.id == id).first()
if not reminder:
raise GraphQLError("Capacity reminder with the given ID does not exist.")
return reminder
@jwt_required()
def resolve_get_all_capacity_reminders(self, info):
query = CapacityReminder.get_query(info)
return query.all()
# MARK: - Mutation
class LoginUser(graphene.Mutation):
class Arguments:
net_id = graphene.String(required=True)
access_token = graphene.String()
refresh_token = graphene.String()
def mutate(self, info, net_id):
user = db_session.query(UserModel).filter(UserModel.net_id == net_id).first()
if not user:
return GraphQLError("No user with those credentials. Please create an account and try again.")
# Generate JWT token
access_token = create_access_token(identity=str(user.id))
refresh_token = create_refresh_token(identity=str(user.id))
db_session.commit()
return LoginUser(access_token=access_token, refresh_token=refresh_token)
class RefreshAccessToken(graphene.Mutation):
new_access_token = graphene.String()
@jwt_required(refresh=True)
def mutate(self, info):
identity = get_jwt_identity()
new_access_token = create_access_token(identity=identity)
return RefreshAccessToken(new_access_token=new_access_token)
class LogoutUser(graphene.Mutation):
success = graphene.Boolean()
@jwt_required(verify_type=False) # Allows both access and refresh tokens
def mutate(self, info):
token = get_jwt()
jti = token["jti"] # Unique identifier for the token
# Get expiration time from JWT itself
expires_at = datetime.fromtimestamp(token["exp"], tz=timezone.utc)
# Store in blocklist
token = TokenBlocklist(jti=jti, expires_at=expires_at)
db_session.add(token)
db_session.commit()
return LogoutUser(success=True)
class CreateUser(graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
net_id = graphene.String(required=True)
email = graphene.String(required=True)
encoded_image = graphene.String(required=False)
Output = User
def mutate(self, info, name, net_id, email, encoded_image=None):
# Check if a user with the given NetID already exists
existing_user = db_session.query(UserModel).filter(UserModel.net_id == net_id).first()
if existing_user:
raise GraphQLError("NetID already exists.")
final_photo_url = None
if encoded_image:
bucket = "appdev-upload"
path = f"uplift-dev/user-profile/{net_id}-profile.png"
region = "nyc3"
logging.info(
"DIGITAL_OCEAN_URL raw=%r normalized=%r",
os.getenv("DIGITAL_OCEAN_URL"),
get_digital_ocean_s3_endpoint_url(),
)
logging.info(
"CreateUser profile picture upload: net_id=%s, bucket=%s, key=%s",
net_id,
bucket,
path,
)
try:
image_data = base64.b64decode(encoded_image, validate=True)
except (binascii.Error, ValueError) as err:
logging.warning(
"Invalid profile image encoding: %s: %s",
type(err).__name__,
err,
)
raise GraphQLError("Invalid profile image encoding.")
try:
logging.info("Attempting S3 put_object for new user profile picture...")
s3 = boto3.client(
"s3",
endpoint_url=get_digital_ocean_s3_endpoint_url(),
aws_access_key_id=os.getenv("DIGITAL_OCEAN_ACCESS"),
aws_secret_access_key=os.getenv("DIGITAL_OCEAN_SECRET_ACCESS"),
config=Config(s3={"addressing_style": "path"}),
)
s3.put_object(
Bucket=bucket,
Key=path,
Body=image_data,
ContentType="image/png",
ACL="public-read",
)
logging.info("S3 put_object succeeded for new user profile picture")
final_photo_url = f"https://{bucket}.{region}.digitaloceanspaces.com/{path}"
except Exception as e:
logging.error(
"S3 upload failed (create user): %s: %s",
type(e).__name__,
e,
)
raise GraphQLError(f"S3 error: {type(e).__name__}: {e}")
new_user = UserModel(name=name, net_id=net_id, email=email, encoded_image=final_photo_url)
db_session.add(new_user)
db_session.commit()
return new_user
class EditUserById(graphene.Mutation):
class Arguments:
user_id = graphene.Int(required=True)
name = graphene.String(required=False)
email = graphene.String(required=False)
encoded_image = graphene.String(required=False)
Output = User
@jwt_required()
def mutate(self, info, user_id, name=None, email=None, encoded_image=None):
existing_user = db_session.query(UserModel).filter(UserModel.id == user_id).first()
if not existing_user:
raise GraphQLError("User with given id does not exist.")
if int(get_jwt_identity()) != user_id:
raise GraphQLError("Unauthorized operation")
if name is not None:
existing_user.name = name
if email is not None:
existing_user.email = email
if encoded_image is not None:
final_photo_url = None
bucket = "appdev-upload"
path = f"uplift-dev/user-profile/{existing_user.net_id}-profile.png"
region = "nyc3"
logging.info(
"DIGITAL_OCEAN_URL raw=%r normalized=%r",
os.getenv("DIGITAL_OCEAN_URL"),
get_digital_ocean_s3_endpoint_url(),
)
logging.info(
"EditUser profile picture upload: user_id=%s, net_id=%s, bucket=%s, key=%s",
user_id,
existing_user.net_id,
bucket,
path,
)
try:
image_data = base64.b64decode(encoded_image, validate=True)
except (binascii.Error, ValueError) as err:
logging.warning(
"Invalid profile image encoding: %s: %s",
type(err).__name__,
err,
)
raise GraphQLError("Invalid profile image encoding.")
try:
logging.info("Attempting S3 put_object for edited user profile picture...")
s3 = boto3.client(
"s3",
endpoint_url=get_digital_ocean_s3_endpoint_url(),
aws_access_key_id=os.getenv("DIGITAL_OCEAN_ACCESS"),
aws_secret_access_key=os.getenv("DIGITAL_OCEAN_SECRET_ACCESS"),
config=Config(s3={"addressing_style": "path"}),
)
s3.put_object(
Bucket=bucket,
Key=path,
Body=image_data,
ContentType="image/png",
ACL="public-read",
)
logging.info("S3 put_object succeeded for edited user profile picture")
final_photo_url = f"https://{bucket}.{region}.digitaloceanspaces.com/{path}"
existing_user.encoded_image = final_photo_url
except Exception as e:
logging.error(
"S3 upload failed (edit user): %s: %s",
type(e).__name__,
e,
)
raise GraphQLError(f"S3 error: {type(e).__name__}: {e}")
db_session.commit()
return existing_user
class EnterGiveaway(graphene.Mutation):
class Arguments: