Ejemplo n.º 1
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 {}
Ejemplo n.º 2
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"],
    }
Ejemplo n.º 3
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 {}
Ejemplo n.º 4
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 {}
Ejemplo n.º 5
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 {}
Ejemplo n.º 6
0
def channels_create_v2(token, name, is_public):
    '''
    Creates a new channel with that name that is either a public or private channel

    Arguments:
        auth_user_id (integer) - id of user who will own the new channel created
        name (string) - name of channel to be created
        is_public (boolean) - confirms whether channel is public or private

    Return Value:
        { channel_id }
    '''
    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(name) > 20:
        raise InputError("Name is longer than the 20 character limit")
    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"]
    }
    # store the details of the new channel in a dictionary
    new_channel = {
        "channel_id": len(data["channels"]),
        "name": name,
        "owner_members": [],
        "all_members": [],
        "is_public": is_public,
    }
    # add the creator of the channel to the owners list and members list
    new_channel["owner_members"].append(new_user)
    new_channel["all_members"].append(new_user)

    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()
    }

    num_channels = data["dreams_stats"]["channels_exist"][-1][
        "num_channels_exist"] + 1
    dreams_channels = {
        "num_channels_exist": num_channels,
        "time_stamp": create_timestamp()
    }

    with open('src/data.json') as FILE:
        data2 = json.load(FILE)
        temp = data2["channels"]
        y = new_channel
        temp.append(y)

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

        temp3 = data2["dreams_stats"]["channels_exist"]
        x = dreams_channels
        temp3.append(x)

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

    calc_involement_rate(u_id)
    calc_utilisation_rate()

    return {'channel_id': new_channel["channel_id"]}
Ejemplo n.º 7
0
def auth_register_v2(email, password, name_first, name_last):
    '''
    function takes new users first name, last name, email and password and generates
    a new user dictionary with all the input data, handle which is a concatenation
    of the users first and last name and a user id and generates authentication 
    token for the users first session

    Arguments:
        email (string) - email entered by new user
        password (string) - password entered by new user
        name_first (string) - first name entered by new user
        name_last (string) - last name entered by new user

    Exceptions:
        InputError - Occurs when:
            * email is not valid (syntax)
            * email address is being used by another user
            * password entered is less than 6 characters long
            * name_first not between 1-50 characters inclusive
            * name_last not between 1-50 characters inclusive

    Return Value:
        Returns auth_user_id on condition that the data entered is all valid and 
        unused as specified in exceptions above
        
        New user is also stored as a dictionary in the users list in the data 
        dictionary in data.py
    '''

    email_syntax = re.compile(
        '^[a-zA-Z0-9]+[\\._]?[a-zA-Z0-9]+[@]\\w+[.]\\w{2,3}$')
    if not email_syntax.match(email):
        raise InputError("Invalid email")

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

    # checks if email has already been used
    for i in range(len(data["users"])):
        if data['users'][i]['email'] == email:
            raise InputError("Email already in use")

    # checks if password is less than 6 characters
    if len(password) < 6:
        raise InputError("Password too short")

    # 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")

    # creates handle from concatenation of first and last name
    # then removes any whitespace and @ characters
    # then checks if handle is longer than 20 characters and caps it at 20
    handle = name_first.lower() + name_last.lower()
    handle = ''.join(handle.split())
    handle = handle.replace("@", "")
    if len(handle) > 20:
        handle = handle[0:20]

    # loop to check if handle already exists and append a number to the end
    orig_handle = handle
    count = 0
    for i in range(len(data["users"])):
        if data['users'][i]['handle'] == handle:
            handle = orig_handle + str(count)
            count += 1

    u_id = len(data["users"])
    token = make_token(u_id)
    if u_id == 0:
        permission_id = 1
    else:
        permission_id = 2
    # create a new dictionary for the user with all relevant data
    new_user = {
        "u_id": u_id,
        "email": email,
        "password": hashlib.sha256(password.encode()).hexdigest(),
        "name_first": name_first,
        "name_last": name_last,
        "handle": handle,
        "token": token,
        "permission_id": permission_id,
        "logged_in": True,
    }

    new_user_stats = {
        "u_id": u_id,
        "stats": {
            "channels_joined": [
                {
                    "num_channels_joined": 0,
                    "time_stamp": create_timestamp()
                },
            ],
            "dms_joined": [{
                "num_dms_joined": 0,
                "time_stamp": create_timestamp()
            }],
            "messages_sent": [{
                "num_messages_sent": 0,
                "time_stamp": create_timestamp()
            }],
            "involvement_rate":
            0.0
        }
    }

    # appends the new dictionary to the "users" list in the data dictionary in data.py

    with open('src/data.json') as FILE:
        data2 = json.load(FILE)
        temp = data2["users"]
        y = new_user
        temp.append(y)
        temp2 = data2["user_stats"]
        z = new_user_stats
        temp2.append(z)

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

    calc_utilisation_rate()

    # return the user id of the newly registered user as the authenticated user id
    return {
        'token': new_user["token"],
        'auth_user_id': new_user["u_id"],
    }
