python-loading-sdk 0.4.0__py3-none-any.whl → 0.5.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.
@@ -1,180 +1,138 @@
1
- import math
2
-
3
- import aiohttp
4
- from loading_sdk.settings import (
5
- API_URL,
6
- API_VERSION,
7
- EDITORIAL_POST_TYPES,
8
- EDITORIAL_SORT,
9
- FORUM_CATEGORIES,
10
- POSTS_PER_PAGE,
11
- USER_AGENT,
12
- )
13
- from loading_sdk.async_api.extractors import extract_data
14
-
15
-
16
- async def async_loading_api_client(email=None, password=None):
17
- client = AsyncLoadingApiClient()
18
- await client._set_cookie(email, password)
19
-
1
+ import asyncio
2
+ from collections.abc import AsyncGenerator
3
+ from contextlib import asynccontextmanager
4
+ from typing import Any, Self
5
+
6
+ import httpx
7
+
8
+ from loading_sdk import _api, _http
9
+ from loading_sdk._api import Operation, T
10
+
11
+
12
+ async def async_loading_api_client(
13
+ email: str | None = None,
14
+ password: str | None = None,
15
+ *,
16
+ transport: httpx.AsyncBaseTransport | None = None,
17
+ timeout: float = 300.0,
18
+ ) -> "AsyncLoadingApiClient":
19
+ client = AsyncLoadingApiClient(transport=transport, timeout=timeout)
20
+ if email and password:
21
+ try:
22
+ login = await client._authenticate(email, password)
23
+ if login.get("code") == 200:
24
+ client._cookies = login.get("cookies")
25
+ except BaseException:
26
+ await client.aclose()
27
+ raise
20
28
  return client
21
29
 
22
30
 
23
31
  class AsyncLoadingApiClient:
