def post(self, name):
        data = Player.parser.parse_args()

        # not getting the name correctly from the url
        name = data["name"]

        if PlayerModel.find_by_name(name):
            return {
                'message': f'A player with name {name} already exists'
            }, 400

        data = Player.parser.parse_args()
        strategy = data['strategy']
        buyIn = data["buyIn"]
        chips = data["buyIn"]
        unitBet = data["unitBet"]

        player = PlayerModel(name=name,
                             strategy=strategy,
                             buyIn=buyIn,
                             chips=chips,
                             unitBet=unitBet)
        # print(f'{name}:{strategy}:{buyIn}:{chips}{unitBet}')

        try:
            player.save_to_db()
        except:
            #raise
            return {'message': 'an error occurred inserting the player.'}, 500

        #return player.json(), 201

        return redirect("/", code=302)
    def put(self, name):
        data = Player.parser.parse_args()

        # not getting the name correctly from the url
        name = data["name"]

        player = PlayerModel.find_by_name(name)

        # PlayerModel.insert(player)
        if player:
            # update attributes
            player.strategy = data['strategy']
            player.buyIn = data["buyIn"]
            player.chips = data["buyIn"]
            player.unitBet = data["unitBet"]
        else:
            player = PlayerModel(name=name,
                                 strategy=strategy,
                                 buyIn=buyIn,
                                 chips=chips,
                                 unitBet=unitBet)

        player.save_to_db()

        return player.json()
Пример #3
0
    def post(self):
        """ Class methods: POST
            Endpoint: /player-register

            Class method that handles post requests for the PlayerRegister Resource.
            Using payload from the POST request, it will use the 'playerName' and 
            the 'secretKey' that were provided to create a new player. This class will
            only handle the registering process.

        Args:

        Returns:
            'message' if either the user already exists or if the player was created succesfully.

        """

        #: object of parsed items set to their appropiate type: This data is reetrieved from payload.
        data = PlayerRegister.__player_parse.parse_args()

        # Check if the player name is already taken
        if (PlayerModel.findByPlayerName(data['playerName'])):
            return {'message': 'User already exists!'}, 409  #Conflict

        # Uses the PlayerRegister function save_to_db() function that uses SQLAlchemys save and commit to register the player
        # to the database
        player = PlayerModel(data['playerName'], data['secretKey'], 'player',
                             'none', 'none', 100, 100)
        player.save_to_db()

        return {'message': 'Player was created succesfully!'}, 201
Пример #4
0
 def put(self, name):
     data = Player.parser.parse_args()
     item = PlayerModel.find_name(name)
     if item is None:
         item = PlayerModel(name, data['price'])
     else:
         item.price = data['price']
         item.save_to_db()
     return item.json()
Пример #5
0
    def put(self, name):
        data = Player.parser.parse_args()

        player = PlayerModel.lookup(name)

        if player is None:
            player = PlayerModel(name, **data)

        player.save()

        return player.json()
Пример #6
0
    def post(self, id):
        token = request.headers.get('authorization')

        if not token:
            return {
                'error': True,
                'message': 'Missing token in authorization header.'
            }, 401

        # Gets the Room the player is currently in
        player_status_response = requests.get(
            'https://lambda-treasure-hunt.herokuapp.com/api/adv/init/',
            headers={
                'authorization': token
            }).json()
        if len(player_status_response['errors']) > 0:
            return player_status_response, 400

        time.sleep(1)

        # finds the the player by their unique log in token
        foundTraversingPlayer = PlayerModel.find_by_password(token)

        if foundTraversingPlayer:
            return {
                "error": True,
                "message": "Your character is already traversing"
            }
        # If the player is not in the DB they are added
        elif not foundTraversingPlayer:

            found_path = GraphTraversal().path_to_target(
                player_status_response['room_id'], id)
            if not found_path:
                return {
                    "error": True,
                    "message": "there is no path to that room you bonobo"
                }

            new_player_data = {
                "password": token,
                "currentRoomId": player_status_response['room_id'],
                "currentPath": json.dumps(found_path),
                "nextAvailableMove": 0,
                "singlePath": True
            }

            foundTraversingPlayer = PlayerModel(**new_player_data)

            foundTraversingPlayer.save_to_db()

        return {'Message': 'Target Traverse has started.'}