Ejemplo n.º 8
0
def channel_invite_v2(token, channel_id, u_id):
    '''
    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.

    Arguments:
        auth_user_id (integer)  - id of user sending invite
        channel_id (integer)    - id of channel being invited to
        u_id (integer) - id of user being invited to channel

    Exceptions:
        InputError  - Occurs when channel_id does not refer to a valid channel.
                    - Occurs when u_id does not refer to a valid user
        AccessError - Occurs when the auth_user_id passed in is not valid
                    - Occurs when the authorised user is not already
                    a member of the channel

    Return Value:
        Returns {}
    '''

    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check that token is valid
    inviteid = None
    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 channel_id exists
    if check_channel_exists(channel_id) == False:
        raise InputError("Invalid channel")
    # 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 channel
    if check_user_in_channel(inviteid, channel_id) == False:
        raise AccessError(
            "Authorised user needs to be a member of the channel")

    invited_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"]
    }
    # check if the user is already a member of the channel
    for i in range(len(data["channels"][channel_id]["all_members"])):
        if u_id == data["channels"][channel_id]["all_members"][i]["u_id"]:
            raise InputError("User already a member of channel")

    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()
    }

    with open('src/data.json') as FILE:
        data2 = json.load(FILE)
        temp = data2["channels"][channel_id]["all_members"]
        y = invited_user
        temp.append(y)
        # if user invited is an owner
        if data2["users"][u_id]["permission_id"] is 1:
            temp2 = data2["channels"][channel_id]["owner_members"]
            y = invited_user
            temp2.append(y)

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

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

    notif_msg = data["users"][inviteid]["handle"] + " invited you to " + data[
        "channels"][channel_id]["name"]
    create_notifications(u_id, channel_id, -1, notif_msg)

    calc_involement_rate(u_id)
    calc_utilisation_rate()

    return {}
Ejemplo n.º 9
0
def channel_join_v2(token, channel_id):
    '''
    Given a channel_id of a channel that the authorised user can join,
    adds them to that channel.

    Arguments:
        auth_user_id (integer) - id of user who can join the channel
        channel_id (integer) - id of channel

    Exceptions:
        InputError - Occurs when channel_id does not refer to a valid channel.
        AccessError - Occurs when channel_id refers to a channel that is
                    private (when authorised user is not a global owner)
                    
    Return Value:
        Returns {}
    '''

    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")

    for i in range(len(data['channels'][channel_id]['all_members'])):
        if data['channels'][channel_id]['all_members'][i]['u_id'] == u_id:
            raise InputError("User is already part of the channel")

    joining_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"]
    }

    if data["channels"][channel_id]["is_public"]:
        if data["users"][u_id]["permission_id"] is 1:
            data["channels"][channel_id]["owner_members"].append(joining_user)
        if len(data["channels"][channel_id]["all_members"]) == 0:
            data["channels"][channel_id]["owner_members"].append(joining_user)
        data["channels"][channel_id]["all_members"].append(joining_user)
    else:
        raise AccessError("Channel is not public")

    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()
    }

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

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

    calc_involement_rate(u_id)
    calc_utilisation_rate()

    return {}
