]> de.git.xonotic.org Git - xonotic/xonstat.git/blobdiff - xonstat/views/submission.py
Clean up the function signature a bit.
[xonotic/xonstat.git] / xonstat / views / submission.py
index 670807b8ad0c403a14d167189eac51e0eae1b1e7..9c2cd9ca9dd18a55870cd980a90426312195ed3c 100644 (file)
@@ -556,54 +556,50 @@ def get_or_create_server(session, name, hashkey, ip_addr, revision, port, impure
     return server
 
 
-def get_or_create_map(session=None, name=None):
+def get_or_create_map(session, name):
     """
     Find a map by name or create one if not found. Parameters:
 
     session - SQLAlchemy database session factory
     name - map name of the map to be found or created
     """
-    try:
-        # find one by the name, if it exists
-        gmap = session.query(Map).filter_by(name=name).one()
-        log.debug("Found map id {0}: {1}".format(gmap.map_id,
-            gmap.name))
-    except NoResultFound, e:
+    maps = session.query(Map).filter_by(name=name).order_by(Map.map_id).all()
+
+    if maps is None or len(maps) == 0:
         gmap = Map(name=name)
         session.add(gmap)
         session.flush()
-        log.debug("Created map id {0}: {1}".format(gmap.map_id,
-            gmap.name))
-    except MultipleResultsFound, e:
-        # multiple found, so use the first one but warn
-        log.debug(e)
-        gmaps = session.query(Map).filter_by(name=name).order_by(
-                Map.map_id).all()
-        gmap = gmaps[0]
-        log.debug("Found map id {0}: {1} but found \
-                multiple".format(gmap.map_id, gmap.name))
+        log.debug("Created map id {}: {}".format(gmap.map_id, gmap.name))
+    elif len(maps) == 1:
+        gmap = maps[0]
+        log.debug("Found map id {}: {}".format(gmap.map_id, gmap.name))
+    else:
+        gmap = maps[0]
+        map_id_list = ", ".join(["{}".format(m.map_id) for m in maps])
+        log.warn("Multiple maps found for {} ({})! Using the first one.".format(name, map_id_list))
 
     return gmap
 
 
-def create_game(session, start_dt, game_type_cd, server_id, map_id,
-        match_id, duration, mod, winner=None):
+def create_game(session, game_type_cd, server_id, map_id, match_id, start_dt, duration, mod,
+                winner=None):
     """
     Creates a game. Parameters:
 
     session - SQLAlchemy database session factory
-    start_dt - when the game started (datetime object)
     game_type_cd - the game type of the game being played
+    mod - mods in use during the game
     server_id - server identifier of the server hosting the game
     map_id - map on which the game was played
-    winner - the team id of the team that won
+    match_id - a unique match ID given by the server
+    start_dt - when the game started (datetime object)
     duration - how long the game lasted
-    mod - mods in use during the game
+    winner - the team id of the team that won
     """
     seq = Sequence('games_game_id_seq')
     game_id = session.execute(seq)
-    game = Game(game_id=game_id, start_dt=start_dt, game_type_cd=game_type_cd,
-                server_id=server_id, map_id=map_id, winner=winner)
+    game = Game(game_id=game_id, start_dt=start_dt, game_type_cd=game_type_cd, server_id=server_id,
+                map_id=map_id, winner=winner)
     game.match_id = match_id
     game.mod = mod[:64]
 
@@ -612,27 +608,25 @@ def create_game(session, start_dt, game_type_cd, server_id, map_id,
     # resolved.
     game.create_dt = start_dt
 
-    try:
-        game.duration = datetime.timedelta(seconds=int(round(float(duration))))
-    except:
-        pass
+    game.duration = duration
 
     try:
-        session.query(Game).filter(Game.server_id==server_id).\
-                filter(Game.match_id==match_id).one()
+        session.query(Game).filter(Game.server_id == server_id)\
+            .filter(Game.match_id == match_id).one()
 
         log.debug("Error: game with same server and match_id found! Ignoring.")
 
-        # if a game under the same server and match_id found,
-        # this is a duplicate game and can be ignored
-        raise pyramid.httpexceptions.HTTPOk('OK')
-    except NoResultFound, e:
+        # if a game under the same server_id and match_id exists, this is a duplicate
+        msg = "Duplicate game (pre-existing match_id)"
+        log.debug(msg)
+        raise pyramid.httpexceptions.HTTPOk(body=msg, content_type="text/plain")
+
+    except NoResultFound:
         # server_id/match_id combination not found. game is ok to insert
         session.add(game)
         session.flush()
-        log.debug("Created game id {0} on server {1}, map {2} at \
-                {3}".format(game.game_id,
-                    server_id, map_id, start_dt))
+        log.debug("Created game id {} on server {}, map {} at {}"
+                  .format(game.game_id, server_id, map_id, start_dt))
 
     return game
 
@@ -972,6 +966,48 @@ def get_ranks(session, player_ids, game_type_cd):
     return ranks
 
 
+def update_player(session, player, events):
+    pass
+
+
+def create_player(session, events):
+    pass
+
+
+def get_or_create_players(session, events_by_hashkey):
+    hashkeys = set(events_by_hashkey.keys())
+    players_by_hashkey = {}
+
+    bot = session.query(Player).filter(Player.player_id == 1).one()
+    anon = session.query(Player).filter(Player.player_id == 2).one()
+
+    # fill in the bots and anonymous players
+    for hashkey in events_by_hashkey.keys():
+        if hashkey.startswith("bot#"):
+            players_by_hashkey[hashkey] = bot
+            hashkeys.remove(hashkey)
+        elif hashkey.startswith("player#"):
+            players_by_hashkey[hashkey] = anon
+            hashkeys.remove(hashkey)
+
+    # We are left with the "real" players and can now fetch them by their collective hashkeys.
+    # Those that are returned here are pre-existing players who need to be updated.
+    for p, hk in session.query(Player, Hashkey)\
+            .filter(Player.player_id == Hashkey.player_id)\
+            .filter(Hashkey.hashkey.in_(hashkeys))\
+            .all():
+                player = update_player(session, p, events_by_hashkey[hk.hashkey])
+                players_by_hashkey[hk.hashkey] = player
+                hashkeys.remove(hk.hashkey)
+
+    # The remainder are the players we haven't seen before, so we need to create them.
+    for hashkey in hashkeys:
+        player = create_player(session, events_by_hashkey[hashkey])
+        players_by_hashkey[hashkey] = player
+
+    return players_by_hashkey
+
+
 def submit_stats(request):
     """
     Entry handler for POST stats submissions.
@@ -1009,15 +1045,18 @@ def submit_stats(request):
 
         game = create_game(
             session=session,
-            start_dt=datetime.datetime.utcnow(),
-            server_id=server.server_id,
             game_type_cd=submission.game_type_cd,
+            mod=submission.mod,
+            server_id=server.server_id,
             map_id=gmap.map_id,
             match_id=submission.match_id,
-            duration=submission.duration,
-            mod=submission.mod
+            start_dt=datetime.datetime.utcnow(),
+            duration=submission.duration
         )
 
+        events_by_hashkey = {elem["P"]: elem for elem in submission.humans + submission.bots}
+        get_or_create_players(session, game, gmap, events_by_hashkey)
+
         # keep track of the players we've seen
         player_ids = []
         pgstats = []
@@ -1041,10 +1080,7 @@ def submit_stats(request):
         game.players = player_ids
 
         for events in submission.teams:
-            try:
-                create_team_stat(session, game, events)
-            except Exception as e:
-                raise e
+            create_team_stat(session, game, events)
 
         if server.elo_ind and gametype_elo_eligible(submission.game_type_cd):
             ep = EloProcessor(session, game, pgstats)