示例#1
0
    def games_history(self, request):
        """
        JWT required. Retrieves user's completed games starting from the provided offset, or 0. Limit 10
        """
        offset = request.offset
        payload = token.decode_jwt(request.jwt_token)

        try:
            user_key = Key(urlsafe=payload.get('user_key'))
        except TypeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to retrieve user\'s games')

        try:
            games = Game.query(
                AND(
                    OR(Game.player_one == user_key,
                       Game.player_two == user_key), Game.game_completed ==
                    True)).order(-Game.date_created).fetch(offset=offset,
                                                           limit=10)
            return UserGamesHistoryResponseForm(games=[
                GamesHistory(player_one=game.player_one_name,
                             player_two=game.player_two_name,
                             game_key=game.key.urlsafe()) for game in games
            ])
        except Exception as e:
            raise endpoints.InternalServerErrorException(
                'An error occurred while retrieving completed games')
示例#2
0
    def retrieve_game(self, request):
        """
        JWT required. Retrieves the game matching the provided key, and returns the game details
        """
        game_key = request.game_key
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
            game = Key(urlsafe=game_key).get()
        except TypeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException(
                'An error occrurred while retrieving game details')

        if game is None:
            raise endpoints.BadRequestException('That game does not exist')

        # k the game exists let's make sure it's the user's game
        if game.player_one != user and game.player_two != user:
            raise endpoints.UnauthorizedException(
                'You are not authorized to view other players games')

        return ViewGameResponseForm(game_key=game_key, game=game.to_form())
