def message_sendlater(token, channel_id, message, time_sent): global message_id # check for access error (user must be in the channel) if user_is_in_channel(getUidFromToken(token), channel_id) is False: raise AccessError('User not in the channel') if len(message) > 1000: raise ValueError_http("Message cannot be longer than 1000 characters") #time sent has to be in the future if float(time_sent) < datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp(): raise ValueError_http("Time set has to be in the future") # add message details channel = getChannelDetails(channel_id) message_id += 1 channel['messages'].insert(0, { 'message_id': message_id, 'u_id': getUidFromToken(token), 'message': message, 'time_created': str(time_sent), 'reacts': [{'react_id': 1, 'u_ids': [], 'is_this_user_reacted' : False}], 'is_pinned': False }) return {'message_id': message_id}
def user_profile_sethandle(token, handle_str): if len(handle_str) < 3 or len(handle_str) > 20: raise ValueError_http("handle_str should be between 3-20 characters") if getUserByHandle(handle_str) != None: raise ValueError_http( "handle_str is already being used by another user") found_user2 = getUserFromToken(token) found_user2['handle_str'] = handle_str return ({})
def message_unreact(token, message_id, react_id): message = getMessageInfo(message_id) channel_id = findMessage(message_id)['channel_id'] u_id = getUidFromToken(token) if user_is_in_channel(u_id, channel_id) is False: raise ValueError_http('User not in channel') if u_id not in message['reacts'][0]['u_ids']: raise ValueError_http(description='Message already unreacted') message['reacts'][0]['u_ids'].remove(u_id) message['reacts'][0]['is_this_user_reacted'] = False print(message)
def user_profile_setname(token, name_first, name_last): validUserT = getUserFromToken(token) if len(name_first) > 50: raise ValueError_http( "Invalid name_first, above the range of 50 characters") if len(name_last) > 50: raise ValueError_http( "Invalid name_last, above the range of 50 characters") if validUserT != None: validUserT['name_first'] = name_first validUserT['name_last'] = name_last return ({})
def message_react(token, message_id, react_id): message = getMessageInfo(message_id) channel_id = findMessage(message_id)['channel_id'] u_id = getUidFromToken(token) #check that user in part of the channel if user_is_in_channel(u_id, channel_id) is False: raise ValueError_http('User not in the channel') #check if message has been reacted if u_id in message['reacts'][0]['u_ids']: raise ValueError_http('Already reacted') message['reacts'][0]['u_ids'].append(u_id) message['reacts'][0]['is_this_user_reacted'] = True
def message_edit(token, message_id, message): # message doesnt exist if messageExists(message_id) is False: raise ValueError_http('Message does not exist') if len(message) > 1000: raise ValueError_http('Message cannot be longer than 1000 characters') channel_id = findMessage(message_id)['channel_id'] # user must be authorized if isAdmin(token, channel_id) is True or message_belong_to_user(token, message_id): getMessageInfo(message_id)['message'] = message else: raise AccessError('User not authorized to edit message') pass
def user_profile_setemail(token, email): data = getData() #'''Email entered is not a valid email''' if not re.match(r"[^@]+@[^@]+\.[^@]+", email): raise ValueError_http("Invalid email") # if getUserByEmail(email) != None: for user in data['users']: if user['email'] == email: raise ValueError_http( "Email address is already being used by another user") found_user = getUserFromToken(token) found_user['email'] = email return ({})
def message_unpin(token, message_id): # user has to be admin message = getMessageInfo(message_id) channel_id = findMessage(message_id)['channel_id'] channel = getChannelDetails(channel_id) u_id = getUidFromToken(token) if u_id not in channel['all_members']: raise AccessError('User is not a member ofo the channel') if isAdmin(token, channel_id) is True and message['is_pinned'] is True: message['is_pinned'] = False elif isAdmin(token, channel_id) is False: raise ValueError_http('User has to be admin to pin') elif message['is_pinned'] is False: raise ValueError_http('Message is already unpinned')
def channels_create(token, name, is_public): global channel_id data = getData() u_id = getUidFromToken(token) # check if length of name <= 20 if len(name) <= 20: # CREATE CHANNEL ID channel_id += 1 channel_dic = { 'channel_id': channel_id, 'name': name, 'is_public': is_public, 'all_members': [u_id], 'owner_members': [u_id], 'messages': [], 'standup_msg': "", 'standup_active': False, 'standup_finish': 0, 'standup_started_by': None } channel_dic2 = {'channel_id': channel_id, 'name': name} data['channel'].append(channel_dic) getUserFromToken(token)['joined_channels'].append(channel_dic2) return {'channel_id': channel_id} else: raise ValueError_http( "The name of the channel cannot be longer than 20 characters")
def channel_addowner(token, channel_id, u_id): data = getData() adder_id = getUidFromToken(token) # check if channel exists channel = getChannelFromChannelId(channel_id) # check if authorized user is an owner of slackr / owner of channel if adder_id not in channel['owner_members']: raise AccessError("You are not authorized to add an owner") # check if user is already an owner of channel / member of channel if u_id in channel['owner_members']: raise ValueError_http("User is already an owner of the channel") # check if user is a member of the channel if u_id not in channel['all_members']: raise ValueError_http("User is not a member of the channel") channel['owner_members'].append(u_id) return ()
def channel_invite(token, channel_id, u_id): data = getData() inviter_id = getUidFromToken(token) # check if u_id refers to a valid user isUidValid(u_id) # check if channel exists channel = getChannelFromChannelId(channel_id) # check if u_id is already in the channel if u_id in channel['all_members']: raise ValueError_http("User is already part of the channel") # # check if user is attempting to invite themself # if inviter_id == u_id: # raise ValueError_http("You are not allowed to invite yourself") # check if authorized user is part of channel if inviter_id not in channel['all_members']: raise AccessError("Authorised user not a member of channel") # check permission of invited user invitee_permission = checkUserPermission(u_id) if invitee_permission == 1 or invitee_permission == 2: channel['owner_members'].append(u_id) channel['all_members'].append(u_id) details_channel = getChannelDetailsSimple(channel_id) getUserFromUid(u_id)['joined_channels'].append(details_channel) return ()
def auth_login(email, password): # check for valid email check_valid_email(email) # check if user exists if userExists(email) == False: raise ValueError_http("User does not exist") login_user = getUserByEmail(email) # check if password entered is corrects if password != login_user['password']: raise ValueError_http("Incorrect password") # generate token for logged in users login_user['token'] = str( jwt.encode({'email': email}, SECRET, algorithm='HS256')) return {'u_id': login_user['u_id'], 'token': login_user['token']}
def getChannelFromMsgId(message_id): data = getData() for channels in data['channel']: for message in channels['messages']: if message_id == message['message_id']: return channels raise ValueError_http("channel not found")
def user_profiles_uploadphoto(token, img_url, x_start, y_start, x_end, y_end): global image_name image_name += 1 filePath = './static/' + str(image_name) + '.jpg' downloadImage(img_url, filePath) #crop image img_obj = Image.open(filePath) width, height = img_obj.size #no input if x_start is None and x_end is None and y_start is None and y_end is None: x_start = 0 x_end = width y_start = 0 y_end = height x_start = int(x_start) y_start = int(y_start) x_end = int(x_end) y_end = int(y_end) #x_start and y_start has to be less than width and hight if x_end > width or y_end > height or x_start >= x_end or y_start >= y_end: raise ValueError_http( f"Crop has to be within the dimension ({width} x {height})") cropped = img_obj.crop((x_start, y_start, x_end, y_end)) #save cropped image filePath_cropped = './static/' + str(image_name) + '_cropped' + '.jpg' #print(final_url) cropped.save(filePath_cropped) final_url = 'http://localhost:' + sys.argv[1] + '/static/' + str( image_name) + '_cropped.jpg' getUserFromToken(token)['profile_img_url'] = final_url
def getMessageInfo(message_id): data = getData() for channel in data['channel']: for message in channel['messages']: if message_id == message['message_id']: return message raise ValueError_http("Message not found")
def message_remove(token, message_id): # message doesnt exist if messageExists(message_id) is False: raise ValueError_http('Message does not exist') channel_id = findMessage(message_id)['channel_id'] # user must be authorized if isAdmin(token, channel_id) is True or message_belong_to_user(token, message_id): channel = findMessage(message_id) channel['messages'].remove(getMessageInfo(message_id)) else: raise AccessError('User not authorized to remove message')
def channel_removeowner(token, channel_id, u_id): data = getData() remover_id = getUidFromToken(token) # check if channel exists channel = getChannelFromChannelId(channel_id) # check if authorized user is an owner of slackr / owner of channel if remover_id not in channel['owner_members']: raise AccessError("You are not authorized to remove an owner") # check if authorized user is the only owner and they are attempting to remove themself if len(channel['owner_members'] ) == 1 and remover_id in channel['owner_members']: raise ValueError_http( "You cannot remove yourself as an owner because you are the only owner" ) # check if user is not an owner of channel if u_id in channel['owner_members']: channel['owner_members'].remove(u_id) return () else: raise ValueError_http("User is not an owner of the channel")
def downloadImage(imageUrl: str, filePath: str): img = sendRequest(imageUrl) if (img == False): raise AccessError("Please enter a valid URL (image has to be .jpg)") if not img.content[:4] == b'\xff\xd8\xff\xe0': raise ValueError_http( "Please enter a valid URL (image has to be .jpg)") urllib.request.urlretrieve(imageUrl, filePath)
def auth_passwordreset_reset(reset_code, new_password): data = getData() # check invalid password if len(new_password) < 6: raise ValueError_http("Invalid password") # check for valid reset code find_email = findResetcodeMatch(reset_code) user = getUserByEmail(find_email) user['password'] = new_password reset_resetCode(find_email) return ()
def standup_send(token, channel_id, message): channel = getChannelFromChannelId(channel_id) if channel['standup_active'] is False: raise ValueError_http('Standup not currently active') #send message normally message_send(token, channel_id, message) #add message to a list msg_with_names = getUserFromToken( token)['handle_str'] + ": " + message + "\n" getChannelFromChannelId(channel_id)['standup_msg'] += msg_with_names
def standup_start(token, channel_id, length): channel = getChannelFromChannelId(channel_id) #check for started standup if channel['standup_active'] is True: raise ValueError_http('Standup has already started') #change standup status to active channel['standup_active'] = True channel['standup_started_by'] = getUidFromToken(token) #store the time finish finish_time = datetime.datetime.now( datetime.timezone.utc).astimezone().timestamp() + length channel['standup_finish'] = finish_time return {'time_finish': finish_time}
def channel_messages(token, channel_id, start): data = getData() u_id = getUidFromToken(token) # check if channel exists channel = getChannelFromChannelId(channel_id) # check if authorized user is a member of channel if u_id not in channel['all_members']: raise AccessError("Authorised User not a member of channel") # check if there are no messages if len(channel['messages']) == 0: return {'messages': [], 'start': start, 'end': start} # check if start < total number of messages if start < len(channel['messages']): if len(channel['messages'][start:]) > 50: end = start + 50 mes = getMessages(u_id, channel['messages'], start, end) else: end = -1 mes = getMessages(u_id, channel['messages'], start, end) return {'messages': mes, 'start': start, 'end': -1} else: raise ValueError_http("Start is greater")
def message_send(token, channel_id, message): global message_id # check for access error (user must be in the channel) if user_is_in_channel(getUidFromToken(token), channel_id) == False: raise AccessError('User not in the channel') if len(message) > 1000: raise ValueError_http("Message cannot be longer than 1000 characters") #if message contains /satndup add to standup dict # add message details channel = getChannelDetails(channel_id) message_id += 1 channel['messages'].insert(0, { 'message_id': message_id, 'u_id': getUidFromToken(token), 'message': message, 'time_created': str(datetime.datetime.now(datetime.timezone.utc).astimezone().timestamp()), #convert to sydney timezone 'reacts': [{'react_id': 1, 'u_ids': [], 'is_this_user_reacted' : False}], 'is_pinned': False }) return {'message_id': message_id}
def getUserByEmail(email): global data for user in data["users"]: if user["email"] == email: return user raise ValueError_http("Email not found")
def getDictFromResetCode(reset_code): data = getData() for dicts in data['resetCode']: if dicts['reset_code'] == reset_code: return dicts raise ValueError_http("Reset_code not found")
def getChannelByChannelName(name): data = getData() for ch in data['channel']: if ch['name'] == name: return ch raise ValueError_http("Channel name not found")
def findResetcodeMatch(reset_code): data = getData() for dicts in data['resetCode']: if dicts['reset_code'] == reset_code: return dicts['email'] raise ValueError_http("Invalid reset_code")
def getUserById(u_id): data = getData() for i in data['users']: if i['u_id'] == u_id: return i raise ValueError_http('User not found')
def checkUserPermission(u_id): data = getData() for user in data['users']: if user['u_id'] == u_id: return user['permission_id'] raise ValueError_http("Invalid user_id")
def isUidValid(u_id): data = getData() for user in data['users']: if user['u_id'] == u_id: return 1 raise ValueError_http("Invalid user_id")