-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
recurring_ical_events.py
1470 lines (1248 loc) · 54.2 KB
/
recurring_ical_events.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
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Calculate repetitions of icalendar components."""
from __future__ import annotations
import contextlib
import datetime
import re
import sys
from abc import ABC, abstractmethod
from collections import defaultdict
from functools import wraps
from typing import TYPE_CHECKING, Callable, Generator, Optional, Sequence, Union
import x_wr_timezone
from dateutil.rrule import rruleset, rrulestr
from icalendar.cal import Component
from icalendar.prop import vDDDTypes
if TYPE_CHECKING:
from icalendar.cal import Component
Time = Union[datetime.date, datetime.datetime]
DateArgument = tuple[int] | Time | str | int
from dateutil.rrule import rrule
UID = str
ComponentID = tuple[str, UID, Time]
Timestamp = float
RecurrenceID = datetime.datetime
RecurrenceIDs = tuple[RecurrenceID]
# The minimum value accepted as date (pytz + zoneinfo)
DATE_MIN = (1970, 1, 1)
DATE_MIN_DT = datetime.date(*DATE_MIN)
# The maximum value accepted as date (pytz + zoneinfo)
DATE_MAX = (2038, 1, 1)
DATE_MAX_DT = datetime.date(*DATE_MAX)
class InvalidCalendar(ValueError):
"""Exception thrown for bad icalendar content."""
def __init__(self, message: str):
"""Create a new error with a message."""
self._message = message
super().__init__(self.message)
@property
def message(self) -> str:
"""The error message."""
return self._message
class PeriodEndBeforeStart(InvalidCalendar):
"""An event or component starts before it ends."""
def __init__(self, message: str, start: Time, end: Time):
"""Create a new PeriodEndBeforeStart error."""
super().__init__(message)
self._start = start
self._end = end
@property
def start(self) -> Time:
"""The start of the component's period."""
return self._start
@property
def end(self) -> Time:
"""The end of the component's period."""
return self._end
class BadRuleStringFormat(InvalidCalendar):
"""An iCal rule string is badly formatted."""
def __init__(self, message: str, rule: str):
"""Create an error with a bad rule string."""
super().__init__(message + ": " + rule)
self._rule = rule
@property
def rule(self) -> str:
"""The malformed rule string"""
return self._rule
def timestamp(dt: datetime.datetime) -> Timestamp:
"""Return the time stamp of a datetime"""
return dt.timestamp()
NEGATIVE_RRULE_COUNT_REGEX = re.compile(r"COUNT=-\d+;?")
def convert_to_date(date: Time) -> datetime.date:
"""Converts a date or datetime to a date"""
return datetime.date(date.year, date.month, date.day)
def convert_to_datetime(date: Time, tzinfo: Optional[datetime.tzinfo]): # noqa: UP007
"""Converts a date to a datetime.
Dates are converted to datetimes with tzinfo.
Datetimes loose their timezone if tzinfo is None.
Datetimes receive tzinfo as a timezone if they do not have a timezone.
Datetimes retain their timezone if they have one already (tzinfo is not None).
"""
if isinstance(date, datetime.datetime):
if date.tzinfo is None:
if tzinfo is not None:
if is_pytz(tzinfo):
return tzinfo.localize(date)
return date.replace(tzinfo=tzinfo)
elif tzinfo is None:
return normalize_pytz(date).replace(tzinfo=None)
return date
if isinstance(date, datetime.date):
return datetime.datetime(date.year, date.month, date.day, tzinfo=tzinfo)
return date
def time_span_contains_event(
span_start: Time,
span_stop: Time,
event_start: Time,
event_stop: Time,
comparable: bool = False, # noqa: FBT001
):
"""Return whether an event should is included within a time span.
- span_start and span_stop define the time span
- event_start and event_stop define the event time
- comparable indicates whether the dates can be compared.
You can set it to True if you are sure you have timezones and
date/datetime correctly or used make_comparable() before.
Note that the stops are exlusive but the starts are inclusive.
This is an essential function of the module. It should be tested in
test/test_time_span_contains_event.py.
This raises a PeriodEndBeforeStart exception if a start is after an end.
"""
if not comparable:
span_start, span_stop, event_start, event_stop = make_comparable(
(span_start, span_stop, event_start, event_stop)
)
if event_start > event_stop:
raise PeriodEndBeforeStart(
(
"the event must start before it ends"
f"(start: {event_start} end: {event_stop})"
),
event_start,
event_stop,
)
if span_start > span_stop:
raise PeriodEndBeforeStart(
(
"the time span must start before it ends"
f"(start: {span_start} end: {span_stop})"
),
span_start,
span_stop,
)
if event_start == event_stop:
if span_start == span_stop:
return event_start == span_start
return span_start <= event_start < span_stop
if span_start == span_stop:
return event_start <= span_start < event_stop
return event_start < span_stop and span_start < event_stop
def make_comparable(dates: Sequence[Time]) -> list[Time]:
"""Make an list or tuple of dates comparable.
Returns an list.
"""
tzinfo = None
for date in dates:
tzinfo = getattr(date, "tzinfo", None)
if tzinfo is not None:
break
return [convert_to_datetime(date, tzinfo) for date in dates]
def compare_greater(date1: Time, date2: Time) -> bool:
"""Compare two dates if date1 > date2 and make them comparable before."""
date1, date2 = make_comparable((date1, date2))
return date1 > date2
def cmp(date1: Time, date2: Time) -> int:
"""Compare two dates, like cmp().
Returns
-------
-1 if date1 < date2
0 if date1 = date2
1 if date1 > date2
"""
# credits: https://www.geeksforgeeks.org/python-cmp-function/
# see https://stackoverflow.com/a/22490617/1320237
date1, date2 = make_comparable((date1, date2))
return (date1 > date2) - (date1 < date2)
def is_pytz(tzinfo: datetime.tzinfo | Time):
"""Whether the time zone requires localize() and normalize().
pytz requires these funtions to be used in order to correctly use the
time zones after operations.
"""
return hasattr(tzinfo, "localize")
def is_pytz_dt(time: Time):
"""Whether the time requires localize() and normalize().
pytz requires these funtions to be used in order to correctly use the
time zones after operations.
"""
return isinstance(time, datetime.datetime) and is_pytz(time.tzinfo)
def normalize_pytz(time: Time):
"""We have to normalize the time after a calculation if we use pytz."""
if is_pytz_dt(time):
return time.tzinfo.normalize(time)
return time
def cached_property(func: Callable):
"""Cache the property value for speed up."""
name = f"_cached_{func.__name__}"
not_found = object()
@property
@wraps(func)
def cached_property(self: object):
value = self.__dict__.get(name, not_found)
if value is not_found:
self.__dict__[name] = value = func(self)
return value
return cached_property
def to_recurrence_ids(time: Time) -> RecurrenceIDs:
"""Convert the time to a recurrence id so it can be hashed and recognized.
The first value should be used to identify a component as it is a datetime in UTC.
The other values can be used to look the component up.
"""
# We are inside the Series calculation with this and want to identify
# a date. It is fair to assume that the timezones are the same now.
if not isinstance(time, datetime.datetime):
return (convert_to_datetime(time, None),)
if time.tzinfo is None:
return (time,)
return (
time.astimezone(datetime.timezone.utc).replace(tzinfo=None),
time.replace(tzinfo=None),
)
def is_date(time: Time):
"""Whether this is a date and not a datetime."""
return isinstance(time, datetime.date) and not isinstance(time, datetime.datetime)
def with_highest_sequence(
adapter1: ComponentAdapter | None, adapter2: ComponentAdapter | None
):
"""Return the one with the highest sequence."""
return max(
adapter1,
adapter2,
key=lambda adapter: -1e10 if adapter is None else adapter.sequence,
)
def get_any(dictionary: dict, keys: Sequence[object], default: object = None):
"""Get any item from the keys and return it."""
result = default
for key in keys:
result = dictionary.get(key, result)
return result
class Series:
"""Base class for components that result in a series of occurrences."""
@property
def occurrence(self) -> type[Occurrence]:
"""A way to override the occurrence class."""
return Occurrence
class NoRecurrence:
"""A strategy to deal with not having a core with rrules."""
check_exdates_datetime: set[RecurrenceID] = set()
check_exdates_date: set[datetime.date] = set()
replace_ends: dict[RecurrenceID, Time] = {}
def as_occurrence(
self,
start: Time,
stop: Time,
occurrence: type[Occurrence],
core: ComponentAdapter,
) -> Occurrence:
raise NotImplementedError("This code should never be reached.")
@property
def core(self) -> ComponentAdapter:
raise NotImplementedError("This code should never be reached.")
def rrule_between(
self,
span_start: Time, # noqa: ARG002
span_stop: Time, # noqa: ARG002
) -> Generator[Time, None, None]:
"""No repetition."""
yield from []
has_core = False
extend_query_span_by = (datetime.timedelta(0), datetime.timedelta(0))
class RecurrenceRules:
"""A strategy if we have an actual core with recurrences."""
has_core = True
def __init__(self, core: ComponentAdapter):
self.core = core
# Setup complete. We create the attribtues
self.start = self.original_start = self.core.start
self.end = self.original_end = self.core.end
self.exdates: set[Time] = set()
self.check_exdates_datetime: set[RecurrenceID] = set() # should be in UTC
self.check_exdates_date: set[datetime.date] = set() # should be in UTC
self.rdates: set[Time] = set()
self.replace_ends: dict[
RecurrenceID, datetime.timedelta
] = {} # for periods, in UTC
# fill the attributes
for exdate in self.core.exdates:
self.exdates.add(exdate)
self.check_exdates_datetime.update(to_recurrence_ids(exdate))
if is_date(exdate):
self.check_exdates_date.add(exdate)
for rdate in self.core.rdates:
if isinstance(rdate, tuple):
# we have a period as rdate
self.rdates.add(rdate[0])
for recurrence_id in to_recurrence_ids(rdate[0]):
self.replace_ends[recurrence_id] = (
rdate[1]
if isinstance(rdate[1], datetime.timedelta)
else rdate[1] - rdate[0]
)
else:
# we have a date/datetime
self.rdates.add(rdate)
# We make sure that all dates and times mentioned here are either:
# - a date
# - a datetime with None is tzinfo
# - a datetime with a timezone
self.make_all_dates_comparable()
# Calculate the rules with the same timezones
rule_set = rruleset(cache=True)
rule_set.until = None
self.rrules = [rule_set]
last_until: Time | None = None
for rrule_string in self.core.rrules:
rule = self.create_rule_with_start(rrule_string)
self.rrules.append(rule)
if rule.until and (
not last_until or compare_greater(rule.until, last_until)
):
last_until = rule.until
for exdate in self.exdates:
self.check_exdates_datetime.add(exdate)
for rdate in self.rdates:
rule_set.rdate(rdate)
if not last_until or not compare_greater(self.start, last_until):
rule_set.rdate(self.start)
@property
def extend_query_span_by(self) -> tuple[datetime.timedelta, datetime.timedelta]:
"""The extension of the time span we need for this component's core."""
return self.core.extend_query_span_by
def create_rule_with_start(self, rule_string) -> rrule:
"""Helper to create an rrule from a rule_string
The rrule is starting at the start of the component.
Since the creation is a bit more complex,
this function handles special cases.
"""
try:
return self.rrulestr(rule_string)
except ValueError:
# string: FREQ=WEEKLY;UNTIL=20191023;BYDAY=TH;WKST=SU
# start: 2019-08-01 14:00:00+01:00
# ValueError: RRULE UNTIL values must be specified in UTC
# when DTSTART is timezone-aware
rule_list = rule_string.split(";UNTIL=")
if len(rule_list) != 2:
raise BadRuleStringFormat(
"UNTIL parameter is missing", rule_string
) from None
date_end_index = rule_list[1].find(";")
if date_end_index == -1:
date_end_index = len(rule_list[1])
until_string = rule_list[1][:date_end_index]
if self.is_all_dates:
until_string = until_string[:8]
elif self.tzinfo is None:
# remove the Z from the time zone
until_string = until_string[:-1]
else:
# we assume the start is timezone aware but the until value
# is not, see the comment above
if len(until_string) == 8:
until_string += "T000000"
if len(until_string) != 15:
raise BadRuleStringFormat(
"UNTIL parameter has a bad format", rule_string
) from None
until_string += "Z" # https://stackoverflow.com/a/49991809
new_rule_string = (
rule_list[0]
+ rule_list[1][date_end_index:]
+ ";UNTIL="
+ until_string
)
return self.rrulestr(new_rule_string)
def rrulestr(self, rule_string) -> rrule:
"""Return an rrulestr with a start. This might fail."""
rule_string = NEGATIVE_RRULE_COUNT_REGEX.sub("", rule_string) # Issue 128
rule = rrulestr(rule_string, dtstart=self.start, cache=True)
rule.string = rule_string
rule.until = until = self._get_rrule_until(rule)
if is_pytz(self.start.tzinfo) and rule.until:
# when starting in a time zone that is one hour off to the end,
# we might miss the last occurrence
# see issue 107 and test/test_issue_107_omitting_last_event.py
rule = rule.replace(until=rule.until + datetime.timedelta(hours=1))
rule.until = until
return rule
def _get_rrule_until(self, rrule) -> None | Time:
"""Return the UNTIL datetime of the rrule or None if absent."""
rule_list = rrule.string.split(";UNTIL=")
if len(rule_list) == 1:
return None
if len(rule_list) != 2:
raise BadRuleStringFormat("There should be only one UNTIL", rrule)
date_end_index = rule_list[1].find(";")
if date_end_index == -1:
date_end_index = len(rule_list[1])
until_string = rule_list[1][:date_end_index]
return vDDDTypes.from_ical(until_string)
def make_all_dates_comparable(self):
"""Make sure we can use all dates with eachother.
Dates may be mixed and we have many of them.
- date
- datetime without timezone
- datetime with timezone
These three are not comparable but can be converted.
"""
self.tzinfo = None
dates = [self.start, self.end, *self.exdates, *self.rdates]
self.is_all_dates = not any(
isinstance(date, datetime.datetime) for date in dates
)
for date in dates:
if isinstance(date, datetime.datetime) and date.tzinfo is not None:
self.tzinfo = date.tzinfo
break
self.start = convert_to_datetime(self.start, self.tzinfo)
self.end = convert_to_datetime(self.end, self.tzinfo)
self.rdates = {
convert_to_datetime(rdate, self.tzinfo) for rdate in self.rdates
}
self.exdates = {
convert_to_datetime(exdate, self.tzinfo) for exdate in self.exdates
}
def rrule_between(self, span_start: Time, span_stop: Time) -> Generator[Time]:
"""Recalculate the rrules so that minor mistakes are corrected."""
# make dates comparable, rrule converts them to datetimes
span_start_dt = convert_to_datetime(span_start, self.tzinfo)
span_stop_dt = convert_to_datetime(span_stop, self.tzinfo)
# we have to account for pytz timezones not being properly calculated
# at the timezone changes. This is a heuristic:
# most changes are only 1 hour.
# This will still create problems at the fringes of
# timezone definition changes.
if is_pytz(self.tzinfo):
span_start_dt = normalize_pytz(
span_start_dt - datetime.timedelta(hours=1)
)
span_stop_dt = normalize_pytz(
span_stop_dt + datetime.timedelta(hours=1)
)
for rule in self.rrules:
for start in rule.between(span_start_dt, span_stop_dt, inc=True):
if is_pytz_dt(start):
# update the time zone in case of summer/winter time change
start = start.tzinfo.localize(start.replace(tzinfo=None)) # noqa: PLW2901
# We could now well be out of bounce of the end of the UNTIL
# value. This is tested by test/test_issue_20_exdate_ignored.py.
if rule.until is None or not compare_greater(start, rule.until):
yield start
def convert_to_original_type(self, date):
"""Convert a date back if this is possible.
Dates may get converted to datetimes to make calculations possible.
This reverts the process where possible so that Repetitions end
up with the type (date/datetime) that was specified in the icalendar
component.
"""
if not isinstance(
self.original_start, datetime.datetime
) and not isinstance(
self.original_end,
datetime.datetime,
):
return convert_to_date(date)
return date
def as_occurrence(
self,
start: Time,
stop: Time,
occurrence: type[Occurrence],
core: ComponentAdapter,
) -> Occurrence:
"""Return this as an occurrence at a specific time."""
return occurrence(
core,
self.convert_to_original_type(start),
self.convert_to_original_type(stop),
)
def __init__(self, components: Sequence[ComponentAdapter]):
"""Create an component which may have repetitions in it."""
if len(components) == 0:
raise ValueError("No components given to calculate a series.")
# We identify recurrences with a timestamp as all recurrence values
# should be the same in UTC either way and we want to omit
# inequality because of timezone implementation mismatches.
self.recurrence_id_to_modification: dict[
RecurrenceID, ComponentAdapter
] = {} # RECURRENCE-ID -> adapter
self.this_and_future = []
self._uid = components[0].uid
core: ComponentAdapter | None = None
for component in components:
if component.is_modification():
recurrence_ids = component.recurrence_ids
for recurrence_id in recurrence_ids:
self.recurrence_id_to_modification[recurrence_id] = (
with_highest_sequence(
self.recurrence_id_to_modification.get(recurrence_id),
component,
)
)
if component.this_and_future:
self.this_and_future.append(recurrence_ids[0])
else:
core = with_highest_sequence(core, component)
self.modifications: set[ComponentAdapter] = set(
self.recurrence_id_to_modification.values()
)
del component
self.recurrence = (
self.NoRecurrence() if core is None else self.RecurrenceRules(core)
)
self.this_and_future.sort()
self.compute_span_extension()
def compute_span_extension(self):
"""Compute how much to extend the span for the rrule to cover all events."""
self._subtract_from_start, self._add_to_stop = (
self.recurrence.extend_query_span_by
)
for adapter in self.this_and_future_components:
subtract_from_start, add_to_stop = adapter.extend_query_span_by
self._subtract_from_start = max(
subtract_from_start, self._subtract_from_start
)
self._add_to_stop = max(add_to_stop, self._add_to_stop)
@property
def this_and_future_components(self) -> Generator[ComponentAdapter]:
"""All components that influence future events."""
if self.recurrence.has_core:
yield self.recurrence.core
for recurrence_id in self.this_and_future:
yield self.recurrence_id_to_modification[recurrence_id]
def get_component_for_recurrence_id(
self, recurrence_id: RecurrenceID
) -> ComponentAdapter:
"""Get the component which contains all information for the recurrence id.
This concerns this modifications that have RANGE=THISANDFUTURE set.
"""
# We assume the the recurrence_id is of the correct timezone.
component = self.recurrence.core
for modification_id in self.this_and_future:
if modification_id < recurrence_id:
component = self.recurrence_id_to_modification[modification_id]
else:
break
return component
def rrule_between(self, span_start: Time, span_stop: Time) -> Generator[Time]:
"""Modify the rrule generation span and yield recurrences."""
expanded_start = normalize_pytz(span_start - self._subtract_from_start)
expanded_stop = normalize_pytz(span_stop + self._add_to_stop)
yield from self.recurrence.rrule_between(
expanded_start,
expanded_stop,
)
def between(self, span_start: Time, span_stop: Time) -> Generator[Occurrence]:
"""Components between the start (inclusive) and end (exclusive).
The result does not need to be ordered.
"""
returned_starts: set[Time] = set()
returned_modifications: set[ComponentAdapter] = set()
# NOTE: If in the following line, we get an error, datetime and date
# may still be mixed because RDATE, EXDATE, start and rule.
for start in self.rrule_between(span_start, span_stop):
recurrence_ids = to_recurrence_ids(start)
if (
start in returned_starts
or convert_to_date(start) in self.recurrence.check_exdates_date
or self.recurrence.check_exdates_datetime & set(recurrence_ids)
):
continue
adapter: ComponentAdapter = get_any(
self.recurrence_id_to_modification, recurrence_ids, self.recurrence.core
)
if adapter is self.recurrence.core:
# We have no modification for this recurrence, so we record the date
returned_starts.add(start)
# This component is the base for this occurrence.
# It usually is the core. However, we may also find a modification
# with RANGE=THISANDFUTURE.
component = self.get_component_for_recurrence_id(recurrence_ids[0])
occurrence_start = normalize_pytz(start + component.move_recurrences_by)
# Consider the RDATE with a PERIOD value
occurrence_end = normalize_pytz(
occurrence_start
+ get_any(
self.recurrence.replace_ends,
recurrence_ids,
component.duration,
)
)
occurrence = self.recurrence.as_occurrence(
occurrence_start, occurrence_end, self.occurrence, component
)
else:
# We found a modification, so we record the modification
if adapter in returned_modifications:
continue
returned_modifications.add(adapter)
occurrence = self.occurrence(adapter)
if occurrence.is_in_span(span_start, span_stop):
yield occurrence
for modification in self.modifications:
# we assume that the modifications are actually included
if (
modification in returned_modifications
or self.recurrence.check_exdates_datetime
& set(modification.recurrence_ids)
):
continue
if modification.is_in_span(span_start, span_stop):
returned_modifications.add(modification)
yield self.occurrence(modification)
@property
def uid(self):
"""The UID that identifies this series."""
return self._uid
def __repr__(self):
"""A string representation."""
return (
f"<{self.__class__.__name__} uid={self.uid} "
f"modifications:{len(self.recurrence_id_to_modification)}>"
)
class ComponentAdapter(ABC):
"""A unified interface to work with icalendar components."""
ATTRIBUTES_TO_DELETE_ON_COPY = ["RRULE", "RDATE", "EXDATE", "RECURRENCE-ID"]
@staticmethod
@abstractmethod
def component_name() -> str:
"""The icalendar component name."""
def __init__(self, component: Component):
"""Create a new adapter."""
self._component = component
@property
def end_property(self) -> str | None:
"""The name of the end property."""
return None
@property
@abstractmethod
def start(self) -> Time:
"""The start time."""
@property
@abstractmethod
def end(self) -> Time:
"""The end time."""
@property
def uid(self) -> UID:
"""The UID of a component.
UID is required by RFC5545.
If the UID is absent, we use the Python ID.
"""
return self._component.get("UID", str(id(self._component)))
@classmethod
def collect_series_from(
cls, source: Component, suppress_errors: tuple[Exception]
) -> Sequence[Series]:
"""Collect all components for this adapter.
This is a shortcut.
"""
return ComponentsWithName(cls.component_name(), cls).collect_series_from(
source, suppress_errors
)
def as_component(self, start: Time, stop: Time, keep_recurrence_attributes: bool): # noqa: FBT001
"""Create a shallow copy of the source event and modify some attributes."""
copied_component = self._component.copy()
copied_component["DTSTART"] = vDDDTypes(start)
copied_component.pop("DURATION", None) # remove duplication in event length
if self.end_property is not None:
copied_component[self.end_property] = vDDDTypes(stop)
if not keep_recurrence_attributes:
for attribute in self.ATTRIBUTES_TO_DELETE_ON_COPY:
if attribute in copied_component:
del copied_component[attribute]
for subcomponent in self._component.subcomponents:
copied_component.add_component(subcomponent)
return copied_component
@cached_property
def recurrence_ids(self) -> RecurrenceIDs:
"""The recurrence ids of the component that might be used to identify it."""
recurrence_id = self._component.get("RECURRENCE-ID")
if recurrence_id is None:
return ()
return to_recurrence_ids(recurrence_id.dt)
@cached_property
def this_and_future(self) -> bool:
"""The recurrence ids has a thisand future range property"""
recurrence_id = self._component.get("RECURRENCE-ID")
if recurrence_id is None:
return False
if "RANGE" in recurrence_id.params:
return recurrence_id.params["RANGE"] == "THISANDFUTURE"
return False
def is_modification(self) -> bool:
"""Whether the adapter is a modification."""
return bool(self.recurrence_ids)
@cached_property
def sequence(self) -> int:
"""The sequence in the history of modification.
The sequence is negative if none was found.
"""
return self._component.get("SEQUENCE", -1)
def __repr__(self) -> str:
"""Debug representation with more info."""
return (
f"<{self.__class__.__name__} UID={self.uid} start={self.start} "
f"recurrence_ids={self.recurrence_ids} sequence={self.sequence} "
f"end={self.end}>"
)
@cached_property
def exdates(self) -> list[Time]:
"""A list of exdates."""
result: list[Time] = []
exdates = self._component.get("EXDATE", [])
for exdates in (exdates,) if not isinstance(exdates, list) else exdates:
result.extend(exdate.dt for exdate in exdates.dts)
return result
@cached_property
def rrules(self) -> set[str]:
"""A list of rrules of this component."""
rules = self._component.get("RRULE", None)
if not rules:
return set()
return {
rrule.to_ical().decode()
for rrule in (rules if isinstance(rules, list) else [rules])
}
@cached_property
def rdates(self) -> list[Time, tuple[Time, Time]]:
"""A list of rdates, possibly a period."""
rdates = self._component.get("RDATE", [])
result = []
for rdates in (rdates,) if not isinstance(rdates, list) else rdates:
result.extend(rdate.dt for rdate in rdates.dts)
return result
@cached_property
def duration(self) -> datetime.timedelta:
"""The duration of the component."""
return self.end - self.start
def is_in_span(self, span_start: Time, span_stop: Time) -> bool:
"""Return whether the component is in the span."""
return time_span_contains_event(span_start, span_stop, self.start, self.end)
@cached_property
def extend_query_span_by(self) -> tuple[datetime.timedelta, datetime.timedelta]:
"""Calculate how much we extend the query span.
If an event is long, we need to extend the query span by the event's duration.
If an event has moved, we need to make sure that that is included, too.
This is so that the RECURRENCE-ID falls within the modified span.
Imagine if the span is exactly a second. How much would we need to query
forward and backward to capture the recurrence id?
Returns two positive spans: (subtract_from_start, add_to_stop)
"""
subtract_from_start = self.duration
add_to_stop = datetime.timedelta(0)
recurrence_id_prop = self._component.get("RECURRENCE-ID")
if recurrence_id_prop:
start, end, recurrence_id = make_comparable(
(self.start, self.end, recurrence_id_prop.dt)
)
if start < recurrence_id:
add_to_stop = recurrence_id - start
if start > recurrence_id:
subtract_from_start = end - recurrence_id
return subtract_from_start, add_to_stop
@cached_property
def move_recurrences_by(self) -> datetime.timedelta:
"""Occurrences of this component should be moved by this amount.
Usually, the occurrence starts at the new start time.
However, if we have a RANGE=THISANDFUTURE, we need to move the occurrence.
RFC 5545:
When the given recurrence instance is
rescheduled, all subsequent instances are also rescheduled by the
same time difference. For instance, if the given recurrence
instance is rescheduled to start 2 hours later, then all
subsequent instances are also rescheduled 2 hours later.
Similarly, if the duration of the given recurrence instance is
modified, then all subsequence instances are also modified to have
this same duration.
"""
if self.this_and_future:
recurrence_id_prop = self._component.get("RECURRENCE-ID")
assert recurrence_id_prop, "RANGE=THISANDFUTURE implies RECURRENCE-ID."
start, recurrence_id = make_comparable((self.start, recurrence_id_prop.dt))
return start - recurrence_id
return datetime.timedelta(0)
class EventAdapter(ComponentAdapter):
"""An icalendar event adapter."""
@staticmethod
def component_name() -> str:
"""The icalendar component name."""
return "VEVENT"
@property
def end_property(self) -> str:
"""DTEND"""
return "DTEND"
@cached_property
def start(self) -> Time:
"""Return DTSTART"""
# Arguably, it may be considered a feature that this breaks
# if no DTSTART is set
return self._component["DTSTART"].dt
@cached_property
def end(self) -> Time:
"""Yield DTEND or calculate the end of the event based on
DTSTART and DURATION.
"""
## an even may have DTEND or DURATION, but not both
end = self._component.get("DTEND")
if end is not None:
return end.dt
duration = self._component.get("DURATION")
if duration is not None:
return normalize_pytz(self._component["DTSTART"].dt + duration.dt)
start = self._component["DTSTART"].dt
if is_date(start):
return start + datetime.timedelta(days=1)
return start
class TodoAdapter(ComponentAdapter):
"""Unified access to TODOs."""
@staticmethod
def component_name() -> str:
"""The icalendar component name."""
return "VTODO"
@property
def end_property(self) -> str:
"""DUE"""
return "DUE"
@cached_property
def start(self) -> Time:
"""Return DTSTART if it set, do not panic if it's not set."""
## easy case - DTSTART set
start = self._component.get("DTSTART")
if start is not None:
return start.dt
## Tasks may have DUE set, but no DTSTART.
## Let's assume 0 duration and return the DUE
due = self._component.get("DUE")
if due is not None:
return due.dt
## Assume infinite time span if neither is given
## (see the comments under _get_event_end)
return DATE_MIN_DT
@cached_property
def end(self) -> Time:
"""Return DUE or DTSTART+DURATION or something"""
## Easy case - DUE is set
end = self._component.get("DUE")
if end is not None:
return end.dt
dtstart = self._component.get("DTSTART")