3 import pyramid.httpexceptions
4 import sqlalchemy as sa
5 import sqlalchemy.sql.functions as func
6 import sqlalchemy.sql.expression as expr
7 from calendar import timegm
8 from collections import namedtuple
9 from webhelpers.paginate import Page
10 from xonstat.models import *
11 from xonstat.util import page_url, to_json, pretty_date, datetime_seconds
12 from xonstat.util import is_cake_day, verify_request
13 from xonstat.views.helpers import RecentGame, recent_games_q
14 from urllib import unquote
16 log = logging.getLogger(__name__)
19 def player_index_data(request):
20 if request.params.has_key('page'):
21 current_page = request.params['page']
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())
32 players = Page(player_q, current_page, items_per_page=25, url=page_url)
34 except Exception as e:
38 return {'players':players
42 def player_index(request):
44 Provides a list of all the current players.
46 return player_index_data(request)
49 def player_index_json(request):
51 Provides a list of all the current players. JSON.
53 return [{'status':'not implemented'}]
56 def get_games_played(player_id):
58 Provides a breakdown by gametype of the games played by player_id.
60 Returns a list of namedtuples with the following members:
67 The list itself is ordered by the number of games played
69 GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
72 raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
74 "SELECT game_type_cd, "
77 "FROM (SELECT g.game_id, "
80 "WHEN g.winner = pgs.team THEN 1 "
81 "WHEN pgs.scoreboardpos = 1 THEN 1 "
85 "WHEN g.winner = pgs.team THEN 0 "
86 "WHEN pgs.scoreboardpos = 1 THEN 0 "
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()
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
107 games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
108 row.losses, win_pct))
111 overall_win_pct = float(overall_wins)/overall_games * 100
113 overall_win_pct = 0.0
115 games_played.append(GamesPlayed('overall', overall_games, overall_wins,
116 overall_losses, overall_win_pct))
118 # sort the resulting list by # of games played
119 games_played = sorted(games_played, key=lambda x:x.games)
120 games_played.reverse()
124 def get_overall_stats(player_id):
126 Provides a breakdown of stats by gametype played by player_id.
128 Returns a dictionary of namedtuples with the following members:
132 - last_played (last time the player played the game type)
133 - last_played_epoch (same as above, but in seconds since epoch)
134 - last_played_fuzzy (same as above, but in relative date)
135 - total_playing_time (total amount of time played the game type)
136 - total_playing_time_secs (same as the above, but in seconds)
137 - total_pickups (ctf only)
138 - total_captures (ctf only)
139 - cap_ratio (ctf only)
140 - total_carrier_frags (ctf only)
144 The key to the dictionary is the game type code. There is also an
145 "overall" game_type_cd which sums the totals and computes the total ratios.
147 OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
148 'k_d_ratio', 'last_played', 'last_played_epoch', 'last_played_fuzzy',
149 'total_playing_time', 'total_playing_time_secs', 'total_pickups', 'total_captures', 'cap_ratio',
150 'total_carrier_frags', 'game_type_cd', 'game_type_descr'])
152 raw_stats = DBSession.query('game_type_cd', 'game_type_descr',
153 'total_kills', 'total_deaths', 'last_played', 'total_playing_time',
154 'total_pickups', 'total_captures', 'total_carrier_frags').\
156 "SELECT g.game_type_cd, "
157 "gt.descr game_type_descr, "
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 "
167 "player_game_stats pgs "
168 "WHERE g.game_id = pgs.game_id "
169 "AND g.game_type_cd = gt.game_type_cd "
170 "AND pgs.player_id = :player_id "
171 "GROUP BY g.game_type_cd, game_type_descr "
173 "SELECT 'overall' game_type_cd, "
174 "'Overall' game_type_descr, "
175 "Sum(pgs.kills) total_kills, "
176 "Sum(pgs.deaths) total_deaths, "
177 "Max(pgs.create_dt) last_played, "
178 "Sum(pgs.alivetime) total_playing_time, "
179 "Sum(pgs.pickups) total_pickups, "
180 "Sum(pgs.captures) total_captures, "
181 "Sum(pgs.carrier_frags) total_carrier_frags "
182 "FROM player_game_stats pgs "
183 "WHERE pgs.player_id = :player_id "
184 ).params(player_id=player_id).all()
186 # 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,
215 game_type_descr=row.game_type_descr)
217 overall_stats[row.game_type_cd] = os
219 # We have to edit "overall" stats to exclude deaths in CTS.
220 # Although we still want to record deaths, they shouldn't
221 # count towards the overall K:D ratio.
222 if 'cts' in overall_stats:
223 os = overall_stats['overall']
226 k_d_ratio = float(os.total_kills)/(os.total_deaths - overall_stats['cts'].total_deaths)
230 non_cts_deaths = os.total_deaths - overall_stats['cts'].total_deaths
233 overall_stats['overall'] = OverallStats(
234 total_kills = os.total_kills,
235 total_deaths = non_cts_deaths,
236 k_d_ratio = k_d_ratio,
237 last_played = os.last_played,
238 last_played_epoch = os.last_played_epoch,
239 last_played_fuzzy = os.last_played_fuzzy,
240 total_playing_time = os.total_playing_time,
241 total_playing_time_secs = os.total_playing_time_secs,
242 total_pickups = os.total_pickups,
243 total_captures = os.total_captures,
244 cap_ratio = os.cap_ratio,
245 total_carrier_frags = os.total_carrier_frags,
246 game_type_cd = os.game_type_cd,
247 game_type_descr = os.game_type_descr)
252 def get_fav_maps(player_id, game_type_cd=None):
254 Provides a breakdown of favorite maps by gametype.
256 Returns a dictionary of namedtuples with the following members:
258 - map_name (map name)
262 The favorite map is defined as the map you've played the most
263 for the given game_type_cd.
265 The key to the dictionary is the game type code. There is also an
266 "overall" game_type_cd which is the overall favorite map. This is
267 defined as the favorite map of the game type you've played the
268 most. The input parameter game_type_cd is for this.
270 FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
272 raw_favs = DBSession.query('game_type_cd', 'map_name',
273 'map_id', 'times_played').\
275 "SELECT game_type_cd, "
279 "FROM (SELECT g.game_type_cd, "
282 "Count(*) times_played, "
285 "partition BY g.game_type_cd "
286 "ORDER BY Count(*) DESC, m.map_id ASC) rank "
288 "player_game_stats pgs, "
290 "WHERE g.game_id = pgs.game_id "
291 "AND g.map_id = m.map_id "
292 "AND pgs.player_id = :player_id "
293 "GROUP BY g.game_type_cd, "
295 "m.name) most_played "
297 "ORDER BY times_played desc "
298 ).params(player_id=player_id).all()
303 fv = FavMap(map_name=row.map_name,
305 times_played=row.times_played,
306 game_type_cd=row.game_type_cd)
308 # if we aren't given a favorite game_type_cd
309 # then the overall favorite is the one we've
311 if overall_fav is None:
312 fav_maps['overall'] = fv
313 overall_fav = fv.game_type_cd
315 # otherwise it is the favorite map from the
316 # favorite game_type_cd (provided as a param)
317 # and we'll overwrite the first dict entry
318 if game_type_cd == fv.game_type_cd:
319 fav_maps['overall'] = fv
321 fav_maps[row.game_type_cd] = fv
326 def get_ranks(player_id):
328 Provides a breakdown of the player's ranks by game type.
330 Returns a dictionary of namedtuples with the following members:
335 The key to the dictionary is the game type code. There is also an
336 "overall" game_type_cd which is the overall best rank.
338 Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
340 raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
342 "select pr.game_type_cd, pr.rank, overall.max_rank "
343 "from player_ranks pr, "
344 "(select game_type_cd, max(rank) max_rank "
346 "group by game_type_cd) overall "
347 "where pr.game_type_cd = overall.game_type_cd "
348 "and player_id = :player_id "
350 params(player_id=player_id).all()
353 found_top_rank = False
354 for row in raw_ranks:
355 rank = Rank(rank=row.rank,
356 max_rank=row.max_rank,
357 percentile=100 - 100*float(row.rank-1)/(row.max_rank-1),
358 game_type_cd=row.game_type_cd)
361 if not found_top_rank:
362 ranks['overall'] = rank
363 found_top_rank = True
364 elif rank.percentile > ranks['overall'].percentile:
365 ranks['overall'] = rank
367 ranks[row.game_type_cd] = rank
372 def get_elos(player_id):
374 Provides a breakdown of the player's elos by game type.
376 Returns a dictionary of namedtuples with the following members:
382 The key to the dictionary is the game type code. There is also an
383 "overall" game_type_cd which is the overall best rank.
385 raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
386 order_by(PlayerElo.elo.desc()).all()
389 found_max_elo = False
391 if not found_max_elo:
392 elos['overall'] = row
395 elos[row.game_type_cd] = row
400 def get_recent_games(player_id, limit=10):
402 Provides a list of recent games for a player. Uses the recent_games_q helper.
404 # recent games played in descending order
405 rgs = recent_games_q(player_id=player_id, force_player_id=True).limit(limit).all()
406 recent_games = [RecentGame(row) for row in rgs]
411 def get_recent_weapons(player_id):
413 Returns the weapons that have been used in the past 90 days
414 and also used in 5 games or more.
416 cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=90)
418 for weapon in DBSession.query(PlayerWeaponStat.weapon_cd, func.count()).\
419 filter(PlayerWeaponStat.player_id == player_id).\
420 filter(PlayerWeaponStat.create_dt > cutoff).\
421 group_by(PlayerWeaponStat.weapon_cd).\
422 having(func.count() > 4).\
424 recent_weapons.append(weapon[0])
426 return recent_weapons
429 def get_accuracy_stats(player_id, weapon_cd, games):
431 Provides accuracy for weapon_cd by player_id for the past N games.
433 # Reaching back 90 days should give us an accurate enough average
434 # We then multiply this out for the number of data points (games) to
435 # create parameters for a flot graph
437 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.hit),
438 func.sum(PlayerWeaponStat.fired)).\
439 filter(PlayerWeaponStat.player_id == player_id).\
440 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
443 avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
445 # Determine the raw accuracy (hit, fired) numbers for $games games
446 # This is then enumerated to create parameters for a flot graph
447 raw_accs = DBSession.query(PlayerWeaponStat.game_id,
448 PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
449 filter(PlayerWeaponStat.player_id == player_id).\
450 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
451 order_by(PlayerWeaponStat.game_id.desc()).\
455 # they come out in opposite order, so flip them in the right direction
459 for i in range(len(raw_accs)):
460 accs.append((raw_accs[i][0], round(float(raw_accs[i][1])/raw_accs[i][2]*100, 2)))
468 def get_damage_stats(player_id, weapon_cd, games):
470 Provides damage info for weapon_cd by player_id for the past N games.
473 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.actual),
474 func.sum(PlayerWeaponStat.hit)).\
475 filter(PlayerWeaponStat.player_id == player_id).\
476 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
479 avg = round(float(raw_avg[0])/raw_avg[1], 2)
481 # Determine the damage efficiency (hit, fired) numbers for $games games
482 # This is then enumerated to create parameters for a flot graph
483 raw_dmgs = DBSession.query(PlayerWeaponStat.game_id,
484 PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
485 filter(PlayerWeaponStat.player_id == player_id).\
486 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
487 order_by(PlayerWeaponStat.game_id.desc()).\
491 # they come out in opposite order, so flip them in the right direction
495 for i in range(len(raw_dmgs)):
496 # try to derive, unless we've hit nothing then set to 0!
498 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
502 dmgs.append((raw_dmgs[i][0], dmg))
503 except Exception as e:
510 def player_info_data(request):
511 player_id = int(request.matchdict['id'])
516 player = DBSession.query(Player).filter_by(player_id=player_id).\
517 filter(Player.active_ind == True).one()
519 games_played = get_games_played(player_id)
520 overall_stats = get_overall_stats(player_id)
521 fav_maps = get_fav_maps(player_id)
522 elos = get_elos(player_id)
523 ranks = get_ranks(player_id)
524 recent_games = get_recent_games(player_id)
525 recent_weapons = get_recent_weapons(player_id)
526 cake_day = is_cake_day(player.create_dt)
528 except Exception as e:
538 ## do not raise exceptions here (only for debugging)
541 return {'player':player,
542 'games_played':games_played,
543 'overall_stats':overall_stats,
547 'recent_games':recent_games,
548 '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 player_id = request.matchdict['player_id']
614 game_type_descr = None
616 if request.params.has_key('type'):
617 game_type_cd = request.params['type']
619 game_type_descr = DBSession.query(GameType.descr).\
620 filter(GameType.game_type_cd == game_type_cd).\
622 except Exception as e:
627 game_type_descr = None
629 if request.params.has_key('page'):
630 current_page = request.params['page']
635 player = DBSession.query(Player).\
636 filter_by(player_id=player_id).\
637 filter(Player.active_ind == True).\
640 rgs_q = recent_games_q(player_id=player.player_id,
641 force_player_id=True, game_type_cd=game_type_cd)
643 games = Page(rgs_q, current_page, items_per_page=20, url=page_url)
645 # replace the items in the canned pagination class with more rich ones
646 games.items = [RecentGame(row) for row in games.items]
648 games_played = get_games_played(player_id)
650 except Exception as e:
654 game_type_descr = None
658 'player_id':player.player_id,
661 'game_type_cd':game_type_cd,
662 'game_type_descr':game_type_descr,
663 'games_played':games_played,
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 # the incoming hashkey is double quoted, and WSGI unquotes once...
796 # hashkey = unquote(hashkey)
798 # if using request verification to obtain the hashkey
799 (idfp, status) = verify_request(request)
800 log.debug("d0_blind_id verification: idfp={0} status={1}\n".format(idfp, status))
802 log.debug("\n----- BEGIN REQUEST BODY -----\n" + request.body +
803 "----- END REQUEST BODY -----\n\n")
805 # if config is to *not* verify requests and we get nothing back, this
806 # query will return nothing and we'll 404.
808 player = DBSession.query(Player).\
809 filter(Player.player_id == Hashkey.player_id).\
810 filter(Player.active_ind == True).\
811 filter(Hashkey.hashkey == idfp).one()
813 games_played = get_games_played(player.player_id)
814 overall_stats = get_overall_stats(player.player_id)
815 fav_maps = get_fav_maps(player.player_id)
816 elos = get_elos(player.player_id)
817 ranks = get_ranks(player.player_id)
818 most_recent_game = get_recent_games(player.player_id, 1)[0]
820 except Exception as e:
821 raise pyramid.httpexceptions.HTTPNotFound
823 return {'player':player,
825 'games_played':games_played,
826 'overall_stats':overall_stats,
830 'most_recent_game':most_recent_game,
834 def player_hashkey_info_json(request):
836 Provides detailed information on a specific player. JSON.
839 # All player_info fields are converted into JSON-formattable dictionaries
840 player_info = player_hashkey_info_data(request)
842 player = player_info['player'].to_dict()
845 for game in player_info['games_played']:
846 games_played[game.game_type_cd] = to_json(game)
849 for gt,stats in player_info['overall_stats'].items():
850 overall_stats[gt] = to_json(stats)
853 for gt,elo in player_info['elos'].items():
854 elos[gt] = to_json(elo.to_dict())
857 for gt,rank in player_info['ranks'].items():
858 ranks[gt] = to_json(rank)
861 for gt,mapinfo in player_info['fav_maps'].items():
862 fav_maps[gt] = to_json(mapinfo)
864 most_recent_game = to_json(player_info['most_recent_game'])
869 'games_played': games_played,
870 'overall_stats': overall_stats,
871 'fav_maps': fav_maps,
874 'most_recent_game': most_recent_game,
878 def player_hashkey_info_text(request):
880 Provides detailed information on a specific player. Plain text.
883 now = timegm(datetime.datetime.utcnow().timetuple())
885 # All player_info fields are converted into JSON-formattable dictionaries
886 player_info = player_hashkey_info_data(request)
888 # gather all of the data up into aggregate structures
889 player = player_info['player']
890 games_played = player_info['games_played']
891 overall_stats = player_info['overall_stats']
892 elos = player_info['elos']
893 ranks = player_info['ranks']
894 fav_maps = player_info['fav_maps']
895 most_recent_game = player_info['most_recent_game']
897 # one-offs for things needing conversion for text/plain
898 player_joined = timegm(player.create_dt.timetuple())
899 player_joined_dt = player.create_dt
900 alivetime = int(datetime_seconds(overall_stats['overall'].total_playing_time))
902 # this is a plain text response, if we don't do this here then
903 # Pyramid will assume html
904 request.response.content_type = 'text/plain'
910 'hashkey': player_info['hashkey'],
911 'player_joined': player_joined,
912 'player_joined_dt': player_joined_dt,
913 'games_played': games_played,
914 'overall_stats': overall_stats,
915 'alivetime': alivetime,
916 'fav_maps': fav_maps,
919 'most_recent_game': most_recent_game,
923 def player_elo_info_data(request):
925 Provides elo information on a specific player. Raw data is returned.
927 (idfp, status) = verify_request(request)
928 log.debug("d0_blind_id verification: idfp={0} status={1}\n".format(idfp, status))
930 log.debug("\n----- BEGIN REQUEST BODY -----\n" + request.body +
931 "----- END REQUEST BODY -----\n\n")
933 hashkey = request.matchdict['hashkey']
935 # the incoming hashkey is double quoted, and WSGI unquotes once...
936 hashkey = unquote(hashkey)
939 player = DBSession.query(Player).\
940 filter(Player.player_id == Hashkey.player_id).\
941 filter(Player.active_ind == True).\
942 filter(Hashkey.hashkey == hashkey).one()
944 elos = get_elos(player.player_id)
946 except Exception as e:
948 raise pyramid.httpexceptions.HTTPNotFound
957 def player_elo_info_json(request):
959 Provides elo information on a specific player. JSON.
961 elo_info = player_elo_info_data(request)
963 player = player_info['player'].to_dict()
966 for gt, elo in elo_info['elos'].items():
967 elos[gt] = to_json(elo.to_dict())
976 def player_elo_info_text(request):
978 Provides elo information on a specific player. Plain text.
981 now = timegm(datetime.datetime.utcnow().timetuple())
983 # All player_info fields are converted into JSON-formattable dictionaries
984 elo_info = player_elo_info_data(request)
986 # this is a plain text response, if we don't do this here then
987 # Pyramid will assume html
988 request.response.content_type = 'text/plain'
993 'hashkey': elo_info['hashkey'],
994 'player': elo_info['player'],
995 'elos': elo_info['elos'],
999 def player_captimes_data(request):
1000 player_id = int(request.matchdict['player_id'])
1004 if request.params.has_key('page'):
1005 current_page = request.params['page']
1009 PlayerCaptimes = namedtuple('PlayerCaptimes', ['fastest_cap',
1010 'create_dt', 'create_dt_epoch', 'create_dt_fuzzy',
1011 'player_id', 'game_id', 'map_id', 'map_name', 'server_id', 'server_name'])
1013 player = DBSession.query(Player).filter_by(player_id=player_id).one()
1015 #pct_q = DBSession.query('fastest_cap', 'create_dt', 'player_id', 'game_id', 'map_id',
1016 # 'map_name', 'server_id', 'server_name').\
1018 # "SELECT ct.fastest_cap, "
1023 # "m.name map_name, "
1025 # "s.name server_name "
1026 # "FROM player_map_captimes ct, "
1030 # "WHERE ct.player_id = :player_id "
1031 # "AND g.game_id = ct.game_id "
1032 # "AND g.server_id = s.server_id "
1033 # "AND m.map_id = ct.map_id "
1034 # #"ORDER BY ct.fastest_cap "
1035 # "ORDER BY ct.create_dt desc"
1036 # ).params(player_id=player_id)
1039 pct_q = DBSession.query(PlayerCaptime.fastest_cap, PlayerCaptime.create_dt,
1040 PlayerCaptime.player_id, PlayerCaptime.game_id, PlayerCaptime.map_id,
1041 Map.name.label('map_name'), Game.server_id, Server.name.label('server_name')).\
1042 filter(PlayerCaptime.player_id==player_id).\
1043 filter(PlayerCaptime.game_id==Game.game_id).\
1044 filter(PlayerCaptime.map_id==Map.map_id).\
1045 filter(Game.server_id==Server.server_id).\
1046 order_by(expr.asc(PlayerCaptime.fastest_cap)) # or PlayerCaptime.create_dt
1048 player_captimes = Page(pct_q, current_page, items_per_page=20, url=page_url)
1050 # replace the items in the canned pagination class with more rich ones
1051 player_captimes.items = [PlayerCaptimes(
1052 fastest_cap=row.fastest_cap,
1053 create_dt=row.create_dt,
1054 create_dt_epoch=timegm(row.create_dt.timetuple()),
1055 create_dt_fuzzy=pretty_date(row.create_dt),
1056 player_id=row.player_id,
1057 game_id=row.game_id,
1059 map_name=row.map_name,
1060 server_id=row.server_id,
1061 server_name=row.server_name
1062 ) for row in player_captimes.items]
1064 except Exception as e:
1066 player_captimes = None
1069 'player_id':player_id,
1071 'captimes':player_captimes,
1072 #'player_url':request.route_url('player_info', id=player_id),
1076 def player_captimes(request):
1077 return player_captimes_data(request)
1080 def player_captimes_json(request):
1081 return player_captimes_data(request)
1084 def player_weaponstats_data_json(request):
1085 player_id = request.matchdict["id"]
1089 game_type_cd = request.params.get("game_type", None)
1090 if game_type_cd == "overall":
1094 if request.params.has_key("limit"):
1095 limit = int(request.params["limit"])
1102 games_raw = DBSession.query(sa.distinct(Game.game_id)).\
1103 filter(Game.game_id == PlayerWeaponStat.game_id).\
1104 filter(PlayerWeaponStat.player_id == player_id)
1106 if game_type_cd is not None:
1107 games_raw = games_raw.filter(Game.game_type_cd == game_type_cd)
1109 games_raw = games_raw.order_by(Game.game_id.desc()).limit(limit).all()
1111 weapon_stats_raw = DBSession.query(PlayerWeaponStat).\
1112 filter(PlayerWeaponStat.player_id == player_id).\
1113 filter(PlayerWeaponStat.game_id.in_(games_raw)).all()
1115 # NVD3 expects data points for all weapons used across the
1116 # set of games *for each* point on the x axis. This means populating
1117 # zero-valued weapon stat entries for games where a weapon was not
1118 # used in that game, but was used in another game for the set
1119 games_to_weapons = {}
1122 for ws in weapon_stats_raw:
1123 if ws.game_id not in games_to_weapons:
1124 games_to_weapons[ws.game_id] = [ws.weapon_cd]
1126 games_to_weapons[ws.game_id].append(ws.weapon_cd)
1128 weapons_used[ws.weapon_cd] = weapons_used.get(ws.weapon_cd, 0) + 1
1129 sum_avgs[ws.weapon_cd] = sum_avgs.get(ws.weapon_cd, 0) + float(ws.hit)/float(ws.fired)
1131 for game_id in games_to_weapons.keys():
1132 for weapon_cd in set(weapons_used.keys()) - set(games_to_weapons[game_id]):
1133 weapon_stats_raw.append(PlayerWeaponStat(player_id=player_id,
1134 game_id=game_id, weapon_cd=weapon_cd))
1136 # averages for the weapons used in the range
1138 for w in weapons_used.keys():
1139 avgs[w] = round(sum_avgs[w]/float(weapons_used[w])*100, 2)
1141 weapon_stats_raw = sorted(weapon_stats_raw, key = lambda x: x.game_id)
1142 games = sorted(games_to_weapons.keys())
1143 weapon_stats = [ws.to_dict() for ws in weapon_stats_raw]
1146 "weapon_stats": weapon_stats,
1147 "weapons_used": weapons_used.keys(),