]> git.rm.cloudns.org Git - xonotic/xonstat.git/commitdiff
Convert the server info to a class-based view callable. Add a dummy JSON view.
authorAnt Zucaro <azucaro@gmail.com>
Sun, 16 Oct 2016 15:25:41 +0000 (11:25 -0400)
committerAnt Zucaro <azucaro@gmail.com>
Sun, 16 Oct 2016 15:25:41 +0000 (11:25 -0400)
xonstat/__init__.py
xonstat/views/__init__.py
xonstat/views/server.py

index 961aa3d253075fbd5f2ff28c4e0d21853fe55b13..b925989c2be691d0e948cebcf16d769f5b978ae4 100644 (file)
@@ -150,11 +150,21 @@ def main(global_config, **settings):
         accept="text/json"
     )
 
-    config.add_route("server_info",      "/server/{id:\d+}")
-    config.add_view(server_info,      route_name="server_info",      renderer="server_info.mako")
-
-    config.add_route("server_info_json", "/server/{id:\d+}.json")
-    config.add_view(server_info_json, route_name="server_info_json", renderer="jsonp")
+    config.add_route("server_info", "/server/{id:\d+}")
+    config.add_view(
+        view=ServerInfo,
+        route_name="server_info",
+        attr="html",
+        renderer="server_info.mako",
+        accept="text/html"
+    )
+    config.add_view(
+        view=ServerInfo,
+        route_name="server_info",
+        attr="json",
+        renderer="server_info.mako",
+        accept="text/json"
+    )
 
     # MAP ROUTES
     config.add_route("map_index",      "/maps")
index 56727ad3a5689765dffa46c9743aaa803f37eb0a..8720cb1a6d3c568c165033d4ec760c4ed15b3e68 100644 (file)
@@ -17,8 +17,7 @@ from xonstat.views.map    import map_info, map_index
 from xonstat.views.map    import map_info_json, map_index_json
 from xonstat.views.map    import map_captimes, map_captimes_json
 
-from xonstat.views.server import server_info, server_info_json
-from xonstat.views.server import ServerIndex
+from xonstat.views.server import ServerIndex, ServerInfo
 
 from xonstat.views.search import search_q, search
 from xonstat.views.search import search_json
index 4145c4b092e8cc4b02dd68de5c6060a4a4c0925c..b914d5d690202a0aef9ad874a648fdfae2747e38 100644 (file)
@@ -2,20 +2,26 @@ import logging
 import sqlalchemy.sql.functions as func
 import sqlalchemy.sql.expression as expr
 from datetime import datetime, timedelta
+from pyramid.httpexceptions import HTTPNotFound
 from webhelpers.paginate import Page
-from xonstat.models import *
+from xonstat.models import DBSession, Player, Server, Map, Game, PlayerGameStat
 from xonstat.util import page_url, html_colors
 from xonstat.views.helpers import RecentGame, recent_games_q
 
 log = logging.getLogger(__name__)
 
 
+# Defaults
+LEADERBOARD_LIFETIME = 30
+LEADERBOARD_COUNT = 10
+RECENT_GAMES_COUNT = 20
+
+
 class ServerIndex(object):
     """Returns a list of servers."""
 
     def __init__(self, request):
         """Common parameter parsing."""
-
         self.request = request
         self.page = request.params.get("page", 1)
         self.servers = self._data()
@@ -44,105 +50,113 @@ class ServerIndex(object):
         }
 
 
