Ejemplo n.º 1
0
def user_profile_sethandle(token, handle_str):
    """Update authorised users handle

    Args:
        token (string)
        handle_str (string)

    Returns:
        (dict): {}
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)

    # Error check: handle_str must be between 3 and 20 characters
    if not validate_handle_str(handle_str):
        raise InputError(
            description=
            "InputError: Handle string must be between 3 and 20 characters (inclusive)"
        )

    # Error check: handle is already used by another user
    if not validate_handle_unique(data, handle_str):
        raise InputError(
            description="InputError: Handle is already used by another user")

    # updating in users list.
    u_id = convert_token_to_u_id(data, token)
    data.set_user_handle(u_id, handle_str)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 2
0
def admin_userpermission_change(token, u_id, permission_id):
    """Given a User by their user ID, set their permissions to new permissions
    described by permission_id

    Args:
        token (string)
        u_id (int)
        permission_id (int)
    """

    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_u_id(data, u_id)


    if permission_id not in (MEMBER, OWNER):
        raise InputError(description="InputError: permission_id does not refer to a value permission")
    
    # Error check: The authorised user is not an owner
    user_id = convert_token_to_u_id(data, token)
    if not validate_flockr_owner(data, user_id):
        raise AccessError(description="AccessError: User is not a flockr owner")

    # Error check (Assumption): First flockr owner cannot have member permissions
    if u_id == data.get_first_owner_u_id() and permission_id == MEMBER:
        raise InputError(description="InputError: First flockr owner cannot be a member")

    data.set_user_permission_id(u_id, permission_id)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 3
0
def channels_list(token):
    """Provide a list of all channels (and their associated details) that the
    authorised user is part of

    Args:
        token (string): unique identifer of user

    Returns:
        (dict): { channels }
    """

    data = pickle.load(open(DATA_FILE, "rb"))

    confirm_token(data, token)

    u_id = convert_token_to_u_id(data, token)
    user_details = data.get_user_details(u_id)

    # Add channels the user is a part of into joined_channels.
    joined_channels = []
    for channel in user_details['channels']:
        joined_channels.append({
            'channel_id': channel['channel_id'],
            'name': channel['name']
        })

    return {'channels': joined_channels}
Ejemplo n.º 4
0
def message_pin(token, message_id):
    """Given a message within a channel, mark it as "pinned" to be given
    special display treatment by the frontend

    Args:
        token (string)
        message_id (int)

    Returns:
        (dict)
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_message_id(data, message_id)

    # Error check: Message with ID message_id is already pinned
    channel_id = data.get_channel_id_with_message_id(message_id)
    channel_messages = data.get_channel_details(channel_id)['messages']
    for curr_message in channel_messages:
        if curr_message['message_id'] == message_id:
            if curr_message['is_pinned']:
                raise InputError(
                    description="InputError: Message is already pinned")

    # Check if user is a flockr owner.
    u_id = convert_token_to_u_id(data, token)
    flockr_owner = validate_u_id_as_flockr_owner(data, u_id)
    channel_member = validate_token_as_channel_member(data, token, channel_id)
    channel_owner = validate_token_as_channel_owner(data, token, channel_id)

    # Error check: The authorised user is not a member of the channel that the message is within
    if not flockr_owner and not channel_member:
        raise AccessError(
            description=
            "AccessError: Authorised user is not a member of the channel \
        that contains the message")

    # Error check: The authorised user is not an owner
    if not flockr_owner and not channel_owner:
        raise AccessError(
            description=
            "AccessError: The authorised user is not an owner of the channel")

    # Pin message (If user is a flockr owner or channel owner).
    for curr_channel in data.get_channels():
        for curr_message in curr_channel['messages']:
            if curr_message['message_id'] == message_id:
                curr_message['is_pinned'] = True

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 5
0
def message_react(token, message_id, react_id):
    """Given a message within a channel the authorised user is part of, add 
    a "react" to that particular message

    Args:
        token (string)
        message_id (int)
        react_id (int)

    Returns:
        (dict): {}
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_message_id(data, message_id)
    confirm_react_id(data, message_id, react_id)

    # Error check: Message with ID message_id already contains an active React
    # with ID react_id from the authorised user
    u_id = convert_token_to_u_id(data, token)
    if validate_active_react_id(data, u_id, message_id, react_id):
        raise InputError(
            description=f"InputError: Message already contains an active react"
        )

    # Error check (Assumption): Flockr member not in channel with message_id
    channel_id = data.get_channel_id_with_message_id(message_id)
    is_member = validate_u_id_as_channel_member(data, u_id, channel_id)
    is_flock_owner = validate_u_id_as_flockr_owner(data, u_id)
    if not is_member and not is_flock_owner:
        raise AccessError(
            description=
            f"AccessError: User is not in the channel that has the message_id {message_id}"
        )

    # unreact all active reacts (based on assumption)
    active_react_ids = data.get_active_react_ids(u_id, message_id)
    if active_react_ids != []:
        for active_react_id in active_react_ids:
            message_unreact(token, message_id, active_react_id)

    # reload to get updated data from message_unreact
    data = pickle.load(open(DATA_FILE, "rb"))

    message = data.get_message_details(channel_id, message_id)
    message['reacts'][react_id - 1]['u_ids'].append(u_id)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 6
0
def message_edit(token, message_id, message):
    """Given a message, update it's text with new text. If the new message is an
    empty string, the message is deleted.

    Args:
        token (string)
        message_id (int)
        message (string)

    Returns:
        (dict): {}
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # remove message if new message is an empty string
    if message == '':
        return message_remove(token, message_id)

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_message_id(data, message_id)

    # Error check: Message is more than 1000 characters or 0 characters
    if len(message) > 1000:
        raise InputError(
            description="InputError: Message has more than 1000 characters")

    # edit the message if user is flockr owner or channel owner or sent by authorized user
    # (Assumption) flockr owner does not need to be a part of the channel to edit message
    u_id = convert_token_to_u_id(data, token)
    channel_id = data.get_channel_id_with_message_id(message_id)
    valid_permission = validate_universal_permission(data, token, channel_id)
    userAuthorized = False
    for channel in data.get_channels():
        for curr_message in channel['messages']:
            if curr_message['message_id'] == message_id:
                if curr_message['u_id'] == u_id or valid_permission:
                    userAuthorized = True
                    data.edit_message(channel_id, message_id, message)

    # Error check: User was not authorised to edit the message
    if not userAuthorized:
        raise AccessError("AccessError: User not authorized to edit message")

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 7
0
def validate_token_as_channel_owner(data, token, channel_id):
    """Returns whether or not the user is an owner of a channel based on the token.

    Args:
        token (string)
        channel_id (int)

    Returns:
        (bool): True if member is an owner in the channel. False otherwise.
    """
    channel_details = data.get_channel_details(channel_id)
    owner_list = list(
        map(lambda owner: owner['u_id'], channel_details['owner_members']))
    u_id = convert_token_to_u_id(data, token)
    if u_id in owner_list:
        return True
    return False
