]> de.git.xonotic.org Git - xonotic/xonstat.git/commitdiff
Merge of zykure's player_info JSON object plus a few bugfixes.
authorAnt Zucaro <azucaro@gmail.com>
Sun, 16 Sep 2012 03:48:08 +0000 (23:48 -0400)
committerAnt Zucaro <azucaro@gmail.com>
Sun, 16 Sep 2012 03:48:08 +0000 (23:48 -0400)
13 files changed:
.gitignore
development.ini
setup.py
xonstat/batch/badges/gen_badges.py
xonstat/batch/badges/skin.py
xonstat/crypto-keygen-standalone [new symlink]
xonstat/static/images/icons/48x48/overall.png [new file with mode: 0644]
xonstat/static/js/bootstrap-tabs.js [new file with mode: 0644]
xonstat/templates/base.mako
xonstat/templates/navlinks.mako
xonstat/templates/player_info.mako
xonstat/util.py
xonstat/views/player.py

index 8e48bc7692b8264bb196983b972be87bab001422..aa68c64a5008f1b10c4d0ce376f1a6b028a9e795 100644 (file)
@@ -1,5 +1,7 @@
-*.pyc
 *~
 *.bak
-xonstat/batch/badges/output/*.png
-xonstat/batch/badges/output/*/*.png
+*.tmp
+*.old
+*.pyc
+/xonstat/batch/badges/output/*.png
+/xonstat/batch/badges/output/*/*.png
index c3d1cf83f50a443f9ffc25209d2c372f447d1b2f..4ba4338e332186a69e0a28f7503cf4b2cc4e2bd4 100755 (executable)
@@ -6,7 +6,7 @@ debug_notfound = false
 debug_routematch = false
 debug_templates = true
 default_locale_name = en
-sqlalchemy.url = postgresql+psycopg2://xonstat:xonstat@localhost:5433/xonstatdb
+sqlalchemy.url = postgresql+psycopg2://xonstat:xonstat@localhost:5432/xonstatdb
 session.type = file
 session.data_dir = %(here)s/data/sessions/data
 session.lock_dir = %(here)s/data/sessions/lock
index ab818f2065892c348b51f5f4c33fba46debd9734..38572a23635c029674d2756496351e4627d337c8 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -4,7 +4,7 @@ import sys
 from setuptools import setup, find_packages
 
 here = os.path.abspath(os.path.dirname(__file__))
