The reflect option is deprecated. Use method instead.
[xonotic/xonstat.git] / xonstat / views / game.py
1 import datetime
2 import logging
3 import re
4 import time
5 from collections import OrderedDict
6 from pyramid.response import Response
7 from sqlalchemy import desc, func, over
8 from webhelpers.paginate import Page, PageURL
9 from xonstat.models import *
10 from xonstat.util import page_url
11 from xonstat.views.helpers import RecentGame, recent_games_q
12
13 log = logging.getLogger(__name__)
14
15
16 # DEPRECATED
17 def _game_index_data(request):
18     game_type_cd = None
19     game_type_descr = None
20
21     if request.params.has_key('game_type_cd'):
22         game_type_cd = request.params['game_type_cd']
23         try:
24             game_type_descr = DBSession.query(GameType.descr).\
25                 filter(GameType.game_type_cd == game_type_cd).\
26                 one()[0]
27         except Exception as e:
28             game_type_cd = None
29
30     if request.params.has_key('page'):
31         current_page = request.params['page']
32     else:
33         current_page = 1
34
35     try:
36         rgs_q = recent_games_q(game_type_cd=game_type_cd)
37
38         games = Page(rgs_q, current_page, items_per_page=10, url=page_url)
39
40         # replace the items in the canned pagination class with more rich ones
41         games.items = [RecentGame(row) for row in games.items]
42
43         pgstats = {}
44         for game in games.items:
45             pgstats[game.game_id] = DBSession.query(PlayerGameStat).\
46                     filter(PlayerGameStat.game_id == game.game_id).\
47                     order_by(PlayerGameStat.scoreboardpos).\
48                     order_by(PlayerGameStat.score).all()
49
50     except Exception as e:
51         games           = None
52         pgstats         = None
53         game_type_cd    = None
54         game_type_descr = None
55
56     return {'games':games,
57             'pgstats':pgstats,
58             'game_type_cd':game_type_cd,
59             'game_type_descr':game_type_descr,
60             }
61
62
63 def game_index(request):
64     """
65     Provides a list of current games, with the associated game stats.
66     These games are ordered by game_id, with the most current ones first.
67     Paginated.
68     """
69     return _game_index_data(request)
70
71
72 def game_index_json(request):
73     """
74     Provides a list of current games, with the associated game stats.
75     These games are ordered by game_id, with the most current ones first.
76     Paginated. JSON.
77     """
78     return [{'status':'not implemented'}]
79
80
81 def _game_info_data(request):
82     game_id = request.matchdict['id']
83
84     if request.params.has_key('show_elo'):
85         show_elo = True
86     else:
87         show_elo = False
88
89     show_latency = False
90
91     try:
92         notfound = False
93
94         (game, server, map, gametype) = DBSession.query(Game, Server, Map, GameType).\
95                 filter(Game.game_id == game_id).\
96                 filter(Game.server_id == Server.server_id).\
97                 filter(Game.map_id == Map.map_id).\
98                 filter(Game.game_type_cd == GameType.game_type_cd).one()
99
100         pgstats = DBSession.query(PlayerGameStat).\
101                 filter(PlayerGameStat.game_id == game_id).\
102                 order_by(PlayerGameStat.scoreboardpos).\
103                 order_by(PlayerGameStat.score).\
104                 all()
105
106         # if at least one player has a valid latency, we'll show the column
107         for pgstat in pgstats:
108             if pgstat.avg_latency is not None:
109                 show_latency = True
110
111         q = DBSession.query(TeamGameStat).\
112                 filter(TeamGameStat.game_id == game_id)
113         if game.game_type_cd == 'ctf':
114             q = q.order_by(TeamGameStat.caps.desc())
115         elif game.game_type_cd == 'ca':
116             q = q.order_by(TeamGameStat.rounds.desc())
117         # dom -> ticks, rc -> laps, nb -> goals, as -> objectives
118
119         q = q.order_by(TeamGameStat.score.desc())
120
121         tgstats = q.all()
122
123         stats_by_team = OrderedDict()
124         for pgstat in pgstats:
125             if pgstat.team not in stats_by_team.keys():
126                 stats_by_team[pgstat.team] = []
127             stats_by_team[pgstat.team].append(pgstat)
128
129         captimes = []
130         if game.game_type_cd == 'ctf':
131             for pgstat in pgstats:
132                 if pgstat.fastest is not None:
133                     captimes.append(pgstat)
134             captimes = sorted(captimes, key=lambda x:x.fastest)
135
136         pwstats = {}
137         for (pwstat, pgstat, weapon) in DBSession.query(PlayerWeaponStat, PlayerGameStat, Weapon).\
138                 filter(PlayerWeaponStat.game_id == game_id).\
139                 filter(PlayerWeaponStat.weapon_cd == Weapon.weapon_cd).\
140                 filter(PlayerWeaponStat.player_game_stat_id == \
141                     PlayerGameStat.player_game_stat_id).\
142                 order_by(PlayerGameStat.scoreboardpos).\
143                 order_by(PlayerGameStat.score).\
144                 order_by(Weapon.descr).\
145                 all():
146                     if pgstat.player_game_stat_id not in pwstats:
147                         pwstats[pgstat.player_game_stat_id] = []
148
149                     # NOTE adding pgstat to position 6 in order to display nick.
150                     # You have to use a slice [0:5] to pass to the accuracy
151                     # template
152                     pwstats[pgstat.player_game_stat_id].append((weapon.descr,
153                         weapon.weapon_cd, pwstat.actual, pwstat.max,
154                         pwstat.hit, pwstat.fired, pgstat))
155
156     except Exception as inst:
157         game = None
158         server = None
159         map = None
160         gametype = None
161         pgstats = None
162         tgstats = None
163         pwstats = None
164         captimes = None
165         show_elo = False
166         show_latency = False
167         stats_by_team = None
168         raise inst
169
170     return {'game':game,
171             'server':server,
172             'map':map,
173             'gametype':gametype,
174             'pgstats':pgstats,
175             'tgstats':tgstats,
176             'pwstats':pwstats,
177             'captimes':captimes,
178             'show_elo':show_elo,
179             'show_latency':show_latency,
180             'stats_by_team':stats_by_team,
181             }
182
183
184 def game_info(request):
185     """
186     List the game stats (scoreboard) for a particular game. Paginated.
187     """
188     return _game_info_data(request)
189
190
191 def game_info_json(request):
192     """
193     List the game stats (scoreboard) for a particular game. Paginated. JSON.
194     """
195     return [{'status':'not implemented'}]
196
197
198 def _rank_index_data(request):
199     if request.params.has_key('page'):
200         current_page = request.params['page']
201     else:
202         current_page = 1
203
204     game_type_cd = request.matchdict['game_type_cd']
205
206     ranks_q = DBSession.query(PlayerRank).\
207             filter(PlayerRank.game_type_cd==game_type_cd).\
208             order_by(PlayerRank.rank)
209
210     ranks = Page(ranks_q, current_page, url=page_url)
211
212     if len(ranks) == 0:
213         ranks = None
214
215     return {
216             'ranks':ranks,
217             'game_type_cd':game_type_cd,
218            }
219
220
221 def rank_index(request):
222     """
223     Provide a list of gametype ranks, paginated.
224     """
225     return _rank_index_data(request)
226
227
228 def rank_index_json(request):
229     """
230     Provide a list of gametype ranks, paginated. JSON.
231     """
232     return [{'status':'not implemented'}]
233
234
235 def game_finder_data(request):
236     if request.params.has_key('page'):
237         current_page = request.params['page']
238     else:
239         current_page = 1
240
241     query = {}
242
243     server_id, map_id, player_id = None, None, None
244     range_start, range_end, game_type_cd = None, None, None
245     game_type_descr = None
246
247     # these become WHERE clauses when present
248     if request.params.has_key('server_id'):
249         server_id = request.params['server_id']
250         query['server_id'] = server_id
251
252     if request.params.has_key('map_id'):
253         map_id = request.params['map_id']
254         query['map_id'] = map_id
255
256     if request.params.has_key('player_id'):
257         player_id = request.params['player_id']
258         query['player_id'] = player_id
259
260     if request.params.has_key('range_start'):
261         range_start = request.params['range_start']
262         query['range_start'] = range_start
263
264     if request.params.has_key('range_end'):
265         range_end = request.params['range_end']
266         query['range_end'] = range_end
267
268     if request.params.has_key('type'):
269         game_type_cd = request.params['type']
270         query['type'] = game_type_cd
271         try:
272             game_type_descr = DBSession.query(GameType.descr).\
273                 filter(GameType.game_type_cd == game_type_cd).\
274                 one()[0]
275         except Exception as e:
276             game_type_cd = None
277
278     rgs_q = recent_games_q(server_id=server_id, map_id=map_id,
279             player_id=player_id, game_type_cd=game_type_cd)
280
281     recent_games = Page(rgs_q, current_page, url=page_url)
282
283     recent_games.items = [RecentGame(row) for row in recent_games.items]
284
285     return {
286             'recent_games':recent_games,
287             'query':query,
288             'game_type_cd':game_type_cd,
289            }
290
291 def game_finder(request):
292     """
293     Provide a list of recent games with an advanced filter.
294     """
295     return game_finder_data(request)