Beispiel #1
0
def update_user(
    user_id=undefined,
    lat=undefined,
    lng=undefined,
    #country = undefined,
    #region = undefined,
    #city = undefined,
    timezone=undefined,
    language=undefined,
    friends=[],
    groups=[],
    additional_public_data=undefined,
):

    User.set_infos(
        user_id=user_id,
        lat=lat,
        lng=lng,
        timezone=timezone,
        #country = country,
        #region = region,
        #city = city,
        language=language,
        groups=groups,
        friends=friends,
        additional_public_data=additional_public_data)

    return User.get_user(user_id)
Beispiel #2
0
def increase_multi_values(request):
    try:
        doc = request.json_body
    except:
        raise APIError(400, "invalid_json", "no valid json body")
    ret = {}
    for user_id, values in doc.items():
        user = User.get_user(user_id)
        if not user:
            raise APIError(404, "user_not_found",
                           "user %s not found" % (user_id, ))

        for variable_name, values_and_keys in values.items():
            for value_and_key in values_and_keys:
                variable = Variable.get_variable_by_name(variable_name)

                if asbool(get_settings().get("enable_user_authentication",
                                             False)):
                    if not Variable.may_increase(variable, request, user_id):
                        raise APIError(
                            403, "forbidden",
                            "You may not increase the variable %s for user %s."
                            % (variable_name, user_id))

                if not variable:
                    raise APIError(404, "variable_not_found",
                                   "variable %s not found" % (variable_name, ))

                if not 'value' in value_and_key:
                    raise APIError(400, "variable_not_found",
                                   "illegal value for %s" % (variable_name, ))

                value = value_and_key['value']
                key = value_and_key.get('key', '')

                Value.increase_value(variable_name, user, value, key)

        output = _get_progress(achievements_for_user=user,
                               requesting_user=request.user)
        output = copy.deepcopy(output)
        to_delete = list()
        for i in range(len(output["achievements"])):
            if len(output["achievements"][i]["new_levels"]) > 0:
                if "levels" in output["achievements"][i]:
                    del output["achievements"][i]["levels"]
                if "priority" in output["achievements"][i]:
                    del output["achievements"][i]["priority"]
                if "goals" in output["achievements"][i]:
                    del output["achievements"][i]["goals"]
            else:
                to_delete.append(i)

        for i in sorted(to_delete, reverse=True):
            del output["achievements"][i]

        if len(output["achievements"]) > 0:
            ret[user_id] = output

    return ret
Beispiel #3
0
def create_user(
        user_id = undefined,
        lat = undefined,
        lng = undefined,
        country = undefined,
        region = undefined,
        city = undefined,
        timezone = undefined,
        language = undefined,
        friends = [],
        groups = [],
        additional_public_data = undefined,
        gen_data = default_gen_data
    ):
    if additional_public_data is undefined:
        additional_public_data = {
            'first_name' : 'Stefan',
            'last_name' : 'Rogers'
        }

    if user_id is undefined:
        user_id = (DBSession.execute("SELECT max(id) as c FROM users").scalar() or 0) + 1
    if lat is undefined:
        lat = randrange_float(gen_data["area"]["min_lat"],gen_data["area"]["max_lat"])

    if lng is undefined:
        lng = randrange_float(gen_data["area"]["min_lng"], gen_data["area"]["max_lng"])

    if country is undefined:
        country = gen_data["country"]

    if timezone is undefined:
        timezone = gen_data["timezone"]

    if region is undefined:
        region = gen_data["region"]

    if city is undefined:
        city = gen_data["city"]

    if language is undefined:
        language = gen_data["language"]

    User.set_infos(
        user_id = user_id,
        lat = lat,
        lng = lng,
        timezone = timezone,
        country = country,
        region = region,
        city = city,
        language = language,
        groups = groups,
        friends = friends,
        additional_public_data = additional_public_data
    )

    return User.get_user(user_id)