-def _server_info_data(request):
-    server_id = request.matchdict['id']
-
-    try:
-        leaderboard_lifetime = int(
-                request.registry.settings['xonstat.leaderboard_lifetime'])
-    except:
-        leaderboard_lifetime = 30
-
-    leaderboard_count = 10
-    recent_games_count = 20
-
-    try:
-        server = DBSession.query(Server).filter_by(server_id=server_id).one()
-
-        # top maps by total times played
-        top_maps = DBSession.query(Game.map_id, Map.name,
-                func.count()).\
-                filter(Map.map_id==Game.map_id).\
-                filter(Game.server_id==server.server_id).\
-                filter(Game.create_dt >
-                    (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
-                order_by(expr.desc(func.count())).\
-                group_by(Game.map_id).\
-                group_by(Map.name).all()[0:leaderboard_count]
-
-        # top players by score
-        top_scorers = DBSession.query(Player.player_id, Player.nick,
-                func.sum(PlayerGameStat.score)).\
-                filter(Player.player_id == PlayerGameStat.player_id).\
-                filter(Game.game_id == PlayerGameStat.game_id).\
-                filter(Game.server_id == server.server_id).\
-                filter(Player.player_id > 2).\
-                filter(PlayerGameStat.create_dt >
-                        (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
-                order_by(expr.desc(func.sum(PlayerGameStat.score))).\
-                group_by(Player.nick).\
-                group_by(Player.player_id).all()[0:leaderboard_count]
-
-        top_scorers = [(player_id, html_colors(nick), score) \
-                for (player_id, nick, score) in top_scorers]
-
-        # top players by playing time
-        top_players = DBSession.query(Player.player_id, Player.nick,
-                func.sum(PlayerGameStat.alivetime)).\
-                filter(Player.player_id == PlayerGameStat.player_id).\
-                filter(Game.game_id == PlayerGameStat.game_id).\
-                filter(Game.server_id == server.server_id).\
-                filter(Player.player_id > 2).\
-                filter(PlayerGameStat.create_dt >
-                        (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
-                order_by(expr.desc(func.sum(PlayerGameStat.alivetime))).\
-                group_by(Player.nick).\
-                group_by(Player.player_id).all()[0:leaderboard_count]
-
-        top_players = [(player_id, html_colors(nick), score) \
-                for (player_id, nick, score) in top_players]
-
-        # recent games played in descending order
-        rgs = recent_games_q(server_id=server_id).limit(recent_games_count).all()
-        recent_games = [RecentGame(row) for row in rgs]
-
-    except Exception as e:
-        server = None
-        recent_games = None
-        top_players = None
-        raise e
-    return {'server':server,
-            'recent_games':recent_games,
-            'top_players': top_players,
-            'top_scorers': top_scorers,
-            'top_maps': top_maps,
-            }
+class ServerInfo(object):
+    """Returns detailed information about a particular server."""
+
+    def __init__(self, request):
+        """Common parameter parsing."""
+        self.request = request
+        self.server_id = request.matchdict.get("id", None)
 
+        raw_lifetime = request.registry.settings.get('xonstat.leaderboard_lifetime',
+                                                     LEADERBOARD_LIFETIME)
+        self.lifetime = int(raw_lifetime)
 
-def server_info(request):
-    """
-    List the stored information about a given server.
-    """
-    serverinfo_data =  _server_info_data(request)
+        self.now = datetime.utcnow()
+        self.server_info = self._data()
 
-    # FIXME: code clone, should get these from _server_info_data
-    leaderboard_count = 10
-    recent_games_count = 20
+    def _top_maps(self):
+        """Top maps on this server by total times played."""
+        try:
+            top_maps = DBSession.query(Game.map_id, Map.name, func.count())\
+                .filter(Map.map_id==Game.map_id)\
+                .filter(Game.server_id==self.server_id)\
+                .filter(Game.create_dt > (self.now - timedelta(days=self.lifetime)))\
+                .group_by(Game.map_id)\
+                .group_by(Map.name) \
+                .order_by(expr.desc(func.count()))\
+                .limit(LEADERBOARD_COUNT)
+        except:
+            top_maps = None
 
-    for i in range(leaderboard_count-len(serverinfo_data['top_maps'])):
-        serverinfo_data['top_maps'].append(('-', '-', '-'))
+        return top_maps
 
-    for i in range(leaderboard_count-len(serverinfo_data['top_scorers'])):
-        serverinfo_data['top_scorers'].append(('-', '-', '-'))
+    def _top_scorers(self):
+        """Top scorers on this server by total score."""
+        try:
+            top_scorers = DBSession.query(Player.player_id, Player.nick,
+                                          func.sum(PlayerGameStat.score))\
+                .filter(Player.player_id == PlayerGameStat.player_id)\
+                .filter(Game.game_id == PlayerGameStat.game_id)\
+                .filter(Game.server_id == self.server_id)\
+                .filter(Player.player_id > 2)\
+                .filter(PlayerGameStat.create_dt >
+                        (self.now - timedelta(days=LEADERBOARD_LIFETIME)))\
+                .order_by(expr.desc(func.sum(PlayerGameStat.score)))\
+                .group_by(Player.nick)\
+                .group_by(Player.player_id)\
+                .limit(LEADERBOARD_COUNT)
+
+            # We can't call a Python function directly in our query, so we have to convert
+            # it out-of-band.
+            top_scorers = [(player_id, html_colors(nick), score)
+                           for (player_id, nick, score) in top_scorers]
+        except:
+            top_scorers = None
 
-    for i in range(leaderboard_count-len(serverinfo_data['top_players'])):
-        serverinfo_data['top_players'].append(('-', '-', '-'))
+        return top_scorers
 
-    return serverinfo_data
+    def _top_players(self):
+        """Top players on this server by total playing time."""
+        try:
+            top_players = DBSession.query(Player.player_id, Player.nick,
+                                          func.sum(PlayerGameStat.alivetime))\
+                .filter(Player.player_id == PlayerGameStat.player_id)\
+                .filter(Game.game_id == PlayerGameStat.game_id)\
+                .filter(Game.server_id == self.server_id)\
+                .filter(Player.player_id > 2)\
+                .filter(PlayerGameStat.create_dt > (self.now - timedelta(days=self.lifetime)))\
+                .order_by(expr.desc(func.sum(PlayerGameStat.alivetime)))\
+                .group_by(Player.nick)\
+                .group_by(Player.player_id)\
+                .limit(LEADERBOARD_COUNT)
+
+            # We can't call a Python function directly in our query, so we have to convert
+            # it out-of-band.
+            top_players = [(player_id, html_colors(nick), score) \
+                    for (player_id, nick, score) in top_players]
+
+        except:
+            top_players = None
 
+        return top_players
 
-def server_info_json(request):
-    """
-    List the stored information about a given server. JSON.
-    """
-    return [{'status':'not implemented'}]
+    def _data(self):
+        """Returns the data shared by all renderers."""
+        try:
+            server = DBSession.query(Server).filter_by(server_id=self.server_id).one()
+
+            top_maps = self._top_maps()
+            top_scorers = self._top_scorers()
+            top_players = self._top_players()
+
+            rgs = recent_games_q(server_id=self.server_id).limit(RECENT_GAMES_COUNT).all()
+            recent_games = [RecentGame(row) for row in rgs]
+        except:
+            raise HTTPNotFound
+
+        return {
+            'server': server,
+            'recent_games': recent_games,
+            'top_players': top_players,
+            'top_scorers': top_scorers,
+            'top_maps': top_maps,
+        }
+
+    def html(self):
+        """For rendering this data using something HTML-based."""
+        return self.server_info
+
+    def json(self):
+        """For rendering this data using JSON."""
+        return {"status":"Not implemented"}