|
| 1 | +import math |
| 2 | + |
1 | 3 | import requests |
2 | 4 |
|
3 | 5 | API_URL = "https://api.loading.se" |
@@ -82,39 +84,48 @@ def get_post(self, post_id): |
82 | 84 |
|
83 | 85 | return response.json() |
84 | 86 |
|
85 | | - def get_thread(self, thread_id): |
| 87 | + def get_thread(self, thread_id, page=None): |
86 | 88 | """Returns post data if the id belongs to a thread start.""" |
87 | 89 |
|
88 | 90 | if not thread_id: |
89 | 91 | return {"code": 404, "message": '"thread_id" is not allowed to be empty'} |
90 | 92 |
|
91 | 93 | url = f"{API_URL}/{API_VERSION}/posts/{thread_id}" |
92 | 94 | headers = {"User-Agent": USER_AGENT} |
| 95 | + |
| 96 | + # Chooses a specific page instead of the first page which is the default page. |
| 97 | + if page and page > 1: |
| 98 | + headers["page"] = str(page) |
| 99 | + |
93 | 100 | response = requests.get(url, headers=headers) |
94 | 101 |
|
95 | | - if response.status_code == 200: |
96 | | - post_data = response.json() |
97 | | - parent_post = post_data["posts"][-1] |
98 | | - parent_user = None |
| 102 | + if response.status_code != 200: |
| 103 | + return response.json() |
99 | 104 |
|
100 | | - # Only thread starts has a title so anything else is a regular post. |
101 | | - if "title" in parent_post: |
102 | | - for user in post_data["users"]: |
103 | | - if user["id"] == parent_post["userId"]: |
104 | | - parent_user = user |
105 | | - break |
| 105 | + data = response.json() |
106 | 106 |
|
| 107 | + if "title" not in data["posts"][-1]: |
| 108 | + return { |
| 109 | + "code": response.status_code, |
| 110 | + "message": "Exists, but was not a thread id", |
| 111 | + } |
| 112 | + |
| 113 | + # Doing this checks to make sure it only return data from a page that exists. |
| 114 | + if page: |
| 115 | + replies = data["posts"][-1]["replies"] |
| 116 | + pages = math.ceil(replies / 30) |
| 117 | + |
| 118 | + # There is always atleast one page. |
| 119 | + if pages == 0: |
| 120 | + pages = 1 |
| 121 | + |
| 122 | + # Page is out of range. |
| 123 | + if page < 1 or page > pages: |
107 | 124 | return { |
108 | 125 | "code": response.status_code, |
109 | | - "post": { |
110 | | - "posts": [parent_post], |
111 | | - "users": [parent_user], |
112 | | - }, |
113 | | - } |
114 | | - else: |
115 | | - return { |
116 | | - "code": response.status_code, |
117 | | - "message": "Exists, but was not a thread id", |
| 126 | + "post": {"posts": [], "users": []}, |
118 | 127 | } |
119 | 128 |
|
120 | | - return response.json() |
| 129 | + successful_response = {"code": response.status_code, "post": data} |
| 130 | + |
| 131 | + return successful_response |
0 commit comments