24
- """
25
- An async client that allows python apps to easily communicate with the loading forums web api.
26
-
27
- Some methods can be used anonymously, while others require the client to be authenticated
28
- with user credentials.
29
-
30
- :param email: users email address (**optional**)
31
- :type email: str
32
- :param password: users password (**optional**)
33
- :type password: str
34
- """
35
-
36
- def __init__(self):
37
- self._cookies = None
38
-
39
- async def _set_cookie(self, email, password):
40
- if email and password:
41
- response = await self._authenticate(email, password)
42
-
43
- if response.get("code") == 200:
44
- self._cookies = response.get("cookies")
45
-
46
- async def _authenticate(self, email, password):
47
- url = f"{API_URL}/{API_VERSION}/auth/login"
48
- headers = {
49
- "User-Agent": USER_AGENT,
50
- "content-type": "application/x-www-form-urlencoded",
51
- }
52
- data = {
53
- "email": email,
54
- "password": password,
55
- }
56
-
57
- async with aiohttp.ClientSession() as session:
58
- async with session.post(url, headers=headers, data=data) as response:
59
- if response.status == 200:
60
- return {"code": response.status, "cookies": response.cookies}
61
-
62
- return await response.json()
63
-
64
- async def _get_threads_in_forum_category(self, category_name, page):
65
- url = f"{API_URL}/{API_VERSION}/posts/"
66
- headers = {"User-Agent": USER_AGENT, category_name: category_name}
67
-
68
- # Chooses a specific page instead of the first page which is the default page.
69
- if page and page > 1:
70
- headers["page"] = str(page)
71
-
72
- # Doing this checks to make sure it only return data from a page that exists.
73
- if page and page < 1:
74
- return {
75
- "code": 404,
76
- "message": "Page number too low",
77
- "data": {"posts": [], "users": []},
78
- }
79
-
80
- async with aiohttp.ClientSession() as session:
81
- async with session.get(url, headers=headers) as response:
82
- data = await response.json()
83
-
84
- # Page out of range.
85
- if not data["posts"]:
86
- return {
87
- "code": 404,
88
- "message": "Page number too high",
89
- "data": data,
90
- }
91
-
92
- return {
93
- "code": response.status,
94
- "message": "OK",
95
- "data": data,
96
- }
97
-
98
- async def get_profile(self):
32
+ """Async Loading.se client. Use an async context manager to reuse connections."""
33
+
34
+ def __init__(
35
+ self,
36
+ *,
37
+ transport: httpx.AsyncBaseTransport | None = None,
38
+ timeout: float = 300.0,
39
+ ) -> None:
40
+ self._timeout = timeout
41
+ self._transport = transport
42
+ self._client = self._new_client() if transport is not None else None
43
+ self._closed = False
44
+ self._entered = False
45
+ self._cookies: httpx.Cookies | None = None
46
+
47
+ def _new_client(self) -> httpx.AsyncClient:
48
+ return httpx.AsyncClient(
49
+ transport=self._transport,
50
+ timeout=httpx.Timeout(self._timeout, connect=min(30.0, self._timeout)),
51
+ follow_redirects=True,
52
+ event_hooks={
53
+ "request": [_http.async_before_send],
54
+ "response": [_http.async_after_receive],
55
+ },
56
+ )
57
+
58
+ async def __aenter__(self) -> Self:
59
+ if self._closed or self._entered:
60
+ raise RuntimeError("SDK client is closed or already entered")
61
+ if self._client is None:
62
+ self._client = self._new_client()
63
+ self._entered = True
64
+ return self
65
+
66
+ async def __aexit__(self, exc_type, exc_value, traceback) -> None:
67
+ await self.aclose()
68
+
69
+ async def aclose(self) -> None:
70
+ """Close the SDK-owned connection pool and any supplied transport."""
71
+ if not self._closed and self._client is not None:
72
+ await self._client.aclose()
73
+ self._closed = True
74
+
75
+ @asynccontextmanager
76
+ async def _session(self) -> AsyncGenerator[httpx.AsyncClient, None]:
77
+ if self._client is not None:
78
+ yield self._client
79
+ else:
80
+ async with self._new_client() as client:
81
+ yield client
82
+
83
+ async def _run(self, operation: Operation[T]) -> T:
84
+ if self._closed:
85
+ raise RuntimeError("SDK client is closed")
86
+ try:
87
+ req = next(operation)
88
+ except StopIteration as done:
89
+ return done.value
90
+ async with self._session() as client:
91
+ while True:
92
+ _http.prepare(req, self._cookies)
93
+ try:
94
+ async with asyncio.timeout(self._timeout):
95
+ response = await client.send(req)
96
+ except TimeoutError as exc:
97
+ raise httpx.TimeoutException(
98
+ "Request exceeded its total timeout", request=req
99
+ ) from exc
100
+ try:
101
+ req = operation.send(response)
102
+ except StopIteration as done:
103
+ return done.value
104
+
105
+ async def _authenticate(self, email: str, password: str) -> dict[str, Any]:
106
+ return await self._run(_api.authenticate(email, password))
107
+
108
+ async def get_profile(self) -> dict[str, Any]:
99
109
  """Returns authenticated users profile data
100
110
 
101
111
  :rtype: dict
102
112
  """
113
+ return await self._run(_api.get_profile())
103
114
 
104
- url = f"{API_URL}/{API_VERSION}/users/profile"
105
- headers = {"User-Agent": USER_AGENT}
106
-
107
- async with aiohttp.ClientSession() as session:
108
- async with session.get(
109
- url, headers=headers, cookies=self._cookies
110
- ) as response:
111
- data = await response.json()
112
-
113
- if response.status == 200:
114
- return {
115
- "code": response.status,
116
- "message": "OK",
117
- "data": data,
118
- }
119
-
120
- return data
121
-
122
- async def search(self, query):
115
+ async def search(self, query: str) -> dict[str, Any]:
123
116
  """Returns posts that matches the query
124
117
 
125
118
  :param query: Search query
126
119
  :type query: str
127
120
  :rtype: dict
128
121
  """
122
+ return await self._run(_api.search(query))
129
123
 
