9cf7d91950731c05ae938d9220097030b2b4f380
[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 collections import namedtuple
5 from datetime import datetime, timedelta
6 from pyramid.httpexceptions import HTTPNotFound
7 from sqlalchemy import func as fg
8 from webhelpers.paginate import Page
9 from xonstat.models import DBSession, Player, Server, Map, Game, PlayerGameStat
10 from xonstat.util import page_url, html_colors
11 from xonstat.views.helpers import RecentGame, recent_games_q
12
13 log = logging.getLogger(__name__)
14
15
16 # Defaults
17 LEADERBOARD_LIFETIME = 30
18 LEADERBOARD_COUNT = 10
19 INDEX_COUNT = 20
20 RECENT_GAMES_COUNT = 20
21
22
23 class ServerIndex(object):
24     """Returns a list of servers."""
25
26     def __init__(self, request):
27         """Common parameter parsing."""
28         self.request = request
29         self.page = request.params.get("page", 1)
30         self.servers = self.raw()
31
32     def raw(self):
33         """Returns the raw data shared by all renderers."""
34         try:
35             server_q = DBSession.query(Server).order_by(Server.server_id.desc())
36             servers = Page(server_q, self.page, items_per_page=25, url=page_url)
37
38         except Exception as e:
39             log.debug(e)
40             raise HTTPNotFound
41
42         return servers
43
44     def html(self):
45         """For rendering this data using something HTML-based."""
46         return {
47             'servers': self.servers,
48         }
49
50     def json(self):
51         """For rendering this data using JSON."""
52         return {
53             'servers': [s.to_dict() for s in self.servers],
54         }
55
56
57 class ServerInfoBase(object):
58     """Baseline parameter parsing for Server URLs with a server_id in them."""
59
60     def __init__(self, request, limit=None, last=None):
61         """Common parameter parsing."""
62         self.request = request
63         self.server_id = request.matchdict.get("id", None)
64
65         raw_lifetime = request.registry.settings.get('xonstat.leaderboard_lifetime',
66                                                      LEADERBOARD_LIFETIME)
67         self.lifetime = int(raw_lifetime)
68
69         self.limit = request.params.get("limit", limit)
70         self.last = request.params.get("last", last)
71         self.now = datetime.utcnow()
72
73
74 class ServerTopMaps(ServerInfoBase):
75     """Returns the top maps played on a given server."""
76
77     def __init__(self, request, limit=INDEX_COUNT, last=None):
78         """Common parameter parsing."""
79         super(ServerTopMaps, self).__init__(request, limit, last)
80
81         self.top_maps = self.raw()
82
83     def raw(self):
84         """Returns the raw data shared by all renderers."""
85         try:
86             top_maps_q = DBSession.query(
87                 fg.row_number().over(order_by=expr.desc(func.count())).label("rank"),
88                 Game.map_id, Map.name, func.count().label("times_played"))\
89                 .filter(Map.map_id==Game.map_id)\
90                 .filter(Game.server_id==self.server_id)\
91                 .filter(Game.create_dt > (self.now - timedelta(days=self.lifetime)))\
92                 .group_by(Game.map_id)\
93                 .group_by(Map.name) \
94                 .order_by(expr.desc(func.count()))
95
96             if self.last:
97                 top_maps_q = top_maps_q.offset(self.last)
98
99             if self.limit:
100                 top_maps_q = top_maps_q.limit(self.limit)
101
102             top_maps = top_maps_q.all()
103         except Exception as e:
104             log.debug(e)
105             raise HTTPNotFound
106
107         return top_maps
108
109     def html(self):
110         """Returns the HTML-ready representation."""
111
112         # build the query string
113         query = {}
114         if len(self.top_maps) > 1:
115             query['last'] = self.top_maps[-1].rank
116
117         return {
118             "server_id": self.server_id,
119             "top_maps": self.top_maps,
120             "query": query,
121         }
122
123     def json(self):
124         """For rendering this data using JSON."""
125         top_maps = [{
126             "rank": tm.rank,
127             "map_id": tm.map_id,
128             "map_name": tm.name,
129             "times_played": tm.times_played,
130         } for tm in self.top_maps]
131
132         return {
133             "server_id": self.server_id,
134             "top_maps": top_maps,
135         }
136
137
138 class ServerTopScorers(ServerInfoBase):
139     """Returns the top scorers on a given server."""
140
141     def __init__(self, request, limit=INDEX_COUNT, last=None):
142         """Common parameter parsing."""
143         super(ServerTopScorers, self).__init__(request, limit, last)
144         self.top_scorers = self.raw()
145
146     def raw(self):
147         """Top scorers on this server by total score."""
148         try:
149             top_scorers_q = DBSession.query(
150                 fg.row_number().over(
151                     order_by=expr.desc(func.sum(PlayerGameStat.score))).label("rank"),
152                 Player.player_id, Player.nick,
153                 func.sum(PlayerGameStat.score).label("total_score"))\
154                 .filter(Player.player_id == PlayerGameStat.player_id)\
155                 .filter(Game.game_id == PlayerGameStat.game_id)\
156                 .filter(Game.server_id == self.server_id)\
157                 .filter(Player.player_id > 2)\
158                 .filter(PlayerGameStat.create_dt >
159                         (self.now - timedelta(days=LEADERBOARD_LIFETIME)))\
160                 .order_by(expr.desc(func.sum(PlayerGameStat.score)))\
161                 .group_by(Player.nick)\
162                 .group_by(Player.player_id)
163
164             if self.last:
165                 top_scorers_q = top_scorers_q.offset(self.last)
166
167             if self.limit:
168                 top_scorers_q = top_scorers_q.limit(self.limit)
169
170             top_scorers = top_scorers_q.all()
171
172         except Exception as e:
173             log.debug(e)
174             raise HTTPNotFound
175
176         return top_scorers
177
178     def html(self):
179         """Returns an HTML-ready representation."""
180         TopScorer = namedtuple("TopScorer", ["rank", "player_id", "nick", "total_score"])
181
182         top_scorers = [TopScorer(ts.rank, ts.player_id, html_colors(ts.nick), ts.total_score)
183                        for ts in self.top_scorers]
184
185         # build the query string
186         query = {}
187         if len(top_scorers) > 1:
188             query['last'] = top_scorers[-1].rank
189
190         return {
191             "server_id": self.server_id,
192             "top_scorers": top_scorers,
193             "query": query,
194         }
195
196     def json(self):
197         """For rendering this data using JSON."""
198         top_scorers = [{
199             "rank": ts.rank,
200             "player_id": ts.player_id,
201             "nick": ts.nick,
202             "score": ts.total_score,
203         } for ts in self.top_scorers]
204
205         return {
206             "server_id": self.server_id,
207             "top_scorers": top_scorers,
208         }
209
210
211 class ServerTopPlayers(ServerInfoBase):
212     """Returns the top players by playing time on a given server."""
213
214     def __init__(self, request, limit=INDEX_COUNT, last=None):
215         """Common parameter parsing."""
216         super(ServerTopPlayers, self).__init__(request, limit, last)
217         self.top_players = self.raw()
218
219     def raw(self):
220         """Top players on this server by total playing time."""
221         try:
222             top_players_q = DBSession.query(
223                 fg.row_number().over(
224                     order_by=expr.desc(func.sum(PlayerGameStat.alivetime))).label("rank"),
225                 Player.player_id, Player.nick,
226                 func.sum(PlayerGameStat.alivetime).label("alivetime"))\
227                 .filter(Player.player_id == PlayerGameStat.player_id)\
228                 .filter(Game.game_id == PlayerGameStat.game_id)\
229                 .filter(Game.server_id == self.server_id)\
230                 .filter(Player.player_id > 2)\
231                 .filter(PlayerGameStat.create_dt > (self.now - timedelta(days=self.lifetime)))\
232                 .order_by(expr.desc(func.sum(PlayerGameStat.alivetime)))\
233                 .group_by(Player.nick)\
234                 .group_by(Player.player_id)
235
236             if self.last:
237                 top_players_q = top_players_q.offset(self.last)
238
239             if self.limit:
240                 top_players_q = top_players_q.limit(self.limit)
241
242             top_players = top_players_q.all()
243
244         except Exception as e:
245             log.debug(e)
246             raise HTTPNotFound
247
248         return top_players
249
250     def html(self):
251         """Returns the HTML-ready representation."""
252         TopPlayer = namedtuple("TopPlayer", ["rank", "player_id", "nick", "alivetime"])
253
254         top_players = [TopPlayer(tp.rank, tp.player_id, html_colors(tp.nick), tp.alivetime)
255                        for tp in self.top_players]
256
257         # build the query string
258         query = {}
259         if len(top_players) > 1:
260             query['last'] = top_players[-1].rank
261
262         return {
263             "server_id": self.server_id,
264             "top_players": top_players,
265             "query": query,
266         }
267
268     def json(self):
269         """For rendering this data using JSON."""
270         top_players = [{
271             "rank": ts.rank,
272             "player_id": ts.player_id,
273             "nick": ts.nick,
274             "time": ts.alivetime.total_seconds(),
275         } for ts in self.top_players]
276
277         return {
278             "server_id": self.server_id,
279             "top_players": top_players,
280         }
281
282
283 class ServerInfo(ServerInfoBase):
284     """Returns detailed information about a particular server."""
285
286     def __init__(self, request):
287         """Common data and parameters."""
288         super(ServerInfo, self).__init__(request)
289
290         # this view uses data from other views, so we'll save the data at that level
291         try:
292             self.server = DBSession.query(Server).filter_by(server_id=self.server_id).one()
293             self.top_maps_v = ServerTopMaps(self.request, limit=LEADERBOARD_COUNT)
294             self.top_scorers_v = ServerTopScorers(self.request, limit=LEADERBOARD_COUNT)
295             self.top_players_v = ServerTopPlayers(self.request, limit=LEADERBOARD_COUNT)
296
297             rgs = recent_games_q(server_id=self.server_id).limit(RECENT_GAMES_COUNT).all()
298             self.recent_games = [RecentGame(row) for row in rgs]
299         except:
300             raise HTTPNotFound
301
302     def raw(self):
303         """Returns the raw data shared by all renderers."""
304         return {
305             'server': self.server,
306             'top_players': self.top_players_v.top_players,
307             'top_scorers': self.top_scorers_v.top_scorers,
308             'top_maps': self.top_maps_v.top_maps,
309             'recent_games': self.recent_games,
310         }
311
312     def html(self):
313         """For rendering this data using something HTML-based."""
314         return {
315             'server': self.server,
316             'top_players': self.top_players_v.html()["top_players"],
317             'top_scorers': self.top_scorers_v.html()["top_scorers"],
318             'top_maps': self.top_maps_v.html()["top_maps"],
319             'recent_games': self.recent_games,
320             'lifetime': self.lifetime,
321         }
322
323     def json(self):
324         """For rendering this data using JSON."""
325         return {
326             'server': self.server.to_dict(),
327             'top_players': self.top_players_v.json(),
328             'top_scorers': self.top_scorers_v.json(),
329             'top_maps': self.top_maps_v.json(),
330             'recent_games': [rg.to_dict() for rg in self.recent_games],
331         }