Пример #1
0
def test_register():
    ''' Tests auth_register '''
    # check output is returned with correct parameters
    output = auth_register("*****@*****.**", "strong_pw", "regi", "ster")
    assert output == {
        'u_id': token_to_user(output['token']),
        'token': output['token']
    }

    # the following will result in value errors
    with pytest.raises(ValueError):
        # entering an invalid email
        auth_register("BadEmail", "strong_pw", "A", "AA")
        # password is not valid
        auth_register("*****@*****.**", 1235, "A", "AA")
        auth_register("*****@*****.**", "1", "A", "AA")
        # first name > 50 characters
        auth_register("*****@*****.**", "strong_pw", "A" * 51, "AA")
        # last name > 50 characters
        auth_register("*****@*****.**", "strong_pw", "A", "AA" * 51)

    # email address already in use
    with pytest.raises(ValueError):
        auth_register("*****@*****.**", "strong_pw", "regi", "ster")

    reset_data()
    # first user
    output = auth_register("*****@*****.**", "strong_pw", "regi", "ster")
    assert output == {
        'u_id': token_to_user(output['token']),
        'token': output['token']
    }
Пример #2
0
def test_channel_removeowner():
    '''
    Testing cases of channel_removeowner
    '''
    reset_data()
    # START SETUP
    token = auth_register('*****@*****.**', 'pass123', 'john',
                          'apple')['token']
    creator_id = token_to_user(token)
    channel_id_public = channel_create(token, 'newChannel', 'true')
    second_token = auth_register('*****@*****.**', 'pass147', 'vicks',
                                 'uwu')['token']
    second_user_id = token_to_user(second_token)
    third_token = auth_register('*****@*****.**', 'pass134124', 'lol',
                                'lmao')['token']
    third_user_id = token_to_user(third_token)
    fourth_token = auth_register('*****@*****.**', 'pass13424', 'Troye',
                                 'Bob')['token']
    fourth_user_id = token_to_user(fourth_token)
    # END SETUP

    # Trying to remove someone not in the channel
    with pytest.raises(ValueError):
        channel_removeowner(token, channel_id_public, fourth_user_id)

    # Invalid token
    with pytest.raises(AccessError):
        channel_removeowner('invalidToken', channel_id_public, second_user_id)
    # Invalid channel ID
    with pytest.raises(ValueError):
        channel_removeowner(token, 666, third_user_id)

    # User already not an owner
    channel_join(fourth_token, channel_id_public)
    with pytest.raises(ValueError):
        channel_removeowner(token, channel_id_public, fourth_user_id)

    # User is not an admin or owner
    channel_join(second_token, channel_id_public)
    channel_join(third_token, channel_id_public)
    channel_addowner(token, channel_id_public, second_user_id)
    with pytest.raises(AccessError):
        channel_removeowner(third_token, channel_id_public, second_user_id)

    # Attempting to change permission of Slackr creator
    with pytest.raises(AccessError):
        channel_removeowner(second_token, channel_id_public, creator_id)

    # Working removeowner
    channel_join(third_token, channel_id_public)
    channel_addowner(token, channel_id_public, third_user_id)
    channel_removeowner(token, channel_id_public, third_user_id)
