Search in sources :

Example 1 with ChunkedFileUploadRemoteOperation

use of com.owncloud.android.lib.resources.files.ChunkedFileUploadRemoteOperation in project android by nextcloud.

the class UploadFileOperation method encryptedUpload.

// gson cannot handle sparse arrays easily, therefore use hashmap
@SuppressLint("AndroidLintUseSparseArrays")
private RemoteOperationResult encryptedUpload(OwnCloudClient client, OCFile parentFile) {
    RemoteOperationResult result = null;
    File temporalFile = null;
    File originalFile = new File(mOriginalStoragePath);
    File expectedFile = null;
    FileLock fileLock = null;
    long size;
    boolean metadataExists = false;
    String token = null;
    ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContext().getContentResolver());
    String privateKey = arbitraryDataProvider.getValue(getAccount().name, EncryptionUtils.PRIVATE_KEY);
    String publicKey = arbitraryDataProvider.getValue(getAccount().name, EncryptionUtils.PUBLIC_KEY);
    try {
        // check conditions
        result = checkConditions(originalFile);
        if (result != null) {
            return result;
        }
        /**
         *** E2E ****
         */
        token = EncryptionUtils.lockFolder(parentFile, client);
        // immediately store it
        mUpload.setFolderUnlockToken(token);
        uploadsStorageManager.updateUpload(mUpload);
        // Update metadata
        Pair<Boolean, DecryptedFolderMetadata> metadataPair = EncryptionUtils.retrieveMetadata(parentFile, client, privateKey, publicKey);
        metadataExists = metadataPair.first;
        DecryptedFolderMetadata metadata = metadataPair.second;
        /**
         ** E2E ****
         */
        // check name collision
        RemoteOperationResult collisionResult = checkNameCollision(client, metadata, parentFile.isEncrypted());
        if (collisionResult != null) {
            result = collisionResult;
            return collisionResult;
        }
        mFile.setDecryptedRemotePath(parentFile.getDecryptedRemotePath() + originalFile.getName());
        String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile);
        expectedFile = new File(expectedPath);
        result = copyFile(originalFile, expectedPath);
        if (!result.isSuccess()) {
            return result;
        }
        // Get the last modification date of the file from the file system
        String lastModifiedTimestamp = Long.toString(originalFile.lastModified() / 1000);
        Long creationTimestamp = FileUtil.getCreationTimestamp(originalFile);
        /**
         *** E2E ****
         */
        // Key, always generate new one
        byte[] key = EncryptionUtils.generateKey();
        // IV, always generate new one
        byte[] iv = EncryptionUtils.randomBytes(EncryptionUtils.ivLength);
        EncryptionUtils.EncryptedFile encryptedFile = EncryptionUtils.encryptFile(mFile, key, iv);
        // new random file name, check if it exists in metadata
        String encryptedFileName = UUID.randomUUID().toString().replaceAll("-", "");
        while (metadata.getFiles().get(encryptedFileName) != null) {
            encryptedFileName = UUID.randomUUID().toString().replaceAll("-", "");
        }
        File encryptedTempFile = File.createTempFile("encFile", encryptedFileName);
        FileOutputStream fileOutputStream = new FileOutputStream(encryptedTempFile);
        fileOutputStream.write(encryptedFile.encryptedBytes);
        fileOutputStream.close();
        /**
         *** E2E ****
         */
        FileChannel channel = null;
        try {
            channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
            fileLock = channel.tryLock();
        } catch (FileNotFoundException e) {
            // this basically means that the file is on SD card
            // try to copy file to temporary dir if it doesn't exist
            String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) + mFile.getRemotePath();
            mFile.setStoragePath(temporalPath);
            temporalFile = new File(temporalPath);
            Files.deleteIfExists(Paths.get(temporalPath));
            result = copy(originalFile, temporalFile);
            if (result.isSuccess()) {
                if (temporalFile.length() == originalFile.length()) {
                    channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
                    fileLock = channel.tryLock();
                } else {
                    result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
                }
            }
        }
        try {
            size = channel.size();
        } catch (IOException e1) {
            size = new File(mFile.getStoragePath()).length();
        }
        for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
            if (ocUpload.getUploadId() == getOCUploadId()) {
                ocUpload.setFileSize(size);
                uploadsStorageManager.updateUpload(ocUpload);
                break;
            }
        }
        // / perform the upload
        if (size > ChunkedFileUploadRemoteOperation.CHUNK_SIZE_MOBILE) {
            boolean onWifiConnection = connectivityService.getConnectivity().isWifi();
            mUploadOperation = new ChunkedFileUploadRemoteOperation(encryptedTempFile.getAbsolutePath(), mFile.getParentRemotePath() + encryptedFileName, mFile.getMimeType(), mFile.getEtagInConflict(), lastModifiedTimestamp, onWifiConnection, token, creationTimestamp, mDisableRetries);
        } else {
            mUploadOperation = new UploadFileRemoteOperation(encryptedTempFile.getAbsolutePath(), mFile.getParentRemotePath() + encryptedFileName, mFile.getMimeType(), mFile.getEtagInConflict(), lastModifiedTimestamp, creationTimestamp, token, mDisableRetries);
        }
        for (OnDatatransferProgressListener mDataTransferListener : mDataTransferListeners) {
            mUploadOperation.addDataTransferProgressListener(mDataTransferListener);
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }
        result = mUploadOperation.execute(client);
        // location in the Nextcloud local folder
        if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
            result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
        }
        if (result.isSuccess()) {
            mFile.setDecryptedRemotePath(parentFile.getDecryptedRemotePath() + originalFile.getName());
            mFile.setRemotePath(parentFile.getRemotePath() + encryptedFileName);
            // update metadata
            DecryptedFolderMetadata.DecryptedFile decryptedFile = new DecryptedFolderMetadata.DecryptedFile();
            DecryptedFolderMetadata.Data data = new DecryptedFolderMetadata.Data();
            data.setFilename(mFile.getDecryptedFileName());
            data.setMimetype(mFile.getMimeType());
            data.setKey(EncryptionUtils.encodeBytesToBase64String(key));
            decryptedFile.setEncrypted(data);
            decryptedFile.setInitializationVector(EncryptionUtils.encodeBytesToBase64String(iv));
            decryptedFile.setAuthenticationTag(encryptedFile.authenticationTag);
            metadata.getFiles().put(encryptedFileName, decryptedFile);
            EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.encryptFolderMetadata(metadata, privateKey);
            String serializedFolderMetadata = EncryptionUtils.serializeJSON(encryptedFolderMetadata);
            // upload metadata
            EncryptionUtils.uploadMetadata(parentFile, serializedFolderMetadata, token, client, metadataExists);
            // unlock
            result = EncryptionUtils.unlockFolder(parentFile, client, token);
            if (result.isSuccess()) {
                token = null;
            }
        }
    } catch (FileNotFoundException e) {
        Log_OC.d(TAG, mFile.getStoragePath() + " not exists anymore");
        result = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
    } catch (OverlappingFileLockException e) {
        Log_OC.d(TAG, "Overlapping file lock exception");
        result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
    } finally {
        mUploadStarted.set(false);
        if (fileLock != null) {
            try {
                fileLock.release();
            } catch (IOException e) {
                Log_OC.e(TAG, "Failed to unlock file with path " + mFile.getStoragePath());
            }
        }
        if (temporalFile != null && !originalFile.equals(temporalFile)) {
            temporalFile.delete();
        }
        if (result == null) {
            result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
        }
        logResult(result, mFile.getStoragePath(), mFile.getRemotePath());
    }
    if (result.isSuccess()) {
        handleSuccessfulUpload(temporalFile, expectedFile, originalFile, client);
    } else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
        getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
    }
    // unlock must be done always
    if (token != null) {
        RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parentFile, client, token);
        if (!unlockFolderResult.isSuccess()) {
            return unlockFolderResult;
        }
    }
    // delete temporal file
    if (temporalFile != null && temporalFile.exists() && !temporalFile.delete()) {
        Log_OC.e(TAG, "Could not delete temporal file " + temporalFile.getAbsolutePath());
    }
    return result;
}
Also used : FileNotFoundException(java.io.FileNotFoundException) ChunkedFileUploadRemoteOperation(com.owncloud.android.lib.resources.files.ChunkedFileUploadRemoteOperation) OCUpload(com.owncloud.android.db.OCUpload) FileLock(java.nio.channels.FileLock) EncryptedFolderMetadata(com.owncloud.android.datamodel.EncryptedFolderMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DecryptedFolderMetadata(com.owncloud.android.datamodel.DecryptedFolderMetadata) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) OnDatatransferProgressListener(com.owncloud.android.lib.common.network.OnDatatransferProgressListener) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) FileChannel(java.nio.channels.FileChannel) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) IOException(java.io.IOException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) FileNotFoundException(java.io.FileNotFoundException) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) IOException(java.io.IOException) EncryptionUtils(com.owncloud.android.utils.EncryptionUtils) RandomAccessFile(java.io.RandomAccessFile) UploadFileRemoteOperation(com.owncloud.android.lib.resources.files.UploadFileRemoteOperation) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) FileOutputStream(java.io.FileOutputStream) RandomAccessFile(java.io.RandomAccessFile) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File) SuppressLint(android.annotation.SuppressLint)

