Ejemplo n.º 1
0
def findList(chatID):
    try:
        chat = db.chats.find({"_id": ObjectId(chatID)}).count()
    except:
        # cuando los id no son validos
        return {"message": "The chat ID is not valid", "status": "error"}
    if chat == 0:
        raise Error404(
            "The chat ID does not exist in the database. Please, confirm the chat ID using /chat/<chatname>"
        )
    message = db.messages.find({'chat.$id': ObjectId(chatID)}, {
        "text": 1,
        "date-time": 1,
        'user.$id': 1
    })
    if message.count() == 0:
        raise Error404("The chat with this ID does not contain messages yet")
    dict_messages = {}
    for mes in message:
        message_id = (re.search(r"\w+\d+\w*", dumps(mes["_id"]))).group()
        user_id = (re.search(r"\w+\d+\w*", dumps(mes["user"]["$id"]))).group()
        dict_messages["Message ID:" + message_id] = [
            mes["text"], "User ID:" + user_id, "Date:" + mes["date-time"]
        ]
    return dict_messages
Ejemplo n.º 2
0
def add_message(conversation_name):
    conversation = db['conversations'].find_one(
        {"conversation_name": conversation_name}, {
            "_id": 1,
            "conversation_name": 1,
            "users": 1
        })
    if not conversation:
        raise Error404("Conversation doesn't exist in database")
    username = request.args.get("username").lower()
    user = db['users'].find_one({"username": username}, {"username": 1})
    if not user:
        raise Error404("User not found in database")
    if user["username"] not in conversation["users"]:
        raise APIError("User is not in this conversation.Please, add it first")

    message = request.args.get("message").replace("%20", " ")
    message_id = db["messages"].insert_one({
        "message":
        message,
        "user": [username, user["_id"]],
        "conversation":
        [conversation["conversation_name"], conversation["_id"]]
    }).inserted_id
    db["users"].update({"_id": user["_id"]},
                       {"$addToSet": {
                           "messages": message_id
                       }})
    db["conversations"].update({"_id": conversation["_id"]},
                               {"$addToSet": {
                                   "messages": message_id
                               }})
    print("hola")
    return (f"{{'message_id':{message_id}}}")
Ejemplo n.º 3
0
def add_user_to_conversation(conversation_name):
    conversation = db['conversations'].find_one(
        {"conversation_name": conversation_name}, {
            "_id": 1,
            "conversation_name": 1,
            "messages": 1
        })
    if not conversation:
        raise Error404("Conversation doesn't exist in database")
    username = request.args.get("username").lower()
    user = db['users'].find_one({"username": username}, {
        "_id": 1,
        "username": 1
    })
    if user == None:
        raise Error404("User not found in database")
    db["conversations"].update({"_id": conversation["_id"]},
                               {"$addToSet": {
                                   "users": username
                               }})
    db["users"].update({"_id": user["_id"]}, {
        "$addToSet": {
            "conversations":
            [conversation["conversation_name"], conversation["_id"]]
        }
    })
    return {username: f"added to {conversation}"}
def getUserMessage(name):
    namereg = re.compile(f"^{name}", re.IGNORECASE)
    user_message = db.messages.find({"user_name":namereg},{"_id":0,"chat_name":1,"chat_id":1,"message_id":1,"message_text":1})
    if not user_message:
        print("ERROR")
        raise Error404("Username not found")
    return dumps(user_message)
Ejemplo n.º 5
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 chat 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 chat id
        post = db.users.find_one({'_id': ObjectId(user_id)})
        if ObjectId(chat_id) not in post['chats_list']:
            post['chats_list'].append(ObjectId(chat_id))
        db.users.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)})
def getChatMessage(chatname):
    namechatreg = re.compile(f"^{chatname}", re.IGNORECASE)
    chat_message = db.messages.find({"chat_name":namechatreg},{"_id":0,"user_name":1,"user_id":1,"message_id":1,"message_text":1})
    if not chat_message:
        print("ERROR")
        raise Error404("Chatname not found")
    return dumps(chat_message)
