Пример #1
0
def join_game():
    # post is considered registering for a game
    #
    # POST /join_game
    #     {"code":<gamecode>,"name":<yourname>,'session':<sessionid>,'secret':<sessionsecret>}
    try:
        try:
            post_data = request.get_json(force=True)
        except:
            return json_error("POST data was not json or malformed.")
            # check we have required keys
        required_keys = ['name', 'code', 'session', 'secret']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))
        try:
            result = santalogic.join_game(post_data['name'], post_data['code'],
                                          post_data['session'],
                                          post_data['secret'])
            if len(result) == 0:
                return json_error("Internal Error",
                                  "Join Error: No results from join function")
            return json_ok(result)
        except SantaErrors.PublicError as e:
            return json_error("{}".format(str(e)))
        except Exception as e:
            return json_error(
                "Internal error occurred",
                "Register Error: {}".format(exception_as_string(e)))
    except Exception as e:
        return json_error("Internal Error Has Occurred.",
                          "Internal Error: {}".format(exception_as_string(e)))
Пример #2
0
def list_owned_games():
    """
    API function for getting owned games list.
    """
    try:
        try:
            post_data = request.get_json(force=True)
        except:
            return json_error("POST data was not json or malformed.")
            # check we have required keys
        required_keys = ['session', 'secret']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))
        try:
            result = santalogic.list_owned_games(post_data['session'],
                                                 post_data['secret'])
            return json_ok(result)
        except SantaErrors.PublicError as e:
            return json_error("{}".format(str(e)))
        except Exception as e:
            return json_error(
                "Internal error occurred",
                "Register Error: {}".format(exception_as_string(e)))
    except Exception as e:
        return json_error("Internal Error Has Occurred.",
                          "Internal Error: {}".format(exception_as_string(e)))
Пример #3
0
def list_user():
    try:

        try:
            post_data = request.get_json(force=True)
        except:
            return json_error("POST data was not json or malformed.")
            # check we have required keys
        required_keys = ['code', 'session', 'secret']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))

        user_list = database.get_users_in_game(post_data['code'],
                                               post_data['session'],
                                               post_data['secret'])
        if len(user_list) == 0:
            return json_error("No results, or not group owner.")

        # convert to list
        flat_list = [user['name'] for user in user_list]
        return json_ok({'users': flat_list})

    except SantaErrors.PublicError as e:
        return json_error("Unable get users: {}".format(str(e)))
    except Exception as e:
        return json_error("Internal Error",
                          "List user error: {}".format(exception_as_string(e)))
Пример #4
0
def results():
    # get considered getting your results
    #
    # GET /user?code=<gamecode>&name=<name>
    #
    try:
        try:
            post_data = request.get_json(force=True)
        except:
            return json_error("POST data was not json or malformed.")
            # check we have required keys
        required_keys = ['code', 'session', 'secret']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))

        result = santalogic.get_game_results(post_data['code'],
                                             post_data['session'],
                                             post_data['secret'])
        return json_ok(result)
    except SantaErrors.PublicError as e:
        return json_error(str(e))
    except Exception as e:
        return json_error("Internal Error",
                          "Internal Error {}".format(exception_as_string(e)))
Пример #5
0
def game_sum():
    # post to update a game status.
    if request.method == 'POST':
        try:
            post_data = request.get_json(force=True)
        except:
            return json_error("invalid json data.")
        if len(post_data) == 0:
            return json_error("No Data sent in request")
        # not making a change just want to authenticate
        required_keys = ['code', 'session', 'secret']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))

        # get info:
        try:
            results = database.get_game_sum(post_data['code'],
                                            post_data['session'],
                                            post_data['secret'])
            if len(results) == 0:
                return json_error("Not found, or bad secret.")

            return json_ok(results[0])
        except SantaErrors.PublicError as e:
            return json_error("Failed to get game: {}".format(str(e)))
        except Exception as e:
            return json_error(
                "failed to get game",
                "Error getting game: {}".format(exception_as_string(e)))
