sendurl 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.
sendurl/__init__.py ADDED
@@ -0,0 +1,101 @@
1
+ """The official Python client for the SendURL REST API.
2
+
3
+ >>> from sendurl import SendURL
4
+ >>> client = SendURL() # reads SENDURL_API_KEY
5
+ >>> link = client.links.create(destination_url="https://example.com")
6
+ >>> link["shortUrl"]
7
+ """
8
+
9
+ from ._async import AsyncSendURL
10
+ from ._base import DEFAULT_BASE_URL
11
+ from ._errors import (
12
+ APIConnectionError,
13
+ APITimeoutError,
14
+ AuthenticationError,
15
+ BadRequestError,
16
+ ConflictError,
17
+ InternalServerError,
18
+ NotFoundError,
19
+ PermissionDeniedError,
20
+ RateLimitError,
21
+ SendURLError,
22
+ ServiceUnavailableError,
23
+ UnprocessableEntityError,
24
+ )
25
+ from ._export import AsyncCSVStream, CSVStream
26
+ from ._sync import SendURL
27
+ from ._types import (
28
+ AbTest,
29
+ AbTestParam,
30
+ AbTestVariant,
31
+ Account,
32
+ AnalyticsClick,
33
+ AnalyticsClickList,
34
+ Breakdown,
35
+ BreakdownRow,
36
+ Click,
37
+ ClickList,
38
+ DeleteResponse,
39
+ Domain,
40
+ DomainList,
41
+ Folder,
42
+ FolderList,
43
+ Link,
44
+ LinkList,
45
+ LinkPreview,
46
+ Overview,
47
+ Pagination,
48
+ QrStyle,
49
+ StatsDay,
50
+ Tag,
51
+ TagList,
52
+ )
53
+ from ._utils import NOT_GIVEN, NotGiven
54
+ from ._version import __version__
55
+
56
+ __all__ = [
57
+ "DEFAULT_BASE_URL",
58
+ "NOT_GIVEN",
59
+ "APIConnectionError",
60
+ "APITimeoutError",
61
+ "AbTest",
62
+ "AbTestParam",
63
+ "AbTestVariant",
64
+ "Account",
65
+ "AnalyticsClick",
66
+ "AnalyticsClickList",
67
+ "AsyncCSVStream",
68
+ "AsyncSendURL",
69
+ "AuthenticationError",
70
+ "BadRequestError",
71
+ "Breakdown",
72
+ "BreakdownRow",
73
+ "CSVStream",
74
+ "Click",
75
+ "ClickList",
76
+ "ConflictError",
77
+ "DeleteResponse",
78
+ "Domain",
79
+ "DomainList",
80
+ "Folder",
81
+ "FolderList",
82
+ "InternalServerError",
83
+ "Link",
84
+ "LinkList",
85
+ "LinkPreview",
86
+ "NotFoundError",
87
+ "NotGiven",
88
+ "Overview",
89
+ "Pagination",
90
+ "PermissionDeniedError",
91
+ "QrStyle",
92
+ "RateLimitError",
93
+ "SendURL",
94
+ "SendURLError",
95
+ "ServiceUnavailableError",
96
+ "StatsDay",
97
+ "Tag",
98
+ "TagList",
99
+ "UnprocessableEntityError",
100
+ "__version__",
101
+ ]
sendurl/_async.py ADDED
@@ -0,0 +1,452 @@
1
+ """The asynchronous client, :class:`AsyncSendURL` (same surface as :class:`SendURL`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import TracebackType
6
+ from typing import Any, AsyncIterator, List, Mapping, Optional, Sequence, Type, Union, cast
7
+
8
+ import httpx
9
+
10
+ from . import _endpoints as ep
11
+ from ._base import AsyncTransport
12
+ from ._endpoints import DateLike, DateTimeLike, StrOrList
13
+ from ._export import AsyncCSVStream, PathLike
14
+ from ._types import (
15
+ Account,
16
+ AnalyticsClick,
17
+ AnalyticsClickList,
18
+ Breakdown,
19
+ Click,
20
+ ClickList,
21
+ DeleteResponse,
22
+ Domain,
23
+ DomainList,
24
+ Folder,
25
+ FolderList,
26
+ Link,
27
+ LinkList,
28
+ Overview,
29
+ StatsDay,
30
+ Tag,
31
+ TagList,
32
+ )
33
+ from ._utils import NOT_GIVEN, NotGiven
34
+
35
+ __all__ = ["AsyncSendURL"]
36
+
37
+
38
+ class _Resource:
39
+ def __init__(self, client: AsyncSendURL) -> None:
40
+ self._client = client
41
+
42
+
43
+ class AccountResource(_Resource):
44
+ async def get(self) -> Account:
45
+ """``GET /me``: the workspace the key acts in, its plan, limits and usage."""
46
+ return cast(Account, await self._client._request(ep.account_get()))
47
+
48
+
49
+ class LinkClicks(_Resource):
50
+ def list(self, link_id: str, *, limit: Optional[int] = None) -> AsyncIterator[Click]:
51
+ """Every click of a link, newest first, following pages as you iterate.
52
+
53
+ ``limit`` is the page size (1-10, default 10), not a total.
54
+ """
55
+ return cast(
56
+ AsyncIterator[Click],
57
+ self._client._paginate(
58
+ lambda cursor: ep.link_clicks_list(link_id, limit=limit, cursor=cursor), "clicks"
59
+ ),
60
+ )
61
+
62
+ async def list_page(
63
+ self, link_id: str, *, limit: Optional[int] = None, cursor: Optional[str] = None
64
+ ) -> ClickList:
65
+ """One page of a link's clicks (``pagination.nextCursor`` reads the next)."""
66
+ return cast(
67
+ ClickList, await self._client._request(ep.link_clicks_list(link_id, limit=limit, cursor=cursor))
68
+ )
69
+
70
+ async def get(self, link_id: str, click_id: str) -> Click:
71
+ """One click of the link."""
72
+ return cast(Click, await self._client._request(ep.link_clicks_get(link_id, click_id)))
73
+
74
+
75
+ class Links(_Resource):
76
+ def __init__(self, client: AsyncSendURL) -> None:
77
+ super().__init__(client)
78
+ self.clicks = LinkClicks(client)
79
+
80
+ async def create(
81
+ self,
82
+ *,
83
+ destination_url: str,
84
+ slug: Optional[str] = None,
85
+ title: Optional[str] = None,
86
+ folder_id: Optional[str] = None,
87
+ domain_id: Optional[str] = None,
88
+ expires_at: Optional[DateTimeLike] = None,
89
+ password: Optional[str] = None,
90
+ ios_url: Optional[str] = None,
91
+ android_url: Optional[str] = None,
92
+ tag_ids: Optional[Sequence[str]] = None,
93
+ qr_style: Optional[Mapping[str, Any]] = None,
94
+ preview: Optional[Mapping[str, Any]] = None,
95
+ ab_test: Optional[Mapping[str, Any]] = None,
96
+ ) -> Link:
97
+ """``POST /links``: create a short link. Arguments left as ``None`` are not sent.
98
+
99
+ ``expires_at`` takes a timezone-aware ``datetime`` or an ISO 8601
100
+ string with an offset. ``qr_style`` is ``{"fg", "bg", "dots", "corners"}``
101
+ (see :class:`QrStyle`; ``"v": 1`` is added for you). Never retried (it
102
+ could create the link twice).
103
+ """
104
+ req = ep.links_create(
105
+ destination_url=destination_url,
106
+ slug=slug,
107
+ title=title,
108
+ folder_id=folder_id,
109
+ domain_id=domain_id,
110
+ expires_at=expires_at,
111
+ password=password,
112
+ ios_url=ios_url,
113
+ android_url=android_url,
114
+ tag_ids=tag_ids,
115
+ qr_style=qr_style,
116
+ preview=preview,
117
+ ab_test=ab_test,
118
+ )
119
+ return cast(Link, await self._client._request(req))
120
+
121
+ def list(
122
+ self,
123
+ *,
124
+ status: Optional[StrOrList] = None,
125
+ q: Optional[str] = None,
126
+ sort: Optional[str] = None,
127
+ folder_id: Optional[str] = None,
128
+ tag_ids: Optional[Sequence[str]] = None,
129
+ limit: Optional[int] = None,
130
+ ) -> AsyncIterator[Link]:
131
+ """Every link matching the filters, following pages as you iterate.
132
+
133
+ ``status``: ``"active"``, ``"disabled"``, ``"expired"``, ``"protected"``,
134
+ ``"limit_reached"`` or a list of them (any). ``sort``:
135
+ ``"created_desc"`` (default), ``"clicks_desc"``, ``"clicks_asc"``.
136
+ ``limit`` is the page size (1-10).
137
+ """
138
+ return cast(
139
+ AsyncIterator[Link],
140
+ self._client._paginate(
141
+ lambda cursor: ep.links_list(
142
+ status=status,
143
+ q=q,
144
+ sort=sort,
145
+ folder_id=folder_id,
146
+ tag_ids=tag_ids,
147
+ limit=limit,
148
+ cursor=cursor,
149
+ ),
150
+ "links",
151
+ ),
152
+ )
153
+
154
+ async def list_page(
155
+ self,
156
+ *,
157
+ status: Optional[StrOrList] = None,
158
+ q: Optional[str] = None,
159
+ sort: Optional[str] = None,
160
+ folder_id: Optional[str] = None,
161
+ tag_ids: Optional[Sequence[str]] = None,
162
+ limit: Optional[int] = None,
163
+ cursor: Optional[str] = None,
164
+ ) -> LinkList:
165
+ """One page of ``GET /links`` with ``summary``, ``usage`` and ``pagination``."""
166
+ req = ep.links_list(
167
+ status=status, q=q, sort=sort, folder_id=folder_id, tag_ids=tag_ids, limit=limit, cursor=cursor
168
+ )
169
+ return cast(LinkList, await self._client._request(req))
170
+
171
+ async def get(self, link_id: str) -> Link:
172
+ """``GET /links/:id``."""
173
+ return cast(Link, await self._client._request(ep.links_get(link_id)))
174
+
175
+ async def update(
176
+ self,
177
+ link_id: str,
178
+ *,
179
+ destination_url: Union[str, NotGiven] = NOT_GIVEN,
180
+ title: Union[str, NotGiven, None] = NOT_GIVEN,
181
+ active: Union[bool, NotGiven] = NOT_GIVEN,
182
+ folder_id: Union[str, NotGiven] = NOT_GIVEN,
183
+ expires_at: Union[DateTimeLike, NotGiven, None] = NOT_GIVEN,
184
+ password: Union[str, NotGiven, None] = NOT_GIVEN,
185
+ ios_url: Union[str, NotGiven, None] = NOT_GIVEN,
186
+ android_url: Union[str, NotGiven, None] = NOT_GIVEN,
187
+ tag_ids: Union[Sequence[str], NotGiven, None] = NOT_GIVEN,
188
+ qr_style: Union[Mapping[str, Any], NotGiven, None] = NOT_GIVEN,
189
+ preview: Union[Mapping[str, Any], NotGiven, None] = NOT_GIVEN,
190
+ ab_test: Union[Mapping[str, Any], NotGiven, None] = NOT_GIVEN,
191
+ ) -> Link:
192
+ """``PATCH /links/:id``: change only the fields you pass.
193
+
194
+ ``None`` clears a field (sent as ``null``): ``ios_url=None`` removes the
195
+ iOS target, ``expires_at=None`` the expiry, ``ab_test=None`` ends the
196
+ test without a winner, ``qr_style=None`` resets the plain code. A field
197
+ you leave out is not touched. ``qr_style`` takes the same object as
198
+ ``create()``.
199
+ """
200
+ req = ep.links_update(
201
+ link_id,
202
+ destination_url=destination_url,
203
+ title=title,
204
+ active=active,
205
+ folder_id=folder_id,
206
+ expires_at=expires_at,
207
+ password=password,
208
+ ios_url=ios_url,
209
+ android_url=android_url,
210
+ tag_ids=tag_ids,
211
+ qr_style=qr_style,
212
+ preview=preview,
213
+ ab_test=ab_test,
214
+ )
215
+ return cast(Link, await self._client._request(req))
216
+
217
+ async def delete(self, link_id: str) -> DeleteResponse:
218
+ """``DELETE /links/:id`` (paid plans; Free gets ``plan_upgrade_required``: disable it instead)."""
219
+ return cast(DeleteResponse, await self._client._request(ep.links_delete(link_id)))
220
+
221
+ async def pick_winner(self, link_id: str, variant_id: str) -> Link:
222
+ """``POST /links/:id/ab-test/winner``: end the test; the variant's URL becomes the destination."""
223
+ req = ep.links_pick_winner(link_id, variant_id=variant_id)
224
+ return cast(Link, await self._client._request(req))
225
+
226
+ async def stats(self, link_id: str) -> List[StatsDay]:
227
+ """``GET /links/:id/stats``: all-time clicks per UTC day (days with clicks only), oldest first."""
228
+ return cast(List[StatsDay], await self._client._request(ep.links_stats(link_id)))
229
+
230
+ async def export(
231
+ self,
232
+ *,
233
+ status: Optional[StrOrList] = None,
234
+ q: Optional[str] = None,
235
+ folder_id: Optional[str] = None,
236
+ tag_ids: Optional[Sequence[str]] = None,
237
+ ) -> AsyncCSVStream:
238
+ """``GET /links/export.csv``: every matching link as CSV, streamed.
239
+
240
+ Errors (e.g. ``export_unavailable``) are raised here; ``async for``
241
+ over the returned :class:`AsyncCSVStream` for ``bytes`` chunks.
242
+ """
243
+ req = ep.links_export(status=status, q=q, folder_id=folder_id, tag_ids=tag_ids)
244
+ return AsyncCSVStream(await self._client._send(req, stream=True))
245
+
246
+ async def export_to_file(
247
+ self,
248
+ path: PathLike,
249
+ *,
250
+ status: Optional[StrOrList] = None,
251
+ q: Optional[str] = None,
252
+ folder_id: Optional[str] = None,
253
+ tag_ids: Optional[Sequence[str]] = None,
254
+ ) -> int:
255
+ """Write the CSV export to ``path``; returns the number of bytes written."""
256
+ written = 0
257
+ csv = await self.export(status=status, q=q, folder_id=folder_id, tag_ids=tag_ids)
258
+ async with csv:
259
+ with open(path, "wb") as out:
260
+ async for chunk in csv:
261
+ out.write(chunk)
262
+ written += len(chunk)
263
+ return written
264
+
265
+
266
+ class Analytics(_Resource):
267
+ """``/analytics/*``. Send these one at a time: busy answers are 503
268
+ ``analytics_unavailable`` (retried for you, honouring ``Retry-After``)."""
269
+
270
+ async def overview(
271
+ self,
272
+ *,
273
+ from_: DateLike,
274
+ to: DateLike,
275
+ tz: Optional[str] = None,
276
+ folder_id: Optional[str] = None,
277
+ link_id: Optional[str] = None,
278
+ compare: Optional[bool] = None,
279
+ ) -> Overview:
280
+ """KPIs, series, top links/tags/social and breakdowns over ``from_``..``to`` (inclusive)."""
281
+ req = ep.analytics_overview(
282
+ from_=from_, to=to, tz=tz, folder_id=folder_id, link_id=link_id, compare=compare
283
+ )
284
+ return cast(Overview, await self._client._request(req))
285
+
286
+ async def breakdown(
287
+ self,
288
+ *,
289
+ from_: DateLike,
290
+ to: DateLike,
291
+ dimension: str,
292
+ tz: Optional[str] = None,
293
+ folder_id: Optional[str] = None,
294
+ link_id: Optional[str] = None,
295
+ order: Optional[str] = None,
296
+ limit: Optional[int] = None,
297
+ by: Optional[str] = None,
298
+ category: Optional[str] = None,
299
+ count_only: Optional[bool] = None,
300
+ ) -> Breakdown:
301
+ """Clicks ranked by ``dimension``: ``link``, ``country``, ``device``,
302
+ ``browser``, ``os``, ``referrer``, ``variant`` (needs ``link_id``), and
303
+ on Pro and above ``city`` and ``utm`` (``by``: source, medium, campaign)."""
304
+ req = ep.analytics_breakdown(
305
+ from_=from_,
306
+ to=to,
307
+ dimension=dimension,
308
+ tz=tz,
309
+ folder_id=folder_id,
310
+ link_id=link_id,
311
+ order=order,
312
+ limit=limit,
313
+ by=by,
314
+ category=category,
315
+ count_only=count_only,
316
+ )
317
+ return cast(Breakdown, await self._client._request(req))
318
+
319
+ def clicks(
320
+ self,
321
+ *,
322
+ from_: DateLike,
323
+ to: DateLike,
324
+ tz: Optional[str] = None,
325
+ folder_id: Optional[str] = None,
326
+ link_id: Optional[str] = None,
327
+ limit: Optional[int] = None,
328
+ ) -> AsyncIterator[AnalyticsClick]:
329
+ """Every click in the range, newest first, following pages as you iterate."""
330
+ return cast(
331
+ AsyncIterator[AnalyticsClick],
332
+ self._client._paginate(
333
+ lambda cursor: ep.analytics_clicks(
334
+ from_=from_,
335
+ to=to,
336
+ tz=tz,
337
+ folder_id=folder_id,
338
+ link_id=link_id,
339
+ limit=limit,
340
+ cursor=cursor,
341
+ ),
342
+ "clicks",
343
+ ),
344
+ )
345
+
346
+ async def clicks_page(
347
+ self,
348
+ *,
349
+ from_: DateLike,
350
+ to: DateLike,
351
+ tz: Optional[str] = None,
352
+ folder_id: Optional[str] = None,
353
+ link_id: Optional[str] = None,
354
+ limit: Optional[int] = None,
355
+ cursor: Optional[str] = None,
356
+ ) -> AnalyticsClickList:
357
+ """One page of clicks in the range."""
358
+ req = ep.analytics_clicks(
359
+ from_=from_, to=to, tz=tz, folder_id=folder_id, link_id=link_id, limit=limit, cursor=cursor
360
+ )
361
+ return cast(AnalyticsClickList, await self._client._request(req))
362
+
363
+
364
+ class Folders(_Resource):
365
+ def list(self, *, limit: Optional[int] = None) -> AsyncIterator[Folder]:
366
+ """Every folder (Default first). Org-level keys only."""
367
+ return cast(
368
+ AsyncIterator[Folder],
369
+ self._client._paginate(lambda cursor: ep.folders_list(limit=limit, cursor=cursor), "folders"),
370
+ )
371
+
372
+ async def list_page(self, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> FolderList:
373
+ return cast(FolderList, await self._client._request(ep.folders_list(limit=limit, cursor=cursor)))
374
+
375
+ async def create(self, *, name: str) -> Folder:
376
+ """``POST /folders`` (name 1-100 characters, unique ignoring case)."""
377
+ return cast(Folder, await self._client._request(ep.folders_create(name=name)))
378
+
379
+
380
+ class Tags(_Resource):
381
+ def list(self, *, limit: Optional[int] = None) -> AsyncIterator[Tag]:
382
+ """Every tag of the workspace, by name."""
383
+ return cast(
384
+ AsyncIterator[Tag],
385
+ self._client._paginate(lambda cursor: ep.tags_list(limit=limit, cursor=cursor), "tags"),
386
+ )
387
+
388
+ async def list_page(self, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> TagList:
389
+ return cast(TagList, await self._client._request(ep.tags_list(limit=limit, cursor=cursor)))
390
+
391
+
392
+ class Domains(_Resource):
393
+ def list(self, *, limit: Optional[int] = None) -> AsyncIterator[Domain]:
394
+ """Every domain (snu.to subdomains and custom domains), newest first."""
395
+ return cast(
396
+ AsyncIterator[Domain],
397
+ self._client._paginate(lambda cursor: ep.domains_list(limit=limit, cursor=cursor), "domains"),
398
+ )
399
+
400
+ async def list_page(self, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> DomainList:
401
+ return cast(DomainList, await self._client._request(ep.domains_list(limit=limit, cursor=cursor)))
402
+
403
+ async def get(self, domain_id: str) -> Domain:
404
+ return cast(Domain, await self._client._request(ep.domains_get(domain_id)))
405
+
406
+
407
+ class AsyncSendURL(AsyncTransport):
408
+ """The asynchronous SendURL client (``await`` every call; ``async for`` over ``list()``).
409
+
410
+ Args:
411
+ api_key: an API key (``snu_...``); defaults to ``$SENDURL_API_KEY``.
412
+ base_url: defaults to ``$SENDURL_BASE_URL``, else ``https://api.sendurl.to/api/v1``.
413
+ timeout: seconds (or an ``httpx.Timeout``) per request; default 30.
414
+ max_retries: retries of a GET on a connection error, 429, 502, 503
415
+ or 504 (default 2). POST, PATCH and DELETE are never retried.
416
+ http_client: an ``httpx.AsyncClient`` to use (proxies, transports...);
417
+ ``aclose()`` leaves it open.
418
+ """
419
+
420
+ def __init__(
421
+ self,
422
+ *,
423
+ api_key: Optional[str] = None,
424
+ base_url: Optional[str] = None,
425
+ timeout: Union[float, httpx.Timeout, None] = 30.0,
426
+ max_retries: int = 2,
427
+ http_client: Optional[httpx.AsyncClient] = None,
428
+ ) -> None:
429
+ super().__init__(
430
+ api_key=api_key,
431
+ base_url=base_url,
432
+ timeout=timeout,
433
+ max_retries=max_retries,
434
+ http_client=http_client,
435
+ )
436
+ self.account = AccountResource(self)
437
+ self.links = Links(self)
438
+ self.analytics = Analytics(self)
439
+ self.folders = Folders(self)
440
+ self.tags = Tags(self)
441
+ self.domains = Domains(self)
442
+
443
+ async def __aenter__(self) -> AsyncSendURL:
444
+ return self
445
+
446
+ async def __aexit__(
447
+ self,
448
+ exc_type: Optional[Type[BaseException]],
449
+ exc: Optional[BaseException],
450
+ tb: Optional[TracebackType],
451
+ ) -> None:
452
+ await self.aclose()