availabili.tf/backend-flask/team.py

90 lines
2.2 KiB
Python
Raw Normal View History

2024-11-02 12:33:27 -07:00
import datetime
from typing import List
from flask import Blueprint, abort, jsonify, make_response, request
2024-11-02 12:33:27 -07:00
import pydantic
from flask_pydantic import validate
from spectree import Response
from models import Player, PlayerTeam, Team, TeamSpec, db
2024-11-02 12:33:27 -07:00
from middleware import requires_authentication
import models
from spec import spec, BaseModel
2024-11-02 12:33:27 -07:00
api_team = Blueprint("team", __name__, url_prefix="/team")
class CreateTeamJson(BaseModel):
team_name: str
webhook_url: str
timezone: str
class ViewTeamResponse(BaseModel):
team: models.TeamSpec
class ViewTeamsResponse(BaseModel):
teams: list[models.TeamSpec]
@api_team.get("/all/")
@spec.validate(
resp=Response(
HTTP_200=ViewTeamsResponse,
HTTP_403=None,
HTTP_404=None,
)
)
2024-11-02 12:33:27 -07:00
@requires_authentication
def view_teams(**kwargs):
2024-11-02 12:33:27 -07:00
player: Player = kwargs["player"]
response = fetch_teams_for_player(player, None)
if isinstance(response, ViewTeamsResponse):
return jsonify(response.dict())
abort(404)
2024-11-02 12:33:27 -07:00
@api_team.get("/id/<team_id>/")
@spec.validate(
resp=Response(
HTTP_200=ViewTeamResponse,
HTTP_403=None,
HTTP_404=None,
)
)
@requires_authentication
def view_team(team_id: int, **kwargs):
player: Player = kwargs["player"]
response = fetch_teams_for_player(player, team_id)
if isinstance(response, ViewTeamResponse):
return jsonify(response.dict())
abort(404)
2024-11-02 12:33:27 -07:00
def fetch_teams_for_player(player: Player, team_id: int | None):
2024-11-02 12:33:27 -07:00
q = db.session.query(
Team
).join(
PlayerTeam
).join(
Player
).where(
2024-11-02 12:33:27 -07:00
PlayerTeam.player_id == player.steam_id
)
if team_id is not None:
q = q.where(PlayerTeam.team_id == team_id)
2024-11-02 12:33:27 -07:00
def map_team_to_spec(team: Team) -> TeamSpec:
return TeamSpec(
id=team.id,
team_name=team.team_name,
discord_webhook_url=None
)
2024-11-02 12:33:27 -07:00
if team_id is None:
teams = q.all()
return ViewTeamsResponse(
teams=list(map(map_team_to_spec, teams))
)
2024-11-02 12:33:27 -07:00
else:
team = q.one_or_none()
if team:
return ViewTeamResponse(
team=map_team_to_spec(team)
)