def __run_game(code: str, sessionid: str, sessionpassword: str):
    # game has two parts, ideas, santas
    # each user is given another user to be santa of
    # each user is also given two unique ideas from the idea pool

    owner = database.get_authenticated_user(sessionid, sessionpassword)

    #all users
    all_users = database.get_users_in_game(code, sessionid, sessionpassword)
    if len(all_users) < 2:
        raise SantaErrors.GameChangeStateError(
            "game requires more than 2 users to run.")

    # get ideas
    all_ideas = database.get_game_ideas(code, sessionid, sessionpassword)
    if len(all_ideas) < len(all_users) * 2:
        raise SantaErrors.GameChangeStateError(
            "game requires at least 2 ideas per user")

    # assing users to santa's
    random.shuffle(all_users)
    try:
        last_user = all_users[-1]
        for user in all_users:
            database.set_user_santa(user['id'], last_user['id'], code,
                                    sessionid, sessionpassword)
            last_user = user
    except Exception as e:
        print("Gamerun: {gameid}, User update failure: {exception}".format(
            gameid=code, exception=exception_as_string(e)))
        raise SantaErrors.GameChangeStateError("Unable to assign santas.")

    random.shuffle(all_ideas)
    idea_chunks = list(__chunks(all_ideas, 2))
    try:
        for i in range(0, len(all_users)):
            for j in idea_chunks[i]:
                database.set_idea_user(j['id'], all_users[i]['id'], code,
                                       sessionid, sessionpassword)
    except Exception as e:
        print("Gamerun: {gameid}, Idea update failure: {exception}".format(
            gameid=code, exception=exception_as_string(e)))
        raise SantaErrors.GameChangeStateError("Unable to assign ideas")

    database.set_game_state(code, sessionid, sessionpassword, 1)

    print("Gamerun: {gameid}, Complete".format(gameid=code))
Пример #7
0
def verify_session():
    """
    API endpoint for verifying as session is a user.
    """
    try:
        try:
            post_data = request.get_json(force=True)
        except Exception as e:
            return json_error("Post Data malformed.")
        # check we have required keys
        required_keys = ['session', 'code', 'secret']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))

        # try verify
        try:
            trim_session = post_data['session'].strip()
            trim_code = post_data['code'].strip()

            result = santalogic.verify_session(trim_session, trim_code,
                                               post_data['secret'])
            if len(result) == 0:
                return json_error(
                    "Unable to Verify",
                    "Verify Error: Empty data from logic function call.")

            return json_ok(result)
        except SantaErrors.PublicError as e:
            return json_error("Unable to Verify: {}".format(str(e)))
        except Exception as e:
            return json_error("Internal Error",
                              internal_message="Verify Error: {}".format(
                                  exception_as_string(e)))
    except Exception as e:
        return json_error("Internal Error",
                          internal_message="Verify Error: {}".format(
                              exception_as_string(e)))
Пример #8
0
def new():
    try:
        try:
            post_data = request.get_json(force=True)
        except:
            return json_error("POST data was not json or malformed.")
        # check we have required keys
        required_keys = ['name', 'session', 'secret']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))
        if len(post_data['name']) > 0:
            try:
                # trim name
                trimed_name = post_data['name']
                game_sig = santalogic.create_game(trimed_name,
                                                  post_data['session'],
                                                  post_data['secret'])
                if len(game_sig) == 0:
                    return json_error("No game returned")
                else:
                    return json_ok(game_sig)
            except SantaErrors.PublicError as e:
                return json_error("Unable to create new group: {}".format(
                    str(e)))
            except Exception as e:
                return json_error(
                    "Unable to generate unique game, please try again.",
                    internal_message="New Failed: {}".format(
                        exception_as_string(e)))
        else:
            json_error("Game name must not be empty.")
    except SantaErrors.PublicError as e:
        return json_error("Unable to create new group: {}".format(str(e)))
    except Exception as e:
        return json_error("An Internal error occurred",
                          internal_message="Uncaught Exception: {}".format(
                              exception_as_string(e)))
Пример #9
0
def auth_register():
    """
    API endpoint for email sign-up
    """
    try:
        try:
            post_data = request.get_json(force=True)
        except Exception as e:
            return json_error("Post Data malformed.")
        # check we have required keys
        required_keys = ['email', 'name']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))

        # try registration
        try:
            trim_name = post_data['name'].strip()
            trim_email = post_data['email'].strip()

            result = santalogic.register_new_user(trim_email, trim_name)
            if len(result) == 0:
                return json_error(
                    "Unable to register.",
                    internal_message=
                    "Registration Failure: no results from function.")
            return json_ok(result)
        except SantaErrors.PublicError as e:
            return json_error("Unable to register {}".format(str(e)))
        except Exception as e:
            return json_error(
                "Unable to register, internal error.",
                "Registration Error: {}".format(exception_as_string(e)))
    except Exception as e:
        return json_error("Internal Error",
                          internal_message="Registration Error: {}".format(
                              exception_as_string(e)))