Ejemplo n.º 8
0
def validate_universal_permission(data, token, channel_id):
    """Validates whether user is a flockr owner or channel owner

    Args:
        token (string): unique identifier for authorised user
        channel_data (dictionary): channel information

    Returns:
        (bool): True if either criteria is met. False otherwise.
    """
    authorized = False
    u_id = convert_token_to_u_id(data, token)
    condition_1 = validate_u_id_as_flockr_owner(data, u_id)
    condition_2 = validate_u_id_as_channel_owner(data, u_id, channel_id)
    if condition_1 or condition_2:
        authorized = True
    return authorized
Ejemplo n.º 9
0
def message_unreact(token, message_id, react_id):
    """Given a message within a channel the authorised user is part of, 
    remove a "react" to that particular message

    Args:
        token (string)
        message_id (int)
        react_id (int)

    Returns:
        (dict): {}
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_message_id(data, message_id)
    confirm_react_id(data, message_id, react_id)

    # Error check: Message with ID message_id does not contain an active React with ID react_id
    u_id = convert_token_to_u_id(data, token)
    if not validate_active_react_id(data, u_id, message_id, react_id):
        raise InputError(
            description=
            f"InputError: Message already contains a non-active react")

    # Error check (Assumption): Flockr member not in channel with message_id
    channel_id = data.get_channel_id_with_message_id(message_id)
    is_member = validate_u_id_as_channel_member(data, u_id, channel_id)
    is_flock_owner = validate_u_id_as_flockr_owner(data, u_id)
    if not is_member and not is_flock_owner:
        raise AccessError(
            description=
            f"AccessError: User is not in the channel that has the message_id {message_id}"
        )

    # Otherwise unreact the message with react_id.
    message = data.get_message_details(channel_id, message_id)
    message['reacts'][react_id - 1]['u_ids'].remove(u_id)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 10
0
def user_profile_setname(token, name_first, name_last):
    """Update the authorised user's first and last name

    Args:
        token (string)
        name_first (string)
        name_last (string)

    Returns:
        (dict): {}
    """

    data = pickle.load(open(DATA_FILE, "rb"))
    # Error checks: Basic validation
    confirm_token(data, token)

    # Error check: Name validation
    if not validate_names(name_first):
        raise InputError(
            description=
            "First name must be between 1 to 50 characters long (inclusive)")
    if not validate_names(name_last):
        raise InputError(
            description=
            "Last name must be between 1 to 50 characters long (inclusive)")
    if not validate_names_characters(name_first):
        raise InputError(
            description=
            "First name can only include uppercase and lowercase alphabetical characters, hyphens or whitespaces"
        )
    if not validate_names_characters(name_last):
        raise InputError(
            description=
            "Last name can only include uppercase and lowercase alphabetical characters, hyphens or whitespaces"
        )

    # changing name in the users field
    u_id = convert_token_to_u_id(data, token)
    data.set_user_name(u_id, name_first, name_last)
    data.set_user_name_in_channels(u_id, name_first, name_last)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)
    return {}
Ejemplo n.º 11
0
def channel_leave(token, channel_id):
    """Given a channel ID, the user removed as a member of this channel

    Args:
        token (string)
        channel_id (int)

    Returns:
        (dict): {}
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_channel_id(data, channel_id)

    # Error check: Authorised user is not a member of channel with channel_id
    if not validate_token_as_channel_member(data, token, channel_id):
        raise AccessError(
            description=
            "AccessError: Authorised user is not a member of the channel")

    u_id = convert_token_to_u_id(data, token)
    data.remove_member_from_channel(u_id, channel_id)
    data.remove_owner_from_channel(u_id, channel_id)
    data.delete_channel_from_user_list(u_id, channel_id)
    channel_details = data.get_channel_details(channel_id)

    # Case where all owners have left, assign the oldest member as the new
    # channel owner.
    if len(channel_details['owner_members']) == 0 and len(
            channel_details['all_members']) != 0:
        data.add_owner_to_channel(channel_details['all_members'][0]['u_id'],
                                  channel_id)

    # Case where all members have left, delete channel from database
    if len(channel_details['all_members']) == 0:
        data.delete_channel(channel_id)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 12