Example 2 with ChunkedFileUploadRemoteOperation

use of com.owncloud.android.lib.resources.files.ChunkedFileUploadRemoteOperation in project android by nextcloud.

the class UploadFileOperation method normalUpload.

private RemoteOperationResult normalUpload(OwnCloudClient client) {
    RemoteOperationResult result = null;
    File temporalFile = null;
    File originalFile = new File(mOriginalStoragePath);
    File expectedFile = null;
    FileLock fileLock = null;
    long size;
    try {
        // check conditions
        result = checkConditions(originalFile);
        if (result != null) {
            return result;
        }
        // check name collision
        RemoteOperationResult collisionResult = checkNameCollision(client, null, false);
        if (collisionResult != null) {
            result = collisionResult;
            return collisionResult;
        }
        String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile);
        expectedFile = new File(expectedPath);
        result = copyFile(originalFile, expectedPath);
        if (!result.isSuccess()) {
            return result;
        }
        // Get the last modification date of the file from the file system
        String lastModifiedTimestamp = Long.toString(originalFile.lastModified() / 1000);
        final Long creationTimestamp = FileUtil.getCreationTimestamp(originalFile);
        FileChannel channel = null;
        try {
            channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
            fileLock = channel.tryLock();
        } catch (FileNotFoundException e) {
            // this basically means that the file is on SD card
            // try to copy file to temporary dir if it doesn't exist
            String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) + mFile.getRemotePath();
            mFile.setStoragePath(temporalPath);
            temporalFile = new File(temporalPath);
            Files.deleteIfExists(Paths.get(temporalPath));
            result = copy(originalFile, temporalFile);
            if (result.isSuccess()) {
                if (temporalFile.length() == originalFile.length()) {
                    channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
                    fileLock = channel.tryLock();
                } else {
                    result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
                }
            }
        }
        try {
            size = channel.size();
        } catch (Exception e1) {
            size = new File(mFile.getStoragePath()).length();
        }
        for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
            if (ocUpload.getUploadId() == getOCUploadId()) {
                ocUpload.setFileSize(size);
                uploadsStorageManager.updateUpload(ocUpload);
                break;
            }
        }
        // perform the upload
        if (size > ChunkedFileUploadRemoteOperation.CHUNK_SIZE_MOBILE) {
            boolean onWifiConnection = connectivityService.getConnectivity().isWifi();
            mUploadOperation = new ChunkedFileUploadRemoteOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimeType(), mFile.getEtagInConflict(), lastModifiedTimestamp, creationTimestamp, onWifiConnection, mDisableRetries);
        } else {
            mUploadOperation = new UploadFileRemoteOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimeType(), mFile.getEtagInConflict(), lastModifiedTimestamp, creationTimestamp, mDisableRetries);
        }
        for (OnDatatransferProgressListener mDataTransferListener : mDataTransferListeners) {
            mUploadOperation.addDataTransferProgressListener(mDataTransferListener);
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }
        if (result.isSuccess() && mUploadOperation != null) {
            result = mUploadOperation.execute(client);
            // location in the Nextcloud local folder
            if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
                result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
            }
        }
    } catch (FileNotFoundException e) {
        Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
        result = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
    } catch (OverlappingFileLockException e) {
        Log_OC.d(TAG, "Overlapping file lock exception");
        result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
    } finally {
        mUploadStarted.set(false);
        if (fileLock != null) {
            try {
                fileLock.release();
            } catch (IOException e) {
                Log_OC.e(TAG, "Failed to unlock file with path " + mOriginalStoragePath);
            }
        }
        if (temporalFile != null && !originalFile.equals(temporalFile)) {
            temporalFile.delete();
        }
        if (result == null) {
            result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
        }
        logResult(result, mOriginalStoragePath, mRemotePath);
    }
    if (result.isSuccess()) {
        handleSuccessfulUpload(temporalFile, expectedFile, originalFile, client);
    } else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
        getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
    }
    // delete temporal file
    if (temporalFile != null && temporalFile.exists() && !temporalFile.delete()) {
        Log_OC.e(TAG, "Could not delete temporal file " + temporalFile.getAbsolutePath());
    }
    return result;
}
Also used : OnDatatransferProgressListener(com.owncloud.android.lib.common.network.OnDatatransferProgressListener) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) FileChannel(java.nio.channels.FileChannel) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) FileNotFoundException(java.io.FileNotFoundException) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) IOException(java.io.IOException) ChunkedFileUploadRemoteOperation(com.owncloud.android.lib.resources.files.ChunkedFileUploadRemoteOperation) OCUpload(com.owncloud.android.db.OCUpload) RandomAccessFile(java.io.RandomAccessFile) UploadFileRemoteOperation(com.owncloud.android.lib.resources.files.UploadFileRemoteOperation) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) FileLock(java.nio.channels.FileLock) RandomAccessFile(java.io.RandomAccessFile) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException)