Пример #3
0
def test_channel_addowner():
    '''
    The following test's various cases of channel_addowner
    '''
    reset_data()
    # START SETUP
    token = auth_register('*****@*****.**', 'pass123', 'john',
                          'apple')['token']
    creator_id = token_to_user(token)
    channel_id_public = channel_create(token, 'newChannel', 'true')
    second_token = auth_register('*****@*****.**', 'pass147', 'vicks',
                                 'uwu')['token']
    second_user_id = token_to_user(second_token)
    third_token = auth_register('*****@*****.**', 'pass134124', 'lol',
                                'lmao')['token']
    third_user_id = token_to_user(third_token)
    # END SETUP

    # Invalid token
    with pytest.raises(AccessError):
        channel_addowner('invalidToken', channel_id_public, second_user_id)
    # Invalid channel ID
    with pytest.raises(ValueError):
        channel_addowner(token, 666, second_user_id)

    # trying to add when user is not in the channel
    with pytest.raises(ValueError):
        channel_addowner(second_token, channel_id_public, third_user_id)

    # trying to add random channel
    with pytest.raises(ValueError):
        channel_addowner(second_token, 999, third_user_id)

    # User is already an owner
    second_channel_id = channel_create(third_token, 'anotherCHannel', 'true')
    with pytest.raises(ValueError):
        channel_addowner(token, second_channel_id, third_user_id)

    # When user is not an admin or owner
    channel_join(second_token, channel_id_public)
    channel_join(third_token, channel_id_public)
    with pytest.raises(AccessError):
        channel_addowner(second_token, channel_id_public, third_user_id)

    # Attempting to change permission of Slackr creator
    with pytest.raises(AccessError):
        channel_addowner(second_token, channel_id_public, creator_id)

    # Working addowner
    channel_addowner(token, channel_id_public, third_user_id)
Пример #4
0
def admin_userpermission_change(token, u_id, permission_id):
    '''
    This is the function file for admin_userpermission_change
    '''
    # Checks
    curr_user_id = token_to_user(token)
    check_valid_user(curr_user_id)
    check_valid_user(u_id)

    # Ensure that the permission_id is valid
    if permission_id not in [1, 2, 3]:
        raise ValueError('The permission_id is invalid')

    # This block details permissions

    # The owner can do anything:
    if server_data.data['users'][curr_user_id]['permission'] == 1:
        pass
    # cannot target the owner
    elif server_data.data['users'][u_id]['permission'] == 1:
        raise AccessError('Cannot change the owners permission')
    # must be an admin or owner
    elif not is_slackr_admin(curr_user_id):
        raise AccessError('User does not have the correct permissions')
    # target user alreay has the permission_id
    elif server_data.data['users'][u_id]['permission'] == permission_id:
        raise ValueError('The target user already has that permission')
    else:
        pass

    # set the permission
    server_data.data['users'][u_id]['permission'] = permission_id

    return {}
Пример #5
0
def standup_send(token, channel_id, message):
    '''
    Using a valid token, the user sends a message in an active standup in the channel
    '''
    if not channel_exists(channel_id):
        raise ValueError(f"channel does not exist")

    if not standup_exists(channel_id):
        raise ValueError(f"Channel does not have an active standup")

    user_id = token_to_user(token)

    if not check_channel_member(user_id, channel_id):
        raise AccessError(
            f"User is not part of specified channel. Please join the channel.")

    if len(message) > 1000:
        raise ValueError(f"Message cannot be over 1000 characters")

    standups = server_data.standups
    target = get_standup(standups, channel_id)
    messages = target['messages']

    new_message = dict()
    new_message['first_name'] = token_to_firstname(token)
    new_message['message'] = message

    messages.append(dict(new_message))
Пример #6
0
def test_login():
    ''' Tests auth_login '''
    auth_register('*****@*****.**', 'strong_pw', 'vvv', 'wwww')
    # Invalid email
    with pytest.raises(ValueError):
        auth_login("invalidEmail", "strong_pw")

    # Invalid password
    with pytest.raises(ValueError):
        auth_login("*****@*****.**", "incorrectPW")

    # Email does not belong to user
    with pytest.raises(ValueError):
        # logging in for user B should fail
        auth_login("*****@*****.**", "random_pw")
        # logging in with wrong password should fail
        auth_login("*****@*****.**", "wrong_pw")
        # logging in with invalid password should fail
        auth_login("*****@*****.**", "1")

    # logging in with empty strings should fail

    # check output is returned with correct parameters
    output = auth_login("*****@*****.**", "strong_pw")
    assert output == {
        'u_id': token_to_user(output['token']),
        'token': output['token']
    }
