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
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ class FileMenuFilterIT : AbstractIT() {
var sut = filterFactory.newInstance(encryptedFolder, mockComponentsGetter, true, user)
var toHide = sut.getToHide(false)

assertFalse(toHide.contains(R.id.action_move_or_copy))

// encrypted folder, with content
assertTrue(toHide.contains(R.id.action_unset_encrypted))
assertTrue(toHide.contains(R.id.action_encrypted))
Expand Down Expand Up @@ -239,6 +241,12 @@ class FileMenuFilterIT : AbstractIT() {
var sut = filterFactory.newInstance(encryptedVideo, mockComponentsGetter, true, user)
var toHide = sut.getToHide(false)

assertFalse(toHide.contains(R.id.action_move_or_copy))

encryptedVideo.isLocked = true
sut = filterFactory.newInstance(encryptedVideo, mockComponentsGetter, true, user)
assertTrue(sut.getToHide(false).contains(R.id.action_move_or_copy))

// encrypted video, with content
assertTrue(toHide.contains(R.id.action_stream_media))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ class FileMenuFilter internal constructor(

if (isEditHidden(capability)) add(R.id.action_edit)
if (!selection.isSingleSelection || synchronizing || containsEncryptedOrLocked) add(R.id.action_rename_file)
if (synchronizing || containsEncryptedOrLocked) add(R.id.action_move_or_copy)
if (synchronizing || selection.containsLocked) add(R.id.action_move_or_copy)
if (synchronizing || selection.containsLocked || selection.containsEncryptedFolderContent()) {
add(R.id.action_remove_file)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class CopyFileOperation extends SyncOperation {

private final String srcPath;
private String targetParentPath;
private EncryptedFileTransfer encryptedTransfer;

/**
* Constructor
Expand All @@ -43,6 +44,10 @@ public CopyFileOperation(String srcPath, String targetParentPath, FileDataStorag
}
}

public void setEncryptedTransfer(EncryptedFileTransfer transfer) {
encryptedTransfer = transfer;
}

/**
* Performs the operation.
*
Expand All @@ -59,6 +64,11 @@ protected RemoteOperationResult run(OwnCloudClient client) {
return new RemoteOperationResult(ResultCode.FILE_NOT_FOUND);
}

OCFile parent = getStorageManager().getFileByEncryptedRemotePath(targetParentPath);
if (encryptedTransfer != null && parent != null && (file.isEncrypted() || parent.isEncrypted())) {
return encryptedTransfer.copy(file, parent, client);
}

/// 2. remote copy
String targetPath = targetParentPath + file.getFileName();
if (file.isFolder()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.operations

import android.content.Context
import com.nextcloud.client.account.User
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation
import com.owncloud.android.lib.resources.files.model.RemoteFile
import com.owncloud.android.operations.factory.UploadFileOperationFactory

@Suppress("DEPRECATION")
class EncryptedFileTransfer(
private val storageManager: FileDataStorageManager,
private val user: User,
private val context: Context,
uploadFactory: UploadFileOperationFactory,
private val keepEncryption: Boolean
) {
private val content = FileTransferContent(context, user, storageManager, uploadFactory)

fun copy(file: OCFile, parent: OCFile, client: OwnCloudClient): RemoteOperationResult<*> =
transfer(file, parent, client, false)

fun move(file: OCFile, parent: OCFile, client: OwnCloudClient): RemoteOperationResult<*> =
transfer(file, parent, client, true)

private fun transfer(
file: OCFile,
parent: OCFile,
client: OwnCloudClient,
removeSource: Boolean
): RemoteOperationResult<*> {
invalidTarget(file, parent, removeSource)?.let { return RemoteOperationResult<Any>(it) }

return try {
val source = FileTransferSource(context, user, storageManager)
if (source.hasLocalChanges(file)) return RemoteOperationResult<Any>(ResultCode.SYNC_CONFLICT)
val stat = ReadFileRemoteOperation(file.remotePath).execute(client)
if (!stat.isSuccess) return stat
val original = stat.data.firstOrNull() as? RemoteFile
?: return RemoteOperationResult<Any>(ResultCode.FILE_NOT_FOUND)
val sourceEtag = original.etag.orEmpty()
if (removeSource && sourceEtag.isEmpty()) {
return RemoteOperationResult<Any>(ResultCode.UNKNOWN_ERROR)
}

val refreshed = refresh(parent, client)
if (!refreshed.isSuccess) return refreshed
val filename = targetName(file, parent, client, !removeSource)
?: return RemoteOperationResult<Any>(ResultCode.INVALID_OVERWRITE)
val copied = copyTree(file, parent, filename, client)
if (!copied.isSuccess || !removeSource) return copied

source.remove(file, sourceEtag, client)
} catch (e: Exception) {
RemoteOperationResult<Any>(e)
}
}

private fun invalidTarget(file: OCFile, parent: OCFile, removeSource: Boolean): ResultCode? = when {
file.remotePath == OCFile.ROOT_PATH || (file.isFolder && parent.remotePath.startsWith(file.remotePath)) ->
if (removeSource) ResultCode.INVALID_MOVE_INTO_DESCENDANT else ResultCode.INVALID_COPY_INTO_DESCENDANT

removeSource && file.parentId == parent.fileId -> ResultCode.INVALID_OVERWRITE

else -> null
}

private fun targetName(file: OCFile, parent: OCFile, client: OwnCloudClient, allowRename: Boolean): String? {
val names = storageManager.getFolderContent(parent, false).asSequence().map { it.decryptedFileName }.toList()
if (names.none { it.equals(file.decryptedFileName, ignoreCase = true) }) return file.decryptedFileName
if (!allowRename || file.parentId != parent.fileId) return null
return UploadFileOperation.getNewAvailableRemotePath(
client,
file.decryptedFileName,
names,
true
)
}

private fun copyTree(
source: OCFile,
parent: OCFile,
filename: String,
client: OwnCloudClient
): RemoteOperationResult<*> {
if (source.isLocked) return RemoteOperationResult<Any>(ResultCode.LOCK_FAILED)
if (!source.isFolder) return content.copy(source, parent, filename, client)

val refreshed = refresh(source, client)
if (!refreshed.isSuccess) return refreshed
// Capture the complete server listing before creating anything in the destination.
val children = storageManager.getFolderContent(source, false).toList()
val path = parent.decryptedRemotePath + filename + OCFile.PATH_SEPARATOR
val created = CreateFolderOperation(path, user, context, storageManager).execute(client)
if (!created.isSuccess) return created
val destination = storageManager.getFileByDecryptedRemotePath(path)
?: return RemoteOperationResult<Any>(ResultCode.FILE_NOT_FOUND)
if (keepEncryption && source.isEncrypted && !parent.isEncrypted) {
val encrypted = FileTransferSource(context, user, storageManager).encrypt(destination, client)
if (!encrypted.isSuccess) return encrypted
}
for (child in children) {
val copied = copyTree(child, destination, child.decryptedFileName, client)
if (!copied.isSuccess) return copied
}
return RemoteOperationResult<Any>(ResultCode.OK)
}

private fun refresh(folder: OCFile, client: OwnCloudClient): RemoteOperationResult<*> = RefreshFolderOperation(
folder,
System.currentTimeMillis(),
false,
true,
true,
storageManager,
user,
context
).execute(client)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.operations

import android.content.Context
import com.nextcloud.client.account.User
import com.nextcloud.client.jobs.upload.FileUploadWorker
import com.nextcloud.utils.extensions.toNextcloudClient
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.e2e.v1.decrypted.DecryptedFolderMetadataFileV1
import com.owncloud.android.datamodel.e2e.v2.decrypted.DecryptedFolderMetadataFile
import com.owncloud.android.db.OCUpload
import com.owncloud.android.files.services.NameCollisionPolicy
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.lib.resources.files.DownloadFileRemoteOperation
import com.owncloud.android.operations.factory.UploadFileOperationFactory
import com.owncloud.android.utils.EncryptionUtils
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import javax.crypto.Cipher

@Suppress("DEPRECATION")
class FileTransferContent(
private val context: Context,
private val user: User,
private val storageManager: FileDataStorageManager,
private val uploadFactory: UploadFileOperationFactory
) {
fun copy(source: OCFile, parent: OCFile, filename: String, client: OwnCloudClient): RemoteOperationResult<*> {
val directoryPath = Files.createTempDirectory(context.cacheDir.toPath(), "file-transfer-")
val directory = directoryPath.toFile()
try {
val raw = directoryPath.resolve(source.remotePath.trimStart('/')).normalize()
require(raw != directoryPath && raw.startsWith(directoryPath))
val download = DownloadFileRemoteOperation(source.remotePath, directory.absolutePath, source.fileLength)
val downloaded = download.execute(client.toNextcloudClient(context))
if (!downloaded.isSuccess) return downloaded

val plaintext = directoryPath.resolve("content")
if (source.isEncrypted) {
decrypt(source, raw, plaintext, client)
} else {
Files.move(raw, plaintext)
}
if (!plaintext.toFile().setLastModified(download.modificationTimestamp)) {
Log_OC.w(TAG, "Unable to preserve transfer modification time")
}
val upload = OCUpload(plaintext.toString(), parent.remotePath + filename, user.accountName).apply {
localAction = FileUploadWorker.LOCAL_BEHAVIOUR_FORGET
nameCollisionPolicy = NameCollisionPolicy.ASK_USER
setUseWifiOnly(false)
}
val operation = uploadFactory.create(context, upload, user = user, storageManager = storageManager)
operation.setKeepE2EELockOnFailure(true)
operation.file.mimeType = source.mimeType
return operation.execute(client)
} finally {
if (!directory.deleteRecursively()) Log_OC.w(TAG, "Unable to remove temporary transfer content")
}
}

private fun decrypt(source: OCFile, raw: Path, plaintext: Path, client: OwnCloudClient) {
val parent = storageManager.getFileById(source.parentId)
?: throw IOException("Encrypted transfer source has no parent")
val metadata = EncryptionUtils.downloadFolderMetadata(parent, client, context, user)
val (key, nonce) = when (metadata) {
is DecryptedFolderMetadataFile -> metadata.metadata.files[source.encryptedFileName]?.let {
it.key to it.nonce
}

is DecryptedFolderMetadataFileV1 -> metadata.files[source.encryptedFileName]?.let {
it.encrypted.key to it.initializationVector
}

else -> null
} ?: throw IOException("Encrypted transfer source is missing from metadata")
val cipher = EncryptionUtils.getCipher(
Cipher.DECRYPT_MODE,
EncryptionUtils.decodeStringToBase64Bytes(key),
EncryptionUtils.decodeStringToBase64Bytes(nonce)
)
Files.newInputStream(raw).use { input ->
Files.newOutputStream(plaintext).use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var count = input.read(buffer)
while (count != -1) {
output.write(cipher.update(buffer, 0, count) ?: byteArrayOf())
count = input.read(buffer)
}
output.write(cipher.doFinal())
}
}
}

companion object {
private val TAG = FileTransferContent::class.java.simpleName
}
}
Loading