]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/views/player.py
Applied feedback from Antibody, improved the *->json functionality
[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 collections import namedtuple
9 from pyramid.response import Response
10 from pyramid.url import current_route_url
11 from sqlalchemy import desc, distinct
12 from webhelpers.paginate import Page, PageURL
13 from xonstat.models import *
14 from xonstat.util import page_url, to_json
15
16 log = logging.getLogger(__name__)
17
18
19 def player_index_data(request):
20     if request.params.has_key('page'):
21         current_page = request.params['page']
22     else:
23         current_page = 1
24
25     try:
26         player_q = DBSession.query(Player).\
27                 filter(Player.player_id > 2).\
28                 filter(Player.active_ind == True).\
29                 filter(sa.not_(Player.nick.like('Anonymous Player%'))).\
30                 order_by(Player.player_id.desc())
31
32         players = Page(player_q, current_page, items_per_page=10, url=page_url)
33
34     except Exception as e:
35         players = None
36         raise e
37
38     return {'players':players
39            }
40
41
42 def player_index(request):
43     """
44     Provides a list of all the current players.
45     """
46     return player_index_data(request)
47
48
49 def player_index_json(request):
50     """
51     Provides a list of all the current players. JSON.
52     """
53     return [{'status':'not implemented'}]
54
55
56 def get_games_played(player_id):
57     """
58     Provides a breakdown by gametype of the games played by player_id.
59
60     Returns a list of namedtuples with the following members:
61         - game_type_cd
62         - games
63         - wins
64         - losses
65         - win_pct
66
67     The list itself is ordered by the number of games played
68     """
69     GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
70         'losses', 'win_pct'])
71
72     raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
73             from_statement(
74                 "SELECT game_type_cd, "
75                        "SUM(win) wins, "
76                        "SUM(loss) losses "
77                 "FROM   (SELECT g.game_id, "
78                                "g.game_type_cd, "
79                                "CASE "
80                                  "WHEN g.winner = pgs.team THEN 1 "
81                                  "WHEN pgs.rank = 1 THEN 1 "
82                                  "ELSE 0 "
83                                "END win, "
84                                "CASE "
85                                  "WHEN g.winner = pgs.team THEN 0 "
86                                  "WHEN pgs.rank = 1 THEN 0 "
87                                  "ELSE 1 "
88                                "END loss "
89                         "FROM   games g, "
90                                "player_game_stats pgs "
91                         "WHERE  g.game_id = pgs.game_id "
92                         "AND pgs.player_id = :player_id) win_loss "
93                 "GROUP  BY game_type_cd "
94             ).params(player_id=player_id).all()
95
96     games_played = []
97     overall_games = 0
98     overall_wins = 0
99     overall_losses = 0
100     for row in raw_games_played:
101         games = row.wins + row.losses
102         overall_games += games
103         overall_wins += row.wins
104         overall_losses += row.losses
105         win_pct = float(row.wins)/games * 100
106
107         games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
108             row.losses, win_pct))
109
110     try:
111         overall_win_pct = float(overall_wins)/overall_games * 100
112     except:
113         overall_win_pct = 0.0
114
115     games_played.append(GamesPlayed('overall', overall_games, overall_wins,
116         overall_losses, overall_win_pct))
117
118     # sort the resulting list by # of games played
119     games_played = sorted(games_played, key=lambda x:x.games)
120     games_played.reverse()
121     return games_played
122
123
124 def get_overall_stats(player_id):
125     """
126     Provides a breakdown of stats by gametype played by player_id.
127
128     Returns a dictionary of namedtuples with the following members:
129         - total_kills
130         - total_deaths
131         - k_d_ratio
132         - last_played (last time the player played the game type)
133         - total_playing_time (total amount of time played the game type)
134         - total_pickups (ctf only)
135         - total_captures (ctf only)
136         - cap_ratio (ctf only)
137         - total_carrier_frags (ctf only)
138         - game_type_cd
139
140     The key to the dictionary is the game type code. There is also an
141     "overall" game_type_cd which sums the totals and computes the total ratios.
142     """
143     OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
144         'k_d_ratio', 'last_played', 'total_playing_time', 'total_pickups',
145         'total_captures', 'cap_ratio', 'total_carrier_frags', 'game_type_cd'])
146
147     raw_stats = DBSession.query('game_type_cd', 'total_kills',
148             'total_deaths', 'last_played', 'total_playing_time',
149             'total_pickups', 'total_captures', 'total_carrier_frags').\
150             from_statement(
151                 "SELECT g.game_type_cd, "
152                        "Sum(pgs.kills)         total_kills, "
153                        "Sum(pgs.deaths)        total_deaths, "
154                        "Max(pgs.create_dt)     last_played, "
155                        "Sum(pgs.alivetime)     total_playing_time, "
156                        "Sum(pgs.pickups)       total_pickups, "
157                        "Sum(pgs.captures)      total_captures, "
158                        "Sum(pgs.carrier_frags) total_carrier_frags "
159                 "FROM   games g, "
160                        "player_game_stats pgs "
161                 "WHERE  g.game_id = pgs.game_id "
162                   "AND  pgs.player_id = :player_id "
163                 "GROUP  BY g.game_type_cd "
164             ).params(player_id=player_id).all()
165
166     # to be indexed by game_type_cd
167     overall_stats = {}
168
169     # sums for the "overall" game type (which is fake)
170     overall_kills = 0
171     overall_deaths = 0
172     overall_last_played = None
173     overall_playing_time = datetime.timedelta(seconds=0)
174     overall_carrier_frags = 0
175
176     for row in raw_stats:
177         # running totals or mins
178         overall_kills += row.total_kills or 0
179         overall_deaths += row.total_deaths or 0
180
181         if overall_last_played is None or row.last_played > overall_last_played:
182             overall_last_played = row.last_played
183
184         overall_playing_time += row.total_playing_time
185
186         # individual gametype ratio calculations
187         try:
188             k_d_ratio = float(row.total_kills)/row.total_deaths
189         except:
190             k_d_ratio = None
191
192         try:
193             cap_ratio = float(row.total_pickups)/row.total_captures
194         except:
195             cap_ratio = None
196
197         overall_carrier_frags += row.total_carrier_frags or 0
198
199         # everything else is untouched or "raw"
200         os = OverallStats(total_kills=row.total_kills,
201                 total_deaths=row.total_deaths,
202                 k_d_ratio=k_d_ratio,
203                 last_played=row.last_played,
204                 total_playing_time=row.total_playing_time,
205                 total_pickups=row.total_pickups,
206                 total_captures=row.total_captures,
207                 cap_ratio=cap_ratio,
208                 total_carrier_frags=row.total_carrier_frags,
209                 game_type_cd=row.game_type_cd)
210
211         overall_stats[row.game_type_cd] = os
212
213     # and lastly, the overall stuff
214     try:
215         overall_k_d_ratio = float(overall_kills)/overall_deaths
216     except:
217         overall_k_d_ratio = None
218
219     os = OverallStats(total_kills=overall_kills,
220             total_deaths=overall_deaths,
221             k_d_ratio=overall_k_d_ratio,
222             last_played=overall_last_played,
223             total_playing_time=overall_playing_time,
224             total_pickups=None,
225             total_captures=None,
226             cap_ratio=None,
227             total_carrier_frags=overall_carrier_frags,
228             game_type_cd='overall')
229
230     overall_stats['overall'] = os
231
232     return overall_stats
233
234
235 def get_fav_maps(player_id, game_type_cd=None):
236     """
237     Provides a breakdown of favorite maps by gametype.
238
239     Returns a dictionary of namedtuples with the following members:
240         - game_type_cd
241         - map_name (map name)
242         - map_id
243         - times_played
244
245     The favorite map is defined as the map you've played the most
246     for the given game_type_cd.
247
248     The key to the dictionary is the game type code. There is also an
249     "overall" game_type_cd which is the overall favorite map. This is
250     defined as the favorite map of the game type you've played the
251     most. The input parameter game_type_cd is for this.
252     """
253     FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
254
255     raw_favs = DBSession.query('game_type_cd', 'map_name',
256             'map_id', 'times_played').\
257             from_statement(
258                 "SELECT game_type_cd, "
259                        "name map_name, "
260                        "map_id, "
261                        "times_played "
262                 "FROM   (SELECT g.game_type_cd, "
263                                "m.name, "
264                                "m.map_id, "
265                                "Count(*) times_played, "
266                                "Row_number() "
267                                  "OVER ( "
268                                    "partition BY g.game_type_cd "
269                                    "ORDER BY Count(*) DESC, m.map_id ASC) rank "
270                         "FROM   games g, "
271                                "player_game_stats pgs, "
272                                "maps m "
273                         "WHERE  g.game_id = pgs.game_id "
274                                "AND g.map_id = m.map_id "
275                                "AND pgs.player_id = :player_id "
276                         "GROUP  BY g.game_type_cd, "
277                                   "m.map_id, "
278                                   "m.name) most_played "
279                 "WHERE  rank = 1 "
280                 "ORDER BY  times_played desc "
281             ).params(player_id=player_id).all()
282
283     fav_maps = {}
284     overall_fav = None
285     for row in raw_favs:
286         fv = FavMap(map_name=row.map_name,
287             map_id=row.map_id,
288             times_played=row.times_played,
289             game_type_cd=row.game_type_cd)
290     
291         # if we aren't given a favorite game_type_cd
292         # then the overall favorite is the one we've
293         # played the most
294         if overall_fav is None:
295             fav_maps['overall'] = fv
296             overall_fav = fv.game_type_cd
297
298         # otherwise it is the favorite map from the
299         # favorite game_type_cd (provided as a param)
300         # and we'll overwrite the first dict entry
301         if game_type_cd == fv.game_type_cd:
302             fav_maps['overall'] = fv
303
304         fav_maps[row.game_type_cd] = fv
305
306     return fav_maps
307
308
309 def get_ranks(player_id):
310     """
311     Provides a breakdown of the player's ranks by game type.
312
313     Returns a dictionary of namedtuples with the following members:
314         - game_type_cd
315         - rank
316         - max_rank
317
318     The key to the dictionary is the game type code. There is also an
319     "overall" game_type_cd which is the overall best rank.
320     """    
321     Rank = namedtuple('Rank', ['rank', 'max_rank', 'game_type_cd'])
322
323     raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
324             from_statement(
325                 "select pr.game_type_cd, pr.rank, overall.max_rank "
326                 "from player_ranks pr,  "
327                    "(select game_type_cd, max(rank) max_rank "
328                     "from player_ranks  "
329                     "group by game_type_cd) overall "
330                 "where pr.game_type_cd = overall.game_type_cd  "
331                 "and player_id = :player_id "
332                 "order by rank").\
333             params(player_id=player_id).all()
334
335     ranks = {}
336     found_top_rank = False
337     for row in raw_ranks:
338         rank = Rank(rank=row.rank,
339             max_rank=row.max_rank,
340             game_type_cd=row.game_type_cd)
341         
342         if not found_top_rank:
343             ranks['overall'] = rank
344             found_top_rank = True
345
346         ranks[row.game_type_cd] = rank
347
348     return ranks;
349
350
351 def get_elos(player_id):
352     """
353     Provides a breakdown of the player's elos by game type.
354
355     Returns a dictionary of namedtuples with the following members:
356         - player_id
357         - game_type_cd
358         - games
359         - elo
360
361     The key to the dictionary is the game type code. There is also an
362     "overall" game_type_cd which is the overall best rank.
363     """
364     raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
365             order_by(PlayerElo.elo.desc()).all()
366
367     elos = {}
368     found_max_elo = False
369     for row in raw_elos:
370         if not found_max_elo:
371             elos['overall'] = row
372             found_max_elo = True
373
374         elos[row.game_type_cd] = row
375
376     return elos
377
378
379 def get_recent_games(player_id):
380     """
381     Provides a list of recent games.
382
383     Returns the full PlayerGameStat, Game, Server, Map
384     objects for all recent games.
385     """
386     RecentGame = namedtuple('RecentGame', ['player_stats', 'game', 'server', 'map'])
387
388     # recent games table, all data
389     recent_games = DBSession.query(PlayerGameStat, Game, Server, Map).\
390             filter(PlayerGameStat.player_id == player_id).\
391             filter(PlayerGameStat.game_id == Game.game_id).\
392             filter(Game.server_id == Server.server_id).\
393             filter(Game.map_id == Map.map_id).\
394             order_by(Game.game_id.desc())[0:10]
395
396     return [
397         RecentGame(player_stats=row.PlayerGameStat,
398             game=row.Game,
399             server=row.Server,
400             map=row.Map)
401         for row in recent_games ]
402
403
404 def get_recent_weapons(player_id):
405     """
406     Returns the weapons that have been used in the past 90 days
407     and also used in 5 games or more.
408     """
409     cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=90)
410     recent_weapons = []
411     for weapon in DBSession.query(PlayerWeaponStat.weapon_cd, func.count()).\
412             filter(PlayerWeaponStat.player_id == player_id).\
413             filter(PlayerWeaponStat.create_dt > cutoff).\
414             group_by(PlayerWeaponStat.weapon_cd).\
415             having(func.count() > 4).\
416             all():
417                 recent_weapons.append(weapon[0])
418
419     return recent_weapons
420
421
422 def get_accuracy_stats(player_id, weapon_cd, games):
423     """
424     Provides accuracy for weapon_cd by player_id for the past N games.
425     """
426     # Reaching back 90 days should give us an accurate enough average
427     # We then multiply this out for the number of data points (games) to
428     # create parameters for a flot graph
429     try:
430         raw_avg = DBSession.query(func.sum(PlayerWeaponStat.hit),
431                 func.sum(PlayerWeaponStat.fired)).\
432                 filter(PlayerWeaponStat.player_id == player_id).\
433                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
434                 one()
435
436         avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
437
438         # Determine the raw accuracy (hit, fired) numbers for $games games
439         # This is then enumerated to create parameters for a flot graph
440         raw_accs = DBSession.query(PlayerWeaponStat.game_id, 
441             PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
442                 filter(PlayerWeaponStat.player_id == player_id).\
443                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
444                 order_by(PlayerWeaponStat.game_id.desc()).\
445                 limit(games).\
446                 all()
447
448         # they come out in opposite order, so flip them in the right direction
449         raw_accs.reverse()
450
451         accs = []
452         for i in range(len(raw_accs)):
453             accs.append((raw_accs[i][0], round(float(raw_accs[i][1])/raw_accs[i][2]*100, 2)))
454     except:
455         accs = []
456         avg = 0.0
457
458     return (avg, accs)
459
460
461 def get_damage_stats(player_id, weapon_cd, games):
462     """
463     Provides damage info for weapon_cd by player_id for the past N games.
464     """
465     try:
466         raw_avg = DBSession.query(func.sum(PlayerWeaponStat.actual),
467                 func.sum(PlayerWeaponStat.hit)).\
468                 filter(PlayerWeaponStat.player_id == player_id).\
469                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
470                 one()
471
472         avg = round(float(raw_avg[0])/raw_avg[1], 2)
473
474         # Determine the damage efficiency (hit, fired) numbers for $games games
475         # This is then enumerated to create parameters for a flot graph
476         raw_dmgs = DBSession.query(PlayerWeaponStat.game_id, 
477             PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
478                 filter(PlayerWeaponStat.player_id == player_id).\
479                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
480                 order_by(PlayerWeaponStat.game_id.desc()).\
481                 limit(games).\
482                 all()
483
484         # they come out in opposite order, so flip them in the right direction
485         raw_dmgs.reverse()
486
487         dmgs = []
488         for i in range(len(raw_dmgs)):
489             # try to derive, unless we've hit nothing then set to 0!
490             try:
491                 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
492             except:
493                 dmg = 0.0
494
495             dmgs.append((raw_dmgs[i][0], dmg))
496     except Exception as e:
497         dmgs = []
498         avg = 0.0
499
500     return (avg, dmgs)
501
502
503 def player_info_data(request):
504     player_id = int(request.matchdict['id'])
505     if player_id <= 2:
506         player_id = -1;
507
508     try:
509         player = DBSession.query(Player).filter_by(player_id=player_id).\
510                 filter(Player.active_ind == True).one()
511
512         games_played   = get_games_played(player_id)
513         overall_stats  = get_overall_stats(player_id)
514         fav_maps       = get_fav_maps(player_id)
515         elos           = get_elos(player_id)
516         ranks          = get_ranks(player_id)
517         recent_games   = get_recent_games(player_id)
518         recent_weapons = get_recent_weapons(player_id)
519
520     except Exception as e:
521         player         = None
522         games_played   = None
523         overall_stats  = None
524         fav_maps       = None
525         elos           = None
526         ranks          = None
527         recent_games   = None
528         recent_weapons = []
529
530     return {'player':player,
531             'games_played':games_played,
532             'overall_stats':overall_stats,
533             'fav_maps':fav_maps,
534             'elos':elos,
535             'ranks':ranks,
536             'recent_games':recent_games,
537             'recent_weapons':recent_weapons
538             }
539
540
541 def player_info(request):
542     """
543     Provides detailed information on a specific player
544     """
545     return player_info_data(request)
546
547
548 def player_info_json(request):
549     """
550     Provides detailed information on a specific player. JSON.
551     """
552     
553     # All player_info fields are converted into JSON-formattable dictionaries
554     player_info = player_info_data(request)    
555     
556     player = player_info['player'].to_dict()
557
558     games_played = {}
559     for game in player_info['games_played']:
560         games_played[game.game_type_cd] = to_json(game)
561     
562     overall_stats = {}
563     for gt,stats in player_info['overall_stats'].items():
564         overall_stats[gt] = to_json(stats)
565     
566     elos = {}
567     for gt,elo in player_info['elos'].items():
568         elos[gt] = to_json(elo.to_dict())
569     
570     ranks = {}
571     for gt,rank in player_info['ranks'].items():
572         ranks[gt] = to_json(rank)
573     
574     fav_maps = {}
575     for gt,mapinfo in player_info['fav_maps'].items():
576         fav_maps[gt] = to_json(mapinfo)
577      
578     recent_games = []
579     for game in player_info['recent_games']:
580         recent_games.append(to_json(game))
581     
582     recent_weapons = player_info['recent_weapons']
583     
584     return [{
585         'player':           player,
586         'games_played':     games_played,
587         'overall_stats':    overall_stats,
588         'fav_maps':         fav_maps,
589         'elos':             elos,
590         'ranks':            ranks,
591         'recent_games':     recent_games,
592         'recent_weapons':   recent_weapons,
593     }]
594     #return [{'status':'not implemented'}]
595
596
597 def player_game_index_data(request):
598     player_id = request.matchdict['player_id']
599
600     if request.params.has_key('page'):
601         current_page = request.params['page']
602     else:
603         current_page = 1
604
605     try:
606         games_q = DBSession.query(Game, Server, Map).\
607             filter(PlayerGameStat.game_id == Game.game_id).\
608             filter(PlayerGameStat.player_id == player_id).\
609             filter(Game.server_id == Server.server_id).\
610             filter(Game.map_id == Map.map_id).\
611             order_by(Game.game_id.desc())
612
613         games = Page(games_q, current_page, items_per_page=10, url=page_url)
614
615         pgstats = {}
616         for (game, server, map) in games:
617             pgstats[game.game_id] = DBSession.query(PlayerGameStat).\
618                     filter(PlayerGameStat.game_id == game.game_id).\
619                     order_by(PlayerGameStat.rank).\
620                     order_by(PlayerGameStat.score).all()
621
622     except Exception as e:
623         player = None
624         games = None
625
626     return {'player_id':player_id,
627             'games':games,
628             'pgstats':pgstats}
629
630
631 def player_game_index(request):
632     """
633     Provides an index of the games in which a particular
634     player was involved. This is ordered by game_id, with
635     the most recent game_ids first. Paginated.
636     """
637     return player_game_index_data(request)
638
639
640 def player_game_index_json(request):
641     """
642     Provides an index of the games in which a particular
643     player was involved. This is ordered by game_id, with
644     the most recent game_ids first. Paginated. JSON.
645     """
646     return [{'status':'not implemented'}]
647
648
649 def player_accuracy_data(request):
650     player_id = request.matchdict['id']
651     allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
652     weapon_cd = 'nex'
653     games = 20
654
655     if request.params.has_key('weapon'):
656         if request.params['weapon'] in allowed_weapons:
657             weapon_cd = request.params['weapon']
658
659     if request.params.has_key('games'):
660         try:
661             games = request.params['games']
662
663             if games < 0:
664                 games = 20
665             if games > 50:
666                 games = 50
667         except:
668             games = 20
669
670     (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
671
672     # if we don't have enough data for the given weapon
673     if len(accs) < games:
674         games = len(accs)
675
676     return {
677             'player_id':player_id, 
678             'player_url':request.route_url('player_info', id=player_id), 
679             'weapon':weapon_cd, 
680             'games':games, 
681             'avg':avg, 
682             'accs':accs
683             }
684
685
686 def player_accuracy(request):
687     """
688     Provides the accuracy for the given weapon. (JSON only)
689     """
690     return player_accuracy_data(request)
691
692
693 def player_accuracy_json(request):
694     """
695     Provides a JSON response representing the accuracy for the given weapon.
696
697     Parameters:
698        weapon = which weapon to display accuracy for. Valid values are 'nex',
699                 'shotgun', 'uzi', and 'minstanex'.
700        games = over how many games to display accuracy. Can be up to 50.
701     """
702     return player_accuracy_data(request)
703
704
705 def player_damage_data(request):
706     player_id = request.matchdict['id']
707     allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
708             'rocketlauncher', 'laser']
709     weapon_cd = 'rocketlauncher'
710     games = 20
711
712     if request.params.has_key('weapon'):
713         if request.params['weapon'] in allowed_weapons:
714             weapon_cd = request.params['weapon']
715
716     if request.params.has_key('games'):
717         try:
718             games = request.params['games']
719
720             if games < 0:
721                 games = 20
722             if games > 50:
723                 games = 50
724         except:
725             games = 20
726
727     (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
728
729     # if we don't have enough data for the given weapon
730     if len(dmgs) < games:
731         games = len(dmgs)
732
733     return {
734             'player_id':player_id, 
735             'player_url':request.route_url('player_info', id=player_id), 
736             'weapon':weapon_cd, 
737             'games':games, 
738             'avg':avg, 
739             'dmgs':dmgs
740             }
741
742
743 def player_damage_json(request):
744     """
745     Provides a JSON response representing the damage for the given weapon.
746
747     Parameters:
748        weapon = which weapon to display damage for. Valid values are
749          'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
750          'laser'.
751        games = over how many games to display damage. Can be up to 50.
752     """
753     return player_damage_data(request)