Compare commits

...
3 Commits
Author SHA1 Message Date
Henrique Dias 67ed670d92 chore(release): 2.63.13 2026-06-06 08:33:27 +02:00
Henrique Dias a1a514dcbb fix: copy/move allow overwrite 2026-06-06 08:28:31 +02:00
Henrique Dias 5f7311d324 refactor: cleanup and simplify upload.ts 2026-06-06 08:15:16 +02:00
9 changed files with 303 additions and 135 deletions

No files matched your search

+12
View File
@@ -2,6 +2,18 @@
All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines. All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
## [2.63.13](https://github.com/filebrowser/filebrowser/compare/v2.63.12...v2.63.13) (2026-06-06)
### Bug Fixes
* copy/move allow overwrite ([a1a514d](https://github.com/filebrowser/filebrowser/commit/a1a514dcbb216d2080412c5354eea1e1fb033050))
### Refactorings
* cleanup and simplify upload.ts ([5f7311d](https://github.com/filebrowser/filebrowser/commit/5f7311d32437e98d7c14c7b307a4f68109275535))
## [2.63.12](https://github.com/filebrowser/filebrowser/compare/v2.63.11...v2.63.12) (2026-06-04) ## [2.63.12](https://github.com/filebrowser/filebrowser/compare/v2.63.11...v2.63.12) (2026-06-04)
@@ -179,6 +179,7 @@ const drop = async (event: Event) => {
to: props.url + encodeURIComponent(fileStore.req?.items[i].name), to: props.url + encodeURIComponent(fileStore.req?.items[i].name),
name: fileStore.req?.items[i].name, name: fileStore.req?.items[i].name,
size: fileStore.req?.items[i].size, size: fileStore.req?.items[i].size,
isDir: fileStore.req?.items[i].isDir,
modified: fileStore.req?.items[i].modified, modified: fileStore.req?.items[i].modified,
overwrite: false, overwrite: false,
rename: false, rename: false,
@@ -204,7 +205,7 @@ const drop = async (event: Event) => {
.catch($showError); .catch($showError);
}; };
const conflict = await upload.checkConflict(items, path); const conflict = await upload.checkConflict(items, path, true);
if (conflict.length > 0) { if (conflict.length > 0) {
layoutStore.showHover({ layoutStore.showHover({
+1 -1
View File
@@ -123,7 +123,7 @@ export default {
}); });
}; };
const conflict = await upload.checkConflict(items, this.dest); const conflict = await upload.checkConflict(items, this.dest, true);
if (conflict.length > 0) { if (conflict.length > 0) {
this.showHover({ this.showHover({
+1 -1
View File
@@ -123,7 +123,7 @@ export default {
}); });
}; };
const conflict = await upload.checkConflict(items, this.dest); const conflict = await upload.checkConflict(items, this.dest, true);
if (conflict.length > 0) { if (conflict.length > 0) {
this.showHover({ this.showHover({
@@ -86,7 +86,8 @@ describe("copy and move conflict prompts", () => {
isDir: false, isDir: false,
}), }),
], ],
"/files/target/" "/files/target/",
true
); );
expect(context.showHover).toHaveBeenCalledWith( expect(context.showHover).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
@@ -109,7 +110,8 @@ describe("copy and move conflict prompts", () => {
isDir: false, isDir: false,
}), }),
], ],
"/files/target/" "/files/target/",
true
); );
expect(context.showHover).toHaveBeenCalledWith( expect(context.showHover).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
+1
View File
@@ -53,6 +53,7 @@ interface ClipItem {
from: string; from: string;
name: string; name: string;
size?: number; size?: number;
isDir?: boolean;
modified?: string; modified?: string;
} }
@@ -0,0 +1,223 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { checkConflict } from "@/utils/upload";
import { files as api } from "@/api";
vi.mock("@/api", () => ({
files: {
fetchAll: vi.fn(),
},
}));
vi.mock("@/api/utils", () => ({
removePrefix: (value: string) => value.replace(/^\/files/, ""),
}));
// upload.ts imports these at module load; they reach window-bound constants
// which don't exist in the node test environment. checkConflict never uses
// them, so empty stubs keep the import graph from blowing up.
vi.mock("@/stores/layout", () => ({ useLayoutStore: vi.fn() }));
vi.mock("@/stores/upload", () => ({ useUploadStore: vi.fn() }));
vi.mock("@/utils/url", () => ({ default: {} }));
// A move/copy/drag item carries `name` (raw) and `to` (URL-encoded) but no
// `fullPath` — mirroring what Move.vue / Copy.vue / ListingItem.vue build.
function moveItem(name: string, dest: string, size = 12) {
return {
from: `/files/source/${encodeURIComponent(name)}`,
to: dest + encodeURIComponent(name),
name,
size,
isDir: false,
overwrite: false,
rename: false,
};
}
describe("checkConflict", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("detects a conflict for a plain filename", async () => {
vi.mocked(api.fetchAll).mockResolvedValue([
{
path: "/target/file.txt",
name: "file.txt",
size: 10,
modified: "2026-06-04T00:00:00Z",
isDir: false,
},
]);
const conflicts = await checkConflict(
[moveItem("file.txt", "/files/target/")],
"/files/target/"
);
expect(conflicts).toHaveLength(1);
expect(conflicts[0].name).toBe("/target/file.txt");
});
// Regression for #5957: names with encodable characters (spaces, "#",
// non-ASCII) were keyed by the URL-encoded `to` value and never matched the
// server's raw path, so the conflict modal was skipped and the backend
// returned a bare 409 instead.
it.each(["my file.txt", "résumé.pdf", "a#b.txt"])(
"detects a conflict for %s (encodable characters)",
async (name) => {
vi.mocked(api.fetchAll).mockResolvedValue([
{
path: `/target/${name}`,
name,
size: 10,
modified: "2026-06-04T00:00:00Z",
isDir: false,
},
]);
const conflicts = await checkConflict(
[moveItem(name, "/files/target/")],
"/files/target/"
);
expect(conflicts).toHaveLength(1);
expect(conflicts[0].name).toBe(`/target/${name}`);
}
);
it("reports no conflict when the destination has no matching name", async () => {
vi.mocked(api.fetchAll).mockResolvedValue([
{
path: "/target/other.txt",
name: "other.txt",
size: 10,
modified: "2026-06-04T00:00:00Z",
isDir: false,
},
]);
const conflicts = await checkConflict(
[moveItem("my file.txt", "/files/target/")],
"/files/target/"
);
expect(conflicts).toHaveLength(0);
});
it("detects nested conflicts for folder uploads via fullPath", async () => {
vi.mocked(api.fetchAll).mockResolvedValue([
{
path: "/target/folder",
name: "folder",
size: 0,
modified: "2026-06-04T00:00:00Z",
isDir: true,
},
{
path: "/target/folder/nested file.txt",
name: "nested file.txt",
size: 10,
modified: "2026-06-04T00:00:00Z",
isDir: false,
},
]);
const files = [
{ name: "folder", size: 0, isDir: true, fullPath: "folder" },
{
name: "nested file.txt",
size: 12,
isDir: false,
fullPath: "folder/nested file.txt",
},
];
const conflicts = await checkConflict(files, "/files/target/");
expect(conflicts).toHaveLength(1);
expect(conflicts[0].name).toBe("/target/folder/nested file.txt");
});
// The "upload folder" file input pushes only files (with a relative
// fullPath) and no directory entries. Conflict detection must still find a
// nested file even though its parent folder is not in the upload list.
it("detects nested conflicts when no directory entries are present", async () => {
vi.mocked(api.fetchAll).mockResolvedValue([
{
path: "/target/folder/deep/file.txt",
name: "file.txt",
size: 10,
modified: "2026-06-04T00:00:00Z",
isDir: false,
},
]);
const files = [
{
name: "file.txt",
size: 12,
isDir: false,
fullPath: "folder/deep/file.txt",
},
];
const conflicts = await checkConflict(files, "/files/target/");
expect(conflicts).toHaveLength(1);
expect(conflicts[0].name).toBe("/target/folder/deep/file.txt");
});
// Copy/move stats the whole destination, so a same-named directory is a
// conflict in its own right (regression for the directory case of #5957).
it("reports a directory conflict for copy/move (includeDirectories)", async () => {
vi.mocked(api.fetchAll).mockResolvedValue([
{
path: "/target/folder",
name: "folder",
size: 0,
modified: "2026-06-04T00:00:00Z",
isDir: true,
},
]);
const items = [{ ...moveItem("folder", "/files/target/", 0), isDir: true }];
const conflicts = await checkConflict(items, "/files/target/", true);
expect(conflicts).toHaveLength(1);
expect(conflicts[0].name).toBe("/target/folder");
});
// Uploads merge into an existing folder, so the directory itself must not be
// reported — only the files inside it can conflict.
it("ignores a directory conflict for uploads (default)", async () => {
vi.mocked(api.fetchAll).mockResolvedValue([
{
path: "/target/folder",
name: "folder",
size: 0,
modified: "2026-06-04T00:00:00Z",
isDir: true,
},
]);
const files = [
{ name: "folder", size: 0, isDir: true, fullPath: "folder" },
];
const conflicts = await checkConflict(files, "/files/target/");
expect(conflicts).toHaveLength(0);
});
it("returns no conflicts when the recursive listing fails", async () => {
vi.mocked(api.fetchAll).mockRejectedValue(new Error("404"));
const conflicts = await checkConflict(
[moveItem("file.txt", "/files/target/")],
"/files/target/"
);
expect(conflicts).toHaveLength(0);
});
});
+56 -129
View File
@@ -4,159 +4,86 @@ import url from "@/utils/url";
import { files as api } from "@/api"; import { files as api } from "@/api";
import { removePrefix } from "@/api/utils"; import { removePrefix } from "@/api/utils";
interface UploadEntryWithChild extends UploadEntry {
children?: UploadEntryWithChild[];
originalIndex: number;
}
/** /**
* Convert UploadList into a forest (array of root nodes). * The path used to detect conflicts against the server's recursive listing.
* This properly handles uploads with multiple top-level files/folders *
* instead of assuming a single root. * It MUST be the raw, un-encoded path relative to the destination:
* @param flatArray * - `fullPath` is set for folder uploads and drag & drop (e.g. "sub/file.txt").
* @param basePath * - `name` is the leaf for every other case (copy/move/paste/single upload),
* which is always a flat top-level entry.
*
* We never key on `item.to`: it is URL-encoded (`dest + encodeURIComponent(name)`)
* and would miss conflicts for any name with encodable characters (spaces, "#",
* non-ASCII, ...), surfacing a raw 409 error instead of the conflict modal.
* @param item
*/ */
function flatToForest( function conflictKey(item: UploadEntry): string {
flatArray: UploadList, return (item.fullPath || item.name).replace(/^\/+/, "");
basePath: string
): UploadEntryWithChild[] {
const nodeMap: Record<string, UploadEntryWithChild> = {};
// First pass: create all nodes
flatArray.forEach((item, index) => {
// File list is created from very different action and info available are not always the same.
// By doing a drag and drop or upload a folder (both from the browser or from the OS) we have the fullPath property available
// By uploading a single file using the file input, we only have the "name" property
// By doing drag and drop from filebrowser to filebrowser, we have the "to" property available but not the fullPath
const fullPathOrTo =
item.fullPath || item.to?.replace(basePath, "") || item.name;
nodeMap[fullPathOrTo!] = {
fullPath: fullPathOrTo,
isDir: item.isDir,
name: item.name,
size: item.size,
originalIndex: index,
...(item.isDir && { children: [] }),
...(item.file && { file: item.file }),
};
});
const roots: UploadEntryWithChild[] = [];
// Second pass: build hierarchy
flatArray.forEach((item) => {
// see comment before to explanation
const fullPathOrTo =
item.fullPath || item.to?.replace(basePath, "") || item.name;
const node = nodeMap[fullPathOrTo!];
const lastSlash = fullPathOrTo!.lastIndexOf("/");
if (lastSlash === -1) {
roots.push(node);
} else {
const parentPath = fullPathOrTo!.substring(0, lastSlash);
const parent = nodeMap[parentPath];
if (parent?.children) {
parent.children.push(node);
}
}
});
return roots;
} }
/** /**
* Return conflict files from * Return the entries from `files` that already exist under `basePath` on the
* @param files - flat upload list to check * server, so the caller can prompt the user to overwrite/rename/skip.
* @param basePath - server destination path (e.g. "/files/uploads/") *
* The whole destination tree is fetched once and indexed by path relative to
* the destination, then every entry is looked up directly — no need to mirror
* the upload's folder structure.
*
* Directory handling differs by action, hence `includeDirectories`:
* - Upload (false): an existing folder is silently merged, so only the
* individual files inside it can conflict.
* - Copy/move (true): the server stats the destination and rejects it whole if
* a same-named entry exists, so the directory itself is a conflict. The list
* only holds the top-level items being moved, so each is reported once.
*
* @param files - flat upload list to check
* @param basePath - server destination path (e.g. "/files/uploads/")
* @param includeDirectories - report directories as conflicts (copy/move)
*/ */
export async function checkConflict( export async function checkConflict(
files: UploadList, files: UploadList,
basePath: string basePath: string,
includeDirectories = false
): Promise<ConflictingResource[]> { ): Promise<ConflictingResource[]> {
console.log( if (files.length === 0) return [];
"Starting conflict check, " + files.length + " possible conflict found."
);
const forest = flatToForest(files, basePath); let serverEntries: RecursiveEntry[];
if (forest.length === 0) return [];
// Single API call: fetch the entire server tree under basePath.
let serverEntries: RecursiveEntry[] = [];
try { try {
// Single API call: fetch the entire server tree under basePath.
serverEntries = await api.fetchAll(basePath); serverEntries = await api.fetchAll(basePath);
} catch { } catch {
console.error( // The destination doesn't exist yet, so nothing can conflict.
`Failed to fetch recursive server listing for ${basePath}. ` +
`Assuming directory doesn't exist and skipping conflict check.`
);
return []; return [];
} }
// Build a lookup map keyed by the normalised server path for O(1) access. // The server returns paths absolute within the user's scope
// The server returns paths relative to the user's scope (e.g. "/uploads/foo.txt"). // (e.g. "/uploads/sub/file.txt"). Strip the basePath prefix so the keys line
// We strip the basePath prefix so the key matches the upload entry's fullPath. // up with each entry's conflictKey, which is relative to the destination.
const normBase = removePrefix(basePath).replace(/\/+$/, ""); const normBase = removePrefix(basePath).replace(/\/+$/, "");
const serverMap = new Map<string, RecursiveEntry>(); const serverMap = new Map<string, RecursiveEntry>();
for (const entry of serverEntries) { for (const entry of serverEntries) {
// entry.path is absolute from server root, e.g. "/uploads/sub/file.txt" const rel = entry.path.startsWith(normBase)
// We need the relative part after normBase, e.g. "sub/file.txt" ? entry.path.slice(normBase.length)
let rel = entry.path; : entry.path;
if (rel.startsWith(normBase)) { serverMap.set(rel.replace(/^\/+/, ""), entry);
rel = rel.slice(normBase.length);
}
// Strip leading slash so it matches fullPath format ("sub/file.txt")
rel = rel.replace(/^\/+/, "");
serverMap.set(rel, entry);
} }
const conflicts: ConflictingResource[] = []; const conflicts: ConflictingResource[] = [];
files.forEach((file, index) => {
if (file.isDir && !includeDirectories) return; // see directory note above
/** const server = serverMap.get(conflictKey(file));
* Walk the upload tree and compare each file node against the if (!server) return;
* pre-fetched server map. Directories only need to be recursed
* when they appear in the map (otherwise no child can conflict).
*/
function recursiveCheckConflict(nodes: UploadEntryWithChild[]): void {
for (const node of nodes) {
if (node.isDir && node.children) {
// Only recurse if this directory exists on the server
const dirKey = node.fullPath!.replace(/^\/+/, "");
if (serverMap.has(dirKey)) {
recursiveCheckConflict(node.children);
}
} else {
// File – check for a conflict against the server map
const fileKey = node.fullPath!.replace(/^\/+/, "");
const serverEntry = serverMap.get(fileKey);
if (serverEntry) { conflicts.push({
conflicts.push({ index,
index: node.originalIndex, name: server.path,
name: serverEntry.path, origin: { lastModified: file.file?.lastModified, size: file.size },
origin: { dest: { lastModified: server.modified, size: server.size },
lastModified: node.file?.lastModified, checked: ["origin"],
size: node.size, isSmallerOnServer: file.size > server.size,
}, });
dest: { });
lastModified: serverEntry.modified,
size: serverEntry.size,
},
checked: ["origin"],
isSmallerOnServer: node.size > serverEntry.size,
});
}
}
}
}
// Walk all root nodes synchronously against the pre-fetched data
recursiveCheckConflict(forest);
console.log(conflicts.length + " conflicts found.");
conflicts.sort((a, b) => a.index - b.index);
return conflicts; return conflicts;
} }
+3 -1
View File
@@ -632,6 +632,7 @@ const copyCut = (event: Event | KeyboardEvent): void => {
from: fileStore.req.items[i].url, from: fileStore.req.items[i].url,
name: fileStore.req.items[i].name, name: fileStore.req.items[i].name,
size: fileStore.req.items[i].size, size: fileStore.req.items[i].size,
isDir: fileStore.req.items[i].isDir,
modified: fileStore.req.items[i].modified, modified: fileStore.req.items[i].modified,
}); });
} }
@@ -661,6 +662,7 @@ const paste = async (event: Event) => {
to, to,
name: item.name, name: item.name,
size: item.size, size: item.size,
isDir: item.isDir,
modified: item.modified, modified: item.modified,
overwrite: false, overwrite: false,
rename: clipboardStore.path == route.path, rename: clipboardStore.path == route.path,
@@ -697,7 +699,7 @@ const paste = async (event: Event) => {
} }
const path = route.path.endsWith("/") ? route.path : route.path + "/"; const path = route.path.endsWith("/") ? route.path : route.path + "/";
const conflict = await upload.checkConflict(items, path); const conflict = await upload.checkConflict(items, path, true);
if (conflict.length > 0) { if (conflict.length > 0) {
layoutStore.showHover({ layoutStore.showHover({