Example #1
0
def createNewGame(request):
    response = {}
    reqMethod = getPostOrGetRequest(request)
    print request.GET
    gameName = reqMethod.get("gameName")
    player = reqMethod.get("playerCount")
    try:
        gameObj = Game.objects.filter(name=gameName)
        if gameObj:
            gameObj = gameObj[0]
            gameObj.player = player
            gameObj.save()
            response = generateStatusJson('success',
                                          'Game updated successfully')

        else:
            gameObj = Game(name=gameName,
                           player=player,
                           roles='{}',
                           playerDetails='{}')
            gameObj.save()
            response = generateStatusJson('success',
                                          'Game created successfully')

    except Exception as e:
        response = generateStatusJson(
            'error',
            e.message.encode('ascii', 'ignore').strip())

    return HttpResponse(response, content_type='application/json')
Example #2
0
def update_free_games():
    free_games = []
    for extrator in FREE_GAME_EXTRACTORS:
        free_games += extrator()

    new_free_games = []
    for free_game in free_games:
        if helper.get_object_or_none(Game,
                                     game_id=free_game['id'],
                                     discount=100.0) == None:
            game = Game(
                provider_name=free_game['provider_name'],
                name=free_game['name'],
                source_url=free_game['url'],
                game_id=free_game['id'],
                original_price=0.0,
                discount=free_game['discount'],
            )
            game.save()
            new_free_games.append(game)

    # Delete expired free games
    undeleted_free_game_ids = [free_game['id'] for free_game in free_games]
    Game.objects.filter(discount=100.0).exclude(
        game_id__in=undeleted_free_game_ids).delete()

    if len(new_free_games) > 0:
        notify_new_free_games(new_free_games)
Example #3
0
    def update(self, instance: Game, validated_data: dict):
        categories_slugs_stringify = validated_data.pop('categories', '')
        categories_slugs = get_list_of_categories_from_stringify_list(
            categories_slugs_stringify)

        add_categories_for_game_creation(categories_slugs, instance)
        instance.__dict__.update(**validated_data)
        instance.save()

        return instance
Example #4
0
def initial_comp_setup():
    round_setup()
    for round in range(1, ROUNDS + 1):
        logger.info("Fetching round %s/%s...", round, ROUNDS)
        start = datetime.now()
        r = requests.get(
            "http://api.stats.foxsports.com.au/3.0/api/sports/league/series/1/seasons/116/rounds/"
            + str(round) +
            "/fixturesandresultswithbyes.json?userkey=A00239D3-45F6-4A0A-810C-54A347F144C2"
        )

        if round == 1:
            # Setup teams if they don't already exist
            team_ids = list(Team.objects.values_list('fox_id', flat=True))

            for game in json.loads(r.text):
                team = {}
                team['name'] = game["team_A"]["name"] + ' ' + game["team_A"][
                    "short_name"]
                team['fox_id'] = game["team_A"]["id"]
                if team['fox_id'] not in team_ids:
                    team_ids.append(team['fox_id'])
                    logger.info("Adding team %s to teams", team['name'])
                    new_team = Team(name=team['name'], fox_id=team['fox_id'])
                    new_team.save()

                team = {}
                team['name'] = game["team_B"]["name"] + ' ' + game["team_B"][
                    "short_name"]
                team['fox_id'] = game["team_B"]["id"]
                if team['fox_id'] not in team_ids:
                    team_ids.append(team['fox_id'])
                    logger.info("Adding team %s to teams", team['name'])
                    new_team = Team(name=team['name'], fox_id=team['fox_id'])
                    new_team.save()

        for game in json.loads(r.text):
            fixture_id = game["fixture_id"]
            round_object = Round.objects.get(round=round)
            game_time = parse_datetime(game["match_start_date"])
            home_team = Team.objects.get(fox_id=game["team_A"]["id"])
            away_team = Team.objects.get(fox_id=game["team_B"]["id"])
            stadium = game["venue"]["name"]
            new_game = Game(fixture_id=fixture_id,
                            start_time=game_time,
                            round=round_object,
                            home_team=home_team,
                            away_team=away_team,
                            stadium=stadium)
            new_game.save()
        end = datetime.now()
        elapsed_time = end - start
        if elapsed_time.total_seconds() < 5:
            time.sleep(5 - elapsed_time.total_seconds())
