]> de.git.xonotic.org Git - xonotic/xonstat.git/blobdiff - xonstat/views/game.py
Add separate views for the top servers on a map.
[xonotic/xonstat.git] / xonstat / views / game.py
index 79920c51e606e377e625abdd1ebe8ba634be4c8d..3df051f4e5e7b464673f149b483db8a5f9ab79e8 100644 (file)
@@ -1,32 +1,24 @@
-import datetime
 import logging
-import re
-import time
 from collections import OrderedDict
-from pyramid.response import Response
-from sqlalchemy import desc, func, over
-from webhelpers.paginate import Page, PageURL
-from xonstat.models import *
+
+from pyramid import httpexceptions
+from sqlalchemy.orm.exc import *
+from webhelpers.paginate import Page
+from xonstat.models import DBSession, Server, Map, Game, PlayerGameStat, PlayerWeaponStat
+from xonstat.models import TeamGameStat, PlayerRank, GameType, Weapon
 from xonstat.util import page_url
 from xonstat.views.helpers import RecentGame, recent_games_q
 
-
 log = logging.getLogger(__name__)
 
 
 def _game_info_data(request):
-    game_id = request.matchdict['id']
-
-    if request.params.has_key('show_elo'):
-        show_elo = True
-    else:
-        show_elo = False
+    game_id = int(request.matchdict['id'])
 
-    show_latency = False
+    # show an extra column if "show_elo" is a GET parameter
+    show_elo = bool(request.params.get("show_elo", False))
 
     try:
-        notfound = False
-
         (game, server, map, gametype) = DBSession.query(Game, Server, Map, GameType).\
                 filter(Game.game_id == game_id).\
                 filter(Game.server_id == Server.server_id).\
@@ -39,10 +31,13 @@ def _game_info_data(request):
                 order_by(PlayerGameStat.score).\
                 all()
 
-        # if at least one player has a valid latency, we'll show the column
+        # Really old games don't have latency sent, so we have to check. If at
+        # least one player has a latency value, we'll show the ping column.
+        show_latency = False
         for pgstat in pgstats:
             if pgstat.avg_latency is not None:
                 show_latency = True
+                break
 
         q = DBSession.query(TeamGameStat).\
                 filter(TeamGameStat.game_id == game_id)
@@ -70,38 +65,23 @@ def _game_info_data(request):
             captimes = sorted(captimes, key=lambda x:x.fastest)
 
         pwstats = {}
-        for (pwstat, pgstat, weapon) in DBSession.query(PlayerWeaponStat, PlayerGameStat, Weapon).\
+        for (pwstat, weapon) in DBSession.query(PlayerWeaponStat, Weapon).\
                 filter(PlayerWeaponStat.game_id == game_id).\
                 filter(PlayerWeaponStat.weapon_cd == Weapon.weapon_cd).\
-                filter(PlayerWeaponStat.player_game_stat_id == \
-                    PlayerGameStat.player_game_stat_id).\
-                order_by(PlayerGameStat.scoreboardpos).\
-                order_by(PlayerGameStat.score).\
-                order_by(Weapon.descr).\
+                order_by(PlayerWeaponStat.actual.desc()).\
                 all():
-                    if pgstat.player_game_stat_id not in pwstats:
-                        pwstats[pgstat.player_game_stat_id] = []
+                    if pwstat.player_game_stat_id not in pwstats:
+                        pwstats[pwstat.player_game_stat_id] = []
 
