From 7ffa3cb022c38b7fecf3af21875b6ab1132ca55b Mon Sep 17 00:00:00 2001 From: "Timothy J. Baek" Date: Thu, 17 Oct 2024 18:24:58 -0700 Subject: [PATCH] refac: folder deletion --- backend/open_webui/apps/webui/models/chats.py | 12 ++++++++++ .../open_webui/apps/webui/models/folders.py | 22 ++++++++++++++++++- .../open_webui/apps/webui/routers/folders.py | 5 ----- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/backend/open_webui/apps/webui/models/chats.py b/backend/open_webui/apps/webui/models/chats.py index 84f8a74d1..22c971243 100644 --- a/backend/open_webui/apps/webui/models/chats.py +++ b/backend/open_webui/apps/webui/models/chats.py @@ -699,6 +699,18 @@ class ChatTable: except Exception: return False + def delete_chats_by_user_id_and_folder_id( + self, user_id: str, folder_id: str + ) -> bool: + try: + with get_db() as db: + db.query(Chat).filter_by(user_id=user_id, folder_id=folder_id).delete() + db.commit() + + return True + except Exception: + return False + def delete_shared_chats_by_user_id(self, user_id: str) -> bool: try: with get_db() as db: diff --git a/backend/open_webui/apps/webui/models/folders.py b/backend/open_webui/apps/webui/models/folders.py index 91aa0175e..fff7b0e7d 100644 --- a/backend/open_webui/apps/webui/models/folders.py +++ b/backend/open_webui/apps/webui/models/folders.py @@ -4,7 +4,7 @@ import uuid from typing import Optional from open_webui.apps.webui.internal.db import Base, get_db - +from open_webui.apps.webui.models.chats import Chats from open_webui.env import SRC_LOG_LEVELS from pydantic import BaseModel, ConfigDict @@ -214,6 +214,26 @@ class FolderTable: try: with get_db() as db: folder = db.query(Folder).filter_by(id=id, user_id=user_id).first() + if not folder: + return False + + # Delete all chats in the folder + Chats.delete_chats_by_user_id_and_folder_id(user_id, folder.id) + + # Delete all children folders + def delete_children(folder): + folder_children = self.get_folders_by_parent_id_and_user_id( + folder.id, user_id + ) + for folder_child in folder_children: + Chats.delete_chats_by_user_id_and_folder_id( + user_id, folder_child.id + ) + delete_children(folder_child) + db.delete(folder_child) + db.commit() + + delete_children(folder) db.delete(folder) db.commit() return True diff --git a/backend/open_webui/apps/webui/routers/folders.py b/backend/open_webui/apps/webui/routers/folders.py index 08f07b8c6..c9321fda4 100644 --- a/backend/open_webui/apps/webui/routers/folders.py +++ b/backend/open_webui/apps/webui/routers/folders.py @@ -234,11 +234,6 @@ async def delete_folder_by_id(id: str, user=Depends(get_verified_user)): try: result = Folders.delete_folder_by_id_and_user_id(id, user.id) if result: - # Delete all chats in the folder - chats = Chats.get_chats_by_folder_id_and_user_id(id, user.id) - for chat in chats: - Chats.delete_chat_by_id(chat.id, user.id) - return result else: raise HTTPException(