Esempio n. 1
0
 def create_all_stats_from_id(id_: str, rank: int = None, replay_ids: List[str] = None, playlist: int = 13,
                              win: bool = None, session=None) -> PlayerDataPoint:
     game_count = player_wrapper.get_total_games(session, id_)
     if game_count == 0:
         raise UserHasNoReplays()
     if rank is None:
         rank = get_rank(id_)
     averaged_stats = player_stat_wrapper.get_averaged_stats(session, id_,
                                                             redis=get_redis(), raw=True,
                                                             rank=rank, replay_ids=replay_ids,
                                                             playlist=playlist, win=win)
     if len(id_) == 11 and id_[0] == 'b' and id_[-1] == 'b':
         names_and_counts: List[Tuple[str, int]] = session.query(PlayerGame.name,
                                                                 func.count(PlayerGame.name).label('c')) \
                                                       .filter(PlayerGame.player == id_) \
                                                       .group_by(PlayerGame.name).order_by(desc('c'))[:5]
         id_ = names_and_counts[0][0]
     playstyle_data_raw: PlayerDataPoint = PlayerDataPoint(name=id_,
                                                           data_points=[
                                                               DataPoint(explanations[
                                                                             k].field_rename if k in explanations else k,
                                                                         averaged_stats[k])
                                                               for k in averaged_stats
                                                           ])
     return playstyle_data_raw
Esempio n. 2
0
    def create_from_id(cls, id_: str, raw=False, rank=None, replay_ids=None, playlist=13, win=None, session=None):
        game_count = player_wrapper.get_total_games(session, id_)
        if game_count == 0:
            raise UserHasNoReplays()
        if rank is None:
            rank = get_rank(id_)
        try:
            averaged_stats = player_stat_wrapper.get_averaged_stats(session, id_,
                                                                    redis=get_redis(), raw=raw,
                                                                    rank=rank, replay_ids=replay_ids,
                                                                    playlist=playlist, win=win)
        except NoResultFound:
            raise NoReplaysForPlaylist(playlist)
        spider_charts_groups = player_stat_wrapper.get_stat_spider_charts()

        play_style_chart_datas: List[PlayStyleChartData] = []
        for spider_chart_group in spider_charts_groups:
            title = spider_chart_group['title']
            chart_data_points = [
                ChartDataPoint(name=explanations[name].short_name if name in explanations else name,
                               value=averaged_stats[name])
                for name in spider_chart_group['group']
            ]
            play_style_chart_datas.append(PlayStyleChartData(title, chart_data_points))

        return PlayStyleResponse(
            chart_datas=play_style_chart_datas,
            show_warning=game_count <= cls.showWarningThreshold
        )
Esempio n. 3
0
def ping(session=None):
    r = get_redis()
    result = r.get('global_stats')
    if result is not None:
        return jsonify({'result': json.loads(result)})
    elif is_local_dev():
        wrapper = global_stats_wrapper.GlobalStatWrapper()
        result = wrapper.get_global_stats(sess=session, with_rank=False)
        return jsonify(result)
Esempio n. 4
0
def vanity_to_steam_id(vanity):
    key = 'vanity_' + vanity
    try:
        redis_instance = get_redis()
    except:
        redis_instance = None
    if redis_instance is not None:
        match = redis_instance.get(key)
        if match is not None:
            return json.loads(match)
    steam_url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key={steamKey}&vanityurl={steamID}'.format(
        steamKey=STEAM_API_KEY, steamID=vanity)
    resp = requests.get(steam_url)
    resp.raise_for_status()
    if resp.json()['response']['success'] == 42:
        return None
    else:
        if redis_instance is not None:
            redis_instance.set(key, json.dumps(resp.json()), ex=60 * 60 * 24)
        return resp.json()
Esempio n. 5
0
def steam_id_to_profile(steam_id):
    key = 'steam_id_' + steam_id
    try:
        redis_instance = get_redis()
    except:
        redis_instance = None
    if redis_instance is not None:
        match = redis_instance.get(key)
        if match is not None:
            return json.loads(match)
    profile_url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={steamKey}&steamids={steamID}'.format(
        steamKey=STEAM_API_KEY, steamID=steam_id)
    resp = requests.get(profile_url)
    resp.raise_for_status()
    if len(resp.json()['response']['players']) == 0:
        return None
    else:
        if redis_instance is not None:
            redis_instance.set(key, json.dumps(resp.json()), ex=60 * 60 * 24)
        profile = resp.json()['response']['players'][0]
        add_or_update_steam_player(profile)
        # return the normal JSON to not change anything else
        return resp.json()
