Exemplo n.º 1
0
def addmessage(conversation_id):
    '''
    This function allows you to add a new message in a conversation. 3 errors are reported.
    '''
    print(f'Requesting to add a message in a chat-room {conversation_id}')
    if db.chatItem.find_one({'_id': ObjectId(conversation_id)}):
        user_id = request.args.get('user_id')
        text_add = request.args.get('text')
        if not user_id:
            raise APIError('Error. user_id doesn\'t exist in database.')
        check_usuario = db.chatItem.find_one({
            "_id": ObjectId(conversation_id),
            'users_ids': {
                '$eq': f'{user_id}'
            }
        })
        username = db.user.find_one({'_id': ObjectId(user_id)})
        if check_usuario:
            db.chatItem.update({"_id": ObjectId(conversation_id)}, {
                '$addToSet': {
                    "messages": {
                        'username': username['username'],
                        'user_id': user_id,
                        'message': text_add
                    }
                }
            })
            return {'conversation_id': conversation_id, 'messages': text_add}
        raise APIError('Error. user_id doesn\'t exist in this chat')
    raise APIError('Error. chat doesn\'t exist')
Exemplo n.º 2
0
def adduser(conversation_id):
    '''
    This function allows you to add a user to a conversation. 3 errors are reported.
    '''
    print(f'Requesting to add users in the chat-room {conversation_id}')
    chat = db.chatItem.find_one({'_id': ObjectId(conversation_id)})
    if len(list(chat)) > 0:
        user_id = request.args.get('user_id')
        if not user_id:
            raise APIError('Error. user_id doesn\'t exist in database.')
        if not db.chatItem.find_one(
            {
                "_id": ObjectId(conversation_id),
                'users_ids': {
                    '$eq': user_id
                }
            }, {'_id': 0}):
            db.chatItem.update({"_id": ObjectId(conversation_id)},
                               {'$addToSet': {
                                   "users_ids": ''.join(user_id)
                               }})
            return db.chatItem.find_one({"_id": ObjectId(conversation_id)},
                                        {'_id': 0})
        raise APIError('Error. user_id already in this chat')
    raise APIError('Error. chat doesn\'t exist')
Exemplo n.º 3
0
def get_chat(chat_name):
    '''
    Function that allows you to create a new chat-room.
    If "users" query parameters exist, you also can populate the room. 
    '''
    print(f'Requesting to create the chat-room {chat_name}')
    res = db.chatItem.find_one({
        'chat_name': chat_name,
    }, {'_id': 0})
    if res:
        raise APIError('Chat name already exist. Change name please! :)')
    # define query params and use the users_id array to check if the Ids are corrects
    user_id = transform_strings_ObjectId(request.args.get('user_id'))
    if not user_id:
        raise APIError(
            'Error. users_ids doesn\'t exist in database. It is not possible to create an empty chat'
        )
    # create room with users
    db.chatItem.insert({
        'chat_name':
        chat_name,
        'users_ids': [
            u_id if db.user.find_one({'_id': ObjectId(u_id)}) else None
            for u_id in user_id
        ]
    })
    res = db.chatItem.find_one({'chat_name': chat_name})
    return json.loads(json_util.dumps(res))
Exemplo n.º 4
0
def insertChat():
    """
  Function that allows creation of a new chats groups
    """ 
    arr = request.args.get("ids")
    name= request.args.get("name",default='')
    
    #creation of a new chats with the users included in arr
    if arr:
        dic={   
            'chat_name': name,
            'users_list':[],
            'messages_list':[]
        }
        chat_id=db_chats.insert_one(dic)
        #insert the users in the chats
        chatId=chat_id.inserted_id
        for user_id in arr:
            addChatUser(chatId, user_id)
        #update of the users chats_list by adding the chats id
        for user_id in arr:
            post=db.find_one({'_id':ObjectId(user_id)})
            post['chats_list'].append(ObjectId(chat_id.inserted_id))
            db.update_one({'_id':ObjectId(user_id)}, {"$set": post}, upsert=False)

    else:
        print("ERROR")
        raise APIError("Tienes que mandar un query parameter ?ids=<arr>&name=<chatname>")
    
    return json.dumps({'chat_id':str(chat_id.inserted_id)})
Exemplo n.º 5
0
def recommenderAnalysis(user_id):
    '''
    This function allows you to perform a recommendation analysis of similar users.
    Based on the topics of the chats, it is possible to identify users who may have affinities with the selected user
    '''
    print(
        f'Requesting by {user_id} for a recommendation of users with similar characteristics'
    )
    user = db.chatItem.find({'users_ids': {'$eq': user_id}})
    if len(list(user)) != 0:
        chat = db.chatItem.find({'_id': {'$ne': None}})
        chat_json = json.loads(json_util.dumps(chat))
        chat_mess = dict()
        count = 0
        for conversation in chat_json:
            for message in conversation.items():
                for mess in message[1]:
                    try:
                        chat_mess[f'{count}'] = {
                            'username': mess['username'],
                            'message': mess['message']
                        }
                        count += 1
                    except:
                        pass
        matrix = createMatrixSimilarity(chat_mess, user_id)
        user = matrix[:1].to_dict()
        reccom_user = matrix[1:6].to_dict()
        return {'Me': user, 'Recommended users': reccom_user}
    raise APIError('The user is not present in any chat')
