Initial display of the frag matrix.
[xonotic/xonstat.git] / xonstat / views / game.py
1 import logging
2 from collections import OrderedDict
3
4 from pyramid import httpexceptions
5 from sqlalchemy.orm.exc import *
6 from webhelpers.paginate import Page
7 from xonstat.models import DBSession, Server, Map, Game, PlayerGameStat, PlayerWeaponStat
8 from xonstat.models import PlayerGameFragMatrix, TeamGameStat, PlayerRank, GameType, Weapon
9 from xonstat.util import page_url
10 from xonstat.views.helpers import RecentGame, recent_games_q
11
12 log = logging.getLogger(__name__)
13
14
15 def _game_info_data(request):
16     game_id = int(request.matchdict['id'])
17
18     # show an extra column if "show_elo" is a GET parameter
19     show_elo = bool(request.params.get("show_elo", False))
20
21     try:
22         (game, server, map, gametype) = DBSession.query(Game, Server, Map, GameType)\
23             .filter(Game.game_id == game_id)\
24             .filter(Game.server_id == Server.server_id)\
25             .filter(Game.map_id == Map.map_id)\
26             .filter(Game.game_type_cd == GameType.game_type_cd)\
27             .one()
28
29         pgstats = DBSession.query(PlayerGameStat)\
30             .filter(PlayerGameStat.game_id == game_id)\
31             .order_by(PlayerGameStat.scoreboardpos)\
32             .order_by(PlayerGameStat.score)\
33             .all()
34
35         # Really old games don't have latency sent, so we have to check. If at
36         # least one player has a latency value, we'll show the ping column.
37         show_latency = False
38         for pgstat in pgstats:
39             if pgstat.avg_latency is not None:
40                 show_latency = True
41                 break
42
43         q = DBSession.query(TeamGameStat).filter(TeamGameStat.game_id == game_id)
44
45         if game.game_type_cd == 'ctf':
46             q = q.order_by(TeamGameStat.caps.desc())
47         elif game.game_type_cd == 'ca':
48             q = q.order_by(TeamGameStat.rounds.desc())
49
50         q = q.order_by(TeamGameStat.score.desc())
51
52         tgstats = q.all()
53
54         stats_by_team = OrderedDict()
55         for pgstat in pgstats:
56             if pgstat.team not in stats_by_team.keys():
57                 stats_by_team[pgstat.team] = []
58             stats_by_team[pgstat.team].append(pgstat)
59
60         captimes = []
61         if game.game_type_cd == 'ctf':
62             for pgstat in pgstats:
63                 if pgstat.fastest is not None:
64                     captimes.append(pgstat)
65             captimes = sorted(captimes, key=lambda x:x.fastest)
66
67         pwstats = {}
68         for (pwstat, weapon) in DBSession.query(PlayerWeaponStat, Weapon)\
69                 .filter(PlayerWeaponStat.game_id == game_id)\
70                 .filter(PlayerWeaponStat.weapon_cd == Weapon.weapon_cd)\
71                 .order_by(PlayerWeaponStat.actual.desc())\
72                 .all():
73                     if pwstat.player_game_stat_id not in pwstats:
74                         pwstats[pwstat.player_game_stat_id] = []
75
76                     pwstats[pwstat.player_game_stat_id].append((weapon.descr,
77                         weapon.weapon_cd, pwstat.actual, pwstat.max,
78                         pwstat.hit, pwstat.fired, pwstat.frags))
79
80         frag_matrix = DBSession.query(PlayerGameFragMatrix)\
81             .filter(PlayerGameFragMatrix.game_id == game_id)\
82             .all()
83
84         matrix_by_pgstat_id = {e.player_game_stat_id: e for e in frag_matrix}
85         if len(matrix_by_pgstat_id):
86             show_frag_matrix = True
87         else:
88             show_frag_matrix = False
89
90     except NoResultFound as e:
91         raise httpexceptions.HTTPNotFound("Could not find that game!")
92
93     except Exception as e:
94         raise e
95
96     return {
97         'game': game,
98         'server': server,
99         'map': map,
100         'gametype': gametype,
101         'pgstats': pgstats,
102         'tgstats': tgstats,
103         'pwstats': pwstats,
104         'captimes': captimes,
105         'show_elo': show_elo,
106         'show_latency': show_latency,
107         'stats_by_team': stats_by_team,
108         'show_frag_matrix': show_frag_matrix,
109         'matrix_by_pgstat_id': matrix_by_pgstat_id,
110     }
111
112
113 def game_info(request):
114     """
115     List the game stats (scoreboard) for a particular game. Paginated.
116     """
117     return _game_info_data(request)
118
119
120 def game_info_json(request):
121     """
122     List the game stats (scoreboard) for a particular game. Paginated. JSON.
123     """
124     return [{'status':'not implemented'}]
125
126
127 def _rank_index_data(request):
128     current_page = request.params.get("page", 1)
129
130     # game type whitelist
131     game_types_allowed = ["ca", "ctf", "dm", "duel", "ft", "ka", "tdm"]
132
133     game_type_cd = request.matchdict['game_type_cd']
134     if game_type_cd not in game_types_allowed:
135         raise httpexceptions.HTTPNotFound()
136
137     ranks_q = DBSession.query(PlayerRank).\
138             filter(PlayerRank.game_type_cd==game_type_cd).\
139             order_by(PlayerRank.rank)
140
141     game_type = DBSession.query(GameType).\
142             filter(GameType.game_type_cd == game_type_cd).one()
143
144     ranks = Page(ranks_q, current_page, url=page_url)
145
146     if len(ranks) == 0:
147         ranks = None
148
149     return {
150             'ranks':ranks,
151             'game_type_cd':game_type_cd,
152             'game_type': game_type,
153            }
154
155
156 def rank_index(request):
157     """
158     Provide a list of gametype ranks, paginated.
159     """
160     return _rank_index_data(request)
161
162
163 def rank_index_json(request):
164     """
165     Provide a list of gametype ranks, paginated. JSON.
166     """
167     return [{'status':'not implemented'}]
168
169
170 def game_finder_data(request):
171     if request.params.has_key('page'):
172         current_page = request.params['page']
173     else:
174         current_page = 1
175
176     query = {}
177
178     server_id, map_id, player_id = None, None, None
179     game_type_cd, start_game_id, end_game_id = None, None, None
180     game_type_descr = None
181
182     # these become WHERE clauses when present
183     if request.params.has_key('server_id'):
184         server_id = request.params['server_id']
185         query['server_id'] = server_id
186
187     if request.params.has_key('map_id'):
188         map_id = request.params['map_id']
189         query['map_id'] = map_id
190
191     if request.params.has_key('player_id'):
192         player_id = request.params['player_id']
193         query['player_id'] = player_id
194
195     if request.params.has_key('start_game_id'):
196         start_game_id = request.params['start_game_id']
197         query['start_game_id'] = start_game_id
198
199     if request.params.has_key('end_game_id'):
200         end_game_id = request.params['end_game_id']
201         query['end_game_id'] = end_game_id
202
203     if request.params.has_key('type'):
204         game_type_cd = request.params['type']
205         query['type'] = game_type_cd
206         try:
207             game_type_descr = DBSession.query(GameType.descr).\
208                 filter(GameType.game_type_cd == game_type_cd).\
209                 one()[0]
210         except Exception as e:
211             game_type_cd = None
212
213     rgs_q = recent_games_q(server_id=server_id, map_id=map_id,
214             player_id=player_id, game_type_cd=game_type_cd,
215             start_game_id=start_game_id, end_game_id=end_game_id)
216
217     try:
218         recent_games = [RecentGame(row) for row in rgs_q.limit(20).all()]
219         
220         if len(recent_games) > 0:
221             query['start_game_id'] = recent_games[-1].game_id + 1
222
223         # build the list of links for the stripe across the top
224         game_type_links = []
225
226         # clear out the game_id window
227         gt_query = query.copy()
228         if 'start_game_id' in gt_query:
229             del gt_query['start_game_id']
230         if 'end_game_id' in gt_query:
231             del gt_query['end_game_id']
232
233         for gt in ('overall','duel','ctf','dm','tdm','ca','kh','ft',
234                 'lms','as','dom','nb','cts','rc'):
235             gt_query['type'] = gt
236             url = request.route_url("game_index", _query=gt_query)
237             game_type_links.append((gt, url))
238
239     except:
240         raise httpexceptions.HTTPBadRequest("Malformed Query")
241
242     return {
243             'recent_games':recent_games,
244             'query':query,
245             'game_type_cd':game_type_cd,
246             'game_type_links':game_type_links,
247            }
248
249
250 def game_finder(request):
251     """
252     Provide a list of recent games with an advanced filter.
253     """
254     return game_finder_data(request)
255
256
257 def game_finder_json(request):
258     """
259     Provide a list of recent games in JSON format.
260     """
261     data = game_finder_data(request)
262     return [rg.to_dict() for rg in data["recent_games"]]