Пример #7
0
def channel_leave(token, channel_id):
    '''
    Using a valid token, the user leaves a channel specified by 'channel_id'

    Raises errors if:
    - Channel doesn't exist
    '''
    is_valid_token(token)
    # When channel Id is invalid
    if not channel_exists(channel_id):
        raise ValueError('Channel does not exist')

# Remove user from 'members' list in channel
# get members list (from channel_id)
    members = members_list(channel_id)

    # remove user from members list
    user_id = token_to_user(token)
    for member in members:
        if member['u_id'] == user_id:
            members.remove(member)

# Remove channel from users 'channels' list
    user_info = get_userinfo(user_id)
    user_info['channels'].remove(channel_id)
Пример #8
0
def channel_create(token, name, is_public):
    '''
    The following function creates a channel
    '''

    # tests for name
    is_valid_name(name)

    if is_public == "true":
        public_bool = True
    elif is_public == "false":
        public_bool = False
    else:
        raise ValueError("Is_public must be true or false")

    # generates current user id from token
    curr_user_id = token_to_user(token)

    check_valid_user(curr_user_id)

    # generates a channel_id and assigns it to a variable
    channel_id = server_data.data["n_channels"]

    # appending a dictionary containing channel details into "channels"
    server_data.data["channels"].append({
        "channel_id":
        channel_id,
        "name":
        name,
        "members": [{
            "u_id": curr_user_id,
            "channel_permission": 1
        }],
        "messages": [],
        "is_public":
        public_bool,
        "channel_n_messages":
        0
    })

    # add all slackr owner / admins into the channel
    for user in server_data.data['users']:
        if is_slackr_admin(user['u_id']) and (user['u_id'] != curr_user_id):
            server_data.data['channels'][channel_id]['members'].append({
                "u_id":
                user['u_id'],
                "channel_permission":
                1
            })
            server_data.data['users'][user['u_id']]['channels'].append(
                channel_id)

    # appending a dictionary containing channel details into 'channels' within "users"
    server_data.data['users'][curr_user_id]['channels'].append(channel_id)

    # increasing n_channels by one
    server_data.data["n_channels"] = ((server_data.data["n_channels"]) + 1)

    # returning channel_id
    return channel_id
Пример #9
0
def standup_start(token, channel_id, length):
    '''
    Using a valid token, the user starts a standup period in a channel that they are
    part of
    '''
    if not channel_exists(channel_id):
        raise ValueError(f"channel does not exist")

    if standup_exists(channel_id):
        raise ValueError(f"A standup is already running in this channel")

    curr_user_id = token_to_user(token)

    if not check_channel_member(curr_user_id, int(channel_id)):
        raise AccessError(
            f"User is not part of specified channel. Please join the channel.")

    standups = server_data.standups

    new = dict()
    new['messages'] = []
    new['u_id'] = curr_user_id
    new['channel_id'] = channel_id
    new['time_end'] = int(t.time() + int(length))

    standups.append(new)
    return new['time_end']
Пример #10
0
def channel_invite(token, channel_id, u_id):
    '''
    The following function invites a given user into a given channel
    '''
    # may need to alter this so that only AUTHORISED members can invite others

    # Perform required checks
    check_valid_channel(channel_id)

    curr_user_id = token_to_user(token)

    check_valid_user(curr_user_id)
    check_valid_user(u_id)
    # Check the current user is actually a member of target channel
    if not check_channel_member(curr_user_id, channel_id):
        raise AccessError('User is not part of the target channel')

    # Check the target user is not already a member of target channel
    if check_channel_member(u_id, channel_id):
        raise ValueError(
            'Target user is already a member of the target channel')

    # If it reaches here, all parameters are valid
    # target user becomes a member of the channel
    for channel in server_data.data['channels']:
        if channel['channel_id'] == channel_id:
            channel['members'].append({'u_id': u_id, 'channel_permission': 0})
            break

    # channel is in the user's channel list
    for user in server_data.data['users']:
        if user['u_id'] == u_id:
            user['channels'].append(channel_id)
            break
    return {}
