Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions __mocks__/@nextcloud/dialogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
2 changes: 1 addition & 1 deletion apps/files/src/components/BreadCrumbs.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 1 addition & 7 deletions apps/files/src/components/FileEntryMixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 1 addition & 7 deletions apps/files/src/services/DropService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down
55 changes: 54 additions & 1 deletion apps/files/src/services/DropServiceUtils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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
Expand Down
26 changes: 17 additions & 9 deletions apps/files/src/services/DropServiceUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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<T extends ((Directory | File) | INode)>(files: Array<T>, destination: IFolder, contents: INode[]): Promise<T[]> {
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
Expand All @@ -228,8 +226,18 @@ export async function resolveConflict<T extends ((Directory | File) | INode)>(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 })
Expand Down
19 changes: 18 additions & 1 deletion tests/playwright/e2e/files/drag-n-drop.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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')
})
})
Loading