Change formatting

This commit is contained in:
magmaus3 2022-11-05 15:09:20 +01:00
parent 0b68a1c4b4
commit 4487003558
Signed by: magmaus3
GPG key ID: 966755D3F4A9B251
3 changed files with 81 additions and 56 deletions

View file

@ -1,2 +1 @@
__version__ = '0.2.0'
__version__ = "0.2.0"

View file

@ -10,48 +10,57 @@ import os
import re
from . import utils
from . import __version__
basedir = os.path.dirname(__file__)
app = FastAPI()
app.mount("/static", StaticFiles(directory=basedir + "/static"), name="static")
template_env = jinja2.Environment(
loader=jinja2.PackageLoader("iwm_browser", "templates"),
auto_reload=True
loader=jinja2.PackageLoader("iwm_browser", "templates"), auto_reload=True
)
template_env.globals['convert_times'] = utils.convert_times
template_env.globals['generate_thumbnail_url'] = utils.generate_thumbnail_url
template_env.globals['__version__'] = __version__
error_template = template_env.get_template("error.html")
template_env.globals["convert_times"] = utils.convert_times
template_env.globals["generate_thumbnail_url"] = utils.generate_thumbnail_url
template_env.globals["__version__"] = __version__
BASE_URL = "http://make.fangam.es"
THUMB_URL = "https://images.make.fangam.es"
utils.global_imgproxy_url = "http://127.0.0.1:8080" # Set it to None to disable the proxy
utils.global_imgproxy_params = {"extension": "webp", "advanced": ["q:50"]} # Set it to None to disable the proxy params
utils.global_imgproxy_url = (
"http://127.0.0.1:8080" # Set it to None to disable the proxy
)
utils.global_imgproxy_params = {
"extension": "webp",
"advanced": ["q:50"],
} # Set it to None to disable the proxy params
# Matches level code.
# \S[A-Z0-9]{4}\-[A-Z0-9]{4} = With dash, no whitespace
# \S[A-Z0-9]{8} = without dash, no whitespace
level_code_regex = re.compile("[A-Z0-9]{4}\-[A-Z0-9]{4}|[A-Z0-9]{8}")
error_template = template_env.get_template("error.html")
@app.get("/", response_class=HTMLResponse)
async def root():
template = template_env.get_template("home.html")
return template.render()
@app.get("/search", response_class=HTMLResponse)
async def search(
q: Union[str, None] = None,
p: int = 0,
sort: str = "average_rating",
dir: str = "desc",
date: int = -1
):
q: Union[str, None] = None,
p: int = 0,
sort: str = "average_rating",
dir: str = "desc",
date: int = -1,
):
template = template_env.get_template("search.html")
limit = 10
if p is None:
p = 0
# Passed to the template
QueryValues = {"q": q, "p": p, "sort": sort, "dir": dir, "date": date}
@ -62,9 +71,13 @@ async def search(
searchValue = q
entryNumber = -1
try:
rq = httpx.get(BASE_URL + "/api/v1/map", params={
"code": levelCode,
}, timeout=10)
rq = httpx.get(
BASE_URL + "/api/v1/map",
params={
"code": levelCode,
},
timeout=10,
)
searchResults = rq.json()
print(rq.url, p * limit)
except httpx.ReadTimeout:
@ -77,7 +90,7 @@ async def search(
params = re.findall("[a-z\-\_]*:[a-zA-Z0-9._\-]*", q)
search = re.sub("\S[a-z\-\_]*:[a-zA-Z0-9._\-]*", "", q).lstrip().rstrip()
for i in params:
split = i.split(':')
split = i.split(":")
if split[0] == "author":
author = {"author": split[1]}
@ -95,40 +108,49 @@ async def search(
searchValue = q
try:
rq = httpx.get(BASE_URL + "/api/v1/map", params={
"start": p * limit,
"limit": limit,
"min_diff": min_diff,
"max_diff": max_diff,
"order": json.dumps([order]),
"name": search,
**last_x_hours, **author
}, timeout=10)
rq = httpx.get(
BASE_URL + "/api/v1/map",
params={
"start": p * limit,
"limit": limit,
"min_diff": min_diff,
"max_diff": max_diff,
"order": json.dumps([order]),
"name": search,
**last_x_hours,
**author,
},
timeout=10,
)
if rq.status_code == 503:
return error_template.render(reason="Server is unavailable right now.")
return error_template.render(
reason="Server is unavailable right now."
)
searchResults = rq.json()
print(rq.url, p * limit)
except httpx.ReadTimeout:
return error_template.render(reason="Server timed out")
except json.decoder.JSONDecodeError:
return error_template.render(reason="Failed to parse server response.", details=rq.text)
return error_template.render(
reason="Failed to parse server response.", details=rq.text
)
except Exception as exc:
return error_template.render(reason="Uncaught exception", details=exc)
entryNumber=len(searchResults)
entryNumber = len(searchResults)
else:
searchValue = ''
searchValue = ""
entryNumber = None
return template.render(
searchResults=searchResults,
THUMB_URL=THUMB_URL,
entryLimit=limit,
entryNumber=entryNumber,
QueryValues=QueryValues
searchResults=searchResults,
THUMB_URL=THUMB_URL,
entryLimit=limit,
entryNumber=entryNumber,
QueryValues=QueryValues,
)
@app.get("/level/{level_id}", response_class=HTMLResponse)
async def showLevel(level_id: int):
template = template_env.get_template("levelInfo.html")
@ -142,17 +164,18 @@ async def showLevel(level_id: int):
except httpx.ReadTimeout:
return error_template.render(reason="Server timed out")
except json.decoder.JSONDecodeError:
return error_template.render(reason="Failed to parse server response.", details=rq.text)
return error_template.render(
reason="Failed to parse server response.", details=rq.text
)
except Exception as exc:
return error_template.render(reason="Uncaught exception", details=exc)
return template.render(
map=searchResults,
THUMB_URL=THUMB_URL,
map=searchResults,
THUMB_URL=THUMB_URL,
)
@app.get("/user/{user_id}", response_class=HTMLResponse)
async def showUser(user_id: int):
template = template_env.get_template("userInfo.html")
@ -166,22 +189,19 @@ async def showUser(user_id: int):
except httpx.ReadTimeout:
return error_template.render(reason="Server timed out")
except json.decoder.JSONDecodeError:
return error_template.render(reason="Failed to parse server response.", details=rq.text)
return error_template.render(
reason="Failed to parse server response.", details=rq.text
)
except Exception as exc:
print(exc)
return error_template.render(reason="Uncaught exception", details=exc)
return template.render(
user=searchResults,
THUMB_URL=THUMB_URL,
user=searchResults,
THUMB_URL=THUMB_URL,
)
def start():
"""Launched with `poetry run start` at root level"""
uvicorn.run("iwm_browser.main:app", host="0.0.0.0", port=7775, reload=True)

View file

@ -1,5 +1,6 @@
from imgproxy import ImgProxy
def convert_times(time):
# Not sure if it's the right way to do that, but it seems to work.
time_seconds = ((time % 60000) / 100) * 2
@ -12,12 +13,17 @@ def convert_times(time):
seconds = "{0:,.2f}".format(seconds).zfill(5)
return (hours,minutes,seconds)
return (hours, minutes, seconds)
# Specify default imgproxy instance.
global_imgproxy_url = None
global_imgproxy_params = None
def generate_thumbnail_url(level_id, thumbnail_url, imgproxy_url=None, imgproxy_params={}):
def generate_thumbnail_url(
level_id, thumbnail_url, imgproxy_url=None, imgproxy_params={}
):
"""Generates thumbnail url."""
global global_imgproxy_url
global global_imgproxy_params
@ -25,7 +31,7 @@ def generate_thumbnail_url(level_id, thumbnail_url, imgproxy_url=None, imgproxy_
imgproxy_url = global_imgproxy_url
if imgproxy_params == {} and global_imgproxy_params is not None:
imgproxy_params = global_imgproxy_params
# Create url
img_url = thumbnail_url + "/" + str(level_id) + ".png"