def unreact(): """ This is a flask wrapper for the message_unreact function Parameters: No parameters Returns: (dictionary): Empty dictionary. """ data = request.get_json() token = data['token'] react_id = int(data['react_id']) message_id = int(data['message_id']) if react_id != 1: raise InputError(description="Invalid react id") if not token_check(token): raise AccessError(description="Invalid user") user = token_check(token) if not react_check(message_id, user['u_id'], react_id): raise InputError(description="Already reacted") message_unreact(token, message_id, 1) return dumps({})
def channel_list(token): '''Lists channels a user is apart of. Parameters: token (str): authorization hash name (string): what channel will be named is_public (bool): true/false for public channel Returns: (int): channel id ''' if token_check(token) == False: raise InputError channel_store = get_channel_store() user = token_check(token) empty_list = [] for channels in channel_store["Channels"]: for member in channels['all_members']: if member["u_id"] == user["u_id"]: empty_list.append({ "channel_id": channels["channel_id"], "name": channels["name"] }) return {'channels': empty_list}
def test_auth_register_valid(): kelly_token = auth_register('*****@*****.**', 'Password', 'Kelly', 'Wolfe') kelly = token_check(kelly_token['token']) assert (kelly_token == {'u_id': kelly['u_id'], 'token': kelly['token']}) # Test for creation of unique handle zach_token = auth_register('*****@*****.**', 'password', 'Kelly', 'Wolfe') zach = token_check(zach_token['token']) assert (zach['handle_str'] != kelly['handle_str'])
def remove(): """ This is a flask wrapper for the message_remove function Parameters: No parameters Returns: (dictionary): Empty dictionary """ data = request.get_json() token = data['token'] message_id = int(data['message_id']) message_probe = message_check(message_id) user = token_check(token) if message_probe is None: raise InputError(description="Message not found") if not check_if_user_in_channel_owner(token, message['channel_id']): raise AccessError(description="User not owner") if user['u_id'] != message_probe['user_id']: raise AccessError(description="User not sender") message_remove(token, message_id) return dumps(message_id)
def search(token, query_str): # search for all channel ids that the user has joined in message # iterate thru message database and append to a new {messages: list} the messages that == user_id # remember to reverse the list before returning it user = token_check(token) message_store = get_messages_store() message_list = {'messages': []} for user_part in user['channel_id_part']: for mem_check in message_store["Messages"]: if mem_check['channel_id'] == user_part: fullstring = mem_check['message'] substring = query_str if substring in fullstring: message_list['messages'].append({ 'message_id': mem_check['message_id'], 'u_id': mem_check['user_id'], 'message': mem_check['message'], 'time_created': str(mem_check['time_created']), 'reacts': mem_check['reacts'], 'is_pinned': mem_check['is_pinned'] }) if len(message_list['messages']) > 1: message_list['messages'].reverse() return message_list
def users_all(token): if not token_check(token): print('Token invalid') raise InputError user_store = get_user_store() user_dict = {'users': []} for indiv_user in user_store['users']: user_dict['users'].append({ 'u_id': indiv_user['u_id'], 'email': indiv_user['email'], 'name_first': indiv_user['name_first'], 'name_last': indiv_user['name_last'], 'handle_str': indiv_user['handle_str'], 'profile_img_url': indiv_user['profile_img_url'] }) return user_dict
def channel_leave(token, channel_id): '''Removes member from a channel. Parameters: token (str): authorization hash channel_id (int): channel identification ''' if channel_check(channel_id) == False: raise InputError if check_if_user_in_channel_member(token, channel_id) == False: raise AccessError channel = channel_check(channel_id) user = token_check(token) for inner in channel['all_members']: if int(inner['u_id']) == int(user['u_id']): channel['all_members'].remove(inner) for leave in user['channel_id_part']: if int(leave) == int(channel_id): user['channel_id_part'].remove(leave) return {}
def message_edit(token, message_id, edited_message): """Edits a current message Parameters: token (string) message_id(int) edited_message(string) """ message = message_check(message_id) if message == None: raise InputError is_owner = owner_channel_check(token, message['channel_id']) user = token_check(token) if user == False: raise AccessError is_sender = False #print("message----->",message) if user['u_id'] == message['user_id']: is_sender = True if (is_owner or is_sender) == False: raise AccessError message['message'] = edited_message #message_data = get_messages_store() #message_data['Messages'].remove(message) return {}
def message_remove(token, message_id): """Removes a message Parameters: token (string) message_id(int) """ message = message_check(message_id) if message == None: raise InputError is_owner = owner_channel_check(token, message['channel_id']) user = token_check(token) if user == False: raise AccessError is_sender = False #print("message----->",message) if user['u_id'] == message['user_id']: is_sender = True #print('is owner: ',is_owner,'is_sender:', is_sender) if (is_owner or is_sender) == False: raise AccessError message_data = get_messages_store() message_data['Messages'].remove(message) return {}
def user_profile_setemail(token, email): print(email) # Check for any name length errors if email_check(email) == False: raise InputError if email_dupe_check(email) == True: raise InputError # We need to assert if the token is registered if token_check(token) == False: raise InputError # get required user dict user = token_check(token) user['email'] = email return {}
def user_profile_setname(token, name_first, name_last): # Check for any name length errors if len(name_first) > 50 or len(name_first) < 1: raise InputError if len(name_last) > 50 or len(name_last) < 1: raise InputError # We need to assert if the token is registered if token_check(token) == False: raise InputError # get required user dict user = token_check(token) user['name_first'] = name_first user['name_last'] = name_last return {}
def search_message(): data = request.get_json() token = data['token'] query_str = data['query_str'] if not token_check(token): raise InputError(description="Invalid_token") message_list = search(token, query_str) return dumps({ 'Messages': message_list['messages'] })
def get_all_users(): # Get current data inside store data = request.get_json() token = data['token'] if not token_check(token): raise InputError(description="Invalid_token") user_list = users_all(token) return dumps({ 'users': user_list['users'] })
def check_if_user_in_channel_owner(token, channel_id): user = token_check(token) channel_store = get_channel_store() result = False for mem_check in channel_store["Channels"]: if mem_check['channel_id'] == channel_id: for mem in mem_check['owner_members']: if mem["u_id"] == user["u_id"]: result = True return result
def message_send(token, channel_id, message): """ Sends a message to the designated channel Parameters: token (string) channel_id(int) message(string) Returns: (dictionary): A dictionary containing the message_id of the message that was sent. """ user = token_check(token) if not user: raise InputError channel = channel_check(channel_id) if channel is None: raise InputError #if check_user_in_channel(user['u_id'], channel_id) == False: # raise AccessError if (len(message) > 1000): raise InputError if not member_channel_check(token, channel_id): raise AccessError # message_store = get_messages_store() for member in channel['all_members']: if user['u_id'] == member['u_id']: message_id = make_message(message, channel_id, user['u_id'], 0) if message == "/hangman": channel['Hangman']['is_hangman_active'] = True make_message( "Welcome to Hangman!\n Please input your guess to start the game in the format /guess x where x is your guess\n", channel_id, user['u_id'], 0) if message[0:6] == "/guess" and channel['Hangman'][ 'is_hangman_active'] == True: hangman = play_hangman(message[7]) print('full hang', hangman) print('this is whats being used to print') print('current word:', hangman['current_word']) print('Hangman drwing:', hangman['hang_man_drawing']) if len(hangman['final']) != 0: channel['Hangman']['is_hangman_active'] = False make_message( hangman['hang_man_drawing'] + "\nWord to guess: " + hangman['print_word'] + hangman['final'], channel_id, user['u_id'], 0) return { 'message_id': message_id, }
def user_profile_sethandle(token, handle_str): if len(handle_str) <= 2 or len(handle_str) >= 20: raise InputError if handle_check(handle_str) == True: raise InputError # get required user dict user = token_check(token) user['handle_str'] = handle_str return {}
def user_remove(token, u_id): user_remove = u_id_check(u_id) permission = get_permission_store() if user_remove == False: raise InputError user_action = token_check(token) print(user_action['u_id']) print(permission['USER_NUM']) if user_action['u_id'] != permission['USER_NUM'][0]: print('raise access error') raise AccessError remove_from_channel(u_id) remove_from_user(u_id)
def check_if_user_in_channel_member(token, channel_id): user = token_check(token) channel_store = get_channel_store() result = False for mem_check in channel_store["Channels"]: if int(mem_check['channel_id']) == int(channel_id): for mem in mem_check['all_members']: if int(mem["u_id"]) == int(user["u_id"]): result = True return result
def message_react(token, message_id, react_id): """ Reacts to a message Parameters: token (string) message_id(int) react_id(int) """ message = message_check(message_id) if message == None: raise InputError if react_id != 1: #This is assuming that there's only 1 react id (1) raise InputError user = token_check(token) if user == None: raise AccessError if react_check(message_id, user['u_id'], react_id): print("react check input errroorrrrrrrr") raise InputError is_this_user_reacted = False flag = 0 for reacts in message['reacts']: if reacts['react_id'] == react_id: reacts['u_ids'].append(int(user['u_id'])) flag = 1 if reacts['is_this_user_reacted']: is_this_user_reacted = True if message['user_id'] == user['u_id']: is_this_user_reacted = True if flag == 0: dict_append = { 'u_ids': [int(user['u_id'])], 'react_id': int(react_id), 'is_this_user_reacted': is_this_user_reacted } message['reacts'].append(dict_append) return {}
def message_send_later(token, channel_id, message, time_sent): """ Sends a message to the designated channel at a specified time Parameters: token (string) channel_id(int) message(string) time_sent (datetime) Returns: (dictionary): A dictionary containing the message_id of the message that was sent. """ user = token_check(token) if user == False: raise InputError channel = channel_check(channel_id) if channel == False: raise InputError if member_channel_check(token, channel_id) == False: raise AccessError if (len(message) > 1000): raise InputError if int(time_sent) < int( datetime.datetime.now().replace(tzinfo=timezone.utc).timestamp()): raise InputError message_store = get_messages_store() for member in channel['all_members']: if user['u_id'] == member['u_id']: wait_time = time_sent - datetime.datetime.now().replace( tzinfo=timezone.utc).timestamp() time.sleep(wait_time) #wait_time = time.mktime(datetime.datetime.now().timetuple()) - time.mktime(time_sent.timetuple()) message_id = make_message(message, channel_id, user['u_id'], 0) return { 'message_id': message_id, }
def get_all_users(): """ This is a flask wrapper for the users_all function Parameters: No parameters Returns: (dictionary): A dictionary which contains a list of all the users and the details that are associated with them """ token = request.args.get("token") if not token_check(token): raise InputError(description="Invalid_token") user_list = users_all(token) return dumps({ 'users': user_list['users'] })
def c_listall(): """ This is a flask wrapper for the channels_list_all function Parameters: No parameters Returns: (dictionary): A dictionary which contains the key called channels and is a list of channels and their associated details """ token = request.args.get('token') if not token_check(token): raise AccessError(description="Invalid token") return_dict = channels_list_all(token) return dumps(return_dict)
def user_handle(): # Request information data = request.get_json() token = data['token'] # Save input as handle set_handle = data['handle_str'] # Validate token first if not token_check(token): raise InputError("Invalid token") # Check requirements for length if (len(set_handle) <= 2 or len(set_handle) >= 20): raise InputError(description="Invalid handle") # Check requirements for duplication if handle_check(set_handle): raise InputError(description="Handle already in use") user_profile_sethandle(token, set_handle) return dumps({})
def channel_addowner(token, channel_id, u_id): '''Adds someone as owner to a channel. Parameters: token (str): authorization hash channel_id (int): channel identification u_id (int): user identification ''' if channel_check(channel_id) == False: raise InputError if check_if_user_in_channel_owner_uid(u_id, channel_id) == True: raise InputError permission_error = token_check(token) if check_if_user_in_channel_owner(token, channel_id) == False: if permission_error['permission_id'] != 1: raise AccessError else: pass channel_store = get_channel_store() user = u_id_check(u_id) for channel in channel_store["Channels"]: if channel["channel_id"] == channel_id: if member_channel_check(user['token'], channel_id) == False: channel["all_members"].append({ "u_id": user["u_id"], "name_first": user['name_first'], "name_last": user["name_last"] }) channel["owner_members"].append({ "u_id": user["u_id"], "name_first": user['name_first'], "name_last": user["name_last"] }) user['channel_id_owned'].append(channel_id) user['channel_id_part'].append(channel_id) return {}
def c_list(): """ This is a flask wrapper for the channel_list function Parameters: No parameters Returns: (dictionary): This dictionary contains a list of all the channels that the user is part of and their associated details """ token = request.args.get('token') if not token_check(token): raise AccessError(description="Invalid token") return_dict = channel_list(token) return dumps(return_dict)
def user_profile_uploadphoto(token, img_url, x_start, y_start, x_end, y_end): #need to complete checks # use library to uplpad photo and crop it # save that new photo to server and get new link # that is the link you want to upload to user profile #opens image fd = urllib.request.urlopen(img_url) image_file = io.BytesIO(fd.read()) try: img = Image.open(image_file) except HTTPError as e: print('The server could not fulfill request.') print('Error code', e.code) #gets current dimensions of picture width, height = img.size #figure out how to check if image is a valid link!! if img.format != 'JPEG': raise InputError if x_end - x_start > int(width) or y_end - y_start > int(height): raise InputError #slightly confused about how to find left, top, right, and bottom- which one they correspond to left = x_start top = y_start #or should this be y_end? right = x_end bottom = y_end img_cropped = img.crop((left, top, right, bottom)) file_name = uuid.uuid4().hex path_name = 'photos/' + file_name + '.jpg' img.save('static/' + path_name, 'JPEG') new_url = url_for('static', filename=path_name, _external=True) user = token_check(token) user['profile_img_url'] = new_url print(user['profile_img_url'])
def search_message(): """ This is a flask wrapper for the search function Parameters: No parameters Returns: (dictionary): Creates a dictionary which contains a key called messages which resturns a collection of the messages (which match a query string) from all of the channels that the user is part of. These messages are sorted from most recent to least recent. """ token = request.args.get("token") query_str = request.args.get("query_str") if not token_check(token): raise InputError(description="Invalid_token") message_list = search(token, query_str) return dumps({ "messages" : message_list['messages'] })
def channels_list_all(token): '''Returns all channels. Parameters: token (str): authorization hash Returns: (list): list of channels ''' if token_check(token) == False: raise InputError channel_store = get_channel_store() empty_list = [] for channels in channel_store['Channels']: empty_list.append({ "channel_id": channels["channel_id"], "name": channels["name"] }) return {'channels': empty_list}
def channel_join(token, channel_id): '''Adds a member to a channel. Parameters: token (str): authorization hash channel_id (int): channel identification ''' if channel_check(channel_id) == False: raise InputError if (check_if_channel_is_public(channel_id) == False or check_if_user_in_channel_member(token, channel_id) == True): raise AccessError channel_store = get_channel_store() channel = channel_check(channel_id) user = token_check(token) for channel in channel_store["Channels"]: #print("gets in for loop") if channel["channel_id"] == int(channel_id): #print("gets in if statement") channel["all_members"].append({ "u_id": user["u_id"], "name_first": user['name_first'], "name_last": user["name_last"], 'profile_img_url': user['profile_img_url'] }) user['channel_id_part'].append(channel_id) return {}
def user_profile(token, u_id): if token_check(token) == False: raise InputError # First we need to assert if the u_id is registered if u_id_check(u_id) == False: raise InputError # get required user dict user = u_id_check(u_id) # create a dict of what we need user_prof_dict = { 'u_id': user['u_id'], 'email': user['email'], 'name_first': user['name_first'], 'name_last': user['name_last'], 'handle_str': user['handle_str'], 'profile_img_url': user['profile_img_url'], } return user_prof_dict