Search in sources :

Example 16 with RemoteOperation

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

the class DetectAuthenticationMethodOperation method run.

/**
     *  Performs the operation.
     * 
     *  Triggers a check of existence on the root folder of the server, granting
     *  that the request is not authenticated.
     *  
     *  Analyzes the result of check to find out what authentication method, if
     *  any, is requested by the server.
     */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    AuthenticationMethod authMethod = AuthenticationMethod.UNKNOWN;
    RemoteOperation operation = new ExistenceCheckRemoteOperation("", mContext, false);
    client.clearCredentials();
    client.setFollowRedirects(false);
    // try to access the root folder, following redirections but not SAML SSO redirections
    result = operation.execute(client);
    String redirectedLocation = result.getRedirectedLocation();
    while (redirectedLocation != null && redirectedLocation.length() > 0 && !result.isIdPRedirection()) {
        client.setBaseUri(Uri.parse(result.getRedirectedLocation()));
        result = operation.execute(client);
        redirectedLocation = result.getRedirectedLocation();
    }
    // analyze response  
    if (result.getHttpCode() == HttpStatus.SC_UNAUTHORIZED) {
        String authRequest = ((result.getAuthenticateHeader()).trim()).toLowerCase();
        if (authRequest.startsWith("basic")) {
            authMethod = AuthenticationMethod.BASIC_HTTP_AUTH;
        } else if (authRequest.startsWith("bearer")) {
            authMethod = AuthenticationMethod.BEARER_TOKEN;
        }
    // else - fall back to UNKNOWN
    } else if (result.isSuccess()) {
        authMethod = AuthenticationMethod.NONE;
    } else if (result.isIdPRedirection()) {
        authMethod = AuthenticationMethod.SAML_WEB_SSO;
    }
    // else - fall back to UNKNOWN
    Log_OC.d(TAG, "Authentication method found: " + authenticationMethodToString(authMethod));
    if (!authMethod.equals(AuthenticationMethod.UNKNOWN)) {
        result = new RemoteOperationResult(true, result.getHttpCode(), result.getHttpPhrase(), null);
    }
    ArrayList<Object> data = new ArrayList<Object>();
    data.add(authMethod);
    result.setData(data);
    // same result instance, so that other errors
    return result;
// can be handled by the caller transparently
}
Also used : ExistenceCheckRemoteOperation(com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) ExistenceCheckRemoteOperation(com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) ArrayList(java.util.ArrayList)

Example 17 with RemoteOperation

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

the class ActivitiesListActivity method onActivityClicked.

@Override
public void onActivityClicked(RichObject richObject) {
    String path = FileUtils.PATH_SEPARATOR + richObject.getPath();
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            swipeEmptyListRefreshLayout.setVisibility(View.VISIBLE);
            swipeListRefreshLayout.setVisibility(View.GONE);
            setLoadingMessage();
        }
    });
    updateTask = new AsyncTask<String, Object, OCFile>() {

        @Override
        protected OCFile doInBackground(String... path) {
            OCFile ocFile = null;
            // always update file as it could be an old state saved in database
            ReadRemoteFileOperation operation = new ReadRemoteFileOperation(path[0]);
            RemoteOperationResult resultRemoteFileOp = operation.execute(ownCloudClient);
            if (resultRemoteFileOp.isSuccess()) {
                OCFile temp = FileStorageUtils.fillOCFile((RemoteFile) resultRemoteFileOp.getData().get(0));
                ocFile = getStorageManager().saveFileWithParent(temp, getBaseContext());
                if (ocFile.isFolder()) {
                    // perform folder synchronization
                    RemoteOperation synchFolderOp = new RefreshFolderOperation(ocFile, System.currentTimeMillis(), false, getFileOperationsHelper().isSharedSupported(), true, getStorageManager(), getAccount(), getApplicationContext());
                    synchFolderOp.execute(ownCloudClient);
                }
            }
            return ocFile;
        }

        @Override
        protected void onPostExecute(OCFile ocFile) {
            if (!isCancelled()) {
                if (ocFile == null) {
                    Toast.makeText(getBaseContext(), R.string.file_not_found, Toast.LENGTH_LONG).show();
                    swipeEmptyListRefreshLayout.setVisibility(View.GONE);
                    swipeListRefreshLayout.setVisibility(View.VISIBLE);
                    dismissLoadingDialog();
                } else {
                    Intent showDetailsIntent;
                    if (PreviewImageFragment.canBePreviewed(ocFile)) {
                        showDetailsIntent = new Intent(getBaseContext(), PreviewImageActivity.class);
                    } else {
                        showDetailsIntent = new Intent(getBaseContext(), FileDisplayActivity.class);
                    }
                    showDetailsIntent.putExtra(EXTRA_FILE, ocFile);
                    showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
                    startActivity(showDetailsIntent);
                }
            }
        }
    };
    updateTask.execute(path);
}
Also used : OCFile(com.owncloud.android.datamodel.OCFile) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) RefreshFolderOperation(com.owncloud.android.operations.RefreshFolderOperation) ReadRemoteFileOperation(com.owncloud.android.lib.resources.files.ReadRemoteFileOperation) RichObject(com.owncloud.android.lib.resources.activities.models.RichObject) Intent(android.content.Intent) BindString(butterknife.BindString) RemoteFile(com.owncloud.android.lib.resources.files.RemoteFile)

