donsoft-connect 1.0.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,302 @@
1
+ """Donsoft Connect server SDK (standard library only).
2
+
3
+ from donsoft_connect import Client, verify_webhook, user_hash
4
+
5
+ client = Client(api_key="dck_...", base_url="https://api.example.com")
6
+ client.conversations.send(conversation_id, "Your order has shipped")
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import random
14
+ import time
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from typing import Any, Dict, List, Mapping, Optional, Union
19
+
20
+ __all__ = [
21
+ "Client",
22
+ "DonsoftError",
23
+ "verify_webhook",
24
+ "construct_webhook_event",
25
+ "sign_webhook",
26
+ "user_hash",
27
+ "SDK_NAME",
28
+ "SDK_VERSION",
29
+ ]
30
+
31
+ SDK_NAME = "python"
32
+ SDK_VERSION = "1.0.0"
33
+
34
+ JSON = Any
35
+ Bytes = Union[str, bytes, bytearray]
36
+
37
+
38
+ class DonsoftError(Exception):
39
+ """API error. ``status`` is the HTTP status (0 for network errors and timeouts)."""
40
+
41
+ def __init__(self, message: str, status: int, body: Any = None) -> None:
42
+ super().__init__(message)
43
+ self.message = message
44
+ self.status = status
45
+ self.body = body
46
+
47
+ def __repr__(self) -> str: # pragma: no cover
48
+ return f"DonsoftError(status={self.status}, message={self.message!r})"
49
+
50
+
51
+ def _public_base(base_url: str) -> str:
52
+ u = base_url.rstrip("/")
53
+ if u.endswith("/api/v1/public"):
54
+ return u
55
+ if u.endswith("/api/v1"):
56
+ return u + "/public"
57
+ return u + "/api/v1/public"
58
+
59
+
60
+ def _query(params: Optional[Mapping[str, Any]]) -> str:
61
+ if not params:
62
+ return ""
63
+ clean = {k: (str(v).lower() if isinstance(v, bool) else str(v)) for k, v in params.items() if v is not None and v != ""}
64
+ return ("?" + urllib.parse.urlencode(clean)) if clean else ""
65
+
66
+
67
+ def _q(s: str) -> str:
68
+ return urllib.parse.quote(str(s), safe="")
69
+
70
+
71
+ class Client:
72
+ """Public REST API client (``Authorization: Bearer dck_...``, base ``API/api/v1/public``).
73
+
74
+ Retries 429, 5xx (writes: only 502/503/504) and network errors (reads only) with backoff.
75
+ """
76
+
77
+ def __init__(self, api_key: str, base_url: str, *, max_retries: int = 3, timeout: float = 30.0) -> None:
78
+ if not api_key:
79
+ raise ValueError("api_key is required")
80
+ if not base_url:
81
+ raise ValueError("base_url is required")
82
+ self.api_key = api_key
83
+ self.base = _public_base(base_url)
84
+ self.max_retries = max_retries
85
+ self.timeout = timeout
86
+ self.conversations = _Conversations(self)
87
+ self.customers = _Customers(self)
88
+ self.tickets = _Tickets(self)
89
+
90
+ def request(self, method: str, path: str, body: Optional[Mapping[str, Any]] = None) -> JSON:
91
+ idempotent = method in ("GET", "DELETE")
92
+ data = json.dumps(body).encode("utf-8") if body is not None else None
93
+ headers = {
94
+ "Authorization": f"Bearer {self.api_key}",
95
+ "Accept": "application/json",
96
+ "User-Agent": f"donsoft-connect-python/{SDK_VERSION}",
97
+ }
98
+ if data is not None:
99
+ headers["Content-Type"] = "application/json"
100
+ attempt = 0
101
+ while True:
102
+ req = urllib.request.Request(self.base + path, data=data, method=method, headers=headers)
103
+ try:
104
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
105
+ raw = res.read()
106
+ return json.loads(raw) if raw else None
107
+ except urllib.error.HTTPError as e:
108
+ raw = e.read()
109
+ try:
110
+ parsed: Any = json.loads(raw) if raw else None
111
+ except ValueError:
112
+ parsed = raw.decode("utf-8", "replace")
113
+ status = e.code
114
+ retryable = status == 429 or (status >= 500 and (idempotent or status in (502, 503, 504)))
115
+ if retryable and attempt < self.max_retries:
116
+ time.sleep(self._retry_after(e.headers.get("Retry-After"), attempt))
117
+ attempt += 1
118
+ continue
119
+ msg = parsed.get("message") if isinstance(parsed, dict) else None
120
+ if isinstance(msg, list):
121
+ msg = "; ".join(str(m) for m in msg)
122
+ raise DonsoftError(str(msg) if msg else f"HTTP {status}", status, parsed) from None
123
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
124
+ if idempotent and attempt < self.max_retries:
125
+ time.sleep(self._backoff(attempt))
126
+ attempt += 1
127
+ continue
128
+ raise DonsoftError(f"Network error: {getattr(e, 'reason', e)}", 0) from None
129
+
130
+ @staticmethod
131
+ def _backoff(attempt: int) -> float:
132
+ return min(0.5 * (2 ** attempt), 8.0) * (0.75 + random.random() * 0.5)
133
+
134
+ def _retry_after(self, header: Optional[str], attempt: int) -> float:
135
+ try:
136
+ v = float(header) if header else 0.0
137
+ except ValueError:
138
+ v = 0.0
139
+ return min(v, 60.0) if v > 0 else self._backoff(attempt)
140
+
141
+
142
+ class _Conversations:
143
+ def __init__(self, c: Client) -> None:
144
+ self._c = c
145
+
146
+ def list(
147
+ self,
148
+ *,
149
+ status: Optional[str] = None,
150
+ assignee: Optional[str] = None,
151
+ channel_id: Optional[str] = None,
152
+ customer_id: Optional[str] = None,
153
+ q: Optional[str] = None,
154
+ before: Optional[str] = None,
155
+ ) -> List[Dict[str, Any]]:
156
+ """Up to 100 conversations, newest activity first. Page back with ``before`` (ISO time)."""
157
+ params = {"status": status, "assignee": assignee, "channelId": channel_id, "customerId": customer_id, "q": q, "before": before}
158
+ return self._c.request("GET", "/conversations" + _query(params))
159
+
160
+ def messages(self, conversation_id: str) -> List[Dict[str, Any]]:
161
+ return self._c.request("GET", f"/conversations/{_q(conversation_id)}/messages")
162
+
163
+ def send(self, conversation_id: str, body: str) -> Dict[str, Any]:
164
+ """Send a message to the customer as the business."""
165
+ return self._c.request("POST", f"/conversations/{_q(conversation_id)}/messages", {"body": body})
166
+
167
+
168
+ class _Customers:
169
+ def __init__(self, c: Client) -> None:
170
+ self._c = c
171
+
172
+ def get(self, customer_id: str) -> Dict[str, Any]:
173
+ return self._c.request("GET", f"/customers/{_q(customer_id)}")
174
+
175
+
176
+ class _Tickets:
177
+ def __init__(self, c: Client) -> None:
178
+ self._c = c
179
+
180
+ def list(
181
+ self,
182
+ *,
183
+ status: Optional[str] = None,
184
+ assignee: Optional[str] = None,
185
+ q: Optional[str] = None,
186
+ page: Optional[int] = None,
187
+ page_size: Optional[int] = None,
188
+ ) -> List[Dict[str, Any]]:
189
+ """One page of tickets (default status ``active``; ``page_size`` up to 100)."""
190
+ params = {"status": status, "assignee": assignee, "q": q, "page": page, "pageSize": page_size}
191
+ return self._c.request("GET", "/tickets" + _query(params))
192
+
193
+ def create(
194
+ self,
195
+ subject: str,
196
+ *,
197
+ description: Optional[str] = None,
198
+ priority: Optional[str] = None,
199
+ category: Optional[str] = None,
200
+ conversation_id: Optional[str] = None,
201
+ customer_id: Optional[str] = None,
202
+ assignee_id: Optional[str] = None,
203
+ ) -> Dict[str, Any]:
204
+ body = {
205
+ "subject": subject,
206
+ "description": description,
207
+ "priority": priority,
208
+ "category": category,
209
+ "conversationId": conversation_id,
210
+ "customerId": customer_id,
211
+ "assigneeId": assignee_id,
212
+ }
213
+ return self._c.request("POST", "/tickets", {k: v for k, v in body.items() if v is not None})
214
+
215
+ def update(
216
+ self,
217
+ ticket_id: str,
218
+ *,
219
+ subject: Optional[str] = None,
220
+ description: Optional[str] = None,
221
+ status: Optional[str] = None,
222
+ priority: Optional[str] = None,
223
+ category: Optional[str] = None,
224
+ assignee_id: Optional[str] = None,
225
+ unassign: Optional[bool] = None,
226
+ ) -> Dict[str, Any]:
227
+ body = {
228
+ "subject": subject,
229
+ "description": description,
230
+ "status": status,
231
+ "priority": priority,
232
+ "category": category,
233
+ "assigneeId": assignee_id,
234
+ "unassign": unassign,
235
+ }
236
+ return self._c.request("PATCH", f"/tickets/{_q(ticket_id)}", {k: v for k, v in body.items() if v is not None})
237
+
238
+
239
+ # ─── Webhooks ────────────────────────────────────────────────────────
240
+
241
+
242
+ def _b(v: Bytes) -> bytes:
243
+ return v.encode("utf-8") if isinstance(v, str) else bytes(v)
244
+
245
+
246
+ def verify_webhook(
247
+ raw_body: Bytes,
248
+ signature_header: Optional[str],
249
+ secret: str,
250
+ tolerance_seconds: int = 300,
251
+ now: Optional[int] = None,
252
+ ) -> bool:
253
+ """Check ``X-Connect-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>``.
254
+
255
+ Pass the RAW request body. Rejects timestamps more than ``tolerance_seconds`` away from now.
256
+ """
257
+ if not signature_header or not secret:
258
+ return False
259
+ t: Optional[int] = None
260
+ sigs: List[str] = []
261
+ for part in signature_header.split(","):
262
+ k, sep, v = part.partition("=")
263
+ if not sep:
264
+ continue
265
+ k, v = k.strip(), v.strip()
266
+ if k == "t":
267
+ try:
268
+ t = int(v)
269
+ except ValueError:
270
+ return False
271
+ elif k == "v1":
272
+ sigs.append(v)
273
+ if t is None or not sigs:
274
+ return False
275
+ now = int(time.time()) if now is None else now
276
+ if abs(now - t) > tolerance_seconds:
277
+ return False
278
+ expected = hmac.new(_b(secret), str(t).encode() + b"." + _b(raw_body), hashlib.sha256).hexdigest()
279
+ return any(hmac.compare_digest(expected, s.lower()) for s in sigs)
280
+
281
+
282
+ def construct_webhook_event(raw_body: Bytes, signature_header: Optional[str], secret: str, tolerance_seconds: int = 300) -> Dict[str, Any]:
283
+ """Verify and parse. Raises ``DonsoftError`` (status 400) on a bad signature."""
284
+ if not verify_webhook(raw_body, signature_header, secret, tolerance_seconds):
285
+ raise DonsoftError("Invalid webhook signature", 400)
286
+ return json.loads(_b(raw_body).decode("utf-8"))
287
+
288
+
289
+ def sign_webhook(raw_body: Bytes, secret: str, timestamp: Optional[int] = None) -> str:
290
+ """Build a signature header (for testing your own handler)."""
291
+ t = int(time.time()) if timestamp is None else timestamp
292
+ sig = hmac.new(_b(secret), str(t).encode() + b"." + _b(raw_body), hashlib.sha256).hexdigest()
293
+ return f"t={t},v1={sig}"
294
+
295
+
296
+ # ─── Identity ────────────────────────────────────────────────────────
297
+
298
+
299
+ def user_hash(secret: str, user_id: Union[str, int]) -> str:
300
+ """``hex(HMAC_SHA256(identity_secret, user_id))`` for ``identify({userId, userHash})``. Server side only."""
301
+ return hmac.new(_b(secret), str(user_id).encode("utf-8"), hashlib.sha256).hexdigest()
302
+
File without changes
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: donsoft-connect
3
+ Version: 1.0.0
4
+ Summary: Donsoft Connect server SDK: public REST API client, webhook signature check, identity userHash. Standard library only.
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/donsoft/donsoft-connect/tree/main/sdks/python
7
+ Project-URL: Source, https://github.com/donsoft/donsoft-connect
8
+ Keywords: donsoft,customer-support,webhooks,api-client
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Typing :: Typed
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # donsoft-connect (Python)
18
+
19
+ Server SDK for Donsoft Connect: the public REST API, webhook signature check, and the identity
20
+ `user_hash` helper. Python 3.8+, standard library only.
21
+
22
+ ```bash
23
+ pip install donsoft-connect
24
+ ```
25
+
26
+ ## REST API
27
+
28
+ ```python
29
+ from donsoft_connect import Client, DonsoftError
30
+
31
+ dc = Client(api_key=os.environ["DONSOFT_API_KEY"], base_url="https://api.example.com")
32
+
33
+ convs = dc.conversations.list(status="open", q="refund")
34
+ msgs = dc.conversations.messages(convs[0]["id"])
35
+ dc.conversations.send(convs[0]["id"], "Your order has shipped")
36
+
37
+ customer = dc.customers.get(convs[0]["customer"]["id"])
38
+
39
+ tickets = dc.tickets.list(status="active", page=1, page_size=50)
40
+ t = dc.tickets.create("Refund for #1234", priority="high", conversation_id=convs[0]["id"])
41
+ dc.tickets.update(t["id"], status="resolved")
42
+
43
+ try:
44
+ dc.customers.get("00000000-0000-0000-0000-000000000000")
45
+ except DonsoftError as e:
46
+ print(e.status, e.message)
47
+ ```
48
+
49
+ `Client(api_key, base_url, *, max_retries=3, timeout=30.0)`. 429 and 5xx are retried with
50
+ exponential backoff (honouring `Retry-After`); writes only on 429/502/503/504.
51
+
52
+ ## Webhooks
53
+
54
+ ```python
55
+ from donsoft_connect import verify_webhook
56
+
57
+ # Flask
58
+ @app.post("/webhooks/donsoft")
59
+ def hook():
60
+ if not verify_webhook(request.get_data(), request.headers.get("X-Connect-Signature"), os.environ["DONSOFT_WEBHOOK_SECRET"]):
61
+ abort(400)
62
+ event = request.get_json() # {id, event, createdAt, tenantId, data}
63
+ return "", 200
64
+ ```
65
+
66
+ `verify_webhook(raw_body, signature_header, secret, tolerance_seconds=300)` checks
67
+ `t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>` in constant time and rejects timestamps
68
+ more than 5 minutes away. `construct_webhook_event(...)` verifies and parses;
69
+ `sign_webhook(body, secret, t)` builds a header for tests.
70
+
71
+ ## Identity
72
+
73
+ ```python
74
+ from donsoft_connect import user_hash
75
+ hash = user_hash(os.environ["DONSOFT_IDENTITY_SECRET"], user.id) # pass with userId to identify()
76
+ ```
77
+
78
+ ## Tests
79
+
80
+ ```bash
81
+ python3 -m unittest # from sdks/python
82
+ ```
@@ -0,0 +1,7 @@
1
+ donsoft_connect/__init__.py,sha256=fBD1tGtswpYc-n4TH7zDEBm_yRGNK_GFZzxTp-o1diE,11094
2
+ donsoft_connect/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ donsoft_connect-1.0.0.dist-info/licenses/LICENSE,sha256=HYxL0EudkTwMCnQ9Ym7q752QnrWskmRGTkg3TZdioC4,1064
4
+ donsoft_connect-1.0.0.dist-info/METADATA,sha256=icVc6AyRxvPAXM5dtr8KIEWlCudiZfcRicMma-Uq2HE,2666
5
+ donsoft_connect-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ donsoft_connect-1.0.0.dist-info/top_level.txt,sha256=b-xCFDfRJjRGGrElUY-M1Pn6p1Ibhi8fb4wa9F3t7zc,16
7
+ donsoft_connect-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Donsoft
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ donsoft_connect