Search in sources :

Example 16 with RemoteOperationResult

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

the class RefreshFolderOperation method refreshSharesForFolder.

/**
     * Syncs the Share resources for the files contained in the folder refreshed (children, not deeper descendants).
     *
     * @param client    Handler of a session with an OC server.
     * @return          The result of the remote operation retrieving the Share resources in the folder refreshed by
     *                  the operation.
     */
private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
    RemoteOperationResult result;
    // remote request 
    GetRemoteSharesForFileOperation operation = new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), true, true);
    result = operation.execute(client);
    if (result.isSuccess()) {
        // update local database
        ArrayList<OCShare> shares = new ArrayList<>();
        for (Object obj : result.getData()) {
            shares.add((OCShare) obj);
        }
        getStorageManager().saveSharesInFolder(shares, mLocalFolder);
    }
    return result;
}
Also used : RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) ArrayList(java.util.ArrayList) OCShare(com.owncloud.android.lib.resources.shares.OCShare) GetRemoteSharesForFileOperation(com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation)

Example 17 with RemoteOperationResult

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

the class UsersAndGroupsSearchProvider method searchForUsersOrGroups.

private Cursor searchForUsersOrGroups(Uri uri) {
    MatrixCursor response = null;
    String userQuery = uri.getLastPathSegment().toLowerCase();
    /// need to trust on the AccountUtils to get the current account since the query in the client side is not
    /// directly started by our code, but from SearchView implementation
    Account account = AccountUtils.getCurrentOwnCloudAccount(getContext());
    /// request to the OC server about users and groups matching userQuery
    GetRemoteShareesOperation searchRequest = new GetRemoteShareesOperation(userQuery, REQUESTED_PAGE, RESULTS_PER_PAGE);
    RemoteOperationResult result = searchRequest.execute(account, getContext());
    List<JSONObject> names = new ArrayList<JSONObject>();
    if (result.isSuccess()) {
        for (Object o : result.getData()) {
            // Get JSonObjects from response
            names.add((JSONObject) o);
        }
    } else {
        showErrorMessage(result);
    }
    /// convert the responses from the OC server to the expected format
    if (names.size() > 0) {
        response = new MatrixCursor(COLUMNS);
        Iterator<JSONObject> namesIt = names.iterator();
        JSONObject item;
        String displayName = null;
        int icon = 0;
        Uri dataUri = null;
        int count = 0;
        MainApp app = (MainApp) getContext().getApplicationContext();
        Uri userBaseUri = new Uri.Builder().scheme(CONTENT).authority(sSuggestAuthority + DATA_USER_SUFFIX).build();
        Uri groupBaseUri = new Uri.Builder().scheme(CONTENT).authority(sSuggestAuthority + DATA_GROUP_SUFFIX).build();
        Uri remoteBaseUri = new Uri.Builder().scheme(CONTENT).authority(sSuggestAuthority + DATA_REMOTE_SUFFIX).build();
        FileDataStorageManager manager = new FileDataStorageManager(account, getContext().getContentResolver());
        boolean federatedShareAllowed = manager.getCapability(account.name).getFilesSharingFederationOutgoing().isTrue();
        try {
            while (namesIt.hasNext()) {
                item = namesIt.next();
                String userName = item.getString(GetRemoteShareesOperation.PROPERTY_LABEL);
                JSONObject value = item.getJSONObject(GetRemoteShareesOperation.NODE_VALUE);
                int type = value.getInt(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE);
                String shareWith = value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH);
                if (ShareType.GROUP.getValue() == type) {
                    displayName = getContext().getString(R.string.share_group_clarification, userName);
                    icon = R.drawable.ic_group;
                    dataUri = Uri.withAppendedPath(groupBaseUri, shareWith);
                } else if (ShareType.FEDERATED.getValue() == type && federatedShareAllowed) {
                    icon = R.drawable.ic_user;
                    if (userName.equals(shareWith)) {
                        displayName = getContext().getString(R.string.share_remote_clarification, userName);
                    } else {
                        String[] uriSplitted = shareWith.split("@");
                        displayName = getContext().getString(R.string.share_known_remote_clarification, userName, uriSplitted[uriSplitted.length - 1]);
                    }
                    dataUri = Uri.withAppendedPath(remoteBaseUri, shareWith);
                } else if (ShareType.USER.getValue() == type) {
                    displayName = userName;
                    icon = R.drawable.ic_user;
                    dataUri = Uri.withAppendedPath(userBaseUri, shareWith);
                }
                if (displayName != null && dataUri != null) {
                    response.newRow().add(// BaseColumns._ID
                    count++).add(// SearchManager.SUGGEST_COLUMN_TEXT_1
                    displayName).add(// SearchManager.SUGGEST_COLUMN_ICON_1
                    icon).add(dataUri);
                }
            }
        } catch (JSONException e) {
            Log_OC.e(TAG, "Exception while parsing data of users/groups", e);
        }
    }
    return response;
}
Also used : Account(android.accounts.Account) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) GetRemoteShareesOperation(com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation) ArrayList(java.util.ArrayList) MainApp(com.owncloud.android.MainApp) JSONException(org.json.JSONException) Uri(android.net.Uri) MatrixCursor(android.database.MatrixCursor) JSONObject(org.json.JSONObject) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) JSONObject(org.json.JSONObject)

