api done
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,38 +0,0 @@
|
||||
import psycopg2
|
||||
|
||||
DATABASE_CONFIG = {
|
||||
'dbname': 'messenger',
|
||||
'user': 'andrei_cerbu',
|
||||
'password': 'andrei',
|
||||
'host': 'localhost',
|
||||
'port': '5432'
|
||||
}
|
||||
|
||||
|
||||
def create_connection():
|
||||
try:
|
||||
connection = psycopg2.connect(**DATABASE_CONFIG)
|
||||
return connection
|
||||
except psycopg2.Error as e:
|
||||
print(f"Error: Unable to connect to the database\n{e}")
|
||||
return None
|
||||
|
||||
|
||||
def execute_query(connection, query, params=None, fetchall=False):
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(query, params)
|
||||
if fetchall:
|
||||
result = cursor.fetchall()
|
||||
return result
|
||||
else:
|
||||
connection.commit() # Commit the transaction for INSERT, UPDATE, DELETE queries
|
||||
except psycopg2.Error as e:
|
||||
print(f"Error: Unable to execute the query\n{e}")
|
||||
return None
|
||||
|
||||
|
||||
def close_connection(connection):
|
||||
if connection:
|
||||
connection.close()
|
||||
print("Connection closed.")
|
||||
@@ -1,81 +0,0 @@
|
||||
from api.v1.database.postgres_database import create_connection, execute_query, close_connection
|
||||
|
||||
|
||||
def get_user_by_id(user_id):
|
||||
connection = create_connection()
|
||||
if connection:
|
||||
try:
|
||||
query = """
|
||||
SELECT * FROM users WHERE id = %s;
|
||||
"""
|
||||
params = (user_id,)
|
||||
result = execute_query(connection, query, params, fetchall=True)
|
||||
if result:
|
||||
user_data = result[0]
|
||||
return user_data
|
||||
else:
|
||||
return None
|
||||
finally:
|
||||
close_connection(connection)
|
||||
|
||||
|
||||
def get_user_by_email(email):
|
||||
connection = create_connection()
|
||||
if connection:
|
||||
try:
|
||||
query = """
|
||||
SELECT * FROM users WHERE email = %s;
|
||||
"""
|
||||
params = (email,)
|
||||
result = execute_query(connection, query, params, fetchall=True)
|
||||
if result:
|
||||
user_data = result[0]
|
||||
return user_data
|
||||
else:
|
||||
return None
|
||||
finally:
|
||||
close_connection(connection)
|
||||
|
||||
|
||||
def create_user_db(username, password, email):
|
||||
connection = create_connection()
|
||||
if connection:
|
||||
try:
|
||||
query = """
|
||||
INSERT INTO users (username, password, email)
|
||||
VALUES (%s, %s, %s);
|
||||
"""
|
||||
params = (username, password, email)
|
||||
execute_query(connection, query, params)
|
||||
finally:
|
||||
close_connection(connection)
|
||||
|
||||
|
||||
def update_user_db(user_id, new_username, new_password, new_email):
|
||||
connection = create_connection()
|
||||
if connection:
|
||||
try:
|
||||
query = """
|
||||
UPDATE users
|
||||
SET username = %s, password = %s, email = %s
|
||||
WHERE id = %s;
|
||||
"""
|
||||
params = (new_username, new_password, new_email, user_id)
|
||||
execute_query(connection, query, params)
|
||||
print(f"User with ID {user_id} updated successfully.")
|
||||
finally:
|
||||
close_connection(connection)
|
||||
|
||||
|
||||
def delete_user_db(user_id):
|
||||
connection = create_connection()
|
||||
if connection:
|
||||
try:
|
||||
query = """
|
||||
DELETE FROM users WHERE id = %s;
|
||||
"""
|
||||
params = (user_id,)
|
||||
execute_query(connection, query, params)
|
||||
print(f"User with ID {user_id} deleted successfully.")
|
||||
finally:
|
||||
close_connection(connection)
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,11 +0,0 @@
|
||||
import bcrypt
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
salt = bcrypt.gensalt()
|
||||
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
|
||||
return hashed_password
|
||||
|
||||
|
||||
def verify_password(password, hashed_password):
|
||||
return bcrypt.checkpw(password.encode('utf-8'), hashed_password)
|
||||
@@ -0,0 +1,3 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
from app.models.login import Login
|
||||
@@ -1,9 +0,0 @@
|
||||
from fastapi import APIRouter
|
||||
from api.v1.models.message import Message
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/messages/", response_model=Message)
|
||||
async def create_message(message: Message):
|
||||
# You would typically save the message to the database here
|
||||
return message
|
||||
@@ -0,0 +1,19 @@
|
||||
from fastapi import APIRouter
|
||||
from .send import send
|
||||
from .get_conversation import get_conversation
|
||||
from app.models import Message
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/send")
|
||||
async def send_router(message: Message):
|
||||
return await send(message)
|
||||
|
||||
|
||||
@router.get("/get_conversation/{conversation_url}")
|
||||
async def get_conversation_router(conversation_url: str):
|
||||
return await get_conversation(conversation_url)
|
||||
|
||||
|
||||
__all__ = ["router"]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
from fastapi import HTTPException, status
|
||||
from database.queries.messages import find_conversation
|
||||
|
||||
|
||||
async def get_conversation(conversation_url: str):
|
||||
conversation = find_conversation(conversation_url)
|
||||
if conversation is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found")
|
||||
return conversation
|
||||
@@ -0,0 +1,17 @@
|
||||
from fastapi import HTTPException
|
||||
from app.models import Message
|
||||
from database.queries.messages import create_conversation, send_message_to_mongodb
|
||||
|
||||
|
||||
async def send(message: Message):
|
||||
conversation_url = create_conversation(message.sender, message.receiver)
|
||||
|
||||
if conversation_url is not None:
|
||||
success = send_message_to_mongodb(conversation_url, message.sender, message.conversation)
|
||||
|
||||
if success:
|
||||
return {"success": True, "message": "Message sent successfully"}
|
||||
raise HTTPException(status_code=500, detail="Internal Server Error")
|
||||
|
||||
raise HTTPException(status_code=500, detail="Error creating conversation")
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from api.v1.models.user import User
|
||||
from api.v1.database.user_queries import get_user_by_email, get_user_by_id
|
||||
from api.v1.database.user_queries import create_user_db, update_user_db, delete_user_db
|
||||
from api.v1.dependencies.security import hash_password
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/users")
|
||||
async def create_user(user: User):
|
||||
result = get_user_by_email(user.email)
|
||||
if result:
|
||||
raise HTTPException(status_code=409, detail='User already exists')
|
||||
|
||||
create_user_db(username=user.username, password=hash_password(user.password), email=user.email)
|
||||
created_user = get_user_by_email(user.email)
|
||||
created_user_dict = {
|
||||
"id": created_user[0],
|
||||
"username": created_user[1],
|
||||
"password": created_user[2],
|
||||
"email": created_user[3],
|
||||
}
|
||||
|
||||
return {'status': 'successful', 'user': created_user_dict}
|
||||
|
||||
|
||||
@router.put("/users")
|
||||
async def update_user(new_info: User):
|
||||
old_info = get_user_by_id(new_info.id)
|
||||
if old_info is None:
|
||||
raise HTTPException(status_code=404, detail='User not found')
|
||||
update_user_db(user_id=new_info.id, new_email=new_info.email,
|
||||
new_username=new_info.username, new_password=hash_password(new_info.password))
|
||||
|
||||
|
||||
@router.delete("/users")
|
||||
async def delete_user(user_id: int):
|
||||
user = get_user_by_id(user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=404, detail='User not found')
|
||||
delete_user_db(user_id)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from fastapi import APIRouter
|
||||
from app.models import User
|
||||
from .create import create_user
|
||||
from .update import update_user
|
||||
from .delete import delete_user
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/create")
|
||||
async def create_user_router(user: User):
|
||||
return await create_user(user)
|
||||
|
||||
|
||||
@router.put("/update")
|
||||
async def update_user_router(user: User):
|
||||
return await update_user(user)
|
||||
|
||||
|
||||
@router.delete("/delete")
|
||||
async def delete_user_router(user_id: int):
|
||||
return await delete_user(user_id)
|
||||
|
||||
|
||||
# Make the router accessible from outside the package
|
||||
__all__ = ["router"]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,20 @@
|
||||
from fastapi import HTTPException
|
||||
from app.models.user import User
|
||||
from database.queries.user import get_user_by_email, create_user_db
|
||||
|
||||
|
||||
async def create_user(user: User):
|
||||
result = get_user_by_email(user.email)
|
||||
if result:
|
||||
raise HTTPException(status_code=409, detail='User already exists')
|
||||
|
||||
create_user_db(username=user.username, password=user.password, email=user.email)
|
||||
created_user = get_user_by_email(user.email)
|
||||
created_user_dict = {
|
||||
"id": created_user[0],
|
||||
"username": created_user[1],
|
||||
"password": created_user[2],
|
||||
"email": created_user[3],
|
||||
}
|
||||
|
||||
return {'user': created_user_dict}
|
||||
@@ -0,0 +1,10 @@
|
||||
from fastapi import HTTPException
|
||||
from database.queries.user import get_user_by_id, delete_user_db
|
||||
|
||||
|
||||
async def delete_user(user_id: int):
|
||||
user = get_user_by_id(user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=404, detail='User not found')
|
||||
delete_user_db(user_id)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
from fastapi import HTTPException
|
||||
from app.models.user import User
|
||||
from database.queries.user import get_user_by_id, update_user_db
|
||||
|
||||
|
||||
async def update_user(new_info: User):
|
||||
old_info = get_user_by_id(new_info.id)
|
||||
if old_info is None:
|
||||
raise HTTPException(status_code=404, detail='User Not Found')
|
||||
update_user_db(user_id=new_info.id, new_email=new_info.email,
|
||||
new_username=new_info.username, new_password=new_info.password)
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,7 +1,8 @@
|
||||
from fastapi import FastAPI
|
||||
from api.v1.endpoints import users, messages
|
||||
from api.v1.endpoints.users import router as users_router
|
||||
from api.v1.endpoints.messages import router as messages_router
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.include_router(users.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(users_router, tags=["Users"], prefix="/users")
|
||||
app.include_router(messages_router, tags=["Messages"], prefix="/messages")
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
from .user import User
|
||||
from .message import Message
|
||||
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Login(BaseModel):
|
||||
password: str
|
||||
email: str
|
||||
@@ -3,7 +3,7 @@ from datetime import datetime
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
text: str
|
||||
sender_id: int
|
||||
receiver_id: int
|
||||
conversation: str
|
||||
sender: int
|
||||
receiver: int
|
||||
timestamp: datetime
|
||||
@@ -0,0 +1,2 @@
|
||||
from .postgresql_database import postgresql_db_handler
|
||||
from .mongodb_database import mongo_db_handler
|
||||
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
from .connection import MONGODB_CONFIG, MongoDbHandler
|
||||
|
||||
mongo_db_handler = MongoDbHandler(**MONGODB_CONFIG)
|
||||
mongo_db_handler.connect()
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,36 @@
|
||||
from pymongo import MongoClient
|
||||
|
||||
MONGODB_CONFIG = {
|
||||
'host': 'localhost',
|
||||
'port': 27017,
|
||||
'dbname': 'local',
|
||||
'collection': 'messenger'
|
||||
}
|
||||
|
||||
|
||||
class MongoDbHandler:
|
||||
def __init__(self, dbname, collection, host, port):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.dbname = dbname
|
||||
self.collection_name = collection
|
||||
self.client = None
|
||||
self.collection = None
|
||||
|
||||
def connect(self):
|
||||
try:
|
||||
self.client = MongoClient(self.host, self.port)
|
||||
db = self.client[self.dbname]
|
||||
self.collection = db[self.collection_name]
|
||||
print("Connected to MongoDB")
|
||||
except Exception as e:
|
||||
self.collection = None
|
||||
|
||||
def close_client(self):
|
||||
if self.client:
|
||||
self.client.close()
|
||||
self.collection = None
|
||||
print("MongoDB client closed.")
|
||||
|
||||
def get_collection(self):
|
||||
return self.collection
|
||||
@@ -0,0 +1,4 @@
|
||||
from .connection import POSTGRESQL_CONFIG, PostgreSQLHandler
|
||||
|
||||
postgresql_db_handler = PostgreSQLHandler(**POSTGRESQL_CONFIG)
|
||||
postgresql_db_handler.connect()
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,54 @@
|
||||
import psycopg2
|
||||
|
||||
|
||||
class PostgreSQLHandler:
|
||||
def __init__(self, dbname, user, password, host, port):
|
||||
self.dbname = dbname
|
||||
self.user = user
|
||||
self.password = password
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.connection = None
|
||||
|
||||
def connect(self):
|
||||
try:
|
||||
self.connection = psycopg2.connect(
|
||||
dbname=self.dbname,
|
||||
user=self.user,
|
||||
password=self.password,
|
||||
host=self.host,
|
||||
port=self.port
|
||||
)
|
||||
print("Connected to PostgreSQL.")
|
||||
return self.connection
|
||||
except psycopg2.Error as e:
|
||||
print(f"Error: Unable to connect to the PostgreSQL database\n{e}")
|
||||
return None
|
||||
|
||||
def execute_query(self, query, params=None, fetchall=False):
|
||||
try:
|
||||
with self.connection.cursor() as cursor:
|
||||
cursor.execute(query, params)
|
||||
if fetchall:
|
||||
result = cursor.fetchall()
|
||||
return result
|
||||
else:
|
||||
self.connection.commit() # Commit the transaction for INSERT, UPDATE, DELETE queries
|
||||
except psycopg2.Error as e:
|
||||
print(f"Error: Unable to execute the query\n{e}")
|
||||
return None
|
||||
|
||||
def close(self):
|
||||
if self.connection:
|
||||
self.connection.close()
|
||||
print("PostgreSQL connection closed.")
|
||||
self.connection = None
|
||||
|
||||
|
||||
POSTGRESQL_CONFIG = {
|
||||
'dbname': 'vliwybbf',
|
||||
'user': 'vliwybbf',
|
||||
'password': 'X0fhZ6NT3mjT7rbgZ5lQQ6ZYQpVyUwxq',
|
||||
'host': 'rogue.db.elephantsql.com',
|
||||
'port': '5432'
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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
|
||||
@@ -0,0 +1,56 @@
|
||||
from database import postgresql_db_handler
|
||||
|
||||
|
||||
def get_user_by_id(user_id):
|
||||
query = """
|
||||
SELECT * FROM users WHERE id = %s;
|
||||
"""
|
||||
params = (user_id,)
|
||||
result = postgresql_db_handler.execute_query(query, params, fetchall=True)
|
||||
if result:
|
||||
user_data = result[0]
|
||||
return user_data
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def get_user_by_email(email):
|
||||
query = """
|
||||
SELECT * FROM users WHERE email = %s;
|
||||
"""
|
||||
params = (email,)
|
||||
result = postgresql_db_handler.execute_query(query, params, fetchall=True)
|
||||
if result:
|
||||
user_data = result[0]
|
||||
return user_data
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def create_user_db(username, password, email):
|
||||
query = """
|
||||
INSERT INTO users (username, password, email)
|
||||
VALUES (%s, %s, %s);
|
||||
"""
|
||||
params = (username, password, email)
|
||||
postgresql_db_handler.execute_query(query, params)
|
||||
|
||||
|
||||
def update_user_db(user_id, new_username, new_password, new_email):
|
||||
query = """
|
||||
UPDATE users
|
||||
SET username = %s, password = %s, email = %s
|
||||
WHERE id = %s;
|
||||
"""
|
||||
params = (new_username, new_password, new_email, user_id)
|
||||
postgresql_db_handler.execute_query(query, params)
|
||||
print(f"User with ID {user_id} updated successfully.")
|
||||
|
||||
|
||||
def delete_user_db(user_id):
|
||||
query = """
|
||||
DELETE FROM users WHERE id = %s;
|
||||
"""
|
||||
params = (user_id,)
|
||||
postgresql_db_handler.execute_query(query, params)
|
||||
print(f"User with ID {user_id} deleted successfully.")
|
||||
Reference in New Issue
Block a user