]> git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/views/game.py
Remove more refs to sqlahelper.
[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     data = _game_info_data(request)
125
126     # convert pwstats into a more JSON-friendly format
127     pwstats = {}
128     for pgstat_id, pwstat_list in data["pwstats"].items():
129         l = []
130         for pwstat in pwstat_list:
131             l.append({
132                 "player_game_stat_id": pgstat_id,
133                 "weapon_cd": pwstat[1],
134                 "actual": pwstat[2],
135                 "max": pwstat[3],
136                 "hit": pwstat[4],
137                 "fired": pwstat[5],
138                 "frags": pwstat[6],
139             })
140
141         pwstats[int(pgstat_id)] = l
142
143     return {
144         "game": data["game"].to_dict(),
145         "server": data["server"].to_dict(),
146         "map": data["map"].to_dict(),
147         'pgstats': [pgstat.to_dict() for pgstat in data["pgstats"]],
148         'pwstats': pwstats,
149         'tgstats': [tgstat.to_dict() for tgstat in data["tgstats"]],
150         # 'captimes': [captime.to_dict() for captime in data["captimes"]],
151     }
152
153
154 def _rank_index_data(request):
155     current_page = request.params.get("page", 1)
156
157     # game type whitelist
158     game_types_allowed = ["ca", "ctf", "dm", "duel", "ft", "ka", "tdm"]
159
160     game_type_cd = request.matchdict['game_type_cd']
161     if game_type_cd not in game_types_allowed:
162         raise httpexceptions.HTTPNotFound()
163
164     ranks_q = DBSession.query(PlayerRank).\
165             filter(PlayerRank.game_type_cd==game_type_cd).\
166             order_by(PlayerRank.rank)
167
168     game_type = DBSession.query(GameType).\
169             filter(GameType.game_type_cd == game_type_cd).one()
170
171     ranks = Page(ranks_q, current_page, url=page_url)
172
173     if len(ranks) == 0:
174         ranks = None
175
176     return {
177             'ranks':ranks,
178             'game_type_cd':game_type_cd,
179             'game_type': game_type,
180            }
181
182
183 def rank_index(request):
184     """
185     Provide a list of gametype ranks, paginated.
186     """
187     return _rank_index_data(request)
188
189
190 def rank_index_json(request):
191     """
192     Provide a list of gametype ranks, paginated. JSON.
193     """
194     return [{'status':'not implemented'}]
195
196
197 def game_finder_data(request):
198     if request.params.has_key('page'):
199         current_page = request.params['page']
200     else:
201         current_page = 1
202
203     query = {}
204
205     server_id, map_id, player_id = None, None, None
206     game_type_cd, start_game_id, end_game_id = None, None, None
207     game_type_descr = None
208
209     # these become WHERE clauses when present
210     if request.params.has_key('server_id'):
211         server_id = request.params['server_id']
212         query['server_id'] = server_id
213
214     if request.params.has_key('map_id'):
215         map_id = request.params['map_id']
216         query['map_id'] = map_id
217
218     if request.params.has_key('player_id'):
219         player_id = request.params['player_id']
220         query['player_id'] = player_id
221
222     if request.params.has_key('start_game_id'):
223         start_game_id = request.params['start_game_id']
224         query['start_game_id'] = start_game_id
225
226     if request.params.has_key('end_game_id'):
227         end_game_id = request.params['end_game_id']
228         query['end_game_id'] = end_game_id
229
230     if request.params.has_key('type'):
231         game_type_cd = request.params['type']
232         query['type'] = game_type_cd
233         try:
234             game_type_descr = DBSession.query(GameType.descr).\
235                 filter(GameType.game_type_cd == game_type_cd).\
236                 one()[0]
237         except Exception as e:
238             game_type_cd = None
239
240     rgs_q = recent_games_q(server_id=server_id, map_id=map_id,
241             player_id=player_id, game_type_cd=game_type_cd,
242             start_game_id=start_game_id, end_game_id=end_game_id)
243
244     try:
245         recent_games = [RecentGame(row) for row in rgs_q.limit(20).all()]
246
247         if len(recent_games) > 0:
248             query['start_game_id'] = recent_games[-1].game_id + 1
249
250         # build the list of links for the stripe across the top
251         game_type_links = []
252
253         # clear out the game_id window
254         gt_query = query.copy()
255         if 'start_game_id' in gt_query:
256             del gt_query['start_game_id']
257         if 'end_game_id' in gt_query:
258             del gt_query['end_game_id']
259
260         for gt in ('overall','duel','ctf','dm','tdm','ca','kh','ft',
261                 'lms','as','dom','nb','cts','rc'):
262             gt_query['type'] = gt
263             url = request.route_url("game_index", _query=gt_query)
264             game_type_links.append((gt, url))
265
266     except:
267         raise httpexceptions.HTTPBadRequest("Malformed Query")
268
269     return {
270             'recent_games':recent_games,
271             'query':query,
272             'game_type_cd':game_type_cd,
273             'game_type_links':game_type_links,
274            }
275
276
277 def game_finder(request):
278     """
279     Provide a list of recent games with an advanced filter.
280     """
281     return game_finder_data(request)
282
283
284 def game_finder_json(request):
285     """
286     Provide a list of recent games in JSON format.
287     """
288     data = game_finder_data(request)
289     return [rg.to_dict() for rg in data["recent_games"]]