-                    # NOTE adding pgstat to position 6 in order to display nick.
-                    # You have to use a slice [0:5] to pass to the accuracy
-                    # template
-                    pwstats[pgstat.player_game_stat_id].append((weapon.descr,
+                    pwstats[pwstat.player_game_stat_id].append((weapon.descr,
                         weapon.weapon_cd, pwstat.actual, pwstat.max,
-                        pwstat.hit, pwstat.fired, pwstat.frags, pgstat))
-
-    except Exception as inst:
-        game = None
-        server = None
-        map = None
-        gametype = None
-        pgstats = None
-        tgstats = None
-        pwstats = None
-        captimes = None
-        show_elo = False
-        show_latency = False
-        stats_by_team = None
-        raise inst
+                        pwstat.hit, pwstat.fired, pwstat.frags))
+
+    except NoResultFound as e:
+        raise httpexceptions.HTTPNotFound("Could not find that game!")
+
+    except Exception as e:
+        raise e
 
     return {'game':game,
             'server':server,
@@ -132,17 +112,22 @@ def game_info_json(request):
 
 
 def _rank_index_data(request):
-    if request.params.has_key('page'):
-        current_page = request.params['page']
-    else:
-        current_page = 1
+    current_page = request.params.get("page", 1)
+
+    # game type whitelist
+    game_types_allowed = ["ca", "ctf", "dm", "duel", "ft", "ka", "tdm"]
 
     game_type_cd = request.matchdict['game_type_cd']
+    if game_type_cd not in game_types_allowed:
+        raise httpexceptions.HTTPNotFound()
 
     ranks_q = DBSession.query(PlayerRank).\
             filter(PlayerRank.game_type_cd==game_type_cd).\
             order_by(PlayerRank.rank)
 
+    game_type = DBSession.query(GameType).\
+            filter(GameType.game_type_cd == game_type_cd).one()
+
     ranks = Page(ranks_q, current_page, url=page_url)
 
     if len(ranks) == 0:
@@ -151,6 +136,7 @@ def _rank_index_data(request):
     return {
             'ranks':ranks,
             'game_type_cd':game_type_cd,
+            'game_type': game_type,
            }
 
 
@@ -215,26 +201,30 @@ def game_finder_data(request):
             player_id=player_id, game_type_cd=game_type_cd,
             start_game_id=start_game_id, end_game_id=end_game_id)
 
-    recent_games = [RecentGame(row) for row in rgs_q.limit(20).all()]
-    
-    if len(recent_games) > 0:
-        query['start_game_id'] = recent_games[-1].game_id + 1
-
-    # build the list of links for the stripe across the top
-    game_type_links = []
-
-    # clear out the game_id window
-    gt_query = query.copy()
-    if 'start_game_id' in gt_query:
-        del gt_query['start_game_id']
-    if 'end_game_id' in gt_query:
-        del gt_query['end_game_id']
-
-    for gt in ('overall','duel','ctf','dm','tdm','ca','kh','ft',
-            'lms','as','dom','nb','cts','rc'):
-        gt_query['type'] = gt
-        url = request.route_url("game_index", _query=gt_query)
-        game_type_links.append((gt, url))
+    try:
+        recent_games = [RecentGame(row) for row in rgs_q.limit(20).all()]
+        
+        if len(recent_games) > 0:
+            query['start_game_id'] = recent_games[-1].game_id + 1
+
+        # build the list of links for the stripe across the top
+        game_type_links = []
+
+        # clear out the game_id window
+        gt_query = query.copy()
+        if 'start_game_id' in gt_query:
+            del gt_query['start_game_id']
+        if 'end_game_id' in gt_query:
+            del gt_query['end_game_id']
+
+        for gt in ('overall','duel','ctf','dm','tdm','ca','kh','ft',
+                'lms','as','dom','nb','cts','rc'):
+            gt_query['type'] = gt
+            url = request.route_url("game_index", _query=gt_query)
+            game_type_links.append((gt, url))
+
+    except:
+        raise httpexceptions.HTTPBadRequest("Malformed Query")
 
     return {
             'recent_games':recent_games,
@@ -243,8 +233,17 @@ def game_finder_data(request):
             'game_type_links':game_type_links,
            }
 
+
 def game_finder(request):
     """
     Provide a list of recent games with an advanced filter.
     """
     return game_finder_data(request)
+
+
+def game_finder_json(request):
+    """
+    Provide a list of recent games in JSON format.
+    """
+    data = game_finder_data(request)
+    return [rg.to_dict() for rg in data["recent_games"]]