Convert the server info to a class-based view callable. Add a dummy JSON view.
[xonotic/xonstat.git] / xonstat / views / server.py
1 import logging
2 import sqlalchemy.sql.functions as func
3 import sqlalchemy.sql.expression as expr
4 from datetime import datetime, timedelta
5 from pyramid.httpexceptions import HTTPNotFound
6 from webhelpers.paginate import Page
7 from xonstat.models import DBSession, Player, Server, Map, Game, PlayerGameStat
8 from xonstat.util import page_url, html_colors
9 from xonstat.views.helpers import RecentGame, recent_games_q
10
11 log = logging.getLogger(__name__)
12
13
14 # Defaults
15 LEADERBOARD_LIFETIME = 30
16 LEADERBOARD_COUNT = 10
17 RECENT_GAMES_COUNT = 20
18
19
20 class ServerIndex(object):
21     """Returns a list of servers."""
22
23     def __init__(self, request):
24         """Common parameter parsing."""
25         self.request = request
26         self.page = request.params.get("page", 1)
27         self.servers = self._data()
28
29     def _data(self):
30         """Returns the data shared by all renderers."""
31         try:
32             server_q = DBSession.query(Server).order_by(Server.server_id.desc())
33             servers = Page(server_q, self.page, items_per_page=25, url=page_url)
34
35         except:
36             servers = None
37
38         return servers
39
40     def html(self):
41         """For rendering this data using something HTML-based."""
42         return {
43             'servers': self.servers,
44         }
45
46     def json(self):
47         """For rendering this data using JSON."""
48         return {
49             'servers': [s.to_dict() for s in self.servers],
50         }
51
52
53 class ServerInfo(object):
54     """Returns detailed information about a particular server."""
55
56     def __init__(self, request):
57         """Common parameter parsing."""
58         self.request = request
59         self.server_id = request.matchdict.get("id", None)
60
61         raw_lifetime = request.registry.settings.get('xonstat.leaderboard_lifetime',
62                                                      LEADERBOARD_LIFETIME)
63         self.lifetime = int(raw_lifetime)
64
65         self.now = datetime.utcnow()
66         self.server_info = self._data()
67
68     def _top_maps(self):
69         """Top maps on this server by total times played."""
70         try:
71             top_maps = DBSession.query(Game.map_id, Map.name, func.count())\
72                 .filter(Map.map_id==Game.map_id)\
73                 .filter(Game.server_id==self.server_id)\
74                 .filter(Game.create_dt > (self.now - timedelta(days=self.lifetime)))\
75                 .group_by(Game.map_id)\
76                 .group_by(Map.name) \
77                 .order_by(expr.desc(func.count()))\
78                 .limit(LEADERBOARD_COUNT)
79         except:
80             top_maps = None
81
82         return top_maps
83
84     def _top_scorers(self):
85         """Top scorers on this server by total score."""
86         try:
87             top_scorers = DBSession.query(Player.player_id, Player.nick,
88                                           func.sum(PlayerGameStat.score))\
89                 .filter(Player.player_id == PlayerGameStat.player_id)\
90                 .filter(Game.game_id == PlayerGameStat.game_id)\
91                 .filter(Game.server_id == self.server_id)\
92                 .filter(Player.player_id > 2)\
93                 .filter(PlayerGameStat.create_dt >
94                         (self.now - timedelta(days=LEADERBOARD_LIFETIME)))\
95                 .order_by(expr.desc(func.sum(PlayerGameStat.score)))\
96                 .group_by(Player.nick)\
97                 .group_by(Player.player_id)\
98                 .limit(LEADERBOARD_COUNT)
99
100             # We can't call a Python function directly in our query, so we have to convert
101             # it out-of-band.
102             top_scorers = [(player_id, html_colors(nick), score)
103                            for (player_id, nick, score) in top_scorers]
104         except:
105             top_scorers = None
106
107         return top_scorers
108
109     def _top_players(self):
110         """Top players on this server by total playing time."""
111         try:
112             top_players = DBSession.query(Player.player_id, Player.nick,
113                                           func.sum(PlayerGameStat.alivetime))\
114                 .filter(Player.player_id == PlayerGameStat.player_id)\
115                 .filter(Game.game_id == PlayerGameStat.game_id)\
116                 .filter(Game.server_id == self.server_id)\
117                 .filter(Player.player_id > 2)\
118                 .filter(PlayerGameStat.create_dt > (self.now - timedelta(days=self.lifetime)))\
119                 .order_by(expr.desc(func.sum(PlayerGameStat.alivetime)))\
120                 .group_by(Player.nick)\
121                 .group_by(Player.player_id)\
122                 .limit(LEADERBOARD_COUNT)
123
124             # We can't call a Python function directly in our query, so we have to convert
125             # it out-of-band.
126             top_players = [(player_id, html_colors(nick), score) \
127                     for (player_id, nick, score) in top_players]
128
129         except:
130             top_players = None
131
132         return top_players
133
134     def _data(self):
135         """Returns the data shared by all renderers."""
136         try:
137             server = DBSession.query(Server).filter_by(server_id=self.server_id).one()
138
139             top_maps = self._top_maps()
140             top_scorers = self._top_scorers()
141             top_players = self._top_players()
142
143             rgs = recent_games_q(server_id=self.server_id).limit(RECENT_GAMES_COUNT).all()
144             recent_games = [RecentGame(row) for row in rgs]
145         except:
146             raise HTTPNotFound
147
148         return {
149             'server': server,
150             'recent_games': recent_games,
151             'top_players': top_players,
152             'top_scorers': top_scorers,
153             'top_maps': top_maps,
154         }
155
156     def html(self):
157         """For rendering this data using something HTML-based."""
158         return self.server_info
159
160     def json(self):
161         """For rendering this data using JSON."""
162         return {"status":"Not implemented"}