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