Compare commits

...
7 Commits
13 changed files with 634 additions and 139 deletions

No files matched your search

+21
View File
@@ -2,6 +2,27 @@
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)
### Bug Fixes
* await copy move conflict detection ([#5978](https://github.com/filebrowser/filebrowser/issues/5978)) ([c1abe8f](https://github.com/filebrowser/filebrowser/commit/c1abe8f561208bf36bde70879d1a15ef9de998fa))
* keep mobile file sort controls visible ([#5977](https://github.com/filebrowser/filebrowser/issues/5977)) ([0bb2768](https://github.com/filebrowser/filebrowser/commit/0bb2768754d11b865d68e72dcd7cebb232a6308a))
* skip inaccessible children when listing directories ([#5958](https://github.com/filebrowser/filebrowser/issues/5958)) ([7b7ff8a](https://github.com/filebrowser/filebrowser/commit/7b7ff8ae8f97393b2e6ae6e061c1f780077c32b6))
## [2.63.11](https://github.com/filebrowser/filebrowser/compare/v2.63.10...v2.63.11) (2026-06-04) ## [2.63.11](https://github.com/filebrowser/filebrowser/compare/v2.63.10...v2.63.11) (2026-06-04)
+55 -2
View File
@@ -18,6 +18,7 @@ import (
"path" "path"
"path/filepath" "path/filepath"
"regexp" "regexp"
"sort"
"strings" "strings"
"time" "time"
@@ -452,8 +453,7 @@ func (i *FileInfo) addSubtitle(fPath string) {
} }
func (i *FileInfo) readListing(checker rules.Checker, readHeader bool, calcImgRes bool) error { func (i *FileInfo) readListing(checker rules.Checker, readHeader bool, calcImgRes bool) error {
afs := &afero.Afero{Fs: i.Fs} dir, err := readDir(i.Fs, i.Path)
dir, err := afs.ReadDir(i.Path)
if err != nil { if err != nil {
return err return err
} }
@@ -535,3 +535,56 @@ func (i *FileInfo) readListing(checker rules.Checker, readHeader bool, calcImgRe
i.Listing = listing i.Listing = listing
return nil return nil
} }
func readDir(afs afero.Fs, dirname string) ([]os.FileInfo, error) {
dir, err := afero.ReadDir(afs, dirname)
if err == nil {
return dir, nil
}
dir, fallbackErr := readDirNames(afs, dirname)
if fallbackErr != nil {
return nil, err
}
return dir, nil
}
func readDirNames(afs afero.Fs, dirname string) ([]os.FileInfo, error) {
file, err := afs.Open(dirname)
if err != nil {
return nil, err
}
names, err := file.Readdirnames(-1)
if closeErr := file.Close(); err == nil && closeErr != nil {
err = closeErr
}
if err != nil {
return nil, err
}
sort.Strings(names)
dir := make([]os.FileInfo, 0, len(names))
for _, name := range names {
fPath := path.Join(dirname, name)
info, err := lstatIfPossible(afs, fPath)
if err != nil {
log.Printf("Skipping inaccessible file %s: %v", fPath, err)
continue
}
dir = append(dir, info)
}
return dir, nil
}
func lstatIfPossible(afs afero.Fs, name string) (os.FileInfo, error) {
if lstaterFs, ok := afs.(afero.Lstater); ok {
info, _, err := lstaterFs.LstatIfPossible(name)
return info, err
}
return afs.Stat(name)
}
+89
View File
@@ -2,6 +2,7 @@ package files
import ( import (
"os" "os"
"path"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -131,3 +132,91 @@ func TestStatRejectsLinkedAncestorEscape(t *testing.T) {
t.Fatalf("expected in-scope file to be served, got %v", err) t.Fatalf("expected in-scope file to be served, got %v", err)
} }
} }
type allowAllChecker struct{}
func (allowAllChecker) Check(string) bool {
return true
}
type inaccessibleChildFs struct {
afero.Fs
child string
}
func (fs inaccessibleChildFs) Open(name string) (afero.File, error) {
file, err := fs.Fs.Open(name)
if err != nil {
return nil, err
}
if path.Clean(name) == "/" {
return inaccessibleChildDir{File: file}, nil
}
return file, nil
}
func (fs inaccessibleChildFs) Stat(name string) (os.FileInfo, error) {
if path.Clean(name) == fs.child {
return nil, os.ErrPermission
}
return fs.Fs.Stat(name)
}
func (fs inaccessibleChildFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
if path.Clean(name) == fs.child {
return nil, false, os.ErrPermission
}
if lstater, ok := fs.Fs.(afero.Lstater); ok {
return lstater.LstatIfPossible(name)
}
info, err := fs.Fs.Stat(name)
return info, false, err
}
type inaccessibleChildDir struct {
afero.File
}
func (dir inaccessibleChildDir) Readdir(int) ([]os.FileInfo, error) {
return nil, os.ErrPermission
}
func TestReadListingSkipsInaccessibleChildren(t *testing.T) {
memFs := afero.NewMemMapFs()
for _, dir := range []string{"/media", "/proton-mount"} {
if err := memFs.Mkdir(dir, 0o755); err != nil {
t.Fatal(err)
}
}
file, err := NewFileInfo(&FileOptions{
Fs: inaccessibleChildFs{Fs: memFs, child: "/proton-mount"},
Path: "/",
Expand: true,
Checker: allowAllChecker{},
})
if err != nil {
t.Fatal(err)
}
if file.Listing == nil {
t.Fatal("expected root listing")
}
if got := len(file.Items); got != 1 {
t.Fatalf("expected one accessible child, got %d", got)
}
if got := file.Items[0].Name; got != "media" {
t.Fatalf("expected accessible child to be listed, got %q", got)
}
if got := file.NumDirs; got != 1 {
t.Fatalf("expected one listed directory, got %d", got)
}
}
@@ -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({
+2 -1
View File
@@ -92,6 +92,7 @@ export default {
to: this.dest + encodeURIComponent(this.req.items[item].name), to: this.dest + encodeURIComponent(this.req.items[item].name),
name: this.req.items[item].name, name: this.req.items[item].name,
size: this.req.items[item].size, size: this.req.items[item].size,
isDir: this.req.items[item].isDir,
modified: this.req.items[item].modified, modified: this.req.items[item].modified,
overwrite: false, overwrite: false,
rename: this.$route.path === this.dest, rename: this.$route.path === this.dest,
@@ -122,7 +123,7 @@ export default {
}); });
}; };
const conflict = 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({
+2 -1
View File
@@ -98,6 +98,7 @@ export default {
to: this.dest + encodeURIComponent(this.req.items[item].name), to: this.dest + encodeURIComponent(this.req.items[item].name),
name: this.req.items[item].name, name: this.req.items[item].name,
size: this.req.items[item].size, size: this.req.items[item].size,
isDir: this.req.items[item].isDir,
modified: this.req.items[item].modified, modified: this.req.items[item].modified,
overwrite: false, overwrite: false,
rename: false, rename: false,
@@ -122,7 +123,7 @@ export default {
}); });
}; };
const conflict = 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({
@@ -0,0 +1,127 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import CopyPrompt from "@/components/prompts/Copy.vue";
import MovePrompt from "@/components/prompts/Move.vue";
import { files as api } from "@/api";
import { checkConflict } from "@/utils/upload";
vi.mock("@/api", () => ({
files: {
copy: vi.fn().mockResolvedValue(undefined),
move: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock("@/api/utils", () => ({
removePrefix: (value: string) => value.replace(/^\/files/, ""),
}));
vi.mock("@/utils/buttons", () => ({
default: {
loading: vi.fn(),
success: vi.fn(),
done: vi.fn(),
},
}));
vi.mock("@/utils/upload", () => ({
checkConflict: vi.fn(),
}));
const conflict = [
{
index: 0,
name: "/target/file.txt",
origin: { size: 12 },
dest: { size: 10 },
checked: ["origin"],
isSmallerOnServer: true,
},
];
function makeContext() {
return {
selected: [0],
req: {
items: [
{
url: "/files/source/file.txt",
name: "file.txt",
size: 12,
isDir: false,
modified: "2026-06-04T00:00:00Z",
},
],
},
dest: "/files/target/",
user: { redirectAfterCopyMove: false },
$route: { path: "/files/source/" },
$router: { push: vi.fn() },
reload: false,
preselect: "",
showHover: vi.fn(),
closeHovers: vi.fn(),
$showError: vi.fn(),
};
}
const event = {
preventDefault: vi.fn(),
};
describe("copy and move conflict prompts", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(checkConflict).mockResolvedValue(conflict);
});
it("waits for copy conflict detection before calling the copy API", async () => {
const context = makeContext();
await (CopyPrompt as any).methods.copy.call(context, event);
expect(checkConflict).toHaveBeenCalledWith(
[
expect.objectContaining({
to: "/files/target/file.txt",
isDir: false,
}),
],
"/files/target/",
true
);
expect(context.showHover).toHaveBeenCalledWith(
expect.objectContaining({
prompt: "resolve-conflict",
props: { conflict },
})
);
expect(api.copy).not.toHaveBeenCalled();
});
it("waits for move conflict detection before calling the move API", async () => {
const context = makeContext();
await (MovePrompt as any).methods.move.call(context, event);
expect(checkConflict).toHaveBeenCalledWith(
[
expect.objectContaining({
to: "/files/target/file.txt",
isDir: false,
}),
],
"/files/target/",
true
);
expect(context.showHover).toHaveBeenCalledWith(
expect.objectContaining({
prompt: "resolve-conflict",
props: expect.objectContaining({
conflict,
files: expect.any(Array),
}),
})
);
expect(api.move).not.toHaveBeenCalled();
});
});
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
const mobileCss = readFileSync(resolve(__dirname, "../mobile.css"), "utf8");
const normalizedCss = mobileCss.replace(/\s+/g, " ");
describe("mobile file listing styles", () => {
it("hides file row metadata without hiding list header sort controls", () => {
expect(normalizedCss).toContain(
"#listing.list .item:not(.header) .size { display: none;"
);
expect(normalizedCss).toContain(
"#listing.list .item:not(.header) .modified { display: none;"
);
expect(normalizedCss).not.toMatch(
/#listing\.list \.item \.(size|modified) \{ display: none;/
);
});
});
+31 -4
View File
@@ -14,12 +14,27 @@
body { body {
padding-bottom: 5em; padding-bottom: 5em;
} }
#listing.list .item .size { #listing.list .item:not(.header) .size {
display: none; display: none;
} }
#listing.list .item .name { #listing.list .item:not(.header) .name {
width: 60%; width: 60%;
} }
#listing.list .item.header .name {
margin-right: 0;
width: 45%;
}
#listing.list .item.header .size {
width: 25%;
}
#listing.list .item.header .modified {
width: 30%;
}
#listing.list .item.header p {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#more { #more {
display: inherit; display: inherit;
} }
@@ -162,10 +177,22 @@
} }
@media (max-width: 450px) { @media (max-width: 450px) {
#listing.list .item .modified { #listing.list .item:not(.header) .modified {
display: none; display: none;
} }
#listing.list .item .name { #listing.list .item:not(.header) .name {
width: 100%; width: 100%;
} }
#listing.list .item.header {
padding: 0.75em 0.5em;
}
#listing.list .item.header .name {
width: 34%;
}
#listing.list .item.header .size {
width: 24%;
}
#listing.list .item.header .modified {
width: 42%;
}
} }
+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({