def standup_send(token, channel_id, message): registeredUsersDB = get_global_registeredUsers() loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() email = token_to_email(token) if not is_loggedIn(loggedInUsersDB, email): raise AccessError(description="Unauthorised Access") channel_id = int(channel_id) channel = getChannel(channelsDB, channel_id) u_id = token_to_u_ID(loggedInUsersDB, token) if not channel['is_standup_running']: raise ValueError(description="No standup is running") if len(message) > 1000: raise ValueError(description="Message too long") if not is_inChannel(channelsDB,channel_id, u_id): raise AccessError(description='You must be in a channel to send a standup') handle = get_user_handle(registeredUsersDB, u_id) message = handle + ' : ' + message +'\n' for standup in channel['standups']: if standup['isActive']: standup['messages'] += message return {}
def message_send_later(token, channel_id, message, time_to_send): messageQueue = get_global_messageQueue() time_to_send = float(time_to_send) time_to_send = int(time_to_send) if len(message) > 1000: raise ValueError(description="Message too long") loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() messageQueue = get_global_messageQueue() channel_id = int(channel_id) u_id = token_to_u_ID(loggedInUsersDB, token) if not is_inChannel( channelsDB=channelsDB, u_id=u_id, channel_id=channel_id): raise AccessError( description='You must join the channel to send a message!') timeNow = (datetime.datetime.utcnow() - datetime.timedelta(seconds=1)).replace( tzinfo=timezone.utc).timestamp() if time_to_send < timeNow: raise ValueError(description='You selected a time in the past!') length = len(messageQueue) + 1 msgElement = create_message_later(u_id, message, time_to_send, channel_id) messageQueue.append(msgElement) # This is just temporary; it will get updated once the message actually sends return {'message_id': length}
def add_member_to_owner(channelDatabaseListDict, ownerU_ID, u_id, channel_id): ownerU_ID = int(ownerU_ID) u_id = int(u_id) channel_id = int(channel_id) for channel in channelDatabaseListDict: if channel['channel_id'] == channel_id: flag = False for owner in channel['owner_members']: if u_id == owner['u_id']: raise ValueError( description="User already an owner of channel") if ownerU_ID == owner['u_id']: flag = True if flag: for member in channel['other_members']: if u_id == member['u_id']: channel['owner_members'].append(member) channel['other_members'].remove(member) return else: raise ValueError( description=f'You cannot promote the uer {u_id} as an owner' )
def check_valid_email(email): if type(email) != str: raise TypeError(description="Email not a string") atIndex = 0 isAt = False isZID = False # check until '@' in email for character in email: if character == '@': isAt = True break atIndex = atIndex + 1 # if '@' doesnt exist if not isAt: raise ValueError(description="Error; not a valid email") # check if the doimain is correct if email[atIndex:] == "@unsw.edu.au": # is a Z ID isZID = True else: raise ValueError(description="Not a valid UNSW email") if isZID: # too long zID if len(email[:atIndex]) != 8: raise ValueError(description="Not a valid ZID") # does not start with z if not (email[0] == 'z' or email[0] == 'Z'): raise ValueError(description="Not a valid ZID") # check if all following characters are numbers for char in email[1:atIndex]: if not char.isdigit(): raise ValueError(description="Not a valid ZID")
def message_unreact(token, message_id, react_id): loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() message_id = int(message_id) react_id = int(react_id) check_reaction(react_id) u_id = token_to_u_ID(loggedInUsersDB, token) channel = get_channel(channelsDB, message_id) if not is_inChannel(channelsDB=channelsDB, u_id=u_id, channel_id=channel['channel_id']): raise AccessError( description='You must be in the channel to unreact to a message!') for message in channel['messagesListDict']: if message['message_id'] == message_id: for reaction in message['reacts']: if reaction['react_id'] == react_id: if u_id in reaction['u_ids']: reaction['u_ids'].remove(u_id) reaction['is_this_user_reacted'] = False for userID in reaction['u_ids']: if get_user_permission(userID) < 2: reaction['is_this_user_reacted'] = True return else: raise ValueError( description='You cant unreact a unreacted message!' ) raise ValueError("Error unreacting")
def admin_permission_change(token, u_id, permission_id): if permission_id > MEMBER() or permission_id < OWNER(): raise ValueError(description="Invalid Permission ID") registeredUsersDB = get_global_registeredUsers() channelsDB = get_global_existingChannels() appointerID = token_to_u_ID(registeredUsersDB, token) appointerID = int(appointerID) u_id = int(u_id) permission_id = int(permission_id) appointerPID = get_user_permission(appointerID) u_PID = get_user_permission(u_id) if appointerPID > permission_id: raise ValueError(description="You are not permitted to change a user to higher permission!") if appointerPID > u_PID: raise ValueError(description="You cannot change a permission of a user with higher permission than you") registeredUsersDB = get_global_registeredUsers() for user in registeredUsersDB: if user['u_id'] == u_id: user['permission_id'] = permission_id promote_to_owner_all_channels(channelsDB, u_id) save_registered_users() return {} raise ValueError(description=f"User with the user id {u_id} not found")
def check_valid_handle(databaseListDict, handle_str): if len(handle_str) > 21: raise ValueError(description='Handle too long') elif len(handle_str) < 2: raise ValueError(description='Handle too short') else: for user in databaseListDict: if user['handle_str'] == handle_str: raise ValueError(description='Existing handle string')
def crop_image(photo, x_start, y_start, x_end, y_end): image = Image.open(photo) width, height = image.size if x_start == x_end or y_start == y_end: raise ValueError('Invalid crop size!') elif x_start >= width or x_start < 0 or x_end >= width or x_end < 0: raise ValueError('Invalid crop size!') elif y_start >= width or y_start < 0 or y_end >= width or y_end < 0: raise ValueError('Invalid crop size!') return image.crop((x_start,y_start,x_end, y_end))
def get_registered_user(dataBaseListDict, email, password): is_found = False for user in dataBaseListDict: if user['email'] == email: if user['password'] == password: is_found = True return user else: raise ValueError(description="Wrong password") if not is_found: raise ValueError(description="User Does Not Exist")
def check_valid_password(password): if type(password) != str: raise TypeError("Password not a string") if len(password) < 4: raise ValueError(description="Invalid password; to little characters") if password == "abcde": raise ValueError( description="Invalid password; enter a harder password") if password == '12345': raise ValueError( description="Invalid password; enter a harder password") if password == "password" or password == "iloveyou" or password == "123456": raise ValueError( description="Invalid password; enter a harder password")
def channel_delete(token, channel_id): loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() email = token_to_email(token) if not is_loggedIn(loggedInUsersDB, email): raise AccessError( description="You must be in a channel to delete a channel!") u_id = token_to_u_ID(loggedInUsersDB, token) u_id = int(u_id) channel_id = int(channel_id) if not is_inChannel( u_id=u_id, channel_id=channel_id, channelsDB=channelsDB): raise AccessError( description='You must be in the channel to delete a channel!') for channel in channelsDB: if channel['channel_id'] == channel_id: for owner in channel['owner_members']: if u_id == owner['u_id']: channelsDB.remove(channel) save_channel() return {} raise ValueError(description='You must be an owner to delete the channel!')
def add_to_channel(channelDatabaseListDict, ownerU_ID, nonMemberU_ID, channel_id): loggedInUsersDB = get_global_loggedInUsers() nonMemberU_ID = int(nonMemberU_ID) channel_id = int(channel_id) ownerU_ID = int(ownerU_ID) firstName = get_firstName(nonMemberU_ID) lastName = get_lastName(nonMemberU_ID) profile_img_url = get_url(nonMemberU_ID) nonMemberP_ID = get_user_permission(nonMemberU_ID) if not is_inChannel(channelDatabaseListDict, channel_id, ownerU_ID): raise AccessError( description='You must be in the channel to invite other members') if nonMemberP_ID < MEMBER(): temp = join_special(channelDatabaseListDict, channel_id, nonMemberU_ID, firstName, lastName, profile_img_url) return else: temp = join_nonSpecial(channelDatabaseListDict, channel_id, nonMemberU_ID, firstName, lastName, profile_img_url) return raise ValueError(description="Unauthorised Access")
def get_channel_details(channelDatabaseListDict, u_id, channel_id): u_id = int(u_id) channel_id = int(channel_id) pID = get_user_permission(u_id) for channel in channelDatabaseListDict: if matching_channel_id_and_public(channel, channel_id): details = channel details['all_members'] = channel['owner_members'] + channel[ 'other_members'] return details elif matching_channel_id_and_private(channel, channel_id): if pID < MEMBER(): details = channel details['all_members'] = channel['owner_members'] + channel[ 'other_members'] return details else: for owner in channel['owner_members']: if owner['u_id'] == u_id: details = channel details['all_members'] = channel[ 'owner_members'] + channel['other_members'] return details for member in channel['other_members']: if member['u_id'] == u_id: details = channel details['all_members'] = channel[ 'owner_members'] + channel['other_members'] return details raise ValueError(description='You cannot view this channel!')
def get_channel(channelDB, message_id): for channel in channelDB: for message in channel['messagesListDict']: if message['message_id'] == message_id: return channel raise ValueError(description=f"Message with {message_id} does not exist")
def channel_join(token, channel_id): registeredUsersDB = get_global_registeredUsers() loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() email = token_to_email(token) if not is_loggedIn(loggedInUsersDB, email): raise AccessError( description="you must be logged in to join of a channel!") # CHECK THE VALIDITY u_id = token_to_u_ID(loggedInUsersDB, token) u_id = int(u_id) channel_id = int(channel_id) first_name = get_firstName(u_id) last_name = get_lastName(u_id) profile_img_url = get_url(u_id) permission = get_user_permission(u_id) if permission < MEMBER(): return join_special(channelsDB, channel_id, u_id, first_name, last_name, profile_img_url) else: return join_nonSpecial(channelsDB, channel_id, u_id, first_name, last_name, profile_img_url) raise ValueError(description="Invalid Channel ID")
def unpin_message(channel, message_id): for message in channel['messagesListDict']: if message['message_id'] == message_id: if not message['is_pinned']: raise ValueError(description="Message already unpinned") else: message['is_pinned'] = False return {}
def true_or_false(boolean): boolean = boolean.upper() if boolean == "TRUE": return True else: return False raise ValueError( description='Please choose if the channel is public or private')
def load_registered_users(): global registeredUsersDB if os.path.exists('registered_users.p'): try: registeredUsersDB = pickle.load(open("registered_users.p", "rb")) # alternative way return registeredUsersDB except: raise ValueError(description='Please refresh the page') else: return []
def load_channels(): global channelsDB if os.path.exists('channels.p'): try: channelsDB = pickle.load(open("channels.p", "rb")) # alternative way return channelsDB except: raise ValueError(description='Please refresh the page') else: return []
def update_email(databaseListDict, u_id, email): u_id = int(u_id) for user in databaseListDict: if user['email'] == email: raise ValueError(description='this email is already taken!') for user in databaseListDict: if user['u_id'] == u_id: user['email'] = email return
def load_message_id(): global message_id if os.path.exists('message_id.p'): try: message_id = pickle.load(open("message_id.p", "rb")) # alternative way return message_id except: raise ValueError(description='Please refresh the page') else: return 0
def message_edit(token, message_id, editMessage): loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() message_id = int(message_id) if len(editMessage) > 1000: raise ValueError(description="Message too long") u_id = token_to_u_ID(loggedInUsersDB, token) channel = get_channel(channelsDB, message_id) if not is_inChannel(channelsDB=channelsDB, u_id=u_id, channel_id=channel['channel_id']): raise AccessError( description='You must be in the channel to edit a message!') for message in channel['messagesListDict']: if message['message_id'] == message_id: if message['u_id'] == u_id: if editMessage.isspace(): message_remove(token, message_id) else: message['message'] = editMessage return {} else: for owner in channel['owner_members']: if u_id == owner['u_id']: if editMessage.isspace(): message_remove(token, message_id) else: message['message'] = editMessage return {} raise AccessError( description= "You did not write this message. You need to be an owner of the channel to edit a message you did not write!" ) raise ValueError(description="Error editting")
def remove_owner(channelDatabaseListDict, userRemoving, userToBeRemoved, channel_id): userRemoving = int(userRemoving) userToBeRemoved = int(userToBeRemoved) channel_id = int(channel_id) userRemoving_PID = get_user_permission(userRemoving) userToBeRemoved_PID = get_user_permission(userToBeRemoved) if userRemoving == userToBeRemoved: raise ValueError(description='You cant remove yourself!') if userRemoving_PID > userToBeRemoved_PID: # ACCESS ERROR raise AccessError( description="You cannot remove a user with higher permission ") for channel in channelDatabaseListDict: if channel['channel_id'] == channel_id: for member in channel['other_members']: if userRemoving == member['u_id']: raise AccessError(description="You are not an owner") if userToBeRemoved == member['u_id']: raise AccessError(description='User is not an owner') found = False for owner in channel['owner_members']: if owner['u_id'] == userRemoving: found = True if not found: raise ValueError( description="You must be an owner to remove an owner") for owner in channel['owner_members']: if owner['u_id'] == userToBeRemoved: channel['other_members'].append(owner) channel['owner_members'].remove(owner) return
def auth_passwordreset_reset(code, password): registeredUsersDB = get_global_registeredUsers() check_valid_reset_code(code) check_valid_password(password) for user in registeredUsersDB: if user['reset_code'] == code: user['password'] = hashPassword(password) user['reset_code'] = None save_registered_users() return {} raise ValueError(description="Please try again")
def message_send(token, channel_id, message, time_sent): if len(message) > 1000: raise ValueError(description="Message too long") loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() channel_id = int(channel_id) u_id = token_to_u_ID(loggedInUsersDB, token) if not is_inChannel( channelsDB=channelsDB, u_id=u_id, channel_id=channel_id): raise AccessError( description='You must join the channel to send a message!') return send_message_help(u_id, channel_id, message, time_sent)
def user_profiles_uploadphoto(token, img_url, x_start, y_start, x_end, y_end, base): channelsDB = get_global_existingChannels() loggedInUsersDB = get_global_loggedInUsers() registeredUsersDB = get_global_registeredUsers() email = token_to_email(token) u_id = token_to_u_ID(registeredUsersDB, token) u_id = int(u_id) if not base: try: update_profile_photo(registeredUsersDB, channelsDB, u_id, img_url) return update_online_profile_photo(loggedInUsersDB, u_id, img_url) except: raise AccessError(description="Error uploading the photo") base = str(base) x_start = int(x_start) y_start = int(y_start) x_end = int(x_end) y_end = int(y_end) if not is_loggedIn(loggedInUsersDB, email): raise AccessError("You must be logged in to change your photo") try: request.urlopen(img_url) except: raise ValueError( description="Cannot open image URL. Please try other images") request.urlretrieve(img_url, f'frontend/prebundle/images/{u_id}.jpg') crop_image(f'frontend/prebundle/images/{u_id}.jpg', x_start, y_start, x_end, y_end).save(f'frontend/prebundle/images/cropped_{u_id}.jpg') port = base[-5:-1] port = int(port) port += 3000 string = 'http://localhost:' + str(port) + '/' local_url = string + f'images/cropped_{u_id}.jpg' #adding port and http to match the localhost'port' print(local_url, '\n\n\n\n\n\n\n\n\n\n\n') # UNTIL HERE ONLYhttp://localhost # DONT TOUCH THE CODE BELOW try: update_profile_photo(registeredUsersDB, channelsDB, u_id, local_url) return update_online_profile_photo(loggedInUsersDB, u_id, local_url) except: raise AccessError(description="Error uploading the photo")
def auth_register(email, password, firstName, lastName): registeredUsersDB = load_user() loggedInUsersDB = get_global_loggedInUsers() check_valid_name(firstName) check_valid_name(lastName) check_valid_email(email) check_valid_password(password) # Converts the passed name into a propoer name # -- starting with a capital letter followed by small letters firstName = convert_legible_name(firstName) lastName = convert_legible_name(lastName) if is_already_registered(registeredUsersDB, email): raise ValueError(description='Email taken by another user') userHandle = generateUserHandle(registeredUsersDB, firstName, lastName) password = hashPassword(password) u_id = generateU_ID(userHandle) permission_id = generate_permission_id(email) # Generate a dictionary with the set values # and also set some required fields to none if not passed in registeredDictionary = generate_empty_user(handle=userHandle, email=email, password=password, u_id=u_id, first_name=firstName, last_name=lastName, permission_id=permission_id) registeredUsersDB.append(registeredDictionary) # Dictionary of email and password for token generation -- think of it as 'payload' userDictionary = generateUserDictionary(email, password) token = generateToken(userDictionary) # The user registered is now logged in loggedInUsersDB.append(registeredDictionary) save_registered_users() return {'u_id': u_id, 'token': token}
def channel_messages(token, channel_id, start): registeredUsersDB = get_global_registeredUsers() loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() start = int(start) end = start + PAGINATION() channel_id = int(channel_id) email = token_to_email(token) if not is_loggedIn(loggedInUsersDB, email): raise AccessError( description= "You must be logged in to view the messages of a channel!") u_id = token_to_u_ID(loggedInUsersDB, token) channel = getChannel(channelsDB, channel_id) messagesLength = len(channel['messagesListDict']) if messagesLength < start: raise ValueError(description="Starting message too big") returnDictionary = {'messages': []} if messagesLength < end: returnDictionary['end'] = -1 returnDictionary['start'] = start else: returnDictionary['end'] = end returnDictionary['start'] = start for message in channel['messagesListDict']: if start == end: break returnDictionary['messages'].append(message) start += 1 save_channel() return returnDictionary
def standup_start(token, channel_id, length): registeredUsersDB = get_global_registeredUsers() loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() email = token_to_email(token) if not is_loggedIn(loggedInUsersDB, email): raise AccessError(description="You should be logged in to start a standup") channel_id = int(channel_id) channel = getChannel(channelsDB, channel_id) u_id = token_to_u_ID(loggedInUsersDB, token) if channel['is_standup_running']: raise ValueError("Another standup is currently running") # Only owner of the channel can start a standup found = False for owner in channel['owner_members']: if owner['u_id'] == u_id: found = True if not found: raise AccessError(description='You must be an owner of a channel to start a standup') now = datetime.datetime.utcnow() time_start = int(now.replace(tzinfo=timezone.utc).timestamp()) time_end = int(time_start + int(length)) tempDict = {} tempDict['u_id'] = u_id tempDict['isActive'] = True tempDict['time_start'] = time_start tempDict['time_end'] = time_end tempDict['messages'] = '' channel['is_standup_running'] = True channel['standups'].append(tempDict) return {'time_finish': time_end}
def channel_invite(token, channel_id, u_id): registeredUsersDB = get_global_registeredUsers() loggedInUsersDB = get_global_loggedInUsers() channelsDB = get_global_existingChannels() email = token_to_email(token) u_id = int(u_id) if not is_loggedIn(loggedInUsersDB, email): raise AccessError( description="You must be logged in invite a friend into a channel!" ) if not is_already_registered(registeredUsersDB, email): raise ValueError(description=f"User with ID {u_id} does not exist") ownerU_ID = token_to_u_ID(loggedInUsersDB, token) ownerU_ID = int(ownerU_ID) channel_id = int(channel_id) add_to_channel(channelsDB, ownerU_ID, u_id, channel_id) save_channel() return {}