nextcloud-client 0.211.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3430 @@
1
+ """CalDAV client for Nextcloud calendar and task operations using caldav library."""
2
+
3
+ import datetime as dt
4
+ import inspect
5
+ import logging
6
+ import re
7
+ import ssl
8
+ import uuid
9
+ from typing import Any
10
+ from urllib.parse import unquote, urlsplit, urlunsplit
11
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
12
+
13
+ import anyio
14
+ import httpx2
15
+ import recurring_ical_events
16
+ from caldav.aio import AsyncCalendar, AsyncDAVClient, AsyncEvent
17
+ from caldav.elements import cdav, dav
18
+ from caldav.lib import error as caldav_error
19
+ from icalendar import Alarm, Calendar, Timezone, vCalAddress, vDDDTypes, vRecur, vText
20
+ from icalendar import Event as ICalEvent
21
+ from icalendar import Todo as ICalTodo
22
+ from lxml import etree # type: ignore[import-untyped] # ty: ignore[import-not-found]
23
+
24
+ from .availability import (
25
+ Span,
26
+ busy_spans_from_events,
27
+ busy_spans_from_vfreebusy,
28
+ daily_windows,
29
+ free_slots,
30
+ parse_time_ranges,
31
+ slot_to_dict,
32
+ to_aware,
33
+ )
34
+ from .dav_errors import DavPreconditionFailed, dav_error_from_response
35
+ from .dav_urls import encode_dav_url
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ # How many calendars to query at once when searching across all of them.
40
+ # Unbounded fan-out would open one connection per calendar; accounts with
41
+ # dozens of calendars would hammer the Nextcloud instance for no gain, since
42
+ # the win is already had after a handful run in parallel.
43
+ CALENDAR_FANOUT = 8
44
+
45
+ # Per-calendar event cap when computing availability. The default listing cap
46
+ # of 50 is fine for "show me what's on", but availability has to see *every*
47
+ # busy event in the window: a dropped event becomes free time that is not free.
48
+ # Bounded all the same, so one pathological calendar cannot pull an unlimited
49
+ # listing into memory.
50
+ AVAILABILITY_EVENT_LIMIT = 1000
51
+
52
+ # Per-calendar match cap for bulk update/delete/move. Same reasoning: the
53
+ # listing default of 50 made a bulk operation silently leave matches untouched.
54
+ BULK_EVENT_LIMIT = 1000
55
+
56
+ # The URI scheme RFC 6638 addresses attendees by.
57
+ _MAILTO = "mailto:"
58
+
59
+
60
+ def _as_list(value: Any) -> list[Any]:
61
+ """Normalise an iCalendar multi-value property to a list.
62
+
63
+ icalendar returns a bare ``vCalAddress`` (a ``str`` subclass) when a
64
+ property occurs once and a list when it occurs several times. Iterating the
65
+ bare value walks its characters, which is how a single attendee used to come
66
+ back as ``"m,a,i,l,t,o,:,..."``.
67
+ """
68
+ if value is None:
69
+ return []
70
+ return list(value) if isinstance(value, list) else [value]
71
+
72
+
73
+ def _address_key(address: Any) -> str:
74
+ """Case-insensitive calendar-user address without the ``mailto:`` scheme."""
75
+ text = str(address).strip()
76
+ if text.lower().startswith(_MAILTO):
77
+ text = text[len(_MAILTO) :]
78
+ return text.lower()
79
+
80
+
81
+ async def _maybe_await(result: Any) -> Any:
82
+ """Await a result if it's a coroutine, otherwise return it directly.
83
+
84
+ caldav v3 uses dual-mode methods that return coroutines for async clients
85
+ but plain objects when the result is already available (e.g. load() on
86
+ already-loaded objects).
87
+ """
88
+ if inspect.isawaitable(result):
89
+ return await result
90
+ return result
91
+
92
+
93
+ # How far back a recurring todo's unfinished backlog is searched. Bounded so an
94
+ # abandoned daily series cannot turn a single todo into thousands of expansions.
95
+ _PENDING_MAX_LOOKBACK = dt.timedelta(days=366 * 3)
96
+
97
+ # An occurrence in one of these states is finished and not part of the backlog.
98
+ _TODO_DONE_STATUSES = frozenset({"COMPLETED", "CANCELLED"})
99
+
100
+ # Fallback VALARM DESCRIPTION per component type. RFC 5545 requires the property
101
+ # on DISPLAY and EMAIL alarms, so a reminder that omits it still needs wording.
102
+ _EVENT_REMINDER_DESCRIPTION = "Event reminder"
103
+ _TODO_REMINDER_DESCRIPTION = "Todo reminder"
104
+
105
+ # The VALARM actions Nextcloud actually schedules (ReminderService::REMINDER_TYPES).
106
+ # RFC 5545 permits other IANA/X- tokens, which it stores but silently ignores.
107
+ _VALARM_ACTIONS = frozenset({"DISPLAY", "EMAIL", "AUDIO"})
108
+
109
+
110
+ def _calendar_is_transparent(response_elem: Any, ns: dict[str, str]) -> bool:
111
+ """Read CalDAV ``schedule-calendar-transp`` from a PROPFIND response.
112
+
113
+ Nextcloud exposes its per-calendar "never show me as busy" switch through
114
+ this property (RFC 4791 5.2.9). The value is an *element*, not text:
115
+ ``<c:schedule-calendar-transp><c:transparent/></c:schedule-calendar-transp>``.
116
+ A missing property means opaque, i.e. the calendar consumes time.
117
+ """
118
+ elem = response_elem.find(".//c:schedule-calendar-transp", ns)
119
+ return elem is not None and elem.find("./c:transparent", ns) is not None
120
+
121
+
122
+ def _rrule_to_string(rrule: Any) -> str:
123
+ """Render an icalendar ``vRecur`` as an RFC 5545 RRULE value.
124
+
125
+ ``str(vRecur)`` yields a Python repr (``vRecur({'FREQ': ['YEARLY']})``),
126
+ which is not a valid RRULE and cannot be fed back into
127
+ ``vRecur.from_ical()`` when a caller round-trips the value into an update.
128
+ """
129
+ if rrule is None:
130
+ return ""
131
+ if isinstance(rrule, list):
132
+ if not rrule:
133
+ return ""
134
+ rrule = rrule[0]
135
+ try:
136
+ return rrule.to_ical().decode("utf-8")
137
+ except AttributeError:
138
+ return str(rrule)
139
+
140
+
141
+ def _shorthand_would_lose(
142
+ stored: list[dict[str, Any]],
143
+ default_description: str,
144
+ default_summary: str,
145
+ ) -> bool:
146
+ """True when the stored alarms carry shape the shorthand cannot express.
147
+
148
+ ``reminder_minutes``/``reminder_email`` rebuild to at most one DISPLAY plus
149
+ one EMAIL, sharing a single whole-minute offset and the default wording. A
150
+ stored set outside that shape — an absolute or sub-minute trigger, several
151
+ distinct offsets, two alarms of the same action, a ``RELATED`` qualifier, a
152
+ custom summary or per-alarm description — cannot survive the rebuild.
153
+
154
+ What the caller is *changing* is deliberately not part of this. A new offset,
155
+ or dropping the EMAIL alarm via ``reminder_email=False``, is the request
156
+ being honoured, not data being lost. Comparing each stored offset against the
157
+ new target made this fire on the most ordinary update there is — nudging a
158
+ reminder's offset — which would have trained the reader to ignore it.
159
+ """
160
+ offsets = {reminder.get("minutes_before") for reminder in stored}
161
+ if len(offsets) > 1:
162
+ return True
163
+
164
+ seen_actions = [reminder.get("action") for reminder in stored]
165
+ if len(seen_actions) != len(set(seen_actions)):
166
+ return True
167
+
168
+ return any(
169
+ "minutes_before" not in reminder
170
+ or reminder.get("action") not in ("DISPLAY", "EMAIL")
171
+ or reminder.get("related")
172
+ # An EMAIL alarm the shorthand itself wrote carries the component title
173
+ # as its subject, so that value is reproducible and not a loss.
174
+ or (reminder.get("summary") or default_summary) != default_summary
175
+ or (reminder.get("description") or default_description) != default_description
176
+ for reminder in stored
177
+ )
178
+
179
+
180
+ def _warn_if_hex_color(color: str) -> None:
181
+ """Warn when a COLOR value will not survive Nextcloud's Calendar UI.
182
+
183
+ RFC 7986 §5.9 defines COLOR as a CSS3 colour *name*, and Nextcloud takes that
184
+ literally: ``getHexForColorName()`` in the Calendar app is a plain
185
+ ``css3Colors[name]`` lookup, so ``#FF0000`` resolves to null and the event
186
+ colour is dropped on display. The property is still written — other CalDAV
187
+ clients may honour it — but the caller deserves to know it will not show up.
188
+ """
189
+ if color.startswith("#"):
190
+ logger.warning(
191
+ "Event color %r is a hex value; Nextcloud's Calendar UI only renders "
192
+ "CSS3 colour names (e.g. 'tomato') and will ignore it",
193
+ color,
194
+ )
195
+
196
+
197
+ def _rrule_with_until(
198
+ rrule_str: str, end_date: str, dtstart: Any, *, replace: bool = False
199
+ ) -> str:
200
+ """Return ``rrule_str`` with an ``UNTIL`` derived from ``end_date``.
201
+
202
+ RFC 5545 §3.3.10 ties UNTIL's value type to DTSTART's: a DATE-valued DTSTART
203
+ (an all-day event) takes a DATE, and anything else takes a UTC date-time —
204
+ including a TZID-bound DTSTART, whose UNTIL must still be expressed in UTC.
205
+ Getting this wrong is not cosmetic; clients drop a recurrence set whose UNTIL
206
+ does not match, so the series silently never ends.
207
+
208
+ ``end_date`` is inclusive-by-day: a date-only value becomes the last moment of
209
+ that day (23:59:59 UTC) for a timed event, so "recur until June 30th" keeps the
210
+ occurrence *on* June 30th rather than dropping it.
211
+
212
+ An existing UNTIL or COUNT raises ``ValueError`` — they are mutually exclusive
213
+ with UNTIL in one rule, and quietly choosing a winner is the silent-ignore
214
+ behaviour this exists to remove. ``replace=True`` drops them instead, for the
215
+ update path: applying an end date to the *stored* rule of an already-bounded
216
+ series means "move the end", not "contradict yourself".
217
+ """
218
+ parts = _rrule_parts_without_bounds(rrule_str, replace=replace)
219
+ all_day = isinstance(dtstart, dt.date) and not isinstance(dtstart, dt.datetime)
220
+ # DTSTART's zone is what "that day" means to the caller, so an end-of-day
221
+ # boundary has to be built in it before being converted to UTC.
222
+ tz = None if all_day else getattr(dtstart, "tzinfo", None)
223
+ until = _format_until(end_date, all_day=all_day, tz=tz)
224
+ return ";".join([*parts, f"UNTIL={until}"])
225
+
226
+
227
+ def _rrule_parts_without_bounds(rrule_str: str, *, replace: bool) -> list[str]:
228
+ """Split an RRULE into parts, dropping or rejecting UNTIL/COUNT."""
229
+ parts = []
230
+ for part in rrule_str.split(";"):
231
+ if not part:
232
+ continue
233
+ name = part.split("=", 1)[0].strip().upper()
234
+ if name not in ("UNTIL", "COUNT"):
235
+ parts.append(part)
236
+ elif not replace:
237
+ raise ValueError(
238
+ f"recurrence_end_date conflicts with {name} already present in "
239
+ f"recurrence_rule ({rrule_str!r}); pass one or the other"
240
+ )
241
+ return parts
242
+
243
+
244
+ def _format_until(end_date: str, *, all_day: bool, tz: dt.tzinfo | None = None) -> str:
245
+ """Render ``end_date`` as an UNTIL value of the type DTSTART requires.
246
+
247
+ ``tz`` is DTSTART's own zone. RFC 5545 requires UNTIL to be *formatted* in
248
+ UTC for a date-time DTSTART, but that is a serialisation rule, not an
249
+ instruction to anchor the boundary to UTC midnight: "until June 30th" means
250
+ the end of June 30th where the event happens. Anchoring in UTC drops the
251
+ last occurrence of any evening event in a zone behind UTC, because its real
252
+ instant falls on the following UTC date — 21:00 in New York on the 30th is
253
+ 01:00 UTC on the 1st, past a ``T235959Z`` cutoff.
254
+ """
255
+ try:
256
+ parsed = dt.datetime.fromisoformat(end_date)
257
+ except ValueError:
258
+ raise ValueError(
259
+ f"recurrence_end_date {end_date!r} is not an ISO 8601 date or datetime"
260
+ ) from None
261
+
262
+ if all_day:
263
+ if end_date != end_date.split("T")[0]:
264
+ # RFC 5545 ties UNTIL's value type to DTSTART's, so an all-day series
265
+ # can only be bounded by a DATE. Dropping the time is the sole
266
+ # correct reading rather than a caller error, hence debug not warn —
267
+ # but it should still be visible to anyone wondering where it went.
268
+ logger.debug(
269
+ "recurrence_end_date %r carries a time of day, which an all-day "
270
+ "series cannot express in UNTIL; using the date alone",
271
+ end_date,
272
+ )
273
+ return parsed.date().strftime("%Y%m%d")
274
+
275
+ if end_date == end_date.split("T")[0]:
276
+ # Date-only input: bound the whole day rather than midnight, which would
277
+ # exclude an occurrence happening later on that date.
278
+ parsed = parsed.replace(hour=23, minute=59, second=59)
279
+ if parsed.tzinfo is None:
280
+ parsed = parsed.replace(tzinfo=tz or dt.UTC)
281
+ return parsed.astimezone(dt.UTC).strftime("%Y%m%dT%H%M%SZ")
282
+
283
+
284
+ def _until_anchor(dtstart: Any, start_str: str | None) -> Any:
285
+ """Return DTSTART as the caller wrote it, for anchoring a date-only UNTIL.
286
+
287
+ A fixed-offset start (``21:00-05:00``) is stored as UTC, so the stored
288
+ DTSTART no longer says which day "until June 30th" ends on. The caller's
289
+ offset still does.
290
+ """
291
+ if isinstance(dtstart, dt.datetime) and start_str:
292
+ caller = dt.datetime.fromisoformat(start_str.replace("Z", "+00:00"))
293
+ if caller.tzinfo is not None:
294
+ return caller
295
+ return dtstart
296
+
297
+
298
+ def _occurrence_is_done(component: Any) -> bool:
299
+ """True when a VTODO occurrence is finished.
300
+
301
+ Clients that materialise recurrences (jtx Board via DAVx5, for one) mark a
302
+ completed instance by writing an override with ``STATUS:COMPLETED``. Some
303
+ leave ``STATUS`` alone and only set ``PERCENT-COMPLETE:100``, so both are
304
+ treated as done.
305
+ """
306
+ status = str(component.get("status") or "").upper()
307
+ if status in _TODO_DONE_STATUSES:
308
+ return True
309
+ try:
310
+ return int(component.get("percent-complete", 0)) >= 100
311
+ except (TypeError, ValueError):
312
+ return False
313
+
314
+
315
+ def _as_utc_datetime(value: dt.date) -> dt.datetime:
316
+ """Normalize a date or datetime to an aware UTC datetime for ordering."""
317
+ if isinstance(value, dt.datetime):
318
+ return value if value.tzinfo else value.replace(tzinfo=dt.UTC)
319
+ return dt.datetime(value.year, value.month, value.day, tzinfo=dt.UTC)
320
+
321
+
322
+ class CalendarClient:
323
+ """Client for Nextcloud CalDAV calendar and task operations."""
324
+
325
+ def __init__(
326
+ self,
327
+ base_url: str,
328
+ username: str,
329
+ *,
330
+ auth_username: str | None = None,
331
+ password: str | None = None,
332
+ token: str | None = None,
333
+ verify: bool | ssl.SSLContext = True,
334
+ ):
335
+ """Initialize CalendarClient with AsyncDAVClient.
336
+
337
+ Pass the raw credential plus an explicit ``auth_type`` so caldav can
338
+ build whichever auth object its active HTTP backend needs. caldav v3
339
+ prefers ``niquests`` over ``httpx2`` and won't accept an ``httpx2.Auth``
340
+ when ``niquests`` is the active backend (issue #731), so we no longer
341
+ accept a pre-built ``httpx2.Auth`` here.
342
+
343
+ Args:
344
+ base_url: Nextcloud base URL
345
+ username: Nextcloud username (UID) used as the DAV path fallback
346
+ auth_username: Credential identity (loginName) the app password
347
+ authenticates against; defaults to ``username``. Differs from
348
+ the UID for OIDC-provisioned users.
349
+ password: App password / login password — selects ``auth_type="basic"``
350
+ token: OAuth bearer token — selects ``auth_type="bearer"``
351
+ verify: TLS verification: False disables it, an SSLContext carries
352
+ a custom CA
353
+
354
+ Pass exactly one of ``password`` or ``token``. Passing neither leaves
355
+ the underlying client unauthenticated.
356
+ """
357
+ self.username = username
358
+ self.base_url = base_url
359
+ # Resolved lazily from the principal on the first write with attendees.
360
+ self._organizer: vCalAddress | None = None
361
+ # The UID (``username``) is the DAV path fallback until principal
362
+ # discovery succeeds; the loginName (``auth_username``) is the
363
+ # credential the app password authenticates against. They differ for
364
+ # OIDC-provisioned users. Defaults to the UID so existing single-user /
365
+ # OAuth callers are unchanged.
366
+ auth_username = auth_username or username
367
+
368
+ auth_kwargs: dict[str, Any] = {}
369
+ if password is not None:
370
+ auth_kwargs = {"password": password, "auth_type": "basic"}
371
+ elif token is not None:
372
+ auth_kwargs = {"password": token, "auth_type": "bearer"}
373
+
374
+ # AsyncDAVClient needs the full base URL for proper URL construction.
375
+ #
376
+ # The X-NC-CalDAV-Webcal-Caching header makes Nextcloud expose external
377
+ # subscriptions (webcal/ICS feeds) as regular, queryable calendars
378
+ # (CachedSubscription) instead of opaque cs:subscribed collections, so
379
+ # their events become readable through the normal event/search tools —
380
+ # the same mechanism desktop clients (Evolution/KDE) rely on (issue #830).
381
+ # list_calendars() overrides this header to "Off" on its own PROPFIND so
382
+ # it can still detect subscriptions and flag them read-only.
383
+ self._dav_client = AsyncDAVClient(
384
+ url=f"{base_url}/remote.php/dav/",
385
+ username=auth_username,
386
+ ssl_verify_cert=verify, # type: ignore[arg-type] # ty: ignore[invalid-argument-type] # caldav types say bool|str but passes through to niquests which accepts SSLContext
387
+ headers={"X-NC-CalDAV-Webcal-Caching": "On"},
388
+ **auth_kwargs,
389
+ )
390
+ self._calendar_home_url = f"{base_url}/remote.php/dav/calendars/{username}/"
391
+ self._principal_resolved = False
392
+
393
+ def _calendar_home_url_from_home_set(self, home_set: Any) -> str | None:
394
+ """Normalize a caldav CalendarSet or URL into an absolute home URL."""
395
+ if home_set is None:
396
+ return None
397
+
398
+ home_url = getattr(home_set, "url", home_set)
399
+ if home_url is None:
400
+ return None
401
+
402
+ home_url = unquote(str(home_url))
403
+ if not home_url:
404
+ return None
405
+ if home_url.startswith("/"):
406
+ # calendar-home-set returns an absolute path that already includes
407
+ # any subpath under which Nextcloud is served (e.g.
408
+ # ``/nextcloud/remote.php/dav/calendars/David/``). Resolve it
409
+ # against the *origin* (scheme + host) of ``base_url`` rather than
410
+ # the full ``base_url`` — concatenating onto a subpath base URL
411
+ # would double the subpath and produce a bogus, unroutable URL
412
+ # (issue #1007).
413
+ origin = urlsplit(self.base_url)
414
+ home_url = urlunsplit((origin.scheme, origin.netloc, home_url, "", ""))
415
+ if not home_url.endswith("/"):
416
+ home_url = f"{home_url}/"
417
+ return home_url
418
+
419
+ async def _calendar_home_url_from_principal(self, principal: Any) -> str | None:
420
+ """Resolve calendar-home-set without using caldav's async-unsafe property."""
421
+ get_property = getattr(principal, "get_property", None)
422
+ if get_property is not None:
423
+ try:
424
+ home_set = await _maybe_await(get_property(cdav.CalendarHomeSet()))
425
+ calendar_home_url = self._calendar_home_url_from_home_set(home_set)
426
+ if calendar_home_url:
427
+ return calendar_home_url
428
+ except (caldav_error.DAVError, AttributeError, TypeError, ValueError) as e:
429
+ logger.warning(
430
+ "CalDAV calendar-home-set discovery failed; deriving from "
431
+ "principal URL: %s",
432
+ e,
433
+ )
434
+
435
+ try:
436
+ home_set = getattr(principal, "calendar_home_set", None)
437
+ home_set = await _maybe_await(home_set)
438
+ return self._calendar_home_url_from_home_set(home_set)
439
+ except (AttributeError, TypeError, ValueError) as e:
440
+ logger.warning(
441
+ "CalDAV calendar-home-set property unavailable; deriving from "
442
+ "principal URL: %s",
443
+ e,
444
+ )
445
+ return None
446
+
447
+ async def _ensure_calendar_home(self) -> None:
448
+ """Discover and cache the authenticated user's CalDAV calendar home."""
449
+ if self._principal_resolved:
450
+ return
451
+
452
+ try:
453
+ get_principal = getattr(self._dav_client, "get_principal", None)
454
+ if get_principal is None:
455
+ principal = await _maybe_await(self._dav_client.principal())
456
+ else:
457
+ principal = await _maybe_await(get_principal())
458
+
459
+ calendar_home_url = await self._calendar_home_url_from_principal(principal)
460
+ if calendar_home_url:
461
+ self._calendar_home_url = calendar_home_url
462
+ self._principal_resolved = True
463
+ return
464
+
465
+ principal_url = getattr(principal, "url", None)
466
+ if principal_url is None:
467
+ raise ValueError("CalDAV principal discovery returned no URL")
468
+ principal_id = unquote(str(principal_url).rstrip("/").split("/")[-1])
469
+ if principal_id:
470
+ self._calendar_home_url = (
471
+ f"{self.base_url}/remote.php/dav/calendars/{principal_id}/"
472
+ )
473
+ self._principal_resolved = True
474
+ except (caldav_error.DAVError, httpx2.HTTPError, ValueError) as e:
475
+ logger.warning(
476
+ "CalDAV principal discovery failed; using username path: %s", e
477
+ )
478
+
479
+ async def _organizer_address(self) -> vCalAddress | None:
480
+ """The authenticated user as an RFC 6638 ``ORGANIZER``, or ``None``.
481
+
482
+ Nextcloud only runs iTIP scheduling (invitations *and* cancellations)
483
+ for an event whose ``ORGANIZER`` is one of the principal's
484
+ ``calendar-user-address-set`` entries. The Calendar web app adds it as
485
+ soon as an attendee is added; a raw CalDAV PUT has to do the same, or a
486
+ later DELETE sends attendees no CANCEL. The address therefore comes from
487
+ the server rather than from configuration, so it always matches.
488
+ """
489
+ cached = getattr(self, "_organizer", None)
490
+ if cached is not None:
491
+ return cached
492
+ try:
493
+ get_principal = getattr(self._dav_client, "get_principal", None)
494
+ principal = await _maybe_await(
495
+ get_principal() if get_principal else self._dav_client.principal()
496
+ )
497
+ addresses = await _maybe_await(principal.calendar_user_address_set())
498
+ mailto = next(
499
+ (a for a in addresses if a and a.lower().startswith(_MAILTO)), None
500
+ )
501
+ if mailto is None:
502
+ logger.warning(
503
+ "Principal has no mailto: calendar-user-address (is an email "
504
+ "set in the Nextcloud profile?); events are created without "
505
+ "ORGANIZER and attendees will not receive cancellations"
506
+ )
507
+ return None
508
+ organizer = vCalAddress(mailto)
509
+ try:
510
+ display_name = await _maybe_await(principal.get_display_name())
511
+ except (caldav_error.DAVError, httpx2.HTTPError, ValueError):
512
+ display_name = None
513
+ if display_name:
514
+ organizer.params["CN"] = vText(display_name)
515
+ self._organizer = organizer
516
+ return organizer
517
+ except (caldav_error.DAVError, httpx2.HTTPError, ValueError) as e:
518
+ logger.warning("Could not resolve ORGANIZER address: %s", e)
519
+ return None
520
+
521
+ @staticmethod
522
+ def _apply_attendees(
523
+ component: Any, attendees_str: str, organizer: vCalAddress | None
524
+ ) -> None:
525
+ """Replace ``component``'s ATTENDEEs from a comma-separated address list.
526
+
527
+ Mirrors the Nextcloud Calendar web app: when there are attendees and an
528
+ organizer is known, ``ORGANIZER`` is set (an existing one is kept) and the
529
+ organizer is listed as an accepted CHAIR. New guests get
530
+ ``PARTSTAT=NEEDS-ACTION;RSVP=TRUE``. Guests that were already on the
531
+ event keep their parameters, so an update does not reset their replies.
532
+ """
533
+ existing = {_address_key(a): a for a in _as_list(component.get("ATTENDEE"))}
534
+ while "ATTENDEE" in component:
535
+ del component["ATTENDEE"]
536
+
537
+ emails: list[str] = []
538
+ for email in attendees_str.split(","):
539
+ email = email.strip()
540
+ if email.lower().startswith(_MAILTO):
541
+ email = email[len(_MAILTO) :]
542
+ if email and email.lower() not in (e.lower() for e in emails):
543
+ emails.append(email)
544
+ if not emails:
545
+ return
546
+
547
+ organizer_key = None
548
+ if "ORGANIZER" in component:
549
+ organizer_key = _address_key(component["ORGANIZER"])
550
+ elif organizer is not None:
551
+ component.add("organizer", organizer)
552
+ organizer_key = _address_key(organizer)
553
+
554
+ if organizer_key and organizer_key not in (e.lower() for e in emails):
555
+ if organizer_key in existing:
556
+ component.add("attendee", existing[organizer_key])
557
+ elif organizer is not None and _address_key(organizer) == organizer_key:
558
+ chair = vCalAddress(str(organizer))
559
+ if "CN" in organizer.params:
560
+ chair.params["CN"] = organizer.params["CN"]
561
+ chair.params["CUTYPE"] = vText("INDIVIDUAL")
562
+ chair.params["ROLE"] = vText("CHAIR")
563
+ chair.params["PARTSTAT"] = vText("ACCEPTED")
564
+ component.add("attendee", chair)
565
+
566
+ for email in emails:
567
+ key = email.lower()
568
+ if key in existing:
569
+ component.add("attendee", existing[key])
570
+ continue
571
+ guest = vCalAddress(f"{_MAILTO}{email}")
572
+ guest.params["CUTYPE"] = vText("INDIVIDUAL")
573
+ if key == organizer_key:
574
+ guest.params["ROLE"] = vText("CHAIR")
575
+ guest.params["PARTSTAT"] = vText("ACCEPTED")
576
+ else:
577
+ guest.params["ROLE"] = vText("REQ-PARTICIPANT")
578
+ guest.params["PARTSTAT"] = vText("NEEDS-ACTION")
579
+ guest.params["RSVP"] = vText("TRUE")
580
+ component.add("attendee", guest)
581
+
582
+ def _get_calendar_url(self, calendar_name: str) -> str:
583
+ """Get the full URL for a calendar.
584
+
585
+ Names arrive decoded or percent-encoded (as they appear in hrefs), so
586
+ normalise to decoded before encoding once. Nextcloud calendar URIs never
587
+ contain a literal ``%``, so the ``unquote`` is lossless in practice.
588
+ """
589
+ return encode_dav_url(f"{self._calendar_home_url}{unquote(calendar_name)}/")
590
+
591
+ def _get_calendar(self, calendar_name: str) -> AsyncCalendar:
592
+ """Get an AsyncCalendar object for the given calendar name."""
593
+ calendar_url = self._get_calendar_url(calendar_name)
594
+ return AsyncCalendar(
595
+ client=self._dav_client, # type: ignore[arg-type] # ty: ignore[invalid-argument-type] # AsyncDAVClient is valid for async mode
596
+ url=calendar_url,
597
+ name=calendar_name,
598
+ )
599
+
600
+ async def _async_object_by_uid(
601
+ self, calendar: AsyncCalendar, uid: str, comp_filter: Any = None
602
+ ) -> Any:
603
+ """Async version of Calendar.get_object_by_uid.
604
+
605
+ Upstream caldav v3's get_object_by_uid is not async-aware: it calls
606
+ search() which returns a coroutine for async clients, then tries to
607
+ iterate the coroutine synchronously. This method properly awaits the
608
+ search result.
609
+ """
610
+ # _hacks="insist" mirrors upstream's Calendar.get_object_by_uid pattern:
611
+ # retries with per-component-type searches if the initial search returns
612
+ # nothing, handling CalDAV servers with incomplete search support.
613
+ items_found = await calendar.search( # type: ignore[misc] # ty: ignore[invalid-await] # dual-mode: returns coroutine for async clients
614
+ uid=uid, xml=comp_filter, post_filter=True, _hacks="insist"
615
+ )
616
+ items_found = [o for o in items_found if o.id == uid]
617
+ if not items_found:
618
+ raise caldav_error.NotFoundError(f"{uid} not found on server")
619
+ return items_found[0]
620
+
621
+ async def close(self):
622
+ """Close the DAV client connection."""
623
+ await self._dav_client.close()
624
+
625
+ async def _wait_for_calendar_propagation(
626
+ self, calendar_name: str, max_attempts: int = 40, initial_delay_ms: int = 100
627
+ ) -> None:
628
+ """Wait for calendar to propagate through Nextcloud's DAV backend.
629
+
630
+ After MKCALENDAR succeeds (201), the calendar may not be immediately queryable
631
+ due to Nextcloud's internal caching/indexing. This polls until it appears.
632
+
633
+ Args:
634
+ calendar_name: Name of the calendar to wait for
635
+ max_attempts: Maximum polling attempts (default: 40)
636
+ initial_delay_ms: Initial delay between attempts in ms (default: 100ms)
637
+ """
638
+ logger.info("Waiting for calendar '%s' to propagate...", calendar_name)
639
+ delay_ms = initial_delay_ms
640
+
641
+ for attempt in range(max_attempts):
642
+ try:
643
+ logger.debug(
644
+ "Attempt %s/%s to find calendar '%s'...",
645
+ attempt + 1,
646
+ max_attempts,
647
+ calendar_name,
648
+ )
649
+ calendars = await self.list_calendars()
650
+ if any(cal["name"] == calendar_name for cal in calendars):
651
+ logger.info(
652
+ "Calendar '%s' became available after %s attempts",
653
+ calendar_name,
654
+ attempt + 1,
655
+ )
656
+ return
657
+ except Exception as e:
658
+ logger.warning(
659
+ "Attempt %s/%s to verify calendar '%s' failed: %s",
660
+ attempt + 1,
661
+ max_attempts,
662
+ calendar_name,
663
+ e,
664
+ )
665
+
666
+ if attempt < max_attempts - 1:
667
+ await anyio.sleep(delay_ms / 1000.0)
668
+ # Exponential backoff: double delay up to 2 seconds max
669
+ delay_ms = min(delay_ms * 2, 2000)
670
+
671
+ logger.error(
672
+ "Calendar '%s' did not become available after %s attempts.",
673
+ calendar_name,
674
+ max_attempts,
675
+ )
676
+
677
+ # ============= Calendar Operations =============
678
+
679
+ async def list_calendars(self) -> list[dict[str, Any]]:
680
+ """List all available calendars for the user.
681
+
682
+ Returns both regular calendars and external read-only subscriptions
683
+ (webcal/ICS feeds). Subscriptions are reported with ``read_only=True``
684
+ and a ``source`` URL pointing at the upstream feed (issue #830).
685
+ """
686
+ await self._ensure_calendar_home()
687
+ # Use custom PROPFIND with CalendarServer namespace (cs:) for calendar-color.
688
+ # caldav library's nsmap lacks "CS" namespace, and its CalendarColor uses
689
+ # Apple iCal namespace which Nextcloud doesn't recognize.
690
+ #
691
+ # cs:source / ical:calendar-color are requested to surface external
692
+ # subscriptions: Nextcloud exposes those as cs:subscribed collections
693
+ # carrying a cs:source href and an Apple-namespace color.
694
+ propfind_body = """<?xml version="1.0" encoding="utf-8"?>
695
+ <d:propfind xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:ical="http://apple.com/ns/ical/">
696
+ <d:prop>
697
+ <d:displayname/>
698
+ <d:resourcetype/>
699
+ <cs:getctag/>
700
+ <c:calendar-description/>
701
+ <cs:calendar-color/>
702
+ <ical:calendar-color/>
703
+ <cs:source/>
704
+ <c:schedule-calendar-transp/>
705
+ </d:prop>
706
+ </d:propfind>"""
707
+
708
+ # Override the client-wide webcal-caching header to "Off" for this
709
+ # PROPFIND so subscriptions are returned as cs:subscribed collections
710
+ # (with cs:source) and can be detected and flagged read-only. With the
711
+ # header "On" they would masquerade as regular calendars, hiding the
712
+ # source URL. Event reads keep the client-wide "On" so they stay
713
+ # queryable (see __init__).
714
+ # Pass the request XML via ``body``, not ``props``: caldav's ``props``
715
+ # expects a list of property *names* and would build its own body
716
+ # (discarding this custom CalendarServer/Apple-namespace markup).
717
+ response = await self._dav_client.propfind(
718
+ # ``_calendar_home_url`` is stored decoded (see
719
+ # ``_calendar_home_url_from_home_set``), so encode it here like
720
+ # every other URL this client puts on the wire, rather than relying
721
+ # on the HTTP layer to normalise a space for us.
722
+ encode_dav_url(self._calendar_home_url),
723
+ body=propfind_body,
724
+ depth=1,
725
+ headers={"X-NC-CalDAV-Webcal-Caching": "Off"},
726
+ )
727
+
728
+ result = []
729
+
730
+ # Parse XML response
731
+ tree = etree.fromstring(response.raw.encode("utf-8"))
732
+ ns = {
733
+ "d": "DAV:",
734
+ "cs": "http://calendarserver.org/ns/",
735
+ "c": "urn:ietf:params:xml:ns:caldav",
736
+ "ical": "http://apple.com/ns/ical/",
737
+ }
738
+
739
+ for response_elem in tree.findall(".//d:response", ns):
740
+ # A response is a calendar if it is a regular calendar collection
741
+ # (c:calendar) or an external subscription (cs:subscribed).
742
+ resourcetype = response_elem.find(".//d:resourcetype", ns)
743
+ if resourcetype is None:
744
+ continue
745
+ is_calendar = resourcetype.find(".//c:calendar", ns) is not None
746
+ is_subscribed = resourcetype.find(".//cs:subscribed", ns) is not None
747
+ if not (is_calendar or is_subscribed):
748
+ continue
749
+
750
+ href = response_elem.find("./d:href", ns)
751
+ if href is None or not href.text:
752
+ continue
753
+
754
+ calendar_url = href.text
755
+ # Extract calendar name from URL
756
+ calendar_name = unquote(calendar_url.rstrip("/").split("/")[-1])
757
+
758
+ # Skip if this is the calendar home itself
759
+ if calendar_url.rstrip("/") == self._calendar_home_url.rstrip("/"):
760
+ continue
761
+
762
+ display_name_elem = response_elem.find(".//d:displayname", ns)
763
+ display_name = (
764
+ display_name_elem.text
765
+ if display_name_elem is not None and display_name_elem.text
766
+ else calendar_name
767
+ )
768
+
769
+ description_elem = response_elem.find(".//c:calendar-description", ns)
770
+ description = (
771
+ description_elem.text
772
+ if description_elem is not None and description_elem.text
773
+ else ""
774
+ )
775
+
776
+ # Regular calendars expose cs:calendar-color; subscriptions store
777
+ # their color under the Apple iCal namespace.
778
+ color_elem = response_elem.find(".//cs:calendar-color", ns)
779
+ if color_elem is None or not color_elem.text:
780
+ color_elem = response_elem.find(".//ical:calendar-color", ns)
781
+ color = (
782
+ color_elem.text
783
+ if color_elem is not None and color_elem.text
784
+ else "#1976D2"
785
+ )
786
+
787
+ # External subscriptions carry a cs:source href pointing at the
788
+ # upstream feed and are read-only.
789
+ source = None
790
+ source_elem = response_elem.find(".//cs:source", ns)
791
+ if source_elem is not None:
792
+ source_href = source_elem.find("./d:href", ns)
793
+ if source_href is not None and source_href.text:
794
+ source = source_href.text
795
+ elif source_elem.text and source_elem.text.strip():
796
+ source = source_elem.text.strip()
797
+
798
+ transparent = _calendar_is_transparent(response_elem, ns)
799
+
800
+ result.append(
801
+ {
802
+ "name": calendar_name,
803
+ "display_name": display_name,
804
+ "description": description,
805
+ "color": color,
806
+ "href": calendar_url,
807
+ "read_only": is_subscribed,
808
+ "source": source,
809
+ "transparent": transparent,
810
+ }
811
+ )
812
+
813
+ logger.debug("Found %s calendars", len(result))
814
+ return result
815
+
816
+ async def create_calendar(
817
+ self,
818
+ calendar_name: str,
819
+ display_name: str = "",
820
+ description: str = "",
821
+ color: str = "#1976D2",
822
+ ) -> dict[str, Any]:
823
+ """Create a new calendar with retry on 429 errors."""
824
+ await self._ensure_calendar_home()
825
+ # Use custom MKCALENDAR XML instead of caldav library's make_calendar() due to:
826
+ # 1. Missing CalendarServer namespace (cs:) in caldav's nsmap
827
+ # 2. caldav's CalendarColor uses Apple iCal namespace, not cs:calendar-color
828
+ # 3. make_calendar() doesn't support calendar-description or calendar-color params
829
+ calendar_url = self._get_calendar_url(calendar_name)
830
+
831
+ mkcalendar_body = f"""<?xml version="1.0" encoding="utf-8"?>
832
+ <mkcalendar xmlns="urn:ietf:params:xml:ns:caldav" xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/">
833
+ <d:set>
834
+ <d:prop>
835
+ <d:displayname>{display_name or calendar_name}</d:displayname>
836
+ <cs:calendar-color>{color}</cs:calendar-color>
837
+ <caldav:calendar-description xmlns:caldav="urn:ietf:params:xml:ns:caldav">{description}</caldav:calendar-description>
838
+ <caldav:supported-calendar-component-set xmlns:caldav="urn:ietf:params:xml:ns:caldav">
839
+ <caldav:comp name="VEVENT"/>
840
+ <caldav:comp name="VTODO"/>
841
+ </caldav:supported-calendar-component-set>
842
+ </d:prop>
843
+ </d:set>
844
+ </mkcalendar>"""
845
+
846
+ # Create calendar via MKCALENDAR request
847
+ response = await self._dav_client.mkcalendar(calendar_url, mkcalendar_body)
848
+
849
+ if response.status != 201:
850
+ raise RuntimeError(
851
+ f"Failed to create calendar '{calendar_name}': HTTP {response.status}"
852
+ )
853
+
854
+ logger.debug("Created calendar: %s", calendar_name)
855
+
856
+ # Wait for calendar to be queryable (Nextcloud eventual consistency)
857
+ await self._wait_for_calendar_propagation(calendar_name)
858
+
859
+ return {
860
+ "name": calendar_name,
861
+ "display_name": display_name or calendar_name,
862
+ "description": description,
863
+ "color": color,
864
+ "status_code": 201,
865
+ }
866
+
867
+ async def delete_calendar(self, calendar_name: str) -> dict[str, Any]:
868
+ """Delete a calendar."""
869
+ await self._ensure_calendar_home()
870
+ # Use absolute URL for deletion
871
+ calendar_url = self._get_calendar_url(calendar_name)
872
+ await self._dav_client.delete(calendar_url)
873
+
874
+ logger.debug("Deleted calendar: %s", calendar_name)
875
+ return {"status_code": 204}
876
+
877
+ # ============= Event Operations =============
878
+
879
+ async def get_calendar_events(
880
+ self,
881
+ calendar_name: str,
882
+ start_datetime: dt.datetime | None = None,
883
+ end_datetime: dt.datetime | None = None,
884
+ limit: int = 50,
885
+ filters: dict[str, Any] | None = None,
886
+ ) -> list[dict[str, Any]]:
887
+ """List events in a calendar within date range.
888
+
889
+ ``filters`` are applied *before* ``limit``, and the cut keeps the
890
+ earliest events by start. Truncating first (in CalDAV response order)
891
+ made a filtered search silently miss matches past the first ``limit``
892
+ events (GH #1774).
893
+ """
894
+ await self._ensure_calendar_home()
895
+ calendar = self._get_calendar(calendar_name)
896
+
897
+ if start_datetime or end_datetime:
898
+ events = await self._search_events_by_date(
899
+ calendar, start_datetime, end_datetime
900
+ )
901
+ # Client-side recurrence expansion preserves DTSTART format
902
+ # (floating / TZID / UTC). RFC 4791 <C:expand> would normalize
903
+ # everything to UTC and erase the original timezone context.
904
+ do_expand = bool(start_datetime and end_datetime)
905
+ # The REPORT above asks for getetag, so the objects carry their own.
906
+ fallback_etags: dict[str, str] = {}
907
+ else:
908
+ events = await calendar.events() # type: ignore[misc] # ty: ignore[invalid-await] # dual-mode
909
+ do_expand = False
910
+ # caldav's events() asks for calendar-data only (verified: .etag is
911
+ # None on every object it returns), so without this the unfiltered
912
+ # listing would pay one PROPFIND per event -- the same 1 + N the
913
+ # date-range path and list_todos were fixed for. One batched
914
+ # collection PROPFIND covers the whole result set.
915
+ fallback_etags = await self._collection_etags(calendar)
916
+
917
+ result = []
918
+ for event in events:
919
+ await _maybe_await(event.load(only_if_unloaded=True))
920
+ if not event.data:
921
+ continue
922
+
923
+ try:
924
+ cal = Calendar.from_ical(event.data)
925
+ except Exception as e:
926
+ logger.error("Error parsing iCalendar event: %s", e)
927
+ continue
928
+
929
+ href = str(event.url)
930
+ # One ETag per stored object: expanded recurrence instances are
931
+ # views of the same resource, so a conditional write against any of
932
+ # them targets that one object. Both sources are per-listing, never
933
+ # per-event -- see the branch above.
934
+ etag = event.etag or fallback_etags.get(unquote(urlsplit(href).path), "")
935
+ event_dicts = self._expand_event_occurrences(
936
+ cal, start_datetime, end_datetime, do_expand
937
+ )
938
+ for event_dict in event_dicts:
939
+ if filters and not self._event_matches_filters(event_dict, filters):
940
+ continue
941
+ event_dict["href"] = href
942
+ event_dict["etag"] = etag
943
+ result.append(event_dict)
944
+
945
+ # The whole window is scanned on purpose (no early break at ``limit``):
946
+ # "earliest N matches" needs every match before the cut.
947
+ # ponytail: ISO strings sort lexicographically, so all-day dates and
948
+ # differing UTC offsets order approximately; parse to instants if that matters.
949
+ result.sort(key=lambda e: e.get("start_datetime", ""))
950
+ if len(result) > limit:
951
+ # Leaves a trace when a cap bites -- notably BULK_EVENT_LIMIT, whose
952
+ # callers have no ``truncated`` field to report it through.
953
+ logger.info(
954
+ "Calendar %s: %d events matched, keeping the earliest %d",
955
+ calendar_name,
956
+ len(result),
957
+ limit,
958
+ )
959
+ return result[:limit]
960
+
961
+ def _expand_event_occurrences(
962
+ self,
963
+ cal: Any,
964
+ start_datetime: dt.datetime | None,
965
+ end_datetime: dt.datetime | None,
966
+ do_expand: bool,
967
+ ) -> list[dict[str, Any]]:
968
+ """Return one event dict per occurrence in [start, end), or one dict for the master VEVENT.
969
+
970
+ When ``do_expand`` is true and the resource has an RRULE, expand recurrences
971
+ client-side using ``recurring_ical_events`` so that TZID and floating-local
972
+ semantics are preserved on the wire (server-side ``<C:expand>`` would
973
+ UTC-normalize every DTSTART per RFC 4791 §9.6.5).
974
+ """
975
+ if not do_expand:
976
+ for component in cal.walk("VEVENT"):
977
+ return [self._extract_vevent_data(component)]
978
+ return []
979
+
980
+ has_rrule = any("rrule" in component for component in cal.walk("VEVENT"))
981
+ if not has_rrule:
982
+ for component in cal.walk("VEVENT"):
983
+ return [self._extract_vevent_data(component)]
984
+ return []
985
+
986
+ if start_datetime is None or end_datetime is None:
987
+ # Expansion needs a window. Checked before the try rather than
988
+ # asserted inside it, where the except would have reported a
989
+ # caller error as a failed expansion (python:S5779).
990
+ logger.warning(
991
+ "Recurrence expansion requested without a date window; "
992
+ "returning master event"
993
+ )
994
+ return [
995
+ self._extract_vevent_data(component) for component in cal.walk("VEVENT")
996
+ ]
997
+
998
+ try:
999
+ occurrences = recurring_ical_events.of(cal).between(
1000
+ start_datetime, end_datetime
1001
+ )
1002
+ except Exception as e:
1003
+ logger.warning(
1004
+ "Client-side recurrence expansion failed (%s); returning master event",
1005
+ e,
1006
+ )
1007
+ return [
1008
+ self._extract_vevent_data(component) for component in cal.walk("VEVENT")
1009
+ ]
1010
+
1011
+ return [self._extract_vevent_data(occ) for occ in occurrences]
1012
+
1013
+ async def _search_events_by_date(
1014
+ self,
1015
+ calendar: AsyncCalendar,
1016
+ start_datetime: dt.datetime | None = None,
1017
+ end_datetime: dt.datetime | None = None,
1018
+ ) -> list:
1019
+ """Execute a CalDAV REPORT with time-range filter.
1020
+
1021
+ Returns raw VEVENT resources (no server-side ``<C:expand>``). The caller
1022
+ is responsible for expanding recurring events client-side so that
1023
+ TZID/floating semantics are preserved.
1024
+ """
1025
+ # Ensure naive datetimes are treated as UTC for the wire-level filter
1026
+ if start_datetime and start_datetime.tzinfo is None:
1027
+ start_datetime = start_datetime.replace(tzinfo=dt.UTC)
1028
+ if end_datetime and end_datetime.tzinfo is None:
1029
+ end_datetime = end_datetime.replace(tzinfo=dt.UTC)
1030
+
1031
+ # Build comp-filter with time-range (mirrors sync Calendar.build_search_xml_query)
1032
+ inner_comp_filter = cdav.CompFilter(name="VEVENT")
1033
+ inner_comp_filter += cdav.TimeRange(start_datetime, end_datetime)
1034
+ outer_comp_filter = cdav.CompFilter(name="VCALENDAR") + inner_comp_filter
1035
+ filter_element = cdav.Filter() + outer_comp_filter
1036
+
1037
+ # Ask for the ETag alongside the calendar data. The REPORT is the hot
1038
+ # path for "list events in a range", and objects built from it are
1039
+ # already loaded -- so without getetag here, surfacing an ETag per event
1040
+ # would fall back to one PROPFIND *each*, turning a single REPORT into
1041
+ # 1 + N requests.
1042
+ data = cdav.CalendarData()
1043
+ query = (
1044
+ cdav.CalendarQuery() + [dav.Prop() + data + dav.GetEtag()] + filter_element
1045
+ )
1046
+
1047
+ body = etree.tostring(
1048
+ query.xmlelement(), encoding="utf-8", xml_declaration=True
1049
+ )
1050
+ assert calendar.client is not None
1051
+ response = await calendar.client.report(str(calendar.url), body, depth=1) # type: ignore[misc] # ty: ignore[invalid-await] # dual-mode
1052
+
1053
+ # Parse response (same pattern as AsyncCalendar.search)
1054
+ objects = []
1055
+ response_data = response.expand_simple_props(
1056
+ [cdav.CalendarData(), dav.GetEtag()]
1057
+ )
1058
+ for href, props in response_data.items():
1059
+ if href == str(calendar.url):
1060
+ continue
1061
+ cal_data = props.get(cdav.CalendarData.tag)
1062
+ if cal_data:
1063
+ etag = props.get(dav.GetEtag.tag)
1064
+ obj = AsyncEvent(
1065
+ client=calendar.client,
1066
+ url=calendar.url.join(encode_dav_url(href)), # type: ignore[union-attr] # ty: ignore[missing-union-attribute] # url is always set for calendars
1067
+ data=cal_data,
1068
+ parent=calendar,
1069
+ # caldav's ``etag`` property reads straight from ``props``,
1070
+ # so seeding it here is what keeps _object_etag off the
1071
+ # PROPFIND fallback.
1072
+ props={dav.GetEtag.tag: etag} if etag else None,
1073
+ )
1074
+ objects.append(obj)
1075
+
1076
+ return objects
1077
+
1078
+ async def create_event(
1079
+ self, calendar_name: str, event_data: dict[str, Any]
1080
+ ) -> dict[str, Any]:
1081
+ """Create a new calendar event."""
1082
+ await self._ensure_calendar_home()
1083
+ calendar = self._get_calendar(calendar_name)
1084
+
1085
+ event_uid = str(uuid.uuid4())
1086
+ organizer = (
1087
+ await self._organizer_address() if event_data.get("attendees") else None
1088
+ )
1089
+ ical_content = self._create_ical_event(
1090
+ event_data, event_uid, organizer=organizer
1091
+ )
1092
+
1093
+ # caldav v3's _async_put raises PutError on HTTP failure
1094
+ event = await calendar.save_event(ical=ical_content) # type: ignore[misc] # ty: ignore[invalid-await] # dual-mode
1095
+
1096
+ logger.debug("Created event %s", event_uid)
1097
+
1098
+ return {
1099
+ "uid": event_uid,
1100
+ "href": str(event.url),
1101
+ "etag": await self._object_etag(event),
1102
+ "status_code": 201,
1103
+ }
1104
+
1105
+ async def update_event(
1106
+ self,
1107
+ calendar_name: str,
1108
+ event_uid: str,
1109
+ event_data: dict[str, Any],
1110
+ etag: str = "",
1111
+ ) -> dict[str, Any]:
1112
+ """Update an existing calendar event.
1113
+
1114
+ Args:
1115
+ etag: The ETag the caller last read. The write is refused with
1116
+ :class:`DavPreconditionFailed` if the event changed since. When
1117
+ omitted, the ETag observed during this call's own read is used,
1118
+ which still closes the read-modify-write window opened here.
1119
+
1120
+ Raises:
1121
+ DavPreconditionFailed: If the event changed since ``etag`` was read.
1122
+ """
1123
+ await self._ensure_calendar_home()
1124
+ calendar = self._get_calendar(calendar_name)
1125
+
1126
+ # Find the event by UID using caldav library
1127
+ event = await self._async_object_by_uid(
1128
+ calendar, event_uid, cdav.CompFilter("VEVENT")
1129
+ )
1130
+ await _maybe_await(event.load(only_if_unloaded=True))
1131
+
1132
+ # The caller's ETag wins: it is their concurrency assertion, covering
1133
+ # the whole read-modify-write cycle rather than just our own read.
1134
+ # Matches the rule the contacts client already follows.
1135
+ if not etag:
1136
+ etag = await self._object_etag(event)
1137
+
1138
+ # Merge updates into existing iCal data. An event stored with attendees
1139
+ # but no ORGANIZER (written before #1497) gets one on any update, so a
1140
+ # later delete still sends attendees a CANCEL.
1141
+ stored = str(event.data or "")
1142
+ needs_organizer = bool(event_data.get("attendees")) or (
1143
+ "ATTENDEE" in stored and "ORGANIZER" not in stored
1144
+ )
1145
+ organizer = await self._organizer_address() if needs_organizer else None
1146
+ updated_ical = self._merge_ical_properties(
1147
+ event.data, # type: ignore[arg-type]
1148
+ event_data,
1149
+ organizer=organizer,
1150
+ )
1151
+
1152
+ new_etag = await self._conditional_put(
1153
+ event, updated_ical, etag, kind="event", uid=event_uid
1154
+ )
1155
+
1156
+ logger.debug("Updated event %s", event_uid)
1157
+ return {
1158
+ "uid": event_uid,
1159
+ "href": str(event.url),
1160
+ "etag": new_etag,
1161
+ "status_code": 200,
1162
+ }
1163
+
1164
+ @staticmethod
1165
+ def _status_from_dav_error(exc: caldav_error.DAVError) -> int | None:
1166
+ """Best-effort HTTP status from a caldav DAVError, or ``None``.
1167
+
1168
+ caldav offers nothing structured here. ``_post_delete`` raises
1169
+ ``DeleteError(errmsg(r))``, and ``errmsg`` formats
1170
+ ``"<status> <reason>\\n\\n<body>"`` — which lands in the exception's
1171
+ ``url`` slot, because ``DAVError.__init__``'s first positional parameter
1172
+ is ``url``. So the status is the leading integer of ``exc.url``, with
1173
+ ``str(exc)`` as a fallback in case a future caldav populates it properly.
1174
+
1175
+ Returns ``None`` when nothing parses; callers must treat that as an
1176
+ unknown refusal rather than substituting a plausible-looking code.
1177
+ """
1178
+ for candidate in (getattr(exc, "url", None), str(exc)):
1179
+ if not candidate:
1180
+ continue
1181
+ match = re.search(r"\b(\d{3})\b", str(candidate))
1182
+ if match:
1183
+ return int(match.group(1))
1184
+ return None
1185
+
1186
+ @staticmethod
1187
+ async def _object_etag(obj: Any) -> str:
1188
+ """Return *obj*'s current strong ETag, or ``""`` if the server withheld one.
1189
+
1190
+ ``load()`` already populates ``{DAV:}getetag`` from the GET response
1191
+ (verified against Nextcloud 32.0.14), so the common path costs no extra
1192
+ request. The PROPFIND is the fallback for an object reached without a
1193
+ load.
1194
+ """
1195
+ etag = obj.etag
1196
+ if etag:
1197
+ return etag
1198
+
1199
+ try:
1200
+ props = await obj.get_properties([dav.GetEtag()])
1201
+ except Exception as e:
1202
+ # An ETag is an optimisation for the caller, not a precondition for
1203
+ # returning the object they asked for. Failing the read because the
1204
+ # concurrency token could not be fetched would be a worse trade.
1205
+ logger.debug("Could not fetch etag for %s: %s", obj.url, e)
1206
+ return ""
1207
+
1208
+ return props.get(dav.GetEtag.tag) or ""
1209
+
1210
+ async def _collection_etags(self, calendar: Any) -> dict[str, str]:
1211
+ """Map decoded href path -> ETag for every object in *calendar*.
1212
+
1213
+ One ``PROPFIND`` (Depth 1, ``getetag`` only) instead of one per object.
1214
+ Mirrors the lightweight ctag/etag PROPFIND the contacts client already
1215
+ uses. Returns ``{}`` on failure -- an ETag is a token for the caller,
1216
+ not a reason to fail the listing that produced it.
1217
+ """
1218
+ body = (
1219
+ '<?xml version="1.0" encoding="utf-8"?>'
1220
+ '<d:propfind xmlns:d="DAV:"><d:prop><d:getetag/></d:prop></d:propfind>'
1221
+ )
1222
+
1223
+ try:
1224
+ response = await self._dav_client.request(
1225
+ str(calendar.url), "PROPFIND", body, {"Depth": "1"}
1226
+ )
1227
+ # Depth 1 includes the collection's own href. Unlike the REPORT
1228
+ # parser, this does not skip it: nothing ever looks the collection
1229
+ # up (only object hrefs are queried), and a collection ctag in the
1230
+ # map is inert. Left in rather than filtered so this stays a plain
1231
+ # transcription of the response.
1232
+ return {
1233
+ unquote(urlsplit(href).path): etag
1234
+ for href, props in response.expand_simple_props([dav.GetEtag()]).items()
1235
+ if (etag := props.get(dav.GetEtag.tag))
1236
+ }
1237
+ except Exception as e:
1238
+ logger.debug("Collection etag PROPFIND failed for %s: %s", calendar.url, e)
1239
+ return {}
1240
+
1241
+ async def _conditional_put(
1242
+ self, obj: Any, ical: str, etag: str, *, kind: str, uid: str
1243
+ ) -> str:
1244
+ """PUT *ical* over *obj*, guarded by ``If-Match``. Returns the new ETag.
1245
+
1246
+ ``caldav``'s own ``save()`` sends no ``If-Match``, so two concurrent
1247
+ updates silently last-write-win. It also *returns* a 412 rather than
1248
+ raising, so the status is checked here explicitly.
1249
+
1250
+ Raises:
1251
+ DavPreconditionFailed: If the object changed since *etag* was read.
1252
+ HTTPStatusError: For any other refusal.
1253
+ """
1254
+ url = str(obj.url)
1255
+ headers = {"Content-Type": "text/calendar; charset=utf-8"}
1256
+ if etag:
1257
+ headers["If-Match"] = etag
1258
+
1259
+ response = await self._dav_client.put(url, ical, headers)
1260
+ status = response.status
1261
+
1262
+ if status >= 400:
1263
+ logger.warning(
1264
+ "Conditional PUT of %s %s refused with %s", kind, uid, status
1265
+ )
1266
+ raise dav_error_from_response(
1267
+ status, method="PUT", url=url, body=getattr(response, "raw", b"") or b""
1268
+ )
1269
+
1270
+ # Nextcloud returns the new ETag on the write, so the caller can chain
1271
+ # another conditional update without re-reading.
1272
+ return response.headers.get("etag", "")
1273
+
1274
+ async def _delete_dav_object(
1275
+ self,
1276
+ calendar_name: str,
1277
+ uid: str,
1278
+ comp_filter: Any,
1279
+ kind: str,
1280
+ ) -> dict[str, Any]:
1281
+ """Delete one CalDAV object, mapping refusals to a structured result.
1282
+
1283
+ Only ``NotFoundError`` used to be caught, so a 403 (Nextcloud refuses to
1284
+ delete iMIP/scheduled objects) or a 409/412 (a stale entry in the calendar
1285
+ trashbin colliding with the delete) escaped as a raw caldav traceback out
1286
+ of the MCP tool.
1287
+
1288
+ Only ``DeleteError`` is treated as a refusal: it is precisely what
1289
+ ``DAVObject._post_delete`` raises when the server rejects the DELETE.
1290
+ caldav's other error classes are flat siblings under ``DAVError``, not
1291
+ subclasses of it, so ``AuthorizationError`` (expired credential) and
1292
+ ``RateLimitError`` (retryable) keep propagating instead of being flattened
1293
+ into a per-object "the server refused this event" message. Catching the
1294
+ ``DAVError`` base would have masked exactly those.
1295
+ """
1296
+ await self._ensure_calendar_home()
1297
+ calendar = self._get_calendar(calendar_name)
1298
+
1299
+ try:
1300
+ obj = await self._async_object_by_uid(calendar, uid, comp_filter)
1301
+ await _maybe_await(obj.delete())
1302
+ logger.debug("Deleted %s %s", kind, uid)
1303
+ return {"success": True, "status_code": 204}
1304
+ except caldav_error.NotFoundError as e:
1305
+ logger.debug("%s %s not found: %s", kind.capitalize(), uid, e)
1306
+ return {"success": True, "status_code": 404}
1307
+ except caldav_error.DeleteError as e:
1308
+ status = self._status_from_dav_error(e)
1309
+ logger.warning(
1310
+ "Server refused to delete %s %s (status %s)",
1311
+ kind,
1312
+ uid,
1313
+ status if status is not None else "unknown",
1314
+ )
1315
+ return {
1316
+ "success": False,
1317
+ "status_code": status if status is not None else 500,
1318
+ "message": self._delete_refusal_message(status, kind),
1319
+ "reason": str(e),
1320
+ }
1321
+
1322
+ @staticmethod
1323
+ def _delete_refusal_message(status: int | None, kind: str) -> str:
1324
+ """Explain a delete refusal in terms of its likely cause."""
1325
+ if status == 403:
1326
+ return (
1327
+ f"The server refused to delete this {kind}. Nextcloud rejects "
1328
+ "deletion of scheduled (iMIP) objects — if you are an attendee, "
1329
+ "decline the invitation instead; if you are the organizer, cancel "
1330
+ "it so attendees are notified."
1331
+ )
1332
+ if status in (409, 412, 500):
1333
+ return (
1334
+ f"The server refused to delete this {kind}, most likely because a "
1335
+ "previously-deleted object with the same UID is still in the "
1336
+ "calendar trashbin. Empty the trashbin in the Nextcloud Calendar "
1337
+ "UI and retry."
1338
+ )
1339
+ return f"The server refused to delete this {kind}" + (
1340
+ f" (HTTP {status})." if status is not None else "."
1341
+ )
1342
+
1343
+ async def delete_event(self, calendar_name: str, event_uid: str) -> dict[str, Any]:
1344
+ """Delete a calendar event.
1345
+
1346
+ Returns a structured result rather than raising on a server refusal —
1347
+ see :meth:`_delete_dav_object`.
1348
+ """
1349
+ return await self._delete_dav_object(
1350
+ calendar_name, event_uid, cdav.CompFilter("VEVENT"), "event"
1351
+ )
1352
+
1353
+ async def get_event(
1354
+ self, calendar_name: str, event_uid: str
1355
+ ) -> tuple[dict[str, Any], str]:
1356
+ """Get detailed information about a specific event."""
1357
+ await self._ensure_calendar_home()
1358
+ calendar = self._get_calendar(calendar_name)
1359
+
1360
+ event = await self._async_object_by_uid(
1361
+ calendar, event_uid, cdav.CompFilter("VEVENT")
1362
+ )
1363
+ await _maybe_await(event.load(only_if_unloaded=True))
1364
+
1365
+ event_data = self._parse_ical_event(event.data) if event.data else None # type: ignore[arg-type]
1366
+ if not event_data:
1367
+ raise ValueError(f"Failed to parse event data for {event_uid}")
1368
+
1369
+ etag = await self._object_etag(event)
1370
+ event_data["href"] = str(event.url)
1371
+ event_data["etag"] = etag
1372
+
1373
+ logger.debug("Retrieved event %s", event_uid)
1374
+ return event_data, etag
1375
+
1376
+ async def _events_from_calendar(
1377
+ self,
1378
+ calendar: dict[str, Any],
1379
+ start_datetime: dt.datetime | None,
1380
+ end_datetime: dt.datetime | None,
1381
+ filters: dict[str, Any] | None,
1382
+ limiter: anyio.CapacityLimiter,
1383
+ slots: list[list[dict[str, Any]]],
1384
+ index: int,
1385
+ limit: int = 50,
1386
+ failures: list[dict[str, str]] | None = None,
1387
+ ) -> None:
1388
+ """One calendar's events, annotated, written into its own slot.
1389
+
1390
+ Failure is contained per calendar: a single unreachable or broken
1391
+ calendar is logged and skipped, exactly as in the previous serial
1392
+ loop, rather than cancelling the whole task group. ``failures``, when
1393
+ given, collects what was skipped so a caller that cannot tolerate a
1394
+ partial listing can say so -- an empty slot is indistinguishable from
1395
+ a calendar that really had no events.
1396
+ """
1397
+ async with limiter:
1398
+ try:
1399
+ events = await self.get_calendar_events(
1400
+ calendar["name"],
1401
+ start_datetime,
1402
+ end_datetime,
1403
+ limit=limit,
1404
+ filters=filters,
1405
+ )
1406
+ except Exception as e:
1407
+ logger.warning(
1408
+ "Error getting events from calendar %s: %s", calendar["name"], e
1409
+ )
1410
+ if failures is not None:
1411
+ failures.append(
1412
+ {"calendar_name": calendar["name"], "error": str(e)}
1413
+ )
1414
+ return
1415
+
1416
+ # Add calendar info to each event
1417
+ for event in events:
1418
+ event["calendar_name"] = calendar["name"]
1419
+ event["calendar_display_name"] = calendar.get(
1420
+ "display_name", calendar["name"]
1421
+ )
1422
+ # The calendar's own "never show me as busy" switch. Carried per
1423
+ # event because availability works on a flat event list and would
1424
+ # otherwise have to re-resolve which calendar each one came from.
1425
+ event["calendar_transparent"] = calendar.get("transparent", False)
1426
+
1427
+ slots[index] = events
1428
+
1429
+ async def search_events_across_calendars(
1430
+ self,
1431
+ start_datetime: dt.datetime | None = None,
1432
+ end_datetime: dt.datetime | None = None,
1433
+ filters: dict[str, Any] | None = None,
1434
+ limit: int = 50,
1435
+ strict: bool = False,
1436
+ failures: list[dict[str, str]] | None = None,
1437
+ ) -> list[dict[str, Any]]:
1438
+ """Search events across all calendars with advanced filtering.
1439
+
1440
+ ``limit`` is per calendar (applied after ``filters``, keeping the
1441
+ earliest events), and truncation is silent -- callers that
1442
+ need every event in the window (availability, above all) must raise it
1443
+ rather than accept a listing that merely looks complete.
1444
+
1445
+ ``strict`` decides what an unreadable calendar means. A listing can
1446
+ reasonably show what it could reach, so the default keeps the
1447
+ skip-and-warn behaviour. Availability cannot: a calendar that failed to
1448
+ load contributes no busy time and therefore reads as free, which is the
1449
+ confidently-wrong answer this whole path exists to avoid. Such a caller
1450
+ passes ``strict=True`` and gets a ``ValueError`` naming the calendars.
1451
+ A lenient caller can pass a ``failures`` list to learn which calendars
1452
+ were skipped (``{"calendar_name", "error"}`` dicts).
1453
+
1454
+ The per-calendar REPORTs are fanned out via ``anyio.create_task_group``
1455
+ instead of awaited one after another. The serial loop cost one full
1456
+ round trip per calendar, so the runtime grew linearly with the number
1457
+ of calendars while barely depending on how many events came back --
1458
+ measured against a real account with 21 calendars, a one-day window
1459
+ took 2.73 s and a 180-day window 2.93 s. The time was round trips, not
1460
+ data.
1461
+
1462
+ Concurrency is bounded by ``CALENDAR_FANOUT``: an account with a
1463
+ hundred calendars should not open a hundred simultaneous connections
1464
+ to the Nextcloud instance.
1465
+
1466
+ Results are written into pre-allocated slots rather than appended, so
1467
+ the returned order still follows the calendar order and does not
1468
+ depend on which REPORT happens to finish first.
1469
+ """
1470
+ await self._ensure_calendar_home()
1471
+ if failures is None:
1472
+ failures = []
1473
+ try:
1474
+ calendars = await self.list_calendars()
1475
+ slots: list[list[dict[str, Any]]] = [[] for _ in calendars]
1476
+ limiter = anyio.CapacityLimiter(CALENDAR_FANOUT)
1477
+
1478
+ async with anyio.create_task_group() as tg:
1479
+ for index, calendar in enumerate(calendars):
1480
+ tg.start_soon(
1481
+ self._events_from_calendar,
1482
+ calendar,
1483
+ start_datetime,
1484
+ end_datetime,
1485
+ filters,
1486
+ limiter,
1487
+ slots,
1488
+ index,
1489
+ limit,
1490
+ failures,
1491
+ )
1492
+
1493
+ events = [event for events in slots for event in events]
1494
+
1495
+ except Exception as e:
1496
+ logger.error("Error searching events across calendars: %s", e)
1497
+ raise
1498
+
1499
+ if strict and failures:
1500
+ raise ValueError(
1501
+ f"Could not read {len(failures)} calendar(s): "
1502
+ + "; ".join(f"{f['calendar_name']} ({f['error']})" for f in failures)
1503
+ )
1504
+ return events
1505
+
1506
+ # ============= Todo/Task Operations (NEW) =============
1507
+
1508
+ async def list_todos(
1509
+ self, calendar_name: str, filters: dict[str, Any] | None = None
1510
+ ) -> list[dict[str, Any]]:
1511
+ """List todos/tasks in a calendar."""
1512
+ await self._ensure_calendar_home()
1513
+ calendar = self._get_calendar(calendar_name)
1514
+
1515
+ # Get all todos including completed ones (filtering is done client-side)
1516
+ todos = await calendar.todos(include_completed=True) # type: ignore[misc] # ty: ignore[invalid-await] # dual-mode
1517
+
1518
+ # caldav's todos() REPORT asks for calendar-data only, so none of these
1519
+ # objects carry an etag and _object_etag would PROPFIND once per todo --
1520
+ # measured at 1 + N against a live instance. Its ``props`` argument
1521
+ # cannot carry getetag (it expects calendar-data-shaped elements only),
1522
+ # so fetch them all in a single collection PROPFIND instead: 1 + 1.
1523
+ # Skipped entirely for an empty calendar -- there is nothing to key.
1524
+ etags = await self._collection_etags(calendar) if todos else {}
1525
+
1526
+ result = []
1527
+ for todo in todos:
1528
+ # Only load if data not already present from REPORT response
1529
+ # This avoids 404 errors for virtual calendars (e.g., Deck boards)
1530
+ await _maybe_await(todo.load(only_if_unloaded=True))
1531
+ if todo.data:
1532
+ todo_dict = self._parse_ical_todo(todo.data) # type: ignore[arg-type]
1533
+ else:
1534
+ continue
1535
+ if todo_dict:
1536
+ href = str(todo.url)
1537
+ todo_dict["href"] = href
1538
+ todo_dict["etag"] = etags.get(unquote(urlsplit(href).path), "")
1539
+
1540
+ # Apply filters if provided
1541
+ if not filters or self._todo_matches_filters(todo_dict, filters):
1542
+ result.append(todo_dict)
1543
+
1544
+ logger.debug("Found %s todos", len(result))
1545
+ return result
1546
+
1547
+ async def create_todo(
1548
+ self, calendar_name: str, todo_data: dict[str, Any]
1549
+ ) -> dict[str, Any]:
1550
+ """Create a new todo/task."""
1551
+ await self._ensure_calendar_home()
1552
+ calendar = self._get_calendar(calendar_name)
1553
+
1554
+ todo_uid = str(uuid.uuid4())
1555
+ ical_content = self._create_ical_todo(todo_data, todo_uid)
1556
+
1557
+ # caldav v3's _async_put raises PutError on HTTP failure
1558
+ todo = await calendar.save_todo(ical=ical_content) # type: ignore[misc] # ty: ignore[invalid-await] # dual-mode
1559
+
1560
+ logger.debug("Created todo %s", todo_uid)
1561
+
1562
+ return {
1563
+ "uid": todo_uid,
1564
+ "href": str(todo.url),
1565
+ "etag": await self._object_etag(todo),
1566
+ "status_code": 201,
1567
+ }
1568
+
1569
+ async def update_todo(
1570
+ self,
1571
+ calendar_name: str,
1572
+ todo_uid: str,
1573
+ todo_data: dict[str, Any],
1574
+ etag: str = "",
1575
+ ) -> dict[str, Any]:
1576
+ """Update an existing todo/task.
1577
+
1578
+ Args:
1579
+ etag: The ETag the caller last read. The write is refused with
1580
+ :class:`DavPreconditionFailed` if the todo changed since. When
1581
+ omitted, the ETag observed during this call's own read is used.
1582
+
1583
+ Raises:
1584
+ DavPreconditionFailed: If the todo changed since ``etag`` was read.
1585
+ """
1586
+ await self._ensure_calendar_home()
1587
+ calendar = self._get_calendar(calendar_name)
1588
+
1589
+ try:
1590
+ # Find the todo by UID
1591
+ todo = await self._async_object_by_uid(
1592
+ calendar, todo_uid, cdav.CompFilter("VTODO")
1593
+ )
1594
+ await _maybe_await(todo.load(only_if_unloaded=True))
1595
+
1596
+ logger.debug(
1597
+ "Loaded todo %s, current data length: %s", todo_uid, len(todo.data)
1598
+ )
1599
+
1600
+ # The caller's ETag wins -- see update_event for the reasoning.
1601
+ if not etag:
1602
+ etag = await self._object_etag(todo)
1603
+
1604
+ # Merge updates into existing iCal data
1605
+ updated_ical = self._merge_ical_todo_properties(
1606
+ todo.data, # type: ignore[arg-type]
1607
+ todo_data,
1608
+ )
1609
+ logger.debug("Merged iCal data length: %s", len(updated_ical))
1610
+
1611
+ new_etag = await self._conditional_put(
1612
+ todo, updated_ical, etag, kind="todo", uid=todo_uid
1613
+ )
1614
+
1615
+ logger.debug("Updated todo %s", todo_uid)
1616
+ return {
1617
+ "uid": todo_uid,
1618
+ "href": str(todo.url),
1619
+ "etag": new_etag,
1620
+ "status_code": 200,
1621
+ }
1622
+ except DavPreconditionFailed:
1623
+ # Listed before the catch-all because it is not a failure of this
1624
+ # call: it is the If-Match guard doing its job when another writer
1625
+ # got there first. The tool layer already logs it at debug and
1626
+ # translates it into an actionable error, so logging it as an error
1627
+ # here would make every contended write look like a server fault --
1628
+ # in exactly the concurrent-write scenario someone would be reading
1629
+ # these logs to understand.
1630
+ raise
1631
+ except Exception as e:
1632
+ logger.error("Error updating todo %s: %s", todo_uid, e)
1633
+ raise
1634
+
1635
+ async def delete_todo(self, calendar_name: str, todo_uid: str) -> dict[str, Any]:
1636
+ """Delete a todo/task.
1637
+
1638
+ Returns a structured result rather than raising on a server refusal —
1639
+ see :meth:`_delete_dav_object`.
1640
+ """
1641
+ return await self._delete_dav_object(
1642
+ calendar_name, todo_uid, cdav.CompFilter("VTODO"), "todo"
1643
+ )
1644
+
1645
+ async def _todos_from_calendar(
1646
+ self,
1647
+ calendar: dict[str, Any],
1648
+ filters: dict[str, Any] | None,
1649
+ limiter: anyio.CapacityLimiter,
1650
+ slots: list[list[dict[str, Any]]],
1651
+ index: int,
1652
+ failures: list[dict[str, str]] | None = None,
1653
+ ) -> None:
1654
+ """One calendar's todos, annotated. Failure is contained per calendar."""
1655
+ async with limiter:
1656
+ try:
1657
+ todos = await self.list_todos(calendar["name"], filters)
1658
+ except Exception as e:
1659
+ logger.warning(
1660
+ "Error getting todos from calendar %s: %s", calendar["name"], e
1661
+ )
1662
+ if failures is not None:
1663
+ failures.append(
1664
+ {"calendar_name": calendar["name"], "error": str(e)}
1665
+ )
1666
+ return
1667
+
1668
+ # Add calendar info to each todo
1669
+ for todo in todos:
1670
+ todo["calendar_name"] = calendar["name"]
1671
+ todo["calendar_display_name"] = calendar.get(
1672
+ "display_name", calendar["name"]
1673
+ )
1674
+
1675
+ slots[index] = todos
1676
+
1677
+ async def search_todos_across_calendars(
1678
+ self,
1679
+ filters: dict[str, Any] | None = None,
1680
+ failures: list[dict[str, str]] | None = None,
1681
+ ) -> list[dict[str, Any]]:
1682
+ """Search todos across all calendars.
1683
+
1684
+ Fanned out like :meth:`search_events_across_calendars` - same serial
1685
+ round-trip problem, same bounded task group, same stable ordering, and
1686
+ the same optional ``failures`` list for calendars that were skipped.
1687
+ """
1688
+ await self._ensure_calendar_home()
1689
+ try:
1690
+ calendars = await self.list_calendars()
1691
+ slots: list[list[dict[str, Any]]] = [[] for _ in calendars]
1692
+ limiter = anyio.CapacityLimiter(CALENDAR_FANOUT)
1693
+
1694
+ async with anyio.create_task_group() as tg:
1695
+ for index, calendar in enumerate(calendars):
1696
+ tg.start_soon(
1697
+ self._todos_from_calendar,
1698
+ calendar,
1699
+ filters,
1700
+ limiter,
1701
+ slots,
1702
+ index,
1703
+ failures,
1704
+ )
1705
+
1706
+ return [todo for todos in slots for todo in todos]
1707
+
1708
+ except Exception as e:
1709
+ logger.error("Error searching todos across calendars: %s", e)
1710
+ raise
1711
+
1712
+ # ============= Helper Methods - Event iCalendar =============
1713
+
1714
+ @staticmethod
1715
+ def _resolve_timezone(tz_name: str) -> ZoneInfo | None:
1716
+ """Resolve an IANA timezone name to ZoneInfo, returning None for invalid input."""
1717
+ if not tz_name:
1718
+ return None
1719
+ try:
1720
+ return ZoneInfo(tz_name)
1721
+ except ZoneInfoNotFoundError:
1722
+ logger.warning(
1723
+ "Unknown IANA timezone %r — falling back to floating local time",
1724
+ tz_name,
1725
+ )
1726
+ return None
1727
+
1728
+ @staticmethod
1729
+ def _stored_is_all_day(component, prop: str = "DTSTART") -> bool | None:
1730
+ """Whether ``prop`` on the stored component is a DATE (all-day) value.
1731
+
1732
+ Returns ``None`` when the property is absent, so callers can distinguish
1733
+ "unknown" from "timed" — the update path needs that difference to decide
1734
+ whether to inherit the stored value type or fall back to a default.
1735
+ """
1736
+ value = component.get(prop)
1737
+ if value is None:
1738
+ return None
1739
+ inner = getattr(value, "dt", None)
1740
+ if inner is None:
1741
+ return None
1742
+ return isinstance(inner, dt.date) and not isinstance(inner, dt.datetime)
1743
+
1744
+ @staticmethod
1745
+ def _stored_tzid(component, prop: str = "DTSTART") -> str | None:
1746
+ """Return the TZID parameter on ``prop``, if the stored value carries one.
1747
+
1748
+ ``None`` for all-day, floating and UTC values — none of which should have
1749
+ a zone inherited onto them.
1750
+ """
1751
+ value = component.get(prop)
1752
+ if value is None:
1753
+ return None
1754
+ tzid = getattr(value, "params", {}).get("TZID")
1755
+ return str(tzid) if tzid else None
1756
+
1757
+ @classmethod
1758
+ def _parse_event_datetime(
1759
+ cls,
1760
+ dt_str: str,
1761
+ tz_name: str | None = None,
1762
+ *,
1763
+ inherited_tz: str | None = None,
1764
+ ) -> tuple[dt.datetime, ZoneInfo | None]:
1765
+ """Parse an ISO datetime string with optional TZID application.
1766
+
1767
+ Returns ``(parsed_dt, applied_zoneinfo)`` where ``applied_zoneinfo``
1768
+ is non-None only when a zone was applied to a naive input — the
1769
+ caller uses this to know whether to emit a VTIMEZONE component.
1770
+
1771
+ ``tz_name`` is the caller's explicit request; ``inherited_tz`` is the TZID
1772
+ already on the stored property. They are separate parameters on purpose:
1773
+ passing the stored zone as ``tz_name`` would fire the "explicit offset;
1774
+ ignoring timezone" warning spuriously on every offset-bearing update, and
1775
+ would override a caller who deliberately wants floating time. Explicit
1776
+ always wins over inherited.
1777
+ """
1778
+ parsed = dt.datetime.fromisoformat(dt_str.replace("Z", "+00:00"))
1779
+ zi = cls._resolve_timezone(tz_name) if tz_name else None
1780
+
1781
+ if parsed.tzinfo is not None:
1782
+ # Only complain about a zone the caller actually asked for.
1783
+ if tz_name:
1784
+ logger.warning(
1785
+ "Datetime %r has an explicit offset; ignoring timezone=%r",
1786
+ dt_str,
1787
+ tz_name,
1788
+ )
1789
+ # fromisoformat gives a fixed-offset tzinfo whose tzname() is e.g.
1790
+ # "UTC+02:00"; icalendar would emit it as an unresolvable TZID.
1791
+ return parsed.astimezone(dt.UTC), None
1792
+
1793
+ if zi is not None:
1794
+ return parsed.replace(tzinfo=zi), zi
1795
+
1796
+ if inherited_tz:
1797
+ # Resolve quietly. A stored TZID is not guaranteed to be an IANA name:
1798
+ # icalendar renders a fixed-offset tzinfo as TZID="UTC-04:00" with no
1799
+ # VTIMEZONE, so inheriting one is expected to fail. Routing that
1800
+ # through _resolve_timezone would log "Unknown IANA timezone", which
1801
+ # reads as an error when the floating-time fallback below is the
1802
+ # correct, harmless outcome. An explicit `timezone=` from the caller
1803
+ # still warns — that one really is a mistake worth surfacing.
1804
+ try:
1805
+ inherited_zi = ZoneInfo(inherited_tz)
1806
+ except (ZoneInfoNotFoundError, ValueError):
1807
+ logger.debug(
1808
+ "Stored TZID %r is not an IANA name; not inheriting it",
1809
+ inherited_tz,
1810
+ )
1811
+ inherited_zi = None
1812
+ if inherited_zi is not None:
1813
+ # Inheriting is the expected behaviour, not a problem — debug, not
1814
+ # warning. Without this, updating the time of a TZID-bound event
1815
+ # without re-passing `timezone` silently produced floating time.
1816
+ logger.debug(
1817
+ "Datetime %r is naive; inheriting stored TZID=%r",
1818
+ dt_str,
1819
+ inherited_tz,
1820
+ )
1821
+ return parsed.replace(tzinfo=inherited_zi), inherited_zi
1822
+
1823
+ logger.warning(
1824
+ "Datetime %r is naive and no timezone was supplied — storing as RFC 5545 floating local time",
1825
+ dt_str,
1826
+ )
1827
+ return parsed, None
1828
+
1829
+ @staticmethod
1830
+ def _build_valarm(
1831
+ reminder: dict[str, Any],
1832
+ default_summary: str,
1833
+ default_description: str = _EVENT_REMINDER_DESCRIPTION,
1834
+ ) -> Alarm:
1835
+ """Build one VALARM from a ``Reminder``-shaped dict.
1836
+
1837
+ Trigger precedence is ``trigger_at`` > ``trigger`` > ``minutes_before``;
1838
+ the model guarantees exactly one is set, so the order only decides which
1839
+ wins if a caller reaches this helper directly.
1840
+
1841
+ Two RFC 5545 rules are enforced here rather than left to the server:
1842
+
1843
+ * ``RELATED`` qualifies a *duration* trigger. Attaching it to an absolute
1844
+ one produces ``TRIGGER;RELATED=START;VALUE=DATE-TIME:...``, which is
1845
+ invalid, so it is only emitted on the relative branches.
1846
+ * An ``EMAIL`` alarm must carry ``SUMMARY`` (the subject) alongside
1847
+ ``DESCRIPTION`` (the body). Nextcloud addresses the message itself,
1848
+ from the component's ATTENDEEs and the calendar's sharees, so no
1849
+ alarm-level ATTENDEE is needed.
1850
+ * ``DESCRIPTION`` belongs to ``DISPLAY`` and ``EMAIL`` alarms only. The
1851
+ ``audioprop`` grammar admits ACTION, TRIGGER, DURATION+REPEAT and
1852
+ ATTACH — writing a description onto an AUDIO alarm produces a
1853
+ spec-invalid component even though lenient parsers accept it.
1854
+ """
1855
+ alarm = Alarm()
1856
+ action = reminder.get("action", "DISPLAY")
1857
+ alarm.add("action", action)
1858
+ if action in ("DISPLAY", "EMAIL"):
1859
+ alarm.add("description", reminder.get("description") or default_description)
1860
+ if action == "EMAIL":
1861
+ alarm.add("summary", reminder.get("summary") or default_summary)
1862
+
1863
+ params: dict[str, str] = {}
1864
+ related = reminder.get("related")
1865
+ if related:
1866
+ params["RELATED"] = str(related)
1867
+
1868
+ if reminder.get("trigger_at"):
1869
+ trigger_dt = dt.datetime.fromisoformat(str(reminder["trigger_at"]))
1870
+ if trigger_dt.tzinfo is None:
1871
+ trigger_dt = trigger_dt.replace(tzinfo=dt.UTC)
1872
+ # RFC 5545 §3.8.6.3: an absolute trigger MUST be UTC. A fixed offset
1873
+ # would otherwise be emitted as TZID="UTC+02:00".
1874
+ trigger_dt = trigger_dt.astimezone(dt.UTC)
1875
+ # RELATED is deliberately dropped here: it has no meaning on an
1876
+ # absolute trigger and makes the property invalid.
1877
+ alarm.add("trigger", trigger_dt, parameters={"VALUE": "DATE-TIME"})
1878
+ elif reminder.get("trigger"):
1879
+ alarm.add(
1880
+ "trigger",
1881
+ vDDDTypes.from_ical(str(reminder["trigger"])),
1882
+ parameters=params,
1883
+ )
1884
+ elif "minutes_before" in reminder:
1885
+ minutes = int(reminder["minutes_before"])
1886
+ alarm.add("trigger", dt.timedelta(minutes=-minutes), parameters=params)
1887
+ else:
1888
+ # The Reminder model already enforces this for anything arriving via
1889
+ # an MCP tool, but the client is usable directly and a bare KeyError
1890
+ # would name a dict key rather than the thing the caller got wrong.
1891
+ raise ValueError(
1892
+ "a reminder needs one of trigger_at, trigger or minutes_before; "
1893
+ f"got {sorted(reminder)}"
1894
+ )
1895
+
1896
+ return alarm
1897
+
1898
+ @staticmethod
1899
+ def _extract_valarms(component: Any) -> list[dict[str, Any]]:
1900
+ """Read a component's VALARMs back into ``Reminder``-shaped dicts.
1901
+
1902
+ An alarm that cannot be represented is skipped rather than surfaced
1903
+ half-built, because the caller's next step is model validation and a
1904
+ malformed alarm must cost at most itself, never the listing it is in.
1905
+ """
1906
+ reminders = []
1907
+ for sub in component.subcomponents:
1908
+ if sub.name != "VALARM":
1909
+ continue
1910
+ reminder = CalendarClient._extract_valarm(sub)
1911
+ if reminder is not None:
1912
+ reminders.append(reminder)
1913
+ return reminders
1914
+
1915
+ @staticmethod
1916
+ def _extract_valarm(alarm: Any) -> dict[str, Any] | None:
1917
+ """Read one VALARM into a ``Reminder``-shaped dict, or ``None``.
1918
+
1919
+ Stored data is normalised to what ``Reminder`` accepts, because this
1920
+ parses whatever any CalDAV client wrote, not only what we write. RFC 5545
1921
+ §3.8.6.1 allows ACTION to carry any IANA or ``X-`` token, so a legacy
1922
+ ``PROCEDURE`` or a custom action is realistic — and left unnormalised it
1923
+ would fail the model's ``Literal`` and take down the whole listing the
1924
+ todo appears in, rather than the one alarm. Nextcloud's own
1925
+ ``ReminderService`` discards an alarm it does not recognise instead of
1926
+ rejecting its component, so unknown actions degrade to DISPLAY here.
1927
+
1928
+ ``None`` means the alarm has no usable TRIGGER. RFC 5545 makes TRIGGER
1929
+ mandatory and Nextcloud cannot schedule an alarm without one, so there is
1930
+ nothing to report — and ``Reminder`` requires exactly one trigger field,
1931
+ so returning a trigger-less dict would fail validation for the whole
1932
+ component just as an unknown ACTION would.
1933
+ """
1934
+ action = str(alarm.get("action", "DISPLAY")).upper()
1935
+ if action not in _VALARM_ACTIONS:
1936
+ logger.warning(
1937
+ "VALARM action %r is not one of %s; reporting it as DISPLAY. "
1938
+ "Nextcloud does not schedule non-standard alarms either",
1939
+ action,
1940
+ ", ".join(sorted(_VALARM_ACTIONS)),
1941
+ )
1942
+ action = "DISPLAY"
1943
+
1944
+ reminder: dict[str, Any] = {
1945
+ "action": action,
1946
+ "description": str(alarm.get("description", "")),
1947
+ }
1948
+ summary = alarm.get("summary")
1949
+ if summary:
1950
+ reminder["summary"] = str(summary)
1951
+
1952
+ trigger = alarm.get("trigger")
1953
+ if trigger is None or getattr(trigger, "dt", None) is None:
1954
+ logger.warning(
1955
+ "Skipping a VALARM with no usable TRIGGER; RFC 5545 requires one "
1956
+ "and Nextcloud cannot schedule the alarm without it"
1957
+ )
1958
+ return None
1959
+
1960
+ value = trigger.dt
1961
+ if not isinstance(value, dt.timedelta):
1962
+ reminder["trigger_at"] = value.isoformat()
1963
+ return reminder
1964
+
1965
+ # Emit exactly one trigger field, because that is what ``Reminder``
1966
+ # accepts — a dict carrying both would not validate when a caller feeds
1967
+ # a read reminder back into an update. Whole-minute offsets take the
1968
+ # friendlier ``minutes_before``, anything else keeps its raw duration.
1969
+ total = value.total_seconds()
1970
+ if total <= 0 and total % 60 == 0:
1971
+ reminder["minutes_before"] = int(-total // 60)
1972
+ else:
1973
+ reminder["trigger"] = vDDDTypes(value).to_ical().decode("utf-8")
1974
+
1975
+ related = trigger.params.get("RELATED") if trigger.params else None
1976
+ if related and str(related).upper() in ("START", "END"):
1977
+ # Same reasoning as ACTION: anything else is malformed input that
1978
+ # must not propagate into the model and break the caller's listing.
1979
+ reminder["related"] = str(related).upper()
1980
+ return reminder
1981
+
1982
+ @staticmethod
1983
+ def _sync_valarms(
1984
+ component: Any,
1985
+ reminders: list[dict[str, Any]],
1986
+ default_summary: str,
1987
+ default_description: str = _EVENT_REMINDER_DESCRIPTION,
1988
+ ) -> None:
1989
+ """Replace every VALARM on ``component`` with ``reminders``, in order."""
1990
+ component.subcomponents = [
1991
+ sub for sub in component.subcomponents if sub.name != "VALARM"
1992
+ ]
1993
+ for reminder in reminders:
1994
+ component.add_component(
1995
+ CalendarClient._build_valarm(
1996
+ reminder, default_summary, default_description
1997
+ )
1998
+ )
1999
+
2000
+ def _apply_reminders(
2001
+ self,
2002
+ component: Any,
2003
+ data: dict[str, Any],
2004
+ default_summary: str,
2005
+ default_description: str = _EVENT_REMINDER_DESCRIPTION,
2006
+ ) -> None:
2007
+ """Write alarms onto ``component`` from whichever form the caller used.
2008
+
2009
+ An explicit ``reminders`` list is authoritative and replaces everything.
2010
+ Otherwise the older ``reminder_minutes`` / ``reminder_email`` pair is
2011
+ honoured as shorthand: a DISPLAY alarm, plus an EMAIL alarm at the same
2012
+ offset when ``reminder_email`` is set.
2013
+
2014
+ Passing none of the three leaves existing alarms alone, which is what
2015
+ makes an unrelated update non-destructive.
2016
+
2017
+ The two shorthand fields are independently updatable: whichever one the
2018
+ caller omits is read back off the stored alarms rather than assumed. The
2019
+ rebuild would otherwise erase what the caller never mentioned —
2020
+ ``reminder_email=True`` on its own would find no minutes, clear every
2021
+ VALARM and add nothing back, and ``reminder_minutes=45`` on its own would
2022
+ silently drop a stored EMAIL alarm.
2023
+ """
2024
+ if "reminders" in data:
2025
+ self._sync_valarms(
2026
+ component,
2027
+ data.get("reminders") or [],
2028
+ default_summary,
2029
+ default_description,
2030
+ )
2031
+ return
2032
+
2033
+ if "reminder_minutes" not in data and "reminder_email" not in data:
2034
+ return
2035
+
2036
+ stored = self._extract_valarms(component)
2037
+ if "reminder_minutes" in data:
2038
+ minutes = data["reminder_minutes"] or 0
2039
+ else:
2040
+ minutes = next(
2041
+ (r["minutes_before"] for r in stored if "minutes_before" in r), 0
2042
+ )
2043
+ want_email = (
2044
+ data["reminder_email"]
2045
+ if "reminder_email" in data
2046
+ else any(r["action"] == "EMAIL" for r in stored)
2047
+ )
2048
+
2049
+ actions = ["DISPLAY"] + (["EMAIL"] if want_email else [])
2050
+ if _shorthand_would_lose(stored, default_description, default_summary):
2051
+ logger.warning(
2052
+ "reminder_minutes/reminder_email rebuilds the alarms as one "
2053
+ "%s at %d minutes, which does not reproduce the %d stored "
2054
+ "alarm(s); use the reminders list to edit them without loss",
2055
+ "/".join(actions),
2056
+ minutes,
2057
+ len(stored),
2058
+ )
2059
+
2060
+ if minutes <= 0 and want_email:
2061
+ logger.warning(
2062
+ "reminder_email was requested but no reminder_minutes was given "
2063
+ "and none could be read from the stored alarms, so there is no "
2064
+ "offset to schedule it at"
2065
+ )
2066
+
2067
+ self._sync_valarms(component, [], default_summary, default_description)
2068
+ if minutes <= 0:
2069
+ return
2070
+
2071
+ for action in actions:
2072
+ component.add_component(
2073
+ self._build_valarm(
2074
+ {
2075
+ "action": action,
2076
+ "description": default_description,
2077
+ "minutes_before": minutes,
2078
+ },
2079
+ default_summary,
2080
+ )
2081
+ )
2082
+
2083
+ def _create_ical_event(
2084
+ self,
2085
+ event_data: dict[str, Any],
2086
+ event_uid: str,
2087
+ organizer: vCalAddress | None = None,
2088
+ ) -> str:
2089
+ """Create iCalendar content from event data."""
2090
+ cal = Calendar()
2091
+ cal.add("prodid", "-//Nextcloud MCP Server//EN")
2092
+ cal.add("version", "2.0")
2093
+
2094
+ event = ICalEvent()
2095
+ event.add("uid", event_uid)
2096
+ event.add("summary", event_data.get("title", ""))
2097
+ event.add("description", event_data.get("description", ""))
2098
+ event.add("location", event_data.get("location", ""))
2099
+
2100
+ # Handle dates/times
2101
+ start_str = event_data.get("start_datetime", "")
2102
+ end_str = event_data.get("end_datetime", "")
2103
+ all_day = event_data.get("all_day", False)
2104
+ tz_name = event_data.get("timezone", "")
2105
+ used_timezones: set[ZoneInfo] = set()
2106
+
2107
+ # Kept for the RRULE below, whose UNTIL must match DTSTART's value type.
2108
+ dtstart_value: dt.date | dt.datetime | None = None
2109
+
2110
+ if start_str:
2111
+ if all_day:
2112
+ start_date = dt.datetime.fromisoformat(start_str.split("T")[0]).date()
2113
+ dtstart_value = start_date
2114
+ event.add("dtstart", start_date)
2115
+ if end_str:
2116
+ end_date = dt.datetime.fromisoformat(end_str.split("T")[0]).date()
2117
+ event.add("dtend", end_date)
2118
+ else:
2119
+ start_dt, zi = self._parse_event_datetime(start_str, tz_name)
2120
+ if zi is not None:
2121
+ used_timezones.add(zi)
2122
+ dtstart_value = start_dt
2123
+ event.add("dtstart", start_dt)
2124
+ if end_str:
2125
+ end_dt, zi = self._parse_event_datetime(end_str, tz_name)
2126
+ if zi is not None:
2127
+ used_timezones.add(zi)
2128
+ event.add("dtend", end_dt)
2129
+
2130
+ # Add categories
2131
+ categories = event_data.get("categories", "")
2132
+ if categories:
2133
+ event.add("categories", [c.strip() for c in categories.split(",")])
2134
+
2135
+ # Add priority and status
2136
+ priority = event_data.get("priority", 5)
2137
+ event.add("priority", priority)
2138
+
2139
+ status = event_data.get("status", "CONFIRMED")
2140
+ event.add("status", status)
2141
+
2142
+ # Add privacy classification
2143
+ privacy = event_data.get("privacy", "PUBLIC")
2144
+ event.add("class", privacy)
2145
+
2146
+ # Add URL
2147
+ url = event_data.get("url", "")
2148
+ if url:
2149
+ event.add("url", url)
2150
+
2151
+ # Add colour (RFC 7986 COLOR)
2152
+ color = event_data.get("color", "")
2153
+ if color:
2154
+ _warn_if_hex_color(color)
2155
+ event.add("color", color)
2156
+
2157
+ # Handle recurrence. A non-empty rule is itself the intent to recur —
2158
+ # requiring recurring=True as well made recurrence_rule a no-op on this
2159
+ # path while the update path applied it unconditionally, so the same
2160
+ # argument meant different things depending on which tool you called.
2161
+ # ``recurring=False`` remains an explicit opt-out.
2162
+ recurrence_rule = event_data.get("recurrence_rule", "")
2163
+ if recurrence_rule and event_data.get("recurring", True):
2164
+ recurrence_end_date = event_data.get("recurrence_end_date", "")
2165
+ if recurrence_end_date:
2166
+ recurrence_rule = _rrule_with_until(
2167
+ recurrence_rule,
2168
+ recurrence_end_date,
2169
+ _until_anchor(dtstart_value, start_str),
2170
+ )
2171
+ event.add("rrule", vRecur.from_ical(recurrence_rule))
2172
+
2173
+ # Add alarms/reminders
2174
+ self._apply_reminders(event, event_data, event_data.get("title", ""))
2175
+
2176
+ # Add attendees (and ORGANIZER, without which Nextcloud sends no CANCEL)
2177
+ attendees = event_data.get("attendees", "")
2178
+ if attendees:
2179
+ self._apply_attendees(event, attendees, organizer)
2180
+
2181
+ # Add timestamps
2182
+ now = dt.datetime.now(dt.UTC)
2183
+ event.add("created", now)
2184
+ event.add("dtstamp", now)
2185
+ event.add("last-modified", now)
2186
+
2187
+ # VTIMEZONE must appear before the referencing VEVENT.
2188
+ for zi in used_timezones:
2189
+ cal.add_component(Timezone.from_tzinfo(zi))
2190
+ cal.add_component(event)
2191
+ return cal.to_ical().decode("utf-8")
2192
+
2193
+ def _extract_vevent_data(self, component) -> dict[str, Any]:
2194
+ """Extract event data from a single VEVENT component."""
2195
+ event_data: dict[str, Any] = {
2196
+ "uid": str(component.get("uid", "")),
2197
+ "title": str(component.get("summary", "")),
2198
+ "description": str(component.get("description", "")),
2199
+ "location": str(component.get("location", "")),
2200
+ "status": str(component.get("status", "CONFIRMED")),
2201
+ # TRANSP marks whether this event consumes time (RFC 5545
2202
+ # 3.8.2.7). Nextcloud surfaces it as Busy/Free on the event.
2203
+ # Without it a caller cannot tell that e.g. birthdays are
2204
+ # explicitly non-blocking. Absent means OPAQUE.
2205
+ "transp": str(component.get("transp", "OPAQUE")).upper(),
2206
+ "priority": int(component.get("priority", 5)),
2207
+ "privacy": str(component.get("class", "PUBLIC")),
2208
+ "url": str(component.get("url", "")),
2209
+ }
2210
+
2211
+ color = component.get("color")
2212
+ if color:
2213
+ event_data["color"] = str(color)
2214
+
2215
+ # Handle dates. The ``.isoformat()`` representation already encodes the
2216
+ # storage semantics: no suffix for floating local, ``+00:00`` for UTC,
2217
+ # and the offset (e.g. ``-04:00``) for TZID-bound datetimes. The IANA
2218
+ # TZID name is surfaced separately as ``start_tz``/``end_tz`` so callers
2219
+ # can distinguish "10am NY time" (recurs in local time across DST) from
2220
+ # "14:00 UTC" (same UTC instant), which the offset alone cannot express.
2221
+ dtstart = component.get("dtstart")
2222
+ if dtstart:
2223
+ event_data["start_datetime"] = dtstart.dt.isoformat()
2224
+ event_data["all_day"] = isinstance(dtstart.dt, dt.date) and not isinstance(
2225
+ dtstart.dt, dt.datetime
2226
+ )
2227
+ tzid = dtstart.params.get("TZID") if dtstart.params else None
2228
+ if tzid:
2229
+ event_data["start_tz"] = str(tzid)
2230
+
2231
+ dtend = component.get("dtend")
2232
+ if dtend:
2233
+ event_data["end_datetime"] = dtend.dt.isoformat()
2234
+ tzid = dtend.params.get("TZID") if dtend.params else None
2235
+ if tzid:
2236
+ event_data["end_tz"] = str(tzid)
2237
+ elif dtstart is not None and component.get("duration") is not None:
2238
+ # RFC 5545 3.6.1 lets an event carry DURATION instead of DTEND.
2239
+ # Without this the event reads as zero-length, so anything working
2240
+ # out how long it lasts -- availability above all -- silently
2241
+ # treats it as not consuming any time.
2242
+ duration = component.get("duration").dt
2243
+ event_data["end_datetime"] = (dtstart.dt + duration).isoformat()
2244
+ if "start_tz" in event_data:
2245
+ event_data["end_tz"] = event_data["start_tz"]
2246
+
2247
+ # Handle categories
2248
+ categories = component.get("categories")
2249
+ if categories:
2250
+ event_data["categories"] = self._extract_categories(categories)
2251
+
2252
+ # Handle recurrence
2253
+ rrule = component.get("rrule")
2254
+ if rrule:
2255
+ event_data["recurring"] = True
2256
+ event_data["recurrence_rule"] = _rrule_to_string(rrule)
2257
+ until = (
2258
+ rrule[0].get("UNTIL") if isinstance(rrule, list) else rrule.get("UNTIL")
2259
+ )
2260
+ if until:
2261
+ # vRecur stores UNTIL as a single-element list of date/datetime.
2262
+ value = until[0] if isinstance(until, list) else until
2263
+ # Same key the update tool accepts, so a read value can be fed
2264
+ # straight back in — the write side is recurrence_end_date.
2265
+ event_data["recurrence_end_date"] = value.isoformat()
2266
+ recurrence_id = component.get("recurrence-id")
2267
+ if recurrence_id:
2268
+ # An expanded occurrence carries RECURRENCE-ID but no RRULE; it is
2269
+ # still one instance of a stored series, which bulk ops must know
2270
+ # before writing by UID (#1499).
2271
+ event_data["recurrence_id"] = recurrence_id.dt.isoformat()
2272
+
2273
+ # Handle attendees
2274
+ # A single ATTENDEE comes back as a bare vCalAddress, not a list.
2275
+ attendees = [
2276
+ str(a).replace("mailto:", "") for a in _as_list(component.get("attendee"))
2277
+ ]
2278
+ if attendees:
2279
+ event_data["attendees"] = ",".join(attendees)
2280
+ organizer = component.get("organizer")
2281
+ if organizer:
2282
+ event_data["organizer"] = str(organizer).replace("mailto:", "")
2283
+
2284
+ reminders = self._extract_valarms(component)
2285
+ if reminders:
2286
+ event_data["reminders"] = reminders
2287
+
2288
+ return event_data
2289
+
2290
+ def _parse_ical_event(self, ical_text: str) -> dict[str, Any] | None:
2291
+ """Parse iCalendar text and extract the first event."""
2292
+ try:
2293
+ cal = Calendar.from_ical(ical_text)
2294
+ for component in cal.walk():
2295
+ if component.name == "VEVENT":
2296
+ return self._extract_vevent_data(component)
2297
+ return None
2298
+ except Exception as e:
2299
+ logger.error("Error parsing iCalendar event: %s", e)
2300
+ return None
2301
+
2302
+ @staticmethod
2303
+ def _validate_all_day_flip(
2304
+ target_all_day: bool, has_start: bool, has_end: bool
2305
+ ) -> None:
2306
+ """Reject flips between all-day and timed that can't produce valid iCal.
2307
+
2308
+ Only called when the update actually changes the value type.
2309
+ """
2310
+ if (has_start or has_end) and not (has_start and has_end):
2311
+ raise ValueError(
2312
+ "changing an event between all-day and timed requires both "
2313
+ "start_datetime and end_datetime, so DTSTART and DTEND cannot "
2314
+ "end up with mismatched value types"
2315
+ )
2316
+ if not has_start and not has_end and not target_all_day:
2317
+ raise ValueError(
2318
+ "converting an all-day event to a timed one requires "
2319
+ "start_datetime and end_datetime — there is no defensible "
2320
+ "time-of-day to invent"
2321
+ )
2322
+
2323
+ def _apply_date_updates(
2324
+ self, component, event_data: dict[str, Any]
2325
+ ) -> set[ZoneInfo]:
2326
+ """Write DTSTART/DTEND onto ``component``, preserving its stored shape.
2327
+
2328
+ Returns the set of zones applied, so the caller can emit the matching
2329
+ VTIMEZONE components.
2330
+
2331
+ Two properties of the stored event are inherited when the caller does not
2332
+ override them, because reading them from ``event_data`` alone is what made
2333
+ updates lossy:
2334
+
2335
+ * **Value type.** ``all_day`` was previously read as
2336
+ ``event_data.get("all_day", False)`` independently in each branch, so
2337
+ updating an all-day event's start without re-passing ``all_day=True``
2338
+ rewrote DTSTART as a naive DATE-TIME — RFC 5545 floating time — and could
2339
+ leave DTSTART and DTEND with mismatched value types, which is invalid
2340
+ iCalendar.
2341
+ * **TZID.** Inherited *per property*: DTSTART and DTEND may legally carry
2342
+ different zones, so sharing DTSTART's would silently relocate the end.
2343
+ """
2344
+ tz_name = event_data.get("timezone", "")
2345
+ used_timezones: set[ZoneInfo] = set()
2346
+
2347
+ has_start = "start_datetime" in event_data
2348
+ has_end = "end_datetime" in event_data
2349
+ if not has_start and not has_end and "all_day" not in event_data:
2350
+ return used_timezones
2351
+
2352
+ stored_all_day = self._stored_is_all_day(component, "DTSTART")
2353
+ if stored_all_day is None:
2354
+ stored_all_day = self._stored_is_all_day(component, "DTEND")
2355
+
2356
+ # Computed once. Falling back to the *stored* type is the fix: absent an
2357
+ # explicit `all_day`, the event keeps the shape it already had.
2358
+ if "all_day" in event_data:
2359
+ target_all_day = bool(event_data["all_day"])
2360
+ else:
2361
+ target_all_day = bool(stored_all_day)
2362
+
2363
+ # ``stored_all_day is None`` means neither DTSTART nor DTEND gave a
2364
+ # definitive type — a VEVENT with no dates at all. There is nothing to
2365
+ # flip *from*, so flip validation is deliberately skipped rather than
2366
+ # guessing; ``bool(None)`` then treats the target as timed, matching the
2367
+ # pre-existing default.
2368
+ flipping = stored_all_day is not None and target_all_day != stored_all_day
2369
+
2370
+ if flipping:
2371
+ self._validate_all_day_flip(target_all_day, has_start, has_end)
2372
+ if not has_start and not has_end:
2373
+ # Timed -> all-day with no new datetimes is well defined: take the
2374
+ # dates off the stored values. (The converse already raised.)
2375
+ self._convert_component_to_all_day(component)
2376
+ return used_timezones
2377
+
2378
+ if has_start:
2379
+ self._write_date_property(
2380
+ component,
2381
+ "DTSTART",
2382
+ event_data["start_datetime"],
2383
+ target_all_day,
2384
+ tz_name,
2385
+ used_timezones,
2386
+ )
2387
+ if has_end:
2388
+ self._write_date_property(
2389
+ component,
2390
+ "DTEND",
2391
+ event_data["end_datetime"],
2392
+ target_all_day,
2393
+ tz_name,
2394
+ used_timezones,
2395
+ )
2396
+
2397
+ if target_all_day:
2398
+ # Apply the same zero-length guard the implicit conversion path uses.
2399
+ # An explicit ``all_day=True`` with start and end resolving to the same
2400
+ # calendar date would otherwise write ``DTEND == DTSTART`` — the very
2401
+ # zero-length DATE range this method rejects elsewhere.
2402
+ self._clamp_all_day_end(component)
2403
+
2404
+ return used_timezones
2405
+
2406
+ def _write_date_property(
2407
+ self,
2408
+ component,
2409
+ prop: str,
2410
+ value: str,
2411
+ all_day: bool,
2412
+ tz_name: str,
2413
+ used_timezones: set[ZoneInfo],
2414
+ ) -> None:
2415
+ """Write one DATE or DATE-TIME property, inheriting that property's TZID."""
2416
+ if all_day:
2417
+ component[prop] = vDDDTypes(
2418
+ dt.datetime.fromisoformat(value.split("T")[0]).date()
2419
+ )
2420
+ return
2421
+
2422
+ parsed, zi = self._parse_event_datetime(
2423
+ value, tz_name, inherited_tz=self._stored_tzid(component, prop)
2424
+ )
2425
+ if zi is not None:
2426
+ used_timezones.add(zi)
2427
+ component[prop] = vDDDTypes(parsed)
2428
+
2429
+ @staticmethod
2430
+ def _clamp_all_day_end(component) -> None:
2431
+ """Ensure an all-day ``DTEND`` is at least the day after ``DTSTART``.
2432
+
2433
+ ``DTEND == DTSTART`` is a zero-length DATE range and invalid per RFC 5545.
2434
+ Shared by both routes that can produce one: the implicit timed -> all-day
2435
+ conversion (``.date()`` on a 09:00-10:00 event collapses both ends onto the
2436
+ same day) and an explicit ``all_day=True`` whose supplied start and end
2437
+ resolve to the same calendar date. A no-op unless both are DATE values.
2438
+ """
2439
+ start_value = component.get("DTSTART")
2440
+ end_value = component.get("DTEND")
2441
+ if start_value is None or end_value is None:
2442
+ return
2443
+ start_date, end_date = start_value.dt, end_value.dt
2444
+ if isinstance(start_date, dt.datetime) or isinstance(end_date, dt.datetime):
2445
+ return # not an all-day pair; nothing to clamp
2446
+ if end_date <= start_date:
2447
+ component["DTEND"] = vDDDTypes(start_date + dt.timedelta(days=1))
2448
+
2449
+ @classmethod
2450
+ def _convert_component_to_all_day(cls, component) -> None:
2451
+ """Re-write stored DTSTART/DTEND as DATE values."""
2452
+ start_value = component.get("DTSTART")
2453
+ if start_value is None:
2454
+ return
2455
+ start_date = start_value.dt
2456
+ start_date = (
2457
+ start_date.date() if isinstance(start_date, dt.datetime) else start_date
2458
+ )
2459
+ component["DTSTART"] = vDDDTypes(start_date)
2460
+
2461
+ end_value = component.get("DTEND")
2462
+ if end_value is not None:
2463
+ end_date = end_value.dt
2464
+ end_date = (
2465
+ end_date.date() if isinstance(end_date, dt.datetime) else end_date
2466
+ )
2467
+ component["DTEND"] = vDDDTypes(end_date)
2468
+
2469
+ cls._clamp_all_day_end(component)
2470
+
2471
+ def _merge_ical_properties(
2472
+ self,
2473
+ raw_ical: str,
2474
+ event_data: dict[str, Any],
2475
+ organizer: vCalAddress | None = None,
2476
+ ) -> str:
2477
+ """Merge new event data into existing raw iCal while preserving all properties.
2478
+
2479
+ The event's own ``UID`` is carried through from ``raw_ical`` like any other
2480
+ preserved property, so no ``event_uid`` argument is needed. (One used to be
2481
+ required solely by the removed rebuild fallback.)
2482
+
2483
+ Raises on any merge failure rather than substituting a synthesised event.
2484
+ This previously caught every exception and fell back to
2485
+ ``_create_ical_event(event_data, ...)``, which rebuilds the event from the
2486
+ *partial update dict* — destroying summary, location, attendees, alarms,
2487
+ RRULE and every custom property the caller did not happen to pass, while
2488
+ reporting success.
2489
+ """
2490
+ cal = Calendar.from_ical(raw_ical)
2491
+
2492
+ for component in cal.walk():
2493
+ if component.name == "VEVENT":
2494
+ # Update only provided properties
2495
+ if "title" in event_data:
2496
+ component["SUMMARY"] = event_data["title"]
2497
+ if "description" in event_data:
2498
+ component["DESCRIPTION"] = event_data["description"]
2499
+ if "location" in event_data:
2500
+ component["LOCATION"] = event_data["location"]
2501
+ if "status" in event_data:
2502
+ component["STATUS"] = event_data["status"].upper()
2503
+ if "priority" in event_data:
2504
+ component["PRIORITY"] = event_data["priority"]
2505
+ if "privacy" in event_data:
2506
+ component["CLASS"] = event_data["privacy"].upper()
2507
+ if "url" in event_data:
2508
+ component["URL"] = event_data["url"]
2509
+
2510
+ # Handle categories
2511
+ if "categories" in event_data:
2512
+ categories_str = event_data["categories"]
2513
+ if categories_str:
2514
+ component["CATEGORIES"] = [
2515
+ c.strip() for c in categories_str.split(",")
2516
+ ]
2517
+ elif "CATEGORIES" in component:
2518
+ del component["CATEGORIES"]
2519
+
2520
+ # Handle colour (RFC 7986 COLOR)
2521
+ if "color" in event_data:
2522
+ color = event_data["color"]
2523
+ if color:
2524
+ _warn_if_hex_color(color)
2525
+ component["COLOR"] = color
2526
+ elif "COLOR" in component:
2527
+ del component["COLOR"]
2528
+
2529
+ # Handle attendees
2530
+ if "attendees" in event_data:
2531
+ self._apply_attendees(
2532
+ component, event_data["attendees"] or "", organizer
2533
+ )
2534
+ elif (
2535
+ organizer is not None
2536
+ and "ATTENDEE" in component
2537
+ and "ORGANIZER" not in component
2538
+ ):
2539
+ # Re-apply the stored guests: keeps their parameters and
2540
+ # adds the missing ORGANIZER + CHAIR.
2541
+ self._apply_attendees(
2542
+ component,
2543
+ ",".join(
2544
+ _address_key(a) for a in _as_list(component["ATTENDEE"])
2545
+ ),
2546
+ organizer,
2547
+ )
2548
+
2549
+ # Handle reminders (VALARM). Omitting all reminder arguments
2550
+ # preserves the stored alarms; ``reminders: []`` clears them.
2551
+ self._apply_reminders(
2552
+ component,
2553
+ event_data,
2554
+ event_data.get("title") or str(component.get("summary", "")),
2555
+ )
2556
+
2557
+ # Handle dates
2558
+ used_timezones = self._apply_date_updates(component, event_data)
2559
+
2560
+ # Handle recurrence. ``recurring=False`` clears the series, which
2561
+ # previously required passing recurrence_rule="" instead — the
2562
+ # flag itself did nothing. An end date may be applied to a rule
2563
+ # supplied now or to the one already stored.
2564
+ #
2565
+ # This must run *after* _apply_date_updates: UNTIL's value type
2566
+ # follows DTSTART, so an update that flips all_day and sets
2567
+ # recurrence_end_date in one call has to see the DTSTART being
2568
+ # written, not the one being replaced. Reading the stored value
2569
+ # here would emit exactly the mismatched RRULE that makes clients
2570
+ # discard the recurrence set.
2571
+ if event_data.get("recurring") is False:
2572
+ if event_data.get("recurrence_end_date"):
2573
+ logger.warning(
2574
+ "recurring=False was passed in the same update that "
2575
+ "set recurrence_end_date, so the series is removed "
2576
+ "and the end date has nothing to bound"
2577
+ )
2578
+ if event_data.get("recurrence_rule"):
2579
+ logger.warning(
2580
+ "recurring=False was passed in the same update that "
2581
+ "set recurrence_rule, so the series is removed and "
2582
+ "the new rule is discarded"
2583
+ )
2584
+ if "RRULE" in component:
2585
+ del component["RRULE"]
2586
+ elif (
2587
+ "recurrence_rule" in event_data
2588
+ or "recurrence_end_date" in event_data
2589
+ ):
2590
+ caller_supplied_rule = "recurrence_rule" in event_data
2591
+ rrule_str = (
2592
+ event_data["recurrence_rule"]
2593
+ if caller_supplied_rule
2594
+ else _rrule_to_string(component.get("rrule"))
2595
+ )
2596
+ if rrule_str:
2597
+ end_date = event_data.get("recurrence_end_date", "")
2598
+ if end_date:
2599
+ dtstart = component.get("dtstart")
2600
+ rrule_str = _rrule_with_until(
2601
+ rrule_str,
2602
+ end_date,
2603
+ _until_anchor(
2604
+ dtstart.dt if dtstart else None,
2605
+ event_data.get("start_datetime"),
2606
+ ),
2607
+ replace=not caller_supplied_rule,
2608
+ )
2609
+ component["RRULE"] = vRecur.from_ical(rrule_str)
2610
+ elif "RRULE" in component:
2611
+ if event_data.get("recurrence_end_date"):
2612
+ logger.warning(
2613
+ "recurrence_rule was cleared in the same update "
2614
+ "that set recurrence_end_date, so the series is "
2615
+ "removed and the end date has nothing to bound"
2616
+ )
2617
+ del component["RRULE"]
2618
+ elif event_data.get("recurrence_end_date"):
2619
+ # No stored rule and none supplied: there is nothing for
2620
+ # the end date to bound, and inventing a series from an
2621
+ # end date alone would be a guess.
2622
+ logger.warning(
2623
+ "recurrence_end_date was given for an event with no "
2624
+ "recurrence rule, so it has no effect; pass "
2625
+ "recurrence_rule as well to make the event recur"
2626
+ )
2627
+
2628
+ # Update timestamps
2629
+ now = dt.datetime.now(dt.UTC)
2630
+ component["LAST-MODIFIED"] = vDDDTypes(now)
2631
+ component["DTSTAMP"] = vDDDTypes(now)
2632
+
2633
+ # Ensure VTIMEZONE definitions exist for any TZID we just attached.
2634
+ existing_tzids = {
2635
+ str(sub.get("TZID", ""))
2636
+ for sub in cal.subcomponents
2637
+ if sub.name == "VTIMEZONE"
2638
+ }
2639
+ for zi in used_timezones:
2640
+ if str(zi) not in existing_tzids:
2641
+ cal.add_component(Timezone.from_tzinfo(zi))
2642
+
2643
+ break
2644
+
2645
+ return cal.to_ical().decode("utf-8")
2646
+
2647
+ # ============= Helper Methods - Todo iCalendar =============
2648
+
2649
+ def _ensure_timezone_aware(self, datetime_str: str) -> dt.datetime:
2650
+ """Parse datetime string and ensure it's timezone-aware.
2651
+
2652
+ If the datetime string doesn't include timezone info, interpret it as UTC.
2653
+ This ensures RFC 5545 compliance for CalDAV/iCalendar properties.
2654
+
2655
+ Args:
2656
+ datetime_str: ISO format datetime string (e.g., "2025-10-19T14:30:00" or "2025-10-19T14:30:00Z")
2657
+
2658
+ Returns:
2659
+ Timezone-aware datetime object
2660
+ """
2661
+ # Replace 'Z' with '+00:00' for consistent parsing
2662
+ datetime_str = datetime_str.replace("Z", "+00:00")
2663
+
2664
+ # Parse the datetime
2665
+ parsed_dt = dt.datetime.fromisoformat(datetime_str)
2666
+
2667
+ # If timezone-naive, assume UTC
2668
+ if parsed_dt.tzinfo is None:
2669
+ parsed_dt = parsed_dt.replace(tzinfo=dt.UTC)
2670
+
2671
+ # Normalize fixed offsets to UTC so no TZID="UTC+02:00" is emitted.
2672
+ return parsed_dt.astimezone(dt.UTC)
2673
+
2674
+ @staticmethod
2675
+ def _is_date_only(value: str) -> bool:
2676
+ """Whether an ISO string names a whole day rather than an instant."""
2677
+ try:
2678
+ dt.date.fromisoformat(value)
2679
+ except ValueError:
2680
+ return False
2681
+ return True
2682
+
2683
+ def _parse_todo_date(self, value: str, *, date_only: bool) -> dt.date | dt.datetime:
2684
+ """Parse a VTODO DUE/DTSTART value, keeping a whole day as a DATE.
2685
+
2686
+ RFC 5545 allows both DATE and DATE-TIME here, and ``date_only`` says
2687
+ which the pair resolved to. Widening a date to midnight UTC (issue
2688
+ #1274) both changes the value the caller gets back and lands on the
2689
+ wrong day for anyone west of UTC.
2690
+ """
2691
+ return (
2692
+ dt.date.fromisoformat(value)
2693
+ if date_only
2694
+ else self._ensure_timezone_aware(value)
2695
+ )
2696
+
2697
+ def _create_ical_todo(self, todo_data: dict[str, Any], todo_uid: str) -> str:
2698
+ """Create iCalendar VTODO content from todo data."""
2699
+ cal = Calendar()
2700
+ cal.add("prodid", "-//Nextcloud MCP Server//EN")
2701
+ cal.add("version", "2.0")
2702
+
2703
+ todo = ICalTodo()
2704
+ todo.add("uid", todo_uid)
2705
+ todo.add("summary", todo_data.get("summary", ""))
2706
+ todo.add("description", todo_data.get("description", ""))
2707
+
2708
+ # Status
2709
+ status = todo_data.get("status", "NEEDS-ACTION").upper()
2710
+ todo.add("status", status)
2711
+
2712
+ # Priority (0-9, 0=undefined)
2713
+ priority = todo_data.get("priority", 0)
2714
+ todo.add("priority", priority)
2715
+
2716
+ # Percent complete
2717
+ percent = todo_data.get("percent_complete", 0)
2718
+ todo.add("percent-complete", percent)
2719
+
2720
+ # Due / start dates. RFC 5545 §3.8.2.3 ties DUE's value type to
2721
+ # DTSTART's, so the pair decides together: date-only on every supplied
2722
+ # side is an all-day task (DATE), a time on either side keeps both as
2723
+ # DATE-TIME.
2724
+ due = todo_data.get("due", "")
2725
+ dtstart = todo_data.get("dtstart", "")
2726
+ date_only = all(self._is_date_only(v) for v in (due, dtstart) if v)
2727
+
2728
+ if due:
2729
+ todo.add("due", vDDDTypes(self._parse_todo_date(due, date_only=date_only)))
2730
+
2731
+ if dtstart:
2732
+ todo.add(
2733
+ "dtstart",
2734
+ vDDDTypes(self._parse_todo_date(dtstart, date_only=date_only)),
2735
+ )
2736
+
2737
+ # Completed timestamp
2738
+ completed = todo_data.get("completed", "")
2739
+ if completed:
2740
+ completed_dt = self._ensure_timezone_aware(completed)
2741
+ todo.add("completed", vDDDTypes(completed_dt))
2742
+
2743
+ # Categories
2744
+ categories = todo_data.get("categories", "")
2745
+ if categories:
2746
+ todo.add("categories", categories.split(","))
2747
+
2748
+ # Alarms/reminders
2749
+ self._apply_reminders(
2750
+ todo, todo_data, todo_data.get("summary", ""), _TODO_REMINDER_DESCRIPTION
2751
+ )
2752
+
2753
+ # Add timestamps
2754
+ now = dt.datetime.now(dt.UTC)
2755
+ todo.add("created", now)
2756
+ todo.add("dtstamp", now)
2757
+ todo.add("last-modified", now)
2758
+
2759
+ cal.add_component(todo)
2760
+ return cal.to_ical().decode("utf-8")
2761
+
2762
+ @staticmethod
2763
+ def _select_master_vtodo(cal: Any) -> Any | None:
2764
+ """Pick the master VTODO from a resource.
2765
+
2766
+ A recurring todo may carry its modified instances in the same resource,
2767
+ each tagged with a RECURRENCE-ID. Taking the first component in document
2768
+ order would let such an override shadow the series, so prefer the
2769
+ component without a RECURRENCE-ID.
2770
+ """
2771
+ components = list(cal.walk("VTODO"))
2772
+ for component in components:
2773
+ if "recurrence-id" not in component:
2774
+ return component
2775
+ return components[0] if components else None
2776
+
2777
+ def _pending_todo_occurrences(
2778
+ self, cal: Any, master: Any, now: dt.datetime | None = None
2779
+ ) -> dict[str, Any]:
2780
+ """Summarise the unfinished occurrences of a recurring VTODO.
2781
+
2782
+ CalDAV never expands VTODO recurrences: a ``calendar-query`` hands back
2783
+ the whole resource, and the master component's DTSTART/DUE describe the
2784
+ *first* instance of the series. Reporting those verbatim makes a live
2785
+ monthly chore from 2023 look years overdue, so the recurrence set is
2786
+ expanded client-side — the same approach
2787
+ :meth:`_expand_event_occurrences` already takes for VEVENT.
2788
+
2789
+ Expansion applies EXDATE and RECURRENCE-ID overrides, which is what
2790
+ makes per-instance completion visible: clients that materialise
2791
+ recurrences write a ``STATUS:COMPLETED`` override per finished instance.
2792
+ An occurrence counts as pending when it has started
2793
+ (``DTSTART <= now``) and is not done — the same rule task apps use to
2794
+ decide what to show, so the result matches what the user sees there.
2795
+
2796
+ Returns ``pending_count`` plus the oldest and newest pending occurrence.
2797
+ An empty dict means the recurrence could not be resolved at all, leaving
2798
+ the master's DTSTART/DUE as the only answer.
2799
+ """
2800
+ dtstart = master.get("dtstart")
2801
+ if not master.get("rrule") or not dtstart:
2802
+ return {}
2803
+
2804
+ now = now or dt.datetime.now(dt.UTC)
2805
+ # `between` returns occurrences overlapping the window, so an instance
2806
+ # that has started but is not yet due is included.
2807
+ window_start = max(_as_utc_datetime(dtstart.dt), now - _PENDING_MAX_LOOKBACK)
2808
+ if window_start >= now:
2809
+ # The series only begins in the future, so nothing has started and
2810
+ # there is no backlog. Querying this span would ask for a window
2811
+ # that ends before it starts, which the expander rejects.
2812
+ return {"pending_count": 0}
2813
+
2814
+ try:
2815
+ occurrences = recurring_ical_events.of(cal, components=["VTODO"]).between(
2816
+ window_start, now
2817
+ )
2818
+ except Exception as e:
2819
+ logger.warning(
2820
+ "Client-side VTODO recurrence expansion failed (%s); "
2821
+ "falling back to the master DTSTART/DUE",
2822
+ e,
2823
+ )
2824
+ return {}
2825
+
2826
+ pending = sorted(
2827
+ (
2828
+ occ
2829
+ for occ in occurrences
2830
+ if occ.get("dtstart") and not _occurrence_is_done(occ)
2831
+ ),
2832
+ key=lambda occ: _as_utc_datetime(occ.get("dtstart").dt),
2833
+ )
2834
+ if not pending:
2835
+ # Every started occurrence is done — the series is up to date.
2836
+ return {"pending_count": 0}
2837
+
2838
+ oldest, newest = pending[0], pending[-1]
2839
+ occurrence_data: dict[str, Any] = {
2840
+ "pending_count": len(pending),
2841
+ "oldest_pending_dtstart": oldest.get("dtstart").dt.isoformat(),
2842
+ "current_dtstart": newest.get("dtstart").dt.isoformat(),
2843
+ }
2844
+ if oldest.get("due"):
2845
+ occurrence_data["oldest_pending_due"] = oldest.get("due").dt.isoformat()
2846
+ if newest.get("due"):
2847
+ occurrence_data["current_due"] = newest.get("due").dt.isoformat()
2848
+ return occurrence_data
2849
+
2850
+ def _parse_ical_todo(
2851
+ self, ical_text: str, now: dt.datetime | None = None
2852
+ ) -> dict[str, Any] | None:
2853
+ """Parse iCalendar text and extract todo data.
2854
+
2855
+ ``now`` overrides the reference instant used to resolve which occurrence
2856
+ of a recurring todo is the current one (injected by tests).
2857
+ """
2858
+ try:
2859
+ cal = Calendar.from_ical(ical_text)
2860
+ component = self._select_master_vtodo(cal)
2861
+ if component is None:
2862
+ return None
2863
+
2864
+ todo_data = {
2865
+ "uid": str(component.get("uid", "")),
2866
+ "summary": str(component.get("summary", "")),
2867
+ "description": str(component.get("description", "")),
2868
+ "status": str(component.get("status", "NEEDS-ACTION")),
2869
+ "priority": int(component.get("priority", 0)),
2870
+ "percent_complete": int(component.get("percent-complete", 0)),
2871
+ }
2872
+
2873
+ # Handle due date
2874
+ due = component.get("due")
2875
+ if due:
2876
+ todo_data["due"] = due.dt.isoformat()
2877
+
2878
+ # Handle start date
2879
+ dtstart = component.get("dtstart")
2880
+ if dtstart:
2881
+ todo_data["dtstart"] = dtstart.dt.isoformat()
2882
+
2883
+ # Handle completed date
2884
+ completed = component.get("completed")
2885
+ if completed:
2886
+ todo_data["completed"] = completed.dt.isoformat()
2887
+
2888
+ # Handle categories
2889
+ categories = component.get("categories")
2890
+ if categories:
2891
+ todo_data["categories"] = self._extract_categories(categories)
2892
+
2893
+ # Handle recurrence. DTSTART/DUE stay as stored so that updates keep
2894
+ # addressing the series, while the pending_* / current_* fields
2895
+ # describe the instances a caller should reason about today.
2896
+ rrule = component.get("rrule")
2897
+ if rrule:
2898
+ todo_data["recurring"] = True
2899
+ todo_data["recurrence_rule"] = _rrule_to_string(rrule)
2900
+ todo_data.update(self._pending_todo_occurrences(cal, component, now))
2901
+
2902
+ reminders = self._extract_valarms(component)
2903
+ if reminders:
2904
+ todo_data["reminders"] = reminders
2905
+
2906
+ return todo_data
2907
+
2908
+ except Exception as e:
2909
+ logger.error("Error parsing iCalendar todo: %s", e)
2910
+ return None
2911
+
2912
+ def _merge_ical_todo_properties(
2913
+ self, raw_ical: str, todo_data: dict[str, Any]
2914
+ ) -> str:
2915
+ """Merge new todo data into existing raw iCal while preserving all properties.
2916
+
2917
+ The todo's own ``UID`` is carried through from ``raw_ical`` like any other
2918
+ preserved property, so no ``todo_uid`` argument is needed. (One used to be
2919
+ required solely by the removed rebuild fallback.)
2920
+
2921
+ Raises on any merge failure rather than substituting a synthesised todo.
2922
+ This previously caught every exception and fell back to
2923
+ ``_create_ical_todo(todo_data, ...)``, which rebuilds the todo from the
2924
+ *partial update dict* — destroying summary, due date, dtstart, completed
2925
+ timestamp, categories, RRULE, alarms and every custom property the caller
2926
+ did not happen to pass, while reporting success.
2927
+ """
2928
+ logger.debug("Merging todo properties: %s", list(todo_data.keys()))
2929
+ cal = Calendar.from_ical(raw_ical)
2930
+
2931
+ for component in cal.walk():
2932
+ if component.name == "VTODO":
2933
+ # Update only provided properties
2934
+ if "summary" in todo_data:
2935
+ component["SUMMARY"] = todo_data["summary"]
2936
+ if "description" in todo_data:
2937
+ component["DESCRIPTION"] = todo_data["description"]
2938
+ if "status" in todo_data:
2939
+ status_value = todo_data["status"].upper()
2940
+ component["STATUS"] = status_value
2941
+ logger.debug("Set STATUS to %s", status_value)
2942
+ if "priority" in todo_data:
2943
+ component["PRIORITY"] = todo_data["priority"]
2944
+ if "percent_complete" in todo_data:
2945
+ percent_value = todo_data["percent_complete"]
2946
+ component["PERCENT-COMPLETE"] = percent_value
2947
+ logger.debug("Set PERCENT-COMPLETE to %s", percent_value)
2948
+
2949
+ # Due / start dates, paired the same way as
2950
+ # _create_ical_todo — except a side that isn't being
2951
+ # updated votes with the value type already stored.
2952
+ supplied = {
2953
+ prop: todo_data[prop]
2954
+ for prop in ("due", "dtstart")
2955
+ if todo_data.get(prop)
2956
+ }
2957
+ date_only = all(
2958
+ self._is_date_only(v) for v in supplied.values()
2959
+ ) and all(
2960
+ self._stored_is_all_day(component, prop.upper()) is not False
2961
+ for prop in ("due", "dtstart")
2962
+ if prop not in supplied
2963
+ )
2964
+
2965
+ # A partial update cannot flip one half of the pair on its
2966
+ # own: writing the supplied side as a DATE-TIME while the
2967
+ # side left out stays a stored DATE is exactly the mismatch
2968
+ # §3.8.2.3 forbids, and there is no defensible time of day
2969
+ # to invent for the property the caller didn't mention.
2970
+ # _validate_all_day_flip rejects the same flip for VEVENT.
2971
+ stranded = [
2972
+ prop
2973
+ for prop in ("due", "dtstart")
2974
+ if supplied
2975
+ and not date_only
2976
+ and prop not in supplied
2977
+ and self._stored_is_all_day(component, prop.upper())
2978
+ ]
2979
+ if stranded:
2980
+ raise ValueError(
2981
+ "changing a whole-day todo to a timed one requires "
2982
+ f"passing {' and '.join(sorted(supplied.keys() | set(stranded)))} "
2983
+ "together, so DUE and DTSTART cannot end up with "
2984
+ "mismatched value types"
2985
+ )
2986
+
2987
+ for prop, value in supplied.items():
2988
+ parsed = self._parse_todo_date(value, date_only=date_only)
2989
+ component[prop.upper()] = vDDDTypes(parsed)
2990
+ logger.debug("Set %s to %s", prop.upper(), parsed)
2991
+
2992
+ # Handle completed date
2993
+ if "completed" in todo_data:
2994
+ completed_str = todo_data["completed"]
2995
+ if completed_str:
2996
+ completed_dt = self._ensure_timezone_aware(completed_str)
2997
+ component["COMPLETED"] = vDDDTypes(completed_dt)
2998
+ logger.debug("Set COMPLETED to %s", completed_dt)
2999
+
3000
+ # Handle categories
3001
+ if "categories" in todo_data:
3002
+ categories_str = todo_data["categories"]
3003
+ if categories_str:
3004
+ component["CATEGORIES"] = [
3005
+ c.strip() for c in categories_str.split(",")
3006
+ ]
3007
+ logger.debug("Set CATEGORIES to %s", categories_str)
3008
+
3009
+ # Handle reminders (VALARM)
3010
+ self._apply_reminders(
3011
+ component,
3012
+ todo_data,
3013
+ todo_data.get("summary") or str(component.get("summary", "")),
3014
+ _TODO_REMINDER_DESCRIPTION,
3015
+ )
3016
+
3017
+ # Update timestamps
3018
+ now = dt.datetime.now(dt.UTC)
3019
+ component["LAST-MODIFIED"] = vDDDTypes(now)
3020
+ component["DTSTAMP"] = vDDDTypes(now)
3021
+
3022
+ break
3023
+
3024
+ return cal.to_ical().decode("utf-8")
3025
+
3026
+ # ============= Helper Methods - Filtering =============
3027
+
3028
+ def _extract_categories(self, categories_obj) -> str:
3029
+ """Extract categories from icalendar object to string."""
3030
+ if not categories_obj:
3031
+ return ""
3032
+
3033
+ try:
3034
+ if hasattr(categories_obj, "cats"):
3035
+ # Handle Categories object with cats attribute
3036
+ return ", ".join(str(cat) for cat in categories_obj.cats)
3037
+ elif hasattr(categories_obj, "__iter__") and not isinstance(
3038
+ categories_obj, str
3039
+ ):
3040
+ # Handle list of vCategory objects or strings
3041
+ result = []
3042
+ for cat in categories_obj:
3043
+ # Try to extract value from vCategory objects using to_ical()
3044
+ if hasattr(cat, "to_ical"):
3045
+ result.append(cat.to_ical().decode("utf-8"))
3046
+ else:
3047
+ result.append(str(cat))
3048
+ return ", ".join(result)
3049
+ else:
3050
+ # Handle single category string or object
3051
+ if hasattr(categories_obj, "to_ical"):
3052
+ return categories_obj.to_ical().decode("utf-8")
3053
+ return str(categories_obj)
3054
+ except Exception as e:
3055
+ logger.warning("Error extracting categories: %s", e)
3056
+ return str(categories_obj)
3057
+
3058
+ def _event_matches_filters(
3059
+ self, event: dict[str, Any], filters: dict[str, Any]
3060
+ ) -> bool:
3061
+ """Check if an event matches the provided filters."""
3062
+ try:
3063
+ # Filter by minimum attendees
3064
+ if "min_attendees" in filters:
3065
+ attendees = event.get("attendees", "")
3066
+ attendee_count = len(attendees.split(",")) if attendees else 0
3067
+ if attendee_count < filters["min_attendees"]:
3068
+ return False
3069
+
3070
+ # Filter by categories
3071
+ if "categories" in filters:
3072
+ event_categories = event.get("categories", "").lower()
3073
+ required_categories = [cat.lower() for cat in filters["categories"]]
3074
+ if not any(cat in event_categories for cat in required_categories):
3075
+ return False
3076
+
3077
+ # Filter by status
3078
+ if "status" in filters:
3079
+ if event.get("status", "").upper() != filters["status"].upper():
3080
+ return False
3081
+
3082
+ # Filter by title contains
3083
+ if "title_contains" in filters:
3084
+ title = event.get("title", "").lower()
3085
+ search_term = filters["title_contains"].lower()
3086
+ if search_term not in title:
3087
+ return False
3088
+
3089
+ # Filter by location contains
3090
+ if "location_contains" in filters:
3091
+ location = event.get("location", "").lower()
3092
+ search_term = filters["location_contains"].lower()
3093
+ if search_term not in location:
3094
+ return False
3095
+
3096
+ # Filter by minimum duration. An event without an end is
3097
+ # zero-length; all-day dates parse as midnight, so a one-day
3098
+ # all-day event lasts 1440 minutes.
3099
+ if "min_duration_minutes" in filters:
3100
+ start = dt.datetime.fromisoformat(event["start_datetime"])
3101
+ end = dt.datetime.fromisoformat(
3102
+ event.get("end_datetime") or event["start_datetime"]
3103
+ )
3104
+ if (end - start) < dt.timedelta(
3105
+ minutes=filters["min_duration_minutes"]
3106
+ ):
3107
+ return False
3108
+
3109
+ return True
3110
+
3111
+ except Exception:
3112
+ # Fail open: an unreadable event stays in the result rather than
3113
+ # vanishing. Logged, since a filter bug would otherwise match all.
3114
+ logger.warning(
3115
+ "Event filter failed; keeping event %r", event.get("uid"), exc_info=True
3116
+ )
3117
+ return True
3118
+
3119
+ def _todo_matches_filters(
3120
+ self, todo: dict[str, Any], filters: dict[str, Any]
3121
+ ) -> bool:
3122
+ """Check if a todo matches the provided filters."""
3123
+ try:
3124
+ # Filter by status
3125
+ if "status" in filters:
3126
+ if todo.get("status", "").upper() != filters["status"].upper():
3127
+ return False
3128
+
3129
+ # Filter by minimum priority
3130
+ if "min_priority" in filters:
3131
+ priority = todo.get("priority", 0)
3132
+ if priority == 0 or priority > filters["min_priority"]:
3133
+ return False
3134
+
3135
+ # Filter by categories
3136
+ if "categories" in filters:
3137
+ todo_categories = todo.get("categories", "").lower()
3138
+ required_categories = [cat.lower() for cat in filters["categories"]]
3139
+ if not any(cat in todo_categories for cat in required_categories):
3140
+ return False
3141
+
3142
+ # Filter by summary contains
3143
+ if "summary_contains" in filters:
3144
+ summary = todo.get("summary", "").lower()
3145
+ search_term = filters["summary_contains"].lower()
3146
+ if search_term not in summary:
3147
+ return False
3148
+
3149
+ return True
3150
+
3151
+ except Exception:
3152
+ # Fail open, logged: see _event_matches_filters.
3153
+ logger.warning(
3154
+ "Todo filter failed; keeping todo %r", todo.get("uid"), exc_info=True
3155
+ )
3156
+ return True
3157
+
3158
+ # ============= Legacy Methods (for backward compatibility) =============
3159
+
3160
+ @staticmethod
3161
+ def _bulk_targets(
3162
+ events: list[dict[str, Any]], apply_to_series: bool, operation: str
3163
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
3164
+ """Split matched events into ``(targets, skipped)``, one entry per stored event.
3165
+
3166
+ A date-window listing expands a recurring series into one dict per
3167
+ occurrence, but every write is by UID and hits the whole series (#1499).
3168
+ So each (calendar, UID) is acted on once, and a recurring series only
3169
+ when ``apply_to_series`` is set. ``move`` recreates the event from the
3170
+ occurrence's fields, which would flatten the series, so it never takes one.
3171
+ """
3172
+ targets: list[dict[str, Any]] = []
3173
+ skipped: list[dict[str, Any]] = []
3174
+ seen: set[tuple[Any, str]] = set()
3175
+ for event in events:
3176
+ key = (event.get("calendar_name"), event["uid"])
3177
+ if key in seen:
3178
+ continue
3179
+ seen.add(key)
3180
+ in_series = event.get("recurring") or event.get("recurrence_id")
3181
+ if in_series and (operation == "move" or not apply_to_series):
3182
+ skipped.append(
3183
+ {
3184
+ "uid": event["uid"],
3185
+ "status": "skipped",
3186
+ "title": event.get("title", ""),
3187
+ "error": (
3188
+ "recurring series cannot be moved in bulk"
3189
+ if operation == "move"
3190
+ else "part of a recurring series; the "
3191
+ f"{operation} would apply to every occurrence. "
3192
+ "Pass apply_to_series=true to confirm."
3193
+ ),
3194
+ }
3195
+ )
3196
+ else:
3197
+ targets.append(event)
3198
+ return targets, skipped
3199
+
3200
+ async def bulk_update_events(
3201
+ self,
3202
+ filter_criteria: dict[str, Any],
3203
+ update_data: dict[str, Any],
3204
+ apply_to_series: bool = False,
3205
+ ) -> dict[str, Any]:
3206
+ """Bulk update events matching filter criteria."""
3207
+ await self._ensure_calendar_home()
3208
+ try:
3209
+ start_datetime = None
3210
+ end_datetime = None
3211
+ if "start_date" in filter_criteria and filter_criteria["start_date"]:
3212
+ start_datetime = dt.datetime.fromisoformat(
3213
+ filter_criteria["start_date"]
3214
+ )
3215
+ if "end_date" in filter_criteria and filter_criteria["end_date"]:
3216
+ end_datetime = dt.datetime.fromisoformat(filter_criteria["end_date"])
3217
+
3218
+ events = await self.search_events_across_calendars(
3219
+ start_datetime=start_datetime,
3220
+ end_datetime=end_datetime,
3221
+ filters=filter_criteria,
3222
+ limit=BULK_EVENT_LIMIT,
3223
+ )
3224
+
3225
+ targets, skipped = self._bulk_targets(events, apply_to_series, "update")
3226
+ updated_count = 0
3227
+ failed_count = 0
3228
+ results = list(skipped)
3229
+
3230
+ for event in targets:
3231
+ try:
3232
+ await self.update_event(
3233
+ event["calendar_name"], event["uid"], update_data
3234
+ )
3235
+ updated_count += 1
3236
+ results.append(
3237
+ {
3238
+ "uid": event["uid"],
3239
+ "status": "updated",
3240
+ "title": event.get("title", ""),
3241
+ }
3242
+ )
3243
+ except Exception as e:
3244
+ failed_count += 1
3245
+ results.append(
3246
+ {
3247
+ "uid": event["uid"],
3248
+ "status": "failed",
3249
+ "error": str(e),
3250
+ "title": event.get("title", ""),
3251
+ }
3252
+ )
3253
+
3254
+ return {
3255
+ "total_found": len(targets) + len(skipped),
3256
+ "updated_count": updated_count,
3257
+ "failed_count": failed_count,
3258
+ "skipped_count": len(skipped),
3259
+ "results": results,
3260
+ }
3261
+
3262
+ except Exception as e:
3263
+ logger.error("Error in bulk update: %s", e)
3264
+ raise
3265
+
3266
+ @staticmethod
3267
+ def _availability_timezone(name: Any) -> dt.tzinfo:
3268
+ """Resolve the zone the windows are built in, refusing a bad name.
3269
+
3270
+ Deliberately not ``_resolve_timezone``, which falls back to floating
3271
+ local time on an unknown name. That is right for storing an event --
3272
+ the time was still given -- but wrong here: business hours and
3273
+ preferred times mean nothing without the zone they are expressed in, so
3274
+ ``timezone="America/New_Yrok"`` would answer confidently in the
3275
+ server's zone and never say it had ignored the request.
3276
+ """
3277
+ text = str(name or "").strip()
3278
+ if not text:
3279
+ # The server's *current* UTC offset, not its IANA zone -- the
3280
+ # stdlib cannot name the latter. A window that crosses a DST change
3281
+ # is therefore built on today's offset, which is the reason to pass
3282
+ # an explicit zone rather than rely on this.
3283
+ return dt.datetime.now().astimezone().tzinfo or dt.UTC
3284
+ try:
3285
+ return ZoneInfo(text)
3286
+ except (ZoneInfoNotFoundError, ValueError) as e:
3287
+ raise ValueError(
3288
+ f"Unknown timezone {text!r}; expected an IANA name such as "
3289
+ "'Europe/Amsterdam'"
3290
+ ) from e
3291
+
3292
+ async def _attendee_busy_spans(
3293
+ self,
3294
+ attendees: list[str],
3295
+ start: dt.datetime,
3296
+ end: dt.datetime,
3297
+ tz: dt.tzinfo,
3298
+ ) -> list[Span]:
3299
+ """Busy spans for other people, via the RFC 6638 scheduling outbox.
3300
+
3301
+ The organizer POSTs a VFREEBUSY REQUEST naming the attendees and the
3302
+ server answers with one free/busy reply per recipient. This is the only
3303
+ way to see time on a calendar we cannot read.
3304
+
3305
+ An attendee the server refuses to report on raises rather than being
3306
+ skipped: treating "I could not check Bob" as "Bob is free" is exactly
3307
+ the kind of confident-wrong answer issue #1394 is about.
3308
+ """
3309
+ get_principal = getattr(self._dav_client, "get_principal", None)
3310
+ principal = await _maybe_await(
3311
+ get_principal() if get_principal else self._dav_client.principal()
3312
+ )
3313
+
3314
+ recipients = [
3315
+ address if address.lower().startswith(_MAILTO) else f"{_MAILTO}{address}"
3316
+ for address in attendees
3317
+ ]
3318
+ replies = await _maybe_await(principal.freebusy_request(start, end, recipients))
3319
+
3320
+ # Keys come back as the recipient URI the server echoes, whose case and
3321
+ # mailto: prefix need not match what we sent.
3322
+ by_address = {
3323
+ key.lower().removeprefix(_MAILTO): value
3324
+ for key, value in replies.items()
3325
+ if key != "errors"
3326
+ }
3327
+ error_by_address = {
3328
+ key.lower().removeprefix(_MAILTO): value
3329
+ for key, value in (replies.get("errors") or {}).items()
3330
+ }
3331
+
3332
+ spans: list[Span] = []
3333
+ for recipient in recipients:
3334
+ address = recipient.lower().removeprefix(_MAILTO)
3335
+ if address in error_by_address:
3336
+ raise ValueError(
3337
+ f"Free/busy lookup for {address} failed: "
3338
+ f"{error_by_address[address]}"
3339
+ )
3340
+ reply = by_address.get(address)
3341
+ if reply is None or not reply.data:
3342
+ raise ValueError(
3343
+ f"The server returned no free/busy information for {address}"
3344
+ )
3345
+ spans.extend(busy_spans_from_vfreebusy(reply.data, tz))
3346
+ return spans
3347
+
3348
+ async def find_availability(
3349
+ self,
3350
+ duration_minutes: int,
3351
+ attendees: list[str] | None = None,
3352
+ start_datetime: dt.datetime | None = None,
3353
+ end_datetime: dt.datetime | None = None,
3354
+ constraints: dict[str, Any] | None = None,
3355
+ ) -> dict[str, Any]:
3356
+ """Find free time slots of at least ``duration_minutes``.
3357
+
3358
+ Busy time is every opaque, non-cancelled event in the user's own
3359
+ calendars within the window, plus -- when ``attendees`` are given --
3360
+ each attendee's free/busy as reported by the scheduling outbox. What is
3361
+ left of the candidate windows (``constraints``) is returned as maximal
3362
+ free spans, longest-possible rather than sliced onto a grid.
3363
+
3364
+ ``constraints`` keys: ``business_hours_only``, ``exclude_weekends``,
3365
+ ``preferred_times``, ``include_all_day``, ``timezone``. An unknown
3366
+ ``timezone`` raises; a malformed entry in ``preferred_times`` is logged
3367
+ and skipped, since one typo in a hint should not fail the query, and
3368
+ overlapping entries are merged.
3369
+
3370
+ Returns the slots together with the window they were computed over, so
3371
+ the caller can report what was actually searched rather than echoing a
3372
+ request that may have left the range open.
3373
+ """
3374
+ if duration_minutes <= 0:
3375
+ raise ValueError("duration_minutes must be positive")
3376
+
3377
+ constraints = constraints or {}
3378
+ tz = self._availability_timezone(constraints.get("timezone"))
3379
+
3380
+ now = dt.datetime.now(tz)
3381
+ start = to_aware(start_datetime, tz) or now
3382
+ # A slot in the past is not availability, whatever the caller asked for.
3383
+ start = max(start, now)
3384
+ end = to_aware(end_datetime, tz) or start + dt.timedelta(days=7)
3385
+ if end <= start:
3386
+ raise ValueError("date_range_end must be after date_range_start")
3387
+
3388
+ # strict: a calendar that failed to load contributes no busy time, so a
3389
+ # silent skip would offer its booked hours as free -- the same reason
3390
+ # _attendee_busy_spans raises rather than shrugging off a missing reply.
3391
+ events = await self.search_events_across_calendars(
3392
+ start_datetime=start,
3393
+ end_datetime=end,
3394
+ limit=AVAILABILITY_EVENT_LIMIT,
3395
+ strict=True,
3396
+ )
3397
+ busy = busy_spans_from_events(
3398
+ events,
3399
+ tz=tz,
3400
+ include_all_day=bool(constraints.get("include_all_day")),
3401
+ )
3402
+
3403
+ attendees = [address for address in (attendees or []) if address.strip()]
3404
+ if attendees:
3405
+ busy.extend(await self._attendee_busy_spans(attendees, start, end, tz))
3406
+
3407
+ windows = daily_windows(
3408
+ start,
3409
+ end,
3410
+ tz=tz,
3411
+ business_hours_only=bool(constraints.get("business_hours_only", True)),
3412
+ exclude_weekends=bool(constraints.get("exclude_weekends", True)),
3413
+ preferred_times=parse_time_ranges(constraints.get("preferred_times")),
3414
+ )
3415
+ slots = free_slots(windows, busy, dt.timedelta(minutes=duration_minutes))
3416
+
3417
+ logger.debug(
3418
+ "Found %d free slot(s) of >=%d min between %s and %s (%d busy span(s))",
3419
+ len(slots),
3420
+ duration_minutes,
3421
+ start,
3422
+ end,
3423
+ len(busy),
3424
+ )
3425
+ return {
3426
+ "slots": [slot_to_dict(slot) for slot in slots],
3427
+ "range_start": start.isoformat(),
3428
+ "range_end": end.isoformat(),
3429
+ "attendees_checked": attendees,
3430
+ }