def get_rank_batch(ids, offline_redis=None, use_redis=True):
    """
    Gets a batch of ranks based on ids. Returns fake data if there is no API key available.

    :param ids: ids to get from RLAPI
    :param offline_redis: Redis to use if not in the application context
    :return: rank information
    """
    rank_datas_for_players = {}
    if fake_data or RL_API_KEY is None:
        return make_fake_data(ids)
    try:
        _redis = get_redis()
    except KeyError:
        _redis = None
        ids_to_find = ids
    except RuntimeError:  # we're not in application context, use our own redis
        if offline_redis is None and use_redis:
            offline_redis = redis.Redis(host='localhost', port=6379)
        _redis = offline_redis
    if _redis is not None:
        ids_to_find = []
        for steam_id in ids:
            try:
                result = _redis.get(steam_id)
            except redis.ConnectionError:
                logger.error('Error connecting to redis')
                _redis = None
                ids_to_find = ids
                break
            if result is not None:
                # logger.debug('Rank is cached')
                rank_datas_for_players[steam_id] = json.loads(
                    result.decode("utf-8"))
            elif steam_id != '0':
                ids_to_find.append(steam_id)
            else:
                rank_datas_for_players['0'] = {}
        if len(ids_to_find) == 0:
            return rank_datas_for_players
        else:
            logger.debug(ids_to_find)
    else:
        ids_to_find = ids
    url = "https://api.rocketleague.com/api/v1/steam/playerskills/"
    headers = {
        'Authorization': f'Token {RL_API_KEY}',
        'Referer': 'http://api.rocketleague.com'
    }

    ids_dict = list(
        filter(lambda x: x['platformId'] == 'steam',
               [{
                   'platformId': get_platform_id(i),
                   'uniqueId': i
               } for i in ids_to_find]))
    post_data = {'player_ids': [p['uniqueId'] for p in ids_dict]}
    data = requests.post(url, headers=headers, json=post_data)
    if data.status_code >= 300:
        return {**rank_datas_for_players, **get_empty_data(ids_to_find)}
    try:
        data = data.json()
    except Exception as e:
        print(e)
        return get_empty_data(ids)
    if 'detail' in data:
        return {str(i): {} for i in ids}
    for player in data:
        rank_datas = {}
        unique_id = player['user_id']
        names = {
            '13': 'standard',
            '11': 'doubles',
            '10': 'duel',
            '12': 'solo',
            '27': 'hoops',
            '28': 'rumble',
            '29': 'dropshot',
            '30': 'snowday'
        }
        if 'player_skills' in player:
            found_modes = []
            for playlist in player['player_skills']:
                if 'tier' in playlist and str(
                        playlist['playlist']) in names:  # excludes unranked
                    mode = names[str(playlist['playlist'])]
                    found_modes.append(mode)
                    rank_data = {
                        'mode':
                        mode,
                        'rank_points':
                        playlist['skill'],
                        'tier':
                        playlist['tier'],
                        'division':
                        playlist['division'],
                        'string':
                        tier_div_to_string(playlist['tier'],
                                           playlist['division'])
                    }
                    rank_datas[str(playlist['playlist'])] = rank_data

            for idx, mode in names.items():
                if mode not in found_modes:
                    rank_datas[idx] = {
                        'mode': mode,
                        'rank_points': 0,
                        'tier': 0,
                        'division': 0,
                        'string': tier_div_to_string(None)
                    }

            if _redis is not None:
                _redis.set(unique_id, json.dumps(rank_datas), ex=2 * 60)
            rank_datas_for_players[unique_id] = rank_datas
        else:
            rank_datas_for_players[unique_id] = {}
    return rank_datas_for_players
Esempio n. 7
0
 def create_by_rank() -> List['GlobalStatsGraph']:
     r = get_redis()
     return json.loads(r.get('global_stats_by_rank'))
 def create() -> List['GlobalStatsGraph']:
     r = get_redis()
     return json.loads(r.get('global_distributions'))