Add separate views for the top servers on a map.
[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 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).one()
27
28         pgstats = DBSession.query(PlayerGameStat).\
29                 filter(PlayerGameStat.game_id == game_id).\
30                 order_by(PlayerGameStat.scoreboardpos).\
31                 order_by(PlayerGameStat.score).\
32                 all()
33
34         # Really old games don't have latency sent, so we have to check. If at
35         # least one player has a latency value, we'll show the ping column.
36         show_latency = False
37         for pgstat in pgstats:
38             if pgstat.avg_latency is not None:
39                 show_latency = True
40                 break
41
42         q = DBSession.query(TeamGameStat).\
43                 filter(TeamGameStat.game_id == game_id)
44         if game.game_type_cd == 'ctf':
45             q = q.order_by(TeamGameStat.caps.desc())
46         elif game.game_type_cd == 'ca':
47             q = q.order_by(TeamGameStat.rounds.desc())
48         # dom -> ticks, rc -> laps, nb -> goals, as -> objectives
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     except NoResultFound as e:
81         raise httpexceptions.HTTPNotFound("Could not find that game!")
82
83     except Exception as e:
84         raise e
85
86     return {'game':game,
87             'server':server,
88             'map':map,
89             'gametype':gametype,
90             'pgstats':pgstats,
91             'tgstats':tgstats,
92             'pwstats':pwstats,
93             'captimes':captimes,
94             'show_elo':show_elo,
95             'show_latency':show_latency,
96             'stats_by_team':stats_by_team,
97             }
98
99
100 def game_info(request):
101     """
102     List the game stats (scoreboard) for a particular game. Paginated.
103     """
104     return _game_info_data(request)
105
106
107 def game_info_json(request):
108     """
109     List the game stats (scoreboard) for a particular game. Paginated. JSON.
110     """
111     return [{'status':'not implemented'}]
112
113
114 def _rank_index_data(request):
115     current_page = request.params.get("page", 1)
116
117     # game type whitelist
118     game_types_allowed = ["ca", "ctf", "dm", "duel", "ft", "ka", "tdm"]
119
120     game_type_cd = request.matchdict['game_type_cd']
121     if game_type_cd not in game_types_allowed:
122         raise httpexceptions.HTTPNotFound()
123
124     ranks_q = DBSession.query(PlayerRank).\
125             filter(PlayerRank.game_type_cd==game_type_cd).\
126             order_by(PlayerRank.rank)
127
128     game_type = DBSession.query(GameType).\
129             filter(GameType.game_type_cd == game_type_cd).one()
130
131     ranks = Page(ranks_q, current_page, url=page_url)
132
133     if len(ranks) == 0:
134         ranks = None
135
136     return {
137             'ranks':ranks,
138             'game_type_cd':game_type_cd,
139             'game_type': game_type,
140            }
141
142
143 def rank_index(request):
144     """
145     Provide a list of gametype ranks, paginated.
146     """
147     return _rank_index_data(request)
148
149
150 def rank_index_json(request):
151     """
152     Provide a list of gametype ranks, paginated. JSON.
153     """
154     return [{'status':'not implemented'}]
155
156
157 def game_finder_data(request):
158     if request.params.has_key('page'):
159         current_page = request.params['page']
160     else:
161         current_page = 1
162
163     query = {}
164
165     server_id, map_id, player_id = None, None, None
166     game_type_cd, start_game_id, end_game_id = None, None, None
167     game_type_descr = None
168
169     # these become WHERE clauses when present
170     if request.params.has_key('server_id'):
171         server_id = request.params['server_id']
172         query['server_id'] = server_id
173
174     if request.params.has_key('map_id'):
175         map_id = request.params['map_id']
176         query['map_id'] = map_id
177
178     if request.params.has_key('player_id'):
179         player_id = request.params['player_id']
180         query['player_id'] = player_id
181
182     if request.params.has_key('start_game_id'):
183         start_game_id = request.params['start_game_id']
184         query['start_game_id'] = start_game_id
185
186     if request.params.has_key('end_game_id'):
187         end_game_id = request.params['end_game_id']
188         query['end_game_id'] = end_game_id
189
190     if request.params.has_key('type'):
191         game_type_cd = request.params['type']
192         query['type'] = game_type_cd
193         try:
194             game_type_descr = DBSession.query(GameType.descr).\
195                 filter(GameType.game_type_cd == game_type_cd).\
196                 one()[0]
197         except Exception as e:
198             game_type_cd = None
199
200     rgs_q = recent_games_q(server_id=server_id, map_id=map_id,
201             player_id=player_id, game_type_cd=game_type_cd,
202             start_game_id=start_game_id, end_game_id=end_game_id)
203
204     try:
205         recent_games = [RecentGame(row) for row in rgs_q.limit(20).all()]
206         
207         if len(recent_games) > 0:
208             query['start_game_id'] = recent_games[-1].game_id + 1
209
210         # build the list of links for the stripe across the top
211         game_type_links = []
212
213         # clear out the game_id window
214         gt_query = query.copy()
215         if 'start_game_id' in gt_query:
216             del gt_query['start_game_id']
217         if 'end_game_id' in gt_query:
218             del gt_query['end_game_id']
219
220         for gt in ('overall','duel','ctf','dm','tdm','ca','kh','ft',
221                 'lms','as','dom','nb','cts','rc'):
222             gt_query['type'] = gt
223             url = request.route_url("game_index", _query=gt_query)
224             game_type_links.append((gt, url))
225
226     except:
227         raise httpexceptions.HTTPBadRequest("Malformed Query")
228
229     return {
230             'recent_games':recent_games,
231             'query':query,
232             'game_type_cd':game_type_cd,
233             'game_type_links':game_type_links,
234            }
235
236
237 def game_finder(request):
238     """
239     Provide a list of recent games with an advanced filter.
240     """
241     return game_finder_data(request)
242
243
244 def game_finder_json(request):
245     """
246     Provide a list of recent games in JSON format.
247     """
248     data = game_finder_data(request)
249     return [rg.to_dict() for rg in data["recent_games"]]