def join_league(): """A form submission to ask to join the league.""" # ensure given an email email = session.get("oauth_email", None) if email is None: # it should have been stored after authenicating message = "Sorry, the authentication provider did not give an email" raise OAuthException(message) # double check the player email has not be taken player = Player.query.filter(Player.email == email).first() if player is not None: login_user(player) return redirect(url_for("homepage")) # double check this is not refresh page issue pending_request = JoinLeagueRequest.query.filter( func.lower(JoinLeagueRequest.email) == email.lower()).first() if pending_request is not None: raise HaveLeagueRequestException("Double submit on form") # ensure the selected team exists team_id = request.form.get("team", None) if team_id is None: raise TeamDoesNotExist(f"Team does not exist - {team_id}") team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(f"Team does not exist - {team_id}") # save the request player_name = request.form.get("name", None) gender = "F" if request.form.get("is_female", False) else "M" league_request = JoinLeagueRequest(email, player_name, team, gender) DB.session.add(league_request) DB.session.commit() return redirect(url_for("league_request_sent"))
def extract_game(game, team_lookup, lookup): """Returns a game json object Parameters: game: the entry for the game team_lookup: a lookup for team names to player ids lookup: a lookup for fields to indexes in columns Returns: a json game object, None if game data not found """ if not is_game_row_valid(game, lookup): return None away = game[lookup["away"]].strip() home = game[lookup["home"]].strip() time = game[lookup["time"]].strip() field = game[lookup["field"]].strip() date = game[lookup["date"]].strip() # check if variables meet certain conditions # else should be good to add game away_team = team_lookup.get(away, None) home_team = team_lookup.get(home, None) if away_team is None: error_message = INVALID_TEAM.format(away_team) raise TeamDoesNotExist(payload={'details': error_message}) if home_team is None: error_message = INVALID_TEAM.format(home_team) raise TeamDoesNotExist(payload={'details': error_message}) return {"away_team_id": away_team, "home_team_id": home_team, "time": time, "field": field, "date": date}
def update(self, date: str = None, time: str = None, home_team_id: int = None, away_team_id: int = None, league_id: int = None, status: str = None, field: str = None, division_id: int = None) -> None: """Update an existing game. Raises: InvalidField TeamDoesNotExist LeagueDoesNotExist """ d = self.date.strftime("%Y-%m-%d") t = self.date.strftime("%H:%M") if date is not None and date_validator(date): d = date elif date is not None: raise InvalidField(payload={'details': "Game - date"}) if time is not None and time_validator(time): t = time elif time is not None: raise InvalidField(payload={'details': "Game - time"}) if (home_team_id is not None and Team.query.get(home_team_id) is not None): self.home_team_id = home_team_id elif home_team_id is not None: raise TeamDoesNotExist(payload={'details': home_team_id}) if (away_team_id is not None and Team.query.get(away_team_id) is not None): self.away_team_id = away_team_id elif away_team_id is not None: raise TeamDoesNotExist(payload={'details': away_team_id}) if league_id is not None and League.query.get(league_id) is not None: self.league_id = league_id elif league_id is not None: raise LeagueDoesNotExist(payload={'details': league_id}) if status is not None and string_validator(status): self.status = status elif status is not None: raise InvalidField(payload={'details': "Game - status"}) if field is not None and field_validator(field): self.field = field elif field is not None: raise InvalidField(payload={'details': "Game - field"}) if (division_id is not None and Division.query.get(division_id) is not None): self.division_id = division_id elif division_id is not None: raise DivisionDoesNotExist(payload={'details': "division_id"}) # worse case just overwrites it with same date or time self.date = datetime.strptime(d + "-" + t, '%Y-%m-%d-%H:%M')
def unsubscribe(kik, team_id): """A function used to unsubscribe a kik user name to a player. Parameters: kik: the kik user name team_id: the id of the team the player belongs to Returns: True Raises: TeamDoesNotExist PlayerNotSubscribed """ player = Player.query.filter_by(kik=kik).first() if player is None: raise PlayerNotSubscribed( payload={'details': "Player is not subscribed"}) team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={"details": team_id}) subscribed = (Espys.query.filter_by(team_id=team_id).filter_by( description=SUBSCRIBED.format(str(player)))).first() if subscribed is not None: # delete the subscription entry DB.session.delete(subscribed) DB.session.commit() # else dont care return True
def get(self, team_id): """ GET request for Team Roster List Route: Routes['team_roster']/<int:team_id> Returns: status: 200 mimetype: application/json data: [ 'team_id': { 'color': '', 'league_id': int, 'sponsor_id': int, 'team_id': int, 'year': int}, 'captain': { 'email': '', 'gender': '', 'player_id': int, 'player_name': ''}, 'players': [{'email': '', 'gender': '', 'player_id': int, 'player_name': ''}] }, 'team_id':{...}, ] """ team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) result = team.json() result['players'] = [] for player in team.players: result['players'].append(player.json()) response = Response(dumps(result), status=200, mimetype="application/json") return response
def post(self): """ POST request for retrieving a captain games that needs scores submitted Route: Route['botcaptaingames'] Parameters: team: the team's id (str) player_id: the captain's player_id (int) Returns: status: 200 mimetype: application/json result: list of games objects """ args = parser.parse_args() team_id = args['team'] player_id = args['player_id'] team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) if team.player_id is None: raise InvalidField( payload={"details": "Team's captain has not been set"}) if player_id != team.player_id: # something fishy is going on raise NotTeamCaptain(payload={'details': player_id}) # captain is authenticated # now get the teams games, that have past game date and have no bats result = [game.json() for game in games_without_scores(team_id)] return Response(dumps(result), status=200, mimetype="application/json")
def delete(self, team_id): """ DELETE request for Team Roster List Routes: Routes['team_roster']/<int:team_id> Parameters : player_id: The player id (int) team_id: The team id (int) Returns: status: 200 mimetype: application/json data: success: tells if request was successful (boolean) message: the status message (string) """ args = parser.parse_args() team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) team.remove_player(args['player_id']) if team.player_id == args['player_id']: team.player_id = None DB.session.commit() response = Response(dumps(None), status=200, mimetype="application/json") return response
def post(self): """ POST request for authenticating a player is a captain of a team Route: Route['kikcaptain'] Parameters: team: the team's id (str) captain: the name of the captain (str) kik: the captain's kik user name (str) Returns: status: 200 mimetype: application/json data: id: the captain's team id """ args = parser.parse_args() captain = args['captain'] team_id = args['team'] kik = args['kik'] team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) team_captain = Player.query.get(team.player_id) if team_captain.name != captain: # the names do not match raise NotTeamCaptain(payload={'details': team_captain.name}) if team_captain.kik is None: # update their kik name team_captain.kik = kik DB.session.commit() elif team_captain.kik != kik: # something fishy is going on raise TeamAlreadyHasCaptain(payload={'details': team_captain.kik}) # captain is authenticated return Response(dumps(team.id), status=200, mimetype="application/json")
def post(self): """ POST request for authenticating a player is a captain of a team Route: Route['botcaptain'] Parameters: team: the team's id (str) player_id: the player_id of the captain (int) Returns: status: 200 mimetype: application/json team.id: the team's id of the captain """ args = parser.parse_args() player_id = args['player_id'] team_id = args['team'] team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) team_captain = Player.query.get(team.player_id) if team_captain.id != player_id: # the names do not match raise NotTeamCaptain(payload={'details': team_captain.name}) # captain is authenticated return Response(dumps(team.id), status=200, mimetype="application/json")
def post(self, team_id): """ POST request for Team Roster List Route: Routes['team_roster']/<int:team_id> Parameters : player_id: a player's identifier (int) captain: a 1 if a captain (int) Returns: status: 200 mimetype: application/json data: success: tells if request was successful (boolean) message: the status message (string) failures: a list of parameters that failed (list of string) """ args = parser.parse_args() team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) captain = False if args['captain'] and args['captain'] == 1: captain = True team.insert_player(args['player_id'], captain=captain) DB.session.commit() response = Response(dumps(None), status=201, mimetype="application/json") return response
def delete(self, team_id): """ DELETE request for Team Route: Routes['team']/<team_id:int> Returns: if found status: 200 mimetype: application/json data: None otherwise status: 404 mimetype: application/json data: None """ team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) # delete a single team team_json = team.json() DB.session.delete(team) DB.session.commit() response = Response(dumps(None), status=200, mimetype="application/json") handle_table_change(Tables.TEAM, item=team_json) return response
def get(self, team_id): """ GET request for Team Object matching given team_id Route: Routes['team']/<team_id:int> Returns: if found status: 200 mimetype: application/json data: { 'team_id': int, 'team_name': string, 'color': string, 'sponsor_id': int, 'league_id': int, 'year': int, 'espys': int, 'captain': string } otherwise status: 404 mimetype: application/json data: None """ # expose a single team entry = Team.query.get(team_id) if entry is None: raise TeamDoesNotExist(payload={'details': team_id}) response = Response(dumps(entry.json()), status=200, mimetype="application/json") return response
def subscribe(kik, name, team_id): """A function used to subscribe a kik user name to a player. Parameters: kik: the kik user name name: the name of the player team_id: the id of the team the player belongs to Returns: True Raises: TeamDoesNotExist PlayerNotOnTeam """ # dont care if they are on the team # check for some goof player = Player.query.filter_by(kik=kik).filter_by(active=True).all() if len(player) > 1 and player[0].name != name: s = "Kik user subscribing as two different people" raise BadRequestError(payload={'details': s}) team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) player = Player.query.filter_by(name=name).filter_by(active=True).all() if len(player) > 1: # f**k i dont know raise InvalidField("Two people with exact name, email the convenors") elif player is None or len(player) == 0: # player is not officially in our db # going to add them as a guest player = Player(name, name + "@guest", gender="M", password="******", active=False) DB.session.add(player) DB.session.commit() else: player = player[0] if player.kik is None: # give them the two points player.kik = kik points_awarded = Espys(team_id, description=AWARD_POINTS.format( str(player), KIKPOINTS), points=KIKPOINTS) DB.session.add(points_awarded) elif player.kik != kik: # the player is subscribing under a new kik name player.kik = kik subscribed = (Espys.query.filter_by(team_id=team_id).filter_by( description=SUBSCRIBED.format(str(player)))).first() if subscribed is None: # player is not subscribed subscribed = Espys(team_id, description=SUBSCRIBED.format(str(player)), points=0) DB.session.add(subscribed) DB.session.commit() return True
def get_active_team(): """Get some active team.""" year = datetime.now().year team = Team.query.filter( and_(Team.year == year, Team.player_id is not None)).first() if team is None: raise TeamDoesNotExist("No team for current year") return Response(json.dumps(team.json(admin=True)), 200, mimetype='application/json')
def decorated(*args, **kwargs): if not are_logged_in(): return redirect(url_for("loginpage")) team_id = kwargs.get('team_id', 1 if not (len(args) > 0) else args[0]) team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={"details": team_id}) if team.player_id != current_user.id: raise NotTeamCaptain(payload={"details": team_id}) return f(*args, **kwargs)
def __init__(self, date: str, time: str, home_team_id: int, away_team_id: int, league_id: int, division_id: int, status: str = "", field: str = ""): """The Constructor. Raises: InvalidField TeamDoesNotExist LeagueDoesNotExist DivisionDoesNotExist """ # check for all the invalid parameters if not date_validator(date): raise InvalidField(payload={'details': "Game - date"}) if not time_validator(time): raise InvalidField(payload={'details': "Game - time"}) self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M') if (home_team_id is None or Team.query.get(home_team_id) is None): raise TeamDoesNotExist(payload={'details': home_team_id}) if (away_team_id is None or Team.query.get(away_team_id) is None): raise TeamDoesNotExist(payload={'details': away_team_id}) if League.query.get(league_id) is None: raise LeagueDoesNotExist(payload={'details': league_id}) if ((status != "" and not string_validator(status)) or (field != "" and not field_validator(field))): raise InvalidField(payload={'details': "Game - field/status"}) if Division.query.get(division_id) is None: raise DivisionDoesNotExist(payload={'details': division_id}) # must be good now self.home_team_id = home_team_id self.away_team_id = away_team_id self.league_id = league_id self.status = status self.field = field self.division_id = division_id
def post(self): """ POST request for submitting a transaction Route: Route['bottransaction'] Parameters: player_id: the id of the player submitting the receipt (int) amount: the amount spent (int) sponsor: the name of the sponsor (str) team_id: the id of the team (int) Returns: status: 200 mimetype: application/json data: True """ args = parser.parse_args() player_id = args['player_id'] team_id = args['team_id'] amount = args['amount'] sponsor_name = args['sponsor'] # ensure the player exists player = Player.query.get(player_id) if player is None: raise PlayerDoesNotExist(payload={'details': player_id}) # ensure the team exist team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) # ensure the sponsor exists sponsor = Sponsor.query.filter_by(name=sponsor_name).first() if sponsor is None: raise SponsorDoesNotExist(payload={'details': sponsor_name}) # player can only submit receipts to their own team if not team.is_player_on_team(player): raise PlayerNotOnTeam(payload={'details': player_id}) # should be good to add the espy now espy = Espys(team_id=team.id, sponsor_id=sponsor.id, points=amount, description="Bot transaction") DB.session.add(espy) DB.session.commit() handle_table_change(Tables.ESPYS) return Response(dumps(espy.id), status=200, mimetype="application/json")
def put(self, team_id): """ PUT request for team Route: Routes['team']/<team_id:int> Parameters : team_id: The team's id (int) team_name: The team's name (string) sponsor_id: The sponsor's id (int) league_id: The league's id (int) color: the color of the team (string) year: the year of the team (int) espys: the total espys points of the team (int) Returns: if found and updated successfully status: 200 mimetype: application/json data: None otherwise possible errors are status: 404, IFSC, LDNESC, PDNESC or SDNESC mimetype: application/json data: None """ # update a single user team = Team.query.get(team_id) args = parser.parse_args() color = None sponsor_id = None league_id = None year = None if team is None: raise TeamDoesNotExist(payload={'details': team_id}) if args['color']: color = args['color'] if args['sponsor_id']: sponsor_id = args['sponsor_id'] if args['league_id']: league_id = args['league_id'] if args['year']: year = args['year'] team.update(color=color, sponsor_id=sponsor_id, league_id=league_id, year=year) DB.session.commit() response = Response(dumps(None), status=200, mimetype="application/json") handle_table_change(Tables.TEAM, item=team.json()) return response
def __init__(self, email: str, name: str, team: 'Team', gender: str): if team is None or not isinstance(team, Team) or team.id is None: raise TeamDoesNotExist("Given team does not exist") if not gender_validator(gender): raise InvalidField(payload={ 'details': "Player League Request - gender"}) if not string_validator(email): raise InvalidField(payload="Player League Request - email") if not string_validator(name): raise InvalidField(payload="Player League Request - name") self.email = email.lower() self.name = name self.team_id = team.id self.pending = True self.gender = gender.lower()
def post(self): """ POST request for retrieving a captain games that needs scores submitted Route: Route['kikcaptaingames'] Parameters: team: the team's id (str) kik: the captain's kik user name (str) Returns: status: 200 mimetype: application/json result: list of games objects """ args = parser.parse_args() team_id = args['team'] kik = args['kik'] team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) if team.player_id is None: raise InvalidField( payload={"details": "Team's captain has not been set"}) team_captain = Player.query.get(team.player_id) if team_captain is None: raise PlayerDoesNotExist(payload={'details': team.player_id}) if team_captain.kik != kik: # something fishy is going on raise NotTeamCaptain(payload={'details': team_captain.kik}) # captain is authenticated # get all the bats for that team and its game id bats = (DB.session.query( Bat.game_id).filter(Bat.team_id == team_id)).all() if (len(bats) > 0): games = (DB.session.query(Game).filter( or_(Game.away_team_id == team_id, Game.home_team_id == team_id)).filter( Game.date <= datetime.today()).filter( ~Game.id.in_(bats))).all() else: games = (DB.session.query(Game).filter( or_(Game.away_team_id == team_id, Game.home_team_id == team_id)).filter( Game.date <= datetime.today())).all() # now get the teams games, that have past game date and have no bats result = [] for game in games: result.append(game.json()) return Response(dumps(result), status=200, mimetype="application/json")
def __init__(self, team_id, sponsor_id=None, description=None, points=0.0, receipt=None, time=None, date=None): """The constructor. Raises: SponsorDoesNotExist TeamDoesNotExist """ if not float_validator(points): raise InvalidField(payload={"details": "Game - points"}) self.points = float(points) self.date = datetime.now() sponsor = None if sponsor_id is not None: sponsor = Sponsor.query.get(sponsor_id) self.receipt = receipt if sponsor_id is not None and sponsor is None: raise SponsorDoesNotExist(payload={"details": sponsor_id}) team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={"details": team_id}) self.description = description self.team_id = team_id self.sponsor_id = sponsor_id self.kik = None if date is not None and not date_validator(date): raise InvalidField(payload={'details': "Game - date"}) if time is not None and not time_validator(time): raise InvalidField(payload={'details': "Game - time"}) if date is not None and time is None: self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M') else: self.date = datetime.today()
def update(self, player_id=None, team_id=None, game_id=None, rbi=None, hit=None, inning=None): """Update an existing bat. Raises: TeamDoesNotExist GameDoesNotExist PlayerDoesNotExist InvalidField """ if team_id is not None and Team.query.get(team_id) is not None: self.team_id = team_id elif team_id is not None: raise TeamDoesNotExist(payload={'details': team_id}) if game_id is not None and Game.query.get(game_id) is not None: self.game_id = game_id elif game_id is not None: raise GameDoesNotExist(payload={'details': game_id}) if player_id is not None and Player.query.get(player_id) is not None: self.player_id = player_id elif player_id is not None: raise PlayerDoesNotExist(payload={'details': player_id}) if rbi is not None and rbi_validator(rbi): self.rbi = rbi elif rbi is not None: raise InvalidField(payload={'details': "Bat - rbi"}) if hit is not None and hit_validator(hit): self.classification = hit elif hit is not None: raise InvalidField(payload={'details': "Bat - hit"}) if inning is not None and inning_validator(inning): self.inning = inning elif inning is not None: raise InvalidField(payload={'details': "Bat - inning"})
def update(self, team_id=None, sponsor_id=None, description=None, points=None, receipt=None, date=None, time=None): """Used to update an existing espy transaction. Raises: TeamDoesNotExist SponsorDoesNotExist """ if points is not None: self.points = points if description is not None: self.description = description if team_id is not None: if Team.query.get(team_id) is not None: self.team_id = team_id else: raise TeamDoesNotExist(payload={"details": team_id}) if sponsor_id is not None: if Sponsor.query.get(sponsor_id) is not None: self.sponsor_id = sponsor_id else: raise SponsorDoesNotExist(payload={"details": sponsor_id}) if receipt is not None: self.receipt = receipt if date is not None and time is None: self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M') if date is not None and time is not None: if date is not None and not date_validator(date): raise InvalidField(payload={'details': "Game - date"}) if time is not None and not time_validator(time): raise InvalidField(payload={'details': "Game - time"}) self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M')
def __init__(self, player_id, team_id, game_id, classification, inning=1, rbi=0): """The constructor. Raises: PlayerDoesNotExist InvalidField TeamDoesNotExist GameDoesNotExist """ # check for exceptions classification = classification.lower().strip() player = Player.query.get(player_id) if player is None: raise PlayerDoesNotExist(payload={'details': player_id}) if not hit_validator(classification, player.gender): raise InvalidField(payload={'details': "Bat - hit"}) if not rbi_validator(rbi): raise InvalidField(payload={'details': "Bat - rbi"}) if not inning_validator(inning): raise InvalidField(payload={'details': "Bat - inning"}) if Team.query.get(team_id) is None: raise TeamDoesNotExist(payload={'details': team_id}) if Game.query.get(game_id) is None: raise GameDoesNotExist(payload={'details': game_id}) # otherwise good and a valid object self.classification = classification self.rbi = rbi self.player_id = player_id self.team_id = team_id self.game_id = game_id self.inning = inning