def delete_user(user_id=undefined, ): User.delete_user(user_id) users = DBSession.execute(select([ t_users.c.id, ])).fetchall() return users
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)
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)
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}
def delete_user(request): """delete a user completely""" user_id = int(request.matchdict["user_id"]) """if asbool(get_settings().get("enable_user_authentication", False)): # ensure that the user exists and we have the permission to update it may_delete = request.has_perm(perm_global_delete_user) or request.has_perm(perm_own_delete_user) and request.user.id == user_id if not may_delete: raise APIError(403, "forbidden", "You may not delete this user.")""" User.delete_user(user_id) return {"status": "OK"}
def create_user(DBSession, user, password): from gengine.app.model import ( AuthUser, User, AuthRole, AuthRolePermission ) with transaction.manager: existing = DBSession.query(AuthUser).filter_by(email=user).first() if not existing: try: user1 = User(id=1, lat=10, lng=50, timezone="Europe/Berlin") DBSession.add(user1) DBSession.flush() auth_user = AuthUser(user_id=user1.id, email=user, password=password, active=True) DBSession.add(auth_user) auth_role = AuthRole(name="Global Admin") DBSession.add(auth_role) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_access_admin_ui)) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_delete_user)) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_increase_value)) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_update_user_infos)) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_read_messages)) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_register_device)) auth_user.roles.append(auth_role) DBSession.add(auth_user) except: pass
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
def upload_view(request): params = request.GET dir_name = os.path.dirname( os.path.abspath(__file__)) + "\\csv_uploads\\file.csv" if request.method == 'POST': if 'upload' in request.POST: content = request.POST['file'].file content = content.read() content = content.decode('utf-8', 'ignore') my_dict = p.get_book(file_type="csv", file_content=content, delimiter=';') my_dict.save_as(dir_name, delimiter=';') with open(dir_name) as f: keys = f.readline().rstrip().split(";") return render_to_response( 'gengine.app:templates/index/upload.jinja2', { 'keys': keys, 'params': params }, request=request) else: user_id = request.POST["user_id"] user_region = request.POST["region"] user_city = request.POST["city"] user_att = [] for key, item in request.POST.items(): if key == 'users': user_att.append(item) #for i in range(0,len(user_att)): #print('user',user_att[i]) User.add_multiple(user_id, user_region, user_city, user_att, dir_name) params.update({'user_id': user_id}) return HTTPFound(request.route_url('goal', _query=params)) else: return {'params': params}
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
def users_cities(request): achievement_id = int(request.matchdict["achievement_id"]) cities = User.sort("City") res_cities = [] res_cities = np.asarray(cities) result = [] for i in range(len(res_cities)): relevance = {'type': 'City', 'value': res_cities[i][0]} result.append({ 'City': res_cities[i][0], 'Leaderboard': Achievement.get_leaderbord_by_relevance(achievement_id, relevance) }) return result
def increase_data(request): dir_name = os.path.dirname( os.path.abspath(__file__)) + "\\csv_uploads\\file.csv" params = request.GET if request.method == 'POST': if 'upload' in request.POST: dir_name = os.path.dirname( os.path.abspath(__file__)) + "\\csv_uploads\\values_data.csv" content = request.POST['file'].file content = content.read() content = content.decode('utf-8', 'ignore') my_dict = p.get_book(file_type="csv", file_content=content, delimiter=';') my_dict.save_as(dir_name, delimiter=';') with open(dir_name) as f: keys_data = f.readline().rstrip().split(";") params.update({'id': request.POST['achievement_id']}) return render_to_response( 'gengine.app:templates/index/increase_data.jinja2', { 'keys_data': keys_data, 'params': params }, request=request) elif 'value' in request.POST: user_id = request.POST["user_id"] variable = request.POST["variable"] value = request.POST["value"] user_id_value = request.POST["user_id_value"] achievement_id = request.POST['achievement_id'] res_id_user = User.get_by_id(user_id, user_id_value) Value.increaseByValue(variable, res_id_user, value) Achievement.update_user_value(achievement_id, res_id_user) return HTTPFound(request.route_url('increase_data', _query=params)) else: user_id = request.POST["user_id"] variable = request.POST["variable"] achievement_id = params["id"] Value.increase(achievement_id, variable, user_id, dir_name) return HTTPFound(request.route_url('leaderboard', _query=params)) else: with open(dir_name) as f: keys = f.readline().rstrip().split(";") achievements = Achievement.get_all_achievements() return {'achievements': achievements, 'params': params, 'keys': keys}
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
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
def auth_login(request): try: doc = request.json_body except: raise APIError(400, "invalid_json", "no valid json body") user = request.user email = doc.get("email") password = doc.get("password") if user: #already logged in token = user.get_or_create_token().token else: if not email or not password: raise APIError(400, "login.email_and_password_required", "You need to send your email and password.") user = DBSession.query(AuthUser).filter_by(email=email).first() if not user or not user.verify_password(password): raise APIError( 401, "login.email_or_password_invalid", "Either the email address or the password is wrong.") if not user.active: raise APIError(400, "user_is_not_activated", "Your user is not activated.") token = AuthToken.generate_token() tokenObj = AuthToken(user_id=user.id, token=token) DBSession.add(tokenObj) return { "token": token, "user": User.full_output(user.user_id), }
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)
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)
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)
def populate_demo(DBSession): from gengine.app.model import ( Achievement, AchievementCategory, Goal, Variable, User, Language, TranslationVariable, Translation, GoalProperty, GoalGoalProperty, Reward, AchievementProperty, AchievementAchievementProperty, AchievementReward, AuthUser, AuthRole, AuthRolePermission ) def add_translation_variable(name): t = TranslationVariable(name=name) DBSession.add(t) return t def add_translation(variable, lang, text): tr = Translation(translationvariable=variable, text=text, language=lang) DBSession.add(tr) return tr with transaction.manager: lang_de = Language(name="de") lang_en = Language(name="en") DBSession.add(lang_de) DBSession.add(lang_en) var_invited_users = Variable(name="invite_users") DBSession.add(var_invited_users) var_invited_users = Variable(name="participate", group="none") DBSession.add(var_invited_users) goal_property_name = GoalProperty(name='name') DBSession.add(goal_property_name) achievementcategory_community = AchievementCategory(name="community") DBSession.add(achievementcategory_community) achievement_invite = Achievement(name='invite_users', evaluation="immediately", maxtimes=20, achievementcategory=achievementcategory_community) DBSession.add(achievement_invite) transvar_invite = add_translation_variable(name="invite_users_goal_name") add_translation(transvar_invite, lang_en, 'Invite ${5*level} Users') add_translation(transvar_invite, lang_de, 'Lade ${5*level} Freunde ein') achievement_invite_goal1 = Goal(name_translation=transvar_invite, condition='{"term": {"type": "literal", "variable": "invite_users"}}', goal="5*level", operator="geq", achievement=achievement_invite) DBSession.add(achievement_invite_goal1) DBSession.add(GoalGoalProperty(goal=achievement_invite_goal1, property=goal_property_name, value_translation=transvar_invite)) achievementcategory_sports = AchievementCategory(name="sports") DBSession.add(achievementcategory_sports) achievement_fittest = Achievement(name='fittest', relevance="friends", maxlevel=100, achievementcategory=achievementcategory_sports) DBSession.add(achievement_fittest) transvar_fittest = add_translation_variable(name="fittest_goal_name") add_translation(transvar_fittest, lang_en, 'Do the most sport activities among your friends') add_translation(transvar_fittest, lang_de, 'Mache unter deinen Freunden am meisten Sportaktivitäten') achievement_fittest_goal1 = Goal(name_translation=transvar_fittest, condition='{"term": {"key": ["5","7","9"], "type": "literal", "key_operator": "IN", "variable": "participate"}}', evaluation="weekly", goal="5*level", achievement=achievement_fittest ) DBSession.add(achievement_fittest_goal1) DBSession.add(GoalGoalProperty(goal=achievement_fittest_goal1, property=goal_property_name, value_translation=transvar_fittest)) property_name = AchievementProperty(name='name') DBSession.add(property_name) property_xp = AchievementProperty(name='xp') DBSession.add(property_xp) property_icon = AchievementProperty(name='icon') DBSession.add(property_icon) reward_badge = Reward(name='badge') DBSession.add(reward_badge) reward_image = Reward(name='backgroud_image') DBSession.add(reward_image) transvar_invite_name = add_translation_variable(name="invite_achievement_name") add_translation(transvar_invite_name, lang_en, 'The Community!') add_translation(transvar_invite_name, lang_de, 'Die Community!') DBSession.add(AchievementAchievementProperty(achievement=achievement_invite, property=property_name, value_translation=transvar_invite_name)) DBSession.add(AchievementAchievementProperty(achievement=achievement_invite, property=property_xp, value='${100 * level}')) DBSession.add(AchievementAchievementProperty(achievement=achievement_invite, property=property_icon, value="https://www.gamification-software.com/img/running.png")) DBSession.add(AchievementReward(achievement=achievement_invite, reward=reward_badge, value="https://www.gamification-software.com/img/trophy.png", from_level=5)) DBSession.add(AchievementReward(achievement=achievement_invite, reward=reward_image, value="https://www.gamification-software.com/img/video-controller-336657_1920.jpg", from_level=5)) transvar_fittest_name = add_translation_variable(name="fittest_achievement_name") add_translation(transvar_fittest_name, lang_en, 'The Fittest!') add_translation(transvar_fittest_name, lang_de, 'Der Fitteste!') DBSession.add(AchievementAchievementProperty(achievement=achievement_fittest, property=property_name, value_translation=transvar_fittest_name)) DBSession.add(AchievementAchievementProperty(achievement=achievement_fittest, property=property_xp, value='${50 + (200 * level)}')) DBSession.add(AchievementAchievementProperty(achievement=achievement_fittest, property=property_icon, value="https://www.gamification-software.com/img/colorwheel.png")) DBSession.add(AchievementReward(achievement=achievement_fittest, reward=reward_badge, value="https://www.gamification-software.com/img/easel.png", from_level=1)) DBSession.add(AchievementReward(achievement=achievement_fittest, reward=reward_image, value="https://www.gamification-software.com/img/game-characters-622654.jpg", from_level=1)) user1 = User(id=1,lat=10,lng=50,timezone="Europe/Berlin") user2 = User(id=2,lat=10,lng=50,timezone="US/Eastern") user3 = User(id=3,lat=10,lng=50) user1.friends.append(user2) user1.friends.append(user3) user2.friends.append(user1) user2.friends.append(user3) user3.friends.append(user1) user3.friends.append(user2) DBSession.add(user1) DBSession.add(user2) DBSession.add(user3) DBSession.flush() try: auth_user = AuthUser(user_id=user1.id,email="*****@*****.**",password="******",active=True) DBSession.add(auth_user) auth_role = AuthRole(name="Global Admin") DBSession.add(auth_role) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_access_admin_ui)) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_delete_user)) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_increase_value)) DBSession.add(AuthRolePermission(role=auth_role, name=perm_global_update_user_infos)) auth_user.roles.append(auth_role) DBSession.add(auth_user) except ImportError as e: print("[auth] feature not installed - not importing auth demo data")
def leaderboard(request): params = request.GET achievement_id = params["id"] sorted_by = {"type": "Global"} achievement = Achievement.get_achievement(achievement_id) if request.method == 'POST': if ('sorted_value' in request.POST): sorted_by["type"] = params["type"] sorted_by.update({'value': request.POST['sorted_value']}) result = Achievement.get_leaderbord_by_relevance( achievement_id, sorted_by) header_table = [] for key, value in result[0]["user"][ "additional_public_data"].items(): header_table.append(key) return { 'header_table': header_table, 'result': result, 'winner': result[0], 'params': params, 'sorted_by': sorted_by["type"], 'achievement': achievement, 'sorted_value': request.POST['sorted_value'] } elif ('sorted_by' in request.POST): sorted_by["type"] = request.POST['sorted_by'] params.update({'type': request.POST['sorted_by']}) if sorted_by["type"] == 'Global': result = Achievement.get_leaderbord_by_achievement( achievement_id) header_table = [] for key, value in result[0]["user"][ "additional_public_data"].items(): header_table.append(key) return { 'header_table': header_table, 'result': result, 'winner': result[0], 'params': params, 'sorted_by': sorted_by["type"], 'achievement': achievement } else: sort_res = User.sort(sorted_by["type"]) myarray = [] myarray = np.asarray(sort_res) result = Achievement.get_leaderbord_by_achievement( achievement_id) header_table = [] for key, value in result[0]["user"][ "additional_public_data"].items(): header_table.append(key) return { 'header_table': header_table, 'result': result, 'winner': result[0], 'exist': sort_res, 'sort_res': myarray, 'params': params, 'sorted_by': sorted_by["type"], 'achievement': achievement } else: result = Achievement.get_leaderbord_by_achievement(achievement_id) header_table = [] for key, value in result[0]["user"]["additional_public_data"].items(): header_table.append(key) return { 'header_table': header_table, 'result': result, 'winner': result[0], 'params': params, 'sorted_by': sorted_by["type"], 'achievement': achievement }
def add_or_update_user(request): """add a user and set its metadata""" user_id = int(request.matchdict["user_id"]) if asbool(get_settings().get("enable_user_authentication", False)): #ensure that the user exists and we have the permission to update it may_update = request.has_perm( perm_global_update_user_infos) or request.has_perm( perm_own_update_user_infos) and request.user.id == user_id if not may_update: raise APIError(403, "forbidden", "You may not edit this user.") #if not exists_by_expr(t_users,t_users.c.id==user_id): # raise APIError(403, "forbidden", "The user does not exist. As the user authentication is enabled, you need to create the AuthUser first.") lat = None if len(request.POST.get("lat", "")) > 0: lat = float(request.POST["lat"]) lon = None if len(request.POST.get("lon", "")) > 0: lon = float(request.POST["lon"]) friends = [] if len(request.POST.get("friends", "")) > 0: friends = [int(x) for x in request.POST["friends"].split(",")] groups = [] if len(request.POST.get("groups", "")) > 0: groups = [int(x) for x in request.POST["groups"].split(",")] timezone = "UTC" if len(request.POST.get("timezone", "")) > 0: timezone = request.POST["timezone"] if not valid_timezone(timezone): timezone = 'UTC' country = None if len(request.POST.get("country", "")) > 0: country = request.POST["country"] region = None if len(request.POST.get("region", "")) > 0: region = request.POST["region"] city = None if len(request.POST.get("city", "")) > 0: city = request.POST["city"] language = None if len(request.POST.get("language", "")) > 0: language = request.POST["language"] additional_public_data = {} if len(request.POST.get("additional_public_data", "")) > 0: try: additional_public_data = json.loads( request.POST["additional_public_data"]) except: additional_public_data = {} User.set_infos(user_id=user_id, lat=lat, lng=lon, timezone=timezone, country=country, region=region, city=city, language=language, friends=friends, groups=groups, additional_public_data=additional_public_data) return {"status": "OK", "user": User.full_output(user_id)}