Skip to content

Commit 2c6eab2

Browse files
committed
player object?
1 parent f162045 commit 2c6eab2

File tree

6 files changed

+164
-16
lines changed

6 files changed

+164
-16
lines changed

main.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
from surftimer.ck_spawnlocations import router as ck_spawnlocations_router
3939
from surftimer.ck_zones import router as ck_zones_router
4040
from surftimer.points import router as points_calculation
41+
from surftimer.refactored import router as refactored_router
4142

4243

4344
class IPValidatorMiddleware(BaseHTTPMiddleware):
@@ -96,6 +97,7 @@ async def dispatch(self, request: Request, call_next):
9697
app.include_router(ck_spawnlocations_router)
9798
app.include_router(ck_zones_router)
9899
app.include_router(points_calculation)
100+
app.include_router(refactored_router)
99101

100102

101103
@app.get("/docs2", include_in_schema=False)

sql.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import mysql.connector
2-
import json
2+
import simplejson as json
33

44

5-
with open('config.json', 'r') as f:
5+
with open("config.json", "r") as f:
66
config = json.load(f)
77

88

@@ -15,17 +15,18 @@ def selectQuery(query):
1515
host=db["HOST"],
1616
user=db["USERNAME"],
1717
password=db["PASSWORD"],
18-
database=db["DB"]
18+
database=db["DB"],
1919
)
2020
mycursor = mydb.cursor(dictionary=True)
2121
mycursor.execute(query)
2222
res = mycursor.fetchall()
2323
for result in res:
2424
json_data.append(dict(result))
25-
25+
2626
mydb.close()
2727
return json_data
2828

29+
2930
def insertQuery(query):
3031
"""Executes `INSERT` query provided and returns `mycursor.rowcount`\n
3132
Connects to a predefined `Database` from `config.json`"""
@@ -34,7 +35,7 @@ def insertQuery(query):
3435
host=db["HOST"],
3536
user=db["USERNAME"],
3637
password=db["PASSWORD"],
37-
database=db["DB"]
38+
database=db["DB"],
3839
)
3940

4041
mycursor = mydb.cursor()
@@ -44,6 +45,7 @@ def insertQuery(query):
4445

4546
return mycursor.rowcount
4647

48+
4749
def insert_escaped_query(query):
4850
"""Executes `INSERT` query `mycursor.execute("", (query))` provided and returns `mycursor.rowcount`\n
4951
Connects to a predefined `Database` from `config.json`"""
@@ -52,7 +54,7 @@ def insert_escaped_query(query):
5254
host=db["HOST"],
5355
user=db["USERNAME"],
5456
password=db["PASSWORD"],
55-
database=db["DB"]
57+
database=db["DB"],
5658
)
5759

5860
mycursor = mydb.cursor()
@@ -62,6 +64,7 @@ def insert_escaped_query(query):
6264

6365
return mycursor.rowcount
6466