Пример #7
0
    def post(self, name):
        data = Player.parser.parse_args()
        team = TeamModel.find_by_name(data['team_name'])
        if team is None:
            return {"message": "Team does not exist"}

        if PlayerModel.find_by_back_number_in_team(data['back_number'],
                                                   team.id):
            return {"message": "Back number is already taken."}

        player = PlayerModel(name, data['back_number'], team.id)
        player.save_to_db()
        return player.json()
Пример #8
0
    def post(self, name):
        if PlayerModel.lookup(name):
            return {'message': "A player with name '{}' already exists.".format(name)}, 400

        data = Player.parser.parse_args()

        player = PlayerModel(name, **data)

        try:
            player.save()
        except:
            return {"message": "An error occurred inserting the player."}, 500

        return player.json(), 201
Пример #9
0
    async def fetch(self, include_stats=False):
        """ Selects given players, if include_stats then will be ordered by elo.
            https://github.com/ModuleLIFT/API/blob/master/docs/modules.md#fetchself-include_statsfalse
        """

        values = dict(self.values)

        if include_stats:
            query = """SELECT IFNULL(statistics.elo, 0) AS elo,
                              IFNULL(statistics.kills, 0) AS kills,
                              IFNULL(statistics.deaths, 0) AS deaths,
                              IFNULL(statistics.assists, 0) AS assists,
                              IFNULL(statistics.shots, 0) AS shots,
                              IFNULL(statistics.hits, 0) AS hits,
                              IFNULL(statistics.damage, 0) AS damage,
                              IFNULL(statistics.headshots, 0) AS headshots,
                              IFNULL(statistics.rounds_won, 0) AS rounds_won,
                              IFNULL(statistics.rounds_lost, 0) AS rounds_lost,
                              IFNULL(statistics.wins, 0) AS wins,
                              IFNULL(statistics.ties, 0) AS ties,
                              IFNULL(statistics.loses, 0) AS loses,
                              users.discord_id, users.name,
                              users.user_id, users.file_type,
                              users.steam_id, users.joined
                    FROM users
                        LEFT JOIN statistics
                                ON users.user_id = statistics.user_id
                                   AND statistics.league_id = :league_id
                                   AND statistics.region = :region
                    WHERE users.user_id IN :user_ids
                    ORDER BY statistics.elo DESC"""

            values["league_id"] = self.current_league.league_id
            values["region"] = self.current_league.region
        else:
            query = """SELECT discord_id, name, user_id, steam_id, joined
                       FROM users WHERE user_id IN :user_ids"""

        rows_formatted = []
        rows_formatted_append = rows_formatted.append
        async for row in SESSIONS.database.iterate(query=query, values=values):

            player = PlayerModel(row)

            if include_stats:
                rows_formatted_append(player.full)
            else:
                rows_formatted_append(player.minimal)

        return Response(data=rows_formatted)
Пример #10
0
    async def fetch(self, include_stats=False):
        """ Selects given players. """

        values = dict(self.values)

        if include_stats:
            query = """SELECT IFNULL(statistics.elo, 0) AS elo,
                              IFNULL(statistics.kills, 0) AS kills,
                              IFNULL(statistics.deaths, 0) AS deaths,
                              IFNULL(statistics.assists, 0) AS assists,
                              IFNULL(statistics.shots, 0) AS shots,
                              IFNULL(statistics.hits, 0) AS hits,
                              IFNULL(statistics.damage, 0) AS damage,
                              IFNULL(statistics.headshots, 0) AS headshots,
                              IFNULL(statistics.roundswon, 0) AS roundswon,
                              IFNULL(statistics.roundslost, 0) AS roundslost,
                              IFNULL(statistics.wins, 0) AS wins,
                              IFNULL(statistics.ties, 0) AS ties,
                              IFNULL(statistics.losses, 0) AS losses,
                              users.discord_id, users.name,
                              users.pfp, users.user_id,
                              users.steam_id, users.joined
                    FROM users
                        LEFT JOIN statistics
                                ON users.user_id = statistics.user_id
                                   AND statistics.league_id = :league_id
                    WHERE users.region = :region
                          AND users.user_id IN :user_ids
                    ORDER BY statistics.elo DESC"""

            values["league_id"] = self.current_league.league_id
        else:
            query = """SELECT discord_id, name, pfp, user_id, steam_id, joined
                       FROM users WHERE region = :region
                                        AND user_id IN :user_ids"""

        rows_formatted = []
        rows_formatted_append = rows_formatted.append
        async for row in self.current_league.obj\
                .database.iterate(query=query, values=values):

            player = PlayerModel(row)

            if include_stats:
                rows_formatted_append(player.full)
            else:
                rows_formatted_append(player.minimal)

        return response(data=rows_formatted)
