5 import sqlalchemy as sa
6 import sqlalchemy.sql.functions as func
8 from calendar import timegm
9 from collections import namedtuple
10 from pyramid.response import Response
11 from pyramid.url import current_route_url
12 from sqlalchemy import desc, distinct
13 from webhelpers.paginate import Page, PageURL
14 from xonstat.models import *
15 from xonstat.util import page_url, to_json, pretty_date
17 log = logging.getLogger(__name__)
20 def player_index_data(request):
21 if request.params.has_key('page'):
22 current_page = request.params['page']
27 player_q = DBSession.query(Player).\
28 filter(Player.player_id > 2).\
29 filter(Player.active_ind == True).\
30 filter(sa.not_(Player.nick.like('Anonymous Player%'))).\
31 order_by(Player.player_id.desc())
33 players = Page(player_q, current_page, items_per_page=10, url=page_url)
35 except Exception as e:
39 return {'players':players
43 def player_index(request):
45 Provides a list of all the current players.
47 return player_index_data(request)
50 def player_index_json(request):
52 Provides a list of all the current players. JSON.
54 return [{'status':'not implemented'}]
57 def get_games_played(player_id):
59 Provides a breakdown by gametype of the games played by player_id.
61 Returns a list of namedtuples with the following members:
68 The list itself is ordered by the number of games played
70 GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
73 raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
75 "SELECT game_type_cd, "
78 "FROM (SELECT g.game_id, "
81 "WHEN g.winner = pgs.team THEN 1 "
82 "WHEN pgs.rank = 1 THEN 1 "
86 "WHEN g.winner = pgs.team THEN 0 "
87 "WHEN pgs.rank = 1 THEN 0 "
91 "player_game_stats pgs "
92 "WHERE g.game_id = pgs.game_id "
93 "AND pgs.player_id = :player_id) win_loss "
94 "GROUP BY game_type_cd "
95 ).params(player_id=player_id).all()
101 for row in raw_games_played:
102 games = row.wins + row.losses
103 overall_games += games
104 overall_wins += row.wins
105 overall_losses += row.losses
106 win_pct = float(row.wins)/games * 100
108 games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
109 row.losses, win_pct))
112 overall_win_pct = float(overall_wins)/overall_games * 100
114 overall_win_pct = 0.0
116 games_played.append(GamesPlayed('overall', overall_games, overall_wins,
117 overall_losses, overall_win_pct))
119 # sort the resulting list by # of games played
120 games_played = sorted(games_played, key=lambda x:x.games)
121 games_played.reverse()
125 def get_overall_stats(player_id):
127 Provides a breakdown of stats by gametype played by player_id.
129 Returns a dictionary of namedtuples with the following members:
133 - last_played (last time the player played the game type)
134 - last_played_epoch (same as above, but in seconds since epoch)
135 - last_played_fuzzy (same as above, but in relative date)
136 - total_playing_time (total amount of time played the game type)
137 - total_pickups (ctf only)
138 - total_captures (ctf only)
139 - cap_ratio (ctf only)
140 - total_carrier_frags (ctf only)
143 The key to the dictionary is the game type code. There is also an
144 "overall" game_type_cd which sums the totals and computes the total ratios.
146 OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
147 'k_d_ratio', 'last_played', 'last_played_epoch', 'last_played_fuzzy',
148 'total_playing_time', 'total_pickups', 'total_captures', 'cap_ratio',
149 'total_carrier_frags', 'game_type_cd'])
151 raw_stats = DBSession.query('game_type_cd', 'total_kills',
152 'total_deaths', 'last_played', 'total_playing_time',
153 'total_pickups', 'total_captures', 'total_carrier_frags').\
155 "SELECT g.game_type_cd, "
156 "Sum(pgs.kills) total_kills, "
157 "Sum(pgs.deaths) total_deaths, "
158 "Max(pgs.create_dt) last_played, "
159 "Sum(pgs.alivetime) total_playing_time, "
160 "Sum(pgs.pickups) total_pickups, "
161 "Sum(pgs.captures) total_captures, "
162 "Sum(pgs.carrier_frags) total_carrier_frags "
164 "player_game_stats pgs "
165 "WHERE g.game_id = pgs.game_id "
166 "AND pgs.player_id = :player_id "
167 "GROUP BY g.game_type_cd "
168 ).params(player_id=player_id).all()
170 # to be indexed by game_type_cd
173 # sums for the "overall" game type (which is fake)
176 overall_last_played = None
177 overall_playing_time = datetime.timedelta(seconds=0)
178 overall_carrier_frags = 0
180 for row in raw_stats:
181 # running totals or mins
182 overall_kills += row.total_kills or 0
183 overall_deaths += row.total_deaths or 0
185 if overall_last_played is None or row.last_played > overall_last_played:
186 overall_last_played = row.last_played
188 overall_playing_time += row.total_playing_time
190 # individual gametype ratio calculations
192 k_d_ratio = float(row.total_kills)/row.total_deaths
197 cap_ratio = float(row.total_captures)/row.total_pickups
201 overall_carrier_frags += row.total_carrier_frags or 0
203 # everything else is untouched or "raw"
204 os = OverallStats(total_kills=row.total_kills,
205 total_deaths=row.total_deaths,
207 last_played=row.last_played,
208 last_played_epoch=timegm(row.last_played.timetuple()),
209 last_played_fuzzy=pretty_date(row.last_played),
210 total_playing_time=row.total_playing_time,
211 total_pickups=row.total_pickups,
212 total_captures=row.total_captures,
214 total_carrier_frags=row.total_carrier_frags,
215 game_type_cd=row.game_type_cd)
217 overall_stats[row.game_type_cd] = os
219 # and lastly, the overall stuff
221 overall_k_d_ratio = float(overall_kills)/overall_deaths
223 overall_k_d_ratio = None
225 os = OverallStats(total_kills=overall_kills,
226 total_deaths=overall_deaths,
227 k_d_ratio=overall_k_d_ratio,
228 last_played=overall_last_played,
229 last_played_epoch=timegm(overall_last_played.timetuple()),
230 last_played_fuzzy=pretty_date(overall_last_played),
231 total_playing_time=overall_playing_time,
235 total_carrier_frags=overall_carrier_frags,
236 game_type_cd='overall')
238 overall_stats['overall'] = os
243 def get_fav_maps(player_id, game_type_cd=None):
245 Provides a breakdown of favorite maps by gametype.
247 Returns a dictionary of namedtuples with the following members:
249 - map_name (map name)
253 The favorite map is defined as the map you've played the most
254 for the given game_type_cd.
256 The key to the dictionary is the game type code. There is also an
257 "overall" game_type_cd which is the overall favorite map. This is
258 defined as the favorite map of the game type you've played the
259 most. The input parameter game_type_cd is for this.
261 FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
263 raw_favs = DBSession.query('game_type_cd', 'map_name',
264 'map_id', 'times_played').\
266 "SELECT game_type_cd, "
270 "FROM (SELECT g.game_type_cd, "
273 "Count(*) times_played, "
276 "partition BY g.game_type_cd "
277 "ORDER BY Count(*) DESC, m.map_id ASC) rank "
279 "player_game_stats pgs, "
281 "WHERE g.game_id = pgs.game_id "
282 "AND g.map_id = m.map_id "
283 "AND pgs.player_id = :player_id "
284 "GROUP BY g.game_type_cd, "
286 "m.name) most_played "
288 "ORDER BY times_played desc "
289 ).params(player_id=player_id).all()
294 fv = FavMap(map_name=row.map_name,
296 times_played=row.times_played,
297 game_type_cd=row.game_type_cd)
299 # if we aren't given a favorite game_type_cd
300 # then the overall favorite is the one we've
302 if overall_fav is None:
303 fav_maps['overall'] = fv
304 overall_fav = fv.game_type_cd
306 # otherwise it is the favorite map from the
307 # favorite game_type_cd (provided as a param)
308 # and we'll overwrite the first dict entry
309 if game_type_cd == fv.game_type_cd:
310 fav_maps['overall'] = fv
312 fav_maps[row.game_type_cd] = fv
317 def get_ranks(player_id):
319 Provides a breakdown of the player's ranks by game type.
321 Returns a dictionary of namedtuples with the following members:
326 The key to the dictionary is the game type code. There is also an
327 "overall" game_type_cd which is the overall best rank.
329 Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
331 raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
333 "select pr.game_type_cd, pr.rank, overall.max_rank "
334 "from player_ranks pr, "
335 "(select game_type_cd, max(rank) max_rank "
337 "group by game_type_cd) overall "
338 "where pr.game_type_cd = overall.game_type_cd "
339 "and player_id = :player_id "
341 params(player_id=player_id).all()
344 found_top_rank = False
345 for row in raw_ranks:
346 rank = Rank(rank=row.rank,
347 max_rank=row.max_rank,
348 percentile=100 - 100*float(row.rank)/row.max_rank,
349 game_type_cd=row.game_type_cd)
352 if not found_top_rank:
353 ranks['overall'] = rank
354 found_top_rank = True
355 elif rank.percentile > ranks['overall'].percentile:
356 ranks['overall'] = rank
358 ranks[row.game_type_cd] = rank
363 def get_elos(player_id):
365 Provides a breakdown of the player's elos by game type.
367 Returns a dictionary of namedtuples with the following members:
373 The key to the dictionary is the game type code. There is also an
374 "overall" game_type_cd which is the overall best rank.
376 raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
377 order_by(PlayerElo.elo.desc()).all()
380 found_max_elo = False
382 if not found_max_elo:
383 elos['overall'] = row
386 elos[row.game_type_cd] = row
391 def get_recent_games(player_id):
393 Provides a list of recent games.
395 Returns the full PlayerGameStat, Game, Server, Map
396 objects for all recent games.
398 RecentGame = namedtuple('RecentGame', ['player_stats', 'game', 'server', 'map'])
400 # recent games table, all data
401 recent_games = DBSession.query(PlayerGameStat, Game, Server, Map).\
402 filter(PlayerGameStat.player_id == player_id).\
403 filter(PlayerGameStat.game_id == Game.game_id).\
404 filter(Game.server_id == Server.server_id).\
405 filter(Game.map_id == Map.map_id).\
406 order_by(Game.game_id.desc())[0:10]
409 RecentGame(player_stats=row.PlayerGameStat,
413 for row in recent_games ]
416 def get_recent_weapons(player_id):
418 Returns the weapons that have been used in the past 90 days
419 and also used in 5 games or more.
421 cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=90)
423 for weapon in DBSession.query(PlayerWeaponStat.weapon_cd, func.count()).\
424 filter(PlayerWeaponStat.player_id == player_id).\
425 filter(PlayerWeaponStat.create_dt > cutoff).\
426 group_by(PlayerWeaponStat.weapon_cd).\
427 having(func.count() > 4).\
429 recent_weapons.append(weapon[0])
431 return recent_weapons
434 def get_accuracy_stats(player_id, weapon_cd, games):
436 Provides accuracy for weapon_cd by player_id for the past N games.
438 # Reaching back 90 days should give us an accurate enough average
439 # We then multiply this out for the number of data points (games) to
440 # create parameters for a flot graph
442 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.hit),
443 func.sum(PlayerWeaponStat.fired)).\
444 filter(PlayerWeaponStat.player_id == player_id).\
445 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
448 avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
450 # Determine the raw accuracy (hit, fired) numbers for $games games
451 # This is then enumerated to create parameters for a flot graph
452 raw_accs = DBSession.query(PlayerWeaponStat.game_id,
453 PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
454 filter(PlayerWeaponStat.player_id == player_id).\
455 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
456 order_by(PlayerWeaponStat.game_id.desc()).\
460 # they come out in opposite order, so flip them in the right direction
464 for i in range(len(raw_accs)):
465 accs.append((raw_accs[i][0], round(float(raw_accs[i][1])/raw_accs[i][2]*100, 2)))
473 def get_damage_stats(player_id, weapon_cd, games):
475 Provides damage info for weapon_cd by player_id for the past N games.
478 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.actual),
479 func.sum(PlayerWeaponStat.hit)).\
480 filter(PlayerWeaponStat.player_id == player_id).\
481 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
484 avg = round(float(raw_avg[0])/raw_avg[1], 2)
486 # Determine the damage efficiency (hit, fired) numbers for $games games
487 # This is then enumerated to create parameters for a flot graph
488 raw_dmgs = DBSession.query(PlayerWeaponStat.game_id,
489 PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
490 filter(PlayerWeaponStat.player_id == player_id).\
491 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
492 order_by(PlayerWeaponStat.game_id.desc()).\
496 # they come out in opposite order, so flip them in the right direction
500 for i in range(len(raw_dmgs)):
501 # try to derive, unless we've hit nothing then set to 0!
503 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
507 dmgs.append((raw_dmgs[i][0], dmg))
508 except Exception as e:
515 def player_info_data(request):
516 player_id = int(request.matchdict['id'])
521 player = DBSession.query(Player).filter_by(player_id=player_id).\
522 filter(Player.active_ind == True).one()
524 games_played = get_games_played(player_id)
525 overall_stats = get_overall_stats(player_id)
526 fav_maps = get_fav_maps(player_id)
527 elos = get_elos(player_id)
528 ranks = get_ranks(player_id)
529 recent_games = get_recent_games(player_id)
530 recent_weapons = get_recent_weapons(player_id)
532 except Exception as e:
542 return {'player':player,
543 'games_played':games_played,
544 'overall_stats':overall_stats,
548 'recent_games':recent_games,
549 'recent_weapons':recent_weapons
553 def player_info(request):
555 Provides detailed information on a specific player
557 return player_info_data(request)
560 def player_info_json(request):
562 Provides detailed information on a specific player. JSON.
565 # All player_info fields are converted into JSON-formattable dictionaries
566 player_info = player_info_data(request)
568 player = player_info['player'].to_dict()
571 for game in player_info['games_played']:
572 games_played[game.game_type_cd] = to_json(game)
575 for gt,stats in player_info['overall_stats'].items():
576 overall_stats[gt] = to_json(stats)
579 for gt,elo in player_info['elos'].items():
580 elos[gt] = to_json(elo.to_dict())
583 for gt,rank in player_info['ranks'].items():
584 ranks[gt] = to_json(rank)
587 for gt,mapinfo in player_info['fav_maps'].items():
588 fav_maps[gt] = to_json(mapinfo)
591 for game in player_info['recent_games']:
592 recent_games.append(to_json(game))
594 #recent_weapons = player_info['recent_weapons']
598 'games_played': games_played,
599 'overall_stats': overall_stats,
600 'fav_maps': fav_maps,
603 'recent_games': recent_games,
604 # 'recent_weapons': recent_weapons,
605 'recent_weapons': ['not implemented'],
607 #return [{'status':'not implemented'}]
610 def player_game_index_data(request):
611 RecentGame = namedtuple('RecentGame', ['game_id', 'game_type_cd', 'winner',
612 'game_create_dt', 'game_epoch', 'game_fuzzy', 'server_id',
613 'server_name', 'map_id', 'map_name', 'team', 'rank', 'elo_delta'])
615 player_id = request.matchdict['player_id']
617 if request.params.has_key('page'):
618 current_page = request.params['page']
623 player = DBSession.query(Player).filter_by(player_id=player_id).\
624 filter(Player.active_ind == True).one()
626 games_q = DBSession.query(Game.game_id, Game.game_type_cd, Game.winner,
627 Game.create_dt, Server.server_id,
628 Server.name.label('server_name'), Map.map_id,
629 Map.name.label('map_name'), PlayerGameStat.team,
630 PlayerGameStat.rank, PlayerGameStat.elo_delta).\
631 filter(PlayerGameStat.game_id == Game.game_id).\
632 filter(PlayerGameStat.player_id == player_id).\
633 filter(Game.server_id == Server.server_id).\
634 filter(Game.map_id == Map.map_id).\
635 order_by(Game.game_id.desc())
637 games = Page(games_q, current_page, items_per_page=10, url=page_url)
639 # replace the items in the canned pagination class with more rich ones
640 games.items = [RecentGame(
641 game_id = row.game_id,
642 game_type_cd = row.game_type_cd,
644 game_create_dt = row.create_dt,
645 game_epoch = timegm(row.create_dt.timetuple()),
646 game_fuzzy = pretty_date(row.create_dt),
647 server_id = row.server_id,
648 server_name = row.server_name,
650 map_name = row.map_name,
653 elo_delta = row.elo_delta
654 ) for row in games.items]
656 except Exception as e:
661 'player_id':player.player_id,
667 def player_game_index(request):
669 Provides an index of the games in which a particular
670 player was involved. This is ordered by game_id, with
671 the most recent game_ids first. Paginated.
673 return player_game_index_data(request)
676 def player_game_index_json(request):
678 Provides an index of the games in which a particular
679 player was involved. This is ordered by game_id, with
680 the most recent game_ids first. Paginated. JSON.
682 return [{'status':'not implemented'}]
685 def player_accuracy_data(request):
686 player_id = request.matchdict['id']
687 allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
691 if request.params.has_key('weapon'):
692 if request.params['weapon'] in allowed_weapons:
693 weapon_cd = request.params['weapon']
695 if request.params.has_key('games'):
697 games = request.params['games']
706 (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
708 # if we don't have enough data for the given weapon
709 if len(accs) < games:
713 'player_id':player_id,
714 'player_url':request.route_url('player_info', id=player_id),
722 def player_accuracy(request):
724 Provides the accuracy for the given weapon. (JSON only)
726 return player_accuracy_data(request)
729 def player_accuracy_json(request):
731 Provides a JSON response representing the accuracy for the given weapon.
734 weapon = which weapon to display accuracy for. Valid values are 'nex',
735 'shotgun', 'uzi', and 'minstanex'.
736 games = over how many games to display accuracy. Can be up to 50.
738 return player_accuracy_data(request)
741 def player_damage_data(request):
742 player_id = request.matchdict['id']
743 allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
744 'rocketlauncher', 'laser']
745 weapon_cd = 'rocketlauncher'
748 if request.params.has_key('weapon'):
749 if request.params['weapon'] in allowed_weapons:
750 weapon_cd = request.params['weapon']
752 if request.params.has_key('games'):
754 games = request.params['games']
763 (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
765 # if we don't have enough data for the given weapon
766 if len(dmgs) < games:
770 'player_id':player_id,
771 'player_url':request.route_url('player_info', id=player_id),
779 def player_damage_json(request):
781 Provides a JSON response representing the damage for the given weapon.
784 weapon = which weapon to display damage for. Valid values are
785 'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
787 games = over how many games to display damage. Can be up to 50.
789 return player_damage_data(request)
792 def player_hashkey_info_data(request):
793 hashkey = request.matchdict['hashkey']
795 player = DBSession.query(Player).\
796 filter(Player.player_id == Hashkey.player_id).\
797 filter(Player.active_ind == True).\
798 filter(Hashkey.hashkey == hashkey).one()
800 games_played = get_games_played(player.player_id)
801 overall_stats = get_overall_stats(player.player_id)
802 fav_maps = get_fav_maps(player.player_id)
803 elos = get_elos(player.player_id)
804 ranks = get_ranks(player.player_id)
806 except Exception as e:
815 return {'player':player,
816 'games_played':games_played,
817 'overall_stats':overall_stats,
824 def player_hashkey_info_json(request):
826 Provides detailed information on a specific player. JSON.
829 # All player_info fields are converted into JSON-formattable dictionaries
830 player_info = player_hashkey_info_data(request)
832 player = player_info['player'].to_dict()
835 for game in player_info['games_played']:
836 games_played[game.game_type_cd] = to_json(game)
839 for gt,stats in player_info['overall_stats'].items():
840 overall_stats[gt] = to_json(stats)
843 for gt,elo in player_info['elos'].items():
844 elos[gt] = to_json(elo.to_dict())
847 for gt,rank in player_info['ranks'].items():
848 ranks[gt] = to_json(rank)
851 for gt,mapinfo in player_info['fav_maps'].items():
852 fav_maps[gt] = to_json(mapinfo)
857 'games_played': games_played,
858 'overall_stats': overall_stats,
859 'fav_maps': fav_maps,