Example 18 with RemoteOperation

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

the class PushUtils method pushRegistrationToServer.

public static void pushRegistrationToServer() {
    String token = PreferenceManager.getPushToken(MainApp.getAppContext());
    arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
    if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url)) && !TextUtils.isEmpty(token)) {
        PushUtils.generateRsa2048KeyPair();
        String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase(Locale.ROOT);
        PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
        if (devicePublicKey != null) {
            byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
            String publicKey = new String(publicKeyBytes);
            publicKey = publicKey.replaceAll("(.{64})", "$1\n");
            publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
            Context context = MainApp.getAppContext();
            String providerValue;
            PushConfigurationState accountPushData = null;
            Gson gson = new Gson();
            for (Account account : AccountUtils.getAccounts(context)) {
                providerValue = arbitraryDataProvider.getValue(account, KEY_PUSH);
                if (!TextUtils.isEmpty(providerValue)) {
                    accountPushData = gson.fromJson(providerValue, PushConfigurationState.class);
                } else {
                    accountPushData = null;
                }
                if (accountPushData != null && !accountPushData.getPushToken().equals(token) && !accountPushData.isShouldBeDeleted() || TextUtils.isEmpty(providerValue)) {
                    try {
                        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
                        OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
                        RemoteOperation registerAccountDeviceForNotificationsOperation = new RegisterAccountDeviceForNotificationsOperation(pushTokenHash, publicKey, context.getResources().getString(R.string.push_server_url));
                        RemoteOperationResult remoteOperationResult = registerAccountDeviceForNotificationsOperation.execute(mClient);
                        if (remoteOperationResult.isSuccess()) {
                            PushResponse pushResponse = remoteOperationResult.getPushResponseData();
                            RemoteOperation registerAccountDeviceForProxyOperation = new RegisterAccountDeviceForProxyOperation(context.getResources().getString(R.string.push_server_url), token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(), pushResponse.getPublicKey());
                            remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);
                            if (remoteOperationResult.isSuccess()) {
                                PushConfigurationState pushArbitraryData = new PushConfigurationState(token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(), pushResponse.getPublicKey(), false);
                                arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH, gson.toJson(pushArbitraryData));
                            }
                        } else if (remoteOperationResult.getCode() == RemoteOperationResult.ResultCode.ACCOUNT_USES_STANDARD_PASSWORD) {
                            arbitraryDataProvider.storeOrUpdateKeyValue(account.name, AccountUtils.ACCOUNT_USES_STANDARD_PASSWORD, "true");
                        }
                    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
                        Log_OC.d(TAG, "Failed to find an account");
                    } catch (AuthenticatorException e) {
                        Log_OC.d(TAG, "Failed via AuthenticatorException");
                    } catch (IOException e) {
                        Log_OC.d(TAG, "Failed via IOException");
                    } catch (OperationCanceledException e) {
                        Log_OC.d(TAG, "Failed via OperationCanceledException");
                    }
                } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
                    deleteRegistrationForAccount(account);
                }
            }
        }
    }
}
Also used : Context(android.content.Context) Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) PublicKey(java.security.PublicKey) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OperationCanceledException(android.accounts.OperationCanceledException) RegisterAccountDeviceForNotificationsOperation(com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForNotificationsOperation) AccountUtils(com.owncloud.android.authentication.AccountUtils) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) Gson(com.google.gson.Gson) AuthenticatorException(android.accounts.AuthenticatorException) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) IOException(java.io.IOException) RegisterAccountDeviceForProxyOperation(com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForProxyOperation) PushConfigurationState(com.owncloud.android.datamodel.PushConfigurationState) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) PushResponse(com.owncloud.android.lib.resources.notifications.models.PushResponse)