0
def channel_join(token, channel_id):
    """Given a channel_id of a channel that the authorised user can join, adds
    them to that channel

    Args:
        token (string)
        channel_id (int)

    Returns:
        (dict): {}
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_channel_id(data, channel_id)

    # Error check (Assumption): Check whether user is a channel member already
    if validate_token_as_channel_member(data, token, channel_id):
        return {}

    # Error check: User cannot join a channel if they are a flockr member and
    # the channel is private
    u_id = convert_token_to_u_id(data, token)
    user = data.get_user_details(u_id)
    channel_details = data.get_channel_details(channel_id)
    if user['permission_id'] == MEMBER and not channel_details['is_public']:
        raise AccessError(
            description=
            "AccessError: Private channel cannot be joined unless user is a flockr owner"
        )

    data.add_member_to_channel(user['u_id'], channel_id)
    data.add_channel_to_user_list(user['u_id'], channel_id)

    # If the user is the flockr owner, make their permissions as a channel owner.
    if user['permission_id'] == OWNER:
        data.add_owner_to_channel(user['u_id'], channel_id)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 13
0
def message_send(token, channel_id, message):
    """Send a message from authorised_user to the channel specified by channel_id

    Args:
        token (string)
        channel_id (int)
        message (string)

    Returns:
        (dict): { message_id }
    """

    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_channel_id(data, channel_id)

    # Error check: Message is more than 1000 characters or 0 characters
    if len(message) > 1000:
        raise InputError(
            description="InputError: Message has more than 1000 characters")
    if len(message) == 0:
        raise InputError(description="InputError: Message is empty")

    # Error check: the authorised user has not joined the channel they are trying to post to
    if not validate_token_as_channel_member(data, token, channel_id):
        raise AccessError(
            description=
            "AccessError: Authorised user is not a member of the channel")

    # Add message to the channel
    message_id = data.generate_message_id()
    u_id = convert_token_to_u_id(data, token)
    data.create_message(u_id, channel_id, message_id, message)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {'message_id': message_id}
Ejemplo n.º 14
0
def channels_create(token, name, is_public):
    """Creates a new channel with that name that is either a public or private channel

    Args:
        token (string)
        name (string)
        is_public (bool)

    Returns:
        (dict): { channel_id }
    """

    data = pickle.load(open(DATA_FILE, "rb"))

    confirm_token(data, token)

    # Error check: Channel name validation
    if len(name) > 20 or len(name) < 1:
        raise InputError(
            description="Channel name must be between 1 to 20 characters")

    # Generate channel_id.
    channel_id = 1
    if len(data.get_channels()) != 0:
        channel_list = data.get_channels()
        channel_id = channel_list[-1]['channel_id'] + 1

    # Create new channel and store it into data structure.
    data.create_channel(name, is_public, channel_id)
    u_id = convert_token_to_u_id(data, token)
    data.add_channel_to_user_list(u_id, channel_id)

    # Add user to created channel as well as making them owner.
    data.add_member_to_channel(u_id, channel_id)
    data.add_owner_to_channel(u_id, channel_id)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {'channel_id': channel_id}
Ejemplo n.º 15
0
def message_remove(token, message_id):
    """Given a message_id for a message, this message is removed from the channel

    Args:
        token (string)
        message_id (int)

    Returns:
        (dict): {}
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)
    confirm_message_id(data, message_id)

    # remove the message if user is flockr owner or channel owner or sent by authorized user
    # (Assumption) flockr owner does not need to be a part of the channel to remove message
    channel_id = data.get_channel_id_with_message_id(message_id)
    u_id = convert_token_to_u_id(data, token)
    valid_permission = validate_universal_permission(data, token, channel_id)
    userAuthorized = False
    for channel in data.get_channels():
        for message in channel['messages']:
            if message['message_id'] == message_id:
                if message['u_id'] == u_id or valid_permission:
                    userAuthorized = True
                    data.remove_message(channel_id, message_id)

    # Error check: User was not authorised to remove the message
    if not userAuthorized:
        raise AccessError(
            description="AccessError: User not authorized to remove message")

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 16
0
def user_profile_setemail(token, email):
    """Update the authorised user's email.

    Args:
        token (string): unique identifier of user.
        email (string): what the email will be set to.

    Returns:
        (dict): Contains no key types.
    """

    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)

    # Make the input email lowercase.
    email = email.lower()

    # Error check: Email validation
    if not validate_create_email(email):
        raise InputError(description="InputError: Invalid email address")
    # Check for whether email is already in use.
    for curr_user in data.get_users():
        if curr_user['email'] == email:
            raise InputError(
                description=
                f"InputError: Email address is already being used by another user"
            )

    u_id = convert_token_to_u_id(data, token)
    data.set_user_email(u_id, email)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}
