Ashad001 commited on
Commit
334ae50
·
1 Parent(s): 7c595ae

DB Implementations UPdated

Browse files
Files changed (2) hide show
  1. chat_manager.py +83 -11
  2. chat_routes.py +18 -8
chat_manager.py CHANGED
@@ -66,7 +66,7 @@ class ChatManager:
66
  finally:
67
  session.close()
68
 
69
- def add_message(self, chat_id: int, content: str, sender: str) -> Dict[str, Any]:
70
  """
71
  Add a message to a chat.
72
 
@@ -74,16 +74,21 @@ class ChatManager:
74
  chat_id: ID of the chat to add the message to
75
  content: Message content
76
  sender: Message sender ('user' or 'bot')
 
77
 
78
  Returns:
79
  Dictionary containing message information
80
  """
81
  session = self.Session()
82
  try:
83
- # Check if chat exists
84
- chat = session.query(Chat).filter(Chat.chat_id == chat_id).first()
 
 
 
 
85
  if not chat:
86
- raise ValueError(f"Chat with ID {chat_id} not found")
87
 
88
  # Create a new message
89
  message = Message(
@@ -183,12 +188,13 @@ class ChatManager:
183
  finally:
184
  session.close()
185
 
186
- def get_chat(self, chat_id: int) -> Dict[str, Any]:
187
  """
188
  Get a chat by ID with all its messages.
189
 
190
  Args:
191
  chat_id: ID of the chat to retrieve
 
192
 
193
  Returns:
194
  Dictionary containing chat information and messages
@@ -196,9 +202,15 @@ class ChatManager:
196
  session = self.Session()
197
  try:
198
  # Get the chat
199
- chat = session.query(Chat).filter(Chat.chat_id == chat_id).first()
 
 
 
 
 
 
200
  if not chat:
201
- raise ValueError(f"Chat with ID {chat_id} not found")
202
 
203
  # Get the chat messages ordered by timestamp
204
  messages = session.query(Message).filter(
@@ -291,23 +303,37 @@ class ChatManager:
291
  finally:
292
  session.close()
293
 
294
- def delete_chat(self, chat_id: int) -> bool:
295
  """
296
  Delete a chat and all its messages.
297
 
298
  Args:
299
  chat_id: ID of the chat to delete
 
300
 
301
  Returns:
302
  True if deletion was successful, False otherwise
303
  """
304
  session = self.Session()
305
  try:
 
 
 
 
 
 
 
 
 
306
  # Delete all messages in the chat
307
  session.query(Message).filter(Message.chat_id == chat_id).delete()
308
 
309
- # Delete the chat
310
- result = session.query(Chat).filter(Chat.chat_id == chat_id).delete()
 
 
 
 
311
  session.commit()
312
 
313
  return result > 0
@@ -495,4 +521,50 @@ class ChatManager:
495
  return title
496
  except Exception as e:
497
  logger.error(f"Error generating title: {str(e)}")
498
- return "New Chat"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  finally:
67
  session.close()
68
 
69
+ def add_message(self, chat_id: int, content: str, sender: str, user_id: Optional[int] = None) -> Dict[str, Any]:
70
  """
71
  Add a message to a chat.
72
 
 
74
  chat_id: ID of the chat to add the message to
75
  content: Message content
76
  sender: Message sender ('user' or 'bot')
77
+ user_id: Optional user ID to verify ownership
78
 
79
  Returns:
80
  Dictionary containing message information
81
  """
82
  session = self.Session()
83
  try:
84
+ # Check if chat exists and belongs to the user if user_id is provided
85
+ query = session.query(Chat).filter(Chat.chat_id == chat_id)
86
+ if user_id is not None:
87
+ query = query.filter((Chat.user_id == user_id) | (Chat.user_id.is_(None)))
88
+
89
+ chat = query.first()
90
  if not chat:
91
+ raise ValueError(f"Chat with ID {chat_id} not found or access denied")
92
 
93
  # Create a new message
94
  message = Message(
 
188
  finally:
189
  session.close()
190
 
191
+ def get_chat(self, chat_id: int, user_id: Optional[int] = None) -> Dict[str, Any]:
192
  """
193
  Get a chat by ID with all its messages.
194
 
195
  Args:
196
  chat_id: ID of the chat to retrieve
197
+ user_id: Optional user ID to verify ownership
198
 
199
  Returns:
200
  Dictionary containing chat information and messages
 
202
  session = self.Session()
203
  try:
204
  # Get the chat
205
+ query = session.query(Chat).filter(Chat.chat_id == chat_id)
206
+
207
+ # If user_id is provided, ensure the chat belongs to this user
208
+ if user_id is not None:
209
+ query = query.filter(Chat.user_id == user_id)
210
+
211
+ chat = query.first()
212
  if not chat:
213
+ raise ValueError(f"Chat with ID {chat_id} not found or access denied")
214
 
215
  # Get the chat messages ordered by timestamp
216
  messages = session.query(Message).filter(
 
303
  finally:
304
  session.close()
305
 
306
+ def delete_chat(self, chat_id: int, user_id: Optional[int] = None) -> bool:
307
  """
308
  Delete a chat and all its messages.
309
 
310
  Args:
311
  chat_id: ID of the chat to delete
312
+ user_id: Optional user ID to verify ownership
313
 
314
  Returns:
315
  True if deletion was successful, False otherwise
316
  """
317
  session = self.Session()
318
  try:
319
+ # Check if chat exists and belongs to the user if user_id is provided
320
+ if user_id is not None:
321
+ chat = session.query(Chat).filter(
322
+ Chat.chat_id == chat_id,
323
+ Chat.user_id == user_id
324
+ ).first()
325
+ if not chat:
326
+ return False # Chat not found or doesn't belong to the user
327
+
328
  # Delete all messages in the chat
329
  session.query(Message).filter(Message.chat_id == chat_id).delete()
330
 
331
+ # Delete the chat (with user_id filter if provided)
332
+ query = session.query(Chat).filter(Chat.chat_id == chat_id)
333
+ if user_id is not None:
334
+ query = query.filter(Chat.user_id == user_id)
335
+
336
+ result = query.delete()
337
  session.commit()
338
 
339
  return result > 0
 
521
  return title
522
  except Exception as e:
523
  logger.error(f"Error generating title: {str(e)}")
524
+ return "New Chat"
525
+
526
+ def delete_empty_chats(self, user_id: Optional[int] = None, is_admin: bool = False) -> int:
527
+ """
528
+ Delete empty chats (chats with no messages) for a user.
529
+
530
+ Args:
531
+ user_id: ID of the user whose empty chats should be deleted
532
+ is_admin: Whether this is an admin user
533
+
534
+ Returns:
535
+ Number of chats deleted
536
+ """
537
+ session = self.Session()
538
+ try:
539
+ # Get all chats for the user
540
+ query = session.query(Chat)
541
+ if user_id is not None:
542
+ query = query.filter(Chat.user_id == user_id)
543
+ elif not is_admin:
544
+ return 0 # Don't delete anything if not a user or admin
545
+
546
+ # For each chat, check if it has any messages
547
+ chats_to_delete = []
548
+ for chat in query.all():
549
+ message_count = session.query(Message).filter(
550
+ Message.chat_id == chat.chat_id
551
+ ).count()
552
+
553
+ if message_count == 0:
554
+ chats_to_delete.append(chat.chat_id)
555
+
556
+ # Delete the empty chats
557
+ if chats_to_delete:
558
+ deleted = session.query(Chat).filter(
559
+ Chat.chat_id.in_(chats_to_delete)
560
+ ).delete(synchronize_session=False)
561
+
562
+ session.commit()
563
+ return deleted
564
+ return 0
565
+ except SQLAlchemyError as e:
566
+ session.rollback()
567
+ logger.error(f"Error deleting empty chats: {str(e)}")
568
+ return 0
569
+ finally:
570
+ session.close()
chat_routes.py CHANGED
@@ -65,10 +65,10 @@ async def create_chat(chat_create: ChatCreate):
65
  raise HTTPException(status_code=500, detail=f"Failed to create chat: {str(e)}")
66
 
67
  @router.post("/{chat_id}/messages", response_model=MessageResponse)
68
- async def add_message(chat_id: int, message: MessageCreate):
69
  """Add a message to a chat"""
70
  try:
71
- result = chat_manager.add_message(chat_id, message.content, message.sender)
72
  return result
73
  except ValueError as e:
74
  raise HTTPException(status_code=404, detail=str(e))
@@ -77,10 +77,10 @@ async def add_message(chat_id: int, message: MessageCreate):
77
  raise HTTPException(status_code=500, detail=f"Failed to add message: {str(e)}")
78
 
79
  @router.get("/{chat_id}", response_model=ChatDetailResponse)
80
- async def get_chat(chat_id: int):
81
  """Get a chat by ID with all messages"""
82
  try:
83
- chat = chat_manager.get_chat(chat_id)
84
  return chat
85
  except ValueError as e:
86
  raise HTTPException(status_code=404, detail=str(e))
@@ -103,12 +103,12 @@ async def get_chats(
103
  raise HTTPException(status_code=500, detail=f"Failed to retrieve chats: {str(e)}")
104
 
105
  @router.delete("/{chat_id}")
106
- async def delete_chat(chat_id: int):
107
  """Delete a chat and all its messages"""
108
  try:
109
- success = chat_manager.delete_chat(chat_id)
110
  if not success:
111
- raise HTTPException(status_code=404, detail=f"Chat with ID {chat_id} not found")
112
  return {"message": f"Chat {chat_id} deleted successfully"}
113
  except HTTPException:
114
  raise
@@ -157,4 +157,14 @@ async def update_chat(chat_id: int, chat_update: ChatUpdate):
157
  raise HTTPException(status_code=404, detail=str(e))
158
  except Exception as e:
159
  logger.error(f"Error updating chat: {str(e)}")
160
- raise HTTPException(status_code=500, detail=f"Failed to update chat: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
65
  raise HTTPException(status_code=500, detail=f"Failed to create chat: {str(e)}")
66
 
67
  @router.post("/{chat_id}/messages", response_model=MessageResponse)
68
+ async def add_message(chat_id: int, message: MessageCreate, user_id: Optional[int] = None):
69
  """Add a message to a chat"""
70
  try:
71
+ result = chat_manager.add_message(chat_id, message.content, message.sender, user_id)
72
  return result
73
  except ValueError as e:
74
  raise HTTPException(status_code=404, detail=str(e))
 
77
  raise HTTPException(status_code=500, detail=f"Failed to add message: {str(e)}")
78
 
79
  @router.get("/{chat_id}", response_model=ChatDetailResponse)
80
+ async def get_chat(chat_id: int, user_id: Optional[int] = None):
81
  """Get a chat by ID with all messages"""
82
  try:
83
+ chat = chat_manager.get_chat(chat_id, user_id)
84
  return chat
85
  except ValueError as e:
86
  raise HTTPException(status_code=404, detail=str(e))
 
103
  raise HTTPException(status_code=500, detail=f"Failed to retrieve chats: {str(e)}")
104
 
105
  @router.delete("/{chat_id}")
106
+ async def delete_chat(chat_id: int, user_id: Optional[int] = None):
107
  """Delete a chat and all its messages"""
108
  try:
109
+ success = chat_manager.delete_chat(chat_id, user_id)
110
  if not success:
111
+ raise HTTPException(status_code=404, detail=f"Chat with ID {chat_id} not found or access denied")
112
  return {"message": f"Chat {chat_id} deleted successfully"}
113
  except HTTPException:
114
  raise
 
157
  raise HTTPException(status_code=404, detail=str(e))
158
  except Exception as e:
159
  logger.error(f"Error updating chat: {str(e)}")
160
+ raise HTTPException(status_code=500, detail=f"Failed to update chat: {str(e)}")
161
+
162
+ @router.post("/cleanup-empty", response_model=dict)
163
+ async def cleanup_empty_chats(request: ChatCreate):
164
+ """Delete empty chats for a user"""
165
+ try:
166
+ deleted_count = chat_manager.delete_empty_chats(request.user_id, request.is_admin)
167
+ return {"message": f"Deleted {deleted_count} empty chats"}
168
+ except Exception as e:
169
+ logger.error(f"Error cleaning up empty chats: {str(e)}")
170
+ raise HTTPException(status_code=500, detail=f"Failed to clean up empty chats: {str(e)}")