Debian Codegraph @

recurring_ical_events/occurrence.py

raw symbols SCIP
1 """Occurrences of events and other components."""
2
3 from __future__ import annotations
4
5 from datetime import date, datetime, timedelta
6 from typing import TYPE_CHECKING, NamedTuple, Optional
7
8 from icalendar import Alarm
9
10 from recurring_ical_events.adapters.component import ComponentAdapter
11 from recurring_ical_events.util import (
12 cached_property,
13 make_comparable,
14 time_span_contains_event,
15 )
16
17 if TYPE_CHECKING:
18 from icalendar import Alarm
19 from icalendar.cal import Component
20
21 from recurring_ical_events.adapters.component import ComponentAdapter
22 from recurring_ical_events.types import UID, RecurrenceIDs, Time
23
24
25 class OccurrenceID(NamedTuple):
26 """The ID of a component's occurrence to identify it clearly.
27
28 Attributes:
29 name: The name of the component, e.g. "VEVENT"
30 uid: The UID of the component.
31 recurrence_id: The Recurrence-ID of the component in UTC but without tzinfo.
32 start: The start of the component
33
34 """
35
36 name: str
37 uid: UID
38 recurrence_id: Optional[Time]
39 start: Time
40
41 def to_string(self) -> str:
42 """Return a string representation of this id."""
43 return "#".join(
44 [
45 self.name,
46 self.recurrence_id.isoformat() if self.recurrence_id else "",
47 self.start.isoformat(),
48 self.uid,
49 ]
50 )
51
52 @staticmethod
53 def _dt_from_string(iso_string: str) -> Time:
54 """Create a datetime from the string representation."""
55 if len(iso_string) == 10:
56 return date.fromisoformat(iso_string)
57 return datetime.fromisoformat(iso_string)
58
59 @classmethod
60 def from_string(cls, string_id: str) -> OccurrenceID:
61 """Parse a string and return the component id."""
62 name, recurrence_id, start, uid = string_id.split("#", 3)
63 return cls(
64 name,
65 uid,
66 cls._dt_from_string(recurrence_id) if recurrence_id else None,
67 cls._dt_from_string(start),
68 )
69
70 @classmethod
71 def from_occurrence(
72 cls, name: str, uid: str, recurrence_ids: RecurrenceIDs, start: Time
73 ):
74 """Create a new OccurrenceID from the given values.
75
76 Args:
77 name: The component name.
78 uid: The UID string.
79 recurrence_ids: The recurrence ID tuple.
80 This is expected as UTC with tzinfo being None.
81 start: start time of the component either with or without timezone
82 """
83 return cls(name, uid, recurrence_ids[0] if recurrence_ids else None, start)
84
85
86 class Occurrence:
87 """A repetition of an event."""
88
89 def __init__(
90 self,
91 adapter: ComponentAdapter,
92 start: Time | None = None,
93 end: Time | None | timedelta = None,
94 sequence: int = -1,
95 ):
96 """Create an event repetition.
97
98 - source - the icalendar Event
99 - start - the start date/datetime to replace
100 - stop - the end date/datetime to replace
101 - sequence - if positive or 0, this sets the SEQUENCE property
102 """
103 self._adapter = adapter
104 self.start = adapter.start if start is None else start
105 self.end = adapter.end if end is None else end
106 self.sequence = sequence
107
108 def as_component(self, keep_recurrence_attributes: bool) -> Component: # noqa: FBT001
109 """Create a shallow copy of the source component and modify some attributes."""
110 component = self._adapter.as_component(
111 self.start, self.end, keep_recurrence_attributes
112 )
113 if self.sequence >= 0:
114 component["SEQUENCE"] = self.sequence
115 return component
116
117 def is_in_span(self, span_start: Time, span_stop: Time) -> bool:
118 """Return whether the component is in the span."""
119 return time_span_contains_event(span_start, span_stop, self.start, self.end)
120
121 def __lt__(self, other: Occurrence) -> bool:
122 """Compare two occurrences for sorting.
123
124 See https://stackoverflow.com/a/4010558/1320237
125 """
126 self_start, other_start = make_comparable((self.start, other.start))
127 return self_start < other_start
128
129 @cached_property
130 def id(self) -> OccurrenceID:
131 """The id of the component."""
132 return OccurrenceID.from_occurrence(
133 self._adapter.component_name(),
134 self._adapter.uid,
135 self._adapter.recurrence_ids,
136 self.start,
137 )
138
139 def __hash__(self) -> int:
140 """Hash this for an occurrence."""
141 return hash(self.id)
142
143 def __eq__(self, other: Occurrence) -> bool:
144 """self == other"""
145 return self.id == other.id
146
147 def component_name(self) -> str:
148 """The name of this component."""
149 return self._adapter.component_name()
150
151 @property
152 def uid(self) -> str:
153 """The UID of this occurrence."""
154 return self._adapter.uid
155
156 def has_alarm(self, alarm: Alarm) -> bool:
157 """Wether this alarm is in this occurrence."""
158 return alarm in self._adapter.alarms
159
160 @property
161 def recurrence_ids(self) -> RecurrenceIDs:
162 """The recurrence ids."""
163 return self._adapter.recurrence_ids
164
165
166 class AlarmOccurrence(Occurrence):
167 """Adapter for absolute alarms."""
168
169 def __init__(
170 self,
171 trigger: datetime,
172 alarm: Alarm,
173 parent: ComponentAdapter | Occurrence,
174 ) -> None:
175 super().__init__(alarm, trigger, trigger)
176 self.parent = parent
177 self.alarm = alarm
178
179 def as_component(self, keep_recurrence_attributes):
180 """Return the alarm's parent as a modified component."""
181 parent = self.parent.as_component(
182 keep_recurrence_attributes=keep_recurrence_attributes
183 )
184 alarm_once = self.alarm.copy()
185 alarm_once.TRIGGER = self.start
186 alarm_once.REPEAT = 0
187 parent.subcomponents = [alarm_once]
188 return parent
189
190 @cached_property
191 def id(self) -> OccurrenceID:
192 """The id of the component."""
193 return OccurrenceID.from_occurrence(
194 self.parent.component_name(),
195 self.parent.uid,
196 self.parent.recurrence_ids,
197 self.start,
198 )
199
200 def __repr__(self) -> str:
201 """repr(self)"""
202 return (
203 f"<{self.__class__.__name__} at {self.start} of"
204 f" {self.alarm} in {self.parent}"
205 )
206
207
208 __all__ = [
209 "AlarmOccurrence",
210 "Occurrence",
211 "OccurrenceID",
212 ]