Add lifetime value to all server top* HTML views.
[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             "lifetime": self.lifetime,
121             "query": query,
122         }
123
124     def json(self):
125         """For rendering this data using JSON."""
126         top_maps = [{
127             "rank": tm.rank,
128             "map_id": tm.map_id,
129             "map_name": tm.name,
130             "times_played": tm.times_played,
131         } for tm in self.top_maps]
132
133         return {
134             "server_id": self.server_id,
135             "top_maps": top_maps,
136         }
137
138
139 class ServerTopScorers(ServerInfoBase):
140     """Returns the top scorers on a given server."""
141
142     def __init__(self, request, limit=INDEX_COUNT, last=None):
143         """Common parameter parsing."""
144         super(ServerTopScorers, self).__init__(request, limit, last)
145         self.top_scorers = self.raw()
146
147     def raw(self):
148         """Top scorers on this server by total score."""
149         try:
150             top_scorers_q = DBSession.query(
151                 fg.row_number().over(
152                     order_by=expr.desc(func.sum(PlayerGameStat.score))).label("rank"),
153                 Player.player_id, Player.nick,
154                 func.sum(PlayerGameStat.score).label("total_score"))\
155                 .filter(Player.player_id == PlayerGameStat.player_id)\
156                 .filter(Game.game_id == PlayerGameStat.game_id)\
157                 .filter(Game.server_id == self.server_id)\
158                 .filter(Player.player_id > 2)\
159                 .filter(PlayerGameStat.create_dt >
160                         (self.now - timedelta(days=LEADERBOARD_LIFETIME)))\
161                 .order_by(expr.desc(func.sum(PlayerGameStat.score)))\
162                 .group_by(Player.nick)\
163                 .group_by(Player.player_id)
164
165             if self.last:
166                 top_scorers_q = top_scorers_q.offset(self.last)
167
168             if self.limit:
169                 top_scorers_q = top_scorers_q.limit(self.limit)
170
171             top_scorers = top_scorers_q.all()
172
173         except Exception as e:
174             log.debug(e)
175             raise HTTPNotFound
176
177         return top_scorers
178
179     def html(self):
180         """Returns an HTML-ready representation."""
181         TopScorer = namedtuple("TopScorer", ["rank", "player_id", "nick", "total_score"])
182
183         top_scorers = [TopScorer(ts.rank, ts.player_id, html_colors(ts.nick), ts.total_score)
184                        for ts in self.top_scorers]
185
186         # build the query string
187         query = {}
188         if len(top_scorers) > 1:
189             query['last'] = top_scorers[-1].rank
190
191         return {
192             "server_id": self.server_id,
193             "top_scorers": top_scorers,
194             "lifetime": self.lifetime,
195             "query": query,
196         }
197
198     def json(self):
199         """For rendering this data using JSON."""
200         top_scorers = [{
201             "rank": ts.rank,
202             "player_id": ts.player_id,
203             "nick": ts.nick,
204             "score": ts.total_score,
205         } for ts in self.top_scorers]
206
207         return {
208             "server_id": self.server_id,
209             "top_scorers": top_scorers,
210         }
211
212
213 class ServerTopPlayers(ServerInfoBase):
214     """Returns the top players by playing time on a given server."""
215
216     def __init__(self, request, limit=INDEX_COUNT, last=None):
217         """Common parameter parsing."""
218         super(ServerTopPlayers, self).__init__(request, limit, last)
219         self.top_players = self.raw()
220
221     def raw(self):
222         """Top players on this server by total playing time."""
223         try:
224             top_players_q = DBSession.query(
225                 fg.row_number().over(
226                     order_by=expr.desc(func.sum(PlayerGameStat.alivetime))).label("rank"),
227                 Player.player_id, Player.nick,
228                 func.sum(PlayerGameStat.alivetime).label("alivetime"))\
229                 .filter(Player.player_id == PlayerGameStat.player_id)\
230                 .filter(Game.game_id == PlayerGameStat.game_id)\
231                 .filter(Game.server_id == self.server_id)\
232                 .filter(Player.player_id > 2)\
233                 .filter(PlayerGameStat.create_dt > (self.now - timedelta(days=self.lifetime)))\
234                 .order_by(expr.desc(func.sum(PlayerGameStat.alivetime)))\
235                 .group_by(Player.nick)\
236                 .group_by(Player.player_id)
237
238             if self.last:
239                 top_players_q = top_players_q.offset(self.last)
240
241             if self.limit:
242                 top_players_q = top_players_q.limit(self.limit)
243
244             top_players = top_players_q.all()
245
246         except Exception as e:
247             log.debug(e)
248             raise HTTPNotFound
249
250         return top_players
251
252     def html(self):
253         """Returns the HTML-ready representation."""
254         TopPlayer = namedtuple("TopPlayer", ["rank", "player_id", "nick", "alivetime"])
255
256         top_players = [TopPlayer(tp.rank, tp.player_id, html_colors(tp.nick), tp.alivetime)
257                        for tp in self.top_players]
258
259         # build the query string
260         query = {}
261         if len(top_players) > 1:
262             query['last'] = top_players[-1].rank
263
264         return {
265             "server_id": self.server_id,
266             "top_players": top_players,
267             "lifetime": self.lifetime,
268             "query": query,
269         }
270
271     def json(self):
272         """For rendering this data using JSON."""
273         top_players = [{
274             "rank": ts.rank,
275             "player_id": ts.player_id,
276             "nick": ts.nick,
277             "time": ts.alivetime.total_seconds(),
278         } for ts in self.top_players]
279
280         return {
281             "server_id": self.server_id,
282             "top_players": top_players,
283         }
284
285
286 class ServerInfo(ServerInfoBase):
287     """Returns detailed information about a particular server."""
288
289     def __init__(self, request):
290         """Common data and parameters."""
291         super(ServerInfo, self).__init__(request)
292
293         # this view uses data from other views, so we'll save the data at that level
294         try:
295             self.server = DBSession.query(Server).filter_by(server_id=self.server_id).one()
296             self.top_maps_v = ServerTopMaps(self.request, limit=LEADERBOARD_COUNT)
297             self.top_scorers_v = ServerTopScorers(self.request, limit=LEADERBOARD_COUNT)
298             self.top_players_v = ServerTopPlayers(self.request, limit=LEADERBOARD_COUNT)
299
300             rgs = recent_games_q(server_id=self.server_id).limit(RECENT_GAMES_COUNT).all()
301             self.recent_games = [RecentGame(row) for row in rgs]
302         except:
303             raise HTTPNotFound
304
305     def raw(self):
306         """Returns the raw data shared by all renderers."""
307         return {
308             'server': self.server,
309             'top_players': self.top_players_v.top_players,
310             'top_scorers': self.top_scorers_v.top_scorers,
311             'top_maps': self.top_maps_v.top_maps,
312             'recent_games': self.recent_games,
313         }
314
315     def html(self):
316         """For rendering this data using something HTML-based."""
317         return {
318             'server': self.server,
319             'top_players': self.top_players_v.html()["top_players"],
320             'top_scorers': self.top_scorers_v.html()["top_scorers"],
321             'top_maps': self.top_maps_v.html()["top_maps"],
322             'recent_games': self.recent_games,
323             'lifetime': self.lifetime,
324         }
325
326     def json(self):
327         """For rendering this data using JSON."""
328         return {
329             'server': self.server.to_dict(),
330             'top_players': self.top_players_v.json(),
331             'top_scorers': self.top_scorers_v.json(),
332             'top_maps': self.top_maps_v.json(),
333             'recent_games': [rg.to_dict() for rg in self.recent_games],
334         }