4 import pyramid.httpexceptions
6 import sqlalchemy as sa
7 import sqlalchemy.sql.functions as func
9 from calendar import timegm
10 from collections import namedtuple
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, datetime_seconds, html_colors
16 from xonstat.views.helpers import RecentGame, recent_games_q
18 log = logging.getLogger(__name__)
21 def player_index_data(request):
22 if request.params.has_key('page'):
23 current_page = request.params['page']
28 player_q = DBSession.query(Player).\
29 filter(Player.player_id > 2).\
30 filter(Player.active_ind == True).\
31 filter(sa.not_(Player.nick.like('Anonymous Player%'))).\
32 order_by(Player.player_id.desc())
34 players = Page(player_q, current_page, items_per_page=10, url=page_url)
36 except Exception as e:
40 return {'players':players
44 def player_index(request):
46 Provides a list of all the current players.
48 return player_index_data(request)
51 def player_index_json(request):
53 Provides a list of all the current players. JSON.
55 return [{'status':'not implemented'}]
58 def get_games_played(player_id):
60 Provides a breakdown by gametype of the games played by player_id.
62 Returns a list of namedtuples with the following members:
69 The list itself is ordered by the number of games played
71 GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
74 raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
76 "SELECT game_type_cd, "
79 "FROM (SELECT g.game_id, "
82 "WHEN g.winner = pgs.team THEN 1 "
83 "WHEN pgs.rank = 1 THEN 1 "
87 "WHEN g.winner = pgs.team THEN 0 "
88 "WHEN pgs.rank = 1 THEN 0 "
92 "player_game_stats pgs "
93 "WHERE g.game_id = pgs.game_id "
94 "AND pgs.player_id = :player_id) win_loss "
95 "GROUP BY game_type_cd "
96 ).params(player_id=player_id).all()
102 for row in raw_games_played:
103 games = row.wins + row.losses
104 overall_games += games
105 overall_wins += row.wins
106 overall_losses += row.losses
107 win_pct = float(row.wins)/games * 100
109 games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
110 row.losses, win_pct))
113 overall_win_pct = float(overall_wins)/overall_games * 100
115 overall_win_pct = 0.0
117 games_played.append(GamesPlayed('overall', overall_games, overall_wins,
118 overall_losses, overall_win_pct))
120 # sort the resulting list by # of games played
121 games_played = sorted(games_played, key=lambda x:x.games)
122 games_played.reverse()
126 def get_overall_stats(player_id):
128 Provides a breakdown of stats by gametype played by player_id.
130 Returns a dictionary of namedtuples with the following members:
134 - last_played (last time the player played the game type)
135 - last_played_epoch (same as above, but in seconds since epoch)
136 - last_played_fuzzy (same as above, but in relative date)
137 - total_playing_time (total amount of time played the game type)
138 - total_playing_time_secs (same as the above, but in seconds)
139 - total_pickups (ctf only)
140 - total_captures (ctf only)
141 - cap_ratio (ctf only)
142 - total_carrier_frags (ctf only)
145 The key to the dictionary is the game type code. There is also an
146 "overall" game_type_cd which sums the totals and computes the total ratios.
148 OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
149 'k_d_ratio', 'last_played', 'last_played_epoch', 'last_played_fuzzy',
150 'total_playing_time', 'total_playing_time_secs', 'total_pickups', 'total_captures', 'cap_ratio',
151 'total_carrier_frags', 'game_type_cd'])
153 raw_stats = DBSession.query('game_type_cd', 'total_kills',
154 'total_deaths', 'last_played', 'total_playing_time',
155 'total_pickups', 'total_captures', 'total_carrier_frags').\
157 "SELECT g.game_type_cd, "
158 "Sum(pgs.kills) total_kills, "
159 "Sum(pgs.deaths) total_deaths, "
160 "Max(pgs.create_dt) last_played, "
161 "Sum(pgs.alivetime) total_playing_time, "
162 "Sum(pgs.pickups) total_pickups, "
163 "Sum(pgs.captures) total_captures, "
164 "Sum(pgs.carrier_frags) total_carrier_frags "
166 "player_game_stats pgs "
167 "WHERE g.game_id = pgs.game_id "
168 "AND pgs.player_id = :player_id "
169 "GROUP BY g.game_type_cd "
171 "SELECT 'overall' game_type_cd, "
172 "Sum(pgs.kills) total_kills, "
173 "Sum(pgs.deaths) total_deaths, "
174 "Max(pgs.create_dt) last_played, "
175 "Sum(pgs.alivetime) total_playing_time, "
176 "Sum(pgs.pickups) total_pickups, "
177 "Sum(pgs.captures) total_captures, "
178 "Sum(pgs.carrier_frags) total_carrier_frags "
180 "player_game_stats pgs "
181 "WHERE g.game_id = pgs.game_id "
182 "AND pgs.player_id = :player_id "
183 ).params(player_id=player_id).all()
185 # to be indexed by game_type_cd
189 for row in raw_stats:
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 # everything else is untouched or "raw"
202 os = OverallStats(total_kills=row.total_kills,
203 total_deaths=row.total_deaths,
205 last_played=row.last_played,
206 last_played_epoch=timegm(row.last_played.timetuple()),
207 last_played_fuzzy=pretty_date(row.last_played),
208 total_playing_time=row.total_playing_time,
209 total_playing_time_secs=int(datetime_seconds(row.total_playing_time)),
210 total_pickups=row.total_pickups,
211 total_captures=row.total_captures,
213 total_carrier_frags=row.total_carrier_frags,
214 game_type_cd=row.game_type_cd)
216 overall_stats[row.game_type_cd] = os
218 # We have to edit "overall" stats to exclude deaths in CTS.
219 # Although we still want to record deaths, they shouldn't
220 # count towards the overall K:D ratio.
221 if 'cts' in overall_stats:
222 os = overall_stats['overall']
225 k_d_ratio = float(os.total_kills)/(os.total_deaths - overall_stats['cts'].total_deaths)
229 non_cts_deaths = os.total_deaths - overall_stats['cts'].total_deaths
232 overall_stats['overall'] = OverallStats(
233 total_kills = os.total_kills,
234 total_deaths = non_cts_deaths,
235 k_d_ratio = k_d_ratio,
236 last_played = os.last_played,
237 last_played_epoch = os.last_played_epoch,
238 last_played_fuzzy = os.last_played_fuzzy,
239 total_playing_time = os.total_playing_time,
240 total_playing_time_secs = os.total_playing_time_secs,
241 total_pickups = os.total_pickups,
242 total_captures = os.total_captures,
243 cap_ratio = os.cap_ratio,
244 total_carrier_frags = os.total_carrier_frags,
245 game_type_cd = os.game_type_cd)
250 def get_fav_maps(player_id, game_type_cd=None):
252 Provides a breakdown of favorite maps by gametype.
254 Returns a dictionary of namedtuples with the following members:
256 - map_name (map name)
260 The favorite map is defined as the map you've played the most
261 for the given game_type_cd.
263 The key to the dictionary is the game type code. There is also an
264 "overall" game_type_cd which is the overall favorite map. This is
265 defined as the favorite map of the game type you've played the
266 most. The input parameter game_type_cd is for this.
268 FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
270 raw_favs = DBSession.query('game_type_cd', 'map_name',
271 'map_id', 'times_played').\
273 "SELECT game_type_cd, "
277 "FROM (SELECT g.game_type_cd, "
280 "Count(*) times_played, "
283 "partition BY g.game_type_cd "
284 "ORDER BY Count(*) DESC, m.map_id ASC) rank "
286 "player_game_stats pgs, "
288 "WHERE g.game_id = pgs.game_id "
289 "AND g.map_id = m.map_id "
290 "AND pgs.player_id = :player_id "
291 "GROUP BY g.game_type_cd, "
293 "m.name) most_played "
295 "ORDER BY times_played desc "
296 ).params(player_id=player_id).all()
301 fv = FavMap(map_name=row.map_name,
303 times_played=row.times_played,
304 game_type_cd=row.game_type_cd)
306 # if we aren't given a favorite game_type_cd
307 # then the overall favorite is the one we've
309 if overall_fav is None:
310 fav_maps['overall'] = fv
311 overall_fav = fv.game_type_cd
313 # otherwise it is the favorite map from the
314 # favorite game_type_cd (provided as a param)
315 # and we'll overwrite the first dict entry
316 if game_type_cd == fv.game_type_cd:
317 fav_maps['overall'] = fv
319 fav_maps[row.game_type_cd] = fv
324 def get_ranks(player_id):
326 Provides a breakdown of the player's ranks by game type.
328 Returns a dictionary of namedtuples with the following members:
333 The key to the dictionary is the game type code. There is also an
334 "overall" game_type_cd which is the overall best rank.
336 Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
338 raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
340 "select pr.game_type_cd, pr.rank, overall.max_rank "
341 "from player_ranks pr, "
342 "(select game_type_cd, max(rank) max_rank "
344 "group by game_type_cd) overall "
345 "where pr.game_type_cd = overall.game_type_cd "
346 "and player_id = :player_id "
348 params(player_id=player_id).all()
351 found_top_rank = False
352 for row in raw_ranks:
353 rank = Rank(rank=row.rank,
354 max_rank=row.max_rank,
355 percentile=100 - 100*float(row.rank)/row.max_rank,
356 game_type_cd=row.game_type_cd)
359 if not found_top_rank:
360 ranks['overall'] = rank
361 found_top_rank = True
362 elif rank.percentile > ranks['overall'].percentile:
363 ranks['overall'] = rank
365 ranks[row.game_type_cd] = rank
370 def get_elos(player_id):
372 Provides a breakdown of the player's elos by game type.
374 Returns a dictionary of namedtuples with the following members:
380 The key to the dictionary is the game type code. There is also an
381 "overall" game_type_cd which is the overall best rank.
383 raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
384 order_by(PlayerElo.elo.desc()).all()
387 found_max_elo = False
389 if not found_max_elo:
390 elos['overall'] = row
393 elos[row.game_type_cd] = row
398 def get_recent_games(player_id):
400 Provides a list of recent games for a player. Uses the recent_games_q helper.
402 # recent games played in descending order
403 rgs = recent_games_q(player_id=player_id).limit(10).all()
404 recent_games = [RecentGame(row) for row in rgs]
409 def get_recent_weapons(player_id):
411 Returns the weapons that have been used in the past 90 days
412 and also used in 5 games or more.
414 cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=90)
416 for weapon in DBSession.query(PlayerWeaponStat.weapon_cd, func.count()).\
417 filter(PlayerWeaponStat.player_id == player_id).\
418 filter(PlayerWeaponStat.create_dt > cutoff).\
419 group_by(PlayerWeaponStat.weapon_cd).\
420 having(func.count() > 4).\
422 recent_weapons.append(weapon[0])
424 return recent_weapons
427 def get_accuracy_stats(player_id, weapon_cd, games):
429 Provides accuracy for weapon_cd by player_id for the past N games.
431 # Reaching back 90 days should give us an accurate enough average
432 # We then multiply this out for the number of data points (games) to
433 # create parameters for a flot graph
435 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.hit),
436 func.sum(PlayerWeaponStat.fired)).\
437 filter(PlayerWeaponStat.player_id == player_id).\
438 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
441 avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
443 # Determine the raw accuracy (hit, fired) numbers for $games games
444 # This is then enumerated to create parameters for a flot graph
445 raw_accs = DBSession.query(PlayerWeaponStat.game_id,
446 PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
447 filter(PlayerWeaponStat.player_id == player_id).\
448 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
449 order_by(PlayerWeaponStat.game_id.desc()).\
453 # they come out in opposite order, so flip them in the right direction
457 for i in range(len(raw_accs)):
458 accs.append((raw_accs[i][0], round(float(raw_accs[i][1])/raw_accs[i][2]*100, 2)))
466 def get_damage_stats(player_id, weapon_cd, games):
468 Provides damage info for weapon_cd by player_id for the past N games.
471 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.actual),
472 func.sum(PlayerWeaponStat.hit)).\
473 filter(PlayerWeaponStat.player_id == player_id).\
474 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
477 avg = round(float(raw_avg[0])/raw_avg[1], 2)
479 # Determine the damage efficiency (hit, fired) numbers for $games games
480 # This is then enumerated to create parameters for a flot graph
481 raw_dmgs = DBSession.query(PlayerWeaponStat.game_id,
482 PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
483 filter(PlayerWeaponStat.player_id == player_id).\
484 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
485 order_by(PlayerWeaponStat.game_id.desc()).\
489 # they come out in opposite order, so flip them in the right direction
493 for i in range(len(raw_dmgs)):
494 # try to derive, unless we've hit nothing then set to 0!
496 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
500 dmgs.append((raw_dmgs[i][0], dmg))
501 except Exception as e:
508 def player_info_data(request):
509 player_id = int(request.matchdict['id'])
514 player = DBSession.query(Player).filter_by(player_id=player_id).\
515 filter(Player.active_ind == True).one()
517 games_played = get_games_played(player_id)
518 overall_stats = get_overall_stats(player_id)
519 fav_maps = get_fav_maps(player_id)
520 elos = get_elos(player_id)
521 ranks = get_ranks(player_id)
522 recent_games = get_recent_games(player_id)
523 recent_weapons = get_recent_weapons(player_id)
525 except Exception as e:
535 return {'player':player,
536 'games_played':games_played,
537 'overall_stats':overall_stats,
541 'recent_games':recent_games,
542 'recent_weapons':recent_weapons
546 def player_info(request):
548 Provides detailed information on a specific player
550 return player_info_data(request)
553 def player_info_json(request):
555 Provides detailed information on a specific player. JSON.
558 # All player_info fields are converted into JSON-formattable dictionaries
559 player_info = player_info_data(request)
561 player = player_info['player'].to_dict()
564 for game in player_info['games_played']:
565 games_played[game.game_type_cd] = to_json(game)
568 for gt,stats in player_info['overall_stats'].items():
569 overall_stats[gt] = to_json(stats)
572 for gt,elo in player_info['elos'].items():
573 elos[gt] = to_json(elo.to_dict())
576 for gt,rank in player_info['ranks'].items():
577 ranks[gt] = to_json(rank)
580 for gt,mapinfo in player_info['fav_maps'].items():
581 fav_maps[gt] = to_json(mapinfo)
584 for game in player_info['recent_games']:
585 recent_games.append(to_json(game))
587 #recent_weapons = player_info['recent_weapons']
591 'games_played': games_played,
592 'overall_stats': overall_stats,
593 'fav_maps': fav_maps,
596 'recent_games': recent_games,
597 # 'recent_weapons': recent_weapons,
598 'recent_weapons': ['not implemented'],
600 #return [{'status':'not implemented'}]
603 def player_game_index_data(request):
604 player_id = request.matchdict['player_id']
606 if request.params.has_key('page'):
607 current_page = request.params['page']
612 player = DBSession.query(Player).filter_by(player_id=player_id).\
613 filter(Player.active_ind == True).one()
615 rgs_q = recent_games_q(player_id=player.player_id)
617 games = Page(rgs_q, current_page, items_per_page=10, url=page_url)
619 # replace the items in the canned pagination class with more rich ones
620 games.items = [RecentGame(row) for row in games.items]
622 except Exception as e:
627 'player_id':player.player_id,
633 def player_game_index(request):
635 Provides an index of the games in which a particular
636 player was involved. This is ordered by game_id, with
637 the most recent game_ids first. Paginated.
639 return player_game_index_data(request)
642 def player_game_index_json(request):
644 Provides an index of the games in which a particular
645 player was involved. This is ordered by game_id, with
646 the most recent game_ids first. Paginated. JSON.
648 return [{'status':'not implemented'}]
651 def player_accuracy_data(request):
652 player_id = request.matchdict['id']
653 allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
657 if request.params.has_key('weapon'):
658 if request.params['weapon'] in allowed_weapons:
659 weapon_cd = request.params['weapon']
661 if request.params.has_key('games'):
663 games = request.params['games']
672 (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
674 # if we don't have enough data for the given weapon
675 if len(accs) < games:
679 'player_id':player_id,
680 'player_url':request.route_url('player_info', id=player_id),
688 def player_accuracy(request):
690 Provides the accuracy for the given weapon. (JSON only)
692 return player_accuracy_data(request)
695 def player_accuracy_json(request):
697 Provides a JSON response representing the accuracy for the given weapon.
700 weapon = which weapon to display accuracy for. Valid values are 'nex',
701 'shotgun', 'uzi', and 'minstanex'.
702 games = over how many games to display accuracy. Can be up to 50.
704 return player_accuracy_data(request)
707 def player_damage_data(request):
708 player_id = request.matchdict['id']
709 allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
710 'rocketlauncher', 'laser']
711 weapon_cd = 'rocketlauncher'
714 if request.params.has_key('weapon'):
715 if request.params['weapon'] in allowed_weapons:
716 weapon_cd = request.params['weapon']
718 if request.params.has_key('games'):
720 games = request.params['games']
729 (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
731 # if we don't have enough data for the given weapon
732 if len(dmgs) < games:
736 'player_id':player_id,
737 'player_url':request.route_url('player_info', id=player_id),
745 def player_damage_json(request):
747 Provides a JSON response representing the damage for the given weapon.
750 weapon = which weapon to display damage for. Valid values are
751 'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
753 games = over how many games to display damage. Can be up to 50.
755 return player_damage_data(request)
758 def player_hashkey_info_data(request):
759 hashkey = request.matchdict['hashkey']
761 player = DBSession.query(Player).\
762 filter(Player.player_id == Hashkey.player_id).\
763 filter(Player.active_ind == True).\
764 filter(Hashkey.hashkey == hashkey).one()
766 games_played = get_games_played(player.player_id)
767 overall_stats = get_overall_stats(player.player_id)
768 fav_maps = get_fav_maps(player.player_id)
769 elos = get_elos(player.player_id)
770 ranks = get_ranks(player.player_id)
772 except Exception as e:
773 raise pyramid.httpexceptions.HTTPNotFound
775 return {'player':player,
777 'games_played':games_played,
778 'overall_stats':overall_stats,
785 def player_hashkey_info_json(request):
787 Provides detailed information on a specific player. JSON.
790 # All player_info fields are converted into JSON-formattable dictionaries
791 player_info = player_hashkey_info_data(request)
793 player = player_info['player'].to_dict()
796 for game in player_info['games_played']:
797 games_played[game.game_type_cd] = to_json(game)
800 for gt,stats in player_info['overall_stats'].items():
801 overall_stats[gt] = to_json(stats)
804 for gt,elo in player_info['elos'].items():
805 elos[gt] = to_json(elo.to_dict())
808 for gt,rank in player_info['ranks'].items():
809 ranks[gt] = to_json(rank)
812 for gt,mapinfo in player_info['fav_maps'].items():
813 fav_maps[gt] = to_json(mapinfo)
818 'games_played': games_played,
819 'overall_stats': overall_stats,
820 'fav_maps': fav_maps,
826 def player_hashkey_info_text(request):
828 Provides detailed information on a specific player. Plain text.
831 now = timegm(datetime.datetime.utcnow().timetuple())
833 # All player_info fields are converted into JSON-formattable dictionaries
834 player_info = player_hashkey_info_data(request)
836 # gather all of the data up into aggregate structures
837 player = player_info['player']
838 games_played = player_info['games_played']
839 overall_stats = player_info['overall_stats']
840 elos = player_info['elos']
841 ranks = player_info['ranks']
842 fav_maps = player_info['fav_maps']
844 # one-offs for things needing conversion for text/plain
845 player_joined = timegm(player.create_dt.timetuple())
846 alivetime = int(datetime_seconds(overall_stats['overall'].total_playing_time))
848 # this is a plain text response, if we don't do this here then
849 # Pyramid will assume html
850 request.response.content_type = 'text/plain'
856 'hashkey': player_info['hashkey'],
857 'player_joined': player_joined,
858 'games_played': games_played,
859 'overall_stats': overall_stats,
860 'alivetime': alivetime,
861 'fav_maps': fav_maps,
867 def player_elo_info_data(request):
869 Provides elo information on a specific player. Raw data is returned.
871 hashkey = request.matchdict['hashkey']
873 player = DBSession.query(Player).\
874 filter(Player.player_id == Hashkey.player_id).\
875 filter(Player.active_ind == True).\
876 filter(Hashkey.hashkey == hashkey).one()
878 elos = get_elos(player.player_id)
880 except Exception as e:
882 raise pyramid.httpexceptions.HTTPNotFound
887 def player_elo_info_json(request):
889 Provides elo information on a specific player. JSON.
891 elo_info = player_elo_info_data(request)
894 for gt, elo in elo_info['elos'].items():
895 elos[gt] = to_json(elo.to_dict())
902 def player_captimes_data(request):
903 player_id = int(request.matchdict['id'])
907 #player_captimes = DBSession.query(PlayerCaptime).\
908 # filter(PlayerCaptime.player_id==player_id).\
909 # order_by(PlayerCaptime.fastest_cap).\
912 PlayerCaptimes = namedtuple('PlayerCaptimes', ['fastest_cap', 'create_dt', 'create_dt_epoch', 'create_dt_fuzzy',
913 'player_id', 'game_id', 'map_id', 'map_name', 'server_id', 'server_name'])
915 dbquery = DBSession.query('fastest_cap', 'create_dt', 'player_id', 'game_id', 'map_id',
916 'map_name', 'server_id', 'server_name').\
918 "SELECT ct.fastest_cap, "
925 "s.name server_name "
926 "FROM player_map_captimes ct, "
930 "WHERE ct.player_id = :player_id "
931 "AND g.game_id = ct.game_id "
932 "AND g.server_id = s.server_id "
933 "AND m.map_id = ct.map_id "
934 #"ORDER BY ct.fastest_cap "
935 "ORDER BY ct.create_dt desc"
936 ).params(player_id=player_id).all()
938 player = DBSession.query(Player).filter_by(player_id=player_id).one()
942 player_captimes.append(PlayerCaptimes(
943 fastest_cap=row.fastest_cap,
944 create_dt=row.create_dt,
945 create_dt_epoch=timegm(row.create_dt.timetuple()),
946 create_dt_fuzzy=pretty_date(row.create_dt),
947 player_id=row.player_id,
950 map_name=row.map_name,
951 server_id=row.server_id,
952 server_name=row.server_name,
956 'captimes':player_captimes,
957 'player_id':player_id,
958 'player_url':request.route_url('player_info', id=player_id),
962 def player_captimes(request):
963 return player_captimes_data(request)
965 def player_captimes_json(request):
966 return player_captimes_data(request)