hapti 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.
- hapti/__init__.py +467 -0
- hapti-0.2.0.dist-info/METADATA +69 -0
- hapti-0.2.0.dist-info/RECORD +5 -0
- hapti-0.2.0.dist-info/WHEEL +5 -0
- hapti-0.2.0.dist-info/top_level.txt +1 -0
hapti/__init__.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
|
|
11
|
+
__all__ = ["Hapti", "HaptiError", "verify_webhook"]
|
|
12
|
+
__version__ = "0.2.0"
|
|
13
|
+
|
|
14
|
+
FINAL = {"succeeded", "failed", "blocked", "incomplete", "needs_person", "cancelled"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class HaptiError(Exception):
|
|
18
|
+
def __init__(self, status, body):
|
|
19
|
+
err = (body or {}).get("error") or {}
|
|
20
|
+
super().__init__(err.get("message") or f"Hapti answered {status}")
|
|
21
|
+
self.status = status
|
|
22
|
+
self.type = err.get("type")
|
|
23
|
+
self.reason = err.get("reason")
|
|
24
|
+
self.index = err.get("index")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _qs(params):
|
|
28
|
+
items = {k: v for k, v in params.items() if v is not None}
|
|
29
|
+
return "?" + urllib.parse.urlencode(items) if items else ""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _q(value):
|
|
33
|
+
return urllib.parse.quote(str(value), safe="")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _Group:
|
|
37
|
+
def __init__(self, client):
|
|
38
|
+
self._c = client
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _Tasks(_Group):
|
|
42
|
+
def create(self, task, idempotency_key=None):
|
|
43
|
+
return self._c.request("POST", "/v1/tasks", task, idempotency_key=idempotency_key or str(uuid.uuid4()))
|
|
44
|
+
|
|
45
|
+
def get(self, task_id):
|
|
46
|
+
return self._c.request("GET", f"/v1/tasks/{task_id}")
|
|
47
|
+
|
|
48
|
+
def list(self, limit=None, status=None, user=None, q=None, since=None, until=None, template=None, batch=None, cursor=None):
|
|
49
|
+
if isinstance(status, (list, tuple)):
|
|
50
|
+
status = ",".join(status)
|
|
51
|
+
return self._c.request("GET", "/v1/tasks" + _qs({"limit": limit, "status": status, "user": user, "q": q, "since": since, "until": until, "template": template, "batch": batch, "cursor": cursor}))
|
|
52
|
+
|
|
53
|
+
def all(self, **filters):
|
|
54
|
+
cursor = None
|
|
55
|
+
while True:
|
|
56
|
+
page = self.list(limit=100, cursor=cursor, **filters)
|
|
57
|
+
yield from page["data"]
|
|
58
|
+
if not page.get("has_more") or not page.get("next_cursor"):
|
|
59
|
+
return
|
|
60
|
+
cursor = page["next_cursor"]
|
|
61
|
+
|
|
62
|
+
def retry(self, task_id, idempotency_key=None):
|
|
63
|
+
return self._c.request("POST", f"/v1/tasks/{task_id}/retry", idempotency_key=idempotency_key)
|
|
64
|
+
|
|
65
|
+
def stream(self, task_id, last_event_id=None, reconnect=True):
|
|
66
|
+
return self._c.stream(f"/v1/tasks/{task_id}/stream", last_event_id=last_event_id, reconnect=reconnect)
|
|
67
|
+
|
|
68
|
+
def answer(self, task_id, value, key=None):
|
|
69
|
+
return self._c.request("POST", f"/v1/tasks/{task_id}/answer", {"value": value, **({"key": key} if key else {})})
|
|
70
|
+
|
|
71
|
+
def cancel(self, task_id):
|
|
72
|
+
return self._c.request("POST", f"/v1/tasks/{task_id}/cancel")
|
|
73
|
+
|
|
74
|
+
def approve(self, task_id, approve=True, by=None):
|
|
75
|
+
return self._c.request("POST", f"/v1/tasks/{task_id}/approve", {"approve": approve, **({"by": by} if by else {})})
|
|
76
|
+
|
|
77
|
+
def estimate(self, task):
|
|
78
|
+
return self._c.request("POST", "/v1/tasks/estimate", task)
|
|
79
|
+
|
|
80
|
+
def proof(self, task_id):
|
|
81
|
+
return self._c.request("GET", f"/v1/tasks/{task_id}/proof")
|
|
82
|
+
|
|
83
|
+
def delete_proof(self, task_id):
|
|
84
|
+
return self._c.request("DELETE", f"/v1/tasks/{task_id}/proof")
|
|
85
|
+
|
|
86
|
+
def dispute(self, task_id, reason):
|
|
87
|
+
return self._c.request("POST", f"/v1/tasks/{task_id}/dispute", {"reason": reason})
|
|
88
|
+
|
|
89
|
+
def file(self, task_id, name):
|
|
90
|
+
return self._c.request("GET", f"/v1/tasks/{task_id}/files/{_q(name)}", raw=True)
|
|
91
|
+
|
|
92
|
+
def wait(self, task_id, on_waiting=None, every=2.0, timeout=3600.0, on_step=None, live=True):
|
|
93
|
+
until = time.time() + timeout
|
|
94
|
+
seen = [None]
|
|
95
|
+
|
|
96
|
+
def look(t):
|
|
97
|
+
if t["status"] in FINAL and t.get("finished_at"):
|
|
98
|
+
return t
|
|
99
|
+
if t.get("pending") and on_waiting and json.dumps(t["pending"], sort_keys=True) != seen[0]:
|
|
100
|
+
seen[0] = json.dumps(t["pending"], sort_keys=True)
|
|
101
|
+
reply = on_waiting(t["pending"], t)
|
|
102
|
+
if reply is not None:
|
|
103
|
+
if t["pending"].get("type") == "question":
|
|
104
|
+
self.answer(task_id, str(reply), t["pending"].get("key"))
|
|
105
|
+
else:
|
|
106
|
+
self.approve(task_id, reply is True)
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
if live:
|
|
110
|
+
try:
|
|
111
|
+
for e in self._c.stream(f"/v1/tasks/{task_id}/stream", deadline=until):
|
|
112
|
+
if e["event"] == "step" and on_step:
|
|
113
|
+
on_step(e["data"])
|
|
114
|
+
if e["event"] == "task":
|
|
115
|
+
done = look(e["data"])
|
|
116
|
+
if done:
|
|
117
|
+
return done
|
|
118
|
+
if e["event"] == "done":
|
|
119
|
+
return self.get(task_id)
|
|
120
|
+
except HaptiError as err:
|
|
121
|
+
if err.status < 500:
|
|
122
|
+
raise
|
|
123
|
+
except (OSError, ValueError):
|
|
124
|
+
pass
|
|
125
|
+
while True:
|
|
126
|
+
t = self.get(task_id)
|
|
127
|
+
done = look(t)
|
|
128
|
+
if done:
|
|
129
|
+
return done
|
|
130
|
+
if time.time() > until:
|
|
131
|
+
raise TimeoutError(f"Hapti: task {task_id} still {t['status']} after {int(timeout)} s")
|
|
132
|
+
time.sleep(every)
|
|
133
|
+
|
|
134
|
+
def run(self, task, on_waiting=None, every=2.0, timeout=3600.0, idempotency_key=None, on_step=None):
|
|
135
|
+
created = self.create(task, idempotency_key=idempotency_key)
|
|
136
|
+
return self.wait(created["id"], on_waiting=on_waiting, every=every, timeout=timeout, on_step=on_step)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class _Batches(_Group):
|
|
140
|
+
def create(self, batch):
|
|
141
|
+
return self._c.request("POST", "/v1/batches", batch)
|
|
142
|
+
|
|
143
|
+
def get(self, batch_id):
|
|
144
|
+
return self._c.request("GET", f"/v1/batches/{batch_id}")
|
|
145
|
+
|
|
146
|
+
def list(self, limit=None):
|
|
147
|
+
return self._c.request("GET", "/v1/batches" + _qs({"limit": limit}))
|
|
148
|
+
|
|
149
|
+
def cancel(self, batch_id):
|
|
150
|
+
return self._c.request("POST", f"/v1/batches/{batch_id}/cancel")
|
|
151
|
+
|
|
152
|
+
def tasks(self, batch_id, status=None):
|
|
153
|
+
after = None
|
|
154
|
+
while True:
|
|
155
|
+
page = self._c.request("GET", f"/v1/batches/{batch_id}/tasks" + _qs({"status": status, "after": after, "limit": 200}))
|
|
156
|
+
yield from page["data"]
|
|
157
|
+
if not page.get("next") or not page["data"]:
|
|
158
|
+
return
|
|
159
|
+
after = page["next"]
|
|
160
|
+
|
|
161
|
+
def wait(self, batch_id, every=5.0):
|
|
162
|
+
while True:
|
|
163
|
+
b = self.get(batch_id)
|
|
164
|
+
if b.get("finished_at"):
|
|
165
|
+
return b
|
|
166
|
+
time.sleep(every)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class _Schedules(_Group):
|
|
170
|
+
def create(self, schedule):
|
|
171
|
+
return self._c.request("POST", "/v1/schedules", schedule)
|
|
172
|
+
|
|
173
|
+
def get(self, schedule_id):
|
|
174
|
+
return self._c.request("GET", f"/v1/schedules/{schedule_id}")
|
|
175
|
+
|
|
176
|
+
def list(self):
|
|
177
|
+
return self._c.request("GET", "/v1/schedules")
|
|
178
|
+
|
|
179
|
+
def pause(self, schedule_id):
|
|
180
|
+
return self._c.request("PATCH", f"/v1/schedules/{schedule_id}", {"paused": True})
|
|
181
|
+
|
|
182
|
+
def resume(self, schedule_id):
|
|
183
|
+
return self._c.request("PATCH", f"/v1/schedules/{schedule_id}", {"paused": False})
|
|
184
|
+
|
|
185
|
+
def delete(self, schedule_id):
|
|
186
|
+
return self._c.request("DELETE", f"/v1/schedules/{schedule_id}")
|
|
187
|
+
|
|
188
|
+
def tasks(self, schedule_id):
|
|
189
|
+
return self._c.request("GET", f"/v1/schedules/{schedule_id}/tasks")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class _Users(_Group):
|
|
193
|
+
def create(self, user):
|
|
194
|
+
return self._c.request("POST", "/v1/users", user)
|
|
195
|
+
|
|
196
|
+
def get(self, user_id):
|
|
197
|
+
return self._c.request("GET", f"/v1/users/{_q(user_id)}")
|
|
198
|
+
|
|
199
|
+
def update(self, user_id, user):
|
|
200
|
+
return self._c.request("PATCH", f"/v1/users/{_q(user_id)}", user)
|
|
201
|
+
|
|
202
|
+
def list(self, limit=None):
|
|
203
|
+
return self._c.request("GET", "/v1/users" + _qs({"limit": limit}))
|
|
204
|
+
|
|
205
|
+
def forget(self, user_id):
|
|
206
|
+
return self._c.request("DELETE", f"/v1/users/{_q(user_id)}")
|
|
207
|
+
|
|
208
|
+
def history(self, user_id):
|
|
209
|
+
return self._c.request("GET", f"/v1/users/{_q(user_id)}/history")
|
|
210
|
+
|
|
211
|
+
def forward(self, user_id, to):
|
|
212
|
+
return self._c.request("PUT", f"/v1/users/{_q(user_id)}/forward", {"to": to})
|
|
213
|
+
|
|
214
|
+
def stop_forward(self, user_id):
|
|
215
|
+
return self._c.request("DELETE", f"/v1/users/{_q(user_id)}/forward")
|
|
216
|
+
|
|
217
|
+
def phone(self, user_id, country=None):
|
|
218
|
+
return self._c.request("POST", f"/v1/users/{_q(user_id)}/phone", {"country": country} if country else {})
|
|
219
|
+
|
|
220
|
+
def release_phone(self, user_id):
|
|
221
|
+
return self._c.request("DELETE", f"/v1/users/{_q(user_id)}/phone")
|
|
222
|
+
|
|
223
|
+
def sms(self, user_id):
|
|
224
|
+
return self._c.request("GET", f"/v1/users/{_q(user_id)}/sms")
|
|
225
|
+
|
|
226
|
+
def connect_link(self, user_id, accounts=None, brand=None, return_url=None, expires_in=None):
|
|
227
|
+
body = {k: v for k, v in {"accounts": accounts, "brand": brand, "return_url": return_url, "expires_in": expires_in}.items() if v is not None}
|
|
228
|
+
return self._c.request("POST", f"/v1/users/{_q(user_id)}/connect", body)
|
|
229
|
+
|
|
230
|
+
def revoke_connect_links(self, user_id):
|
|
231
|
+
return self._c.request("DELETE", f"/v1/users/{_q(user_id)}/connect")
|
|
232
|
+
|
|
233
|
+
def set_limits(self, user_id, tasks_per_day=None, cents_per_month=None):
|
|
234
|
+
limits = {k: v for k, v in {"tasks_per_day": tasks_per_day, "cents_per_month": cents_per_month}.items() if v is not None}
|
|
235
|
+
return self._c.request("PATCH", f"/v1/users/{_q(user_id)}", {"limits": limits or None})
|
|
236
|
+
|
|
237
|
+
def usage(self, user_id, start=None, end=None):
|
|
238
|
+
return self._c.request("GET", f"/v1/users/{_q(user_id)}/usage" + _qs({"from": start, "to": end}))
|
|
239
|
+
|
|
240
|
+
def give_mandate(self, user_id, mandate):
|
|
241
|
+
return self._c.request("POST", f"/v1/users/{_q(user_id)}/mandate", mandate)
|
|
242
|
+
|
|
243
|
+
def revoke_mandate(self, user_id):
|
|
244
|
+
return self._c.request("DELETE", f"/v1/users/{_q(user_id)}/mandate")
|
|
245
|
+
|
|
246
|
+
def drop_session(self, user_id):
|
|
247
|
+
return self._c.request("DELETE", f"/v1/users/{_q(user_id)}/session")
|
|
248
|
+
|
|
249
|
+
def put_account(self, user_id, account, value):
|
|
250
|
+
return self._c.request("PUT", f"/v1/users/{_q(user_id)}/accounts/{_q(account)}", value)
|
|
251
|
+
|
|
252
|
+
def accounts(self, user_id):
|
|
253
|
+
return self._c.request("GET", f"/v1/users/{_q(user_id)}/accounts")
|
|
254
|
+
|
|
255
|
+
def delete_account(self, user_id, account):
|
|
256
|
+
return self._c.request("DELETE", f"/v1/users/{_q(user_id)}/accounts/{_q(account)}")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class _Endpoints(_Group):
|
|
260
|
+
def list(self):
|
|
261
|
+
return self._c.request("GET", "/v1/webhooks/endpoints")
|
|
262
|
+
|
|
263
|
+
def create(self, url, events=None, description=None, headers=None):
|
|
264
|
+
return self._c.request("POST", "/v1/webhooks/endpoints", {"url": url, **({"events": events} if events else {}), **({"description": description} if description else {}), **({"headers": headers} if headers else {})})
|
|
265
|
+
|
|
266
|
+
def get(self, endpoint_id):
|
|
267
|
+
return self._c.request("GET", f"/v1/webhooks/endpoints/{endpoint_id}")
|
|
268
|
+
|
|
269
|
+
def update(self, endpoint_id, **fields):
|
|
270
|
+
return self._c.request("PATCH", f"/v1/webhooks/endpoints/{endpoint_id}", fields)
|
|
271
|
+
|
|
272
|
+
def delete(self, endpoint_id):
|
|
273
|
+
return self._c.request("DELETE", f"/v1/webhooks/endpoints/{endpoint_id}")
|
|
274
|
+
|
|
275
|
+
def secret(self, endpoint_id):
|
|
276
|
+
return self._c.request("GET", f"/v1/webhooks/endpoints/{endpoint_id}/secret")["secret"]
|
|
277
|
+
|
|
278
|
+
def roll_secret(self, endpoint_id, expires_in_hours=None):
|
|
279
|
+
return self._c.request("POST", f"/v1/webhooks/endpoints/{endpoint_id}/roll-secret", {} if expires_in_hours is None else {"expires_in_hours": expires_in_hours})
|
|
280
|
+
|
|
281
|
+
def recover(self, endpoint_id, since=None):
|
|
282
|
+
return self._c.request("POST", f"/v1/webhooks/endpoints/{endpoint_id}/recover", {"since": since} if since else {})
|
|
283
|
+
|
|
284
|
+
def test(self, endpoint_id):
|
|
285
|
+
return self._c.request("POST", f"/v1/webhooks/endpoints/{endpoint_id}/test")
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class _Webhooks(_Group):
|
|
289
|
+
def __init__(self, client):
|
|
290
|
+
super().__init__(client)
|
|
291
|
+
self.endpoints = _Endpoints(client)
|
|
292
|
+
|
|
293
|
+
def events(self):
|
|
294
|
+
return self._c.request("GET", "/v1/webhooks/events")
|
|
295
|
+
|
|
296
|
+
def list_events(self, type=None, object=None, since=None, limit=None, cursor=None):
|
|
297
|
+
return self._c.request("GET", "/v1/events" + _qs({"type": type, "object": object, "since": since, "limit": limit, "cursor": cursor}))
|
|
298
|
+
|
|
299
|
+
def get_event(self, event_id):
|
|
300
|
+
return self._c.request("GET", f"/v1/events/{event_id}")
|
|
301
|
+
|
|
302
|
+
def deliveries(self, endpoint=None, event=None, state=None, limit=None, cursor=None):
|
|
303
|
+
return self._c.request("GET", "/v1/webhooks/deliveries" + _qs({"endpoint": endpoint, "event": event, "state": state, "limit": limit, "cursor": cursor}))
|
|
304
|
+
|
|
305
|
+
def delivery(self, delivery_id):
|
|
306
|
+
return self._c.request("GET", f"/v1/webhooks/deliveries/{delivery_id}")
|
|
307
|
+
|
|
308
|
+
def resend(self, delivery_id):
|
|
309
|
+
return self._c.request("POST", f"/v1/webhooks/deliveries/{delivery_id}/resend")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class _Recipes(_Group):
|
|
313
|
+
def list(self):
|
|
314
|
+
return self._c.request("GET", "/v1/recipes")
|
|
315
|
+
|
|
316
|
+
def get(self, recipe_id):
|
|
317
|
+
return self._c.request("GET", f"/v1/recipes/{recipe_id}")
|
|
318
|
+
|
|
319
|
+
def rename(self, recipe_id, name):
|
|
320
|
+
return self._c.request("PATCH", f"/v1/recipes/{recipe_id}", {"name": name})
|
|
321
|
+
|
|
322
|
+
def delete(self, recipe_id):
|
|
323
|
+
return self._c.request("DELETE", f"/v1/recipes/{recipe_id}")
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
class Hapti:
|
|
327
|
+
def __init__(self, api_key=None, base_url=None, retries=3, timeout=60.0, version=None):
|
|
328
|
+
self.key = api_key or os.environ.get("HAPTI_API_KEY")
|
|
329
|
+
if not self.key:
|
|
330
|
+
raise ValueError('Hapti: an API key is needed (Hapti("hp_test_...") or the HAPTI_API_KEY variable)')
|
|
331
|
+
self.base = (base_url or os.environ.get("HAPTI_BASE_URL") or "https://api.hapti.dev").rstrip("/")
|
|
332
|
+
self.retries = retries
|
|
333
|
+
self.timeout = timeout
|
|
334
|
+
self.version = version
|
|
335
|
+
self.tasks = _Tasks(self)
|
|
336
|
+
self.webhooks = _Webhooks(self)
|
|
337
|
+
self.batches = _Batches(self)
|
|
338
|
+
self.schedules = _Schedules(self)
|
|
339
|
+
self.users = _Users(self)
|
|
340
|
+
self.recipes = _Recipes(self)
|
|
341
|
+
|
|
342
|
+
def events(self, reconnect=True):
|
|
343
|
+
return self.stream("/v1/stream", reconnect=reconnect)
|
|
344
|
+
|
|
345
|
+
def _headers(self):
|
|
346
|
+
h = {"Authorization": f"Bearer {self.key}", "User-Agent": f"hapti-python/{__version__}"}
|
|
347
|
+
if self.version:
|
|
348
|
+
h["Hapti-Version"] = self.version
|
|
349
|
+
return h
|
|
350
|
+
|
|
351
|
+
def stream(self, path, last_event_id=None, reconnect=True, deadline=None):
|
|
352
|
+
last = last_event_id
|
|
353
|
+
failures = 0
|
|
354
|
+
while True:
|
|
355
|
+
if deadline and time.time() > deadline:
|
|
356
|
+
raise TimeoutError(f"Hapti: {path} still open at the deadline")
|
|
357
|
+
headers = {**self._headers(), "Accept": "text/event-stream", **({"Last-Event-ID": last} if last else {})}
|
|
358
|
+
req = urllib.request.Request(self.base + path, method="GET", headers=headers)
|
|
359
|
+
try:
|
|
360
|
+
res = urllib.request.urlopen(req, timeout=max(30.0, self.timeout))
|
|
361
|
+
except urllib.error.HTTPError as e:
|
|
362
|
+
try:
|
|
363
|
+
parsed = json.loads(e.read())
|
|
364
|
+
except ValueError:
|
|
365
|
+
parsed = {}
|
|
366
|
+
if e.code < 500 and e.code != 429:
|
|
367
|
+
raise HaptiError(e.code, parsed) from None
|
|
368
|
+
failures += 1
|
|
369
|
+
if not reconnect or failures > self.retries:
|
|
370
|
+
raise HaptiError(e.code, parsed) from None
|
|
371
|
+
time.sleep(0.5 * 2 ** failures)
|
|
372
|
+
continue
|
|
373
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
|
374
|
+
failures += 1
|
|
375
|
+
if not reconnect or failures > self.retries:
|
|
376
|
+
raise
|
|
377
|
+
time.sleep(0.5 * 2 ** failures)
|
|
378
|
+
continue
|
|
379
|
+
failures = 0
|
|
380
|
+
event, data = "message", None
|
|
381
|
+
try:
|
|
382
|
+
with res:
|
|
383
|
+
for raw in res:
|
|
384
|
+
line = raw.decode("utf-8").rstrip("\r\n")
|
|
385
|
+
if line == "":
|
|
386
|
+
if data is not None:
|
|
387
|
+
yield {"event": event, "data": json.loads(data), "id": last}
|
|
388
|
+
if event == "done":
|
|
389
|
+
return
|
|
390
|
+
event, data = "message", None
|
|
391
|
+
elif line.startswith("event:"):
|
|
392
|
+
event = line[6:].strip()
|
|
393
|
+
elif line.startswith("id:"):
|
|
394
|
+
last = line[3:].strip()
|
|
395
|
+
elif line.startswith("data:"):
|
|
396
|
+
data = (data + "\n" if data is not None else "") + line[5:].lstrip()
|
|
397
|
+
if deadline and time.time() > deadline:
|
|
398
|
+
raise TimeoutError(f"Hapti: {path} still open at the deadline")
|
|
399
|
+
except (OSError, ConnectionError):
|
|
400
|
+
if not reconnect:
|
|
401
|
+
raise
|
|
402
|
+
if not reconnect:
|
|
403
|
+
return
|
|
404
|
+
time.sleep(1)
|
|
405
|
+
|
|
406
|
+
def balance(self):
|
|
407
|
+
return self.request("GET", "/v1/billing")
|
|
408
|
+
|
|
409
|
+
def usage(self, start=None, end=None):
|
|
410
|
+
return self.request("GET", "/v1/usage" + _qs({"from": start, "to": end}))
|
|
411
|
+
|
|
412
|
+
def usage_by_user(self, start=None, end=None):
|
|
413
|
+
return self.request("GET", "/v1/usage/users" + _qs({"from": start, "to": end}))
|
|
414
|
+
|
|
415
|
+
def request(self, method, path, body=None, idempotency_key=None, raw=False):
|
|
416
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
417
|
+
headers = self._headers()
|
|
418
|
+
if method == "POST" and not idempotency_key:
|
|
419
|
+
idempotency_key = str(uuid.uuid4())
|
|
420
|
+
if data is not None:
|
|
421
|
+
headers["Content-Type"] = "application/json"
|
|
422
|
+
if idempotency_key:
|
|
423
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
424
|
+
safe = method == "GET" or bool(idempotency_key)
|
|
425
|
+
attempt = 0
|
|
426
|
+
while True:
|
|
427
|
+
req = urllib.request.Request(self.base + path, data=data, method=method, headers=headers)
|
|
428
|
+
try:
|
|
429
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
430
|
+
payload = res.read()
|
|
431
|
+
return payload if raw else (json.loads(payload) if payload else {})
|
|
432
|
+
except urllib.error.HTTPError as e:
|
|
433
|
+
payload = e.read()
|
|
434
|
+
if (e.code == 429 or (e.code >= 500 and safe)) and attempt < self.retries:
|
|
435
|
+
wait = e.headers.get("Retry-After")
|
|
436
|
+
time.sleep(float(wait) if wait and wait.isdigit() else 0.5 * 2 ** attempt)
|
|
437
|
+
attempt += 1
|
|
438
|
+
continue
|
|
439
|
+
try:
|
|
440
|
+
parsed = json.loads(payload)
|
|
441
|
+
except ValueError:
|
|
442
|
+
parsed = {}
|
|
443
|
+
raise HaptiError(e.code, parsed) from None
|
|
444
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
|
445
|
+
if safe and attempt < self.retries:
|
|
446
|
+
time.sleep(0.5 * 2 ** attempt)
|
|
447
|
+
attempt += 1
|
|
448
|
+
continue
|
|
449
|
+
raise
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def verify_webhook(raw_body, signature_header, secret, tolerance_seconds=300, now=None):
|
|
453
|
+
pairs = [p.strip().split("=", 1) for p in (signature_header or "").split(",") if "=" in p]
|
|
454
|
+
ts_raw = next((v for k, v in pairs if k == "t"), "")
|
|
455
|
+
sigs = [v for k, v in pairs if k == "v1" and v]
|
|
456
|
+
try:
|
|
457
|
+
ts = int(ts_raw)
|
|
458
|
+
except ValueError:
|
|
459
|
+
return False
|
|
460
|
+
if not sigs or abs((now or time.time()) - ts) > tolerance_seconds:
|
|
461
|
+
return False
|
|
462
|
+
body = raw_body.decode() if isinstance(raw_body, (bytes, bytearray)) else raw_body
|
|
463
|
+
for s in (secret if isinstance(secret, (list, tuple)) else [secret]):
|
|
464
|
+
mac = hmac.new(s.encode(), f"{ts}.{body}".encode(), hashlib.sha256).hexdigest()
|
|
465
|
+
if any(hmac.compare_digest(mac, v) for v in sigs):
|
|
466
|
+
return True
|
|
467
|
+
return False
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hapti
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Hapti: an agent that does tasks on any website by sight, paid only when it succeeds
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://hapti.dev
|
|
7
|
+
Project-URL: Documentation, https://hapti.dev/docs/
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# hapti
|
|
12
|
+
|
|
13
|
+
An agent that does tasks on any website by sight, in a real browser. You pay only when it succeeds.
|
|
14
|
+
|
|
15
|
+
Documentation: [hapti.dev/docs](https://hapti.dev/docs/) · API reference: [hapti.dev/docs/api-tasks](https://hapti.dev/docs/api-tasks) · For AI agents: [hapti.dev/llms.txt](https://hapti.dev/llms.txt)
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pip install hapti
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from hapti import Hapti
|
|
23
|
+
|
|
24
|
+
hapti = Hapti() # reads HAPTI_API_KEY
|
|
25
|
+
|
|
26
|
+
task = hapti.tasks.run({
|
|
27
|
+
"url": "https://www.example.com",
|
|
28
|
+
"goal": "Read the main title of the page",
|
|
29
|
+
"output": {"type": "object", "required": ["title"], "properties": {"title": {"type": "string"}}},
|
|
30
|
+
})
|
|
31
|
+
print(task["result"]["data"]["title"])
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
When the site asks for something the task does not have, `on_waiting` gets it and what it returns is sent back:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
hapti.tasks.run(
|
|
38
|
+
{"url": "https://portal.example.com", "goal": "Declare the claim", "data": {"contract": "AX-1"}, "user": "customer-42"},
|
|
39
|
+
on_waiting=lambda pending, task: ask_my_user(pending["text"]),
|
|
40
|
+
)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`pending["action_url"]` is also a ready page you may send to your user yourself: they answer or approve on it, once, without any key.
|
|
44
|
+
|
|
45
|
+
Every `user` keeps their session, device and mailbox; every success becomes a recipe replayed next time; `output` gives `result["data"]` checked against your schema, and a task that cannot fit it is not billed.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
batch = hapti.batches.create({"template": {"url": url, "goal": goal}, "items": [{"user": c.id, "data": {"contract": c.contract}} for c in customers]})
|
|
49
|
+
for t in hapti.batches.tasks(batch["id"]):
|
|
50
|
+
print(t["id"], t["status"])
|
|
51
|
+
|
|
52
|
+
hapti.schedules.create({"cron": "0 9 * * 1-5", "timezone": "Europe/Paris", "task": {"url": url, "goal": goal}})
|
|
53
|
+
hapti.tasks.estimate({"url": url, "goal": goal})
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from hapti import verify_webhook
|
|
58
|
+
verify_webhook(raw_body, headers["Hapti-Signature"], secret)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Test keys (`hp_test_...`) are free and never send the data to the sites. Live keys (`hp_live_...`) are billed only when a task succeeds.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
link = hapti.users.connect_link("customer-42", accounts=[{"account": "bank", "origin": "https://www.my-bank.com", "label": "My bank"}], brand={"name": "Acme"})
|
|
65
|
+
hapti.users.set_limits("customer-42", tasks_per_day=20, cents_per_month=500)
|
|
66
|
+
hapti.users.usage("customer-42")["billed_cents"]
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`link["url"]` is a page you send to your user yourself: they put their credentials in the vault and give their consent; you never see their secrets.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
hapti/__init__.py,sha256=kr6PBZloTyJhDrQ3qLURHAJNhSXDqk_z9p-KIhUx0Ls,19421
|
|
2
|
+
hapti-0.2.0.dist-info/METADATA,sha256=4vUjvcXykn3n9wfHWNVMA11yzDL6uLfzmXi53rspAy4,2775
|
|
3
|
+
hapti-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
4
|
+
hapti-0.2.0.dist-info/top_level.txt,sha256=CL0LUDWttvU4M6-VMIud9tw44JnxNjn4ZvvxcsFPHrk,6
|
|
5
|
+
hapti-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hapti
|