Debian Codegraph @

recurring_ical_events/series/rrule.py

raw symbols SCIP
1 """Calculation of series based on rrule."""
2
3 from __future__ import annotations
4
5 import datetime
6 from typing import TYPE_CHECKING, Generator, Sequence
7
8 from dateutil.rrule import rrule, rruleset, rrulestr
9 from icalendar.prop import vDDDTypes
10
11 from recurring_ical_events.constants import NEGATIVE_RRULE_COUNT_REGEX
12 from recurring_ical_events.errors import BadRuleStringFormat
13 from recurring_ical_events.occurrence import Occurrence
14 from recurring_ical_events.util import (
15 compare_greater,
16 convert_to_date,
17 convert_to_datetime,
18 get_any,
19 is_date,
20 is_pytz,
21 is_pytz_dt,
22 normalize_pytz,
23 to_recurrence_ids,
24 with_highest_sequence,
25 )
26
27 if TYPE_CHECKING:
28 from recurring_ical_events.adapters.component import ComponentAdapter
29 from recurring_ical_events.types import RecurrenceID, Time
30
31
32 class Series:
33 """Base class for components that result in a series of occurrences."""
34
35 def occurrence(
36 self,
37 adapter: ComponentAdapter,
38 start: Time | None = None,
39 end: Time | None | datetime.timedelta = None,
40 ) -> Occurrence:
41 """A way to override the occurrence class."""
42 return Occurrence(adapter, start, end, sequence=self.sequence)
43
44 class NoRecurrence:
45 """A strategy to deal with not having a core with rrules."""
46
47 check_exdates_datetime: set[RecurrenceID] = set()
48 check_exdates_date: set[datetime.date] = set()
49 replace_ends: dict[RecurrenceID, Time] = {}
50 sequence = -1
51
52 def as_occurrence(
53 self,
54 start: Time,
55 stop: Time,
56 occurrence: type[Occurrence],
57 core: ComponentAdapter,
58 ) -> Occurrence:
59 raise NotImplementedError("This code should never be reached.")
60
61 @property
62 def core(self) -> ComponentAdapter:
63 raise NotImplementedError("This code should never be reached.")
64
65 def rrule_between(
66 self,
67 span_start: Time, # noqa: ARG002
68 span_stop: Time, # noqa: ARG002
69 ) -> Generator[Time, None, None]:
70 """No repetition."""
71 yield from []
72
73 has_core = False
74 extend_query_span_by = (datetime.timedelta(0), datetime.timedelta(0))
75 components = []
76
77 class RecurrenceRules:
78 """A strategy if we have an actual core with recurrences."""
79
80 has_core = True
81
82 @property
83 def sequence(self) -> int:
84 """The sequence of the code component."""
85 return self.core.sequence
86
87 def __init__(self, core: ComponentAdapter):
88 self.core = core
89 # Setup complete. We create the attribtues
90 self.start = self.original_start = self.core.start
91 self.end = self.original_end = self.core.end
92 self.exdates: set[Time] = set()
93 self.check_exdates_datetime: set[RecurrenceID] = set() # should be in UTC
94 self.check_exdates_date: set[datetime.date] = set() # should be in UTC
95 self.rdates: set[Time] = set()
96 self.replace_ends: dict[
97 RecurrenceID, datetime.timedelta
98 ] = {} # for periods, in UTC
99 # fill the attributes
100 for exdate in self.core.exdates:
101 self.exdates.add(exdate)
102 self.check_exdates_datetime.update(to_recurrence_ids(exdate))
103 if is_date(exdate):
104 self.check_exdates_date.add(exdate)
105 for rdate in self.core.rdates:
106 if isinstance(rdate, tuple):
107 # we have a period as rdate
108 self.rdates.add(rdate[0])
109 for recurrence_id in to_recurrence_ids(rdate[0]):
110 self.replace_ends[recurrence_id] = (
111 rdate[1]
112 if isinstance(rdate[1], datetime.timedelta)
113 else rdate[1] - rdate[0]
114 )
115 else:
116 # we have a date/datetime
117 self.rdates.add(rdate)
118
119 # We make sure that all dates and times mentioned here are either:
120 # - a date
121 # - a datetime with None is tzinfo
122 # - a datetime with a timezone
123 self.make_all_dates_comparable()
124
125 # Calculate the rules with the same timezones
126 rule_set = rruleset(cache=True)
127 rule_set.until = None
128 self.rrules = [rule_set]
129 last_until: Time | None = None
130 for rrule_string in self.core.rrules:
131 rule = self.create_rule_with_start(rrule_string)
132 self.rrules.append(rule)
133 if rule.until and (
134 not last_until or compare_greater(rule.until, last_until)
135 ):
136 last_until = rule.until
137
138 for exdate in self.exdates:
139 self.check_exdates_datetime.add(exdate)
140 for rdate in self.rdates:
141 rule_set.rdate(rdate)
142
143 if not last_until or not compare_greater(self.start, last_until):
144 rule_set.rdate(self.start)
145
146 @property
147 def extend_query_span_by(self) -> tuple[datetime.timedelta, datetime.timedelta]:
148 """The extension of the time span we need for this component's core."""
149 return self.core.extend_query_span_by
150
151 def create_rule_with_start(self, rule_string: str) -> rrule:
152 """Helper to create an rrule from a rule_string
153
154 The rrule is starting at the start of the component.
155 Since the creation is a bit more complex,
156 this function handles special cases.
157 """
158 try:
159 return self.rrulestr(rule_string)
160 except ValueError:
161 # string: FREQ=WEEKLY;UNTIL=20191023;BYDAY=TH;WKST=SU
162 # start: 2019-08-01 14:00:00+01:00
163 # ValueError: RRULE UNTIL values must be specified in UTC
164 # when DTSTART is timezone-aware
165 rule_list = rule_string.split(";UNTIL=")
166 if len(rule_list) != 2:
167 raise BadRuleStringFormat(
168 "UNTIL parameter is missing", rule_string
169 ) from None
170 date_end_index = rule_list[1].find(";")
171 if date_end_index == -1:
172 date_end_index = len(rule_list[1])
173 until_string = rule_list[1][:date_end_index]
174 if self.is_all_dates:
175 until_string = until_string[:8]
176 elif self.tzinfo is None:
177 # remove the Z from the time zone
178 until_string = until_string[:-1]
179 else:
180 # we assume the start is timezone aware but the until value
181 # is not, see the comment above
182 if len(until_string) == 8:
183 until_string += "T000000"
184 if len(until_string) != 15:
185 raise BadRuleStringFormat(
186 "UNTIL parameter has a bad format", rule_string
187 ) from None
188 until_string += "Z" # https://stackoverflow.com/a/49991809
189 new_rule_string = (
190 rule_list[0]
191 + rule_list[1][date_end_index:]
192 + ";UNTIL="
193 + until_string
194 )
195 return self.rrulestr(new_rule_string)
196
197 def rrulestr(self, rule_string) -> rrule:
198 """Return an rrulestr with a start. This might fail."""
199 rule_string = NEGATIVE_RRULE_COUNT_REGEX.sub("", rule_string) # Issue 128
200 rule = rrulestr(rule_string, dtstart=self.start, cache=True)
201 rule.string = rule_string
202 rule.until = until = self._get_rrule_until(rule)
203 if is_pytz(self.start.tzinfo) and rule.until:
204 # when starting in a time zone that is one hour off to the end,
205 # we might miss the last occurrence
206 # see issue 107 and test/test_issue_107_omitting_last_event.py
207 rule = rule.replace(until=rule.until + datetime.timedelta(hours=1))
208 rule.until = until
209 return rule
210
211 def _get_rrule_until(self, rrule) -> None | Time:
212 """Return the UNTIL datetime of the rrule or None if absent."""
213 rule_list = rrule.string.split(";UNTIL=")
214 if len(rule_list) == 1:
215 return None
216 if len(rule_list) != 2:
217 raise BadRuleStringFormat("There should be only one UNTIL", rrule)
218 date_end_index = rule_list[1].find(";")
219 if date_end_index == -1:
220 date_end_index = len(rule_list[1])
221 until_string = rule_list[1][:date_end_index]
222 return vDDDTypes.from_ical(until_string)
223
224 def make_all_dates_comparable(self):
225 """Make sure we can use all dates with eachother.
226
227 Dates may be mixed and we have many of them.
228 - date
229 - datetime without timezone
230 - datetime with timezone
231 These three are not comparable but can be converted.
232 """
233 self.tzinfo = None
234 dates = [self.start, self.end, *self.exdates, *self.rdates]
235 self.is_all_dates = not any(
236 isinstance(date, datetime.datetime) for date in dates
237 )
238 for date in dates:
239 if isinstance(date, datetime.datetime) and date.tzinfo is not None:
240 self.tzinfo = date.tzinfo
241 break
242 self.start = convert_to_datetime(self.start, self.tzinfo)
243
244 self.end = convert_to_datetime(self.end, self.tzinfo)
245 self.rdates = {
246 convert_to_datetime(rdate, self.tzinfo) for rdate in self.rdates
247 }
248 self.exdates = {
249 convert_to_datetime(exdate, self.tzinfo) for exdate in self.exdates
250 }
251
252 def rrule_between(self, span_start: Time, span_stop: Time) -> Generator[Time]:
253 """Recalculate the rrules so that minor mistakes are corrected."""
254 # make dates comparable, rrule converts them to datetimes
255 span_start_dt = convert_to_datetime(span_start, self.tzinfo)
256 span_stop_dt = convert_to_datetime(span_stop, self.tzinfo)
257 # we have to account for pytz timezones not being properly calculated
258 # at the timezone changes. This is a heuristic:
259 # most changes are only 1 hour.
260 # This will still create problems at the fringes of
261 # timezone definition changes.
262 if is_pytz(self.tzinfo):
263 span_start_dt = normalize_pytz(
264 span_start_dt - datetime.timedelta(hours=1)
265 )
266 span_stop_dt = normalize_pytz(
267 span_stop_dt + datetime.timedelta(hours=1)
268 )
269 for rule in self.rrules:
270 for start in rule.between(span_start_dt, span_stop_dt, inc=True):
271 if is_pytz_dt(start):
272 # update the time zone in case of summer/winter time change
273 start = start.tzinfo.localize(start.replace(tzinfo=None)) # noqa: PLW2901
274 # We could now well be out of bounce of the end of the UNTIL
275 # value. This is tested by test/test_issue_20_exdate_ignored.py.
276 if rule.until is None or not compare_greater(start, rule.until):
277 yield start
278
279 def convert_to_original_type(self, date):
280 """Convert a date back if this is possible.
281
282 Dates may get converted to datetimes to make calculations possible.
283 This reverts the process where possible so that Repetitions end
284 up with the type (date/datetime) that was specified in the icalendar
285 component.
286 """
287 if not isinstance(
288 self.original_start, datetime.datetime
289 ) and not isinstance(
290 self.original_end,
291 datetime.datetime,
292 ):
293 return convert_to_date(date)
294 return date
295
296 def as_occurrence(
297 self,
298 start: Time,
299 stop: Time,
300 occurrence: type[Occurrence],
301 core: ComponentAdapter,
302 ) -> Occurrence:
303 """Return this as an occurrence at a specific time."""
304 return occurrence(
305 core,
306 self.convert_to_original_type(start),
307 self.convert_to_original_type(stop),
308 )
309
310 @property
311 def components(self) -> list[ComponentAdapter]:
312 """The components in this recurrence calculation."""
313 return [self.core]
314
315 def __init__(self, components: Sequence[ComponentAdapter]):
316 """Create an component which may have repetitions in it."""
317 if len(components) == 0:
318 raise ValueError("No components given to calculate a series.")
319 # We identify recurrences with a timestamp as all recurrence values
320 # should be the same in UTC either way and we want to omit
321 # inequality because of timezone implementation mismatches.
322 self.recurrence_id_to_modification: dict[
323 RecurrenceID, ComponentAdapter
324 ] = {} # RECURRENCE-ID -> adapter
325 self.this_and_future = []
326 self._uid = components[0].uid
327 core: ComponentAdapter | None = None
328 for component in components:
329 if component.is_modification():
330 recurrence_ids = component.recurrence_ids
331 for recurrence_id in recurrence_ids:
332 self.recurrence_id_to_modification[recurrence_id] = (
333 with_highest_sequence(
334 self.recurrence_id_to_modification.get(recurrence_id),
335 component,
336 )
337 )
338 if component.this_and_future:
339 self.this_and_future.append(recurrence_ids[0])
340 else:
341 core = with_highest_sequence(core, component)
342 self.modifications: set[ComponentAdapter] = set(
343 self.recurrence_id_to_modification.values()
344 )
345 del component
346 self.recurrence = (
347 self.NoRecurrence() if core is None else self.RecurrenceRules(core)
348 )
349 self.this_and_future.sort()
350 self.sequence = max(component.sequence for component in self.components)
351 self.compute_span_extension()
352
353 def compute_span_extension(self):
354 """Compute how much to extend the span for the rrule to cover all events."""
355 self._subtract_from_start, self._add_to_stop = (
356 self.recurrence.extend_query_span_by
357 )
358 for adapter in self.this_and_future_components:
359 subtract_from_start, add_to_stop = adapter.extend_query_span_by
360 self._subtract_from_start = max(
361 subtract_from_start, self._subtract_from_start
362 )
363 self._add_to_stop = max(add_to_stop, self._add_to_stop)
364
365 @property
366 def components(self) -> list[ComponentAdapter]:
367 """All the components in this sequence.
368
369 Components with the same UID might not occur if the SEQUENCE
370 number suggests that they are obsolete.
371 """
372 return self.recurrence.components + list(self.modifications)
373
374 @property
375 def this_and_future_components(self) -> Generator[ComponentAdapter]:
376 """All components that influence future events."""
377 if self.recurrence.has_core:
378 yield self.recurrence.core
379 for recurrence_id in self.this_and_future:
380 yield self.recurrence_id_to_modification[recurrence_id]
381
382 def get_component_for_recurrence_id(
383 self, recurrence_id: RecurrenceID
384 ) -> ComponentAdapter:
385 """Get the component which contains all information for the recurrence id.
386
387 This concerns this modifications that have RANGE=THISANDFUTURE set.
388 """
389 # We assume the the recurrence_id is of the correct timezone.
390 component = self.recurrence.core
391 for modification_id in self.this_and_future:
392 if modification_id < recurrence_id:
393 component = self.recurrence_id_to_modification[modification_id]
394 else:
395 break
396 return component
397
398 def rrule_between(self, span_start: Time, span_stop: Time) -> Generator[Time]:
399 """Modify the rrule generation span and yield recurrences."""
400 expanded_start = normalize_pytz(span_start - self._subtract_from_start)
401 expanded_stop = normalize_pytz(span_stop + self._add_to_stop)
402 yield from self.recurrence.rrule_between(
403 expanded_start,
404 expanded_stop,
405 )
406
407 def between(self, span_start: Time, span_stop: Time) -> Generator[Occurrence]:
408 """Components between the start (inclusive) and end (exclusive).
409
410 The result does not need to be ordered.
411 """
412 returned_starts: set[Time] = set()
413 returned_modifications: set[ComponentAdapter] = set()
414 # NOTE: If in the following line, we get an error, datetime and date
415 # may still be mixed because RDATE, EXDATE, start and rule.
416 for start in self.rrule_between(span_start, span_stop):
417 recurrence_ids = to_recurrence_ids(start)
418 if (
419 start in returned_starts
420 or convert_to_date(start) in self.recurrence.check_exdates_date
421 or self.recurrence.check_exdates_datetime & set(recurrence_ids)
422 ):
423 continue
424 adapter: ComponentAdapter = get_any(
425 self.recurrence_id_to_modification, recurrence_ids, self.recurrence.core
426 )
427 if adapter is self.recurrence.core:
428 # We have no modification for this recurrence, so we record the date
429 returned_starts.add(start)
430 # This component is the base for this occurrence.
431 # It usually is the core. However, we may also find a modification
432 # with RANGE=THISANDFUTURE.
433 component = self.get_component_for_recurrence_id(recurrence_ids[0])
434 occurrence_start = normalize_pytz(start + component.move_recurrences_by)
435 # Consider the RDATE with a PERIOD value
436 occurrence_end = normalize_pytz(
437 occurrence_start
438 + get_any(
439 self.recurrence.replace_ends,
440 recurrence_ids,
441 component.duration,
442 )
443 )
444 occurrence = self.recurrence.as_occurrence(
445 occurrence_start, occurrence_end, self.occurrence, component
446 )
447 else:
448 # We found a modification, so we record the modification
449 if adapter in returned_modifications:
450 continue
451 returned_modifications.add(adapter)
452 occurrence = self.occurrence(adapter)
453 if occurrence.is_in_span(span_start, span_stop):
454 yield occurrence
455 for modification in self.modifications:
456 # we assume that the modifications are actually included
457 if (
458 modification in returned_modifications
459 or self.recurrence.check_exdates_datetime
460 & set(modification.recurrence_ids)
461 ):
462 continue
463 if modification.is_in_span(span_start, span_stop):
464 returned_modifications.add(modification)
465 yield self.occurrence(modification)
466
467 @property
468 def uid(self):
469 """The UID that identifies this series."""
470 return self._uid
471
472 def __repr__(self):
473 """A string representation."""
474 return (
475 f"<{self.__class__.__name__} uid={self.uid} "
476 f"modifications:{len(self.recurrence_id_to_modification)}>"
477 )
478
479
480 ___all__ = ["Series"]