Skip to content

Commit

Permalink
[front] Auto rename uploaded files (#9376)
Browse files Browse the repository at this point in the history
  • Loading branch information
tdraier authored Dec 16, 2024
1 parent 0cfebe6 commit 3831df7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
14 changes: 6 additions & 8 deletions extension/app/src/hooks/useFileUploaderService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,12 @@ export function useFileUploaderService(conversationId?: string) {
): Result<FileBlob, FileBlobUploadError>[] => {
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;
Expand Down
28 changes: 20 additions & 8 deletions front/hooks/useFileUploaderService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -118,14 +132,12 @@ export function useFileUploaderService({
): Result<FileBlob, FileBlobUploadError>[] => {
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);
Expand Down

0 comments on commit 3831df7

Please sign in to comment.