Esempio n. 1
0
def search(token, query_str):
    try:
        decodeToken(token)
        retMessages = []
        channelList = channels_list(token)['channels']
        # Loop through all channels and messages for matches
        for inChannel in channelList:
            for channel in channels:
                if inChannel['channel_id'] == channel['channel_id']:
                    for message in channel['messages']:
                        if query_str in message['message']:
                            retMessages.append(message)
        return {"messages": retMessages}
    except AccessError as e:
        raise e
Esempio n. 2
0
def channels_create(token, name, is_public):
    try:
        if len(name) > 20:
            raise ValueError("Name must be 20 characters or less.")

        # Get user information
        channel_id = len(channels)
        u_id = decodeToken(token)
        users = getUser(u_id)
        name_first = users['name_first']
        name_last = users['name_last']
        profile_img_url = users['profile_img_url']

        owner_members = [{
            "u_id": u_id,
            "name_first": name_first,
            "name_last": name_last,
            "profile_img_url": profile_img_url
        }]
        all_members = [{
            "u_id": u_id,
            "name_first": name_first,
            "name_last": name_last,
            "profile_img_url": profile_img_url
        }]

        newChannel(channel_id, name, is_public, owner_members, all_members)
        return channel_id

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 3
0
def channel_addowner(token, channel_id, u_id):
    global channels

    try:
        # Get user information
        userID = decodeToken(token)
        users = getUser(int(u_id))
        target = {'u_id':int(u_id), 'name_first':users['name_first'], 'name_last':users['name_last'], "profile_img_url": users['profile_img_url']}
        grantusers = getUser(userID)
        granter = {'u_id':userID, 'name_first':grantusers['name_first'], 'name_last':grantusers['name_last'], "profile_img_url": grantusers['profile_img_url']}
        permissions = grantusers['permission_id']

        # Channel operations
        channel = getChannel(channel_id)
        if granter in channel['owner_members'] or permissions < 3:
            if target in channel['owner_members']:
                raise ValueError("User already an owner")
            elif target in channel['all_members']:
                channel['owner_members'].append(target)
                return {}
            else:
                channel['owner_members'].append(target)
                channel['all_members'].append(target)
                return {}
        raise AccessError("User is not an owner")

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 4
0
def message_react(token, message_id, react_id):
    global data
    global valid_tokens
    global channels
    try:
        u_id = decodeToken(token)
        #check if react_id is valid at the start
        if react_id != 1:
            raise ValueError("Invalid react ID!")

        message = getMessage(message_id)
        channel = getMessageChannel(message_id)
        isUserChan(u_id, channel)
        for react in message["reacts"]:
            for react_users in react[
                    "u_ids"]:  #check that the user hasn't already reacted
                if react_users == u_id:
                    raise ValueError(
                        "User already has an active react for this message!")
        for react in message["reacts"]:
            if react["react_id"] == react_id:
                react["u_ids"].append(u_id)  #add the reaction
                return {}
        message["reacts"].append({
            "react_id": react_id,
            "u_ids": [u_id]
        })  # genereate the react and ass
        return {}

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 5
0
def channels_listall(token):
    global channels
    try:
        decodeToken(token)
        channelList = {"channels": []}

        for channel in channels:
            channelList['channels'].append({
                "channel_id": channel['channel_id'],
                "name": channel['name']
            })

        return channelList

    except AccessError as e:
        raise e