Пример #11
0
def sample_data(app, db):
    admin = UserModel(email='*****@*****.**', password='******')
    guest = UserModel(email='*****@*****.**', password='******')
    db.session.add(admin)
    db.session.add(guest)

    team1 = TeamModel(name='England')
    team2 = TeamModel(name='Australia')

    db.session.add(team1)
    db.session.add(team2)
    db.session.commit()

    player1a = PlayerModel(name='Jack', team_id=team1.id)
    player1b = PlayerModel(name='Jill', team_id=team1.id)
    db.session.add(player1a)
    db.session.add(player1b)

    player2a = PlayerModel(name='Jamie', team_id=team2.id)
    player2b = PlayerModel(name='James', team_id=team2.id)
    db.session.add(player2a)
    db.session.add(player2b)

    db.session.commit()
Пример #12
0
    def post(self, name):
        if PlayerModel.find_name(name):
            return {
                'message':
                "An item with name '{}' already exists.".format(name)
            }, 400

        data = Player.parser.parse_args()

        item = PlayerModel(name, **data)

        try:
            item.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500

        return item.json(), 201

        players.append(player)
        return player
Пример #13
0
    async def players(self):
        """ Pulls players
            https://github.com/ModuleLIFT/API/blob/master/docs/modules.md#playersself
        """

        query = """SELECT IFNULL(statistics.elo, 0) AS elo,
                          IFNULL(statistics.kills, 0) AS kills,
                          IFNULL(statistics.deaths, 0) AS deaths,
                          IFNULL(statistics.assists, 0) AS assists,
                          IFNULL(statistics.shots, 0) AS shots,
                          IFNULL(statistics.hits, 0) AS hits,
                          IFNULL(statistics.damage, 0) AS damage,
                          IFNULL(statistics.headshots, 0) AS headshots,
                          IFNULL(statistics.rounds_won, 0) AS rounds_won,
                          IFNULL(statistics.rounds_lost, 0) AS rounds_lost,
                          IFNULL(statistics.wins, 0) AS wins,
                          IFNULL(statistics.ties, 0) AS ties,
                          IFNULL(statistics.loses, 0) AS loses,
                          users.steam_id, users.discord_id,
                          users.name, users.file_type,
                          users.user_id, users.joined
                    FROM users
                        LEFT JOIN statistics
                                ON users.user_id = statistics.user_id
                                   AND statistics.region = :region
                                   AND statistics.league_id = :league_id
                    WHERE users.user_id = :search OR users.steam_id = :search
                         OR users.discord_id = :search
                         OR users.name LIKE :search
                    ORDER BY statistics.elo {}
                    LIMIT :limit, :offset""".format(self.order_by)

        rows_formatted = []
        rows_formatted_append = rows_formatted.append
        async for row in SESSIONS.database.iterate(
                query=query, values=self.values):
            rows_formatted_append(PlayerModel(row).full)

        return Response(data=rows_formatted)
