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