gabriel-calendar 0.1.0__tar.gz
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.
- gabriel_calendar-0.1.0/LICENSE +21 -0
- gabriel_calendar-0.1.0/PKG-INFO +56 -0
- gabriel_calendar-0.1.0/README.md +42 -0
- gabriel_calendar-0.1.0/pyproject.toml +24 -0
- gabriel_calendar-0.1.0/setup.cfg +4 -0
- gabriel_calendar-0.1.0/src/gabriel_calendar/__init__.py +529 -0
- gabriel_calendar-0.1.0/src/gabriel_calendar/_wire.py +191 -0
- gabriel_calendar-0.1.0/src/gabriel_calendar/py.typed +0 -0
- gabriel_calendar-0.1.0/src/gabriel_calendar.egg-info/PKG-INFO +56 -0
- gabriel_calendar-0.1.0/src/gabriel_calendar.egg-info/SOURCES.txt +12 -0
- gabriel_calendar-0.1.0/src/gabriel_calendar.egg-info/dependency_links.txt +1 -0
- gabriel_calendar-0.1.0/src/gabriel_calendar.egg-info/requires.txt +1 -0
- gabriel_calendar-0.1.0/src/gabriel_calendar.egg-info/top_level.txt +1 -0
- gabriel_calendar-0.1.0/tests/test_conformance.py +216 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EzEasy
|
|
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.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gabriel-calendar
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async SDK for the Gabriel Calendar service
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/Easy-Ez/gabriel-calendar
|
|
7
|
+
Project-URL: Documentation, https://github.com/Easy-Ez/gabriel-calendar/blob/main/spec/api.md
|
|
8
|
+
Project-URL: Issues, https://github.com/Easy-Ez/gabriel-calendar/issues
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: httpx<0.29,>=0.28.1
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# Gabriel Calendar SDK for Python
|
|
16
|
+
|
|
17
|
+
An async client for the Gabriel Calendar service. It connects a Google Calendar account, streams changes to the linked primary calendar over SSE, and supports pending invitations, RSVP, and single-event writes.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
python -m pip install gabriel-calendar
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Requires Python 3.11 or later, a Gabriel Calendar service URL, and a project session supplied by the service operator. Load the session from your application's secret store and pass it through `get_project_credential`.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import asyncio
|
|
29
|
+
import os
|
|
30
|
+
|
|
31
|
+
from gabriel_calendar import CalendarClient
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def main():
|
|
35
|
+
client = await CalendarClient.connect(
|
|
36
|
+
base_url="https://calendar.example.invalid",
|
|
37
|
+
get_project_credential=lambda: os.environ["GABRIEL_PROJECT_SESSION"],
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
@client.on("invitation.received")
|
|
41
|
+
def handle_invitation(notice):
|
|
42
|
+
print(notice.type)
|
|
43
|
+
|
|
44
|
+
async with client:
|
|
45
|
+
page = await client.events.list_invitations()
|
|
46
|
+
print("Pending invitations", len(page.events))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
asyncio.run(main())
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`connect()` opens the Google consent page and pairs a consumer. Use `save_grant` to store its connection ID, consumer ID, and credential in a secret store. Construct a new `CalendarClient` with those IDs and a `get_credential` callback to resume delivery in another process. Notifications are acknowledged after the registered handlers succeed. Use `notification_id` to make handler side effects idempotent across restarts.
|
|
53
|
+
|
|
54
|
+
Request `can_rsvp`, `can_create`, or `can_manage` when pairing a writer. For a guest event, also request `can_invite` and set `notify_guests` explicitly on each write. Creation takes an idempotency key, and updates and cancellations take the current event version.
|
|
55
|
+
|
|
56
|
+
[SDK and HTTP contract](https://github.com/Easy-Ez/gabriel-calendar/blob/main/spec/api.md) · [Service setup](https://github.com/Easy-Ez/gabriel-calendar/blob/main/docs/zh-CN/testing.md)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Gabriel Calendar SDK for Python
|
|
2
|
+
|
|
3
|
+
An async client for the Gabriel Calendar service. It connects a Google Calendar account, streams changes to the linked primary calendar over SSE, and supports pending invitations, RSVP, and single-event writes.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
python -m pip install gabriel-calendar
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires Python 3.11 or later, a Gabriel Calendar service URL, and a project session supplied by the service operator. Load the session from your application's secret store and pass it through `get_project_credential`.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import asyncio
|
|
15
|
+
import os
|
|
16
|
+
|
|
17
|
+
from gabriel_calendar import CalendarClient
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def main():
|
|
21
|
+
client = await CalendarClient.connect(
|
|
22
|
+
base_url="https://calendar.example.invalid",
|
|
23
|
+
get_project_credential=lambda: os.environ["GABRIEL_PROJECT_SESSION"],
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
@client.on("invitation.received")
|
|
27
|
+
def handle_invitation(notice):
|
|
28
|
+
print(notice.type)
|
|
29
|
+
|
|
30
|
+
async with client:
|
|
31
|
+
page = await client.events.list_invitations()
|
|
32
|
+
print("Pending invitations", len(page.events))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
asyncio.run(main())
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`connect()` opens the Google consent page and pairs a consumer. Use `save_grant` to store its connection ID, consumer ID, and credential in a secret store. Construct a new `CalendarClient` with those IDs and a `get_credential` callback to resume delivery in another process. Notifications are acknowledged after the registered handlers succeed. Use `notification_id` to make handler side effects idempotent across restarts.
|
|
39
|
+
|
|
40
|
+
Request `can_rsvp`, `can_create`, or `can_manage` when pairing a writer. For a guest event, also request `can_invite` and set `notify_guests` explicitly on each write. Creation takes an idempotency key, and updates and cancellations take the current event version.
|
|
41
|
+
|
|
42
|
+
[SDK and HTTP contract](https://github.com/Easy-Ez/gabriel-calendar/blob/main/spec/api.md) · [Service setup](https://github.com/Easy-Ez/gabriel-calendar/blob/main/docs/zh-CN/testing.md)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "gabriel-calendar"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Async SDK for the Gabriel Calendar service"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = ["httpx>=0.28.1,<0.29"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Repository = "https://github.com/Easy-Ez/gabriel-calendar"
|
|
17
|
+
Documentation = "https://github.com/Easy-Ez/gabriel-calendar/blob/main/spec/api.md"
|
|
18
|
+
Issues = "https://github.com/Easy-Ez/gabriel-calendar/issues"
|
|
19
|
+
|
|
20
|
+
[tool.setuptools.packages.find]
|
|
21
|
+
where = ["src"]
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.package-data]
|
|
24
|
+
gabriel_calendar = ["py.typed"]
|
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
"""Async SDK for the Gabriel Calendar service."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import codecs
|
|
7
|
+
import inspect
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import webbrowser
|
|
11
|
+
from collections import deque
|
|
12
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
13
|
+
from contextlib import aclosing
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any, Literal, TypeVar
|
|
16
|
+
from urllib.parse import quote, urlencode
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
|
|
20
|
+
from ._wire import (
|
|
21
|
+
CALENDAR_ID, CREDENTIAL, EVENT_ID, RSVP_STATUSES, UUID, VERSION,
|
|
22
|
+
CalendarError, CalendarEvent, EventRef, EventTime, Notification, Rsvp, decode_event,
|
|
23
|
+
decode_notification, matches, object_value, require, validated_url,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"CalendarClient", "CalendarError", "CalendarEvent", "EventRef", "EventTime",
|
|
28
|
+
"Grant", "InvitationPage", "LifecycleEvent", "Notification", "Rsvp", "decode_notification",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
Credential = Callable[[], str | Awaitable[str]]
|
|
32
|
+
T = TypeVar("T")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Grant:
|
|
37
|
+
connection_id: str
|
|
38
|
+
consumer_id: str
|
|
39
|
+
credential: str
|
|
40
|
+
|
|
41
|
+
def __repr__(self) -> str:
|
|
42
|
+
return "Grant(credential=[redacted])"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class LifecycleEvent:
|
|
47
|
+
type: str
|
|
48
|
+
error: CalendarError | None = None
|
|
49
|
+
reason: str | None = None
|
|
50
|
+
attempt: int | None = None
|
|
51
|
+
delay_ms: int | None = None
|
|
52
|
+
code: str | None = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class InvitationPage:
|
|
57
|
+
events: list[CalendarEvent]
|
|
58
|
+
next_page_cursor: str | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
Handler = Callable[[Notification | LifecycleEvent], None | Awaitable[None]]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def _result(value: T | Awaitable[T]) -> T:
|
|
65
|
+
return await value if inspect.isawaitable(value) else value
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def _authorization(get_credential: Credential) -> str:
|
|
69
|
+
try:
|
|
70
|
+
credential = await _result(get_credential())
|
|
71
|
+
except Exception:
|
|
72
|
+
raise CalendarError("AUTH_REQUIRED") from None
|
|
73
|
+
require(matches(credential, CREDENTIAL), "AUTH_REQUIRED")
|
|
74
|
+
return "Bearer " + credential
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _response_error(payload: Any, status: int, request_id: Any, retry: Any) -> CalendarError:
|
|
78
|
+
error = payload.get("error") if isinstance(payload, dict) else None
|
|
79
|
+
code = error.get("code") if isinstance(error, dict) else None
|
|
80
|
+
return CalendarError(
|
|
81
|
+
code if matches(code, re.compile(r"[A-Z_]{1,64}")) else "HTTP_ERROR", status,
|
|
82
|
+
request_id if matches(request_id, UUID) else None,
|
|
83
|
+
min(3600, retry) if type(retry) is int and retry > 0 else None,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _checked_response(response: httpx.Response) -> Any:
|
|
88
|
+
try:
|
|
89
|
+
payload = response.json()
|
|
90
|
+
except ValueError:
|
|
91
|
+
payload = None
|
|
92
|
+
if not response.is_success:
|
|
93
|
+
retry = response.headers.get("retry-after")
|
|
94
|
+
raise _response_error(payload, response.status_code, response.headers.get("x-request-id"),
|
|
95
|
+
int(retry) if matches(retry, re.compile(r"[0-9]{1,4}")) else None)
|
|
96
|
+
return payload
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def _request(
|
|
100
|
+
base: str, path: str, get_credential: Credential, *, method: str = "GET",
|
|
101
|
+
body: dict[str, Any] | None = None, if_match: str | None = None, idempotency_key: str | None = None,
|
|
102
|
+
) -> dict[str, Any] | None:
|
|
103
|
+
headers = {"Authorization": await _authorization(get_credential)}
|
|
104
|
+
if if_match is not None:
|
|
105
|
+
headers["If-Match"] = if_match
|
|
106
|
+
if idempotency_key is not None:
|
|
107
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
108
|
+
try:
|
|
109
|
+
# Use HTTPX's transport directly so its client logger does not record calendar IDs in URLs.
|
|
110
|
+
async with asyncio.timeout(35), httpx.AsyncHTTPTransport(trust_env=False) as transport:
|
|
111
|
+
request = httpx.Request(method, base + path, headers=headers, json=body)
|
|
112
|
+
response = await transport.handle_async_request(request)
|
|
113
|
+
try:
|
|
114
|
+
await response.aread()
|
|
115
|
+
finally:
|
|
116
|
+
await response.aclose()
|
|
117
|
+
except (httpx.HTTPError, TimeoutError):
|
|
118
|
+
raise CalendarError("NETWORK_ERROR") from None
|
|
119
|
+
if response.status_code == 204:
|
|
120
|
+
return None
|
|
121
|
+
return object_value(_checked_response(response))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def _stream(base: str, path: str, get_credential: Credential) -> AsyncIterator[tuple[str, str]]:
|
|
125
|
+
headers = {"Authorization": await _authorization(get_credential), "Accept": "text/event-stream"}
|
|
126
|
+
try:
|
|
127
|
+
async with httpx.AsyncHTTPTransport(trust_env=False) as transport:
|
|
128
|
+
async with asyncio.timeout(35):
|
|
129
|
+
response = await transport.handle_async_request(httpx.Request("GET", base + path, headers=headers))
|
|
130
|
+
try:
|
|
131
|
+
if not response.is_success:
|
|
132
|
+
async with asyncio.timeout(35):
|
|
133
|
+
await response.aread()
|
|
134
|
+
_checked_response(response)
|
|
135
|
+
require(response.status_code == 200 and
|
|
136
|
+
response.headers.get("content-type", "").split(";")[0].strip().lower() == "text/event-stream")
|
|
137
|
+
decoder = codecs.getincrementaldecoder("utf-8-sig")()
|
|
138
|
+
chunks = response.aiter_bytes()
|
|
139
|
+
newline = re.compile(r"\r\n|[\r\n]")
|
|
140
|
+
buffer = event = data = ""
|
|
141
|
+
size = 0
|
|
142
|
+
comment = False
|
|
143
|
+
while True:
|
|
144
|
+
try:
|
|
145
|
+
async with asyncio.timeout(35):
|
|
146
|
+
chunk = await anext(chunks)
|
|
147
|
+
except StopAsyncIteration:
|
|
148
|
+
raise CalendarError("NETWORK_ERROR") from None
|
|
149
|
+
try:
|
|
150
|
+
buffer += decoder.decode(chunk)
|
|
151
|
+
except UnicodeError:
|
|
152
|
+
raise CalendarError("INVALID_RESPONSE") from None
|
|
153
|
+
while match := newline.search(buffer):
|
|
154
|
+
if match.group() == "\r" and match.end() == len(buffer):
|
|
155
|
+
break
|
|
156
|
+
line, buffer = buffer[:match.start()], buffer[match.end():]
|
|
157
|
+
size += len(line) + 1
|
|
158
|
+
require(size <= 256 * 1024)
|
|
159
|
+
if not line:
|
|
160
|
+
frame = (event or "message", data[:-1]) if data else ("heartbeat", "") if comment else None
|
|
161
|
+
event = data = ""
|
|
162
|
+
size = 0
|
|
163
|
+
comment = False
|
|
164
|
+
if frame:
|
|
165
|
+
yield frame
|
|
166
|
+
elif line.startswith(":"):
|
|
167
|
+
comment = True
|
|
168
|
+
else:
|
|
169
|
+
field, _, raw = line.partition(":")
|
|
170
|
+
value = raw.removeprefix(" ")
|
|
171
|
+
if field == "event":
|
|
172
|
+
event = value
|
|
173
|
+
if field == "data":
|
|
174
|
+
data += value + "\n"
|
|
175
|
+
require(len(buffer) + size <= 256 * 1024)
|
|
176
|
+
finally:
|
|
177
|
+
await response.aclose()
|
|
178
|
+
except (httpx.HTTPError, TimeoutError):
|
|
179
|
+
raise CalendarError("NETWORK_ERROR") from None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
async def _next_frame(frames: AsyncIterator[tuple[str, str]]) -> tuple[str, str]:
|
|
183
|
+
return await anext(frames)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _frame_data(value: str) -> Any:
|
|
187
|
+
try:
|
|
188
|
+
return json.loads(value)
|
|
189
|
+
except ValueError:
|
|
190
|
+
raise CalendarError("INVALID_RESPONSE") from None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
async def _open_browser(url: str) -> None:
|
|
194
|
+
if not await asyncio.to_thread(webbrowser.open, url):
|
|
195
|
+
raise CalendarError("BROWSER_UNAVAILABLE")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _retryable(error: CalendarError) -> bool:
|
|
199
|
+
return (
|
|
200
|
+
error.code in ("NETWORK_ERROR", "HANDLER_FAILED", "READER_BUSY", "RATE_LIMITED")
|
|
201
|
+
or error.status is not None and error.status >= 500
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _terminal(error: CalendarError) -> LifecycleEvent:
|
|
206
|
+
if error.code == "CURSOR_EXPIRED":
|
|
207
|
+
return LifecycleEvent("connection.gap", error=error, reason="cursor_expired")
|
|
208
|
+
if error.code == "AUTH_REQUIRED":
|
|
209
|
+
return LifecycleEvent("auth.required", error=error)
|
|
210
|
+
return LifecycleEvent("connection.error", error=error)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@dataclass
|
|
214
|
+
class _Run:
|
|
215
|
+
ready: asyncio.Future[None]
|
|
216
|
+
task: asyncio.Task[None] | None = None
|
|
217
|
+
intake: asyncio.Task[Any] | None = None
|
|
218
|
+
stopping: bool = False
|
|
219
|
+
abandoned: bool = False
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class _Events:
|
|
223
|
+
def __init__(self, client: CalendarClient) -> None:
|
|
224
|
+
self._client = client
|
|
225
|
+
|
|
226
|
+
async def create(
|
|
227
|
+
self, calendar_id: str, *, title: str, start: str, end: str, idempotency_key: str,
|
|
228
|
+
show_as: Literal["busy", "free"] | None = None,
|
|
229
|
+
guests: list[str] | None = None, notify_guests: bool | None = None,
|
|
230
|
+
) -> CalendarEvent:
|
|
231
|
+
require(
|
|
232
|
+
matches(calendar_id, CALENDAR_ID) and matches(idempotency_key, re.compile(r"[A-Za-z0-9_-]{1,128}"))
|
|
233
|
+
and all(isinstance(value, str) for value in (title, start, end))
|
|
234
|
+
and (show_as is None or show_as in ("busy", "free"))
|
|
235
|
+
and (guests is None or (isinstance(guests, list) and len(guests) <= 12
|
|
236
|
+
and all(isinstance(guest, str) for guest in guests)))
|
|
237
|
+
and (notify_guests is None or type(notify_guests) is bool)
|
|
238
|
+
and (not guests or notify_guests is not None), "INVALID_ARGUMENT",
|
|
239
|
+
)
|
|
240
|
+
path = f"{self._client._path}/calendars/{quote(calendar_id, safe='')}/events"
|
|
241
|
+
body: dict[str, Any] = {"title": title, "start": start, "end": end}
|
|
242
|
+
if show_as is not None:
|
|
243
|
+
body["showAs"] = show_as
|
|
244
|
+
if guests is not None:
|
|
245
|
+
body["guests"] = guests
|
|
246
|
+
if notify_guests is not None:
|
|
247
|
+
body["notifyGuests"] = notify_guests
|
|
248
|
+
event = decode_event(await _request(
|
|
249
|
+
self._client._base, path, self._client._credential, method="POST", body=body, idempotency_key=idempotency_key,
|
|
250
|
+
))
|
|
251
|
+
require(calendar_id == "primary" or calendar_id == event.ref.calendar_id)
|
|
252
|
+
return event
|
|
253
|
+
|
|
254
|
+
async def update(
|
|
255
|
+
self, ref: EventRef, *, if_match: str, title: str | None = None,
|
|
256
|
+
start: str | None = None, end: str | None = None, notify_guests: bool | None = None,
|
|
257
|
+
) -> CalendarEvent:
|
|
258
|
+
require((title is not None or start is not None or end is not None)
|
|
259
|
+
and (title is None or isinstance(title, str))
|
|
260
|
+
and ((start is None and end is None) or (isinstance(start, str) and isinstance(end, str))),
|
|
261
|
+
"INVALID_ARGUMENT")
|
|
262
|
+
patch = {key: value for key, value in (("title", title), ("start", start), ("end", end)) if value is not None}
|
|
263
|
+
return await self._manage(ref, if_match, notify_guests, patch)
|
|
264
|
+
|
|
265
|
+
async def cancel(self, ref: EventRef, *, if_match: str, notify_guests: bool | None = None) -> CalendarEvent:
|
|
266
|
+
return await self._manage(ref, if_match, notify_guests)
|
|
267
|
+
|
|
268
|
+
async def _manage(
|
|
269
|
+
self, ref: EventRef, if_match: str, notify_guests: bool | None, patch: dict[str, str] | None = None,
|
|
270
|
+
) -> CalendarEvent:
|
|
271
|
+
require(isinstance(ref, EventRef) and matches(ref.calendar_id, CALENDAR_ID)
|
|
272
|
+
and matches(ref.event_id, EVENT_ID) and matches(if_match, VERSION)
|
|
273
|
+
and (notify_guests is None or type(notify_guests) is bool), "INVALID_ARGUMENT")
|
|
274
|
+
path = f"{self._client._path}/calendars/{quote(ref.calendar_id, safe='')}/events/{quote(ref.event_id, safe='')}"
|
|
275
|
+
updating = patch is not None
|
|
276
|
+
body: dict[str, Any] = dict(patch or {})
|
|
277
|
+
if notify_guests is not None:
|
|
278
|
+
body["notifyGuests"] = notify_guests
|
|
279
|
+
event = decode_event(await _request(
|
|
280
|
+
self._client._base, path if updating else path + "/cancel", self._client._credential,
|
|
281
|
+
method="PATCH" if updating else "POST", body=body, if_match=if_match,
|
|
282
|
+
))
|
|
283
|
+
require(event.ref == ref and (event.status != "cancelled" and event.version is not None
|
|
284
|
+
if updating else event.status == "cancelled"))
|
|
285
|
+
return event
|
|
286
|
+
|
|
287
|
+
async def list_invitations(
|
|
288
|
+
self, *, calendar_id: str = "primary", page_cursor: str | None = None, limit: int | None = None,
|
|
289
|
+
) -> InvitationPage:
|
|
290
|
+
return await self._client.list_invitations(calendar_id=calendar_id, page_cursor=page_cursor, limit=limit)
|
|
291
|
+
|
|
292
|
+
async def rsvp(self, ref: EventRef, status: Rsvp, *, if_match: str | None = None) -> CalendarEvent:
|
|
293
|
+
require(
|
|
294
|
+
isinstance(ref, EventRef) and matches(ref.calendar_id, CALENDAR_ID) and matches(ref.event_id, EVENT_ID)
|
|
295
|
+
and status in RSVP_STATUSES and (if_match is None or matches(if_match, VERSION)), "INVALID_ARGUMENT",
|
|
296
|
+
)
|
|
297
|
+
path = f"{self._client._path}/calendars/{quote(ref.calendar_id, safe='')}/events/{quote(ref.event_id, safe='')}/rsvp"
|
|
298
|
+
event = decode_event(await _request(
|
|
299
|
+
self._client._base, path, self._client._credential, method="PUT", body={"status": status}, if_match=if_match,
|
|
300
|
+
))
|
|
301
|
+
require(event.ref == ref)
|
|
302
|
+
return event
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
class CalendarClient:
|
|
306
|
+
def __init__(self, *, base_url: str, connection_id: str, consumer_id: str, get_credential: Credential) -> None:
|
|
307
|
+
self._base = validated_url(base_url, origin_only=True)
|
|
308
|
+
require(matches(connection_id, UUID) and matches(consumer_id, UUID) and callable(get_credential), "INVALID_ARGUMENT")
|
|
309
|
+
self.connection_id = connection_id
|
|
310
|
+
self.consumer_id = consumer_id
|
|
311
|
+
self._credential = get_credential
|
|
312
|
+
self._path = f"/v1/connections/{connection_id}"
|
|
313
|
+
self._reader = f"{self._path}/consumers/{consumer_id}"
|
|
314
|
+
self.events = _Events(self)
|
|
315
|
+
self._handlers: dict[str, list[Handler]] = {}
|
|
316
|
+
self._processed: set[str] = set()
|
|
317
|
+
self._processed_order: deque[str] = deque()
|
|
318
|
+
self._run: _Run | None = None
|
|
319
|
+
|
|
320
|
+
@classmethod
|
|
321
|
+
async def connect(
|
|
322
|
+
cls, *, base_url: str, get_project_credential: Credential,
|
|
323
|
+
open_browser: Callable[[str], None | Awaitable[None]] | None = None,
|
|
324
|
+
can_rsvp: bool = False, can_create: bool = False, can_manage: bool = False, can_invite: bool = False,
|
|
325
|
+
save_grant: Callable[[Grant], None | Awaitable[None]] | None = None,
|
|
326
|
+
) -> CalendarClient:
|
|
327
|
+
base = validated_url(base_url, origin_only=True)
|
|
328
|
+
require(callable(get_project_credential)
|
|
329
|
+
and all(type(value) is bool for value in (can_rsvp, can_create, can_manage, can_invite)),
|
|
330
|
+
"INVALID_ARGUMENT")
|
|
331
|
+
project = get_project_credential
|
|
332
|
+
try:
|
|
333
|
+
async with asyncio.timeout(15 * 60):
|
|
334
|
+
session = object_value(await _request(base, "/v1/connect-sessions", project, method="POST"))
|
|
335
|
+
require(matches(session.get("sessionId"), UUID))
|
|
336
|
+
await _result((open_browser or _open_browser)(validated_url(session.get("authorizationUrl"))))
|
|
337
|
+
while True:
|
|
338
|
+
result = object_value(await _request(base, f"/v1/connect-sessions/{session['sessionId']}", project))
|
|
339
|
+
if result.get("status") == "failed":
|
|
340
|
+
raise CalendarError("CONSENT_FAILED")
|
|
341
|
+
if result.get("status") == "connected":
|
|
342
|
+
connection = result.get("connectionId")
|
|
343
|
+
require(matches(connection, UUID))
|
|
344
|
+
capabilities = {"canRsvp": can_rsvp}
|
|
345
|
+
if can_create:
|
|
346
|
+
capabilities["canCreate"] = True
|
|
347
|
+
if can_manage:
|
|
348
|
+
capabilities["canManage"] = True
|
|
349
|
+
if can_invite:
|
|
350
|
+
capabilities["canInvite"] = True
|
|
351
|
+
grant = object_value(await _request(
|
|
352
|
+
base, f"/v1/connections/{connection}/consumers", project, method="POST", body=capabilities,
|
|
353
|
+
))
|
|
354
|
+
require(grant.get("connectionId") == connection and matches(grant.get("consumerId"), UUID)
|
|
355
|
+
and matches(grant.get("credential"), CREDENTIAL))
|
|
356
|
+
credential = grant["credential"]
|
|
357
|
+
if save_grant is not None:
|
|
358
|
+
await _result(save_grant(Grant(connection, grant["consumerId"], credential)))
|
|
359
|
+
return cls(base_url=base, connection_id=connection, consumer_id=grant["consumerId"],
|
|
360
|
+
get_credential=lambda: credential)
|
|
361
|
+
require(result.get("status") == "pending")
|
|
362
|
+
await asyncio.sleep(1)
|
|
363
|
+
except TimeoutError:
|
|
364
|
+
raise CalendarError("CONSENT_EXPIRED") from None
|
|
365
|
+
|
|
366
|
+
def on(self, kind: str, handler: Handler | None = None):
|
|
367
|
+
handlers = self._handlers.setdefault(kind, [])
|
|
368
|
+
|
|
369
|
+
def subscribe(callback: Handler):
|
|
370
|
+
if callback not in handlers:
|
|
371
|
+
handlers.append(callback)
|
|
372
|
+
return callback
|
|
373
|
+
|
|
374
|
+
if handler is None:
|
|
375
|
+
return subscribe
|
|
376
|
+
subscribe(handler)
|
|
377
|
+
|
|
378
|
+
def unsubscribe() -> None:
|
|
379
|
+
if handler in handlers:
|
|
380
|
+
handlers.remove(handler)
|
|
381
|
+
|
|
382
|
+
return unsubscribe
|
|
383
|
+
|
|
384
|
+
async def list_invitations(
|
|
385
|
+
self, *, calendar_id: str = "primary", page_cursor: str | None = None, limit: int | None = None,
|
|
386
|
+
) -> InvitationPage:
|
|
387
|
+
require(matches(calendar_id, CALENDAR_ID) and (page_cursor is None or matches(page_cursor, EVENT_ID))
|
|
388
|
+
and (limit is None or type(limit) is int and 1 <= limit <= 100), "INVALID_ARGUMENT")
|
|
389
|
+
query = {"rsvp": "needsAction"}
|
|
390
|
+
if page_cursor is not None:
|
|
391
|
+
query["pageCursor"] = page_cursor
|
|
392
|
+
if limit is not None:
|
|
393
|
+
query["limit"] = str(limit)
|
|
394
|
+
path = f"{self._path}/calendars/{quote(calendar_id, safe='')}/events?{urlencode(query)}"
|
|
395
|
+
result = object_value(await _request(self._base, path, self._credential))
|
|
396
|
+
events = result.get("events")
|
|
397
|
+
next_cursor = result.get("nextPageCursor")
|
|
398
|
+
require(isinstance(events, list) and len(events) <= 100
|
|
399
|
+
and ("nextPageCursor" not in result or matches(next_cursor, EVENT_ID)))
|
|
400
|
+
return InvitationPage([decode_event(event) for event in events], next_cursor)
|
|
401
|
+
|
|
402
|
+
async def start(self) -> None:
|
|
403
|
+
if self._run is not None:
|
|
404
|
+
raise CalendarError("INVALID_STATE")
|
|
405
|
+
run = _Run(asyncio.get_running_loop().create_future())
|
|
406
|
+
self._run = run
|
|
407
|
+
run.task = asyncio.create_task(self._listen(run))
|
|
408
|
+
try:
|
|
409
|
+
await asyncio.wait_for(asyncio.shield(run.ready), timeout=35)
|
|
410
|
+
except TimeoutError:
|
|
411
|
+
run.ready.cancel()
|
|
412
|
+
await self.stop(drain=0)
|
|
413
|
+
raise CalendarError("NETWORK_TIMEOUT") from None
|
|
414
|
+
except BaseException:
|
|
415
|
+
run.ready.cancel()
|
|
416
|
+
await self.stop(drain=0)
|
|
417
|
+
raise
|
|
418
|
+
|
|
419
|
+
async def stop(self, *, drain: float = 10.0) -> None:
|
|
420
|
+
require(type(drain) in (int, float) and 0 <= drain <= 60, "INVALID_ARGUMENT")
|
|
421
|
+
run = self._run
|
|
422
|
+
if run is None or run.task is None:
|
|
423
|
+
return
|
|
424
|
+
run.stopping = True
|
|
425
|
+
if run.intake is not None:
|
|
426
|
+
run.intake.cancel()
|
|
427
|
+
if run.task is asyncio.current_task():
|
|
428
|
+
return
|
|
429
|
+
_, pending = await asyncio.wait({run.task}, timeout=drain)
|
|
430
|
+
if pending:
|
|
431
|
+
run.abandoned = True
|
|
432
|
+
run.task.cancel()
|
|
433
|
+
|
|
434
|
+
async def __aenter__(self) -> CalendarClient:
|
|
435
|
+
await self.start()
|
|
436
|
+
return self
|
|
437
|
+
|
|
438
|
+
async def __aexit__(self, *_: object) -> None:
|
|
439
|
+
await self.stop()
|
|
440
|
+
|
|
441
|
+
async def _intake(self, run: _Run, awaitable: Any) -> Any:
|
|
442
|
+
run.intake = asyncio.create_task(awaitable)
|
|
443
|
+
try:
|
|
444
|
+
return await run.intake
|
|
445
|
+
finally:
|
|
446
|
+
run.intake = None
|
|
447
|
+
|
|
448
|
+
async def _emit(self, event: Notification | LifecycleEvent, run: _Run, strict: bool) -> None:
|
|
449
|
+
for handler in tuple(self._handlers.get(event.type, ())):
|
|
450
|
+
if run.abandoned or (not strict and run.stopping):
|
|
451
|
+
return
|
|
452
|
+
try:
|
|
453
|
+
await _result(handler(event))
|
|
454
|
+
except Exception:
|
|
455
|
+
if strict:
|
|
456
|
+
raise CalendarError("HANDLER_FAILED") from None
|
|
457
|
+
|
|
458
|
+
async def _process(self, event: Notification, run: _Run) -> None:
|
|
459
|
+
if event.notification_id not in self._processed:
|
|
460
|
+
await self._emit(event, run, strict=True)
|
|
461
|
+
if run.abandoned:
|
|
462
|
+
return
|
|
463
|
+
self._processed.add(event.notification_id)
|
|
464
|
+
self._processed_order.append(event.notification_id)
|
|
465
|
+
if len(self._processed_order) > 1024:
|
|
466
|
+
self._processed.remove(self._processed_order.popleft())
|
|
467
|
+
if not run.abandoned:
|
|
468
|
+
result = await _request(
|
|
469
|
+
self._base, self._reader + "/ack", self._credential, method="POST", body={"cursor": event.cursor},
|
|
470
|
+
)
|
|
471
|
+
require(result is None)
|
|
472
|
+
|
|
473
|
+
async def _listen(self, run: _Run) -> None:
|
|
474
|
+
ready = False
|
|
475
|
+
attempt = 0
|
|
476
|
+
try:
|
|
477
|
+
while not run.stopping:
|
|
478
|
+
try:
|
|
479
|
+
opened = False
|
|
480
|
+
async with aclosing(_stream(self._base, self._reader + "/stream", self._credential)) as frames:
|
|
481
|
+
while not run.stopping:
|
|
482
|
+
# Wrap anext in a coroutine because create_task requires one.
|
|
483
|
+
frame = await self._intake(run, _next_frame(frames))
|
|
484
|
+
if run.stopping:
|
|
485
|
+
break
|
|
486
|
+
kind, raw = frame
|
|
487
|
+
if kind == "heartbeat":
|
|
488
|
+
if opened:
|
|
489
|
+
attempt = 0
|
|
490
|
+
continue
|
|
491
|
+
if kind == "ready":
|
|
492
|
+
require(not opened)
|
|
493
|
+
object_value(_frame_data(raw))
|
|
494
|
+
opened = ready = True
|
|
495
|
+
if not run.ready.done():
|
|
496
|
+
run.ready.set_result(None)
|
|
497
|
+
await self._emit(LifecycleEvent("connection.ready"), run, strict=False)
|
|
498
|
+
continue
|
|
499
|
+
if kind == "error":
|
|
500
|
+
data = object_value(_frame_data(raw))
|
|
501
|
+
status = data.get("status")
|
|
502
|
+
require(type(status) is int and 400 <= status <= 599)
|
|
503
|
+
raise _response_error(data, status, data.get("requestId"), data.get("retryAfter"))
|
|
504
|
+
require(opened and kind == "notification")
|
|
505
|
+
await self._process(decode_notification(_frame_data(raw), self.connection_id), run)
|
|
506
|
+
attempt = 0
|
|
507
|
+
except CalendarError as error:
|
|
508
|
+
if run.stopping:
|
|
509
|
+
break
|
|
510
|
+
if not _retryable(error):
|
|
511
|
+
if not run.ready.done():
|
|
512
|
+
run.ready.set_exception(error)
|
|
513
|
+
await self._emit(_terminal(error), run, strict=False)
|
|
514
|
+
return
|
|
515
|
+
attempt += 1
|
|
516
|
+
delay_ms = error.retry_after * 1000 if error.retry_after else min(250 * 2 ** min(attempt - 1, 7), 30_000)
|
|
517
|
+
await self._emit(
|
|
518
|
+
LifecycleEvent("connection.reconnecting", attempt=attempt, delay_ms=delay_ms, code=error.code),
|
|
519
|
+
run, strict=False,
|
|
520
|
+
)
|
|
521
|
+
if not run.stopping:
|
|
522
|
+
await self._intake(run, asyncio.sleep(delay_ms / 1000))
|
|
523
|
+
except asyncio.CancelledError:
|
|
524
|
+
if not run.stopping:
|
|
525
|
+
raise
|
|
526
|
+
finally:
|
|
527
|
+
if not run.ready.done():
|
|
528
|
+
run.ready.set_exception(CalendarError("INVALID_STATE"))
|
|
529
|
+
self._run = None
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import date, datetime
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
from urllib.parse import urlsplit
|
|
8
|
+
|
|
9
|
+
Rsvp = Literal["accepted", "tentative", "declined"]
|
|
10
|
+
RSVP_STATUSES = ("accepted", "tentative", "declined")
|
|
11
|
+
CALENDAR_TYPES = (
|
|
12
|
+
"invitation.received", "event.created", "event.updated", "event.cancelled", "event.rsvp_changed",
|
|
13
|
+
)
|
|
14
|
+
UUID = re.compile(r"[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")
|
|
15
|
+
CREDENTIAL = re.compile(r"[A-Za-z0-9_-]{43}")
|
|
16
|
+
CALENDAR_ID = re.compile(r"(?!\.{1,2}$)[A-Za-z0-9_@.+#-]{1,512}")
|
|
17
|
+
EVENT_ID = re.compile(r"[A-Za-z0-9_-]{1,1024}")
|
|
18
|
+
VERSION = re.compile(r'"[\x21\x23-\x7e]{1,256}"')
|
|
19
|
+
_CURSOR = re.compile(r"[1-9]\d{0,18}\.[A-Za-z0-9_-]{43}", re.ASCII)
|
|
20
|
+
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}", re.ASCII)
|
|
21
|
+
_DATE_TIME = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})", re.ASCII)
|
|
22
|
+
_FIELDS = {
|
|
23
|
+
"status": "status", "title": "title", "start": "start", "end": "end",
|
|
24
|
+
"location": "location", "myResponse": "my_response", "recurringEventId": "recurring_event_id",
|
|
25
|
+
"originalStartTime": "original_start_time",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class CalendarError(Exception):
|
|
30
|
+
def __init__(
|
|
31
|
+
self, code: str, status: int | None = None, request_id: str | None = None,
|
|
32
|
+
retry_after: int | None = None,
|
|
33
|
+
) -> None:
|
|
34
|
+
super().__init__(code)
|
|
35
|
+
self.code = code
|
|
36
|
+
self.status = status
|
|
37
|
+
self.request_id = request_id
|
|
38
|
+
self.retry_after = retry_after
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class EventRef:
|
|
43
|
+
calendar_id: str
|
|
44
|
+
event_id: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class EventTime:
|
|
49
|
+
date: str | None = None
|
|
50
|
+
date_time: str | None = None
|
|
51
|
+
time_zone: str | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class CalendarEvent:
|
|
56
|
+
ref: EventRef
|
|
57
|
+
status: str
|
|
58
|
+
version: str | None = None
|
|
59
|
+
title: str | None = None
|
|
60
|
+
start: EventTime | None = None
|
|
61
|
+
end: EventTime | None = None
|
|
62
|
+
location: str | None = None
|
|
63
|
+
my_response: str | None = None
|
|
64
|
+
recurring_event_id: str | None = None
|
|
65
|
+
original_start_time: EventTime | None = None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class Notification:
|
|
70
|
+
schema_version: int
|
|
71
|
+
notification_id: str
|
|
72
|
+
cursor: str
|
|
73
|
+
connection_id: str
|
|
74
|
+
type: str
|
|
75
|
+
observed_at: str
|
|
76
|
+
changed_fields: tuple[str, ...]
|
|
77
|
+
ref: EventRef | None = None
|
|
78
|
+
event: CalendarEvent | None = None
|
|
79
|
+
reason: str | None = None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def require(condition: object, code: str = "INVALID_RESPONSE") -> None:
|
|
83
|
+
if not condition:
|
|
84
|
+
raise CalendarError(code)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def object_value(value: Any) -> dict[str, Any]:
|
|
88
|
+
require(isinstance(value, dict))
|
|
89
|
+
return value
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def matches(value: object, pattern: re.Pattern[str]) -> bool:
|
|
93
|
+
return isinstance(value, str) and pattern.fullmatch(value) is not None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _valid_date_time(value: str) -> bool:
|
|
97
|
+
if not matches(value, _DATE_TIME):
|
|
98
|
+
return False
|
|
99
|
+
try:
|
|
100
|
+
offset = value[-6:]
|
|
101
|
+
if not value.endswith("Z") and (int(offset[1:3]) > 23 or int(offset[4:6]) > 59):
|
|
102
|
+
return False
|
|
103
|
+
datetime.fromisoformat(value)
|
|
104
|
+
return True
|
|
105
|
+
except ValueError:
|
|
106
|
+
return False
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _decode_time(value: Any) -> EventTime:
|
|
110
|
+
item = object_value(value)
|
|
111
|
+
time_zone = item.get("timeZone")
|
|
112
|
+
require("timeZone" not in item or isinstance(time_zone, str) and 1 <= len(time_zone) <= 128)
|
|
113
|
+
if matches(item.get("date"), _DATE) and "dateTime" not in item:
|
|
114
|
+
try:
|
|
115
|
+
date.fromisoformat(item["date"])
|
|
116
|
+
except ValueError:
|
|
117
|
+
raise CalendarError("INVALID_RESPONSE") from None
|
|
118
|
+
return EventTime(date=item["date"], time_zone=time_zone)
|
|
119
|
+
require("date" not in item and _valid_date_time(item.get("dateTime")))
|
|
120
|
+
return EventTime(date_time=item["dateTime"], time_zone=time_zone)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _decode_ref(value: Any) -> EventRef:
|
|
124
|
+
item = object_value(value)
|
|
125
|
+
require(matches(item.get("calendarId"), CALENDAR_ID) and matches(item.get("eventId"), EVENT_ID))
|
|
126
|
+
return EventRef(item["calendarId"], item["eventId"])
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def decode_event(value: Any) -> CalendarEvent:
|
|
130
|
+
item = object_value(value)
|
|
131
|
+
ref = _decode_ref(item.get("ref"))
|
|
132
|
+
require(item.get("status") in ("confirmed", "tentative", "cancelled"))
|
|
133
|
+
require("version" not in item or matches(item["version"], VERSION))
|
|
134
|
+
for field in ("title", "location"):
|
|
135
|
+
require(field not in item or isinstance(item[field], str) and len(item[field]) <= 8192)
|
|
136
|
+
require("myResponse" not in item or item["myResponse"] in ("needsAction", *RSVP_STATUSES))
|
|
137
|
+
require("recurringEventId" not in item or matches(item["recurringEventId"], EVENT_ID))
|
|
138
|
+
return CalendarEvent(
|
|
139
|
+
ref, item["status"], item.get("version"), item.get("title"),
|
|
140
|
+
_decode_time(item["start"]) if "start" in item else None,
|
|
141
|
+
_decode_time(item["end"]) if "end" in item else None,
|
|
142
|
+
item.get("location"), item.get("myResponse"), item.get("recurringEventId"),
|
|
143
|
+
_decode_time(item["originalStartTime"]) if "originalStartTime" in item else None,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def decode_notification(value: Any, connection_id: str | None = None) -> Notification:
|
|
148
|
+
item = object_value(value)
|
|
149
|
+
schema = item.get("schemaVersion")
|
|
150
|
+
bound = item.get("connectionId")
|
|
151
|
+
require(type(schema) is int and schema == 1 and matches(bound, UUID))
|
|
152
|
+
require(connection_id is None or connection_id == bound)
|
|
153
|
+
cursor = item.get("cursor")
|
|
154
|
+
require(matches(cursor, _CURSOR) and item.get("notificationId") == bound + ":" + cursor.split(".")[0])
|
|
155
|
+
require(_valid_date_time(item.get("observedAt")))
|
|
156
|
+
fields = item.get("changedFields")
|
|
157
|
+
require(isinstance(fields, list) and all(isinstance(field, str) and field in _FIELDS for field in fields)
|
|
158
|
+
and len(set(fields)) == len(fields))
|
|
159
|
+
kind = item.get("type")
|
|
160
|
+
reason = item.get("reason")
|
|
161
|
+
ref = event = None
|
|
162
|
+
if kind == "connection.gap":
|
|
163
|
+
require(reason == "provider_cursor_expired" and "ref" not in item and "event" not in item and not fields)
|
|
164
|
+
else:
|
|
165
|
+
require(kind in CALENDAR_TYPES and fields)
|
|
166
|
+
ref = _decode_ref(item.get("ref"))
|
|
167
|
+
event = decode_event(item.get("event"))
|
|
168
|
+
require(event.ref == ref)
|
|
169
|
+
if kind == "event.cancelled":
|
|
170
|
+
require(reason == "provider_cancelled_or_removed" and event.status == "cancelled")
|
|
171
|
+
else:
|
|
172
|
+
require("reason" not in item and event.status != "cancelled")
|
|
173
|
+
return Notification(
|
|
174
|
+
1, item["notificationId"], cursor, bound, kind, item["observedAt"],
|
|
175
|
+
tuple(_FIELDS[field] for field in fields), ref, event, reason,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def validated_url(value: str, origin_only: bool = False) -> str:
|
|
180
|
+
try:
|
|
181
|
+
require(isinstance(value, str) and len(value) <= 8192 and not re.search(r"[\s\\\x00-\x1f\x7f]", value))
|
|
182
|
+
result = urlsplit(value)
|
|
183
|
+
require(result.hostname and result.username is None and result.password is None and "#" not in value)
|
|
184
|
+
require(result.scheme == "https" or result.scheme == "http" and result.hostname in {"127.0.0.1", "localhost", "::1"})
|
|
185
|
+
require(result.port is None or 1 <= result.port <= 65535)
|
|
186
|
+
if origin_only:
|
|
187
|
+
require(result.path in ("", "/") and "?" not in value)
|
|
188
|
+
return result.scheme + "://" + result.netloc
|
|
189
|
+
return result.geturl()
|
|
190
|
+
except (ValueError, CalendarError):
|
|
191
|
+
raise CalendarError("INVALID_ARGUMENT" if origin_only else "INVALID_RESPONSE") from None
|
|
File without changes
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gabriel-calendar
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async SDK for the Gabriel Calendar service
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/Easy-Ez/gabriel-calendar
|
|
7
|
+
Project-URL: Documentation, https://github.com/Easy-Ez/gabriel-calendar/blob/main/spec/api.md
|
|
8
|
+
Project-URL: Issues, https://github.com/Easy-Ez/gabriel-calendar/issues
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: httpx<0.29,>=0.28.1
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# Gabriel Calendar SDK for Python
|
|
16
|
+
|
|
17
|
+
An async client for the Gabriel Calendar service. It connects a Google Calendar account, streams changes to the linked primary calendar over SSE, and supports pending invitations, RSVP, and single-event writes.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
python -m pip install gabriel-calendar
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Requires Python 3.11 or later, a Gabriel Calendar service URL, and a project session supplied by the service operator. Load the session from your application's secret store and pass it through `get_project_credential`.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import asyncio
|
|
29
|
+
import os
|
|
30
|
+
|
|
31
|
+
from gabriel_calendar import CalendarClient
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def main():
|
|
35
|
+
client = await CalendarClient.connect(
|
|
36
|
+
base_url="https://calendar.example.invalid",
|
|
37
|
+
get_project_credential=lambda: os.environ["GABRIEL_PROJECT_SESSION"],
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
@client.on("invitation.received")
|
|
41
|
+
def handle_invitation(notice):
|
|
42
|
+
print(notice.type)
|
|
43
|
+
|
|
44
|
+
async with client:
|
|
45
|
+
page = await client.events.list_invitations()
|
|
46
|
+
print("Pending invitations", len(page.events))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
asyncio.run(main())
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`connect()` opens the Google consent page and pairs a consumer. Use `save_grant` to store its connection ID, consumer ID, and credential in a secret store. Construct a new `CalendarClient` with those IDs and a `get_credential` callback to resume delivery in another process. Notifications are acknowledged after the registered handlers succeed. Use `notification_id` to make handler side effects idempotent across restarts.
|
|
53
|
+
|
|
54
|
+
Request `can_rsvp`, `can_create`, or `can_manage` when pairing a writer. For a guest event, also request `can_invite` and set `notify_guests` explicitly on each write. Creation takes an idempotency key, and updates and cancellations take the current event version.
|
|
55
|
+
|
|
56
|
+
[SDK and HTTP contract](https://github.com/Easy-Ez/gabriel-calendar/blob/main/spec/api.md) · [Service setup](https://github.com/Easy-Ez/gabriel-calendar/blob/main/docs/zh-CN/testing.md)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/gabriel_calendar/__init__.py
|
|
5
|
+
src/gabriel_calendar/_wire.py
|
|
6
|
+
src/gabriel_calendar/py.typed
|
|
7
|
+
src/gabriel_calendar.egg-info/PKG-INFO
|
|
8
|
+
src/gabriel_calendar.egg-info/SOURCES.txt
|
|
9
|
+
src/gabriel_calendar.egg-info/dependency_links.txt
|
|
10
|
+
src/gabriel_calendar.egg-info/requires.txt
|
|
11
|
+
src/gabriel_calendar.egg-info/top_level.txt
|
|
12
|
+
tests/test_conformance.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
httpx<0.29,>=0.28.1
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gabriel_calendar
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import secrets as random_source
|
|
6
|
+
import threading
|
|
7
|
+
import unittest
|
|
8
|
+
from collections import deque
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from gabriel_calendar import CalendarClient, CalendarError, Notification, decode_notification
|
|
14
|
+
|
|
15
|
+
FIXTURE = json.loads((Path(__file__).resolve().parents[3] / "spec/fixtures/mvp.json").read_text())
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@contextmanager
|
|
19
|
+
def harness(test, steps):
|
|
20
|
+
project = random_source.token_urlsafe(32)
|
|
21
|
+
grant = random_source.token_urlsafe(32)
|
|
22
|
+
remaining = deque(steps)
|
|
23
|
+
failures = []
|
|
24
|
+
|
|
25
|
+
class Handler(BaseHTTPRequestHandler):
|
|
26
|
+
protocol_version = "HTTP/1.1"
|
|
27
|
+
|
|
28
|
+
def log_message(self, *_):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
def run_step(self):
|
|
32
|
+
try:
|
|
33
|
+
step = remaining.popleft()
|
|
34
|
+
test.assertEqual(self.path, step["path"])
|
|
35
|
+
test.assertEqual(self.command, step["method"])
|
|
36
|
+
expected = project if step.get("project") else grant
|
|
37
|
+
test.assertTrue(self.headers.get("Authorization") == "Bearer " + expected)
|
|
38
|
+
test.assertEqual(self.headers.get("If-Match"), step.get("ifMatch"))
|
|
39
|
+
test.assertEqual(self.headers.get("Idempotency-Key"), step.get("idempotencyKey"))
|
|
40
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
41
|
+
body = json.loads(self.rfile.read(length)) if length else None
|
|
42
|
+
test.assertEqual(body, step.get("body"))
|
|
43
|
+
if step["status"] == 0:
|
|
44
|
+
self.close_connection = True
|
|
45
|
+
return
|
|
46
|
+
if "stream" in step:
|
|
47
|
+
test.assertEqual(self.headers.get("Accept"), "text/event-stream")
|
|
48
|
+
def frame(kind, payload):
|
|
49
|
+
return f"event: {kind}\r\ndata: {json.dumps(payload)}\r\n\r\n".encode()
|
|
50
|
+
data = b": synthetic heartbeat\r\n\r\n" + frame("ready", {})
|
|
51
|
+
data += b"".join(frame("notification", FIXTURE["notifications"][key]) for key in step["stream"])
|
|
52
|
+
if "streamError" in step:
|
|
53
|
+
data += frame("error", step["streamError"])
|
|
54
|
+
self.send_response(step["status"])
|
|
55
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
56
|
+
self.send_header("Transfer-Encoding", "chunked")
|
|
57
|
+
self.end_headers()
|
|
58
|
+
try:
|
|
59
|
+
for offset in range(0, len(data), 53):
|
|
60
|
+
chunk = data[offset:offset + 53]
|
|
61
|
+
self.wfile.write(f"{len(chunk):x}\r\n".encode() + chunk + b"\r\n")
|
|
62
|
+
self.wfile.write(b"0\r\n\r\n")
|
|
63
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
64
|
+
pass
|
|
65
|
+
self.close_connection = True
|
|
66
|
+
return
|
|
67
|
+
payload = step.get("payload")
|
|
68
|
+
if step.get("grant"):
|
|
69
|
+
payload = {**payload, "credential": grant}
|
|
70
|
+
data = json.dumps(payload).encode() if payload is not None else b""
|
|
71
|
+
self.send_response(step["status"])
|
|
72
|
+
self.send_header("X-Request-Id", FIXTURE["requestId"])
|
|
73
|
+
self.send_header("Content-Length", str(len(data)))
|
|
74
|
+
self.send_header("Content-Type", "application/json")
|
|
75
|
+
if step.get("retryAfter"):
|
|
76
|
+
self.send_header("Retry-After", str(step["retryAfter"]))
|
|
77
|
+
self.end_headers()
|
|
78
|
+
self.wfile.write(data)
|
|
79
|
+
except Exception as error:
|
|
80
|
+
failures.append(error)
|
|
81
|
+
self.close_connection = True
|
|
82
|
+
|
|
83
|
+
do_GET = do_POST = do_PUT = do_PATCH = run_step
|
|
84
|
+
|
|
85
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
86
|
+
thread = threading.Thread(target=lambda: server.serve_forever(poll_interval=0.02), daemon=True)
|
|
87
|
+
thread.start()
|
|
88
|
+
try:
|
|
89
|
+
yield f"http://127.0.0.1:{server.server_port}", project, grant
|
|
90
|
+
finally:
|
|
91
|
+
server.shutdown()
|
|
92
|
+
thread.join()
|
|
93
|
+
server.server_close()
|
|
94
|
+
if failures:
|
|
95
|
+
raise failures[0]
|
|
96
|
+
test.assertFalse(remaining)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Conformance(unittest.IsolatedAsyncioTestCase):
|
|
100
|
+
def test_decode(self):
|
|
101
|
+
for raw in FIXTURE["notifications"].values():
|
|
102
|
+
event = decode_notification(raw, FIXTURE["connectionId"])
|
|
103
|
+
self.assertEqual(event.notification_id, raw["notificationId"])
|
|
104
|
+
self.assertEqual(event.type, raw["type"])
|
|
105
|
+
invitation = decode_notification(FIXTURE["notifications"]["invitation"])
|
|
106
|
+
self.assertEqual(invitation.event.start.date_time, "2030-01-01T12:00:00+08:00")
|
|
107
|
+
self.assertEqual(invitation.event.original_start_time.date, "2030-01-01")
|
|
108
|
+
self.assertEqual(invitation.changed_fields, ("status", "my_response"))
|
|
109
|
+
for raw in FIXTURE["invalidNotifications"]:
|
|
110
|
+
with self.assertRaisesRegex(CalendarError, "INVALID_RESPONSE"):
|
|
111
|
+
decode_notification(raw)
|
|
112
|
+
|
|
113
|
+
async def test_lifecycle(self):
|
|
114
|
+
with harness(self, FIXTURE["steps"]) as (base, project, grant):
|
|
115
|
+
client = await CalendarClient.connect(
|
|
116
|
+
base_url=base, get_project_credential=lambda: project, can_rsvp=True, can_create=True, can_manage=True, can_invite=True,
|
|
117
|
+
open_browser=lambda url: self.assertEqual(url, "https://consent.example.invalid/authorize"),
|
|
118
|
+
save_grant=lambda saved: self.assertTrue(saved.credential == grant),
|
|
119
|
+
)
|
|
120
|
+
self.assertEqual(client.consumer_id, FIXTURE["consumerId"])
|
|
121
|
+
raw = FIXTURE["createInput"]
|
|
122
|
+
options = dict(start=raw["start"], end=raw["end"], show_as=raw["showAs"], idempotency_key=FIXTURE["createKey"])
|
|
123
|
+
with self.assertRaisesRegex(CalendarError, "INVALID_ARGUMENT"):
|
|
124
|
+
await client.events.create("primary", title=raw["title"], guests=raw["guests"], **options)
|
|
125
|
+
options.update(guests=raw["guests"], notify_guests=raw["notifyGuests"])
|
|
126
|
+
created = await client.events.create("primary", title=raw["title"], **options)
|
|
127
|
+
self.assertEqual(created.title, raw["title"])
|
|
128
|
+
self.assertEqual(created.ref.event_id, "syntheticcreated")
|
|
129
|
+
with self.assertRaisesRegex(CalendarError, "IDEMPOTENCY_CONFLICT"):
|
|
130
|
+
await client.events.create("primary", title="Changed appointment", **options)
|
|
131
|
+
patch = FIXTURE["updateInput"]
|
|
132
|
+
with self.assertRaisesRegex(CalendarError, "INVALID_ARGUMENT"):
|
|
133
|
+
await client.events.update(created.ref, start=patch["start"], if_match=created.version)
|
|
134
|
+
updated = await client.events.update(created.ref, **patch, if_match=created.version, notify_guests=False)
|
|
135
|
+
self.assertEqual(updated.start.date_time, patch["start"])
|
|
136
|
+
with self.assertRaisesRegex(CalendarError, "VERSION_CONFLICT"):
|
|
137
|
+
await client.events.cancel(created.ref, if_match=created.version, notify_guests=True)
|
|
138
|
+
self.assertEqual((await client.events.cancel(updated.ref, if_match=updated.version, notify_guests=True)).status, "cancelled")
|
|
139
|
+
[event] = (await client.events.list_invitations()).events
|
|
140
|
+
self.assertEqual(event.my_response, "needsAction")
|
|
141
|
+
reply = await client.events.rsvp(event.ref, "tentative", if_match=event.version)
|
|
142
|
+
self.assertEqual(reply.my_response, "tentative")
|
|
143
|
+
with self.assertRaisesRegex(CalendarError, "VERSION_CONFLICT") as failure:
|
|
144
|
+
await client.events.rsvp(event.ref, "tentative", if_match='"stale"')
|
|
145
|
+
self.assertEqual(failure.exception.request_id, FIXTURE["requestId"])
|
|
146
|
+
retries = []
|
|
147
|
+
processed = []
|
|
148
|
+
gaps = []
|
|
149
|
+
terminal = asyncio.Event()
|
|
150
|
+
first = True
|
|
151
|
+
|
|
152
|
+
@client.on("connection.reconnecting")
|
|
153
|
+
def retry(event):
|
|
154
|
+
retries.append((event.code, event.delay_ms))
|
|
155
|
+
|
|
156
|
+
@client.on("invitation.received")
|
|
157
|
+
async def invite(event):
|
|
158
|
+
nonlocal first
|
|
159
|
+
if first:
|
|
160
|
+
first = False
|
|
161
|
+
raise RuntimeError("Synthetic handler failure")
|
|
162
|
+
processed.append(event.notification_id)
|
|
163
|
+
|
|
164
|
+
client.on("event.rsvp_changed", lambda event: processed.append(event.notification_id))
|
|
165
|
+
|
|
166
|
+
@client.on("connection.gap")
|
|
167
|
+
def gap(event):
|
|
168
|
+
if isinstance(event, Notification):
|
|
169
|
+
processed.append(event.notification_id)
|
|
170
|
+
else:
|
|
171
|
+
gaps.append(event.error.code)
|
|
172
|
+
terminal.set()
|
|
173
|
+
|
|
174
|
+
async with asyncio.timeout(8), client:
|
|
175
|
+
await terminal.wait()
|
|
176
|
+
self.assertEqual(gaps, ["CURSOR_EXPIRED"])
|
|
177
|
+
self.assertEqual(retries, [tuple(pair) for pair in FIXTURE["expectedRetries"]])
|
|
178
|
+
self.assertEqual(processed, [
|
|
179
|
+
event["notificationId"] for event in FIXTURE["notifications"].values() if event["type"] != "event.cancelled"
|
|
180
|
+
])
|
|
181
|
+
|
|
182
|
+
async def test_initial_auth_error(self):
|
|
183
|
+
connection, consumer = FIXTURE["connectionId"], FIXTURE["consumerId"]
|
|
184
|
+
path = f"/v1/connections/{connection}/consumers/{consumer}/stream"
|
|
185
|
+
steps = [{"method": "GET", "path": path, "status": 401, "payload": FIXTURE["authError"]}]
|
|
186
|
+
with harness(self, steps) as (base, _, grant):
|
|
187
|
+
client = CalendarClient(base_url=base, connection_id=connection, consumer_id=consumer, get_credential=lambda: grant)
|
|
188
|
+
auth = []
|
|
189
|
+
client.on("auth.required", lambda event: auth.append(event.error.code))
|
|
190
|
+
with self.assertRaisesRegex(CalendarError, "AUTH_REQUIRED"):
|
|
191
|
+
await client.start()
|
|
192
|
+
self.assertEqual(auth, ["AUTH_REQUIRED"])
|
|
193
|
+
|
|
194
|
+
async def test_stop_drains_current_handler(self):
|
|
195
|
+
with harness(self, FIXTURE["drainSteps"]) as (base, _, grant):
|
|
196
|
+
client = CalendarClient(base_url=base, connection_id=FIXTURE["connectionId"],
|
|
197
|
+
consumer_id=FIXTURE["consumerId"], get_credential=lambda: grant)
|
|
198
|
+
entered = asyncio.Event()
|
|
199
|
+
blocked = asyncio.Event()
|
|
200
|
+
processed = []
|
|
201
|
+
|
|
202
|
+
@client.on("invitation.received")
|
|
203
|
+
async def first(event):
|
|
204
|
+
entered.set()
|
|
205
|
+
await blocked.wait()
|
|
206
|
+
processed.append(event.type)
|
|
207
|
+
|
|
208
|
+
client.on("event.rsvp_changed", lambda event: processed.append(event.type))
|
|
209
|
+
async with asyncio.timeout(3):
|
|
210
|
+
await client.start()
|
|
211
|
+
await entered.wait()
|
|
212
|
+
drained = asyncio.create_task(client.stop())
|
|
213
|
+
await asyncio.sleep(0)
|
|
214
|
+
blocked.set()
|
|
215
|
+
await drained
|
|
216
|
+
self.assertEqual(processed, ["invitation.received"])
|