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