def get(self, scope): try: if scope.upper() == "ALL": all_users = [] for i in UserCreateUpdateService.get_all_users(): all_users.append( UserConverter.convert_user_dto_to_public_response_dto( i)) return {'response': all_users}, 200 elif scope.upper() == "SINGLE": request = UserFetchResource.parser.parse_args() user = get_jwt_identity() if not user: return { 'error': ErrorEnums.SESSION_NOT_FOUND_ERROR.value }, 403 if not request.get('Id'): return ErrorEnums.ID_MISSING_ERROR.value, 400 if len(request.get('Id')) != 24: return ErrorEnums.INVALID_ID_FORMAT_ERROR.value, 400 user = UserCreateUpdateService.get_existing_user_by_id( request.get('Id')) if 'error' in user.keys(): return user, 404 return UserConverter.convert_user_dto_to_public_response_dto( user), 200 else: return { 'error': 'Unknown scope encountered. Please check your input.' }, 400 except Exception as e: return {'error': 'Exception - {} - occurred.'.format(e.args)}, 400
async def giveaway_command(self, ctx): winners = self.client.global_variables.giveaway_winners log.info("Previous giveaway winners are: " + UserUtils.print_names(winners)) channel = self.client.get_channel(Config.GIVEAWAY_VOICE_CHANNEL_ID) channel_members = channel.members log.info("Giveaway channel members are: " + UserUtils.print_names(channel_members)) # channel_members = TestUtils.generate_players_list(14) # spectators = TestUtils.generate_players_list(3, UserUtils.IDLE) # channel_members.extend(spectators) prev_winners_msg = self.generate_prev_winners_msg(winners) contenders = ListUtils.remove_sub_list(channel_members, winners) log.info("Giveaway contenders are: " + UserUtils.print_names(contenders)) if not contenders: log.info("No contenders for giveaway") await ctx.send(embed=discord.Embed(title=giveaway_title, description=prev_winners_msg + '\n' + "No contenders!", color=discord.Color.blue())) return player_lottery_msg = self.generate_players_lottery_msg(self, contenders) random_index = ListUtils.get_rand_index(contenders) new_winner = contenders[random_index] log.info("The new winner is: " + UserUtils.get_nick_or_name(new_winner)) winners.append(new_winner) await ctx.send(embed=discord.Embed(title=giveaway_title, description=giveaway_desc.format(prev_winners_msg, player_lottery_msg, new_winner.mention), color=discord.Color.blue()))
async def add_to_bench_command(self, ctx, user: discord.Member): user_name = UserUtils.get_nick_or_name_emojiless(user) log.info("Adding %s to bench...", user_name) bench = self.client.global_variables.bench bench.append(user) await ctx.send(ctx.author.mention + " User `" + user_name + "` has been added to the bench") await ctx.send( embed=UserUtils.generate_player_list_embed(bench, "Bench"))
async def remove_from_bench_command(self, ctx, user: discord.Member): user_name = UserUtils.get_nick_or_name_emojiless(user) log.info("Removing %s from bench...", user.name) bench = self.client.global_variables.bench if user in bench: bench.remove(user) await ctx.send(ctx.author.mention + " User `" + user_name + "` has been removed from the bench") else: await ctx.send(ctx.author.mention + " User `" + user_name + "` is not in the bench") await ctx.send( embed=UserUtils.generate_player_list_embed(bench, "Bench"))
def generate_prev_winners_msg(winners): if not winners: return '' return 'Previous giveaway winners:\n' + '\n'.join( [UserUtils.get_nick_or_name(winner) for winner in winners]) + '\n'
def update_email(identity, new_em): user = UserDatabaseService.get_user_by_id(identity.get('id')) try: user.update(set__email=new_em, set__last_updated_at=datetime.datetime.now(), set__last_updated_by=user) updated_user = dataStateAccess.UserDTO.user_dto( UserDatabaseService.get_user_by_id(identity.get('id'))) is_update_verified = verify_email_update_for_user( updated_user, new_em) if not is_update_verified: return [{ 'error': 'There was some error while updating email. Error Code: {}' .format(str(int(time.time() * 1000))) }, 500] response = UserUtils.convert_user_dto_to_public_response_dto( updated_user) return [{ 'Success': 'Email updated successfully.', 'updatedUserDetails': response }, 200] except Exception as e: return [{ "error": "There was some error. Exception: {}, Error Code: {}".format( e, str(int(time.time() * 1000))) }, 500]
def activate_deactivate_user( curr_user: dict, email: str, is_admin_action: bool, action) -> list: print( 'INFO: activation deactivation request received at {} for' ' \nuser: {},\nemail: {},\nadmin_action: {},\npermission: {}]'.format( str(datetime.datetime.now()), curr_user, email, is_admin_action, action )) email_length_invalid = UserUtils.verify_email_length(email, email) if email_length_invalid: return email_length_invalid elif curr_user.get('email') != email and not is_admin_action: return [{'error': 'Please provide your own valid email id address.'}, 404] UserDatabaseService.activate_deactivate_user(curr_user, email, is_admin_action, action) if action == AdminPermissionEnums.DEACTIVATE.name: deleted_user = dataStateAccess.UserDTO.user_dto(UserDatabaseService.get_active_inactive_single_user_by_email(email)) if deleted_user and not deleted_user.get('is_active'): # # Active tokens for current user should be revoked as soon as the user marks himself as inactive. user_session_history = SessionHistoryDatabaseService() session_bucket = user_session_history.get_active_sessions_for_user(deleted_user) if session_bucket: session_service = SessionService() session_service.revoke_session_token(session_bucket[0].get('access_token_jti')) return [{'response': 'User successfully deleted.'}, 200] return [{'error': 'No user with email {} found.'.format(email)}, 400] elif action == AdminPermissionEnums.ACTIVATE.name: activated_user = dataStateAccess.UserDTO.user_dto(UserDatabaseService.get_active_inactive_single_user_by_email(email)) if activated_user and activated_user.get('is_active'): return [{'response': 'User successfully restored.'}, 200] return [{'error': 'No user with email {} found .'.format(email)}, 400] print("Some error encountered, {}.".format(str(datetime.datetime.now()))) return [{'error': 'There was some error, please contact developer.'}, 500]
async def generate_members_in_bench_msg(bench): member_names = '\n'.join( [UserUtils.get_nick_or_name(m) for m in bench]) return discord.Embed(title="{} member(s) in {}".format( len(bench), "Bench"), description=member_names, color=discord.Color.blue())
def generate_session_token(self, user): self.session_dao = SessionHistoryDatabaseService() active_token = self.get_active_token_record(user) if active_token: return active_token session_token = self.generate_fresh_session_token( UserConverter.convert_user_dto_to_public_response_dto(user)) self.session_dao.insert_login_session(user.get('email'), session_token) return session_token
def generate_team_embed_message(number_of_team, team): embed = discord.Embed(title="Team " + str(number_of_team) + " (" + str(TeamUtils.get_team_avg_sr(team)) + " SR)", color=0x00FF00) for x in range(0, len(team)): player = team[x] embed.add_field(name="Player " + str(x + 1) + ":", value=UserUtils.get_nick_or_name(player), inline=True) return embed
def update_user_email(user, old_em, new_em): is_length_invalid = UserUtils.verify_email_length(old_em, new_em) if is_length_invalid: return is_length_invalid u = get_existing_user_by_id(user['id']) if 'error' in u.keys(): return [u, 500] if u['email'] != old_em: return [{'error': '{} does not match your current email address. Please check and try again.'.format(old_em)}, 404] elif old_em == new_em: return [{'error': 'Email is already up to date for the user.'}, 200] email_exists_already = verify_if_email_already_exists(new_em) if email_exists_already: return [{'error': 'Cannot update email as the user with email id - {} already exists.'.format(new_em)}, 409] updated_user = UserDatabaseService.update_email(user, new_em) return updated_user
def update_user_generic_data(user_identity, new_user_data): old_user_data = UserDatabaseService.get_user_by_id( user_identity.get('id')) verify_alt_username_existence_for_email = UserDatabaseService( ).get_user_by_alt_username(new_user_data.get('email').rsplit('@') [0]) if new_user_data.get('email') else None try: updated_user = UserUtils.convert_update_request_for_persistence( new_user_data, old_user_data) updated_user.last_updated_at = datetime.datetime.now() updated_user.last_updated_by = old_user_data if verify_alt_username_existence_for_email: updated_user.alt_username = updated_user.username updated_user.save(force_insert=False) return old_user_data.reload() except Exception as e: return "{}".format(e)
def put(self): try: user_identity = get_jwt_identity() user_request = UpdateUserDetails.parser.parse_args() if not user_request: return {'response': 'Details already up to date.'}, 200 user_request = UserConverterUtils.convert_request_to_user_update_dto(user_request, user_identity) updated_user = UserCreateUpdateService.create_update_user(user_identity, user_request, True) if not isinstance(updated_user, str): updated_user = updated_user return { 'response': { 'updatedUser': updated_user } }, 200 return {'error': updated_user}, 400 except Exception as e: return {'error': 'Exception - {} - occurred.'.format(e.args)}, 400
def create_user(user): new_user = models.User() try: verify_alt_username_existence_for_email = UserDatabaseService( ).get_user_by_alt_username(user.get('email').rsplit('@')[0]) returned_user = UserUtils.validate_and_convert_new_user_request_object( user, new_user) if isinstance(returned_user, str): return returned_user if verify_alt_username_existence_for_email: returned_user.alt_username = returned_user.username else: returned_user.alt_username = str( user.get('email').rsplit('@')[0]) returned_user.save() return returned_user # type is object except Exception as e: return "[{}]".format(e)
def user_dto(user): try: if not user: print(f"DEBUG: Received : {user} for user_dto.") return None book_bucket = list() books = UserUtils.get_user_favourite_books(user) if books: for book in books: book_bucket.append(BookDTO.embed_book_dto(book)) user_followers = [ EmbeddedDocumentDTO.generate_embedded_dto(user) for user in list(user.all_followers) ] user_following = [ EmbeddedDocumentDTO.generate_embedded_dto(user) for user in list(user.all_following) ] user_blocked = [ EmbeddedDocumentDTO.generate_embedded_dto(user) for user in list(user.blocked_users) ] return { 'id': str(user.pk), 'first_name': user.first_name, 'last_name': user.last_name if user.last_name else "", 'date_of_birth': str(user.date_of_birth)[:10], 'email': user.email, 'phone_number': user.phone_number, 'username': user.username, 'alternate_username': user.alt_username, 'is_active': user.is_active, 'created_at': str(user.created_at), 'password': str(user.password), 'is_admin': bool(user.is_admin), 'fav_books': book_bucket if book_bucket else [], 'followers': user_followers if user_followers else [], 'following': user_following if user_following else [], 'blocked': user_blocked if user_blocked else [] } except Exception as e: print("DEBUG: Exception occurred at USER_DTO_PRIVATE - {}".format(e))
def update_user_name(user: dict, old_username: str, new_username: str): is_length_verified = UserUtils.verify_username_length(old_username, new_username) if is_length_verified: return is_length_verified user = get_existing_user_by_id(user['id']) if 'error' in user.keys(): return [user, 500] elif old_username != user['username']: return [ { 'Error': '{} does not match the current username. Please correct your username and retry again.' .format(old_username) }, 404 ] elif old_username == new_username: return [{'error': 'Username is already up to date for the user.'}, 200] if verify_if_username_already_exists(new_username): return [{'error': 'User with username - {} already exists.'.format(new_username)}, 409] response = UserDatabaseService.update_username(user, new_username) return response
def update_username(identity, new_username): user = UserDatabaseService.get_user_by_id(identity.get('id')) user.update(set__username=new_username, set__last_updated_at=datetime.datetime.now(), set__last_updated_by=user) updated_user = dataStateAccess.UserDTO.user_dto( UserDatabaseService.get_user_by_id(identity.get('id'))) is_validated = verify_username_update_for_user(updated_user, new_username) if is_validated: return [{ 'Success': 'Username successfully updated.', 'updatedUserDetails': UserUtils.convert_user_dto_to_public_response_dto(updated_user) }, 200] return [{ 'Error': 'There was some error. Please retry again. Error code: {}'.format( str(int(time.time() * 1000))) }, 500]
def test_if_user_exist_by_username_true(self): exp_value = True username = "******" act_value = UserUtils.if_user_exist_by_username(username) self.assertEqual(exp_value, act_value)
def test_get_all_users_list(self): users_list = UserUtils.get_all_users_list() print(users_list)
def test_if_user_exist_by_username_false(self): exp_value = False username = "******" act_value = UserUtils.if_user_exist_by_username(username) self.assertEqual(exp_value, act_value)
async def generate_teams_command(self, ctx): self.client.global_variables.teams = list() self.client.global_variables.spectators = list() teams = self.client.global_variables.teams teams.append(list()) teams.append(list()) bench = self.client.global_variables.bench log.info("Generating teams...") voice_channel = self.client.get_channel( Config.COMMUNITY_GAMES_VOICE_CHANNEL_ID) members = voice_channel.members # members = TestUtils.generate_players_list(14) # spectators = TestUtils.generate_players_list(3, UserUtils.IDLE) # members.extend(spectators) self.client.global_variables.spectators = UserUtils.filter_spectators( members) spectators = self.client.global_variables.spectators log.info("Spectator players:%s", UserUtils.print_players(spectators)) log.debug("Removing spectators: %s from player pool: %s", UserUtils.print_players(spectators), UserUtils.print_players(members)) UserUtils.remove_players_from_list(spectators, members) log.debug("Player pool after removing spectators: %s", UserUtils.print_players(members)) log.debug("Removing spectators: %s from player bench: %s", UserUtils.print_players(spectators), UserUtils.print_players(bench)) UserUtils.remove_players_from_list(spectators, bench) log.debug("Bench pool after removing spectators: %s", UserUtils.print_players(bench)) num_of_players = len(members) await ctx.send(embed=( UserUtils.generate_player_list_embed(members, voice_channel.name))) if spectators: await ctx.send(embed=UserUtils.generate_player_list_embed( spectators, "Spectators")) log.info("Current number of players: " + str(num_of_players)) if num_of_players < 12: error_msg = self.get_not_enough_players_msg(num_of_players) log.error(error_msg) await ctx.send(ctx.author.mention + error_msg) return UserUtils.remove_players_from_list(bench, members) log.info("Adding previously benched players to teams:%s", UserUtils.print_players(bench)) self.generate_teams(bench) log.info("Adding players from players pool to teams:%s", UserUtils.print_players(members)) self.generate_teams(members) log.info("Adding unselected players to bench:%s", UserUtils.print_players(members)) bench.extend(members) bench = ListUtils.remove_duplicates(bench) members.clear() team0 = teams[0] team1 = teams[1] log.info("Teams generated are: " "\n Team 1: %s " "\n Team 2: %s", UserUtils.print_players(team0), UserUtils.print_players(team1)) await ctx.send(embed=self.generate_team_embed_message(1, team0)) await ctx.send(embed=self.generate_team_embed_message(2, team1)) await ctx.send( embed=UserUtils.generate_player_list_embed(bench, "Bench"))
def generate_players_lottery_msg(self, players): return 'Contenders:\n' + '\n'.join( [self.get_rand_declare_msg().format(UserUtils.get_nick_or_name(player)) for player in players])