示例#1
0
def login():
    email = request.form.get("email", None)
    password = request.form.get("password", None)

    if None in (email, password):
        return api_error("E-mail or password is missing, check your data", 1), 400 # TODO: define a error code list

    login_req = LoginRequest(email=email, password=password)

    try:
        response = userservice.authenticate(login_req, timeout=3000) # timeout after 3 seconds

        #handle response.userId
        if isinstance(response, LoginResponse):
            return jsonify({"token": token_signer.dumps(response.userId)})
        if isinstance(response, RpcError):
            errors = {
                1: {"message": "Internal service error", "code": "000"},
                5: {"message": "Wrong email or password", "code": "010"},
            }

            return api_error(**errors.get(response.error_code, {"message": "Error code not defined"})), 400
        #return api_error("Wrong password", 501)
    except TimeoutError as e:
        return api_error("Service not available", 500) # ???
示例#2
0
def get_lobby(id):
    try:
        response = lobbyservice.get_lobby(GetLobbyStateRequest(lobbyId=id), timeout=5000)
        if isinstance(response, RpcError) and response.error_code == 2:
            return api_error("Lobby does not exists", 226), 404
        if not isinstance(response, GetLobbyStateResponse): # maybe RpcError
            return api_error("Internal service error", 400), 400

        lobby = response.lobby

        if not g.user.id in map(lambda m: m.user.id, lobby.lobbymembers):
            return api_error("You are not permitted to that lobby", 42), 400

        return jsonify(
            lobby={
                "l_id": lobby.lobbyId,
                "size": lobby.gameType,
                "owner": True if g.user.id == lobby.owner.id else False,
                "invited_count": len(lobby.lobbymembers),
                "accepted_count": len(filter(lambda p: p.status == "member", lobby.lobbymembers)),
                "players": [
                    {"u_id": player.user.id, "u_mail": player.user.email, "status": "accepted" if player.status == "member" else "waiting"}
                    for player in list(lobby.lobbymembers)
                ]
            }
        )
    except TimeoutError as e:
        return api_error("Service is not available", 500), 500
示例#3
0
def game_details(game_id):
    msg = GameInfoRequest(gameId=game_id)

    try:
        rep = gameservice.send(msg, timeout=5000)
        if isinstance(rep, GameError):
            return api_error(rep.description, rep.code), 400
        else:
            # dict, user_id => user
            users_response = userservice.get_multiple_users(GetMultipleUsersRequest(userIds=map(lambda p: p.userId, list(rep.game.players))), timeout=5000)
            user_dict = {user.id: user for user in users_response.users}

            return jsonify({ "gameId" : rep.game.gameId,
                             "players" : [ { "userId" : player.userId,
                                             "email": user_dict.get(player.userId).email,
                                            "state" : player.state,
                                            "x" : player.x,
                                            "y" : player.y,
                                            "score": player.score,
                                            #"question" : player.question,
                                            #"alternatives" : [a for a in player.alternatives],
                                            "answeredCorrectly" : player.answeredCorrectly } for player in rep.game.players ],
                             "board" : [ b for b in rep.game.board ]
                          })
    except TimeoutError as e:
        return api_error("Game service not available", 500)
示例#4
0
def lobby_invitation(lobby_id):
    try:
        if not request.json:
            return api_error("Required JSON body is missing or bad type, check your content-type")

        raw_user_ids = request.json.get("invite")
        if not raw_user_ids or not isinstance(raw_user_ids, list):
            return api_error("Required JSON body is missing or bad type", 004), 400
        user_ids = map(lambda x: int(x), raw_user_ids) # better method?


        response = lobbyservice.invite_to_lobby(
            InviteLobbyRequest(userId=g.user.id, lobbyId=lobby_id, invites=user_ids),
            timeout=5000
        )

        # TODO: return RpcError in the service
        #if isinstance(response, RpcError):
        #    pass

        if not isinstance(response, InviteLobbyResponse):
            return api_error("Internal service error")
        if response.friends_invited:
            return "OK"
        return "UNKNOWN INVITATION ERROR", 400

    except TimeoutError as e:
        return api_error("Service not available", 500), 500
    except ValueError as e:
        return  api_error("JSON object invite should be an array with only integers", 004), 400
