opush-sdk 0.1.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.
- opush/__init__.py +55 -0
- opush/_async.py +339 -0
- opush/_core.py +553 -0
- opush/_sync.py +336 -0
- opush/_target.py +103 -0
- opush/_version.py +1 -0
- opush/crypto.py +200 -0
- opush/errors.py +50 -0
- opush/models.py +290 -0
- opush/py.typed +0 -0
- opush/signature.py +37 -0
- opush_sdk-0.1.0.dist-info/METADATA +370 -0
- opush_sdk-0.1.0.dist-info/RECORD +15 -0
- opush_sdk-0.1.0.dist-info/WHEEL +4 -0
- opush_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
opush/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Python SDK for Opush push notifications (https://opu.sh).
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
from opush import Opush
|
|
6
|
+
|
|
7
|
+
with Opush("YOUR_KEY") as client:
|
|
8
|
+
client.push("42 GB in 12 minutes", title="Backup done")
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ._async import AsyncHeartbeat, AsyncOpush, AsyncQuestion
|
|
12
|
+
from ._core import Attachment, Level, PushOptions
|
|
13
|
+
from ._sync import Heartbeat, Opush, Question
|
|
14
|
+
from ._version import __version__
|
|
15
|
+
from .crypto import AesEncryption, HpkeEncryption
|
|
16
|
+
from .errors import MissingDependencyError, OpushError
|
|
17
|
+
from .models import (
|
|
18
|
+
Alert,
|
|
19
|
+
AlertStep,
|
|
20
|
+
Answer,
|
|
21
|
+
Button,
|
|
22
|
+
DeviceResult,
|
|
23
|
+
Escalation,
|
|
24
|
+
PushResult,
|
|
25
|
+
QuestionState,
|
|
26
|
+
Schedule,
|
|
27
|
+
)
|
|
28
|
+
from .signature import verify_signature
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"AesEncryption",
|
|
32
|
+
"Alert",
|
|
33
|
+
"AlertStep",
|
|
34
|
+
"Answer",
|
|
35
|
+
"AsyncHeartbeat",
|
|
36
|
+
"AsyncOpush",
|
|
37
|
+
"AsyncQuestion",
|
|
38
|
+
"Attachment",
|
|
39
|
+
"Button",
|
|
40
|
+
"DeviceResult",
|
|
41
|
+
"Escalation",
|
|
42
|
+
"Heartbeat",
|
|
43
|
+
"HpkeEncryption",
|
|
44
|
+
"Level",
|
|
45
|
+
"MissingDependencyError",
|
|
46
|
+
"Opush",
|
|
47
|
+
"OpushError",
|
|
48
|
+
"PushOptions",
|
|
49
|
+
"PushResult",
|
|
50
|
+
"Question",
|
|
51
|
+
"QuestionState",
|
|
52
|
+
"Schedule",
|
|
53
|
+
"__version__",
|
|
54
|
+
"verify_signature",
|
|
55
|
+
]
|
opush/_async.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
"""The asynchronous client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import datetime, timedelta, timezone
|
|
11
|
+
from types import TracebackType
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from ._core import ClientCore, ProgressState, PushOptions, RequestSpec, parse_response, should_retry
|
|
17
|
+
from ._target import last_segment, parse_heartbeat
|
|
18
|
+
from .crypto import Encryption
|
|
19
|
+
from .errors import OpushError
|
|
20
|
+
from .models import Alert, PushResult, QuestionState
|
|
21
|
+
|
|
22
|
+
if sys.version_info >= (3, 11):
|
|
23
|
+
from typing import Self, Unpack
|
|
24
|
+
else: # pragma: no cover
|
|
25
|
+
from typing_extensions import Self, Unpack
|
|
26
|
+
|
|
27
|
+
__all__ = ["AsyncOpush", "AsyncQuestion", "AsyncHeartbeat"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
async def _send_with(client: httpx.AsyncClient, spec: RequestSpec, timeout: float) -> httpx.Response:
|
|
31
|
+
return await client.request(
|
|
32
|
+
spec.method,
|
|
33
|
+
spec.url,
|
|
34
|
+
json=spec.json,
|
|
35
|
+
data=spec.data,
|
|
36
|
+
files=spec.files,
|
|
37
|
+
content=spec.content,
|
|
38
|
+
params=spec.params,
|
|
39
|
+
headers=spec.headers,
|
|
40
|
+
timeout=spec.timeout or timeout,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AsyncOpush(ClientCore):
|
|
45
|
+
"""Asynchronous Opush client. Takes the same arguments as :class:`opush.Opush`.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
key: A device push key, or a full push URL such as
|
|
49
|
+
``https://opu.sh/KEY`` or ``https://opu.sh/c/KEY`` (channel).
|
|
50
|
+
Defaults to the ``OPUSH_KEY`` environment variable.
|
|
51
|
+
keys: Several device keys. The same push goes to all of them.
|
|
52
|
+
channel: A team channel push key or URL. Defaults to ``OPUSH_CHANNEL``.
|
|
53
|
+
server: The server URL, including any path prefix of an enterprise
|
|
54
|
+
server. Defaults to the server in the push URL, then
|
|
55
|
+
``OPUSH_SERVER``, then ``https://opu.sh``.
|
|
56
|
+
basic_auth: ``(user, password)`` or ``"user:password"`` for enterprise
|
|
57
|
+
servers that use Basic Auth.
|
|
58
|
+
timeout: Request timeout in seconds.
|
|
59
|
+
retries: How many times to retry after ``429``, ``503`` or a network
|
|
60
|
+
error, waiting for ``Retry-After``. Off by default because a
|
|
61
|
+
retried push may be delivered twice.
|
|
62
|
+
encrypt: Default encryption for every push (see :mod:`opush.crypto`).
|
|
63
|
+
http_client: An existing ``httpx.AsyncClient`` to use. It isn't closed
|
|
64
|
+
by :meth:`aclose`.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
key: str | None = None,
|
|
70
|
+
*,
|
|
71
|
+
keys: Sequence[str] | None = None,
|
|
72
|
+
channel: str | None = None,
|
|
73
|
+
server: str | None = None,
|
|
74
|
+
basic_auth: tuple[str, str] | str | None = None,
|
|
75
|
+
timeout: float = 30.0,
|
|
76
|
+
retries: int = 0,
|
|
77
|
+
encrypt: Encryption | Mapping[str, Any] | None = None,
|
|
78
|
+
http_client: httpx.AsyncClient | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
super().__init__(
|
|
81
|
+
key,
|
|
82
|
+
keys=keys,
|
|
83
|
+
channel=channel,
|
|
84
|
+
server=server,
|
|
85
|
+
basic_auth=basic_auth,
|
|
86
|
+
timeout=timeout,
|
|
87
|
+
retries=retries,
|
|
88
|
+
encrypt=encrypt,
|
|
89
|
+
)
|
|
90
|
+
self._owns_client = http_client is None
|
|
91
|
+
self._client = http_client or httpx.AsyncClient()
|
|
92
|
+
self.progress = AsyncProgress(self)
|
|
93
|
+
self.alerts = AsyncAlerts(self)
|
|
94
|
+
|
|
95
|
+
# -- lifecycle ---------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
async def aclose(self) -> None:
|
|
98
|
+
"""Close the HTTP client if this object created it."""
|
|
99
|
+
if self._owns_client:
|
|
100
|
+
await self._client.aclose()
|
|
101
|
+
|
|
102
|
+
async def __aenter__(self) -> Self:
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
async def __aexit__(
|
|
106
|
+
self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
|
|
107
|
+
) -> None:
|
|
108
|
+
await self.aclose()
|
|
109
|
+
|
|
110
|
+
# -- transport ---------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
async def _request(self, spec: RequestSpec) -> Any:
|
|
113
|
+
attempt = 0
|
|
114
|
+
while True:
|
|
115
|
+
try:
|
|
116
|
+
try:
|
|
117
|
+
response = await _send_with(self._client, spec, self.timeout)
|
|
118
|
+
except httpx.HTTPError as exc:
|
|
119
|
+
raise OpushError(f"Request failed: {exc}") from exc
|
|
120
|
+
return parse_response(spec, response.status_code, response.headers, response.text)
|
|
121
|
+
except OpushError as error:
|
|
122
|
+
wait = should_retry(error, attempt, self.retries)
|
|
123
|
+
if wait is None:
|
|
124
|
+
raise
|
|
125
|
+
attempt += 1
|
|
126
|
+
await asyncio.sleep(wait)
|
|
127
|
+
|
|
128
|
+
# -- pushes ------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
async def push(self, body: str | None = None, /, **options: Unpack[PushOptions]) -> PushResult:
|
|
131
|
+
"""Send a push.
|
|
132
|
+
|
|
133
|
+
``body`` can be passed as the first argument. Other options mirror the
|
|
134
|
+
push parameters (https://opu.sh/docs/push/parameters): ``title``,
|
|
135
|
+
``subtitle``, ``markdown``, ``level``, ``sound``, ``url``, ``group``,
|
|
136
|
+
``buttons``, ``attachments``, ``at``/``delay``/``repeat``,
|
|
137
|
+
``escalate``, ``encrypt`` and more.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
OpushError: The server rejected the push.
|
|
141
|
+
"""
|
|
142
|
+
return PushResult.from_dict(await self._request(self.build_push(body, options)))
|
|
143
|
+
|
|
144
|
+
async def recall(self, push_id: str) -> PushResult:
|
|
145
|
+
"""Remove a push sent with ``id=push_id`` from the devices. Also cancels
|
|
146
|
+
a pending schedule and an escalating alert with that id."""
|
|
147
|
+
return PushResult.from_dict(await self._request(self.build_recall(push_id)))
|
|
148
|
+
|
|
149
|
+
# -- questions ---------------------------------------------------------
|
|
150
|
+
|
|
151
|
+
async def ask(
|
|
152
|
+
self,
|
|
153
|
+
title: str,
|
|
154
|
+
*,
|
|
155
|
+
body: str | None = None,
|
|
156
|
+
options: Sequence[str] | None = None,
|
|
157
|
+
allow_text: bool = False,
|
|
158
|
+
placeholder: str | None = None,
|
|
159
|
+
timeout: int | timedelta | None = None,
|
|
160
|
+
callback_url: str | None = None,
|
|
161
|
+
group: str | None = None,
|
|
162
|
+
device_key: str | None = None,
|
|
163
|
+
) -> AsyncQuestion:
|
|
164
|
+
"""Push a question to a device. Await :meth:`AsyncQuestion.wait` for the answer.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
title: The question, up to 200 characters.
|
|
168
|
+
body: More context, up to 2,000 characters.
|
|
169
|
+
options: Up to 4 choices.
|
|
170
|
+
allow_text: Allow a typed answer.
|
|
171
|
+
placeholder: Hint in the text field.
|
|
172
|
+
timeout: Seconds (or a timedelta) until the question expires,
|
|
173
|
+
60 to 604800. Server default is one hour.
|
|
174
|
+
callback_url: Opush POSTs the answered question here once. Check
|
|
175
|
+
it with :func:`opush.verify_signature`.
|
|
176
|
+
group: Inbox group.
|
|
177
|
+
device_key: Which device to ask, when the client has several keys.
|
|
178
|
+
"""
|
|
179
|
+
spec = self.build_ask(
|
|
180
|
+
title,
|
|
181
|
+
body=body,
|
|
182
|
+
options=options,
|
|
183
|
+
allow_text=allow_text,
|
|
184
|
+
placeholder=placeholder,
|
|
185
|
+
timeout=timeout,
|
|
186
|
+
callback_url=callback_url,
|
|
187
|
+
group=group,
|
|
188
|
+
device_key=device_key,
|
|
189
|
+
)
|
|
190
|
+
return AsyncQuestion._from_response(self, await self._request(spec))
|
|
191
|
+
|
|
192
|
+
async def get_question(self, question_id: str, *, wait: int = 0) -> QuestionState:
|
|
193
|
+
"""Read a question. ``wait`` (0 to 50 seconds) holds the request open
|
|
194
|
+
until the question is no longer pending."""
|
|
195
|
+
qid = last_segment(question_id, "ask")
|
|
196
|
+
return QuestionState.from_dict(await self._request(self.build_get_question(qid, wait)))
|
|
197
|
+
|
|
198
|
+
async def cancel_question(self, question_id: str) -> QuestionState:
|
|
199
|
+
"""Cancel a pending question and remove its notification."""
|
|
200
|
+
qid = last_segment(question_id, "ask")
|
|
201
|
+
return QuestionState.from_dict(await self._request(self.build_cancel_question(qid)))
|
|
202
|
+
|
|
203
|
+
# -- heartbeats --------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
def heartbeat(self, check: str) -> AsyncHeartbeat:
|
|
206
|
+
"""Return a heartbeat for a check ID or a heartbeat URL
|
|
207
|
+
(``https://opu.sh/hb/CHECK_ID``)."""
|
|
208
|
+
check_id, server = parse_heartbeat(check)
|
|
209
|
+
return AsyncHeartbeat(self, check_id, server)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class AsyncProgress:
|
|
213
|
+
"""Live progress cards: ``client.progress.start/update/end``."""
|
|
214
|
+
|
|
215
|
+
def __init__(self, client: AsyncOpush) -> None:
|
|
216
|
+
self._client = client
|
|
217
|
+
|
|
218
|
+
async def start(
|
|
219
|
+
self, id: str, title: str, *, status: str | None = None, progress: float | None = None
|
|
220
|
+
) -> PushResult:
|
|
221
|
+
"""Start a card. Starting always alerts."""
|
|
222
|
+
spec = self._client.build_progress("start", id, {"title": title, "status": status, "progress": progress})
|
|
223
|
+
return PushResult.from_dict(await self._client._request(spec))
|
|
224
|
+
|
|
225
|
+
async def update(
|
|
226
|
+
self,
|
|
227
|
+
id: str,
|
|
228
|
+
*,
|
|
229
|
+
title: str | None = None,
|
|
230
|
+
status: str | None = None,
|
|
231
|
+
progress: float | None = None,
|
|
232
|
+
state: ProgressState | None = None,
|
|
233
|
+
alert: bool = False,
|
|
234
|
+
) -> PushResult:
|
|
235
|
+
"""Update a card. Fields left out keep their last value."""
|
|
236
|
+
fields = {"title": title, "status": status, "progress": progress, "state": state, "alert": alert}
|
|
237
|
+
return PushResult.from_dict(await self._client._request(self._client.build_progress("update", id, fields)))
|
|
238
|
+
|
|
239
|
+
async def end(
|
|
240
|
+
self,
|
|
241
|
+
id: str,
|
|
242
|
+
*,
|
|
243
|
+
status: str | None = None,
|
|
244
|
+
state: ProgressState | None = None,
|
|
245
|
+
progress: float | None = None,
|
|
246
|
+
alert: bool = False,
|
|
247
|
+
) -> PushResult:
|
|
248
|
+
"""End a card. Without ``state`` it ends as ``success``."""
|
|
249
|
+
fields = {"status": status, "state": state, "progress": progress, "alert": alert}
|
|
250
|
+
return PushResult.from_dict(await self._client._request(self._client.build_progress("end", id, fields)))
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class AsyncAlerts:
|
|
254
|
+
"""Escalating alerts: ``client.alerts.get/cancel``."""
|
|
255
|
+
|
|
256
|
+
def __init__(self, client: AsyncOpush) -> None:
|
|
257
|
+
self._client = client
|
|
258
|
+
|
|
259
|
+
async def get(self, alert_id: str) -> Alert:
|
|
260
|
+
"""Return the alert. Accepts the alert ID or its ``status_url``."""
|
|
261
|
+
spec = self._client.build_alert("GET", last_segment(alert_id, "alerts"))
|
|
262
|
+
return Alert.from_dict(await self._client._request(spec))
|
|
263
|
+
|
|
264
|
+
async def cancel(self, alert_id: str) -> Alert:
|
|
265
|
+
"""Stop escalating. Accepts the alert ID or its ``status_url``."""
|
|
266
|
+
spec = self._client.build_alert("DELETE", last_segment(alert_id, "alerts"))
|
|
267
|
+
return Alert.from_dict(await self._client._request(spec))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@dataclass
|
|
271
|
+
class AsyncHeartbeat:
|
|
272
|
+
"""Check-ins for a heartbeat monitor."""
|
|
273
|
+
|
|
274
|
+
_client: AsyncOpush = field(repr=False)
|
|
275
|
+
check_id: str
|
|
276
|
+
server: str | None = None
|
|
277
|
+
|
|
278
|
+
async def ok(self, message: str | None = None) -> None:
|
|
279
|
+
"""Report success."""
|
|
280
|
+
await self._client._request(self._client.build_heartbeat(self.check_id, self.server, None, message))
|
|
281
|
+
|
|
282
|
+
async def fail(self, message: str | None = None) -> None:
|
|
283
|
+
"""Report a failure. The first 1,000 characters of ``message`` show in the push."""
|
|
284
|
+
await self._client._request(self._client.build_heartbeat(self.check_id, self.server, "fail", message))
|
|
285
|
+
|
|
286
|
+
async def start(self) -> None:
|
|
287
|
+
"""Mark the start of a run, so the next success records its duration."""
|
|
288
|
+
await self._client._request(self._client.build_heartbeat(self.check_id, self.server, "start", None))
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
@dataclass
|
|
292
|
+
class AsyncQuestion:
|
|
293
|
+
"""A question that was pushed to a device."""
|
|
294
|
+
|
|
295
|
+
_client: AsyncOpush = field(repr=False)
|
|
296
|
+
id: str
|
|
297
|
+
answer_url: str | None
|
|
298
|
+
expires_at: datetime | None
|
|
299
|
+
callback_secret: str | None = field(default=None, repr=False)
|
|
300
|
+
|
|
301
|
+
@classmethod
|
|
302
|
+
def _from_response(cls, client: AsyncOpush, data: Mapping[str, Any]) -> AsyncQuestion:
|
|
303
|
+
from .models import parse_time
|
|
304
|
+
|
|
305
|
+
secret = data.get("callback_secret")
|
|
306
|
+
return cls(
|
|
307
|
+
client,
|
|
308
|
+
id=str(data.get("question_id", "")),
|
|
309
|
+
answer_url=data.get("answer_url") if isinstance(data.get("answer_url"), str) else None,
|
|
310
|
+
expires_at=parse_time(data.get("expires_at")),
|
|
311
|
+
callback_secret=secret if isinstance(secret, str) else None,
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
async def get(self) -> QuestionState:
|
|
315
|
+
"""Read the question right away."""
|
|
316
|
+
return await self._client.get_question(self.id)
|
|
317
|
+
|
|
318
|
+
async def wait(self, timeout: float | timedelta | None = None) -> QuestionState:
|
|
319
|
+
"""Wait until the question is answered, expires, or is cancelled.
|
|
320
|
+
|
|
321
|
+
Args:
|
|
322
|
+
timeout: Give up after this many seconds and return the pending
|
|
323
|
+
state. ``None`` waits until the question expires.
|
|
324
|
+
"""
|
|
325
|
+
seconds = timeout.total_seconds() if isinstance(timeout, timedelta) else timeout
|
|
326
|
+
deadline = None if seconds is None else time.monotonic() + seconds
|
|
327
|
+
while True:
|
|
328
|
+
remaining = 50.0 if deadline is None else deadline - time.monotonic()
|
|
329
|
+
state = await self._client.get_question(self.id, wait=int(max(0, min(50, remaining))))
|
|
330
|
+
if not state.pending:
|
|
331
|
+
return state
|
|
332
|
+
if deadline is not None and time.monotonic() >= deadline - 0.5:
|
|
333
|
+
return state
|
|
334
|
+
if self.expires_at is not None and datetime.now(timezone.utc) >= self.expires_at:
|
|
335
|
+
return state
|
|
336
|
+
|
|
337
|
+
async def cancel(self) -> QuestionState:
|
|
338
|
+
"""Cancel the question and remove its notification."""
|
|
339
|
+
return await self._client.cancel_question(self.id)
|