gcal-sync 9.2.0__tar.gz → 9.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/PKG-INFO +1 -1
  2. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/api.py +144 -39
  3. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/auth.py +18 -8
  4. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/model.py +3 -4
  5. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/sync.py +39 -2
  6. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync.egg-info/PKG-INFO +1 -1
  7. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/pyproject.toml +5 -1
  8. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/tests/test_api.py +532 -1
  9. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/tests/test_auth.py +57 -0
  10. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/tests/test_sync.py +221 -0
  11. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/LICENSE +0 -0
  12. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/README.md +0 -0
  13. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/__init__.py +0 -0
  14. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/const.py +0 -0
  15. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/exceptions.py +0 -0
  16. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/py.typed +0 -0
  17. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/store.py +0 -0
  18. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync/timeline.py +0 -0
  19. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync.egg-info/SOURCES.txt +0 -0
  20. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync.egg-info/dependency_links.txt +0 -0
  21. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync.egg-info/requires.txt +0 -0
  22. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/gcal_sync.egg-info/top_level.txt +0 -0
  23. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/setup.cfg +0 -0
  24. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/tests/test_model.py +0 -0
  25. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/tests/test_store.py +0 -0
  26. {gcal_sync-9.2.0 → gcal_sync-9.2.2}/tests/test_timeline.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gcal_sync
3
- Version: 9.2.0
3
+ Version: 9.2.2
4
4
  Summary: A python library for syncing Google Calendar to local storage
5
5
  Author-email: Allen Porter <allen.porter@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -435,8 +435,7 @@ class GoogleCalendarService:
435
435
  body: dict[str, Any],
436
436
  ) -> None:
437
437
  """Updates an event using patch semantics, with raw API data."""
