api done
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
from database import postgresql_db_handler, mongo_db_handler
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def create_conversation(user1_id, user2_id):
|
||||
query = '''
|
||||
SELECT conversation_url FROM conversations
|
||||
WHERE id_user1 = %s AND id_user2 = %s
|
||||
'''
|
||||
params = (user1_id, user2_id)
|
||||
existing_conversation = postgresql_db_handler.execute_query(query, params, fetchall=True)
|
||||
|
||||
if existing_conversation:
|
||||
conversation_url = existing_conversation[0][0]
|
||||
else:
|
||||
current_datetime = datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
unique_id = str(uuid.uuid4()).replace('-', '')
|
||||
conversation_url = f"{current_datetime}_{unique_id}"
|
||||
|
||||
query = '''
|
||||
INSERT INTO conversations (id_user1, id_user2, conversation_url)
|
||||
VALUES (%s, %s, %s)
|
||||
'''
|
||||
params = (user1_id, user2_id, conversation_url)
|
||||
postgresql_db_handler.execute_query(query, params)
|
||||
|
||||
return conversation_url
|
||||
|
||||
|
||||
def find_conversation(conversation_url):
|
||||
collection = mongo_db_handler.get_collection()
|
||||
query = {'name': conversation_url}
|
||||
result_set = collection.find_one(query)
|
||||
|
||||
if result_set:
|
||||
return {'chat': result_set['chat']}
|
||||
return None
|
||||
|
||||
|
||||
def send_message_to_mongodb(conversation_url, sender, message):
|
||||
try:
|
||||
collection = mongo_db_handler.get_collection()
|
||||
existing_document = collection.find_one({"name": conversation_url})
|
||||
|
||||
if existing_document is not None:
|
||||
new_message = {"sender": sender, "message": message, "timestamp": datetime.now()}
|
||||
collection.update_one(
|
||||
{"name": conversation_url},
|
||||
{"$push": {"chat": new_message}}
|
||||
)
|
||||
else:
|
||||
collection.insert_one({
|
||||
"name": conversation_url,
|
||||
"chat": [{"sender": sender, "message": message, "timestamp": datetime.now()}]
|
||||
})
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"Unable to send message to MongoDB: {str(e)}")
|
||||
return False
|
||||
Reference in New Issue
Block a user