示例#3
0
    def retrieve_invite(self, request):
        """
        JWT required. Retrieve the next 10 invites associated with the user starting from the provided offset, or 0
        """
        offset = request.offset
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
        except TypeError:
            raise endpoints.BadRequestException('key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException('key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException('An error occurred when attempting to take the turn')

        # user is here let's get their invites
        invites = Invite.query(Invite.to_player == user,
                               Invite.rejected == False,
                               Invite.accepted == False).fetch(limit=10, offset=offset)
        return RetrieveInviteResponseForm(
            invites=[InviteForm(
                inviter=invite.from_player.urlsafe(),
                inviter_name=invite.from_player_name
            ) for invite in invites]
        )
示例#4
0
    def cancel_game(self, request):
        """
        JWT required. This will cancel the game associated with the provided game key.
        """
        game_key = request.game_key
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key')).get()
            game = Key(urlsafe=game_key).get()
        except TypeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to take the turn')

        if user is None or game is None:
            raise endpoints.BadRequestException(
                'Could not locate the user and game specified')

        try:
            if game.player_one != user.key and game.player_two != user.key:
                # this isn't even the user's game!
                raise endpoints.UnauthorizedException(
                    'Can not cancel someone else\'s game')

            if game.player_one_completed is True and game.player_two_completed is True:
                raise endpoints.BadRequestException(
                    'Can not cancel a game that has already been completed')

            if game.player_one_cancelled is True or game.player_two_cancelled is True:
                raise endpoints.BadRequestException(
                    'Game has been cancelled already')

            # game has not been completed / cancelled already
            if game.player_one == user.key:
                game.player_one_cancelled = True
                game.player_two_completed = True
                player_two = game.player_two.get()
                player_two.wins += 1
                game.put()
                player_two.put()
            elif game.player_two == user.key:
                game.player_two_cancelled = True
                game.player_one_completed = True
                player_one = game.player_one.get()
                player_one.wins += 1
                game.put()
                player_one.put()

            return message_types.VoidMessage()

        except Exception as e:
            # print e.message
            raise endpoints.InternalServerErrorException(
                'An error occurred while trying to cancel the game')
示例#5
0
 def wrapper(self):
     if self.request.body is None or self.request.body is '':
         return self.response.set_status(
             400, 'Please include the token with the request')
     try:
         data = json.loads(self.request.body)
     except ValueError:
         return self.response.set_status(
             500, 'An error occurred while processing your request. '
             'Check your request body and try again')
     except:
         return self.error(500)
     jwt_token = data.get('jwt_token')
     payload = token.decode_jwt(jwt_token)
     if payload is '' or payload is None:
         return self.error(401)
     func(self, payload)
示例#6
0
    def roll_history(self, request):
        """
        JWT required. Retrieves user's roll history for the provided game
        """
        game_key = request.game_key
        payload = token.decode_jwt(request.jwt_token)

        try:
            game = Key(urlsafe=game_key)
            user = Key(urlsafe=payload.get('user_key'))
        except TypeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException(
                'An error occurred when retrieving roll history')

        turncard = TurnCard.query(TurnCard.owner == user,
                                  TurnCard.game == game).get()
        if turncard is None:
            raise endpoints.BadRequestException(
                'There are no turns associated with that turncard')
        turns = []
        for turn in turncard.turns:
            turn = turn.get()
            turns.append({
                "roll_one": turn.roll_one,
                "roll_two": turn.roll_two,
                "roll_three": turn.roll_three,
                "allocated_to": turn.allocated_to,
                "date_completed": turn.date_completed.isoformat()
            })

        return UserRollHistoryResponseForm(rolls=[
            UserRollHistory(roll_one=turn['roll_one'],
                            roll_two=turn['roll_two'],
                            roll_three=turn['roll_three'],
                            allocated_to=turn['allocated_to'],
                            date_completed=turn['date_completed'])
            for turn in turns
        ])
示例#7
0
    def cancel_invite(self, request):
        """
        JWT required. Cancel the invite associated with the user
        """
        target_user = request.target_user
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
        except TypeError:
            raise endpoints.BadRequestException('key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException('key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException('An error occurred when attempting to take the turn')

        if target_user is None or target_user is '':
            raise endpoints.BadRequestException('The target user was not provided')

        invite = Invite.query(Invite.from_player == user,
                               Invite.rejected == False,
                               Invite.accepted == False).get()

        if invite is None:
            invite = Invite.query(Invite.to_player == user,
                                  Invite.rejected == False,
                                  Invite.accepted == False).get()

        if invite is None:
            raise endpoints.BadRequestException('No pending invites exist for these users')

        # let's cancel the invite
        try:
            invite.rejected = True
            invite.put()
            return message_types.VoidMessage()
        except:
            raise endpoints.InternalServerErrorException('An error occurred while attempting to cancel the invite')
示例#8
0
    def create_invite(self, request):
        """
        JWT required. Provided the user does not have an active game with the provided player two, creates
        an invite for player two. If player two has already invited the user to play a game, accepts the
        invite and creates a game for them.

        If a game is created, the user will be able to retrieve it from game endpoint and begin playing.
        """
        player_two_key = request.player_two_key
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key')).get()
            # grab player two please
            player_two = Key(urlsafe=player_two_key).get()
        except TypeError:
            raise endpoints.BadRequestException('key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException('key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException('An error occurred when attempting to take the turn')

        if player_two is None:
            raise endpoints.BadRequestException('Player does not exist')

        # awesome we have player one and two
        game = Game.query(
            Game.player_one == user.key,
            Game.player_two == player_two.key,
            Game.player_one_completed == False,
            Game.player_two_completed == False).get()

        if game is None:
            game = Game.query(Game.player_one == player_two.key,
                              Game.player_two == user.key,
                              Game.player_one_completed == False,
                              Game.player_two_completed == False).get()

        # if a game exists between these users, they need to finish it first please
        if game is not None:
            # not entirely certain what to set here, as the request wasn't necessarily wrong, but the
            # user already has a game with player_two
            raise endpoints.BadRequestException("An existing game must be finished before starting another one")

        # let's check for an existing invite between these players
        invite = Invite.query(
            Invite.from_player == user.key,
            Invite.to_player == player_two.key,
            Invite.accepted == False,
            Invite.rejected == False
        ).get()

        if invite is not None:
            raise endpoints.BadRequestException(
                "A pending invite must be accepted or declined before creating another one")

        invite = Invite.query(
            Invite.from_player == player_two.key,
            Invite.to_player == user.key,
            Invite.accepted == False,
            Invite.rejected == False
        ).get()

        if invite is not None:
            # awesome! the inviter already has an invitation from the invitee.
            # start a game, and create the turncards for each player
            try:
                game = Game(
                    player_one=player_two.key,
                    player_one_name=player_two.username,
                    player_two=user.key,
                    player_two_name=user.username
                )
                game.put()
                player_one_turncard = TurnCard(
                    owner=player_two.key,
                    game=game.key
                )
                player_two_turncard = TurnCard(
                    owner=user.key,
                    game=game.key
                )
                player_one_turncard.put()
                player_two_turncard.put()

                return CreateInviteResponseForm(
                    game_key=game.key.urlsafe(),
                    game=game.to_form()
                )

            except Exception as e:
                # print e.message
                raise endpoints.InternalServerErrorException('An error occurred while attempting to create a game')

        # alright there are no invites between these players yet so let's make one
        try:
            invite = Invite(
                from_player=user.key,
                from_player_name=user.username,
                to_player=player_two.key,
                to_player_name=player_two.username
            )
            invite.put()
            return CreateInviteResponseForm()
        except:
            raise endpoints.InternalServerErrorException('An error occurred while attempting to create an invite')
示例#9
0
    def take_turn(self, request):
        """
        JWT required. Given game key and turn key, will locate the turn card for the user, and initiate a turn if there are < 13
        turns. If the most recent turn contains empty rolls, this will expect a dice argument indicating which dice
        to reroll. If a dice argument is not given, rerolls all dice.
        """
        turn_key = request.turn_key
        dice_to_roll = request.dice_to_roll
        payload = token.decode_jwt(request.jwt_token)
        game_key = request.game_key

        try:
            user = Key(urlsafe=payload.get('user_key'))
            game = Key(urlsafe=game_key)
        except TypeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except Exception as e:
            # print e.message
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to take the turn')

        # get the turncard first, make sure it belongs to this user, then take the turn if possible else return
        # an error
        turncard = TurnCard.query(TurnCard.owner == user,
                                  TurnCard.game == game).get()
        if turncard is None:
            raise endpoints.BadRequestException(
                'No turns associated with this game and user')

        if turncard.owner != user:
            raise endpoints.UnauthorizedException(
                'User is not associated with this game')

        total_turns = len(turncard.turns)
        if total_turns == 0:
            raise endpoints.BadRequestException(
                'You need to start a new turn before you can roll')

        # the user owns this card, and there are still turns left. Let's take one
        current_turn = turncard.turns[total_turns - 1].get()

        if total_turns == 13:
            # check if the move has been allocated already
            if current_turn.allocated_to is not None:
                raise endpoints.BadRequestException('The game is already over')

            # check to make sure last turn is complete
            if len(current_turn.roll_three) != 0:
                raise endpoints.BadRequestException(
                    'You need to complete this turn to finish the game')

        # check if the current turn is completed, if it is, return error
        if current_turn.allocated_to is not None:
            raise endpoints.BadRequestException(
                'This turn has already been completed')

        # the turn hasn't been completed, so, make sure the dice to roll are in the previous roll, and then
        # roll the dice and assign them to the current roll
        roll_results = []
        turn_roll_count = 2

        if len(current_turn.roll_three) != 0:
            # turn needs to be completed
            raise endpoints.BadRequestException(
                "You need to complete this turn")
        elif len(current_turn.roll_two) == 0:
            try:
                roll_results = roll_dice(current_turn.roll_one, dice_to_roll)
                current_turn.roll_two = roll_results
            except ValueError:
                raise endpoints.BadRequestException(
                    'Dice do not match previous roll')
            except:
                raise endpoints.InternalServerErrorException(
                    'Error occurred while rolling')
        else:
            try:
                roll_results = roll_dice(current_turn.roll_two, dice_to_roll)
                current_turn.roll_three = roll_results
                turn_roll_count = 3
            except ValueError:
                raise endpoints.BadRequestException(
                    'Dice do not match previous roll')
            except:
                raise endpoints.InternalServerErrorException(
                    'Error occurred while rolling')
        try:
            turncard.turns[total_turns - 1] = current_turn.key
            turncard.put()

            return TakeTurnResponseForm(game_key=game_key,
                                        turn_key=turn_key,
                                        roll_results=roll_results,
                                        turn_roll_count=turn_roll_count)

        except Exception as e:
            # print e.message
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to take the turn')
示例#10
0
    def complete_turn(self, request):
        """
        JWT required. This will complete the provided turn. Expects to get the string representation of the
        cell to score e.g. "twos, sm_straight, full_house, etc..."
        """
        game_key = request.game_key
        allocate_to = request.allocate_to
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
            game = Key(urlsafe=game_key)
        except TypeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to complete the turn')

        turncard = TurnCard.query(TurnCard.owner == user,
                                  TurnCard.game == game).get()
        if turncard is None:
            raise endpoints.BadRequestException(
                'Turn does not exist for the provided game')

        if turncard.owner != user:
            raise endpoints.UnauthorizedException(
                'User is not associated with the provided game')

        total_turns = len(turncard.turns)
        if total_turns < 1:
            raise endpoints.BadRequestException(
                'You should begin a turn before trying to complete one')
        # doesn't matter what turn this is, as long as it exists, and it hasn't been allocated, we can try to
        # allocate it to the game
        current_turn = turncard.turns[total_turns - 1].get()

        if current_turn.allocated_to is not None:
            raise endpoints.BadRequestException(
                'This turn has already been completed')

        try:
            game = game.get()
            if game is None:
                raise endpoints.BadRequestException('This game does not exist')

            # game exists, so let's try to allocate this
            if game.player_one == user:
                score_player_one(allocate_to, game, current_turn)
            elif game.player_two == user:
                score_player_two(allocate_to, game, current_turn)
                game.player_two_last_turn_date = datetime.now()
            else:
                raise endpoints.BadRequestException(
                    'The user provided is not associated with this game')

            if total_turns == 13:
                # game is finished!
                complete_game(game, user)

            game.put()
            current_turn.put()
            return message_types.VoidMessage()

        except exceptions.AlreadyAssignedError as e:
            raise endpoints.BadRequestException(e.message)
        except Exception as e:
            # print e.message
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to complete the turn')
示例#11
0
    def new_turn(self, request):
        """
        JWT required. Creates a new turn and rolls the dice for the first time.
        """
        game_key = request.game_key
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
            game = Key(urlsafe=game_key)
        except TypeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except Exception as e:
            # print e.message
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to create the turn')

        # we have the user and turncard just verify this is their turncard, verify the latest turn is complete, and
        # then create this new turn and add it to turncard.turns array
        turncard = TurnCard.query(TurnCard.owner == user,
                                  TurnCard.game == game).get()
        if turncard is None:
            raise endpoints.BadRequestException(
                'No turns associated with this game and user')

        if turncard.owner != user:
            raise endpoints.UnauthorizedException(
                'User is not associated with this game')

        total_turns = len(turncard.turns)

        if total_turns != 0:
            current_turn = turncard.turns[total_turns - 1].get()
            if total_turns == 13:
                # check if the move has been allocated already
                if current_turn.allocated_to is not None:
                    raise endpoints.BadRequestException(
                        'The game is already over')

                # check to make sure last turn is complete
                if len(current_turn.roll_three) != 0:
                    raise endpoints.BadRequestException(
                        'You need to complete this turn to finish the game')

            if current_turn.allocated_to is None:
                raise endpoints.BadRequestException(
                    'You need to finish this turn before starting a new one')
        try:
            roll_results = roll_dice([0, 0, 0, 0, 0], [0, 0, 0, 0, 0])
            new_turn = Turn(roll_one=roll_results, roll_two=[], roll_three=[])
            new_turn.put()
            turncard.turns += [new_turn.key]
            turncard.put()

            return NewTurnResponseForm(game_key=game_key,
                                       turn_key=new_turn.key.urlsafe(),
                                       roll_results=roll_results,
                                       turn_roll_count=1)
        except Exception as e:
            # print e.message
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to create the turn')