Exemplo n.º 6
0
def creandoUsuarioDiferenteAlDeMiriam(username):
    name_taken = db.user.distinct("name")
    add_user= {"username": username}
    if username in name_taken:
        raise APIError(f"User_name {username} already exists")
    else:
        user_id = db.user.insert_one(add_user)
        return dumps(f"The user was succesfully created!! user_name: {username}, user_id: {user_id.inserted_id}")
Exemplo n.º 7
0
def createChat():
    """    
    This function creates a new chat with Participants as a param and assigns a groupname to the chat.
    """
    group = request.args.getlist("Participants")
    group_name= request.args.get("Group_name")
    if db.convo.find_one({"Group_name":group_name}) == None:
        create_chat = db.convo.insert({"Group_name":group_name, "Participants": participants}) 
        return dumps(f"The chat was succesfully created!! convo_id: {create_chat}")
    raise APIError(f"Group_name {group_name} already exists")
Exemplo n.º 8
0
def create_user(username):
    """
    Function that allows creation of a new username but will warn us if name is already selected
    """
    res = db.find_one({'username': username},{'_id':0})
    if res:
        raise APIError('Username already exists. Select a new option')
    else:
        dic={
            'user_name':username,
            'chats': []
        }
    user_id=db.insert_one(dic)
    return json.dumps({'user_id':str(user_id.inserted_id)})
Exemplo n.º 9
0
def get_user(username):
    '''
    This function allows you to create a new username.
    If it is already present in the app database, an error will be displayed
    '''
    #username = request.args.get('username') this is for query parameter
    print(f'Requesting to create the username {username}')
    res = db.user.find_one({
        'username': username,
    }, {'_id': 0})
    if res:
        raise APIError('Username already exists. Please choose another one!')
    db.user.insert({'username': username})
    res_ok = db.user.find_one({'username': username})
    res_ok2 = json.loads(json_util.dumps(res_ok))
    return {'status': 'ok', 'data': res_ok2}
Exemplo n.º 10
0
def listMessage(conversation_id):
    '''
    This function allows you to download and view the messages of a conversation through a request from the API
    '''
    print(f'Requesting to list all message in the chat-room {conversation_id}')
    chat = db.chatItem.find_one({'_id': ObjectId(conversation_id)})
    if chat:
        try:
            chat_json = json.loads(json_util.dumps(chat))
            return {
                'conversation_id': chat_json['_id'],
                'chat_name': chat_json['chat_name'],
                'messages': chat_json['messages']
            }
        except:
            raise Error404('List empty')
    raise APIError('Error. chat doesn\'t exist')
def sentimentAnalysis(conversation_id):
    '''
    This function receives an Id_conversation as a parameter, returning a sentiment analysis of all chat messages
    '''
    print(
        f'Requesting to a sentiment analysis from the chat-room {conversation_id}'
    )
    chat = db.chatItem.find_one({'_id': ObjectId(conversation_id)})
    if chat:
        chat_json = json.loads(json_util.dumps(chat))
        chat_mess = []
        for message in chat_json.items():
            for mess in message[1]:
                try:
                    chat_mess.append(mess['message'])
                except:
                    pass
        if len(chat_mess) > 0:
            return json.dumps(polarityBySentence(chat_mess))
        raise Error404('List empty')
    raise APIError('Error. chat doesn\'t exist')
Exemplo n.º 12
0
def addChatUser(chat_id, user_id=None):
    if user_id==None:
        user_id= request.args.get("user_id")
    if user_id!=None and chat_id!=None:
        #update of the chats document by adding the user id
        post=db_chats.find_one({'_id':ObjectId(chat_id)})
        if ObjectId(user_id) not in post['users_list']:
            post['users_list'].append(ObjectId(user_id))
        db_chats.update_one({'_id':ObjectId(chat_id)}, {"$set": post}, upsert=False)
        
        #update of the user permissions by adding the chats id
        post=db.find_one({'_id':ObjectId(user_id)})
        if ObjectId(chat_id) not in post['chats_list']:
            post['chats_list'].append(ObjectId(chat_id))
        db.update_one({'_id':ObjectId(user_id)}, {"$set": post}, upsert=False)
    elif not chat_id:
        print("ERROR")
        raise Error404("chat_id not found")
    elif not user_id:
        print("ERROR")
        raise APIError("You should send these query parameters ?user_id=<user_id>")

    return json.dumps({'chat_id': str(chat_id)})