Exemple #1
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 {}
Exemple #2
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
Exemple #3
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 {}
Exemple #4
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}
Exemple #5
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 {}
Exemple #6
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
    })
Exemple #7
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 {}
Exemple #8
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
Exemple #9
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
Exemple #10
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
Exemple #11
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 {}
Exemple #12
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 {}
Exemple #13
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 {}
Exemple #14
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 {}
Exemple #15
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