Highlight the filtered game mode.
[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 = 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         # top captimes
116         captimes_raw = DBSession.query(Player.player_id, Player.nick,
117             PlayerCaptime.fastest_cap, PlayerCaptime.game_id).\
118                 filter(PlayerCaptime.map_id == map_id).\
119                 filter(Player.player_id == PlayerCaptime.player_id).\
120                 order_by(PlayerCaptime.fastest_cap).\
121                 limit(25).\
122                 all()
123
124         captimes = [Captime(c.player_id, html_colors(c.nick),
125             c.fastest_cap, c.game_id) for c in captimes_raw]
126
127     except Exception as e:
128         gmap = None
129     return {'gmap':gmap,
130             'recent_games':recent_games,
131             'top_scorers':top_scorers,
132             'top_players':top_players,
133             'top_servers':top_servers,
134             'captimes':captimes,
135             }
136
137
138 def map_info(request):
139     """
140     List the information stored about a given map.
141     """
142     mapinfo_data =  _map_info_data(request)
143
144     # FIXME: code clone, should get these from _map_info_data
145     leaderboard_count = 10
146     recent_games_count = 20
147
148     for i in range(leaderboard_count-len(mapinfo_data['top_scorers'])):
149         mapinfo_data['top_scorers'].append(('-', '-', '-'))
150
151     for i in range(leaderboard_count-len(mapinfo_data['top_players'])):
152         mapinfo_data['top_players'].append(('-', '-', '-'))
153
154     for i in range(leaderboard_count-len(mapinfo_data['top_servers'])):
155         mapinfo_data['top_servers'].append(('-', '-', '-'))
156
157     return mapinfo_data
158
159
160 def map_info_json(request):
161     """
162     List the information stored about a given map. JSON.
163     """
164     return [{'status':'not implemented'}]
165
166
167 def map_captimes_data(request):
168     map_id = int(request.matchdict['id'])
169
170     MapCaptimes = namedtuple('PlayerCaptimes', ['fastest_cap', 'create_dt', 'create_dt_epoch', 'create_dt_fuzzy',
171         'player_id', 'player_nick', 'player_nick_stripped', 'player_nick_html',
172         'game_id', 'server_id', 'server_name'])
173
174     dbquery = DBSession.query('fastest_cap', 'create_dt', 'player_id', 'game_id',
175                 'server_id', 'server_name', 'player_nick').\
176             from_statement(
177                 "SELECT ct.fastest_cap, "
178                        "ct.create_dt, "
179                        "ct.player_id, "
180                        "ct.game_id, "
181                        "g.server_id, "
182                        "s.name server_name, "
183                        "pgs.nick player_nick "
184                 "FROM   player_map_captimes ct, "
185                        "games g, "
186                        "maps m, "
187                        "servers s, "
188                        "player_game_stats pgs "
189                 "WHERE  ct.map_id = :map_id "
190                   "AND  g.game_id = ct.game_id "
191                   "AND  g.server_id = s.server_id "
192                   "AND  m.map_id = ct.map_id "
193                   "AND  pgs.player_id = ct.player_id "
194                   "AND  pgs.game_id = ct.game_id "
195                 "ORDER  BY ct.fastest_cap "
196             ).params(map_id=map_id).all()
197
198     mmap = DBSession.query(Map).filter_by(map_id=map_id).one()
199
200     map_captimes = []
201     for row in dbquery:
202         map_captimes.append(MapCaptimes(
203                 fastest_cap=row.fastest_cap,
204                 create_dt=row.create_dt,
205                 create_dt_epoch=timegm(row.create_dt.timetuple()),
206                 create_dt_fuzzy=pretty_date(row.create_dt),
207                 player_id=row.player_id,
208                 player_nick=row.player_nick,
209                 player_nick_stripped=strip_colors(row.player_nick),
210                 player_nick_html=html_colors(row.player_nick),
211                 game_id=row.game_id,
212                 server_id=row.server_id,
213                 server_name=row.server_name,
214             ))
215
216     return {
217             'captimes':map_captimes,
218             'map_id':map_id,
219             'map_url':request.route_url('map_info', id=map_id),
220             'map':mmap,
221         }
222
223 def map_captimes(request):
224     return map_captimes_data(request)
225
226 def map_captimes_json(request):
227     return map_captimes_data(request)