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