Skip to content

Commit 5c4168c

Browse files
Merge pull request #49 from pycalendar/feat/free-busy-queries
Free/busy queries
2 parents 514b84c + 519c7fe commit 5c4168c

12 files changed

Lines changed: 1360 additions & 51 deletions

File tree

‎news/13.bugfix.1.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``get_availability`` no longer silently returns the wrong account's busy intervals when asked about more than one account. ``Principal/getAvailability`` has no ``accountId`` argument, so it can only ever report on the account you are authenticated as; any other account id in the request now always goes through the ``CalendarEvent/query`` fallback, which does scope to an explicit account, instead of returning the same primary account's data twice under different keys.

‎news/13.bugfix.2.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``get_availability``'s ``CalendarEvent/query`` fallback now converts each event's start and end time to UTC correctly, using the event's own time zone. It previously returned the JSCalendar ``start`` value unconverted, which is only correct when the event's time zone happens to be UTC; for any other time zone the fallback path returned a busy interval offset from the real one.

‎news/13.feature.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Added ``get_availability`` on both ``JMAPClient`` and ``AsyncJMAPClient``, returning busy intervals for one or more accounts over a time period. For your own account, it tries ``Principal/getAvailability`` first (draft-ietf-jmap-calendars, section 2.2), using your own Principal id straight from the session with no extra round trip. The issue that requested this named the primary method as ``CalendarEvent/free``, which does not exist in the spec; ``Principal/getAvailability`` is the real one, confirmed by reading the spec directly and by testing it live against both Cyrus and Stalwart.
2+
3+
For any other account, and for your own account if it lacks ``Principal/getAvailability`` support, ``get_availability`` falls back to a ``CalendarEvent/query`` scan with recurrence expansion, so a recurring event contributes one interval per occurrence rather than one for the whole series. Checking someone else's availability by email is not supported yet, the same limitation ``share_calendar`` already has for Principal ids in general.

