importly 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.
importly/_errors.py ADDED
@@ -0,0 +1,198 @@
1
+ """Errors raised by the Importly client.
2
+
3
+ Every error is an ``ImportlyError``. Request errors (the API said no) are
4
+ ``APIError`` subclasses chosen by HTTP status and ``code``. A job that was
5
+ accepted but failed later raises ``JobFailedError`` from the ``wait_*`` and
6
+ one-call helpers.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Dict, Mapping, Optional
12
+
13
+
14
+ class ImportlyError(Exception):
15
+ """Base class for every error this package raises."""
16
+
17
+ def __init__(
18
+ self,
19
+ message: str,
20
+ *,
21
+ code: Optional[str] = None,
22
+ documentation_url: Optional[str] = None,
23
+ ) -> None:
24
+ super().__init__(message)
25
+ self.message = message
26
+ self.code = code
27
+ self.documentation_url = documentation_url
28
+
29
+ def __str__(self) -> str:
30
+ parts = [self.message]
31
+ if self.code:
32
+ parts.append(f"[{self.code}]")
33
+ if self.documentation_url:
34
+ parts.append(f"See {self.documentation_url}")
35
+ return " ".join(parts)
36
+
37
+
38
+ class MissingAPIKeyError(ImportlyError):
39
+ """No API key was passed and ``IMPORTLY_API_KEY`` is not set."""
40
+
41
+
42
+ class APIConnectionError(ImportlyError):
43
+ """The request never got an HTTP response (DNS, TLS, timeout, reset)."""
44
+
45
+
46
+ class APIError(ImportlyError):
47
+ """The API answered with an error status."""
48
+
49
+ def __init__(
50
+ self,
51
+ message: str,
52
+ *,
53
+ status_code: int,
54
+ code: Optional[str] = None,
55
+ documentation_url: Optional[str] = None,
56
+ body: Optional[Mapping[str, Any]] = None,
57
+ ) -> None:
58
+ super().__init__(message, code=code, documentation_url=documentation_url)
59
+ self.status_code = status_code
60
+ self.body: Dict[str, Any] = dict(body or {})
61
+
62
+
63
+ class InvalidRequestError(APIError):
64
+ """400: a parameter is missing or invalid. Fix the request; don't retry it."""
65
+
66
+
67
+ class InvalidURLError(InvalidRequestError):
68
+ """400 with ``INVALID_URL`` (or ``PLAYLIST_NOT_SUPPORTED``): the media URL was rejected."""
69
+
70
+
71
+ class AuthenticationError(APIError):
72
+ """401: the API key is missing or invalid."""
73
+
74
+
75
+ class InsufficientBalanceError(APIError):
76
+ """402: the balance is below what the job needs to start. Add credits, then retry."""
77
+
78
+ @property
79
+ def balance_required(self) -> Optional[float]:
80
+ value = self.body.get("balanceRequired")
81
+ return float(value) if value is not None else None
82
+
83
+ @property
84
+ def endpoint(self) -> Optional[str]:
85
+ return self.body.get("endpoint")
86
+
87
+
88
+ class NotFoundError(APIError):
89
+ """404: no job with that id belongs to this account."""
90
+
91
+
92
+ class RateLimitError(APIError):
93
+ """429: over the hourly limit for this endpoint. Wait ``retry_after`` seconds."""
94
+
95
+ @property
96
+ def retry_after(self) -> Optional[float]:
97
+ value = self.body.get("retryAfter")
98
+ return float(value) if value is not None else None
99
+
100
+ @property
101
+ def limit(self) -> Optional[int]:
102
+ return self.body.get("limit")
103
+
104
+ @property
105
+ def remaining(self) -> Optional[int]:
106
+ return self.body.get("remaining")
107
+
108
+ @property
109
+ def reset(self) -> Optional[int]:
110
+ """When the window resets, as Unix time in milliseconds."""
111
+ return self.body.get("reset")
112
+
113
+
114
+ class InternalServerError(APIError):
115
+ """5xx: something broke on Importly's side. Safe to retry with backoff."""
116
+
117
+
118
+ class JobFailedError(ImportlyError):
119
+ """A job was accepted but failed, e.g. ``VIDEO_PRIVATE`` or ``MAX_COST_EXCEEDED``."""
120
+
121
+ def __init__(
122
+ self,
123
+ message: str,
124
+ *,
125
+ job_id: str,
126
+ job_type: str,
127
+ code: Optional[str] = None,
128
+ documentation_url: Optional[str] = None,
129
+ raw: Optional[Mapping[str, Any]] = None,
130
+ ) -> None:
131
+ super().__init__(message, code=code, documentation_url=documentation_url)
132
+ self.job_id = job_id
133
+ self.job_type = job_type
134
+ self.raw: Dict[str, Any] = dict(raw or {})
135
+
136
+
137
+ class TranscriptionProviderRequiredError(JobFailedError):
138
+ """The media has no captions and no speech-to-text provider was set.
139
+
140
+ ``quote`` holds what built-in speech-to-text (``provider="importly"``) would
141
+ cost, when the duration is known.
142
+ """
143
+
144
+ @property
145
+ def quote(self) -> Optional[Dict[str, Any]]:
146
+ return self.raw.get("quote")
147
+
148
+
149
+ class JobTimeoutError(ImportlyError):
150
+ """The job was still running when the wait timed out. It may still finish."""
151
+
152
+ def __init__(self, message: str, *, job_id: str, job_type: str) -> None:
153
+ super().__init__(message)
154
+ self.job_id = job_id
155
+ self.job_type = job_type
156
+
157
+
158
+ def error_from_response(status_code: int, body: Any) -> APIError:
159
+ """Map an error response to the matching ``APIError`` subclass."""
160
+ data: Dict[str, Any] = body if isinstance(body, dict) else {}
161
+ message = str(data.get("error") or data.get("message") or f"HTTP {status_code}")
162
+ code = data.get("code")
163
+ kwargs: Dict[str, Any] = {
164
+ "status_code": status_code,
165
+ "code": code,
166
+ "documentation_url": data.get("documentationUrl"),
167
+ "body": data,
168
+ }
169
+ if status_code == 401:
170
+ return AuthenticationError(message, **kwargs)
171
+ if status_code == 402:
172
+ return InsufficientBalanceError(message, **kwargs)
173
+ if status_code == 404:
174
+ return NotFoundError(message, **kwargs)
175
+ if status_code == 429:
176
+ return RateLimitError(message, **kwargs)
177
+ if status_code == 400:
178
+ if code in ("INVALID_URL", "PLAYLIST_NOT_SUPPORTED"):
179
+ return InvalidURLError(message, **kwargs)
180
+ return InvalidRequestError(message, **kwargs)
181
+ if status_code >= 500:
182
+ return InternalServerError(message, **kwargs)
183
+ return APIError(message, **kwargs)
184
+
185
+
186
+ def job_failed_error(job_type: str, job_id: str, data: Mapping[str, Any]) -> JobFailedError:
187
+ """Build the error for a job whose status is ``failed``."""
188
+ message = str(data.get("message") or f"{job_type} job {job_id} failed")
189
+ code = data.get("code")
190
+ cls = TranscriptionProviderRequiredError if code == "TRANSCRIPTION_PROVIDER_REQUIRED" else JobFailedError
191
+ return cls(
192
+ message,
193
+ job_id=job_id,
194
+ job_type=job_type,
195
+ code=code,
196
+ documentation_url=data.get("documentationUrl"),
197
+ raw=data,
198
+ )
importly/_types.py ADDED
@@ -0,0 +1,302 @@
1
+ """Typed results returned by the Importly client.
2
+
3
+ Each result keeps the API's JSON in ``raw`` so fields the API adds later are
4
+ still reachable without a new release of this package.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Dict, List, Literal, Mapping, Optional
11
+
12
+ JobType = Literal["import", "transcribe", "metadata", "basic-metadata"]
13
+ JobStatusValue = Literal["queued", "running", "completed", "failed"]
14
+
15
+ FINAL_STATUSES = ("completed", "failed")
16
+
17
+
18
+ def _float(value: Any) -> Optional[float]:
19
+ return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None
20
+
21
+
22
+ def _int(value: Any) -> Optional[int]:
23
+ return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None
24
+
25
+
26
+ def format_timestamp(seconds: float) -> str:
27
+ """``75.4`` -> ``"00:01:15"``."""
28
+ total = int(seconds)
29
+ return f"{total // 3600:02d}:{(total % 3600) // 60:02d}:{total % 60:02d}"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class QueuedJob:
34
+ """What a ``start_*`` call returns: the job id to poll or match a webhook against."""
35
+
36
+ job_id: str
37
+ status: str
38
+ message: Optional[str] = None
39
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
40
+
41
+ @classmethod
42
+ def from_dict(cls, data: Mapping[str, Any]) -> "QueuedJob":
43
+ return cls(job_id=str(data["jobId"]), status=str(data.get("status", "queued")), message=data.get("message"), raw=dict(data))
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class TranscriptSegment:
48
+ start: float
49
+ end: float
50
+ text: str
51
+
52
+ @classmethod
53
+ def from_dict(cls, data: Mapping[str, Any]) -> "TranscriptSegment":
54
+ return cls(start=float(data.get("start") or 0), end=float(data.get("end") or 0), text=str(data.get("text") or ""))
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class TranscriptChunk:
59
+ """Consecutive segments grouped into one window of roughly ``chunk_seconds``."""
60
+
61
+ index: int
62
+ start: float
63
+ end: float
64
+ text: str
65
+
66
+ @property
67
+ def start_timestamp(self) -> str:
68
+ return format_timestamp(self.start)
69
+
70
+ @property
71
+ def end_timestamp(self) -> str:
72
+ return format_timestamp(self.end)
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class Transcript:
77
+ """A finished transcription: full text plus timestamped segments."""
78
+
79
+ text: str
80
+ source: Optional[str] = None
81
+ language: Optional[str] = None
82
+ duration: Optional[float] = None
83
+ segments: List[TranscriptSegment] = field(default_factory=list)
84
+ cost_in_dollars: Optional[float] = None
85
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
86
+
87
+ @classmethod
88
+ def from_dict(cls, data: Mapping[str, Any]) -> "Transcript":
89
+ inner = data.get("data") if isinstance(data.get("data"), Mapping) else {}
90
+ segments = inner.get("segments") if isinstance(inner, Mapping) else None
91
+ return cls(
92
+ text=str(data.get("text") or ""),
93
+ source=data.get("source"),
94
+ language=data.get("language"),
95
+ duration=_float(data.get("duration")),
96
+ segments=[TranscriptSegment.from_dict(s) for s in (segments or []) if isinstance(s, Mapping)],
97
+ cost_in_dollars=_float(data.get("costInDollars")),
98
+ raw=dict(data),
99
+ )
100
+
101
+ def chunks(self, chunk_seconds: float = 120) -> List[TranscriptChunk]:
102
+ """Group segments into windows of about ``chunk_seconds``.
103
+
104
+ A chunk closes at the first segment boundary at or past the window, so
105
+ no segment is split. With no segments, the whole text is one chunk.
106
+ """
107
+ if chunk_seconds <= 0:
108
+ raise ValueError("chunk_seconds must be positive")
109
+ if not self.segments:
110
+ if not self.text:
111
+ return []
112
+ return [TranscriptChunk(index=0, start=0.0, end=self.duration or 0.0, text=self.text)]
113
+ chunks: List[TranscriptChunk] = []
114
+ current: List[TranscriptSegment] = []
115
+ for segment in self.segments:
116
+ if current and segment.start - current[0].start >= chunk_seconds:
117
+ chunks.append(self._chunk(len(chunks), current))
118
+ current = []
119
+ current.append(segment)
120
+ if current:
121
+ chunks.append(self._chunk(len(chunks), current))
122
+ return chunks
123
+
124
+ @staticmethod
125
+ def _chunk(index: int, segments: List[TranscriptSegment]) -> TranscriptChunk:
126
+ text = " ".join(s.text.strip() for s in segments if s.text.strip())
127
+ return TranscriptChunk(index=index, start=segments[0].start, end=segments[-1].end, text=text)
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class S3Location:
132
+ url: Optional[str] = None
133
+ bucket: Optional[str] = None
134
+ key: Optional[str] = None
135
+
136
+ @classmethod
137
+ def from_dict(cls, data: Mapping[str, Any]) -> "S3Location":
138
+ return cls(url=data.get("url"), bucket=data.get("bucket"), key=data.get("key"))
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class ImportResult:
143
+ """A finished import: a signed download link (valid 7 days) and file details."""
144
+
145
+ media_url: Optional[str] = None
146
+ title: Optional[str] = None
147
+ duration: Optional[float] = None
148
+ thumbnail_url: Optional[str] = None
149
+ filename: Optional[str] = None
150
+ file_size_bytes: Optional[int] = None
151
+ downloaded_bytes: Optional[int] = None
152
+ cost_in_dollars: Optional[float] = None
153
+ transcript: Optional[Transcript] = None
154
+ transcript_skipped_reason: Optional[str] = None
155
+ s3_storage: Optional[S3Location] = None
156
+ s3_storage_error: Optional[str] = None
157
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
158
+
159
+ @classmethod
160
+ def from_dict(cls, data: Mapping[str, Any]) -> "ImportResult":
161
+ transcript_data = data.get("transcript")
162
+ transcript: Optional[Transcript] = None
163
+ skipped: Optional[str] = None
164
+ if isinstance(transcript_data, Mapping):
165
+ if transcript_data.get("status") == "skipped":
166
+ skipped = str(transcript_data.get("reason") or "skipped")
167
+ elif "text" in transcript_data:
168
+ transcript = Transcript.from_dict(transcript_data)
169
+ s3 = data.get("s3Storage")
170
+ return cls(
171
+ media_url=data.get("mediaUrl"),
172
+ title=data.get("title"),
173
+ duration=_float(data.get("duration")),
174
+ thumbnail_url=data.get("thumbnailUrl"),
175
+ filename=data.get("filename"),
176
+ file_size_bytes=_int(data.get("fileSizeBytes")),
177
+ downloaded_bytes=_int(data.get("downloadedBytes")),
178
+ cost_in_dollars=_float(data.get("costInDollars")),
179
+ transcript=transcript,
180
+ transcript_skipped_reason=skipped,
181
+ s3_storage=S3Location.from_dict(s3) if isinstance(s3, Mapping) else None,
182
+ s3_storage_error=data.get("s3StorageError"),
183
+ raw=dict(data),
184
+ )
185
+
186
+
187
+ @dataclass(frozen=True)
188
+ class Metadata:
189
+ """Full metadata. Fields vary by platform; everything is in ``raw`` (snake_case)."""
190
+
191
+ id: Optional[str] = None
192
+ title: Optional[str] = None
193
+ description: Optional[str] = None
194
+ duration: Optional[float] = None
195
+ uploader: Optional[str] = None
196
+ upload_date: Optional[str] = None
197
+ view_count: Optional[int] = None
198
+ like_count: Optional[int] = None
199
+ thumbnail: Optional[str] = None
200
+ webpage_url: Optional[str] = None
201
+ tags: List[str] = field(default_factory=list)
202
+ formats: List[Dict[str, Any]] = field(default_factory=list, repr=False)
203
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
204
+
205
+ @classmethod
206
+ def from_dict(cls, data: Mapping[str, Any]) -> "Metadata":
207
+ return cls(
208
+ id=data.get("id"),
209
+ title=data.get("title"),
210
+ description=data.get("description"),
211
+ duration=_float(data.get("duration")),
212
+ uploader=data.get("uploader"),
213
+ upload_date=data.get("upload_date"),
214
+ view_count=_int(data.get("view_count")),
215
+ like_count=_int(data.get("like_count")),
216
+ thumbnail=data.get("thumbnail"),
217
+ webpage_url=data.get("webpage_url"),
218
+ tags=[str(t) for t in (data.get("tags") or [])],
219
+ formats=[dict(f) for f in (data.get("formats") or []) if isinstance(f, Mapping)],
220
+ raw=dict(data),
221
+ )
222
+
223
+
224
+ @dataclass(frozen=True)
225
+ class BasicMetadata:
226
+ """Title, duration and thumbnail: the fast, cheap preview."""
227
+
228
+ title: Optional[str] = None
229
+ duration: Optional[float] = None
230
+ thumbnail: Optional[str] = None
231
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
232
+
233
+ @classmethod
234
+ def from_dict(cls, data: Mapping[str, Any]) -> "BasicMetadata":
235
+ return cls(title=data.get("title"), duration=_float(data.get("duration")), thumbnail=data.get("thumbnail"), raw=dict(data))
236
+
237
+
238
+ @dataclass(frozen=True)
239
+ class Balance:
240
+ balance: float
241
+ currency: str = "USD"
242
+
243
+ @classmethod
244
+ def from_dict(cls, data: Mapping[str, Any]) -> "Balance":
245
+ return cls(balance=float(data.get("balance") or 0), currency=str(data.get("currency") or "USD"))
246
+
247
+
248
+ @dataclass(frozen=True)
249
+ class JobStatus:
250
+ """One poll of a job's ``/status`` endpoint.
251
+
252
+ ``result`` is the typed result once ``status == "completed"`` (an
253
+ ``ImportResult``, ``Transcript``, ``Metadata`` or ``BasicMetadata``).
254
+ ``code``, ``message`` and ``documentation_url`` are set when it failed.
255
+ """
256
+
257
+ job_id: str
258
+ job_type: str
259
+ status: str
260
+ result: Any = None
261
+ code: Optional[str] = None
262
+ message: Optional[str] = None
263
+ documentation_url: Optional[str] = None
264
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
265
+
266
+ @property
267
+ def is_done(self) -> bool:
268
+ return self.status in FINAL_STATUSES
269
+
270
+ @property
271
+ def succeeded(self) -> bool:
272
+ return self.status == "completed"
273
+
274
+ @property
275
+ def failed(self) -> bool:
276
+ return self.status == "failed"
277
+
278
+
279
+ RESULT_PARSERS = {
280
+ "import": ImportResult.from_dict,
281
+ "transcribe": Transcript.from_dict,
282
+ "metadata": Metadata.from_dict,
283
+ "basic-metadata": BasicMetadata.from_dict,
284
+ }
285
+
286
+
287
+ def parse_job_status(job_type: str, data: Mapping[str, Any]) -> JobStatus:
288
+ status = str(data.get("status") or "queued")
289
+ result_data = data.get("result")
290
+ result = None
291
+ if status == "completed" and isinstance(result_data, Mapping):
292
+ result = RESULT_PARSERS[job_type](result_data)
293
+ return JobStatus(
294
+ job_id=str(data.get("jobId") or ""),
295
+ job_type=job_type,
296
+ status=status,
297
+ result=result,
298
+ code=data.get("code"),
299
+ message=data.get("message"),
300
+ documentation_url=data.get("documentationUrl"),
301
+ raw=dict(data),
302
+ )
importly/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
importly/py.typed ADDED
File without changes
importly/webhooks.py ADDED
@@ -0,0 +1,116 @@
1
+ """Parse the webhooks Importly sends to your ``webhook_url``.
2
+
3
+ Importly POSTs once per job: ``success: true`` with the result fields flattened
4
+ into ``data`` when the job completes, or ``success: false`` with ``code`` and
5
+ ``message`` when it fails for good. Deliveries are not retried, so keep a
6
+ polling fallback (``client.get_job(event.job_type, event.job_id)``).
7
+
8
+ Webhooks are not signed. Put a hard-to-guess token in your webhook URL
9
+ (``https://your-app.com/webhooks/importly?token=...``) and check it with
10
+ ``token_matches``, and match ``event.job_id`` against the ids you started. For
11
+ anything that moves money or data, confirm with ``client.get_job(...)``.
12
+
13
+ Flask example::
14
+
15
+ from importly.webhooks import parse_webhook, token_matches
16
+
17
+ @app.post("/webhooks/importly")
18
+ def importly_webhook():
19
+ if not token_matches(request.args.get("token"), os.environ["IMPORTLY_WEBHOOK_TOKEN"]):
20
+ abort(401)
21
+ event = parse_webhook(request.get_data())
22
+ if event.succeeded and event.job_type == "transcribe":
23
+ save_transcript(event.job_id, event.result.text)
24
+ elif event.failed:
25
+ mark_failed(event.job_id, event.code, event.message)
26
+ return "", 204
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import hmac
32
+ import json
33
+ from dataclasses import dataclass, field
34
+ from typing import Any, Dict, Mapping, Optional, Union
35
+
36
+ from ._errors import ImportlyError, JobFailedError, job_failed_error
37
+ from ._types import RESULT_PARSERS
38
+
39
+ _ENVELOPE_KEYS = ("jobId", "type", "status")
40
+
41
+
42
+ class InvalidWebhookError(ImportlyError):
43
+ """The body isn't an Importly webhook payload."""
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class WebhookEvent:
48
+ """One webhook delivery.
49
+
50
+ ``result`` is typed by ``job_type``: ``ImportResult`` (import),
51
+ ``Transcript`` (transcribe), ``Metadata`` (metadata) or ``BasicMetadata``
52
+ (basic-metadata). It is ``None`` when the job failed.
53
+ """
54
+
55
+ job_id: str
56
+ job_type: str
57
+ status: str
58
+ result: Any = None
59
+ code: Optional[str] = None
60
+ message: Optional[str] = None
61
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
62
+
63
+ @property
64
+ def succeeded(self) -> bool:
65
+ return self.status == "completed"
66
+
67
+ @property
68
+ def failed(self) -> bool:
69
+ return self.status == "failed"
70
+
71
+ def to_error(self) -> JobFailedError:
72
+ """The failure as an exception, e.g. to raise it in a worker."""
73
+ return job_failed_error(self.job_type, self.job_id, self.raw.get("data") or {})
74
+
75
+
76
+ def parse_webhook(payload: Union[bytes, str, Mapping[str, Any]]) -> WebhookEvent:
77
+ """Parse a webhook body (raw bytes, a JSON string, or an already-decoded dict)."""
78
+ body: Any = payload
79
+ if isinstance(payload, (bytes, bytearray)):
80
+ payload = payload.decode("utf-8")
81
+ if isinstance(payload, str):
82
+ try:
83
+ body = json.loads(payload)
84
+ except ValueError as error:
85
+ raise InvalidWebhookError("Webhook body is not valid JSON") from error
86
+ if not isinstance(body, Mapping) or not isinstance(body.get("data"), Mapping):
87
+ raise InvalidWebhookError("Webhook body has no 'data' object")
88
+ data = body["data"]
89
+ missing = [key for key in _ENVELOPE_KEYS if key not in data]
90
+ if missing:
91
+ raise InvalidWebhookError(f"Webhook data is missing {', '.join(missing)}")
92
+ job_type = str(data["type"])
93
+ if job_type not in RESULT_PARSERS:
94
+ raise InvalidWebhookError(f"Unknown webhook job type: {job_type}")
95
+ status = str(data["status"])
96
+ failed = body.get("success") is False or status == "failed"
97
+ result = None
98
+ if not failed:
99
+ fields = {k: v for k, v in data.items() if k not in _ENVELOPE_KEYS}
100
+ result = RESULT_PARSERS[job_type](fields)
101
+ return WebhookEvent(
102
+ job_id=str(data["jobId"]),
103
+ job_type=job_type,
104
+ status="failed" if failed else status,
105
+ result=result,
106
+ code=data.get("code"),
107
+ message=data.get("message"),
108
+ raw=dict(body),
109
+ )
110
+
111
+
112
+ def token_matches(received: Optional[str], expected: str) -> bool:
113
+ """Constant-time check of the token you put in your webhook URL."""
114
+ if not received or not expected:
115
+ return False
116
+ return hmac.compare_digest(received.encode(), expected.encode())