Пример #11
0
def channel_messages(token, channel_id, start):
    '''
    The following function shows up to 50 messages in a given channel
    '''
    # check token
    curr_user_id = token_to_user(token)

    # Check if the user exists
    check_valid_user(curr_user_id)
    check_valid_channel(channel_id)

    cha_data = server_data.data['channels'][channel_id]

    if not check_channel_member(curr_user_id,
                                channel_id) and not cha_data['is_public']:
        raise AccessError('User is not in the target channel. Error code: 1')

    #tests for validity of token, channel_id and start

    # checks if start is valid else raise error
    valid_start(start)
    if start >= (
            server_data.data["channels"][channel_id]["channel_n_messages"]):
        raise ValueError("Start is greater than total number of messages")

    # checks if channel_id is valid else raise error
    channel_id_exists(channel_id)

    return_amount = 49
    messages = []
    actual_start = server_data.data["channels"][channel_id][
        "channel_n_messages"] - start - 1
    counter = actual_start

    if actual_start > return_amount:
        last = actual_start - return_amount
        for counter in range(actual_start, last, -1):
            messages.append(
                server_data.data["channels"][channel_id]["messages"][counter])
        end = start + return_amount

    else:
        end = -1
        while counter > -1:
            messages.append(
                server_data.data["channels"][channel_id]["messages"][counter])
            counter = counter - 1

    # return correct react types
    for msg in messages:
        for react in msg['reacts']:
            if curr_user_id in react['u_ids']:
                react['is_this_user_reacted'] = True
            else:
                react['is_this_user_reacted'] = False

    return {'messages': messages, 'start': start, 'end': end}
Пример #12
0
def user_profile_setname(token, name_first, name_last):
    '''
    Update the authorised user's first and last name
    '''
    is_valid_name(name_first)
    is_valid_name(name_last)
    current_user_id = (token_to_user(token))
    server_data.data['users'][current_user_id]['name_first'] = name_first
    server_data.data['users'][current_user_id]['name_last'] = name_last
    return {}
Пример #13
0
def test_admin_change():
    ''' Tests permission change '''
    reset_data()
    token = auth_register("*****@*****.**", "testpass", "john",
                          "smith")['token']
    owner_id = token_to_user(token)
    second_token = auth_register("*****@*****.**", "testpass", "john",
                                 "smith")['token']
    second_id = token_to_user(second_token)
    third_token = auth_register("*****@*****.**", "testpass",
                                "john", "smith")['token']
    third_id = token_to_user(third_token)

    # Invalid token
    with pytest.raises(AccessError):
        admin_userpermission_change('invalidToken', second_id, 1)

    # Invalid user id
    with pytest.raises(ValueError):
        admin_userpermission_change(token, 123123, 1)

    # Invalid permission_id
    with pytest.raises(ValueError):
        admin_userpermission_change(token, second_id, 42)

    # Owner can do anything
    admin_userpermission_change(token, second_id, 2)

    # Cannot target the owner
    with pytest.raises(AccessError):
        admin_userpermission_change(second_token, owner_id, 2)

    # Not an admin or owner
    admin_userpermission_change(token, second_id, 3)
    with pytest.raises(AccessError):
        admin_userpermission_change(second_token, third_id, 2)
    print(server_data.data)

    # User already has that permission id
    admin_userpermission_change(token, second_id, 2)
    admin_userpermission_change(second_token, third_id, 2)
    with pytest.raises(ValueError):
        admin_userpermission_change(second_token, third_id, 2)
Пример #14
0
def channel_removeowner(token, channel_id, u_id):
    '''
    Using a valid token, remove a users permission as an owner in a specified channel

    Raises errors if:
    - Channel doesn't exist
    - the user is already an not an owner of that channel
    - token's user doesn't have permission to remove owners
    '''
    is_valid_token(token)
    check_valid_user(u_id)

    token_id = token_to_user(token)

    check_valid_user(token_id)
    check_valid_channel(channel_id)

    if not check_channel_member(u_id, channel_id):
        raise ValueError('Target user is not in the channel')

