Reduce the number of fast caps shown on the map_info page.
[xonotic/xonstat.git] / xonstat / views / map.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 webhelpers.paginate import Page
7 from xonstat.models import *
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 def _map_index_data(request):
14     if request.params.has_key('page'):
15         current_page = request.params['page']
16     else:
17         current_page = 1
18
19     try:
20         map_q = DBSession.query(Map).\
21                 order_by(Map.map_id.desc())
22
23         maps = Page(map_q, current_page, items_per_page=25, url=page_url)
24
25     except Exception as e:
26         maps = None
27
28     return {'maps':maps, }
29
30
31 def map_index(request):
32     """
33     Provides a list of all the current maps.
34     """
35     return _map_index_data(request)
36
37
38 def map_index_json(request):
39     """
40     Provides a JSON-serialized list of all the current maps.
41     """
42     view_data = _map_index_data(request)
43
44     maps = [m.to_dict() for m in view_data['maps']]
45
46     return maps
47
48
49 def _map_info_data(request):
50     map_id = int(request.matchdict['id'])
51
52     try:
53         leaderboard_lifetime = int(
54                 request.registry.settings['xonstat.leaderboard_lifetime'])
55     except:
56         leaderboard_lifetime = 30
57
58     leaderboard_count = 10
59     recent_games_count = 20
60
61     # captime tuples
62     Captime = namedtuple('Captime', ['player_id', 'nick_html_colors',
63         'fastest_cap', 'game_id'])
64
65     try:
66         gmap = DBSession.query(Map).filter_by(map_id=map_id).one()
67
68         # recent games played in descending order
69         rgs = recent_games_q(map_id=map_id).limit(recent_games_count).all()
70         recent_games = [RecentGame(row) for row in rgs]
71
72         # top players by score
73         top_scorers = DBSession.query(Player.player_id, Player.nick,
74                 func.sum(PlayerGameStat.score)).\
75                 filter(Player.player_id == PlayerGameStat.player_id).\
76                 filter(Game.game_id == PlayerGameStat.game_id).\
77                 filter(Game.map_id == map_id).\
78                 filter(Player.player_id > 2).\
79                 filter(PlayerGameStat.create_dt >
80                         (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
81                 order_by(expr.desc(func.sum(PlayerGameStat.score))).\
82                 group_by(Player.nick).\
83                 group_by(Player.player_id).all()[0:leaderboard_count]
84
85         top_scorers = [(player_id, html_colors(nick), score) \
86                 for (player_id, nick, score) in top_scorers]
87
88         # top players by playing time
89         top_players = DBSession.query(Player.player_id, Player.nick,
90                 func.sum(PlayerGameStat.alivetime)).\
91                 filter(Player.player_id == PlayerGameStat.player_id).\
92                 filter(Game.game_id == PlayerGameStat.game_id).\
93                 filter(Game.map_id == map_id).\
94                 filter(Player.player_id > 2).\
95                 filter(PlayerGameStat.create_dt >
96                         (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
97                 order_by(expr.desc(func.sum(PlayerGameStat.alivetime))).\
98                 group_by(Player.nick).\
99                 group_by(Player.player_id).all()[0:leaderboard_count]
100
101         top_players = [(player_id, html_colors(nick), score) \
102                 for (player_id, nick, score) in top_players]
103
104         # top servers using/playing this map
105         top_servers = DBSession.query(Server.server_id, Server.name,
106                 func.count(Game.game_id)).\
107                 filter(Game.server_id == Server.server_id).\
108                 filter(Game.map_id == map_id).\
109                 filter(Game.create_dt >
110                         (datetime.utcnow() - timedelta(days=leaderboard_lifetime))).\
111                 order_by(expr.desc(func.count(Game.game_id))).\
112                 group_by(Server.name).\
113                 group_by(Server.server_id).all()[0:leaderboard_count]
114
115         # TODO make this a configuration parameter to be set in the settings
116         # top captimes
117         captimes_raw = DBSession.query(Player.player_id, Player.nick,
118             PlayerCaptime.fastest_cap, PlayerCaptime.game_id).\
119                 filter(PlayerCaptime.map_id == map_id).\
120                 filter(Player.player_id == PlayerCaptime.player_id).\
121                 order_by(PlayerCaptime.fastest_cap).\
122                 limit(10).\
123                 all()
124
125         captimes = [Captime(c.player_id, html_colors(c.nick),
126             c.fastest_cap, c.game_id) for c in captimes_raw]
127
128     except Exception as e:
129         gmap = None
130     return {'gmap':gmap,
131             'recent_games':recent_games,
132             'top_scorers':top_scorers,
133             'top_players':top_players,
134             'top_servers':top_servers,
135             'captimes':captimes,
136             }
137
138
139 def map_info(request):
140     """
141     List the information stored about a given map.
142     """
143     mapinfo_data =  _map_info_data(request)
144
145     # FIXME: code clone, should get these from _map_info_data
146     leaderboard_count = 10
147     recent_games_count = 20
148
149     for i in range(leaderboard_count-len(mapinfo_data['top_scorers'])):
150         mapinfo_data['top_scorers'].append(('-', '-', '-'))
151
152     for i in range(leaderboard_count-len(mapinfo_data['top_players'])):
153         mapinfo_data['top_players'].append(('-', '-', '-'))
154
155     for i in range(leaderboard_count-len(mapinfo_data['top_servers'])):
156         mapinfo_data['top_servers'].append(('-', '-', '-'))
157
158     return mapinfo_data
159
160
161 def map_info_json(request):
162     """
163     List the information stored about a given map. JSON.
164     """
165     return [{'status':'not implemented'}]
166
167
168 def map_captimes_data(request):
169     map_id = int(request.matchdict['id'])
170
171     current_page = request.params.get('page', 1)
172
173     try:
174         mmap = DBSession.query(Map).filter_by(map_id=map_id).one()
175
176         mct_q = DBSession.query(PlayerCaptime.fastest_cap, PlayerCaptime.create_dt,
177                 PlayerCaptime.player_id, PlayerCaptime.game_id,
178                 Game.server_id, Server.name.label('server_name'),
179                 PlayerGameStat.nick.label('player_nick')).\
180                 filter(PlayerCaptime.map_id==map_id).\
181                 filter(PlayerCaptime.game_id==Game.game_id).\
182                 filter(PlayerCaptime.map_id==Map.map_id).\
183                 filter(Game.server_id==Server.server_id).\
184                 filter(PlayerCaptime.player_id==PlayerGameStat.player_id).\
185                 filter(PlayerCaptime.game_id==PlayerGameStat.game_id).\
186                 order_by(expr.asc(PlayerCaptime.fastest_cap))
187
188     except Exception as e:
189         raise pyramid.httpexceptions.HTTPNotFound
190
191     map_captimes = Page(mct_q, current_page, items_per_page=20, url=page_url)
192
193     map_captimes.items = [MapCapTime(row) for row in map_captimes.items]
194
195     return {
196             'map_id':map_id,
197             'map':mmap,
198             'captimes':map_captimes,
199         }
200
201 def map_captimes(request):
202     return map_captimes_data(request)
203
204 def map_captimes_json(request):
205     current_page = request.params.get('page', 1)
206     data = map_captimes_data(request)
207
208     return {
209             "map": data["map"].to_dict(),
210             "captimes": [e.to_dict() for e in data["captimes"].items],
211             "page": current_page,
212             }