67+
6568
def syncQuery(query):
6669
db = config["DATABASE"]
6770
mydb = mysql.connector.connect(
@@ -75,4 +78,4 @@ def syncQuery(query):
7578

7679
mydb.commit()
7780

78-
return mycursor.rowcount
81+
return mycursor.rowcount

surftimer/ck_bonus.py

Lines changed: 57 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,62 @@ def selectPersonalBonusRecords(
191191
return xquery
192192

193193

194+
@router.get(
195+
"/surftimer/selectPersonalBonusesMap",
196+
name="Get Player Bonus info for map",
197+
tags=["ck_bonus", "Refactored"],
198+
)
199+
def selectPersonalBonusesMap(
200+
request: Request, response: Response, steamid32: str, mapname: str
201+
):
202+
"""merge ```char sql_selectPersonalBonusRecords[] = ....```\n
203+
and\n
204+
```char sql_selectPlayerRankBonus[] = ....```\n
205+
and maybe more to output a single object with Bonus information for player"""
206+
tic = time.perf_counter()
207+
208+
# Check if data is cached in Redis
209+
cache_key = f"selectPersonalBonusesMap:{steamid32}-{mapname}"
210+
cached_data = get_cache(cache_key)
211+
212+
if cached_data is not None:
213+
print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)")
214+
response.headers["content-type"] = "application/json"
215+
response.status_code = status.HTTP_200_OK
216+
response.body = json.loads(cached_data, use_decimal=True, parse_nan=True)
217+
return response
218+
219+
xquery = selectQuery(
220+
surftimer.queries.sql_selectPersonalBonusRecords.format(steamid32, mapname)
221+
)
222+
223+
if len(xquery) <= 0:
224+
response.headers["content-type"] = "application/json"
225+
response.status_code = status.HTTP_204_NO_CONTENT
226+
return response
227+
228+
for completion in xquery:
229+
zonegroup = completion["zonegroup"]
230+
rank_query = selectQuery(
231+
surftimer.queries.sql_selectPlayerRankBonusCount.format(
232+
steamid32,
233+
mapname,
234+
zonegroup,
235+
mapname,
236+
zonegroup,
237+
)
238+
)
239+
completion["rank"] = rank_query.pop()["COUNT(steamid)"]
240+
241+
toc = time.perf_counter()
242+
print(f"Execution time {toc - tic:0.4f}")
243+
244+
# Cache the data in Redis
245+
set_cache(cache_key, xquery)
246+
247+
return xquery
248+
249+
194250
@router.get(
195251
"/surftimer/selectPlayerRankBonus",
196252
name="Get Player Rank Bonus",
@@ -887,9 +943,7 @@ def getRankSteamIdBonus(
887943

888944
if zonegroup == 0:
889945
xquery = selectQuery(
890-
surftimer.queries.sql_stray_steamIdFromMapRank.format(
891-
mapname, limit
892-
)
946+
surftimer.queries.sql_stray_steamIdFromMapRank.format(mapname, limit)
893947
)
894948
else:
895949
xquery = selectQuery(

surftimer/ck_checkpoints.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,7 @@ async def selectCheckpoints(
9191
surftimer.queries.sql_selectCheckpoints.format(mapname, steamid32)
9292
)
9393

94-
if len(xquery) > 0:
95-
# xquery = xquery.pop()
96-
print("Hit, length:", len(xquery))
97-
else:
94+
if len(xquery) <= 0:
9895
response.status_code = status.HTTP_204_NO_CONTENT
9996
return response
10097

surftimer/queries.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@
1010
sql_insertBonus = "INSERT INTO ck_bonus (steamid, name, mapname, runtime, zonegroup, velStartXY, velStartXYZ, velStartZ) VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')"
1111
sql_updateBonus = "UPDATE ck_bonus SET runtime = '{}', name = '{}', velStartXY = {}, velStartXYZ = {}, velStartZ = {} WHERE steamid = '{}' AND mapname = '{}' AND zonegroup = {} AND style = 0"
1212
sql_selectBonusCount = "SELECT zonegroup, style, count(1) FROM ck_bonus WHERE mapname = '{}' GROUP BY zonegroup, style;"
13-
sql_selectPersonalBonusRecords = "SELECT runtime, zonegroup, style FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND runtime > '0.0'"
13+
sql_selectPersonalBonusRecords = "SELECT runtime, zonegroup, style, velStartXY, velStartXYZ, velStartZ FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND runtime > '0.0'"
1414
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;"
15+
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;"
1516
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);"
1617
sql_deleteBonus = "DELETE FROM ck_bonus WHERE mapname = '{}'"
1718
sql_selectAllBonusTimesinMap = (
@@ -25,7 +26,7 @@
2526
sql_stray_deleteSpecificBonus = (
2627
"DELETE FROM ck_bonus WHERE zonegroup = {} AND mapname = '{}';"
2728
)
28-
sql_stray_selectPersonalBonusPrestrafeSpeeds = "SELECT zonegroup, style, velStartXY, velStartXYZ, velStartZ FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND runtime > '0.0';"
29+
sql_stray_selectPersonalBonusPrestrafeSpeeds = "SELECT zonegroup, style, velStartXY, velStartXYZ, velStartZ FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND runtime > '0.0';" # merged with sql_selectPersonalBonusRecords
2930
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 = {};"
3031
sql_stray_viewBonusStyleRunRank = "SELECT count(runtime)+1 FROM ck_bonus WHERE mapname = '{}' AND zonegroup = '{}' AND style = '{}' AND runtime < {}"
3132
sql_stray_selectPersonalBonusStylesRecords = "SELECT runtime, zonegroup FROM ck_bonus WHERE steamid = '{}' AND mapname = '{}' AND style = '{}' AND runtime > '0.0'"

surftimer/refactored.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
from fastapi import APIRouter, Request, Response, status
2+
from fastapi.responses import JSONResponse
3+
from pydantic import BaseModel
4+
from decimal import Decimal
5+
import simplejson as json
6+
from sql import selectQuery, insertQuery
7+
from globals import set_cache, get_cache, all_styles
8+
import time, surftimer.queries
9+
10+
11+
router = APIRouter()
12+
13+
14+
@router.get(
15+
"/surftimer/getPlayerInitData",
16+
name="Player map data",
17+
tags=["Refactored"],
18+
)
19+
def getPlayerInitData(
20+
request: Request,
21+
response: Response,
22+
steamid32: str,
23+
mapname: str,
24+
):
25+
"""combines the following:\n
26+
```char sql_selectPlayerOptions[] = ....```\n
27+
```char sql_selectPersonalBonusRecords[] = ....```\n
28+
```char sql_selectCheckpoints[] = ....```\n
29+
```char sql_selectPlayerRankBonusCount[] = ....```\n
30+
and maybe more to output a single object with player data"""
31+
tic = time.perf_counter()
32+
33+
# Check if data is cached in Redis
34+
cache_key = f"getPlayerInitData:{steamid32}-{mapname}"
35+
cached_data = get_cache(cache_key)
36+
37+
if cached_data is not None:
38+
print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)")
39+
response.headers["content-type"] = "application/json"
40+
response.status_code = status.HTTP_200_OK
41+
response.body = json.loads(cached_data, use_decimal=True, parse_nan=True)
42+
return response
43+
44+
options_data = selectQuery(
45+
surftimer.queries.sql_selectPlayerOptions.format(steamid32)
46+
)
47+
48+
points_data = selectQuery(
49+
surftimer.queries.sql_selectRankedPlayer.format(steamid32)
50+
)
51+
52+
bonus_data = selectQuery(
53+
surftimer.queries.sql_selectPersonalBonusRecords.format(steamid32, mapname)
54+
)
55+
56+
checkpoints_data = selectQuery(
57+
surftimer.queries.sql_selectCheckpoints.format(mapname, steamid32)
58+
)
59+
60+
# if len(bonus_data) <= 0:
61+
# response.headers["content-type"] = "application/json"
62+
# response.status_code = status.HTTP_204_NO_CONTENT
63+
# return response
64+
65+
for completion in bonus_data:
66+
zonegroup = completion["zonegroup"]
67+
rank_query = selectQuery(
68+
surftimer.queries.sql_selectPlayerRankBonusCount.format(
69+
steamid32,
70+
mapname,
71+
zonegroup,
72+
mapname,
73+
zonegroup,
74+
)
75+
)
76+
completion["rank"] = rank_query.pop()["COUNT(steamid)"]
77+
78+
toc = time.perf_counter()
79+
print(f"Execution time {toc - tic:0.4f}")
80+
81+
output = {
82+
"options_data": options_data.pop(),
83+
"points_data": points_data,
84+
"bonus_data": bonus_data,
85+
"checkpoints_data": checkpoints_data,
86+
}
87+
88+
# Cache the data in Redis
89+
set_cache(cache_key, output)
90+
91+
return output

0 commit comments

Comments
 (0)