Esempio n. 6
0
def standup_send(token, channel_id, message):
    try:
        u_id = decodeToken(token)
        # Check length is OK
        if len(message) > 1000:
            raise ValueError("Length is too long")
        # Get user permissions
        for user in data:
            if user['u_id'] == u_id:
                permissions = user['permission_id']
                name_first = user['name_first']
        # Prepare a new message
        newMessage = name_first + ': ' + message + ' '
        # Add the new message if allowed
        channel = getChannel(channel_id)
        for member in channel['all_members']:
            if member['u_id'] == u_id or permissions < 3:
                if channel['standup_status']:
                    channel['standup_message'] += newMessage
                    return {}
                raise ValueError("Standup not running!")
        raise AccessError("User is not an owner!")
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 7
0
def channel_join(token, channel_id):
    global channels
    try:
        # Get user information
        u_id = decodeToken(token)
        users = getUser(u_id)
        permission = users['permission_id']
        userDetails = {
            "u_id": u_id,
            "name_first": users['name_first'],
            "name_last": users['name_last'],
            "profile_img_url": users['profile_img_url']
        }

        # Channel operations
        channel = getChannel(channel_id)
        if not channel[
                'is_public'] and permission == 3:  #Checks if channel is public
            raise AccessError("You do not have access to this channel")
        else:
            channel['all_members'].append(userDetails)
            if userDetails not in channel['owner_members'] and permission < 3:
                channel['owner_members'].append(userDetails)
            return {}

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 8
0
def admin_userpermission_change(token, u_id, permission_id):
    
    try:
        # Check if user is authenticated and get the requesting user ID from token
        granterID = decodeToken(token)

        # Check if the target uID format is valid
        if not u_id.isdigit():
            raise ValueError("Invalid user ID!")

        # Check if the target permission ID is valid
        if int(permission_id) > 3 or int(permission_id) < 1:
            raise ValueError("Invalid permission id")

        # Find the requesting user
        permissions = getUser(granterID)['permission_id']

        # Check if requesting user has permissions for the action
        if permissions < 3:
            setPermission(u_id, permission_id)
            return {}
        raise AccessError("Granter is not an admin or owner")     
        
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e 
Esempio n. 9
0
def user_profile(token, u_id):
    global data
    try:
        decodeToken(token)
        # return info on the target user
        for user in data:
            if user['u_id'] == int(u_id):
                return {
                    'email': user['email'],
                    'name_first': user['name_first'],
                    'name_last': user['name_last'],
                    'handle_str': user['handle'],
                    'profile_img_url': user['profile_img_url']
                }
        raise ValueError("Not a valid user")
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 10
0
def standup_active(token, channel_id):
    global start_time
    try:
        decodeToken(token)
        # Check standup status
        for channel in channels:
            if channel['channel_id'] == int(channel_id):
                if not channel['standup_status']:
                    return {'is_active': False, 'time_finish': None}
                else:
                    return {
                        'is_active': True,
                        'time_finish': channel['time_finish']
                    }
        raise ValueError("Channel ID is invalid!")
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 11
0
def users_all(token):
    global data
    try:
        decodeToken(token)
        result = []
        # accumulate users
        for user in data:
            result.append({
                'u_id': user['u_id'],
                'email': user['email'],
                'name_first': user['name_first'],
                'name_last': user['name_last'],
                'handle_str': user['handle'],
                'profile_img_url': user['profile_img_url']
            })
        if result == []:
            raise ValueError("No Users")
        else:
            return {"users": result}
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 12
0
def channels_list(token):
    global channels
    try:
        u_id = decodeToken(token)
        channelList = {"channels":[]}

        for channel in channels:
            for user in channel['all_members']:
                if user['u_id'] == u_id:
                    channelList['channels'].append({"channel_id":channel['channel_id'], "name":channel['name']})

        return channelList
    except AccessError as e:
        raise e