-README = open(os.path.join(here, 'README.txt')).read()
+README = open(os.path.join(here, 'README.md')).read()
 CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
 
 requires = [
index 1d3acf1a02c1ac49ba69a73f69129a420560aa0d..44d73aec3da4f1ea2a16690cf9e965c954777b33 100644 (file)
@@ -7,6 +7,7 @@ import sqlalchemy.sql.functions as func
 from sqlalchemy import distinct
 from pyramid.paster import bootstrap
 from xonstat.models import *
+from xonstat.util import datetime_seconds
 
 from skin import Skin
 from playerdata import PlayerData
@@ -113,7 +114,6 @@ for arg in sys.argv[1:]:
 if len(skins) == 0:
     skins = [ skin_classic, skin_minimal ]
 
-
 # environment setup
 env = bootstrap('../../../development.ini')
 req = env['request']
@@ -147,8 +147,7 @@ playerdata = PlayerData()
 if len(players) > 0:
     stop = datetime.now()
     td = stop-start
-    total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
-    print "Query took %.2f seconds" % (total_seconds)
+    print "Query took %.2f seconds" % (datetime_seconds(td))
 
     print "Creating badges for %d players ..." % len(players)
     start = datetime.now()
@@ -160,20 +159,18 @@ if len(players) > 0:
         playerdata.get_data(player_id)
         sstop = datetime.now()
         td = sstop-sstart
-        total_seconds = float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
-        data_time += total_seconds
+        data_time += datetime_seconds(td)
 
         sstart = datetime.now()
         for sk in skins:
             sk.render_image(playerdata, "output/%s/%d.png" % (str(sk), player_id[0]))
         sstop = datetime.now()
         td = sstop-sstart
-        total_seconds = float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
-        render_time += total_seconds
+        render_time += datetime_seconds(td)
 
     stop = datetime.now()
     td = stop-start
-    total_seconds = float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
+    total_seconds = datetime_seconds(td)
     print "Creating the badges took %.1f seconds (%.3f s per player)" % (total_seconds, total_seconds/float(len(players)))
     print "Total time for rendering images: %.3f s" % render_time
     print "Total time for getting data: %.3f s" % data_time
index 56bc1d09b3bdbc1cb73e890c2aa43b48813ac216..399bb7989a025a4eeec7068f3c6f5abf3a7cdeaa 100644 (file)
@@ -15,7 +15,7 @@ _dec_colors = [ (0.5,0.5,0.5),
                 (1.0,1.0,0.0),
                 (0.2,0.4,1.0),
                 (0.2,1.0,1.0),
-                (1.0,0.2,102),
+                (1.0,0.2,0.4),
                 (1.0,1.0,1.0),
                 (0.6,0.6,0.6),
                 (0.5,0.5,0.5)
@@ -266,11 +266,11 @@ class Skin:
         # fontsize is reduced if width gets too large
         ctx.select_font_face(self.font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
         shrinknick = 0
-        while shrinknick < 10:
+        while shrinknick < 0.6*fontsize:
             ctx.set_font_size(self.nick_fontsize - shrinknick)
             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
             if tw > self.nick_maxwidth:
-                shrinknick += 2
+                shrinknick += 1
                 continue
             break
 
diff --git a/xonstat/crypto-keygen-standalone b/xonstat/crypto-keygen-standalone
new file mode 120000 (symlink)
index 0000000..32f91eb
--- /dev/null
@@ -0,0 +1 @@
+/usr/local/games/Xonotic/misc/infrastructure/keygen/crypto-keygen-standalone
\ No newline at end of file
diff --git a/xonstat/static/images/icons/48x48/overall.png b/xonstat/static/images/icons/48x48/overall.png
new file mode 100644 (file)
index 0000000..5a2b5e9
Binary files /dev/null and b/xonstat/static/images/icons/48x48/overall.png differ
diff --git a/xonstat/static/js/bootstrap-tabs.js b/xonstat/static/js/bootstrap-tabs.js
new file mode 100644 (file)
index 0000000..a3c7ee1
--- /dev/null
@@ -0,0 +1,80 @@
+/* ========================================================
+ * bootstrap-tabs.js v1.4.0
+ * http://twitter.github.com/bootstrap/javascript.html#tabs
+ * ========================================================
+ * Copyright 2011 Twitter, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ======================================================== */
+
+
+!function( $ ){
+
+  "use strict"
+
+  function activate ( element, container ) {
+    container
+      .find('> .active')
+      .removeClass('active')
+      .find('> .dropdown-menu > .active')
+      .removeClass('active')
+
+    element.addClass('active')
+
+    if ( element.parent('.dropdown-menu') ) {
+      element.closest('li.dropdown').addClass('active')
+    }
+  }
+
+  function tab( e ) {
+    var $this = $(this)
+      , $ul = $this.closest('ul:not(.dropdown-menu)')
+      , href = $this.attr('href')
+      , previous
+      , $href
+
+    if ( /^#\w+/.test(href) ) {
+      e.preventDefault()
+
+      if ( $this.parent('li').hasClass('active') ) {
+        return
+      }
+
+      previous = $ul.find('.active a').last()[0]
+      $href = $(href)
+
+      activate($this.parent('li'), $ul)
+      activate($href, $href.parent())
+
+      $this.trigger({
+        type: 'change'
+      , relatedTarget: previous
+      })
+    }
+  }
+
+
+ /* TABS/PILLS PLUGIN DEFINITION
+  * ============================ */
+
+  $.fn.tabs = $.fn.pills = function ( selector ) {
+    return this.each(function () {
+      $(this).delegate(selector || '.tabs li > a, .pills > li > a', 'click', tab)
+    })
+  }
+
+  $(document).ready(function () {
+    $('body').tabs('ul[data-tabs] li > a, ul[data-pills] > li > a')
+  })
+
+}( window.jQuery || window.ender );
index b9b00f73f5a92309cddc63a5b780c512ef22f332..c935dc6563011b5f250928319c479f69c3ceb735 100644 (file)
@@ -16,6 +16,8 @@
     <link href="/static/css/style.css" rel="stylesheet">
     <link type="images/vnd.microsoft.icon" rel="shortcut icon" href="/static/favicon.ico">
     </%block>
+    
+    <script src="/static/js/jquery-1.7.1.min.js"></script>
   </head>
 
   <body>
index 5c1fa4fae06a36f1a8f2d54667bc3f6b5ce2229d..4f9aa837e18db3ced656bab62b08d11d29ed8e8e 100644 (file)
@@ -6,6 +6,10 @@ if 'search_query' in kwargs.keys():
     kwargs['_query'] = dict(kwargs['_query'].items() + kwargs['search_query'].items())
 %>
 
+% if not last:
+    <% last = 1 %>
+% endif
+
 % if not (curr == last and curr == 1):
     % if curr != 1:
             <% kwargs['_query']['page'] = curr-1 %>
index 3149228e486c7b5c168efd5d4f43486818ba715f..c88c96c27c924cf3511fbc72ec9b5a7fc6abd033 100644 (file)
@@ -8,11 +8,14 @@ ${nav.nav('players')}
 
 <%block name="js">
     % if player is not None:
-      <script src="/static/js/jquery-1.7.1.min.js"></script>
       <script src="/static/js/jquery.flot.min.js"></script>
+      <script src="/static/js/bootstrap-tabs.js"></script>
       <script type="text/javascript">
-      $(function () {
+      jQuery(document).ready(function ($) {
+          $(".tabs").tabs();
+      });      
 
+      $(function () {
           // plot the accuracy graph
           function plot_acc_graph(data) {
               var games = new Array();
@@ -77,10 +80,12 @@ ${nav.nav('players')}
           }
 
           var previousPoint = null;
+          var previousLabel = null;
           $('#acc-graph').bind("plothover", function (event, pos, item) {
               if (item) {
-                  if (previousPoint != item.dataIndex) {
+                  if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
                     previousPoint = item.dataIndex;
+                    previousLabel = item.series.label;
 
                     $("#tooltip").remove();
                     var x = item.datapoint[0].toFixed(2),
@@ -92,13 +97,15 @@ ${nav.nav('players')}
               else {
                   $("#tooltip").remove();
                   previousPoint = null;
+                  previousLabel = null;
               }
           });
 
           $('#dmg-graph').bind("plothover", function (event, pos, item) {
               if (item) {
-                  if (previousPoint != item.dataIndex) {
+                  if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
                     previousPoint = item.dataIndex;
+                    previousLabel = item.series.label;
 
                     $("#tooltip").remove();
                     var x = item.datapoint[0].toFixed(2),
@@ -110,6 +117,7 @@ ${nav.nav('players')}
               else {
                   $("#tooltip").remove();
                   previousPoint = null;
+                  previousLabel = null;
               }
           });
 
@@ -158,6 +166,7 @@ ${nav.nav('players')}
           });
       })
       </script>
+      <script src="/static/js/bootstrap-tabs.min.js"></script>
     % endif
 </%block>
 
@@ -184,33 +193,55 @@ Player Information
 
       Last Seen: <small><span class="abstime" data-epoch="${recent_games[0][1].epoch()}" title="${recent_games[0][1].create_dt.strftime('%a, %d %b %Y %H:%M:%S UTC')}">${recent_games[0][1].fuzzy_date()}</span> </small><br />
 
-      Playing Time: <small>${total_stats['alivetime']} </small><br />
-
-      <% games_breakdown_str = ', '.join(["{0} {1}".format(ng, gt) for (gt, ng) in games_breakdown]) %>
-      Games Played: <small>${total_games} (${games_breakdown_str})</small><br />
-
-      % if fav_map is not None:
-      Favorite Map: <small><a href="${request.route_url('map_info', id=fav_map['id'])}" title="view map info">${fav_map['name']}</a></small><br />
+      Playing Time: <small>${total_stats['alivetime']}
+      % if total_stats['alivetime_month'] and total_stats['alivetime'] > total_stats['alivetime_month']:
+          % if total_stats['alivetime_week'] and total_stats['alivetime_month'] > total_stats['alivetime_week']:
+              <br />(${total_stats['alivetime_month']} this month; ${total_stats['alivetime_week']} this week)
+          % else:
+              <br />(${total_stats['alivetime_month']} this month)
+          % endif
       % endif
+      </small><br />
+
+      <% games_breakdown_str = ', '.join(["{0} {1}".format(ng, gt) for (gt, ng) in total_stats['games_breakdown'].items()]) %>
+      Games Played: <small>${total_stats['games']}<br />(${games_breakdown_str})</small><br />
     </p>
   </div>
   <div class="span6">
     <p>
-       % if total_games > 0 and total_stats['wins'] is not None:
-       Win Percentage: <small>${round(float(total_stats['wins'])/total_games * 100, 2)}% (${total_stats['wins']} wins, ${total_games - total_stats['wins']} losses) </small><br />
-       % endif
+      % if fav_server is not None:
+      Favorite Server: <small><a href="${request.route_url('server_info', id=fav_server[0]['id'])}" title="view server info">${fav_server[0]['name']}</a></small><br />
+      % endif
+
+      % if fav_map is not None:
+      Favorite Map: <small><a href="${request.route_url('map_info', id=fav_map[0]['id'])}" title="view map info">${fav_map[0]['name']}</a></small><br />
+      % endif
+
+      % if fav_weapon is not None:
+      Favorite Weapon: <small>${fav_weapon[0]['name']}</small><br />
+      % endif
+
+      % if total_stats['games'] > 0 and total_stats['wins'] is not None:
+      Win Percentage: <small>${round(float(total_stats['wins'])/total_stats['games'] * 100, 2)}% (${total_stats['wins']} wins, ${total_stats['games'] - total_stats['wins']} losses) </small><br />
+      % endif
 
-       % if total_stats['kills'] > 0 and total_stats['deaths'] > 0:
-       Kill Ratio: <small>${round(float(total_stats['kills'])/total_stats['deaths'], 3)} (${total_stats['kills']} kills, ${total_stats['deaths']} deaths) </small><br />
-       % endif
+      % if total_stats['kills'] > 0 and total_stats['deaths'] > 0:
+      Kill Ratio: <small>${round(float(total_stats['kills'])/total_stats['deaths'], 3)} (${total_stats['kills']} kills, ${total_stats['deaths']} deaths, ${total_stats['suicides']} suicides) </small><br />
+      % endif
+    </p>
+  </div>
+</div>
 
+<div class="row">
+  <div class="span12">
+    <p>
        % if elos_display is not None and len(elos_display) > 0:
        Elo:
-          <small>${', '.join(elos_display)} </small>
-          <br />
-          %if '*' in ', '.join(elos_display):
-              <small><i>*preliminary Elo</i></small><br />
+          <small>${elos_display} </small>
+          %if '*' in elos_display:
+              <small><i>*preliminary Elo</i></small>
           %endif
+          <br />
       % endif
 
       % if ranks_display != '':
@@ -220,7 +251,6 @@ Player Information
   </div>
 </div>
 
-
 % if 'nex' in recent_weapons or 'rifle' in recent_weapons or 'minstanex' in recent_weapons or 'uzi' in recent_weapons or 'shotgun' in recent_weapons:
 <div class="row">
   <div class="span10">
@@ -235,7 +265,7 @@ Player Information
           <div class="acc-weap weapon-active">
             <img src="${request.static_url("xonstat:static/images/nex.png")}" />
             <p><small>Nex</small></p>
-            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'nex'})}" title="Show nex accuracy"></a>
+            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','nex')])}" title="Show nex accuracy"></a>
           </div>
         </li>
         % endif
@@ -245,7 +275,7 @@ Player Information
           <div class="acc-weap">
             <img src="${request.static_url("xonstat:static/images/rifle.png")}" />
             <p><small>Rifle</small></p>
-            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'rifle'})}" title="Show rifle accuracy"></a>
+            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','rifle')])}" title="Show rifle accuracy"></a>
           </div>
         </li>
         % endif
@@ -255,7 +285,7 @@ Player Information
           <div class="acc-weap">
             <img src="${request.static_url("xonstat:static/images/minstanex.png")}" />
             <p><small>Minstanex</small></p>
-            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'minstanex'})}" title="Show minstanex accuracy"></a>
+            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','minstanex')])}" title="Show minstanex accuracy"></a>
           </div>
         </li>
         % endif