Ejemplo n.º 17
0
def user_profile_uploadphoto(token, img_url, x_start, y_start, x_end, y_end):
    """Given a URL of an image on the internet, crops the image within bounds (x_start, y_start) and (x_end, y_end). Position (0,0) is the top left.

    Args:
        token (string)
        img_url (string)
        x_start (int)
        y_start (int)
        x_end (int)
        y_end (int)

    Returns:
        (dict): {}
    """
    data = pickle.load(open(DATA_FILE, "rb"))

    # Error checks: Basic validation
    confirm_token(data, token)

    # Error check: img_url returns an HTTP status other than 200.
    try:
        response = requests.get(img_url)
    except:
        raise InputError(
            description="InputError: Image URL cannot be requested")
    if response.status_code != 200:
        raise InputError(
            description=
            "InputError: Image URL returns an HTTP status other than 200")

    # Generate file url path
    img_file_local_path = generate_img_file_path()

    # Error check: check if the image can be download. If can, download it.
    try:
        urllib.request.urlretrieve(img_url, 'src/' + img_file_local_path)
    except:
        raise InputError(
            description="InputError: Image URL cannot be retrieved")

    # Error check: Image uploaded is not a JPG
    if imghdr.what('src/' + img_file_local_path) != "jpeg":
        os.remove('src/' + img_file_local_path)
        raise InputError(description="InputError: Image uploaded is not a JPG")

    # Error check: Check if the x and y dimensions are within bounds
    img_object = Image.open('src/' + img_file_local_path)
    width, height = img_object.size
    if x_start not in range(0, width):
        os.remove('src/' + img_file_local_path)
        raise InputError(description="x_start not in boundary of the image")
    if x_end not in range(0, width + 1):
        os.remove('src/' + img_file_local_path)
        raise InputError(description="x_end not in boundary of the image")
    if y_start not in range(0, height):
        os.remove('src/' + img_file_local_path)
        raise InputError(description="y_start not in boundary of the image")
    if y_end not in range(0, height + 1):
        os.remove('src/' + img_file_local_path)
        raise InputError(description="y_end not in boundary of the image")
    if x_end <= x_start:
        os.remove('src/' + img_file_local_path)
        raise InputError(description="x_end must be greater than x_start")
    if y_end <= y_start:
        os.remove('src/' + img_file_local_path)
        raise InputError(description="y_end must be greater than y_start")

    # Crop the images
    img_object.crop(
        (x_start, y_start, x_end, y_end)).save('src/' + img_file_local_path)

    # Assign image to the user and save it on the server
    u_id = convert_token_to_u_id(data, token)
    try:
        server_img_url = f"{request.url_root}{img_file_local_path}"
    except:
        os.remove('src/' + img_file_local_path)
        raise AccessError(description="Server must be running to upload photo")
    data.set_user_photo(u_id, server_img_url)
    data.set_user_photo_in_channels(u_id, server_img_url)

    with open(DATA_FILE, 'wb') as FILE:
        pickle.dump(data, FILE)

    return {}