Example 18 with RemoteOperationResult

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

the class UpdateShareViaLinkOperation method run.

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    OCShare publicShare = getStorageManager().getFirstShareByPathAndType(mPath, ShareType.PUBLIC_LINK, "");
    if (publicShare == null) {
        // TODO try to get remote share before failing?
        return new RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
    }
    // Update remote share with password
    UpdateRemoteShareOperation updateOp = new UpdateRemoteShareOperation(publicShare.getRemoteId());
    updateOp.setPassword(mPassword);
    updateOp.setExpirationDate(mExpirationDateInMillis);
    updateOp.setPublicUpload(mPublicUpload);
    RemoteOperationResult result = updateOp.execute(client);
    if (result.isSuccess()) {
        // Retrieve updated share / save directly with password? -> no; the password is not to be saved
        RemoteOperation getShareOp = new GetRemoteShareOperation(publicShare.getRemoteId());
        result = getShareOp.execute(client);
        if (result.isSuccess()) {
            OCShare share = (OCShare) result.getData().get(0);
            updateData(share);
        }
    }
    return result;
}
Also used : RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) GetRemoteShareOperation(com.owncloud.android.lib.resources.shares.GetRemoteShareOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) UpdateRemoteShareOperation(com.owncloud.android.lib.resources.shares.UpdateRemoteShareOperation) OCShare(com.owncloud.android.lib.resources.shares.OCShare)

Example 19 with RemoteOperationResult

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

the class UploadFileOperation method copy.

/**
     * 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
     */
private RemoteOperationResult copy(File sourceFile, File targetFile) throws IOException {
    Log_OC.d(TAG, "Copying local file");
    RemoteOperationResult result = null;
    if (FileStorageUtils.getUsableSpace(mAccount.name) < sourceFile.length()) {
        result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
        // error condition when the file should be copied
        return result;
    } else {
        Log_OC.d(TAG, "Creating temporal folder");
        File temporalParent = targetFile.getParentFile();
        temporalParent.mkdirs();
        if (!temporalParent.isDirectory()) {
            throw new IOException("Unexpected error: parent directory could not be created");
        }
        Log_OC.d(TAG, "Creating temporal file");
        targetFile.createNewFile();
        if (!targetFile.isFile()) {
            throw new IOException("Unexpected error: target file could not be created");
        }
        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();
            }
            if (mCancellationRequested.get()) {
                result = new RemoteOperationResult(new OperationCancelledException());
                return result;
            }
        } catch (Exception e) {
            result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
            return result;
        } 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 result;
}
Also used : RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) OCFile(com.owncloud.android.datamodel.OCFile) RemoteFile(com.owncloud.android.lib.resources.files.RemoteFile) File(java.io.File) Uri(android.net.Uri) FileInputStream(java.io.FileInputStream) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) IOException(java.io.IOException)

Example 20 with RemoteOperationResult

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

