-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
244 lines (190 loc) · 7.87 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from fastapi import FastAPI
from backend import *
import copy
import re
from starlette.responses import JSONResponse
from fastapi.responses import FileResponse
app = FastAPI(
title="BPS Circular API",
description="An API that can work with the circulars of Birla Public School",
version="1.0.0",
)
circular_list_cache = CircularListCache()
@app.exception_handler(500)
async def handler_500(err, e):
error_content = copy.deepcopy(error_response)
error_content["error"] = str(err)
return JSONResponse(content=error_content, status_code=500)
@app.exception_handler(404)
async def handler_404(err, e):
error_content = copy.deepcopy(error_response)
error_content['http_status'] = 404
error_content["error"] = "Not Found"
return JSONResponse(content=error_content, status_code=404)
@app.get("/")
async def root():
return_list = copy.deepcopy(success_response)
# noinspection PyTypedDict
return_list["data"] = "Welcome to the API. Please refer to the documentation " \
"at https://bpsapi.rajtech.me/docs for more information."
return return_list
@app.get("/categories")
async def _get_categories():
return_list = copy.deepcopy(success_response)
return_list['data'] = [i for i in categories.keys()]
return return_list
# Get RAW circular lists
@app.get("/list")
@app.get("/list/{category}")
async def _get_circular_list(category: str | int):
# Get the category id from the category name/id provided
if type(category) is int or category.isdigit():
category = int(category)
else:
category = categories.get(category.lower())
if category is None:
error = copy.deepcopy(error_response)
error['error'] = f'Invalid category'
error['http_status'] = 422
return JSONResponse(content=error, status_code=422)
# Get the number of pages in the category
num_pages = await get_num_pages(category)
if num_pages == 0:
error = copy.deepcopy(error_response)
error['error'] = f'Invalid category'
error['http_status'] = 422
return JSONResponse(content=error, status_code=422)
# Get the circular list
res = await get_list(category, num_pages)
# Add the result to the return list
return_list = copy.deepcopy(success_response)
return_list['data'] = res
# if len(return_list['data']) == 0:
# return_list['data'] = []
return return_list
# Get latest circular
@app.get("/latest")
@app.get("/latest/{category}")
async def _get_latest_circular(category: str | int):
# Get the category id from the category name/id provided
if type(category) is int or category.isdigit():
category = int(category)
else:
category = categories.get(category.lower())
if category is None:
log.debug("Category is none, 400'ing")
error = copy.deepcopy(error_response)
error['error'] = f'Invalid category'
error['http_status'] = 422
return JSONResponse(content=error, status_code=422)
return_list = copy.deepcopy(success_response)
try:
res = await get_latest(category)
return_list['data'] = res
except Exception as e:
error = copy.deepcopy(error_response)
error['error'] = f'Invalid category'
error['http_status'] = 422
return JSONResponse(content=error, status_code=422)
return return_list
@app.get("/search")
@app.get("/search/{query}")
async def _search(query: str | int, amount: int = 3): # TODO try to make searching by id faster
# check if it is a circular id or title
if type(query) == int or query.isdigit():
log.debug("Searching by id")
return_list = copy.deepcopy(success_response)
res = await search_from_id(query)
if res is not None:
return_list['data'] = [res]
else:
return_list['data'] = []
return return_list
if amount < 1:
amount = 3
# If title is a circular title, get a list of all circulars by scraping the website
res = await search_algo(circular_list_cache, query, amount)
return_list = copy.deepcopy(success_response)
if res is None:
return_list['data'] = None
return return_list
if res is not None:
return_list['data'] = res
return return_list
@app.get("/getpng")
@app.get("/get-png")
async def _get_png(url):
circular_pdf_regex = r"^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)bpsdoha\.(com|net|edu\.qa)" \
r"\/circular\/category\/[0-9]+.*\?download=[0-9]+"
primary_circular_pdf_regex = (r"^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)bpsdoha\.(com|net|edu\.qa)"
r"\/primaryi\/primary-circular\?download=[0-9]+")
if not re.match(circular_pdf_regex, url) and not re.match(primary_circular_pdf_regex, url):
error = copy.deepcopy(error_response)
error['error'] = f'Invalid URL'
error['http_status'] = 422
return JSONResponse(content=error, status_code=422)
try:
res = await get_png(url)
except Exception as e:
error = copy.deepcopy(error_response)
error['error'] = f'Error while attempting to get the PNG'
error['http_status'] = 400
return JSONResponse(content=error, status_code=400)
return_list = copy.deepcopy(success_response)
return_list['data'] = res
return return_list
@app.get("/circular-image/{image_path}")
async def _get_circular_images(image_path) -> JSONResponse:
# return ./circularimages/{image_path} as an image
if not os.path.exists(f"./circularimages/{image_path}"):
try:
# If the imagepath is a circular id with .png extension
if image_path[:4].isdigit() and image_path.endswith(".png"):
# if image is not referring to first page of circular
if "-" in image_path:
log.debug("Image is not first page of circular")
raise LookupError
# try to get the circular
res = await search_from_id(image_path[:4])
if res is None:
log.debug("Circular not found")
raise LookupError
# Try to get the image
res = await get_png(res['link'])
if res is None:
log.debug("Image not found")
raise LookupError
# if the image exists now
if os.path.exists(f"./circularimages/{image_path}"):
return FileResponse(f"./circularimages/{image_path}")
else:
log.debug("Image still not found")
raise LookupError
else:
log.debug("invalid image path")
raise LookupError
except LookupError:
error = copy.deepcopy(error_response)
error['error'] = f'Image not found'
error['http_status'] = 404
return JSONResponse(content=error, status_code=404)
return FileResponse(f"./circularimages/{image_path}")
@app.get("/new-circulars/{circular_id}")
async def _new_circulars(circular_id: int):
"""Returns the circulars succeeding the given one."""
if circular_list_cache.expiry < time.time():
circular_list = await circular_list_cache.refresh_circulars()
else:
circular_list = circular_list_cache.cache
for index in range(len(circular_list)):
if circular_list[index]['id'] == str(circular_id):
passed_circular_index = index
break
else:
error = copy.deepcopy(error_response)
error['error'] = f'Circular ID does not exist'
error['http_status'] = 422
return JSONResponse(content=error, status_code=422)
return_list = copy.deepcopy(success_response)
return_list['data'] = circular_list[:passed_circular_index]
return return_list