# User is already not an owner of that channel
    if not is_owner(u_id, channel_id):
        raise ValueError('User is already not an owner')

    curr_user_id = token_to_user(token)

    # When user is not an admin or owner, only owners can remove other owners (AccessError)
    if not is_owner(curr_user_id,
                    channel_id) and not is_slackr_admin(curr_user_id):
        raise AccessError('You do not have permission to remove this owner')

    if server_data.data['users'][u_id]['permission'] == 1:
        raise AccessError('Cannot change the permission of Slackr creator')

# Remove user permission as owner
# get members list (from channel_id)
    members = members_list(channel_id)

    # change user permission to '0'
    for member in members:
        if member['u_id'] == u_id:
            member['channel_permission'] = 0
Пример #15
0
def user_profile_sethandle(token, handle_str):
    '''
    Update the authorised user's handle (i.e. display name)
    '''
    current_user_id = token_to_user(token)
    # Check if handle is withint character limit
    if len(handle_str) > 20:
        raise ValueError("Handle exceeds 20 characters")
    if len(handle_str) < 3:
        raise ValueError("Handle must contain at least 3 characters")

    # Update handle
    server_data.data['users'][current_user_id]['handle_str'] = handle_str
    return {}
Пример #16
0
def test_channel_invite():
    '''
    Testing cases of channel_invite
    '''
    reset_data()
    # START SETUP
    token = auth_register('*****@*****.**', 'pass123', 'john',
                          'apple')['token']
    second_token = auth_register('*****@*****.**', 'pass147', 'vicks',
                                 'uwu')['token']
    second_user_id = token_to_user(second_token)
    channel_id_private = channel_create(token, 'privateChannel', 'false')
    channel_id_public = channel_create(token, 'NotPrivate', 'true')
    third_token = auth_register('*****@*****.**', 'pass134124', 'lol',
                                'lmao')['token']
    third_user_id = token_to_user(third_token)
    # END SETUP

    # check if the current user who is inviting is actually part of the target channel
    with pytest.raises(AccessError):
        channel_invite(second_token, channel_id_private, third_user_id)

    # Invalid token
    with pytest.raises(AccessError):
        channel_invite('invalidToken', channel_id_private, second_user_id)

    # Working channel invite
    channel_invite(token, channel_id_private, third_user_id)
    assert check_channel_member(third_user_id, channel_id_private)

    # Inviting user who is already in the channel
    with pytest.raises(AccessError):
        channel_invite(second_token, channel_id_public, third_user_id)

    # Target user already in channel
    with pytest.raises(ValueError):
        channel_invite(token, channel_id_private, third_user_id)
Пример #17
0
def message_unreact(token, message_id, react_id):
    '''
    This function unreacts to a message
    '''

    curr_user_id = token_to_user(token)

    message = get_msg_dict(message_id)
    channel = msg_to_channel(message_id)

    # check if the message_id is valid
    if message_id >= server_data.data["n_messages"]:
        raise ValueError("message_id is invalid")

    is_msg_removed(message_id)

    # check if the user is valid
    check_valid_user(curr_user_id)

    # check if the channel is valid
    check_valid_channel(channel["channel_id"])

    # check if the user is in the channel
    if not check_channel_member(curr_user_id, channel["channel_id"]):
        raise AccessError("User is not a member of the channel")

    # check if the react_id is valid, only 1 in iteration 2
    react_id_list = [1]
    if react_id not in react_id_list:
        raise ValueError("React ID is not valid")

    # check if the message already has the react_id
    # check if the user has reacted to that message

    present_flag = 0
    for react_dict in message['reacts']:
        if react_dict['react_id'] == react_id:
            present_flag = 1
            if curr_user_id in react_dict['u_ids']:
                # the current user has reacted
                react_dict['u_ids'].remove(curr_user_id)
            if len(react_dict['u_ids']) == 0:
                # remove react entirely if no more members
                del react_dict

    if present_flag == 0:
        raise ValueError("Message does not have that react")

    return {}