@@ -265,7 +295,7 @@ Player Information
           <div class="acc-weap">
             <img src="${request.static_url("xonstat:static/images/uzi.png")}" />
             <p><small>Uzi</small></p>
-            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'uzi'})}" title="Show uzi accuracy"></a>
+            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','uzi')])}" title="Show uzi accuracy"></a>
           </div>
         </li>
         % endif
@@ -275,7 +305,7 @@ Player Information
           <div class="acc-weap">
             <img src="${request.static_url("xonstat:static/images/shotgun.png")}" />
             <p><small>Shotgun</small></p>
-            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'shotgun'})}" title="Show shotgun accuracy"></a>
+            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','shotgun')])}" title="Show shotgun accuracy"></a>
           </div>
         </li>
         % endif
@@ -301,7 +331,7 @@ Player Information
           <div class="dmg-weap weapon-active">
             <img src="${request.static_url("xonstat:static/images/rocketlauncher.png")}" />
             <p><small>Rocket</small></p>
-            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'rocketlauncher'})}" title="Show rocket launcher efficiency"></a>
+            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','rocketlauncher')])}" title="Show rocket launcher efficiency"></a>
           </div>
         </li>
         % endif
@@ -311,7 +341,7 @@ Player Information
           <div class="dmg-weap">
             <img src="${request.static_url("xonstat:static/images/grenadelauncher.png")}" />
             <p><small>Mortar</small></p>
