1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398 | """Async client for the ScaiDial ↔ ScaiWave connector.
Dependency: ``httpx``. Semantics: https://www.scailabs.ai/docs/scaigrid/scaidial/integrations/scaiwave-connector
async with ScaiDialWaveClient("https://scaigrid.scailabs.ai", token) as dial:
me = await dial.me("usr_…")
"""
from __future__ import annotations
import hashlib
import hmac
import json
import time
from collections.abc import AsyncIterator, Mapping
from typing import Any
import httpx
API_PREFIX = "/v1/public/scaidial/wave"
class ScaiDialWaveError(Exception):
"""Non-2xx response from the connector."""
def __init__(self, status: int, code: str, message: str) -> None:
super().__init__(f"{status} {code}: {message}")
self.status = status
self.code = code
self.message = message
class WebhookVerificationError(Exception):
"""Webhook signature missing/invalid or timestamp outside the window."""
def verify_webhook(
body: bytes,
headers: Mapping[str, str],
secret: str,
tolerance_s: int = 300,
) -> dict[str, Any]:
"""Check ``X-ScaiDial-Signature`` over the raw body; return the event."""
lower = {k.lower(): v for k, v in headers.items()}
ts_raw = lower.get("x-scaidial-timestamp", "")
sig = lower.get("x-scaidial-signature", "")
try:
ts = int(ts_raw)
except ValueError as exc:
raise WebhookVerificationError("missing or invalid timestamp") from exc
if abs(time.time() - ts) > tolerance_s:
raise WebhookVerificationError("timestamp outside tolerance")
expected = (
"v1=" + hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
)
if not sig or not hmac.compare_digest(sig.encode(), expected.encode()):
raise WebhookVerificationError("signature mismatch")
return json.loads(body)
class ScaiDialWaveClient:
"""One method per connector endpoint. ``user`` is the ScaiKey id
(``usr_…``) or ScaiGrid user id the call is made on behalf of."""
def __init__(self, base_url: str, token: str, *, timeout: float = 15.0) -> None:
self._http = httpx.AsyncClient(
base_url=base_url.rstrip("/") + API_PREFIX,
headers={"Authorization": f"Bearer {token}"},
timeout=timeout,
)
async def __aenter__(self) -> ScaiDialWaveClient:
return self
async def __aexit__(self, *exc: object) -> None:
await self.aclose()
async def aclose(self) -> None:
await self._http.aclose()
# -- plumbing --------------------------------------------------------
async def _request(
self,
method: str,
path: str,
*,
user: str | None = None,
json_body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
raw: bool = False,
files: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
) -> Any: # noqa: ANN401
headers = {"X-ScaiDial-User": user} if user else {}
if params:
params = {k: v for k, v in params.items() if v is not None}
resp = await self._http.request(
method, path, headers=headers, json=json_body, params=params, files=files, data=data
)
if resp.status_code >= 400:
code, message = "http_error", resp.text[:300]
try:
payload = resp.json()
except ValueError:
payload = {}
if isinstance(payload.get("error"), dict):
code = payload["error"].get("code", code)
message = payload["error"].get("message", message)
elif "detail" in payload: # request validation (FastAPI shape)
code, message = "validation_error", json.dumps(payload["detail"])[:500]
raise ScaiDialWaveError(resp.status_code, code, message)
if raw:
return resp.content
if resp.status_code == 204 or not resp.content:
return None
return resp.json().get("data")
# -- events + rings --------------------------------------------------
async def list_events(self, after: str = "0", limit: int = 100) -> dict[str, Any]:
return await self._request("GET", "/events", params={"after": after, "limit": limit})
async def iter_events(
self, after: str = "0", page_size: int = 500
) -> AsyncIterator[dict[str, Any]]:
"""Yield every event after ``after`` (oldest first) until caught up."""
while True:
page = await self.list_events(after, page_size)
for event in page["items"]:
yield event
if len(page["items"]) < page_size:
return
after = page["last_id"]
async def list_rings(
self, user: str | None = None, tenant_id: str | None = None
) -> list[dict[str, Any]]:
data = await self._request("GET", "/rings", user=user, params={"tenant_id": tenant_id})
return data["items"]
async def accept_ring(
self, user: str, leg_id: str, device: str | None = None
) -> dict[str, Any]:
return await self._request(
"POST", f"/rings/{leg_id}/accept", user=user, json_body={"device": device}
)
async def decline_ring(
self,
user: str,
leg_id: str,
fallback: str = "voicemail",
forward_to: str | None = None,
) -> dict[str, Any]:
return await self._request(
"POST",
f"/rings/{leg_id}/decline",
user=user,
json_body={"fallback": fallback, "forward_to": forward_to},
)
# -- user + extensions -----------------------------------------------
async def me(self, user: str) -> dict[str, Any]:
return await self._request("GET", "/me", user=user)
async def get_extension(self, user: str, extension_id: str) -> dict[str, Any]:
return await self._request("GET", f"/extensions/{extension_id}", user=user)
async def update_extension(self, user: str, extension_id: str, **fields: Any) -> dict[str, Any]: # noqa: ANN401
"""PATCH settings, e.g. ``dnd=True``, ``ring_timeout_s=20``."""
return await self._request(
"PATCH", f"/extensions/{extension_id}", user=user, json_body=fields
)
async def list_forward_rules(self, user: str, extension_id: str) -> list[dict[str, Any]]:
data = await self._request("GET", f"/extensions/{extension_id}/forward-rules", user=user)
return data["items"]
async def create_forward_rule(
self,
user: str,
extension_id: str,
condition: str,
forward_to: str,
priority: int = 100,
enabled: bool = True,
) -> dict[str, Any]:
return await self._request(
"POST",
f"/extensions/{extension_id}/forward-rules",
user=user,
json_body={
"condition": condition,
"forward_to": forward_to,
"priority": priority,
"enabled": enabled,
},
)
async def delete_forward_rule(self, user: str, extension_id: str, rule_id: str) -> None:
await self._request(
"DELETE", f"/extensions/{extension_id}/forward-rules/{rule_id}", user=user
)
async def directory(self, user: str, q: str = "", limit: int = 20) -> list[dict[str, Any]]:
data = await self._request("GET", "/directory", user=user, params={"q": q, "limit": limit})
return data["items"]
# -- calls -----------------------------------------------------------
async def place_call(self, user: str, from_extension_id: str, to: str) -> dict[str, Any]:
return await self._request(
"POST",
"/calls",
user=user,
json_body={"from_extension_id": from_extension_id, "to": to},
)
async def active_calls(self, user: str) -> list[dict[str, Any]]:
return (await self._request("GET", "/calls/active", user=user))["items"]
async def call_history(
self, user: str, limit: int = 50, before: str | None = None
) -> list[dict[str, Any]]:
data = await self._request(
"GET", "/calls/history", user=user, params={"limit": limit, "before": before}
)
return data["items"]
async def rejoin_token(self, user: str, call_id: str) -> dict[str, Any]:
return await self._request("POST", f"/calls/{call_id}/token", user=user)
async def hangup(self, user: str, leg_id: str) -> None:
await self._request("POST", f"/legs/{leg_id}/hangup", user=user)
async def hold(self, user: str, leg_id: str) -> None:
await self._request("POST", f"/legs/{leg_id}/hold", user=user)
async def unhold(self, user: str, leg_id: str) -> None:
await self._request("POST", f"/legs/{leg_id}/unhold", user=user)
async def transfer(self, user: str, leg_id: str, to: str) -> dict[str, Any]:
return await self._request(
"POST", f"/legs/{leg_id}/transfer", user=user, json_body={"to": to, "mode": "blind"}
)
async def merge_calls(self, user: str, keep_leg_id: str, merge_leg_id: str) -> dict[str, Any]:
"""Three-way call: ``merge_leg_id``'s call joins ``keep_leg_id``'s."""
return await self._request(
"POST",
"/calls/merge",
user=user,
json_body={"keep_leg_id": keep_leg_id, "merge_leg_id": merge_leg_id},
)
async def conference(self, user: str, leg_id: str) -> dict[str, Any]:
return await self._request("GET", f"/legs/{leg_id}/conference", user=user)
async def conference_focus(self, user: str, leg_id: str, focus: str) -> dict[str, Any]:
"""``all`` (join), ``kept`` (split), ``<bridge_id>`` (swap), ``none`` (hold)."""
return await self._request(
"POST", f"/legs/{leg_id}/conference/focus", user=user, json_body={"focus": focus}
)
async def conference_drop(self, user: str, leg_id: str, bridge_id: str) -> dict[str, Any]:
return await self._request(
"POST", f"/legs/{leg_id}/conference/drop", user=user, json_body={"bridge_id": bridge_id}
)
async def moh_playlists(self, user: str) -> dict[str, Any]:
return await self._request("GET", "/moh/playlists", user=user)
async def moh_create_playlist(
self, user: str, name: str, shuffle: bool = True
) -> dict[str, Any]:
return await self._request(
"POST", "/moh/playlists", user=user, json_body={"name": name, "shuffle": shuffle}
)
async def moh_upload(
self,
user: str,
playlist_id: str,
filename: str,
data: bytes,
*,
title: str | None = None,
artist: str | None = None,
) -> dict[str, Any]:
"""Upload a song; the caller states the user confirmed the rights."""
form = {"rights_confirmed": "true"}
if title:
form["title"] = title
if artist:
form["artist"] = artist
return await self._request(
"POST",
f"/moh/playlists/{playlist_id}/tracks",
user=user,
files={"file": (filename, data)},
data=form,
)
async def start_attended_transfer(self, user: str, leg_id: str, to: str) -> dict[str, Any]:
"""Consult ``to`` first; returns ``{consult_id, state, ...}``."""
return await self._request(
"POST", f"/legs/{leg_id}/transfer", user=user, json_body={"to": to, "mode": "attended"}
)
async def transfer_status(self, user: str, consult_id: str) -> dict[str, Any]:
return await self._request("GET", f"/transfers/{consult_id}", user=user)
async def complete_transfer(self, user: str, consult_id: str) -> dict[str, Any]:
return await self._request("POST", f"/transfers/{consult_id}/complete", user=user)
async def cancel_transfer(self, user: str, consult_id: str) -> dict[str, Any]:
return await self._request("POST", f"/transfers/{consult_id}/cancel", user=user)
# -- voicemail -------------------------------------------------------
async def list_voicemail(
self,
user: str,
extension_id: str | None = None,
unheard: bool = False,
limit: int = 50,
) -> list[dict[str, Any]]:
data = await self._request(
"GET",
"/voicemail",
user=user,
params={"extension_id": extension_id, "unheard": str(unheard).lower(), "limit": limit},
)
return data["items"]
async def get_voicemail(self, user: str, voicemail_id: str) -> dict[str, Any]:
return await self._request("GET", f"/voicemail/{voicemail_id}", user=user)
async def voicemail_audio(self, user: str, voicemail_id: str) -> bytes:
"""WAV, 16 kHz mono."""
return await self._request("GET", f"/voicemail/{voicemail_id}/audio", user=user, raw=True)
async def mark_voicemail_listened(self, user: str, voicemail_id: str) -> None:
await self._request("POST", f"/voicemail/{voicemail_id}/listened", user=user)
async def delete_voicemail(self, user: str, voicemail_id: str) -> None:
await self._request("DELETE", f"/voicemail/{voicemail_id}", user=user)
# -- call recording, transcripts, live captions ------------------------
async def recording_control(self, user: str, call_id: str, action: str) -> dict[str, Any]:
"""``action``: start | pause | resume | stop. ``start`` returns once
the announcement has played. Returns the recording object."""
return await self._request("POST", f"/calls/{call_id}/recording/{action}", user=user)
async def captions(self, user: str, call_id: str, on: bool) -> dict[str, Any]:
"""Live captions on/off; they arrive in the LiveKit room as text
streams on topic ``lk.transcription``."""
action = "start" if on else "stop"
return await self._request("POST", f"/calls/{call_id}/captions/{action}", user=user)
async def list_recordings(
self,
user: str,
call_id: str | None = None,
extension_id: str | None = None,
before: str | None = None,
limit: int = 50,
) -> list[dict[str, Any]]:
data = await self._request(
"GET",
"/recordings",
user=user,
params={
"call_id": call_id,
"extension_id": extension_id,
"before": before,
"limit": limit,
},
)
return list(data["items"])
async def get_recording(self, user: str, recording_id: str) -> dict[str, Any]:
return await self._request("GET", f"/recordings/{recording_id}", user=user)
async def recording_audio(self, user: str, recording_id: str) -> bytes:
"""Ogg/Opus, 16 kHz mono. For playback in a client, proxy the
endpoint and forward the ``Range`` header instead."""
return await self._request("GET", f"/recordings/{recording_id}/audio", user=user, raw=True)
async def recording_transcript(self, user: str, recording_id: str) -> dict[str, Any]:
"""``{transcript_state, language, summary, text, turns}``."""
return await self._request("GET", f"/recordings/{recording_id}/transcript", user=user)
async def delete_recording(self, user: str, recording_id: str) -> None:
await self._request("DELETE", f"/recordings/{recording_id}", user=user)
|