From 3831df76b6b10a13e905d7ea9fba84e942e84964 Mon Sep 17 00:00:00 2001 From: Thomas Draier Date: Mon, 16 Dec 2024 08:38:02 +0100 Subject: [PATCH] [front] Auto rename uploaded files (#9376) --- .../app/src/hooks/useFileUploaderService.ts | 14 ++++------ front/hooks/useFileUploaderService.ts | 28 +++++++++++++------ 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/extension/app/src/hooks/useFileUploaderService.ts b/extension/app/src/hooks/useFileUploaderService.ts index 4edb0258e109..a155f679a5d3 100644 --- a/extension/app/src/hooks/useFileUploaderService.ts +++ b/extension/app/src/hooks/useFileUploaderService.ts @@ -141,14 +141,12 @@ export function useFileUploaderService(conversationId?: string) { ): Result[] => { return selectedFiles.reduce( (acc, file) => { - if (fileBlobs.some((f) => f.id === file.name)) { - sendNotification({ - type: "error", - title: "File already exists.", - description: `File "${file.name}" is already uploaded.`, - }); - - return acc; // Ignore if file already exists. + while (fileBlobs.some((f) => f.id === file.name)) { + const [base, ext] = file.name.split(/\.(?=[^.]+$)/); + const name = findAvailableTitle(base, ext, [ + ...fileBlobs.map((f) => f.filename), + ]); + file = new File([file], name, { type: file.type }); } const contentType = file.type; diff --git a/front/hooks/useFileUploaderService.ts b/front/hooks/useFileUploaderService.ts index f94a6f4795d1..884a4aae1460 100644 --- a/front/hooks/useFileUploaderService.ts +++ b/front/hooks/useFileUploaderService.ts @@ -62,6 +62,20 @@ export function useFileUploaderService({ const sendNotification = useSendNotification(); + const findAvailableTitle = ( + baseTitle: string, + ext: string, + existingTitles: string[] + ) => { + let count = 1; + let title = `${baseTitle}.${ext}`; + while (existingTitles.includes(title)) { + title = `${baseTitle}-${count++}.${ext}`; + } + existingTitles.push(title); + return title; + }; + const handleFilesUpload = async (files: File[]) => { setIsProcessingFiles(true); @@ -118,14 +132,12 @@ export function useFileUploaderService({ ): Result[] => { return selectedFiles.reduce( (acc, file) => { - if (fileBlobs.some((f) => f.id === file.name)) { - sendNotification({ - type: "error", - title: `Failed to upload file ${file.name}`, - description: `File "${file.name}" is already uploaded.`, - }); - - return acc; // Ignore if file already exists. + while (fileBlobs.some((f) => f.id === file.name)) { + const [base, ext] = file.name.split(/\.(?=[^.]+$)/); + const name = findAvailableTitle(base, ext, [ + ...fileBlobs.map((f) => f.filename), + ]); + file = new File([file], name, { type: file.type }); } const contentType = getMimeTypeFromFile(file);