-            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'grenadelauncher'})}" title="Show mortar damage efficiency"></a>
+            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','grenadelauncher')])}" title="Show mortar damage efficiency"></a>
           </div>
         </li>
         % endif
@@ -321,7 +351,7 @@ Player Information
           <div class="dmg-weap">
             <img src="${request.static_url("xonstat:static/images/electro.png")}" />
             <p><small>Electro</small></p>
-            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'electro'})}" title="Show electro damage efficiency"></a>
+            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','electro')])}" title="Show electro damage efficiency"></a>
           </div>
         </li>
         % endif
@@ -331,7 +361,7 @@ Player Information
           <div class="dmg-weap">
             <img src="${request.static_url("xonstat:static/images/crylink.png")}" />
             <p><small>Crylink</small></p>
-            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'crylink'})}" title="Show crylink damage efficiency"></a>
+            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','crylink')])}" title="Show crylink damage efficiency"></a>
           </div>
         </li>
         % endif
@@ -341,7 +371,7 @@ Player Information
           <div class="dmg-weap">
             <img src="${request.static_url("xonstat:static/images/hagar.png")}" />
             <p><small>Hagar</small></p>
-            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'hagar'})}" title="Show hagar damage efficiency"></a>
+            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','hagar')])}" title="Show hagar damage efficiency"></a>
           </div>
         </li>
         % endif
@@ -351,7 +381,7 @@ Player Information
           <div class="dmg-weap">
             <img src="${request.static_url("xonstat:static/images/laser.png")}" />
             <p><small>Laser</small></p>
-            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'laser'})}" title="Show laser damage efficiency"></a>
+            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','laser')])}" title="Show laser damage efficiency"></a>
           </div>
         </li>
         % endif
@@ -363,9 +393,166 @@ Player Information
 </div>
 % endif
 