Example #5
0
def initial_comp_setup():
    round_setup()
    for round in range(1, ROUNDS+1):
        logger.info("Fetching round %s/%s...", round, ROUNDS)
        start = datetime.now()
        r = requests.get("http://api.stats.foxsports.com.au/3.0/api/sports/league/series/1/seasons/114/rounds/"+str(round)+"/fixturesandresultswithbyes.json?userkey=A00239D3-45F6-4A0A-810C-54A347F144C2")

        if round==1:
            teams = []
            for game in json.loads(r.text):
                team = {}
                team['name']=game["team_A"]["name"]+' '+game["team_A"]["short_name"]
                team['fox_id']=game["team_A"]["id"]
                if team not in teams:
                    teams.append(team)
                    logger.info("Adding team %s to teams", team['name'])
                    new_team=Team(name=team['name'], fox_id=team['fox_id'])
                    new_team.save()

                team = {}
                team['name']=game["team_B"]["name"]+' '+game["team_B"]["short_name"]
                team['fox_id']=game["team_B"]["id"]
                if team not in teams:
                    teams.append(team)
                    logger.info("Adding team %s to teams", team['name'])
                    new_team=Team(name=team['name'], fox_id=team['fox_id'])
                    new_team.save()



        for game in json.loads(r.text):
            fixture_id = game["fixture_id"]
            round_object = Round.objects.get(round=round)
            game_time = parse_datetime(game["match_start_date"])
            home_team = Team.objects.get(fox_id=game["team_A"]["id"])
            away_team = Team.objects.get(fox_id=game["team_B"]["id"])
            stadium = game["venue"]["name"]
            new_game = Game(fixture_id=fixture_id,
                            start_time = game_time,
                            round=round_object,
                            home_team=home_team,
                            away_team=away_team,
                            stadium=stadium)
            new_game.save()
        end = datetime.now()
        elapsed_time = end-start
        if elapsed_time.total_seconds()<5:
            time.sleep(5 - elapsed_time.total_seconds())
Example #6
0
 def new(self, request, *args, **kwargs):
     serializer = GameNewSerializer(data=request.data)
     game = None
     player = self.request.user
     if serializer.is_valid(raise_exception=True):
         rows = serializer.validated_data['rows']
         columns = serializer.validated_data['columns']
         mines = serializer.validated_data['mines']
         game = Game()
         game.title = 'Game for user %s' % player.username
         board, player_board = Game.new_boards(rows, columns, mines)
         game.board = board
         game.player_board = player_board
         game.state = Game.STATE_NEW
         game.player = player
         game.save()
     serializer = GameSerializer(game, context={'request': request})
     return Response(serializer.data)
Example #7
0
def game_create(request):
    if request.method == "POST":
        # Generate a random, 6-digit number
        gameID = 0
        while gameID < 100000 or gameID > 999999:
            gameID = math.floor(random.random() * 10**6)

        # Create the game model
        game = Game(gameID=gameID)
        game.save()

        # Create the player model
        playerID = request.POST.get("playerID", "")
        playerName = request.POST.get("playerName", "")
        player = Player(game=game,
                        cookie=playerID,
                        name=playerName,
                        holdings=1500)
        player.save()

        return JsonResponse({"status": "success", "data": {"gameID": gameID}})
    else:
        return JsonResponse({"status": "error", "data": None})
Example #8
0
def createNewGame(request):
    response={}
    reqMethod = getPostOrGetRequest(request)
    print request.GET
    gameName = reqMethod.get("gameName")
    player = reqMethod.get("playerCount")
    try:
        gameObj = Game.objects.filter(name=gameName)
        if gameObj:
            gameObj = gameObj[0]
            gameObj.player = player
            gameObj.save()
            response = generateStatusJson('success', 'Game updated successfully')

        else:
            gameObj = Game(name=gameName, player=player ,roles='{}',playerDetails='{}')
            gameObj.save()
            response = generateStatusJson('success', 'Game created successfully')

    except  Exception as e:
        response = generateStatusJson('error', e.message.encode('ascii', 'ignore').strip())

    return HttpResponse(response,content_type='application/json')
