Exemple #1
0
    def on_execute(self, command: CreateLeagueSubscriptionsCommand) -> CreateLeagueSubscriptionsResult:
        league_id = command.league.id if command.league else command.league_id

        if not league_id:
            Logger.warn("CreateLeagueSubscriptions - No league ID")
            return CreateLeagueSubscriptionsResult(command=command, error="Missing league id")

        api_key = self.settings.api_key
        league_command_sub_id = f"league_{league_id}-commands"
        league_command_endpoint = f"{self.settings.endpoint}/system/league_command?league_id={league_id}&key={api_key}"
        league_command_subscription = self.publisher.create_push_subscription(league_command_sub_id, LEAGUE_COMMAND_TOPIC, league_command_endpoint)
        league_command_subscription = league_command_subscription.name

        transaction = self.league_repo.firestore.create_transaction()

        @firestore.transactional
        def update_in_transaction(transaction):
            league = self.league_repo.get(league_id, transaction)
            league.league_command_subscription = True

            self.league_repo.update(league, transaction)

        update_in_transaction(transaction)

        return CreateLeagueSubscriptionsResult(
            command=command,
            subscriptions=[
                league_command_subscription,
            ],
        )
Exemple #2
0
    def on_execute(self, command: EndOfWeekCommand) -> EndOfWeekResult:

        # @firestore.transactional
        # def end_of_week(transaction: Transaction) -> EndOfWeekResult:
        season = self.settings.current_season
        # current_week = self.public_repo.get_state().current_week
        # completed_week = current_week - 1
        # completed_games = self.game_repo.for_week(season, completed_week)
        # completed_game_ids = [g.id for g in completed_games]

        if self.public_repo.get_switches().enable_score_testing:
            season = 2019
            Logger.warn("SCORE TESTING SWITCH IS ENABLED")

        players = self.player_repo.get_all(season)
        # players = [self.player_repo.get(season, "111244")]

        updated_players = []
        for player in players:
            if not player.game_stats:
                continue

            # Not ideal - might need to be revisited, but this missed the players on bye.
            # Maybe can be restored after being run once?
            # player_games_ids = list(player.game_stats.keys())
            # player_games_ids.sort()

            # last_player_game_id = player_games_ids[-1]
            # if last_player_game_id not in completed_game_ids:
            #     continue

            player.recalc_season_stats()
            updated_players.append(player)
            self.player_repo.set(season, player)

        # return EndOfWeekResult(command=command, updated_players=updated_players)

        # transaction = self.player_repo.firestore.create_transaction()
        # result: EndOfWeekResult = end_of_week(transaction)

        # if result.success:
        command = CalculateSeasonScoreCommand()
        payload = LeagueCommandPushData(
            command_type=LeagueCommandType.CALCULATE_SEASON_SCORE,
            command_data=command.dict())
        self.publisher.publish(payload, LEAGUE_COMMAND_TOPIC)

        return EndOfWeekResult(command=command,
                               updated_players=updated_players)
    def on_execute(
        self, command: UpdatePlayerStatsForWeekCommand
    ) -> UpdatePlayerStatsForWeekResult:
        Logger.info(f"Updating player stats for week {command.week}")

        season = command.season

        if self.public_repo.get_switches().enable_score_testing:
            season = 2019
            Logger.warn("SCORE TESTING SWITCH IS ENABLED")

        current_games = self.get_current_games(season, command.week)
        player_updates = get_players(current_games)

        transaction = self.game_repo.firestore.create_transaction()

        @firestore.transactional
        def update(transaction, players: List[GamePlayerStats]):

            pending_player_updates = []

            for player_update in players:
                player = self.player_repo.get(season, player_update.player.id,
                                              transaction)
                game_id = player_update.game_id
                if not player:
                    player = from_game_player(player_update.player,
                                              player_update.team)

                if not player.game_stats:
                    player.game_stats = {}

                player.game_stats[game_id] = PlayerGameStats(
                    team=player.team, **player_update.stats.dict())
                pending_player_updates.append(player)

            for player in pending_player_updates:
                self.player_repo.set(season, player, transaction)

            return pending_player_updates

        update(transaction, player_updates)

        return UpdatePlayerStatsForWeekResult(command=command, )
Exemple #4
0
def __get_token(request: Request):
    if "Authorization" not in request.headers:
        return None

    header = request.headers["Authorization"]

    try:
        parts = header.split(" ")
        if len(parts) < 2:
            Logger.warn("Invalid bearer token (less than 2 parts)")
            return None

        token = parts[1]
        # Logger.info(token)
        token = auth.verify_id_token(token, check_revoked=True)
        uid = token["uid"]
        request.state.uid = uid
        context.data["user_id"] = uid
        return token

    except auth.ExpiredIdTokenError:
        Logger.warn("Expired token encountered")
    except auth.InvalidIdTokenError:
        Logger.warn("Invalid token encountered")
    except BaseException as ex:
        Logger.error("Exception occurred while decoding token", exc_info=ex)
        return None
Exemple #5
0
    def from_cfl_roster(abbreviation: str):
        if abbreviation in ["DE", "DT"]:
            abbreviation = "DL"

        if abbreviation in ["OL", "LS", "G", "T"]:
            abbreviation = "ol"

        if abbreviation in ["P"]:
            abbreviation = "K"

        if abbreviation in ["FB"]:
            abbreviation = "RB"

        if abbreviation in ["SB", "TE"]:
            abbreviation = "WR"

        if abbreviation in ["S", "CB"]:
            abbreviation = "DB"

        try:
            return PositionType(abbreviation.lower())
        except Exception:
            Logger.warn(f"Encountered unknown position '{abbreviation}'")
            return PositionType.other