Beispiel #4
0
def progress_user(request):
    dir_name = os.path.dirname(
        os.path.abspath(__file__)) + "\\csv_uploads\\file.csv"
    params = request.GET
    with open(dir_name) as f:
        keys = f.readline().rstrip().split(";")
    achievements = Achievement.get_all_achievements()
    if request.method == 'POST':
        achievement_id = request.POST['achievement_id']
        user_id = request.POST['user_id']
        sort_by = request.POST['sort_by']
        user_id_value = request.POST['user_id_value']
        res_id_user = User.get_by_id(user_id, user_id_value)
        leaderboard = Achievement.get_leaderbord_by_user(
            achievement_id, res_id_user, sort_by)
        user = leaderboard['leaderboard'][leaderboard['user_position']]
        user_object = User.get_user(res_id_user)
        prog = Achievement.evaluate(user_object,
                                    achievement_id,
                                    achievement_date=None,
                                    execute_triggers=True)
        rewards = []
        badges = []
        current_level = prog['level']
        all_rewards = AchievementReward.get_rewards(achievement_id, 6)
        all_badges = AchievementReward.get_rewards(achievement_id, 1)
        for i in range(0, len(all_rewards)):
            if all_rewards[i]['from_level'] <= current_level:
                rewards.append(all_rewards[i]['value'])
        for i in range(0, len(all_badges)):
            if all_badges[i]['from_level'] <= current_level:
                badges.append(all_badges[i]['value'])
        """
        levels = prog['levels']
        for key,value in levels.items():
            if value['level'] <= current_level:
                for key,value in value['rewards'].items():
                    if value['name'] == 'badge':
                        badges.append(value['value'])
                    if value['name'] == 'reward':
                        rewards.append(value['value'])
        """
        header_user = []
        for key, value in user['user']['additional_public_data'].items():
            header_user.append(key)
        return {
            'header_user': header_user,
            'user': user,
            'achievements': achievements,
            'params': params,
            'keys': keys,
            'badges': badges,
            'rewards': rewards,
            'current_level': current_level
        }
    else:
        return {'achievements': achievements, 'params': params, 'keys': keys}
Beispiel #5
0
def increase_value(request):
    """increase a value for the user"""

    user_id = int(request.matchdict["user_id"])
    try:
        value = float(request.POST["value"])
    except:
        try:
            doc = request.json_body
            value = doc["value"]
        except:
            raise APIError(400, "invalid_value", "Invalid value provided")

    key = request.matchdict["key"] if (
        "key" in request.matchdict
        and request.matchdict["key"] is not None) else ""
    variable_name = request.matchdict["variable_name"]

    user = User.get_user(user_id)
    if not user:
        raise APIError(404, "user_not_found", "user not found")

    variable = Variable.get_variable_by_name(variable_name)
    if not variable:
        raise APIError(404, "variable_not_found", "variable not found")

    if asbool(get_settings().get("enable_user_authentication", False)):
        if not Variable.may_increase(variable, request, user_id):
            raise APIError(403, "forbidden",
                           "You may not increase the variable for this user.")

    Value.increase_value(variable_name, user, value, key)

    output = _get_progress(achievements_for_user=user,
                           requesting_user=request.user)
    output = copy.deepcopy(output)
    to_delete = list()
    for i in range(len(output["achievements"])):
        if len(output["achievements"][i]["new_levels"]) > 0:
            if "levels" in output["achievements"][i]:
                del output["achievements"][i]["levels"]
            if "priority" in output["achievements"][i]:
                del output["achievements"][i]["priority"]
            if "goals" in output["achievements"][i]:
                del output["achievements"][i]["goals"]
        else:
            to_delete.append(i)

    for i in sorted(to_delete, reverse=True):
        del output["achievements"][i]

    return output
Beispiel #6
0
def get_position_user(request):
    """get all relevant data concerning the user's progress"""
    try:
        user_id = int(request.matchdict["user_id"])
    except:
        raise APIError(400, "illegal_user_id", "no valid user_id given")

    user = User.get_user(user_id)
    if not user:
        raise APIError(404, "user_not_found", "user not found")

    output = _get_progress(achievements_for_user=user,
                           requesting_user=request.user)
    output = copy.deepcopy(output)

    Achievements = []
    for i in range(len(output["achievements"])):
        if "new_levels" in output["achievements"][i]:
            del output["achievements"][i]["new_levels"]
        achievement = {}
        achievement["achievement_name"] = output["achievements"][i][
            "internal_name"]
        achievement["achievement_category"] = output["achievements"][i][
            "achievementcategory"]
        achievement["maxlevel"] = output["achievements"][i]["maxlevel"]
        achievement["level"] = output["achievements"][i]["level"]
        goals = output["achievements"][i]["goals"]
        for goal in goals:
            if "leaderboard" in goals[goal]:
                del goals[goal]["leaderboard"]
            if "properties" in goals[goal]:
                del goals[goal]["properties"]
            if "priority" in goals[goal]:
                del goals[goal]["priority"]
            if "leaderboard_position" in goals[goal]:
                goals[goal]["leaderboard_position"] = goals[goal][
                    "leaderboard_position"] + 1
        achievement["goals"] = goals
        Achievements.append(achievement)
    res = {'user': user["id"], 'achievements': Achievements}

    return res
