]> de.git.xonotic.org Git - xonotic/xonstat.git/blobdiff - xonstat/views/player.py
Merge branch 'master' into zykure/approved
[xonotic/xonstat.git] / xonstat / views / player.py
index 79ff34b3cbd4b1c19b8d867d6767788f5ac019a8..197a4d28b8301cd3e6a05fca75a02d01c2d74421 100644 (file)
@@ -1,18 +1,14 @@
 import datetime
-import json
 import logging
-import re
+import pyramid.httpexceptions
 import sqlalchemy as sa
 import sqlalchemy.sql.functions as func
-import time
 from calendar import timegm
 from collections import namedtuple
-from pyramid.response import Response
-from pyramid.url import current_route_url
-from sqlalchemy import desc, distinct
-from webhelpers.paginate import Page, PageURL
+from webhelpers.paginate import Page
 from xonstat.models import *
-from xonstat.util import page_url, to_json, pretty_date
+from xonstat.util import page_url, to_json, pretty_date, datetime_seconds
+from xonstat.views.helpers import RecentGame, recent_games_q
 
 log = logging.getLogger(__name__)
 
@@ -30,7 +26,7 @@ def player_index_data(request):
                 filter(sa.not_(Player.nick.like('Anonymous Player%'))).\
                 order_by(Player.player_id.desc())
 
-        players = Page(player_q, current_page, items_per_page=10, url=page_url)
+        players = Page(player_q, current_page, items_per_page=25, url=page_url)
 
     except Exception as e:
         players = None
@@ -79,12 +75,12 @@ def get_games_played(player_id):
                                "g.game_type_cd, "
                                "CASE "
                                  "WHEN g.winner = pgs.team THEN 1 "
-                                 "WHEN pgs.rank = 1 THEN 1 "
+                                 "WHEN pgs.scoreboardpos = 1 THEN 1 "
                                  "ELSE 0 "
                                "END win, "
                                "CASE "
                                  "WHEN g.winner = pgs.team THEN 0 "
-                                 "WHEN pgs.rank = 1 THEN 0 "
+                                 "WHEN pgs.scoreboardpos = 1 THEN 0 "
                                  "ELSE 1 "
                                "END loss "
                         "FROM   games g, "
@@ -134,6 +130,7 @@ def get_overall_stats(player_id):
         - last_played_epoch (same as above, but in seconds since epoch)
         - last_played_fuzzy (same as above, but in relative date)
         - total_playing_time (total amount of time played the game type)
+        - total_playing_time_secs (same as the above, but in seconds)
         - total_pickups (ctf only)
         - total_captures (ctf only)
         - cap_ratio (ctf only)
