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