Debian Codegraph @

recurring_ical_events/query.py

raw symbols SCIP
1 """Core functionality: querying the calendar for occurrences."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import datetime
7 import itertools
8 import sys
9 from typing import TYPE_CHECKING, ClassVar, Generator, Optional, Sequence
10
11 try:
12 from typing import TypeAlias
13 except ImportError:
14 from typing_extensions import TypeAlias
15
16 import icalendar
17
18 from recurring_ical_events.adapters.component import ComponentAdapter
19 from recurring_ical_events.constants import DATE_MAX_DT, DATE_MIN_DT
20 from recurring_ical_events.errors import (
21 BadRuleStringFormat,
22 InvalidCalendar,
23 PeriodEndBeforeStart,
24 )
25 from recurring_ical_events.occurrence import OccurrenceID
26 from recurring_ical_events.pages import Pages
27 from recurring_ical_events.selection.base import SelectComponents
28 from recurring_ical_events.util import compare_greater
29
30 if TYPE_CHECKING:
31 from icalendar.cal import Component
32
33 from recurring_ical_events.occurrence import Occurrence
34 from recurring_ical_events.series import Series
35 from recurring_ical_events.types import (
36 DateArgument,
37 Time,
38 )
39
40 if sys.version_info >= (3, 10):
41 T_COMPONENTS : TypeAlias = Sequence[str | type[ComponentAdapter] | SelectComponents]
42 else:
43 # see https://github.com/python/cpython/issues/86399#issuecomment-1093889925
44 T_COMPONENTS : TypeAlias = Sequence[str]
45
46
47 class CalendarQuery:
48 """Query a calendar for occurrences.
49
50 Functions like :meth:`at`, :meth:`between` andm :meth:`after`
51 can be used to query the selected components.
52 If any malformed icalendar information is found,
53 an :class:`InvalidCalendar` exception is raised.
54 For other bad arguments, you should expect a :class:`ValueError`.
55
56 Attributes:
57 suppressed_errors: a list of errors to suppress when
58 skip_bad_series is True
59 """
60
61 suppressed_errors : ClassVar[type[Exception]] = [
62 BadRuleStringFormat,
63 PeriodEndBeforeStart,
64 icalendar.InvalidCalendar,
65 ]
66 from recurring_ical_events.selection.name import ComponentsWithName
67
68 def __init__(
69 self,
70 calendar: Component,
71 keep_recurrence_attributes: bool = False, # noqa: FBT001
72 components: T_COMPONENTS = ("VEVENT",),
73 skip_bad_series: bool = False, # noqa: FBT001
74 ):
75 """Create an unfoldable calendar from a given calendar.
76
77 Arguments:
78 calendar: an :class:`icalendar.cal.Calendar` component like
79 :class:`icalendar.cal.Calendar`.
80 keep_recurrence_attributes: Whether to keep attributes that are only used
81 to calculate the recurrence (``RDATE``, ``EXDATE``, ``RRULE``).
82 components: A list of component type names of which the recurrences
83 should be returned. This can also be instances of
84 :class:`SelectComponents`.
85 Examples: ``("VEVENT", "VTODO", "VJOURNAL", "VALARM")``
86 skip_bad_series: Whether to skip series of components that contain
87 errors. You can use :attr:`CalendarQuery.suppressed_errors` to
88 specify which errors to skip.
89 """
90 self.keep_recurrence_attributes = keep_recurrence_attributes
91 if calendar.get("CALSCALE", "GREGORIAN") != "GREGORIAN":
92 # https://www.kanzaki.com/docs/ical/calscale.html
93 raise InvalidCalendar("Only Gregorian calendars are supported.")
94
95 self.series: list[Series] = [] # component
96 self._skip_errors = tuple(self.suppressed_errors) if skip_bad_series else ()
97 for component_adapter_id in components:
98 if isinstance(component_adapter_id, str):
99 component_adapter = self.ComponentsWithName(component_adapter_id)
100 else:
101 component_adapter = component_adapter_id
102 self.series.extend(
103 component_adapter.collect_series_from(calendar, self._skip_errors)
104 )
105
106 @staticmethod
107 def to_datetime(date: DateArgument):
108 """Convert date inputs of various sorts into a datetime object.
109
110 Arguments:
111 date: A date specification.
112
113 Date Specification:
114
115 - a year like ``(2019,)`` or ``2019`` (:class:`int`)
116 - a month like ``(2019, 1)`` for January of 2019
117 - a day like ``(2019, 1, 19)`` for the first of January 2019
118 - a day with hours, ``(2019, 1, 19, 1)``
119 - a day with minutes, ``(2019, 1, 19, 13, 30 )``
120 - a day with seconds, ``(2019, 1, 19, 13, 30, 59)``
121 - a :class:`datetime.datetime` or :class:`datetime.date`
122 - a :class:`str` in the format ``yyyymmdd``
123 - a :class:`str` in the format ``yyyymmddThhmmssZ``
124
125 """
126 if isinstance(date, int):
127 date = (date,)
128 if isinstance(date, tuple):
129 date += (1,) * (3 - len(date))
130 return datetime.datetime(*date) # noqa: DTZ001
131 if isinstance(date, str):
132 # see https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
133 if len(date) == 8:
134 return datetime.datetime.strptime(date, "%Y%m%d") # noqa: DTZ007
135 return datetime.datetime.strptime(date, "%Y%m%dT%H%M%SZ") # noqa: DTZ007
136 return date
137
138 def all(self) -> Generator[Component]:
139 """Generate all Components.
140
141 The Components are sorted from the first to the last Occurrence.
142 Calendars can contain millions of Occurrences. This iterates
143 safely across all of them.
144 """
145 # MAX and MIN values may change in the future
146 return self.after(DATE_MIN_DT)
147
148 _DELTAS = [
149 datetime.timedelta(days=1),
150 datetime.timedelta(hours=1),
151 datetime.timedelta(minutes=1),
152 datetime.timedelta(seconds=1),
153 ]
154
155 def at(self, date: DateArgument):
156 """Return all events within the next 24 hours of starting at the given day.
157
158 Arguments:
159 date: A date specification, see :meth:`to_datetime`.
160
161 This is translated to :meth:`between` in the following way:
162
163 - A year returns all occurrences within that year.
164 Example: ``(2019,)``, ``2019``
165 - A month returns all occurrences within that month.
166 Example: ``(2019, 1)``
167 - A day returns all occurrences within that day.
168 Examples:
169
170 - ``(2019, 1, 19)``
171 - ``datetime.date(2019, 1, 19)``
172 - ``"20190101"``
173
174 - An hour returns all occurrences within that hour.
175 Example: ``(2019, 1, 19, 1)``
176 - A minute returns all occurrences within that minute.
177 Example: ``(2019, 1, 19, 13, 30 )``
178 - A second returns all occurrences at that exact second.
179 Examples:
180
181 - ``(2019, 1, 19, 13, 30, 59)``
182 - ``datetime.datetime(2019, 1, 19, 13, 30, 59)``
183 - ``datetime.datetime(2019, 1, 19, tzinfo=datetime.timezone.utc)``,
184 - ``datetime.datetime(2019, 1, 19, 13, 30, 59, tzinfo=ZoneInfo('Europe/London'))``
185 - ``"20190119T133059Z"``
186 """ # noqa: E501
187 if isinstance(date, int):
188 date = (date,)
189 if isinstance(date, str):
190 if len(date) != 8 or not date.isdigit():
191 raise ValueError(f"Format yyyymmdd expected for {date!r}.")
192 date = (int(date[:4], 10), int(date[4:6], 10), int(date[6:]))
193 if isinstance(date, datetime.datetime):
194 return self.between(date, date)
195 if isinstance(date, datetime.date):
196 return self.between(date, date + datetime.timedelta(days=1))
197 if len(date) == 1:
198 return self.between((date[0], 1, 1), (date[0] + 1, 1, 1))
199 if len(date) == 2:
200 year, month = date
201 if month == 12:
202 return self.between((year, 12, 1), (year + 1, 1, 1))
203 return self.between((year, month, 1), (year, month + 1, 1))
204 dt = self.to_datetime(date)
205 return self._between(dt, dt + self._DELTAS[len(date) - 3])
206
207 def between(self, start: DateArgument, stop: DateArgument | datetime.timedelta):
208 """Return events at a time between start (inclusive) and end (inclusive)
209
210 Arguments:
211 start: A date specification. See :meth:`to_datetime`.
212 stop: A date specification or a :class:`datetime.timedelta`
213 relative to start.
214
215 .. warning::
216
217 If you pass a :class:`datetime.datetime` to both ``start`` and
218 ``stop``, make sure the :attr:`datetime.datetime.tzinfo` is
219 the same.
220 """
221 start = self.to_datetime(start)
222 stop = (
223 start + stop
224 if isinstance(stop, datetime.timedelta)
225 else self.to_datetime(stop)
226 )
227 return self._between(start, stop)
228
229 def _occurrences_to_components(
230 self, occurrences: list[Occurrence]
231 ) -> list[Component]:
232 """Map occurrences to components."""
233 return [
234 occurrence.as_component(self.keep_recurrence_attributes)
235 for occurrence in occurrences
236 ]
237
238 def _between(self, start: Time, end: Time) -> list[Component]:
239 """Return the occurrences between the start and the end."""
240 return self._occurrences_to_components(self._occurrences_between(start, end))
241
242 def _occurrences_between(self, start: Time, end: Time) -> list[Occurrence]:
243 """Return the components between the start and the end."""
244 occurrences: list[Occurrence] = []
245 for series in self.series:
246 with contextlib.suppress(self._skip_errors):
247 occurrences.extend(series.between(start, end))
248 return occurrences
249
250 def after(self, earliest_end: DateArgument) -> Generator[Component]:
251 """Iterate over components happening during or after earliest_end.
252
253 Arguments:
254 earliest_end: A date specification. See :meth:`to_datetime`.
255 Anything happening during or after earliest_end is returned
256 in the order of start time.
257 """
258 earliest_end = self.to_datetime(earliest_end)
259 for occurrence in self._after(earliest_end):
260 yield occurrence.as_component(self.keep_recurrence_attributes)
261
262 def _after(self, earliest_end: Time) -> Generator[Occurrence]:
263 """Iterate over occurrences happening during or after earliest_end."""
264 time_span = datetime.timedelta(days=1)
265 min_time_span = datetime.timedelta(minutes=15)
266 done = False
267 result_ids: set[OccurrenceID] = set()
268
269 while not done:
270 try:
271 next_end = earliest_end + time_span
272 except OverflowError:
273 # We ran to the end
274 next_end = DATE_MAX_DT
275 if compare_greater(earliest_end, next_end):
276 return # we might run too far
277 done = True
278 occurrences = self._occurrences_between(earliest_end, next_end)
279 occurrences.sort()
280 for occurrence in occurrences:
281 if occurrence.id not in result_ids:
282 yield occurrence
283 result_ids.add(occurrence.id)
284 # prepare next query
285 time_span = max(
286 time_span / 2 if occurrences else time_span * 2,
287 min_time_span,
288 ) # binary search to improve speed
289 earliest_end = next_end
290
291 def count(self) -> int:
292 """Return the amount of recurring components in this calendar.
293
294 .. warning::
295
296 Do not use this in production as it generates all occurrences.
297 """
298 i = 0
299 for _ in self.all():
300 i += 1
301 return i
302
303 @property
304 def first(self) -> Component:
305 """Return the first recurring component in this calendar.
306
307 Returns:
308 The first recurring component in this calendar.
309
310 Raises:
311 IndexError: if the calendar is empty
312 """
313 for component in self.all():
314 return component
315 raise IndexError("No components found.")
316
317 def paginate(
318 self,
319 page_size: int,
320 earliest_end: Optional[DateArgument] = None,
321 latest_start: Optional[DateArgument] = None,
322 next_page_id: str = "",
323 ) -> Pages:
324 """Return pages for pagination.
325
326 Args:
327 page_size: the number of components per page
328 earliest_end: the start of the first page
329 All components occur after this date.
330 See :meth:`to_datetime` for possible values.
331 latest_start: the end of the last page
332 All components occur before this date.
333 See :meth:`to_datetime` for possible values.
334 next_page_id: The id of the next page.
335 This is optional for the first page.
336 These are safe to pass outside of the application and back in.
337 """
338 latest_start = None if latest_start is None else self.to_datetime(latest_start)
339 earliest_end = (
340 DATE_MIN_DT if earliest_end is None else self.to_datetime(earliest_end)
341 )
342 if next_page_id:
343 first_occurrence_id = OccurrenceID.from_string(next_page_id)
344 if not compare_greater(earliest_end, first_occurrence_id.start):
345 iterator = self._after(first_occurrence_id.start)
346 lost_occurrences = [] # in case we do not find the event
347 for occurrence in iterator:
348 lost_occurrences.append(occurrence)
349 oid = occurrence.id
350 if oid == first_occurrence_id:
351 iterator = itertools.chain([occurrence], iterator)
352 break
353 if compare_greater(oid.start, first_occurrence_id.start):
354 iterator = itertools.chain(lost_occurrences, iterator)
355 break
356 else:
357 iterator = self._after(earliest_end)
358 else:
359 iterator = self._after(earliest_end)
360 return Pages(
361 occurrence_iterator=iterator,
362 size=page_size,
363 stop=latest_start,
364 keep_recurrence_attributes=self.keep_recurrence_attributes,
365 )
366
367
368 __all__ = ["T_COMPONENTS", "CalendarQuery"]