-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathoperations.py
More file actions
2723 lines (2316 loc) · 90.4 KB
/
operations.py
File metadata and controls
2723 lines (2316 loc) · 90.4 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
# Database operations for Google Calendar API Replica
# CRUD operations for all Calendar API resources
import logging
from datetime import datetime, timezone, timedelta
from typing import Any, Optional
logger = logging.getLogger(__name__)
from sqlalchemy.orm import Session
from sqlalchemy import select, and_, or_, func, update, delete
from sqlalchemy.exc import IntegrityError
from .schema import (
User,
Calendar,
CalendarListEntry,
Event,
EventAttendee,
EventReminder,
AclRule,
Setting,
Channel,
SyncToken,
AccessRole,
EventStatus,
AclScopeType,
)
from ..core.utils import (
generate_event_id,
generate_calendar_id,
generate_ical_uid,
generate_acl_rule_id,
generate_etag,
generate_sync_token,
extract_datetime,
format_rfc3339,
parse_rfc3339,
calendar_now,
PageToken,
parse_instance_id,
parse_original_start_time,
build_original_start_time,
format_instance_id,
expand_recurrence,
)
from ..core.errors import (
CalendarNotFoundError,
EventNotFoundError,
AclNotFoundError,
SettingNotFoundError,
ValidationError,
RequiredFieldError,
DuplicateError,
ForbiddenError,
SyncTokenExpiredError,
)
# ============================================================================
# USER OPERATIONS
# ============================================================================
def create_user(
session: Session,
email: str,
user_id: Optional[str] = None,
display_name: Optional[str] = None,
create_primary_calendar: bool = True,
) -> User:
"""Create a new user with optional primary calendar."""
if user_id is None:
# Use email as user ID (Google-style)
user_id = email
user = User(
id=user_id,
email=email,
display_name=display_name,
)
session.add(user)
if create_primary_calendar:
# Create primary calendar for user
calendar = Calendar(
id=email, # Primary calendar ID is user's email
summary=display_name or email,
owner_id=user_id,
etag=generate_etag(f"{email}:1"),
)
session.add(calendar)
# Create CalendarListEntry for the primary calendar
entry = CalendarListEntry(
id=f"{user_id}:{email}",
user_id=user_id,
calendar_id=email,
access_role=AccessRole.owner,
primary=True,
etag=generate_etag(f"{email}:list:1"),
)
session.add(entry)
# Create owner ACL rule (include calendar_id in rule id for uniqueness)
acl_rule = AclRule(
id=generate_acl_rule_id("user", email, calendar_id=email),
calendar_id=email,
role=AccessRole.owner,
scope_type=AclScopeType.user,
scope_value=email,
etag=generate_etag(f"{email}:acl:1"),
)
session.add(acl_rule)
# Create default settings
_create_default_settings(session, user_id)
try:
session.flush()
except IntegrityError:
session.rollback()
raise DuplicateError(f"User already exists: {email}")
return user
def get_user(session: Session, user_id: str) -> Optional[User]:
"""Get a user by ID."""
return session.get(User, user_id)
def get_user_by_email(session: Session, email: str) -> Optional[User]:
"""Get a user by email."""
return session.execute(
select(User).where(User.email == email)
).scalar_one_or_none()
def _create_default_settings(session: Session, user_id: str) -> None:
"""Create default settings for a new user."""
default_settings = {
"timezone": "UTC",
"locale": "en",
"dateFieldOrder": "MDY",
"format24HourTime": "false",
"weekStart": "0", # Sunday
"defaultEventLength": "60",
"showDeclinedEvents": "true",
"hideInvitations": "false",
"hideWeekends": "false",
"useKeyboardShortcuts": "true",
"autoAddHangouts": "true",
"remindOnRespondedEventsOnly": "false",
}
for setting_id, value in default_settings.items():
setting = Setting(
user_id=user_id,
setting_id=setting_id,
value=value,
etag=generate_etag(f"{user_id}:{setting_id}:1"),
)
session.add(setting)
# ============================================================================
# CALENDAR OPERATIONS
# ============================================================================
def create_calendar(
session: Session,
owner_id: str,
summary: str,
description: Optional[str] = None,
location: Optional[str] = None,
time_zone: Optional[str] = None,
calendar_id: Optional[str] = None,
) -> Calendar:
"""Create a new secondary calendar."""
owner = session.get(User, owner_id)
if owner is None:
raise ValidationError(f"Owner not found: {owner_id}")
if calendar_id is None:
calendar_id = generate_calendar_id(owner.email, is_primary=False)
calendar = Calendar(
id=calendar_id,
summary=summary,
description=description,
location=location,
time_zone=time_zone or "UTC",
owner_id=owner_id,
data_owner=owner.email, # Read-only field for secondary calendars
etag=generate_etag(f"{calendar_id}:1"),
)
session.add(calendar)
# Create CalendarListEntry for owner
entry = CalendarListEntry(
id=f"{owner_id}:{calendar_id}",
user_id=owner_id,
calendar_id=calendar_id,
access_role=AccessRole.owner,
primary=False,
etag=generate_etag(f"{calendar_id}:list:1"),
)
session.add(entry)
# Create owner ACL rule
# Include calendar_id in rule_id to make it unique per calendar
acl_rule_id = f"{calendar_id}:{generate_acl_rule_id('user', owner.email)}"
acl_rule = AclRule(
id=acl_rule_id,
calendar_id=calendar_id,
role=AccessRole.owner,
scope_type=AclScopeType.user,
scope_value=owner.email,
etag=generate_etag(f"{calendar_id}:acl:1"),
)
session.add(acl_rule)
try:
session.flush()
except IntegrityError:
session.rollback()
raise DuplicateError(f"Calendar already exists: {calendar_id}")
return calendar
def get_calendar(
session: Session,
calendar_id: str,
user_id: Optional[str] = None,
) -> Calendar:
"""Get a calendar by ID, optionally resolving 'primary'."""
if calendar_id == "primary" and user_id:
user = session.get(User, user_id)
if user:
calendar_id = user.email
calendar = session.get(Calendar, calendar_id)
if calendar is None or calendar.deleted:
raise CalendarNotFoundError(calendar_id)
return calendar
def update_calendar(
session: Session,
calendar_id: str,
user_id: str,
summary: Optional[str] = None,
description: Optional[str] = None,
location: Optional[str] = None,
time_zone: Optional[str] = None,
) -> Calendar:
"""Update a calendar's metadata."""
calendar = get_calendar(session, calendar_id, user_id)
_check_calendar_access(session, calendar_id, user_id, AccessRole.owner)
if summary is not None:
calendar.summary = summary
if description is not None:
calendar.description = description
if location is not None:
calendar.location = location
if time_zone is not None:
calendar.time_zone = time_zone
calendar.updated_at = calendar_now()
calendar.etag = generate_etag(f"{calendar_id}:{calendar.updated_at.isoformat()}")
return calendar
def delete_calendar(
session: Session,
calendar_id: str,
user_id: str,
) -> None:
"""Delete a secondary calendar."""
calendar = get_calendar(session, calendar_id, user_id)
_check_calendar_access(session, calendar_id, user_id, AccessRole.owner)
# Check if this is a primary calendar (can't delete primary)
user = session.get(User, user_id)
if user and calendar_id == user.email:
raise ValidationError("Cannot delete primary calendar")
# Soft delete
calendar.deleted = True
calendar.updated_at = calendar_now()
def clear_calendar(
session: Session,
calendar_id: str,
user_id: str,
) -> None:
"""Clear all events from a calendar (primary only)."""
calendar = get_calendar(session, calendar_id, user_id)
_check_calendar_access(session, calendar_id, user_id, AccessRole.owner)
# Mark all events as cancelled
session.execute(
update(Event)
.where(Event.calendar_id == calendar.id)
.values(
status=EventStatus.cancelled,
updated_at=calendar_now(),
)
)
# ============================================================================
# CALENDAR LIST OPERATIONS
# ============================================================================
def insert_calendar_list_entry(
session: Session,
user_id: str,
calendar_id: str,
color_id: Optional[str] = None,
background_color: Optional[str] = None,
foreground_color: Optional[str] = None,
hidden: bool = False,
selected: bool = True,
default_reminders: Optional[list[dict[str, Any]]] = None,
notification_settings: Optional[dict[str, Any]] = None,
summary_override: Optional[str] = None,
) -> CalendarListEntry:
"""Add a calendar to user's calendar list."""
# Verify calendar exists
calendar = session.get(Calendar, calendar_id)
if calendar is None or calendar.deleted:
raise CalendarNotFoundError(calendar_id)
# Check if user has read access
access_role = _get_user_access_role(session, calendar_id, user_id)
if access_role is None:
raise ForbiddenError(f"No access to calendar: {calendar_id}")
# Check if entry already exists
existing = session.execute(
select(CalendarListEntry).where(
and_(
CalendarListEntry.user_id == user_id,
CalendarListEntry.calendar_id == calendar_id,
)
)
).scalar_one_or_none()
if existing:
raise DuplicateError("Calendar already in list")
entry = CalendarListEntry(
id=f"{user_id}:{calendar_id}",
user_id=user_id,
calendar_id=calendar_id,
access_role=access_role,
color_id=color_id,
background_color=background_color,
foreground_color=foreground_color,
hidden=hidden,
selected=selected,
default_reminders=default_reminders,
notification_settings=notification_settings,
summary_override=summary_override,
primary=False,
etag=generate_etag(f"{user_id}:{calendar_id}:1"),
)
session.add(entry)
try:
session.flush()
except IntegrityError:
session.rollback()
raise DuplicateError("Calendar already in list")
return entry
def get_calendar_list_entry(
session: Session,
user_id: str,
calendar_id: str,
) -> CalendarListEntry:
"""Get a calendar list entry."""
if calendar_id == "primary":
user = session.get(User, user_id)
if user:
calendar_id = user.email
entry = session.execute(
select(CalendarListEntry).where(
and_(
CalendarListEntry.user_id == user_id,
CalendarListEntry.calendar_id == calendar_id,
CalendarListEntry.deleted == False, # noqa: E712
)
)
).scalar_one_or_none()
if entry is None:
raise CalendarNotFoundError(calendar_id)
return entry
def list_calendar_list_entries(
session: Session,
user_id: str,
max_results: int = 250,
page_token: Optional[str] = None,
min_access_role: Optional[str] = None,
show_deleted: bool = False,
show_hidden: bool = False,
sync_token: Optional[str] = None,
) -> tuple[list[CalendarListEntry], Optional[str], Optional[str]]:
"""
List calendar list entries for a user.
Returns: (entries, next_page_token, next_sync_token)
"""
# Handle sync token
if sync_token:
token_record = session.execute(
select(SyncToken).where(
and_(
SyncToken.token == sync_token,
SyncToken.user_id == user_id,
SyncToken.resource_type == "calendarList",
)
)
).scalar_one_or_none()
if token_record is None or token_record.expires_at < calendar_now():
raise SyncTokenExpiredError()
# Return only items updated since token was created
query = select(CalendarListEntry).where(
and_(
CalendarListEntry.user_id == user_id,
CalendarListEntry.updated_at > token_record.snapshot_time,
)
)
else:
query = select(CalendarListEntry).where(
CalendarListEntry.user_id == user_id
)
# Apply filters
if not show_deleted:
query = query.where(CalendarListEntry.deleted == False) # noqa: E712
if not show_hidden:
query = query.where(CalendarListEntry.hidden == False) # noqa: E712
if min_access_role:
role_order = ["freeBusyReader", "reader", "writer", "owner"]
# Validate min_access_role before using it
if min_access_role not in role_order:
raise ValidationError(
f"Invalid minAccessRole value: {min_access_role}. "
f"Must be one of: {', '.join(role_order)}"
)
min_idx = role_order.index(min_access_role)
allowed_roles = role_order[min_idx:]
query = query.where(
CalendarListEntry.access_role.in_([AccessRole[r] for r in allowed_roles])
)
# Get total count for pagination
query = query.order_by(CalendarListEntry.id)
# Apply pagination
offset = 0
if page_token:
offset, _ = PageToken.decode(page_token)
query = query.offset(offset).limit(max_results + 1)
entries = list(session.execute(query).scalars().all())
# Check if there are more results
next_page_token = None
if len(entries) > max_results:
entries = entries[:max_results]
next_page_token = PageToken.encode(offset + max_results)
# Generate sync token for next incremental sync
next_sync_token = None
if not page_token and not sync_token:
# Only generate sync token for initial full sync
next_sync_token = _create_sync_token(session, user_id, "calendarList")
return entries, next_page_token, next_sync_token
def update_calendar_list_entry(
session: Session,
user_id: str,
calendar_id: str,
summary_override: Optional[str] = None,
color_id: Optional[str] = None,
background_color: Optional[str] = None,
foreground_color: Optional[str] = None,
hidden: Optional[bool] = None,
selected: Optional[bool] = None,
default_reminders: Optional[list[dict[str, Any]]] = None,
notification_settings: Optional[dict[str, Any]] = None,
) -> CalendarListEntry:
"""Update a calendar list entry."""
entry = get_calendar_list_entry(session, user_id, calendar_id)
if summary_override is not None:
entry.summary_override = summary_override
if color_id is not None:
entry.color_id = color_id
if background_color is not None:
entry.background_color = background_color
if foreground_color is not None:
entry.foreground_color = foreground_color
if hidden is not None:
entry.hidden = hidden
if selected is not None:
entry.selected = selected
if default_reminders is not None:
entry.default_reminders = default_reminders
if notification_settings is not None:
entry.notification_settings = notification_settings
entry.updated_at = calendar_now()
entry.etag = generate_etag(f"{entry.id}:{entry.updated_at.isoformat()}")
return entry
def delete_calendar_list_entry(
session: Session,
user_id: str,
calendar_id: str,
) -> None:
"""Remove a calendar from user's calendar list."""
entry = get_calendar_list_entry(session, user_id, calendar_id)
# Can't remove primary calendar
if entry.primary:
raise ValidationError("Cannot remove primary calendar from list")
# Soft delete
entry.deleted = True
entry.updated_at = calendar_now()
# ============================================================================
# EVENT OPERATIONS
# ============================================================================
def create_event(
session: Session,
calendar_id: str,
user_id: str,
start: dict[str, Any],
end: dict[str, Any],
summary: Optional[str] = None,
description: Optional[str] = None,
location: Optional[str] = None,
attendees: Optional[list[dict[str, Any]]] = None,
recurrence: Optional[list[str]] = None,
reminders: Optional[dict[str, Any]] = None,
event_id: Optional[str] = None,
ical_uid: Optional[str] = None,
**kwargs: Any,
) -> Event:
"""Create a new event."""
calendar = get_calendar(session, calendar_id, user_id)
_check_calendar_access(session, calendar.id, user_id, AccessRole.writer)
user = session.get(User, user_id)
if user is None:
raise ValidationError(f"User not found: {user_id}")
# Generate event ID if not provided
if event_id is None:
event_id = generate_event_id()
# Validate event ID format
from ..core.utils import validate_event_id
if not validate_event_id(event_id):
raise ValidationError(f"Invalid event ID format: {event_id}", field="id")
# Generate iCalUID if not provided
if ical_uid is None:
ical_uid = generate_ical_uid(event_id, calendar.id)
# Extract datetime for indexing
start_dt = extract_datetime(start)
end_dt = extract_datetime(end)
start_date = start.get("date")
end_date = end.get("date")
# Extract organizer/creator fields from kwargs to allow override (e.g., for import)
# Use provided values if present, otherwise default to current user
# This matches Google Calendar API behavior where imports preserve original organizer
organizer_email = kwargs.pop("organizer_email", None) or user.email
organizer_display_name = kwargs.pop("organizer_display_name", None) or user.display_name
organizer_self = organizer_email == user.email
event = Event(
id=event_id,
calendar_id=calendar.id,
summary=summary,
description=description,
location=location,
start=start,
end=end,
start_datetime=start_dt,
end_datetime=end_dt,
start_date=start_date,
end_date=end_date,
recurrence=recurrence,
reminders=reminders,
ical_uid=ical_uid,
creator_id=user_id,
creator_email=user.email,
creator_display_name=user.display_name,
creator_self=True,
organizer_id=user_id,
organizer_email=organizer_email,
organizer_display_name=organizer_display_name,
organizer_self=organizer_self,
etag=generate_etag(f"{event_id}:1"),
**{k: v for k, v in kwargs.items() if hasattr(Event, k)},
)
session.add(event)
# Add attendees
if attendees:
for idx, attendee_data in enumerate(attendees):
# Validate email is required for attendees (per Google Calendar API)
if "email" not in attendee_data or not attendee_data["email"]:
raise RequiredFieldError(f"attendees[{idx}].email")
attendee = EventAttendee(
event_id=event_id,
email=attendee_data["email"],
display_name=attendee_data.get("displayName"),
organizer=attendee_data.get("organizer", False),
self_=attendee_data.get("email") == user.email,
optional=attendee_data.get("optional", False),
response_status=attendee_data.get("responseStatus", "needsAction"),
comment=attendee_data.get("comment"),
additional_guests=attendee_data.get("additionalGuests", 0),
)
session.add(attendee)
try:
session.flush()
except IntegrityError:
session.rollback()
raise DuplicateError(f"Event already exists: {event_id}")
return event
def get_event(
session: Session,
calendar_id: str,
event_id: str,
user_id: str,
time_zone: Optional[str] = None,
) -> Event:
"""
Get an event by ID, including recurring event instances.
This function handles three cases:
1. Regular event: Returns the event directly
2. Persisted exception: Returns the exception event
3. Virtual instance: Creates and returns a virtual Event object
Args:
session: Database session
calendar_id: Calendar ID
event_id: Event ID (may be an instance ID like "abc123_20180618T100000Z")
user_id: User ID for access check
time_zone: Optional timezone for response formatting
Returns:
Event object (may be virtual for recurring instances)
Raises:
EventNotFoundError: If event not found or cancelled
"""
calendar = get_calendar(session, calendar_id, user_id)
_check_calendar_access(session, calendar.id, user_id, AccessRole.reader)
# First, try to find the event directly (handles regular events and exceptions)
event = session.get(Event, event_id)
if event is not None and event.calendar_id == calendar.id:
if event.status == EventStatus.cancelled:
raise EventNotFoundError(event_id)
return event
# Check if this is a recurring instance ID
base_id, original_time_str = parse_instance_id(event_id)
if not original_time_str:
# Not an instance ID and not found as regular event
raise EventNotFoundError(event_id)
# Get the master recurring event
master = session.get(Event, base_id)
if master is None or master.calendar_id != calendar.id or not master.recurrence:
raise EventNotFoundError(event_id)
if master.status == EventStatus.cancelled:
raise EventNotFoundError(event_id)
# Parse the original start time
original_dt = parse_original_start_time(original_time_str)
# Check for a cancelled exception for this instance
cancelled = session.execute(
select(Event).where(
and_(
Event.id == event_id,
Event.status == EventStatus.cancelled,
)
)
).scalar_one_or_none()
if cancelled:
raise EventNotFoundError(event_id)
# Verify this instance exists in the recurrence
time_min = original_dt - timedelta(minutes=1)
time_max = original_dt + timedelta(minutes=1)
instance_dates = expand_recurrence(
recurrence=master.recurrence,
start=master.start_datetime,
time_min=time_min,
time_max=time_max,
max_instances=10,
)
# Check if the original_dt is in the expanded instances
instance_found = False
for inst_dt in instance_dates:
# Normalize to UTC for comparison
if inst_dt.tzinfo is None:
inst_dt = inst_dt.replace(tzinfo=timezone.utc)
else:
inst_dt = inst_dt.astimezone(timezone.utc)
if abs((inst_dt - original_dt).total_seconds()) < 60: # Within 1 minute
instance_found = True
break
if not instance_found:
raise EventNotFoundError(event_id)
# Create virtual instance with attendees inherited from master
return _create_virtual_instance(master, original_dt, event_id, master.attendees)
def list_events(
session: Session,
calendar_id: str,
user_id: str,
max_results: int = 250,
page_token: Optional[str] = None,
time_min: Optional[str] = None,
time_max: Optional[str] = None,
updated_min: Optional[str] = None,
single_events: bool = False,
order_by: Optional[str] = None,
q: Optional[str] = None,
show_deleted: bool = False,
sync_token: Optional[str] = None,
ical_uid: Optional[str] = None,
) -> tuple[list[Event], Optional[str], Optional[str]]:
"""
List events from a calendar.
Returns: (events, next_page_token, next_sync_token)
"""
calendar = get_calendar(session, calendar_id, user_id)
_check_calendar_access(session, calendar.id, user_id, AccessRole.reader)
# Handle sync token
if sync_token:
token_record = session.execute(
select(SyncToken).where(
and_(
SyncToken.token == sync_token,
SyncToken.user_id == user_id,
SyncToken.resource_type == "events",
SyncToken.resource_id == calendar.id,
)
)
).scalar_one_or_none()
if token_record is None or token_record.expires_at < calendar_now():
raise SyncTokenExpiredError()
query = select(Event).where(
and_(
Event.calendar_id == calendar.id,
Event.updated_at > token_record.snapshot_time,
)
)
else:
query = select(Event).where(Event.calendar_id == calendar.id)
# Apply filters
if not show_deleted:
query = query.where(Event.status != EventStatus.cancelled)
if time_min:
from ..core.utils import parse_rfc3339
min_dt = parse_rfc3339(time_min)
query = query.where(
or_(
Event.end_datetime >= min_dt,
Event.end_date >= min_dt.strftime("%Y-%m-%d"),
)
)
if time_max:
from ..core.utils import parse_rfc3339
max_dt = parse_rfc3339(time_max)
query = query.where(
or_(
Event.start_datetime < max_dt,
Event.start_date < max_dt.strftime("%Y-%m-%d"),
)
)
if updated_min:
from ..core.utils import parse_rfc3339
upd_dt = parse_rfc3339(updated_min)
query = query.where(Event.updated_at >= upd_dt)
if ical_uid:
query = query.where(Event.ical_uid == ical_uid)
if q:
# Simple text search in summary, description, location
search_pattern = f"%{q}%"
query = query.where(
or_(
Event.summary.ilike(search_pattern),
Event.description.ilike(search_pattern),
Event.location.ilike(search_pattern),
)
)
# Handle single_events: when true, expand recurring events into instances
# instead of returning master events
recurring_masters = []
if single_events:
# Derive recurring_query from the already-filtered query so it inherits
# all filters (q, updated_min, ical_uid, time bounds, etc.)
# Add the recurrence predicate to get only recurring masters
recurring_query = query.where(Event.recurrence != None) # noqa: E711
recurring_masters = list(session.execute(recurring_query).scalars().all())
# Exclude recurring masters from main query (we'll merge expanded instances)
query = query.where(Event.recurrence == None) # noqa: E711
# Apply ordering
if order_by == "startTime":
query = query.order_by(Event.start_datetime.asc(), Event.id.asc())
elif order_by == "updated":
query = query.order_by(Event.updated_at.desc(), Event.id.asc())
else:
query = query.order_by(Event.start_datetime.asc(), Event.id.asc())
# For single_events with recurring masters, we need different pagination handling
if single_events and recurring_masters:
from ..core.utils import expand_recurrence, format_rfc3339, parse_rfc3339
from datetime import timedelta
# Parse page_token offset BEFORE expansion so we know how many instances to generate
offset = 0
if page_token:
offset, _ = PageToken.decode(page_token)
# Calculate how many instances we need: offset + max_results + 1 (for next page check)
instances_needed = offset + max_results + 1
# Get all non-recurring events first (no pagination yet)
all_events = list(session.execute(query).scalars().all())
# Determine time bounds for expansion
now = calendar_now()
min_dt = parse_rfc3339(time_min) if time_min else now - timedelta(days=30)
max_dt = parse_rfc3339(time_max) if time_max else now + timedelta(days=365)
# Ensure timezone-aware
if min_dt.tzinfo is None:
min_dt = min_dt.replace(tzinfo=timezone.utc)
if max_dt.tzinfo is None:
max_dt = max_dt.replace(tzinfo=timezone.utc)
# Expand each recurring master into instances
for master in recurring_masters:
if not master.start_datetime or not master.recurrence:
continue
start_dt = master.start_datetime
if start_dt.tzinfo is None:
start_dt = start_dt.replace(tzinfo=timezone.utc)
# Calculate duration
duration = timedelta(hours=1)
if master.end_datetime and master.start_datetime:
duration = master.end_datetime - master.start_datetime
# Get all exceptions for this master event
exceptions_query = select(Event).where(
Event.recurring_event_id == master.id
)
exceptions = list(session.execute(exceptions_query).scalars().all())
# Build a set of exception original start times (for excluding from virtual instances)
exception_times: set[str] = set()
for exc in exceptions:
if exc.original_start_time and exc.original_start_time.get("dateTime"):
# Store the time string for comparison
exc_dt = parse_rfc3339(exc.original_start_time["dateTime"])
if exc_dt.tzinfo is None:
exc_dt = exc_dt.replace(tzinfo=timezone.utc)
exception_times.add(exc_dt.strftime('%Y%m%dT%H%M%SZ'))
# Add exception events to results (modified or cancelled if show_deleted)
for exc in exceptions:
if exc.status == EventStatus.cancelled and not show_deleted:
continue
# Check if exception is in time range
if exc.start_datetime:
exc_start = exc.start_datetime
if exc_start.tzinfo is None:
exc_start = exc_start.replace(tzinfo=timezone.utc)
if exc_start >= min_dt and exc_start < max_dt:
all_events.append(exc)
try:
instance_dates = expand_recurrence(
recurrence=master.recurrence,
start=start_dt,
time_min=min_dt,
time_max=max_dt,
max_instances=instances_needed, # Expand enough for pagination
)
except Exception as e:
# Log and skip if recurrence expansion fails
# Keep broad exception to maintain graceful degradation (matching Google's behavior)
logger.warning(
"Failed to expand recurrence for event %s: %s", master.id, e
)
continue
# Get master's attendees for copying to virtual instances
master_attendees = master.attendees
# Create instance objects (excluding those with exceptions)
for inst_start in instance_dates:
# Normalize inst_start to UTC
if inst_start.tzinfo is None:
inst_start = inst_start.replace(tzinfo=timezone.utc)
# Skip if there's an exception for this instance
inst_time_str = inst_start.strftime('%Y%m%dT%H%M%SZ')
if inst_time_str in exception_times:
continue
inst_end = inst_start + duration
instance_id = f"{master.id}_{inst_time_str}"
instance = Event(
id=instance_id,
calendar_id=master.calendar_id,
ical_uid=master.ical_uid,
summary=master.summary,
description=master.description,
location=master.location,
color_id=master.color_id,
status=master.status,
visibility=master.visibility,
transparency=master.transparency,
creator_email=master.creator_email,
creator_display_name=master.creator_display_name,
creator_profile_id=master.creator_profile_id,
creator_self=master.creator_self,