Search in sources :

Example 71 with RemoteOperationResult

use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by nextcloud.

the class SynchronizeFolderOperation method fetchAndSyncRemoteFolder.

private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) throws OperationCancelledException {
    if (mCancellationRequested.get()) {
        throw new OperationCancelledException();
    }
    ReadFolderRemoteOperation operation = new ReadFolderRemoteOperation(mRemotePath);
    RemoteOperationResult result = operation.execute(client);
    Log_OC.d(TAG, "Synchronizing " + user.getAccountName() + mRemotePath);
    if (result.isSuccess()) {
        synchronizeData(result.getData());
        if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
            result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
        // should be a different result code, but will do the job
        }
    } else {
        if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
            removeLocalFolder();
        }
    }
    return result;
}
Also used : OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) ReadFolderRemoteOperation(com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation)

Example 72 with RemoteOperationResult

use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by nextcloud.

the class StreamMediaFileOperation method run.

protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;
    Utf8PostMethod postMethod = null;
    try {
        postMethod = new Utf8PostMethod(client.getBaseUri() + STREAM_MEDIA_URL + JSON_FORMAT);
        postMethod.setParameter("fileId", fileID);
        // remote request
        postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);
        if (status == HttpStatus.SC_OK) {
            String response = postMethod.getResponseBodyAsString();
            // Parse the response
            JSONObject respJSON = new JSONObject(response);
            String url = respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA).getString(NODE_URL);
            result = new RemoteOperationResult(true, postMethod);
            ArrayList<Object> urlArray = new ArrayList<>();
            urlArray.add(url);
            result.setData(urlArray);
        } else {
            result = new RemoteOperationResult(false, postMethod);
            client.exhaustResponse(postMethod.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Get stream url for file with id " + fileID + " failed: " + result.getLogMessage(), result.getException());
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return result;
}
Also used : Utf8PostMethod(org.apache.commons.httpclient.methods.Utf8PostMethod) JSONObject(org.json.JSONObject) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject)

Example 73 with RemoteOperationResult

use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by nextcloud.

the class FileUploader method uploadFile.

/**
 * Core upload method: sends the file(s) to upload
 *
 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
 */
public void uploadFile(String uploadKey) {
    mCurrentUpload = mPendingUploads.get(uploadKey);
    if (mCurrentUpload != null) {
        // / Check account existence
        if (!accountManager.exists(mCurrentUpload.getAccount())) {
            Log_OC.w(TAG, "Account " + mCurrentUpload.getAccount().name + " does not exist anymore -> cancelling all its uploads");
            cancelUploadsForAccount(mCurrentUpload.getAccount());
            return;
        }
        // / OK, let's upload
        mUploadsStorageManager.updateDatabaseUploadStart(mCurrentUpload);
        notifyUploadStart(mCurrentUpload);
        sendBroadcastUploadStarted(mCurrentUpload);
        RemoteOperationResult uploadResult = null;
        try {
            // / prepare client object to send the request to the ownCloud server
            if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
                mCurrentAccount = mCurrentUpload.getAccount();
                mStorageManager = new FileDataStorageManager(getCurrentUser().get(), getContentResolver());
            }
            // else, reuse storage manager from previous operation
            // always get client from client manager, to get fresh credentials in case of update
            OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this);
            mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, this);
            // // If parent folder is encrypted, upload file encrypted
            // OCFile parent = mStorageManager.getFileByPath(mCurrentUpload.getFile().getParentRemotePath());
            // if (parent.isEncrypted()) {
            // UploadEncryptedFileOperation uploadEncryptedFileOperation =
            // new UploadEncryptedFileOperation(parent, mCurrentUpload);
            // 
            // uploadResult = uploadEncryptedFileOperation.execute(mUploadClient, mStorageManager);
            // } else {
            // / perform the regular upload
            uploadResult = mCurrentUpload.execute(mUploadClient);
        // }
        } catch (Exception e) {
            Log_OC.e(TAG, "Error uploading", e);
            uploadResult = new RemoteOperationResult(e);
        } finally {
            Pair<UploadFileOperation, String> removeResult;
            if (mCurrentUpload.wasRenamed()) {
                removeResult = mPendingUploads.removePayload(mCurrentAccount.name, mCurrentUpload.getOldFile().getRemotePath());
            // TODO: grant that name is also updated for mCurrentUpload.getOCUploadId
            } else {
                removeResult = mPendingUploads.removePayload(mCurrentAccount.name, mCurrentUpload.getDecryptedRemotePath());
            }
            mUploadsStorageManager.updateDatabaseUploadResult(uploadResult, mCurrentUpload);
            // / notify result
            notifyUploadResult(mCurrentUpload, uploadResult);
            sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
        }
        // generate new Thumbnail
        Optional<User> user = getCurrentUser();
        if (user.isPresent()) {
            final ThumbnailsCacheManager.ThumbnailGenerationTask task = new ThumbnailsCacheManager.ThumbnailGenerationTask(mStorageManager, user.get());
            File file = new File(mCurrentUpload.getOriginalStoragePath());
            String remoteId = mCurrentUpload.getFile().getRemoteId();
            task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, remoteId));
        }
    }
}
Also used : User(com.nextcloud.client.account.User) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) UploadFileOperation(com.owncloud.android.operations.UploadFileOperation) ThumbnailsCacheManager(com.owncloud.android.datamodel.ThumbnailsCacheManager) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File)

