def message_send(token, channel_id, message): #Send a message from authorised_user to the channel specified by channel_id with open('data_store.json', 'r') as FILE: database = json.load(FILE) #Check if lenght of string is <1000 if len(message) > 1000: raise InputError(description='Message length greater than 1000.') email = find_token(token) for user in database["users"]: if user["email"] == email: for channel in database["channels"]: if channel["channel_id"] == channel_id: for member in channel["members"]: if member == user["u_id"]: timestamp = datetime.now().timestamp() message_id = uuid.uuid4().int text = { "message_id": message_id, "u_id": user["u_id"], "message": message, "time_created": timestamp, "reacts": [], "is_pinned": False } channel["messages"].append(text) with open('data_store.json', 'w') as FILE: json.dump(database, FILE) return {"message_id": message_id} raise AccessError( description='User is not a memmber of the channel') raise AccessError(description='Invalid token')
def channels_create(token, name, is_public): '''Creates a channel and assigns first user as owner.''' # Opens database with open('data_store.json', 'r') as FILE: database = json.load(FILE) # Find email from token email = find_token(token) for user in database["users"]: if user["email"] == email: #Checks the length of channel name if len(name) > 20: raise InputError( description='Name cannot be over 20 characters long') # Generate channel_id that is 5 digits long, convert to string new_id = uuid.uuid4().int channel_id = str(new_id)[:5] # Create new channel new_channel = { "channel_id": channel_id, "name": name, "is_public": is_public, "members": [user["u_id"]], "owners": [user["u_id"]], "messages": [] } # Add channel to list of channels database["channels"].append(new_channel) with open('data_store.json', 'w') as FILE: json.dump(database, FILE) return {"channel_id": new_channel["channel_id"]} raise AccessError(description="Invalid token")
def standup_send(token, channel_id, message): '''A function to send a message and packages it into one whole message under standup.''' database = get_data() email = find_token(token) for user in database["users"]: # check if token is valid if user["email"] == email: check_token = True if check_token is False: raise AccessError(description='Invalid token') channel = find_channel(database, channel_id) if channel is None: # check valid channel_id raise InputError(description='channel_id is not a valid channel') if channel["standup_active"] is None: raise InputError(description='No current active standup in channel') if len(message) > 1000: raise InputError(description='Message cannot be over 1000 characters long') for user in database["users"]: if user["email"] == email: if user["u_id"] not in channel["all_members"]: raise AccessError(description='user is not a member of the channel') database["standup_messages"].append(message) # add to list of messages in that channel return {}
def channel_invite(token, channel_id, u_id): '''Functions that invites user to channel''' database = get_data() # Find the channel dict with given channel id for channel in database["channels"]: if channel["channel_id"] == channel_id: # Finds user sending the invite from token email = find_token(token) for user_1 in database['users']: if user_1['email'] == email: # Check if user1 is part of the channel for member in channel["members"]: if user_1["u_id"] == member: # Finds the user invited from u_id for user_2 in database['users']: if user_2["u_id"] == u_id: # Adds user2 as a member of the channel channel["members"].append(u_id) with open('data_store.json', 'w') as FILE: json.dump(database, FILE) return {} raise InputError( description='u_id does not refer to valid user' ) raise InputError( description='User is not a member of the channel') raise AccessError(description='Invalid token')
def search(token, message): ''' Given a query string, return a collection of messages in all of the channels that the user has joined that match the query. ''' message_list = [] u_id = None database = get_data() #Find user email from token email = find_token(token) #Find u_id from email for user in database['users']: if user['email'] == email: u_id = user['u_id'] #Find matching message and u_id and add to list for i in database["channels"]: if u_id in i['members']: for all_message in i['messages']: if u_id == all_message['u_id']: if message in all_message['message']: message_list.append(all_message) message_list.reverse() return { "messages" : message_list }
def channel_removeowner(token, channel_id, u_id): '''Removes user with given u_id from the list of owners in that channel''' database = get_data() # Find channel dict with given channel_id for channel in database['channels']: if channel['channel_id'] == channel_id: #Find user from token email = find_token(token) for user_1 in database['users']: if user_1['email'] == email: #Check if authorised user is an owner for owner in channel['owners']: if owner == user_1['u_id']: for owner in channel['owners']: if owner == u_id: #u_id is given input from function channel['owners'].remove(u_id) with open('data_store.json', 'w') as FILE: json.dump(database, FILE) return {} raise InputError( description='User is not owner of channel') raise AccessError( description='Authorised user is not owner of channel') raise AccessError(description="Invalid token") raise InputError(description="Invalid channel_id")
def channel_addowner(token, channel_id, u_id): '''Turns the user with given u_id into an owner of the channel''' database = get_data() # Find channel dict with given channel_id for channel in database['channels']: if channel['channel_id'] == channel_id: #Find user from token email = find_token(token) for user_1 in database['users']: if user_1['email'] == email: #Check if authorised user is an owner for owner in channel['owners']: if owner == user_1['u_id']: #Check if other user is owner as well for owner in channel['owners']: if owner == u_id: #u_id is given input from function raise InputError( description= 'User is already owner of channel') channel['owners'].append( u_id) #Adds user as owner if user is not owner with open('data_store.json', 'w') as FILE: json.dump(database, FILE) return {} raise AccessError( description='User is not owner of channel') raise AccessError(description="Invalid token") raise InputError(description="Invalid channel_id")
def standup_start(token, channel_id, length): '''Starts a standup in a channel.''' database = get_data() database['standup_messages'] = [] ## set up a message list for stand up message email = find_token(token) for user in database["users"]: if user["email"] == email: check_token = True if check_token is False: raise AccessError(description='Invalid token') channel = find_channel(database, channel_id) if channel is None: # check standup start condition raise InputError(description='channel id is not a valid channel') if channel['standup_active']: raise InputError(description='standup is currently running in channel') time_start = time.time() channel['standup_active'] = time_start + length # save as time, otherwise none while time.time() < time_start + length: pass # stand_up/send message will be add into database['standup_messages'] channel['standup_active'] = None for i in database['standup_messages']: message_send(token, channel_id, i) database['standup_messages'].clear() # clear standup messages after standup is end store_data(database) return {time_start + length}
def channel_messages(token, channel_id, start): '''Function that shows up to 50 messages based on the start value''' database = get_data() # Find channel dict with given channel_id for channel in database['channels']: if channel['channel_id'] == channel_id: #Find user from token email = find_token(token) for user_1 in database['users']: if user_1['email'] == email: #Check if user is member of channel for member in channel['members']: if member == user_1['u_id']: #Find total number of messages messages_total = len(channel['messages']) #Check for empty list if not channel["messages"]: return { "messages": [], "start": start, "end": -1 } #Start value is bigger than total number of messages start = int(start) if start > messages_total: raise InputError( description='Start value is too big') recent_messages = [] end = start + 50 #Runs through up to 50 messages if end > messages_total: #Less than 50 messages left to load end = messages_total while end > start: #Starts from end of messages to start value recent_messages.append( channel['messages'][end - 1]) end -= 1 return { "messages": recent_messages, "start": start, "end": -1 } while end > start: #Last message will be first message returned recent_messages.append( channel['messages'][end - 1]) end -= 1 return { "messages": recent_messages, "start": start, "end": start + 50 } raise AccessError( description="User is not a member of the channel") raise AccessError(description="Invalid token") raise InputError(description="Invalid channel_id")
def auth_logout(token): '''Function to logout a user.''' with open("data_store.json", "r") as FILE: database = json.load(FILE) # Check if token is valid email = find_token(token) for user in database["users"]: if user["email"] == email: return {'is_success': True} return {'is_success': False}
def check_token(token): email = find_token(token) database = get_data() if email is None: raise AccessError(description='Invalid token') else: # Check if a decoded token belongs to an existing user for user in database["users"]: if user["email"] == email: return email raise AccessError(description='Invalid token')
def channels_listall(token): '''Returns a list of all the channels in the slackr.''' # Opens database with open("data_store.json", "r") as FILE: database = json.load(FILE) # Verifying Token email = find_token(token) for user in database["users"]: if user["email"] == email: all_channels = [] for channel in database["channels"]: # Get all channels in slackr channel_dict = give_channel(channel) all_channels.append(channel_dict) return {"channels": all_channels} raise AccessError(description="Invalid token")
def user_upload_photo(token, img_url, x_start, y_start, x_end, y_end): '''Crops an image from a URL and sets as user profile picture.''' database = get_data() # Find user from token email = find_token(token) for user in database["users"]: if user["email"] == email: # Save image from img_url into static folder # and check that it returns a HTTP status of 200 try: local_filename, headers = urllib.request.urlretrieve(img_url) except urllib.error.HTTPError: raise ValueError("img_url returns HTTP status other than 200") # Check if image is jpg type if headers["Content-Type"] not in ["image/jpeg", "image/jpg"]: raise ValueError("Image uploaded is not a JPG") # Open the image in static folder with Image.open(local_filename) as img: # Check if crop dimensions are within bounds of the image size width, height = img.size if x_start < 0 or y_start < 0 or \ x_start > width or y_start > height: raise ValueError( "Index not within the dimensions of the image") if x_end > width or y_end > width or \ x_end < x_start or y_end < y_start: raise ValueError( "Index not within the dimensions of the image") # Crop the image box = (x_start, y_start, x_end, y_end) cropped_img = img.crop(box) file_name = temporary_code() cropped_img.save("static/" + file_name + ".jpg") # Set the new url to user's profile_img_url e.g. /static/filename.jpg new_url = url_for("static", filename=file_name + ".jpg", _external=True) user["profile_img_url"] = new_url with open('data_store.json', 'w') as FILE: json.dump(database, FILE) return {}
def channels_list(token): '''Returns a list of channels the user is in.''' # Opens database with open("data_store.json", "r") as FILE: database = json.load(FILE) # Verifying Token email = find_token(token) for user in database["users"]: if user["email"] == email: all_channels = [] for channel in database["channels"]: # Find all channels user is in if user["u_id"] in channel["members"]: channel_dict = give_channel(channel) all_channels.append(channel_dict) return {"channels": all_channels} raise AccessError(description="Invalid token")
def channel_leave(token, channel_id): '''Given a channel ID, the user removed as a member of this channel.''' database = get_data() # Find channel dict with given channel_id for channel in database["channels"]: if channel["channel_id"] == channel_id: # Find user from token email = find_token(token) for user in database["users"]: if user["email"] == email: # Check if user is in channel for member in channel["members"]: if member == user["u_id"]: channel["members"].remove(user["u_id"]) with open('data_store.json', 'w') as FILE: json.dump(database, FILE) return {} raise AccessError( description="User is not a member of the channel") raise AccessError(description="Invalid token") raise InputError(description="Invalid channel_id")
def channel_details(token, channel_id): '''Function that returns the details of channel''' database = get_data() email = find_token(token) for user in database["users"]: if user["email"] == email: # Find channel dict with given channel_id for channel in database["channels"]: if channel["channel_id"] == channel_id: owner_members = [] for owner in channel["owners"]: owner_dict = get_profile(owner) owner_members.append(owner_dict) all_members = [] for member in channel["members"]: member_dict = get_profile(member) all_members.append(member_dict) return { "name": channel["name"], "owner_members": owner_members, "all_members": all_members } raise AccessError(description="Invalid token")
def standup_active(token, channel_id): '''Checks if a channel currently has an active standup.''' database = get_data() email = find_token(token) for user in database["users"]: if user["email"] == email: check_token = True if check_token is False: raise AccessError(description='Invalid token') channel = find_channel(database, channel_id) if channel is None: # check valid channel_id raise InputError(description='channel_id is not a valid channel') if "standup_active" not in channel: # no saved time, there is no current standup session is_active = False time_finish = None else: time_finish = channel['standup_active'] # set time_finished as saved time is_active = True return { "is_active" : is_active, "time_finish" : time_finish }
def channel_join(token, channel_id): '''Given a channel_id, adds the authorised user to the channel''' database = get_data() # Find channel dict with given channel_id for channel in database["channels"]: if channel["channel_id"] == channel_id: # Check if channel is private if channel["is_public"] is False: raise AccessError(description="Channel is private") # Find user from token email = find_token(token) for user in database["users"]: if user["email"] == email: for member in channel["members"]: if user["u_id"] == member: raise InputError( description= 'User is already a member of the channel') channel["members"].append(user["u_id"]) with open('data_store.json', 'w') as FILE: json.dump(database, FILE) return {} raise AccessError(description="Invalid token") raise InputError(description="Invalid channel_id")