From 8c8d1ffb6296d1a648a566a8c4f420c824aaa697 Mon Sep 17 00:00:00 2001 From: alperozturk96 Date: Thu, 19 Nov 2026 11:23:43 +0100 Subject: [PATCH 1/6] introduce UploadLocalFileTransfer for local file transfers in UploadFileOperation Signed-off-by: alperozturk96 --- .../operations/UploadFileOperation.java | 167 ++---------------- .../upload/UploadLocalFileTransfer.kt | 154 ++++++++++++++++ 2 files changed, 168 insertions(+), 153 deletions(-) create mode 100644 app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt diff --git a/app/src/main/java/com/owncloud/android/operations/UploadFileOperation.java b/app/src/main/java/com/owncloud/android/operations/UploadFileOperation.java index 4270b3e4bdb2..030df86b627e 100644 --- a/app/src/main/java/com/owncloud/android/operations/UploadFileOperation.java +++ b/app/src/main/java/com/owncloud/android/operations/UploadFileOperation.java @@ -13,7 +13,6 @@ import android.annotation.SuppressLint; import android.content.Context; -import android.net.Uri; import android.text.TextUtils; import android.text.format.Formatter; @@ -67,24 +66,20 @@ import com.owncloud.android.operations.upload.UploadFileException; import com.owncloud.android.operations.upload.UploadFileOperationExtensionsKt; import com.owncloud.android.operations.upload.UploadFileResolver; +import com.owncloud.android.operations.upload.UploadLocalFileTransfer; import com.owncloud.android.utils.EncryptionUtils; import com.owncloud.android.utils.EncryptionUtilsV2; import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.FileUtil; import com.owncloud.android.utils.MimeTypeUtil; -import com.owncloud.android.utils.UriUtils; import com.owncloud.android.utils.theme.CapabilityUtils; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.RequestEntity; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; @@ -176,6 +171,7 @@ public class UploadFileOperation extends SyncOperation { private OCFile duplicatedEncryptedFile; private AtomicBoolean missingPermissionThrown = new AtomicBoolean(false); private final UploadFileResolver uploadFileResolver; + private final UploadLocalFileTransfer localFileTransfer; public static OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType) { return UploadFileResolver.obtainNewOCFileToUpload(remotePath, localPath, mimeType); @@ -263,6 +259,11 @@ public UploadFileOperation(UploadsStorageManager uploadsStorageManager, mFolderUnlockToken = upload.getFolderUnlockToken(); mDisableRetries = disableRetries; uploadFileResolver = new UploadFileResolver(this); + localFileTransfer = new UploadLocalFileTransfer(context, + user.getAccountName(), + mOriginalStoragePath, + localBehaviour, + mCancellationRequested); } public boolean isWifiRequired() { @@ -574,7 +575,7 @@ private RemoteOperationResult encryptedUpload(OwnCloudClient client, OCFile pare String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile); e2eFiles.setExpectedFile(new File(expectedPath)); - result = copyFile(e2eFiles.getOriginalFile(), expectedPath); + result = localFileTransfer.copyToTemporalFileIfNeeded(mFile, e2eFiles.getOriginalFile(), expectedPath); if (!result.isSuccess()) { return result; } @@ -738,7 +739,7 @@ private Triple initFileChannel(Rem } Files.deleteIfExists(Paths.get(temporalPath)); - result = copy(e2eFiles.getOriginalFile(), e2eFiles.getTemporalFile()); + result = localFileTransfer.copy(e2eFiles.getOriginalFile(), e2eFiles.getTemporalFile()); if (result.isSuccess()) { if (e2eFiles.getTemporalFile().length() == e2eFiles.getOriginalFile().length()) { @@ -1051,7 +1052,7 @@ private RemoteOperationResult normalUpload(OwnCloudClient client) { String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile); expectedFile = new File(expectedPath); - result = copyFile(originalFile, expectedPath); + result = localFileTransfer.copyToTemporalFileIfNeeded(mFile, originalFile, expectedPath); if (!result.isSuccess()) { Log_OC.e(TAG, "file copying failed"); return result; @@ -1072,7 +1073,7 @@ private RemoteOperationResult normalUpload(OwnCloudClient client) { temporalFile = new File(temporalPath); Files.deleteIfExists(Paths.get(temporalPath)); - result = copy(originalFile, temporalFile); + result = localFileTransfer.copy(originalFile, temporalFile); if (!result.isSuccess()) return result; @@ -1227,24 +1228,6 @@ private void logResult(RemoteOperationResult result, String sourcePath, Strin } } - private RemoteOperationResult copyFile(File originalFile, String expectedPath) throws OperationCancelledException, - IOException { - if (mLocalBehaviour == FileUploadWorker.LOCAL_BEHAVIOUR_COPY && !mOriginalStoragePath.equals(expectedPath)) { - String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) + - mFile.getRemotePath(); - mFile.setStoragePath(temporalPath); - File temporalFile = new File(temporalPath); - - return copy(originalFile, temporalFile); - } - - if (mCancellationRequested.get()) { - throw new OperationCancelledException(); - } - - return new RemoteOperationResult<>(ResultCode.OK); - } - @CheckResult private RemoteOperationResult checkNameCollision(OCFile parentFile, OwnCloudClient client, @@ -1354,7 +1337,7 @@ private void handleLocalBehaviour(File temporalFile, Log_OC.d(TAG, "COPY local behaviour will be handled"); if (temporalFile != null) { try { - move(temporalFile, expectedFile); + localFileTransfer.move(temporalFile, expectedFile); } catch (IOException e) { Log_OC.e(TAG, e.getMessage()); @@ -1363,7 +1346,7 @@ private void handleLocalBehaviour(File temporalFile, } } else if (originalFile != null) { try { - copy(originalFile, expectedFile); + localFileTransfer.copy(originalFile, expectedFile); } catch (IOException e) { Log_OC.e(TAG, e.getMessage()); } @@ -1381,7 +1364,7 @@ private void handleLocalBehaviour(File temporalFile, File newFile = new File(expectedPath); try { - move(originalFile, newFile); + localFileTransfer.move(originalFile, newFile); } catch (IOException e) { Log_OC.e(TAG, "Error moving file, keeping original: " + originalFile.getAbsolutePath(), e); mFile.setStoragePath(""); @@ -1549,128 +1532,6 @@ public boolean isUploadInProgress() { } - /** - * TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult}, - * TODO use Exceptions instead - * - * @param sourceFile Source file to copy. - * @param targetFile Target location to copy the file. - * @return {@link RemoteOperationResult} - * @throws IOException exception if file cannot be accessed - */ - private RemoteOperationResult copy(File sourceFile, File targetFile) throws IOException { - Log_OC.d(TAG, "Copying local file"); - - if (FileStorageUtils.getUsableSpace() < sourceFile.length()) { - return new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL); // error when the file should be copied - } else { - Log_OC.d(TAG, "Creating temporal folder"); - File temporalParent = targetFile.getParentFile(); - - if (!temporalParent.mkdirs() && !temporalParent.isDirectory()) { - return new RemoteOperationResult(ResultCode.CANNOT_CREATE_FILE); - } - - Log_OC.d(TAG, "Creating temporal file"); - if (!targetFile.createNewFile() && !targetFile.isFile()) { - return new RemoteOperationResult(ResultCode.CANNOT_CREATE_FILE); - } - - Log_OC.d(TAG, "Copying file contents"); - InputStream in = null; - OutputStream out = null; - - try { - if (!mOriginalStoragePath.equals(targetFile.getAbsolutePath())) { - // In case document provider schema as 'content://' - if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) { - Uri uri = Uri.parse(mOriginalStoragePath); - in = mContext.getContentResolver().openInputStream(uri); - } else { - in = new FileInputStream(sourceFile); - } - out = new FileOutputStream(targetFile); - int nRead; - byte[] buf = new byte[4096]; - while (!mCancellationRequested.get() && - (nRead = in.read(buf)) > -1) { - out.write(buf, 0, nRead); - } - out.flush(); - - } // else: weird but possible situation, nothing to copy - - if (mCancellationRequested.get()) { - return new RemoteOperationResult(new OperationCancelledException()); - } - } catch (Exception e) { - return new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED); - } finally { - try { - if (in != null) { - in.close(); - } - } catch (Exception e) { - Log_OC.d(TAG, "Weird exception while closing input stream for " + - mOriginalStoragePath + " (ignoring)", e); - } - try { - if (out != null) { - out.close(); - } - } catch (Exception e) { - Log_OC.d(TAG, "Weird exception while closing output stream for " + - targetFile.getAbsolutePath() + " (ignoring)", e); - } - } - } - return new RemoteOperationResult(ResultCode.OK); - } - - - /** - * TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult}, - * TODO use Exceptions instead - * TODO refactor both this and 'copy' in a single method - * - * @param sourceFile Source file to move. - * @param targetFile Target location to move the file. - * @throws IOException exception if file cannot be read/wrote - */ - private void move(File sourceFile, File targetFile) throws IOException { - if (targetFile.equals(sourceFile)) { - return; - } - - File expectedFolder = targetFile.getParentFile(); - Files.createDirectories(expectedFolder.toPath()); - - if (!expectedFolder.isDirectory()) { - throw new IOException("Target folder is not a directory: " + expectedFolder.getAbsolutePath()); - } - - if (sourceFile.renameTo(targetFile)) { - return; - } - - Files.createFile(targetFile.toPath()); - try ( - FileChannel inChannel = new FileInputStream(sourceFile).getChannel(); - FileChannel outChannel = new FileOutputStream(targetFile).getChannel() - ) { - inChannel.transferTo(0, inChannel.size(), outChannel); - } catch (IOException e) { - Files.deleteIfExists(targetFile.toPath()); - throw e; - } - - try { - Files.delete(sourceFile.toPath()); - } catch (IOException e) { - Log_OC.w(TAG, "Moved file but could not delete source: " + sourceFile.getAbsolutePath()); - } - } - /** * Saves a OC File after a successful upload. *

diff --git a/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt b/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt new file mode 100644 index 000000000000..7627a1258c9d --- /dev/null +++ b/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt @@ -0,0 +1,154 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.operations.upload + +import android.content.Context +import androidx.core.net.toUri +import com.nextcloud.client.jobs.upload.FileUploadWorker +import com.owncloud.android.datamodel.OCFile +import com.owncloud.android.lib.common.operations.OperationCancelledException +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode +import com.owncloud.android.lib.common.utils.Log_OC +import com.owncloud.android.utils.FileStorageUtils +import com.owncloud.android.utils.UriUtils +import java.io.File +import java.io.FileInputStream +import java.io.FileNotFoundException +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import java.util.concurrent.atomic.AtomicBoolean + +class UploadLocalFileTransfer( + private val context: Context, + private val accountName: String, + private val originalStoragePath: String, + private val localBehaviour: Int, + private val cancellationRequested: AtomicBoolean +) { + companion object { + private const val TAG = "UploadLocalFileTransfer" + private const val COPY_BUFFER_SIZE_BYTES = 64 * 1024 + } + + @Throws(OperationCancelledException::class, IOException::class) + fun copyToTemporalFileIfNeeded(file: OCFile, originalFile: File, expectedPath: String): RemoteOperationResult<*> { + if (localBehaviour == FileUploadWorker.LOCAL_BEHAVIOUR_COPY && originalStoragePath != expectedPath) { + val temporalPath = FileStorageUtils.getInternalTemporalPath(accountName, context) + file.remotePath + file.storagePath = temporalPath + + return copy(originalFile, File(temporalPath)) + } + + if (cancellationRequested.get()) { + throw OperationCancelledException() + } + + return RemoteOperationResult(ResultCode.OK) + } + + @Throws(IOException::class) + fun copy(sourceFile: File, targetFile: File): RemoteOperationResult<*> { + Log_OC.d(TAG, "Copying local file") + + if (FileStorageUtils.usableSpace < sourceFile.length()) { + return RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL) + } + + if (!createTargetFile(targetFile)) { + return RemoteOperationResult(ResultCode.CANNOT_CREATE_FILE) + } + + try { + if (originalStoragePath != targetFile.absolutePath) { + copyContents(sourceFile, targetFile) + } + } catch (e: Exception) { + Log_OC.e(TAG, "Could not copy $originalStoragePath to ${targetFile.absolutePath}", e) + return RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED) + } + + if (cancellationRequested.get()) { + return RemoteOperationResult(OperationCancelledException()) + } + + return RemoteOperationResult(ResultCode.OK) + } + + @Throws(IOException::class) + fun move(sourceFile: File, targetFile: File) { + if (targetFile == sourceFile) { + return + } + + val targetFolder = targetFile.parentFile + ?: throw IOException("Target file has no parent folder: ${targetFile.absolutePath}") + Files.createDirectories(targetFolder.toPath()) + + if (sourceFile.renameTo(targetFile)) { + return + } + + copyAndDeleteSource(sourceFile.toPath(), targetFile.toPath()) + } + + @Throws(IOException::class) + private fun createTargetFile(targetFile: File): Boolean { + val parent = targetFile.parentFile ?: return false + if (!parent.mkdirs() && !parent.isDirectory) { + return false + } + + return targetFile.createNewFile() || targetFile.isFile + } + + private fun copyContents(sourceFile: File, targetFile: File) { + openSourceStream(sourceFile).use { input -> + FileOutputStream(targetFile).use { output -> + val buffer = ByteArray(COPY_BUFFER_SIZE_BYTES) + while (!cancellationRequested.get()) { + val bytesRead = input.read(buffer) + if (bytesRead < 0) { + break + } + + output.write(buffer, 0, bytesRead) + } + } + } + } + + private fun openSourceStream(sourceFile: File): InputStream { + if (!originalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) { + return FileInputStream(sourceFile) + } + + return context.contentResolver.openInputStream(originalStoragePath.toUri()) + ?: throw FileNotFoundException("Cannot open input stream for $originalStoragePath") + } + + @Throws(IOException::class) + private fun copyAndDeleteSource(source: Path, target: Path) { + Files.createFile(target) + try { + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING) + } catch (e: IOException) { + Files.deleteIfExists(target) + throw e + } + + try { + Files.delete(source) + } catch (e: IOException) { + Log_OC.w(TAG, "Moved file but could not delete source: $source, ${e.message}") + } + } +} From b848b93060d62be9f40810684ec7454e8a6dfc0c Mon Sep 17 00:00:00 2001 From: alperozturk96 Date: Thu, 19 Nov 2026 11:35:51 +0100 Subject: [PATCH 2/6] add tests Signed-off-by: alperozturk96 --- .../upload/UploadLocalFileTransfer.kt | 23 +- .../upload/UploadLocalFileTransferTest.kt | 246 ++++++++++++++++++ 2 files changed, 259 insertions(+), 10 deletions(-) create mode 100644 app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt diff --git a/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt b/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt index 7627a1258c9d..fbbbf68382fa 100644 --- a/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt +++ b/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt @@ -22,6 +22,7 @@ import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.io.InputStream +import java.io.OutputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption @@ -112,17 +113,19 @@ class UploadLocalFileTransfer( private fun copyContents(sourceFile: File, targetFile: File) { openSourceStream(sourceFile).use { input -> - FileOutputStream(targetFile).use { output -> - val buffer = ByteArray(COPY_BUFFER_SIZE_BYTES) - while (!cancellationRequested.get()) { - val bytesRead = input.read(buffer) - if (bytesRead < 0) { - break - } - - output.write(buffer, 0, bytesRead) - } + FileOutputStream(targetFile).use { output -> copyUntilCancelled(input, output) } + } + } + + private fun copyUntilCancelled(input: InputStream, output: OutputStream) { + val buffer = ByteArray(COPY_BUFFER_SIZE_BYTES) + while (!cancellationRequested.get()) { + val bytesRead = input.read(buffer) + if (bytesRead < 0) { + return } + + output.write(buffer, 0, bytesRead) } } diff --git a/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt b/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt new file mode 100644 index 000000000000..8738077bd4a3 --- /dev/null +++ b/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt @@ -0,0 +1,246 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.operations.upload + +import android.content.ContentResolver +import android.content.Context +import android.net.Uri +import com.nextcloud.client.jobs.upload.FileUploadWorker +import com.owncloud.android.datamodel.OCFile +import com.owncloud.android.lib.common.operations.OperationCancelledException +import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode +import com.owncloud.android.utils.FileStorageUtils +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkStatic +import io.mockk.unmockkAll +import io.mockk.verify +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean + +class UploadLocalFileTransferTest { + + @get:Rule + val temporaryFolder = TemporaryFolder() + + private val contentResolver: ContentResolver = mockk() + private val context: Context = mockk { + every { contentResolver } returns this@UploadLocalFileTransferTest.contentResolver + } + private val contentUri: Uri = mockk() + private val cancellationRequested = AtomicBoolean(false) + + private lateinit var sourceFile: File + private lateinit var temporalFolder: File + + @Before + fun setUp() { + sourceFile = temporaryFolder.newFile(SOURCE_NAME).apply { writeText(CONTENT) } + temporalFolder = temporaryFolder.newFolder(TEMPORAL_FOLDER_NAME) + + mockkStatic(FileStorageUtils::class) + every { FileStorageUtils.usableSpace } returns Long.MAX_VALUE + every { FileStorageUtils.getInternalTemporalPath(ACCOUNT_NAME, context) } returns temporalFolder.absolutePath + + mockkStatic(Uri::class) + every { Uri.parse(CONTENT_URI) } returns contentUri + } + + @After + fun tearDown() { + unmockkAll() + } + + private fun createTransfer( + originalStoragePath: String = sourceFile.absolutePath, + localBehaviour: Int = FileUploadWorker.LOCAL_BEHAVIOUR_COPY + ) = UploadLocalFileTransfer(context, ACCOUNT_NAME, originalStoragePath, localBehaviour, cancellationRequested) + + private fun targetFile(vararg segments: String) = File(temporaryFolder.root, segments.joinToString(File.separator)) + + @Test + fun copyWritesSourceContentIntoTarget() { + val target = targetFile(TARGET_NAME) + + val result = createTransfer().copy(sourceFile, target) + + assertTrue(result.isSuccess) + assertEquals(CONTENT, target.readText()) + assertTrue(sourceFile.exists()) + } + + @Test + fun copyCreatesMissingParentFolders() { + val target = targetFile(NESTED_FOLDER_NAME, NESTED_FOLDER_NAME, TARGET_NAME) + + val result = createTransfer().copy(sourceFile, target) + + assertTrue(result.isSuccess) + assertEquals(CONTENT, target.readText()) + } + + @Test + fun copyOverwritesExistingTarget() { + val target = targetFile(TARGET_NAME).apply { writeText(OTHER_CONTENT) } + + val result = createTransfer().copy(sourceFile, target) + + assertTrue(result.isSuccess) + assertEquals(CONTENT, target.readText()) + } + + @Test + fun copyReturnsLocalStorageFullWhenSpaceIsNotEnough() { + every { FileStorageUtils.usableSpace } returns 0L + val target = targetFile(TARGET_NAME) + + val result = createTransfer().copy(sourceFile, target) + + assertEquals(ResultCode.LOCAL_STORAGE_FULL, result.code) + assertFalse(target.exists()) + } + + @Test + fun copyReturnsCannotCreateFileWhenParentIsAFile() { + val parentAsFile = temporaryFolder.newFile(PARENT_AS_FILE_NAME) + + val result = createTransfer().copy(sourceFile, File(parentAsFile, TARGET_NAME)) + + assertEquals(ResultCode.CANNOT_CREATE_FILE, result.code) + } + + @Test + fun copyReturnsLocalStorageNotCopiedWhenSourceIsMissing() { + val missingSource = targetFile(MISSING_NAME) + + val result = createTransfer(originalStoragePath = missingSource.absolutePath) + .copy(missingSource, targetFile(TARGET_NAME)) + + assertEquals(ResultCode.LOCAL_STORAGE_NOT_COPIED, result.code) + } + + @Test + fun copySkipsContentWhenTargetIsOriginalFile() { + val result = createTransfer().copy(sourceFile, sourceFile) + + assertTrue(result.isSuccess) + assertEquals(CONTENT, sourceFile.readText()) + } + + @Test + fun copyReturnsCancelledResultWhenCancellationRequested() { + cancellationRequested.set(true) + val target = targetFile(TARGET_NAME) + + val result = createTransfer().copy(sourceFile, target) + + assertEquals(ResultCode.CANCELLED, result.code) + assertEquals(0L, target.length()) + } + + @Test + fun copyReadsContentUriThroughContentResolver() { + every { contentResolver.openInputStream(contentUri) } returns ByteArrayInputStream(OTHER_CONTENT.toByteArray()) + val target = targetFile(TARGET_NAME) + + val result = createTransfer(originalStoragePath = CONTENT_URI).copy(sourceFile, target) + + assertTrue(result.isSuccess) + assertEquals(OTHER_CONTENT, target.readText()) + } + + @Test + fun copyReturnsLocalStorageNotCopiedWhenContentResolverReturnsNull() { + every { contentResolver.openInputStream(contentUri) } returns null + + val result = createTransfer(originalStoragePath = CONTENT_URI).copy(sourceFile, targetFile(TARGET_NAME)) + + assertEquals(ResultCode.LOCAL_STORAGE_NOT_COPIED, result.code) + } + + @Test + fun moveRenamesSourceIntoTarget() { + val target = targetFile(NESTED_FOLDER_NAME, TARGET_NAME) + + createTransfer().move(sourceFile, target) + + assertFalse(sourceFile.exists()) + assertEquals(CONTENT, target.readText()) + } + + @Test + fun moveKeepsFileWhenSourceAndTargetAreSame() { + createTransfer().move(sourceFile, File(sourceFile.absolutePath)) + + assertEquals(CONTENT, sourceFile.readText()) + } + + @Test + fun copyToTemporalFileCopiesIntoTemporalPathForCopyBehaviour() { + val file = OCFile(REMOTE_PATH) + + val result = createTransfer().copyToTemporalFileIfNeeded(file, sourceFile, targetFile(TARGET_NAME).path) + + val expectedTemporalPath = temporalFolder.absolutePath + REMOTE_PATH + assertTrue(result.isSuccess) + assertEquals(expectedTemporalPath, file.storagePath) + assertEquals(CONTENT, File(expectedTemporalPath).readText()) + } + + @Test + fun copyToTemporalFileSkipsCopyWhenOriginalIsExpectedPath() { + val file = OCFile(REMOTE_PATH).apply { storagePath = sourceFile.absolutePath } + + val result = createTransfer().copyToTemporalFileIfNeeded(file, sourceFile, sourceFile.absolutePath) + + assertTrue(result.isSuccess) + assertEquals(sourceFile.absolutePath, file.storagePath) + verify(exactly = 0) { FileStorageUtils.getInternalTemporalPath(any(), any()) } + } + + @Test + fun copyToTemporalFileSkipsCopyForMoveBehaviour() { + val file = OCFile(REMOTE_PATH).apply { storagePath = sourceFile.absolutePath } + + val result = createTransfer(localBehaviour = FileUploadWorker.LOCAL_BEHAVIOUR_MOVE) + .copyToTemporalFileIfNeeded(file, sourceFile, targetFile(TARGET_NAME).path) + + assertTrue(result.isSuccess) + assertEquals(sourceFile.absolutePath, file.storagePath) + } + + @Test(expected = OperationCancelledException::class) + fun copyToTemporalFileThrowsWhenCancelledWithoutCopy() { + cancellationRequested.set(true) + + createTransfer(localBehaviour = FileUploadWorker.LOCAL_BEHAVIOUR_MOVE) + .copyToTemporalFileIfNeeded(OCFile(REMOTE_PATH), sourceFile, targetFile(TARGET_NAME).path) + } + + companion object { + private const val ACCOUNT_NAME = "user@nextcloud.example" + private const val CONTENT = "local file content" + private const val OTHER_CONTENT = "content from provider" + private const val SOURCE_NAME = "source.txt" + private const val TARGET_NAME = "target.txt" + private const val MISSING_NAME = "missing.txt" + private const val PARENT_AS_FILE_NAME = "parent.txt" + private const val NESTED_FOLDER_NAME = "nested" + private const val TEMPORAL_FOLDER_NAME = "tmp" + private const val REMOTE_PATH = "/Photos/target.txt" + private const val CONTENT_URI = "content://com.example.provider/document/1" + } +} From 622c0d7252cbe8f366fd9bb8179507a85f366582 Mon Sep 17 00:00:00 2001 From: alperozturk96 Date: Thu, 19 Nov 2026 11:57:01 +0100 Subject: [PATCH 3/6] use backtick names Signed-off-by: alperozturk96 --- .../upload/UploadLocalFileTransferTest.kt | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt b/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt index 8738077bd4a3..8ba27285eee2 100644 --- a/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt +++ b/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt @@ -72,7 +72,7 @@ class UploadLocalFileTransferTest { private fun targetFile(vararg segments: String) = File(temporaryFolder.root, segments.joinToString(File.separator)) @Test - fun copyWritesSourceContentIntoTarget() { + fun `copy writes source content into target`() { val target = targetFile(TARGET_NAME) val result = createTransfer().copy(sourceFile, target) @@ -83,7 +83,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyCreatesMissingParentFolders() { + fun `copy creates missing parent folders`() { val target = targetFile(NESTED_FOLDER_NAME, NESTED_FOLDER_NAME, TARGET_NAME) val result = createTransfer().copy(sourceFile, target) @@ -93,7 +93,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyOverwritesExistingTarget() { + fun `copy overwrites existing target`() { val target = targetFile(TARGET_NAME).apply { writeText(OTHER_CONTENT) } val result = createTransfer().copy(sourceFile, target) @@ -103,7 +103,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyReturnsLocalStorageFullWhenSpaceIsNotEnough() { + fun `copy returns local storage full when space is not enough`() { every { FileStorageUtils.usableSpace } returns 0L val target = targetFile(TARGET_NAME) @@ -114,7 +114,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyReturnsCannotCreateFileWhenParentIsAFile() { + fun `copy returns cannot create file when parent is a file`() { val parentAsFile = temporaryFolder.newFile(PARENT_AS_FILE_NAME) val result = createTransfer().copy(sourceFile, File(parentAsFile, TARGET_NAME)) @@ -123,7 +123,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyReturnsLocalStorageNotCopiedWhenSourceIsMissing() { + fun `copy returns local storage not copied when source is missing`() { val missingSource = targetFile(MISSING_NAME) val result = createTransfer(originalStoragePath = missingSource.absolutePath) @@ -133,7 +133,7 @@ class UploadLocalFileTransferTest { } @Test - fun copySkipsContentWhenTargetIsOriginalFile() { + fun `copy skips content when target is original file`() { val result = createTransfer().copy(sourceFile, sourceFile) assertTrue(result.isSuccess) @@ -141,7 +141,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyReturnsCancelledResultWhenCancellationRequested() { + fun `copy returns cancelled result when cancellation requested`() { cancellationRequested.set(true) val target = targetFile(TARGET_NAME) @@ -152,7 +152,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyReadsContentUriThroughContentResolver() { + fun `copy reads content uri through content resolver`() { every { contentResolver.openInputStream(contentUri) } returns ByteArrayInputStream(OTHER_CONTENT.toByteArray()) val target = targetFile(TARGET_NAME) @@ -163,7 +163,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyReturnsLocalStorageNotCopiedWhenContentResolverReturnsNull() { + fun `copy returns local storage not copied when content resolver returns null`() { every { contentResolver.openInputStream(contentUri) } returns null val result = createTransfer(originalStoragePath = CONTENT_URI).copy(sourceFile, targetFile(TARGET_NAME)) @@ -172,7 +172,7 @@ class UploadLocalFileTransferTest { } @Test - fun moveRenamesSourceIntoTarget() { + fun `move renames source into target`() { val target = targetFile(NESTED_FOLDER_NAME, TARGET_NAME) createTransfer().move(sourceFile, target) @@ -182,14 +182,14 @@ class UploadLocalFileTransferTest { } @Test - fun moveKeepsFileWhenSourceAndTargetAreSame() { + fun `move keeps file when source and target are same`() { createTransfer().move(sourceFile, File(sourceFile.absolutePath)) assertEquals(CONTENT, sourceFile.readText()) } @Test - fun copyToTemporalFileCopiesIntoTemporalPathForCopyBehaviour() { + fun `copyToTemporalFileIfNeeded copies into temporal path for copy behaviour`() { val file = OCFile(REMOTE_PATH) val result = createTransfer().copyToTemporalFileIfNeeded(file, sourceFile, targetFile(TARGET_NAME).path) @@ -201,7 +201,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyToTemporalFileSkipsCopyWhenOriginalIsExpectedPath() { + fun `copyToTemporalFileIfNeeded skips copy when original is expected path`() { val file = OCFile(REMOTE_PATH).apply { storagePath = sourceFile.absolutePath } val result = createTransfer().copyToTemporalFileIfNeeded(file, sourceFile, sourceFile.absolutePath) @@ -212,7 +212,7 @@ class UploadLocalFileTransferTest { } @Test - fun copyToTemporalFileSkipsCopyForMoveBehaviour() { + fun `copyToTemporalFileIfNeeded skips copy for move behaviour`() { val file = OCFile(REMOTE_PATH).apply { storagePath = sourceFile.absolutePath } val result = createTransfer(localBehaviour = FileUploadWorker.LOCAL_BEHAVIOUR_MOVE) @@ -223,7 +223,7 @@ class UploadLocalFileTransferTest { } @Test(expected = OperationCancelledException::class) - fun copyToTemporalFileThrowsWhenCancelledWithoutCopy() { + fun `copyToTemporalFileIfNeeded throws when cancelled without copy`() { cancellationRequested.set(true) createTransfer(localBehaviour = FileUploadWorker.LOCAL_BEHAVIOUR_MOVE) From 4299b531636be4a74795b63edaa26f3ba70aea05 Mon Sep 17 00:00:00 2001 From: alperozturk96 Date: Thu, 19 Nov 2026 11:59:38 +0100 Subject: [PATCH 4/6] use backtick names Signed-off-by: alperozturk96 --- .../android/operations/upload/UploadLocalFileTransferTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt b/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt index 8ba27285eee2..114d409413f1 100644 --- a/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt +++ b/app/src/test/java/com/owncloud/android/operations/upload/UploadLocalFileTransferTest.kt @@ -133,7 +133,7 @@ class UploadLocalFileTransferTest { } @Test - fun `copy skips content when target is original file`() { + fun `copy keeps original file intact when target is original file`() { val result = createTransfer().copy(sourceFile, sourceFile) assertTrue(result.isSuccess) From c1857245906585955383f3a795acfae108f969b4 Mon Sep 17 00:00:00 2001 From: alperozturk96 Date: Thu, 19 Nov 2026 12:07:54 +0100 Subject: [PATCH 5/6] add log for successfull path Signed-off-by: alperozturk96 --- .../upload/UploadLocalFileTransfer.kt | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt b/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt index fbbbf68382fa..897f727eaba8 100644 --- a/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt +++ b/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt @@ -45,48 +45,62 @@ class UploadLocalFileTransfer( if (localBehaviour == FileUploadWorker.LOCAL_BEHAVIOUR_COPY && originalStoragePath != expectedPath) { val temporalPath = FileStorageUtils.getInternalTemporalPath(accountName, context) + file.remotePath file.storagePath = temporalPath + Log_OC.d(TAG, "Copying original file to temporal path: $temporalPath") return copy(originalFile, File(temporalPath)) } if (cancellationRequested.get()) { + Log_OC.w(TAG, "Upload cancelled before temporal copy: $originalStoragePath") throw OperationCancelledException() } + Log_OC.d(TAG, "Temporal copy not needed, local behaviour: $localBehaviour, path: $originalStoragePath") + return RemoteOperationResult(ResultCode.OK) } @Throws(IOException::class) fun copy(sourceFile: File, targetFile: File): RemoteOperationResult<*> { - Log_OC.d(TAG, "Copying local file") + val targetPath = targetFile.absolutePath + Log_OC.d(TAG, "Copying $originalStoragePath to $targetPath") - if (FileStorageUtils.usableSpace < sourceFile.length()) { + val usableSpace = FileStorageUtils.usableSpace + if (usableSpace < sourceFile.length()) { + Log_OC.e(TAG, "Not enough space to copy ${sourceFile.length()} bytes, usable: $usableSpace bytes") return RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL) } if (!createTargetFile(targetFile)) { + Log_OC.e(TAG, "Cannot create target file: $targetPath") return RemoteOperationResult(ResultCode.CANNOT_CREATE_FILE) } try { - if (originalStoragePath != targetFile.absolutePath) { + if (originalStoragePath == targetPath) { + Log_OC.d(TAG, "Target is the original file, content copy skipped: $targetPath") + } else { copyContents(sourceFile, targetFile) } } catch (e: Exception) { - Log_OC.e(TAG, "Could not copy $originalStoragePath to ${targetFile.absolutePath}", e) + Log_OC.e(TAG, "Could not copy $originalStoragePath to $targetPath", e) return RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED) } if (cancellationRequested.get()) { + Log_OC.w(TAG, "Copy cancelled: $originalStoragePath to $targetPath") return RemoteOperationResult(OperationCancelledException()) } + Log_OC.d(TAG, "Copied $originalStoragePath to $targetPath, size: ${targetFile.length()} bytes") + return RemoteOperationResult(ResultCode.OK) } @Throws(IOException::class) fun move(sourceFile: File, targetFile: File) { if (targetFile == sourceFile) { + Log_OC.d(TAG, "Source and target are the same, nothing to move: ${sourceFile.absolutePath}") return } @@ -95,10 +109,14 @@ class UploadLocalFileTransfer( Files.createDirectories(targetFolder.toPath()) if (sourceFile.renameTo(targetFile)) { + Log_OC.d(TAG, "Moved by rename: ${sourceFile.absolutePath} to ${targetFile.absolutePath}") return } + Log_OC.d(TAG, "Rename failed, moving by copy: ${sourceFile.absolutePath} to ${targetFile.absolutePath}") copyAndDeleteSource(sourceFile.toPath(), targetFile.toPath()) + + Log_OC.d(TAG, "Moved by copy: ${sourceFile.absolutePath} to ${targetFile.absolutePath}") } @Throws(IOException::class) @@ -144,6 +162,7 @@ class UploadLocalFileTransfer( try { Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING) } catch (e: IOException) { + Log_OC.e(TAG, "Could not copy $source to $target, partial target removed", e) Files.deleteIfExists(target) throw e } From 936ee6cf8abd786f8c0ad6466da61574aef15164 Mon Sep 17 00:00:00 2001 From: alperozturk96 Date: Thu, 19 Nov 2026 12:18:04 +0100 Subject: [PATCH 6/6] copyToTemporalFileIfNeeded copies the original into the app's internal tmp/ and points mFile at that copy. Neither the normal nor the encrypted upload path knew about it, so nothing ever deleted it, fixing via this Signed-off-by: alperozturk96 --- .../operations/UploadFileOperation.java | 2 ++ .../upload/UploadLocalFileTransfer.kt | 27 ++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/owncloud/android/operations/UploadFileOperation.java b/app/src/main/java/com/owncloud/android/operations/UploadFileOperation.java index 030df86b627e..7d19c786531a 100644 --- a/app/src/main/java/com/owncloud/android/operations/UploadFileOperation.java +++ b/app/src/main/java/com/owncloud/android/operations/UploadFileOperation.java @@ -936,6 +936,7 @@ private RemoteOperationResult releaseLocksAndUnlockE2EFolder(FileLock fileLock, result = new RemoteOperationResult<>(ResultCode.UNKNOWN_ERROR); } + localFileTransfer.deleteTemporalCopyUnlessConflict(result.getCode()); logResult(result, mFile.getStoragePath(), mFile.getRemotePath()); if (token == null || token.isEmpty()) { @@ -1197,6 +1198,7 @@ private RemoteOperationResult normalUpload(OwnCloudClient client) { logResult(result, mOriginalStoragePath, mRemotePath); uploadsStorageManager.updateDatabaseUploadResult(result, this); + localFileTransfer.deleteTemporalCopyUnlessConflict(result.getCode()); } if (result.isSuccess()) { diff --git a/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt b/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt index 897f727eaba8..e97908939020 100644 --- a/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt +++ b/app/src/main/java/com/owncloud/android/operations/upload/UploadLocalFileTransfer.kt @@ -9,6 +9,7 @@ package com.owncloud.android.operations.upload import android.content.Context import androidx.core.net.toUri import com.nextcloud.client.jobs.upload.FileUploadWorker +import com.nextcloud.utils.extensions.isConflict import com.owncloud.android.datamodel.OCFile import com.owncloud.android.lib.common.operations.OperationCancelledException import com.owncloud.android.lib.common.operations.RemoteOperationResult @@ -40,6 +41,8 @@ class UploadLocalFileTransfer( private const val COPY_BUFFER_SIZE_BYTES = 64 * 1024 } + private var temporalCopy: File? = null + @Throws(OperationCancelledException::class, IOException::class) fun copyToTemporalFileIfNeeded(file: OCFile, originalFile: File, expectedPath: String): RemoteOperationResult<*> { if (localBehaviour == FileUploadWorker.LOCAL_BEHAVIOUR_COPY && originalStoragePath != expectedPath) { @@ -47,7 +50,12 @@ class UploadLocalFileTransfer( file.storagePath = temporalPath Log_OC.d(TAG, "Copying original file to temporal path: $temporalPath") - return copy(originalFile, File(temporalPath)) + val temporalFile = File(temporalPath) + if (temporalFile.absolutePath != originalStoragePath) { + temporalCopy = temporalFile + } + + return copy(originalFile, temporalFile) } if (cancellationRequested.get()) { @@ -60,6 +68,23 @@ class UploadLocalFileTransfer( return RemoteOperationResult(ResultCode.OK) } + fun deleteTemporalCopyUnlessConflict(resultCode: ResultCode) { + val file = temporalCopy ?: return + if (resultCode.isConflict()) { + Log_OC.d(TAG, "Temporal copy kept for conflict resolution: ${file.absolutePath}") + return + } + + temporalCopy = null + + try { + Files.deleteIfExists(file.toPath()) + Log_OC.d(TAG, "Deleted temporal copy: ${file.absolutePath}") + } catch (e: IOException) { + Log_OC.w(TAG, "Could not delete temporal copy: ${file.absolutePath}, ${e.message}") + } + } + @Throws(IOException::class) fun copy(sourceFile: File, targetFile: File): RemoteOperationResult<*> { val targetPath = targetFile.absolutePath