130
- url = f"{API_URL}/{API_VERSION}/search/"
131
- headers = {
132
- "User-Agent": USER_AGENT,
133
- "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
134
- }
135
- data = {"query": query}
136
-
137
- async with aiohttp.ClientSession() as session:
138
- async with session.post(url, headers=headers, data=data) as response:
139
- data = await response.json()
140
-
141
- if response.status == 200:
142
- return {
143
- "code": response.status,
144
- "message": "OK" if len(data["posts"]) else "No results",
145
- "data": data,
146
- }
147
-
148
- return data
149
-
150
- async def get_post(self, post_id):
124
+ async def get_post(self, post_id: str) -> dict[str, Any]:
151
125
  """Returns a specific post
152
126
 
153
127
  :param post_id: unique post id
154
128
  :type post_id: str
155
129
  :rtype: dict
156
130
  """
131
+ return await self._run(_api.get_post(post_id))
157
132
 
158
- if not post_id:
159
- return {"code": 404, "message": '"post_id" is not allowed to be empty'}
160
-
161
- url = f"{API_URL}/{API_VERSION}/posts/{post_id}"
162
- headers = {"User-Agent": USER_AGENT}
163
-
164
- async with aiohttp.ClientSession() as session:
165
- async with session.get(url, headers=headers) as response:
166
- data = await response.json()
167
-
168
- if response.status == 200:
169
- return {
170
- "code": response.status,
171
- "message": "OK",
172
- "data": data,
173
- }
174
-
175
- return data
176
-
177
- async def get_thread(self, thread_id, page=None):
133
+ async def get_thread(
134
+ self, thread_id: str, page: int | None = None
135
+ ) -> dict[str, Any]:
178
136
  """Returns all posts on a specific page from a specific thread
179
137
 
180
138
  :param thread_id: unique thread_id
@@ -183,89 +141,32 @@ class AsyncLoadingApiClient:
183
141
  :type page: int
184
142
  :rtype: dict
185
143
  """
144
+ return await self._run(_api.get_thread(thread_id, page))
186
145
 
187
- if not thread_id:
188
- return {"code": 404, "message": '"thread_id" is not allowed to be empty'}
189
-
190
- url = f"{API_URL}/{API_VERSION}/posts/{thread_id}"
191
- headers = {"User-Agent": USER_AGENT}
192
-
193
- # Chooses a specific page instead of the first page which is the default page.
194
- if page and page > 1:
195
- headers["page"] = str(page)
196
-
197
- async with aiohttp.ClientSession() as session:
198
- async with session.get(url, headers=headers) as response:
199
- data = await response.json()
200
-
201
- if response.status != 200:
202
- return data
203
-
204
- if "title" not in data["posts"][-1]:
205
- return {
206
- "code": response.status,
207
- "message": "Exists, but was not a thread id",
208
- }
209
-
210
- # Doing this checks to make sure it only return data from a page that exists.
211
- if page:
212
- replies = data["posts"][-1]["replies"]
213
- pages = math.ceil(replies / 30)
214
-
215
- # There is always atleast one page.
216
- if pages == 0:
217
- pages = 1
218
-
219
- # Page is out of range.
220
- if page < 1:
221
- return {
222
- "code": response.status,
223
- "message": "Page number too low",
224
- "data": {"posts": [], "users": []},
225
- }
226
-
227
- if page > pages:
228
- return {
229
- "code": response.status,
230
- "message": "Page number too high",
231
- "data": {"posts": [], "users": []},
232
- }
233
-
234
- successful_response = {
235
- "code": response.status,
236
- "message": "OK",
237
- "data": data,
238
- }
239
-
240
- return successful_response
241
-
242
- async def get_games(self, page=None):
146
+ async def get_games(self, page: int | None = None) -> dict[str, Any]:
243
147
  """Retruns threads from a specific page in the game category
244
148
 
245
149
  :param page: Game forum page
246
150
  :type page: int
247
151
  :rtype: dict
248
152
  """
