| 1 |
"""Base class for all adapters.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import datetime |
| 6 |
from abc import ABC, abstractmethod |
| 7 |
from typing import TYPE_CHECKING, Optional, Sequence |
| 8 |
|
| 9 |
from icalendar.prop import vDDDTypes |
| 10 |
|
| 11 |
from recurring_ical_events.util import ( |
| 12 |
cached_property, |
| 13 |
make_comparable, |
| 14 |
time_span_contains_event, |
| 15 |
to_recurrence_ids, |
| 16 |
) |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from icalendar import Alarm |
| 20 |
from icalendar.cal import Component |
| 21 |
|
| 22 |
from recurring_ical_events.series import Series |
| 23 |
from recurring_ical_events.types import UID, RecurrenceIDs, Time |
| 24 |
|
| 25 |
|
| 26 |
class ComponentAdapter(ABC): |
| 27 |
"""A unified interface to work with icalendar components.""" |
| 28 |
|
| 29 |
ATTRIBUTES_TO_DELETE_ON_COPY = ["RRULE", "RDATE", "EXDATE"] |
| 30 |
|
| 31 |
@staticmethod |
| 32 |
@abstractmethod |
| 33 |
def component_name() -> str: |
| 34 |
"""The icalendar component name.""" |
| 35 |
|
| 36 |
def __init__(self, component: Component): |
| 37 |
"""Create a new adapter.""" |
| 38 |
self._component = component |
| 39 |
|
| 40 |
@property |
| 41 |
def alarms(self) -> list[Alarm]: |
| 42 |
"""The alarms in this component.""" |
| 43 |
return self._component.walk("VALARM") |
| 44 |
|
| 45 |
@property |
| 46 |
def end_property(self) -> str | None: |
| 47 |
"""The name of the end property.""" |
| 48 |
return None |
| 49 |
|
| 50 |
@property |
| 51 |
def start(self) -> Time: |
| 52 |
"""The start time.""" |
| 53 |
return self.span[0] |
| 54 |
|
| 55 |
@property |
| 56 |
def end(self) -> Time: |
| 57 |
"""The end time.""" |
| 58 |
return self.span[1] |
| 59 |
|
| 60 |
@cached_property |
| 61 |
def span(self): |
| 62 |
"""Return (start, end).""" |
| 63 |
start, end = make_comparable((self.raw_start, self.raw_end)) |
| 64 |
if start > end: |
| 65 |
return end, start |
| 66 |
return start, end |
| 67 |
|
| 68 |
@property |
| 69 |
@abstractmethod |
| 70 |
def raw_start(self): |
| 71 |
"""Return the start property of the component.""" |
| 72 |
|
| 73 |
@property |
| 74 |
@abstractmethod |
| 75 |
def raw_end(self): |
| 76 |
"""Return the start property of the component.""" |
| 77 |
|
| 78 |
@property |
| 79 |
def uid(self) -> UID: |
| 80 |
"""The UID of a component. |
| 81 |
|
| 82 |
UID is required by RFC5545. |
| 83 |
If the UID is absent, we use the Python ID. |
| 84 |
""" |
| 85 |
return self._component.get("UID", str(id(self._component))) |
| 86 |
|
| 87 |
@classmethod |
| 88 |
def collect_series_from( |
| 89 |
cls, source: Component, suppress_errors: tuple[Exception] |
| 90 |
) -> Sequence[Series]: |
| 91 |
"""Collect all components for this adapter. |
| 92 |
|
| 93 |
This is a shortcut. |
| 94 |
""" |
| 95 |
from recurring_ical_events.selection.name import ComponentsWithName |
| 96 |
|
| 97 |
return ComponentsWithName(cls.component_name(), cls).collect_series_from( |
| 98 |
source, suppress_errors |
| 99 |
) |
| 100 |
|
| 101 |
def as_component( |
| 102 |
self, |
| 103 |
start: Optional[Time] = None, |
| 104 |
stop: Optional[Time] = None, |
| 105 |
keep_recurrence_attributes: bool = True, |
| 106 |
): |
| 107 |
"""Create a shallow copy of the source event and modify some attributes.""" |
| 108 |
copied_component = self._component.copy() |
| 109 |
copied_component["DTSTART"] = vDDDTypes(self.start if start is None else start) |
| 110 |
copied_component.pop("DURATION", None) |
| 111 |
if self.end_property is not None: |
| 112 |
copied_component[self.end_property] = vDDDTypes( |
| 113 |
self.end if stop is None else stop |
| 114 |
) |
| 115 |
if not keep_recurrence_attributes: |
| 116 |
for attribute in self.ATTRIBUTES_TO_DELETE_ON_COPY: |
| 117 |
if attribute in copied_component: |
| 118 |
del copied_component[attribute] |
| 119 |
for subcomponent in self._component.subcomponents: |
| 120 |
copied_component.add_component(subcomponent) |
| 121 |
if "RECURRENCE-ID" not in copied_component: |
| 122 |
copied_component["RECURRENCE-ID"] = vDDDTypes( |
| 123 |
copied_component["DTSTART"].dt |
| 124 |
) |
| 125 |
return copied_component |
| 126 |
|
| 127 |
@cached_property |
| 128 |
def recurrence_ids(self) -> RecurrenceIDs: |
| 129 |
"""The recurrence ids of the component that might be used to identify it.""" |
| 130 |
recurrence_id = self._component.get("RECURRENCE-ID") |
| 131 |
if recurrence_id is None: |
| 132 |
return () |
| 133 |
return to_recurrence_ids(recurrence_id.dt) |
| 134 |
|
| 135 |
@cached_property |
| 136 |
def this_and_future(self) -> bool: |
| 137 |
"""The recurrence ids has a thisand future range property""" |
| 138 |
recurrence_id = self._component.get("RECURRENCE-ID") |
| 139 |
if recurrence_id is None: |
| 140 |
return False |
| 141 |
if "RANGE" in recurrence_id.params: |
| 142 |
return recurrence_id.params["RANGE"] == "THISANDFUTURE" |
| 143 |
return False |
| 144 |
|
| 145 |
def is_modification(self) -> bool: |
| 146 |
"""Whether the adapter is a modification.""" |
| 147 |
return bool(self.recurrence_ids) |
| 148 |
|
| 149 |
@cached_property |
| 150 |
def sequence(self) -> int: |
| 151 |
"""The sequence in the history of modification. |
| 152 |
|
| 153 |
The sequence is negative if none was found. |
| 154 |
""" |
| 155 |
return self._component.get("SEQUENCE", -1) |
| 156 |
|
| 157 |
def __repr__(self) -> str: |
| 158 |
"""Debug representation with more info.""" |
| 159 |
return ( |
| 160 |
f"<{self.__class__.__name__} UID={self.uid} start={self.start} " |
| 161 |
f"recurrence_ids={self.recurrence_ids} sequence={self.sequence} " |
| 162 |
f"end={self.end}>" |
| 163 |
) |
| 164 |
|
| 165 |
@cached_property |
| 166 |
def exdates(self) -> list[Time]: |
| 167 |
"""A list of exdates.""" |
| 168 |
result: list[Time] = [] |
| 169 |
exdates = self._component.get("EXDATE", []) |
| 170 |
for exdates in (exdates,) if not isinstance(exdates, list) else exdates: |
| 171 |
result.extend(exdate.dt for exdate in exdates.dts) |
| 172 |
return result |
| 173 |
|
| 174 |
@cached_property |
| 175 |
def rrules(self) -> set[str]: |
| 176 |
"""A list of rrules of this component.""" |
| 177 |
rules = self._component.get("RRULE", None) |
| 178 |
if not rules: |
| 179 |
return set() |
| 180 |
return { |
| 181 |
rrule.to_ical().decode() |
| 182 |
for rrule in (rules if isinstance(rules, list) else [rules]) |
| 183 |
} |
| 184 |
|
| 185 |
@cached_property |
| 186 |
def rdates(self) -> list[Time, tuple[Time, Time]]: |
| 187 |
"""A list of rdates, possibly a period.""" |
| 188 |
rdates = self._component.get("RDATE", []) |
| 189 |
result = [] |
| 190 |
for rdates in (rdates,) if not isinstance(rdates, list) else rdates: |
| 191 |
result.extend(rdate.dt for rdate in rdates.dts) |
| 192 |
return result |
| 193 |
|
| 194 |
@cached_property |
| 195 |
def duration(self) -> datetime.timedelta: |
| 196 |
"""The duration of the component.""" |
| 197 |
return self.end - self.start |
| 198 |
|
| 199 |
def is_in_span(self, span_start: Time, span_stop: Time) -> bool: |
| 200 |
"""Return whether the component is in the span.""" |
| 201 |
return time_span_contains_event(span_start, span_stop, self.start, self.end) |
| 202 |
|
| 203 |
@cached_property |
| 204 |
def extend_query_span_by(self) -> tuple[datetime.timedelta, datetime.timedelta]: |
| 205 |
"""Calculate how much we extend the query span. |
| 206 |
|
| 207 |
If an event is long, we need to extend the query span by the event's duration. |
| 208 |
If an event has moved, we need to make sure that that is included, too. |
| 209 |
|
| 210 |
This is so that the RECURRENCE-ID falls within the modified span. |
| 211 |
Imagine if the span is exactly a second. How much would we need to query |
| 212 |
forward and backward to capture the recurrence id? |
| 213 |
|
| 214 |
Returns two positive spans: (subtract_from_start, add_to_stop) |
| 215 |
""" |
| 216 |
subtract_from_start = self.duration |
| 217 |
add_to_stop = datetime.timedelta(0) |
| 218 |
recurrence_id_prop = self._component.get("RECURRENCE-ID") |
| 219 |
if recurrence_id_prop: |
| 220 |
start, end, recurrence_id = make_comparable( |
| 221 |
(self.start, self.end, recurrence_id_prop.dt) |
| 222 |
) |
| 223 |
if start < recurrence_id: |
| 224 |
add_to_stop = recurrence_id - start |
| 225 |
if start > recurrence_id: |
| 226 |
subtract_from_start = end - recurrence_id |
| 227 |
return subtract_from_start, add_to_stop |
| 228 |
|
| 229 |
@cached_property |
| 230 |
def move_recurrences_by(self) -> datetime.timedelta: |
| 231 |
"""Occurrences of this component should be moved by this amount. |
| 232 |
|
| 233 |
Usually, the occurrence starts at the new start time. |
| 234 |
However, if we have a RANGE=THISANDFUTURE, we need to move the occurrence. |
| 235 |
|
| 236 |
RFC 5545: |
| 237 |
|
| 238 |
When the given recurrence instance is |
| 239 |
rescheduled, all subsequent instances are also rescheduled by the |
| 240 |
same time difference. For instance, if the given recurrence |
| 241 |
instance is rescheduled to start 2 hours later, then all |
| 242 |
subsequent instances are also rescheduled 2 hours later. |
| 243 |
Similarly, if the duration of the given recurrence instance is |
| 244 |
modified, then all subsequence instances are also modified to have |
| 245 |
this same duration. |
| 246 |
""" |
| 247 |
if self.this_and_future: |
| 248 |
recurrence_id_prop = self._component.get("RECURRENCE-ID") |
| 249 |
assert recurrence_id_prop, "RANGE=THISANDFUTURE implies RECURRENCE-ID." |
| 250 |
start, recurrence_id = make_comparable((self.start, recurrence_id_prop.dt)) |
| 251 |
return start - recurrence_id |
| 252 |
return datetime.timedelta(0) |
| 253 |
|
| 254 |
|
| 255 |
__all__ = ["ComponentAdapter"] |