Example 19 with RemoteOperation

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

the class OperationsService method dispatchResultToOperationListeners.

/**
 * Notifies the currently subscribed listeners about the end of an operation.
 *
 * @param operation Finished operation.
 * @param result    Result of the operation.
 */
protected void dispatchResultToOperationListeners(final RemoteOperation operation, final RemoteOperationResult result) {
    int count = 0;
    for (OnRemoteOperationListener listener : mOperationsBinder.mBoundListeners.keySet()) {
        final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
        if (handler != null) {
            handler.post(() -> listener.onRemoteOperationFinish(operation, result));
            count += 1;
        }
    }
    if (count == 0) {
        Pair<RemoteOperation, RemoteOperationResult> undispatched = new Pair<>(operation, result);
        mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
    }
    Timber.d("Called " + count + " listeners");
}
Also used : RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OnRemoteOperationListener(com.owncloud.android.lib.common.operations.OnRemoteOperationListener) Handler(android.os.Handler) Pair(android.util.Pair)

Example 20 with RemoteOperation

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

the class OperationsService method onStartCommand.

/**
 * Entry point to add a new operation to the queue of operations.
 *
 * New operations are added calling to startService(), resulting in a call to this method.
 * This ensures the service will keep on working although the caller activity goes away.
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Timber.d("Starting command with id %s", startId);
    // the rest of the operations are requested through the Binder
    if (ACTION_SYNC_FOLDER.equals(intent.getAction())) {
        if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
            Timber.e("Not enough information provided in intent");
            return START_NOT_STICKY;
        }
        Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
        String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
        Pair<Account, String> itemSyncKey = new Pair<>(account, remotePath);
        Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
        if (itemToQueue != null) {
            mSyncFolderHandler.add(account, remotePath, (SynchronizeFolderOperation) itemToQueue.second);
            Message msg = mSyncFolderHandler.obtainMessage();
            msg.arg1 = startId;
            msg.obj = itemSyncKey;
            mSyncFolderHandler.sendMessage(msg);
        }
    } else {
        Message msg = mOperationsHandler.obtainMessage();
        msg.arg1 = startId;
        mOperationsHandler.sendMessage(msg);
    }
    return START_NOT_STICKY;
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) Message(android.os.Message) Pair(android.util.Pair)

Aggregations

RemoteOperation (com.owncloud.android.lib.common.operations.RemoteOperation)31 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)24 Account (android.accounts.Account)7 OCFile (com.owncloud.android.datamodel.OCFile)7 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)7 Pair (android.util.Pair)6 OCShare (com.owncloud.android.lib.resources.shares.OCShare)6 ArrayList (java.util.ArrayList)6 RefreshFolderOperation (com.owncloud.android.operations.RefreshFolderOperation)5 Handler (android.os.Handler)4 ExistenceCheckRemoteOperation (com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation)4 GetUserInfoRemoteOperation (com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation)4 User (com.nextcloud.client.account.User)3 FileDataStorageManager (com.owncloud.android.datamodel.FileDataStorageManager)3 ReadFileRemoteOperation (com.owncloud.android.lib.resources.files.ReadFileRemoteOperation)3 RestoreFileVersionRemoteOperation (com.owncloud.android.lib.resources.files.RestoreFileVersionRemoteOperation)3 SearchRemoteOperation (com.owncloud.android.lib.resources.files.SearchRemoteOperation)3 GetShareRemoteOperation (com.owncloud.android.lib.resources.shares.GetShareRemoteOperation)3 UpdateShareRemoteOperation (com.owncloud.android.lib.resources.shares.UpdateShareRemoteOperation)3 AuthenticatorException (android.accounts.AuthenticatorException)2