@@ -145,7 +142,7 @@ def get_overall_stats(player_id):
     """
     OverallStats = namedtuple('OverallStats', ['total_kills', 'total_deaths',
         'k_d_ratio', 'last_played', 'last_played_epoch', 'last_played_fuzzy',
-        'total_playing_time', 'total_pickups', 'total_captures', 'cap_ratio',
+        'total_playing_time', 'total_playing_time_secs', 'total_pickups', 'total_captures', 'cap_ratio',
         'total_carrier_frags', 'game_type_cd'])
 
     raw_stats = DBSession.query('game_type_cd', 'total_kills',
@@ -165,28 +162,25 @@ def get_overall_stats(player_id):
                 "WHERE  g.game_id = pgs.game_id "
                   "AND  pgs.player_id = :player_id "
                 "GROUP  BY g.game_type_cd "
+                "UNION "
+                "SELECT 'overall' game_type_cd, "
+                       "Sum(pgs.kills)         total_kills, "
+                       "Sum(pgs.deaths)        total_deaths, "
+                       "Max(pgs.create_dt)     last_played, "
+                       "Sum(pgs.alivetime)     total_playing_time, "
+                       "Sum(pgs.pickups)       total_pickups, "
+                       "Sum(pgs.captures)      total_captures, "
+                       "Sum(pgs.carrier_frags) total_carrier_frags "
+                "FROM   games g, "
+                       "player_game_stats pgs "
+                "WHERE  g.game_id = pgs.game_id "
+                  "AND  pgs.player_id = :player_id "
             ).params(player_id=player_id).all()
 
     # to be indexed by game_type_cd
     overall_stats = {}
 
-    # sums for the "overall" game type (which is fake)
-    overall_kills = 0
-    overall_deaths = 0
-    overall_last_played = None
-    overall_playing_time = datetime.timedelta(seconds=0)
-    overall_carrier_frags = 0
-
     for row in raw_stats:
-        # running totals or mins
-        overall_kills += row.total_kills or 0
-        overall_deaths += row.total_deaths or 0
-
-        if overall_last_played is None or row.last_played > overall_last_played:
-            overall_last_played = row.last_played
-
-        overall_playing_time += row.total_playing_time
-
         # individual gametype ratio calculations
         try:
             k_d_ratio = float(row.total_kills)/row.total_deaths
@@ -198,8 +192,6 @@ def get_overall_stats(player_id):
         except:
             cap_ratio = None
 
-        overall_carrier_frags += row.total_carrier_frags or 0
-
         # everything else is untouched or "raw"
         os = OverallStats(total_kills=row.total_kills,
                 total_deaths=row.total_deaths,
@@ -208,6 +200,7 @@ def get_overall_stats(player_id):
                 last_played_epoch=timegm(row.last_played.timetuple()),
                 last_played_fuzzy=pretty_date(row.last_played),
                 total_playing_time=row.total_playing_time,
+                total_playing_time_secs=int(datetime_seconds(row.total_playing_time)),
                 total_pickups=row.total_pickups,
                 total_captures=row.total_captures,
                 cap_ratio=cap_ratio,
@@ -216,26 +209,34 @@ def get_overall_stats(player_id):
 
         overall_stats[row.game_type_cd] = os
 
-    # and lastly, the overall stuff
-    try:
-        overall_k_d_ratio = float(overall_kills)/overall_deaths
-    except:
-        overall_k_d_ratio = None
-
-    os = OverallStats(total_kills=overall_kills,
-            total_deaths=overall_deaths,
-            k_d_ratio=overall_k_d_ratio,
-            last_played=overall_last_played,
-            last_played_epoch=timegm(overall_last_played.timetuple()),
-            last_played_fuzzy=pretty_date(overall_last_played),
-            total_playing_time=overall_playing_time,
-            total_pickups=None,
-            total_captures=None,
-            cap_ratio=None,
-            total_carrier_frags=overall_carrier_frags,
-            game_type_cd='overall')
-
-    overall_stats['overall'] = os
+    # We have to edit "overall" stats to exclude deaths in CTS.
+    # Although we still want to record deaths, they shouldn't
+    # count towards the overall K:D ratio.
+    if 'cts' in overall_stats:
+        os = overall_stats['overall']
+
+        try:
+            k_d_ratio = float(os.total_kills)/(os.total_deaths - overall_stats['cts'].total_deaths)
+        except:
+            k_d_ratio = None
+
+        non_cts_deaths = os.total_deaths - overall_stats['cts'].total_deaths
+
+
+        overall_stats['overall'] = OverallStats(
+                total_kills             = os.total_kills,
+                total_deaths            = non_cts_deaths,
+                k_d_ratio               = k_d_ratio,
+                last_played             = os.last_played,
+                last_played_epoch       = os.last_played_epoch,
+                last_played_fuzzy       = os.last_played_fuzzy,
+                total_playing_time      = os.total_playing_time,
+                total_playing_time_secs = os.total_playing_time_secs,
+                total_pickups           = os.total_pickups,
+                total_captures          = os.total_captures,
+                cap_ratio               = os.cap_ratio,
+                total_carrier_frags     = os.total_carrier_frags,
+                game_type_cd            = os.game_type_cd)
 
     return overall_stats
 
@@ -295,7 +296,7 @@ def get_fav_maps(player_id, game_type_cd=None):
             map_id=row.map_id,
             times_played=row.times_played,
             game_type_cd=row.game_type_cd)
-    
+
         # if we aren't given a favorite game_type_cd
         # then the overall favorite is the one we've
         # played the most
@@ -325,7 +326,7 @@ def get_ranks(player_id):
 
     The key to the dictionary is the game type code. There is also an
     "overall" game_type_cd which is the overall best rank.
-    """    
+    """
     Rank = namedtuple('Rank', ['rank', 'max_rank', 'percentile', 'game_type_cd'])
 
     raw_ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
@@ -345,7 +346,7 @@ def get_ranks(player_id):
     for row in raw_ranks:
         rank = Rank(rank=row.rank,
             max_rank=row.max_rank,
-            percentile=100 - 100*float(row.rank)/row.max_rank,
+            percentile=100 - 100*float(row.rank-1)/(row.max_rank-1),
             game_type_cd=row.game_type_cd)
 
 
@@ -390,27 +391,13 @@ def get_elos(player_id):
 
 def get_recent_games(player_id):
     """