‎src/calendaring_jmap/_methods/event.py‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,19 +112,35 @@ def build_event_query(
112112
sort: list[dict] | None = None,
113113
position: int = 0,
114114
limit: int | None = None,
115+
expand_recurrences: bool = False,
116+
time_zone: str | None = None,
115117
) -> tuple:
116118
"""Build a ``CalendarEvent/query`` method call tuple.
117119
118120
Args:
119121
account_id: The JMAP accountId to query.
120122
filter_condition: A ``FilterCondition`` or ``FilterOperator`` dict, e.g.
121-
``{"after": "2024-01-01T00:00:00Z", "before": "2024-12-31T23:59:59Z"}``.
122-
``None`` means no filter (return all events).
123+
``{"after": "2024-01-01T00:00:00", "before": "2024-12-31T23:59:59"}``.
124+
``after``/``before`` are ``LocalDateTime`` (no ``Z``/UTC suffix;
125+
confirmed live against Cyrus, which rejects a ``Z``-suffixed
126+
value with ``invalidArguments``). ``None`` means no filter
127+
(return all events).
123128
sort: List of ``Comparator`` dicts, e.g.
124129
``[{"property": "start", "isAscending": True}]``.
125130
``None`` means server default ordering.
126131
position: Zero-based index of the first result to return.
127132
limit: Maximum number of IDs to return. ``None`` means no limit.
133+
expand_recurrences: If true, the server returns one synthetic id per
134+
matching occurrence of a recurring event instead of a single id
135+
for the whole series (JMAP Calendars §5.11). ``filter_condition``
136+
must then include both ``after`` and ``before``, or the server
137+
rejects the call with ``invalidArguments`` (confirmed live).
138+
Without this, a recurring series is still found by ``after``/
139+
``before`` but returned as one object carrying only the master
140+
occurrence's own ``start``, not whichever occurrence(s) actually
141+
fall in the window.
142+
time_zone: The time zone for ``after``/``before``, defaults to
143+
``Etc/UTC`` server-side if omitted.
128144
129145
Returns:
130146
A 3-tuple ``("CalendarEvent/query", arguments_dict, call_id)``.
@@ -136,6 +152,10 @@ def build_event_query(
136152
args["sort"] = sort
137153
if limit is not None:
138154
args["limit"] = limit
155+
if expand_recurrences:
156+
args["expandRecurrences"] = expand_recurrences
157+
if time_zone is not None:
158+
args["timeZone"] = time_zone
139159
return ("CalendarEvent/query", args, "ev-query-0")
140160

141161

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# SPDX-FileCopyrightText: 2026 calendaring-jmap contributors
2+
# SPDX-License-Identifier: AGPL-3.0-or-later
3+
4+
"""
5+
JMAP Principal method builders and response parsers.
6+
7+
These are pure functions — no HTTP, no state. They build the request
8+
tuples that go into a ``methodCalls`` list, and parse the corresponding
9+
``methodResponses`` entries.
10+
11+
``Principal/getAvailability`` is defined in draft-ietf-jmap-calendars §2.2,
12+
layered on the ``Principal`` object from RFC 9670 (JMAP Sharing). It is not
13+
a get/set/query method; it takes its own bespoke arguments and returns a
14+
list of ``BusyPeriod`` objects, also defined in that same section.
15+
"""
16+
17+
from __future__ import annotations
18+
19+
20+
def build_get_availability(
21+
principal_id: str,
22+
utc_start: str,
23+
utc_end: str,
24+
show_details: bool = False,
25+
event_properties: list[str] | None = None,
26+
) -> tuple:
27+
"""Build a ``Principal/getAvailability`` method call tuple.
28+
29+
Deliberately has no ``account_id`` parameter, unlike every other
30+
``build_*`` function in this package. Confirmed live against Cyrus:
31+
passing ``accountId`` inside this method's own arguments dict fails
32+
with ``invalidArguments: ["accountId"]``, even with a verified-correct
33+
value, while omitting it (so the server falls back to the
34+
authenticated user's own account) succeeds. Confirmed live against
35+
Stalwart that passing ``accountId`` explicitly works fine there, so
36+
omitting it is the one shape that works on both.
37+
38+
Args:
39+
principal_id: The id of the ``Principal`` to calculate availability
40+
for, from ``Session.account_capabilities`` (see
41+
``_JMAPClientBase._current_user_principal_id``) or ``Principal/get``.
42+
Not the same as a JMAP accountId.
43+
utc_start: Start of the period to check, inclusive, as a
44+
``UTCDateTime`` string (e.g. ``"2024-01-01T00:00:00Z"``).
45+
utc_end: End of the period to check, exclusive, as a ``UTCDateTime``
46+
string.
47+
show_details: If true, populate each returned ``BusyPeriod.event``
48+
with the underlying event, where the caller has ``mayReadItems``
49+
and the event isn't private. Confirmed live: Stalwart also
50+
requires ``event_properties`` to be set for this to take
51+
effect at all; omitting it returns ``event: null`` on Stalwart
52+
even with ``show_details=True``, unlike Cyrus which returns full
53+
details by default.
54+
event_properties: Which ``CalendarEvent`` properties to include in
55+
each returned event, when ``show_details`` is true. Confirmed
56+
live: Stalwart only supports ``["id"]``/``["baseEventId"]`` here,
57+
rejecting other property names with ``invalidArguments``.
58+
59+
Returns:
60+
A 3-tuple ``("Principal/getAvailability", arguments_dict, call_id)``.
61+
"""
62+
args: dict = {"id": principal_id, "utcStart": utc_start, "utcEnd": utc_end}
63+
if show_details:
64+
args["showDetails"] = show_details
65+
if event_properties is not None:
66+
args["eventProperties"] = event_properties
67+
return ("Principal/getAvailability", args, "principal-getavailability-0")
68+
69+
70+
def parse_get_availability(response_args: dict) -> list[dict]:
71+
"""Parse the arguments dict from a ``Principal/getAvailability`` response.
72+
73+
Args:
74+
response_args: The second element of a ``methodResponses`` entry
75+
whose method name is ``"Principal/getAvailability"``.
76+
77+
Returns:
78+
List of raw ``BusyPeriod`` dicts, each with ``utcStart``, ``utcEnd``,
79+
``busyStatus``, ``event`` (``None`` unless ``showDetails`` was set
80+
and permitted), and ``accountId``. Callers convert these to typed
81+
:class:`~calendaring_jmap.objects.busy_interval.BusyInterval`
82+
objects; this function does not.
83+
"""
84+
return response_args.get("list", [])

‎src/calendaring_jmap/async_client.py‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,10 @@
4444
build_event_set_create,
4545
build_event_set_destroy,
4646
build_event_set_update,
47+
parse_event_get,
4748
parse_event_set,
4849
)
50+
from calendaring_jmap._methods.principal import build_get_availability, parse_get_availability
4951
from calendaring_jmap._methods.task import (
5052
build_task_get,
5153
build_task_list_get,
@@ -54,14 +56,15 @@
5456
build_task_set_update,
5557
parse_task_set,
5658
)
57-
from calendaring_jmap.client import _DEFAULT_USING, _TASK_USING, _JMAPClientBase
59+
from calendaring_jmap.client import _DEFAULT_USING, _PRINCIPALS_USING, _TASK_USING, _JMAPClientBase
5860
from calendaring_jmap.constants import (
5961
PARTICIPATION_STATUS_ACCEPTED,
6062
PARTICIPATION_STATUS_DECLINED,
6163
PARTICIPATION_STATUS_TENTATIVE,
6264
)
6365
from calendaring_jmap.convert import ical_to_jscal
64-
from calendaring_jmap.error import JMAPAuthError, JMAPMethodError
66+
from calendaring_jmap.error import _DEFAULT_ERROR_TYPE, JMAPAuthError, JMAPMethodError
67+
from calendaring_jmap.objects.busy_interval import BusyInterval
6568
from calendaring_jmap.objects.calendar import JMAPCalendar
6669
from calendaring_jmap.objects.calendar_object import JMAPCalendarObject
6770
from calendaring_jmap.session import Session, async_fetch_session
@@ -198,7 +201,7 @@ async def _request(self, method_calls: list[tuple], using: list[str] | None = No
198201
for resp in method_responses:
199202
method_name, resp_args, call_id = resp
200203
if method_name == "error":
201-
error_type = resp_args.get("type", "serverError")
204+
error_type = resp_args.get("type", _DEFAULT_ERROR_TYPE)
202205
raise JMAPMethodError(
203206
url=session.api_url,
204207
reason=f"Method call failed: {resp_args}",
@@ -664,6 +667,60 @@ async def search_events(
664667
calendar_id=calendar_id, start=start, end=end, text=text, account_id=account_id
665668
)
666669

670+
async def get_availability(
671+
self,
672+
account_ids: list[str],
673+
start: str,
674+
end: str,
675+
show_details: bool = False,
676+
) -> dict[str, list[BusyInterval]]:
677+
"""Return busy intervals for each of your own accounts over a time period.
678+
679+
See :meth:`JMAPClient.get_availability` for the full semantics.
680+
"""
681+
session = await self._get_session()
682+
result: dict[str, list[BusyInterval]] = {}
683+
for account_id in account_ids:
684+
if self._can_use_principal_availability(session, account_id):
685+
principal_id = self._current_user_principal_id(session)
686+
if principal_id is not None:
687+
try:
688+
result[account_id] = await self._get_availability_via_principal(
689+
principal_id, start, end, show_details
690+
)
691+
continue
692+
except JMAPMethodError as e:
693+
if not self._should_fall_back_to_query(e.error_type):
694+
raise
695+
result[account_id] = await self._get_availability_via_fallback(account_id, start, end)
696+
return result
697+
698+
async def _get_availability_via_principal(
699+
self, principal_id: str, start: str, end: str, show_details: bool
700+
) -> list[BusyInterval]:
701+
session = await self._get_session()
702+
call = build_get_availability(
703+
principal_id,
704+
self._as_utc_datetime(start),
705+
self._as_utc_datetime(end),
706+
show_details=show_details,
707+
)
708+
responses = await self._request([call], using=_PRINCIPALS_USING)
709+
for method_name, resp_args, _ in responses:
710+
if method_name == "Principal/getAvailability":
711+
return [BusyInterval.from_jmap(bp) for bp in parse_get_availability(resp_args)]
712+
raise JMAPMethodError(url=session.api_url, reason="No Principal/getAvailability response")
713+
714+
async def _get_availability_via_fallback(
715+
self, account_id: str, start: str, end: str
716+
) -> list[BusyInterval]:
717+
calls = self._build_availability_fallback_calls(account_id, start, end)
718+
responses = await self._request(calls)
719+
for method_name, resp_args, _ in responses:
720+
if method_name == "CalendarEvent/get":
721+
return self._busy_intervals_from_events(parse_event_get(resp_args))
722+
return []
723+
667724
async def get_sync_token(self) -> str:
668725
"""Return the current CalendarEvent state string for use as a sync token.
669726

0 commit comments

Comments
 (0)