+<div class="row">
+  <div class="span8 tabbable">
+    <h3>Game Breakdown</h3>
+    <ul class="tabs nav nav-pills" data-tabs="tabs">
+    <% gametypes = ['Overall', 'Duel', 'DM', 'TDM', 'CTF'] %>
+    % for gtc in gametypes:
+      % if gtc.lower() == 'overall' or total_stats['games_breakdown'].has_key(gtc.lower()):
+        % if gtc.lower() == 'overall':
+      <li class="active">
+        % else:
+      <li>
+        % endif
+        <a href="#breakdown-${gtc.lower()}" data-toggle="tabs">${gtc}</a>
+      </li>
+      % endif
+    % endfor
+    </ul>
+    <div class="tab-content">
+    % for gtc in gametypes:
+      <% gtc_key = gtc.lower() %>
+      % if gtc_key == "overall":
+        <% total     = total_stats['games'] %>
+        <% alivetime = total_stats['alivetime'] %>
+        <% wins      = total_stats['wins'] %>
+        <% losses    = total - wins %>
+        <% kills     = total_stats['kills'] %>
+        <% deaths    = total_stats['deaths'] %>
+        <% suicides  = total_stats['suicides'] %>
+      % elif total_stats['games_breakdown'].has_key(gtc_key):
+        <% total     = total_stats['games_breakdown'][gtc_key] %>
+        <% alivetime = total_stats['games_alivetime'][gtc_key] %>
+        <% wins      = total_stats[gtc_key+'_wins'] %>
+        <% losses    = total - wins %>
+        % if gtc_key == "ctf":
+          <% caps      = total_stats[gtc_key+'_caps'] %>
+          <% pickups   = total_stats[gtc_key+'_pickups'] %>
+          <% returns   = total_stats[gtc_key+'_returns'] %>
+          <% drops     = total_stats[gtc_key+'_drops'] %>
+          <% fckills   = total_stats[gtc_key+'_fckills'] %>
+        % else:
+          <% kills     = total_stats[gtc_key+'_kills'] %>
+          <% deaths    = total_stats[gtc_key+'_deaths'] %>
+          <% suicides  = total_stats[gtc_key+'_suicides'] %>
+        % endif
+      % endif
+      % if gtc_key == 'overall' or total_stats['games_breakdown'].has_key(gtc_key):
+        % if gtc_key == 'overall':
+      <div class="tab-pane active" id="breakdown-${gtc_key}">
+        % else:
+      <div class="tab-pane" id="breakdown-${gtc_key}">
+        % endif
+        <div style="margin:15px;float:left;"><img title="${gtc}" src="/static/images/icons/48x48/${gtc_key}.png" alt="${gtc}" /></div>
+        <table class="table table-bordered table-condensed">
+          <thead>
+          </thead>
+          <tbody>
+            <tr>
+              <td><b>Games Played:</b></td>
+              <td>${total}</td>
+              % if gtc_key == 'overall':
+              <td></td>
+              % else:
+              <td>${round(float(total)/total_stats['games'] * 100, 2)}% of all games</td>
+              % endif
+            </tr>
+            <tr>
+              <td><b>Playing Time:</b></td>
+              <td>${alivetime} hours</td>
+              % if gtc_key == 'overall':
+              <td></td>
+              % else:
+              <td>${round(float(alivetime.total_seconds())/total_stats['alivetime'].total_seconds() * 100, 2)}% of total playing time</td>
+              % endif
+            </tr>
+            <tr>
+              <td width="30%"><b>Win Percentage:</b></td>
+              <td width="30%">${round(float(wins)/total * 100, 2)}%</td>
+              <td width="40%">${wins} wins, ${losses} losses</td>
+            </tr>
+            % if gtc_key == 'ctf':
+            <tr>
+              <td><b>Caps:</b></td>
+              <td>${round(float(caps)/total, 2)} per game</td>
+              <td>${caps} total</td>
+            </tr>
+            <tr>
+              <td><b>Pickups:</b></td>
+              <td>${round(float(pickups)/total, 2)} per game</td>
+              <td>${pickups} total</td>
+            </tr>
+            <tr>
+              <td><b>Drops:</b></td>
+              <td>${round(float(drops)/total, 2)} per game</td>
+              <td>${drops} total</td>
+            </tr>
+            <tr>
+              <td><b>Returns:</b></td>
+              <td>${round(float(returns)/total, 2)} per game</td>
+              <td>${returns} total</td>
+            </tr>
+            <tr>
+              <td><b>FC Kills:</b></td>
+              <td>${round(float(fckills)/total, 2)} per game</td>
+              <td>${fckills} total</td>
+            </tr>
+            <tr>
+              <td><b>Cap Ratio:</b></td>
+              <td>${round(float(caps)/pickups, 3)}</td>
+              <td></td>
+            </tr>
+            <tr>
+              <td><b>Drop Ratio:</b></td>
+              <td>${round(float(drops)/pickups, 3)}</td>
+              <td></td>
+            </tr>
+            <tr>
+              <td><b>Return Ratio:</b></td>
+              <td>${round(float(returns)/fckills, 3)}</td>
+              <td></td>
+            </tr>
+            % else:
+            <tr>
+              <td><b>Kills:</b></td>
+              <td>${round(float(kills)/total, 2)} per game</td>
+              <td>${kills} total</td>
+            </tr>
+            <tr>
+              <td><b>Deaths:</b></td>
+              <td>${round(float(deaths)/total, 2)} per game</td>
+              <td>${deaths} total</td>
+            </tr>
+            <tr>
+              <td><b>Suicides:</b></td>
+              <td>${round(float(suicides)/total, 2)} per game</td>
+              <td>${suicides} total</td>
+            </tr>
+            <tr>
+              <td><b>Kill Ratio:</b></td>
+              <td>${round(float(kills)/deaths, 3)}</td>
+              <td></td>
+            </tr>
+            <tr>
+              <td><b>Suicide Ratio:</b></td>
+              <td>${round(float(suicides)/deaths, 3)}</td>
+              <td></td>
+            </tr>
+            % endif
+          </tbody>
+        </table>
+      </div>
+      % endif
+    % endfor
+    </div>
+  </div>
+</div>
+
 
 ##### RECENT GAMES (v2) ####
 % if recent_games:
+<br />
 <div class="row">
   <div class="span12">
     <h3>Recent Games</h3>