-    Provides a list of recent games.
-
-    Returns the full PlayerGameStat, Game, Server, Map
-    objects for all recent games.
+    Provides a list of recent games for a player. Uses the recent_games_q helper.
     """
-    RecentGame = namedtuple('RecentGame', ['player_stats', 'game', 'server', 'map'])
+    # recent games played in descending order
+    rgs = recent_games_q(player_id=player_id).limit(10).all()
+    recent_games = [RecentGame(row) for row in rgs]
 
-    # recent games table, all data
-    recent_games = DBSession.query(PlayerGameStat, Game, Server, Map).\
-            filter(PlayerGameStat.player_id == player_id).\
-            filter(PlayerGameStat.game_id == Game.game_id).\
-            filter(Game.server_id == Server.server_id).\
-            filter(Game.map_id == Map.map_id).\
-            order_by(Game.game_id.desc())[0:10]
-
-    return [
-        RecentGame(player_stats=row.PlayerGameStat,
-            game=row.Game,
-            server=row.Server,
-            map=row.Map)
-        for row in recent_games ]
+    return recent_games
 
 
 def get_recent_weapons(player_id):
@@ -449,7 +436,7 @@ def get_accuracy_stats(player_id, weapon_cd, games):
 
         # Determine the raw accuracy (hit, fired) numbers for $games games
         # This is then enumerated to create parameters for a flot graph
-        raw_accs = DBSession.query(PlayerWeaponStat.game_id, 
+        raw_accs = DBSession.query(PlayerWeaponStat.game_id,
             PlayerWeaponStat.hit, PlayerWeaponStat.fired).\
                 filter(PlayerWeaponStat.player_id == player_id).\
                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
@@ -485,7 +472,7 @@ def get_damage_stats(player_id, weapon_cd, games):
 
         # Determine the damage efficiency (hit, fired) numbers for $games games
         # This is then enumerated to create parameters for a flot graph
-        raw_dmgs = DBSession.query(PlayerWeaponStat.game_id, 
+        raw_dmgs = DBSession.query(PlayerWeaponStat.game_id,
             PlayerWeaponStat.actual, PlayerWeaponStat.hit).\
                 filter(PlayerWeaponStat.player_id == player_id).\
                 filter(PlayerWeaponStat.weapon_cd == weapon_cd).\
@@ -561,38 +548,38 @@ def player_info_json(request):
     """
     Provides detailed information on a specific player. JSON.
     """
-    
+
     # All player_info fields are converted into JSON-formattable dictionaries
-    player_info = player_info_data(request)    
-    
+    player_info = player_info_data(request)
+
     player = player_info['player'].to_dict()
 
     games_played = {}
     for game in player_info['games_played']:
         games_played[game.game_type_cd] = to_json(game)
-    
+
     overall_stats = {}
     for gt,stats in player_info['overall_stats'].items():
         overall_stats[gt] = to_json(stats)
-    
+
     elos = {}
     for gt,elo in player_info['elos'].items():
         elos[gt] = to_json(elo.to_dict())
-    
+
     ranks = {}
     for gt,rank in player_info['ranks'].items():
         ranks[gt] = to_json(rank)
-    
+
     fav_maps = {}
     for gt,mapinfo in player_info['fav_maps'].items():
         fav_maps[gt] = to_json(mapinfo)
-     
+
     recent_games = []
     for game in player_info['recent_games']:
         recent_games.append(to_json(game))
-    
+
     #recent_weapons = player_info['recent_weapons']
-    
+
     return [{
         'player':           player,
         'games_played':     games_played,
@@ -610,35 +597,58 @@ def player_info_json(request):
 def player_game_index_data(request):
     player_id = request.matchdict['player_id']
 
+    game_type_cd = None
+    game_type_descr = None
+
+    if request.params.has_key('type'):
+        game_type_cd = request.params['type']
+        try:
+            game_type_descr = DBSession.query(GameType.descr).\
+                filter(GameType.game_type_cd == game_type_cd).\
+                one()[0]
+        except Exception as e:
+            pass
+
+    else:
+        game_type_cd = None
+        game_type_descr = None
+
     if request.params.has_key('page'):
         current_page = request.params['page']
     else:
         current_page = 1
 
     try:
-        games_q = DBSession.query(Game, Server, Map).\
-            filter(PlayerGameStat.game_id == Game.game_id).\
-            filter(PlayerGameStat.player_id == player_id).\
-            filter(Game.server_id == Server.server_id).\
-            filter(Game.map_id == Map.map_id).\
-            order_by(Game.game_id.desc())
-
-        games = Page(games_q, current_page, items_per_page=10, url=page_url)
-
-        pgstats = {}
-        for (game, server, map) in games:
-            pgstats[game.game_id] = DBSession.query(PlayerGameStat).\
-                    filter(PlayerGameStat.game_id == game.game_id).\
-                    order_by(PlayerGameStat.rank).\
-                    order_by(PlayerGameStat.score).all()
+        player = DBSession.query(Player).\
+                filter_by(player_id=player_id).\
+                filter(Player.active_ind == True).\
+                one()
+
+        rgs_q = recent_games_q(player_id=player.player_id,
+            force_player_id=True, game_type_cd=game_type_cd)
+
+        games = Page(rgs_q, current_page, items_per_page=10, url=page_url)
+
+        # replace the items in the canned pagination class with more rich ones
+        games.items = [RecentGame(row) for row in games.items]
+
+        games_played = get_games_played(player_id)
 
     except Exception as e:
         player = None
         games = None
+        game_type_cd = None
+        game_type_descr = None
+        games_played = None
 
-    return {'player_id':player_id,
+    return {
+            'player_id':player.player_id,
+            'player':player,
             'games':games,
-            'pgstats':pgstats}
+            'game_type_cd':game_type_cd,
+            'game_type_descr':game_type_descr,
+            'games_played':games_played,
+           }
 
 
 def player_game_index(request):
@@ -687,11 +697,11 @@ def player_accuracy_data(request):
         games = len(accs)
 
     return {
-            'player_id':player_id, 
-            'player_url':request.route_url('player_info', id=player_id), 
-            'weapon':weapon_cd, 
-            'games':games, 
-            'avg':avg, 
+            'player_id':player_id,
+            'player_url':request.route_url('player_info', id=player_id),
+            'weapon':weapon_cd,
+            'games':games,
+            'avg':avg,
             'accs':accs
             }
 
@@ -744,11 +754,11 @@ def player_damage_data(request):
         games = len(dmgs)
 
     return {
-            'player_id':player_id, 
-            'player_url':request.route_url('player_info', id=player_id), 
-            'weapon':weapon_cd, 
-            'games':games, 
-            'avg':avg, 
+            'player_id':player_id,
+            'player_url':request.route_url('player_info', id=player_id),
+            'weapon':weapon_cd,
+            'games':games,
+            'avg':avg,
             'dmgs':dmgs
             }
 
@@ -764,3 +774,214 @@ def player_damage_json(request):
        games = over how many games to display damage. Can be up to 50.
     """
     return player_damage_data(request)
