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