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