Browse Source

refac: uploads delete

Timothy J. Baek 10 months ago
parent
commit
d5a1030000

+ 39 - 19
backend/apps/webui/routers/files.py

@@ -32,11 +32,11 @@ from constants import ERROR_MESSAGES
 from importlib import util
 import os
 import uuid
+import os, shutil, logging, re
 
-from config import SRC_LOG_LEVELS, UPLOAD_DIR
 
+from config import SRC_LOG_LEVELS, UPLOAD_DIR
 
-import logging
 
 log = logging.getLogger(__name__)
 log.setLevel(SRC_LOG_LEVELS["MODELS"])
@@ -111,6 +111,43 @@ async def list_files(user=Depends(get_verified_user)):
     return files
 
 
+############################
+# Delete All Files
+############################
+
+
+@router.delete("/all")
+async def delete_all_files(user=Depends(get_admin_user)):
+    result = Files.delete_all_files()
+
+    if result:
+        folder = f"{UPLOAD_DIR}"
+        try:
+            # Check if the directory exists
+            if os.path.exists(folder):
+                # Iterate over all the files and directories in the specified directory
+                for filename in os.listdir(folder):
+                    file_path = os.path.join(folder, filename)
+                    try:
+                        if os.path.isfile(file_path) or os.path.islink(file_path):
+                            os.unlink(file_path)  # Remove the file or link
+                        elif os.path.isdir(file_path):
+                            shutil.rmtree(file_path)  # Remove the directory
+                    except Exception as e:
+                        print(f"Failed to delete {file_path}. Reason: {e}")
+            else:
+                print(f"The directory {folder} does not exist")
+        except Exception as e:
+            print(f"Failed to process the directory {folder}. Reason: {e}")
+
+        return {"message": "All files deleted successfully"}
+    else:
+        raise HTTPException(
+            status_code=status.HTTP_400_BAD_REQUEST,
+            detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
+        )
+
+
 ############################
 # Get File By Id
 ############################
@@ -181,20 +218,3 @@ async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
             status_code=status.HTTP_401_UNAUTHORIZED,
             detail=ERROR_MESSAGES.NOT_FOUND,
         )
-
-
-############################
-# Delete All Files
-############################
-
-
-@router.delete("/all")
-async def delete_all_files(user=Depends(get_admin_user)):
-    result = Files.delete_all_files()
-    if result:
-        return {"message": "All files deleted successfully"}
-    else:
-        raise HTTPException(
-            status_code=status.HTTP_400_BAD_REQUEST,
-            detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
-        )

+ 31 - 0
src/lib/apis/files/index.ts

@@ -150,3 +150,34 @@ export const deleteFileById = async (token: string, id: string) => {
 
 	return res;
 };
+
+export const deleteAllFiles = async (token: string) => {
+	let error = null;
+
+	const res = await fetch(`${WEBUI_API_BASE_URL}/files/all`, {
+		method: 'DELETE',
+		headers: {
+			Accept: 'application/json',
+			'Content-Type': 'application/json',
+			authorization: `Bearer ${token}`
+		}
+	})
+		.then(async (res) => {
+			if (!res.ok) throw await res.json();
+			return res.json();
+		})
+		.then((json) => {
+			return json;
+		})
+		.catch((err) => {
+			error = err.detail;
+			console.log(err);
+			return null;
+		});
+
+	if (error) {
+		throw error;
+	}
+
+	return res;
+};

+ 3 - 2
src/lib/components/admin/Settings/Documents.svelte

@@ -1,5 +1,6 @@
 <script lang="ts">
 	import { getDocs } from '$lib/apis/documents';
+	import { deleteAllFiles, deleteFileById } from '$lib/apis/files';
 	import {
 		getQuerySettings,
 		scanDocs,
@@ -217,8 +218,8 @@
 
 <ResetUploadDirConfirmDialog
 	bind:show={showResetUploadDirConfirm}
-	on:confirm={() => {
-		const res = resetUploadDir(localStorage.token).catch((error) => {
+	on:confirm={async () => {
+		const res = await deleteAllFiles(localStorage.token).catch((error) => {
 			toast.error(error);
 			return null;
 		});