Ejemplo n.º 7
0
def addUser(chatID, userID):
    try:
        chat = db.chats.find({"_id": ObjectId(chatID)}).count()
        user = db.users.find({"_id": ObjectId(userID)}).count()
    except:
        # cuando los id no son validos
        return {
            "message": "The user or chat ID is not valid",
            "status": "error"
        }
    if chat == 0 or user == 0:
        raise Error404(
            "The user or chat ID does not exist in the database. Please, confirm the user or chat ID using /user/<username> or /chat/<chatname>"
        )
    userInChat = db.chats.find({
        "$and": [{
            "_id": ObjectId(chatID)
        }, {
            'users.$id': ObjectId(userID)
        }]
    }).count()
    if userInChat != 0:
        raise Error404("This user is already in this chat")
    db.chats.update_one({"_id": ObjectId(chatID)}, {
        "$push": {
            "users": {
                "$ref": "users",
                "$id": ObjectId(userID),
                "$db": "api-project"
            }
        }
    })
    db.users.update_one({"_id": ObjectId(userID)}, {
        "$push": {
            "chats": {
                "$ref": "chats",
                "$id": ObjectId(chatID),
                "$db": "api-project"
            }
        }
    })
    return {
        "status":
        f"The chat with the ID '{chatID}' has a new user with the ID '{userID}'"
    }
Ejemplo n.º 8
0
def createChat(chatname, userID):
    if userID:
        try:
            #testar si el ID es valido
            usuario = db.users.find({"_id": ObjectId(userID)})
        except:
            return {"message": "The user ID is not valid", "status": "error"}
        if usuario.count() == 0:
            #el usuario ya debe existir en la base de datos usuarios si quiero introducirlo en un chat
            raise Error404(
                "The user ID doesn't exist in the database. Please, confirm the user ID using /user/<username>"
            )
    check = chatID(chatname)
    if check != "Failed":
        #no debe existir otro chat con el mismo nombre
        raise Error404(
            f"A chat with that name already exists with the ID {check}. To insert an user in it,please, use:/chat/<chatID>/adduser/<userID>"
        )
    chat_profile = {'name': chatname, 'users': []}
    db.chats.insert_one(chat_profile)
    chat_id = chatID(chatname)
    if userID:
        db.chats.update_one({"_id": ObjectId(chat_id)}, {
            "$push": {
                "users": {
                    "$ref": "users",
                    "$id": ObjectId(userID),
                    "$db": "api-project"
                }
            }
        })
        db.users.update_one({"_id": ObjectId(userID)}, {
            "$push": {
                "chats": {
                    "$ref": "chats",
                    "$id": ObjectId(chat_id),
                    "$db": "api-project"
                }
            }
        })
    return {
        "status":
        f"The chat '{chatname}' has been created with the corresponding ID {chat_id}"
    }
Ejemplo n.º 9
0
def showme(conversation_id):
    """
    Funct shows all messages from a conversation.
    """
    cursor_mensajes = db.NEWCHAT.find({"Group": conversation_id})
    mensajes = dumps(cursor_mensajes)
    print(type(mensajes))
    if mensajes != "[]":
        return mensajes
    raise Error404("Para estos parametros, no hay match! Prueba con otros.")
Ejemplo n.º 10
0
def get_user_info(username):
    user = db['users'].find_one({"username": username}, {
        "_id": 1,
        "username": 1,
        "conversations": 1,
        "messages": 1
    })
    if user == None:
        raise Error404("User not found in database")
    return dumps(user)
Ejemplo n.º 11
0
def find_closest_users(user_id):
    user = db['users'].find_one({"username":user_id},{"username":1})
    if not user:
        raise Error404("User not found in database")
    user_puntuation=value_user(user_id).compound
    print(user_puntuation)
    puntuations=pd.read_csv("././output/valorations.csv")
    puntuations["relations"]=abs(puntuations["compound"]-user_puntuation)
    names_index=puntuations.relations.sort_values()[1:4].index
    usernames=[puntuations["Unnamed: 0"][index] for index in names_index]
    return {"closest_users":" , ".join(usernames)}
Ejemplo n.º 12
0
def insertUser(username):
    if username:
        dic = {
            'user_name': username,
            'insertion_date': getDate(),
            'chats_list': []
        }
        user_id = db.users.insert_one(dic)
    else:
        print("ERROR")
        raise Error404("name not found")
    return json.dumps({'user_id': str(user_id.inserted_id)})