示例#5
0
def create_lobby():
    try:
        game_size = request.form.get("size", type=int)
        if not game_size:
            return api_error("Missing required parameter size", 004), 400

        response = lobbyservice.create_lobby(CreateLobbyRequest(userId=g.user.id, gameType=game_size), timeout=5000)
        if not isinstance(response, CreateLobbyResponse): # maybe RpcError
            return api_error("Internal service error", 400), 400

        lobby_response = lobbyservice.get_lobby(GetLobbyStateRequest(lobbyId=response.lobbyId), timeout=5000)
        if not isinstance(lobby_response, GetLobbyStateResponse): # maybe RpcError
            return api_error("Internal service error", 400), 400

        lobby = lobby_response.lobby
        return jsonify(
            lobby={
                "l_id": lobby.lobbyId,
                "size": lobby.gameType,
                "owner": True if g.user.id == lobby.owner.id else False,
                "players": [
                    {"u_id": player.user.id, "u_mail": player.user.email, "status": "accepted" if player.status == "member" else "waiting"}
                    for player in list(lobby.lobbymembers)
                ]
            }
        )
    except TimeoutError as e:
        return api_error("Service is not available", 500), 500
    except Exception as e:
        return api_error("Internal server error", 500), 500
示例#6
0
def end_lobby(lobby_id):
    try:
        response = lobbyservice.remove_lobby(RemoveLobbyRequest(userId=g.user.id, lobbyId=lobby_id), timeout=5000)

        # TODO: add RpcError check!
        if isinstance(response, RemoveLobbyResponse):
            if response.lobby_removed: return "OK"
        return api_error("You are not permitted to that lobby", 42), 400 # assume until usage of RpcError
    except TimeoutError as e:
        return api_error("Service is not available", 500, 500)
示例#7
0
def delete_friend(friend_id):
    try:
        response = friendservice.remove_friend(RemoveFriendRequest(userId=g.user.id, friendId=friend_id), timeout=5000)
        if not isinstance(response, RemoveFriendResponse):
            return api_error("Internal service error", 500), 500 # probably return RpcError
        return "OK" if response.friend_removed else (api_error("No such user exists", "011"), 200)
    except Exception as e:
        print "DELETE_FRIEND-ERROR:", e
        traceback.print_exc()
        return api_error("Service not available", 500), 500
示例#8
0
def start_lobby(lobby_id):
    try:
        response = lobbyservice.start_game(StartGameRequest(userId=g.user.id, lobbyId=lobby_id), timeout=5000)

        if isinstance(response, RpcError):
            if response.error_code == 2:
                return api_error("There exists no such lobby", 226), 404
            return api_error("You are not permitted to that lobby", 42), 400
        return "OK"
    except TimeoutError as e:
        return api_error("Service is not available", 500), 500
示例#9
0
def deny_invite(lobby_id):
    try:
        response = lobbyservice.answer_lobby_invite(
            AnswerLobbyInviteRequest(userId=g.user.id, lobbyId=lobby_id, answer="deny")
        )
        if isinstance(response, RpcError):
            errors = {
                2: ({"message": "There exists no such lobby", "code": 226}, 404),
                30: ({"message": "You are not permitted to that lobby", "code": 227}, 400),
                31: ({"message": "The lobby is full", "code": 225}, 400),
            }
            error, status_code = errors.get(response.error_code)
            return api_error(**error), status_code
        return "OK" # TODO: fix real implementation according to spec when it's commented how it should be
    except TimeoutError as e:
        return api_error("Service not available", 500), 500
示例#10
0
def question(game_id):
    try:
        req = QuestionRequest(
            gameId=game_id,
            userId=g.user.id
        )

        rep = gameservice.send(req)
        if isinstance(rep, GameError):
            return api_error(rep.description, rep.code)
        else:
            return jsonify({ "question" : rep.question, "alternatives" : [a for a in rep.alternatives] })
    except TimeoutError as e:
        return api_error("Game service not available", 500)
    except Exception as e:
        traceback.print_exc(sys.stdout)
        return api_error("Service not available", 500), 500
示例#11
0
def list_games():
    # state, id, game size,
    try:
        response = gameservice.send(GameListRequest(userId=g.user.id), timeout=5000)
        if isinstance(response, GameError):
            return api_error(response.description, response.code), 400
        return jsonify(
            games=[{
                    "id": game.gameId,
                    "size": len(game.players),
                    "state": next((player.state for player in game.players if player.userId == g.user.id), 0)
                   }
                   for game in list(response.games)
            ])

    except TimeoutError as e:
        return api_error("Service is not available", 500), 500
示例#12
0
def add_friend():
    try:
        email = request.form.get("friend")
        if not email:
            # or a error message that tells that the email is missing?
            return api_error("Missing required friend parameter", 004), 400

        response = friendservice.add_friend(AddFriendRequest(userId=g.user.id,friend_email=email), timeout=5000)
        if isinstance(response, AddFriendResponse):
            if response.friend_added:
                return "OK"
            return api_error("No such user exists"), 400
        else:
            return api_error("Internal service error", 000), 400

    except Exception as e:
        print "add_friend", e
        traceback.print_exc()
        return api_error("Service not available", 500), 500
