Skip to content

Commit

Permalink
player object?
Browse files Browse the repository at this point in the history
  • Loading branch information
tslashd committed Sep 20, 2023
1 parent f162045 commit 2c6eab2
Show file tree
Hide file tree
Showing 6 changed files with 164 additions and 16 deletions.
2 changes: 2 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
17 changes: 10 additions & 7 deletions sql.py
Original file line number Diff line number Diff line change
@@ -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)


Expand All @@ -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`"""
Expand All @@ -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()
Expand All @@ -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`"""
Expand All @@ -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()
Expand All @@ -62,6 +64,7 @@ def insert_escaped_query(query):

return mycursor.rowcount


def syncQuery(query):
db = config["DATABASE"]
mydb = mysql.connector.connect(
Expand All @@ -75,4 +78,4 @@ def syncQuery(query):

mydb.commit()

return mycursor.rowcount
return mycursor.rowcount
60 changes: 57 additions & 3 deletions surftimer/ck_bonus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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(
Expand Down
5 changes: 1 addition & 4 deletions surftimer/ck_checkpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 3 additions & 2 deletions surftimer/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand All @@ -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'"
Expand Down
91 changes: 91 additions & 0 deletions surftimer/refactored.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 2c6eab2

Please sign in to comment.