2 from collections import OrderedDict
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
12 log = logging.getLogger(__name__)
15 def _game_info_data(request):
16 game_id = int(request.matchdict['id'])
18 # show an extra column if "show_elo" is a GET parameter
19 show_elo = bool(request.params.get("show_elo", False))
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)\
29 pgstats = DBSession.query(PlayerGameStat)\
30 .filter(PlayerGameStat.game_id == game_id)\
31 .order_by(PlayerGameStat.scoreboardpos)\
32 .order_by(PlayerGameStat.score)\
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.
38 for pgstat in pgstats:
39 if pgstat.avg_latency is not None:
43 q = DBSession.query(TeamGameStat).filter(TeamGameStat.game_id == game_id)
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())
50 q = q.order_by(TeamGameStat.score.desc())
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)
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)
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())\
73 if pwstat.player_game_stat_id not in pwstats:
74 pwstats[pwstat.player_game_stat_id] = []
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))
80 frag_matrix = DBSession.query(PlayerGameFragMatrix)\
81 .filter(PlayerGameFragMatrix.game_id == game_id)\
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
88 show_frag_matrix = False
90 except NoResultFound as e:
91 raise httpexceptions.HTTPNotFound("Could not find that game!")
93 except Exception as e:
100 'gametype': gametype,
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,
113 def game_info(request):
115 List the game stats (scoreboard) for a particular game. Paginated.
117 return _game_info_data(request)
120 def game_info_json(request):
122 List the game stats (scoreboard) for a particular game. Paginated. JSON.
124 data = _game_info_data(request)
126 # convert pwstats into a more JSON-friendly format
128 for pgstat_id, pwstat_list in data["pwstats"].items():
130 for pwstat in pwstat_list:
132 "player_game_stat_id": pgstat_id,
133 "weapon_cd": pwstat[1],
141 pwstats[int(pgstat_id)] = l
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"]],
149 'tgstats': [tgstat.to_dict() for tgstat in data["tgstats"]],
150 # 'captimes': [captime.to_dict() for captime in data["captimes"]],
154 def _rank_index_data(request):
155 current_page = request.params.get("page", 1)
157 # game type whitelist
158 game_types_allowed = ["ca", "ctf", "dm", "duel", "ft", "ka", "tdm"]
160 game_type_cd = request.matchdict['game_type_cd']
161 if game_type_cd not in game_types_allowed:
162 raise httpexceptions.HTTPNotFound()
164 ranks_q = DBSession.query(PlayerRank).\
165 filter(PlayerRank.game_type_cd==game_type_cd).\
166 order_by(PlayerRank.rank)
168 game_type = DBSession.query(GameType).\
169 filter(GameType.game_type_cd == game_type_cd).one()
171 ranks = Page(ranks_q, current_page, url=page_url)
178 'game_type_cd':game_type_cd,
179 'game_type': game_type,
183 def rank_index(request):
185 Provide a list of gametype ranks, paginated.
187 return _rank_index_data(request)
190 def rank_index_json(request):
192 Provide a list of gametype ranks, paginated. JSON.
194 return [{'status':'not implemented'}]
197 def game_finder_data(request):
198 if request.params.has_key('page'):
199 current_page = request.params['page']
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
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
214 if request.params.has_key('map_id'):
215 map_id = request.params['map_id']
216 query['map_id'] = map_id
218 if request.params.has_key('player_id'):
219 player_id = request.params['player_id']
220 query['player_id'] = player_id
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
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
230 if request.params.has_key('type'):
231 game_type_cd = request.params['type']
232 query['type'] = game_type_cd
234 game_type_descr = DBSession.query(GameType.descr).\
235 filter(GameType.game_type_cd == game_type_cd).\
237 except Exception as e:
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)
245 recent_games = [RecentGame(row) for row in rgs_q.limit(20).all()]
247 if len(recent_games) > 0:
248 query['start_game_id'] = recent_games[-1].game_id + 1
250 # build the list of links for the stripe across the top
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']
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))
267 raise httpexceptions.HTTPBadRequest("Malformed Query")
270 'recent_games':recent_games,
272 'game_type_cd':game_type_cd,
273 'game_type_links':game_type_links,
277 def game_finder(request):
279 Provide a list of recent games with an advanced filter.
281 return game_finder_data(request)
284 def game_finder_json(request):
286 Provide a list of recent games in JSON format.
288 data = game_finder_data(request)
289 return [rg.to_dict() for rg in data["recent_games"]]