Ejemplo n.º 13
0
def addMessage(chatID, userID, date, text):
    #Add a message to the conversation. Check that the incoming user is part of this chat id. If not, raise an exception.
    try:
        chat = db.chats.find({"_id": ObjectId(chatID)}).count()
        user = db.users.find({"_id": ObjectId(userID)}).count()
    except:
        # cuando los id no son validos
        return {
            "message": "The user or chat ID is not valid",
            "status": "error"
        }
    if chat == 0 or user == 0:
        raise Error404(
            "The user or chat ID does not exist in the database. Please, confirm the user or chat ID using /user/<username> or /chat/<chatname>"
        )
    userInChat = db.chats.find({
        "$and": [{
            "_id": ObjectId(chatID)
        }, {
            'users.$id': ObjectId(userID)
        }]
    }).count()
    if userInChat == 0:
        raise Error404(
            "This user is not in this chat. Please, add the user to this chat before doing this step"
        )
    message = messageID(text, date, chatID, userID)
    if message != "Failed":
        raise Error404(
            f"This message from this user at that date-time is already in this chat with the ID {message}"
        )
    message_profile = {
        'text': text,
        "date-time": date,
        "chat": DBRef("chats", ObjectId(chatID), "api-project"),
        "user": DBRef("users", ObjectId(userID), "api-project")
    }
    db.messages.insert(message_profile)
    message_id = messageID(text, date, chatID, userID)
    return {"status": f"The message with the ID '{message_id}' has been added"}
Ejemplo n.º 14
0
def newfriend(user_id):
    """
    Funct returns a new friend similar to a user
    """
    if db.User.find_one({"_id": ObjectId(user_id)}) != None:
        by_id = [
            str(x["_id"]) for x in list(db.User.find({}, {"username": 0}))
        ]
        distances = createsimilars(by_id)
        return dumps(distances[user_id].sort_values(ascending=False)[1:3])
    raise Error404(
        "Parecce que estos user_id, no hay mensajes encontrados! Prueba con otros."
    )
Ejemplo n.º 15
0
def createUser(username):
    check = userID(username)
    if check != "Failed":
        raise Error404(
            f"An user with this name already exists with the ID {check}. If you want to create a different user, please, change the user name"
        )
    user_profile = {'name': username, "chats": []}
    db.users.insert_one(user_profile)
    user_id = userID(username)
    return {
        "status":
        f"The user '{username}' has been created with the corresponding ID {user_id}"
    }
Ejemplo n.º 16
0
def ReportsentAnalysis(chatID):
    try:
        chat = db.chats.find({"_id": ObjectId(chatID)}).count()
    except:
        # cuando los id no son validos
        return {"message": "The chat ID is not valid", "status": "error"}
    if chat == 0:
        raise Error404(
            "The chat ID does not exist in the database. Please, confirm the chat ID using /chat/<chatname>"
        )
    messages = db.messages.aggregate([{
        "$match": {
            "chat.$id": ObjectId(chatID)
        }
    }, {
        "$group": {
            "_id": "$user",
            "messages": {
                "$push": "$text"
            }
        }
    }])
    docs = {}
    for mes in messages:
        identificador = (re.search(r"\w+\d+\w*", dumps(mes["_id"]))).group()
        docs[identificador] = (".".join(mes['messages']))
    if not docs:
        raise Error404("The chat with this ID does not contain messages yet")
    analysis_by_user = {}
    for key, value in docs.items():
        sentiment = sia.polarity_scores(value)
        analysis_by_user[key] = sentiment
    return {
        f"Sentiment analysis per user in chat with ID {chatID}":
        analysis_by_user
    }
Ejemplo n.º 17
0
def getCompany(name):
    namereg = re.compile(f"^{name}", re.IGNORECASE)
    company = db.find_one({"name": namereg}, {
        "_id": 0,
        "name": 1,
        "home_url": 1,
        "email_address": 1
    })
    print(namereg)
    if not company:
        print("ERROR")
        raise Error404("company not found")
    print("OK")
    #return dumps(company)
    return {"status": "success", "dbresponse": dumps(company)}
Ejemplo n.º 18
0
def getChat(name):

    chatname = re.compile(f"^{name}", re.IGNORECASE)
    chat = list(
        db.Project_Api.find({"Chat": chatname}, {
            "_id": 0,
            "Name": 1,
            "Frase": 1,
            "Date": 1
        }))
    print(chatname)
    if not chatname:
        print("ERROR")
        raise Error404("Chat not found")

    return dumps(chat)