Ejemplo n.º 10
0
def message_remove_v1(token, message_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check to see if message exists
    if check_message_exists(message_id) == False:
        raise InputError("Message does not exist")
    u_id = None
    # token check
    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 message was sent by the authorised user making the request
    valid = True
    if check_message_sent_by_user(u_id, message_id) == False:
        valid = False
    # check to see if token belongs to the owner of message 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["channels"][channel_id]["owner_members"])):
            if data["channels"][channel_id]["owner_members"][i][
                    "u_id"] == u_id:
                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"
            )

    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)

    for i in range(len(data["messages"])):
        if data["messages"][i]["message_id"] == message_id:
            del data["messages"][i]
            break
    with open('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent=4)

    calc_involement_rate(u_id)
    calc_utilisation_rate()

    return {}
Ejemplo n.º 11
0
def message_sendlaterdm_v1(token, dm_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 
    '''
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check for valid token and get u_id
    senderid = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            senderid = data["users"][i]["u_id"]
    if senderid is None:
        raise AccessError("Invalid token")
    # check that the channel_id is valid
    if check_dm_exists(dm_id) == False:
        raise InputError("Invalid dm")
    # check that the message does not contain more than 1000 characters
    if len(message) > 1000:
        raise InputError("Message is longer than the 1000 character limit")
    # check sender is part of the channel
    if check_user_in_dm(senderid, dm_id) == False:
        raise AccessError("Authorised user is not part of the dm")
    # check time sent is not in the past
    now = datetime.now()
    if int(time_sent) < int(datetime.timestamp(now)):
        raise InputError("Time sent is in the past")
    timeout = int(time_sent) - int(datetime.timestamp(now))

    time.sleep(timeout)
    channel_id = -1
    new_message = {
        'message_id': get_new_message_id(),
        'u_id': senderid,
        'message': message,
        'time_created': time_sent,
        'channel_id': channel_id,
        'dm_id': dm_id,
        'reacts': [{
            'react_id': 1,
            'u_ids': [],
            'is_this_user_reacted': False
        }],
        'is_pinned': False
    }

    num_messages_sent = data["user_stats"][senderid]["stats"]["messages_sent"][
        -1]["num_messages_sent"] + 1
    messages_sent = {
        "num_messages_sent": num_messages_sent,
        "time_stamp": time_sent
    }
    data["user_stats"][senderid]["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": time_sent
    }
    data["dreams_stats"]["messages_exist"].append(dreams_messages)

    data["messages"].append(new_message)

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

    calc_involement_rate(senderid)
    calc_utilisation_rate()

    return {
        'message_id': new_message["message_id"],
    }
Ejemplo n.º 12
0
def dm_create_v1(token, u_ids):
    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:
            # getting the specfic u_id for the owner
            u_id = data['users'][i]['u_id']
    if u_id is None:
        raise AccessError("Invalid token")
    new_dm = {
        "dm_id": len(data["dms"]),
        "name": [],
        "members": [],
        "owner_members": [],
    }
    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"]
    }
    new_dm["owner_members"].append(new_owner)
    new_dm["members"].append(new_owner)
    # go through each u_id separately
    '''
    u_ids contains the user(s) that this DM is directed to, and will not include the creator. 
    '''
    memberslist = []
    for user_id in u_ids:
        '''
        name should be automatically generated based on the user(s) that is 
        in this dm (have to also include owner). The name should be an 
        alphabetically-sorted, comma-separated list of user handles, 
        e.g. 'handle1, handle2, handle3'.
        '''
        if check_user_exists(user_id) == False:
            raise InputError("Invalid User")
        handlenew = data['users'][user_id]['handle']
        new_user = {
            'u_id': user_id,
            'email': data["users"][user_id]["email"],
            'name_first': data["users"][user_id]["name_first"],
            'name_last': data["users"][user_id]["name_last"],
            'handle': handlenew
        }
        memberslist.append(handlenew)
        # adding user info into dm member list
        new_dm["members"].append(new_user)
    memberslist.append(data["users"][u_id]["handle"])

    sortedlist = sorted(memberslist, key=str.lower)
    new_dm["name"] = ", ".join(sortedlist)
    data["dms"].append(new_dm)

    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)

    for user_id in u_ids:
        num_dms_joined = data["user_stats"][user_id]["stats"]["dms_joined"][
            -1]["num_dms_joined"] + 1
        dms_joined = {
            "num_dms_joined": num_dms_joined,
            "time_stamp": create_timestamp()
        }
        data["user_stats"][user_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', 'r') as FILE:
        data2 = json.load(FILE)

    dm_id = len(data2["dms"]) - 1

    notif_msg = data2["users"][u_id]["handle"] + " added you to dm " + data2[
        "dms"][dm_id]["name"]
    for i in range(len(data2["dms"][dm_id]["members"])):
        member_id = data2["dms"][dm_id]["members"][i]["u_id"]
        if member_id == u_id:
            pass
        else:
            create_notifications(member_id, -1, dm_id, notif_msg)

    calc_involement_rate(u_id)
    for user_id in u_ids:
        calc_involement_rate(user_id)
    calc_utilisation_rate()

    return {'dm_id': new_dm["dm_id"], 'dm_name': new_dm["name"]}