diff --git a/__mocks__/@nextcloud/dialogs.ts b/__mocks__/@nextcloud/dialogs.ts index 547057355089b..1b1338223df48 100644 --- a/__mocks__/@nextcloud/dialogs.ts +++ b/__mocks__/@nextcloud/dialogs.ts @@ -11,3 +11,4 @@ export const showWarning = vi.fn() export const showInfo = vi.fn() export const showError = vi.fn() export const showUndo = vi.fn() +export const openConflictPicker = vi.fn() diff --git a/apps/files/src/components/BreadCrumbs.vue b/apps/files/src/components/BreadCrumbs.vue index 567aecd337981..c500e9bf6b0df 100644 --- a/apps/files/src/components/BreadCrumbs.vue +++ b/apps/files/src/components/BreadCrumbs.vue @@ -314,7 +314,7 @@ export default defineComponent({ // Else we're moving/copying files const nodes = selection.map((source) => this.filesStore.getNode(source)) as Node[] - await onDropInternalFiles(nodes, folder, contents.contents, isCopy) + await onDropInternalFiles(nodes, folder, isCopy) // Reset selection after we dropped the files // if the dropped files are within the selection diff --git a/apps/files/src/components/FileEntryMixin.ts b/apps/files/src/components/FileEntryMixin.ts index f91b0da193f69..1b16e24b12256 100644 --- a/apps/files/src/components/FileEntryMixin.ts +++ b/apps/files/src/components/FileEntryMixin.ts @@ -548,19 +548,13 @@ export default defineComponent({ return } - // We might not have the target directory fetched yet - const cachedContents = this.filesStore.getNodesByPath(this.activeView.id, this.source.path) - const contents = cachedContents.length === 0 - ? (await this.activeView!.getContents(this.source.path)).contents - : cachedContents - const isCopy = event.ctrlKey this.dragover = false logger.debug('Dropped', { event, folder: this.source, selection }) const nodes = selection.map((source) => this.filesStore.getNode(source)) as Node[] - await onDropInternalFiles(nodes, this.source, contents, isCopy) + await onDropInternalFiles(nodes, this.source, isCopy) // Reset selection after we dropped the files // if the dropped files are within the selection diff --git a/apps/files/src/services/DropService.ts b/apps/files/src/services/DropService.ts index 91f6e78e974b9..66f8347ab9c6f 100644 --- a/apps/files/src/services/DropService.ts +++ b/apps/files/src/services/DropService.ts @@ -193,15 +193,9 @@ export async function onDropExternalFiles(root: RootDirectory, destination: IFol * * @param nodes - The nodes being dropped * @param destination - The destination folder - * @param contents - The contents of the destination folder * @param isCopy - Whether the operation is a copy */ -export async function onDropInternalFiles(nodes: INode[], destination: IFolder, contents: INode[], isCopy = false) { - // Check for conflicts on root elements - if (getConflicts(nodes, contents).length !== 0) { - nodes = await resolveConflict(nodes, destination, contents) - } - +export async function onDropInternalFiles(nodes: INode[], destination: IFolder, isCopy = false) { if (nodes.length === 0) { logger.info('No files to process', { nodes }) showInfo(t('files', 'No files to process')) diff --git a/apps/files/src/services/DropServiceUtils.spec.ts b/apps/files/src/services/DropServiceUtils.spec.ts index 3fc76656bca0c..764f5e30e7988 100644 --- a/apps/files/src/services/DropServiceUtils.spec.ts +++ b/apps/files/src/services/DropServiceUtils.spec.ts @@ -3,13 +3,15 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ +import { openConflictPicker } from '@nextcloud/dialogs' +import { Folder, File as NcFile, Permission } from '@nextcloud/files' import { join } from 'node:path' import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { DataTransferItem as DataTransferItemMock, FileSystemDirectoryEntry, fileSystemEntryToDataTransferItem, FileSystemFileEntry } from '../../../../__tests__/FileSystemAPIUtils.ts' import { logger } from '../utils/logger.ts' import { newNodeName } from '../utils/newNodeDialog.ts' import { dataTransferToFileTree } from './DropService.ts' -import { Directory, renameInvalidDroppedEntries, traverseTree } from './DropServiceUtils.ts' +import { Directory, renameInvalidDroppedEntries, resolveConflict, traverseTree } from './DropServiceUtils.ts' vi.mock('@nextcloud/dialogs') vi.mock('../utils/newNodeDialog.ts') @@ -165,6 +167,57 @@ describe('renameInvalidDroppedEntries', () => { }) }) +describe('resolveConflict', () => { + const source = 'https://cloud.example.com/remote.php/dav/files/test/folder' + const destination = new Folder({ id: 1, owner: 'test', permissions: Permission.ALL, root: '/files/test', source }) + + /** + * Build an existing file node inside the destination folder. + * + * @param name - The file name + */ + function existing(name: string) { + return new NcFile({ id: 2, owner: 'test', permissions: Permission.ALL, root: '/files/test', source: `${source}/${name}`, mime: 'text/plain' }) + } + + beforeEach(() => vi.mocked(openConflictPicker).mockReset()) + + it('only passes the conflicting nodes to the conflict picker', async () => { + const conflicting = new File(['new'], 'a.txt') + const other = new File([], 'c.txt') + const contents = [existing('a.txt'), existing('b.txt')] + vi.mocked(openConflictPicker).mockResolvedValue({ selected: [conflicting], renamed: [], skipped: [] }) + + const result = await resolveConflict([conflicting, other], destination, contents) + + expect(openConflictPicker).toHaveBeenCalledWith('/folder', [conflicting], [contents[0]]) + expect(result).toEqual([other, conflicting]) + }) + + it('gives files the user wants to keep both of a unique name', async () => { + const conflicting = new File(['new'], 'a.txt', { type: 'text/plain' }) + vi.mocked(openConflictPicker).mockResolvedValue({ selected: [], renamed: [conflicting], skipped: [] }) + + const result = await resolveConflict([conflicting], destination, [existing('a.txt'), existing('a (1).txt')]) + + expect(result).toHaveLength(1) + expect(result[0].name).toBe('a (2).txt') + expect(result[0].type).toBe('text/plain') + expect(await result[0].text()).toBe('new') + }) + + it('keeps the contents of a renamed folder', async () => { + const folder = new Directory('photos.2024', [new File([], 'img.png')]) + vi.mocked(openConflictPicker).mockResolvedValue({ selected: [], renamed: [folder], skipped: [] }) + + const result = await resolveConflict([folder], destination, [existing('photos.2024')]) + + expect(result[0]).toBeInstanceOf(Directory) + expect(result[0].name).toBe('photos.2024 (1)') + expect((result[0] as Directory).contents[0].name).toBe('img.png') + }) +}) + describe('DropService dataTransferToFileTree', () => { beforeAll(() => { // @ts-expect-error jsdom doesn't have DataTransferItem diff --git a/apps/files/src/services/DropServiceUtils.ts b/apps/files/src/services/DropServiceUtils.ts index 2db745e461ca2..3433915bebe9c 100644 --- a/apps/files/src/services/DropServiceUtils.ts +++ b/apps/files/src/services/DropServiceUtils.ts @@ -13,6 +13,7 @@ import { getUniqueName } from '@nextcloud/files' import { defaultRemoteURL, defaultRootPath, getClient, getDefaultPropfind, resultToNode } from '@nextcloud/files/dav' import { t } from '@nextcloud/l10n' import { join } from '@nextcloud/paths' +import { getConflicts } from '../utils/conflicts.ts' import { getFilenameValidity } from '../utils/filenameValidity.ts' import { logger } from '../utils/logger.ts' import { newNodeName } from '../utils/newNodeDialog.ts' @@ -204,20 +205,17 @@ export async function createDirectoryIfNotExists(path: string, destination?: IFo * @param destination - destination folder * @param contents - existing contents of the destination folder */ -export async function resolveConflict(files: Array, destination: IFolder, contents: INode[]): Promise { +export async function resolveConflict(files: (Directory | File)[], destination: IFolder, contents: INode[]): Promise<(Directory | File)[]> { try { // List all conflicting files - const conflicts = files.filter((file: File | INode) => { - return contents.find((node: INode) => node.basename === (file instanceof File ? file.name : file.basename)) - }).filter(Boolean) as (File | INode)[] + const conflicts = getConflicts(files, contents) // List of incoming files that are NOT in conflict - const uploads = files.filter((file: File | INode) => { - return !conflicts.includes(file) - }) + const uploads = files.filter((file) => !conflicts.includes(file)) // Let the user choose what to do with the conflicting files - const conflictResults = await openConflictPicker(destination.path, conflicts, contents) + const existing = contents.filter((node) => conflicts.some((file) => file.name === node.basename)) + const conflictResults = await openConflictPicker(destination.path, conflicts, existing) logger.debug('Conflict resolution', { uploads, conflictResults }) // If the user selected nothing, we cancel the upload @@ -228,8 +226,18 @@ export async function resolveConflict(fi return [] } + // The picker only marks the files to keep both of, renaming is up to us + const usedNames = [...contents.map((node) => node.basename), ...files.map((file) => file.name)] + const renamed = conflictResults.renamed.map((file) => { + const name = getUniqueName(file.name, usedNames, { ignoreFileExtension: file instanceof Directory }) + usedNames.push(name) + return file instanceof Directory + ? new Directory(name, file.contents) + : new File([file], name, { type: file.type, lastModified: file.lastModified }) + }) + // Update the list of files to upload - return [...uploads, ...conflictResults.selected, ...conflictResults.renamed] as (typeof files) + return [...uploads, ...conflictResults.selected, ...renamed] } catch (error) { // User cancelled logger.warn('User cancelled the upload', { error }) diff --git a/tests/playwright/e2e/files/drag-n-drop.spec.ts b/tests/playwright/e2e/files/drag-n-drop.spec.ts index 7e443d3a6253f..6ffc701aef92b 100644 --- a/tests/playwright/e2e/files/drag-n-drop.spec.ts +++ b/tests/playwright/e2e/files/drag-n-drop.spec.ts @@ -4,7 +4,7 @@ */ import { expect, test } from '../../support/fixtures/files-page.ts' -import { mkdir, uploadContent } from '../../support/utils/dav.ts' +import { getFileContent, mkdir, uploadContent } from '../../support/utils/dav.ts' import { createFileDataTransfer, dropFilesOn } from '../../support/utils/drag-drop.ts' import { getToast } from '../../support/utils/toast.ts' @@ -123,4 +123,21 @@ test.describe('files: Drag and Drop onto a folder row', () => { await expect(page.getByRole('dialog')).toBeVisible() expect(putFired).toBe(false) }) + + test('keeps both files when the target folder has other files too', async ({ page, user, filesListPage }) => { + await uploadContent(page.request, user, 'original', 'text/plain', '/subfolder/collide.txt') + await uploadContent(page.request, user, 'other', 'text/plain', '/subfolder/other.txt') + await filesListPage.open() + await expect(filesListPage.getRowForFile('subfolder')).toBeVisible() + + const dataTransfer = await createFileDataTransfer(page, [{ name: 'collide.txt', content: 'replacement' }]) + await dropFilesOn(filesListPage.getRowForFile('subfolder'), dataTransfer) + + const uploaded = page.waitForResponse((r) => r.request().method() === 'PUT' && decodeURIComponent(r.url()).endsWith('/subfolder/collide (1).txt')) + await page.getByRole('dialog').getByRole('button', { name: 'Keep both' }).click() + await uploaded + + expect(await getFileContent(page.request, user, '/subfolder/collide.txt')).toBe('original') + expect(await getFileContent(page.request, user, '/subfolder/collide (1).txt')).toBe('replacement') + }) })