sapancal 0.2.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.
sapancal/__init__.py ADDED
@@ -0,0 +1,66 @@
1
+ """The SapanCal API client: connect Google and Microsoft calendars, find availability, write events, verify webhooks."""
2
+
3
+ from ._client import AsyncSapanCal, SapanCal, DateTimeInput
4
+ from ._errors import SapanCalApiError, SapanCalConnectionError, SapanCalError, WebhookVerificationError
5
+ from ._types import (
6
+ AvailabilityResponse,
7
+ AvailabilitySlot,
8
+ Calendar,
9
+ CalendarChangedEvent,
10
+ CalendarChangedWebhookData,
11
+ Connection,
12
+ ConnectionCreatedEvent,
13
+ ConnectionRelinkedEvent,
14
+ ConnectionRelinkRequiredEvent,
15
+ ConnectionRevokedEvent,
16
+ ConnectionWebhookData,
17
+ ConnectSession,
18
+ Event,
19
+ FreeBusyResponse,
20
+ ParticipantError,
21
+ TimeInterval,
22
+ User,
23
+ )
24
+ from ._version import __version__
25
+ from ._webhooks import (
26
+ DEFAULT_WEBHOOK_TOLERANCE,
27
+ WEBHOOK_EVENT_ID_HEADER,
28
+ WEBHOOK_SIGNATURE_HEADER,
29
+ WebhookEvent,
30
+ sign_webhook,
31
+ verify_webhook,
32
+ )
33
+
34
+ __all__ = [
35
+ "AsyncSapanCal",
36
+ "AvailabilityResponse",
37
+ "AvailabilitySlot",
38
+ "SapanCal",
39
+ "SapanCalApiError",
40
+ "SapanCalConnectionError",
41
+ "SapanCalError",
42
+ "Calendar",
43
+ "CalendarChangedEvent",
44
+ "CalendarChangedWebhookData",
45
+ "Connection",
46
+ "ConnectionCreatedEvent",
47
+ "ConnectionRelinkedEvent",
48
+ "ConnectionRelinkRequiredEvent",
49
+ "ConnectionRevokedEvent",
50
+ "ConnectionWebhookData",
51
+ "ConnectSession",
52
+ "DEFAULT_WEBHOOK_TOLERANCE",
53
+ "DateTimeInput",
54
+ "Event",
55
+ "FreeBusyResponse",
56
+ "ParticipantError",
57
+ "TimeInterval",
58
+ "User",
59
+ "WEBHOOK_EVENT_ID_HEADER",
60
+ "WEBHOOK_SIGNATURE_HEADER",
61
+ "WebhookEvent",
62
+ "WebhookVerificationError",
63
+ "__version__",
64
+ "sign_webhook",
65
+ "verify_webhook",
66
+ ]
sapancal/_client.py ADDED
@@ -0,0 +1,605 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ import os
6
+ import random
7
+ import re
8
+ import time
9
+ from collections.abc import Mapping, Sequence
10
+ from datetime import datetime
11
+ from types import TracebackType
12
+ from typing import Any, Literal, NamedTuple, TypeVar, cast
13
+ from urllib.parse import quote
14
+
15
+ import httpx
16
+
17
+ from ._errors import SapanCalApiError, SapanCalConnectionError, SapanCalError
18
+ from ._types import (
19
+ AvailabilityRequestParticipant,
20
+ AvailabilityResponse,
21
+ Calendar,
22
+ Connection,
23
+ ConnectSession,
24
+ Event,
25
+ FreeBusyResponse,
26
+ User,
27
+ )
28
+ from ._version import __version__
29
+ from ._webhooks import DEFAULT_WEBHOOK_TOLERANCE, WebhookEvent, sign_webhook, verify_webhook
30
+
31
+ DEFAULT_TIMEOUT = 30.0
32
+ DEFAULT_MAX_RETRIES = 2
33
+ _MAX_RETRY_AFTER = 60
34
+ """A ``Retry-After`` longer than this (seconds) isn't waited out; the error is raised instead."""
35
+ _RETRY_STATUSES = frozenset({429, 502, 503, 504})
36
+ _API_KEY = re.compile(r"^(?:sc|bc)_(?:live|test)_([a-z]{2})_")
37
+
38
+ _T = TypeVar("_T")
39
+ DateTimeInput = datetime | str
40
+ """A timezone-aware ``datetime`` or an ISO 8601 string with an offset."""
41
+
42
+
43
+ class _Request(NamedTuple):
44
+ method: str
45
+ path: str
46
+ body: Any = None
47
+
48
+
49
+ def _seg(value: str) -> str:
50
+ # quote() leaves dots alone, and URL handling would collapse an id of "." or ".." (or skip an
51
+ # empty one) into a different route.
52
+ if value in ("", ".", ".."):
53
+ raise ValueError('Ids in the request path must not be empty, "." or "..".')
54
+ return quote(value, safe="")
55
+
56
+
57
+ def _jsonable(value: Any) -> Any:
58
+ if isinstance(value, datetime):
59
+ if value.tzinfo is None or value.utcoffset() is None:
60
+ raise ValueError("Pass timezone-aware datetimes (e.g. datetime.now(timezone.utc)); a naive datetime is ambiguous.")
61
+ return value.isoformat()
62
+ if isinstance(value, Mapping):
63
+ return {k: _jsonable(v) for k, v in value.items()}
64
+ if isinstance(value, (list, tuple)):
65
+ return [_jsonable(v) for v in value]
66
+ return value
67
+
68
+
69
+ def _body(**fields: Any) -> dict[str, Any]:
70
+ """The request body: omitted (None) fields are left out, datetimes become ISO 8601."""
71
+ return {k: _jsonable(v) for k, v in fields.items() if v is not None}
72
+
73
+
74
+ def _fallback_code(status: int) -> str:
75
+ return {401: "unauthorized", 403: "forbidden", 404: "not_found", 429: "rate_limited"}.get(
76
+ status, "internal_error" if status >= 500 else "invalid_request"
77
+ )
78
+
79
+
80
+ def _api_error(response: httpx.Response) -> SapanCalApiError:
81
+ header = response.headers.get("retry-after")
82
+ retry_after = int(header) if header and header.isdigit() else None
83
+ try:
84
+ err = response.json().get("error") or {}
85
+ except (ValueError, AttributeError):
86
+ err = {} # not our JSON (a proxy or load balancer answered)
87
+ return SapanCalApiError(
88
+ status=response.status_code,
89
+ code=err.get("code") or _fallback_code(response.status_code),
90
+ message=err.get("message") or f"SapanCal returned HTTP {response.status_code}.",
91
+ request_id=err.get("request_id") or response.headers.get("x-request-id"),
92
+ details=err.get("details"),
93
+ retry_after=retry_after,
94
+ )
95
+
96
+
97
+ def _backoff(attempt: int, retry_after: int | None) -> float:
98
+ """Exponential backoff with jitter (0.5 s, 1 s, 2 s ... capped at 8 s), or ``Retry-After`` when sent."""
99
+ if retry_after is not None:
100
+ return float(retry_after)
101
+ base = min(0.5 * 2.0**attempt, 8.0)
102
+ return base / 2 + random.random() * base / 2
103
+
104
+
105
+ def _parse(response: httpx.Response) -> Any:
106
+ return response.json() if response.content else None
107
+
108
+
109
+ class _Config:
110
+ def __init__(self, api_key: str | None, base_url: str | None, webhook_secret: str | None, timeout: float, max_retries: int) -> None:
111
+ key = api_key or os.environ.get("SAPANCAL_API_KEY")
112
+ if not key:
113
+ raise SapanCalError("Missing API key. Pass it to SapanCal(api_key) or set SAPANCAL_API_KEY.")
114
+ url = base_url or os.environ.get("SAPANCAL_BASE_URL")
115
+ match = _API_KEY.match(key)
116
+ if not url and not match:
117
+ raise SapanCalError("That doesn't look like a SapanCal API key (sc_live_... or sc_test_...). Copy it from the console.")
118
+ self.api_key = key
119
+ self.base_url = (url or f"https://api.sapancal.com/{match.group(1) if match else ''}/v1").rstrip("/")
120
+ self.webhook_secret = webhook_secret or os.environ.get("SAPANCAL_WEBHOOK_SECRET")
121
+ self.timeout = timeout
122
+ self.max_retries = max_retries
123
+
124
+ def headers(self, has_body: bool) -> dict[str, str]:
125
+ headers = {"authorization": f"Bearer {self.api_key}", "accept": "application/json", "user-agent": f"sapancal-python/{__version__}"}
126
+ if has_body:
127
+ headers["content-type"] = "application/json"
128
+ return headers
129
+
130
+ def retry_delay(self, attempt: int, error: SapanCalApiError | None) -> float | None:
131
+ """Seconds to wait before retrying, or None to give up."""
132
+ if attempt >= self.max_retries:
133
+ return None
134
+ if error is None:
135
+ return _backoff(attempt, None)
136
+ if error.status not in _RETRY_STATUSES or (error.retry_after or 0) > _MAX_RETRY_AFTER:
137
+ return None
138
+ return _backoff(attempt, error.retry_after)
139
+
140
+
141
+ # ---------- operations ----------
142
+
143
+
144
+ def _create_connect_session(user_id: str, redirect_uri: str, provider: str | None, connection_id: str | None) -> _Request:
145
+ return _Request("POST", "/connect_sessions", _body(user_id=user_id, redirect_uri=redirect_uri, provider=provider, connection_id=connection_id))
146
+
147
+
148
+ def _free_busy(user_ids: Sequence[str], start: DateTimeInput, end: DateTimeInput, calendar_ids: Mapping[str, Sequence[str]] | None) -> _Request:
149
+ return _Request("POST", "/free_busy", _body(user_ids=user_ids, start=start, end=end, calendar_ids=calendar_ids))
150
+
151
+
152
+ def _upsert_event(user_id: str, event_id: str, fields: dict[str, Any]) -> _Request:
153
+ return _Request("PUT", f"/users/{_seg(user_id)}/events/{_seg(event_id)}", _body(**fields))
154
+
155
+
156
+ class Webhooks:
157
+ """Webhook signature checks. These run locally and make no API calls."""
158
+
159
+ def __init__(self, config: _Config) -> None:
160
+ self._config = config
161
+
162
+ def verify(self, payload: str | bytes, headers: Mapping[str, Any], *, secret: str | None = None, tolerance: int = DEFAULT_WEBHOOK_TOLERANCE) -> WebhookEvent:
163
+ """Checks the ``SapanCal-Signature`` header and returns the parsed event, or raises
164
+ ``WebhookVerificationError``. ``secret`` defaults to the client's ``webhook_secret``."""
165
+ key = secret or self._config.webhook_secret
166
+ if not key:
167
+ raise SapanCalError("Missing webhook secret. Pass secret=, set webhook_secret on the client, or set SAPANCAL_WEBHOOK_SECRET.")
168
+ return verify_webhook(payload, headers, key, tolerance=tolerance)
169
+
170
+ def sign(self, payload: str | bytes, *, secret: str | None = None, timestamp: int | None = None) -> str:
171
+ """A valid ``SapanCal-Signature`` header for ``payload``, for testing your webhook handler."""
172
+ key = secret or self._config.webhook_secret
173
+ if not key:
174
+ raise SapanCalError("Missing webhook secret.")
175
+ return sign_webhook(payload, key, timestamp=timestamp)
176
+
177
+
178
+ # ---------- sync client ----------
179
+
180
+
181
+ class SapanCal:
182
+ """The SapanCal API client.
183
+
184
+ ::
185
+
186
+ from sapancal import SapanCal
187
+
188
+ client = SapanCal() # reads SAPANCAL_API_KEY
189
+ session = client.connect_sessions.create(user_id="user_123", redirect_uri="https://app.example.com/calendar/done")
190
+ """
191
+
192
+ def __init__(
193
+ self,
194
+ api_key: str | None = None,
195
+ *,
196
+ base_url: str | None = None,
197
+ webhook_secret: str | None = None,
198
+ timeout: float = DEFAULT_TIMEOUT,
199
+ max_retries: int = DEFAULT_MAX_RETRIES,
200
+ http_client: httpx.Client | None = None,
201
+ ) -> None:
202
+ """
203
+ Args:
204
+ api_key: Your API key (``sc_live_...`` or ``sc_test_...``). Defaults to ``SAPANCAL_API_KEY``.
205
+ base_url: The API's base URL, up to and including ``/v1``. Defaults to ``SAPANCAL_BASE_URL``,
206
+ then to ``https://api.sapancal.com/{region}/v1`` with the region taken from the key.
207
+ webhook_secret: The signing secret (``whsec_...``) for ``webhooks.verify``. Defaults to ``SAPANCAL_WEBHOOK_SECRET``.
208
+ timeout: Seconds before a request attempt is abandoned.
209
+ max_retries: Retries for network errors, 429 and 502-504, with backoff that honours ``Retry-After``.
210
+ http_client: An ``httpx.Client`` to send requests with (proxies, custom transports).
211
+ """
212
+ self._config = _Config(api_key, base_url, webhook_secret, timeout, max_retries)
213
+ self._owns_client = http_client is None
214
+ self._http = http_client or httpx.Client(timeout=timeout)
215
+ self.connect_sessions = ConnectSessions(self)
216
+ self.users = Users(self)
217
+ self.connections = Connections(self)
218
+ self.free_busy = FreeBusy(self)
219
+ self.availability = Availability(self)
220
+ self.events = Events(self)
221
+ self.webhooks = Webhooks(self._config)
222
+
223
+ @property
224
+ def base_url(self) -> str:
225
+ return self._config.base_url
226
+
227
+ def _send(self, request: _Request) -> Any:
228
+ content = None if request.body is None else json.dumps(request.body)
229
+ headers = self._config.headers(content is not None)
230
+ url = f"{self._config.base_url}{request.path}"
231
+ attempt = 0
232
+ while True:
233
+ try:
234
+ response = self._http.request(request.method, url, content=content, headers=headers, timeout=self._config.timeout)
235
+ except httpx.TransportError as err:
236
+ delay = self._config.retry_delay(attempt, None)
237
+ if delay is None:
238
+ raise _connection_error(err, self._config.timeout) from err
239
+ time.sleep(delay)
240
+ attempt += 1
241
+ continue
242
+ if response.is_success:
243
+ return _parse(response)
244
+ error = _api_error(response)
245
+ delay = self._config.retry_delay(attempt, error)
246
+ if delay is None:
247
+ raise error
248
+ time.sleep(delay)
249
+ attempt += 1
250
+
251
+ def close(self) -> None:
252
+ """Closes the HTTP client, unless you passed your own."""
253
+ if self._owns_client:
254
+ self._http.close()
255
+
256
+ def __enter__(self) -> SapanCal:
257
+ return self
258
+
259
+ def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None:
260
+ self.close()
261
+
262
+
263
+ def _connection_error(err: httpx.TransportError, timeout: float) -> SapanCalConnectionError:
264
+ if isinstance(err, httpx.TimeoutException):
265
+ return SapanCalConnectionError(f"Request timed out after {timeout:g} s.")
266
+ return SapanCalConnectionError(f"Could not reach SapanCal: {err}")
267
+
268
+
269
+ class _Resource:
270
+ def __init__(self, client: SapanCal) -> None:
271
+ self._client = client
272
+
273
+ def _send(self, request: _Request, _: type[_T]) -> _T:
274
+ return cast(_T, self._client._send(request))
275
+
276
+
277
+ class ConnectSessions(_Resource):
278
+ """Connect sessions: one-time links that take an end user through connecting a Google or Microsoft calendar."""
279
+
280
+ def create(self, *, user_id: str, redirect_uri: str, provider: Literal["google", "microsoft"] | None = None, connection_id: str | None = None) -> ConnectSession:
281
+ """Starts a connect session. Send the user to ``session["url"]``; they come back to ``redirect_uri``
282
+ with ``connect_session_id`` and ``status`` in the query string.
283
+
284
+ Args:
285
+ user_id: Your own identifier for the end user.
286
+ redirect_uri: Must exactly match one of the application's registered redirect URIs.
287
+ provider: Offer only this provider on the connect page.
288
+ connection_id: Relink this existing connection (it must belong to ``user_id``).
289
+ """
290
+ return self._send(_create_connect_session(user_id, redirect_uri, provider, connection_id), ConnectSession)
291
+
292
+ def get(self, connect_session_id: str) -> ConnectSession:
293
+ """Reads a connect session, e.g. on your redirect page to get the new ``connection``."""
294
+ return self._send(_Request("GET", f"/connect_sessions/{_seg(connect_session_id)}"), ConnectSession)
295
+
296
+
297
+ class Users(_Resource):
298
+ """End users, identified by your own ids."""
299
+
300
+ def get(self, user_id: str) -> User:
301
+ """A user and their connections."""
302
+ return self._send(_Request("GET", f"/users/{_seg(user_id)}"), User)
303
+
304
+ def update(self, user_id: str, *, default_connection_id: str) -> User:
305
+ """Changes the connection events are written to by default."""
306
+ return self._send(_Request("PATCH", f"/users/{_seg(user_id)}", _body(default_connection_id=default_connection_id)), User)
307
+
308
+ def delete(self, user_id: str) -> None:
309
+ """Disconnects every connection of the user and forgets them."""
310
+ self._client._send(_Request("DELETE", f"/users/{_seg(user_id)}"))
311
+
312
+
313
+ class Connections(_Resource):
314
+ """Connections: one user's link to one Google or Microsoft account."""
315
+
316
+ def get(self, connection_id: str) -> Connection:
317
+ return self._send(_Request("GET", f"/connections/{_seg(connection_id)}"), Connection)
318
+
319
+ def delete(self, connection_id: str) -> None:
320
+ """Disconnects the account and revokes SapanCal's access to it."""
321
+ self._client._send(_Request("DELETE", f"/connections/{_seg(connection_id)}"))
322
+
323
+ def list_calendars(self, connection_id: str) -> list[Calendar]:
324
+ """The account's calendars, for ``calendar_ids`` and event writes."""
325
+ return self._send(_Request("GET", f"/connections/{_seg(connection_id)}/calendars"), list[Calendar])
326
+
327
+
328
+ class FreeBusy(_Resource):
329
+ """Busy time for one or more users."""
330
+
331
+ def query(self, *, user_ids: Sequence[str], start: DateTimeInput, end: DateTimeInput, calendar_ids: Mapping[str, Sequence[str]] | None = None) -> FreeBusyResponse:
332
+ """Busy, tentative and out-of-office time per user, merged and sorted.
333
+
334
+ Args:
335
+ user_ids: Your ids for the users.
336
+ start: Start of the range.
337
+ end: End of the range, at most 62 days after ``start``.
338
+ calendar_ids: Calendars to read per user id; by default each active connection's primary calendar.
339
+ """
340
+ return self._send(_free_busy(user_ids, start, end, calendar_ids), FreeBusyResponse)
341
+
342
+
343
+ class Availability(_Resource):
344
+ """Times when participants are free: bookable slots or free periods."""
345
+
346
+ def query(
347
+ self,
348
+ *,
349
+ participants: Sequence[AvailabilityRequestParticipant | Mapping[str, Any]],
350
+ periods: Sequence[Mapping[str, DateTimeInput]],
351
+ slot_duration_minutes: int,
352
+ required: Literal["all", "any"] | None = None,
353
+ slot_interval_minutes: int | None = None,
354
+ buffer_before_minutes: int | None = None,
355
+ buffer_after_minutes: int | None = None,
356
+ format: Literal["slots", "periods"] | None = None,
357
+ ) -> AvailabilityResponse:
358
+ """Finds free time.
359
+
360
+ Args:
361
+ participants: ``[{"user_id": ..., "calendar_ids": [...]}]``; ``calendar_ids`` is optional.
362
+ periods: Windows to search, ``[{"start": ..., "end": ...}]``, spanning at most 62 days.
363
+ slot_duration_minutes: Length of each slot (a multiple of 5).
364
+ required: ``"all"`` (default): everyone must be free. ``"any"``: at least one must be.
365
+ slot_interval_minutes: Gap between slot start times; defaults to ``slot_duration_minutes``.
366
+ buffer_before_minutes: Free time required before each slot.
367
+ buffer_after_minutes: Free time required after each slot.
368
+ format: ``"slots"`` (default) or ``"periods"`` (maximal free intervals).
369
+ """
370
+ request = _Request(
371
+ "POST",
372
+ "/availability",
373
+ _body(
374
+ participants=participants,
375
+ periods=periods,
376
+ slot_duration_minutes=slot_duration_minutes,
377
+ required=required,
378
+ slot_interval_minutes=slot_interval_minutes,
379
+ buffer_before_minutes=buffer_before_minutes,
380
+ buffer_after_minutes=buffer_after_minutes,
381
+ format=format,
382
+ ),
383
+ )
384
+ return self._send(request, AvailabilityResponse)
385
+
386
+
387
+ class Events(_Resource):
388
+ """Events in users' calendars, keyed by your own event id."""
389
+
390
+ def upsert(
391
+ self,
392
+ user_id: str,
393
+ event_id: str,
394
+ *,
395
+ summary: str,
396
+ start: DateTimeInput,
397
+ end: DateTimeInput,
398
+ description: str | None = None,
399
+ time_zone: str | None = None,
400
+ location: str | None = None,
401
+ all_day: bool | None = None,
402
+ connection_id: str | None = None,
403
+ calendar_id: str | None = None,
404
+ transparency: Literal["opaque", "transparent"] | None = None,
405
+ ) -> Event:
406
+ """Creates the event, or updates it if ``event_id`` was written before. Safe to retry.
407
+
408
+ Args:
409
+ summary: Event title.
410
+ time_zone: IANA time zone, e.g. ``Australia/Sydney``.
411
+ connection_id: Write to this connection instead of the user's default one.
412
+ calendar_id: Write to this calendar instead of the connection's primary calendar.
413
+ transparency: ``"opaque"`` (default) blocks time in free/busy; ``"transparent"`` doesn't.
414
+ """
415
+ fields = dict(summary=summary, start=start, end=end, description=description, time_zone=time_zone, location=location, all_day=all_day, connection_id=connection_id, calendar_id=calendar_id, transparency=transparency)
416
+ return self._send(_upsert_event(user_id, event_id, fields), Event)
417
+
418
+ def delete(self, user_id: str, event_id: str) -> None:
419
+ """Deletes the event from the calendar it was written to."""
420
+ self._client._send(_Request("DELETE", f"/users/{_seg(user_id)}/events/{_seg(event_id)}"))
421
+
422
+
423
+ # ---------- async client ----------
424
+
425
+
426
+ class AsyncSapanCal:
427
+ """The SapanCal API client for asyncio. Same methods as ``SapanCal``, awaited.
428
+
429
+ ::
430
+
431
+ async with AsyncSapanCal() as client:
432
+ slots = await client.availability.query(participants=[{"user_id": "user_123"}], periods=[...], slot_duration_minutes=30)
433
+ """
434
+
435
+ def __init__(
436
+ self,
437
+ api_key: str | None = None,
438
+ *,
439
+ base_url: str | None = None,
440
+ webhook_secret: str | None = None,
441
+ timeout: float = DEFAULT_TIMEOUT,
442
+ max_retries: int = DEFAULT_MAX_RETRIES,
443
+ http_client: httpx.AsyncClient | None = None,
444
+ ) -> None:
445
+ self._config = _Config(api_key, base_url, webhook_secret, timeout, max_retries)
446
+ self._owns_client = http_client is None
447
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
448
+ self.connect_sessions = AsyncConnectSessions(self)
449
+ self.users = AsyncUsers(self)
450
+ self.connections = AsyncConnections(self)
451
+ self.free_busy = AsyncFreeBusy(self)
452
+ self.availability = AsyncAvailability(self)
453
+ self.events = AsyncEvents(self)
454
+ self.webhooks = Webhooks(self._config)
455
+
456
+ @property
457
+ def base_url(self) -> str:
458
+ return self._config.base_url
459
+
460
+ async def _send(self, request: _Request) -> Any:
461
+ content = None if request.body is None else json.dumps(request.body)
462
+ headers = self._config.headers(content is not None)
463
+ url = f"{self._config.base_url}{request.path}"
464
+ attempt = 0
465
+ while True:
466
+ try:
467
+ response = await self._http.request(request.method, url, content=content, headers=headers, timeout=self._config.timeout)
468
+ except httpx.TransportError as err:
469
+ delay = self._config.retry_delay(attempt, None)
470
+ if delay is None:
471
+ raise _connection_error(err, self._config.timeout) from err
472
+ await asyncio.sleep(delay)
473
+ attempt += 1
474
+ continue
475
+ if response.is_success:
476
+ return _parse(response)
477
+ error = _api_error(response)
478
+ delay = self._config.retry_delay(attempt, error)
479
+ if delay is None:
480
+ raise error
481
+ await asyncio.sleep(delay)
482
+ attempt += 1
483
+
484
+ async def aclose(self) -> None:
485
+ """Closes the HTTP client, unless you passed your own."""
486
+ if self._owns_client:
487
+ await self._http.aclose()
488
+
489
+ async def __aenter__(self) -> AsyncSapanCal:
490
+ return self
491
+
492
+ async def __aexit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None:
493
+ await self.aclose()
494
+
495
+
496
+ class _AsyncResource:
497
+ def __init__(self, client: AsyncSapanCal) -> None:
498
+ self._client = client
499
+
500
+ async def _send(self, request: _Request, _: type[_T]) -> _T:
501
+ return cast(_T, await self._client._send(request))
502
+
503
+
504
+ class AsyncConnectSessions(_AsyncResource):
505
+ """Connect sessions: one-time links that take an end user through connecting a Google or Microsoft calendar."""
506
+
507
+ async def create(self, *, user_id: str, redirect_uri: str, provider: Literal["google", "microsoft"] | None = None, connection_id: str | None = None) -> ConnectSession:
508
+ """Starts a connect session. See ``SapanCal.connect_sessions.create``."""
509
+ return await self._send(_create_connect_session(user_id, redirect_uri, provider, connection_id), ConnectSession)
510
+
511
+ async def get(self, connect_session_id: str) -> ConnectSession:
512
+ return await self._send(_Request("GET", f"/connect_sessions/{_seg(connect_session_id)}"), ConnectSession)
513
+
514
+
515
+ class AsyncUsers(_AsyncResource):
516
+ """End users, identified by your own ids."""
517
+
518
+ async def get(self, user_id: str) -> User:
519
+ return await self._send(_Request("GET", f"/users/{_seg(user_id)}"), User)
520
+
521
+ async def update(self, user_id: str, *, default_connection_id: str) -> User:
522
+ return await self._send(_Request("PATCH", f"/users/{_seg(user_id)}", _body(default_connection_id=default_connection_id)), User)
523
+
524
+ async def delete(self, user_id: str) -> None:
525
+ await self._client._send(_Request("DELETE", f"/users/{_seg(user_id)}"))
526
+
527
+
528
+ class AsyncConnections(_AsyncResource):
529
+ """Connections: one user's link to one Google or Microsoft account."""
530
+
531
+ async def get(self, connection_id: str) -> Connection:
532
+ return await self._send(_Request("GET", f"/connections/{_seg(connection_id)}"), Connection)
533
+
534
+ async def delete(self, connection_id: str) -> None:
535
+ await self._client._send(_Request("DELETE", f"/connections/{_seg(connection_id)}"))
536
+
537
+ async def list_calendars(self, connection_id: str) -> list[Calendar]:
538
+ return await self._send(_Request("GET", f"/connections/{_seg(connection_id)}/calendars"), list[Calendar])
539
+
540
+
541
+ class AsyncFreeBusy(_AsyncResource):
542
+ """Busy time for one or more users."""
543
+
544
+ async def query(self, *, user_ids: Sequence[str], start: DateTimeInput, end: DateTimeInput, calendar_ids: Mapping[str, Sequence[str]] | None = None) -> FreeBusyResponse:
545
+ return await self._send(_free_busy(user_ids, start, end, calendar_ids), FreeBusyResponse)
546
+
547
+
548
+ class AsyncAvailability(_AsyncResource):
549
+ """Times when participants are free: bookable slots or free periods."""
550
+
551
+ async def query(
552
+ self,
553
+ *,
554
+ participants: Sequence[AvailabilityRequestParticipant | Mapping[str, Any]],
555
+ periods: Sequence[Mapping[str, DateTimeInput]],
556
+ slot_duration_minutes: int,
557
+ required: Literal["all", "any"] | None = None,
558
+ slot_interval_minutes: int | None = None,
559
+ buffer_before_minutes: int | None = None,
560
+ buffer_after_minutes: int | None = None,
561
+ format: Literal["slots", "periods"] | None = None,
562
+ ) -> AvailabilityResponse:
563
+ """Finds free time. See ``SapanCal.availability.query``."""
564
+ request = _Request(
565
+ "POST",
566
+ "/availability",
567
+ _body(
568
+ participants=participants,
569
+ periods=periods,
570
+ slot_duration_minutes=slot_duration_minutes,
571
+ required=required,
572
+ slot_interval_minutes=slot_interval_minutes,
573
+ buffer_before_minutes=buffer_before_minutes,
574
+ buffer_after_minutes=buffer_after_minutes,
575
+ format=format,
576
+ ),
577
+ )
578
+ return await self._send(request, AvailabilityResponse)
579
+
580
+
581
+ class AsyncEvents(_AsyncResource):
582
+ """Events in users' calendars, keyed by your own event id."""
583
+
584
+ async def upsert(
585
+ self,
586
+ user_id: str,
587
+ event_id: str,
588
+ *,
589
+ summary: str,
590
+ start: DateTimeInput,
591
+ end: DateTimeInput,
592
+ description: str | None = None,
593
+ time_zone: str | None = None,
594
+ location: str | None = None,
595
+ all_day: bool | None = None,
596
+ connection_id: str | None = None,
597
+ calendar_id: str | None = None,
598
+ transparency: Literal["opaque", "transparent"] | None = None,
599
+ ) -> Event:
600
+ """Creates the event, or updates it if ``event_id`` was written before. See ``SapanCal.events.upsert``."""
601
+ fields = dict(summary=summary, start=start, end=end, description=description, time_zone=time_zone, location=location, all_day=all_day, connection_id=connection_id, calendar_id=calendar_id, transparency=transparency)
602
+ return await self._send(_upsert_event(user_id, event_id, fields), Event)
603
+
604
+ async def delete(self, user_id: str, event_id: str) -> None:
605
+ await self._client._send(_Request("DELETE", f"/users/{_seg(user_id)}/events/{_seg(event_id)}"))
sapancal/_errors.py ADDED
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ class SapanCalError(Exception):
7
+ """Base class for every error this SDK raises."""
8
+
9
+
10
+ class SapanCalApiError(SapanCalError):
11
+ """The API answered with an error (``{"error": {"code", "message", "request_id"}}``).
12
+
13
+ Branch on ``code``, which is stable; ``message`` is for people::
14
+
15
+ try:
16
+ client.events.upsert(user_id, event_id, summary="Intro call", start=start, end=end)
17
+ except SapanCalApiError as err:
18
+ if err.code == "relink_required":
19
+ ...
20
+ """
21
+
22
+ status: int
23
+ """HTTP status code."""
24
+ code: str
25
+ """Stable error code (``not_found``, ``relink_required``, ``rate_limited``, ...). New codes may be added."""
26
+ message: str
27
+ request_id: str | None
28
+ """Same as the ``X-Request-Id`` header. Quote it when asking for support."""
29
+ details: Any
30
+ """Extra detail. Validation errors carry ``issues: [{path, message, code}]``."""
31
+ retry_after: int | None
32
+ """Seconds to wait before retrying, from ``Retry-After`` (rate limits and provider outages)."""
33
+
34
+ def __init__(self, *, status: int, code: str, message: str, request_id: str | None, details: Any = None, retry_after: int | None = None) -> None:
35
+ super().__init__(message)
36
+ self.status = status
37
+ self.code = code
38
+ self.message = message
39
+ self.request_id = request_id
40
+ self.details = details
41
+ self.retry_after = retry_after
42
+
43
+ def __repr__(self) -> str:
44
+ return f"SapanCalApiError(status={self.status}, code={self.code!r}, message={self.message!r}, request_id={self.request_id!r})"
45
+
46
+
47
+ class SapanCalConnectionError(SapanCalError):
48
+ """The request never got an answer: network failure, DNS, TLS or timeout."""
49
+
50
+
51
+ class WebhookVerificationError(SapanCalError):
52
+ """A webhook's ``SapanCal-Signature`` is missing, malformed, stale or doesn't match the body."""
sapancal/_types.py ADDED
@@ -0,0 +1,283 @@
1
+ """Generated from hosting/api/openapi.json by `npm run openapi` (tools/sdk-types.ts). Do not edit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal, NotRequired, TypedDict
6
+
7
+
8
+ class CreateConnectSessionRequest(TypedDict):
9
+ user_id: str
10
+ """Your own identifier for the end user (1–255 characters). The prefix `sapancal-test:` is reserved."""
11
+ redirect_uri: str
12
+ """Where the user is sent when the flow ends. Must exactly match one of the application's registered redirect URIs."""
13
+ provider: NotRequired[Literal["google", "microsoft"]]
14
+ """Offer only this provider on the connect page. The page still shows, so the user can accept the terms."""
15
+ connection_id: NotRequired[str]
16
+ """Relink this existing connection (it must belong to `user_id`). The user must sign in to the same provider account."""
17
+
18
+
19
+ class ConnectSession(TypedDict):
20
+ """A one-time link that takes an end user through connecting a calendar account."""
21
+ id: str
22
+ """Connect session id (`cs_…`)."""
23
+ status: Literal["pending", "redirected", "completed", "denied", "error", "expired"]
24
+ """`pending`: created, not opened. `redirected`: the user went to the provider. `completed`: a connection was made or relinked. `denied`: the user declined at the provider. `error`: see `error_code`. `expired`: not finished in time."""
25
+ user_id: str
26
+ url: str
27
+ """The hosted connect page. Send the user here."""
28
+ expires_at: str
29
+ """When the session expires (30 minutes after creation)."""
30
+ connection: Connection | None
31
+ """The connection made or relinked, once `status` is `completed`."""
32
+ error_code: str | None
33
+ """Why the session ended in `error`: `account_mismatch` (a relink signed in to a different account), `connection_limit_reached`, `connection_not_found` (the connection being relinked was deleted), `session_expired` or `internal_error`. New codes may be added."""
34
+
35
+
36
+ class Connection(TypedDict):
37
+ """One end user's link to one Google or Microsoft account."""
38
+ id: str
39
+ """Connection id (`conn_…`)."""
40
+ user_id: str
41
+ """Your identifier for the end user who owns the connection."""
42
+ provider: Literal["google", "microsoft"]
43
+ email: str | None
44
+ """The provider account's email address."""
45
+ display_name: str | None
46
+ """The provider account's display name."""
47
+ status: Literal["active", "relink_required", "revoked"]
48
+ """`active`: usable. `relink_required`: the provider stopped accepting the stored grant; send the user through a connect session with `connection_id` to fix it. `revoked`: disconnected for good."""
49
+ primary_calendar_id: str | None
50
+ """The provider's id for the account's primary calendar."""
51
+ connected_at: str
52
+ """When the connection was first made."""
53
+ last_used_at: str | None
54
+
55
+
56
+ class User(TypedDict):
57
+ """An end user, identified by your own id, and their connections."""
58
+ user_id: str
59
+ default_connection_id: str | None
60
+ """The connection events are written to when an event write names no `connection_id`."""
61
+ connections: list[Connection]
62
+ created_at: str
63
+ """When the user first connected a calendar."""
64
+
65
+
66
+ class UpdateUserRequest(TypedDict):
67
+ default_connection_id: str
68
+ """An `active` connection of this user."""
69
+
70
+
71
+ class Calendar(TypedDict):
72
+ id: str
73
+ """The provider's calendar id. Use it in `calendar_ids` and event writes."""
74
+ name: str
75
+ primary: bool
76
+ """True for the account's primary calendar."""
77
+ can_write: bool
78
+ """True when events can be written to this calendar."""
79
+ time_zone: str | None
80
+ """IANA time zone of the calendar, when the provider reports one."""
81
+
82
+
83
+ class FreeBusyRequest(TypedDict):
84
+ user_ids: list[str]
85
+ start: str
86
+ """Start of the range."""
87
+ end: str
88
+ """End of the range: after `start` and at most 62 days later."""
89
+ calendar_ids: NotRequired[dict[str, list[str]]]
90
+ """Calendars to read per user id: calendar ids from any of the user's connections, `primary` (the default connection's primary calendar) or an account's email address (its primary calendar). A user not listed is read on every active connection's primary calendar."""
91
+
92
+
93
+ class FreeBusyResponseUser(TypedDict):
94
+ user_id: str
95
+ busy: list[TimeInterval]
96
+ """Busy, tentative and out-of-office time, merged and sorted."""
97
+
98
+
99
+ class FreeBusyResponse(TypedDict):
100
+ users: list[FreeBusyResponseUser]
101
+ errors: list[ParticipantError]
102
+ """Users whose calendars could not be read. They are left out of `users`."""
103
+
104
+
105
+ class TimeInterval(TypedDict):
106
+ """A half-open interval `[start, end)` in UTC."""
107
+ start: str
108
+ end: str
109
+
110
+
111
+ class ParticipantError(TypedDict):
112
+ """A user whose calendars couldn't be read. The rest of the request still succeeds."""
113
+ user_id: str
114
+ connection_id: str | None
115
+ code: Literal["relink_required", "provider_unavailable", "not_found", "no_connections"]
116
+ """`relink_required`: the user must relink the connection. `provider_unavailable`: the provider failed; retry later. `not_found`: no such user or calendar. `no_connections`: the user has no connected calendars."""
117
+ message: str
118
+
119
+
120
+ class AvailabilityRequestParticipant(TypedDict):
121
+ user_id: str
122
+ """Your own identifier for the end user (1–255 characters). The prefix `sapancal-test:` is reserved."""
123
+ calendar_ids: NotRequired[list[str]]
124
+ """Calendar ids from any of the user's connections, `primary` (the default connection's primary calendar) or an account's email address (its primary calendar). Defaults to every active connection's primary calendar."""
125
+
126
+
127
+ class AvailabilityRequestPeriod(TypedDict):
128
+ start: str
129
+ end: str
130
+
131
+
132
+ class AvailabilityRequest(TypedDict):
133
+ participants: list[AvailabilityRequestParticipant]
134
+ required: NotRequired[Literal["all", "any"]]
135
+ """`all`: every participant must be free. `any`: at least one must be; each result lists who is.
136
+ Defaults to `"all"`."""
137
+ periods: list[AvailabilityRequestPeriod]
138
+ """Windows to search. Each must end after it starts, and together they span at most 62 days."""
139
+ slot_duration_minutes: int
140
+ """Length of each slot."""
141
+ slot_interval_minutes: NotRequired[int]
142
+ """Gap between slot start times, which align to this grid from 00:00 UTC. Defaults to `slot_duration_minutes`."""
143
+ buffer_before_minutes: NotRequired[int]
144
+ """Free time required before each slot.
145
+ Defaults to `0`."""
146
+ buffer_after_minutes: NotRequired[int]
147
+ """Free time required after each slot.
148
+ Defaults to `0`."""
149
+ format: NotRequired[Literal["slots", "periods"]]
150
+ """`slots`: bookable slots of `slot_duration_minutes` on the `slot_interval_minutes` grid. `periods`: maximal free intervals (no grid) at least `slot_duration_minutes` long; with `required: "any"` an interval ends wherever the set of free participants changes.
151
+ Defaults to `"slots"`."""
152
+
153
+
154
+ class AvailabilityResponse(TypedDict):
155
+ slots: NotRequired[list[AvailabilitySlot]]
156
+ """Present when `format` is `slots`."""
157
+ periods: NotRequired[list[AvailabilitySlot]]
158
+ """Present when `format` is `periods`."""
159
+ errors: list[ParticipantError]
160
+ """Participants whose calendars could not be read. They are left out; with `required: "all"` that means no results."""
161
+
162
+
163
+ class AvailabilitySlot(TypedDict):
164
+ start: str
165
+ end: str
166
+ user_ids: list[str]
167
+ """Participants free for the whole interval, buffers included."""
168
+
169
+
170
+ class UpsertEventRequest(TypedDict):
171
+ summary: str
172
+ """Event title."""
173
+ description: NotRequired[str]
174
+ start: str
175
+ end: str
176
+ """Must be after `start`."""
177
+ time_zone: NotRequired[str]
178
+ """IANA time zone for the event, e.g. `Australia/Sydney`."""
179
+ location: NotRequired[str]
180
+ all_day: NotRequired[bool]
181
+ """Defaults to `false`."""
182
+ connection_id: NotRequired[str]
183
+ """Write to this connection instead of the user's default connection."""
184
+ calendar_id: NotRequired[str]
185
+ """Write to this calendar instead of the connection's primary calendar."""
186
+ transparency: NotRequired[Literal["opaque", "transparent"]]
187
+ """`opaque` blocks time in free/busy; `transparent` does not.
188
+ Defaults to `"opaque"`."""
189
+
190
+
191
+ class Event(TypedDict):
192
+ """The link between your event id and the provider's event."""
193
+ event_id: str
194
+ """Your event id from the path."""
195
+ connection_id: str
196
+ """The connection the event was written to."""
197
+ calendar_id: str
198
+ """The calendar the event was written to."""
199
+ provider_event_id: str
200
+ """The provider's id for the event."""
201
+
202
+
203
+ class ErrorError(TypedDict):
204
+ code: Literal["invalid_request", "unauthorized", "forbidden", "not_found", "conflict", "relink_required", "provider_unavailable", "rate_limited", "company_suspended", "connection_limit_reached", "wrong_region", "internal_error"]
205
+ """Stable, machine-readable error code."""
206
+ message: str
207
+ """Human-readable explanation. It may change; branch on `code`."""
208
+ request_id: str
209
+ """Same as the `X-Request-Id` header. Quote it when asking for support."""
210
+ details: NotRequired[Any]
211
+ """Extra detail. Validation errors carry `issues: [{ path, message, code }]`, with `path` like `body.periods.0.end`."""
212
+
213
+
214
+ class Error(TypedDict):
215
+ error: ErrorError
216
+
217
+
218
+ class ConnectionWebhookData(TypedDict):
219
+ user_id: str
220
+ connection_id: str
221
+ provider: Literal["google", "microsoft"]
222
+ email: str | None
223
+ status: Literal["active", "relink_required", "revoked"]
224
+ """`active`: usable. `relink_required`: the provider stopped accepting the stored grant; send the user through a connect session with `connection_id` to fix it. `revoked`: disconnected for good."""
225
+
226
+
227
+ class CalendarChangedWebhookData(TypedDict):
228
+ user_id: str
229
+ connection_id: str
230
+ calendar_id: str
231
+ """The calendar that changed."""
232
+ provider: Literal["google", "microsoft"]
233
+ changed_at: str
234
+
235
+
236
+ class ConnectionCreatedEvent(TypedDict):
237
+ """A user connected a calendar account."""
238
+ id: str
239
+ """Event id (`evt_…`), also sent as `SapanCal-Event-Id`. Retries reuse it: de-duplicate on it."""
240
+ type: Literal["connection.created"]
241
+ created_at: str
242
+ application_id: str
243
+ data: ConnectionWebhookData
244
+
245
+
246
+ class ConnectionRelinkedEvent(TypedDict):
247
+ """A user relinked a connection."""
248
+ id: str
249
+ """Event id (`evt_…`), also sent as `SapanCal-Event-Id`. Retries reuse it: de-duplicate on it."""
250
+ type: Literal["connection.relinked"]
251
+ created_at: str
252
+ application_id: str
253
+ data: ConnectionWebhookData
254
+
255
+
256
+ class ConnectionRelinkRequiredEvent(TypedDict):
257
+ """A connection needs relinking (the provider stopped accepting its grant)."""
258
+ id: str
259
+ """Event id (`evt_…`), also sent as `SapanCal-Event-Id`. Retries reuse it: de-duplicate on it."""
260
+ type: Literal["connection.relink_required"]
261
+ created_at: str
262
+ application_id: str
263
+ data: ConnectionWebhookData
264
+
265
+
266
+ class ConnectionRevokedEvent(TypedDict):
267
+ """A connection was revoked."""
268
+ id: str
269
+ """Event id (`evt_…`), also sent as `SapanCal-Event-Id`. Retries reuse it: de-duplicate on it."""
270
+ type: Literal["connection.revoked"]
271
+ created_at: str
272
+ application_id: str
273
+ data: ConnectionWebhookData
274
+
275
+
276
+ class CalendarChangedEvent(TypedDict):
277
+ """Events changed on a connection's primary calendar."""
278
+ id: str
279
+ """Event id (`evt_…`), also sent as `SapanCal-Event-Id`. Retries reuse it: de-duplicate on it."""
280
+ type: Literal["calendar.changed"]
281
+ created_at: str
282
+ application_id: str
283
+ data: CalendarChangedWebhookData
sapancal/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
sapancal/_webhooks.py ADDED
@@ -0,0 +1,116 @@
1
+ """Webhook signatures.
2
+
3
+ SapanCal-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, f"{t}.{body}")>[,v1=...]
4
+
5
+ During a signing-secret rotation the header carries one ``v1=`` per secret (new first), so either passes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import re
14
+ import time
15
+ from collections.abc import Mapping
16
+ from typing import Any, Union, cast
17
+
18
+ from ._errors import WebhookVerificationError
19
+ from ._types import (
20
+ CalendarChangedEvent,
21
+ ConnectionCreatedEvent,
22
+ ConnectionRelinkedEvent,
23
+ ConnectionRelinkRequiredEvent,
24
+ ConnectionRevokedEvent,
25
+ )
26
+
27
+ WEBHOOK_SIGNATURE_HEADER = "SapanCal-Signature"
28
+ WEBHOOK_EVENT_ID_HEADER = "SapanCal-Event-Id"
29
+ DEFAULT_WEBHOOK_TOLERANCE = 300
30
+ """How far a signature's timestamp may be from now, in seconds, before it's rejected as a replay."""
31
+
32
+ WebhookEvent = Union[ConnectionCreatedEvent, ConnectionRelinkedEvent, ConnectionRelinkRequiredEvent, ConnectionRevokedEvent, CalendarChangedEvent]
33
+ """Every webhook SapanCal sends. Narrow on ``event["type"]``."""
34
+
35
+ _HEX64 = re.compile(r"^[0-9a-fA-F]{64}$")
36
+ _TIMESTAMP = re.compile(r"^\d{1,12}$")
37
+
38
+
39
+ def _bytes(payload: str | bytes | bytearray | memoryview) -> bytes:
40
+ if isinstance(payload, str):
41
+ return payload.encode("utf-8")
42
+ if isinstance(payload, (bytes, bytearray, memoryview)):
43
+ return bytes(payload)
44
+ raise WebhookVerificationError("Webhook payload must be the raw request body (str or bytes), not parsed JSON.")
45
+
46
+
47
+ def _header(headers: Mapping[str, Any], name: str) -> str | None:
48
+ value = headers.get(name)
49
+ if value is None:
50
+ lower = name.lower()
51
+ value = next((v for k, v in headers.items() if isinstance(k, str) and k.lower() == lower), None)
52
+ if isinstance(value, (list, tuple)):
53
+ value = value[0] if value else None
54
+ return value if isinstance(value, str) else None
55
+
56
+
57
+ def _parse(value: str) -> tuple[int, list[str]] | None:
58
+ timestamp: int | None = None
59
+ signatures: list[str] = []
60
+ for part in value.split(","):
61
+ key, sep, val = part.partition("=")
62
+ if not sep:
63
+ continue
64
+ key, val = key.strip(), val.strip()
65
+ if key == "t":
66
+ if not _TIMESTAMP.match(val):
67
+ return None
68
+ timestamp = int(val)
69
+ elif key == "v1" and _HEX64.match(val):
70
+ signatures.append(val.lower())
71
+ return None if timestamp is None or not signatures else (timestamp, signatures)
72
+
73
+
74
+ def _mac(secret: str, timestamp: int, body: bytes) -> str:
75
+ return hmac.new(secret.encode("utf-8"), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
76
+
77
+
78
+ def verify_webhook(
79
+ payload: str | bytes | bytearray | memoryview,
80
+ headers: Mapping[str, Any],
81
+ secret: str,
82
+ *,
83
+ tolerance: int = DEFAULT_WEBHOOK_TOLERANCE,
84
+ ) -> WebhookEvent:
85
+ """Checks a webhook's signature and returns the parsed event, or raises ``WebhookVerificationError``.
86
+
87
+ ``payload`` is the raw request body (``request.body`` in Django, ``request.get_data()`` in Flask,
88
+ ``await request.body()`` in FastAPI). De-duplicate on ``event["id"]``: retries reuse it.
89
+ """
90
+ if not secret:
91
+ raise WebhookVerificationError("A webhook signing secret is required.")
92
+ body = _bytes(payload)
93
+ value = _header(headers, WEBHOOK_SIGNATURE_HEADER)
94
+ if not value:
95
+ raise WebhookVerificationError(f"Missing {WEBHOOK_SIGNATURE_HEADER} header.")
96
+ parsed = _parse(value)
97
+ if parsed is None:
98
+ raise WebhookVerificationError(f"Malformed {WEBHOOK_SIGNATURE_HEADER} header.")
99
+ timestamp, signatures = parsed
100
+ if abs(int(time.time()) - timestamp) > tolerance:
101
+ raise WebhookVerificationError("Webhook timestamp is outside the tolerance. Check your server clock, or this may be a replay.")
102
+ expected = _mac(secret, timestamp, body)
103
+ # Check every candidate so timing doesn't reveal which matched.
104
+ matches = [hmac.compare_digest(expected, sig) for sig in signatures]
105
+ if not any(matches):
106
+ raise WebhookVerificationError("Webhook signature does not match. Check the signing secret, and pass the raw body.")
107
+ try:
108
+ return cast(WebhookEvent, json.loads(body))
109
+ except ValueError as err:
110
+ raise WebhookVerificationError("Webhook body is not valid JSON.") from err
111
+
112
+
113
+ def sign_webhook(payload: str | bytes, secret: str, *, timestamp: int | None = None) -> str:
114
+ """A valid ``SapanCal-Signature`` header for ``payload``, for testing your webhook handler."""
115
+ ts = int(time.time()) if timestamp is None else timestamp
116
+ return f"t={ts},v1={_mac(secret, ts, _bytes(payload))}"
sapancal/py.typed ADDED
File without changes
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.5
2
+ Name: sapancal
3
+ Version: 0.2.0
4
+ Summary: The SapanCal API client for Python: connect Google and Microsoft calendars, find availability, write events, verify webhooks.
5
+ Project-URL: Homepage, https://sapancal.com
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: availability,calendar,free busy,google calendar,microsoft outlook,sapancal,scheduling
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Framework :: AsyncIO
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.11
15
+ Requires-Dist: httpx<1,>=0.27
16
+ Description-Content-Type: text/markdown
17
+
18
+ # SapanCal for Python
19
+
20
+ The official client for the [SapanCal](https://sapancal.com) API: connect your users' Google and Microsoft calendars, find when they're free, and write events, from one API.
21
+
22
+ - Sync and asyncio clients
23
+ - Fully typed: responses are `TypedDict`s generated from the API's OpenAPI document
24
+ - Retries rate limits and provider hiccups for you
25
+ - Webhook signature verification built in
26
+ - One dependency (`httpx`), Python 3.11+
27
+
28
+ ```sh
29
+ pip install sapancal
30
+ ```
31
+
32
+ ## Quickstart
33
+
34
+ ```python
35
+ from sapancal import SapanCal
36
+
37
+ client = SapanCal() # reads SAPANCAL_API_KEY
38
+ ```
39
+
40
+ Your API key is in the console under **Application → API keys**. It already says which region your application lives in, so there's nothing else to configure.
41
+
42
+ ### 1. Connect a calendar
43
+
44
+ Create a connect session for one of your users and send them to its `url`:
45
+
46
+ ```python
47
+ session = client.connect_sessions.create(
48
+ user_id="user_123", # your own id for the user
49
+ redirect_uri="https://app.example.com/calendar/connected",
50
+ )
51
+ return redirect(session["url"])
52
+ ```
53
+
54
+ They sign in to Google or Microsoft and come back to your `redirect_uri` with `connect_session_id` and `status` in the query string:
55
+
56
+ ```python
57
+ # GET /calendar/connected?connect_session_id=cs_...&status=success
58
+ session = client.connect_sessions.get(request.args["connect_session_id"])
59
+ if session["status"] == "completed":
60
+ print("Connected", session["connection"]["email"])
61
+ ```
62
+
63
+ ### 2. Find a time
64
+
65
+ ```python
66
+ from datetime import datetime
67
+ from zoneinfo import ZoneInfo
68
+
69
+ sydney = ZoneInfo("Australia/Sydney")
70
+ result = client.availability.query(
71
+ participants=[{"user_id": "user_123"}, {"user_id": "user_456"}],
72
+ periods=[{"start": datetime(2026, 11, 2, 9, tzinfo=sydney), "end": datetime(2026, 11, 2, 17, tzinfo=sydney)}],
73
+ slot_duration_minutes=30,
74
+ )
75
+ for slot in result["slots"]:
76
+ print(slot["start"], slot["user_ids"])
77
+ ```
78
+
79
+ `start` and `end` take a timezone-aware `datetime` or an ISO 8601 string. For raw busy blocks instead of slots, use `client.free_busy.query(user_ids=[...], start=..., end=...)`.
80
+
81
+ ### 3. Book it
82
+
83
+ Events are keyed by your own id, so the same call creates and later updates the event, and a retry never makes a duplicate:
84
+
85
+ ```python
86
+ slot = result["slots"][0]
87
+ client.events.upsert("user_123", "booking_789", summary="Intro call", start=slot["start"], end=slot["end"], time_zone="Australia/Sydney")
88
+
89
+ client.events.delete("user_123", "booking_789")
90
+ ```
91
+
92
+ ### 4. Handle webhooks
93
+
94
+ SapanCal tells you when a connection is created, needs relinking or is revoked, and when a calendar changes. Verify the signature against the **raw** request body:
95
+
96
+ ```python
97
+ from sapancal import WebhookVerificationError
98
+
99
+ # Flask
100
+ @app.post("/webhooks/sapancal")
101
+ def sapancal_webhook():
102
+ try:
103
+ event = client.webhooks.verify(request.get_data(), request.headers) # secret from SAPANCAL_WEBHOOK_SECRET
104
+ except WebhookVerificationError:
105
+ return "", 400
106
+
107
+ if event["type"] == "connection.relink_required":
108
+ ask_user_to_reconnect(event["data"]["user_id"], event["data"]["connection_id"])
109
+ elif event["type"] == "calendar.changed":
110
+ resync(event["data"]["user_id"], event["data"]["calendar_id"])
111
+ return "", 204
112
+ ```
113
+
114
+ In Django pass `request.body` and `request.headers`; in FastAPI, `await request.body()` and `request.headers`. Verification fails if the signature is missing, wrong or older than five minutes. Deliveries are retried, so use `event["id"]` to skip ones you've already handled. During a signing-secret rotation both the old and new secret are accepted.
115
+
116
+ To test your handler, sign your own payload with `sapancal.sign_webhook(body, "whsec_test")` and send it as the `SapanCal-Signature` header.
117
+
118
+ ## Async
119
+
120
+ ```python
121
+ from sapancal import AsyncSapanCal
122
+
123
+ async with AsyncSapanCal() as client:
124
+ user = await client.users.get("user_123")
125
+ ```
126
+
127
+ Every method is the same, awaited.
128
+
129
+ ## All methods
130
+
131
+ | Method | API |
132
+ |---|---|
133
+ | `connect_sessions.create(user_id=, redirect_uri=, provider=, connection_id=)` | `POST /connect_sessions` |
134
+ | `connect_sessions.get(id)` | `GET /connect_sessions/{id}` |
135
+ | `users.get(user_id)` | `GET /users/{user_id}` |
136
+ | `users.update(user_id, default_connection_id=)` | `PATCH /users/{user_id}` |
137
+ | `users.delete(user_id)` | `DELETE /users/{user_id}` |
138
+ | `connections.get(id)` | `GET /connections/{id}` |
139
+ | `connections.delete(id)` | `DELETE /connections/{id}` |
140
+ | `connections.list_calendars(id)` | `GET /connections/{id}/calendars` |
141
+ | `free_busy.query(user_ids=, start=, end=, calendar_ids=)` | `POST /free_busy` |
142
+ | `availability.query(participants=, periods=, slot_duration_minutes=, ...)` | `POST /availability` |
143
+ | `events.upsert(user_id, event_id, summary=, start=, end=, ...)` | `PUT /users/{user_id}/events/{event_id}` |
144
+ | `events.delete(user_id, event_id)` | `DELETE /users/{user_id}/events/{event_id}` |
145
+ | `webhooks.verify(payload, headers, secret=)` | checks a webhook locally |
146
+
147
+ Arguments and response keys use the API's names, so the [API reference](https://api.sapancal.com/openapi.json) applies as written.
148
+
149
+ ## Errors
150
+
151
+ API errors raise `SapanCalApiError`. Branch on `code`, which is stable; the message is for people.
152
+
153
+ ```python
154
+ from sapancal import SapanCalApiError
155
+
156
+ try:
157
+ client.events.upsert(user_id, booking_id, summary="Intro call", start=start, end=end)
158
+ except SapanCalApiError as err:
159
+ if err.code == "relink_required":
160
+ # The user revoked access or changed their password: send them through a new connect
161
+ # session with connection_id to relink.
162
+ ...
163
+ raise
164
+ ```
165
+
166
+ `SapanCalApiError` has `status`, `code`, `message`, `request_id` (quote it to support), `details` (validation issues) and `retry_after`. Network failures and timeouts raise `SapanCalConnectionError`. Both extend `SapanCalError`.
167
+
168
+ ## Retries and timeouts
169
+
170
+ Network errors, `429` and `502`–`504` are retried twice with exponential backoff, waiting as long as the API's `Retry-After` asks (up to 60 seconds; longer waits raise instead). Each attempt times out after 30 seconds.
171
+
172
+ ```python
173
+ client = SapanCal(max_retries=4, timeout=10)
174
+ ```
175
+
176
+ ## Configuration
177
+
178
+ | Argument | Environment variable | Default |
179
+ |---|---|---|
180
+ | `api_key` | `SAPANCAL_API_KEY` | required |
181
+ | `webhook_secret` | `SAPANCAL_WEBHOOK_SECRET` | none |
182
+ | `base_url` | `SAPANCAL_BASE_URL` | `https://api.sapancal.com/{region}/v1`, region from the key |
183
+ | `timeout` | | `30` seconds |
184
+ | `max_retries` | | `2` |
185
+ | `http_client` | | a new `httpx.Client` / `httpx.AsyncClient` |
186
+
187
+ ## License
188
+
189
+ MIT
@@ -0,0 +1,11 @@
1
+ sapancal/__init__.py,sha256=aW7X_o4TXFHGHgWgkS7dBUEIvyfiujDo0HNIETnnJ2Q,1681
2
+ sapancal/_client.py,sha256=wEifoqrcakPI75znKlEsn2Lca5DdE5LjNxqOt68YQQg,25715
3
+ sapancal/_errors.py,sha256=tZhJFl1bzubx_7ZCtH8GV_xwKpDesCqnbDb1dayie1o,1922
4
+ sapancal/_types.py,sha256=_7zI_MjawzPFD9dPluxlPBjAQGhtiyE7Rhk71S2dFWE,11496
5
+ sapancal/_version.py,sha256=Zn1KFblwuFHiDRdRAiRnDBRkbPttWh44jKa5zG2ov0E,22
6
+ sapancal/_webhooks.py,sha256=yzBxR9K9HCayIUoJ-VhrVS-ENLhL5lmeVp4wPcg55vo,4611
7
+ sapancal/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ sapancal-0.2.0.dist-info/METADATA,sha256=tHUcctKz3agdXL8hS8Lz6nOhavmN3L94j6hDKxo7kh4,7177
9
+ sapancal-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ sapancal-0.2.0.dist-info/licenses/LICENSE,sha256=iSzLHapatvjPSsNFoHafF5_3c3zz8SXW70O3NxXlBnM,1075
11
+ sapancal-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sapan Labs Pty Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.