]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/views/player.py
Fix merge conflict, change indentation a bit.
[xonotic/xonstat.git] / xonstat / views / player.py
1 import datetime
2 import json
3 import logging
4 import re
5 import sqlalchemy as sa
6 import sqlalchemy.sql.functions as func
7 import time
8 from pyramid.response import Response
9 from pyramid.url import current_route_url
10 from sqlalchemy import desc, distinct
11 from webhelpers.paginate import Page, PageURL
12 from xonstat.models import *
13 from xonstat.util import page_url
14
15 log = logging.getLogger(__name__)
16
17
18 def _player_index_data(request):
19     if request.params.has_key('page'):
20         current_page = request.params['page']
21     else:
22         current_page = 1
23
24     try:
25         player_q = DBSession.query(Player).\
26                 filter(Player.player_id > 2).\
27                 filter(Player.active_ind == True).\
28                 filter(sa.not_(Player.nick.like('Anonymous Player%'))).\
29                 order_by(Player.player_id.desc())
30
31         players = Page(player_q, current_page, items_per_page=10, url=page_url)
32
33     except Exception as e:
34         players = None
35         raise e
36
37     return {'players':players
38            }
39
40
41 def player_index(request):
42     """
43     Provides a list of all the current players.
44     """
45     return _player_index_data(request)
46
47
48 def player_index_json(request):
49     """
50     Provides a list of all the current players. JSON.
51     """
52     return [{'status':'not implemented'}]
53
54
55 def _get_games_played(player_id):
56     """
57     Provides a breakdown by gametype of the games played by player_id.
58
59     Returns a tuple containing (total_games, games_breakdown), where
60     total_games is the absolute number of games played by player_id
61     and games_breakdown is an array containing (game_type_cd, # games)
62     """
63     games_played = DBSession.query(Game.game_type_cd, func.count()).\
64             filter(Game.game_id == PlayerGameStat.game_id).\
65             filter(PlayerGameStat.player_id == player_id).\
66             group_by(Game.game_type_cd).\
67             order_by(func.count().desc()).all()
68
69     total = 0
70     for (game_type_cd, games) in games_played:
71         total += games
72
73     return (total, games_played)
74
75
76 # TODO: should probably factor the above function into this one such that
77 # total_stats['ctf_games'] is the count of CTF games and so on...
78 def _get_total_stats(player_id):
79     """
80     Provides aggregated stats by player_id.
81
82     Returns a dict with the keys 'kills', 'deaths', 'alivetime'.
83
84     kills = how many kills a player has over all games
85     deaths = how many deaths a player has over all games
86     alivetime = how long a player has played over all games
87
88     If any of the above are None, they are set to 0.
89     """
90     total_stats = {}
91     (total_stats['kills'], total_stats['deaths'], total_stats['alivetime']) = DBSession.\
92             query("total_kills", "total_deaths", "total_alivetime").\
93             from_statement(
94                 "select sum(kills) total_kills, "
95                 "sum(deaths) total_deaths, "
96                 "sum(alivetime) total_alivetime "
97                 "from player_game_stats "
98                 "where player_id=:player_id"
99             ).params(player_id=player_id).one()
100
101     (total_stats['wins'],) = DBSession.\
102             query("total_wins").\
103             from_statement(
104                 "select count(*) total_wins "
105                 "from games g, player_game_stats pgs "
106                 "where g.game_id = pgs.game_id "
107                 "and player_id=:player_id "
108                 "and (g.winner = pgs.team or pgs.rank = 1)"
109             ).params(player_id=player_id).one()
110
111     for (key,value) in total_stats.items():
112         if value == None:
113             total_stats[key] = 0
114
115     return total_stats
116
117
118 def get_accuracy_stats(player_id, weapon_cd, games):
119     """
120     Provides accuracy for weapon_cd by player_id for the past N games.
121     """
122     # Reaching back 90 days should give us an accurate enough average
123     # We then multiply this out for the number of data points (games) to
124     # create parameters for a flot graph
125     try:
126         raw_avg = DBSession.query(func.sum(PlayerWeaponStat.hit),
127                 func.sum(PlayerWeaponStat.fired)).\
128                 filter(PlayerWeaponStat.player_id == player_id).\
129                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
130                 one()
131
132         avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
133
134         # Determine the raw accuracy (hit, fired) numbers for $games games
135         # This is then enumerated to create parameters for a flot graph
136         raw_accs = DBSession.query(PlayerWeaponStat.game_id, 
137             PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
138                 filter(PlayerWeaponStat.player_id == player_id).\
139                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
140                 order_by(PlayerWeaponStat.game_id.desc()).\
141                 limit(games).\
142                 all()
143
144         # they come out in opposite order, so flip them in the right direction
145         raw_accs.reverse()
146
147         accs = []
148         for i in range(len(raw_accs)):
149             accs.append((raw_accs[i][0], round(float(raw_accs[i][1])/raw_accs[i][2]*100, 2)))
150     except:
151         accs = []
152         avg = 0.0
153
154     return (avg, accs)
155
156
157 def get_damage_stats(player_id, weapon_cd, games):
158     """
159     Provides damage info for weapon_cd by player_id for the past N games.
160     """
161     try:
162         raw_avg = DBSession.query(func.sum(PlayerWeaponStat.actual),
163                 func.sum(PlayerWeaponStat.hit)).\
164                 filter(PlayerWeaponStat.player_id == player_id).\
165                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
166                 one()
167
168         avg = round(float(raw_avg[0])/raw_avg[1], 2)
169
170         # Determine the damage efficiency (hit, fired) numbers for $games games
171         # This is then enumerated to create parameters for a flot graph
172         raw_dmgs = DBSession.query(PlayerWeaponStat.game_id, 
173             PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
174                 filter(PlayerWeaponStat.player_id == player_id).\
175                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
176                 order_by(PlayerWeaponStat.game_id.desc()).\
177                 limit(games).\
178                 all()
179
180         # they come out in opposite order, so flip them in the right direction
181         raw_dmgs.reverse()
182
183         dmgs = []
184         for i in range(len(raw_dmgs)):
185             # try to derive, unless we've hit nothing then set to 0!
186             try:
187                 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
188             except:
189                 dmg = 0.0
190
191             dmgs.append((raw_dmgs[i][0], dmg))
192     except Exception as e:
193         dmgs = []
194         avg = 0.0
195
196     return (avg, dmgs)
197
198
199 def _player_info_data(request):
200     player_id = int(request.matchdict['id'])
201     if player_id <= 2:
202         player_id = -1;
203
204     try:
205         player = DBSession.query(Player).filter_by(player_id=player_id).\
206                 filter(Player.active_ind == True).one()
207
208         # games played, alivetime, wins, kills, deaths
209         total_stats = _get_total_stats(player.player_id)
210
211         # games breakdown - N games played (X ctf, Y dm) etc
212         (total_games, games_breakdown) = _get_games_played(player.player_id)
213
214
215         # friendly display of elo information and preliminary status
216         elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
217                 filter(PlayerElo.game_type_cd.in_(['ctf','duel','dm'])).\
218                 order_by(PlayerElo.elo.desc()).all()
219
220         elos_display = []
221         for elo in elos:
222             if elo.games > 32:
223                 str = "{0} ({1})"
224             else:
225                 str = "{0}* ({1})"
226
227             elos_display.append(str.format(round(elo.elo, 3),
228                 elo.game_type_cd))
229
230         # which weapons have been used in the past 90 days
231         # and also, used in 5 games or more?
232         back_then = datetime.datetime.utcnow() - datetime.timedelta(days=90)
233         recent_weapons = []
234         for weapon in DBSession.query(PlayerWeaponStat.weapon_cd, func.count()).\
235                 filter(PlayerWeaponStat.player_id == player_id).\
236                 filter(PlayerWeaponStat.create_dt > back_then).\
237                 group_by(PlayerWeaponStat.weapon_cd).\
238                 having(func.count() > 4).\
239                 all():
240                     recent_weapons.append(weapon[0])
241
242         # recent games table, all data
243         recent_games = DBSession.query(PlayerGameStat, Game, Server, Map).\
244                 filter(PlayerGameStat.player_id == player_id).\
245                 filter(PlayerGameStat.game_id == Game.game_id).\
246                 filter(Game.server_id == Server.server_id).\
247                 filter(Game.map_id == Map.map_id).\
248                 order_by(Game.game_id.desc())[0:10]
249
250     except Exception as e:
251         player = None
252         elos_display = None
253         total_stats = None
254         recent_games = None
255         total_games = None
256         games_breakdown = None
257         recent_weapons = []
258
259     return {'player':player,
260             'elos_display':elos_display,
261             'recent_games':recent_games,
262             'total_stats':total_stats,
263             'total_games':total_games,
264             'games_breakdown':games_breakdown,
265             'recent_weapons':recent_weapons,
266             }
267
268
269 def player_info(request):
270     """
271     Provides detailed information on a specific player
272     """
273     return _player_info_data(request)
274
275
276 def player_info_json(request):
277     """
278     Provides detailed information on a specific player. JSON.
279     """
280     return [{'status':'not implemented'}]
281
282
283 def _player_game_index_data(request):
284     player_id = request.matchdict['player_id']
285
286     if request.params.has_key('page'):
287         current_page = request.params['page']
288     else:
289         current_page = 1
290
291     try:
292         games_q = DBSession.query(Game, Server, Map).\
293             filter(PlayerGameStat.game_id == Game.game_id).\
294             filter(PlayerGameStat.player_id == player_id).\
295             filter(Game.server_id == Server.server_id).\
296             filter(Game.map_id == Map.map_id).\
297             order_by(Game.game_id.desc())
298
299         games = Page(games_q, current_page, items_per_page=10, url=page_url)
300
301         pgstats = {}
302         for (game, server, map) in games:
303             pgstats[game.game_id] = DBSession.query(PlayerGameStat).\
304                     filter(PlayerGameStat.game_id == game.game_id).\
305                     order_by(PlayerGameStat.rank).\
306                     order_by(PlayerGameStat.score).all()
307
308     except Exception as e:
309         player = None
310         games = None
311
312     return {'player_id':player_id,
313             'games':games,
314             'pgstats':pgstats}
315
316
317 def player_game_index(request):
318     """
319     Provides an index of the games in which a particular
320     player was involved. This is ordered by game_id, with
321     the most recent game_ids first. Paginated.
322     """
323     return _player_game_index_data(request)
324
325
326 def player_game_index_json(request):
327     """
328     Provides an index of the games in which a particular
329     player was involved. This is ordered by game_id, with
330     the most recent game_ids first. Paginated. JSON.
331     """
332     return [{'status':'not implemented'}]
333
334
335 def _player_accuracy_data(request):
336     player_id = request.matchdict['id']
337     allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
338     weapon_cd = 'nex'
339     games = 20
340
341     if request.params.has_key('weapon'):
342         if request.params['weapon'] in allowed_weapons:
343             weapon_cd = request.params['weapon']
344
345     if request.params.has_key('games'):
346         try:
347             games = request.params['games']
348
349             if games < 0:
350                 games = 20
351             if games > 50:
352                 games = 50
353         except:
354             games = 20
355
356     (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
357
358     # if we don't have enough data for the given weapon
359     if len(accs) < games:
360         games = len(accs)
361
362     return {
363             'player_id':player_id, 
364             'player_url':request.route_url('player_info', id=player_id), 
365             'weapon':weapon_cd, 
366             'games':games, 
367             'avg':avg, 
368             'accs':accs
369             }
370
371
372 def player_accuracy(request):
373     """
374     Provides the accuracy for the given weapon. (JSON only)
375     """
376     return _player_accuracy_data(request)
377
378
379 def player_accuracy_json(request):
380     """
381     Provides a JSON response representing the accuracy for the given weapon.
382
383     Parameters:
384        weapon = which weapon to display accuracy for. Valid values are 'nex',
385                 'shotgun', 'uzi', and 'minstanex'.
386        games = over how many games to display accuracy. Can be up to 50.
387     """
388     return _player_accuracy_data(request)
389
390
391 def _player_damage_data(request):
392     player_id = request.matchdict['id']
393     allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
394             'rocketlauncher', 'laser']
395     weapon_cd = 'rocketlauncher'
396     games = 20
397
398     if request.params.has_key('weapon'):
399         if request.params['weapon'] in allowed_weapons:
400             weapon_cd = request.params['weapon']
401
402     if request.params.has_key('games'):
403         try:
404             games = request.params['games']
405
406             if games < 0:
407                 games = 20
408             if games > 50:
409                 games = 50
410         except:
411             games = 20
412
413     (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
414
415     # if we don't have enough data for the given weapon
416     if len(dmgs) < games:
417         games = len(dmgs)
418
419     return {
420             'player_id':player_id, 
421             'player_url':request.route_url('player_info', id=player_id), 
422             'weapon':weapon_cd, 
423             'games':games, 
424             'avg':avg, 
425             'dmgs':dmgs
426             }
427
428
429 def player_damage_json(request):
430     """
431     Provides a JSON response representing the damage for the given weapon.
432
433     Parameters:
434        weapon = which weapon to display damage for. Valid values are
435          'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
436          'laser'.
437        games = over how many games to display damage. Can be up to 50.
438     """
439     return _player_damage_data(request)