index f9aa1d5c07f96135f47cfdc71d2972bb3b693ec1..7c2692d45d51651605b2e78ba9ff98929fd7fd50 100644 (file)
@@ -151,3 +151,7 @@ def pretty_date(time=False):
         return "almost 2 years ago"
     else:
         return "about {0} years ago".format(int(round(dim/525600.0)))
+
+def datetime_seconds(td):
+    return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
+
index b1fbd5d8ca643ef2f84613fc345dbace2126000f..a783785324bf8a2ab021503717152b192194caa4 100644 (file)
@@ -10,7 +10,7 @@ from pyramid.url import current_route_url
 from sqlalchemy import desc, distinct
 from webhelpers.paginate import Page, PageURL
 from xonstat.models import *
-from xonstat.util import page_url
+from xonstat.util import page_url, datetime_seconds
 
 log = logging.getLogger(__name__)
 
@@ -54,6 +54,8 @@ def player_index_json(request):
 
 def _get_games_played(player_id):
     """
+    DEPRECATED: Now included in _get_total_stats()
+    
     Provides a breakdown by gametype of the games played by player_id.
 
     Returns a tuple containing (total_games, games_breakdown), where
@@ -73,30 +75,68 @@ def _get_games_played(player_id):
     return (total, games_played)
 
 
-# TODO: should probably factor the above function into this one such that
-# total_stats['ctf_games'] is the count of CTF games and so on...
 def _get_total_stats(player_id):
     """
     Provides aggregated stats by player_id.
 
     Returns a dict with the keys 'kills', 'deaths', 'alivetime'.
 
+    games = how many games a player has played
+    games_breakdown = how many games of given type a player has played (dictionary)
+    games_alivetime = how many time a player has spent in a give game type (dictionary)
     kills = how many kills a player has over all games
     deaths = how many deaths a player has over all games
+    suicides = how many suicides a player has over all games
     alivetime = how long a player has played over all games