Example 74 with RemoteOperationResult

use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by nextcloud.

the class FileDownloader method downloadFile.

/**
 * Core download method: requests a file to download and stores it.
 *
 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
 */
private void downloadFile(String downloadKey) {
    mStartedDownload = true;
    mCurrentDownload = mPendingDownloads.get(downloadKey);
    if (mCurrentDownload != null) {
        // Detect if the account exists
        if (accountManager.exists(mCurrentDownload.getAccount())) {
            Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().name + " exists");
            notifyDownloadStart(mCurrentDownload);
            RemoteOperationResult downloadResult = null;
            try {
                // / prepare client object to send the request to the ownCloud server
                Account currentDownloadAccount = mCurrentDownload.getAccount();
                Optional<User> currentDownloadUser = accountManager.getUser(currentDownloadAccount.name);
                if (!currentUser.equals(currentDownloadUser)) {
                    currentUser = currentDownloadUser;
                    mStorageManager = new FileDataStorageManager(currentUser.get(), getContentResolver());
                }
                // else, reuse storage manager from previous operation
                // always get client from client manager, to get fresh credentials in case
                // of update
                OwnCloudAccount ocAccount = currentDownloadUser.get().toOwnCloudAccount();
                mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, this);
                // / perform the download
                downloadResult = mCurrentDownload.execute(mDownloadClient);
                if (downloadResult.isSuccess()) {
                    saveDownloadedFile();
                }
            } catch (Exception e) {
                Log_OC.e(TAG, "Error downloading", e);
                downloadResult = new RemoteOperationResult(e);
            } finally {
                Pair<DownloadFileOperation, String> removeResult = mPendingDownloads.removePayload(mCurrentDownload.getUser().getAccountName(), mCurrentDownload.getRemotePath());
                if (downloadResult == null) {
                    downloadResult = new RemoteOperationResult(new RuntimeException("Error downloading…"));
                }
                // / notify result
                notifyDownloadResult(mCurrentDownload, downloadResult);
                sendBroadcastDownloadFinished(mCurrentDownload, downloadResult, removeResult.second);
            }
        } else {
            // Cancel the transfer
            Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount() + " doesn't exist");
            cancelDownloadsForAccount(mCurrentDownload.getAccount());
        }
    }
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) DownloadFileOperation(com.owncloud.android.operations.DownloadFileOperation) User(com.nextcloud.client.account.User) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount)

Example 75 with RemoteOperationResult

use of com.owncloud.android.lib.common.operations.RemoteOperationResult in project android by nextcloud.

the class CreateFolderOperation method encryptedCreate.

