Exemplo n.º 1
0
def user():
    if current_user.is_anonymous:
        return abort(404)

    with Database() as db:
        params = (current_user.discord_id, current_user.discord_tag,
                  current_user.discord_avatar, current_user.ns2_id)
        db.execute(ns2plus_queries.UPDATE_DISCORD_DATA, params)

    return render_template('user.html')
Exemplo n.º 2
0
def total_players():
    with Database() as db:
        data = db.execute(ns2plus_queries.NEW_PLAYERS).fetchall()
        df = pd.DataFrame(data)
        df['Datetime'] = pd.to_datetime(df['roundDate'])
        df = df.set_index('Datetime')
        df = df.steamId.resample('W').count()
        response = [{
            'x': x.to_pydatetime().strftime('%Y-%m-%d %H:%M:%S'),
            'y': int(y)
        } for x, y in zip(list(df.index), list(df.values.cumsum()))]
        return jsonify(response)
Exemplo n.º 3
0
def matches_week():
    with Database() as db:
        data = db.execute(ns2plus_queries.MATCHES_WEEK).fetchall()
        df = pd.DataFrame(data)
        df['Datetime'] = pd.to_datetime(df['roundDate'])
        df = df.set_index('Datetime')
        df = df.roundId.resample('W').count()
        response = [{
            'x': x.to_pydatetime().strftime('%Y-%m-%d %H:%M:%S'),
            'y': int(y)
        } for x, y in zip(list(df.index), list(df.values))]
        return jsonify(response)
Exemplo n.º 4
0
def kill_graph():
    with Database() as db:
        players = {}
        links_i = []
        links_v = []
        last_round_id = db.execute(ns2plus_queries.LAST_ROUND_ID).fetchone()
        data = db.execute(ns2plus_queries.KILL_GRAPH,
                          last_round_id - 10).fetchall()
        for r in data:
            kfId = r['killerSteamId']
            vId = r['victimSteamId']
            kills = r['kills']
            if kfId not in players:
                players[kfId] = r['killerName']
            if vId not in players:
                players[vId] = r['victimName']

            if (kfId, vId) not in links_i and (vId, kfId) not in links_i:
                links_i.append((kfId, vId))
                links_v.append(kills)
            else:
                for pair in [(kfId, vId), (vId, kfId)]:
                    try:
                        i = links_i.index(pair)
                    except:
                        pass
                    else:
                        links_v[i] += kills
    response = {
        'nodes': [{
            'id': k,
            'name': v
        } for k, v in players.items()],
        'links': [{
            'source': link[0],
            'target': link[1],
            'value': links_v[i]
        } for i, link in enumerate(links_i)]
    }
    return jsonify(response)
Exemplo n.º 5
0
def match(roundid):
    roundid = int(roundid)
    if not roundid:
        return abort(404)

    data = {}
    with Database() as db:
        round_info = db.execute(ns2plus_queries.ROUND_INFO, roundid).fetchall()
        if not round_info:
            return abort(404)

        data.update(round_info[0])

        path = 'static/img/map_screenshots/'
        abs_path = os.path.join(os.path.dirname(__file__), path)
        for file in os.listdir(abs_path):
            if data['mapName'] in file:
                data['background'] = '/' + path + file
        if 'background' not in data:
            data['background'] = '/' + path + 'default.jpg'

    return render_template('match.html', data=data)
