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 "
93 "AND g.players @> ARRAY[: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()
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)
146 The key to the dictionary is the game type code. There is also an
147 "overall" game_type_cd which sums the totals and computes the total ratios.
149 OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
150 'k_d_ratio', 'last_played', 'last_played_epoch', 'last_played_fuzzy',
151 'total_playing_time', 'total_playing_time_secs', 'total_pickups', 'total_captures', 'cap_ratio',
152 'total_carrier_frags', 'game_type_cd', 'game_type_descr'])
154 raw_stats = DBSession.query('game_type_cd', 'game_type_descr',
155 'total_kills', 'total_deaths', 'last_played', 'total_playing_time',
156 'total_pickups', 'total_captures', 'total_carrier_frags').\
158 "SELECT g.game_type_cd, "
159 "gt.descr game_type_descr, "
160 "Sum(pgs.kills) total_kills, "
161 "Sum(pgs.deaths) total_deaths, "
162 "Max(pgs.create_dt) last_played, "
163 "Sum(pgs.alivetime) total_playing_time, "
164 "Sum(pgs.pickups) total_pickups, "
165 "Sum(pgs.captures) total_captures, "
166 "Sum(pgs.carrier_frags) total_carrier_frags "
169 "player_game_stats pgs "
170 "WHERE g.game_id = pgs.game_id "
171 "AND g.game_type_cd = gt.game_type_cd "
172 "AND g.players @> ARRAY[:player_id] "
173 "AND pgs.player_id = :player_id "
174 "GROUP BY g.game_type_cd, game_type_descr "
176 "SELECT 'overall' game_type_cd, "
177 "'Overall' game_type_descr, "
178 "Sum(pgs.kills) total_kills, "
179 "Sum(pgs.deaths) total_deaths, "
180 "Max(pgs.create_dt) last_played, "
181 "Sum(pgs.alivetime) total_playing_time, "
182 "Sum(pgs.pickups) total_pickups, "
183 "Sum(pgs.captures) total_captures, "
184 "Sum(pgs.carrier_frags) total_carrier_frags "
185 "FROM player_game_stats pgs "
186 "WHERE pgs.player_id = :player_id "
187 ).params(player_id=player_id).all()
189 # to be indexed by game_type_cd
192 for row in raw_stats:
193 # individual gametype ratio calculations
195 k_d_ratio = float(row.total_kills)/row.total_deaths
200 cap_ratio = float(row.total_captures)/row.total_pickups
204 # everything else is untouched or "raw"
205 os = OverallStats(total_kills=row.total_kills,
206 total_deaths=row.total_deaths,
208 last_played=row.last_played,
209 last_played_epoch=timegm(row.last_played.timetuple()),
210 last_played_fuzzy=pretty_date(row.last_played),
211 total_playing_time=row.total_playing_time,
212 total_playing_time_secs=int(datetime_seconds(row.total_playing_time)),
213 total_pickups=row.total_pickups,
214 total_captures=row.total_captures,
216 total_carrier_frags=row.total_carrier_frags,
217 game_type_cd=row.game_type_cd,
218 game_type_descr=row.game_type_descr)
220 overall_stats[row.game_type_cd] = os
222 # We have to edit "overall" stats to exclude deaths in CTS.
223 # Although we still want to record deaths, they shouldn't
224 # count towards the overall K:D ratio.
225 if 'cts' in overall_stats:
226 os = overall_stats['overall']
229 k_d_ratio = float(os.total_kills)/(os.total_deaths - overall_stats['cts'].total_deaths)
233 non_cts_deaths = os.total_deaths - overall_stats['cts'].total_deaths
236 overall_stats['overall'] = OverallStats(
237 total_kills = os.total_kills,
238 total_deaths = non_cts_deaths,
239 k_d_ratio = k_d_ratio,
240 last_played = os.last_played,
241 last_played_epoch = os.last_played_epoch,
242 last_played_fuzzy = os.last_played_fuzzy,
243 total_playing_time = os.total_playing_time,
244 total_playing_time_secs = os.total_playing_time_secs,
245 total_pickups = os.total_pickups,
246 total_captures = os.total_captures,
247 cap_ratio = os.cap_ratio,
248 total_carrier_frags = os.total_carrier_frags,
249 game_type_cd = os.game_type_cd,
250 game_type_descr = os.game_type_descr)
255 def get_fav_maps(player_id, game_type_cd=None):
257 Provides a breakdown of favorite maps by gametype.
259 Returns a dictionary of namedtuples with the following members:
261 - map_name (map name)
265 The favorite map is defined as the map you've played the most
266 for the given game_type_cd.
268 The key to the dictionary is the game type code. There is also an
269 "overall" game_type_cd which is the overall favorite map. This is
270 defined as the favorite map of the game type you've played the
271 most. The input parameter game_type_cd is for this.
273 FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
275 raw_favs = DBSession.query('game_type_cd', 'map_name',
276 'map_id', 'times_played').\
278 "SELECT game_type_cd, "
282 "FROM (SELECT g.game_type_cd, "
285 "Count(*) times_played, "
288 "partition BY g.game_type_cd "
289 "ORDER BY Count(*) DESC, m.map_id ASC) rank "
291 "player_game_stats pgs, "
293 "WHERE g.game_id = pgs.game_id "
294 "AND g.map_id = m.map_id "
295 "AND g.players @> ARRAY[:player_id]"
296 "AND pgs.player_id = :player_id "
297 "GROUP BY g.game_type_cd, "
299 "m.name) most_played "
301 "ORDER BY times_played desc "
302 ).params(player_id=player_id).all()
307 fv = FavMap(map_name=row.map_name,
309 times_played=row.times_played,
310 game_type_cd=row.game_type_cd)
312 # if we aren't given a favorite game_type_cd
313 # then the overall favorite is the one we've
315 if overall_fav is None:
316 fav_maps['overall'] = fv
317 overall_fav = fv.game_type_cd
319 # otherwise it is the favorite map from the
320 # favorite game_type_cd (provided as a param)
321 # and we'll overwrite the first dict entry
322 if game_type_cd == fv.game_type_cd:
323 fav_maps['overall'] = fv
325 fav_maps[row.game_type_cd] = fv
330 def get_ranks(player_id):
332 Provides a breakdown of the player's ranks by game type.
334 Returns a dictionary of namedtuples with the following members:
339 The key to the dictionary is the game type code. There is also an
340 "overall" game_type_cd which is the overall best rank.
342 Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
344 raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
346 "select pr.game_type_cd, pr.rank, overall.max_rank "
347 "from player_ranks pr, "
348 "(select game_type_cd, max(rank) max_rank "
350 "group by game_type_cd) overall "
351 "where pr.game_type_cd = overall.game_type_cd "
353 "and player_id = :player_id "
355 params(player_id=player_id).all()
358 found_top_rank = False
359 for row in raw_ranks:
360 rank = Rank(rank=row.rank,
361 max_rank=row.max_rank,
362 percentile=100 - 100*float(row.rank-1)/(row.max_rank-1),
363 game_type_cd=row.game_type_cd)
366 if not found_top_rank:
367 ranks['overall'] = rank
368 found_top_rank = True
369 elif rank.percentile > ranks['overall'].percentile:
370 ranks['overall'] = rank
372 ranks[row.game_type_cd] = rank
377 def get_elos(player_id):
379 Provides a breakdown of the player's elos by game type.
381 Returns a dictionary of namedtuples with the following members:
387 The key to the dictionary is the game type code. There is also an
388 "overall" game_type_cd which is the overall best rank.
390 raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
391 order_by(PlayerElo.elo.desc()).all()
394 found_max_elo = False
396 if not found_max_elo:
397 elos['overall'] = row
400 elos[row.game_type_cd] = row
405 def get_recent_games(player_id, limit=10):
407 Provides a list of recent games for a player. Uses the recent_games_q helper.
409 # recent games played in descending order
410 rgs = recent_games_q(player_id=player_id, force_player_id=True).limit(limit).all()
411 recent_games = [RecentGame(row) for row in rgs]
416 def get_accuracy_stats(player_id, weapon_cd, games):
418 Provides accuracy for weapon_cd by player_id for the past N games.
420 # Reaching back 90 days should give us an accurate enough average
421 # We then multiply this out for the number of data points (games) to
422 # create parameters for a flot graph
424 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.hit),
425 func.sum(PlayerWeaponStat.fired)).\
426 filter(PlayerWeaponStat.player_id == player_id).\
427 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
430 avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
432 # Determine the raw accuracy (hit, fired) numbers for $games games
433 # This is then enumerated to create parameters for a flot graph
434 raw_accs = DBSession.query(PlayerWeaponStat.game_id,
435 PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
436 filter(PlayerWeaponStat.player_id == player_id).\
437 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
438 order_by(PlayerWeaponStat.game_id.desc()).\
442 # they come out in opposite order, so flip them in the right direction
446 for i in range(len(raw_accs)):
447 accs.append((raw_accs[i][0], round(float(raw_accs[i][1])/raw_accs[i][2]*100, 2)))
455 def get_damage_stats(player_id, weapon_cd, games):
457 Provides damage info for weapon_cd by player_id for the past N games.
460 raw_avg = DBSession.query(func.sum(PlayerWeaponStat.actual),
461 func.sum(PlayerWeaponStat.hit)).\
462 filter(PlayerWeaponStat.player_id == player_id).\
463 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
466 avg = round(float(raw_avg[0])/raw_avg[1], 2)
468 # Determine the damage efficiency (hit, fired) numbers for $games games
469 # This is then enumerated to create parameters for a flot graph
470 raw_dmgs = DBSession.query(PlayerWeaponStat.game_id,
471 PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
472 filter(PlayerWeaponStat.player_id == player_id).\
473 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
474 order_by(PlayerWeaponStat.game_id.desc()).\
478 # they come out in opposite order, so flip them in the right direction
482 for i in range(len(raw_dmgs)):
483 # try to derive, unless we've hit nothing then set to 0!
485 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
489 dmgs.append((raw_dmgs[i][0], dmg))
490 except Exception as e:
497 def get_player_medals(player_id):
498 """Retrieves the list of medals the player has received from tournaments or
501 medals = DBSession.query(PlayerMedal)\
502 .filter(PlayerMedal.player_id==player_id)\
503 .order_by(PlayerMedal.place)\
504 .order_by(PlayerMedal.create_dt)\
509 except Exception as e:
514 def player_info_data(request):
515 player_id = int(request.matchdict['id'])
520 player = DBSession.query(Player).filter_by(player_id=player_id).\
521 filter(Player.active_ind == True).one()
523 games_played = get_games_played(player_id)
524 overall_stats = get_overall_stats(player_id)
525 fav_maps = get_fav_maps(player_id)
526 elos = get_elos(player_id)
527 ranks = get_ranks(player_id)
528 medals = get_player_medals(player_id)
529 recent_games = get_recent_games(player_id)
530 cake_day = is_cake_day(player.create_dt)
532 except Exception as e:
533 raise pyramid.httpexceptions.HTTPNotFound
535 ## do not raise application exceptions here (only for debugging)
538 return {'player':player,
539 'games_played':games_played,
540 'overall_stats':overall_stats,
545 'recent_games':recent_games,
550 def player_info(request):
552 Provides detailed information on a specific player
554 return player_info_data(request)
557 def player_info_json(request):
559 Provides detailed information on a specific player. JSON.
562 # All player_info fields are converted into JSON-formattable dictionaries
563 player_info = player_info_data(request)
565 player = player_info['player'].to_dict()
568 for game in player_info['games_played']:
569 games_played[game.game_type_cd] = to_json(game)
572 for gt,stats in player_info['overall_stats'].items():
573 overall_stats[gt] = to_json(stats)
576 for gt,elo in player_info['elos'].items():
577 elos[gt] = to_json(elo.to_dict())
580 for gt,rank in player_info['ranks'].items():
581 ranks[gt] = to_json(rank)
584 for gt,mapinfo in player_info['fav_maps'].items():
585 fav_maps[gt] = to_json(mapinfo)
587 recent_games = [g.to_dict() for g in player_info['recent_games']]
591 'games_played': games_played,
592 'overall_stats': overall_stats,
593 'fav_maps': fav_maps,
596 'recent_games': recent_games,
600 def player_game_index_data(request):
602 player_id = int(request.matchdict['player_id'])
607 game_type_descr = None
609 if request.params.has_key('type'):
610 game_type_cd = request.params['type']
612 game_type_descr = DBSession.query(GameType.descr).\
613 filter(GameType.game_type_cd == game_type_cd).\
615 except Exception as e:
620 game_type_descr = None
622 if request.params.has_key('page'):
623 current_page = request.params['page']
628 player = DBSession.query(Player).\
629 filter_by(player_id=player_id).\
630 filter(Player.active_ind == True).\
633 rgs_q = recent_games_q(player_id=player.player_id,
634 force_player_id=True, game_type_cd=game_type_cd)
636 games = Page(rgs_q, current_page, items_per_page=20, url=page_url)
638 # replace the items in the canned pagination class with more rich ones
639 games.items = [RecentGame(row) for row in games.items]
641 games_played = get_games_played(player_id)
643 except Exception as e:
648 game_type_descr = None
652 'player_id':player.player_id,
655 'game_type_cd':game_type_cd,
656 'game_type_descr':game_type_descr,
657 'games_played':games_played,
661 def player_game_index(request):
663 Provides an index of the games in which a particular
664 player was involved. This is ordered by game_id, with
665 the most recent game_ids first. Paginated.
667 return player_game_index_data(request)
670 def player_game_index_json(request):
672 Provides an index of the games in which a particular
673 player was involved. This is ordered by game_id, with
674 the most recent game_ids first. Paginated. JSON.
676 return [{'status':'not implemented'}]
679 def player_accuracy_data(request):
680 player_id = request.matchdict['id']
681 allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
685 if request.params.has_key('weapon'):
686 if request.params['weapon'] in allowed_weapons:
687 weapon_cd = request.params['weapon']
689 if request.params.has_key('games'):
691 games = request.params['games']
700 (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
702 # if we don't have enough data for the given weapon
703 if len(accs) < games:
707 'player_id':player_id,
708 'player_url':request.route_url('player_info', id=player_id),
716 def player_accuracy(request):
718 Provides the accuracy for the given weapon. (JSON only)
720 return player_accuracy_data(request)
723 def player_accuracy_json(request):
725 Provides a JSON response representing the accuracy for the given weapon.
728 weapon = which weapon to display accuracy for. Valid values are 'nex',
729 'shotgun', 'uzi', and 'minstanex'.
730 games = over how many games to display accuracy. Can be up to 50.
732 return player_accuracy_data(request)
735 def player_damage_data(request):
736 player_id = request.matchdict['id']
737 allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
738 'rocketlauncher', 'laser']
739 weapon_cd = 'rocketlauncher'
742 if request.params.has_key('weapon'):
743 if request.params['weapon'] in allowed_weapons:
744 weapon_cd = request.params['weapon']
746 if request.params.has_key('games'):
748 games = request.params['games']
757 (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
759 # if we don't have enough data for the given weapon
760 if len(dmgs) < games:
764 'player_id':player_id,
765 'player_url':request.route_url('player_info', id=player_id),
773 def player_damage_json(request):
775 Provides a JSON response representing the damage for the given weapon.
778 weapon = which weapon to display damage for. Valid values are
779 'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
781 games = over how many games to display damage. Can be up to 50.
783 return player_damage_data(request)
786 def player_hashkey_info_data(request):
787 # hashkey = request.matchdict['hashkey']
789 # the incoming hashkey is double quoted, and WSGI unquotes once...
790 # hashkey = unquote(hashkey)
792 # if using request verification to obtain the hashkey
793 (idfp, status) = verify_request(request)
794 log.debug("d0_blind_id verification: idfp={0} status={1}\n".format(idfp, status))
796 log.debug("\n----- BEGIN REQUEST BODY -----\n" + request.body +
797 "----- END REQUEST BODY -----\n\n")
799 # if config is to *not* verify requests and we get nothing back, this
800 # query will return nothing and we'll 404.
802 player = DBSession.query(Player).\
803 filter(Player.player_id == Hashkey.player_id).\
804 filter(Player.active_ind == True).\
805 filter(Hashkey.hashkey == idfp).one()
807 games_played = get_games_played(player.player_id)
808 overall_stats = get_overall_stats(player.player_id)
809 fav_maps = get_fav_maps(player.player_id)
810 elos = get_elos(player.player_id)
811 ranks = get_ranks(player.player_id)
812 most_recent_game = get_recent_games(player.player_id, 1)[0]
814 except Exception as e:
815 raise pyramid.httpexceptions.HTTPNotFound
817 return {'player':player,
819 'games_played':games_played,
820 'overall_stats':overall_stats,
824 'most_recent_game':most_recent_game,
828 def player_hashkey_info_json(request):
830 Provides detailed information on a specific player. JSON.
833 # All player_info fields are converted into JSON-formattable dictionaries
834 player_info = player_hashkey_info_data(request)
836 player = player_info['player'].to_dict()
839 for game in player_info['games_played']:
840 games_played[game.game_type_cd] = to_json(game)
843 for gt,stats in player_info['overall_stats'].items():
844 overall_stats[gt] = to_json(stats)
847 for gt,elo in player_info['elos'].items():
848 elos[gt] = to_json(elo.to_dict())
851 for gt,rank in player_info['ranks'].items():
852 ranks[gt] = to_json(rank)
855 for gt,mapinfo in player_info['fav_maps'].items():
856 fav_maps[gt] = to_json(mapinfo)
858 most_recent_game = to_json(player_info['most_recent_game'])
863 'games_played': games_played,
864 'overall_stats': overall_stats,
865 'fav_maps': fav_maps,
868 'most_recent_game': most_recent_game,
872 def player_hashkey_info_text(request):
874 Provides detailed information on a specific player. Plain text.
877 now = timegm(datetime.datetime.utcnow().timetuple())
879 # All player_info fields are converted into JSON-formattable dictionaries
880 player_info = player_hashkey_info_data(request)
882 # gather all of the data up into aggregate structures
883 player = player_info['player']
884 games_played = player_info['games_played']
885 overall_stats = player_info['overall_stats']
886 elos = player_info['elos']
887 ranks = player_info['ranks']
888 fav_maps = player_info['fav_maps']
889 most_recent_game = player_info['most_recent_game']
891 # one-offs for things needing conversion for text/plain
892 player_joined = timegm(player.create_dt.timetuple())
893 player_joined_dt = player.create_dt
894 alivetime = int(datetime_seconds(overall_stats['overall'].total_playing_time))
896 # this is a plain text response, if we don't do this here then
897 # Pyramid will assume html
898 request.response.content_type = 'text/plain'
904 'hashkey': player_info['hashkey'],
905 'player_joined': player_joined,
906 'player_joined_dt': player_joined_dt,
907 'games_played': games_played,
908 'overall_stats': overall_stats,
909 'alivetime': alivetime,
910 'fav_maps': fav_maps,
913 'most_recent_game': most_recent_game,
917 def player_elo_info_data(request):
919 Provides elo information on a specific player. Raw data is returned.
921 (idfp, status) = verify_request(request)
922 log.debug("d0_blind_id verification: idfp={0} status={1}\n".format(idfp, status))
924 log.debug("\n----- BEGIN REQUEST BODY -----\n" + request.body +
925 "----- END REQUEST BODY -----\n\n")
927 hashkey = request.matchdict['hashkey']
929 # the incoming hashkey is double quoted, and WSGI unquotes once...
930 hashkey = unquote(hashkey)
933 player = DBSession.query(Player).\
934 filter(Player.player_id == Hashkey.player_id).\
935 filter(Player.active_ind == True).\
936 filter(Hashkey.hashkey == hashkey).one()
938 elos = get_elos(player.player_id)
940 except Exception as e:
942 raise pyramid.httpexceptions.HTTPNotFound
951 def player_elo_info_json(request):
953 Provides elo information on a specific player. JSON.
955 elo_info = player_elo_info_data(request)
957 player = player_info['player'].to_dict()
960 for gt, elo in elo_info['elos'].items():
961 elos[gt] = to_json(elo.to_dict())
970 def player_elo_info_text(request):
972 Provides elo information on a specific player. Plain text.
975 now = timegm(datetime.datetime.utcnow().timetuple())
977 # All player_info fields are converted into JSON-formattable dictionaries
978 elo_info = player_elo_info_data(request)
980 # this is a plain text response, if we don't do this here then
981 # Pyramid will assume html
982 request.response.content_type = 'text/plain'
987 'hashkey': elo_info['hashkey'],
988 'player': elo_info['player'],
989 'elos': elo_info['elos'],
993 def player_captimes_data(request):
994 player_id = int(request.matchdict['player_id'])
998 page = request.params.get("page", 1)
1000 sort = request.params.get("sort", "create_dt")
1003 player = DBSession.query(Player).filter_by(player_id=player_id).one()
1005 pct_q = DBSession.query(PlayerCaptime.fastest_cap, PlayerCaptime.create_dt,
1006 PlayerCaptime.player_id, PlayerCaptime.game_id, PlayerCaptime.map_id,
1007 Map.name.label('map_name'), Game.server_id, Server.name.label('server_name')).\
1008 filter(PlayerCaptime.player_id==player_id).\
1009 filter(PlayerCaptime.game_id==Game.game_id).\
1010 filter(PlayerCaptime.map_id==Map.map_id).\
1011 filter(Game.server_id==Server.server_id)
1013 if sort == "fastest":
1014 pct_q = pct_q.order_by(PlayerCaptime.fastest_cap)
1017 pct_q = pct_q.order_by(expr.desc(PlayerCaptime.create_dt))
1019 except Exception as e:
1020 raise pyramid.httpexceptions.HTTPNotFound
1022 captimes = Page(pct_q, page, items_per_page=20, url=page_url)
1024 # replace the items in the canned pagination class with more rich ones
1025 captimes.items = [PlayerCapTime(row) for row in captimes.items]
1028 "player_id" : player_id,
1030 "captimes" : captimes,
1036 def player_captimes(request):
1037 return player_captimes_data(request)
1040 def player_captimes_json(request):
1041 data = player_captimes_data(request)
1042 page = request.params.get("page", 1)
1044 # perform any necessary JSON conversions
1045 player_id = data["player_id"]
1046 player = data["player"].to_dict()
1047 captimes = [ct.to_dict() for ct in data["captimes"].items]
1051 "captimes" : captimes,
1056 def player_weaponstats_data_json(request):
1057 player_id = int(request.matchdict["id"])
1061 game_type_cd = request.params.get("game_type", None)
1062 if game_type_cd == "overall":
1066 if request.params.has_key("limit"):
1067 limit = int(request.params["limit"])
1075 # the game_ids of the most recently played ones
1076 # of the given game type is used for a subquery
1077 games_list = DBSession.query(Game.game_id).\
1078 filter(Game.players.contains([player_id]))
1080 if game_type_cd is not None:
1081 games_list = games_list.filter(Game.game_type_cd == game_type_cd)
1083 games_list = games_list.order_by(Game.game_id.desc()).limit(limit)
1085 weapon_stats_raw = DBSession.query(PlayerWeaponStat).\
1086 filter(PlayerWeaponStat.player_id == player_id).\
1087 filter(PlayerWeaponStat.game_id.in_(games_list)).\
1090 games_to_weapons = {}
1093 for ws in weapon_stats_raw:
1094 if ws.game_id not in games_to_weapons:
1095 games_to_weapons[ws.game_id] = [ws.weapon_cd]
1097 games_to_weapons[ws.game_id].append(ws.weapon_cd)
1099 weapons_used[ws.weapon_cd] = weapons_used.get(ws.weapon_cd, 0) + 1
1100 sum_avgs[ws.weapon_cd] = sum_avgs.get(ws.weapon_cd, 0) + float(ws.hit)/float(ws.fired)
1102 # Creating zero-valued weapon stat entries for games where a weapon was not
1103 # used in that game, but was used in another game for the set. This makes
1104 # the charts look smoother
1105 for game_id in games_to_weapons.keys():
1106 for weapon_cd in set(weapons_used.keys()) - set(games_to_weapons[game_id]):
1107 weapon_stats_raw.append(PlayerWeaponStat(player_id=player_id,
1108 game_id=game_id, weapon_cd=weapon_cd))
1110 # averages for the weapons used in the range
1112 for w in weapons_used.keys():
1113 avgs[w] = round(sum_avgs[w]/float(weapons_used[w])*100, 2)
1115 weapon_stats_raw = sorted(weapon_stats_raw, key = lambda x: x.game_id)
1116 games = sorted(games_to_weapons.keys())
1117 weapon_stats = [ws.to_dict() for ws in weapon_stats_raw]
1120 "weapon_stats": weapon_stats,
1121 "weapons_used": weapons_used.keys(),
1127 def player_versus_data(request):
1129 p1_id = int(request.params.get("p1", None))
1130 p2_id = int(request.params.get("p2", None))
1135 players = DBSession.query(Player).filter(sa.or_(Player.player_id ==
1136 p1_id, Player.player_id == p2_id)).order_by(Player.player_id).all()
1139 if len(players) < 2:
1140 raise Exception("Not enough players found.")
1142 # assign the players from the array retrieved above
1143 if players[0].player_id == p1_id:
1150 # note that wins and losses are from p1's perspective
1151 win_loss_sql = """select win_loss, count(1)
1154 when pgsp1.score >= pgsp2.score then 'win'
1157 from games g join player_game_stats pgsp1
1158 on g.game_id = pgsp1.game_id and pgsp1.player_id = :p1
1159 join player_game_stats pgsp2
1160 on g.game_id = pgsp2.game_id and pgsp2.player_id = :p2
1161 where g.players @> ARRAY[:p1,:p2]
1162 and g.game_type_cd = 'duel'
1163 and pgsp1.create_dt between g.create_dt - interval '1 hour'
1164 and g.create_dt + interval '1 hour'
1165 and pgsp2.create_dt between g.create_dt - interval '1 hour'
1166 and g.create_dt + interval '1 hour'
1171 wins_losses = DBSession.query("win_loss", "count").\
1172 from_statement(win_loss_sql).\
1173 params(p1=p1_id, p2=p2_id).all()
1175 for row in wins_losses:
1176 if row.win_loss == "win":
1178 elif row.win_loss == "loss":
1181 # grab the 20 most recent games between the two
1182 rgs_raw = recent_games_q(player_id=p1_id, player_id_2=p2_id,
1183 game_type_cd="duel").limit(20).all()
1185 rgs = [RecentGame(row) for row in rgs_raw]
1187 except Exception as e:
1203 "p1_wins" : p1_wins,
1204 "p2_wins" : p2_wins,
1205 "recent_games" : rgs,
1209 def player_versus(request):
1210 return player_versus_data(request)