]> de.git.xonotic.org Git - xonotic/xonstat.git/blobdiff - xonstat/views/submission.py
Update the is_supported_game_type function to use the new object.
[xonotic/xonstat.git] / xonstat / views / submission.py
index 373dc8a91f26cbb07352a50b9bc3561b9ebe811f..1b7417f78f1124eeeda6aa9487e1bbf0025c2076 100644 (file)
@@ -16,27 +16,6 @@ from xonstat.util import strip_colors, qfont_decode, verify_request, weapon_map
 log = logging.getLogger(__name__)
 
 
-def is_real_player(events):
-    """
-    Determines if a given set of events correspond with a non-bot
-    """
-    if not events['P'].startswith('bot'):
-        return True
-    else:
-        return False
-
-
-def played_in_game(events):
-    """
-    Determines if a given set of player events correspond with a player who
-    played in the game (matches 1 and scoreboardvalid 1)
-    """
-    if 'matches' in events and 'scoreboardvalid' in events:
-        return True
-    else:
-        return False
-
-
 class Submission(object):
     """Parses an incoming POST request for stats submissions."""
 
@@ -106,6 +85,12 @@ class Submission(object):
         # has a human player fired a shot?
         self.human_fired_weapon = False
 
+        # does any human have a non-zero score?
+        self.human_nonzero_score = False
+
+        # does any human have a fastest cap?
+        self.human_fastest = False
+
     def next_item(self):
         """Returns the next key:value pair off the queue."""
         try:
@@ -119,11 +104,24 @@ class Submission(object):
         except:
             return None, None
 
-    def check_for_new_weapon_fired(self, sub_key):
-        """Checks if a given weapon fired event is a new one for the match."""
-        weapon = sub_key.split("-")[1]
-        if weapon not in self.weapons:
-            self.weapons.add(weapon)
+    def add_weapon_fired(self, sub_key):
+        """Adds a weapon to the set of weapons fired during the match (a set)."""
+        self.weapons.add(sub_key.split("-")[1])
+
+    @staticmethod
+    def is_human_player(player):
+        """
+        Determines if a given set of events correspond with a non-bot
+        """
+        return not player['P'].startswith('bot')
+
+    @staticmethod
+    def played_in_game(player):
+        """
+        Determines if a given set of player events correspond with a player who
+        played in the game (matches 1 and scoreboardvalid 1)
+        """
+        return 'matches' in player and 'scoreboardvalid' in player
 
     def parse_player(self, key, pid):
         """Construct a player events listing from the submission."""
@@ -134,6 +132,8 @@ class Submission(object):
         player = {key: pid}
 
         player_fired_weapon = False
+        player_nonzero_score = False
+        player_fastest = False
 
         # Consume all following 'i' 'n' 't'  'e' records
         while len(self.q) > 0:
@@ -146,7 +146,11 @@ class Submission(object):
 
                 if sub_key.endswith("cnt-fired"):
                     player_fired_weapon = True
-                    self.check_for_new_weapon_fired(sub_key)
+                    self.add_weapon_fired(sub_key)
+                elif sub_key == 'scoreboard-score' and int(sub_value) != 0:
+                    player_nonzero_score = True
+                elif sub_key == 'scoreboard-fastest':
+                    player_fastest = True
             elif key == 'n':
                 player[key] = unicode(value, 'utf-8')
             elif key in player_keys:
@@ -156,18 +160,25 @@ class Submission(object):
                 self.q.appendleft("{} {}".format(key, value))
                 break
 
-        played = played_in_game(player)
-        human = is_real_player(player)
+        played = self.played_in_game(player)
+        human = self.is_human_player(player)
 
         if played and human:
             self.humans.append(player)
 
             if player_fired_weapon:
                 self.human_fired_weapon = True
+
+            if player_nonzero_score:
+                self.human_nonzero_score = True
+
+            if player_fastest:
+                self.human_fastest = True
+
         elif played and not human:
             self.bots.append(player)
-        else:
-            self.players.append(player)
+
+        self.players.append(player)
 
     def parse_team(self, key, tid):
         """Construct a team events listing from the submission."""
@@ -218,10 +229,16 @@ class Submission(object):
 
         return self
 
+    def __repr__(self):
+        """Debugging representation of a submission."""
+        return "game_type_cd: {}, mod: {}, players: {}, humans: {}, bots: {}, weapons: {}".format(
+            self.game_type_cd, self.mod, len(self.players), len(self.humans), len(self.bots),
+            self.weapons)
+
 
 def elo_submission_category(submission):
     """Determines the Elo category purely by what is in the submission data."""
-    mod = submission.meta.get("O", "None")
+    mod = submission.mod
 
     vanilla_allowed_weapons = {"shotgun", "devastator", "blaster", "mortar", "vortex", "electro",
                                "arc", "hagar", "crylink", "machinegun"}
@@ -243,79 +260,9 @@ def elo_submission_category(submission):
     return "general"
 
 
-def parse_stats_submission(body):
-    """
-    Parses the POST request body for a stats submission
+def is_blank_game(submission):
     """