示例#13
0
def answer(game_id):
    try:
        answer = request.form.get("answer", type=int)
        if not answer:
            return api_error("Missing required parameter answer", 400), 400

        req = AnswerRequest(
            gameId=game_id,
            userId=g.user.id,
            answer=answer
        )

        rep = gameservice.send(req)
        if isinstance(rep, GameError):
            return api_error(rep.description, rep.code)
        else:
            return jsonify({ "isCorrect" : rep.isCorrect })
    except TimeoutError as e:
        return api_error("Game service not available", 500)
    except Exception as e:
        return api_error("Service not available", 500), 500
示例#14
0
def create_user():
    email = request.form.get("email")
    password = request.form.get("password")

    if not (password or email):
        return api_error("Missing email or password", 102), 400

    try:
        response = userservice.create_user(RegistrationRequest(email=email, password=password), timeout=5000) # timeout after 5 sec

        if isinstance(response, RegistrationResponse):
            return str(response.userId)
        elif isinstance(response, RpcError):
            errors = {
                1: {"message": "Internal service error", "code": "000"},
                11: {"message": "This mail is already taken", "code": "101"},
            }

            return api_error(**errors.get(response.error_code, {"message": "Error code not defined"})), 400
    except TimeoutError as e:
        return api_error("Service not available", 500)
示例#15
0
def get_friends():
    try:
        response = friendservice.get_friends(GetFriendsRequest(userId=g.user.id), timeout=5000)

        return jsonify({"friends": map(
            lambda user: dict(id=user.id, email=user.email),
            response.friends
        )})
    except Exception as e:
        print "friends:", e
        traceback.print_exc()
        return api_error("Service not available", 500), 500
示例#16
0
def lobby_invitation(lobby_id):
    try:
        if not request.json:
            return api_error("Required JSON body is missing or bad type, check your content-type")

        raw_user_ids = request.json.get("invite")
        if not raw_user_ids or not isinstance(raw_user_ids, list):
            return api_error("Required JSON body is missing or bad type", 004), 400
        user_ids = map(lambda x: int(x), raw_user_ids) # better method?


        response = lobbyservice.invite_to_lobby(
            InviteLobbyRequest(userId=g.user.id, lobbyId=lobby_id, invites=user_ids),
            timeout=5000
        )

        if isinstance(response, RpcError):
            errors = {
                2: ({"message": "There exists no such lobby", "code": 226}, 404),
                30: ({"message": "You are not permitted to that lobby", "code": 42}, 400),
                #31: ({"message": "The lobby is full", "code": 225}, 400),
            }
            error, status_code = errors.get(response.error_code)
            return api_error(**error), status_code

        if not isinstance(response, InviteLobbyResponse):
            return api_error("Internal service error")
        if response.friends_invited:
            return "OK"
        return "UNKNOWN INVITATION ERROR", 400

    except TimeoutError as e:
        return api_error("Service not available", 500), 500
    except ValueError as e:
        return  api_error("JSON object invite should be an array with only integers", 004), 400
示例#17
0
def player_move(game_id):

    if None in ([request.form.get("x"), request.form.get("y")]):
        return api_error("Some of the required parameters x and y are missing", 004), 400

    try:
        req = MoveRequest(
            x=request.form.get("x", None, type=int),
            y=request.form.get("y", None, type=int),
            gameId=game_id,
            userId=g.user.id
        )

        rep = gameservice.send(req, timeout=5000)
        if isinstance(rep, GameError):
            return api_error(rep.description, rep.code)
        else:
            return "" # assuming this returns 200 OK
    except TimeoutError as e:
        return api_error("Game service not available", 500), 500
    except Exception as e:
        return api_error("Service not available", 500), 500
示例#18
0
def get_lobbies():
    try:
        response = lobbyservice.get_lobbies(GetLobbyListRequest(userId=g.user.id), timeout=5000)

        lobbies_objects = [
            {
                "l_id": lobby.lobbyId,
                "owner": True if g.user.id == lobby.owner.id else False,
                "size": lobby.gameType,
                "invited_count": len(lobby.lobbymembers),
                "accepted_count": len(filter(lambda p: p.status == "member", lobby.lobbymembers))
            }
            for lobby in response.lobbies
        ]
        return jsonify(
            lobbies=lobbies_objects
        )
    except TimeoutError as e:
        return api_error("Service is not available", 500), 500
    except Exception as e:
        print "webapi#get_lobbies", e
        return api_error("Internal server error", 500), 500