+    alivetime_week = how long a player has played over all games in the last week
+    alivetime_month = how long a player has played over all games in the last month
+    wins = how many games a player has won
 
     If any of the above are None, they are set to 0.
     """
+    # 7 and 30 day windows
+    one_week_ago  = datetime.datetime.utcnow() - datetime.timedelta(days=7)
+    one_month_ago = datetime.datetime.utcnow() - datetime.timedelta(days=30)
+
     total_stats = {}
-    (total_stats['kills'], total_stats['deaths'], total_stats['alivetime']) = DBSession.\
-            query("total_kills", "total_deaths", "total_alivetime").\
-            from_statement(
-                "select sum(kills) total_kills, "
-                "sum(deaths) total_deaths, "
-                "sum(alivetime) total_alivetime "
-                "from player_game_stats "
-                "where player_id=:player_id"
-            ).params(player_id=player_id).one()
+
+    games_played = DBSession.query(
+            Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(PlayerGameStat.player_id == player_id).\
+            group_by(Game.game_type_cd).\
+            order_by(func.count().desc()).\
+            all()
+
+    total_stats['games'] = 0
+    total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
+    total_stats['games_alivetime'] = {}
+    for (game_type_cd, games, alivetime) in games_played:
+        total_stats['games'] += games
+        total_stats['games_breakdown'][game_type_cd] = games
+        total_stats['games_alivetime'][game_type_cd] = alivetime
+
+     # more fields can be added here, e.g. 'collects' for kh games
+    (total_stats['kills'], total_stats['deaths'], total_stats['suicides'],
+     total_stats['alivetime'],) = DBSession.query(
+            func.sum(PlayerGameStat.kills),
+            func.sum(PlayerGameStat.deaths),
+            func.sum(PlayerGameStat.suicides),
+            func.sum(PlayerGameStat.alivetime)).\
+            filter(PlayerGameStat.player_id == player_id).\
+            one()
+
+    (total_stats['alivetime_week'],) = DBSession.query(
+            func.sum(PlayerGameStat.alivetime)).\
+            filter(PlayerGameStat.player_id == player_id).\
+            filter(PlayerGameStat.create_dt > one_week_ago).\
+            one()
+
+    (total_stats['alivetime_month'],) = DBSession.query(
+            func.sum(PlayerGameStat.alivetime)).\
+            filter(PlayerGameStat.player_id == player_id).\
+            filter(PlayerGameStat.create_dt > one_month_ago).\
+            one()
 
     (total_stats['wins'],) = DBSession.\
             query("total_wins").\
@@ -108,6 +148,84 @@ def _get_total_stats(player_id):
                 "and (g.winner = pgs.team or pgs.rank = 1)"
             ).params(player_id=player_id).one()
 
+#    (total_stats['wins'],) = DBSession.query(
+#            func.count("*")).\
+#            filter(Game.game_id == PlayerGameStat.game_id).\
+#            filter(PlayerGameStat.player_id == player_id).\
+#            filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
+#            one()
+
+    (total_stats['duel_wins'],) = DBSession.query(
+            func.count("*")).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.game_type_cd == "duel").\
+            filter(PlayerGameStat.player_id == player_id).\
+            filter(PlayerGameStat.rank == 1).\
+            one()
+
+    (total_stats['duel_kills'], total_stats['duel_deaths'], total_stats['duel_suicides'],) = DBSession.query(
+            func.sum(PlayerGameStat.kills),
+            func.sum(PlayerGameStat.deaths),
+            func.sum(PlayerGameStat.suicides)).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.game_type_cd == "duel").\
+            filter(PlayerGameStat.player_id == player_id).\
+            one()
+
+    (total_stats['dm_wins'],) = DBSession.query(
+            func.count("*")).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.game_type_cd == "dm").\
+            filter(PlayerGameStat.player_id == player_id).\
+            filter(PlayerGameStat.rank == 1).\
+            one()
+
+    (total_stats['dm_kills'], total_stats['dm_deaths'], total_stats['dm_suicides'],) = DBSession.query(
+            func.sum(PlayerGameStat.kills),
+            func.sum(PlayerGameStat.deaths),
+            func.sum(PlayerGameStat.suicides)).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.game_type_cd == "dm").\
+            filter(PlayerGameStat.player_id == player_id).\
+            one()
+
+    (total_stats['tdm_kills'], total_stats['tdm_deaths'], total_stats['tdm_suicides'],) = DBSession.query(
+            func.sum(PlayerGameStat.kills),
+            func.sum(PlayerGameStat.deaths),
+            func.sum(PlayerGameStat.suicides)).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.game_type_cd == "tdm").\
+            filter(PlayerGameStat.player_id == player_id).\
+            one()
+
+    (total_stats['tdm_wins'],) = DBSession.query(
+            func.count("*")).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.game_type_cd == "tdm").\
+            filter(PlayerGameStat.player_id == player_id).\
+            filter(PlayerGameStat.rank == 1).\
+            one()
+
+    (total_stats['ctf_wins'],) = DBSession.query(
+            func.count("*")).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.game_type_cd == "ctf").\
+            filter(PlayerGameStat.player_id == player_id).\
+            filter(PlayerGameStat.rank == 1).\
+            one()
+
+    (total_stats['ctf_caps'], total_stats['ctf_pickups'], total_stats['ctf_drops'],
+     total_stats['ctf_returns'], total_stats['ctf_fckills'],) = DBSession.query(
+            func.sum(PlayerGameStat.captures),
+            func.sum(PlayerGameStat.pickups),
+            func.sum(PlayerGameStat.drops),
+            func.sum(PlayerGameStat.returns),
+            func.sum(PlayerGameStat.carrier_frags)).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.game_type_cd == "ctf").\
+            filter(PlayerGameStat.player_id == player_id).\
+            one()
+
     for (key,value) in total_stats.items():
         if value == None:
             total_stats[key] = 0
@@ -133,15 +251,80 @@ def _get_fav_map(player_id):
             filter(PlayerGameStat.create_dt > back_then).\
             group_by(Map.name, Map.map_id).\
             order_by(func.count().desc()).\
-            limit(1).one()
+            limit(5).all()
 
-    fav_map = {}
-    fav_map['name'] = raw_fav_map[0]
-    fav_map['id'] = raw_fav_map[1]
+    fav_map = []
+    for map_e in raw_fav_map:
+        entry = {}
+        entry['name'] = map_e[0]
+        entry['id']   = map_e[1]
+        fav_map.append(entry)
 
     return fav_map
 
 
+def _get_fav_weapon(player_id):
+    """
+    Get the player's favorite weapon. The favorite weapon is defined
+    as the weapon that he or she has employed the most in the past 
+    90 days.
+
+    Returns a sequence of dictionaries with keys for the weapon's name and id.
+    The sequence holds the most-used weapons in decreasing order.
+    """
+    # 90 day window
+    back_then = datetime.datetime.utcnow() - datetime.timedelta(days=90)
+
+    raw_fav_weapon = DBSession.query(Weapon.descr, Weapon.weapon_cd).\
+            filter(Game.game_id == PlayerWeaponStat.game_id).\
+            filter(PlayerWeaponStat.player_id == player_id).\
+            filter(PlayerWeaponStat.weapon_cd == Weapon.weapon_cd).\
+            filter(PlayerWeaponStat.create_dt > back_then).\
+            group_by(Weapon.descr, Weapon.weapon_cd).\
+            order_by(func.count().desc()).\
+            limit(5).all()
+
+    fav_weapon = []
+    for wpn_e in raw_fav_weapon:
+        entry = {}
+        entry['name'] = wpn_e[0]
+        entry['id']   = wpn_e[1]
+        fav_weapon.append(entry)
+
+    return fav_weapon
+
+
+def _get_fav_server(player_id):
+    """
+    Get the player's favorite server. The favorite server is defined
+    as the server that he or she has played on the most in the past 
+    90 days.
+
+    Returns a sequence of dictionaries with keys for the server's name and id.
+    The sequence holds the most-used servers in decreasing order.
+    """
+    # 90 day window
+    back_then = datetime.datetime.utcnow() - datetime.timedelta(days=90)
+
+    raw_fav_server = DBSession.query(Server.name, Server.server_id).\
+            filter(Game.game_id == PlayerGameStat.game_id).\
+            filter(Game.server_id == Server.server_id).\
+            filter(PlayerGameStat.player_id == player_id).\
+            filter(PlayerGameStat.create_dt > back_then).\
+            group_by(Server.name, Server.server_id).\
+            order_by(func.count().desc()).\
+            limit(5).all()
+
+    fav_server = []
+    for srv_e in raw_fav_server:
+        entry = {}
+        entry['name'] = srv_e[0]
+        entry['id']   = srv_e[1]
+        fav_server.append(entry)
+
+    return fav_server
+
+
 def _get_rank(player_id):
     """
     Get the player's rank as well as the total number of ranks.