Exemple #6
0
async def warn():
    Logger.warn("This is a test warn log entry")
    Logger.warn("This is a test warn log entry with extra info",
                extra={"foo": "bar"})
    return {"logger": Logger.logger_type()}
Exemple #7
0
    def on_execute(self, command: CalculateSeasonScoreCommand) -> CalculateSeasonScoreResult:

        season = self.settings.current_season

        if self.public_repo.get_switches().enable_score_testing:
            season = 2019
            Logger.warn("SCORE TESTING SWITCH IS ENABLED")

        players = self.player_repo.get_all(season)
        # players = [self.player_repo.get(season, "156305", transaction)]
        player_scores = self.player_score_repo.get_all(command.league_id)
        scoring = self.league_config_repo.get_scoring_config(command.league_id)

        player_scores = {player_score.id: player_score for player_score in player_scores}

        for player in players:
            player_score = player_scores.get(player.id, None)

            if not player_score:
                player_score = LeaguePlayerScore(id=player.id, game_stats=player.game_stats or {})
                player_scores[player.id] = player_score
                for game_id in player_score.game_stats:
                    game = player_score.game_stats[game_id]
                    player_score.game_scores[game_id] = scoring.calculate_score(game)

            player_score.season_stats = player.season_stats
            player_score.season_score = scoring.calculate_score(player.season_stats)

            player_score.games_played = len(player_score.game_stats)
            player_score.average = player_score.season_score.total_score / player_score.games_played if player_score.games_played > 0 else 0

        players = {player.id: player for player in players}
        player_scores = list(player_scores.values())
        player_scores.sort(key=lambda x: x.season_score.total_score, reverse=True)

        rank = 0
        skip_by = 1
        last_player_score: LeaguePlayerScore = None

        for player_score in player_scores:
            tied = last_player_score and player_score.season_score.total_score == last_player_score.season_score.total_score

            if tied:
                player_score.rank = rank
                skip_by += 1
            else:
                rank += skip_by
                skip_by = 1
                player_score.rank = rank

            last_player_score = player_score

        for player_score in player_scores:
            self.player_score_repo.set(command.league_id, player_score)

        result_scores = [
            {
                "id": score.id,
                "player": players[score.id].display_name,
                "score": score.season_score.total_score,
                "rank": score.rank,

            } for score in player_scores]

        return CalculateSeasonScoreResult(command=command, scores=result_scores)
Exemple #8
0
    def on_execute(self, command: UpdateGamesCommand) -> UpdateGamesResult:
        Logger.info(f"Updating games for week {command.week}")

        season = command.season

        if self.public_repo.get_switches().enable_score_testing:
            season = 2019
            Logger.warn("SCORE TESTING SWITCH IS ENABLED")

        current_games = self.get_current_games(season, command.week)
        stored_games = self.get_stored_games(season, command.week)

        roster_added = False
        for game_id in current_games:
            current_game = current_games[game_id]
            stored_game = stored_games.get(game_id, None)
            if current_game.away_roster and (not stored_game
                                             or not stored_game.away_roster):
                roster_added = True

            if current_game.home_roster and (not stored_game
                                             or not stored_game.home_roster):
                roster_added = True

        game_updates = get_changed_games(current_games, stored_games)
        player_updates = get_changed_players(game_updates, stored_games)

        transaction = self.game_repo.firestore.create_transaction()

        locked_teams: List[str] = []
        active_games_count = 0

        opponents: Dict[str, str] = {}

        for game in current_games.values():
            if game.event_status.event_status_id == EVENT_STATUS_POSTPONED:
                continue

            opponents[
                game.teams.away.abbreviation] = game.teams.home.abbreviation
            opponents[
                game.teams.home.abbreviation] = game.teams.away.abbreviation

            if game.event_status.has_started():
                active_games_count += 1
                locked_teams.append(game.teams.away.abbreviation)
                locked_teams.append(game.teams.home.abbreviation)

        all_games_active = active_games_count == len(current_games)

        new_locks_state = Locks.create(locked_teams, all_games_active)

        new_scoreboard = Scoreboard.create(current_games.values())
        new_opponents = Opponents.create(opponents)

        @firestore.transactional
        def update_games(transaction, games: Dict[str, Game],
                         players: List[GamePlayerStats]):
            state = self.state_repo.get()

            new_state = state.copy()
            new_state.locks = new_locks_state

            current_scoreboard = self.public_repo.get_scoreboard()
            current_opponents = self.public_repo.get_opponents()

            pending_player_updates = []

            for player_update in players:
                player = self.player_repo.get(season, player_update.player.id,
                                              transaction)
                game_id = player_update.game_id
                if not player:
                    player = from_game_player(player_update.player,
                                              player_update.team)

                if not player.game_stats:
                    player.game_stats = {}

                player.game_stats[game_id] = PlayerGameStats(
                    team=player.team, **player_update.stats.dict())
                player.recalc_season_stats()  # Should this be here?
                pending_player_updates.append(player)

            for game_id in games:
                game = game_updates[game_id]
                self.game_repo.set(season, game, transaction)

            for player in pending_player_updates:
                self.player_repo.set(season, player, transaction)

            if new_state.changed(state):
                self.state_repo.set(new_state, transaction)

            if new_scoreboard.changed(current_scoreboard):
                self.public_repo.set_scoreboard(new_scoreboard, transaction)

            if new_opponents.changed(current_opponents):
                self.public_repo.set_opponents(new_opponents, transaction)

            return pending_player_updates

        update_games(transaction, game_updates, player_updates)
        payloads = self.publish_changed_players(player_updates)

        if roster_added:
            self.publisher.publish(BaseModel(), UPDATE_PLAYERS_TOPIC)

        return UpdateGamesResult(
            command=command,
            changed_games=[game_updates[game_id] for game_id in game_updates],
            changed_players=payloads)