intelligence-cloud 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.
@@ -0,0 +1,179 @@
1
+ """Errors raised by the SDK.
2
+
3
+ Everything the SDK raises derives from :class:`IntelligenceCloudError`. Errors returned by the API
4
+ derive from :class:`ApiError` and carry ``status``, ``code``, ``message`` and ``request_id``.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from typing import Any, List, Optional
10
+
11
+ EXTENSION_CONFLICT_MESSAGE = "Extension is already monitored at another location."
12
+ MFA_MESSAGE = "Integration users need MFA off for their company. API keys arrive in December 2026."
13
+
14
+
15
+ class IntelligenceCloudError(Exception):
16
+ """Base class for every SDK error."""
17
+
18
+
19
+ class InvalidRequestError(IntelligenceCloudError, ValueError):
20
+ """The request was refused by the SDK before it was sent (unknown filter, bad date, too many ids...)."""
21
+
22
+
23
+ class ApiError(IntelligenceCloudError):
24
+ """The API answered with an error status.
25
+
26
+ ``str(error)`` carries only the status, code and request id, plus text the SDK wrote itself
27
+ (``public_message``). The server's own text is on ``message``: it can echo phone numbers or other
28
+ values from the request, so keep it out of logs. Log ``status``, ``code`` and ``request_id``.
29
+ """
30
+
31
+ def __init__(self, status: int, code: Optional[str], message: str, request_id: Optional[str] = None,
32
+ *, public_message: Optional[str] = None):
33
+ self.status = status
34
+ self.code = code
35
+ self.message = message
36
+ self.request_id = request_id
37
+ self.public_message = public_message
38
+ super().__init__(self._text())
39
+
40
+ def _text(self) -> str:
41
+ parts = [f"HTTP {self.status}"]
42
+ if self.code:
43
+ parts.append(str(self.code))
44
+ text = " ".join(parts)
45
+ if self.public_message:
46
+ text += f": {self.public_message}"
47
+ if self.request_id:
48
+ text += f" (request_id {self.request_id})"
49
+ return text
50
+
51
+
52
+ class AuthError(ApiError):
53
+ """401: sign-in failed, or the token could not be renewed."""
54
+
55
+
56
+ class PasswordExpiredError(AuthError):
57
+ """The integration user's password has expired. A person sets a new one in the app; then update
58
+ your secret store and sign in again."""
59
+
60
+
61
+ class NotFoundError(ApiError):
62
+ """404. Also returned for records outside your login's scope."""
63
+
64
+ def _text(self) -> str:
65
+ return super()._text() + " Not found, or outside what this login can see."
66
+
67
+
68
+ class ConflictError(ApiError):
69
+ """409: duplicate name or email, already active or inactive, or an extension already monitored."""
70
+
71
+ def __init__(self, status: int, code: Optional[str], message: str, request_id: Optional[str] = None,
72
+ extensions: Optional[List[str]] = None, *, public_message: Optional[str] = None):
73
+ self.extensions: List[str] = extensions or []
74
+ super().__init__(status, code, message, request_id, public_message=public_message)
75
+
76
+
77
+ class ValidationError(ApiError):
78
+ """400 or 422: the request was malformed or a value was refused."""
79
+
80
+
81
+ class RateLimitError(ApiError):
82
+ """429 after the SDK's retries ran out."""
83
+
84
+ def __init__(self, status: int, code: Optional[str], message: str, request_id: Optional[str] = None,
85
+ retry_after: Optional[float] = None, *, public_message: Optional[str] = None):
86
+ self.retry_after = retry_after
87
+ super().__init__(status, code, message, request_id, public_message=public_message)
88
+
89
+
90
+ class MfaRequiredError(IntelligenceCloudError):
91
+ """Sign-in returned ``mfa_required``. Integration users need MFA off for their company."""
92
+
93
+ def __init__(self, message: str = MFA_MESSAGE):
94
+ super().__init__(message)
95
+
96
+
97
+ class FrontlineRequiredError(IntelligenceCloudError):
98
+ """Conversation data needs a frontline login. Admin logins see empty lists by design."""
99
+
100
+ def __init__(self, role: Optional[str]):
101
+ self.role = role
102
+ super().__init__(
103
+ f"This login has role {role!r}. Conversation data (calls, alerts, tasks, insights) needs a "
104
+ "frontline_user login; admin logins get empty lists."
105
+ )
106
+
107
+
108
+ class ConnectorError(IntelligenceCloudError):
109
+ """A connector ended in ``error``. ``state_reason`` says why (for example ``invalid_permissions``)."""
110
+
111
+ def __init__(self, connector: Any):
112
+ data = connector if isinstance(connector, dict) else {}
113
+ self.connector = data
114
+ self.connector_id = data.get("id")
115
+ self.status = data.get("status")
116
+ self.state_reason = data.get("state_reason")
117
+ self.status_message = data.get("status_message")
118
+ super().__init__(f"Connector {self.connector_id} is in error: {self.state_reason or 'unknown reason'}")
119
+
120
+
121
+ class ConnectorTimeoutError(IntelligenceCloudError):
122
+ """The connector did not reach a final status in time. Check it again later with get_connector."""
123
+
124
+ def __init__(self, connector: Any, waited: float):
125
+ data = connector if isinstance(connector, dict) else {}
126
+ self.connector = data
127
+ self.status = data.get("status")
128
+ super().__init__(f"Connector {data.get('id')} still {self.status!r} after {waited:.0f} s")
129
+
130
+
131
+ class ExtensionMappingError(IntelligenceCloudError):
132
+ """A workflow created or updated the user, but could not map the user's numbers.
133
+
134
+ The usual cause is a connector that is not ``active`` yet. Fix the connector, then run the workflow
135
+ again (it finds the user and carries on) or call ``sync_numbers``.
136
+ """
137
+
138
+ def __init__(self, user_id: Optional[str], cause: ApiError):
139
+ self.user_id = user_id
140
+ self.cause = cause
141
+ super().__init__(f"User {user_id}: numbers not mapped ({cause}). Number mappings need an active "
142
+ "connector and extensions no other location monitors.")
143
+
144
+
145
+ class WebhookPayloadError(IntelligenceCloudError, ValueError):
146
+ """The webhook body is not JSON, or is a malformed After Call event. Answer 400."""
147
+
148
+
149
+ class PayloadTooLargeError(WebhookPayloadError):
150
+ """The webhook body is larger than ``max_bytes``. Answer 413."""
151
+
152
+
153
+ _TOKEN_RE = re.compile(r"[0-9*#+]+")
154
+
155
+
156
+ def requested_numbers(body: Any) -> List[str]:
157
+ """Every number listed under ``monitored_numbers`` anywhere in a request body."""
158
+ out: List[str] = []
159
+ if isinstance(body, dict):
160
+ for key, value in body.items():
161
+ if key == "monitored_numbers" and isinstance(value, list):
162
+ out.extend(str(v) for v in value if str(v) not in out)
163
+ else:
164
+ out.extend(n for n in requested_numbers(value) if n not in out)
165
+ elif isinstance(body, list):
166
+ for value in body:
167
+ out.extend(n for n in requested_numbers(value) if n not in out)
168
+ return out
169
+
170
+
171
+ def extension_conflict_numbers(message: str, requested: Optional[List[str]] = None) -> List[str]:
172
+ """The requested extensions that the server's 409 message names. Nothing else from the message
173
+ is kept."""
174
+ wanted = set(requested or [])
175
+ seen: List[str] = []
176
+ for tok in _TOKEN_RE.findall(message or ""):
177
+ if tok in wanted and tok not in seen:
178
+ seen.append(tok)
179
+ return seen
@@ -0,0 +1,292 @@
1
+ """Conversation intelligence: calls, alerts, tasks, insights and webhook configuration."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from datetime import date, datetime
6
+ from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Sequence, Union
7
+
8
+ from . import _spec
9
+ from ._base import Namespace, Page, unwrap
10
+ from .errors import FrontlineRequiredError, InvalidRequestError
11
+
12
+ if TYPE_CHECKING: # pragma: no cover
13
+ from .client import Client
14
+
15
+ When = Union[str, datetime]
16
+ Ids = Union[str, Sequence[str]]
17
+
18
+
19
+ @dataclass
20
+ class RecordingLink:
21
+ """A signed link to the call's audio (WAV). No Authorization header is needed and Range requests
22
+ work. It expires 120 minutes after issue. Anyone holding it can download the audio: never log it."""
23
+
24
+ url: str = field(repr=False)
25
+ expires_at: Optional[datetime]
26
+
27
+
28
+ @dataclass
29
+ class WebhookTestResult:
30
+ """The outcome of a test send: whether the receiver answered 2xx, and its HTTP status."""
31
+
32
+ success: bool
33
+ http_status: Optional[int]
34
+
35
+
36
+ def _search_term(phone: Optional[str], text: Optional[str]) -> Optional[str]:
37
+ if phone is not None and text is not None:
38
+ raise InvalidRequestError("Pass phone or text, not both: the API has one search field")
39
+ term = phone if phone is not None else text
40
+ if term is None:
41
+ return None
42
+ term = str(term).strip()
43
+ if len(term) < 2:
44
+ raise InvalidRequestError("search terms need at least 2 characters (shorter ones are ignored by the API)")
45
+ return term
46
+
47
+
48
+ class Intelligence(Namespace):
49
+ """Read conversation data with a **frontline** login, and configure webhooks with an admin login."""
50
+
51
+ def __init__(self, client: "Client"):
52
+ super().__init__(client)
53
+ self._me: Optional[Dict[str, Any]] = None
54
+
55
+ # ------------------------------------------------------------------ account
56
+
57
+ def whoami(self) -> Dict[str, Any]:
58
+ """The signed-in user (``GET /me``): role, company, locations, products."""
59
+ self._me = unwrap(self._c.account.get_me()) or {}
60
+ return self._me
61
+
62
+ def require_frontline(self) -> Dict[str, Any]:
63
+ """Raise FrontlineRequiredError unless this is a frontline login (admins see empty lists)."""
64
+ me = self._me if self._me is not None else self.whoami()
65
+ if me.get("role") != "frontline_user":
66
+ raise FrontlineRequiredError(me.get("role"))
67
+ return me
68
+
69
+ # ------------------------------------------------------------------ calls
70
+
71
+ def _call_filters(self, phone, text, date_from, date_to, status, sentiment, has_open_tasks, multi_leg,
72
+ location_ids, company_id) -> Dict[str, Any]:
73
+ self.require_frontline()
74
+ return dict(search=_search_term(phone, text), date_from=date_from, date_to=date_to, status=status,
75
+ sentiment=sentiment, has_open_tasks=has_open_tasks, multi_leg=multi_leg,
76
+ location_id=location_ids, company_id=company_id)
77
+
78
+ def search_calls(self, phone: Optional[str] = None, text: Optional[str] = None,
79
+ date_from: Optional[When] = None, date_to: Optional[When] = None,
80
+ status: Optional[str] = None, sentiment: Optional[str] = None,
81
+ has_open_tasks: Optional[bool] = None, multi_leg: Optional[bool] = None,
82
+ location_ids: Optional[Ids] = None, *, company_id: Optional[str] = None,
83
+ limit: Optional[int] = None, cursor: Optional[str] = None) -> Page:
84
+ """One page of calls, newest first. ``phone`` and ``text`` both search (one or the other).
85
+
86
+ Without ``date_from`` the window starts at 00:00 UTC seven days ago.
87
+ """
88
+ f = self._call_filters(phone, text, date_from, date_to, status, sentiment, has_open_tasks, multi_leg,
89
+ location_ids, company_id)
90
+ return self._c.calls.list_calls(limit=limit, cursor=cursor, **f)
91
+
92
+ def iter_calls(self, phone: Optional[str] = None, text: Optional[str] = None,
93
+ date_from: Optional[When] = None, date_to: Optional[When] = None,
94
+ status: Optional[str] = None, sentiment: Optional[str] = None,
95
+ has_open_tasks: Optional[bool] = None, multi_leg: Optional[bool] = None,
96
+ location_ids: Optional[Ids] = None, *, company_id: Optional[str] = None) -> Iterator[Dict[str, Any]]:
97
+ """Every matching call, following cursors 100 at a time."""
98
+ f = self._call_filters(phone, text, date_from, date_to, status, sentiment, has_open_tasks, multi_leg,
99
+ location_ids, company_id)
100
+ return self._c.calls.iter_calls(**f)
101
+
102
+ def get_call(self, call_id: str) -> Dict[str, Any]:
103
+ """Call detail: summary, analysis, sentiment, tasks."""
104
+ self.require_frontline()
105
+ return unwrap(self._c.calls.get_call(call_id))
106
+
107
+ def get_transcript(self, call_id: str) -> List[Dict[str, Any]]:
108
+ """Transcript segments: ``time``, ``speaker`` ("Speaker 1"...), ``name``, ``text``."""
109
+ self.require_frontline()
110
+ data = unwrap(self._c.calls.get_call_transcript(call_id)) or {}
111
+ return data.get("transcript") or []
112
+
113
+ def get_recording_url(self, call_id: str) -> Optional[RecordingLink]:
114
+ """The call's recording link and its expiry, or None when the call has no recording.
115
+
116
+ Only the link and expiry are returned. Fetch a new link when it expires."""
117
+ self.require_frontline()
118
+ resp = self._c._request("getCall", {"callId": call_id}, {}, None)
119
+ link = _spec.recording_link(self._c._json(resp))
120
+ if link is None:
121
+ return None
122
+ expires = link.get("recording_url_expires_at")
123
+ try:
124
+ when = datetime.fromisoformat(_spec.format_datetime(expires, "expires_at").replace("Z", "+00:00")) \
125
+ if expires else None
126
+ except (ValueError, InvalidRequestError):
127
+ when = None
128
+ return RecordingLink(url=link["recording_url"], expires_at=when)
129
+
130
+ # ------------------------------------------------------------------ alerts
131
+
132
+ def _alert_filters(self, alert_name, numbers, text, sentiment, date_from, date_to, location_ids, topic,
133
+ company_id) -> Dict[str, Any]:
134
+ self.require_frontline()
135
+ if numbers is not None and isinstance(numbers, str):
136
+ numbers = [numbers]
137
+ return dict(keyword=alert_name, numbers=numbers, search=_search_term(None, text), sentiment=sentiment,
138
+ date_from=date_from, date_to=date_to, location_id=location_ids, topic=topic,
139
+ company_id=company_id)
140
+
141
+ def search_alerts(self, alert_name: Optional[str] = None, numbers: Optional[Sequence[str]] = None,
142
+ text: Optional[str] = None, sentiment: Optional[str] = None,
143
+ date_from: Optional[When] = None, date_to: Optional[When] = None,
144
+ location_ids: Optional[Ids] = None, *, topic: Optional[str] = None,
145
+ company_id: Optional[str] = None, limit: Optional[int] = None,
146
+ cursor: Optional[str] = None) -> Page:
147
+ """One page of First Alert hits, newest first.
148
+
149
+ ``alert_name`` is the exact, case-sensitive rule name. ``numbers`` (up to 25) match caller or
150
+ callee by substring; formatting is stripped for you.
151
+ """
152
+ f = self._alert_filters(alert_name, numbers, text, sentiment, date_from, date_to, location_ids, topic,
153
+ company_id)
154
+ return self._c.alerts.list_alerts(limit=limit, cursor=cursor, **f)
155
+
156
+ def iter_alerts(self, alert_name: Optional[str] = None, numbers: Optional[Sequence[str]] = None,
157
+ text: Optional[str] = None, sentiment: Optional[str] = None,
158
+ date_from: Optional[When] = None, date_to: Optional[When] = None,
159
+ location_ids: Optional[Ids] = None, *, topic: Optional[str] = None,
160
+ company_id: Optional[str] = None) -> Iterator[Dict[str, Any]]:
161
+ f = self._alert_filters(alert_name, numbers, text, sentiment, date_from, date_to, location_ids, topic,
162
+ company_id)
163
+ return self._c.alerts.iter_alerts(**f)
164
+
165
+ def get_alert(self, alert_id: str, with_call: bool = False) -> Optional[Dict[str, Any]]:
166
+ """One alert by id (searched by id, no date window). With ``with_call`` the call detail is
167
+ added under ``call``. Returns None when the alert is not visible."""
168
+ self.require_frontline()
169
+ aid = alert_id.strip().lower()
170
+ page = self._c.alerts.list_alerts(search=aid, limit=10)
171
+ alert = next((a for a in page.items if a.get("id") == aid), None)
172
+ if alert is not None and with_call and alert.get("call_id"):
173
+ alert = dict(alert)
174
+ alert["call"] = self.get_call(alert["call_id"])
175
+ return alert
176
+
177
+ def get_alerts_dashboard(self, date_from: Optional[When] = None, date_to: Optional[When] = None,
178
+ location_ids: Optional[Ids] = None, *,
179
+ company_id: Optional[str] = None) -> Dict[str, Any]:
180
+ self.require_frontline()
181
+ return unwrap(self._c.alerts.get_alerts_dashboard(date_from=date_from, date_to=date_to,
182
+ location_id=location_ids, company_id=company_id))
183
+
184
+ # ------------------------------------------------------------------ tasks
185
+
186
+ def _task_filters(self, kw: Dict[str, Any]) -> Dict[str, Any]:
187
+ self.require_frontline()
188
+ kw["location_id"] = kw.pop("location_ids")
189
+ return kw
190
+
191
+ def list_tasks(self, status: Optional[str] = None, call_id: Optional[str] = None,
192
+ task_id: Optional[str] = None, due_on: Optional[Union[str, date]] = None,
193
+ date_from: Optional[When] = None, date_to: Optional[When] = None,
194
+ search: Optional[str] = None, location_ids: Optional[Ids] = None, *,
195
+ today_start: Optional[When] = None, company_id: Optional[str] = None,
196
+ limit: Optional[int] = None, cursor: Optional[str] = None) -> Page:
197
+ """One page of follow-up tasks. ``date_from``/``date_to`` filter on creation time; no default window."""
198
+ f = self._task_filters(dict(status=status, call_id=call_id, task_id=task_id, due_on=due_on,
199
+ date_from=date_from, date_to=date_to, search=_search_term(None, search),
200
+ location_ids=location_ids, today_start=today_start, company_id=company_id))
201
+ return self._c.tasks.list_tasks(limit=limit, cursor=cursor, **f)
202
+
203
+ def iter_tasks(self, status: Optional[str] = None, call_id: Optional[str] = None,
204
+ task_id: Optional[str] = None, due_on: Optional[Union[str, date]] = None,
205
+ date_from: Optional[When] = None, date_to: Optional[When] = None,
206
+ search: Optional[str] = None, location_ids: Optional[Ids] = None, *,
207
+ today_start: Optional[When] = None,
208
+ company_id: Optional[str] = None) -> Iterator[Dict[str, Any]]:
209
+ f = self._task_filters(dict(status=status, call_id=call_id, task_id=task_id, due_on=due_on,
210
+ date_from=date_from, date_to=date_to, search=_search_term(None, search),
211
+ location_ids=location_ids, today_start=today_start, company_id=company_id))
212
+ return self._c.tasks.iter_tasks(**f)
213
+
214
+ # ------------------------------------------------------------------ insights
215
+
216
+ def get_insights_dashboard(self, start: When, end: When, trending_limit: Optional[int] = None,
217
+ location_ids: Optional[Ids] = None, *,
218
+ company_id: Optional[str] = None) -> Dict[str, Any]:
219
+ """Insights Hub dashboard for a window (both ends required, at most 366 days)."""
220
+ self.require_frontline()
221
+ if trending_limit is not None and not 1 <= trending_limit <= 10:
222
+ raise InvalidRequestError("trending_limit: 1 to 10")
223
+ return unwrap(self._c.insights.get_insights_dashboard(start=start, end=end, trending_limit=trending_limit,
224
+ location_id=location_ids, company_id=company_id))
225
+
226
+ def list_topic_calls(self, slug: str, date_from: Optional[When] = None, date_to: Optional[When] = None,
227
+ sentiment: Optional[str] = None, outcome: Optional[str] = None,
228
+ search: Optional[str] = None, location_ids: Optional[Ids] = None, *,
229
+ company_id: Optional[str] = None, limit: Optional[int] = None,
230
+ cursor: Optional[str] = None) -> Page:
231
+ """Calls for one topic (slug from the dashboard's ``topic_call_volumes``)."""
232
+ self.require_frontline()
233
+ return self._c.insights.list_topic_calls(slug, date_from=date_from, date_to=date_to, sentiment=sentiment,
234
+ outcome=outcome, search=_search_term(None, search),
235
+ location_id=location_ids, company_id=company_id, limit=limit,
236
+ cursor=cursor)
237
+
238
+ def iter_topic_calls(self, slug: str, date_from: Optional[When] = None, date_to: Optional[When] = None,
239
+ sentiment: Optional[str] = None, outcome: Optional[str] = None,
240
+ search: Optional[str] = None, location_ids: Optional[Ids] = None, *,
241
+ company_id: Optional[str] = None) -> Iterator[Dict[str, Any]]:
242
+ self.require_frontline()
243
+ return self._c.insights.iter_topic_calls(slug, date_from=date_from, date_to=date_to, sentiment=sentiment,
244
+ outcome=outcome, search=_search_term(None, search),
245
+ location_id=location_ids, company_id=company_id)
246
+
247
+ # ------------------------------------------------------------------ webhook configuration (admin)
248
+
249
+ def get_after_call_webhook(self, location_id: str) -> Optional[Dict[str, Any]]:
250
+ """The location's After Call webhook (``webhook_url``, ``enabled``), or None when not set."""
251
+ return unwrap(self._c.webhooks.get_after_call_webhook(location_id))
252
+
253
+ def set_after_call_webhook(self, location_id: str, url: str, enabled: bool = True) -> Dict[str, Any]:
254
+ """Set the After Call webhook (HTTPS). It receives every call at the location. Pause with
255
+ ``enabled=False``; there is no delete."""
256
+ _https(url)
257
+ return unwrap(self._c.webhooks.save_after_call_webhook(location_id, {"webhook_url": url, "enabled": enabled}))
258
+
259
+ def test_after_call_webhook(self, location_id: str) -> WebhookTestResult:
260
+ """Send the test payload to the saved URL."""
261
+ data = unwrap(self._c.webhooks.test_after_call_webhook(location_id)) or {}
262
+ return WebhookTestResult(bool(data.get("success")), data.get("http_status"))
263
+
264
+ def get_first_alert_webhook(self, location_id: str) -> Optional[str]:
265
+ """The First Alert location webhook URL, or None."""
266
+ return (unwrap(self._c.first_alert.get_first_alert_config(location_id)) or {}).get("webhook_url")
267
+
268
+ def set_first_alert_webhook(self, location_id: str, url: Optional[str]) -> Dict[str, Any]:
269
+ """Set (or clear with None) the First Alert location webhook. Monitored numbers are kept."""
270
+ if url is not None:
271
+ _https(url)
272
+ fa = self._c.first_alert
273
+ cfg = unwrap(fa.get_first_alert_config(location_id)) or {}
274
+ from .resources import merge_mappings
275
+ mappings: List[Dict[str, Any]] = []
276
+ for m in cfg.get("connector_mappings") or []:
277
+ mappings = merge_mappings(mappings, m["connector_id"], add=m.get("monitored_numbers") or [])
278
+ return unwrap(fa.save_first_alert_config(location_id, {"webhook_url": url, "connector_mappings": mappings}))
279
+
280
+ def test_first_alert_webhook(self, location_id: str, url: Optional[str] = None) -> WebhookTestResult:
281
+ """Send a test to ``url`` (default: the saved URL)."""
282
+ target = url or self.get_first_alert_webhook(location_id)
283
+ if not target:
284
+ raise InvalidRequestError("No First Alert webhook URL is set for this location")
285
+ _https(target)
286
+ data = unwrap(self._c.first_alert.test_first_alert_webhook(location_id, {"url": target})) or {}
287
+ return WebhookTestResult(bool(data.get("success")), data.get("status_code"))
288
+
289
+
290
+ def _https(url: str) -> None:
291
+ if not isinstance(url, str) or not url.lower().startswith("https://"):
292
+ raise InvalidRequestError("Webhook URLs must use HTTPS")
File without changes
@@ -0,0 +1,197 @@
1
+ """Receive the After Call webhook: parse the event and drop duplicates.
2
+
3
+ The webhook sends every call at the location, unsigned. Use an unguessable HTTPS URL, answer 2xx
4
+ within 2 seconds and do the work afterwards. Treat an event as a notification: read the call with
5
+ ``client.intelligence.get_call(event.call.id)`` before you write it anywhere. Expect repeats of the
6
+ same ``call.id``; upsert on it. Event types you don't handle come back as :class:`UnknownEvent`:
7
+ answer 2xx and ignore them.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import threading
13
+ from collections import OrderedDict
14
+ from dataclasses import dataclass, field
15
+ from datetime import date, datetime, timezone
16
+ from typing import Any, Dict, List, Mapping, Optional, Protocol, Union
17
+
18
+ from . import _spec
19
+ from .errors import PayloadTooLargeError, WebhookPayloadError
20
+
21
+ AFTER_CALL_EVENT_TYPE = "end_of_call_summary"
22
+ MAX_EVENT_BYTES = 262_144 # 256 KB; answer 413 to anything larger
23
+
24
+
25
+ @dataclass
26
+ class AfterCallCall:
27
+ id: str
28
+ call_type: str
29
+ duration_seconds: int
30
+ call_date: date
31
+ caller_name: Optional[str] = None
32
+ caller_number: Optional[str] = None
33
+ callee_name: Optional[str] = None
34
+ callee_number: Optional[str] = None
35
+ platform: Optional[str] = None
36
+
37
+
38
+ @dataclass
39
+ class AfterCallSummary:
40
+ text: Optional[str] = None
41
+ sentiment: Optional[str] = None
42
+ key_points: List[str] = field(default_factory=list)
43
+ action_items: List[str] = field(default_factory=list)
44
+
45
+
46
+ @dataclass
47
+ class AfterCallLocation:
48
+ id: str
49
+ company_id: Optional[str] = None
50
+ connector_id: Optional[str] = None
51
+
52
+
53
+ @dataclass
54
+ class AfterCallEvent:
55
+ """An ``end_of_call_summary`` event. Fetch full detail with ``client.intelligence.get_call(event.call.id)``."""
56
+
57
+ version: str
58
+ type: str
59
+ is_test: bool
60
+ location_id: str
61
+ timestamp: datetime
62
+ call: AfterCallCall
63
+ location: AfterCallLocation
64
+ summary: Optional[AfterCallSummary] = None
65
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
66
+
67
+
68
+ @dataclass
69
+ class UnknownEvent:
70
+ """A delivery whose ``type`` this SDK version does not handle. Answer 2xx and ignore it."""
71
+
72
+ type: Optional[str]
73
+ version: Optional[str]
74
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
75
+
76
+
77
+ def _req(d: Mapping[str, Any], key: str, typ: Any, where: str) -> Any:
78
+ if key not in d:
79
+ raise WebhookPayloadError(f"{where}.{key} is missing")
80
+ v = d[key]
81
+ if typ is int and isinstance(v, bool):
82
+ raise WebhookPayloadError(f"{where}.{key} has the wrong type")
83
+ if not isinstance(v, typ):
84
+ raise WebhookPayloadError(f"{where}.{key} has the wrong type")
85
+ return v
86
+
87
+
88
+ def _ts(value: str, where: str) -> datetime:
89
+ try:
90
+ return datetime.fromisoformat(value.replace("Z", "+00:00").replace("z", "+00:00")).astimezone(timezone.utc)
91
+ except (ValueError, AttributeError):
92
+ try:
93
+ return datetime.fromisoformat(_spec.format_datetime(value, where).replace("Z", "+00:00"))
94
+ except Exception:
95
+ raise WebhookPayloadError(f"{where} is not an RFC 3339 timestamp") from None
96
+
97
+
98
+ def parse_after_call_event(body: Union[bytes, str, Mapping[str, Any]],
99
+ max_bytes: int = MAX_EVENT_BYTES) -> Union[AfterCallEvent, UnknownEvent]:
100
+ """Parse and check an After Call webhook body. Fields outside the published schema are dropped.
101
+
102
+ Returns :class:`AfterCallEvent`, or :class:`UnknownEvent` for any other event type (answer 2xx and
103
+ ignore it). Raises :class:`PayloadTooLargeError` (answer 413) for a body over ``max_bytes`` and
104
+ :class:`WebhookPayloadError` (answer 400) for a body that is not JSON or a malformed After Call event.
105
+ """
106
+ if isinstance(body, str):
107
+ body = body.encode("utf-8")
108
+ if isinstance(body, (bytes, bytearray)):
109
+ if max_bytes and len(body) > max_bytes:
110
+ raise PayloadTooLargeError(f"body is larger than {max_bytes} bytes")
111
+ try:
112
+ body = json.loads(bytes(body).decode("utf-8"))
113
+ except (ValueError, UnicodeDecodeError):
114
+ raise WebhookPayloadError("body is not JSON") from None
115
+ if not isinstance(body, Mapping):
116
+ raise WebhookPayloadError("body is not a JSON object")
117
+ if body.get("type") != AFTER_CALL_EVENT_TYPE:
118
+ typ, ver = body.get("type"), body.get("version")
119
+ return UnknownEvent(type=typ if isinstance(typ, str) else None,
120
+ version=ver if isinstance(ver, str) else None, raw=dict(body))
121
+ data = _spec.project(dict(body), _spec.schema_by_name("AfterCallSummaryEvent"))
122
+ call = _req(data, "call", dict, "event")
123
+ loc = _req(data, "location", dict, "event")
124
+ try:
125
+ call_date = date.fromisoformat(_req(call, "call_date", str, "call"))
126
+ except ValueError:
127
+ raise WebhookPayloadError("call.call_date is not YYYY-MM-DD") from None
128
+ summary = data.get("summary")
129
+ return AfterCallEvent(
130
+ version=_req(data, "version", str, "event"),
131
+ type=data["type"],
132
+ is_test=_req(data, "is_test", bool, "event"),
133
+ location_id=_req(data, "location_id", str, "event"),
134
+ timestamp=_ts(_req(data, "timestamp", str, "event"), "timestamp"),
135
+ call=AfterCallCall(
136
+ id=_req(call, "id", str, "call"),
137
+ call_type=_req(call, "call_type", str, "call"),
138
+ duration_seconds=_req(call, "duration_seconds", int, "call"),
139
+ call_date=call_date,
140
+ caller_name=call.get("caller_name"),
141
+ caller_number=call.get("caller_number"),
142
+ callee_name=call.get("callee_name"),
143
+ callee_number=call.get("callee_number"),
144
+ platform=call.get("platform"),
145
+ ),
146
+ location=AfterCallLocation(id=loc.get("id") or data["location_id"], company_id=loc.get("company_id"),
147
+ connector_id=loc.get("connector_id")),
148
+ summary=AfterCallSummary(
149
+ text=summary.get("text"), sentiment=summary.get("sentiment"),
150
+ key_points=list(summary.get("key_points") or []), action_items=list(summary.get("action_items") or []),
151
+ ) if isinstance(summary, dict) else None,
152
+ raw=data,
153
+ )
154
+
155
+
156
+ class DedupStore(Protocol):
157
+ """Remembers which keys were seen. ``add`` returns True when the key is new."""
158
+
159
+ def add(self, key: str) -> bool: ...
160
+
161
+
162
+ class MemoryDedupStore:
163
+ """In-memory LRU of the most recent keys (process-local)."""
164
+
165
+ def __init__(self, max_size: int = 10_000):
166
+ self.max_size = max_size
167
+ self._keys: "OrderedDict[str, None]" = OrderedDict()
168
+ self._lock = threading.Lock()
169
+
170
+ def add(self, key: str) -> bool:
171
+ with self._lock:
172
+ if key in self._keys:
173
+ self._keys.move_to_end(key)
174
+ return False
175
+ self._keys[key] = None
176
+ if len(self._keys) > self.max_size:
177
+ self._keys.popitem(last=False)
178
+ return True
179
+
180
+
181
+ class Deduplicator:
182
+ """Spots repeat deliveries of the same call. Pass a shared ``store`` when you run several workers.
183
+
184
+ The same name and meaning in every SDK: ``is_duplicate`` (Python), ``isDuplicate`` (PHP,
185
+ TypeScript) returns True for a repeat. A repeat can carry newer data: when you keep a copy, upsert
186
+ on ``call.id`` rather than dropping the later delivery.
187
+ """
188
+
189
+ def __init__(self, max_size: int = 10_000, store: Optional[DedupStore] = None):
190
+ self.store = store or MemoryDedupStore(max_size)
191
+
192
+ def is_duplicate(self, event_or_call_id: Union[AfterCallEvent, str]) -> bool:
193
+ """True if this call was seen before; otherwise records it and returns False."""
194
+ key = event_or_call_id.call.id if isinstance(event_or_call_id, AfterCallEvent) else str(event_or_call_id)
195
+ if not key:
196
+ raise ValueError("a call id is required")
197
+ return not self.store.add(key)