Esempio n. 13
0
def channel_leave(token, channel_id):
    try:
        u_id = decodeToken(token)
        # Channel operations
        channel = getChannel(channel_id)
        for user in channel['all_members']:
            if user['u_id'] == u_id:
                channel['all_members'].remove(user)
                if user in channel['owner_members']:
                    channel['owner_members'].remove(user)
                return {}
        raise AccessError('User is not a member')
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 14
0
def standup_start(token, channel_id, length):
    try:
        u_id = decodeToken(token)
        permissions = getUserPerm(u_id)
        channel = getChannel(channel_id)
        for owner in channel['owner_members']:
            if owner['u_id'] == u_id or permissions < 3:
                if not channel['standup_status']:
                    time_finish = datetime.now(timezone.utc).timestamp() + length
                    channel['standup_status'] = True
                    channel['time_finish'] = time_finish
                    return {"time_finish":time_finish}
                raise ValueError("Standup already running!")
        raise AccessError("User is not an owner!")
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 15
0
def channel_messages(token, channel_id, start):
    global channels
    try:
        u_id = decodeToken(token)
        # Channel operations
        channel = getChannel(channel_id)
        for users in channel['all_members']:
            if users['u_id'] == u_id or data[u_id]['permission_id'] < 3:
                if int(start) > len(channel['messages']):
                    raise ValueError(
                        "Start is greater than the number of messages")
                newMsg = channel[
                    'messages']  #inject is_user_reacts into messages to return
                for messages in newMsg:
                    for reacts in messages['reacts']:
                        reacts['is_this_user_reacted'] = False  #default
                        for react_users in reacts['u_ids']:
                            if react_users == u_id:
                                reacts[
                                    'is_this_user_reacted'] = True  #if user has reacted
                if len(newMsg) <= int(start) + 50:
                    return {
                        'messages':
                        newMsg[len(channel['messages']) - int(start)::-1],
                        'start':
                        start,
                        'end':
                        -1
                    }
                else:
                    return {
                        'messages':
                        newMsg[len(channel['messages']
                                   ):len(channel['messages']) - 51:-1],
                        'start':
                        start,
                        'end':
                        int(start) + 50
                    }
        raise AccessError("Must be a member of channel to see messages")
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 16
0
def user_profiles_uploadphoto(token, img_url, x_start, y_start, x_end, y_end):
    global data
    global channels
    try:
        host_name = 'http://' + getHostName() + '/'
        u_id = decodeToken(token)
        # validate file format
        if ".jpg" not in img_url:
            raise ValueError('Not a JPG')
        # set path
        path = "static/" + str(u_id) + "_profile_image" + ".jpg"
        # open the image
        try:
            urllib.request.urlretrieve(img_url, path)
            image = Image.open(path)
        except:
            raise ValueError('Invalid url')
        #cropping setup
        width, height = image.size

        border = (x_start, y_start, x_end, y_end)
        if x_start < 0 or x_start > width:
            raise ValueError('Dimensions incorrect')
        if y_start < 0 or y_start > height:
            raise ValueError('Dimensions incorrect')
        if x_end < 0 or x_end > width:
            raise ValueError('Dimensions incorrect')
        if y_end < 0 or y_end > height:
            raise ValueError('Dimensions incorrect')
        # crop and serve
        (image.crop(border)).save(path, "JPEG")
        data[u_id]['profile_img_url'] = host_name + path
        for channel in channels:
            for user in channel['all_members']:
                if user['u_id'] == u_id:
                    user['profile_img_url'] = host_name + path
            for user in channel['owner_members']:
                if user['u_id'] == u_id:
                    user['profile_img_url'] = host_name + path
        return {}
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 17
0
def message_send(token, channel_id, message):
    global data
    global valid_tokens
    global channels

    try:
        u_id = decodeToken(token)
        channel = getChannel(channel_id)
        isUserChan(u_id, channel)  #Will raise error if fails
        if len(message) > 1000:
            raise ValueError(
                "Message can not be greather than 1000 character limit")
        elif len(message) == 0:  #this appears to be handled by front end...
            raise ValueError("Message can not be empty")
        else:
            return addMessage(channel, message, u_id)

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 18
0
def channel_details(token, channel_id):
    try:
        # Get user details
        u_id = decodeToken(token)
        user = getUser(u_id)
        permissions = user['permission_id']

        # Get channel details
        channel = getChannel(channel_id)
        if channel['is_public'] == 'true' or permissions < 3:
            return {
                "name": channel['name'],
                "owner_members": channel['owner_members'],
                "all_members": channel['all_members']
            }
        raise AccessError("User is not member of channel")

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 19
0
def message_unpin(token, message_id):
    global data
    global valid_tokens
    global channels
    try:
        u_id = decodeToken(token)
        message = getMessage(message_id)
        channel = getMessageChannel(message_id)
        isUserChan(u_id, channel) #Will raise error if fails
        for members in data: 
            if members["u_id"] == u_id:
                if int(members["permission_id"]) == 1 or int(members["permission_id"]) == 2: #check user is admin ############ ADMIN OR OWNER?
                    if message["is_pinned"]: #check if pinned
                        message["is_pinned"] = False
                        return {}
                    raise ValueError("Message is not pinned!")
        raise ValueError("User does not have permission to unpin!")   
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 20
0
def user_profile_sethandle(token, handle_str):
    global data
    try:
        u_id = decodeToken(token)
        #check if handle is already in use
        for user in data:
            if user['handle'] == handle_str:
                raise ValueError("Handle already in use")
        #check handle is valid
        if (len(handle_str) < 3) or (len(handle_str) >
                                     20):  #inclusive? assumed to be inclusive
            raise ValueError("Handle must be between 3 and 20 characters")
        # make the change
        for user in data:
            if user['u_id'] == int(u_id):
                user['handle'] = handle_str
                return {}
        raise ValueError("Not a valid user")
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 21
0
def user_profile_setemail(token, email):
    global data
    try:
        u_id = decodeToken(token)
        #check if email is already in use
        for user in data:
            if user['email'] == email:
                raise ValueError("Email already in use")
        #check email is valid
        if not re.search(regex, email):
            raise ValueError("Invalid Email")
        # set email
        for user in data:
            if user['u_id'] == int(u_id):
                user['email'] = email
                return {}
        raise ValueError("Not a valid user")  #technically impossible to reach

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 22
0
def message_unreact(token, message_id, react_id):
    global channels
    try:
        u_id = decodeToken(token)
        #check if react_id is valid at the start
        if react_id != 1:
            raise ValueError("Invalid react ID!")

        channel = getMessageChannel(message_id)
        message = getMessage(message_id)
        isUserChan(u_id, channel) #Will raise error if fails
        for react in message["reacts"]: 
            for react_users in react["u_ids"]: #check that the user hasn't already reacted
                if react_users == u_id:
                    react["u_ids"].remove(u_id)
                    return {}
        raise ValueError("User already has no active react for this message!")

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 23
0
def channel_invite(token, channel_id, u_id):
    try:
        # Get user information
        userID = decodeToken(token)
        grant_user = getUser(userID)
        granter = {'u_id':userID, 'name_first':grant_user['name_first'], 'name_last':grant_user['name_last'], "profile_img_url": grant_user['profile_img_url']}
        target_user = getUser(int(u_id))
        target = {'u_id':int(u_id), 'name_first':target_user['name_first'], 'name_last':target_user['name_last'], 'profile_img_url': target_user['profile_img_url']}

        # Can't invite yourself...
        if granter == target:
            raise ValueError("Can't invite yourself!")

        # Channel operations
        channel = getChannel(channel_id)
        if granter in channel['all_members']:
            channel['all_members'].append(target)
            return {}
        raise AccessError("User not a member of channel")
                    
    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 24
