kickpython 0.1.5__py3-none-any.whl → 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.
kickpython/__init__.py CHANGED
@@ -1,9 +1,125 @@
1
- """
2
- KickPython - Python wrapper for Kick.com API
1
+ """kickpython: async Python client for the Kick.com API.
2
+
3
+ Official API: :class:`KickClient`. Webhooks: :class:`WebhookHandler`.
4
+ Unofficial websocket chat reader: :class:`LiveChat`.
3
5
  """
4
6
 
5
- from .api import KickAPI
7
+ from ._version import __version__
8
+ from .client import KickClient
9
+ from .errors import (
10
+ BadRequestError,
11
+ ConflictError,
12
+ ForbiddenError,
13
+ KickAPIError,
14
+ KickError,
15
+ MissingTokenError,
16
+ NotFoundError,
17
+ OAuthError,
18
+ RateLimitError,
19
+ ServerError,
20
+ UnauthorizedError,
21
+ WebhookVerificationError,
22
+ )
23
+ from .events import (
24
+ ChannelFollowed,
25
+ ChatMessage,
26
+ EventUser,
27
+ KicksGifted,
28
+ LivestreamMetadataUpdated,
29
+ LivestreamStatusUpdated,
30
+ ModerationBanned,
31
+ RewardRedemptionUpdated,
32
+ SubscriptionGifts,
33
+ SubscriptionNew,
34
+ SubscriptionRenewal,
35
+ WebhookEvent,
36
+ )
37
+ from .models import (
38
+ AdBreak,
39
+ AdBreakStatus,
40
+ Category,
41
+ Channel,
42
+ ChatMessageSent,
43
+ DropsClaim,
44
+ EventSubscription,
45
+ FailedRedemption,
46
+ KicksLeaderboard,
47
+ Livestream,
48
+ LivestreamsStats,
49
+ Page,
50
+ Reward,
51
+ RewardRedemption,
52
+ RewardRedemptions,
53
+ SubscriptionResult,
54
+ TokenInfo,
55
+ User,
56
+ )
57
+ from .oauth import AuthorizationRequest, build_authorization_url
58
+ from .realtime import ChannelRef, LiveChat, LiveChatMessage, RealtimeError
59
+ from .scopes import EventType, Scope
60
+ from .tokens import JSONFileTokenStore, MemoryTokenStore, SQLiteTokenStore, Token, TokenStore
61
+ from .webhooks import WebhookHandler, WebhookKeyUnavailable, parse_event, verify_signature
6
62
 
7
- __version__ = "0.1.0"
8
- __author__ = "berkay.digital"
9
- __all__ = ["KickAPI"]
63
+ __all__ = [
64
+ "AdBreak",
65
+ "AdBreakStatus",
66
+ "AuthorizationRequest",
67
+ "BadRequestError",
68
+ "Category",
69
+ "Channel",
70
+ "ChannelFollowed",
71
+ "ChannelRef",
72
+ "ChatMessage",
73
+ "ChatMessageSent",
74
+ "ConflictError",
75
+ "DropsClaim",
76
+ "EventSubscription",
77
+ "EventType",
78
+ "EventUser",
79
+ "FailedRedemption",
80
+ "ForbiddenError",
81
+ "JSONFileTokenStore",
82
+ "KickAPIError",
83
+ "KickClient",
84
+ "KickError",
85
+ "KicksGifted",
86
+ "KicksLeaderboard",
87
+ "LiveChat",
88
+ "LiveChatMessage",
89
+ "Livestream",
90
+ "LivestreamMetadataUpdated",
91
+ "LivestreamStatusUpdated",
92
+ "LivestreamsStats",
93
+ "MemoryTokenStore",
94
+ "MissingTokenError",
95
+ "ModerationBanned",
96
+ "NotFoundError",
97
+ "OAuthError",
98
+ "Page",
99
+ "RateLimitError",
100
+ "RealtimeError",
101
+ "Reward",
102
+ "RewardRedemption",
103
+ "RewardRedemptionUpdated",
104
+ "RewardRedemptions",
105
+ "SQLiteTokenStore",
106
+ "Scope",
107
+ "ServerError",
108
+ "SubscriptionGifts",
109
+ "SubscriptionNew",
110
+ "SubscriptionRenewal",
111
+ "SubscriptionResult",
112
+ "Token",
113
+ "TokenInfo",
114
+ "TokenStore",
115
+ "UnauthorizedError",
116
+ "User",
117
+ "WebhookEvent",
118
+ "WebhookHandler",
119
+ "WebhookKeyUnavailable",
120
+ "WebhookVerificationError",
121
+ "__version__",
122
+ "build_authorization_url",
123
+ "parse_event",
124
+ "verify_signature",
125
+ ]
kickpython/_http.py ADDED
@@ -0,0 +1,452 @@
1
+ """HTTP transport shared by a client and its user-bound views."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import email.utils
8
+ import functools
9
+ import json as jsonlib
10
+ import logging
11
+ import random
12
+ from collections.abc import AsyncIterator, Iterable, Mapping
13
+ from dataclasses import replace
14
+ from datetime import datetime, timezone
15
+ from typing import Any, Literal
16
+
17
+ import aiohttp
18
+
19
+ from ._version import __version__
20
+ from .errors import (
21
+ KickAPIError,
22
+ MissingTokenError,
23
+ OAuthError,
24
+ RateLimitError,
25
+ error_for_status,
26
+ )
27
+ from .tokens import MemoryTokenStore, Token, TokenStore
28
+
29
+ log = logging.getLogger("kickpython")
30
+
31
+ AuthMode = Literal["user", "any", "app", "none"]
32
+ """How a request authenticates.
33
+
34
+ ``user``: needs the bound user's token. ``any``: the bound user's token if
35
+ there is one, else an app token. ``app``: always an app token. ``none``: no
36
+ Authorization header.
37
+ """
38
+
39
+ DEFAULT_API_BASE = "https://api.kick.com"
40
+ DEFAULT_OAUTH_BASE = "https://id.kick.com"
41
+ REFRESH_MARGIN = 60.0 # refresh access tokens this many seconds before they expire
42
+ MAX_RETRY_SLEEP = 60.0
43
+
44
+ Params = Mapping[str, Any] | Iterable[tuple[str, Any]] | None
45
+
46
+
47
+ def _encode_params(params: Params) -> list[tuple[str, str]]:
48
+ """Flatten params. Lists become repeated keys; ``None`` values are dropped."""
49
+ if params is None:
50
+ return []
51
+ items = params.items() if isinstance(params, Mapping) else params
52
+ out: list[tuple[str, str]] = []
53
+ for key, value in items:
54
+ if value is None:
55
+ continue
56
+ if isinstance(value, (list, tuple, set, frozenset)):
57
+ out.extend((key, _scalar(v)) for v in value)
58
+ else:
59
+ out.append((key, _scalar(value)))
60
+ return out
61
+
62
+
63
+ def _scalar(value: Any) -> str:
64
+ if isinstance(value, bool):
65
+ return "true" if value else "false"
66
+ return str(value.value if hasattr(value, "value") else value)
67
+
68
+
69
+ class Transport:
70
+ def __init__(
71
+ self,
72
+ *,
73
+ client_id: str | None,
74
+ client_secret: str | None,
75
+ access_token: str | None,
76
+ token_store: TokenStore | None,
77
+ session: aiohttp.ClientSession | None,
78
+ user_agent: str | None,
79
+ api_base: str,
80
+ oauth_base: str,
81
+ timeout: float,
82
+ max_retries: int,
83
+ ) -> None:
84
+ self.client_id = client_id
85
+ self.client_secret = client_secret
86
+ self.static_token = access_token
87
+ self.store: TokenStore = token_store if token_store is not None else MemoryTokenStore()
88
+ self._session = session
89
+ self._owns_session = session is None
90
+ self.user_agent = (
91
+ user_agent
92
+ or f"kickpython/{__version__} (+https://github.com/berkay-digital/kickpython)"
93
+ )
94
+ self.api_base = api_base.rstrip("/")
95
+ self.oauth_base = oauth_base.rstrip("/")
96
+ self.timeout = aiohttp.ClientTimeout(total=timeout)
97
+ self.max_retries = max(0, max_retries)
98
+ self._app_token: Token | None = None
99
+ self._app_lock = asyncio.Lock()
100
+ self._user_locks: dict[int, asyncio.Lock] = {}
101
+ # One in-flight refresh per user. It survives a cancelled caller, and
102
+ # the next caller for that user joins it instead of reusing the old
103
+ # (now dead) refresh token.
104
+ self._refreshing: dict[int, asyncio.Task[Token]] = {}
105
+
106
+ # Session --------------------------------------------------------------
107
+
108
+ @property
109
+ def session(self) -> aiohttp.ClientSession:
110
+ if self._session is None or self._session.closed:
111
+ if not self._owns_session:
112
+ raise RuntimeError("the aiohttp session passed to KickClient is closed")
113
+ self._session = aiohttp.ClientSession(timeout=self.timeout)
114
+ return self._session
115
+
116
+ async def close(self) -> None:
117
+ if self._owns_session and self._session is not None and not self._session.closed:
118
+ await self._session.close()
119
+ self._session = None
120
+
121
+ # OAuth server ---------------------------------------------------------
122
+
123
+ def require_credentials(self) -> tuple[str, str]:
124
+ if not self.client_id or not self.client_secret:
125
+ raise MissingTokenError(
126
+ "client_id and client_secret are required for this (OAuth token requests)"
127
+ )
128
+ return self.client_id, self.client_secret
129
+
130
+ async def oauth_post(
131
+ self,
132
+ path: str,
133
+ *,
134
+ form: Mapping[str, str] | None = None,
135
+ params: Params = None,
136
+ bearer: str | None = None,
137
+ ) -> Any:
138
+ headers = {"User-Agent": self.user_agent, "Accept": "application/json"}
139
+ if bearer:
140
+ headers["Authorization"] = f"Bearer {bearer}"
141
+ if form is not None:
142
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
143
+ url = f"{self.oauth_base}{path}"
144
+ async with self.session.post(
145
+ url,
146
+ data=dict(form) if form is not None else None,
147
+ params=_encode_params(params),
148
+ headers=headers,
149
+ ) as resp:
150
+ text = await resp.text()
151
+ if resp.status >= 400:
152
+ raise OAuthError(
153
+ f"{resp.status} from {path}: {_short(text)}", status=resp.status, body=text
154
+ )
155
+ if not text.strip():
156
+ return None
157
+ try:
158
+ return await resp.json(content_type=None)
159
+ except ValueError:
160
+ return text
161
+
162
+ async def fetch_app_token(self) -> Token:
163
+ client_id, secret = self.require_credentials()
164
+ data = await self.oauth_post(
165
+ "/oauth/token",
166
+ form={
167
+ "grant_type": "client_credentials",
168
+ "client_id": client_id,
169
+ "client_secret": secret,
170
+ },
171
+ )
172
+ return Token.from_oauth_response(data)
173
+
174
+ async def app_token(self, *, force: bool = False, failed: str | None = None) -> Token:
175
+ async with self._app_lock:
176
+ tok = self._app_token
177
+ if tok is not None and failed is not None and tok.access_token != failed:
178
+ return tok # someone else already replaced the failing token
179
+ if force or tok is None or tok.is_expired(REFRESH_MARGIN):
180
+ tok = await self.fetch_app_token()
181
+ self._app_token = tok
182
+ log.debug("fetched new app access token")
183
+ return tok
184
+
185
+ async def refresh(self, token: Token) -> Token:
186
+ """Refresh ``token`` and save the result.
187
+
188
+ Kick rotates the refresh token, so once the request is sent the old
189
+ pair is dead. The exchange and the save run in their own task: if the
190
+ caller is cancelled (a timeout, say) the task still finishes and saves
191
+ the new pair, and the next request for this user waits for it.
192
+ """
193
+ self.require_credentials()
194
+ if not token.refresh_token:
195
+ raise MissingTokenError(f"token for user {token.user_id} has no refresh token")
196
+ assert token.user_id is not None
197
+ uid = token.user_id
198
+ task = self._refreshing.get(uid)
199
+ if task is None or task.done():
200
+ task = asyncio.ensure_future(self._refresh_and_save(token))
201
+ self._refreshing[uid] = task
202
+ task.add_done_callback(functools.partial(self._forget_refresh, uid))
203
+ return await asyncio.shield(task)
204
+
205
+ def _forget_refresh(self, user_id: int, task: asyncio.Task[Token]) -> None:
206
+ if self._refreshing.get(user_id) is task:
207
+ del self._refreshing[user_id]
208
+ if not task.cancelled():
209
+ task.exception() # mark retrieved; callers already got it
210
+
211
+ @contextlib.asynccontextmanager
212
+ async def exclusive_user(self, user_id: int) -> AsyncIterator[None]:
213
+ """Hold a user's token lock with no refresh in flight."""
214
+ async with self._lock_for(user_id):
215
+ pending = self._refreshing.get(user_id)
216
+ if pending is not None:
217
+ with contextlib.suppress(Exception):
218
+ await asyncio.shield(pending)
219
+ yield
220
+
221
+ async def _refresh_and_save(self, token: Token) -> Token:
222
+ client_id, secret = self.require_credentials()
223
+ assert token.refresh_token is not None and token.user_id is not None
224
+ try:
225
+ data = await self.oauth_post(
226
+ "/oauth/token",
227
+ form={
228
+ "grant_type": "refresh_token",
229
+ "client_id": client_id,
230
+ "client_secret": secret,
231
+ "refresh_token": token.refresh_token,
232
+ },
233
+ )
234
+ except OAuthError as exc:
235
+ if exc.status in (400, 401):
236
+ # Another process sharing the store may have refreshed first.
237
+ current = await self.store.get(token.user_id)
238
+ if current is not None and current.refresh_token != token.refresh_token:
239
+ log.info("token for user %s was refreshed elsewhere", token.user_id)
240
+ return current
241
+ raise MissingTokenError(
242
+ f"refreshing the token for user {token.user_id} failed ({exc.status}); "
243
+ "the user needs to authorize the app again"
244
+ ) from exc
245
+ raise
246
+ new = Token.from_oauth_response(data, user_id=token.user_id)
247
+ if not new.scopes:
248
+ new = replace(new, scopes=token.scopes)
249
+ if not new.refresh_token:
250
+ new = replace(
251
+ new, refresh_token=token.refresh_token, refresh_expires_at=token.refresh_expires_at
252
+ )
253
+ try:
254
+ await self.store.set(new)
255
+ except Exception:
256
+ log.critical(
257
+ "refreshed the token for user %s but could not save it; the old refresh "
258
+ "token no longer works",
259
+ token.user_id,
260
+ exc_info=True,
261
+ )
262
+ raise
263
+ log.info("refreshed access token for user %s", token.user_id)
264
+ return new
265
+
266
+ def _lock_for(self, user_id: int) -> asyncio.Lock:
267
+ lock = self._user_locks.get(user_id)
268
+ if lock is None:
269
+ lock = self._user_locks[user_id] = asyncio.Lock()
270
+ return lock
271
+
272
+ async def user_token(
273
+ self, user_id: int, *, force: bool = False, failed: str | None = None
274
+ ) -> Token:
275
+ async with self._lock_for(user_id):
276
+ pending = self._refreshing.get(user_id)
277
+ if pending is not None:
278
+ # A refresh from a cancelled caller is still running: use its result.
279
+ with contextlib.suppress(Exception):
280
+ await asyncio.shield(pending)
281
+ tok = await self.store.get(user_id)
282
+ if tok is None:
283
+ raise MissingTokenError(
284
+ f"no token stored for user {user_id}; run the OAuth flow for this user first"
285
+ )
286
+ if failed is not None and tok.access_token != failed:
287
+ return tok
288
+ if force or tok.is_expired(REFRESH_MARGIN):
289
+ tok = await self.refresh(tok)
290
+ return tok
291
+
292
+ async def _introspect(self, token: str | None) -> dict[str, Any] | None:
293
+ if not token:
294
+ return None
295
+ try:
296
+ body = await self.oauth_post("/oauth/token/introspect", bearer=token)
297
+ except (OAuthError, aiohttp.ClientError, asyncio.TimeoutError):
298
+ return None
299
+ data = body.get("data") if isinstance(body, dict) else None
300
+ return data if isinstance(data, dict) else None
301
+
302
+ # API server -----------------------------------------------------------
303
+
304
+ async def _bearer(self, auth: AuthMode, user_id: int | None) -> tuple[str | None, str]:
305
+ """Return (access token, kind) where kind is static/user/app/none."""
306
+ if auth == "none":
307
+ return None, "none"
308
+ if auth in ("user", "any") and user_id is not None:
309
+ # A bound user always means that user's stored token, never the fixed one.
310
+ return (await self.user_token(user_id)).access_token, "user"
311
+ if self.static_token:
312
+ return self.static_token, "static"
313
+ if auth == "user":
314
+ raise MissingTokenError(
315
+ "this endpoint needs a user access token: use client.as_user(user_id) "
316
+ "or pass access_token="
317
+ )
318
+ return (await self.app_token()).access_token, "app"
319
+
320
+ async def request(
321
+ self,
322
+ method: str,
323
+ path: str,
324
+ *,
325
+ auth: AuthMode = "any",
326
+ user_id: int | None = None,
327
+ params: Params = None,
328
+ json: Any = None,
329
+ ) -> Any:
330
+ """Call the API and return the decoded JSON body (``None`` for empty bodies)."""
331
+ url = f"{self.api_base}{path}"
332
+ query = _encode_params(params)
333
+ token, kind = await self._bearer(auth, user_id)
334
+ reauthed = False
335
+ attempt = 0
336
+ while True:
337
+ headers = {"User-Agent": self.user_agent, "Accept": "application/json"}
338
+ if token:
339
+ headers["Authorization"] = f"Bearer {token}"
340
+ try:
341
+ async with self.session.request(
342
+ method, url, params=query, json=json, headers=headers
343
+ ) as resp:
344
+ status = resp.status
345
+ text = await resp.text()
346
+ retry_after = resp.headers.get("Retry-After")
347
+ except (aiohttp.ClientConnectionError, asyncio.TimeoutError) as exc:
348
+ if method == "GET" and attempt < self.max_retries:
349
+ attempt += 1
350
+ await asyncio.sleep(_backoff(attempt))
351
+ log.warning("%s %s failed (%s), retrying", method, path, exc)
352
+ continue
353
+ raise
354
+
355
+ if status < 400:
356
+ return _decode(text)
357
+
358
+ if status == 401 and not reauthed and kind in ("user", "app"):
359
+ reauthed = True
360
+ # Kick also answers 401 when a valid token lacks the endpoint's
361
+ # scope. Refreshing can't fix that, so check the token first.
362
+ info = await self._introspect(token)
363
+ if info is not None and info.get("active"):
364
+ err = _api_error(status, text, method, path, retry_after)
365
+ scopes = info.get("scope") or "none"
366
+ err.args = (
367
+ f"{err.args[0]}: the {kind} token is valid, so it most likely lacks "
368
+ f"the scope this endpoint needs (token scopes: {scopes})",
369
+ )
370
+ raise err
371
+ log.info("%s %s returned 401, refreshing the %s token", method, path, kind)
372
+ if kind == "user":
373
+ assert user_id is not None
374
+ token = (await self.user_token(user_id, force=True, failed=token)).access_token
375
+ else:
376
+ token = (await self.app_token(force=True, failed=token)).access_token
377
+ continue
378
+
379
+ wait: float | None = None
380
+ if status == 429:
381
+ parsed = _parse_retry_after(retry_after)
382
+ wait = parsed if parsed is not None else _backoff(attempt + 1)
383
+ elif status >= 500 and method == "GET":
384
+ wait = _backoff(attempt + 1)
385
+ if wait is not None and attempt < self.max_retries and wait <= MAX_RETRY_SLEEP:
386
+ attempt += 1
387
+ log.warning("%s %s returned %s, retrying in %.1fs", method, path, status, wait)
388
+ await asyncio.sleep(wait)
389
+ continue
390
+
391
+ raise _api_error(status, text, method, path, retry_after)
392
+
393
+
394
+ def _decode(text: str) -> Any:
395
+ if not text.strip():
396
+ return None
397
+ try:
398
+ return jsonlib.loads(text)
399
+ except ValueError:
400
+ return text
401
+
402
+
403
+ def _api_error(
404
+ status: int, text: str, method: str, path: str, retry_after: str | None
405
+ ) -> KickAPIError:
406
+ body = _decode(text)
407
+ message, data = "", None
408
+ if isinstance(body, dict):
409
+ message = str(body.get("message") or "")
410
+ data = body.get("data")
411
+ if not message and isinstance(data, dict):
412
+ message = str(data.get("type") or data.get("message") or "")
413
+ elif isinstance(body, str):
414
+ message = _short(body)
415
+ cls = error_for_status(status)
416
+ message = message or "request failed"
417
+ if cls is RateLimitError:
418
+ return RateLimitError(
419
+ status,
420
+ message,
421
+ data=data,
422
+ method=method,
423
+ url=path,
424
+ retry_after=_parse_retry_after(retry_after),
425
+ )
426
+ return cls(status, message, data=data, method=method, url=path)
427
+
428
+
429
+ def _parse_retry_after(value: str | None) -> float | None:
430
+ if not value:
431
+ return None
432
+ try:
433
+ return max(0.0, float(value))
434
+ except ValueError:
435
+ pass
436
+ try: # RFC 9110 also allows an HTTP date
437
+ when = email.utils.parsedate_to_datetime(value)
438
+ except (TypeError, ValueError):
439
+ return None
440
+ if when.tzinfo is None:
441
+ when = when.replace(tzinfo=timezone.utc)
442
+ return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
443
+
444
+
445
+ def _backoff(attempt: int) -> float:
446
+ delay: float = min(MAX_RETRY_SLEEP, 0.5 * 2.0 ** (attempt - 1))
447
+ return delay + random.uniform(0, 0.25)
448
+
449
+
450
+ def _short(text: str, limit: int = 300) -> str:
451
+ text = text.strip().replace("\n", " ")
452
+ return text if len(text) <= limit else text[:limit] + "..."
kickpython/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"