Пример #18
0
def user_profile_setemail(token, email):
    '''
    Update the authorised user's email address
    '''
    current_user_id = token_to_user(token)

    # Check if valid email
    is_email(email)

    # Check if email is being used by another user
    for user in server_data.data['users']:
        if user['email'] == email:
            raise ValueError("Email address is already being used by another user")
    # Update email
    server_data.data['users'][current_user_id]['email'] = email
    return {}
Пример #19
0
def channels_list(token):
    '''
    The following function creates a channel
    '''
    is_valid_token(token)
    curr_user_id = token_to_user(token)
    channel_list = server_data.data['users'][curr_user_id]['channels']

    full_list = []
    for c_id in channel_list:
        curr_channel = server_data.data['channels'][c_id]
        full_list.append({
            'channel_id': curr_channel['channel_id'],
            'name': curr_channel['name']
        })
    return full_list
Пример #20
0
def channel_details(token, channel_id):
    '''
    The following function gives details about a given channel
    '''
    # check token
    curr_user_id = token_to_user(token)

    # Check if the user exists
    check_valid_user(curr_user_id)
    check_valid_channel(channel_id)

    channel_data = server_data.data['channels'][channel_id]

    if not check_channel_member(curr_user_id,
                                channel_id) and not channel_data['is_public']:
        raise AccessError('User is not in the target private channel')

    # Return channel details

    # format: { name, owner_members, all_members }

    # add owner and all members
    owner_members = []
    all_members = []
    for member in channel_data['members']:
        user = server_data.data['users'][member['u_id']]
        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']
        })
        if member['channel_permission'] == 1:
            owner_members.append({
                'u_id': user['u_id'],
                'name_first': user['name_first'],
                'name_last': user['name_last'],
                'profile_img_url': user['profile_img_url']
            })

    return ({
        'name': channel_data['name'],
        'owner_members': owner_members,
        'all_members': all_members
    })
Пример #21
0
def message_react(token, message_id, react_id):
    '''
    This function reacts to a message
    '''
    curr_user_id = token_to_user(token)

    message = get_msg_dict(message_id)
    channel = msg_to_channel(message_id)

    # check if the message_id is valid
    if message_id >= server_data.data["n_messages"]:
        raise ValueError("message_id is invalid")

    is_msg_removed(message_id)

    # check if the user is valid
    check_valid_user(curr_user_id)

    # check if the channel is valid
    check_valid_channel(channel["channel_id"])

    # check if the user is in the channel
    if not check_channel_member(curr_user_id, channel["channel_id"]):
        raise AccessError("User is not a member of the channel")

    # check if the react_id is valid, only 1 in iteration 2
    react_id_list = [1]
    if react_id not in react_id_list:
        raise ValueError("React ID is not valid")

    # if the message already has the react id
    for react in message["reacts"]:
        if react['react_id'] == react_id:
            # check if the current user has already reacted
            if curr_user_id in react['u_ids']:
                raise ValueError("Message already reacted by current user")
            # react to the message!
            react['u_ids'].append(curr_user_id)
            return {}

    # otherwise, the message has not been reacted too
    message['reacts'].append({'react_id': react_id, 'u_ids': [curr_user_id]})

    return {}
Пример #22
0
def test_add_all_slackr_and_admins():
    '''
    Test adding a user who has slackr admin into the channel
    '''
    # set-up
    # create first user with slackr permission
    token = auth_register('*****@*****.**', 'pass123', 'john',
                          'apple')['token']
    creator_id = token_to_user(token)
    assert is_slackr_admin(creator_id)

    # make another user and make channel
    second_token = auth_register('*****@*****.**', 'pass147', 'vicks',
                                 'uwu')['token']
    channel_id_public = channel_create(second_token, 'newChannel', "true")

    # assert that slackr admin is in the channel
    assert check_channel_member(creator_id, channel_id_public)
    reset_data()