Beispiel #7
0
def get_progress(request):
    """get all relevant data concerning the user's progress"""
    try:
        user_id = int(request.matchdict["user_id"])
    except:
        raise APIError(400, "illegal_user_id", "no valid user_id given")

    user = User.get_user(user_id)
    if not user:
        raise APIError(404, "user_not_found", "user not found")

    output = _get_progress(achievements_for_user=user,
                           requesting_user=request.user)
    output = copy.deepcopy(output)

    for i in range(len(output["achievements"])):
        if "new_levels" in output["achievements"][i]:
            del output["achievements"][i]["new_levels"]

    return output
Beispiel #8
0
    def test_evaluate_goal(self):

        user = create_user()
        create_variable(variable_name="invite_users", variable_group="day")
        Value.increase_value(variable_name="invite_users",
                             user=user,
                             value=6,
                             key=None)
        Value.increase_value(variable_name="invite_users",
                             user=user,
                             value=7,
                             key=None)

        create_variable(variable_name="participate", variable_group="day")
        Value.increase_value(variable_name="participate",
                             user=user,
                             value=6,
                             key="5")
        Value.increase_value(variable_name="participate",
                             user=user,
                             value=3,
                             key="7")
        Value.increase_value(variable_name="participate",
                             user=user,
                             value=5,
                             key="7")

        # Goal Participate with group_by = False
        achievement = create_achievement(
            achievement_name="participate_achievement")
        goal = create_goals(achievement,
                            goal_group_by_key=False,
                            goal_goal="3*level")
        achievement_date = Achievement.get_datetime_for_evaluation_type(
            User.get_user(user.id)["timezone"], achievement["evaluation"])

        evaluation_result = Goal.evaluate(goal,
                                          achievement,
                                          achievement_date,
                                          user,
                                          level=4,
                                          goal_eval_cache_before=False,
                                          execute_triggers=True)
        print(evaluation_result)
        # True cases
        self.assertGreaterEqual(evaluation_result["value"], 12)
        self.assertEqual(evaluation_result["achieved"], True)

        # Goal Participate with group_by = True
        goal2 = create_goals(achievement,
                             goal_group_by_key=True,
                             goal_goal="3*level")
        evaluation_result2 = Goal.evaluate(goal2,
                                           achievement,
                                           achievement_date,
                                           user,
                                           level=4,
                                           goal_eval_cache_before=False,
                                           execute_triggers=True)
        print(evaluation_result2)

        self.assertLessEqual(evaluation_result2["value"], 12)
        self.assertEqual(evaluation_result2["achieved"], False)

        # Goal invite_users
        achievement1 = create_achievement(
            achievement_name="invite_users_achievement")
        goal1 = create_goals(achievement1, goal_goal="4*level")
        achievement_date1 = Achievement.get_datetime_for_evaluation_type(
            User.get_user(user.id)["timezone"], achievement1["evaluation"])

        evaluation_result1 = Goal.evaluate(goal1,
                                           achievement1,
                                           achievement_date1,
                                           user,
                                           level=2,
                                           goal_eval_cache_before=False,
                                           execute_triggers=True)
        print(evaluation_result1)

        self.assertGreaterEqual(evaluation_result1["value"], 8)
        self.assertEqual(evaluation_result1["achieved"], True)
Beispiel #9
0
    def test_compute_progress(self):

        user = create_user()
        create_variable(variable_name="invite_users", variable_group="day")
        Value.increase_value(variable_name="invite_users",
                             user=user,
                             value=6,
                             key=None)
        Value.increase_value(variable_name="invite_users",
                             user=user,
                             value=7,
                             key=None)

        create_variable(variable_name="participate", variable_group="day")
        Value.increase_value(variable_name="participate",
                             user=user,
                             value=2,
                             key="5")
        Value.increase_value(variable_name="participate",
                             user=user,
                             value=3,
                             key="7")
        Value.increase_value(variable_name="participate",
                             user=user,
                             value=5,
                             key="7")

        achievement = create_achievement(
            achievement_name="invite_users_achievement")
        goal = create_goals(achievement)

        # goal is for invite_users, its group_by_key is false, progress is sum of all the values
        achievement_date = Achievement.get_datetime_for_evaluation_type(
            User.get_user(user.id)["timezone"], achievement["evaluation"])
        users_progress_goal = Goal.compute_progress(
            goal=goal,
            achievement=achievement,
            user=user,
            evaluation_date=achievement_date)
        goal_evaluation = {
            e["user_id"]: e["value"]
            for e in users_progress_goal
        }
        print(goal_evaluation)

        self.assertLessEqual(goal_evaluation.get(user.id), 13)

        # For goal1, since its group_by_key is True, it'll add the values of the same key
        achievement1 = create_achievement(
            achievement_name="participate_achievement")
        goal1 = create_goals(achievement1)
        achievement_date1 = Achievement.get_datetime_for_evaluation_type(
            User.get_user(user.id)["timezone"], achievement1["evaluation"])
        users_progress_goal1 = Goal.compute_progress(
            goal=goal1,
            achievement=achievement1,
            user=user,
            evaluation_date=achievement_date1)
        goal_evaluation1 = {
            e["user_id"]: e["value"]
            for e in users_progress_goal1
        }
        print(goal_evaluation1)

        self.assertLess(goal_evaluation1.get(user.id), 10)

        # Check with group_by_key for goals participate = False
        goal2 = create_goals(achievement1, goal_group_by_key=False)
        users_progress_goal1 = Goal.compute_progress(
            goal=goal2,
            achievement=achievement1,
            user=user,
            evaluation_date=achievement_date1)
        goal_evaluation2 = {
            e["user_id"]: e["value"]
            for e in users_progress_goal1
        }
        print(goal_evaluation2)
        self.assertLessEqual(goal_evaluation2.get(user.id), 10)