Пример #14
0
    async def get(self):
        """ Gets infomation on given player. """

        query = """SELECT users.user_id, users.steam_id,
                          users.discord_id, users.name,
                          users.pfp, users.joined,
                          IFNULL(statistics.total_time, 0) AS total_time,
                          IFNULL(statistics.elo, 0) AS elo,
                          IFNULL(statistics.kills, 0) AS kills,
                          IFNULL(statistics.deaths, 0) AS deaths,
                          IFNULL(statistics.assists, 0) AS assists,
                          IFNULL(statistics.shots, 0) AS shots,
                          IFNULL(statistics.hits, 0) AS hits,
                          IFNULL(statistics.damage, 0) AS damage,
                          IFNULL(statistics.headshots, 0) AS headshots,
                          IFNULL(statistics.roundswon, 0) AS roundswon,
                          IFNULL(statistics.roundslost, 0) AS roundslost,
                          IFNULL(statistics.wins, 0) AS wins,
                          IFNULL(statistics.ties, 0) AS ties,
                          IFNULL(statistics.losses, 0) AS losses
                        FROM users
                        LEFT JOIN statistics
                            ON statistics.user_id = users.user_id
                    WHERE (users.steam_id = :user_id
                           OR users.discord_id = :user_id
                           OR users.user_id = :user_id)
                          AND statistics.region = :region
                          AND statistics.league_id = :league_id
                """

        row = await self.current_league.obj.database.fetch_one(
            query=query,
            values=self.values
        )
        if row:
            return response(data=PlayerModel(row).full)
        else:
            return response(error="Invalid user")
Пример #15
0
    async def get(self):
        """ Gets infomation on given player.
            https://github.com/ModuleLIFT/API/blob/master/docs/modules.md#getself-1
        """

        query = """SELECT users.user_id, users.steam_id,
                          users.discord_id, users.name,
                          users.joined, users.file_type,
                          IFNULL(statistics.total_time, 0) AS total_time,
                          IFNULL(statistics.elo, 0) AS elo,
                          IFNULL(statistics.kills, 0) AS kills,
                          IFNULL(statistics.deaths, 0) AS deaths,
                          IFNULL(statistics.assists, 0) AS assists,
                          IFNULL(statistics.shots, 0) AS shots,
                          IFNULL(statistics.hits, 0) AS hits,
                          IFNULL(statistics.damage, 0) AS damage,
                          IFNULL(statistics.headshots, 0) AS headshots,
                          IFNULL(statistics.rounds_won, 0) AS rounds_won,
                          IFNULL(statistics.rounds_lost, 0) AS rounds_lost,
                          IFNULL(statistics.wins, 0) AS wins,
                          IFNULL(statistics.ties, 0) AS ties,
                          IFNULL(statistics.loses, 0) AS loses
                        FROM users
                            LEFT JOIN statistics
                                ON statistics.user_id = users.user_id
                                AND statistics.region = :region
                                AND statistics.league_id = :league_id
                    WHERE users.user_id = :user_id
                """

        row = await SESSIONS.database.fetch_one(query=query,
                                                values=self.values)

        if row:
            return Response(data=PlayerModel(row).full)
        else:
            return Response(error="Invalid user")
Пример #16
0
    async def players(self):
        """ Pulls players """

        query = """SELECT IFNULL(statistics.elo, 0) AS elo,
                          IFNULL(statistics.kills, 0) AS kills,
                          IFNULL(statistics.deaths, 0) AS deaths,
                          IFNULL(statistics.assists, 0) AS assists,
                          IFNULL(statistics.shots, 0) AS shots,
                          IFNULL(statistics.hits, 0) AS hits,
                          IFNULL(statistics.damage, 0) AS damage,
                          IFNULL(statistics.headshots, 0) AS headshots,
                          IFNULL(statistics.roundswon, 0) AS roundswon,
                          IFNULL(statistics.roundslost, 0) AS roundslost,
                          IFNULL(statistics.wins, 0) AS wins,
                          IFNULL(statistics.ties, 0) AS ties,
                          IFNULL(statistics.losses, 0) AS losses,
                          users.steam_id, users.discord_id,
                          users.name,users.pfp,
                          users.user_id, users.joined
                    FROM users
                        INNER JOIN statistics
                                ON users.user_id = statistics.user_id
                    WHERE users.region = :region
                          AND users.league_id = :league_id
                    AND (users.user_id = :search OR users.steam_id = :search
                         OR users.discord_id = :search
                         OR users.name LIKE :search)
                    ORDER BY statistics.elo {}
                    LIMIT :limit, :offset""".format(self.order_by)

        rows_formatted = []
        rows_formatted_append = rows_formatted.append
        async for row in self.current_league.obj.database.iterate(
                query=query, values=self.values):
            rows_formatted_append(PlayerModel(row).full)

        return response(data=rows_formatted)
