From 2c6eab27e68bc4bfd8a74df6ffd98b27ae5219e2 Mon Sep 17 00:00:00 2001 From: T <74899888+tslashd@users.noreply.github.com> Date: Thu, 21 Sep 2023 01:45:10 +0300 Subject: [PATCH] player object? --- main.py | 2 + sql.py | 17 ++++--- surftimer/ck_bonus.py | 60 ++++++++++++++++++++++-- surftimer/ck_checkpoints.py | 5 +- surftimer/queries.py | 5 +- surftimer/refactored.py | 91 +++++++++++++++++++++++++++++++++++++ 6 files changed, 164 insertions(+), 16 deletions(-) create mode 100644 surftimer/refactored.py diff --git a/main.py b/main.py index 6193fc4..fa87dda 100644 --- a/main.py +++ b/main.py @@ -38,6 +38,7 @@ from surftimer.ck_spawnlocations import router as ck_spawnlocations_router from surftimer.ck_zones import router as ck_zones_router from surftimer.points import router as points_calculation +from surftimer.refactored import router as refactored_router class IPValidatorMiddleware(BaseHTTPMiddleware): @@ -96,6 +97,7 @@ async def dispatch(self, request: Request, call_next): app.include_router(ck_spawnlocations_router) app.include_router(ck_zones_router) app.include_router(points_calculation) +app.include_router(refactored_router) @app.get("/docs2", include_in_schema=False) diff --git a/sql.py b/sql.py index c9768db..856ef53 100644 --- a/sql.py +++ b/sql.py @@ -1,8 +1,8 @@ import mysql.connector -import json +import simplejson as json -with open('config.json', 'r') as f: +with open("config.json", "r") as f: config = json.load(f) @@ -15,17 +15,18 @@ def selectQuery(query): host=db["HOST"], user=db["USERNAME"], password=db["PASSWORD"], - database=db["DB"] + database=db["DB"], ) mycursor = mydb.cursor(dictionary=True) mycursor.execute(query) res = mycursor.fetchall() for result in res: json_data.append(dict(result)) - + mydb.close() return json_data + def insertQuery(query): """Executes `INSERT` query provided and returns `mycursor.rowcount`\n Connects to a predefined `Database` from `config.json`""" @@ -34,7 +35,7 @@ def insertQuery(query): host=db["HOST"], user=db["USERNAME"], password=db["PASSWORD"], - database=db["DB"] + database=db["DB"], ) mycursor = mydb.cursor() @@ -44,6 +45,7 @@ def insertQuery(query): return mycursor.rowcount + def insert_escaped_query(query): """Executes `INSERT` query `mycursor.execute("", (query))` provided and returns `mycursor.rowcount`\n Connects to a predefined `Database` from `config.json`""" @@ -52,7 +54,7 @@ def insert_escaped_query(query): host=db["HOST"], user=db["USERNAME"], password=db["PASSWORD"], - database=db["DB"] + database=db["DB"], ) mycursor = mydb.cursor() @@ -62,6 +64,7 @@ def insert_escaped_query(query): return mycursor.rowcount + def syncQuery(query): db = config["DATABASE"] mydb = mysql.connector.connect( @@ -75,4 +78,4 @@ def syncQuery(query): mydb.commit() - return mycursor.rowcount \ No newline at end of file + return mycursor.rowcount diff --git a/surftimer/ck_bonus.py b/surftimer/ck_bonus.py index dbcf296..ad63dfa 100644 --- a/surftimer/ck_bonus.py +++ b/surftimer/ck_bonus.py @@ -191,6 +191,62 @@ def selectPersonalBonusRecords( return xquery +@router.get( + "/surftimer/selectPersonalBonusesMap", + name="Get Player Bonus info for map", + tags=["ck_bonus", "Refactored"], +) +def selectPersonalBonusesMap( + request: Request, response: Response, steamid32: str, mapname: str +): + """merge ```char sql_selectPersonalBonusRecords[] = ....```\n + and\n + ```char sql_selectPlayerRankBonus[] = ....```\n + and maybe more to output a single object with Bonus information for player""" + tic = time.perf_counter() + + # Check if data is cached in Redis + cache_key = f"selectPersonalBonusesMap:{steamid32}-{mapname}" + cached_data = get_cache(cache_key) + + if cached_data is not None: + print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)") + response.headers["content-type"] = "application/json" + response.status_code = status.HTTP_200_OK + response.body = json.loads(cached_data, use_decimal=True, parse_nan=True) + return response + + xquery = selectQuery( + surftimer.queries.sql_selectPersonalBonusRecords.format(steamid32, mapname) + ) + + if len(xquery) <= 0: + response.headers["content-type"] = "application/json" + response.status_code = status.HTTP_204_NO_CONTENT + return response + + for completion in xquery: + zonegroup = completion["zonegroup"] + rank_query = selectQuery( + surftimer.queries.sql_selectPlayerRankBonusCount.format( + steamid32, + mapname, + zonegroup, + mapname, + zonegroup, + ) + ) + completion["rank"] = rank_query.pop()["COUNT(steamid)"] + + toc = time.perf_counter() + print(f"Execution time {toc - tic:0.4f}") + + # Cache the data in Redis + set_cache(cache_key, xquery) + + return xquery + + @router.get( "/surftimer/selectPlayerRankBonus", name="Get Player Rank Bonus", @@ -887,9 +943,7 @@ def getRankSteamIdBonus( if zonegroup == 0: xquery = selectQuery( - surftimer.queries.sql_stray_steamIdFromMapRank.format( - mapname, limit - ) + surftimer.queries.sql_stray_steamIdFromMapRank.format(mapname, limit) ) else: xquery = selectQuery( diff --git a/surftimer/ck_checkpoints.py b/surftimer/ck_checkpoints.py index 5acd1cd..b52aad7 100644 --- a/surftimer/ck_checkpoints.py +++ b/surftimer/ck_checkpoints.py @@ -91,10 +91,7 @@ async def selectCheckpoints( surftimer.queries.sql_selectCheckpoints.format(mapname, steamid32) ) - if len(xquery) > 0: - # xquery = xquery.pop() - print("Hit, length:", len(xquery)) - else: + if len(xquery) <= 0: response.status_code = status.HTTP_204_NO_CONTENT return response diff --git a/surftimer/queries.py b/surftimer/queries.py index 97167de..9fc872e 100644 --- a/surftimer/queries.py +++ b/surftimer/queries.py @@ -10,8 +10,9 @@ sql_insertBonus = "INSERT INTO ck_bonus (steamid, name, mapname, runtime, zonegroup, velStartXY, velStartXYZ, velStartZ) VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')" sql_updateBonus = "UPDATE ck_bonus SET runtime = '{}', name = '{}', velStartXY = {}, velStartXYZ = {}, velStartZ = {} WHERE steamid = '{}' AND mapname = '{}' AND zonegroup = {} AND style = 0" sql_selectBonusCount = "SELECT zonegroup, style, count(1) FROM ck_bonus WHERE mapname = '{}' GROUP BY zonegroup, style;" -sql_selectPersonalBonusRecords = "SELECT runtime, zonegroup, style FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND runtime > '0.0'" +sql_selectPersonalBonusRecords = "SELECT runtime, zonegroup, style, velStartXY, velStartXYZ, velStartZ FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND runtime > '0.0'" sql_selectPlayerRankBonus = "SELECT name FROM ck_bonus WHERE runtime <= (SELECT runtime FROM ck_bonus WHERE steamid = '{}' AND mapname= '{}' AND runtime > 0.0 AND zonegroup = {} AND style = 0) AND mapname = '{}' AND zonegroup = {} AND style = 0;" +sql_selectPlayerRankBonusCount = "SELECT COUNT(steamid) FROM ck_bonus WHERE runtime <= (SELECT runtime FROM ck_bonus WHERE steamid = '{}' AND mapname= '{}' AND runtime > 0.0 AND zonegroup = {} AND style = 0) AND mapname = '{}' AND zonegroup = {} AND style = 0;" sql_selectFastestBonus = "SELECT t1.name, t1.runtime, t1.zonegroup, t1.style, t1.velStartXY, t1.velStartXYZ, t1.velstartZ from ck_bonus t1 where t1.mapname = '{}' and t1.runtime = (select min(t2.runtime) from ck_bonus t2 where t2.mapname = t1.mapname and t2.zonegroup = t1.zonegroup and t2.style = t1.style);" sql_deleteBonus = "DELETE FROM ck_bonus WHERE mapname = '{}'" sql_selectAllBonusTimesinMap = ( @@ -25,7 +26,7 @@ sql_stray_deleteSpecificBonus = ( "DELETE FROM ck_bonus WHERE zonegroup = {} AND mapname = '{}';" ) -sql_stray_selectPersonalBonusPrestrafeSpeeds = "SELECT zonegroup, style, velStartXY, velStartXYZ, velStartZ FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND runtime > '0.0';" +sql_stray_selectPersonalBonusPrestrafeSpeeds = "SELECT zonegroup, style, velStartXY, velStartXYZ, velStartZ FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND runtime > '0.0';" # merged with sql_selectPersonalBonusRecords sql_stray_selectMapRankBonusStyle = "SELECT name FROM ck_bonus WHERE runtime <= (SELECT runtime FROM ck_bonus WHERE steamid = '{}' AND mapname= '{}' AND style = {} AND runtime > 0.0 AND zonegroup = {}) AND mapname = '{}' AND style = {} AND zonegroup = {};" sql_stray_viewBonusStyleRunRank = "SELECT count(runtime)+1 FROM ck_bonus WHERE mapname = '{}' AND zonegroup = '{}' AND style = '{}' AND runtime < {}" sql_stray_selectPersonalBonusStylesRecords = "SELECT runtime, zonegroup FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND style = '{}' AND runtime > '0.0'" diff --git a/surftimer/refactored.py b/surftimer/refactored.py new file mode 100644 index 0000000..02428f9 --- /dev/null +++ b/surftimer/refactored.py @@ -0,0 +1,91 @@ +from fastapi import APIRouter, Request, Response, status +from fastapi.responses import JSONResponse +from pydantic import BaseModel +from decimal import Decimal +import simplejson as json +from sql import selectQuery, insertQuery +from globals import set_cache, get_cache, all_styles +import time, surftimer.queries + + +router = APIRouter() + + +@router.get( + "/surftimer/getPlayerInitData", + name="Player map data", + tags=["Refactored"], +) +def getPlayerInitData( + request: Request, + response: Response, + steamid32: str, + mapname: str, +): + """combines the following:\n + ```char sql_selectPlayerOptions[] = ....```\n + ```char sql_selectPersonalBonusRecords[] = ....```\n + ```char sql_selectCheckpoints[] = ....```\n + ```char sql_selectPlayerRankBonusCount[] = ....```\n + and maybe more to output a single object with player data""" + tic = time.perf_counter() + + # Check if data is cached in Redis + cache_key = f"getPlayerInitData:{steamid32}-{mapname}" + cached_data = get_cache(cache_key) + + if cached_data is not None: + print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)") + response.headers["content-type"] = "application/json" + response.status_code = status.HTTP_200_OK + response.body = json.loads(cached_data, use_decimal=True, parse_nan=True) + return response + + options_data = selectQuery( + surftimer.queries.sql_selectPlayerOptions.format(steamid32) + ) + + points_data = selectQuery( + surftimer.queries.sql_selectRankedPlayer.format(steamid32) + ) + + bonus_data = selectQuery( + surftimer.queries.sql_selectPersonalBonusRecords.format(steamid32, mapname) + ) + + checkpoints_data = selectQuery( + surftimer.queries.sql_selectCheckpoints.format(mapname, steamid32) + ) + + # if len(bonus_data) <= 0: + # response.headers["content-type"] = "application/json" + # response.status_code = status.HTTP_204_NO_CONTENT + # return response + + for completion in bonus_data: + zonegroup = completion["zonegroup"] + rank_query = selectQuery( + surftimer.queries.sql_selectPlayerRankBonusCount.format( + steamid32, + mapname, + zonegroup, + mapname, + zonegroup, + ) + ) + completion["rank"] = rank_query.pop()["COUNT(steamid)"] + + toc = time.perf_counter() + print(f"Execution time {toc - tic:0.4f}") + + output = { + "options_data": options_data.pop(), + "points_data": points_data, + "bonus_data": bonus_data, + "checkpoints_data": checkpoints_data, + } + + # Cache the data in Redis + set_cache(cache_key, output) + + return output