-    # storage vars for the request body
-    game_meta = {}
-    events = {}
-    players = []
-    teams = []
-
-    # we're not in either stanza to start
-    in_P = in_Q = False
-
-    for line in body.split('\n'):
-        try:
-            (key, value) = line.strip().split(' ', 1)
-
-            # Server (S) and Nick (n) fields can have international characters.
-            if key in 'S' 'n':
-                value = unicode(value, 'utf-8')
-
-            if key not in 'P' 'Q' 'n' 'e' 't' 'i':
-                game_meta[key] = value
-
-            if key == 'Q' or key == 'P':
-                #log.debug('Found a {0}'.format(key))
-                #log.debug('in_Q: {0}'.format(in_Q))
-                #log.debug('in_P: {0}'.format(in_P))
-                #log.debug('events: {0}'.format(events))
-
-                # check where we were before and append events accordingly
-                if in_Q and len(events) > 0:
-                    #log.debug('creating a team (Q) entry')
-                    teams.append(events)
-                    events = {}
-                elif in_P and len(events) > 0:
-                    #log.debug('creating a player (P) entry')
-                    players.append(events)
-                    events = {}
-
-                if key == 'P':
-                    #log.debug('key == P')
-                    in_P = True
-                    in_Q = False
-                elif key == 'Q':
-                    #log.debug('key == Q')
-                    in_P = False
-                    in_Q = True
-
-                events[key] = value
-
-            if key == 'e':
-                (subkey, subvalue) = value.split(' ', 1)
-                events[subkey] = subvalue
-            if key == 'n':
-                events[key] = value
-            if key == 't':
-                events[key] = value
-        except:
-            # no key/value pair - move on to the next line
-            pass
-
-    # add the last entity we were working on
-    if in_P and len(events) > 0:
-        players.append(events)
-    elif in_Q and len(events) > 0:
-        teams.append(events)
-
-    return (game_meta, players, teams)
-
-
-def is_blank_game(gametype, players):
-    """Determine if this is a blank game or not. A blank game is either:
+    Determine if this is a blank game or not. A blank game is either:
 
     1) a match that ended in the warmup stage, where accuracy events are not
     present (for non-CTS games)
@@ -332,40 +279,24 @@ def is_blank_game(gametype, players):
 
     1) a match in which no player made a positive or negative score
     """
-    r = re.compile(r'acc-.*-cnt-fired')
-    flg_nonzero_score = False
-    flg_acc_events = False
-    flg_fastest_lap = False
-
-    for events in players:
-        if is_real_player(events) and played_in_game(events):
-            for (key,value) in events.items():
-                if key == 'scoreboard-score' and value != 0:
-                    flg_nonzero_score = True
-                if r.search(key):
-                    flg_acc_events = True
-                if key == 'scoreboard-fastest':
-                    flg_fastest_lap = True
-
-    if gametype == 'cts':
-        return not flg_fastest_lap
-    elif gametype == 'nb':
-        return not flg_nonzero_score
+    if submission.game_type_cd == 'cts':
+        return not submission.human_fastest
+    elif submission.game_type_cd == 'nb':
+        return not submission.human_nonzero_score
     else:
-        return not (flg_nonzero_score and flg_acc_events)
+        return not (submission.human_nonzero_score and submission.human_fired_weapon)
 
 
-def get_remote_addr(request):
-    """Get the Xonotic server's IP address"""
-    if 'X-Forwarded-For' in request.headers:
-        return request.headers['X-Forwarded-For']
-    else:
-        return request.remote_addr
+def has_required_metadata(submission):
+    """Determines if a submission has all the required metadata fields."""
+    return (submission.game_type_cd is not None
+            and submission.map_name is not None
+            and submission.match_id is not None
+            and submission.server_name is not None)
 
 
-def is_supported_gametype(gametype, version):
-    """Whether a gametype is supported or not"""
-    is_supported = False
+def is_supported_gametype(submission):
+    """Determines if a submission is of a valid and supported game type."""
 
     # if the type can be supported, but with version constraints, uncomment
     # here and add the restriction for a specific version below
@@ -388,18 +319,23 @@ def is_supported_gametype(gametype, version):
             'tdm',
         )
 
-    if gametype in supported_game_types:
-        is_supported = True
-    else:
-        is_supported = False
+    is_supported = submission.game_type_cd in supported_game_types
 
     # some game types were buggy before revisions, thus this additional filter
-    if gametype == 'ca' and version <= 5:
+    if submission.game_type_cd == 'ca' and submission.version <= 5:
         is_supported = False
 
     return is_supported
 
 
+def get_remote_addr(request):
+    """Get the Xonotic server's IP address"""
+    if 'X-Forwarded-For' in request.headers:
+        return request.headers['X-Forwarded-For']
+    else:
+        return request.remote_addr
+
+
 def do_precondition_checks(request, game_meta, raw_players):
     """Precondition checks for ALL gametypes.
        These do not require a database connection."""
@@ -482,22 +418,6 @@ def has_minimum_real_players(settings, player_events):
     return flg_has_min_real_players
 
 
-def has_required_metadata(metadata):
-    """
-    Determines if a give set of metadata has enough data to create a game,
-    server, and map with.
-    """
-    flg_has_req_metadata = True
-
-    if 'G' not in metadata or\
-        'M' not in metadata or\
-        'I' not in metadata or\
-        'S' not in metadata:
-            flg_has_req_metadata = False
-
-    return flg_has_req_metadata
-
-
 def should_do_weapon_stats(game_type_cd):
     """True of the game type should record weapon stats. False otherwise."""
     if game_type_cd in 'cts':