Пример #10
0
def game():
    # get for getting info about game
    if request.method == 'GET':
        try:
            game_result = santalogic.get_game(request.args.get('code'))
            # id is internal so we should remove it from a public response.
            if 'id' in game_result:
                del game_result['id']
            return json_ok(game_result)
        except Exception as e:
            return json_error(str(e))
    # post to update a game status.
    if request.method == 'POST':
        try:
            post_data = request.get_json(force=True)
        except:
            return json_error("invalid json data.")
        if len(post_data) == 0:
            return json_error("No Data sent in request")

        required_keys = ['code', 'session', 'secret', 'state']
        missing_keys = [x for x in required_keys if x not in post_data]
        if (len(missing_keys) > 0):
            return json_error(
                "A required Key is missing {}".format(missing_keys))

        try:
            santalogic.update_game_state(post_data['code'],
                                         post_data['session'],
                                         post_data['secret'],
                                         post_data['state'])
            return json_ok({})
        except SantaErrors.PublicError as e:
            return json_error(str(e))
        except SantaErrors.PrivateError as e:
            return json_error(
                "Internal Error",
                "Game State issue: {game} , {exception}".format(
                    exception=str(e), game=post_data['code']))
        except Exception as e:
            return json_error(
                "Internal Error", "Internal error on state change {}".format(
                    exception_as_string(e)))

    # we shouldn't get here, but return a message just incase we do
    return json_error("No sure what to do")
Пример #11
0
def init_db_tables():
    try:
        try:
            post_data = request.get_json(force=True)
        except Exception as e:
            return json_error("Post Data malformed.")
        if 'admin_key' in post_data:
            init_result = database.init_tables(post_data['admin_key'])
            return json_ok(init_result)
        else:
            return json_error("",
                              internal_message="Opportunistic init attempt")
    except Exception as e:
        return json_error("",
                          internal_message="Init Error: {}".format(
                              exception_as_string(e)))
    # due to the nature of the interface no error messages are currently returned.
    return json_error("Not Implemented")
Пример #12
0
def reset():
    # clear and create a new db set
    try:
        try:
            post_data = request.get_json(force=True)
        except Exception as e:
            return json_error("Post Data malformed.")
        if 'admin_key' in post_data:
            reset_result = database.reset_all_tables(post_data['admin_key'])
            return json_ok(reset_result)
        else:
            return json_error("",
                              internal_message="Opportunistic reset attempt")
    except Exception as e:
        return json_error("",
                          internal_message="Reset Error: {}".format(
                              exception_as_string(e)))
    # due to the nature of the interface no error messages are currently returned.
    return json_error("Not Implemented")
Пример #13
0
def idea():
    if request.method == 'POST':
        # this is to add new ideas/suggestions to the group.
        try:
            try:
                post_data = request.get_json(force=True)
            except:
                return json_error("POST data was not json or malformed.")
                # check we have required keys
            required_keys = ['idea', 'code', 'session', 'secret']
            missing_keys = [x for x in required_keys if x not in post_data]
            if (len(missing_keys) > 0):
                return json_error(
                    "A required Key is missing {}".format(missing_keys))
            try:
                idea_results = santalogic.add_idea(post_data['code'],
                                                   post_data['idea'],
                                                   post_data['session'],
                                                   post_data['secret'])
                return json_ok(idea_results)
            except FileNotFoundError as e:
                return json_error(str(e))
            except Exception as e:
                return json_error(
                    "Error adding idea",
                    "Idea Error: {}".format(exception_as_string(e)))

        except:
            return json_error(
                "Internal Error.",
                "Idea POST error: {}".format(exception_as_string(e)))
    if request.method == 'GET':
        # this is to retrive the left over list.
        # not sure that it makes sense to restrict this to creators.
        get_code = request.args.get('code')
        try:
            game_result = santalogic.get_game(get_code)
        except Exception as e:
            return json_error(str(e))

        # test if group is "rolled"
        if game_result['state'] == 1:
            try:
                idea_results = database.get_idea(
                    {
                        'game': game_result['id'],
                        'userid': -1,
                    },
                    properties=['idea'])

                if len(idea_results) == 0:
                    return json_ok({'ideas': ['All ideas were used!']})

                return json_ok({'ideas': [x['idea'] for x in idea_results]})
            except Exception as e:
                return json_error("Error getting ideas.",
                                  "Error getting ideas: {}".format(str(e)))

        # state is not 1
        else:
            return json_error("Group has not been rolled yet, nothing to get.")
    return json_error("Not sure what to do.")