예제 #1
0
def message_share_v1(token, og_message_id, message, channel_id, dm_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check token
    shareid = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            shareid = data["users"][i]["u_id"]
    if shareid is None:
        raise AccessError("Invalid token")
    # check whether user is part of the channel/dm
    if channel_id == -1:
        if check_user_in_dm(shareid, dm_id) == False:
            raise AccessError("Authorised user is not part of the channel")
        new_message = message + "\n\"\"\"\n" + data["messages"][og_message_id][
            "message"] + "\n\"\"\""
        shared_message_id = message_senddm_v1(token, dm_id, new_message)

    if dm_id == -1:
        if check_user_in_channel(shareid, channel_id) == False:
            raise AccessError("Authorised user needs to be a member of the dm")
        new_message = message + "\n\"\"\"\n" + data["messages"][og_message_id][
            "message"] + "\n\"\"\""
        shared_message_id = message_send_v2(token, channel_id, new_message)

    return {
        'shared_message_id': shared_message_id["message_id"],
    }
예제 #2
0
def admin_userpermission_change_v1(token, u_id, permission_id):

    # token check
    if check_token_valid(token) is False:
        raise AccessError("Invalid Token")

    if permission_id is not 1 and permission_id is not 2:
        raise InputError("Invalid permission_id")

    if not check_user_exists(u_id):
        raise InputError("invalid u_id")

    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)

    owner = False
    owner_id = convert_token(token)
    if data['users'][owner_id]['permission_id'] == 1:
        owner = True

    if owner == True:
        for i in range(len(data['users'])):
            if u_id == data['users'][i]['u_id']:
                data['users'][i]['permission_id'] = permission_id
    else:
        raise AccessError("Unauthorised user, user is not an owner")

    with open ('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent = 4)

    return {
        
    }
예제 #3
0
def channel_addowner_v1(token, channel_id, u_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check that token is valid
    user_id = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            user_id = data['users'][i]['u_id']
    if user_id is None:
        raise AccessError("Invalid token")
    # check if the channel_id exists
    if check_channel_exists(channel_id) == False:
        raise InputError("Invalid channel")

    # check if the user is already an owner of the channel
    for i in range(len(data["channels"][channel_id]["owner_members"])):
        if data["channels"][channel_id]["owner_members"][i]["u_id"] == u_id:
            raise InputError("User already an owner")

    # check if u_id belongs to an existing member of the channel
    if check_user_in_channel(u_id, channel_id) == False:
        raise InputError(
            "User must be a member of the channel to become owner")

    dreamsowner = False
    channelowner = False

    # confirm if token belongs to a dream owner
    if data['users'][user_id]['permission_id'] == 1:
        dreamsowner = True

    # confirm if token belongs to an owner
    for i in range(len(data["channels"][channel_id]["owner_members"])):
        if data["channels"][channel_id]["owner_members"][i]["u_id"] == user_id:
            channelowner = True

    if dreamsowner or channelowner:
        # information of new owner to be added
        new_owner = {
            "u_id": u_id,
            'email': data["users"][u_id]["email"],
            'name_first': data["users"][u_id]["name_first"],
            'name_last': data["users"][u_id]["name_last"],
            'handle': data["users"][u_id]["handle"]
        }
        data["channels"][channel_id]["owner_members"].append(new_owner)
    else:
        raise AccessError("Unauthorised user, user is not an owner")

    with open('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent=4)

    notif_msg = data["users"][u_id][
        "handle"] + " added you as owner in " + data["channels"][channel_id][
            "name"]
    create_notifications(u_id, channel_id, -1, notif_msg)

    return {}
예제 #4
0
def dm_invite_v1(token, dm_id, u_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    inviteid = None
    # check that token is valid
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            inviteid = data["users"][i]["u_id"]
    if inviteid is None:
        raise AccessError("Invalid token")
    # check if the dm_id exists
    if check_dm_exists(dm_id) == False:
        raise InputError("Invalid dm")
    # check if the u_id is valid
    if check_user_exists(u_id) == False:
        raise InputError("Invalid User")
    # checking if the person inviting is in the dm
    if check_user_in_dm(inviteid, dm_id) == False:
        raise AccessError("Authorised user needs to be a member of the dm")
    # checking if the person being invited is already in the dm
    if check_user_in_dm(u_id, dm_id) == True:
        raise InputError("User already a member of this dm")
    new_user = {
        'u_id': u_id,
        'email': data["users"][u_id]["email"],
        'name_first': data["users"][u_id]["name_first"],
        'name_last': data["users"][u_id]["name_last"],
        'handle': data["users"][u_id]["handle"]
    }

    memberslist = data["dms"][dm_id]["name"].split(", ")
    memberslist.append(data["users"][u_id]["handle"])
    sortedlist = sorted(memberslist, key=str.lower)
    final_list = ", ".join(sortedlist)

    #name = data["dms"][dm_id]["name"] + ", " + data["users"][u_id]["handle"]
    data["dms"][dm_id]["members"].append(new_user)
    data["dms"][dm_id]["name"] = final_list

    num_dms_joined = data["user_stats"][u_id]["stats"]["dms_joined"][-1][
        "num_dms_joined"] + 1
    dms_joined = {
        "num_dms_joined": num_dms_joined,
        "time_stamp": create_timestamp()
    }
    data["user_stats"][u_id]["stats"]["dms_joined"].append(dms_joined)

    with open('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent=4)

    notif_msg = data["users"][inviteid][
        "handle"] + " added you to dm " + final_list
    create_notifications(u_id, -1, dm_id, notif_msg)

    calc_involement_rate(u_id)
    calc_utilisation_rate()

    return {}
예제 #5
0
def message_send_v2(token, channel_id, message):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    u_id = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            u_id = data["users"][i]["u_id"]
    if u_id is None:
        raise AccessError("Invalid token")
    if len(message) > 1000:
        raise InputError("Message is longer than the 1000 character limit")
    if check_user_in_channel(u_id, channel_id) == False:
        raise AccessError("Authorised user is not part of the channel")
    dm_id = -1

    new_message = {
        'message_id': get_new_message_id(),
        'u_id': u_id,
        'message': message,
        'time_created': create_timestamp(),
        'channel_id': channel_id,
        'dm_id': dm_id,
        'reacts': [{
            'react_id': 1,
            'u_ids': [],
            'is_this_user_reacted': False
        }],
        'is_pinned': False
    }

    data["messages"].append(new_message)

    num_messages_sent = data["user_stats"][u_id]["stats"]["messages_sent"][-1][
        "num_messages_sent"] + 1
    messages_sent = {
        "num_messages_sent": num_messages_sent,
        "time_stamp": create_timestamp()
    }
    data["user_stats"][u_id]["stats"]["messages_sent"].append(messages_sent)

    num_messages = data["dreams_stats"]["messages_exist"][-1][
        "num_messages_exist"] + 1
    dreams_messages = {
        "num_messages_exist": num_messages,
        "time_stamp": create_timestamp()
    }
    data["dreams_stats"]["messages_exist"].append(dreams_messages)

    with open('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent=4)

    calc_involement_rate(u_id)
    calc_utilisation_rate()

    return {
        'message_id': new_message["message_id"],
    }
예제 #6
0
def message_edit_v2(token, message_id, message):
    '''
    Arguments:
        token (string) - the token of the user who wants to create a channel
        message_id (int) - the id of the message being edited
        message (string) - the new message

    Exceptions:
        InputError - Message is more than 1000 characters or the message id refers to a deleted message
        AccessError - The authorised user has not joined the channel they are trying to post to

    Return value:
        Returns {}
    '''

    # get data
    data = getData()

    # get id
    auth_user_id = findUser(token)

    # Checks that the length is not above 1000 characters
    if len(message) > 1000:
        raise InputError(
            description="Message must be less than 1000 characters")

    # Finds the message
    msg = get_message(message_id, data)

    if msg == -1:
        raise AccessError(description="Message does not exist")

    # Checks the message was sent by the user requesting to edit it or
    # the user is a channel owner
    if msg['u_id'] != auth_user_id and get_user_details(
            auth_user_id, data)['permission_id'] != 1:
        raise AccessError(
            description=
            "User requesting edit did not post message or not channel owner")

    # Delete the message if message is empty, updates the message if it isn't
    if message == '':
        remove_msg_from_channel_or_dm(data, msg)
    else:
        msg_key = data['messages'].index(msg)
        data['messages'][msg_key]['message'] = message

    # Sends notification
    send_msg_notification(data, token, message, msg['channel_id'],
                          msg['dm_id'], False, -1)

    append_user_stats(findUser(token), data)
    append_dream_stats(findUser(token), data)

    writeData(data)

    return {}
예제 #7
0
파일: standup.py 프로젝트: xahk786/COMP1531
def standup_active_v1(token, channel_id):
    """
    For a given channel which the user is a part of, return whether or not there is an active standup running

    Parameters: 
        token(str): the user's token
        channel_id(int): the channel_id that is being checked for an active standup
    Returns: 
        dict with keys is_active (boolean), time_finish (int):
            -is_active: True or False based on whether or not there is a standup active
            -time_finish: If no standup running, key value would be None, else returns the unix timestamp of when the standup finishes
    """
    
    data = getData()
    auth_user_id = find_user_id(token)

    if auth_user_id == False:
        raise AccessError(description = 'User is not a registered user')

    channel_id = int(channel_id)
    #input error if channel id not a valid channel 
    channel_found = False

    if data.get("channels") != None: 
        for channel in data["channels"]:
            if channel["channel_id"] == channel_id:
                channel_found = True

    if channel_found == False:
        raise InputError(description = 'Channel ID is not a valid channel')
        
    #assumes that only a user in the channel can check if a standup is running 
    user_found = False
    for memb in data["channels"][channel_id - 1]['all_members']:
        if memb["u_id"] == auth_user_id:
            user_found = True
    
    if user_found == False:
        raise AccessError(description = 'User not in channel')
            
    time_finish = None
    is_active = False
    
    if data.get("active_standups") == None:
        time_finish = None
        is_active = False
        
    else:
        for i in data["active_standups"]:
            if i["channel_id"] == channel_id:
                time_finish = i["time_finish"]
                is_active = True
                           
    return {'is_active': is_active,
            'time_finish': time_finish
            }   
예제 #8
0
def check_user_permissions(data, msg_key, auth_user_id):
    if data['messages'][msg_key]['dm_id'] == -1:
        channel_members = get_channel_members(
            data['messages'][msg_key]['channel_id'], data)
        if auth_user_id not in channel_members:
            raise AccessError("User not in channel")
    else:
        dm_members = get_dm_members(data['messages'][msg_key]['dm_id'], data)
        if auth_user_id not in dm_members:
            raise AccessError("User not in DM")
예제 #9
0
def channel_removeowner_v1(token, channel_id, u_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check that token is valid
    removeid = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            removeid = data['users'][i]['u_id']
    if removeid is None:
        raise AccessError("Invalid token")
    # check if the channel_id exists
    if check_channel_exists(channel_id) == False:
        raise InputError("Invalid channel")

    ownercheck = False
    index = 0

    # make sure person being removed is an existing owner
    for i in range(len(data["channels"][channel_id]["owner_members"])):
        if data["channels"][channel_id]["owner_members"][i]["u_id"] == u_id:
            ownercheck = True
            index = i
    if ownercheck is False:
        raise InputError("User not an owner")

    dreamsowner = False
    channelowner = False

    if len(data["channels"][channel_id]["owner_members"]) == 1 and len(
            data["channels"][channel_id]["all_members"]) == 1:
        raise AccessError("Last member can not remove themselves as an owner")
    # check person trying to remove owner is a dreams owner
    if data['users'][removeid]['permission_id'] == 1:
        dreamsowner = True
    # check person trying to remove owner is a channel owner
    for i in range(len(data["channels"][channel_id]["owner_members"])):
        if data["channels"][channel_id]["owner_members"][i][
                "u_id"] == removeid:
            channelowner = True

    if dreamsowner or channelowner:
        del data["channels"][channel_id]["owner_members"][index]
    else:
        raise AccessError("Unauthorised user, user is not an owner")

    with open('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent=4)

    notif_msg = data["users"][removeid][
        "handle"] + " removed you as owner in " + data["channels"][channel_id][
            "name"]
    create_notifications(u_id, channel_id, -1, notif_msg)

    return {}
예제 #10
0
def channel_leave_v1(token, channel_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check that token is valid
    u_id = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            u_id = data["users"][i]["u_id"]
    if u_id is None:
        raise AccessError("Invalid token")

    # check if the channel_id exists
    if check_channel_exists(channel_id) == False:
        raise InputError("Invalid channel")
    # check that the user attempting to leave is a member of the channel
    if check_user_in_channel(u_id, channel_id) == False:
        raise AccessError(
            "Authorised user needs to be a member of the channel")

    with open('src/data.json') as FILE:
        data2 = json.load(FILE)

    for i in range(len(data2["channels"][channel_id]["all_members"])):
        if u_id == data2["channels"][channel_id]["all_members"][i]["u_id"]:
            del data2["channels"][channel_id]["all_members"][i]
            break
    for i in range(len(data2["channels"][channel_id]["owner_members"])):
        if u_id == data2["channels"][channel_id]["owner_members"][i]["u_id"]:
            del data2["channels"][channel_id]["owner_members"][i]
            if len(
                    data2["channels"][channel_id]["owner_members"]
            ) == 0 and len(data2["channels"][channel_id]["all_members"]) > 0:
                data2["channels"][channel_id]["owner_members"].append(
                    data2["channels"][channel_id]["all_members"][0])
            break

    num_channels_joined = data["user_stats"][u_id]["stats"]["channels_joined"][
        -1]["num_channels_joined"] - 1
    channels_joined = {
        "num_channels_joined": num_channels_joined,
        "time_stamp": create_timestamp()
    }

    data2["user_stats"][u_id]["stats"]["channels_joined"].append(
        channels_joined)

    with open('src/data.json', 'w') as FILE:
        json.dump(data2, FILE, indent=4)

    calc_involement_rate(u_id)
    calc_utilisation_rate()

    return {}
예제 #11
0
def dm_remove_v1(token, dm_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    u_id = None
    # check that token is valid and that the token belongs to the owner
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            u_id = data['users'][i]['u_id']
    if u_id is None:
        raise AccessError("Invalid token")
    # check if the dm_id exists
    if check_dm_exists(dm_id) == False:
        raise InputError("Invalid dm")
    # check that the owner is attempting to remove
    if check_owner_of_dm(u_id, dm_id) == False:
        raise AccessError("Only the dm owner can delete this dm")

    for i in range(len(data["dms"])):
        if data["dms"][i]["dm_id"] == dm_id:
            for j in range(len(data["dms"][dm_id]["members"])):
                u_id = data["dms"][dm_id]["members"][j]["u_id"]
                num_dms_joined = data["user_stats"][u_id]["stats"][
                    "dms_joined"][-1]["num_dms_joined"] - 1
                dms_joined = {
                    "num_dms_joined": num_dms_joined,
                    "time_stamp": create_timestamp()
                }
                data["user_stats"][u_id]["stats"]["dms_joined"].append(
                    dms_joined)

    num_dms = data["dreams_stats"]["dms_exist"][-1]["num_dms_exist"] - 1
    dreams_dms = {"num_dms_exist": num_dms, "time_stamp": create_timestamp()}
    data["dreams_stats"]["dms_exist"].append(dreams_dms)

    with open('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent=4)

    with open('src/data.json') as FILE:
        data2 = json.load(FILE)
        for i in range(len(data2["dms"])):
            if data2["dms"][i]["dm_id"] == dm_id:
                del data2["dms"][i]
                break

    with open('src/data.json', 'w') as FILE:
        json.dump(data2, FILE, indent=4)

    calc_involement_rate(u_id)
    for u_id in range(len(data["dms"][dm_id]["members"])):
        calc_involement_rate(u_id)
    calc_utilisation_rate()

    return {}
예제 #12
0
def standup_send_v1(token, channel_id, message):
    '''
    Starts a standup in a channel for 'length' seconds.

    Arguments:
        token (string)          - token of user starting standup
        channel_id (integer)    - id of channel standup is in
        message (string)        - buffered message that is sent to standup

    Exceptions:
        InputError  - Occurs when channel_id does not refer to a valid channel
                    - Occurs when the message is over 1000 characters in length
                    (excluding the name of the user)
                    - Occurs when there is no active standup in the channel
        AccessError - Occurs when the token passed in is not valid
                    - Occurs when the authorised user is not already
                    a member of the channel

    Return Value:
        Returns {}
    '''
    # exception checks
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    u_id = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            u_id = data['users'][i]['u_id']
    if u_id is None:
        raise AccessError("Invalid token")
    if check_channel_exists(channel_id) == False:
        raise InputError("Invalid channel")
    if check_user_in_channel(u_id, channel_id) == False:
        raise AccessError("Authorised user is not part of the channel")
    if len(message) > 1000:
        raise InputError("Message is longer than the 1000 character limit")
    standupActive = standup_active_v1(token, channel_id)
    if standupActive['is_active'] == False:
        raise InputError("No active standup running in this channel")

    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)

    for i in range(len(data['users'])):
        if data["users"][i]['token'] == token:
            firstName = data["users"][i]['name_first']

    new_message = {'name': firstName, 'message': message}
    for i in range(len(data["standups"])):
        if data["standups"][i]["channel_id"] == channel_id:
            data["standups"][i]["messages"].append(new_message)

    return {}
예제 #13
0
def message_edit_v2(token, message_id, message):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    editorid = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            editorid = data["users"][i]["u_id"]
    if editorid is None:
        raise AccessError("Invalid token")
    if len(message) > 1000:
        raise InputError("Message is longer than the 1000 character limit")
    # check to see if message exists
    if check_message_exists(message_id) == False:
        raise InputError("Message does not exist")
    # check to see if message is being edited by authorised user
    valid = True
    if check_message_sent_by_user(editorid, message_id) == False:
        valid = False
    # check to see if token belongs to the owner of channel being deleted
    for i in range(len(data["messages"])):
        if data["messages"][i]["message_id"] == message_id:
            channel_id = data["messages"][i]["channel_id"]

    if channel_id is not -1:
        for i in range(len(data["messages"])):
            if data["messages"][i]["message_id"] == message_id:
                channel_id = data["messages"][i]["channel_id"]
        for i in range(len(data["channels"][channel_id]["owner_members"])):
            if data["channels"][channel_id]["owner_members"][i][
                    "u_id"] == editorid:
                valid = True
        if valid == False:
            raise AccessError(
                "Authorised User is not the owner of this channel and did not send this message"
            )
    else:
        if valid == False:
            raise AccessError(
                "Authorised User is not the owner of this dm and did not send this message"
            )

    with open('src/data.json') as FILE:
        data2 = json.load(FILE)
    for i in range(len(data2["messages"]) - 1):
        if data2["messages"][i]["message_id"] == message_id:
            if message is '':
                del data2["messages"][i]
            else:
                data2["messages"][i]["message"] = message
    with open('src/data.json', 'w') as FILE:
        json.dump(data2, FILE, indent=4)
    return {}
예제 #14
0
def check_user_owners_permissions(data, msg_key, auth_user_id):
    if data['messages'][msg_key]['dm_id'] == -1:
        channel_members = get_channel_members(
            data['messages'][msg_key]['channel_id'], data)
        owner_members = get_channel_owners(
            data['messages'][msg_key]['channel_id'], data)
        if auth_user_id not in channel_members or auth_user_id not in owner_members:
            raise AccessError("User not in channel or not channel owner")
    else:
        dm_members = get_dm_members(data['messages'][msg_key]['dm_id'], data)
        if auth_user_id not in dm_members or auth_user_id != get_dm_owner(
                data['messages'][msg_key]['dm_id'], data):
            raise AccessError("User not in DM or not DM owner")
예제 #15
0
def channel_invite_v2(token, channel_id, u_id):
    '''
    Summary:
        Invites a user (with user id u_id) to join a channel with ID channel_id. 
        Once invited the user is added to the channel immediately.
    Args:
        token (string): A user session token 
        channel_id (int): A channel_id number
        u_id (int): A user id 
    Returns: 
        empty dictionary

    Raises:
        InputError when:
            channel_id does not refer to a valid channel
            u_id does not refer to a valid user
        AccessError when:
            the authorised user is not already a member of the channel
    '''
    global users, channels
    assert check_token(token)
    auth_user = user_from_token(token)

    if valid_channel(channel_id) == False:
        raise InputError(f"Channel ID {channel_id} is not a valid channel")

    if valid_user(u_id) == False:
        raise InputError(f"u_id {u_id} does not refer to a valid user")

    current_channel = find_channel(
        channel_id)  #current channel with the given channel id
    invitee = user_from_id(u_id)

    if auth_user['u_id'] not in current_channel['all_members']:
        raise AccessError(
            f"Authorised user {auth_user['u_id']} is not a member of channel with channel_id {channel_id}"
        )

    if u_id in current_channel['all_members']:
        raise AccessError(
            f"u_id {u_id} you are inviting is already inside the channel")

    current_channel['all_members'].append(u_id)
    if invitee[
            'permission'] == 1:  # Dreams owner is automatically channel owner
        current_channel['owner_members'].append(u_id)
    invitee['channels'].append(channel_id)
    update_user_channel_stats(invitee['u_id'])
    send_channel_added_notification(auth_user['handle_str'], u_id,
                                    current_channel['channel_id'])
    return {}
예제 #16
0
def message_pin_v1(token, message_id):
    '''Summary
        Given a message within a channel or DM, mark it as "pinned" to be given special display treatment by the frontend
    Args:
        token (string): A user session token
        message_id (int): A message_id of the message
    
    Returns:
        A empty dictionary
    
    Raises:
       Raises:
        InputError when:
            message_id is not a valid message
            Message with ID message_id is already pinned
        AccessError when:
            The authorised user is not a member of the channel
            The authorised user is not a member of the DM that the message is within
            The authorised user is not an owner of the channel or DM
    '''
    check_token(token)
    auth_user = user_from_token(token)
    if valid_message(message_id) == False:
        raise InputError("message_id is not a valid message")

    message = get_message_from_message_id(message_id)

    if message['is_pinned'] == True:
        raise InputError("Message with ID message_id is already pinned")

    if message['channel_id'] == -1:  #this means this is a dm message
        current_dm = find_dm(message['dm_id'])
        if auth_user['u_id'] not in current_dm['members']:
            raise AccessError("The authorised user is not a member of the DM")
        if auth_user['u_id'] != current_dm[
                'creator']:  # this error will get raised twice is this ok? / this is kinda redundent because if u have to be the owner to pin whats the point of checking for members?
            raise AccessError("The authorised user is not an owner of the DM")
        message['is_pinned'] = True

    if message['dm_id'] == -1:  # this means this a channel message
        current_channel = find_channel(message['channel_id'])
        if auth_user['u_id'] not in current_channel['all_members']:
            raise AccessError(
                "The authorised user is not a member of the channel")
        if auth_user['u_id'] not in current_channel['owner_members']:
            raise AccessError(
                "The authorised user is not an owner of the channel")
        message['is_pinned'] = True

    return {}
예제 #17
0
def message_share_v1(token, og_message_id, message, channel_id, dm_id):
    '''
    Summary:
        og_message_id is the original message. 
        
        channel_id is the channel that the message is being shared to, 
        and is -1 if it is being sent to a DM. 
        
        dm_id is the DM that the message is being shared to, 
        and is -1 if it is being sent to a channel.
        
        message is the optional message in addition to the shared message, 
        and will be an empty string '' if no message is given   
    Args:
        token (string): A user session token 
        og_message_id (int): the message id of the original message
        message (string): a message string added to the shared message
        channel_id (int): A channel_id number -1 if we are sharing to dms
        dm_id (int): A message_id number -1 if send to we are sharing to channels
    Returns: 
        dictionary which contains the shared_message_id
    Raises:
        AccessError when:
            the authorised user has not joined the channel or DM they are trying to share the message to
    '''
    global users, channels, next_message_id, dms, messages
    assert check_token(token)
    auth_user_id = user_from_token(token)['u_id']
    og_message_text = get_message_from_message_id(og_message_id)['message']

    shared_message = message + '\n\n' + og_message_text
    is_channel_message = (channel_id != -1)
    shared_message_id = -1
    if is_channel_message:
        if is_channel_member(auth_user_id, channel_id):
            shared_message_id = message_send_v2(token, channel_id,
                                                shared_message)['message_id']
        else:
            raise AccessError(
                f"Authorised user with id {auth_user_id} has not joined the channel they are trying to share the message to"
            )
    else:
        if is_dm_member(dm_id, auth_user_id):
            shared_message_id = message_senddm_v1(token, dm_id,
                                                  shared_message)['message_id']
        else:
            raise AccessError(
                f"Authorised user with id {auth_user_id} has not joined the DM they are trying to share the message to"
            )
    return {'shared_message_id': shared_message_id}
예제 #18
0
def message_remove_v1(token, message_id):
    '''
    Arguments:
        token (string) - the token of the user who wants to create a channel
        message_id (int) - the id of the message being removed

    Exceptions:
        InputError - Message id no longer exists
        AccessError - User did not send message and is not an owner of the channel/dm or dreams

    Return value:
        Returns {}
    '''

    # get data
    data = getData()

    # get id
    auth_user_id = findUser(token)

    # Checks the message was sent by the user requesting to edit it or
    # the user is a channel owner
    msg = get_message(message_id, data)

    if msg == -1:
        raise AccessError(description="Message does not exist")

    chan_owners = []
    if msg['channel_id'] != -1:
        chan = get_channel_details(msg, data)
        chan_owners = get_channel_owners(chan['channel_id'], data)

    if msg['u_id'] != auth_user_id and get_user_details(
            auth_user_id,
            data)['permission_id'] != 1 and auth_user_id not in chan_owners:
        raise AccessError(
            description=
            "User requesting edit did not post message or not channel/DREAMS owner"
        )

    # Remove from channels/dms list
    remove_msg_from_channel_or_dm(data, msg)

    append_user_stats(findUser(token), data)
    append_dream_stats(findUser(token), data)

    writeData(data)

    return {}
예제 #19
0
def dm_leave_v1(token, dm_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check that token is valid
    leaveid = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            leaveid = data["users"][i]["u_id"]
    if leaveid is None:
        raise AccessError("Invalid token")
    # check if the dm_id exists
    if check_dm_exists(dm_id) == False:
        raise InputError("Invalid dm")
    # check that the user attempting to leave is a member of the dm
    if check_user_in_dm(leaveid, dm_id) == False:
        raise AccessError("Authorised user needs to be a member of the dm")

    memberslist = data["dms"][dm_id]["name"].split(", ")
    memberslist.remove(data["users"][leaveid]["handle"])
    final_list = ", ".join(memberslist)

    data["dms"][dm_id]["name"] = final_list

    for i in range(len(data["dms"][dm_id]["members"])):
        if leaveid == data["dms"][dm_id]["members"][i]["u_id"]:
            del data["dms"][dm_id]["members"][i]
            break

    for i in range(len(data["dms"][dm_id]["owner_members"])):
        if leaveid == data["dms"][dm_id]["owner_members"][i]["u_id"]:
            del data["dms"][dm_id]["owner_members"][i]
            data["dms"][dm_id]["owner_members"].append(
                data["dms"][dm_id]["members"][0])

    num_dms_joined = data["user_stats"][leaveid]["stats"]["dms_joined"][-1][
        "num_dms_joined"] - 1
    dms_joined = {
        "num_dms_joined": num_dms_joined,
        "time_stamp": create_timestamp()
    }
    data["user_stats"][leaveid]["stats"]["dms_joined"].append(dms_joined)

    with open('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent=4)

    calc_involement_rate(leaveid)
    calc_utilisation_rate()

    return {}
예제 #20
0
파일: dm.py 프로젝트: Stress-Puppy/1531
def dm_leave_v1(token, dm_id):
    '''
    Summary:
        Given a DM ID, the user is removed as a member of this DM
    Args:
        token (string): A user session token 
        dm_id (int): A dm_id number
    Returns: 
        a empty dictionary
    Raises:
        InputError when:
            dm_id is not a valid DM
        AccessError when:
            Authorised user is not a member of DM with dm_id
    '''
    global users, channels, dms
    assert check_token(token)

    auth_user = user_from_token(token)
    if valid_dm(dm_id) == False:
        raise InputError(f"dm_id is not a valid DM")

    current_dm = find_dm(dm_id)  #find the current dm

    if auth_user['u_id'] not in current_dm['members']:
        raise AccessError(f"Authorised user is not a member of DM with dm_id")

    # Remove dm from user's list of dms
    auth_user['dms'].remove(dm_id)
    update_user_dm_stats(auth_user['u_id'])

    # Remove user from dm's members list
    current_dm['members'].remove(auth_user['u_id'])

    return {}
예제 #21
0
def channel_details(token, channel_id):
    '''
        returns a dictionary of information about the channel and it's users
    '''
    user_id = check_token(token)
    if not is_valid_channel(channel_id):
        raise InputError(description="Invalid channel id")

    if not is_user_a_member(channel_id, user_id):
        raise AccessError(
            description="User does not have access to this channel")
    owner_members = []
    all_members = []
    for user_id in get_channel_owners(channel_id):
        member_info = get_member_information(user_id)
        owner_members.append(member_info)
        all_members.append(member_info)

    for user_id in get_channel_members(channel_id):
        member_info = get_member_information(user_id)
        all_members.append(member_info)
    return {
        'name': get_channels()[channel_id]['name'],
        'owner_members': owner_members,
        'all_members': all_members
    }
예제 #22
0
def channels_listall_v2(token):
    '''
    Provides a list of all channels (and their associated details)

    Arguments:
        auth_user_id (integer) - id of user whose channels are to be listed

    Exceptions:
        AccessError - Occurs when the authorised user does not have a corresponding
                      u_id
    Return Value:
        { channels }
    '''
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check if token is valid - still have to do
    auth_user_id = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            auth_user_id = int(data['users'][i]['u_id'])
    if auth_user_id is None:
        raise AccessError("Invalid token")
    userch = []
    for channel in data['channels']:
        new_dict = {
            'channel_id': channel["channel_id"],
            'name': channel['name']
        }
        userch.append(new_dict)
    return {'channels': userch}
예제 #23
0
def message_sendlater(token, channel_id, message, time_sent):
    '''
    sends a message at a given time_sent, where time_sent is a unix timestamp
    greater than the current time.
    '''
    u_id = check_token(token)
    if not is_valid_channel(channel_id):
        raise InputError(description="No channel exists with that ID")
    if not is_user_a_member(channel_id, u_id):
        raise AccessError(description='You are not a member of this channel')
    if len(message) > 1000 or len(message) < 1:
        raise InputError(
            description=
            'Your message should be less than 1000 characters and at least 1 character'
        )
    curr_time = get_current_timestamp()
    if curr_time >= time_sent:
        raise InputError(description="You can not send a message back in time")
    delay = time_sent - curr_time
    message_id = get_num_messages()
    set_num_messages(message_id + 1)
    message_template = create_message(u_id, message_id, time_sent, message)
    timer = Timer(delay, sendlater_end, args=[channel_id, message_template])
    timer.start()
    return {'message_id': message_id}
예제 #24
0
def message_pin(token, message_id):
    '''
    Pins a message in a channel
    '''
    u_id = check_token(token)
    channel_specific = get_channel_by_msg_id(message_id)
    message_specific = get_message_by_msg_id(message_id)

    if u_id not in channel_specific['members'] and not is_channel_owner(
            token, channel_specific):
        raise AccessError(
            description=
            'The authorised user is not a member of the channel that the message is within'
        )

    if not is_channel_owner(token, channel_specific):
        raise InputError(description='The authorised user is not an owner')

    if message_specific['is_pinned']:
        raise InputError(
            description='Message with ID message_id is already pinned')

    if is_channel_owner(token, channel_specific
                        ) is True and message_specific['is_pinned'] is False:
        message_specific['is_pinned'] = True

    return {}
예제 #25
0
def admin_userpermission_change_v1(token, u_id, permission_id):
    """Summary
        Enables a Dreams owner to change the permissions of another user between Dreams owner (1) and
        standard user (2).
    Args:
        token (string): User session token
        u_id (integer): User id number
        permission_id (integer): Either 1, indicating Dreams owner, or 2, indicating standard user
    
    Returns:
        Empty dictionary
    
    Raises:
        AccessError: When an invalid token value is given, or when the user associated with the token
                     is not a Dreams owner
        InputError: When permission_id does not refer to a valid permission, or 
                    u_id does not refer to a valid user
    """
    check_token(token)  # Check for invalid token

    if user_from_token(token)['permission'] != 1:
        raise AccessError("Authorised user is not an owner.")

    if not 1 <= permission_id <= 2:  # Check for invalid permission_id
        raise InputError("permission_id does not refer to a valid permission.")

    # Search for user with user id u_id and change their permission if found
    for user in users:
        if user['u_id'] == u_id:
            user['permission'] = permission_id
            return {}
    raise InputError("u_id does not refer to a valid user.")
예제 #26
0
def user_profile_sethandle_v1(token, handle_str):
    # token check
    if check_token_valid(token) is False:
        raise AccessError("Invalid Token")

    handle = ''.join(handle_str.split())
    handle = handle.replace("@","")
    handle = handle.lower()

    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)

    for i in range(len(data['users'])):
        if data['users'][i]['handle'] == handle:
            raise InputError("Handle already in use")

    for j in range(len(data['users'])):
        if data['users'][j]['token'] == token:
            if len(handle) < 3 or len(handle) > 20:
                raise InputError("Invalid handle")

            data['users'][j]['handle'] = handle

            with open('src/data.json', 'w') as FILE:
                json.dump(data,FILE, indent = 4)

    return {
    }
예제 #27
0
def user_profile_setname_v1(token, name_first, name_last):

    if check_token_valid(token) is False:
        raise AccessError("Invalid Token")

    # checks if first and last names are between 1-50 characters long
    if len(name_first) < 1 or len(name_first) > 50:
        raise InputError("Name must be between 1-50 characters")
        
    if len(name_last) < 1 or len(name_last) > 50:
        raise InputError("Name must be between 1-50 characters")

    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)

    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            data['users'][i]['name_first'] = name_first
            data['users'][i]['name_last'] = name_last

            with open('src/data.json', 'w') as FILE:
                json.dump(data,FILE, indent = 4)

    return {
    }
예제 #28
0
def search_v2(token, query_str):
    
    # token check
    if check_token_valid(token) is False:
        raise AccessError("Invalid Token")

    messages = []

    # append to list all messages that match query string from
    # channels/DM that user has joined
    with open ("src/data.json") as FILE:
        data = json.load(FILE)

    u_id = convert_token(token)
    for i in range(len(data['messages'])):
        dm_id = data['messages'][i]['dm_id']
        channel_id = data['messages'][i]['channel_id']
        if dm_id == -1:
            if check_user_in_channel(u_id, channel_id):
                if query_str.lower() in data['messages'][i]['message'].lower():
                    messages.append(data['messages'][i])
        else:
            if check_user_in_dm(u_id, dm_id):
                if query_str.lower() in data['messages'][i]['message'].lower():
                    messages.append(data['messages'][i])
    
    print(messages)
    return {
        'messages': messages
    }
예제 #29
0
def notifications_get_v1(token):
    '''
    channel invite, channel addowner, channel removeowner
    message send, message share
    dm create, dm invite, senddm,
    admins
    '''

    # token check
    if check_token_valid(token) is False:
        raise AccessError("Invalid Token")

    with open ("src/data.json") as FILE:
        data = json.load(FILE)
        
    user_id = convert_token(token)
    notifications = []
    count = 0
    for i in range(len(data["notifications"])):
        if count < 20:
            if data["notifications"][i]["u_id"] == user_id:
                notification = {
                    "channel_id": data["notifications"][i]["channel_id"],
                    "dm_id": data["notifications"][i]["dm_id"],
                    "notification_message": data["notifications"][i]["notification_message"]
                }
                notifications.insert(0,notification)
            else:
                break
            count += 1
    
    return {
        "notifications": notifications
    }
예제 #30
0
def permission_change(token, u_id, permission_id):
    '''change a user's permissions on the server

    :param token: jwt token
    :type token: str
    :param u_id: User id corresponding to the target user
    :type u_id: int
    :param permission_id: ID of user new permissions
    :type permission_id: int
    :raises InputError: u_id does not correspond to a user
    :raises InputError: Invalid Permission ID
    :raises AccessError: User is not a slackr owner
    :return: empty dictionary
    :rtype: dict
    '''
    user_id = check_token(token)
    if not user_id in get_slackr_owners():
        raise AccessError(
            description='You are not permitted to perform this action')

    if not is_valid_user(u_id):
        raise InputError(description='User does not exist')
    if permission_id not in (1, 2):
        raise InputError(description='Invalid permission ID')
    # all possible errors raised.
    if permission_id == 1:
        get_users()[u_id]['is_owner'] = True
    elif permission_id == 2:
        get_users()[u_id]['is_owner'] = False

    return {}