diff --git a/CLIPBOARD_UPLOAD_POC.md b/CLIPBOARD_UPLOAD_POC.md new file mode 100644 index 0000000000000..4b14b1968e4c6 --- /dev/null +++ b/CLIPBOARD_UPLOAD_POC.md @@ -0,0 +1,106 @@ +# Clipboard Image Upload – Proof of Concept + +**Related issue:** [Nextcloud #37830](https://github.com/nextcloud/server/issues/37830) + +## 1. Objective + +The goal is to allow users to paste copied images directly into the currently open folder in Nextcloud Files using Ctrl+V or Cmd+V, without having to save the image locally and upload it manually. + +My approach was to make clipboard upload an extension of the existing upload functionality rather than introducing a separate upload mechanism. + +## 2. Scope and assumptions + +- Support single and multiple images copied to the clipboard. +- Preserve the original filename, image content, MIME type and modification timestamp provided by the browser. +- Generate a valid fallback filename when the original filename is missing or invalid. +- Handle duplicate filenames using Nextcloud's existing conflict resolution dialog. +- Use existing upload permissions and storage quota restrictions. +- Preserve normal paste behaviour when the clipboard does not contain images. + +The feature only processes image files exposed by the browser's clipboard event. Fetching images from copied URLs, processing HTML content and uploading non-image files are outside the scope of this PoC. + +## 3. Supported views + +| View | Clipboard upload | +|---|---| +| All files / Personal files | Supported in writable folders | +| Nested folders | Supported | +| Internal shared folders | Supported with upload permission | +| Public writable folders | Supported | +| Read-only folders | Not supported | +| File Drop shares | Not supported | +| Overview views without a valid upload destination | Not supported | +| Folders with exhausted storage quota | Not supported | + +Rather than relying on a hardcoded list of view names, the implementation uses the current folder, view context and existing permission checks. + +File Drop is intentionally excluded because visitors cannot read the destination contents required by the clipboard conflict resolution logic. + +## 4. Special cases and expected behaviour + +| Scenario | Expected behaviour | +|---|---| +| Pasting text, HTML or a URL without image files | Preserve normal paste behaviour | +| Pasting while editing a filename or using an input field | Ignore clipboard upload | +| Pasting while a modal dialog is open | Ignore clipboard upload | +| Duplicate filenames within a batch | Generate unique filenames | +| Conflict with an existing file | Use existing conflict resolution options | +| Cancelling conflict resolution | Cancel the batch | +| Navigating away during an upload | Retain the original destination | +| Consecutive accepted paste events | Process batches sequentially | +| Upload or destination-fetch failure | Handle the error and allow subsequent uploads | + +## 5. Implementation approach + +The implementation is divided into two main parts: + +- **FilesList.vue:** Registers and removes the paste event listener, validates the current view and destination, checks upload permissions and quota, and displays error notifications for blocked clipboard uploads. +- **ClipboardUploadService.ts:** - Validates clipboard paste events, extracts clipboard images, prepares filenames, handles conflicts and passes the files to Nextcloud's existing uploader. + +I chose this separation to keep the view responsible for application context and the service responsible for clipboard-specific logic. + +Reusing the existing uploader and conflict picker avoids duplicating upload functionality and keeps the behaviour consistent with standard file uploads. + +No new dependencies or backend changes were introduced. + +## 6. Testing + +The implementation was validated using three levels of testing: + +| Testing approach | Result | +|---|---| +| Vitest unit tests | 13/13 passed | +| Playwright end-to-end tests | 10/10 passed | +| Manual testing | Completed | + +Manual testing included native clipboard interactions, nested folders, filename conflicts, sharing permissions, storage quotas, network interruptions and navigation during uploads. + +## 7. Known limitations + +- File Drop support would require a different approach to conflict handling. +- The local development environment displays incomplete metadata in the existing conflict dialog. This behaviour was reproduced on the original baseline without the clipboard implementation and was therefore left unchanged. +- Browsers assign generic filenames such as image.png to screenshots both on macOS and windows. Since the Clipboard API cannot reliably distinguish a screenshot from an existing image file with the same name, automatically renaming it could alter legitimate filenames. The current implementation intentionally preserves valid filenames and reuses Nextcloud's existing conflict-resolution mechanism to maintain consistency and user control. Alternative naming strategies remain open for discussion. + +## 8. AI-assisted development + +I used ChatGPT and Cursor for exploring implementation approaches, discussing edge cases, refining code, designing tests and reviewing changes. + +I evaluated the suggestions against Nextcloud's existing architecture and conventions, reviewed the implementation, executed the automated tests and manually validated the feature in the development environment. + +## 9. Running the tests + +The implementation was developed using Nextcloud's official Docker development environment. + +**Unit tests:** + +```bash +npm test -- apps/files/src/services/ClipboardUploadService.spec.ts +``` + +**End-to-end tests:** + +```bash +npx playwright test clipboard-upload.spec.ts --workers=1 +``` + +To manually reproduce the feature, open a writable folder in Nextcloud Files, copy an image and press Ctrl+V or Cmd+V. \ No newline at end of file diff --git a/apps/files/src/services/ClipboardUploadService.spec.ts b/apps/files/src/services/ClipboardUploadService.spec.ts new file mode 100644 index 0000000000000..ee24b89c633a1 --- /dev/null +++ b/apps/files/src/services/ClipboardUploadService.spec.ts @@ -0,0 +1,467 @@ +/*! + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { IFolder, INode } from '@nextcloud/files' + +import { openConflictPicker, showError } from '@nextcloud/dialogs' +import { getUploader } from '@nextcloud/files/upload' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { getClipboardImages, prepareClipboardImages, shouldIgnoreClipboardPaste, uploadClipboardImages } from './ClipboardUploadService.ts' + +vi.mock('@nextcloud/dialogs', () => ({ + openConflictPicker: vi.fn(), + showError: vi.fn(), +})) + +vi.mock('@nextcloud/files/upload', () => ({ + getUploader: vi.fn(), +})) + +vi.mock('@nextcloud/capabilities', () => ({ + getCapabilities: () => ({ + files: { + forbidden_filename_characters: ['/', '\\'], + forbidden_filenames: ['.htaccess'], + forbidden_filename_basenames: ['con'], + forbidden_filename_extensions: ['.exe', '.part'], + }, + }), +})) + +function createClipboardEvent( + items: Pick[] = [], + files: File[] = [], +): ClipboardEvent { + const event = new Event('paste', { + bubbles: true, + cancelable: true, + }) + + Object.defineProperty(event, 'clipboardData', { + value: { items, files }, + }) + + return event as ClipboardEvent +} + +function createFileItem(file: File) { + return { + kind: 'file', + type: file.type, + getAsFile: () => file, + } +} + +describe('getClipboardImages', () => { + it('returns no images for missing or empty clipboard data', () => { + const event = new Event('paste') as ClipboardEvent + + expect(getClipboardImages(event)).toEqual([]) + expect(getClipboardImages(createClipboardEvent())).toEqual([]) + }) + + it('ignores non-image clipboard content', () => { + const event = createClipboardEvent(['text/plain', 'text/html', 'text/uri-list'].map((type) => ({ + kind: 'string', + type, + getAsFile: () => null, + }))) + + expect(getClipboardImages(event)).toEqual([]) + }) + + it('extracts multiple images and ignores non-image files', () => { + const png = new File(['png-content'], 'image.png', { + type: 'image/png', + }) + const jpeg = new File(['jpeg-content'], 'photo.jpg', { + type: 'image/jpeg', + }) + const document = new File(['text'], 'notes.txt', { + type: 'text/plain', + }) + + const event = createClipboardEvent([ + createFileItem(png), + createFileItem(document), + createFileItem(jpeg), + ]) + + const images = getClipboardImages(event) + + expect(images).toHaveLength(2) + expect(images[0]).toBe(png) + expect(images[1]).toBe(jpeg) + }) + + it('falls back to clipboard files when items contain no usable files', () => { + const image = new File(['image-content'], 'photo.png', { + type: 'image/png', + }) + const document = new File(['text'], 'notes.txt', { + type: 'text/plain', + }) + + const event = createClipboardEvent([ + { + kind: 'file', + type: 'image/png', + getAsFile: () => null, + }, + ], [image, document]) + + expect(getClipboardImages(event)).toEqual([image]) + }) +}) + +describe('prepareClipboardImages', () => { + it('preserves valid filenames and original file objects', () => { + const files = [ + new File(['png-content'], 'image.png', { + type: 'image/png', + }), + new File(['jpeg-content'], 'My Photo.jpg', { + type: 'image/jpeg', + }), + ] + + const result = prepareClipboardImages(files) + + expect(result).toHaveLength(2) + expect(result[0]).toBe(files[0]) + expect(result[1]).toBe(files[1]) + }) + + it('generates fallback filenames while preserving content and metadata', async () => { + const files = [ + new File(['png-content'], '', { + type: 'image/png', + lastModified: 1234567890, + }), + new File(['jpeg-content'], 'con.jpg', { + type: 'image/jpeg', + lastModified: 9876543210, + }), + ] + + const result = prepareClipboardImages(files) + + expect(result.map((file) => file.name)).toEqual([ + 'Clipboard.png', + 'Clipboard.jpg', + ]) + + for (const [index, file] of result.entries()) { + expect(file.type).toBe(files[index].type) + expect(file.size).toBe(files[index].size) + expect(file.lastModified).toBe(files[index].lastModified) + expect(await file.arrayBuffer()).toEqual(await files[index].arrayBuffer()) + } + }) + + it('generates unique filenames without colliding with other incoming files', async () => { + const files = [ + new File(['first'], 'image.png', { + type: 'image/png', + }), + new File(['second'], 'image.png', { + type: 'image/png', + lastModified: 1234567890, + }), + new File(['third'], 'image (1).png', { + type: 'image/png', + }), + ] + + const result = prepareClipboardImages(files) + + expect(result.map((file) => file.name)).toEqual([ + 'image.png', + 'image (2).png', + 'image (1).png', + ]) + + expect(new Set(result.map((file) => file.name)).size).toBe(3) + expect(result[0]).toBe(files[0]) + expect(result[2]).toBe(files[2]) + + expect(result[1]).not.toBe(files[1]) + expect(result[1].type).toBe(files[1].type) + expect(result[1].size).toBe(files[1].size) + expect(result[1].lastModified).toBe(files[1].lastModified) + expect(await result[1].arrayBuffer()).toEqual(await files[1].arrayBuffer()) + }) +}) + +describe('uploadClipboardImages', () => { + const batchUpload = vi.fn() + + function createContext() { + return { + folder: { + source: '/remote.php/dav/files/testuser/photos', + } as IFolder, + getContents: vi.fn().mockResolvedValue([]), + } + } + + function createImageEvent() { + const image = new File(['image-content'], 'photo.png', { + type: 'image/png', + }) + + return createClipboardEvent([createFileItem(image)]) + } + + beforeEach(() => { + vi.mocked(getUploader, { partial: true }).mockReturnValue({ + batchUpload, + }) + }) + + afterEach(() => { + vi.resetAllMocks() + document.body.replaceChildren() + }) + + it('ignores prevented events, editable targets and visible dialogs', async () => { + const context = createContext() + + // An already prevented event + const preventedEvent = createImageEvent() + preventedEvent.preventDefault() + + expect(shouldIgnoreClipboardPaste(preventedEvent)).toBe(true) + await uploadClipboardImages(preventedEvent, context) + + // An editable element has focus + const input = document.createElement('input') + document.body.appendChild(input) + input.focus() + + const editableEvent = createImageEvent() + + expect(shouldIgnoreClipboardPaste(editableEvent)).toBe(true) + await uploadClipboardImages(editableEvent, context) + + expect(editableEvent.defaultPrevented).toBe(false) + + input.remove() + + // A visible modal dialog + const modal = document.createElement('div') + modal.classList.add('modal-mask') + + const checkVisibility = vi.fn().mockReturnValue(true) + + Object.defineProperty(modal, 'checkVisibility', { + value: checkVisibility, + }) + + document.body.appendChild(modal) + + const modalEvent = createImageEvent() + + expect(shouldIgnoreClipboardPaste(modalEvent)).toBe(true) + await uploadClipboardImages(modalEvent, context) + + expect(modalEvent.defaultPrevented).toBe(false) + expect(getUploader).not.toHaveBeenCalled() + expect(batchUpload).not.toHaveBeenCalled() + expect(context.getContents).not.toHaveBeenCalled() + expect(showError).not.toHaveBeenCalled() + + // A hidden modal must not prevent clipboard uploads + checkVisibility.mockReturnValue(false) + batchUpload.mockResolvedValue(undefined) + + const hiddenModalEvent = createImageEvent() + + expect(shouldIgnoreClipboardPaste(hiddenModalEvent)).toBe(false) + await uploadClipboardImages(hiddenModalEvent, context) + + expect(hiddenModalEvent.defaultPrevented).toBe(true) + expect(batchUpload).toHaveBeenCalledTimes(1) + expect(showError).not.toHaveBeenCalled() + }) + + it('uploads images to the correct destination and prevents native paste', async () => { + const context = createContext() + + const image = new File(['image-content'], 'photo.png', { + type: 'image/png', + }) + + const event = createClipboardEvent([createFileItem(image)]) + + let mapping: Record | false | undefined + + batchUpload.mockImplementation(async (_path, _files, options) => { + mapping = await options.callback(['photo.png'], '') + }) + + await uploadClipboardImages(event, context) + + expect(event.defaultPrevented).toBe(true) + expect(batchUpload).toHaveBeenCalledTimes(1) + + expect(batchUpload).toHaveBeenCalledWith( + '', + [image], + expect.objectContaining({ + root: context.folder.source, + callback: expect.any(Function), + }), + ) + + expect(context.getContents).toHaveBeenCalledWith('') + + expect(mapping).toEqual({ + 'photo.png': 'photo.png', + }) + + expect(openConflictPicker).not.toHaveBeenCalled() + expect(showError).not.toHaveBeenCalled() + }) + + it('resolves mixed conflicts and preserves non-conflicting files', async () => { + const context = createContext() + + const files = [ + new File(['replacement'], 'replace.png', { type: 'image/png' }), + new File(['duplicate'], 'duplicate.png', { type: 'image/png' }), + new File(['skipped'], 'skip.png', { type: 'image/png' }), + new File(['unique'], 'unique.png', { type: 'image/png' }), + ] + + const existingNodes = [ + { basename: 'replace.png' } as INode, + { basename: 'duplicate.png' } as INode, + { basename: 'skip.png' } as INode, + { basename: 'duplicate (1).png' } as INode, + { basename: 'unrelated.txt' } as INode, + ] + + context.getContents.mockResolvedValue(existingNodes) + + vi.mocked(openConflictPicker).mockResolvedValue({ + selected: [files[0]], + renamed: [files[1]], + skipped: [files[2]], + }) + + let mapping: Record | false | undefined + + batchUpload.mockImplementation(async (_path, _files, options) => { + mapping = await options.callback( + files.map((file) => file.name), + '', + ) + }) + + await uploadClipboardImages( + createClipboardEvent(files.map(createFileItem)), + context, + ) + + expect(openConflictPicker).toHaveBeenCalledTimes(1) + + expect(openConflictPicker).toHaveBeenCalledWith( + '', + files.slice(0, 3), + existingNodes.slice(0, 3), + { recursive: false }, + ) + + expect(mapping).toEqual({ + 'replace.png': 'replace.png', + 'duplicate.png': 'duplicate (2).png', + 'unique.png': 'unique.png', + }) + + expect(showError).not.toHaveBeenCalled() + }) + + it('cancels the entire batch when conflict resolution is dismissed', async () => { + const context = createContext() + + const files = [ + new File(['duplicate'], 'photo.png', { type: 'image/png' }), + new File(['unique'], 'unique.png', { type: 'image/png' }), + ] + + context.getContents.mockResolvedValue([ + { basename: 'photo.png' } as INode, + ]) + + vi.mocked(openConflictPicker).mockResolvedValue(null) + + let mapping: Record | false | undefined + + batchUpload.mockImplementation(async (_path, _files, options) => { + mapping = await options.callback( + files.map((file) => file.name), + '', + ) + }) + + await uploadClipboardImages( + createClipboardEvent(files.map(createFileItem)), + context, + ) + + expect(openConflictPicker).toHaveBeenCalledTimes(1) + expect(mapping).toBe(false) + expect(showError).not.toHaveBeenCalled() + }) + + it('processes batches sequentially and recovers after an upload failure', async () => { + const context = createContext() + + let rejectUpload!: (error: Error) => void + + const firstUpload = new Promise((_resolve, reject) => { + rejectUpload = reject + }) + + batchUpload + .mockImplementationOnce(() => firstUpload) + .mockResolvedValueOnce(undefined) + + const first = uploadClipboardImages(createImageEvent(), context) + const second = uploadClipboardImages(createImageEvent(), context) + + await Promise.resolve() + + try { + expect(batchUpload).toHaveBeenCalledTimes(1) + } finally { + rejectUpload(new Error('Upload failed')) + await Promise.all([first, second]) + } + + expect(batchUpload).toHaveBeenCalledTimes(2) + expect(showError).toHaveBeenCalledTimes(1) + }) + + it('aborts conflict resolution when destination fetching fails', async () => { + const context = createContext() + + context.getContents.mockRejectedValue(new Error('Clipboard upload destination changed')) + + let mapping: Record | false | undefined + + batchUpload.mockImplementation(async (_path, _files, options) => { + mapping = await options.callback(['photo.png'], '') + }) + + await uploadClipboardImages(createImageEvent(), context) + + expect(context.getContents).toHaveBeenCalledWith('') + expect(mapping).toBe(false) + expect(openConflictPicker).not.toHaveBeenCalled() + expect(showError).toHaveBeenCalledTimes(1) + }) +}) diff --git a/apps/files/src/services/ClipboardUploadService.ts b/apps/files/src/services/ClipboardUploadService.ts new file mode 100644 index 0000000000000..f8121dd07f4b0 --- /dev/null +++ b/apps/files/src/services/ClipboardUploadService.ts @@ -0,0 +1,268 @@ +/*! + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { IFolder, INode } from '@nextcloud/files' + +import { openConflictPicker, showError } from '@nextcloud/dialogs' +import { getUniqueName } from '@nextcloud/files' +import { getUploader } from '@nextcloud/files/upload' +import { translate as t } from '@nextcloud/l10n' +import { basename } from '@nextcloud/paths' +import { getConflicts } from '../utils/conflicts.ts' +import { getFilenameValidity } from '../utils/filenameValidity.ts' +import { logger } from '../utils/logger.ts' + +interface ClipboardUploadContext { + folder: IFolder + getContents: (path: string) => Promise +} + +// Process clipboard batches sequentially to avoid filename conflicts +// between concurrent paste operations. +let pendingClipboardUpload = Promise.resolve() + +/** + * Extract image files from a clipboard event. + * + * @param event - The clipboard paste event + */ +export function getClipboardImages(event: ClipboardEvent): File[] { + const clipboardData = event.clipboardData + + if (!clipboardData) { + return [] + } + + const images = Array.from(clipboardData.items) + .filter((item) => item.kind === 'file') + .map((item) => item.getAsFile()) + .filter((file): file is File => file !== null) + .filter((file) => file.type.startsWith('image/')) + + if (images.length > 0) { + return images + } + + return Array.from(clipboardData.files) + .filter((file) => file.type.startsWith('image/')) +} + +/** + * Get a filename extension for an image MIME type. + * + * @param mimeType - The image MIME type + */ +function getImageExtension(mimeType: string): string { + const extensions: Record = { + 'image/png': 'png', + 'image/jpeg': 'jpg', + 'image/gif': 'gif', + 'image/webp': 'webp', + 'image/svg+xml': 'svg', + 'image/bmp': 'bmp', + 'image/tiff': 'tiff', + 'image/avif': 'avif', + 'image/heic': 'heic', + 'image/heif': 'heif', + 'image/x-icon': 'ico', + 'image/vnd.microsoft.icon': 'ico', + } + + return extensions[mimeType] ?? '' +} + +/** + * Prepare clipboard images with valid and unique filenames. + * + * @param files - The clipboard image files + */ +export function prepareClipboardImages(files: File[]): File[] { + const usedNames: string[] = [] + const originalNames = files.map((file) => file.name) + + return files.map((file) => { + let name = file.name + + if (!name || getFilenameValidity(name, false, false) !== '') { + const extension = getImageExtension(file.type) + const fallbackName = t('files', 'Clipboard') + + name = extension + ? `${fallbackName}.${extension}` + : fallbackName + } + + if (usedNames.includes(name)) { + name = getUniqueName(name, [...usedNames, ...originalNames]) + } + + const validationError = getFilenameValidity(name, false, false) + + if (validationError !== '') { + throw new Error(validationError) + } + + usedNames.push(name) + + if (name === file.name) { + return file + } + + return new File([file], name, { + type: file.type, + lastModified: file.lastModified, + }) + }) +} + +/** + * Check whether a paste target is editable. + * + * @param target - The event target + */ +function isEditableTarget(target: EventTarget | null): boolean { + return target instanceof HTMLElement + && ( + target instanceof HTMLInputElement + || target instanceof HTMLTextAreaElement + || target instanceof HTMLSelectElement + || target.isContentEditable + ) +} + +/** + * Check whether a visible modal dialog is open. + */ +function hasOpenDialog(): boolean { + return Array.from(document.getElementsByClassName('modal-mask')) + .some((element) => element.checkVisibility()) +} + +/** + * Check whether clipboard upload should ignore this paste event. + * + * Preserves native paste behaviour for already-handled events, editable + * fields and visible modal dialogs. + * + * @param event - The clipboard paste event + */ +export function shouldIgnoreClipboardPaste(event: ClipboardEvent): boolean { + return event.defaultPrevented + || isEditableTarget(event.target) + || isEditableTarget(document.activeElement) + || hasOpenDialog() +} + +/** + * Resolve filename conflicts using the existing conflict picker. + * + * @param names - Incoming filenames + * @param path - Destination path + * @param files - Prepared clipboard image files + * @param getContents - Function to retrieve destination contents + */ +async function handleConflicts( + names: string[], + path: string, + files: File[], + getContents: ClipboardUploadContext['getContents'], +): Promise | false> { + try { + const contents = await getContents(path) + const incomingFiles = files.filter((file) => names.includes(file.name)) + const conflicts = getConflicts(incomingFiles, contents) + + const mapping = Object.fromEntries(names.map((name) => [name, name])) + + if (conflicts.length === 0) { + return mapping + } + + const existingNodes = contents.filter((node) => conflicts.some((file) => file.name === node.basename)) + + const result = await openConflictPicker( + basename(path), + conflicts, + existingNodes, + { recursive: false }, + ) + + if (!result) { + return false + } + + const usedNames = [ + ...contents.map((node) => node.basename), + ...names, + ] + + for (const file of result.skipped) { + delete mapping[file.name] + } + + for (const file of result.renamed) { + const name = getUniqueName(file.name, usedNames) + + mapping[file.name] = name + usedNames.push(name) + } + + return mapping + } catch (error) { + logger.error('Error during clipboard upload conflict resolution', { + error, + }) + + showError(t('files', 'Some files could not be uploaded')) + + return false + } +} + +/** + * Upload clipboard images into the provided destination folder. + * + * @param event - The clipboard paste event + * @param context - The upload destination and contents provider + */ +export async function uploadClipboardImages( + event: ClipboardEvent, + context: ClipboardUploadContext, +): Promise { + if (shouldIgnoreClipboardPaste(event)) { + return + } + + const images = getClipboardImages(event) + + if (images.length === 0) { + return + } + + event.preventDefault() + + const root = context.folder.source + + const upload = pendingClipboardUpload.then(async () => { + try { + const files = prepareClipboardImages(images) + + await getUploader().batchUpload('', files, { + root, + callback: (names, path) => handleConflicts(names, path, files, context.getContents), + }) + } catch (error) { + logger.error('Error while uploading clipboard images', { + error, + }) + + showError(t('files', 'Some files could not be uploaded')) + } + }) + + pendingClipboardUpload = upload + + await upload +} diff --git a/apps/files/src/views/FilesList.vue b/apps/files/src/views/FilesList.vue index fffbba3e3865b..e65bf4c062b60 100644 --- a/apps/files/src/views/FilesList.vue +++ b/apps/files/src/views/FilesList.vue @@ -193,6 +193,7 @@ import { useEnabledFileListActions } from '../composables/useFileListActions.ts' import { useFileListWidth } from '../composables/useFileListWidth.ts' import { useNewFileMenuActions } from '../composables/useNewFileMenuActions.ts' import { useRouteParameters } from '../composables/useRouteParameters.ts' +import { getClipboardImages, shouldIgnoreClipboardPaste, uploadClipboardImages } from '../services/ClipboardUploadService.ts' import { useActiveStore } from '../store/active.ts' import { useFilesStore } from '../store/files.ts' import { useFiltersStore } from '../store/filters.ts' @@ -438,6 +439,15 @@ export default defineComponent({ return this.currentFolder?.attributes?.['quota-available-bytes'] === 0 }, + cantUploadLabel() { + if (this.isQuotaExceeded) { + return t('files', 'You have used your space quota and cannot upload files anymore.') + } else if (!this.canUpload) { + return t('files', 'You do not have permission to upload or create files here.') + } + return null + }, + showCustomEmptyView() { return !this.loading && this.isEmptyDir && this.currentView?.emptyView !== undefined }, @@ -505,6 +515,7 @@ export default defineComponent({ }, async mounted() { + document.addEventListener('paste', this.onClipboardPaste) subscribe('files:node:updated', this.onUpdatedNode) // reload on settings change @@ -533,6 +544,7 @@ export default defineComponent({ unsubscribe('files:config:updated', this.fetchContent) unsubscribe('files:filters:changed', this.filterDirContent) unsubscribe('files:search:updated', this.onUpdateSearch) + document.removeEventListener('paste', this.onClipboardPaste) }, methods: { @@ -700,6 +712,71 @@ export default defineComponent({ this.loadingAction = null } }, + + /** + * Upload pasted clipboard images into the current folder. + * + * @param event - The clipboard paste event + */ + async onClipboardPaste(event: ClipboardEvent) { + if (!this.currentFolder + || !this.currentView + || this.loading + || this.navigating + || this.error + || shouldIgnoreClipboardPaste(event)) { + return + } + + if (getClipboardImages(event).length === 0) { + return + } + + const expectedSource = this.directory === '/' + ? this.filesStore.getRoot(this.currentView.id)?.source + : this.pathsStore.getPath(this.currentView.id, this.directory) + + if (!expectedSource || expectedSource !== this.currentFolder.source) { + return + } + + if (this.cantUploadLabel) { + event.preventDefault() + showError(this.cantUploadLabel) + return + } + + if (this.isPublic + && (this.currentFolder.permissions & Permission.READ) === 0) { + event.preventDefault() + showError(t('files', 'Some files could not be uploaded')) + return + } + + // Capture the destination and view before uploading. + const folder = this.currentFolder + const source = folder.source + const view = this.currentView + const directory = this.directory + + await uploadClipboardImages(event, { + folder, + getContents: async (path) => { + const controller = new AbortController() + + const result = await view.getContents( + join(directory, path), + { signal: controller.signal }, + ) + + if (!path && result.folder.source !== source) { + throw new Error('Clipboard upload destination changed') + } + + return result.contents + }, + }) + }, }, }) diff --git a/tests/playwright/e2e/files/clipboard-upload.spec.ts b/tests/playwright/e2e/files/clipboard-upload.spec.ts new file mode 100644 index 0000000000000..a59857e669223 --- /dev/null +++ b/tests/playwright/e2e/files/clipboard-upload.spec.ts @@ -0,0 +1,367 @@ +/*! + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { runOcc } from '@nextcloud/e2e-test-server/docker' +import { expect, test } from '../../support/fixtures/files-page.ts' +import { test as sharingTest } from '../../support/fixtures/files-sharing-page.ts' +import { pasteImages, PNG_CONTENT } from '../../support/utils/clipboard.ts' +import { DAV_FILES_ENDPOINT, mkdir, uploadContent } from '../../support/utils/dav.ts' +import { BUNDLED_PERMISSIONS, createShare, updateShare, waitForShare } from '../../support/utils/sharing.ts' +import { getToast } from '../../support/utils/toast.ts' + +test.describe('files: Clipboard image upload', () => { + test('can paste an image into the current folder', async ({ page, filesListPage }) => { + await filesListPage.open() + await filesListPage.waitForListLoaded() + + const uploaded = page.waitForResponse((response) => response.request().method() === 'PUT' + && DAV_FILES_ENDPOINT.test(response.url()) + && response.url().endsWith('/clipboard-image.png')) + + const handled = await pasteImages( + filesListPage.getContentArea(), + ['clipboard-image.png'], + ) + + expect(handled).toBe(true) + + const response = await uploaded + + expect(response.ok()).toBe(true) + + await expect(filesListPage.getRowForFile('clipboard-image.png')).toBeVisible() + + const storedFile = await page.request.get(response.url()) + + expect(storedFile.ok()).toBe(true) + expect(await storedFile.body()).toEqual(Buffer.from(PNG_CONTENT, 'base64')) + }) + + test('can paste multiple images into a nested folder', async ({ page, user, filesListPage }) => { + await mkdir(page.request, user, '/photos') + await mkdir(page.request, user, '/photos/clipboard') + + await filesListPage.open() + await filesListPage.navigateToFolder('photos/clipboard') + await filesListPage.waitForListLoaded() + + const filenames = ['first.png', 'second.png'] + + const uploads = Promise.all(filenames.map((name) => page.waitForResponse((response) => response.request().method() === 'PUT' + && DAV_FILES_ENDPOINT.test(response.url()) + && response.url().endsWith(`/photos/clipboard/${name}`)))) + + const handled = await pasteImages( + filesListPage.getContentArea(), + filenames, + ) + + expect(handled).toBe(true) + + for (const response of await uploads) { + expect(response.ok()).toBe(true) + } + + for (const name of filenames) { + await expect(filesListPage.getRowForFile(name)).toBeVisible() + } + + await filesListPage.open() + await filesListPage.waitForListLoaded() + + for (const name of filenames) { + await expect(filesListPage.getRowForFile(name)).toHaveCount(0) + } + }) + + test('can keep both images when a filename conflict occurs', async ({ page, user, filesListPage }) => { + const content = Buffer.from(PNG_CONTENT, 'base64') + + await uploadContent( + page.request, + user, + content, + 'image/png', + '/duplicate.png', + ) + + await uploadContent( + page.request, + user, + 'unrelated content', + 'text/plain', + '/unrelated.txt', + ) + + await filesListPage.open() + await filesListPage.waitForListLoaded() + + await expect(filesListPage.getRowForFile('duplicate.png')).toBeVisible() + + const handled = await pasteImages( + filesListPage.getContentArea(), + ['duplicate.png'], + ) + + expect(handled).toBe(true) + + const dialog = page.getByRole('dialog') + + await expect(dialog).toBeVisible() + + const uploaded = page.waitForResponse((response) => response.request().method() === 'PUT' + && DAV_FILES_ENDPOINT.test(response.url()) + && decodeURIComponent(response.url()).endsWith('/duplicate (1).png')) + + await dialog.getByRole('button', { name: 'Keep both', exact: true }).click() + + expect((await uploaded).ok()).toBe(true) + + await expect(filesListPage.getRowForFile('duplicate.png')).toBeVisible() + await expect(filesListPage.getRowForFile('duplicate (1).png')).toBeVisible() + await expect(filesListPage.getRowForFile('unrelated.txt')).toBeVisible() + }) + + test('does not upload clipboard images while renaming a file', async ({ page, user, filesListPage }) => { + await uploadContent( + page.request, + user, + 'original content', + 'text/plain', + '/document.txt', + ) + + await filesListPage.open() + await filesListPage.waitForListLoaded() + + await filesListPage.triggerActionForFile('document.txt', 'rename') + + const input = filesListPage.getRenameInputForFile('document.txt') + + await expect(input).toBeVisible() + await input.focus() + await expect(input).toBeFocused() + + let putFired = false + + page.on('request', (request) => { + if (request.method() === 'PUT' && DAV_FILES_ENDPOINT.test(request.url())) { + putFired = true + } + }) + + const handled = await pasteImages(input, ['ignored.png']) + + expect(handled).toBe(false) + + await expect(input).toBeFocused() + await expect(filesListPage.getRowForFile('ignored.png')).toHaveCount(0) + + await input.fill('renamed') + await expect(input).toHaveValue('renamed') + + await input.press('Escape') + + await expect(filesListPage.getRowForFile('document.txt')).toBeVisible() + await expect(page.getByRole('dialog')).toHaveCount(0) + + expect(putFired).toBe(false) + }) + + test('uploads into the original folder when navigating away', async ({ page, user, filesListPage }) => { + await mkdir(page.request, user, '/original') + await mkdir(page.request, user, '/other') + + await filesListPage.open() + await filesListPage.navigateToFolder('original') + await filesListPage.waitForListLoaded() + + let uploadStarted = false + let releaseUpload!: () => void + + const uploadGate = new Promise((resolve) => { + releaseUpload = resolve + }) + + // Pause the actual upload request until navigation completes. + await page.route('**/navigation.png', async (route) => { + if (route.request().method() !== 'PUT') { + await route.continue() + return + } + + uploadStarted = true + await uploadGate + await route.continue() + }) + + const [response] = await Promise.all([ + page.waitForResponse((response) => response.request().method() === 'PUT' + && DAV_FILES_ENDPOINT.test(response.url()) + && response.url().endsWith('/original/navigation.png')), + (async () => { + try { + const handled = await pasteImages( + filesListPage.getContentArea(), + ['navigation.png'], + ) + + expect(handled).toBe(true) + + await expect.poll(() => uploadStarted).toBe(true) + + await filesListPage.navigateToBreadcrumb('All files') + await filesListPage.navigateToFolder('other') + await filesListPage.waitForListLoaded() + } finally { + releaseUpload() + } + })(), + ]) + + expect(response.ok()).toBe(true) + + await expect(filesListPage.getRowForFile('navigation.png')).toHaveCount(0) + + await filesListPage.navigateToBreadcrumb('All files') + await filesListPage.navigateToFolder('original') + await filesListPage.waitForListLoaded() + + await expect(filesListPage.getRowForFile('navigation.png')).toBeVisible() + }) + + test('does not upload clipboard images when the storage quota is exhausted', async ({ page, user, filesListPage }) => { + // Ensure the user has already consumed more than one byte. + await uploadContent( + page.request, + user, + Buffer.from(PNG_CONTENT, 'base64'), + 'image/png', + '/existing.png', + ) + + await runOcc([ + 'user:setting', + user.userId, + 'files', + 'quota', + '1 B', + ]) + + await filesListPage.open() + await filesListPage.waitForListLoaded() + + await expect(filesListPage.getRowForFile('existing.png')).toBeVisible() + await expect(page.locator('[data-cy-upload-picker]')).toHaveCount(0) + + let putFired = false + + page.on('request', (request) => { + if (request.method() === 'PUT' && DAV_FILES_ENDPOINT.test(request.url())) { + putFired = true + } + }) + + const handled = await pasteImages( + filesListPage.getContentArea(), + ['quota-blocked.png'], + ) + + expect(handled).toBe(true) + + await expect(getToast(page, 'You have used your space quota and cannot upload files anymore.')).toBeVisible() + await expect(filesListPage.getRowForFile('quota-blocked.png')).toHaveCount(0) + await expect(filesListPage.getRowForFile('existing.png')).toBeVisible() + + expect(putFired).toBe(false) + }) +}) + +sharingTest.describe('files: Clipboard image upload in internal shares', () => { + sharingTest('respects writable and read-only sharing permissions', async ({ + page, + user, + owner, + ownerRequest, + filesListPage, + }) => { + const folderName = 'clipboard-shared' + + await mkdir(ownerRequest, owner, `/${folderName}`) + + const share = await createShare( + ownerRequest, + `/${folderName}`, + user.userId, + { permissions: BUNDLED_PERMISSIONS.UPLOAD_AND_UPDATE }, + ) + + await waitForShare( + page.request, + user, + '', + folderName, + (permissions) => permissions.includes('C'), + ) + + await filesListPage.open() + await filesListPage.navigateToFolder(folderName) + await filesListPage.waitForListLoaded() + + const uploaded = page.waitForResponse((response) => response.request().method() === 'PUT' + && DAV_FILES_ENDPOINT.test(response.url()) + && response.url().endsWith(`/${folderName}/shared-image.png`)) + + const writablePaste = await pasteImages( + filesListPage.getContentArea(), + ['shared-image.png'], + ) + + expect(writablePaste).toBe(true) + expect((await uploaded).ok()).toBe(true) + + await expect(filesListPage.getRowForFile('shared-image.png')).toBeVisible() + + // Revoke write permission and wait for the change to propagate. + await updateShare(ownerRequest, share.id, { + permissions: BUNDLED_PERMISSIONS.READ_ONLY, + }) + + await waitForShare( + page.request, + user, + '', + folderName, + (permissions) => !permissions.includes('C'), + ) + + await filesListPage.open() + await filesListPage.navigateToFolder(folderName) + await filesListPage.waitForListLoaded() + + await expect(page.locator('[data-cy-upload-picker]')).toHaveCount(0) + + let putFired = false + + page.on('request', (request) => { + if (request.method() === 'PUT' && DAV_FILES_ENDPOINT.test(request.url())) { + putFired = true + } + }) + + const readOnlyPaste = await pasteImages( + filesListPage.getContentArea(), + ['read-only.png'], + ) + + expect(readOnlyPaste).toBe(true) + + await expect(getToast(page, 'You do not have permission to upload or create files here.')).toBeVisible() + await expect(filesListPage.getRowForFile('read-only.png')).toHaveCount(0) + await expect(filesListPage.getRowForFile('shared-image.png')).toBeVisible() + + expect(putFired).toBe(false) + }) +}) diff --git a/tests/playwright/e2e/files_sharing/public-share/clipboard-upload.spec.ts b/tests/playwright/e2e/files_sharing/public-share/clipboard-upload.spec.ts new file mode 100644 index 0000000000000..e3f16d4eb604f --- /dev/null +++ b/tests/playwright/e2e/files_sharing/public-share/clipboard-upload.spec.ts @@ -0,0 +1,176 @@ +/* + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { expect, test } from '../../../support/fixtures/public-share-page.ts' +import { pasteImages, PNG_CONTENT } from '../../../support/utils/clipboard.ts' +import { DAV_FILES_ENDPOINT, getFileContent, mkdir, uploadContent } from '../../../support/utils/dav.ts' +import { BUNDLED_PERMISSIONS, createLinkShare } from '../../../support/utils/sharing.ts' +import { getToast } from '../../../support/utils/toast.ts' + +test.describe('files_sharing: Public share - clipboard image upload', () => { + test('can paste an image into a writable public share', async ({ + page, + user, + ownerRequest, + publicShare, + filesListPage, + }) => { + await mkdir(ownerRequest, user, '/writable') + + const share = await createLinkShare(ownerRequest, '/writable', { + permissions: BUNDLED_PERMISSIONS.UPLOAD_AND_UPDATE, + }) + + await publicShare.open(share.url) + await filesListPage.waitForList() + await filesListPage.waitForListLoaded() + + const uploaded = page.waitForResponse((response) => response.request().method() === 'PUT' + && DAV_FILES_ENDPOINT.test(response.url()) + && response.url().endsWith('/public-image.png')) + + const handled = await pasteImages( + filesListPage.getContentArea(), + ['public-image.png'], + ) + + expect(handled).toBe(true) + expect((await uploaded).ok()).toBe(true) + + await expect(filesListPage.getRowForFile('public-image.png')).toBeVisible() + + // Verify the image was stored in the owner's folder without modification. + const storedFile = await ownerRequest.get(`/remote.php/dav/files/${encodeURIComponent(user.userId)}/writable/public-image.png`) + + expect(storedFile.ok()).toBe(true) + expect(await storedFile.body()).toEqual(Buffer.from(PNG_CONTENT, 'base64')) + }) + + test('does not upload clipboard images into a read-only public share', async ({ + page, + user, + ownerRequest, + publicShare, + filesListPage, + }) => { + await mkdir(ownerRequest, user, '/read-only') + + await uploadContent( + ownerRequest, + user, + 'existing content', + 'text/plain', + '/read-only/existing.txt', + ) + + const share = await createLinkShare(ownerRequest, '/read-only', { + permissions: BUNDLED_PERMISSIONS.READ_ONLY, + }) + + await publicShare.open(share.url) + await filesListPage.waitForList() + await filesListPage.waitForListLoaded() + + await expect(filesListPage.getRowForFile('existing.txt')).toBeVisible() + await expect(page.locator('[data-cy-upload-picker]')).toHaveCount(0) + + let putFired = false + + page.on('request', (request) => { + if (request.method() === 'PUT' && DAV_FILES_ENDPOINT.test(request.url())) { + putFired = true + } + }) + + const handled = await pasteImages( + filesListPage.getContentArea(), + ['read-only.png'], + ) + + expect(handled).toBe(true) + + await expect(getToast(page, 'You do not have permission to upload or create files here.')).toBeVisible() + await expect(filesListPage.getRowForFile('read-only.png')).toHaveCount(0) + await expect(filesListPage.getRowForFile('existing.txt')).toBeVisible() + + const storedFile = await ownerRequest.get(`/remote.php/dav/files/${encodeURIComponent(user.userId)}/read-only/read-only.png`) + + expect(storedFile.status()).toBe(404) + expect(putFired).toBe(false) + }) + + test('rejects clipboard images in a file-drop share while preserving standard uploads', async ({ + page, + user, + ownerRequest, + publicShare, + filesListPage, + }) => { + await mkdir(ownerRequest, user, '/file-drop') + + await uploadContent( + ownerRequest, + user, + 'private content', + 'text/plain', + '/file-drop/private.txt', + ) + + const share = await createLinkShare(ownerRequest, '/file-drop', { + permissions: BUNDLED_PERMISSIONS.FILE_DROP, + }) + + await publicShare.open(share.url) + + await expect(publicShare.fileDropDescription('file-drop')).toBeVisible() + await expect(filesListPage.getRowForFile('private.txt')).toHaveCount(0) + + let clipboardPutFired = false + + page.on('request', (request) => { + if (request.method() === 'PUT' + && DAV_FILES_ENDPOINT.test(request.url()) + && request.url().endsWith('/file-drop-image.png')) { + clipboardPutFired = true + } + }) + + const handled = await pasteImages( + filesListPage.getContentArea(), + ['file-drop-image.png'], + ) + + expect(handled).toBe(true) + + await expect(getToast(page, 'Some files could not be uploaded')).toBeVisible() + await expect(publicShare.fileDropDescription('file-drop')).toBeVisible() + + // Standard File Drop uploads must remain functional after an ignored paste. + await page.getByRole('button', { name: 'Upload', exact: true }).click() + + await publicShare.uploadFiles('Upload files', [ + { + name: 'standard-upload.txt', + mimeType: 'text/plain', + buffer: Buffer.from('standard upload content'), + }, + ]) + + await expect.poll(() => getFileContent( + ownerRequest, + user, + '/file-drop/standard-upload.txt', + ).catch(() => '')).toBe('standard upload content') + + // Uploaded files must remain hidden from the guest. + await expect(filesListPage.getRowForFile('standard-upload.txt')).toHaveCount(0) + + // Verify the clipboard image was never stored in the owner's folder. + const storedFile = await ownerRequest.get(`/remote.php/dav/files/${encodeURIComponent(user.userId)}/file-drop/file-drop-image.png`) + + expect(storedFile.status()).toBe(404) + expect(clipboardPutFired).toBe(false) + }) +}) diff --git a/tests/playwright/support/utils/clipboard.ts b/tests/playwright/support/utils/clipboard.ts new file mode 100644 index 0000000000000..9296741ac1995 --- /dev/null +++ b/tests/playwright/support/utils/clipboard.ts @@ -0,0 +1,38 @@ +/*! + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { Locator } from '@playwright/test' + +// A valid 1x1 pixel PNG image. +export const PNG_CONTENT = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC' + +/** + * Simulate pasting image files from the clipboard. + * + * @param target - The element receiving the paste event + * @param filenames - The image filenames + */ +export async function pasteImages(target: Locator, filenames: string[]): Promise { + return target.evaluate((element, { filenames, content }) => { + const dataTransfer = new DataTransfer() + const bytes = Uint8Array.from(atob(content), (character) => character.charCodeAt(0)) + + for (const name of filenames) { + dataTransfer.items.add(new File([bytes], name, { + type: 'image/png', + })) + } + + const event = new ClipboardEvent('paste', { + bubbles: true, + cancelable: true, + clipboardData: dataTransfer, + }) + + element.dispatchEvent(event) + + return event.defaultPrevented + }, { filenames, content: PNG_CONTENT }) +}