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