+
+
+def player_hashkey_info_data(request):
+    hashkey = request.matchdict['hashkey']
+    try:
+        player = DBSession.query(Player).\
+                filter(Player.player_id == Hashkey.player_id).\
+                filter(Player.active_ind == True).\
+                filter(Hashkey.hashkey == hashkey).one()
+
+        games_played   = get_games_played(player.player_id)
+        overall_stats  = get_overall_stats(player.player_id)
+        fav_maps       = get_fav_maps(player.player_id)
+        elos           = get_elos(player.player_id)
+        ranks          = get_ranks(player.player_id)
+
+    except Exception as e:
+        raise pyramid.httpexceptions.HTTPNotFound
+
+    return {'player':player,
+            'hashkey':hashkey,
+            'games_played':games_played,
+            'overall_stats':overall_stats,
+            'fav_maps':fav_maps,
+            'elos':elos,
+            'ranks':ranks,
+            }
+
+
+def player_hashkey_info_json(request):
+    """
+    Provides detailed information on a specific player. JSON.
+    """
+
+    # All player_info fields are converted into JSON-formattable dictionaries
+    player_info = player_hashkey_info_data(request)
+
+    player = player_info['player'].to_dict()
+
+    games_played = {}
+    for game in player_info['games_played']:
+        games_played[game.game_type_cd] = to_json(game)
+
+    overall_stats = {}
+    for gt,stats in player_info['overall_stats'].items():
+        overall_stats[gt] = to_json(stats)
+
+    elos = {}
+    for gt,elo in player_info['elos'].items():
+        elos[gt] = to_json(elo.to_dict())
+
+    ranks = {}
+    for gt,rank in player_info['ranks'].items():
+        ranks[gt] = to_json(rank)
+
+    fav_maps = {}
+    for gt,mapinfo in player_info['fav_maps'].items():
+        fav_maps[gt] = to_json(mapinfo)
+
+    return [{
+        'version':          1,
+        'player':           player,
+        'games_played':     games_played,
+        'overall_stats':    overall_stats,
+        'fav_maps':         fav_maps,
+        'elos':             elos,
+        'ranks':            ranks,
+    }]
+
+
+def player_hashkey_info_text(request):
+    """
+    Provides detailed information on a specific player. Plain text.
+    """
+    # UTC epoch
+    now = timegm(datetime.datetime.utcnow().timetuple())
+
+    # All player_info fields are converted into JSON-formattable dictionaries
+    player_info = player_hashkey_info_data(request)
+
+    # gather all of the data up into aggregate structures
+    player = player_info['player']
+    games_played = player_info['games_played']
+    overall_stats = player_info['overall_stats']
+    elos = player_info['elos']
+    ranks = player_info['ranks']
+    fav_maps = player_info['fav_maps']
+
+    # one-offs for things needing conversion for text/plain
+    player_joined = timegm(player.create_dt.timetuple())
+    alivetime = int(datetime_seconds(overall_stats['overall'].total_playing_time))
+
+    # this is a plain text response, if we don't do this here then
+    # Pyramid will assume html
+    request.response.content_type = 'text/plain'
+
+    return {
+        'version':          1,
+        'now':              now,
+        'player':           player,
+        'hashkey':          player_info['hashkey'],
+        'player_joined':    player_joined,
+        'games_played':     games_played,
+        'overall_stats':    overall_stats,
+        'alivetime':        alivetime,
+        'fav_maps':         fav_maps,
+        'elos':             elos,
+        'ranks':            ranks,
+    }
+
+
+def player_elo_info_data(request):
+    """
+    Provides elo information on a specific player. Raw data is returned.
+    """
+    hashkey = request.matchdict['hashkey']
+    try:
+        player = DBSession.query(Player).\
+                filter(Player.player_id == Hashkey.player_id).\
+                filter(Player.active_ind == True).\
+                filter(Hashkey.hashkey == hashkey).one()
+
+        elos = get_elos(player.player_id)
+
+    except Exception as e:
+        log.debug(e)
+        raise pyramid.httpexceptions.HTTPNotFound
+
+    return {'elos':elos}
+
+
+def player_elo_info_json(request):
+    """
+    Provides elo information on a specific player. JSON.
+    """
+    elo_info = player_elo_info_data(request)
+
+    elos = {}
+    for gt, elo in elo_info['elos'].items():
+        elos[gt] = to_json(elo.to_dict())
+
+    return [{
+        'version':          1,
+        'elos':             elos,
+    }]
+
+def player_captimes_data(request):
+    player_id = int(request.matchdict['id'])
+    if player_id <= 2:
+        player_id = -1;
+
+    #player_captimes = DBSession.query(PlayerCaptime).\
+    #        filter(PlayerCaptime.player_id==player_id).\
+    #        order_by(PlayerCaptime.fastest_cap).\
+    #        all()
+
+    PlayerCaptimes = namedtuple('PlayerCaptimes', ['fastest_cap', 'create_dt', 'create_dt_epoch', 'create_dt_fuzzy',
+        'player_id', 'game_id', 'map_id', 'map_name', 'server_id', 'server_name'])
+
+    dbquery = DBSession.query('fastest_cap', 'create_dt', 'player_id', 'game_id', 'map_id',
+                'map_name', 'server_id', 'server_name').\
+            from_statement(
+                "SELECT ct.fastest_cap, "
+                       "ct.create_dt, "
+                       "ct.player_id, "
+                       "ct.game_id, "
+                       "ct.map_id, "
+                       "m.name map_name, "
+                       "g.server_id, "
+                       "s.name server_name "
+                "FROM   player_map_captimes ct, "
+                       "games g, "
+                       "maps m, "
+                       "servers s "
+                "WHERE  ct.player_id = :player_id "
+                  "AND  g.game_id = ct.game_id "
+                  "AND  g.server_id = s.server_id "
+                  "AND  m.map_id = ct.map_id "
+                #"ORDER  BY ct.fastest_cap "
+                "ORDER  BY ct.create_dt desc"
+            ).params(player_id=player_id).all()
+
+    player = DBSession.query(Player).filter_by(player_id=player_id).one()
+
+    player_captimes = []
+    for row in dbquery:
+        player_captimes.append(PlayerCaptimes(
+                fastest_cap=row.fastest_cap,
+                create_dt=row.create_dt,
+                create_dt_epoch=timegm(row.create_dt.timetuple()),
+                create_dt_fuzzy=pretty_date(row.create_dt),
+                player_id=row.player_id,
+                game_id=row.game_id,
+                map_id=row.map_id,
+                map_name=row.map_name,
+                server_id=row.server_id,
+                server_name=row.server_name,
+            ))
+
+    return {
+            'captimes':player_captimes,
+            'player_id':player_id,
+            'player_url':request.route_url('player_info', id=player_id),
+            'player':player,
+        }
+
+def player_captimes(request):
+    return player_captimes_data(request)
+
+def player_captimes_json(request):
+    return player_captimes_data(request)