Example #9
0
def new_game(request):
    game = Game()
    game.save()
    return Response(status=status.HTTP_200_OK, data={"game_link": game.id})
Example #10
0
 if host:
     p = Profile.objects.get(nickname=host[:-1])
     try:
         e = Event.objects.get(host=p, date=date)
     except:
         print("No event")
         e = Event(league=league, host=p, date=date, status='F')
         e.save()
     g = None
     try:
         g = Game.objects.get(event=e, number=int(game))
     except:
         print("No game")
         try:
             g = Game(event=e, number=int(game), stake=stake)
             g.save()
         except:
             pass
     if g:
         j = 0
         for player in df.columns[7:-3]:
             placing = df[df.columns[7 + j]][i]
             j = j + 1
             if placing in [0, 1, 2, 3]:
                 print(player, placing)
                 p = Profile.objects.get(nickname=player)
                 try:
                     pg = GamePlayer.objects.get(game=g, player=p)
                 except:
                     pg = GamePlayer(game=g, player=p)
                     pg.position = placing
Example #11
0
def add_categories_for_game_creation(categories_slugs: list, game: Game):
    game.categories.set(Category.objects.filter(slug__in=categories_slugs))
    game.save()

    return game
Example #12
0
def get_recent_matches(summoner_id, region):
    """
    Retrieves game data for last 10 games played by a summoner, given a summoner ID and region.

    This potentially executes several queries:
    -first, we get match history.
        -game stats
        -IDs of participants
    -then we make a list of summoner IDs that we don't have in the DB
        -this gets broken up into MAX_IDS chunks and each chunk is a queried as a single call for basic summoner data

    Since match history returns the last 10 games, and each game can have 9 other players
    (assuming non-hexakill mode) - that's 90 potentially unknown summoner IDs + 1 for the summoner in question,
    giving us 91 summoner IDs that we need to query.

    91 / 40 = 2.275 rounded up is 3 queries at most for summoner ID data.

    3 + 1 (for the initial match history call) = 4 calls at most.
    """

    #print 'get_recent_matches()', summoner_id, region

    recent = riot_api.get_recent_games(summoner_id, region)

    # First make a set of the associated summoner IDs (a set cannot have duplicate entries).
    unique_players = set()
    for g in recent['games']:
        if 'fellowPlayers' in g:
            for p in g['fellowPlayers']:
                unique_players.add(p['summonerId'])

    # Now we take note of any summoner IDs we already have cached (so we can remove them).
    to_remove = set()
    for p in unique_players:
        try:
            Summoner.objects.filter(region=region).get(summoner_id=p)
            to_remove.add(p)
        except ObjectDoesNotExist:
            pass

    # Remove the already cached summoner IDs from the working set.
    for p in to_remove:
        unique_players.remove(p)

    player_list = list(unique_players)  # make a list of the set, so we can call chunks() on it

    # Don't forget, we have to check for the summoner ID whose history we're examining as well!
    try:
        Summoner.objects.filter(region=region).get(summoner_id=summoner_id)
    except ObjectDoesNotExist:  # if it isn't cached, and it isn't in the list yet, add it
        if summoner_id not in player_list:
            player_list.append(summoner_id)

    query_list = list(chunks(player_list, MAX_IDS))  # query_list now holds a list of lists of at most MAX_ID elements

    # Now ask the API for info on summoners, at most MAX_ID at a time.
    #print 'Now asking for participants...'
    summoner_dto = []
    for i in query_list:
        summoner_dto.append(riot_api.get_summoners(ids=i, region=region))

    #print 'Done getting participants!'

    # TODO: This part is sometimes getting duplicate summoners! (fixed?)
    # Now put those summoner DTOs in the cache.
    for chunk in summoner_dto:
        for player in chunk:
            # for v in chunk[player]:
            #     print v, len(v)
            #print u'ADDING summoner {}'.format(chunk[player]['name'])
            summoner = Summoner(summoner_id=chunk[player]['id'],
                                name=chunk[player]['name'],
                                std_name=chunk[player]['name'].replace(' ', '').lower(),
                                profile_icon_id=chunk[player]['profileIconId'],
                                revision_date=chunk[player]['revisionDate'],
                                summoner_level=chunk[player]['summonerLevel'],
                                region=region)

            # Sometimes requests will go out synchronously for the same summoner.
            # This means the cache is not hit and a double query for a single summoner occurs.
            # Duplicate summoners are prevented via the unique_together constraint on summoner_id and region,
            # which will throw IntegrityError and prevent the dupe from being made.
            try:
                #print summoner.name, len(summoner.name)
                summoner.save()
            except IntegrityError:
                pass

    # Requires summoners (as well as all related field values) to be cached before-hand (summoner caching done above).
    for match in recent['games']:
        # first fill in the simple stuff
        game = Game(summoner_id=Summoner.objects.filter(region=region).get(summoner_id=summoner_id),
                    champion_id=Champion.objects.get(champion_id=match['championId']),
                    create_date=match['createDate'],
                    game_id=match['gameId'],
                    game_mode=match['gameMode'],
                    game_type=match['gameType'],
                    invalid=match['invalid'],
                    ip_earned=match['ipEarned'],
                    level=match['level'],
                    map_id=match['mapId'],
                    spell_1=SummonerSpell.objects.get(spell_id=match['spell1']),
                    spell_2=SummonerSpell.objects.get(spell_id=match['spell2']),
                    sub_type=match['subType'],
                    team_id=match['teamId'],
                    region=region,
                    champion_key=Champion.objects.get(champion_id=match['championId']).key)

        stats = RawStat()

        # Here we add stats that were returned (only stats that aren't None or 0 will be returned by API)
        for i in match['stats']:
            setattr(stats, inflection.underscore(i), match['stats'][i])

        stats.save()

        # associate the RawStat object with this game
        game.stats = stats

        game_saved = False

        # Ensures no dupes of Game (or any related objects).
        try:
            game.save()
            game_saved = True
        except IntegrityError:
            pass

        # if game saved, we're good and just need to add the participating players
        if game_saved:
            # associate each Player object with this game
            if 'fellowPlayers' in match:
                for p in match['fellowPlayers']:
                    player = Player(champion=Champion.objects.get(champion_id=p['championId']),
                                    summoner=Summoner.objects.filter(region=region).get(summoner_id=p['summonerId']),
                                    team_id=p['teamId'],
                                    participant_of=game)
                    player.save()
        else:  # if it didn't save, we can get rid of the stats object too.
            stats.delete()