Exemplo n.º 6
0
def get_stats(endpoint, filter, limit, page):
    response = {}

    with Database() as db:
        if endpoint == "matches":
            query = ns2plus_queries.MATCHES
            filters = [f'{filter}%', f'%{filter}%']
        elif endpoint == "players":
            query = ns2plus_queries.PLAYERS
            filters = [f'%{filter}%', f'%{filter}%']
        else:
            return abort(404)

        limits = [(page - 1) * limit, limit]

        data = db.execute(ns2plus_queries.limit(query),
                          filters + limits).fetchall()
        total_count = db.execute(ns2plus_queries.count(query),
                                 filters).fetchone()

        # Specific parsing per endpoint
        if endpoint == "matches":
            for row in data:
                m, s = divmod(row['roundLength'], 60)
                h, m = divmod(m, 60)
                row['roundLength'] = "%d:%02d:%02d" % (
                    h, m, s) if h else "%02d:%02d" % (m, s)
                row['roundDateH'] = naturaltime(
                    datetime.datetime.strptime(row['roundDate'],
                                               '%Y-%m-%d %H:%M:%S'))
        if endpoint == "players":
            for row in data:
                time_played = row['timePlayed'] if row['timePlayed'] else 0
                m, s = divmod(time_played, 60)
                h, m = divmod(m, 60)
                row['timePlayed'] = "%d:%02d:%02d" % (h, m, s)

                # Fix because some players in ns2plus tables
                # are in PlayerStats but not in PlayerRoundStats
                # for some reason
                if row["name_list"]:
                    name_list = row["name_list"].split(',')
                else:
                    name_list = [row["playerName"]]

                name_list = ', '.join(name_list)

                if len(name_list) > 15:
                    name_list = name_list[:15] + '...'

                row["name_list"] = name_list

                row['lastSeenH'] = naturaltime(
                    datetime.datetime.strptime(row['lastSeen'],
                                               '%Y-%m-%d %H:%M:%S'))

        response['result'] = data

    response['total_count'] = total_count
    response['limit'] = limit
    p_offset = 1 if total_count % limit else 0
    response['total_pages'] = p_offset + total_count // limit
    response['page'] = page

    return response
Exemplo n.º 7
0
def player(steamid):
    steamid = int(steamid)
    if not steamid:
        return abort(404)

    data = {}

    with Database() as db:
        # Fetch all query data first
        player_stats = db.execute(ns2plus_queries.PLAYER_STATS,
                                  steamid).fetchall()
        if not player_stats:
            return abort(404)
        data.update(player_stats[0])

        player_other_names = db.execute(ns2plus_queries.PLAYER_OTHER_NAMES,
                                        steamid).fetchall()
        data['other_names'] = [x['playerName'] for x in player_other_names]

        player_weapon_acc = db.execute(ns2plus_queries.PLAYER_WEAPON_ACC,
                                       steamid).fetchall()
        data['weapon_acc'] = {x['weapon']: x['acc'] for x in player_weapon_acc}

        player_wins = pd.DataFrame(
            db.execute(ns2plus_queries.PLAYER_WINS, steamid).fetchall())

        # TODO: check formula
        data['steam_url'] = SteamID(int((data['steamId'] - 1) / 2), 1, 1,
                                    0).community_url()

        # Winrate over time chart
        for team in (1, 2):
            df = player_wins[player_wins['teamNumber'] == team]
            shift = 30 - len(df) % 30
            df = df.groupby((np.arange(len(df)) + shift) // 30).agg({
                'win': ['sum', 'count'],
                'roundDate': ['last']
            })
            if len(df):
                df['winrate'] = df[('win', 'sum')] / df[('win', 'count')]
                data[f'team{team}_winrate'] = [{
                    'x': p[2],
                    'y': int(p[3] * 100)
                } for p in df.values]

        # Activity chart
        q = [(ns2plus_queries.PLAYER_ACTIVITY, 'activity', steamid),
             (ns2plus_queries.SERVER_ACTIVITY, 'server_activity', None)]
        for query, key, arg in q:
            if arg:
                q = db.execute(query, arg).fetchall()
            else:
                q = db.execute(query).fetchall()
            df = pd.DataFrame(q)
            df['Datetime'] = pd.to_datetime(df['roundDate'])
            df = df.set_index('Datetime')
            df = df.hoursPlayed.resample('W').sum()
            data[key] = [{
                'x': x.to_pydatetime().strftime('%Y-%m-%d %H:%M:%S'),
                'y': '%.2f' % y
            } for x, y in zip(list(df.index), list(df.values))]

        # Class time chart
        q = db.execute(ns2plus_queries.PLAYER_CLASSTIME, steamid).fetchall()
        data['classes'] = {
            c['class']: '%.2f' % c['classTime'] if c['classTime'] else 0
            for c in q
        }
        lifeforms = ['Gorge', 'Lerk', 'Fade', 'Onos']
        lifeforms_time = [(l, float(data['classes'][l])) for l in lifeforms]
        data['lifeform'] = max(lifeforms_time, key=lambda x: x[1])[0]

    return render_template('player.html', data=data)