Пример #17
0
Файл: user.py Проект: ttibau/API
    async def create(self, steam_id,
                     ip=None, name=None,
                     discord_id=None, pfp=None):
        """ Creates user from given steam ID.

            pfp should be a link to a image.

            If name, discord_id or pfp not passed then info from
            steam API will be used instead.

            If IP isn't passed then alt detection isn't done.

            https://github.com/ModuleLIFT/API/blob/master/docs/modules.md#createself-steam_id-ipnone-namenone-discord_idnone-pfpnone
        """

        self.user_id = Misc.uuid4()

        validate = await self._validate_and_format(
            steam_id,
            ip,
            name,
            discord_id,
            pfp
        )

        if validate.error:
            return validate

        validate.data["user_id"] = self.user_id

        # Normally sql would handle this,
        # but this saves us from having to do a query
        # for the return.
        validate.data["joined"] = datetime.now()

        query = """INSERT INTO
                   users (
                       user_id,
                       steam_id,
                       discord_id,
                       name,
                       file_type,
                       joined,
                       ip
                   )
                   VALUES (
                       :user_id,
                       :steam_id,
                       :discord_id,
                       :name,
                       :file_type,
                       :joined,
                       :ip
                   )"""

        await SESSIONS.database.execute(query=query, values=validate.data)

        return Response(
            data=PlayerModel(validate.data).minimal,
            background=validate.background
        )
Пример #18
0
    def post(self):
        """ Class method: POST  


            Class method that will handle POST request for the CreateLobby Resource.
            Users that will hit the '/create-lobby' will use this method. 

            Attributes:
            Return:
                return a successful message that the Lobby has been created.
                return an error message if the lobby could not be made

        """
        playerName = current_identity.playerName
        player = PlayerModel.findByPlayerName(playerName)

        # Checks if the user creating the lobby isn't part of one already
        if (player.currentLobby == -1):

            try:
                newLobby = LobbyModel(player.playerName)
                newLobby.save_to_db()
            except:
                return {
                    'message':
                    'Could not create lobby. Error with creating lobby.'
                }

            try:
                home = LocationModel(player.playerName, 'home')
                home.save_to_db()
            except:
                return {
                    'message':
                    'Could not create lobby. Error with creating player home.'
                }

            try:
                player.currentLobby = newLobby.lobbyId
                player.homeId = home.id
                player.locationId = home.id
                player.save_to_db()
            except:
                return {
                    'message':
                    'Could not create lobby. Error with setting player details'
                }

            try:
                clerkName = ''.join(reversed(player.playerName))
                clerkSecretKey = ''.join(reversed(player.secretKey))

                storeClerk = PlayerModel(clerkName, clerkSecretKey, 'npc',
                                         'none', 'none', 100, 100)
                store = LocationModel(clerkName, 'store')
                store.save_to_db()

                storeClerk.homeId = store.id
                storeClerk.locationId = store.id
                storeClerk.currentLobby = player.currentLobby
                storeClerk.save_to_db()
            except:
                return {
                    'message':
                    'Could not create lobby. Error with creating clerk'
                }

            try:
                policeName = 'Chief Wiggum'
                policeSecretKey = 'ralph'

                gameCop = PlayerModel(policeName, policeSecretKey, 'npc',
                                      'none', 'gun', 100, 100)
                policeStation = LocationModel(clerkName, 'station')
                policeStation.save_to_db()

                gameCop.homeId = policeStation.id
                gameCop.locationId = policeStation.id
                gameCop.currentLobby = player.currentLobby
                gameCop.save_to_db()
            except:
                return {
                    'message':
                    'Could not create lobby. Error with creating cop'
                }

            return {'message': 'Lobby was created succesfully!'}

        return {'message': 'Lobby already exists!'}