153
+ return await self._run(_api.category_page("games", page))
249
154
 
250
- category_name = "games"
251
- thread_data = await self._get_threads_in_forum_category(category_name, page)
252
-
253
- return thread_data
254
-
255
- async def get_other(self, page=None):
155
+ async def get_other(self, page: int | None = None) -> dict[str, Any]:
256
156
  """Retruns threads from a specific page in the other category
257
157
 
258
158
  :param page: Other forum page
259
159
  :type page: int
260
160
  :rtype: dict
261
161
  """
262
-
263
- category_name = "other"
264
- thread_data = await self._get_threads_in_forum_category(category_name, page)
265
-
266
- return thread_data
267
-
268
- async def get_editorials(self, page=None, post_type=None, sort=None):
162
+ return await self._run(_api.category_page("other", page))
163
+
164
+ async def get_editorials(
165
+ self,
166
+ page: int | None = None,
167
+ post_type: str | None = None,
168
+ sort: str | None = None,
169
+ ) -> dict[str, Any]:
269
170
  """Retruns threads from a specific page in the texts category
270
171
 
271
172
  :param page: Texts forum page (**optional**)
@@ -278,51 +179,9 @@ class AsyncLoadingApiClient:
278
179
  :type sort: str
279
180
  :rtype: dict
280
181
  """
182
+ return await self._run(_api.category_page("texts", page, post_type, sort))
281
183
 
282
- url = f"{API_URL}/{API_VERSION}/posts/"
283
- headers = {
284
- "User-Agent": USER_AGENT,
285
- "texts": "texts",
286
- "post-type": "neRegular",
287
- }
288
-
289
- if post_type and post_type in EDITORIAL_POST_TYPES:
290
- headers["post-type"] = post_type
291
-
292
- if sort and sort in EDITORIAL_SORT:
293
- headers["sort"] = sort
294
-
295
- # Chooses a specific page instead of the first page which is the default page.
296
- if page and page > 1:
297
- headers["page"] = str(page)
298
-
299
- # Doing this checks to make sure it only return data from a page that exists.
300
- if page and page < 1:
301
- return {
302
- "code": 404,
303
- "message": "Page number too low",
304
- "data": {"posts": [], "users": []},
305
- }
306
-
307
- async with aiohttp.ClientSession() as session:
308
- async with session.get(url, headers=headers) as response:
309
- data = await response.json()
310
-
311
- # Page out of range.
312
- if not data["posts"]:
313
- return {
314
- "code": 404,
315
- "message": "Page number too high",
316
- "data": data,
317
- }
318
-
319
- return {
320
- "code": response.status,
321
- "message": "OK",
322
- "data": data,
323
- }
324
-
325
- async def create_post(self, thread_id, message):
184
+ async def create_post(self, thread_id: str, message: str) -> dict[str, Any]:
326
185
  """Create new post in a thread
327
186
 
328
187
  :param thread_id: Unique thread id
@@ -331,45 +190,9 @@ class AsyncLoadingApiClient:
331
190
  :type message: str
332
191
  :rtype: dict
333
192
  """
193
+ return await self._run(_api.create_post(thread_id, message))
334
194
 
335
- if not thread_id:
336
- return {"code": 400, "message": '"thread_id" is not allowed to be empty'}
337
-
338
- url = f"{API_URL}/{API_VERSION}/posts/{thread_id}"
339
- headers = {
340
- "User-Agent": USER_AGENT,
341
- "content-type": "application/x-www-form-urlencoded",
342
- }
343
- data = {"body": message}
344
-
345
- async with aiohttp.ClientSession() as session:
346
- async with session.post(
347
- url,
348
- headers=headers,
349
- data=data,
350
- cookies=self._cookies,
351
- ) as response:
352
- data = await response.json()
353
-
354
- # Has no auth token.
355
- if response.status == 401:
356
- return data
357
-
358
- # Post id doesn't exist.
359
- if response.status == 404:
360
- return data
361
-
362
- if response.status == 201:
363
- return {
364
- "code": response.status,
365
- "message": "Post created",
366
- "data": data,
367
- }
368
-
369
- # Handle any other unknown status code.
370
- return data
371
-
372
- async def edit_post(self, post_id, message):
195
+ async def edit_post(self, post_id: str, message: str) -> dict[str, Any]:
373
196
  """Edit existing post in a thread
374
197
 
375
198
  :param post_id: Unique post id
@@ -379,44 +202,11 @@ class AsyncLoadingApiClient:
379
202
  :type message: str
380
203
  :rtype: dict
381
204
  """
