]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/views/player.py
CTS deaths should not count towards the overall K:D ratio
[xonotic/xonstat.git] / xonstat / views / player.py
1 import datetime
2 import json
3 import logging
4 import pyramid.httpexceptions
5 import re
6 import sqlalchemy as sa
7 import sqlalchemy.sql.functions as func
8 import time
9 from calendar import timegm
10 from collections import namedtuple
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, datetime_seconds, html_colors
16 from xonstat.views.helpers import RecentGame, recent_games_q
17
18 log = logging.getLogger(__name__)
19
20
21 def player_index_data(request):
22     if request.params.has_key('page'):
23         current_page = request.params['page']
24     else:
25         current_page = 1
26
27     try:
28         player_q = DBSession.query(Player).\
29                 filter(Player.player_id > 2).\
30                 filter(Player.active_ind == True).\
31                 filter(sa.not_(Player.nick.like('Anonymous Player%'))).\
32                 order_by(Player.player_id.desc())
33
34         players = Page(player_q, current_page, items_per_page=10, url=page_url)
35
36     except Exception as e:
37         players = None
38         raise e
39
40     return {'players':players
41            }
42
43
44 def player_index(request):
45     """
46     Provides a list of all the current players.
47     """
48     return player_index_data(request)
49
50
51 def player_index_json(request):
52     """
53     Provides a list of all the current players. JSON.
54     """
55     return [{'status':'not implemented'}]
56
57
58 def get_games_played(player_id):
59     """
60     Provides a breakdown by gametype of the games played by player_id.
61
62     Returns a list of namedtuples with the following members:
63         - game_type_cd
64         - games
65         - wins
66         - losses
67         - win_pct
68
69     The list itself is ordered by the number of games played
70     """
71     GamesPlayed = namedtuple('GamesPlayed', ['game_type_cd', 'games', 'wins',
72         'losses', 'win_pct'])
73
74     raw_games_played = DBSession.query('game_type_cd', 'wins', 'losses').\
75             from_statement(
76                 "SELECT game_type_cd, "
77                        "SUM(win) wins, "
78                        "SUM(loss) losses "
79                 "FROM   (SELECT g.game_id, "
80                                "g.game_type_cd, "
81                                "CASE "
82                                  "WHEN g.winner = pgs.team THEN 1 "
83                                  "WHEN pgs.rank = 1 THEN 1 "
84                                  "ELSE 0 "
85                                "END win, "
86                                "CASE "
87                                  "WHEN g.winner = pgs.team THEN 0 "
88                                  "WHEN pgs.rank = 1 THEN 0 "
89                                  "ELSE 1 "
90                                "END loss "
91                         "FROM   games g, "
92                                "player_game_stats pgs "
93                         "WHERE  g.game_id = pgs.game_id "
94                         "AND pgs.player_id = :player_id) win_loss "
95                 "GROUP  BY game_type_cd "
96             ).params(player_id=player_id).all()
97
98     games_played = []
99     overall_games = 0
100     overall_wins = 0
101     overall_losses = 0
102     for row in raw_games_played:
103         games = row.wins + row.losses
104         overall_games += games
105         overall_wins += row.wins
106         overall_losses += row.losses
107         win_pct = float(row.wins)/games * 100
108
109         games_played.append(GamesPlayed(row.game_type_cd, games, row.wins,
110             row.losses, win_pct))
111
112     try:
113         overall_win_pct = float(overall_wins)/overall_games * 100
114     except:
115         overall_win_pct = 0.0
116
117     games_played.append(GamesPlayed('overall', overall_games, overall_wins,
118         overall_losses, overall_win_pct))
119
120     # sort the resulting list by # of games played
121     games_played = sorted(games_played, key=lambda x:x.games)
122     games_played.reverse()
123     return games_played
124
125
126 def get_overall_stats(player_id):
127     """
128     Provides a breakdown of stats by gametype played by player_id.
129
130     Returns a dictionary of namedtuples with the following members:
131         - total_kills
132         - total_deaths
133         - k_d_ratio
134         - last_played (last time the player played the game type)
135         - last_played_epoch (same as above, but in seconds since epoch)
136         - last_played_fuzzy (same as above, but in relative date)
137         - total_playing_time (total amount of time played the game type)
138         - total_playing_time_secs (same as the above, but in seconds)
139         - total_pickups (ctf only)
140         - total_captures (ctf only)
141         - cap_ratio (ctf only)
142         - total_carrier_frags (ctf only)
143         - game_type_cd
144
145     The key to the dictionary is the game type code. There is also an
146     "overall" game_type_cd which sums the totals and computes the total ratios.
147     """
148     OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
149         'k_d_ratio', 'last_played', 'last_played_epoch', 'last_played_fuzzy',
150         'total_playing_time', 'total_playing_time_secs', 'total_pickups', 'total_captures', 'cap_ratio',
151         'total_carrier_frags', 'game_type_cd'])
152
153     raw_stats = DBSession.query('game_type_cd', 'total_kills',
154             'total_deaths', 'last_played', 'total_playing_time',
155             'total_pickups', 'total_captures', 'total_carrier_frags').\
156             from_statement(
157                 "SELECT g.game_type_cd, "
158                        "Sum(pgs.kills)         total_kills, "
159                        "Sum(pgs.deaths)        total_deaths, "
160                        "Max(pgs.create_dt)     last_played, "
161                        "Sum(pgs.alivetime)     total_playing_time, "
162                        "Sum(pgs.pickups)       total_pickups, "
163                        "Sum(pgs.captures)      total_captures, "
164                        "Sum(pgs.carrier_frags) total_carrier_frags "
165                 "FROM   games g, "
166                        "player_game_stats pgs "
167                 "WHERE  g.game_id = pgs.game_id "
168                   "AND  pgs.player_id = :player_id "
169                 "GROUP  BY g.game_type_cd "
170                 "UNION "
171                 "SELECT 'overall' game_type_cd, "
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   games g, "
180                        "player_game_stats pgs "
181                 "WHERE  g.game_id = pgs.game_id "
182                   "AND  pgs.player_id = :player_id "
183             ).params(player_id=player_id).all()
184
185     # to be indexed by game_type_cd
186     overall_stats = {}
187     raw_overall = None
188
189     for row in raw_stats:
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         # everything else is untouched or "raw"
202         os = OverallStats(total_kills=row.total_kills,
203                 total_deaths=row.total_deaths,
204                 k_d_ratio=k_d_ratio,
205                 last_played=row.last_played,
206                 last_played_epoch=timegm(row.last_played.timetuple()),
207                 last_played_fuzzy=pretty_date(row.last_played),
208                 total_playing_time=row.total_playing_time,
209                 total_playing_time_secs=int(datetime_seconds(row.total_playing_time)),
210                 total_pickups=row.total_pickups,
211                 total_captures=row.total_captures,
212                 cap_ratio=cap_ratio,
213                 total_carrier_frags=row.total_carrier_frags,
214                 game_type_cd=row.game_type_cd)
215
216         overall_stats[row.game_type_cd] = os
217
218     # We have to edit "overall" stats to exclude deaths in CTS.
219     # Although we still want to record deaths, they shouldn't
220     # count towards the overall K:D ratio.
221     if 'cts' in overall_stats:
222         os = overall_stats['overall']
223
224         try:
225             k_d_ratio = float(os.total_kills)/(os.total_deaths - overall_stats['cts'].total_deaths)
226         except:
227             k_d_ratio = None
228
229         non_cts_deaths = os.total_deaths - overall_stats['cts'].total_deaths
230
231
232         overall_stats['overall'] = OverallStats(
233                 total_kills             = os.total_kills,
234                 total_deaths            = non_cts_deaths,
235                 k_d_ratio               = k_d_ratio,
236                 last_played             = os.last_played,
237                 last_played_epoch       = os.last_played_epoch,
238                 last_played_fuzzy       = os.last_played_fuzzy,
239                 total_playing_time      = os.total_playing_time,
240                 total_playing_time_secs = os.total_playing_time_secs,
241                 total_pickups           = os.total_pickups,
242                 total_captures          = os.total_captures,
243                 cap_ratio               = os.cap_ratio,
244                 total_carrier_frags     = os.total_carrier_frags,
245                 game_type_cd            = os.game_type_cd)
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)/row.max_rank,
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):
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).limit(10).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
525     except Exception as e:
526         player         = None
527         games_played   = None
528         overall_stats  = None
529         fav_maps       = None
530         elos           = None
531         ranks          = None
532         recent_games   = None
533         recent_weapons = []
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     if request.params.has_key('page'):
607         current_page = request.params['page']
608     else:
609         current_page = 1
610
611     try:
612         player = DBSession.query(Player).filter_by(player_id=player_id).\
613                 filter(Player.active_ind == True).one()
614
615         rgs_q = recent_games_q(player_id=player.player_id)
616
617         games = Page(rgs_q, current_page, items_per_page=10, url=page_url)
618
619         # replace the items in the canned pagination class with more rich ones
620         games.items = [RecentGame(row) for row in games.items]
621
622     except Exception as e:
623         player = None
624         games = None
625
626     return {
627             'player_id':player.player_id,
628             'player':player,
629             'games':games,
630            }
631
632
633 def player_game_index(request):
634     """
635     Provides an index of the games in which a particular
636     player was involved. This is ordered by game_id, with
637     the most recent game_ids first. Paginated.
638     """
639     return player_game_index_data(request)
640
641
642 def player_game_index_json(request):
643     """
644     Provides an index of the games in which a particular
645     player was involved. This is ordered by game_id, with
646     the most recent game_ids first. Paginated. JSON.
647     """
648     return [{'status':'not implemented'}]
649
650
651 def player_accuracy_data(request):
652     player_id = request.matchdict['id']
653     allowed_weapons = ['nex', 'rifle', 'shotgun', 'uzi', 'minstanex']
654     weapon_cd = 'nex'
655     games = 20
656
657     if request.params.has_key('weapon'):
658         if request.params['weapon'] in allowed_weapons:
659             weapon_cd = request.params['weapon']
660
661     if request.params.has_key('games'):
662         try:
663             games = request.params['games']
664
665             if games < 0:
666                 games = 20
667             if games > 50:
668                 games = 50
669         except:
670             games = 20
671
672     (avg, accs) = get_accuracy_stats(player_id, weapon_cd, games)
673
674     # if we don't have enough data for the given weapon
675     if len(accs) < games:
676         games = len(accs)
677
678     return {
679             'player_id':player_id,
680             'player_url':request.route_url('player_info', id=player_id),
681             'weapon':weapon_cd,
682             'games':games,
683             'avg':avg,
684             'accs':accs
685             }
686
687
688 def player_accuracy(request):
689     """
690     Provides the accuracy for the given weapon. (JSON only)
691     """
692     return player_accuracy_data(request)
693
694
695 def player_accuracy_json(request):
696     """
697     Provides a JSON response representing the accuracy for the given weapon.
698
699     Parameters:
700        weapon = which weapon to display accuracy for. Valid values are 'nex',
701                 'shotgun', 'uzi', and 'minstanex'.
702        games = over how many games to display accuracy. Can be up to 50.
703     """
704     return player_accuracy_data(request)
705
706
707 def player_damage_data(request):
708     player_id = request.matchdict['id']
709     allowed_weapons = ['grenadelauncher', 'electro', 'crylink', 'hagar',
710             'rocketlauncher', 'laser']
711     weapon_cd = 'rocketlauncher'
712     games = 20
713
714     if request.params.has_key('weapon'):
715         if request.params['weapon'] in allowed_weapons:
716             weapon_cd = request.params['weapon']
717
718     if request.params.has_key('games'):
719         try:
720             games = request.params['games']
721
722             if games < 0:
723                 games = 20
724             if games > 50:
725                 games = 50
726         except:
727             games = 20
728
729     (avg, dmgs) = get_damage_stats(player_id, weapon_cd, games)
730
731     # if we don't have enough data for the given weapon
732     if len(dmgs) < games:
733         games = len(dmgs)
734
735     return {
736             'player_id':player_id,
737             'player_url':request.route_url('player_info', id=player_id),
738             'weapon':weapon_cd,
739             'games':games,
740             'avg':avg,
741             'dmgs':dmgs
742             }
743
744
745 def player_damage_json(request):
746     """
747     Provides a JSON response representing the damage for the given weapon.
748
749     Parameters:
750        weapon = which weapon to display damage for. Valid values are
751          'grenadelauncher', 'electro', 'crylink', 'hagar', 'rocketlauncher',
752          'laser'.
753        games = over how many games to display damage. Can be up to 50.
754     """
755     return player_damage_data(request)
756
757
758 def player_hashkey_info_data(request):
759     hashkey = request.matchdict['hashkey']
760     try:
761         player = DBSession.query(Player).\
762                 filter(Player.player_id == Hashkey.player_id).\
763                 filter(Player.active_ind == True).\
764                 filter(Hashkey.hashkey == hashkey).one()
765
766         games_played   = get_games_played(player.player_id)
767         overall_stats  = get_overall_stats(player.player_id)
768         fav_maps       = get_fav_maps(player.player_id)
769         elos           = get_elos(player.player_id)
770         ranks          = get_ranks(player.player_id)
771
772     except Exception as e:
773         raise pyramid.httpexceptions.HTTPNotFound
774
775     return {'player':player,
776             'hashkey':hashkey,
777             'games_played':games_played,
778             'overall_stats':overall_stats,
779             'fav_maps':fav_maps,
780             'elos':elos,
781             'ranks':ranks,
782             }
783
784
785 def player_hashkey_info_json(request):
786     """
787     Provides detailed information on a specific player. JSON.
788     """
789
790     # All player_info fields are converted into JSON-formattable dictionaries
791     player_info = player_hashkey_info_data(request)
792
793     player = player_info['player'].to_dict()
794
795     games_played = {}
796     for game in player_info['games_played']:
797         games_played[game.game_type_cd] = to_json(game)
798
799     overall_stats = {}
800     for gt,stats in player_info['overall_stats'].items():
801         overall_stats[gt] = to_json(stats)
802
803     elos = {}
804     for gt,elo in player_info['elos'].items():
805         elos[gt] = to_json(elo.to_dict())
806
807     ranks = {}
808     for gt,rank in player_info['ranks'].items():
809         ranks[gt] = to_json(rank)
810
811     fav_maps = {}
812     for gt,mapinfo in player_info['fav_maps'].items():
813         fav_maps[gt] = to_json(mapinfo)
814
815     return [{
816         'version':          1,
817         'player':           player,
818         'games_played':     games_played,
819         'overall_stats':    overall_stats,
820         'fav_maps':         fav_maps,
821         'elos':             elos,
822         'ranks':            ranks,
823     }]
824
825
826 def player_hashkey_info_text(request):
827     """
828     Provides detailed information on a specific player. Plain text.
829     """
830     # UTC epoch
831     now = timegm(datetime.datetime.utcnow().timetuple())
832
833     # All player_info fields are converted into JSON-formattable dictionaries
834     player_info = player_hashkey_info_data(request)
835
836     # gather all of the data up into aggregate structures
837     player = player_info['player']
838     games_played = player_info['games_played']
839     overall_stats = player_info['overall_stats']
840     elos = player_info['elos']
841     ranks = player_info['ranks']
842     fav_maps = player_info['fav_maps']
843
844     # one-offs for things needing conversion for text/plain
845     player_joined = timegm(player.create_dt.timetuple())
846     alivetime = int(datetime_seconds(overall_stats['overall'].total_playing_time))
847
848     # this is a plain text response, if we don't do this here then
849     # Pyramid will assume html
850     request.response.content_type = 'text/plain'
851
852     return {
853         'version':          1,
854         'now':              now,
855         'player':           player,
856         'hashkey':          player_info['hashkey'],
857         'player_joined':    player_joined,
858         'games_played':     games_played,
859         'overall_stats':    overall_stats,
860         'alivetime':        alivetime,
861         'fav_maps':         fav_maps,
862         'elos':             elos,
863         'ranks':            ranks,
864     }
865
866
867 def player_elo_info_data(request):
868     """
869     Provides elo information on a specific player. Raw data is returned.
870     """
871     hashkey = request.matchdict['hashkey']
872     try:
873         player = DBSession.query(Player).\
874                 filter(Player.player_id == Hashkey.player_id).\
875                 filter(Player.active_ind == True).\
876                 filter(Hashkey.hashkey == hashkey).one()
877
878         elos = get_elos(player.player_id)
879
880     except Exception as e:
881         log.debug(e)
882         raise pyramid.httpexceptions.HTTPNotFound
883
884     return {'elos':elos}
885
886
887 def player_elo_info_json(request):
888     """
889     Provides elo information on a specific player. JSON.
890     """
891     elo_info = player_elo_info_data(request)
892
893     elos = {}
894     for gt, elo in elo_info['elos'].items():
895         elos[gt] = to_json(elo.to_dict())
896
897     return [{
898         'version':          1,
899         'elos':             elos,
900     }]
901
902 def player_captimes_data(request):
903     player_id = int(request.matchdict['id'])
904     if player_id <= 2:
905         player_id = -1;
906
907     #player_captimes = DBSession.query(PlayerCaptime).\
908     #        filter(PlayerCaptime.player_id==player_id).\
909     #        order_by(PlayerCaptime.fastest_cap).\
910     #        all()
911
912     PlayerCaptimes = namedtuple('PlayerCaptimes', ['fastest_cap', 'create_dt', 'create_dt_epoch', 'create_dt_fuzzy',
913         'player_id', 'game_id', 'map_id', 'map_name', 'server_id', 'server_name'])
914
915     dbquery = DBSession.query('fastest_cap', 'create_dt', 'player_id', 'game_id', 'map_id',
916                 'map_name', 'server_id', 'server_name').\
917             from_statement(
918                 "SELECT ct.fastest_cap, "
919                        "ct.create_dt, "
920                        "ct.player_id, "
921                        "ct.game_id, "
922                        "ct.map_id, "
923                        "m.name map_name, "
924                        "g.server_id, "
925                        "s.name server_name "
926                 "FROM   player_map_captimes ct, "
927                        "games g, "
928                        "maps m, "
929                        "servers s "
930                 "WHERE  ct.player_id = :player_id "
931                   "AND  g.game_id = ct.game_id "
932                   "AND  g.server_id = s.server_id "
933                   "AND  m.map_id = ct.map_id "
934                 #"ORDER  BY ct.fastest_cap "
935                 "ORDER  BY ct.create_dt desc"
936             ).params(player_id=player_id).all()
937
938     player = DBSession.query(Player).filter_by(player_id=player_id).one()
939
940     player_captimes = []
941     for row in dbquery:
942         player_captimes.append(PlayerCaptimes(
943                 fastest_cap=row.fastest_cap,
944                 create_dt=row.create_dt,
945                 create_dt_epoch=timegm(row.create_dt.timetuple()),
946                 create_dt_fuzzy=pretty_date(row.create_dt),
947                 player_id=row.player_id,
948                 game_id=row.game_id,
949                 map_id=row.map_id,
950                 map_name=row.map_name,
951                 server_id=row.server_id,
952                 server_name=row.server_name,
953             ))
954
955     return {
956             'captimes':player_captimes,
957             'player_id':player_id,
958             'player_url':request.route_url('player_info', id=player_id),
959             'player':player,
960         }
961
962 def player_captimes(request):
963     return player_captimes_data(request)
964
965 def player_captimes_json(request):
966     return player_captimes_data(request)