Пример #23
0
def message_sendlater(token, channel_id, message, time_sent):
    '''
    Using a valid token, the user sends a message to a channel that they are part of
    at a specific time in the future
    '''
    if not channel_exists(channel_id):
        raise ValueError(f"channel does not exist")

    if message is None:
        raise ValueError(f"No message")

    if int(time_sent) < t.time():
        raise ValueError(f"Time is in the past")

    is_valid_token(token)

    is_valid_message(message)
    curr_user_id = token_to_user(token)
    check_valid_user(curr_user_id)

    if not check_channel_member(curr_user_id, channel_id):
        raise AccessError(
            f"User is not part of specified channel. Please join the channel.")

    message_id = server_data.data['n_messages']
    server_data.data['n_messages'] += 1

    messages_later = server_data.messages_later

    new_message = dict()
    new_message['message_id'] = message_id
    new_message['u_id'] = curr_user_id
    new_message['message'] = message
    new_message['time_created'] = int(time_sent)
    new_message['channel_id'] = channel_id
    new_message['reacts'] = []
    new_message['is_pinned'] = False

    messages_later.append(dict(new_message))

    return message_id
Пример #24
0
def message_send(token, channel_id, message):
    '''
    Using a valid token, the user sends a message to a channel that they are part of
    '''
    curr_user_id = token_to_user(token)

    check_valid_user(curr_user_id)

    if not channel_exists(channel_id):
        raise ValueError(f"channel does not exist")

    if message is None:
        raise ValueError(f"No message")

    if len(message) > 1000:
        raise ValueError(f"Message cannot be over 1000 characters")

    if not check_channel_member(curr_user_id, channel_id):
        raise AccessError(
            f"User is not part of specified channel. Please join the channel.")

    info = channel_info(channel_id)

    messages = info['messages']
    message_id = server_data.data['n_messages']
    server_data.data['n_messages'] += 1

    new_message = dict()
    new_message['message_id'] = message_id
    new_message['u_id'] = curr_user_id
    new_message['message'] = message
    new_message['time_created'] = int(t.time())
    new_message['reacts'] = []
    new_message['is_pinned'] = False

    server_data.data["channels"][channel_id]["channel_n_messages"] += 1
    messages.append(dict(new_message))

    return message_id
Пример #25
0
def search(token, query_str):
    '''
    Searches for a message
    Generates a list of messages that match the query_str
    '''

    is_valid_message(query_str)
    current_user_id = token_to_user(token)
    # List of matching messages
    matching = []

    #  Add Only list messages from channels user is part of

    # List of channel ids that the user is part of
    list_of_channels = server_data.data['users'][current_user_id]['channels']

    for channel_id in list_of_channels:
        for message in server_data.data['channels'][channel_id]['messages']:
            if query_str in message['message']:
                matching.append(message)

    return {'messages': matching}
Пример #26
0
def message_edit(token, message_id, message):
    '''
    The following function edits a message
    '''

    curr_user_id = token_to_user(token)
    check_valid_user(curr_user_id)

    # if message too long / not a string
    is_valid_message(message)
    message_dict = get_msg_dict(message_id)

    # check if the message exists
    is_msg_removed(message_id)

    # Check if message is the same
    msg_str = (get_msg_dict(message_id))['message']
    if msg_str == message:
        raise ValueError(f"Message is the same")

    channel = msg_to_channel(message_id)
    check_channel_member(curr_user_id, channel['channel_id'])

    if message_dict['u_id'] == curr_user_id:
        pass
    elif is_slackr_admin(curr_user_id):
        pass
    elif is_owner(curr_user_id, channel['channel_id']):
        pass
    else:
        raise AccessError('User does not have the right permission')

    if message == "":
        message_remove(token, message_id)
    else:
        message_dict['message'] = message

    return {}