382
- if not message:
383
- return {"code": 400, "message": '"message" is not allowed to be empty'}
384
-
385
- url = f"{API_URL}/{API_VERSION}/posts/{post_id}"
386
- headers = {
387
- "User-Agent": USER_AGENT,
388
- "content-type": "application/x-www-form-urlencoded",
389
- }
390
- data = {"body": message}
391
-
392
- async with aiohttp.ClientSession() as session:
393
- async with session.patch(
394
- url,
395
- headers=headers,
396
- data=data,
397
- cookies=self._cookies,
398
- ) as response:
399
- data = await response.json()
400
-
401
- # Has no auth token.
402
- if response.status == 401:
403
- return data
404
-
405
- # Post id doesn't exist.
406
- if response.status == 404:
407
- return data
408
-
409
- if response.status == 200:
410
- return {
411
- "code": response.status,
412
- "message": "Post updated",
413
- "data": data,
414
- }
415
-
416
- # Handle any other unknown status code.
417
- return data
418
-
419
- async def create_thread(self, title, message, category_name, post_type=None):
205
+ return await self._run(_api.edit_post(post_id, message))
206
+
207
+ async def create_thread(
208
+ self, title: str, message: str, category_name: str, post_type: str | None = None
209
+ ) -> dict[str, Any]:
420
210
  """Create new thread in one of the forum categories
421
211
 
422
212
  :param title: Thread title
@@ -428,55 +218,11 @@ class AsyncLoadingApiClient:
428
218
  :param post_type: Creates a "regular" thread by the default. (**optional**)
429
219
  :rtype: dict
430
220
  """
431
- if category_name not in ["games", "other"]:
432
- return {"code": 400, "message": "Invalid forum category"}
433
-
434
- if post_type and post_type not in EDITORIAL_POST_TYPES:
435
- return {"code": 400, "message": "Invalid post_type"}
436
-
437
- if not post_type:
438
- post_type = "regular"
439
-
440
- url = f"{API_URL}/{API_VERSION}/posts/"
441
- headers = {
442
- "User-Agent": USER_AGENT,
443
- "content-type": "application/x-www-form-urlencoded",
444
- }
445
- data = {
446
- "category": category_name,
447
- "postType": post_type,
448
- "title": title,
449
- "body": message,
450
- }
451
- async with aiohttp.ClientSession() as session:
452
- async with session.post(
453
- url,
454
- headers=headers,
455
- data=data,
456
- cookies=self._cookies,
457
- ) as response:
458
- data = await response.json()
459
-
460
- # Validation errors. Happens when title or message is empty.
461
- # Possibly in other cases too.
462
- if response.status == 400:
463
- return data
464
-
465
- # No auth token.
466
- if response.status == 401:
467
- return data
468
-
469
- if response.status == 201:
470
- return {
471
- "code": response.status,
472
- "message": "Thread created",
473
- "data": data,
474
- }
475
-
476
- # Handle any other unknown status code.
477
- return data
478
-
479
- async def edit_thread(self, thread_id, message):
221
+ return await self._run(
222
+ _api.create_thread(title, message, category_name, post_type)
223
+ )
224
+
225
+ async def edit_thread(self, thread_id: str, message: str) -> dict[str, Any]:
480
226
  """Edit existing thread
481
227
 
482
228
  :param thread_id: Unique thread id
@@ -486,113 +232,37 @@ class AsyncLoadingApiClient:
486
232
  :type message: str
487
233
  :rtype: dict
488
234
  """