Ejemplo n.º 19
0
def getName(name):

    namereg = re.compile(f"^{name}", re.IGNORECASE)
    name = list(
        db.Project_Api.find({"Name": namereg}, {
            "_id": 0,
            "Name": 1,
            "Frase": 1,
            "Date": 1
        }))
    print(namereg)
    if not name:
        print("ERROR")
        raise Error404("Name not found")

    return dumps(name)
Ejemplo n.º 20
0
def addmessage(conversation_id, user_id):
    """
    Funct add a message to a conversation by the user_id.
    """
    texto = request.args.get('text')
    print(texto)
    if db.Conversation.find_one({
            "_id": ObjectId(conversation_id),
            "Participants": user_id
    }):
        db.NEWCHAT.insert({
            "Message": texto,
            "by": user_id,
            "Group": conversation_id
        })
        return "Mensaje enviado"
    raise Error404("Para estos parametros, no hay match! Prueba con otros.")
Ejemplo n.º 21
0
def list_messages_of_chat(conversation_name):
    conversation = db['conversations'].find_one(
        {"conversation_name": conversation_name}, {
            "_id": 1,
            "conversation_name": 1,
            "users": 1,
            "messages": 1
        })
    if not conversation:
        raise Error404("Conversation doesn't exist in database")
    pointers = db["messages"].find({"_id": {"$in": conversation["messages"]}})
    if not pointers:
        raise APIError("Conversation is empty")
    list_of_messages = ([{
        sentence['user'][0]: sentence['message']
    } for sentence in pointers])
    return (json.dumps(list_of_messages))
Ejemplo n.º 22
0
def value_conversation(conversation_name):
    conversation = db['conversations'].find_one(
        {"conversation_name": conversation_name}, {
            "_id": 1,
            "conversation_name": 1,
            "messages": 1
        })
    if not conversation:
        raise Error404("Conversation doesn't exist in database")
    sia = SentimentIntensityAnalyzer()
    valorations = pd.DataFrame(columns=["neg", "neu", "pos", "compound"])
    sentences = json.loads(list_messages_of_chat(conversation_name))
    for sentence in sentences:
        scores = sia.polarity_scores(list(sentence.values())[0])
        scores_df = pd.DataFrame(data=[scores.values()],
                                 columns=["neg", "neu", "pos", "compound"])
        valorations = pd.concat([valorations, scores_df])
    return (valorations.mean().to_json())
Ejemplo n.º 23
0
def add_more_tochat(conversation_id):
    """    
    Funct adds a existing user to a conversation.
    """
    if db.Conversation.find_one({"_id": ObjectId(conversation_id)}):
        new_one = request.args.getlist('add_user_id')
        db.Conversation.update_one(
            {"_id": ObjectId(conversation_id)},
            {"$push": {
                "Participants": {
                    "$each": new_one
                }
            }})
        return str(
            db.Conversation.find_one({"_id": ObjectId(conversation_id)}, {
                "Participants": 1,
                "_id": 0
            })["Participants"])
    raise Error404("Esa conversacion. No existe!")
Ejemplo n.º 24
0
def howufeel(conversation_id):
    """
    Funct returns a dict with average feelings of all the message from one user.
    """
    if db.Conversation.find_one({"_id": ObjectId(conversation_id)}):
        print("Bien")
        cursor_message = db.NEWCHAT.find({"Group": conversation_id}, {
            "_id": 0,
            "Group": 0,
            "by": 0
        })
        mis_mensajes = list(cursor_message)
        print(mis_mensajes)
        print(len(mis_mensajes))
        if mis_mensajes:
            only_sentences = [sentence["Message"] for sentence in mis_mensajes]
            sia = SentimentIntensityAnalyzer()
            ss = [sia.polarity_scores(x) for x in only_sentences]
            return pd.DataFrame(ss).mean().to_json()
    raise Error404("Para estos parametros, no hay match! Prueba con otros.")
Ejemplo n.º 25
0
def returnID(ID, topic, name):
    # return the response for an ID asked
    if ID == "Failed":
        raise Error404(f"No {topic} exists with that name in the database")
    return {f"The corresponding ID for the {topic} '{name}' is": ID}