Example #13
0
def get_recent_matches(summoner_id, region):
    """
    Retrieves game data for last 10 games played by a summoner, given a summoner ID and region.

    This potentially executes several queries:
    -first, we get match history.
        -game stats
        -IDs of participants
    -then we make a list of summoner IDs that we don't have in the DB
        -this gets broken up into MAX_IDS chunks and each chunk is a queried as a single call for basic summoner data

    Since match history returns the last 10 games, and each game can have 9 other players
    (assuming non-hexakill mode) - that's 90 potentially unknown summoner IDs + 1 for the summoner in question,
    giving us 91 summoner IDs that we need to query.

    91 / 40 = 2.275 rounded up is 3 queries at most for summoner ID data.

    3 + 1 (for the initial match history call) = 4 calls at most.
    """

    #print 'get_recent_matches()', summoner_id, region

    recent = riot_api.get_recent_games(summoner_id, region)

    # First make a set of the associated summoner IDs (a set cannot have duplicate entries).
    unique_players = set()
    for g in recent['games']:
        if 'fellowPlayers' in g:
            for p in g['fellowPlayers']:
                unique_players.add(p['summonerId'])

    # Now we take note of any summoner IDs we already have cached (so we can remove them).
    to_remove = set()
    for p in unique_players:
        try:
            Summoner.objects.filter(region=region).get(summoner_id=p)
            to_remove.add(p)
        except ObjectDoesNotExist:
            pass

    # Remove the already cached summoner IDs from the working set.
    for p in to_remove:
        unique_players.remove(p)

    player_list = list(
        unique_players
    )  # make a list of the set, so we can call chunks() on it

    # Don't forget, we have to check for the summoner ID whose history we're examining as well!
    try:
        Summoner.objects.filter(region=region).get(summoner_id=summoner_id)
    except ObjectDoesNotExist:  # if it isn't cached, and it isn't in the list yet, add it
        if summoner_id not in player_list:
            player_list.append(summoner_id)

    query_list = list(
        chunks(player_list, MAX_IDS)
    )  # query_list now holds a list of lists of at most MAX_ID elements

    # Now ask the API for info on summoners, at most MAX_ID at a time.
    #print 'Now asking for participants...'
    summoner_dto = []
    for i in query_list:
        summoner_dto.append(riot_api.get_summoners(ids=i, region=region))

    #print 'Done getting participants!'

    # TODO: This part is sometimes getting duplicate summoners! (fixed?)
    # Now put those summoner DTOs in the cache.
    for chunk in summoner_dto:
        for player in chunk:
            # for v in chunk[player]:
            #     print v, len(v)
            #print u'ADDING summoner {}'.format(chunk[player]['name'])
            summoner = Summoner(summoner_id=chunk[player]['id'],
                                name=chunk[player]['name'],
                                std_name=chunk[player]['name'].replace(
                                    ' ', '').lower(),
                                profile_icon_id=chunk[player]['profileIconId'],
                                revision_date=chunk[player]['revisionDate'],
                                summoner_level=chunk[player]['summonerLevel'],
                                region=region)

            # Sometimes requests will go out synchronously for the same summoner.
            # This means the cache is not hit and a double query for a single summoner occurs.
            # Duplicate summoners are prevented via the unique_together constraint on summoner_id and region,
            # which will throw IntegrityError and prevent the dupe from being made.
            try:
                #print summoner.name, len(summoner.name)
                summoner.save()
            except IntegrityError:
                pass

    # Requires summoners (as well as all related field values) to be cached before-hand (summoner caching done above).
    for match in recent['games']:
        # first fill in the simple stuff
        game = Game(
            summoner_id=Summoner.objects.filter(region=region).get(
                summoner_id=summoner_id),
            champion_id=Champion.objects.get(champion_id=match['championId']),
            create_date=match['createDate'],
            game_id=match['gameId'],
            game_mode=match['gameMode'],
            game_type=match['gameType'],
            invalid=match['invalid'],
            ip_earned=match['ipEarned'],
            level=match['level'],
            map_id=match['mapId'],
            spell_1=SummonerSpell.objects.get(spell_id=match['spell1']),
            spell_2=SummonerSpell.objects.get(spell_id=match['spell2']),
            sub_type=match['subType'],
            team_id=match['teamId'],
            region=region,
            champion_key=Champion.objects.get(
                champion_id=match['championId']).key)

        stats = RawStat()

        # Here we add stats that were returned (only stats that aren't None or 0 will be returned by API)
        for i in match['stats']:
            setattr(stats, inflection.underscore(i), match['stats'][i])

        stats.save()

        # associate the RawStat object with this game
        game.stats = stats

        game_saved = False

        # Ensures no dupes of Game (or any related objects).
        try:
            game.save()
            game_saved = True
        except IntegrityError:
            pass

        # if game saved, we're good and just need to add the participating players
        if game_saved:
            # associate each Player object with this game
            if 'fellowPlayers' in match:
                for p in match['fellowPlayers']:
                    player = Player(
                        champion=Champion.objects.get(
                            champion_id=p['championId']),
                        summoner=Summoner.objects.filter(region=region).get(
                            summoner_id=p['summonerId']),
                        team_id=p['teamId'],
                        participant_of=game)
                    player.save()
        else:  # if it didn't save, we can get rid of the stats object too.
            stats.delete()