Exemplo n.º 1
0
def standup_send(token, channel_id, message):
    c = find_channel(channel_id)
    if c is None:  #  invalid channel_id.
        raise InputError(description='invalid channel_id')

    now = datetime.datetime.utcnow()
    timestamp = int(now.replace(tzinfo=datetime.timezone.utc).timestamp()
                    )  #  no no active standup is runing in the given channel
    diff = time_difference(c['standup']['finish_time'], timestamp)
    if diff <= 0:
        raise InputError(
            description='No active standup is runing in this channel')

    if len(message) > 1000:  #message is more than 1000 characters
        raise InputError(description='Message is more than 1000 characters')

    u1_id = token_into_user_id(token)  #the user is not a member of the channel
    l = []
    for i in c['all_members']:
        l.append(i['u_id'])
    if u1_id not in l:
        raise AccessError(
            description='The authorised user is not a member of the channel')

    u_fname = token_into_name(token)
    mess_send = u_fname + ': ' + message + '\n'  #in the form like "Steve: I like soft candy"
    data.message_package_add(channel_id, mess_send)

    return {}
Exemplo n.º 2
0
def auth_login(email, password):
    """Used to log user into program."""

    # check if email is valid.
    regex_email_check(email)

    # Check if email is used by user.
    focus_user = check_in_users('email', data.return_users(), email)

    # If not stored, raise an error.
    if focus_user is None:
        raise InputError('Email is not for a registered user')

    # Check password is correct
    if focus_user['password'] != hash_(password):
        raise InputError('Incorrect Password')

    # Creates a token
    u_id = focus_user['u_id']
    session_secret = create_secret(50)
    token = create_token(u_id, session_secret)

    # update the session_secret in stored users
    data.update_user(u_id, 'session_secret', session_secret)

    token_object = {
        'u_id': u_id,
        'token': token,
    }

    return token_object
Exemplo n.º 3
0
def user_profile(token, u_id):
    """For a valid user, returns information about their user_id, email, first name, last name, and handle.

    Raises:
        1. InputError
            - User with u_id is not a valid user
    """
    person = decode_token(token)
    if person is None:
        return {'is_success': False}
    # Avoid someone put a string
    try:
        u_id = int(u_id)
    except Exception as e:
        raise InputError('terrible uid') from e
    user = None

    for i in data.return_users():
        if i['u_id'] == u_id:
            user = i

    if user is None:
        raise InputError('not user')

    return {
        'user': {
            'u_id': u_id,
            'email': user['email'],
            'name_first': user['name_first'],
            'name_last': user['name_last'],
            'handle_str': user['handle_str'],
            'profile_img_url': '',
        },
    }
Exemplo n.º 4
0
def user_profile_setname(token, name_first, name_last):
    """Update the authorised user's first and last name.

    Raises:
        1. InputError
            - name_first is not between 1 and 50 characters inclusively in length
            - name_last is not between 1 and 50 characters inclusively in length
    """
    # decode the token
    person = decode_token(token)
    if person is None:
        return {'is_success': False}
    email = person.get('email')

    # Check first name matches requirements.
    if len(name_first) < 1 or len(name_first) > 50:
        raise InputError('invalid first name')

    # Check Last Name matches requirements.
    if len(name_last) < 1 or len(name_last) > 50:
        raise InputError('invalid last name')
    user=check_in_users("email",data.return_users(),email)
    user['name_first']=name_first
    user['name_last']=name_last
    data.updateByEmail(user,email)
    return {}
