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