Beispiel #10
0
    def test_get_leaderboard(self):

        achievement = create_achievement(
            achievement_name="invite_users_achievement")
        goals = create_goals(achievement)

        # Create multiple users for a goal
        user1 = create_user()
        user2 = create_user(lat=85.59,
                            lng=65.75,
                            country="USA",
                            region="Lethal crosside",
                            city="New York",
                            timezone="US/Eastern",
                            language="en",
                            additional_public_data={
                                "first_name": "Michael",
                                "last_name": "Clarke"
                            })

        # Create Third user
        user3 = create_user(lat=12.1,
                            lng=12.2,
                            country="RO",
                            region="Transylvania",
                            city="Cluj-Napoca",
                            timezone="Europe/Bucharest",
                            language="en",
                            additional_public_data={
                                "first_name": "Rudolf",
                                "last_name": "Red Nose"
                            },
                            friends=[1, 2])

        # Create Fourth user
        user4 = create_user(lat=25.56,
                            lng=15.89,
                            country="AU",
                            region="Sydney",
                            city="New South Wales",
                            timezone="Australia/Sydney",
                            language="en",
                            additional_public_data={
                                "first_name": "Steve",
                                "last_name": "Waugh"
                            },
                            friends=[3])

        achievement_date_for_user1 = Achievement.get_datetime_for_evaluation_type(
            User.get_user(user1.id)["timezone"], achievement["evaluation"])
        achievement_date_for_user2 = Achievement.get_datetime_for_evaluation_type(
            User.get_user(user2.id)["timezone"], achievement["evaluation"])
        achievement_date_for_user3 = Achievement.get_datetime_for_evaluation_type(
            User.get_user(user3.id)["timezone"], achievement["evaluation"])
        achievement_date_for_user4 = Achievement.get_datetime_for_evaluation_type(
            User.get_user(user4.id)["timezone"], achievement["evaluation"])
        print(achievement_date_for_user4)

        create_goal_evaluation_cache(
            goal_id=goals.id,
            gec_achievement_date=achievement_date_for_user1,
            gec_user_id=user1.id,
            gec_value=22.00,
            gec_achieved=True)
        create_goal_evaluation_cache(
            goal_id=goals.id,
            gec_achievement_date=achievement_date_for_user2,
            gec_user_id=user2.id,
            gec_value=8.00,
            gec_achieved=True)
        create_goal_evaluation_cache(
            goal_id=goals.id,
            gec_achievement_date=achievement_date_for_user3,
            gec_user_id=user3.id,
            gec_value=15.00,
            gec_achieved=True)

        # Test for finding leaderboard in case where goal has been evaluated for all given users

        # First get list of friends (user_ids) of given user
        user_ids = Achievement.get_relevant_users_by_achievement_and_user(
            achievement, user3.id)

        # Get leaderboard
        positions = Goal.get_leaderboard(goals, achievement_date_for_user3,
                                         user_ids)
        print(positions)
        self.assertEqual(positions[0]["value"], 22.00)
        self.assertEqual(positions[1]["value"], 15.00)
        self.assertEqual(positions[2]["value"], 8.00)

        # Test for Goal is not evaluated for few user_ids
        create_variable(variable_name="invite_users", variable_group="day")
        Value.increase_value(variable_name="invite_users",
                             user=user4,
                             value=6,
                             key=None)
        Value.increase_value(variable_name="invite_users",
                             user=user4,
                             value=9,
                             key=None)

        user_ids = Achievement.get_relevant_users_by_achievement_and_user(
            achievement, user4.id)
        positions = Goal.get_leaderboard(goals, achievement_date_for_user4,
                                         user_ids)

        print(positions)
        self.assertEqual(positions[0]["value"], 15.00)