def channel_messages(token, channel_id, start): """ Obtain message chain for user in a channel. """ # Open database to get info for error testing database = DataBase() channel = database.get_channel_info(channel_id) channel_member = database.get_account_info(token) # Error checking if not channel: raise InputError('Channel does not exist') if channel_member['permissions'] != OWNER_PERMISSIONS: if channel_member['u_id'] not in channel['members_id']: raise AccessError('Not a member in the channel') if start >= len(channel['messages']) and start != 0: raise InputError('Non-existent message') result = {} result['start'] = start # Use slicing and try statement to slice list of messages if start + 50 > len(channel['messages']): result['end'] = -1 else: result['end'] = start + 50 result['messages'] = channel['messages'][start:start + 50] return result
def user_profile_uploadphoto(token, img_url, x_start, y_start, x_end, y_end): """ User uploads profile picture. """ database = DataBase() directory = "src/res/avatar/" user_id = str(database.get_account_info(token)['u_id']) try: avatar_file, header = urllib.request.urlretrieve( img_url, directory + user_id + ".jpg") # No use for header header = str(header) except: raise InputError #Error checking image = Image.open(avatar_file) width, height = image.size if width <= x_end or height <= y_end: raise InputError('Cannot crop picture to specified x, y coordinates') file_list = glob.glob(f'{directory}{user_id}*') if imghdr.what(file_list[0]) != 'jpeg': os.remove(file_list[0]) raise InputError('Picture is not jpg') #Implementation avatar_file_cropped = Image.open(avatar_file) avatar_file_cropped = avatar_file_cropped.crop( (x_start, y_start, x_end, y_end)) avatar_file_cropped.save("src/res/avatar/" + str(database.get_account_info(token)['u_id']) + ".jpg")
def test_user_profile_sethandle_failed_already_exists(user_init): user_profile_sethandle(user_init[1]["token"], "new_handle1") data = DataBase() user_dict = data.get_account_info(user_init[1]["token"]) print(user_dict) with pytest.raises(InputError): user_profile_sethandle(user_init[0]["token"], "new_handle1")
def test_message_react(message_init): m_id = message_send(message_init[0]['token'], message_init[2], "message")['message_id'] message_react(message_init[0]['token'], m_id, 1) database = DataBase() assert message_init[0]['u_id'] in database.get_channel_messages( message_init[2])[int(str(m_id)[5:10])]['reacts'][0]['u_ids']
def test_message_pin(message_init): m_id = message_send(message_init[0]['token'], message_init[2], "message")['message_id'] message_pin(message_init[0]['token'], m_id) database = DataBase() assert database.get_channel_messages(message_init[2])[int( str(m_id)[5:10])]['is_pinned'] == True
def auth_login(email, password): """ Logs user into flockr (tracks account in database). """ email_in_database = check_email_in_database(email) validate_email_regex = check_email_regex(email) if not email_in_database or not validate_email_regex: raise InputError('Invalid email or email already in database') database = DataBase() users = database.database_dict['users'] valid_user = {} for user in users: if user['email'] == email and user['password'] == password: valid_user = user break if not valid_user: raise InputError('Invalid email or email already in database') # Add user to active_user database active_users = database.database_dict['active_users'] token_str_1 = f"active_user_{valid_user['u_id']}" token_str_2 = f"{database.database_dict['no_active_users']}" token_str = token_str_1 + "_" + token_str_2 token_str = database.token_generator(token_str) return_dict = {'u_id': valid_user['u_id'], 'token': token_str} active_users.append(return_dict) database.database_dict['no_active_users'] += 1 database.close() return return_dict
def users_all(token): """ Get list of all users. """ database = DataBase() users = make_user_list_other(database.database_dict['users']) return {'users': users}
def channels_create(token, name, is_public): """ Create a channel for a user. """ if len(name) > 20: raise InputError database = DataBase() # Get user channel_creator = database.get_account_info(token) # Get Channel ID and change number of channels database.database_dict['no_channels'] += 1 channel_id = database.database_dict['no_channels'] #We assume that channel_id start from 0->1->2->3->4->... new_channel = { 'standup': { 'user_token': None, 'end': None, 'message': "" }, 'creator_token': channel_creator['u_id'], 'name': name, 'channel_id': channel_id, 'is_public': is_public, 'owners_id': [], 'members_id': [], 'no_sent_messages': 0, 'messages': [] } new_channel['members_id'].append(channel_creator['u_id']) new_channel['owners_id'].append(channel_creator['u_id']) database.database_dict['channels'].append(new_channel) database.close() return {'channel_id': channel_id}
def auth_passwordreset_reset(reset_code, new_password): """ Reset password given a reset code. """ # Try decrypting jwt string try: decrypted_dict = jwt.decode(reset_code, RESET_PASSWORD_KEY, algorithms=['HS256']) except Exception: raise InputError email = decrypted_dict['email'] # Check if password and email is valid if not validate_password(new_password) or not check_email_in_database( email): raise InputError # Reset the password database = DataBase() u_id = 0 users = database.database_dict['users'] for user in users: if user['email'] == email: break u_id += 1 target_user = database.database_dict['users'][u_id] target_user['password'] = new_password database.close() return {}
def message_send(token, channel_id, message): """ Send message in channel. """ # Raise error if message is too long if len(message) > 1000: raise InputError('Message over 1000 words') database = DataBase() user_id = database.get_account_info(token)['u_id'] channel = database.get_channel_info(channel_id) # Raise error is user_id is not part of channel. if user_id not in channel['members_id']: raise AccessError('Not a channel member') # Create message_id channel_id_str = str(NO_CHANNELS - channel_id) message_id = channel_id_str + str(channel['no_sent_messages']).zfill(5) message_id += str(user_id) message_id = int(message_id) # Create message_dict dt = datetime.now() timestamp = int(dt.replace(tzinfo=timezone.utc).timestamp()) message_dict = {} message_dict['message_id'] = message_id message_dict['u_id'] = user_id message_dict['message'] = message message_dict['time_created'] = timestamp message_dict['reacts'] = [{'react_id': 1, 'u_ids': [], 'is_this_user_reacted': False}] message_dict['is_pinned'] = False channel['messages'] = [message_dict] + channel['messages'] channel['no_sent_messages'] += 1 database.close() return { 'message_id': message_id, }
def global_variables(url): """ Variables to be used in all functions. """ data_1 = {} data_1['email'] = '*****@*****.**' data_1['password'] = '******' data_1['name_first'] = 'name_first' data_1['name_last'] = 'name_last' data_2 = {} data_2['email'] = '*****@*****.**' data_2['password'] = '******' data_2['name_first'] = 'name_first' data_2['name_last'] = 'name_last' pathname = "/auth/register" response_1 = requests.post(url + pathname, json=data_1) response_2 = requests.post(url + pathname, json=data_2) try: pytest.global_token_1 = json.loads(response_1.text)['token'] pytest.global_token_2 = json.loads(response_2.text)['token'] except: database = DataBase() pytest.global_token_1 = database.database_dict['active_users'][0][ 'token'] pytest.global_token_2 = database.database_dict['active_users'][1][ 'token']
def test_perm_change_access_error(other_init): database = DataBase() admin = database.get_account_info(other_init[0]['token']) admin['permissions'] = 2 database.close() with pytest.raises(AccessError): admin_userpermission_change(other_init[0]['token'], other_init[1]['u_id'], 1)
def test_message_sendlater_with_fomatted_time(message_init): m_id = message_sendlater( message_init[0]['token'], message_init[2], "message", str(datetime.datetime.now().replace(microsecond=0) + datetime.timedelta(seconds=2)))['message_id'] database = DataBase() assert database.get_channel_messages(message_init[2])[int( str(m_id)[5:10])]['message_id'] == m_id
def test_perm_change(other_init): database = DataBase() admin = database.get_account_info(other_init[0]['token']) admin['permissions'] = 1 database.close() result = admin_userpermission_change(other_init[0]['token'], other_init[1]['u_id'], 1) assert result == {}
def channels_listall(token): """ Admin feature to know all of the channels. """ # Need to change token structure. database = DataBase() current_channels = database.database_dict['channels'] current_channels = make_channels_list(current_channels) return {'channels': current_channels}
def user_profile(token, u_id): """ Obtain user profile. """ database = DataBase() user_profile = database.get_info_from_id(u_id) if not user_profile: raise InputError('User does not exist') return {'user': user_profile}
def test_user_profile_uploadphoto(user_init): user_profile_uploadphoto( user_init[0]['token'], "https://secure.aspca.org/files/aspca/p2p-campaign-images/user-2660231/guide-dogs_025-11.jpg", 0, 0, 1000, 1000) database = DataBase() fname = "src/res/avatar/" + str( database.get_account_info(user_init[0]['token'])['u_id']) + ".jpg" assert os.path.isfile(fname)
def test_message_edit(message_init): m_id = message_send(message_init[0]['token'], message_init[2], "message")['message_id'] # Edited message_edit(message_init[0]['token'], m_id, "edited") # Deleted message_edit(message_init[0]['token'], m_id, "") database = DataBase() assert len(database.get_channel_messages(message_init[2])) == 0
def user_profile_setemail(token, email): """ Change email. """ database = DataBase() user_profile = database.get_account_info(token) if not validate_email(email): raise InputError('Email can\'t be used') user_profile['email'] = email return {}
def test_message_pin_remote(url, message_init): m_id = message_send(message_init[0]['token'], message_init[2], "message")['message_id'] requests.post(f'{url}message/pin', json={ 'token': message_init[0]['token'], 'message_id': m_id, }) database = DataBase() assert database.get_channel_messages(message_init[2])[int( str(m_id)[5:10])]['is_pinned'] == True
def global_variables(): """ Variables to be used in all functions. """ try: pytest.global_token_1 = auth_register("*****@*****.**", "password", "name_first", "name_last") pytest.global_token_2 = auth_register("*****@*****.**", "password", "name_first", "name_last") except InputError: database = DataBase() pytest.global_token_1 = database.database_dict['active_users'][0] pytest.global_token_2 = database.database_dict['active_users'][1]
def test_standup_active_ends_and_sends_message(standup_init): standup_start(standup_init[0]['token'], standup_init[2], 10) standup_send(standup_init[0]['token'], standup_init[2], "heyo") standup_send(standup_init[0]['token'], standup_init[2], "heyo0000") time.sleep(11) # Not active result = standup_active(standup_init[0]['token'], standup_init[2]) assert not result['is_active'] database = DataBase() messages = database.get_channel_info(standup_init[2])['messages'] assert messages[0]
def test_channel_leave_remote(url, channel_init): ''' test_channel_leave_remote ''' requests.post(f'{url}channel/leave', json={ 'token': channel_init[1]['token'], 'channel_id': channel_init[2] }) database = DataBase() assert channel_init[1]['u_id'] not in database.get_channel_info( channel_init[2])['members_id']
def user_profile_setname(token, name_first, name_last): """ user sets name. """ database = DataBase() user_profile = database.get_account_info(token) if not validate_names(name_first, name_last): raise InputError user_profile['name_first'] = name_first user_profile['name_last'] = name_last database.close() return {}
def test_message_react_remote(url, message_init): m_id = message_send(message_init[0]['token'], message_init[2], "message")['message_id'] requests.post(f'{url}message/react', json={ 'token': message_init[0]['token'], 'message_id': m_id, 'react_id': 1 }) database = DataBase() assert message_init[0]['u_id'] in database.get_channel_messages( message_init[2])[int(str(m_id)[5:10])]['reacts'][0]['u_ids']
def check_email_in_database(email): """ Checks if email is present in database. """ # Open database database = DataBase() email_in_database = False users = database.database_dict['users'] for user in users: if user['email'] == email: email_in_database = True break return email_in_database
def test_channel_removeowner_remote(url, channel_init): ''' test_channel_removeowner_remote ''' requests.post(f'{url}channel/removeowner', json={ 'token': channel_init[0]['token'], 'channel_id': channel_init[2], 'u_id': channel_init[0]['u_id'] }) database = DataBase() assert channel_init[0]['u_id'] not in database.get_channel_info( channel_init[2])['owners_id']
def test_channel_join_remote(url, channel_init): ''' test_channel_join_remote ''' test_channel_public_id = channels_create(channel_init[0]['token'], f"test_public{UNIQUE_ID}", True) requests.post(f'{url}channel/join', json={ 'token': channel_init[1]['token'], 'channel_id': test_channel_public_id['channel_id'] }) database = DataBase() assert channel_init[1]['u_id'] in database.get_channel_info( test_channel_public_id['channel_id'])['members_id']
def channels_list(token): """ Return the user the list of channels they are in. """ # Open database database = DataBase() channel_member = database.get_account_info(token) channel_member_u_id = channel_member['u_id'] # Get member_channels member_channels = [] for channel in database.database_dict['channels']: if channel_member_u_id in channel['members_id']: member_channels.append(channel) member_channels = make_channels_list(member_channels) return {'channels': member_channels}
def user_profile_sethandle(token, handle_str): """ Let user modify handle. """ if len(handle_str) > 20 or len(handle_str) < 3: raise InputError('Illegible handle') database = DataBase() user_profile = database.get_account_info(token) users = database.database_dict['users'] for user in users: if handle_str == user['handle_str']: raise InputError('Handle already exists') user_profile['handle_str'] = handle_str database.close() return {}