]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/views/player.py
Merge branch 'nvd3' of github.com:antzucaro/XonStat into nvd3
[xonotic/xonstat.git] / xonstat / views / player.py
1 import datetime
2 import logging
3 import pyramid.httpexceptions
4 import sqlalchemy as sa
5 import sqlalchemy.sql.functions as func
6 from calendar import timegm
7 from collections import namedtuple
8 from webhelpers.paginate import Page
9 from xonstat.models import *
10 from xonstat.util import page_url, to_json, pretty_date, datetime_seconds
11 from xonstat.util import is_cake_day, verify_request
12 from xonstat.views.helpers import RecentGame, recent_games_q
13
14 log = logging.getLogger(__name__)
15
16
17 def player_index_data(request):
18     if request.params.has_key('page'):
19         current_page = request.params['page']
20     else:
21         current_page = 1
22
23     try:
24         player_q = DBSession.query(Player).\
25                 filter(Player.player_id > 2).\
26                 filter(Player.active_ind == True).\
27                 filter(sa.not_(Player.nick.like('Anonymous Player%'))).\
28                 order_by(Player.player_id.desc())
29
30         players = Page(player_q, current_page, items_per_page=25, url=page_url)
31
32     except Exception as e:
33         players = None
34         raise e
35
36     return {'players':players
37            }
38
39
40 def player_index(request):
41     """
42     Provides a list of all the current players.
43     """
44     return player_index_data(request)
45
46
47 def player_index_json(request):
48     """
49     Provides a list of all the current players. JSON.
50     """
51     return [{'status':'not implemented'}]
52
53
54 def get_games_played(player_id):
55     """
56     Provides a breakdown by gametype of the games played by player_id.
57
58     Returns a list of namedtuples with the following members:
59         - game_type_cd
60         - games
61         - wins
62         - losses
63         - win_pct
64
65     The list itself is ordered by the number of games played
66     """
67     GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
68         'losses', 'win_pct'])
69
70     raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
71             from_statement(
72                 "SELECT game_type_cd, "
73                        "SUM(win) wins, "
74                        "SUM(loss) losses "
75                 "FROM   (SELECT g.game_id, "
76                                "g.game_type_cd, "
77                                "CASE "
78                                  "WHEN g.winner = pgs.team THEN 1 "
79                                  "WHEN pgs.scoreboardpos = 1 THEN 1 "
80                                  "ELSE 0 "
81                                "END win, "
82                                "CASE "
83                                  "WHEN g.winner = pgs.team THEN 0 "
84                                  "WHEN pgs.scoreboardpos = 1 THEN 0 "
85                                  "ELSE 1 "
86                                "END loss "
87                         "FROM   games g, "
88                                "player_game_stats pgs "
89                         "WHERE  g.game_id = pgs.game_id "
90                         "AND pgs.player_id = :player_id) win_loss "
91                 "GROUP  BY game_type_cd "
92             ).params(player_id=player_id).all()
93
94     games_played = []
95     overall_games = 0
96     overall_wins = 0
97     overall_losses = 0
98     for row in raw_games_played:
99         games = row.wins + row.losses
100         overall_games += games
101         overall_wins += row.wins
102         overall_losses += row.losses
103         win_pct = float(row.wins)/games * 100
104
105         games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
106             row.losses, win_pct))
107
108     try:
109         overall_win_pct = float(overall_wins)/overall_games * 100
110     except:
111         overall_win_pct = 0.0
112
113     games_played.append(GamesPlayed('overall', overall_games, overall_wins,
114         overall_losses, overall_win_pct))
115
116     # sort the resulting list by # of games played
117     games_played = sorted(games_played, key=lambda x:x.games)
118     games_played.reverse()
119     return games_played
120
121
122 def get_overall_stats(player_id):
123     """
124     Provides a breakdown of stats by gametype played by player_id.
125
126     Returns a dictionary of namedtuples with the following members:
127         - total_kills
128         - total_deaths
129         - k_d_ratio
130         - last_played (last time the player played the game type)
131         - last_played_epoch (same as above, but in seconds since epoch)
132         - last_played_fuzzy (same as above, but in relative date)
133         - total_playing_time (total amount of time played the game type)
134         - total_playing_time_secs (same as the above, but in seconds)
135         - total_pickups (ctf only)
136         - total_captures (ctf only)
137         - cap_ratio (ctf only)
138         - total_carrier_frags (ctf only)
139         - game_type_cd
140         - game_type_descr
141
142     The key to the dictionary is the game type code. There is also an
143     "overall" game_type_cd which sums the totals and computes the total ratios.
144     """
145     OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
146         'k_d_ratio', 'last_played', 'last_played_epoch', 'last_played_fuzzy',
147         'total_playing_time', 'total_playing_time_secs', 'total_pickups', 'total_captures', 'cap_ratio',
148         'total_carrier_frags', 'game_type_cd', 'game_type_descr'])
149
150     raw_stats = DBSession.query('game_type_cd', 'game_type_descr',
151             'total_kills', 'total_deaths', 'last_played', 'total_playing_time',
152             'total_pickups', 'total_captures', 'total_carrier_frags').\
153             from_statement(
154                 "SELECT g.game_type_cd, "
155                        "gt.descr game_type_descr, "
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                        "cd_game_type gt, "
165                        "player_game_stats pgs "
166                 "WHERE  g.game_id = pgs.game_id "
167                   "AND  g.game_type_cd = gt.game_type_cd "
168                   "AND  pgs.player_id = :player_id "
169                 "GROUP  BY g.game_type_cd, game_type_descr "
170                 "UNION "
171                 "SELECT 'overall'              game_type_cd, "
172                        "'Overall'              game_type_descr, "
173                        "Sum(pgs.kills)         total_kills, "
174                        "Sum(pgs.deaths)        total_deaths, "
175                        "Max(pgs.create_dt)     last_played, "
176                        "Sum(pgs.alivetime)     total_playing_time, "
177                        "Sum(pgs.pickups)       total_pickups, "
178                        "Sum(pgs.captures)      total_captures, "
179                        "Sum(pgs.carrier_frags) total_carrier_frags "
180                 "FROM   player_game_stats pgs "
181                 "WHERE  pgs.player_id = :player_id "
182             ).params(player_id=player_id).all()
183
184     # to be indexed by game_type_cd
185     overall_stats = {}
186
187     for row in raw_stats:
188         # individual gametype ratio calculations
189         try:
190             k_d_ratio = float(row.total_kills)/row.total_deaths
191         except:
192             k_d_ratio = None
193
194         try:
195             cap_ratio = float(row.total_captures)/row.total_pickups
196         except:
197             cap_ratio = None
198
199         # everything else is untouched or "raw"
200         os = OverallStats(total_kills=row.total_kills,
201                 total_deaths=row.total_deaths,
202                 k_d_ratio=k_d_ratio,
203                 last_played=row.last_played,
204                 last_played_epoch=timegm(row.last_played.timetuple()),
205                 last_played_fuzzy=pretty_date(row.last_played),
206                 total_playing_time=row.total_playing_time,
207                 total_playing_time_secs=int(datetime_seconds(row.total_playing_time)),
208                 total_pickups=row.total_pickups,
209                 total_captures=row.total_captures,
210                 cap_ratio=cap_ratio,
211                 total_carrier_frags=row.total_carrier_frags,
212                 game_type_cd=row.game_type_cd,
213                 game_type_descr=row.game_type_descr)
214
215         overall_stats[row.game_type_cd] = os
216
217     # We have to edit "overall" stats to exclude deaths in CTS.
218     # Although we still want to record deaths, they shouldn't
219     # count towards the overall K:D ratio.
220     if 'cts' in overall_stats:
221         os = overall_stats['overall']
222
223         try:
224             k_d_ratio = float(os.total_kills)/(os.total_deaths - overall_stats['cts'].total_deaths)
225         except:
226             k_d_ratio = None
227
228         non_cts_deaths = os.total_deaths - overall_stats['cts'].total_deaths
229
230
231         overall_stats['overall'] = OverallStats(
232                 total_kills             = os.total_kills,
233                 total_deaths            = non_cts_deaths,
234                 k_d_ratio               = k_d_ratio,
235                 last_played             = os.last_played,
236                 last_played_epoch       = os.last_played_epoch,
237                 last_played_fuzzy       = os.last_played_fuzzy,
238                 total_playing_time      = os.total_playing_time,
239                 total_playing_time_secs = os.total_playing_time_secs,
240                 total_pickups           = os.total_pickups,
241                 total_captures          = os.total_captures,
242                 cap_ratio               = os.cap_ratio,
243                 total_carrier_frags     = os.total_carrier_frags,
244                 game_type_cd            = os.game_type_cd,
245                 game_type_descr         = os.game_type_descr)
246
247     return overall_stats
248
249
250 def get_fav_maps(player_id, game_type_cd=None):
251     """
252     Provides a breakdown of favorite maps by gametype.
253
254     Returns a dictionary of namedtuples with the following members:
255         - game_type_cd
256         - map_name (map name)
257         - map_id
258         - times_played
259
260     The favorite map is defined as the map you've played the most
261     for the given game_type_cd.
262
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.
267     """
268     FavMap = namedtuple('FavMap', ['map_name', 'map_id', 'times_played', 'game_type_cd'])
269
270     raw_favs = DBSession.query('game_type_cd', 'map_name',
271             'map_id', 'times_played').\
272             from_statement(
273                 "SELECT game_type_cd, "
274                        "name map_name, "
275                        "map_id, "
276                        "times_played "
277                 "FROM   (SELECT g.game_type_cd, "
278                                "m.name, "
279                                "m.map_id, "
280                                "Count(*) times_played, "
281                                "Row_number() "
282                                  "OVER ( "
283                                    "partition BY g.game_type_cd "
284                                    "ORDER BY Count(*) DESC, m.map_id ASC) rank "
285                         "FROM   games g, "
286                                "player_game_stats pgs, "
287                                "maps m "
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, "
292                                   "m.map_id, "
293                                   "m.name) most_played "
294                 "WHERE  rank = 1 "
295                 "ORDER BY  times_played desc "
296             ).params(player_id=player_id).all()
297
298     fav_maps = {}
299     overall_fav = None
300     for row in raw_favs:
301         fv = FavMap(map_name=row.map_name,
302             map_id=row.map_id,
303             times_played=row.times_played,
304             game_type_cd=row.game_type_cd)
305
306         # if we aren't given a favorite game_type_cd
307         # then the overall favorite is the one we've
308         # played the most
309         if overall_fav is None:
310             fav_maps['overall'] = fv
311             overall_fav = fv.game_type_cd
312
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
318
319         fav_maps[row.game_type_cd] = fv
320
321     return fav_maps
322
323
324 def get_ranks(player_id):
325     """
326     Provides a breakdown of the player's ranks by game type.
327
328     Returns a dictionary of namedtuples with the following members:
329         - game_type_cd
330         - rank
331         - max_rank
332
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.
335     """
336     Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
337
338     raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
339             from_statement(
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 "
343                     "from player_ranks  "
344                     "group by game_type_cd) overall "
345                 "where pr.game_type_cd = overall.game_type_cd  "
346                 "and player_id = :player_id "
347                 "order by rank").\
348             params(player_id=player_id).all()
349
350     ranks = {}
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-1)/(row.max_rank-1),
356             game_type_cd=row.game_type_cd)
357
358
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
364
365         ranks[row.game_type_cd] = rank
366
367     return ranks;
368
369
370 def get_elos(player_id):
371     """
372     Provides a breakdown of the player's elos by game type.
373
374     Returns a dictionary of namedtuples with the following members:
375         - player_id
376         - game_type_cd
377         - games
378         - elo
379
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.
382     """
383     raw_elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
384             order_by(PlayerElo.elo.desc()).all()
385
386     elos = {}
387     found_max_elo = False
388     for row in raw_elos:
389         if not found_max_elo:
390             elos['overall'] = row
391             found_max_elo = True
392
393         elos[row.game_type_cd] = row
394
395     return elos
396
397
398 def get_recent_games(player_id, limit=10):
399     """
400     Provides a list of recent games for a player. Uses the recent_games_q helper.
401     """
402     # recent games played in descending order
403     rgs = recent_games_q(player_id=player_id, force_player_id=True).limit(limit).all()
404     recent_games = [RecentGame(row) for row in rgs]
405
406     return recent_games
407
408
409 def get_recent_weapons(player_id):
410     """
411     Returns the weapons that have been used in the past 90 days
412     and also used in 5 games or more.
413     """
414     cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=90)
415     recent_weapons = []
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).\
421             all():
422                 recent_weapons.append(weapon[0])
423
424     return recent_weapons
425
426
427 def get_accuracy_stats(player_id, weapon_cd, games):
428     """
429     Provides accuracy for weapon_cd by player_id for the past N games.
430     """
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
434     try:
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).\
439                 one()
440
441         avg = round(float(raw_avg[0])/raw_avg[1]*100, 2)
442
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()).\
450                 limit(games).\
451                 all()
452
453         # they come out in opposite order, so flip them in the right direction
454         raw_accs.reverse()
455
456         accs = []
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)))
459     except:
460         accs = []
461         avg = 0.0
462
463     return (avg, accs)
464
465
466 def get_damage_stats(player_id, weapon_cd, games):
467     """
468     Provides damage info for weapon_cd by player_id for the past N games.
469     """
470     try:
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).\
475                 one()
476
477         avg = round(float(raw_avg[0])/raw_avg[1], 2)
478
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()).\
486                 limit(games).\
487                 all()
488
489         # they come out in opposite order, so flip them in the right direction
490         raw_dmgs.reverse()
491
492         dmgs = []
493         for i in range(len(raw_dmgs)):
494             # try to derive, unless we've hit nothing then set to 0!
495             try:
496                 dmg = round(float(raw_dmgs[i][1])/raw_dmgs[i][2], 2)
497             except:
498                 dmg = 0.0
499
500             dmgs.append((raw_dmgs[i][0], dmg))
501     except Exception as e:
502         dmgs = []
503         avg = 0.0
504
505     return (avg, dmgs)
506
507
508 def player_info_data(request):
509     player_id = int(request.matchdict['id'])
510     if player_id <= 2:
511         player_id = -1;
512
513     try:
514         player = DBSession.query(Player).filter_by(player_id=player_id).\
515                 filter(Player.active_ind == True).one()
516
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)
524         cake_day       = is_cake_day(player.create_dt)
525
526     except Exception as e:
527         player         = None
528         games_played   = None
529         overall_stats  = None
530         fav_maps       = None
531         elos           = None
532         ranks          = None
533         recent_games   = None
534         recent_weapons = []
535         cake_day       = False
536         ## do not raise exceptions here (only for debugging)
537         # raise e
538
539     return {'player':player,
540             'games_played':games_played,
541             'overall_stats':overall_stats,
542             'fav_maps':fav_maps,
543             'elos':elos,
544             'ranks':ranks,
545             'recent_games':recent_games,
546             'recent_weapons':recent_weapons,
547             'cake_day':cake_day,
548             }
549
550
551 def player_info(request):
552     """
553     Provides detailed information on a specific player
554     """
555     return player_info_data(request)
556
557
558 def player_info_json(request):
559     """
560     Provides detailed information on a specific player. JSON.
561     """
562
563     # All player_info fields are converted into JSON-formattable dictionaries
564     player_info = player_info_data(request)
565
566     player = player_info['player'].to_dict()
567
568     games_played = {}
569     for game in player_info['games_played']:
570         games_played[game.game_type_cd] = to_json(game)
571
572     overall_stats = {}
573     for gt,stats in player_info['overall_stats'].items():
574         overall_stats[gt] = to_json(stats)
575
576     elos = {}
577     for gt,elo in player_info['elos'].items():
578         elos[gt] = to_json(elo.to_dict())
579
580     ranks = {}
581     for gt,rank in player_info['ranks'].items():
582         ranks[gt] = to_json(rank)
583
584     fav_maps = {}
585     for gt,mapinfo in player_info['fav_maps'].items():
586         fav_maps[gt] = to_json(mapinfo)
587
588     recent_games = []
589     for game in player_info['recent_games']:
590         recent_games.append(to_json(game))
591
592     #recent_weapons = player_info['recent_weapons']
593
594     return [{
595         'player':           player,
596         'games_played':     games_played,
597         'overall_stats':    overall_stats,
598         'fav_maps':         fav_maps,
599         'elos':             elos,
600         'ranks':            ranks,
601         'recent_games':     recent_games,
602     #    'recent_weapons':   recent_weapons,
603         'recent_weapons':   ['not implemented'],
604     }]
605     #return [{'status':'not implemented'}]
606
607
608 def player_game_index_data(request):
609     player_id = request.matchdict['player_id']
610
611     game_type_cd = None
612     game_type_descr = None
613
614     if request.params.has_key('type'):
615         game_type_cd = request.params['type']
616         try:
617             game_type_descr = DBSession.query(GameType.descr).\
618                 filter(GameType.game_type_cd == game_type_cd).\
619                 one()[0]
620         except Exception as e:
621             pass
622
623     else:
624         game_type_cd = None
625         game_type_descr = None
626
627     if request.params.has_key('page'):
628         current_page = request.params['page']
629     else:
630         current_page = 1
631
632     try:
633         player = DBSession.query(Player).\
634                 filter_by(player_id=player_id).\
635                 filter(Player.active_ind == True).\
636                 one()
637
638         rgs_q = recent_games_q(player_id=player.player_id,
639             force_player_id=True, game_type_cd=game_type_cd)
640
641         games = Page(rgs_q, current_page, items_per_page=20, url=page_url)
642
643         # replace the items in the canned pagination class with more rich ones
644         games.items = [RecentGame(row) for row in games.items]
645
646         games_played = get_games_played(player_id)
647
648     except Exception as e:
649         player = None
650         games = None
651         game_type_cd = None
652         game_type_descr = None
653         games_played = None
654
655     return {
656             'player_id':player.player_id,
657             'player':player,
658             'games':games,
659             'game_type_cd':game_type_cd,
660             'game_type_descr':game_type_descr,
661             'games_played':games_played,
662            }
663
664
665 def player_game_index(request):
666     """
667     Provides an index of the games in which a particular
668     player was involved. This is ordered by game_id, with
669     the most recent game_ids first. Paginated.
670     """
671     return player_game_index_data(request)
672
673
674 def player_game_index_json(request):
675     """
676     Provides an index of the games in which a particular
677     player was involved. This is ordered by game_id, with
678     the most recent game_ids first. Paginated. JSON.
679     """
680     return [{'status':'not implemented'}]
681
682
683 def player_accuracy_data(request):
684     player_id = request.matchdict['id']
685     allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
686     weapon_cd = 'nex'
687     games = 20
688
689     if request.params.has_key('weapon'):
690         if request.params['weapon'] in allowed_weapons:
691             weapon_cd = request.params['weapon']
692
693     if request.params.has_key('games'):
694         try:
695             games = request.params['games']
696
697             if games < 0:
698                 games = 20
699             if games > 50:
700                 games = 50
701         except:
702             games = 20
703
704     (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
705
706     # if we don't have enough data for the given weapon
707     if len(accs) < games:
708         games = len(accs)
709
710     return {
711             'player_id':player_id,
712             'player_url':request.route_url('player_info', id=player_id),
713             'weapon':weapon_cd,
714             'games':games,
715             'avg':avg,
716             'accs':accs
717             }
718
719
720 def player_accuracy(request):
721     """
722     Provides the accuracy for the given weapon. (JSON only)
723     """
724     return player_accuracy_data(request)
725
726
727 def player_accuracy_json(request):
728     """
729     Provides a JSON response representing the accuracy for the given weapon.
730
731     Parameters:
732        weapon = which weapon to display accuracy for. Valid values are 'nex',
733                 'shotgun', 'uzi', and 'minstanex'.
734        games = over how many games to display accuracy. Can be up to 50.
735     """
736     return player_accuracy_data(request)
737
738
739 def player_damage_data(request):
740     player_id = request.matchdict['id']
741     allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
742             'rocketlauncher', 'laser']
743     weapon_cd = 'rocketlauncher'
744     games = 20
745
746     if request.params.has_key('weapon'):
747         if request.params['weapon'] in allowed_weapons:
748             weapon_cd = request.params['weapon']
749
750     if request.params.has_key('games'):
751         try:
752             games = request.params['games']
753
754             if games < 0:
755                 games = 20
756             if games > 50:
757                 games = 50
758         except:
759             games = 20
760
761     (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
762
763     # if we don't have enough data for the given weapon
764     if len(dmgs) < games:
765         games = len(dmgs)
766
767     return {
768             'player_id':player_id,
769             'player_url':request.route_url('player_info', id=player_id),
770             'weapon':weapon_cd,
771             'games':games,
772             'avg':avg,
773             'dmgs':dmgs
774             }
775
776
777 def player_damage_json(request):
778     """
779     Provides a JSON response representing the damage for the given weapon.
780
781     Parameters:
782        weapon = which weapon to display damage for. Valid values are
783          'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
784          'laser'.
785        games = over how many games to display damage. Can be up to 50.
786     """
787     return player_damage_data(request)
788
789
790 def player_hashkey_info_data(request):
791     (idfp, status) = verify_request(request)
792
793     # if config is to *not* verify requests and we get nothing back, this
794     # query will return nothing and we'll 404.
795     try:
796         player = DBSession.query(Player).\
797                 filter(Player.player_id == Hashkey.player_id).\
798                 filter(Player.active_ind == True).\
799                 filter(Hashkey.hashkey == idfp).one()
800
801         games_played      = get_games_played(player.player_id)
802         overall_stats     = get_overall_stats(player.player_id)
803         fav_maps          = get_fav_maps(player.player_id)
804         elos              = get_elos(player.player_id)
805         ranks             = get_ranks(player.player_id)
806         most_recent_game  = get_recent_games(player.player_id, 1)[0]
807
808     except Exception as e:
809         raise pyramid.httpexceptions.HTTPNotFound
810
811     return {'player':player,
812             'hashkey':hashkey,
813             'games_played':games_played,
814             'overall_stats':overall_stats,
815             'fav_maps':fav_maps,
816             'elos':elos,
817             'ranks':ranks,
818             'most_recent_game':most_recent_game,
819             }
820
821
822 def player_hashkey_info_json(request):
823     """
824     Provides detailed information on a specific player. JSON.
825     """
826
827     # All player_info fields are converted into JSON-formattable dictionaries
828     player_info = player_hashkey_info_data(request)
829
830     player = player_info['player'].to_dict()
831
832     games_played = {}
833     for game in player_info['games_played']:
834         games_played[game.game_type_cd] = to_json(game)
835
836     overall_stats = {}
837     for gt,stats in player_info['overall_stats'].items():
838         overall_stats[gt] = to_json(stats)
839
840     elos = {}
841     for gt,elo in player_info['elos'].items():
842         elos[gt] = to_json(elo.to_dict())
843
844     ranks = {}
845     for gt,rank in player_info['ranks'].items():
846         ranks[gt] = to_json(rank)
847
848     fav_maps = {}
849     for gt,mapinfo in player_info['fav_maps'].items():
850         fav_maps[gt] = to_json(mapinfo)
851
852     most_recent_game = to_json(player_info['most_recent_game'])
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         'most_recent_game': most_recent_game,
863     }]
864
865
866 def player_hashkey_info_text(request):
867     """
868     Provides detailed information on a specific player. Plain text.
869     """
870     # UTC epoch
871     now = timegm(datetime.datetime.utcnow().timetuple())
872
873     # All player_info fields are converted into JSON-formattable dictionaries
874     player_info = player_hashkey_info_data(request)
875
876     # gather all of the data up into aggregate structures
877     player = player_info['player']
878     games_played = player_info['games_played']
879     overall_stats = player_info['overall_stats']
880     elos = player_info['elos']
881     ranks = player_info['ranks']
882     fav_maps = player_info['fav_maps']
883     most_recent_game = player_info['most_recent_game']
884
885     # one-offs for things needing conversion for text/plain
886     player_joined = timegm(player.create_dt.timetuple())
887     player_joined_dt = player.create_dt
888     alivetime = int(datetime_seconds(overall_stats['overall'].total_playing_time))
889
890     # this is a plain text response, if we don't do this here then
891     # Pyramid will assume html
892     request.response.content_type = 'text/plain'
893
894     return {
895         'version':          1,
896         'now':              now,
897         'player':           player,
898         'hashkey':          player_info['hashkey'],
899         'player_joined':    player_joined,
900         'player_joined_dt': player_joined_dt,
901         'games_played':     games_played,
902         'overall_stats':    overall_stats,
903         'alivetime':        alivetime,
904         'fav_maps':         fav_maps,
905         'elos':             elos,
906         'ranks':            ranks,
907         'most_recent_game': most_recent_game,
908     }
909
910
911 def player_elo_info_data(request):
912     """
913     Provides elo information on a specific player. Raw data is returned.
914     """
915     hashkey = request.matchdict['hashkey']
916     print "player_elo_info_data [hashkey={0}]".format(hashkey)
917     try:
918         player = DBSession.query(Player).\
919                 filter(Player.player_id == Hashkey.player_id).\
920                 filter(Player.active_ind == True).\
921                 filter(Hashkey.hashkey == hashkey).one()
922
923         elos = get_elos(player.player_id)
924
925     except Exception as e:
926         log.debug(e)
927         raise pyramid.httpexceptions.HTTPNotFound
928
929     return {
930         'hashkey':hashkey,
931         'player':player,
932         'elos':elos,
933     }
934
935
936 def player_elo_info_json(request):
937     """
938     Provides elo information on a specific player. JSON.
939     """
940     elo_info = player_elo_info_data(request)
941
942     player = player_info['player'].to_dict()
943
944     elos = {}
945     for gt, elo in elo_info['elos'].items():
946         elos[gt] = to_json(elo.to_dict())
947
948     return [{
949         'version':          1,
950         'player':           player,
951         'elos':             elos,
952     }]
953
954
955 def player_elo_info_text(request):
956     """
957     Provides elo information on a specific player. Plain text.
958     """
959     # UTC epoch
960     now = timegm(datetime.datetime.utcnow().timetuple())
961
962     # All player_info fields are converted into JSON-formattable dictionaries
963     elo_info = player_elo_info_data(request)
964
965     # this is a plain text response, if we don't do this here then
966     # Pyramid will assume html
967     request.response.content_type = 'text/plain'
968
969     return {
970         'version':          1,
971         'now':              now,
972         'hashkey':          elo_info['hashkey'],
973         'player':           elo_info['player'],
974         'elos':             elo_info['elos'],
975     }
976
977
978 def player_captimes_data(request):
979     player_id = int(request.matchdict['id'])
980     if player_id <= 2:
981         player_id = -1;
982
983     PlayerCaptimes = namedtuple('PlayerCaptimes', ['fastest_cap', 'create_dt', 'create_dt_epoch', 'create_dt_fuzzy',
984         'player_id', 'game_id', 'map_id', 'map_name', 'server_id', 'server_name'])
985
986     dbquery = DBSession.query('fastest_cap', 'create_dt', 'player_id', 'game_id', 'map_id',
987                 'map_name', 'server_id', 'server_name').\
988             from_statement(
989                 "SELECT ct.fastest_cap, "
990                        "ct.create_dt, "
991                        "ct.player_id, "
992                        "ct.game_id, "
993                        "ct.map_id, "
994                        "m.name map_name, "
995                        "g.server_id, "
996                        "s.name server_name "
997                 "FROM   player_map_captimes ct, "
998                        "games g, "
999                        "maps m, "
1000                        "servers s "
1001                 "WHERE  ct.player_id = :player_id "
1002                   "AND  g.game_id = ct.game_id "
1003                   "AND  g.server_id = s.server_id "
1004                   "AND  m.map_id = ct.map_id "
1005                 #"ORDER  BY ct.fastest_cap "
1006                 "ORDER  BY ct.create_dt desc"
1007             ).params(player_id=player_id).all()
1008
1009     player = DBSession.query(Player).filter_by(player_id=player_id).one()
1010
1011     player_captimes = []
1012     for row in dbquery:
1013         player_captimes.append(PlayerCaptimes(
1014                 fastest_cap=row.fastest_cap,
1015                 create_dt=row.create_dt,
1016                 create_dt_epoch=timegm(row.create_dt.timetuple()),
1017                 create_dt_fuzzy=pretty_date(row.create_dt),
1018                 player_id=row.player_id,
1019                 game_id=row.game_id,
1020                 map_id=row.map_id,
1021                 map_name=row.map_name,
1022                 server_id=row.server_id,
1023                 server_name=row.server_name,
1024             ))
1025
1026     return {
1027             'captimes':player_captimes,
1028             'player_id':player_id,
1029             'player_url':request.route_url('player_info', id=player_id),
1030             'player':player,
1031         }
1032
1033 def player_captimes(request):
1034     return player_captimes_data(request)
1035
1036 def player_captimes_json(request):
1037     return player_captimes_data(request)
1038
1039
1040 def player_nvd3_damage(request):
1041     player_id = int(request.matchdict['id'])
1042     if player_id <= 2:
1043         player_id = -1;
1044
1045     game_type_cd = None
1046     if request.params.has_key("game_type"):
1047         game_type_cd = request.params["game_type"]
1048
1049     limit = 20
1050     if request.params.has_key("limit"):
1051         limit = int(request.params["limit"])
1052
1053         if limit < 0:
1054             limit = 20
1055         if limit > 50:
1056             limit = 50
1057
1058     return { "player_id": player_id,
1059         "game_type_cd": game_type_cd,
1060         "limit": limit,
1061     }
1062
1063 def player_weaponstats_data_json(request):
1064     player_id = request.matchdict["id"]
1065     if player_id <= 2:
1066         player_id = -1;
1067
1068     game_type_cd = None
1069     if request.params.has_key("game_type"):
1070         game_type_cd = request.params["game_type"]
1071
1072     limit = 20
1073     if request.params.has_key("limit"):
1074         limit = int(request.params["limit"])
1075
1076         if limit < 0:
1077             limit = 20
1078         if limit > 50:
1079             limit = 50
1080
1081     games_raw = DBSession.query(sa.distinct(Game.game_id)).\
1082         filter(Game.game_id == PlayerWeaponStat.game_id).\
1083         filter(PlayerWeaponStat.player_id == player_id)
1084
1085     if game_type_cd is not None:
1086         games_raw = games_raw.filter(Game.game_type_cd == game_type_cd)
1087
1088     games_raw = games_raw.order_by(Game.game_id.desc()).limit(limit).all()
1089
1090     weapon_stats_raw = DBSession.query(PlayerWeaponStat).\
1091         filter(PlayerWeaponStat.player_id == player_id).\
1092         filter(PlayerWeaponStat.game_id.in_(games_raw)).all()
1093
1094     # NVD3 expects data points for all weapons used across the
1095     # set of games *for each* point on the x axis. This means populating
1096     # zero-valued weapon stat entries for games where a weapon was not
1097     # used in that game, but was used in another game for the set
1098     games_to_weapons = {}
1099     weapons_used = []
1100     for ws in weapon_stats_raw:
1101         if ws.game_id not in games_to_weapons:
1102             games_to_weapons[ws.game_id] = [ws.weapon_cd]
1103         else:
1104             games_to_weapons[ws.game_id].append(ws.weapon_cd)
1105
1106         if ws.weapon_cd not in weapons_used:
1107             weapons_used.append(ws.weapon_cd)
1108
1109     for game_id in games_to_weapons.keys():
1110         for weapon_cd in set(weapons_used) - set(games_to_weapons[game_id]):
1111             log.debug("Inserting zero value for game_id {0} weapon {1}".format(game_id, weapon_cd))
1112             weapon_stats_raw.append(PlayerWeaponStat(player_id=player_id,
1113                 game_id=game_id, weapon_cd=weapon_cd))
1114
1115
1116     weapon_stats_raw = sorted(weapon_stats_raw, key              = lambda x: x.game_id)
1117     games            = sorted(games_to_weapons.keys())
1118     weapon_stats     = [ws.to_dict() for ws in weapon_stats_raw]
1119
1120     return {
1121         "weapon_stats": weapon_stats,
1122         "weapons_used": weapons_used,
1123         "games": games,
1124     }
1125