Пример #27
0
def message_pin(token, message_id):
    '''
    The following function pins a message
    '''

    curr_user_id = token_to_user(token)

    message = get_msg_dict(message_id)
    channel = msg_to_channel(message_id)

    # check if the message_id is valid
    if message_id >= server_data.data["n_messages"]:
        raise ValueError("message_id is invalid")

    is_msg_removed(int(message_id))

    # check if the user is valid
    check_valid_user(curr_user_id)

    # check if the channel is valid
    check_valid_channel(channel["channel_id"])

    # check if the user is in the channel
    if not check_channel_member(curr_user_id, channel["channel_id"]):
        raise AccessError("User is not a member of the channel")

    # User must be a admin of either the channel or slackr
    check_permission = server_data.data["users"][curr_user_id]["permission"]
    check_isowner = is_owner(curr_user_id, channel["channel_id"])
    if (not check_isowner) and check_permission == 3:
        raise ValueError("User is not authorised for this action")

    # check if the message is already pinned
    if message["is_pinned"]:
        raise ValueError("Message is already pinned")

    message["is_pinned"] = True
    return {}
Пример #28
0
def user_profiles_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.
    '''

    curr_user_id = token_to_user(token)
    check_valid_user(curr_user_id)

    # checks if img_url is valid
    is_valid_url(img_url)

    # retrieving the url
    filepath = './static/' + token + '.jpg'
    urllib.request.urlretrieve(img_url, filepath)

    # opening the file for cropping
    Image.open(filepath).convert('RGB').save(filepath)
    img = Image.open(filepath)

    # crop length must be withing dimensions of the image
    width, height = img.size

    if (x_start < 0 or y_start < 0 or x_end > width or y_end > height):
        raise ValueError(
            "x_start, y_start, x_end and y_end must be within the dimensions of the image"
        )

    if (x_start > x_end or y_start > y_end):
        raise ValueError("x_start and y_start must be smaller than x_end and y_end respectively")

    # cropping image
    cropped = img.crop((x_start, y_start, x_end, y_end))
    cropped.save(filepath)

    return {}
Пример #29
0
def message_remove(token, message_id):
    '''
    The following function removes a message @@ can change to remove completely
    '''

    curr_user_id = token_to_user(token)
    check_valid_user(curr_user_id)

    message = get_msg_dict(message_id)

    # check if the message exists
    is_msg_removed(message_id)

    channel = msg_to_channel(message_id)
    check_channel_member(curr_user_id, channel['channel_id'])

    # if the message was sent by the user
    if message['u_id'] == curr_user_id:
        pass
    # if the current user is a owner of the channel
    elif is_slackr_admin(curr_user_id):
        pass
    elif is_owner(curr_user_id, channel['channel_id']):
        pass
    else:
        raise AccessError('User does not have the right permission')

    # decrease the channel_n_messages and n_messages
    channel["channel_n_messages"] -= 1

    # deleting message
    for i in range(len(channel['messages'])):
        if channel['messages'][i]['message_id'] == int(message_id):
            del channel['messages'][i]
            break

    return {}
Пример #30
0
def channel_addowner(token, channel_id, u_id):
    '''
    Using a valid token, add a user specified by 'u_id' as an owner of a specific channel

    Raises errors if:
    - Channel doesn't exist
    - the user is already an owner of that channel
    - token's user doesn't have permission to assign owners
    '''
    is_valid_token(token)
    check_valid_user(u_id)

    token_id = token_to_user(token)

    check_valid_user(token_id)
    check_valid_channel(channel_id)

    if not check_channel_member(u_id, channel_id):
        raise ValueError('Target user is not in the channel')

# When user is not an admin or owner, only owners can add other owners (AccessError)
    if not is_owner(token_id, channel_id) and not is_slackr_admin(token_id):
        raise AccessError('You do not have permission to assign an owner')

# User is already an owner of that channel
    if is_owner(u_id, channel_id):
        raise ValueError('User is already an owner')

# Change user permission to owner
# get members list (from channel_id)
    members = members_list(channel_id)

    # change user permission to '1'
    for member in members:
        if member['u_id'] == u_id:
            member['channel_permission'] = 1