Add a hashkey view similar to the player_info JSON one.
[xonotic/xonstat.git] / xonstat / views / player.py
1 import datetime
2 import json
3 import logging
4 import re
5 import sqlalchemy as sa
6 import sqlalchemy.sql.functions as func
7 import time
8 from 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
16
17 log = logging.getLogger(__name__)
18
19
20 def player_index_data(request):
21     if request.params.has_key('page'):
22         current_page = request.params['page']
23     else:
24         current_page = 1
25
26     try:
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())
32
33         players = Page(player_q, current_page, items_per_page=10, url=page_url)
34
35     except Exception as e:
36         players = None
37         raise e
38
39     return {'players':players
40            }
41
42
43 def player_index(request):
44     """
45     Provides a list of all the current players.
46     """
47     return player_index_data(request)
48
49
50 def player_index_json(request):
51     """
52     Provides a list of all the current players. JSON.
53     """
54     return [{'status':'not implemented'}]
55
56
57 def get_games_played(player_id):
58     """
59     Provides a breakdown by gametype of the games played by player_id.
60
61     Returns a list of namedtuples with the following members:
62         - game_type_cd
63         - games
64         - wins
65         - losses
66         - win_pct
67
68     The list itself is ordered by the number of games played
69     """
70     GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
71         'losses', 'win_pct'])
72
73     raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
74             from_statement(
75                 "SELECT game_type_cd, "
76                        "SUM(win) wins, "
77                        "SUM(loss) losses "
78                 "FROM   (SELECT g.game_id, "
79                                "g.game_type_cd, "
80                                "CASE "
81                                  "WHEN g.winner = pgs.team THEN 1 "
82                                  "WHEN pgs.rank = 1 THEN 1 "
83                                  "ELSE 0 "
84                                "END win, "
85                                "CASE "
86                                  "WHEN g.winner = pgs.team THEN 0 "
87                                  "WHEN pgs.rank = 1 THEN 0 "
88                                  "ELSE 1 "
89                                "END loss "
90                         "FROM   games g, "
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()
96
97     games_played = []
98     overall_games = 0
99     overall_wins = 0
100     overall_losses = 0
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
107
108         games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
109             row.losses, win_pct))
110
111     try:
112         overall_win_pct = float(overall_wins)/overall_games * 100
113     except:
114         overall_win_pct = 0.0
115
116     games_played.append(GamesPlayed('overall', overall_games, overall_wins,
117         overall_losses, overall_win_pct))
118
119     # sort the resulting list by # of games played
120     games_played = sorted(games_played, key=lambda x:x.games)
121     games_played.reverse()
122     return games_played
123
124
125 def get_overall_stats(player_id):
126     """
127     Provides a breakdown of stats by gametype played by player_id.
128
129     Returns a dictionary of namedtuples with the following members:
130         - total_kills
131         - total_deaths
132         - k_d_ratio
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)
141         - game_type_cd
142
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.
145     """
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'])
150
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').\
154             from_statement(
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 "
163                 "FROM   games g, "
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()
169
170     # to be indexed by game_type_cd
171     overall_stats = {}
172
173     # sums for the "overall" game type (which is fake)
174     overall_kills = 0
175     overall_deaths = 0
176     overall_last_played = None
177     overall_playing_time = datetime.timedelta(seconds=0)
178     overall_carrier_frags = 0
179
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
184
185         if overall_last_played is None or row.last_played > overall_last_played:
186             overall_last_played = row.last_played
187
188         overall_playing_time += row.total_playing_time
189
190         # individual gametype ratio calculations
191         try:
192             k_d_ratio = float(row.total_kills)/row.total_deaths
193         except:
194             k_d_ratio = None
195
196         try:
197             cap_ratio = float(row.total_captures)/row.total_pickups
198         except:
199             cap_ratio = None
200
201         overall_carrier_frags += row.total_carrier_frags or 0
202
203         # everything else is untouched or "raw"
204         os = OverallStats(total_kills=row.total_kills,
205                 total_deaths=row.total_deaths,
206                 k_d_ratio=k_d_ratio,
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,
213                 cap_ratio=cap_ratio,
214                 total_carrier_frags=row.total_carrier_frags,
215                 game_type_cd=row.game_type_cd)
216
217         overall_stats[row.game_type_cd] = os
218
219     # and lastly, the overall stuff
220     try:
221         overall_k_d_ratio = float(overall_kills)/overall_deaths
222     except:
223         overall_k_d_ratio = None
224
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,
232             total_pickups=None,
233             total_captures=None,
234             cap_ratio=None,
235             total_carrier_frags=overall_carrier_frags,
236             game_type_cd='overall')
237
238     overall_stats['overall'] = os
239
240     return overall_stats
241
242
243 def get_fav_maps(player_id, game_type_cd=None):
244     """
245     Provides a breakdown of favorite maps by gametype.
246
247     Returns a dictionary of namedtuples with the following members:
248         - game_type_cd
249         - map_name (map name)
250         - map_id
251         - times_played
252
253     The favorite map is defined as the map you've played the most
254     for the given game_type_cd.
255
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.
260     """
261     FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
262
263     raw_favs = DBSession.query('game_type_cd', 'map_name',
264             'map_id', 'times_played').\
265             from_statement(
266                 "SELECT game_type_cd, "
267                        "name map_name, "
268                        "map_id, "
269                        "times_played "
270                 "FROM   (SELECT g.game_type_cd, "
271                                "m.name, "
272                                "m.map_id, "
273                                "Count(*) times_played, "
274                                "Row_number() "
275                                  "OVER ( "
276                                    "partition BY g.game_type_cd "
277                                    "ORDER BY Count(*) DESC, m.map_id ASC) rank "
278                         "FROM   games g, "
279                                "player_game_stats pgs, "
280                                "maps m "
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, "
285                                   "m.map_id, "
286                                   "m.name) most_played "
287                 "WHERE  rank = 1 "
288                 "ORDER BY  times_played desc "
289             ).params(player_id=player_id).all()
290
291     fav_maps = {}
292     overall_fav = None
293     for row in raw_favs:
294         fv = FavMap(map_name=row.map_name,
295             map_id=row.map_id,
296             times_played=row.times_played,
297             game_type_cd=row.game_type_cd)
298     
299         # if we aren't given a favorite game_type_cd
300         # then the overall favorite is the one we've
301         # played the most
302         if overall_fav is None:
303             fav_maps['overall'] = fv
304             overall_fav = fv.game_type_cd
305
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
311
312         fav_maps[row.game_type_cd] = fv
313
314     return fav_maps
315
316
317 def get_ranks(player_id):
318     """
319     Provides a breakdown of the player's ranks by game type.
320
321     Returns a dictionary of namedtuples with the following members:
322         - game_type_cd
323         - rank
324         - max_rank
325
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.
328     """    
329     Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
330
331     raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
332             from_statement(
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 "
336                     "from player_ranks  "
337                     "group by game_type_cd) overall "
338                 "where pr.game_type_cd = overall.game_type_cd  "
339                 "and player_id = :player_id "
340                 "order by rank").\
341             params(player_id=player_id).all()
342
343     ranks = {}
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)
350
351
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
357
358         ranks[row.game_type_cd] = rank
359
360     return ranks;
361
362
363 def get_elos(player_id):
364     """
365     Provides a breakdown of the player's elos by game type.
366
367     Returns a dictionary of namedtuples with the following members:
368         - player_id
369         - game_type_cd
370         - games
371         - elo
372
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.
375     """
376     raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
377             order_by(PlayerElo.elo.desc()).all()
378
379     elos = {}
380     found_max_elo = False
381     for row in raw_elos:
382         if not found_max_elo:
383             elos['overall'] = row
384             found_max_elo = True
385
386         elos[row.game_type_cd] = row
387
388     return elos
389
390
391 def get_recent_games(player_id):
392     """
393     Provides a list of recent games.
394
395     Returns the full PlayerGameStat, Game, Server, Map
396     objects for all recent games.
397     """
398     RecentGame = namedtuple('RecentGame', ['player_stats', 'game', 'server', 'map'])
399
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]
407
408     return [
409         RecentGame(player_stats=row.PlayerGameStat,
410             game=row.Game,
411             server=row.Server,
412             map=row.Map)
413         for row in recent_games ]
414
415
416 def get_recent_weapons(player_id):
417     """
418     Returns the weapons that have been used in the past 90 days
419     and also used in 5 games or more.
420     """
421     cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=90)
422     recent_weapons = []
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).\
428             all():
429                 recent_weapons.append(weapon[0])
430
431     return recent_weapons
432
433
434 def get_accuracy_stats(player_id, weapon_cd, games):
435     """
436     Provides accuracy for weapon_cd by player_id for the past N games.
437     """
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
441     try:
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).\
446                 one()
447
448         avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
449
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()).\
457                 limit(games).\
458                 all()
459
460         # they come out in opposite order, so flip them in the right direction
461         raw_accs.reverse()
462
463         accs = []
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)))
466     except:
467         accs = []
468         avg = 0.0
469
470     return (avg, accs)
471
472
473 def get_damage_stats(player_id, weapon_cd, games):
474     """
475     Provides damage info for weapon_cd by player_id for the past N games.
476     """
477     try:
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).\
482                 one()
483
484         avg = round(float(raw_avg[0])/raw_avg[1], 2)
485
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()).\
493                 limit(games).\
494                 all()
495
496         # they come out in opposite order, so flip them in the right direction
497         raw_dmgs.reverse()
498
499         dmgs = []
500         for i in range(len(raw_dmgs)):
501             # try to derive, unless we've hit nothing then set to 0!
502             try:
503                 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
504             except:
505                 dmg = 0.0
506
507             dmgs.append((raw_dmgs[i][0], dmg))
508     except Exception as e:
509         dmgs = []
510         avg = 0.0
511
512     return (avg, dmgs)
513
514
515 def player_info_data(request):
516     player_id = int(request.matchdict['id'])
517     if player_id <= 2:
518         player_id = -1;
519
520     try:
521         player = DBSession.query(Player).filter_by(player_id=player_id).\
522                 filter(Player.active_ind == True).one()
523
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)
531
532     except Exception as e:
533         player         = None
534         games_played   = None
535         overall_stats  = None
536         fav_maps       = None
537         elos           = None
538         ranks          = None
539         recent_games   = None
540         recent_weapons = []
541
542     return {'player':player,
543             'games_played':games_played,
544             'overall_stats':overall_stats,
545             'fav_maps':fav_maps,
546             'elos':elos,
547             'ranks':ranks,
548             'recent_games':recent_games,
549             'recent_weapons':recent_weapons
550             }
551
552
553 def player_info(request):
554     """
555     Provides detailed information on a specific player
556     """
557     return player_info_data(request)
558
559
560 def player_info_json(request):
561     """
562     Provides detailed information on a specific player. JSON.
563     """
564
565     # All player_info fields are converted into JSON-formattable dictionaries
566     player_info = player_info_data(request)    
567
568     player = player_info['player'].to_dict()
569
570     games_played = {}
571     for game in player_info['games_played']:
572         games_played[game.game_type_cd] = to_json(game)
573
574     overall_stats = {}
575     for gt,stats in player_info['overall_stats'].items():
576         overall_stats[gt] = to_json(stats)
577
578     elos = {}
579     for gt,elo in player_info['elos'].items():
580         elos[gt] = to_json(elo.to_dict())
581
582     ranks = {}
583     for gt,rank in player_info['ranks'].items():
584         ranks[gt] = to_json(rank)
585
586     fav_maps = {}
587     for gt,mapinfo in player_info['fav_maps'].items():
588         fav_maps[gt] = to_json(mapinfo)
589
590     recent_games = []
591     for game in player_info['recent_games']:
592         recent_games.append(to_json(game))
593
594     #recent_weapons = player_info['recent_weapons']
595
596     return [{
597         'player':           player,
598         'games_played':     games_played,
599         'overall_stats':    overall_stats,
600         'fav_maps':         fav_maps,
601         'elos':             elos,
602         'ranks':            ranks,
603         'recent_games':     recent_games,
604     #    'recent_weapons':   recent_weapons,
605         'recent_weapons':   ['not implemented'],
606     }]
607     #return [{'status':'not implemented'}]
608
609
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'])
614
615     player_id = request.matchdict['player_id']
616
617     if request.params.has_key('page'):
618         current_page = request.params['page']
619     else:
620         current_page = 1
621
622     try:
623         player = DBSession.query(Player).filter_by(player_id=player_id).\
624                 filter(Player.active_ind == True).one()
625
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())
636
637         games = Page(games_q, current_page, items_per_page=10, url=page_url)
638
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,
643             winner         = row.winner,
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,
649             map_id         = row.map_id,
650             map_name       = row.map_name,
651             team           = row.team,
652             rank           = row.rank,
653             elo_delta      = row.elo_delta
654         ) for row in games.items]
655
656     except Exception as e:
657         player = None
658         games = None
659
660     return {
661             'player_id':player.player_id,
662             'player':player,
663             'games':games,
664            }
665
666
667 def player_game_index(request):
668     """
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.
672     """
673     return player_game_index_data(request)
674
675
676 def player_game_index_json(request):
677     """
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.
681     """
682     return [{'status':'not implemented'}]
683
684
685 def player_accuracy_data(request):
686     player_id = request.matchdict['id']
687     allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
688     weapon_cd = 'nex'
689     games = 20
690
691     if request.params.has_key('weapon'):
692         if request.params['weapon'] in allowed_weapons:
693             weapon_cd = request.params['weapon']
694
695     if request.params.has_key('games'):
696         try:
697             games = request.params['games']
698
699             if games < 0:
700                 games = 20
701             if games > 50:
702                 games = 50
703         except:
704             games = 20
705
706     (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
707
708     # if we don't have enough data for the given weapon
709     if len(accs) < games:
710         games = len(accs)
711
712     return {
713             'player_id':player_id, 
714             'player_url':request.route_url('player_info', id=player_id), 
715             'weapon':weapon_cd, 
716             'games':games, 
717             'avg':avg, 
718             'accs':accs
719             }
720
721
722 def player_accuracy(request):
723     """
724     Provides the accuracy for the given weapon. (JSON only)
725     """
726     return player_accuracy_data(request)
727
728
729 def player_accuracy_json(request):
730     """
731     Provides a JSON response representing the accuracy for the given weapon.
732
733     Parameters:
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.
737     """
738     return player_accuracy_data(request)
739
740
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'
746     games = 20
747
748     if request.params.has_key('weapon'):
749         if request.params['weapon'] in allowed_weapons:
750             weapon_cd = request.params['weapon']
751
752     if request.params.has_key('games'):
753         try:
754             games = request.params['games']
755
756             if games < 0:
757                 games = 20
758             if games > 50:
759                 games = 50
760         except:
761             games = 20
762
763     (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
764
765     # if we don't have enough data for the given weapon
766     if len(dmgs) < games:
767         games = len(dmgs)
768
769     return {
770             'player_id':player_id, 
771             'player_url':request.route_url('player_info', id=player_id), 
772             'weapon':weapon_cd, 
773             'games':games, 
774             'avg':avg, 
775             'dmgs':dmgs
776             }
777
778
779 def player_damage_json(request):
780     """
781     Provides a JSON response representing the damage for the given weapon.
782
783     Parameters:
784        weapon = which weapon to display damage for. Valid values are
785          'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
786          'laser'.
787        games = over how many games to display damage. Can be up to 50.
788     """
789     return player_damage_data(request)
790
791
792 def player_hashkey_info_data(request):
793     hashkey = request.matchdict['hashkey']
794     try:
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()
799
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)
805
806     except Exception as e:
807         raise e
808         player         = None
809         games_played   = None
810         overall_stats  = None
811         fav_maps       = None
812         elos           = None
813         ranks          = None
814
815     return {'player':player,
816             'games_played':games_played,
817             'overall_stats':overall_stats,
818             'fav_maps':fav_maps,
819             'elos':elos,
820             'ranks':ranks,
821             }
822
823
824 def player_hashkey_info_json(request):
825     """
826     Provides detailed information on a specific player. JSON.
827     """
828
829     # All player_info fields are converted into JSON-formattable dictionaries
830     player_info = player_hashkey_info_data(request)
831
832     player = player_info['player'].to_dict()
833
834     games_played = {}
835     for game in player_info['games_played']:
836         games_played[game.game_type_cd] = to_json(game)
837
838     overall_stats = {}
839     for gt,stats in player_info['overall_stats'].items():
840         overall_stats[gt] = to_json(stats)
841
842     elos = {}
843     for gt,elo in player_info['elos'].items():
844         elos[gt] = to_json(elo.to_dict())
845
846     ranks = {}
847     for gt,rank in player_info['ranks'].items():
848         ranks[gt] = to_json(rank)
849
850     fav_maps = {}
851     for gt,mapinfo in player_info['fav_maps'].items():
852         fav_maps[gt] = to_json(mapinfo)
853
854     return [{
855         'version':          1,
856         'player':           player,
857         'games_played':     games_played,
858         'overall_stats':    overall_stats,
859         'fav_maps':         fav_maps,
860         'elos':             elos,
861         'ranks':            ranks,
862     }]