the class UploadFileOperation method run.

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    mCancellationRequested.set(false);
    mUploadStarted.set(true);
    RemoteOperationResult result = null;
    File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
    try {
        /// Check that connectivity conditions are met and delays the upload otherwise
        if (delayForWifi()) {
            Log_OC.d(TAG, "Upload delayed until WiFi is available: " + getRemotePath());
            return new RemoteOperationResult(ResultCode.DELAYED_FOR_WIFI);
        }
        /// check if the file continues existing before schedule the operation
        if (!originalFile.exists()) {
            Log_OC.d(TAG, mOriginalStoragePath.toString() + " not exists anymore");
            return new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
        }
        /// check the existence of the parent folder for the file to upload
        String remoteParentPath = new File(getRemotePath()).getParent();
        remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ? remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
        result = grantFolderExistence(remoteParentPath, client);
        if (!result.isSuccess()) {
            return result;
        }
        /// set parent local id in uploading file
        OCFile parent = getStorageManager().getFileByPath(remoteParentPath);
        mFile.setParentId(parent.getFileId());
        /// automatic rename of file to upload in case of name collision in server
        Log_OC.d(TAG, "Checking name collision in server");
        if (!mForceOverwrite) {
            String remotePath = getAvailableRemotePath(client, mRemotePath);
            mWasRenamed = !remotePath.equals(mRemotePath);
            if (mWasRenamed) {
                createNewOCFile(remotePath);
                Log_OC.d(TAG, "File renamed as " + remotePath);
            }
            mRemotePath = remotePath;
            mRenameUploadListener.onRenameUpload();
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }
        String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
        expectedFile = new File(expectedPath);
        /// copy the file locally before uploading
        if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY && !mOriginalStoragePath.equals(expectedPath)) {
            String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
            mFile.setStoragePath(temporalPath);
            temporalFile = new File(temporalPath);
            result = copy(originalFile, temporalFile);
            if (result != null) {
                return result;
            }
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }
        // Get the last modification date of the file from the file system
        Long timeStampLong = originalFile.lastModified() / 1000;
        String timeStamp = timeStampLong.toString();
        /// perform the upload
        if (mChunked && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE) {
            mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict(), timeStamp);
        } else {
            mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict(), timeStamp);
        }
        Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
        while (listener.hasNext()) {
            mUploadOperation.addDatatransferProgressListener(listener.next());
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }
        result = mUploadOperation.execute(client);
        // location in the ownCloud local folder
        if (result.isSuccess()) {
            if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
                String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
                if (mOriginalStoragePath.equals(temporalPath)) {
                    // delete local file is was pre-copied in temporary folder (see .ui.helpers.UriUploader)
                    temporalFile = new File(temporalPath);
                    temporalFile.delete();
                }
                mFile.setStoragePath("");
            } else {
                mFile.setStoragePath(expectedPath);
                if (temporalFile != null) {
                    // FileUploader.LOCAL_BEHAVIOUR_COPY
                    move(temporalFile, expectedFile);
                } else {
                    // FileUploader.LOCAL_BEHAVIOUR_MOVE
                    move(originalFile, expectedFile);
                    getStorageManager().deleteFileInMediaScan(originalFile.getAbsolutePath());
                }
                FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
            }
        } else if (result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
            result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
    } finally {
        mUploadStarted.set(false);
        if (temporalFile != null && !originalFile.equals(temporalFile)) {
            temporalFile.delete();
        }
        if (result == null) {
            result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
        }
        if (result.isSuccess()) {
            Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
        } else {
            if (result.getException() != null) {
                if (result.isCancelled()) {
                    Log_OC.w(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
                } else {
                    Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage(), result.getException());
                }
            } else {
                Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
            }
        }
    }
    if (result.isSuccess()) {
        saveUploadedFile(client);
    } else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
        getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
    }
    return result;
}
Also used : OCFile(com.owncloud.android.datamodel.OCFile) ChunkedUploadRemoteFileOperation(com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation) UploadRemoteFileOperation(com.owncloud.android.lib.resources.files.UploadRemoteFileOperation) OnDatatransferProgressListener(com.owncloud.android.lib.common.network.OnDatatransferProgressListener) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) ChunkedUploadRemoteFileOperation(com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation) OCFile(com.owncloud.android.datamodel.OCFile) RemoteFile(com.owncloud.android.lib.resources.files.RemoteFile) File(java.io.File) OperationCancelledException(com.owncloud.android.lib.common.operations.OperationCancelledException) IOException(java.io.IOException)

Aggregations

RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)46 OCFile (com.owncloud.android.datamodel.OCFile)11 ArrayList (java.util.ArrayList)9 RemoteOperation (com.owncloud.android.lib.common.operations.RemoteOperation)7 OCShare (com.owncloud.android.lib.resources.shares.OCShare)7 FileDataStorageManager (com.owncloud.android.datamodel.FileDataStorageManager)6 ExistenceCheckRemoteOperation (com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation)6 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)5 OperationCancelledException (com.owncloud.android.lib.common.operations.OperationCancelledException)5 File (java.io.File)5 IOException (java.io.IOException)5 Account (android.accounts.Account)4 Uri (android.net.Uri)4 Intent (android.content.Intent)3 RemoteFile (com.owncloud.android.lib.resources.files.RemoteFile)3 GetRemoteSharesForFileOperation (com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation)3 UserInfo (com.owncloud.android.lib.resources.users.GetRemoteUserInfoOperation.UserInfo)3 AccountManager (android.accounts.AccountManager)2 Pair (android.util.Pair)2 OwnCloudClient (com.owncloud.android.lib.common.OwnCloudClient)2