235
+ return await self._run(_api.edit_thread(thread_id, message))
489
236
 
490
- thread_data = await self.edit_post(thread_id, message)
491
-
492
- if thread_data["code"] == 200:
493
- thread_data["message"] = "Thread updated"
494
-
495
- return thread_data
496
-
497
- async def get_about(self):
237
+ async def get_about(self) -> dict[str, Any]:
498
238
  """Get about page data
499
239
 
500
240
  :rtype dict
501
241
  """
242
+ return await self._run(_api.get_about())
502
243
 
503
- data = await extract_data("about")
504
-
505
- if not data:
506
- return {"code": 404, "message": "No data found", "data": None}
507
-
508
- return {"code": 200, "message": "OK", "data": data}
509
-
510
- async def get_socials(self):
244
+ async def get_socials(self) -> dict[str, Any]:
511
245
  """Get social media links
512
246
 
513
247
  :rtype dict
514
248
  """
249
+ return await self._run(_api.get_socials())
515
250
 
516
- data = await extract_data("socials")
517
-
518
- if not data:
519
- return {"code": 404, "message": "No results found", "data": None}
520
-
521
- return {"code": 200, "message": "OK", "data": data}
522
-
523
- async def get_total_thread_pages(self, thread_id):
251
+ async def get_total_thread_pages(self, thread_id: str) -> int | dict[str, Any]:
524
252
  """Returns total pages of a thread.
525
253
 
526
254
  :param thread_id: Unique thread id
527
255
  :type thread_id: str
528
- :rtype: dict
256
+ :returns: The page count, or the error dictionary returned by get_thread.
257
+ :rtype: int | dict
529
258
  """
259
+ return await self._run(_api.get_total_thread_pages(thread_id))
530
260
 
531
- response = await self.get_thread(thread_id)
532
-
533
- if response["code"] != 200:
534
- return response
535
-
536
- thread_start = response["data"]["posts"][-1]
537
- replies = max(thread_start["replies"], 1)
538
- pages = math.ceil(replies / POSTS_PER_PAGE)
539
-
540
- return pages
541
-
542
- async def get_total_category_pages(self, category):
261
+ async def get_total_category_pages(self, category: str) -> dict[str, Any]:
543
262
  """Returns total pages of a forum category.
544
263
 
545
264
  :param category: Category name. Can be games, other, or texts
546
265
  :type category: str
547
266
  :rtype: dict
548
267
  """
549
-
550
- if category not in FORUM_CATEGORIES:
551
- return {"code": 404, "message": "Invalid category", "data": None}
552
-
553
- working_page = None
554
- current_page = 1
555
- url = f"{API_URL}/{API_VERSION}/posts/"
556
- headers = {
557
- "User-Agent": USER_AGENT,
558
- "page": str(current_page),
559
- category: category,
560
- }
561
-
562
- if category == "texts":
563
- headers["post-type"] = "neRegular"
564
-
565
- async with aiohttp.ClientSession() as session:
566
- # Double current page until no results are returned
567
- # then we know all pages after that won't work either.
568
- while True:
569
- headers["page"] = str(current_page)
570
- async with session.get(url, headers=headers) as response:
571
- data = await response.json()
572
-
573
- if not data["posts"]:
574
- break
575
-
576
- working_page = current_page
577
- current_page *= 2
578
-
579
- # Check the page in the middle of highest known working page and
580
- # current page until they have the same page number.
581
- while True:
582
- page = working_page + (current_page - working_page) / 2
583
- headers["page"] = str(page)
584
-
585
- async with session.get(url, headers=headers) as response:
586
- data = await response.json()
587
-
588
- if data["posts"]:
589
- working_page = page
590
- else:
591
- current_page = page
592
-
593
- if math.floor(current_page) == math.floor(working_page):
594
- break
595
-
596
- total_pages = math.floor(working_page)
597
-
598
- return total_pages
268
+ return await self._run(_api.get_total_category_pages(category))