Example #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 {}
Example #2
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"],
    }
Example #3
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
    }
Example #4
0
def message_senddm_v1(token, dm_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_dm(u_id, dm_id) == False:
        raise AccessError("Authorised user is not part of the channel")
    channel_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
    }

    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)
    data["messages"].append(new_message)

    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"],
    }
Example #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 {}
Example #6
0
def dm_messages_v1(token, dm_id, start):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check that token is valid
    userid = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            userid = data['users'][i]['u_id']
    if userid is None:
        raise AccessError("Invalid token")
    # check if the dm_id exists
    if check_dm_exists(dm_id) == False:
        raise InputError("Invalid dm")
    # check user belongs in dm
    if check_user_in_dm(userid, dm_id) == False:
        raise AccessError("Authorised User must be a part of the dm")

    end = start + 50
    counter = 0
    messagelist1 = []
    messagelist2 = []
    finallist = []
    for i in range(len(data["messages"])):
        if data["messages"][i]["dm_id"] == dm_id:
            messagelist1.insert(0, data["messages"][i])
            messagelist2.append(data["messages"][i])
    # check for start being less than total messages in dm
    if start > len(messagelist1):
        raise InputError("Not enough messages in dm")

    for i in range(start, len(messagelist1)):
        if counter is 50:
            break
        if end > len(messagelist1):
            finallist.append(messagelist1[i])
        else:
            finallist.insert(0, messagelist2[i])
        counter += 1
    if counter < 50:
        end = -1

    return {
        'messages': finallist,
        'start': start,
        'end': end,
    }
Example #7
0
def message_react_v1(token, message_id, react_id):
    ''' 
    Given a message within a channel the authorised user is
    part of, add a "react" to that particular message
    '''
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check for valid token and get u_id
    reactorid = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            reactorid = data["users"][i]["u_id"]
    if reactorid is None:
        raise AccessError("Invalid token")
    # check message exists
    if check_message_exists(message_id) == False:
        raise InputError("Message does not exist")
    # check whether user is within channel/Dm which the message is in
    for i in range(len(data["messages"])):
        if data["messages"][i]["message_id"] == message_id:
            channel_id = data["messages"][i]["channel_id"]
            dm_id = data["messages"][i]["dm_id"]

    if channel_id == -1:
        if check_user_in_dm(reactorid, dm_id) == False:
            raise AccessError("Authorised user is not part of the dm")
    if dm_id == -1:
        if check_user_in_channel(reactorid, channel_id) == False:
            raise AccessError("Authorised user is not part of the channel")
    # check react_id is valid
    if react_id != 1:
        raise InputError("Invalid react_id")
    reacts_list = data["messages"][message_id]["reacts"]
    # check if react_id already exists
    if reactorid in reacts_list[int(react_id) - 1]['u_ids']:
        raise InputError("Message already contains this react_id")
    # adding the u_id of the person making a react
    reacts_list[int(react_id) - 1]['u_ids'].append(reactorid)
    reacts_list[int(react_id) - 1]['is_this_user_reacted'] = True

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

    return {}
Example #8
0
def message_unpin_v1(token, message_id):
    '''
    Given a message within a channel, mark it as "pinned" to
    be given special display treatment by the frontend
    '''
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check for valid token and get u_id
    pinnerid = None
    for i in range(len(data['users'])):
        if data['users'][i]['token'] == token:
            pinnerid = data["users"][i]["u_id"]
    if pinnerid is None:
        raise AccessError("Invalid token")
    # check that message_id is valid
    if check_message_exists(message_id) == False:
        raise InputError("Message does not exist")
    for i in range(len(data["messages"])):
        if data["messages"][i]["message_id"] == message_id:
            channel_id = data["messages"][i]["channel_id"]
            dm_id = data["messages"][i]["dm_id"]
    # check whether user is within channel/Dm which the message is in
    if channel_id == -1:
        if check_user_in_dm(pinnerid, dm_id) == False:
            raise AccessError("Authorised user is not part of the dm")
        if check_owner_of_dm(pinnerid, dm_id) == False:
            raise AccessError("Authorised user is not an owner of the dm")
    if dm_id == -1:
        if check_user_in_channel(pinnerid, channel_id) == False:
            raise AccessError("Authorised user is not part of the channel")
        if check_owner_of_channel(pinnerid, channel_id) == False:
            raise AccessError("Authorised user is not an owner of the channel")
    # check whether the message is already unpinned
    if data["messages"][message_id]['is_pinned'] == False:
        raise InputError("Message is already unpinned")
    # unpin the message
    data["messages"][message_id]['is_pinned'] = False
    with open('src/data.json', 'w') as FILE:
        json.dump(data, FILE, indent=4)

    return {}
Example #9
0
def dm_details_v1(token, dm_id):
    with open('src/data.json', 'r') as FILE:
        data = json.load(FILE)
    # check if token exists
    auth_user_id = None
    for user in data["users"]:
        if user["token"] == token:
            auth_user_id = user["u_id"]
    if auth_user_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 whether user belongs in this dm
    if check_user_in_dm(auth_user_id, dm_id) == False:
        raise AccessError("Authorised user needs to be a \
        member of the dm")
    return {
        'name': data["dms"][dm_id]['name'],
        'members': data["dms"][dm_id]['members']
    }
Example #10
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"],
    }