smswire 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.
- smswire/__init__.py +17 -0
- smswire/_client.py +575 -0
- smswire/_http.py +141 -0
- smswire/_requests.py +166 -0
- smswire/_version.py +1 -0
- smswire/errors.py +24 -0
- smswire/py.typed +0 -0
- smswire/types.py +282 -0
- smswire/webhooks.py +61 -0
- smswire-0.2.0.dist-info/METADATA +206 -0
- smswire-0.2.0.dist-info/RECORD +13 -0
- smswire-0.2.0.dist-info/WHEEL +4 -0
- smswire-0.2.0.dist-info/licenses/LICENSE +21 -0
smswire/_http.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import email.utils
|
|
5
|
+
import json
|
|
6
|
+
import random
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any, Dict, Optional
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .errors import SMSWireError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Request:
|
|
18
|
+
method: str
|
|
19
|
+
path: str
|
|
20
|
+
query: Optional[Dict[str, Any]] = None
|
|
21
|
+
body: Any = None
|
|
22
|
+
headers: Dict[str, str] = field(default_factory=dict)
|
|
23
|
+
#: Safe to repeat after a 5xx or a dropped connection (GET, PATCH, DELETE, or a POST with an Idempotency-Key).
|
|
24
|
+
idempotent: bool = True
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Settings:
|
|
29
|
+
api_key: str
|
|
30
|
+
base_url: str
|
|
31
|
+
max_retries: int
|
|
32
|
+
max_retry_wait: float
|
|
33
|
+
timeout: float
|
|
34
|
+
user_agent: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _retry_after(header: Optional[str]) -> Optional[float]:
|
|
38
|
+
if not header:
|
|
39
|
+
return None
|
|
40
|
+
try:
|
|
41
|
+
return max(0.0, float(header))
|
|
42
|
+
except ValueError:
|
|
43
|
+
pass
|
|
44
|
+
try:
|
|
45
|
+
at = email.utils.parsedate_to_datetime(header)
|
|
46
|
+
except (TypeError, ValueError):
|
|
47
|
+
return None
|
|
48
|
+
return max(0.0, at.timestamp() - time.time())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def error_from(res: httpx.Response) -> SMSWireError:
|
|
52
|
+
code, message = "http_error", f"HTTP {res.status_code}"
|
|
53
|
+
try:
|
|
54
|
+
body = res.json()
|
|
55
|
+
if isinstance(body, dict) and isinstance(body.get("error"), str) and isinstance(body.get("message"), str):
|
|
56
|
+
code, message = body["error"], body["message"]
|
|
57
|
+
except (ValueError, json.JSONDecodeError):
|
|
58
|
+
pass # Not JSON (a proxy's error page): keep the generic code.
|
|
59
|
+
return SMSWireError(res.status_code, code, message, _retry_after(res.headers.get("retry-after")))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def retry_delay(err: SMSWireError, req: Request, attempt: int, settings: Settings) -> Optional[float]:
|
|
63
|
+
"""Seconds to wait before trying [err]'s request again, or None to give up."""
|
|
64
|
+
if attempt >= settings.max_retries:
|
|
65
|
+
return None
|
|
66
|
+
retryable = err.status == 429 or (req.idempotent and (err.status is None or err.status >= 500))
|
|
67
|
+
if not retryable:
|
|
68
|
+
return None
|
|
69
|
+
if err.retry_after is not None:
|
|
70
|
+
return err.retry_after if err.retry_after <= settings.max_retry_wait else None
|
|
71
|
+
return float(min(8.0, 0.5 * 2**attempt) * (1 + random.random() * 0.25))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _build(settings: Settings, req: Request) -> Dict[str, Any]:
|
|
75
|
+
headers = {
|
|
76
|
+
"Authorization": f"Bearer {settings.api_key}",
|
|
77
|
+
"Accept": "application/json",
|
|
78
|
+
"User-Agent": settings.user_agent,
|
|
79
|
+
**req.headers,
|
|
80
|
+
}
|
|
81
|
+
params = {k: _query_value(v) for k, v in (req.query or {}).items() if v is not None}
|
|
82
|
+
kwargs: Dict[str, Any] = {"method": req.method, "url": settings.base_url.rstrip("/") + req.path, "headers": headers, "params": params}
|
|
83
|
+
if req.body is not None:
|
|
84
|
+
kwargs["json"] = req.body
|
|
85
|
+
return kwargs
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _query_value(v: Any) -> str:
|
|
89
|
+
if isinstance(v, bool):
|
|
90
|
+
return "true" if v else "false"
|
|
91
|
+
if hasattr(v, "isoformat"):
|
|
92
|
+
return str(v.isoformat())
|
|
93
|
+
return str(v)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _network_error(e: Exception, settings: Settings, url: str) -> SMSWireError:
|
|
97
|
+
if isinstance(e, httpx.TimeoutException):
|
|
98
|
+
return SMSWireError(None, "timeout", f"No answer within {settings.timeout} s")
|
|
99
|
+
return SMSWireError(None, "network_error", f"Could not reach {url}: {e}")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _result(res: httpx.Response) -> Any:
|
|
103
|
+
return res.json() if res.content else None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def send(client: httpx.Client, settings: Settings, req: Request) -> Any:
|
|
107
|
+
kwargs = _build(settings, req)
|
|
108
|
+
attempt = 0
|
|
109
|
+
while True:
|
|
110
|
+
try:
|
|
111
|
+
res = client.request(**kwargs, timeout=settings.timeout)
|
|
112
|
+
except httpx.TransportError as e:
|
|
113
|
+
err = _network_error(e, settings, settings.base_url)
|
|
114
|
+
else:
|
|
115
|
+
if res.is_success:
|
|
116
|
+
return _result(res)
|
|
117
|
+
err = error_from(res)
|
|
118
|
+
wait = retry_delay(err, req, attempt, settings)
|
|
119
|
+
if wait is None:
|
|
120
|
+
raise err
|
|
121
|
+
time.sleep(wait)
|
|
122
|
+
attempt += 1
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
async def send_async(client: httpx.AsyncClient, settings: Settings, req: Request) -> Any:
|
|
126
|
+
kwargs = _build(settings, req)
|
|
127
|
+
attempt = 0
|
|
128
|
+
while True:
|
|
129
|
+
try:
|
|
130
|
+
res = await client.request(**kwargs, timeout=settings.timeout)
|
|
131
|
+
except httpx.TransportError as e:
|
|
132
|
+
err = _network_error(e, settings, settings.base_url)
|
|
133
|
+
else:
|
|
134
|
+
if res.is_success:
|
|
135
|
+
return _result(res)
|
|
136
|
+
err = error_from(res)
|
|
137
|
+
wait = retry_delay(err, req, attempt, settings)
|
|
138
|
+
if wait is None:
|
|
139
|
+
raise err
|
|
140
|
+
await asyncio.sleep(wait)
|
|
141
|
+
attempt += 1
|
smswire/_requests.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""The public API's calls as Requests; the sync and async clients only differ in how they send them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Any, Dict, Optional, Sequence, Union
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
|
|
10
|
+
from ._http import Request
|
|
11
|
+
|
|
12
|
+
When = Union[str, datetime, None]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _iso(value: When) -> Optional[str]:
|
|
16
|
+
return value.isoformat() if isinstance(value, datetime) else value
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _clean(**fields: Any) -> Dict[str, Any]:
|
|
20
|
+
"""The JSON body: None means "not given", so it is left out. ``from_`` is sent as ``from``."""
|
|
21
|
+
return {k.rstrip("_"): (_iso(v) if isinstance(v, datetime) else v) for k, v in fields.items() if v is not None}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Paths:
|
|
25
|
+
def __init__(self, project: str) -> None:
|
|
26
|
+
p = f"/v1/p/{quote(project, safe='')}"
|
|
27
|
+
self.messages = f"{p}/messages"
|
|
28
|
+
self.otp = f"{p}/otp"
|
|
29
|
+
self.schedules = f"{p}/schedules"
|
|
30
|
+
self.groups = f"{p}/groups"
|
|
31
|
+
self.campaigns = f"{p}/campaigns"
|
|
32
|
+
|
|
33
|
+
@staticmethod
|
|
34
|
+
def one(base: str, id: str) -> str:
|
|
35
|
+
return f"{base}/{quote(id, safe='')}"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def send_message(paths: Paths, idempotency_key: Optional[str], **fields: Any) -> Request:
|
|
39
|
+
return Request(
|
|
40
|
+
"POST",
|
|
41
|
+
paths.messages,
|
|
42
|
+
body=_clean(**fields),
|
|
43
|
+
headers={"Idempotency-Key": idempotency_key or str(uuid.uuid4())},
|
|
44
|
+
idempotent=True,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def send_bulk(paths: Paths, **fields: Any) -> Request:
|
|
49
|
+
messages: Sequence[Any] = fields.pop("messages") or ()
|
|
50
|
+
return Request("POST", f"{paths.messages}/bulk", body={**_clean(**fields), "messages": [_clean(**m) for m in messages]}, idempotent=False)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_message(paths: Paths, id: str) -> Request:
|
|
54
|
+
return Request("GET", Paths.one(paths.messages, id))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def cancel_message(paths: Paths, id: str) -> Request:
|
|
58
|
+
return Request("DELETE", Paths.one(paths.messages, id))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def list_messages(paths: Paths, **query: Any) -> Request:
|
|
62
|
+
return Request("GET", paths.messages, query=query)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def send_otp(paths: Paths, **fields: Any) -> Request:
|
|
66
|
+
return Request("POST", paths.otp, body=_clean(**fields), idempotent=False)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def verify_otp(paths: Paths, id: str, code: str) -> Request:
|
|
70
|
+
return Request("POST", f"{paths.otp}/verify", body={"id": id, "code": code}, idempotent=False)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def create_schedule(paths: Paths, **fields: Any) -> Request:
|
|
74
|
+
return Request("POST", paths.schedules, body=_clean(**fields), idempotent=False)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def list_schedules(paths: Paths) -> Request:
|
|
78
|
+
return Request("GET", paths.schedules)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def get_schedule(paths: Paths, id: str) -> Request:
|
|
82
|
+
return Request("GET", Paths.one(paths.schedules, id))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def update_schedule(paths: Paths, id: str, **changes: Any) -> Request:
|
|
86
|
+
# Only what's passed changes; an explicit None clears the field.
|
|
87
|
+
return Request("PATCH", Paths.one(paths.schedules, id), body={k: _iso(v) for k, v in changes.items()})
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def delete_schedule(paths: Paths, id: str) -> Request:
|
|
91
|
+
return Request("DELETE", Paths.one(paths.schedules, id))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def create_group(paths: Paths, **fields: Any) -> Request:
|
|
95
|
+
return Request("POST", paths.groups, body=_clean(**fields), idempotent=False)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def list_groups(paths: Paths) -> Request:
|
|
99
|
+
return Request("GET", paths.groups)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def get_group(paths: Paths, id: str) -> Request:
|
|
103
|
+
return Request("GET", Paths.one(paths.groups, id))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def update_group(paths: Paths, id: str, **changes: Any) -> Request:
|
|
107
|
+
# Only what's passed changes; keywords=[] turns joining by text off, join_reply=None clears it.
|
|
108
|
+
return Request("PATCH", Paths.one(paths.groups, id), body=dict(changes))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def delete_group(paths: Paths, id: str) -> Request:
|
|
112
|
+
return Request("DELETE", Paths.one(paths.groups, id))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def create_campaign(paths: Paths, **fields: Any) -> Request:
|
|
116
|
+
return Request("POST", paths.campaigns, body=_clean(**fields), idempotent=False)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def list_campaigns(paths: Paths) -> Request:
|
|
120
|
+
return Request("GET", paths.campaigns)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def get_campaign(paths: Paths, id: str) -> Request:
|
|
124
|
+
return Request("GET", Paths.one(paths.campaigns, id))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def update_campaign(paths: Paths, id: str, **changes: Any) -> Request:
|
|
128
|
+
# Only what's passed changes; the rest of the campaign stays as it is.
|
|
129
|
+
return Request("PATCH", Paths.one(paths.campaigns, id), body=dict(changes))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def delete_campaign(paths: Paths, id: str) -> Request:
|
|
133
|
+
return Request("DELETE", Paths.one(paths.campaigns, id))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def preview_campaign(paths: Paths, id: str) -> Request:
|
|
137
|
+
return Request("GET", f"{Paths.one(paths.campaigns, id)}/preview")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def campaign_results(paths: Paths, id: str) -> Request:
|
|
141
|
+
return Request("GET", f"{Paths.one(paths.campaigns, id)}/results")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def send_campaign(paths: Paths, id: str) -> Request:
|
|
145
|
+
return Request("POST", f"{Paths.one(paths.campaigns, id)}/send", idempotent=False)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def control_campaign(paths: Paths, id: str, status: str) -> Request:
|
|
149
|
+
return Request("POST", f"{Paths.one(paths.campaigns, id)}/control", body={"status": status})
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def cancel_campaign(paths: Paths, id: str) -> Request:
|
|
153
|
+
return Request("POST", f"{Paths.one(paths.campaigns, id)}/cancel")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def list_group_members(paths: Paths, id: str, **query: Any) -> Request:
|
|
157
|
+
return Request("GET", f"{Paths.one(paths.groups, id)}/members", query={k: v for k, v in query.items() if v is not None})
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def add_group_members(paths: Paths, id: str, members: Sequence[Any]) -> Request:
|
|
161
|
+
return Request("POST", f"{Paths.one(paths.groups, id)}/members", body={"members": [_clean(**m) for m in members]})
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def remove_group_member(paths: Paths, id: str, phone: str) -> Request:
|
|
165
|
+
return Request("DELETE", f"{Paths.one(paths.groups, id)}/members/{quote(phone, safe='')}")
|
|
166
|
+
|
smswire/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
smswire/errors.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SMSWireError(Exception):
|
|
7
|
+
"""A request that failed: the API's answer, or a network problem (``status`` is None)."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, status: Optional[int], code: str, message: str, retry_after: Optional[float] = None) -> None:
|
|
10
|
+
super().__init__(message)
|
|
11
|
+
#: HTTP status, or None when no answer arrived.
|
|
12
|
+
self.status = status
|
|
13
|
+
#: Stable machine code: ``invalid_request``, ``rate_limited``, ``network_error``, ``timeout``, …
|
|
14
|
+
self.code = code
|
|
15
|
+
self.message = message
|
|
16
|
+
#: Seconds until trying again makes sense (from Retry-After), when the API said.
|
|
17
|
+
self.retry_after = retry_after
|
|
18
|
+
|
|
19
|
+
def __repr__(self) -> str:
|
|
20
|
+
return f"SMSWireError(status={self.status!r}, code={self.code!r}, message={self.message!r})"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SignatureError(Exception):
|
|
24
|
+
"""A webhook whose signature is missing, wrong or too old. Answer it with 400."""
|
smswire/py.typed
ADDED
|
File without changes
|
smswire/types.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""Shapes the API returns, as TypedDicts (plain dicts at runtime). Mirrors sdks/openapi.json."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, List, Literal, Optional, TypedDict
|
|
6
|
+
|
|
7
|
+
MessageType = Literal["otp", "transactional", "notification", "marketing"]
|
|
8
|
+
MessageStatus = Literal["queued", "sending", "sent", "delivered", "failed", "cancelled"]
|
|
9
|
+
OtpFailure = Literal["invalid", "expired", "too_many_attempts", "already_used"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _MessageRequired(TypedDict):
|
|
13
|
+
id: str
|
|
14
|
+
to: str
|
|
15
|
+
status: MessageStatus
|
|
16
|
+
segments: int
|
|
17
|
+
type: MessageType
|
|
18
|
+
tags: List[str]
|
|
19
|
+
received_at: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Message(_MessageRequired, total=False):
|
|
23
|
+
error: Optional[str]
|
|
24
|
+
language: Optional[str]
|
|
25
|
+
metadata: Optional[Dict[str, Any]]
|
|
26
|
+
batch_id: Optional[str]
|
|
27
|
+
scheduled_at: Optional[str]
|
|
28
|
+
sent_at: Optional[str]
|
|
29
|
+
delivered_at: Optional[str]
|
|
30
|
+
redacted: bool
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _MessagePageRequired(TypedDict):
|
|
34
|
+
data: List[Message]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MessagePage(_MessagePageRequired, total=False):
|
|
38
|
+
next_cursor: Optional[str]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class RejectedItem(TypedDict):
|
|
42
|
+
index: int
|
|
43
|
+
to: str
|
|
44
|
+
reason: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class BulkResult(TypedDict):
|
|
48
|
+
batch_id: str
|
|
49
|
+
accepted: int
|
|
50
|
+
rejected: List[RejectedItem]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Otp(TypedDict):
|
|
54
|
+
id: str
|
|
55
|
+
to: str
|
|
56
|
+
expires_at: str
|
|
57
|
+
message_id: str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class _OtpVerificationRequired(TypedDict):
|
|
61
|
+
valid: bool
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class OtpVerification(_OtpVerificationRequired, total=False):
|
|
65
|
+
reason: Optional[OtpFailure]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _ScheduleRunRequired(TypedDict):
|
|
69
|
+
at: str
|
|
70
|
+
status: Literal["sent", "failed", "skipped"]
|
|
71
|
+
accepted: int
|
|
72
|
+
rejected: int
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ScheduleRun(_ScheduleRunRequired, total=False):
|
|
76
|
+
message_id: Optional[str]
|
|
77
|
+
batch_id: Optional[str]
|
|
78
|
+
error: Optional[str]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _ScheduleRecipients(TypedDict):
|
|
82
|
+
numbers: int
|
|
83
|
+
group_ids: List[str]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class _ScheduleRequired(TypedDict):
|
|
87
|
+
id: str
|
|
88
|
+
name: str
|
|
89
|
+
cron: str
|
|
90
|
+
timezone: str
|
|
91
|
+
enabled: bool
|
|
92
|
+
tags: List[str]
|
|
93
|
+
recipients: _ScheduleRecipients
|
|
94
|
+
run_count: int
|
|
95
|
+
created_at: str
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Schedule(_ScheduleRequired, total=False):
|
|
99
|
+
body: Optional[str]
|
|
100
|
+
template_id: Optional[str]
|
|
101
|
+
language: Optional[str]
|
|
102
|
+
type: Optional[MessageType]
|
|
103
|
+
next_run_at: Optional[str]
|
|
104
|
+
last_run_at: Optional[str]
|
|
105
|
+
ends_at: Optional[str]
|
|
106
|
+
max_runs: Optional[int]
|
|
107
|
+
last_run: Optional[ScheduleRun]
|
|
108
|
+
runs: Optional[List[ScheduleRun]]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class SchedulePage(TypedDict):
|
|
112
|
+
data: List[Schedule]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class BulkItem(TypedDict, total=False):
|
|
116
|
+
to: str
|
|
117
|
+
body: Optional[str]
|
|
118
|
+
language: Optional[str]
|
|
119
|
+
variables: Optional[Dict[str, Any]]
|
|
120
|
+
type: Optional[MessageType]
|
|
121
|
+
tags: Optional[List[str]]
|
|
122
|
+
metadata: Optional[Dict[str, Any]]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class ScheduleRecipient(TypedDict, total=False):
|
|
126
|
+
to: str
|
|
127
|
+
variables: Optional[Dict[str, Any]]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
CampaignStatus = Literal["draft", "scheduled", "sending", "paused", "done", "cancelled"]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class CampaignAudience(TypedDict, total=False):
|
|
134
|
+
group_ids: List[str]
|
|
135
|
+
numbers: List[str]
|
|
136
|
+
messages: List[ScheduleRecipient]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class CampaignExclude(TypedDict, total=False):
|
|
140
|
+
group_ids: List[str]
|
|
141
|
+
recent_days: Optional[int]
|
|
142
|
+
no_reply_to_campaign_id: Optional[str]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class CampaignQuietHours(TypedDict):
|
|
146
|
+
start: str
|
|
147
|
+
end: str
|
|
148
|
+
timezone: str
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class _CampaignRequired(TypedDict):
|
|
152
|
+
id: str
|
|
153
|
+
name: str
|
|
154
|
+
status: CampaignStatus
|
|
155
|
+
body: str
|
|
156
|
+
type: MessageType
|
|
157
|
+
tags: List[str]
|
|
158
|
+
audience: CampaignAudience
|
|
159
|
+
exclude: CampaignExclude
|
|
160
|
+
rate: int
|
|
161
|
+
consent: bool
|
|
162
|
+
total: int
|
|
163
|
+
runs: int
|
|
164
|
+
created_at: str
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class Campaign(_CampaignRequired, total=False):
|
|
168
|
+
sim: Optional[int]
|
|
169
|
+
quiet_hours: Optional[CampaignQuietHours]
|
|
170
|
+
stop_footer: Optional[str]
|
|
171
|
+
next_run_at: Optional[str]
|
|
172
|
+
last_run_at: Optional[str]
|
|
173
|
+
cron: Optional[str]
|
|
174
|
+
timezone: Optional[str]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class CampaignList(TypedDict):
|
|
178
|
+
data: List[Campaign]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class CampaignRun(TypedDict):
|
|
182
|
+
batch_id: str
|
|
183
|
+
total: int
|
|
184
|
+
delivered: int
|
|
185
|
+
failed: int
|
|
186
|
+
created_at: str
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class _CampaignResultsRequired(TypedDict):
|
|
190
|
+
delivered: int
|
|
191
|
+
failed: int
|
|
192
|
+
awaiting: int
|
|
193
|
+
waiting: int
|
|
194
|
+
parts: int
|
|
195
|
+
replies: int
|
|
196
|
+
opt_outs: int
|
|
197
|
+
runs: List[CampaignRun]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class CampaignResults(_CampaignResultsRequired, total=False):
|
|
201
|
+
delivery_rate: Optional[float]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class CampaignExcluded(TypedDict):
|
|
205
|
+
group: int
|
|
206
|
+
recent: int
|
|
207
|
+
replied: int
|
|
208
|
+
duplicate: int
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class CampaignPreview(TypedDict):
|
|
212
|
+
recipients: int
|
|
213
|
+
excluded: CampaignExcluded
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class _CampaignSendRequired(TypedDict):
|
|
217
|
+
status: Literal["queued", "scheduled"]
|
|
218
|
+
accepted: int
|
|
219
|
+
rejected: List[RejectedItem]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class CampaignSendResult(_CampaignSendRequired, total=False):
|
|
223
|
+
batch_id: Optional[str]
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
GroupJoinSource = Literal["manual", "import", "keyword", "api"]
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class _GroupRequired(TypedDict):
|
|
230
|
+
id: str
|
|
231
|
+
name: str
|
|
232
|
+
size: int
|
|
233
|
+
keywords: List[str]
|
|
234
|
+
created_at: str
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class Group(_GroupRequired, total=False):
|
|
238
|
+
join_reply: Optional[str]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class GroupList(TypedDict):
|
|
242
|
+
data: List[Group]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class _GroupMemberRequired(TypedDict):
|
|
246
|
+
contact_id: str
|
|
247
|
+
phone: str
|
|
248
|
+
fields: Dict[str, str]
|
|
249
|
+
joined_at: str
|
|
250
|
+
source: GroupJoinSource
|
|
251
|
+
opted_out: bool
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class GroupMember(_GroupMemberRequired, total=False):
|
|
255
|
+
name: Optional[str]
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class _GroupMemberPageRequired(TypedDict):
|
|
259
|
+
data: List[GroupMember]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class GroupMemberPage(_GroupMemberPageRequired, total=False):
|
|
263
|
+
next_cursor: Optional[str]
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
class InvalidMember(TypedDict):
|
|
267
|
+
index: int
|
|
268
|
+
phone: str
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class AddMembersResult(TypedDict):
|
|
272
|
+
added: int
|
|
273
|
+
already: int
|
|
274
|
+
invalid: List[InvalidMember]
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class GroupMemberInput(TypedDict, total=False):
|
|
278
|
+
phone: str
|
|
279
|
+
name: Optional[str]
|
|
280
|
+
fields: Optional[Dict[str, str]]
|
|
281
|
+
language: Optional[str]
|
|
282
|
+
|
smswire/webhooks.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, Dict, List, Optional, Tuple, Union, cast
|
|
9
|
+
|
|
10
|
+
from .errors import SignatureError
|
|
11
|
+
|
|
12
|
+
#: The header the signature arrives in.
|
|
13
|
+
SIGNATURE_HEADER = "X-SMSWire-Signature"
|
|
14
|
+
|
|
15
|
+
_HEX = re.compile(r"^[0-9a-fA-F]{64}$")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _parse(header: str) -> Optional[Tuple[int, List[str]]]:
|
|
19
|
+
t: Optional[int] = None
|
|
20
|
+
signatures: List[str] = []
|
|
21
|
+
for part in header.split(","):
|
|
22
|
+
key, sep, value = part.partition("=")
|
|
23
|
+
if not sep:
|
|
24
|
+
continue
|
|
25
|
+
key, value = key.strip(), value.strip()
|
|
26
|
+
if key == "t" and value.isdigit():
|
|
27
|
+
t = int(value)
|
|
28
|
+
elif key == "v1" and _HEX.match(value):
|
|
29
|
+
signatures.append(value.lower())
|
|
30
|
+
if t is None or not signatures:
|
|
31
|
+
return None
|
|
32
|
+
return t, signatures
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def verify_webhook(
|
|
36
|
+
raw_body: Union[bytes, str],
|
|
37
|
+
signature: Optional[str],
|
|
38
|
+
secret: str,
|
|
39
|
+
*,
|
|
40
|
+
tolerance: int = 300,
|
|
41
|
+
now: Optional[float] = None,
|
|
42
|
+
) -> Dict[str, Any]:
|
|
43
|
+
"""Checks a webhook's X-SMSWire-Signature against the **raw** request body and returns the event.
|
|
44
|
+
|
|
45
|
+
Raises SignatureError when the signature is missing, wrong, or more than ``tolerance``
|
|
46
|
+
seconds off. Pass the body exactly as received, not re-serialised JSON.
|
|
47
|
+
"""
|
|
48
|
+
if not secret:
|
|
49
|
+
raise SignatureError("No webhook signing secret given")
|
|
50
|
+
parsed = _parse(signature or "")
|
|
51
|
+
if parsed is None:
|
|
52
|
+
raise SignatureError(f"Missing or malformed {SIGNATURE_HEADER} header")
|
|
53
|
+
t, signatures = parsed
|
|
54
|
+
current = time.time() if now is None else now
|
|
55
|
+
if abs(current - t) > tolerance:
|
|
56
|
+
raise SignatureError("Signature timestamp is outside the tolerance")
|
|
57
|
+
body = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body
|
|
58
|
+
expected = hmac.new(secret.encode("utf-8"), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
|
|
59
|
+
if not any(hmac.compare_digest(s, expected) for s in signatures):
|
|
60
|
+
raise SignatureError("Signature does not match")
|
|
61
|
+
return cast(Dict[str, Any], json.loads(body))
|