private RemoteOperationResult encryptedCreate(OCFile parent, OwnCloudClient client) {
    ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
    String privateKey = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.PRIVATE_KEY);
    String publicKey = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.PUBLIC_KEY);
    String token = null;
    Boolean metadataExists;
    DecryptedFolderMetadata metadata;
    String encryptedRemotePath = null;
    String filename = new File(remotePath).getName();
    try {
        // lock folder
        token = EncryptionUtils.lockFolder(parent, client);
        // get metadata
        Pair<Boolean, DecryptedFolderMetadata> metadataPair = EncryptionUtils.retrieveMetadata(parent, client, privateKey, publicKey);
        metadataExists = metadataPair.first;
        metadata = metadataPair.second;
        // check if filename already exists
        if (isFileExisting(metadata, filename)) {
            return new RemoteOperationResult(RemoteOperationResult.ResultCode.FOLDER_ALREADY_EXISTS);
        }
        // generate new random file name, check if it exists in metadata
        String encryptedFileName = createRandomFileName(metadata);
        encryptedRemotePath = parent.getRemotePath() + encryptedFileName;
        RemoteOperationResult result = new CreateFolderRemoteOperation(encryptedRemotePath, true, token).execute(client);
        if (result.isSuccess()) {
            // update metadata
            metadata.getFiles().put(encryptedFileName, createDecryptedFile(filename));
            EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.encryptFolderMetadata(metadata, privateKey);
            String serializedFolderMetadata = EncryptionUtils.serializeJSON(encryptedFolderMetadata);
            // upload metadata
            EncryptionUtils.uploadMetadata(parent, serializedFolderMetadata, token, client, metadataExists);
            // unlock folder
            if (token != null) {
                RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parent, client, token);
                if (unlockFolderResult.isSuccess()) {
                    token = null;
                } else {
                    // TODO do better
                    throw new RuntimeException("Could not unlock folder!");
                }
            }
            RemoteOperationResult remoteFolderOperationResult = new ReadFolderRemoteOperation(encryptedRemotePath).execute(client);
            createdRemoteFolder = (RemoteFile) remoteFolderOperationResult.getData().get(0);
            OCFile newDir = createRemoteFolderOcFile(parent, filename, createdRemoteFolder);
            getStorageManager().saveFile(newDir);
            RemoteOperationResult encryptionOperationResult = new ToggleEncryptionRemoteOperation(newDir.getLocalId(), newDir.getRemotePath(), true).execute(client);
            if (!encryptionOperationResult.isSuccess()) {
                throw new RuntimeException("Error creating encrypted subfolder!");
            }
        } else {
            // revert to sane state in case of any error
            Log_OC.e(TAG, remotePath + " hasn't been created");
        }
        return result;
    } catch (Exception e) {
        if (!EncryptionUtils.unlockFolder(parent, client, token).isSuccess()) {
            throw new RuntimeException("Could not clean up after failing folder creation!");
        }
        // remove folder
        if (encryptedRemotePath != null) {
            RemoteOperationResult removeResult = new RemoveRemoteEncryptedFileOperation(encryptedRemotePath, parent.getLocalId(), user.toPlatformAccount(), context, filename).execute(client);
            if (!removeResult.isSuccess()) {
                throw new RuntimeException("Could not clean up after failing folder creation!");
            }
        }
        // TODO do better
        return new RemoteOperationResult(e);
    } finally {
        // unlock folder
        if (token != null) {
            RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parent, client, token);
            if (!unlockFolderResult.isSuccess()) {
                // TODO do better
                throw new RuntimeException("Could not unlock folder!");
            }
        }
    }
}
Also used : CreateFolderRemoteOperation(com.owncloud.android.lib.resources.files.CreateFolderRemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) ReadFolderRemoteOperation(com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation) OCFile(com.owncloud.android.datamodel.OCFile) EncryptedFolderMetadata(com.owncloud.android.datamodel.EncryptedFolderMetadata) DecryptedFolderMetadata(com.owncloud.android.datamodel.DecryptedFolderMetadata) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File) ToggleEncryptionRemoteOperation(com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation)

Aggregations

RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)172 OCFile (com.owncloud.android.datamodel.OCFile)48 RemoteOperation (com.owncloud.android.lib.common.operations.RemoteOperation)24 ArrayList (java.util.ArrayList)24 FileDataStorageManager (com.owncloud.android.datamodel.FileDataStorageManager)22 IOException (java.io.IOException)22 Account (android.accounts.Account)19 User (com.nextcloud.client.account.User)18 OCShare (com.owncloud.android.lib.resources.shares.OCShare)18 File (java.io.File)18 OperationCancelledException (com.owncloud.android.lib.common.operations.OperationCancelledException)17 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)16 Context (android.content.Context)15 OwnCloudClient (com.owncloud.android.lib.common.OwnCloudClient)12 RemoteFile (com.owncloud.android.lib.resources.files.model.RemoteFile)12 FileNotFoundException (java.io.FileNotFoundException)12 Intent (android.content.Intent)11 JSONObject (org.json.JSONObject)11 Test (org.junit.Test)11 Uri (android.net.Uri)10