0
def message_remove(token, message_id):
    global channels

    try:
        u_id = decodeToken(token)

        message = getMessage(message_id)
        channel = getMessageChannel(message_id)
        if message["u_id"] == u_id:  #check if user is the sender
            channel["messages"].remove(message)
            return {}
        for members in channel["owner_members"]:  #user is owner of channel
            if members["u_id"] == u_id:
                channel["messages"].remove(message)
                return {}
        if getUserPerm(u_id) == 2 or getUserPerm(u_id) == 1:
            channel["messages"].remove(message)
            return {}
        raise AccessError("User does not have permission to remove message!")

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e
Esempio n. 25
0
def message_edit(token, message_id, new_message):
    global channels

    try:
        u_id = decodeToken(token)
        message = getMessage(message_id)
        channel = getMessageChannel(message_id)
        if message["u_id"] == u_id: #check if user is the sender
            doEdit(message, new_message, token)
            return {}        
        for members in channel["owner_members"]: #user is owner of channel
            if members["u_id"] == u_id:
                doEdit(message, new_message, token)
                return {}
        users = getUser(u_id) #user is admin
        if users["permission_id"] == 1 or users["permission_id"] == 2:
            doEdit(message, new_message, token)
            return {}
        raise AccessError("User does not have permission to edit message!")

    except ValueError as e:
        raise e
    except AccessError as e:
        raise e