Exemplo n.º 5
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: the token of the people who edit it.
        channel_id: the channel which is the target of message.
        message_id: the specific message.
        react_id: the react_id is always 1 for thumbs up
    RETURNS:
        {}

    THEREFORE, TEST EVERYTHING BELOW:
    1. InputError
      - Message_id is not a valid message within a channel that the authorised user has joined.
      - react_id is not a valid React ID. The only valid react ID the frontend has is 1.
      - Message with ID message_id does not contain an active React with ID react_id.
    """
    auth_id = token_into_user_id(token)
    if auth_id == -1:
        raise InputError(description='invalid token.')

    if react_id != 1:
        raise InputError(description='invalid react_id.')

    # AccessError 3: invalid channel_id.
    message_got = find_message(message_id)
    if message_got is None:
        raise InputError(description='invalid message_id.')

    if not find_one_in_message(message_got, auth_id):
        raise AccessError(description='the auth already exist.')

    edit_msg_react_in_list(message_got, auth_id, 'delete')
    return {}
Exemplo n.º 6
0
def channel_messages(token, channel_id, start):
    """Return 50 messages between `start` and `start + 50`.

    Args:
        token: the token of authorised user.
        channel_id: the id of channel we need info.
        start: the message we want to grab next 50 messages.

    Returns:
        -1: for no more message after start.
        50:
            1. exist messages after start and no more than 50 messages.
            2. the exist messages after start more than 50, just return the top 50 ones.
        { messages, start, end }

    Raises:
        1. InputError
            - the channel id is invalid;
            - start is greater than the total number of messages in the channel.
        2. AccessError
            - the authorised user is not in this channel.
    """
    end = -1

    auth_id = token_into_user_id(token)  # InputError 1: invalid token.
    if auth_id == -1:
        raise InputError('invalid token')

    channel_got = find_channel(channel_id)  # InputError 2: invalid channel_id.
    if channel_got is None:
        raise InputError('onvalid channel_id')

    if not find_one_in_channel(channel_got, auth_id):
        raise InputError('the auth is not in channel'
                         )  # AccessError 3: if the auth not in channel.

    num_msgs = len(channel_got['message'])
    if num_msgs < start:  # InputError 4: the start >= total messages.
        raise InputError(' the start >= total messages')

    return_msg = []  # Case 6: messages is more than 50, get top.
    if num_msgs > (start + 50):
        return_msg = channel_got['message'][start:start + 51]
        end = start + 50
    else:  # Case 7: Get all messages which in (0, 50].
        return_msg = channel_got['message'][start:]

    for msg in return_msg:
        msg['reacts'][0]['is_this_user_reacted'] = False
        if auth_id in msg['reacts'][0]['u_ids']:
            msg['reacts'][0]['is_this_user_reacted'] = True

    return {                                # Return the struct.
        'messages': return_msg,
        'start': start,
        'end': end,
    }
Exemplo n.º 7
0
def channel_invite(token, channel_id, u_id):
    """Invites a user (with user id u_id) to join a channel with ID channel_id.

    Args:
        token: the token of the invitee.
        channel_id: the channel which is the target of inviter.
        u_id: the user id of the inviter.

    Returns:
        None.

    Raises:
        1. InputError
            - the channel id is invalid;
            - the user id is invalid;
            - the user token is invalid.
        2. AccessError
            - the authorised user is not in this channel.
        3. Repeated Invite
            - Repeated invite one person who is already in.
    """
    auth_id = token_into_user_id(token)  # InputError 1: invalid token.
    if auth_id == -1:
        raise InputError('invalid token')

    channel_got = find_channel(channel_id)  # InputError 2: invalid channel_id.
    if channel_got is None:
        raise InputError('invalid channel_id')

    user = find_user(u_id)  # InputError 3: invalid user_id.
    if user == -1:
        raise InputError('invalid user_id')

    if not find_one_in_channel(channel_got, auth_id):
        raise InputError('the auth not in channel'
                         )  # AccessError 4: if the auth not in channel.

    if find_one_in_channel(channel_got, u_id):
        return  # Case 5: if the member already in, skip it.

    user_struct = find_user(u_id)  # Case 6: no error, add the member.
    user = {  # Create a new struct to store user's info.
        'u_id': u_id,
        'name_first': user_struct['name_first'],
        'name_last': user_struct['name_last'],
        'profile_img_url': ''
    }
    add_one_in_channel(channel_id, user)  # Add the above struct into channel.
Exemplo n.º 8
0
def owner_from_token(token):
    """Find owner from token."""
    user = decode_token(token)
    if user is None:
        raise InputError("Couldn't Decode Token")

    return user
Exemplo n.º 9
0
def passwordreset_request(email):
    """Password reseting request."""

    # find the user in question
    focus_user = None
    for user in data.return_users():
        if user['email'] == email:
            focus_user = user
            break
    if focus_user is None:
        raise InputError('This is an incorrect email')

    # create the secret code
    code = create_secret(10, whitespace=False)

    # store the code
    u_id = focus_user['u_id']
    data.update_user(u_id, 'password_reset', {
        'origin': datetime.datetime.utcnow(),
        'code': code
    })

    # get the html formatted
    html = data.return_password_reset_email().format(
        PREVIEWTEXT='This is your password reset code',
        FIRSTNAME=focus_user.get('name_first'),
        CODE=code)

    # send the email
    send_email(email, html)
    return {}
Exemplo n.º 10
0
def channel_addowner(token, channel_id, u_id):
    """Make user with user id u_id an owner of this channel.

    Args:
        token: the token of authorised user.
        channel_id: the channel which is adding a owner.
        u_id: the user who would be adding into the owner list.

    Returns:
        None.

    Raises:
        1. InputError
            - channel ID is not a valid channel;
            - when user with user id u_id is already an owner of the channel.
        2. AccessError
            - when the authorized user is not an owner of the flockr;
            - or an owner of this channel(won't focus on flockr this iteration).
    """
    this_channel = find_channel(channel_id)
    if this_channel is None:  # InputError 1: invalid channel_id.
        raise InputError('invalid channel_id')

    auth_id = token_into_user_id(token)
    if auth_id == -1:  # InputError 2: invalid token.
        raise InputError('invalid token')

    # check whether the user is already an owner
    if find_current_owner(this_channel, u_id):
        raise InputError('user is already owner'
                         )  # InputError 3: check whether user is owner.

    if not find_current_owner(this_channel,
                              auth_id) and check_permission(auth_id) != 1:
        raise InputError('auth is not flockr owner or this channel owner'
                         )  # AccessError 4: if the auth not in channel.

    owner_detail = find_user(u_id)
    owners = {  # Case 5: if all passed, add user into owner.
        'u_id': u_id,
        'name_first': owner_detail['name_first'],
        'name_last': owner_detail['name_last'],
        'profile_img_url': ''
    }
    add_owner_in_channel(channel_id, owners)
    return {}
Exemplo n.º 11
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: the token of the people who edit it.
        message_id: the new message.

    RETURNS:
        {}

    THEREFORE, TEST EVERYTHING BELOW:
    1. InputError
      - Message_id is not a valid message.
      - Message is already pinned.
      - Token invalid.
    2. AccessError
      - The authorised user is not a member of the channel that the message is within.
      - The authorised user is not an owner.
    """
    # InputError 1: invalid token.
    auth_id = token_into_user_id(token)
    if auth_id == -1:
        raise InputError(description='invalid token.')

    # InputError 2: Message id is not exist
    message_using = find_message(message_id)
    if message_using is None:
        raise InputError(description='invalid message id.')

    # InputError 3: Message already pin
    message_using = find_message(message_id)
    if message_using['is_pinned']:
        raise InputError(description='Message already pin')

    # AccessError 4: token peroson is not owner
    test_owener = if_auth_is_message_channel_owner(auth_id,
                                                   message_using['channel_id'])
    # if it is neither channel owner nor messager sender
    # raise for access error
    if test_owener is False:
        raise AccessError(description='token peroson is not owner.')

    # Case 5: no error, change the message pin
    change_msg_pin(message_using, True)
    return {}
Exemplo n.º 12
0
def get_profile_photo_path(u_id):
    """Returns a profile picture path, and url from the u_id."""
    path = os.getcwd() + '/src/data/profiles/' + u_id + '.jpg'
    # make sure path is valid
    try:
        Image.open(path)
    except Exception as e:
        raise InputError("You don't have a profile picture") from e
    return path
Exemplo n.º 13
0
def channel_removeowner(token, channel_id, u_id):
    """Remove user with user id u_id an owner of this channel.

    Args:
        token: the token of authorised user.
        channel_id: the channel which is removing a owner.
        u_id: the user who would be removed from the owner list.

    Returns:
        None.

    Raises:
        1. InputError
            - channel ID is not a valid channel;
            - when user with user id u_id is already an owner of the channel.
        2. AccessError
            - when the authorized user is not an owner of the flockr;
            - or an owner of this channel(won't focus on flockr this iteration).
    """
    this_channel = find_channel(channel_id)
    if this_channel is None:  # InputError 1: invalid channel_id.
        raise InputError('invalid channel_id')

    auth_id = token_into_user_id(token)
    if auth_id == -1:  # InputError 2: invalid token.
        raise InputError('invalid token')

    if find_current_owner(this_channel, u_id) is False:
        raise InputError(
            'user is not owner')  # InputError 3: check whether user is owner.

    user = find_user(u_id)
    if user == -1:  # InputError 4: check if the user_id valid.
        raise InputError('u_id is not valid')

    if find_current_owner(this_channel,
                          auth_id) is False and check_permission(auth_id) != 1:
        raise InputError('auth is not flockr owner or this channel owner'
                         )  # AccessError 5: if the auth not in channel.

    rm_owner_in_channel(channel_id,
                        u_id)  # Case 6: if all passed, pop the user off.
    return {}
Exemplo n.º 14
0
def echo():
    """
    Sanity test domain for echo.
    No other purpose than a basic server test.
    """
    data = request.args.get('data')
    if data == 'echo':
        raise InputError(description='Cannot echo "echo"')
    return jsonify({
        'data': data
    })
Exemplo n.º 15
0
def regex_email_check(email):
    """
    Check that the email is validly formatted email.
    Not using the given regex method as it tells me that my own
    actual email is not a real email.
    """
    regex = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"
    # regex = r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'

    if re.search(regex, email) is None:
        raise InputError("That's not a real email!")
Exemplo n.º 16
0
def auth_register_error_check(email, password, name_first, name_last):
    """Handles error checking for auth_register."""

    # Check for valid input.
    regex_email_check(email)

    # Check if email is already used.
    if check_in_users('email', data.return_users(), email) is not None:
        raise InputError('Email Already in Use')

    # check len(password) >= 6.
    if len(password) < 6:
        raise InputError('Password Too Short')

    # Check first name matches requirements.
    if len(name_first) < 1 or len(name_first) > 50:
        raise InputError('First Name Incorrect Length')

    # Check Last Name matches requirements.
    if len(name_last) < 1 or len(name_last) > 50:
        raise InputError('Last Name Incorrect Length')
Exemplo n.º 17
0
def message_remove(token, message_id):
    """Given a message_id for a message, this message is removed from the channel.

    Args:
        token: the token of the people who authority.
        channel_id: the channel which is the target of message.

    RETURNS:
        {}

    THEREFORE, TEST EVERYTHING BELOW:
    1. inputError
      - Message id is not exist.
    2. accessError excluding
      - Message with message_id was sent by the authorised user making this reques.
      - The authorised user is an owner of this channel or the flockr.
    """

    # InputError 1: invalid token.
    auth_id = token_into_user_id(token)
    if auth_id == -1:
        raise InputError(description='invalid token.')

    # InputError 2: Message id is not exist
    message_using = find_message(message_id)
    if message_using is None:
        raise InputError(description='invalid message id.')

    # AccessError 3: excluding message sender and channel_owner
    test_owener = if_auth_owner(auth_id, message_using['channel_id'])
    # if it is neither channel owner nor messager sender
    # raise for access error
    if test_owener is False and message_using['u_id'] != auth_id:
        raise AccessError(
            description='neither message sender nor channel_owner.')

    # Case 4: no error, delete the message
    delete_msg_in_list(message_using)
    return {}
Exemplo n.º 18
0
def channel_leave(token, channel_id):
    """Given a channel ID, the user removed as a member of this channel.

    Args:
        token: the token of user who is leaving.
        channel_id: the channel which user is leaving.

    Returns:
        None.

    Raises:
        1. InputError
            - the channel id is invalid;
        2. AccessError
            - the authorised user is not in this channel.
    """
    target_channel = find_channel(channel_id)
    if target_channel is None:  # InputError 1: invalid channel_id.
        raise InputError('invalid channel_id')

    auth_id = token_into_user_id(token)
    if auth_id == -1:  # InputError 2: invalid token.
        raise InputError('invalid token')

    if not find_one_in_channel(target_channel, auth_id):
        raise InputError('the auth not in channel'
                         )  # AccessError 3: if the auth not in channel.

        # Case 4: the user is one of the owners.
    if find_current_owner(target_channel, auth_id) is True:
        if number_of_owners(channel_id) > 1:
            rm_owner_in_channel(channel_id, auth_id)
            remove_a_member_in_channel(auth_id, channel_id)
        else:  # Case 5: close the non-owner channel.
            remove_whole_channel(channel_id)
            # Case 6: the user is not an owner.
    remove_a_member_in_channel(auth_id, channel_id)

    return {}
Exemplo n.º 19
0
def channel_join(token, channel_id):
    """Join the user by his/her token into a channel by channel_id.

    Args:
        token: the token of user who is leaving.
        channel_id: the channel which user is leaving.

    Returns:
        None.

    Raises:
        1. InputError
            - the channel id is invalid;
        2. AccessError
            - the channel is PRIVATE.
    """
    target_channel = find_channel(channel_id)
    if target_channel is None:  # InputError 1: invalid channel_id.
        raise InputError('invalid channel_id')

    if not is_channel_public(channel_id):
        raise InputError(
            'channel is PRIVATE')  # AccessError 2: channel is PRIVATE.

    auth_id = token_into_user_id(token)
    if auth_id == -1:
        raise InputError('invalid token')  # InputError 3: invalid token.

    new_member_struct = find_user(auth_id)
    user = {  # Case 4: add this user into member list.
        'u_id': auth_id,
        'name_first': new_member_struct['name_first'],
        'name_last': new_member_struct['name_last'],
        'profile_img_url': ''
    }

    add_one_in_channel(channel_id, user)

    return {}
Exemplo n.º 20
0
def admin_userpermission_change(token, u_id, permission_id):
    """Change the permission if the admin is a owner."""
    i = owner_from_token(token)  # check that token exists

    users = data.return_users()
    found = 0
    for user in users:  # Check that u_id is valid.
        if user['u_id'] == u_id:
            found = 1
            break

    if found != 1:
        raise InputError(description='The u_id is invalid.')

    if permission_id not in range(1, 3):  # Check the permission_id.
        raise InputError(description='The permission_id is invalid.')

    if i['permission_id'] != 1:  # The admin is not a owner_num.
        raise AccessError(description='The admin is not a owner.')

    data.update_user(u_id, 'permission_id', permission_id)

    return {}
Exemplo n.º 21
0
def standup_start(token, channel_id, length):
    auth_id = token_into_user_id(token)  # invalid token.
    if auth_id == -1:
        raise InputError(description='invalid token')

    c1 = find_channel(channel_id)  #  invalid channel_id.
    if c1 is None:
        raise InputError(description='invalid channel_id')

    now = datetime.datetime.utcnow()
    timestamp = int(now.replace(tzinfo=datetime.timezone.utc).timestamp())
    '''
    if time_difference(c1['standup']['finish_time'], timestamp) > 0:
        raise InputError(description='An active standup is currently running in this channel')
    '''
    is_act = standup_active(token, channel_id).get('is_active')
    if is_act == True:
        raise InputError(
            description='An active standup is currently running in this channel'
        )

    #Firstly, empty the message package
    data.message_package_empty(channel_id)

    #last_time = datetime.datetime.strptime(f_time,'%Y-%m-%d %H:%M:%S')
    next_time = timestamp + length
    data.change_finish_time(channel_id, next_time)

    #send the message at the end of the standup
    threading.Timer(length, send_message_package, (
        token,
        channel_id,
    )).start()

    return {
        'time_finish': next_time,
    }
Exemplo n.º 22
0
def passwordreset_reset(reset_code, new_password):
    """Check if reset_code is correct."""

    # check that password is valid length
    if len(new_password) < 6:
        raise InputError('Password Too Short')
    now = datetime.datetime.utcnow()

    # check that the code stored was the same as given code
    focus_user = None
    for user in data.return_users():
        if (user.get('password_reset').get('code') == reset_code and abs(
            (now - user.get('password_reset').get('origin')).total_seconds()) <
                500):
            focus_user = user
            break
    # raise input error if person is faulty
    if focus_user is None:
        raise InputError('Invalid Reset Code')

    # store the new password
    data.update_user(focus_user['u_id'], 'password', hash_(new_password))

    return {}
Exemplo n.º 23
0
def channel_details(token, channel_id):
    """Provide basic details about the channel by its id.

    Args:
        token: the token of authorised user.
        channel_id: the id of channel we need info.

    Returns:
        {'name': channel_got['name'],
        'owner_members':channel_got['owner_members'],
        'all_members': channel_got['all_members'],}

    Raises:
        1. InputError
            - the channel id is invalid;
            - the user token is invalid.
        2. AccessError
            - the authorised user is not in this channel.
    """
    auth_id = token_into_user_id(token)  # InputError 1: invalid token.
    if auth_id == -1:
        raise InputError('invalid token')

    channel_got = find_channel(channel_id)  # InputError 2: invalid channel_id.
    if channel_got is None:
        raise InputError('invalid channel_id')

    if not find_one_in_channel(channel_got, auth_id):
        raise InputError('the auth is not in channel'
                         )  # AccessError 3: if the auth not in channel.

    return {                                # Case 4: all passed, return channel.
        'name': channel_got['name'],
        'owner_members':channel_got['owner_members'],
        'all_members': channel_got['all_members'],
    }
Exemplo n.º 24
0
def channels_create(token, name, is_public):
    """Create a new empty channel."""
    if len(name) > 20:                      # The length of channel name should <= 20.
        raise InputError('The length of channel name should <= 20')

    i = owner_from_token(token)
    owner_id = i['u_id']
    owner_fn = i['name_first']
    owner_ln = i['name_last']

    standup = {
        'finish_time':-1,
        'message_package':'',
    }

    channel_id = create_channel_id(data.return_channels())
    channel_new = {                         # Initialize the new channel.
        'name': name,
        'channel_id':channel_id,
        'owner_members': [
            {
                'u_id': owner_id,
                'name_first': owner_fn,
                'name_last': owner_ln,
                'profile_img_url':''

            }
        ],
        'all_members': [
            {
                'u_id': owner_id,
                'name_first': owner_fn,
                'name_last': owner_ln,
                'profile_img_url':''
            }
        ],
        'is_public': is_public,
        'message':[],
        'standup': standup
    }

    data.append_channels(channel_new)       # Add this new channel into data.
    return {
        'channel_id': channel_id
    }
Exemplo n.º 25
0
def standup_active(token, channel_id):
    channel_got = find_channel(channel_id)  #  invalid channel_id.
    if channel_got is None:
        raise InputError(description='invalid channel_id')

    now = datetime.datetime.utcnow()
    timestamp = int(now.replace(tzinfo=datetime.timezone.utc).timestamp())
    diff = time_difference(channel_got['standup']['finish_time'], timestamp)
    if diff > 0:
        is_active = True
        time_finish = channel_got['standup']['finish_time']
    else:
        is_active = False
        time_finish = None
    return {
        'is_active': is_active,
        'time_finish': time_finish,
    }
Exemplo n.º 26
0
def user_profile_sethandle(token, handle_str):
    """Update the authorised user's handle (i.e. display name).

    Raises:
        1. InputError
            - handle_str must be between 3 and 20 characters
            - handle is already used by another user
    """
    person = decode_token(token)
    if person is None:
        return {'is_success': False}
    email = person.get('email')
    # handle_str must be between 3 and 20 characters
    if len(handle_str) < 3 or len(handle_str) > 20:
        raise InputError('1')
    user=check_in_users("email",data.return_users(),email)
    user['handle_str']=handle_str
    data.updateByEmail(user,email)
    return {}
Exemplo n.º 27
0
def user_profile_setemail(token, email):
    """Update the authorised user's email address.

    Raises:
        1. InputError
            - Email entered is not a valid email using the method provided
            - Email address is already being used by another user
    """
    person = decode_token(token)
    if person is None:
        return {'is_success': False}
    email_now = person.get('email')

    regex_email_check(email)

    user = check_in_users('email', data.return_users(), email)
    if user is not None:
        raise InputError('Cannot use this email repeating :(')

    user = check_in_users('email', data.return_users(), email_now)

    user['email']=email
    data.updateByEmail(user,email_now)
    return {}
Exemplo n.º 28
0
def user_profile_uploadphoto(token, img_url, x_start, y_start, x_end, y_end):
    """Upload the photo.

    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. It will save this file to be served.
    """
    # find the user specified
    user = decode_token(token)

    # get the profile picture
    r = requests.get(img_url, stream=True)

    # check whether the image is real
    if r.status_code != 200:
        raise InputError('Image did not return correctly')

    # open image
    try:
        img = Image.open(r.raw)
    except Exception as e:
        raise InputError('Input is not an image') from e
    # check if img is jpeg
    if img.format != 'JPEG':
        raise InputError('Please Input a JPEG as your Profile Picture')

    # make sure dimensions are valid
    if x_start < 0 or y_start < 0:
        raise InputError('Invalid Dimensions')
    if x_end < x_start or y_end < y_start:
        raise InputError('Invalid Dimensions')
    width, height = img.size
    if width < x_end or height < y_end:
        raise InputError('Invalid Dimensions')

    # crop the image
    cropped = img.crop((x_start, y_start, x_end, y_end))
    #  save image to directory
    data.save_image(cropped, user['u_id'])

    return {}
Exemplo n.º 29
0
def message_sendlater(token, channel_id, message, time_sent):
    """Send a message from authorised_user to the channel specified by channel_id automatically at a specified time in the future.

    Args:
        token: the token of the people who edit it.
        channel_id: the channel which is the target of message.
        message: the new message.
        time_sent: when the msg would be sent

    RETURNS:
        return {
            'message_id': new_msg_id,
        }

    THEREFORE, TEST EVERYTHING BELOW:
    1. InputError
      - Channel ID is not a valid channel
      - Message is more than 1000 characters
      - Time sent is a time in the past
    2. AccessError
      - when the authorised user has not joined the channel they are trying to post to.
    """
    # InputError 1: invalid token.
    auth_id = token_into_user_id(token)
    if auth_id == -1:
        raise InputError(description='invalid token.')

    # InputError 2: Message is more than 1000 characters.
    if len(message) > 1000:
        raise InputError(description='Message is more than 1000 characters.')

    # AccessError 3: invalid channel_id.
    channel_got = find_channel(channel_id)
    if channel_got is None:
        raise AccessError(description='invalid channel_id.')

    # AccessError 4: if the auth not in channel.
    if not find_one_in_channel(channel_got, auth_id):
        raise AccessError(description='auth not in channel')

    #Input error 5: the time is in the past
    # record the time rightnow
    now = datetime.utcnow()
    timestamp = int(now.replace(tzinfo=timezone.utc).timestamp())
    if (time_sent < timestamp):
        raise InputError(description='The time is in the past')

    # Case 5: no error, add the message
    new_msg_id = 1
    if len(data.return_messages()) != 0:
        new_msg_id = data.return_messages()[0]['message_id'] + 1

    # create the message struct
    return_message = {
        'message_id': new_msg_id,
        'channel_id': channel_id,
        'u_id': auth_id,
        'message': message,
        'time_created': time_sent,
        'reacts': [{
            'react_id': 1,
            'u_ids': [],
            'is_this_user_reacted': False
        }],
        'is_pinned': False
    }

    # insert the message in the top of messages in the channel.
    time.sleep(time_sent - timestamp)
    adding_message(return_message, channel_id)
    return {
        'message_id': new_msg_id,
    }
Exemplo n.º 30
0
def message_send(token, channel_id, message):
    """Send a message from authorised_user to the channel specified by channel_id.

    Args:
        token: the token of the sender.
        channel_id: the channel which is the target of message.
        message: the message we send.

    RETURNS:
        {message_id}

    THEREFORE, TEST EVERYTHING BELOW:
    1. inputError
      - Message is more than 1000 characters.
    2. accessError
      - The authorised user has not joined the channel they are trying to post to.
      - Cannot find the channel_id.
    """

    # InputError 1: invalid token.
    auth_id = token_into_user_id(token)
    if auth_id == -1:
        raise InputError(description='invalid token.')

    # InputError 2: Message is more than 1000 characters.
    if len(message) > 1000:
        raise InputError(description='Message is more than 1000 characters.')

    # AccessError 3: invalid channel_id.
    channel_got = find_channel(channel_id)
    if channel_got is None:
        raise AccessError(description='invalid channel_id.')

    # AccessError 4: if the auth not in channel.
    if not find_one_in_channel(channel_got, auth_id):
        raise AccessError(description='auth not in channel')

    # Case 5: no error, add the message
    new_msg_id = 1
    if len(data.return_messages()) != 0:
        new_msg_id = data.return_messages()[0]['message_id'] + 1

    # record the time rightnow
    now = datetime.utcnow()
    timestamp = int(now.replace(tzinfo=timezone.utc).timestamp())

    # create the message struct
    return_message = {
        'message_id': new_msg_id,
        'channel_id': channel_id,
        'u_id': auth_id,
        'message': message,
        'time_created': timestamp,
        'reacts': [{
            'react_id': 1,
            'u_ids': [],
            'is_this_user_reacted': False
        }],
        'is_pinned': False
    }

    # insert the message in the top of messages in the channel.
    adding_message(return_message, channel_id)

    return {
        'message_id': new_msg_id,
    }