@@ -255,7 +438,8 @@ def player_info_data(request):
         total_stats = _get_total_stats(player.player_id)
 
         # games breakdown - N games played (X ctf, Y dm) etc
-        (total_games, games_breakdown) = _get_games_played(player.player_id)
+        # DEPRECATED: included in total_stats, see above
+        # (total_games, games_breakdown) = _get_games_played(player.player_id)
 
         # favorite map from the past 90 days
         try:
@@ -263,12 +447,25 @@ def player_info_data(request):
         except:
             fav_map = None
 
+        # favorite weapon from the past 90 days
+        try:
+            fav_weapon = _get_fav_weapon(player.player_id)
+        except:
+            fav_weapon = None
+
+        # favorite server from the past 90 days
+        try:
+            fav_server = _get_fav_server(player.player_id)
+        except:
+            fav_server = None
+
         # friendly display of elo information and preliminary status
         elos = DBSession.query(PlayerElo).filter_by(player_id=player_id).\
                 filter(PlayerElo.game_type_cd.in_(['ctf','duel','dm'])).\
                 order_by(PlayerElo.elo.desc()).all()
 
         elos_display = []
+        elos_dict    = {}
         for elo in elos:
             if elo.games > 32:
                 str = "{0} ({1})"
@@ -277,11 +474,18 @@ def player_info_data(request):
 
             elos_display.append(str.format(round(elo.elo, 3),
                 elo.game_type_cd))
+            elos_dict[elo.game_type_cd] = round(elo.elo, 3)
+        elos_display = ', '.join(elos_display)
 
         # get current rank information
         ranks = _get_rank(player_id)
-        ranks_display = ', '.join(["{1} of {2} ({0})".format(gtc, rank,
-            max_rank) for gtc, rank, max_rank in ranks])
+        
+        ranks_display = []
+        ranks_dict    = {}
+        for gtc,rank,max_rank in ranks:
+            ranks_display.append("{1} of {2} ({0})".format(gtc, rank, max_rank))
+            ranks_dict[gtc] = (rank, max_rank)
+        ranks_display = ', '.join(ranks_display)
 
 
         # which weapons have been used in the past 90 days
@@ -306,23 +510,33 @@ def player_info_data(request):
 
     except Exception as e:
         player = None
+        elos = None
         elos_display = None
         total_stats = None
         recent_games = None
-        total_games = None
-        games_breakdown = None
+        # DEPRECATED: included in total_stats, see above
+        #total_games = None
+        #games_breakdown = None
         recent_weapons = []
         fav_map = None
+        fav_weapon = None
+        fav_server = None
+        ranks = None
         ranks_display = None;
 
     return {'player':player,
+            'elos':elos_dict,
             'elos_display':elos_display,
             'recent_games':recent_games,
             'total_stats':total_stats,
-            'total_games':total_games,
-            'games_breakdown':games_breakdown,
+            # DEPRECATED: included in total_stats, see above
+            #'total_games':total_games,
+            #'games_breakdown':games_breakdown,
             'recent_weapons':recent_weapons,
             'fav_map':fav_map,
+            'fav_weapon':fav_weapon,
+            'fav_server':fav_server,
+            'ranks':ranks_dict,
             'ranks_display':ranks_display,
             }
 
@@ -338,7 +552,44 @@ def player_info_json(request):
     """
     Provides detailed information on a specific player. JSON.
     """
-    return [{'status':'not implemented'}]
+    player_info = player_info_data(request)
+    json_result = {
+        'player': {
+            'id':               player_info['player'].player_id,
+            'nick':             player_info['player'].nick.encode('utf-8'),
+            'stripped_nick':    player_info['player'].nick_strip_colors(),
+            'joined':           player_info['player'].create_dt.isoformat(),
+            },
+        'elos':         player_info['elos'],
+        'ranks':        player_info['ranks'],
+        'total_stats':  {
+                'games':            player_info['total_stats']['games'],
+                'games_breakdown':  player_info['total_stats']['games_breakdown'],
+                'alivetime':        datetime_seconds(player_info['total_stats']['alivetime']),
+                'kills':            player_info['total_stats']['kills'],
+                'deaths':           player_info['total_stats']['deaths'],
+                'suicides':         player_info['total_stats']['suicides'],
+                'wins':             player_info['total_stats']['wins'],
+                # FIXME - current "wins" query is flawed!
+                #'losses':           player_info['total_stats']['loses'],
+            },
+        'recent_games': [
+                {
+                    'game_id':      game.game_id,
+                    'game_type':    game.game_type_cd,
+                    'server':       server.name,
+                    'map':          map.name,
+                    'team':         gamestat.team,
+                    'rank':         gamestat.rank,
+                    'win':          ((gamestat.team != None and gamestat.team == game.winner)
+                                        or (gamestat.team == None and gamestat.rank == 1)),
+                    'time':         game.create_dt.isoformat(),
+                }
+                for (gamestat, game, server, map) in player_info['recent_games'][:5]
+            ],
+        }
+    print json_result
+    return json_result
 
 
 def player_game_index_data(request):