Aggregations

OCFile (com.owncloud.android.datamodel.OCFile)2 OCUpload (com.owncloud.android.db.OCUpload)2 OnDatatransferProgressListener (com.owncloud.android.lib.common.network.OnDatatransferProgressListener)2 OperationCancelledException (com.owncloud.android.lib.common.operations.OperationCancelledException)2 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)2 ChunkedFileUploadRemoteOperation (com.owncloud.android.lib.resources.files.ChunkedFileUploadRemoteOperation)2 UploadFileRemoteOperation (com.owncloud.android.lib.resources.files.UploadFileRemoteOperation)2 RemoteFile (com.owncloud.android.lib.resources.files.model.RemoteFile)2 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 RandomAccessFile (java.io.RandomAccessFile)2 FileChannel (java.nio.channels.FileChannel)2 FileLock (java.nio.channels.FileLock)2 OverlappingFileLockException (java.nio.channels.OverlappingFileLockException)2 SuppressLint (android.annotation.SuppressLint)1 ArbitraryDataProvider (com.owncloud.android.datamodel.ArbitraryDataProvider)1 DecryptedFolderMetadata (com.owncloud.android.datamodel.DecryptedFolderMetadata)1 EncryptedFolderMetadata (com.owncloud.android.datamodel.EncryptedFolderMetadata)1 EncryptionUtils (com.owncloud.android.utils.EncryptionUtils)1