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.
- loading_sdk/__init__.py +1 -1
- loading_sdk/_api.py +254 -0
- loading_sdk/_http.py +47 -0
- loading_sdk/_parsing.py +70 -0
- loading_sdk/async_api/client.py +149 -479
- loading_sdk/async_api/extractors.py +18 -80
- loading_sdk/sync_api/client.py +126 -443
- loading_sdk/sync_api/extractors.py +18 -80
- python_loading_sdk-0.5.0.dist-info/METADATA +185 -0
- python_loading_sdk-0.5.0.dist-info/RECORD +16 -0
- {python_loading_sdk-0.4.0.dist-info → python_loading_sdk-0.5.0.dist-info}/WHEEL +1 -1
- python_loading_sdk-0.4.0.dist-info/METADATA +0 -127
- python_loading_sdk-0.4.0.dist-info/RECORD +0 -14
- tests/test_api.py +0 -1924
- /tests/__init__.py → /loading_sdk/py.typed +0 -0
- {python_loading_sdk-0.4.0.dist-info → python_loading_sdk-0.5.0.dist-info/licenses}/LICENSE.md +0 -0
loading_sdk/__init__.py
CHANGED
loading_sdk/_api.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Shared SDK operations yield HTTP requests and consume buffered responses.
|
|
2
|
+
|
|
3
|
+
The sync and async clients drive these operations with their respective HTTPX clients.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from collections.abc import Generator
|
|
7
|
+
from typing import Any, TypeVar
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from loading_sdk import _parsing, settings
|
|
12
|
+
|
|
13
|
+
T = TypeVar("T")
|
|
14
|
+
Operation = Generator[httpx.Request, httpx.Response, T]
|
|
15
|
+
Result = dict[str, Any]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def request(
|
|
19
|
+
method: str,
|
|
20
|
+
path: str,
|
|
21
|
+
*,
|
|
22
|
+
data: dict[str, str] | None = None,
|
|
23
|
+
headers: dict[str, str] | None = None,
|
|
24
|
+
authenticated: bool = False,
|
|
25
|
+
) -> httpx.Request:
|
|
26
|
+
return httpx.Request(
|
|
27
|
+
method,
|
|
28
|
+
f"{settings.API_URL}/{settings.API_VERSION}/{path}",
|
|
29
|
+
headers={"User-Agent": settings.USER_AGENT, **(headers or {})},
|
|
30
|
+
data=data,
|
|
31
|
+
extensions={"sdk_auth": authenticated},
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def web_request(path: str) -> httpx.Request:
|
|
36
|
+
return httpx.Request(
|
|
37
|
+
"GET",
|
|
38
|
+
f"{settings.BASE_URL}/{path}",
|
|
39
|
+
headers={"User-Agent": settings.USER_AGENT},
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def result(data: Any, message: str = "OK", code: int = 200) -> Result:
|
|
44
|
+
return {"code": code, "message": message, "data": data}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parsed(response: httpx.Response, message: str = "OK", status: int = 200) -> Result:
|
|
48
|
+
data = response.json()
|
|
49
|
+
return result(data, message, status) if response.status_code == status else data
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def authenticate(email: str, password: str) -> Operation[Result]:
|
|
53
|
+
login = request("POST", "auth/login", data={"email": email, "password": password})
|
|
54
|
+
login.extensions["sdk_login"] = True
|
|
55
|
+
response = yield login
|
|
56
|
+
if response.status_code == 200:
|
|
57
|
+
return {"code": 200, "cookies": login.extensions["sdk_cookies"]}
|
|
58
|
+
return response.json()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def get_profile() -> Operation[Result]:
|
|
62
|
+
return parsed((yield request("GET", "users/profile", authenticated=True)))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def search(query: str) -> Operation[Result]:
|
|
66
|
+
response = yield request(
|
|
67
|
+
"POST",
|
|
68
|
+
"search/",
|
|
69
|
+
data={"query": query},
|
|
70
|
+
headers={"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"},
|
|
71
|
+
)
|
|
72
|
+
data = response.json()
|
|
73
|
+
if response.status_code != 200:
|
|
74
|
+
return data
|
|
75
|
+
return result(data, "OK" if data["posts"] else "No results")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def missing(field: str, code: int) -> Result:
|
|
79
|
+
return {"code": code, "message": f'"{field}" is not allowed to be empty'}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def get_post(post_id: str) -> Operation[Result]:
|
|
83
|
+
if not post_id:
|
|
84
|
+
return missing("post_id", 404)
|
|
85
|
+
return parsed((yield request("GET", f"posts/{post_id}")))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def page_count(replies: int) -> int:
|
|
89
|
+
return max(1, (replies + settings.POSTS_PER_PAGE - 1) // settings.POSTS_PER_PAGE)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def page_error(message: str, code: int) -> Result:
|
|
93
|
+
return result({"posts": [], "users": []}, message, code)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def get_thread(thread_id: str, page: int | None = None) -> Operation[Result]:
|
|
97
|
+
if not thread_id:
|
|
98
|
+
return missing("thread_id", 404)
|
|
99
|
+
headers = {"page": str(page)} if page and page > 1 else {}
|
|
100
|
+
response = yield request("GET", f"posts/{thread_id}", headers=headers)
|
|
101
|
+
data = response.json()
|
|
102
|
+
if response.status_code != 200:
|
|
103
|
+
return data
|
|
104
|
+
first = data["posts"][-1]
|
|
105
|
+
if "title" not in first:
|
|
106
|
+
return {"code": 200, "message": "Exists, but was not a thread id"}
|
|
107
|
+
if page and page < 1:
|
|
108
|
+
return page_error("Page number too low", 200)
|
|
109
|
+
if page and page > page_count(first["replies"]):
|
|
110
|
+
return page_error("Page number too high", 200)
|
|
111
|
+
return result(data)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def category_headers(
|
|
115
|
+
category: str,
|
|
116
|
+
page: int | None,
|
|
117
|
+
post_type: str | None = None,
|
|
118
|
+
sort: str | None = None,
|
|
119
|
+
) -> dict[str, str]:
|
|
120
|
+
headers = {category: category}
|
|
121
|
+
if page and page > 1:
|
|
122
|
+
headers["page"] = str(page)
|
|
123
|
+
if category == "texts":
|
|
124
|
+
headers["post-type"] = (
|
|
125
|
+
post_type if post_type in settings.EDITORIAL_POST_TYPES else "neRegular"
|
|
126
|
+
)
|
|
127
|
+
if sort and sort in settings.EDITORIAL_SORT:
|
|
128
|
+
headers["sort"] = sort
|
|
129
|
+
return headers
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def category_page(
|
|
133
|
+
category: str,
|
|
134
|
+
page: int | None,
|
|
135
|
+
post_type: str | None = None,
|
|
136
|
+
sort: str | None = None,
|
|
137
|
+
) -> Operation[Result]:
|
|
138
|
+
if page and page < 1:
|
|
139
|
+
return page_error("Page number too low", 404)
|
|
140
|
+
response = yield request(
|
|
141
|
+
"GET", "posts/", headers=category_headers(category, page, post_type, sort)
|
|
142
|
+
)
|
|
143
|
+
data = response.json()
|
|
144
|
+
if "posts" not in data:
|
|
145
|
+
return data
|
|
146
|
+
if not data["posts"]:
|
|
147
|
+
return result(data, "Page number too high", 404)
|
|
148
|
+
return result(data)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def create_post(thread_id: str, message: str) -> Operation[Result]:
|
|
152
|
+
if not thread_id:
|
|
153
|
+
return missing("thread_id", 400)
|
|
154
|
+
response = yield request(
|
|
155
|
+
"POST", f"posts/{thread_id}", data={"body": message}, authenticated=True
|
|
156
|
+
)
|
|
157
|
+
return parsed(response, "Post created", 201)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def edit_post(post_id: str, message: str) -> Operation[Result]:
|
|
161
|
+
if not message:
|
|
162
|
+
return missing("message", 400)
|
|
163
|
+
response = yield request(
|
|
164
|
+
"PATCH", f"posts/{post_id}", data={"body": message}, authenticated=True
|
|
165
|
+
)
|
|
166
|
+
return parsed(response, "Post updated")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def create_thread(
|
|
170
|
+
title: str, message: str, category_name: str, post_type: str | None
|
|
171
|
+
) -> Operation[Result]:
|
|
172
|
+
if category_name not in ("games", "other"):
|
|
173
|
+
return {"code": 400, "message": "Invalid forum category"}
|
|
174
|
+
if post_type and post_type not in settings.EDITORIAL_POST_TYPES:
|
|
175
|
+
return {"code": 400, "message": "Invalid post_type"}
|
|
176
|
+
response = yield request(
|
|
177
|
+
"POST",
|
|
178
|
+
"posts/",
|
|
179
|
+
authenticated=True,
|
|
180
|
+
data={
|
|
181
|
+
"category": category_name,
|
|
182
|
+
"postType": post_type or "regular",
|
|
183
|
+
"title": title,
|
|
184
|
+
"body": message,
|
|
185
|
+
},
|
|
186
|
+
)
|
|
187
|
+
return parsed(response, "Thread created", 201)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def edit_thread(thread_id: str, message: str) -> Operation[Result]:
|
|
191
|
+
response = yield from edit_post(thread_id, message)
|
|
192
|
+
if response["code"] == 200:
|
|
193
|
+
response["message"] = "Thread updated"
|
|
194
|
+
return response
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def main_script(page: str) -> Operation[str | None]:
|
|
198
|
+
html = yield web_request(page)
|
|
199
|
+
path = _parsing.main_script_path(html.text)
|
|
200
|
+
if path is None:
|
|
201
|
+
return None
|
|
202
|
+
script = yield web_request(path)
|
|
203
|
+
return script.text
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def get_about() -> Operation[Result]:
|
|
207
|
+
response = yield request("GET", "editorial/")
|
|
208
|
+
if response.status_code == 200:
|
|
209
|
+
data = response.json()
|
|
210
|
+
return result({"people": data["editorials"], "moderators": data["moderators"]})
|
|
211
|
+
if response.status_code == 404:
|
|
212
|
+
# Older deployments embed the staff lists in a JavaScript chunk.
|
|
213
|
+
script = yield from main_script("om")
|
|
214
|
+
chunks = _parsing.chunk_urls(script or "", settings.BASE_URL)
|
|
215
|
+
if chunks:
|
|
216
|
+
chunk = yield httpx.Request(
|
|
217
|
+
"GET", chunks[-1], headers={"User-Agent": settings.USER_AGENT}
|
|
218
|
+
)
|
|
219
|
+
staff = _parsing.legacy_about(chunk.text)
|
|
220
|
+
if staff:
|
|
221
|
+
return result(staff)
|
|
222
|
+
return result(None, "No data found", 404)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def get_socials() -> Operation[Result]:
|
|
226
|
+
script = yield from main_script("")
|
|
227
|
+
links = _parsing.social_links(script or "")
|
|
228
|
+
return result(links) if links else result(None, "No results found", 404)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def get_total_thread_pages(thread_id: str) -> Operation[int | Result]:
|
|
232
|
+
response = yield from get_thread(thread_id)
|
|
233
|
+
if response["code"] != 200 or "data" not in response:
|
|
234
|
+
return response
|
|
235
|
+
return page_count(response["data"]["posts"][-1]["replies"])
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def get_total_category_pages(category: str) -> Operation[Result]:
|
|
239
|
+
if category not in settings.FORUM_CATEGORIES:
|
|
240
|
+
return result(None, "Invalid category", 404)
|
|
241
|
+
lower, upper, page = 0, None, 1
|
|
242
|
+
while upper is None or upper - lower > 1:
|
|
243
|
+
headers = category_headers(category, page)
|
|
244
|
+
headers["page"] = str(page)
|
|
245
|
+
response = yield request("GET", "posts/", headers=headers)
|
|
246
|
+
data = response.json()
|
|
247
|
+
if "posts" not in data:
|
|
248
|
+
return data
|
|
249
|
+
if data["posts"]:
|
|
250
|
+
lower = page
|
|
251
|
+
else:
|
|
252
|
+
upper = page
|
|
253
|
+
page = page * 2 if upper is None else (lower + upper) // 2
|
|
254
|
+
return result({"total_pages": lower})
|
loading_sdk/_http.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Cookie and redirect policy shared by the HTTPX clients."""
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
|
|
5
|
+
from loading_sdk import settings
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def api_origin(url: httpx.URL) -> bool:
|
|
9
|
+
api = httpx.URL(settings.API_URL)
|
|
10
|
+
return (url.scheme, url.host, url.port) == (api.scheme, api.host, api.port)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def prepare(request: httpx.Request, cookies: httpx.Cookies | None) -> None:
|
|
14
|
+
if request.extensions.get("sdk_login"):
|
|
15
|
+
request.extensions["sdk_cookies"] = httpx.Cookies()
|
|
16
|
+
elif request.extensions.get("sdk_auth"):
|
|
17
|
+
request.extensions["sdk_cookies"] = httpx.Cookies(cookies)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def before_send(request: httpx.Request) -> None:
|
|
21
|
+
# HTTPX builds redirect requests from the pool's cookie jar. Apply the SDK's
|
|
22
|
+
# per-operation jar on every hop, including redirects between sibling hosts.
|
|
23
|
+
request.headers.pop("cookie", None)
|
|
24
|
+
jar = request.extensions.get("sdk_cookies")
|
|
25
|
+
if jar is None:
|
|
26
|
+
return
|
|
27
|
+
if api_origin(request.url):
|
|
28
|
+
jar.set_cookie_header(request)
|
|
29
|
+
elif request.method not in ("GET", "HEAD"):
|
|
30
|
+
raise httpx.RequestError(
|
|
31
|
+
"Refusing to forward an authenticated form to another origin",
|
|
32
|
+
request=request,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def after_receive(response: httpx.Response) -> None:
|
|
37
|
+
jar = response.request.extensions.get("sdk_cookies")
|
|
38
|
+
if jar is not None and api_origin(response.request.url):
|
|
39
|
+
jar.extract_cookies(response)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def async_before_send(request: httpx.Request) -> None:
|
|
43
|
+
before_send(request)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def async_after_receive(response: httpx.Response) -> None:
|
|
47
|
+
after_receive(response)
|
loading_sdk/_parsing.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
from urllib.parse import urlsplit
|
|
4
|
+
|
|
5
|
+
from bs4 import BeautifulSoup, Tag
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main_script_path(source: str) -> str | None:
|
|
9
|
+
soup = BeautifulSoup(source, "html.parser")
|
|
10
|
+
script = soup.find(src=re.compile(r"/static/js/main\.[0-9a-zA-Z]+\.js"))
|
|
11
|
+
if isinstance(script, Tag):
|
|
12
|
+
src = script.get("src")
|
|
13
|
+
if isinstance(src, str):
|
|
14
|
+
return src.removeprefix("/")
|
|
15
|
+
return None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def chunk_urls(source: str, base_url: str) -> list[str]:
|
|
19
|
+
match = re.search(r"(static/js/).+?(?=\{)(.+?(?=\[)).+(.chunk.js)", source)
|
|
20
|
+
if not match:
|
|
21
|
+
return []
|
|
22
|
+
|
|
23
|
+
# Quote the numeric chunk IDs to turn the JavaScript object into JSON.
|
|
24
|
+
chunk_ids = json.loads(re.sub(r"([0-9]+?(?=:))", r'"\1"', match.group(2)))
|
|
25
|
+
return [
|
|
26
|
+
f"{base_url}/{match.group(1)}{key}.{value}{match.group(3)}"
|
|
27
|
+
for key, value in chunk_ids.items()
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def legacy_about(about_script_source: str) -> dict | None:
|
|
32
|
+
match = re.search(r"var.e=(.+?)(?=\.map).+a=(.+?)(?=\.map)", about_script_source)
|
|
33
|
+
|
|
34
|
+
if not match:
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
people = re.sub(r"(\{|\,)([a-z]+)(\:)", r'\1"\2"\3', match.group(1))
|
|
38
|
+
people = re.sub(r"(.+)(')(.+)(')(.+)", r'\1"\3"\5', people)
|
|
39
|
+
people = people.replace('slags "vuxen p', "slags 'vuxen p")
|
|
40
|
+
people = people.replace('riktigt"-framtid', "riktigt'-framtid")
|
|
41
|
+
people = people.replace("\\n", "")
|
|
42
|
+
people = people.encode("utf-8").decode("unicode_escape")
|
|
43
|
+
|
|
44
|
+
moderators = re.sub(r"(\{|\,)([a-z]+)(\:)", r'\1"\2"\3', match.group(2))
|
|
45
|
+
moderators = re.sub(r"(.+)(')(.+)(')(.+)", r'\1"\3"\5', moderators)
|
|
46
|
+
moderators = moderators.replace("\\n", "")
|
|
47
|
+
moderators = moderators.encode("utf-8").decode("unicode_escape")
|
|
48
|
+
|
|
49
|
+
data = {
|
|
50
|
+
"people": json.loads(people),
|
|
51
|
+
"moderators": json.loads(moderators),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return data
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def social_links(source: str) -> list[dict[str, str]]:
|
|
58
|
+
links = re.findall(
|
|
59
|
+
r'href:"(https://[^"]+)",target:"_blank",rel:"noreferrer noopener",'
|
|
60
|
+
r'className:"Footer-(?:icon|patreon)"',
|
|
61
|
+
source,
|
|
62
|
+
)
|
|
63
|
+
socials = []
|
|
64
|
+
for link in links:
|
|
65
|
+
host = urlsplit(link).hostname
|
|
66
|
+
if host:
|
|
67
|
+
socials.append(
|
|
68
|
+
{"name": host.removeprefix("www.").split(".")[0], "link": link}
|
|
69
|
+
)
|
|
70
|
+
return socials
|