git.haldean.org apex / master data.py
master

Tree @master (Download .tar.gz)

data.py @masterraw · history · blame

from datetime import datetime, timezone
import csv
import json

from globals import *

valid_fields = set([
    "hero",
    "droploc",
    "endloc",
    "teamsleft",
    "minutes",
    "selfdc",
    "teamdc",
    "gun1",
    "gun2",
    "attachments",
    "hacker",
    "teamquality",
    "selfkills",
    "squadkills",
    ])

dump_fields = ["key", "time"] + sorted(list(valid_fields))

def store(username, gamedata):
    req_fields = set(gamedata.keys())
    missing = valid_fields - req_fields
    extra = req_fields - valid_fields
    if missing or extra:
        raise ValueError(
            "bad game data: missing {}, extra {}".format(missing, extra))
    now = datetime.now(timezone.utc)
    now_ts = now.timestamp()
    gamekey = "apex:games:{}:{}".format(username, now_ts)
    if r.get(gamekey) is not None:
        raise ValueError(
            "game key {} already exists".format(gamekey))
    gamedata["key"] = gamekey
    gamedata["time"] = now.isoformat()
    gamedata["user"] = username
    r.set(gamekey, json.dumps(gamedata))
    r.sadd("apex:games:{}".format(username), gamekey)

def get_user_games(username):
    return r.smembers("apex:games:{}".format(username))

def get_game(gamekey):
    return json.loads(r.get(gamekey).decode("utf-8"))

def dump_games_to_json(username):
    gamekeys = list(get_user_games(username))
    gamekeys.sort()
    rows = []
    cols = list(valid_fields)
    cols.sort()
    d = []
    for key in gamekeys:
        gamedata = get_game(key)
        rows.append(gamedata.get("time"))
        d.append([gamedata.get(k) for k in cols])
    return json.dumps({
        "rows": rows,
        "cols": cols,
        "data": d,
    })