438
- await self._auth.request(
439
- "patch",
438
+ await self._auth.patch(
440
439
  CALENDAR_EVENT_ID_URL.format(
441
440
  calendar_id=pathname2url(calendar_id), event_id=pathname2url(event_id)
442
441
  ),
@@ -449,8 +448,7 @@ class GoogleCalendarService:
449
448
  event_id: str,
450
449
  ) -> None:
451
450
  """Delete an event on the specified calendar."""
452
- await self._auth.request(
453
- "delete",
451
+ await self._auth.delete(
454
452
  CALENDAR_EVENT_ID_URL.format(
455
453
  calendar_id=pathname2url(calendar_id), event_id=pathname2url(event_id)
456
454
  ),
@@ -522,6 +520,39 @@ class Range(str, enum.Enum):
522
520
  """The range of the recurrence identifier and all subsequent values."""
523
521
 
524
522
 
523
+ def _lookup_event_id(events_data: dict[str, Any], event_id: str) -> Event | None:
524
+ """Find the event with the specified id in the store, ignoring cancelled events."""
525
+ if not (data := events_data.get(event_id)) or (
526
+ data.get("status") == EventStatusEnum.CANCELLED
527
+ ):
528
+ return None
529
+ return Event(**data)
530
+
531
+
532
+ def _lookup_primary_event(events_data: dict[str, Any], ical_uuid: str) -> Event | None:
533
+ """Find the event with the iCalUID in the store, ignoring cancelled events.
534
+
535
+ Modified instances of a recurring event share the iCalUID of the recurring
536
+ event, so they are skipped and only the primary event itself is returned.
537
+ """
538
+ for data in events_data.values():
539
+ if (
540
+ data.get("ical_uuid") == ical_uuid
541
+ and not data.get("recurring_event_id")
542
+ and data.get("status") != EventStatusEnum.CANCELLED
543
+ ):
544
+ return Event(**data)
545
+ return None
546
+
547
+
548
+ def _validate_ical_uuid(event: Event, ical_uuid: str, event_id: str) -> None:
549
+ """Raise if the stored event does not belong to the iCalUID."""
550
+ if event.ical_uuid != ical_uuid:
551
+ raise ValueError(
552
+ f"Mismatched ids ical_uuid={ical_uuid} and event_id={event_id}"
553
+ )
554
+
555
+
525
556
  class CalendarEventStoreService:
526
557
  """Performs event lookups from the local store.
527
558
 
@@ -611,31 +642,21 @@ class CalendarEventStoreService:
611
642
  commands to send to the calendar API, so it may be operating on stale data.
612
643
  You should sync the event store after performing a delete operation to
613
644
  ensure the store reflects the latest information from the server
614
- """
615
- event = await self._lookup_ical_uuid(ical_uuid)
616
- if not event or not event.id:
617
- raise ValueError(f"Event does not exist: {ical_uuid} or malformed")
618
-
619
- if (
620
- event_id
621
- and recurrence_range == Range.THIS_AND_FUTURE
622
- and SyntheticEventId.parse(event_id).dtstart == event.start.value
623
- ):
624
- # Editing the first instance and all forward is the same as deleting
625
- # the entire series so don't bother forking a new event
626
- event_id = None
627
645
 
628
- if not event_id or not event.recurrence:
646
+ A `ValueError` is raised when the targeted event is not in the local store,
647
+ including when only modified instances of a recurring event are stored but
648
+ not the recurring event itself (except for deleting such an instance with
649
+ `Range.NONE`), when the `event_id` refers to an event or instance that was
650
+ already cancelled, or when the `event_id` does not belong to the `ical_uuid`.
651
+ """
652
+ event, primary_event_id, synthetic_event_id = await self._async_resolve_event(
653
+ ical_uuid, event_id, recurrence_range
654
+ )
655
+ if not event_id or synthetic_event_id is None:
629
656
  # Deleting a single event or entire series of a recurring event
630
- await self._api.async_delete_event(self._calendar_id, event.id)
657
+ await self._api.async_delete_event(self._calendar_id, primary_event_id)
631
658
  return
632
659
 
633
- synthetic_event_id = SyntheticEventId.parse(event_id)
634
- if synthetic_event_id.original_event_id != event.id:
635
- raise ValueError(
636
- f"Mismatched ids ical_uuid={ical_uuid} and event_id={event_id}"
637
- )
638
-
639
660
  if recurrence_range == Range.NONE:
640
661
  # A single recurrence instance is removed, marked as cancelled
641
662
  cancelled_event = Event(
@@ -652,23 +673,115 @@ class CalendarEventStoreService:
652
673
  await self._api.async_patch_event(self._calendar_id, event_id, body)
653
674
  return
654
675
 
676
+ await self._async_truncate_series(event, primary_event_id, synthetic_event_id)
677
+
678
+ async def _async_resolve_event(
679
+ self,
680
+ ical_uuid: str,
681
+ event_id: str | None,
682
+ recurrence_range: Range,
683
+ ) -> tuple[Event, str, SyntheticEventId | None]:
684
+ """Resolve the stored event targeted by a mutation.
685
+
686
+ Returns the stored event, its primary event id, and the parsed instance id
687
+ when the mutation targets instances of a recurring event. The instance id
688
+ is None when the mutation applies to a single event or an entire series.
689
+
690
+ Modified instances of a recurring event share the iCalUID of the recurring
691
+ event, so an `event_id` is resolved by id and the `ical_uuid` is only used
692
+ to validate it. Cancelled events in the store are ignored, and targeting a
693
+ cancelled event or instance by its `event_id` raises a `ValueError`.
694
+ """
695
+ if not ical_uuid:
696
+ raise ValueError("Event does not exist: ical_uuid is required")
697
+ events_data = await self._lookup_events_data()
698
+ if not event_id:
699
+ if (
700
+ not (event := _lookup_primary_event(events_data, ical_uuid))
701
+ or not event.id
702
+ ):
703
+ raise ValueError(f"Event does not exist: {ical_uuid} or malformed")
704
+ return event, event.id, None
705
+
706
+ if (data := events_data.get(event_id)) and (
707
+ data.get("status") == EventStatusEnum.CANCELLED
708
+ ):
709
+ raise ValueError(f"Event does not exist: {event_id} was cancelled")
710
+
711
+ synthetic_event_id: SyntheticEventId | None = None
712
+ if event := _lookup_event_id(events_data, event_id):
713
+ _validate_ical_uuid(event, ical_uuid, event_id)
714
+ if event.recurring_event_id:
715
+ # A modified instance of a recurring event. Its id is assigned by
716
+ # the calendar API and is not necessarily a synthetic event id,
717
+ # e.g. for events with a floating time.
718
+ if event.original_start_time:
719
+ synthetic_event_id = SyntheticEventId.of(
720
+ event.recurring_event_id, event.original_start_time.value
721
+ )
722
+ elif SyntheticEventId.is_valid(event_id):
723
+ synthetic_event_id = SyntheticEventId.parse(event_id)
724
+ else:
725
+ raise ValueError(f"Event does not exist: {event_id} or malformed")
726
+ if recurrence_range == Range.NONE:
727
+ return event, event.recurring_event_id, synthetic_event_id
728
+ elif recurrence_range == Range.NONE and not event.recurrence:
729
+ # A single event
730
+ return event, event_id, None
731
+
732
+ # An instance of a recurring event, resolved via the recurring event
733
+ if synthetic_event_id is None:
734
+ if not SyntheticEventId.is_valid(event_id):
735
+ raise ValueError(f"Event does not exist: {event_id} or malformed")
736
+ synthetic_event_id = SyntheticEventId.parse(event_id)
737
+ primary_event_id = synthetic_event_id.original_event_id
738
+ event = _lookup_event_id(events_data, primary_event_id)
739
+ if not event or not event.recurrence:
740
+ raise ValueError(
741
+ f"Event does not exist: recurring event {primary_event_id} of "
742
+ f"{event_id} is not in the store"
743
+ )
744
+ _validate_ical_uuid(event, ical_uuid, event_id)
745
+
746
+ if (
747
+ recurrence_range == Range.THIS_AND_FUTURE
748
+ and synthetic_event_id.dtstart == event.start.value
749
+ ):
750
+ # Editing the first instance and all forward is the same as editing
751
+ # the entire series so don't bother forking a new event
752
+ return event, primary_event_id, None
753
+ return event, primary_event_id, synthetic_event_id
754
+
755
+ async def _async_truncate_series(
756
+ self,
757
+ event: Event,
758
+ primary_event_id: str,
759
+ synthetic_event_id: SyntheticEventId,
760
+ ) -> None:
761
+ """End a recurring series before the specified instance."""
655
762
  # Assumes any recurrence deletion is valid, and that overwriting
656
763
  # the "until" value will not produce more instances.
657
764
  if not (recur := event.recur):
658
765
  raise ValueError(f"Unable to update RRULE, does not conform: {recur}")
659
766
 
660
- if len(recur.rrule) > 1:
661
- raise ValueError(f"Can't update event with multiple RRULE: {recur.rrule}")
767
+ if len(recur.rrule) != 1:
768
+ raise ValueError(
769
+ f"Can't update event without exactly one RRULE: {recur.rrule}"
770
+ )
662
771
 
663
772
  # Stop recurring events before the specified date. This assumes that
664
773
  # setting the "until" field won't create more instances by changing count.
665
774
  # UNTIL is inclusive so it can't include the specified exdate. FREQ=DAILY
666
775
  # is the lowest frequency supported so subtracting one day is
667
- # safe and works for both dates and datetimes.
776
+ # safe and works for both dates and datetimes. An UNTIL with a time zone
777
+ # must be specified in UTC.
778
+ until = synthetic_event_id.dtstart - datetime.timedelta(days=1)
779
+ if isinstance(until, datetime.datetime) and until.tzinfo is not None:
780
+ until = until.astimezone(datetime.UTC)
668
781
  recur.rrule[0].count = None
669
- recur.rrule[0].until = synthetic_event_id.dtstart - datetime.timedelta(days=1)
782
+ recur.rrule[0].until = until
670
783
  updated_event = Event(
671
- id=event.id, # Primary event
784
+ id=primary_event_id, # Primary event
672
785
  recurrence=recur.as_recurrence(),
673
786
  start=event.start,
674
787
  end=event.end,
@@ -678,18 +791,10 @@ class CalendarEventStoreService:
678
791
  )
679
792
  del body["start"]
680
793
  del body["end"]
681
- await self._api.async_patch_event(self._calendar_id, event.id, body)
794
+ await self._api.async_patch_event(self._calendar_id, primary_event_id, body)
682
795
 
683
796
  async def _lookup_events_data(self) -> dict[str, Any]:
684
797
  """Loookup the raw events storage dictionary."""
685
798
  store_data = await self._store.async_load() or {}
686
799
  store_data.setdefault(ITEMS, {})
687
800
  return store_data.get(ITEMS, {}) # type: ignore[no-any-return]
688
-
689
- async def _lookup_ical_uuid(self, ical_uuid: str) -> Event | None:
690
- """Find the specified event by id in the local store."""
691
- events_data = await self._lookup_events_data()
692
- for data in events_data.values():
693
- if (event_uuid := data.get("ical_uuid")) and event_uuid == ical_uuid:
694
- return Event(**data)
695
- return None
@@ -86,14 +86,20 @@ class AbstractAuth(ABC): # pylint: disable=too-few-public-methods
86
86
  _LOGGER.debug("request[post json]=%s", kwargs["json"])
87
87
  return await self._websession.request(method, url, **kwargs, headers=headers)
88
88
 
89
- async def get(self, url: str, **kwargs: Any) -> aiohttp.ClientResponse:
90
- """Make a get request."""
89
+ async def _checked_request(
90
+ self, method: str, url: str, **kwargs: Any
91
+ ) -> aiohttp.ClientResponse:
92
+ """Make a request and raise an ApiException on failure."""
91
93
  try:
92
- resp = await self.request("get", url, **kwargs)
94
+ resp = await self.request(method, url, **kwargs)
93
95
  except ClientError as err:
94
96
  raise ApiException(f"Error connecting to API: {err}") from err
95
97
  return await AbstractAuth._raise_for_status(resp)
96
98
 
99
+ async def get(self, url: str, **kwargs: Any) -> aiohttp.ClientResponse:
100
+ """Make a get request."""
101
+ return await self._checked_request("get", url, **kwargs)
102
+
97
103
  async def get_json(self, url: str, **kwargs: Any) -> dict[str, Any]:
98
104
  """Make a get request and return json response."""
99
105
  resp = await self.get(url, **kwargs)
@@ -108,11 +114,7 @@ class AbstractAuth(ABC): # pylint: disable=too-few-public-methods
108
114
 
109
115
  async def post(self, url: str, **kwargs: Any) -> aiohttp.ClientResponse:
110
116
  """Make a post request."""
111
- try:
112
- resp = await self.request("post", url, **kwargs)
113
- except ClientError as err:
114
- raise ApiException(f"Error connecting to API: {err}") from err
115
- return await AbstractAuth._raise_for_status(resp)
117
+ return await self._checked_request("post", url, **kwargs)
116
118
 
117
119
  async def post_json(self, url: str, **kwargs: Any) -> dict[str, Any]:
118
120
  """Make a post request and return a json response."""
@@ -126,6 +128,14 @@ class AbstractAuth(ABC): # pylint: disable=too-few-public-methods
126
128
  _LOGGER.debug("response=%s", result)
127
129
  return result
128
130
 
131
+ async def patch(self, url: str, **kwargs: Any) -> aiohttp.ClientResponse:
132
+ """Make a patch request."""
133
+ return await self._checked_request("patch", url, **kwargs)
134
+
135
+ async def delete(self, url: str, **kwargs: Any) -> aiohttp.ClientResponse:
136
+ """Make a delete request."""
137
+ return await self._checked_request("delete", url, **kwargs)
138
+
129
139
  @staticmethod
130
140
  async def _raise_for_status(resp: aiohttp.ClientResponse) -> aiohttp.ClientResponse:
131
141
  """Raise exceptions on failure methods."""
@@ -896,10 +896,9 @@ class Event(CalendarBaseModel):
896
896
  ):
897
897
  # Date should be floating
898
898
  return date_value.replace(tzinfo=None)
899
- elif dtstart.date:
900
- if isinstance(date_value, datetime.datetime):
901
- # UNTIL is a DATE-TIME but must be a DATE
902
- return date_value.date()
899
+ elif dtstart.date and isinstance(date_value, datetime.datetime):
900
+ # UNTIL is a DATE-TIME but must be a DATE
901
+ return date_value.date()
903
902
  return date_value
904
903
 
905
904
  @model_validator(mode="before")
@@ -13,7 +13,6 @@ may then query the latest information from the local store service.
13
13
  from __future__ import annotations
14
14
 
15
15
  import datetime
16
- import json
17
16
  import logging
18
17
  from collections.abc import Awaitable, Callable
19
18
  from typing import Any
@@ -32,6 +31,7 @@ from .api import (
32
31
  )
33
32
  from .const import CALENDAR_LIST_SYNC, EVENT_SYNC, ITEMS, SYNC_TOKEN, SYNC_TOKEN_VERSION
34
33
  from .exceptions import InvalidSyncTokenException
34
+ from .model import Event, EventStatusEnum
35
35
  from .store import CalendarStore, InMemoryCalendarStore, ScopedCalendarStore
36
36
 
37
37
  _LOGGER = logging.getLogger(__name__)
@@ -49,10 +49,46 @@ def _items_func(
49
49
  for item in result.items:
50
50
  if not item.id:
51
51
  continue
52
- items[item.id] = json.loads(item.model_dump_json())
52
+ if isinstance(item, Event) and item.status == EventStatusEnum.CANCELLED:
53
+ # Convert to a minimal tombstone, stripping event content (summary,
54
+ # description, attendees, etc.). Deleted non-recurring tombstones are
55
+ # pruned after all pages complete; recurring exception tombstones are
56
+ # kept only while their parent recurring event remains active.
57
+ items[item.id] = item.model_dump(
58
+ mode="json",
59
+ include={"id", "status", "recurring_event_id", "original_start_time"},
60
+ exclude_none=True,
61
+ )
62
+ else:
63
+ items[item.id] = item.model_dump(mode="json", exclude_none=True)
53
64
  return items
54
65
 
55
66
 
67
+ def _prune_cancelled_events(stored_items: dict[str, Any]) -> None:
68
+ """Remove cancelled events and orphaned recurring exceptions from the store.
69
+
70
+ Cancelled exceptions of an active recurring event (those with both
71
+ `recurring_event_id` and `original_start_time`) must be retained for the
72
+ lifetime of the parent recurring event so timeline expansion can exclude
73
+ those cancelled occurrences from the parent's recurrence rule. All other
74
+ cancelled events and any children of a cancelled recurring master are
75
+ removed.
76
+ """
77
+ to_delete: list[str] = []
78
+ for item_id, data in stored_items.items():
79
+ parent_id = data.get("recurring_event_id")
80
+ parent = stored_items.get(parent_id) if parent_id else None
81
+ if (
82
+ parent is not None and parent.get("status") == EventStatusEnum.CANCELLED
83
+ ) or (
84
+ data.get("status") == EventStatusEnum.CANCELLED
85
+ and not (parent is not None and data.get("original_start_time"))
86
+ ):
87
+ to_delete.append(item_id)
88
+ for item_id in to_delete:
89
+ del stored_items[item_id]
90
+
91
+
56
92
  async def _run_sync[T: SyncableRequest, S: SyncableResponse](
57
93
  store_data: dict[str, Any],
58
94
  new_request: Callable[[str | None], T],
@@ -208,4 +244,5 @@ class CalendarEventSyncManager:
208
244
  store_data = await _run_sync(
209
245
  store_data, new_request, self._api.async_list_events_page, _items_func
210
246
  )
247
+ _prune_cancelled_events(store_data[ITEMS])
211
248
  await self._store.async_save(store_data)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gcal_sync
3
- Version: 9.2.0
3
+ Version: 9.2.2
4
4
  Summary: A python library for syncing Google Calendar to local storage
5
5
  Author-email: Allen Porter <allen.porter@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -4,7 +4,7 @@ requires = ["setuptools>=77.0"]
4
4
 
5
5
  [project]
6
6
  name = "gcal_sync"
7
- version = "9.2.0"
7
+ version = "9.2.2"
8
8
  license = "Apache-2.0"
9
9
  license-files = ["LICENSE"]
10
10
  description = "A python library for syncing Google Calendar to local storage"
@@ -69,3 +69,7 @@ warn_untyped_fields = true
69
69
 
70
70
  [tool.ty.src]
71
71
  exclude = ["tests", "examples"]
72
+
73
+ [tool.coverage.run]
74
+ core = "sysmon"
75
+ disable_warnings = ["no-sysmon"]