Search in sources :

Example 6 with OwnCloudClient

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

the class FileActivity method performCredentialsUpdate.

public void performCredentialsUpdate(Account account, Context context) {
    try {
        // / step 1 - invalidate credentials of current account
        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
        OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount);
        if (client != null) {
            OwnCloudCredentials credentials = client.getCredentials();
            if (credentials != null) {
                AccountManager accountManager = AccountManager.get(context);
                if (credentials.authTokenExpires()) {
                    accountManager.invalidateAuthToken(account.type, credentials.getAuthToken());
                } else {
                    accountManager.clearPassword(account);
                }
            }
        }
        // / step 2 - request credentials to user
        Intent updateAccountCredentials = new Intent(context, AuthenticatorActivity.class);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivityForResult(updateAccountCredentials, REQUEST_CODE__UPDATE_CREDENTIALS);
    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
        DisplayUtils.showSnackMessage(this, R.string.auth_account_does_not_exist);
    }
}
Also used : UserAccountManager(com.nextcloud.client.account.UserAccountManager) AccountManager(android.accounts.AccountManager) Intent(android.content.Intent) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) OwnCloudCredentials(com.owncloud.android.lib.common.OwnCloudCredentials)

Example 7 with OwnCloudClient

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

the class InputStreamBinder method processRequestV2.

private Response processRequestV2(final NextcloudRequest request, final InputStream requestBodyInputStream) throws UnsupportedOperationException, com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
    Account account = accountManager.getAccountByName(request.getAccountName());
    if (account == null) {
        throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND);
    }
    // Validate token
    if (!isValid(request)) {
        throw new IllegalStateException(EXCEPTION_INVALID_TOKEN);
    }
    // Validate URL
    if (request.getUrl().length() == 0 || request.getUrl().charAt(0) != PATH_SEPARATOR) {
        throw new IllegalStateException(EXCEPTION_INVALID_REQUEST_URL, new IllegalStateException("URL need to start with a /"));
    }
    OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton();
    OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
    OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context);
    HttpMethodBase method = buildMethod(request, client.getBaseUri(), requestBodyInputStream);
    if (request.getParameterV2() != null && !request.getParameterV2().isEmpty()) {
        method.setQueryString(convertListToNVP(request.getParameterV2()));
    } else {
        method.setQueryString(convertMapToNVP(request.getParameter()));
    }
    method.addRequestHeader("OCS-APIREQUEST", "true");
    for (Map.Entry<String, List<String>> header : request.getHeader().entrySet()) {
        // https://stackoverflow.com/a/3097052
        method.addRequestHeader(header.getKey(), TextUtils.join(",", header.getValue()));
        if ("OCS-APIREQUEST".equalsIgnoreCase(header.getKey())) {
            throw new IllegalStateException("The 'OCS-APIREQUEST' header will be automatically added by the Nextcloud SSO Library. " + "Please remove the header before making a request");
        }
    }
    client.setFollowRedirects(request.isFollowRedirects());
    int status = client.executeMethod(method);
    // Check if status code is 2xx --> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success
    if (status >= HTTP_STATUS_CODE_OK && status < HTTP_STATUS_CODE_MULTIPLE_CHOICES) {
        return new Response(method);
    } else {
        InputStream inputStream = method.getResponseBodyAsStream();
        String total = "No response body";
        // If response body is available
        if (inputStream != null) {
            total = inputStreamToString(inputStream);
            Log_OC.e(TAG, total);
        }
        method.releaseConnection();
        throw new IllegalStateException(EXCEPTION_HTTP_REQUEST_FAILED, new IllegalStateException(String.valueOf(status), new IllegalStateException(total)));
    }
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) HttpMethodBase(org.apache.commons.httpclient.HttpMethodBase) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OwnCloudClientManager(com.owncloud.android.lib.common.OwnCloudClientManager) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) List(java.util.List) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) Map(java.util.Map)

Example 8 with OwnCloudClient

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

the class AuthenticatorAsyncTask method doInBackground.

@Override
protected RemoteOperationResult<UserInfo> doInBackground(Object... params) {
    RemoteOperationResult<UserInfo> result;
    if (params != null && params.length == 2 && mWeakContext.get() != null) {
        String url = (String) params[0];
        Context context = mWeakContext.get();
        OwnCloudCredentials credentials = (OwnCloudCredentials) params[1];
        // Client
        Uri uri = Uri.parse(url);
        NextcloudClient nextcloudClient = OwnCloudClientFactory.createNextcloudClient(uri, credentials.getUsername(), credentials.toOkHttpCredentials(), context, true);
        // Operation - get display name
        RemoteOperationResult<UserInfo> userInfoResult = new GetUserInfoRemoteOperation().execute(nextcloudClient);
        // Operation - try credentials
        if (userInfoResult.isSuccess()) {
            OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(uri, context, true);
            client.setUserId(userInfoResult.getResultData().getId());
            client.setCredentials(credentials);
            ExistenceCheckRemoteOperation operation = new ExistenceCheckRemoteOperation(ROOT_PATH, SUCCESS_IF_ABSENT);
            result = operation.execute(client);
            if (operation.wasRedirected()) {
                RedirectionPath redirectionPath = operation.getRedirectionPath();
                String permanentLocation = redirectionPath.getLastPermanentLocation();
                result.setLastPermanentLocation(permanentLocation);
            }
            result.setResultData(userInfoResult.getResultData());
        } else {
            result = userInfoResult;
        }
    } else {
        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.UNKNOWN_ERROR);
    }
    return result;
}
Also used : Context(android.content.Context) RedirectionPath(com.owncloud.android.lib.common.network.RedirectionPath) NextcloudClient(com.nextcloud.common.NextcloudClient) GetUserInfoRemoteOperation(com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation) ExistenceCheckRemoteOperation(com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) UserInfo(com.owncloud.android.lib.common.UserInfo) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) Uri(android.net.Uri) OwnCloudCredentials(com.owncloud.android.lib.common.OwnCloudCredentials)

Example 9 with OwnCloudClient

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

the class PushUtils method deleteRegistrationForAccount.

private static void deleteRegistrationForAccount(Account account) {
    Context context = MainApp.getAppContext();
    OwnCloudAccount ocAccount;
    arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
    try {
        ocAccount = new OwnCloudAccount(account, context);
        OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
        RemoteOperation unregisterAccountDeviceForNotificationsOperation = new UnregisterAccountDeviceForNotificationsOperation();
        RemoteOperationResult remoteOperationResult = unregisterAccountDeviceForNotificationsOperation.execute(mClient);
        if (remoteOperationResult.getHttpCode() == HttpStatus.SC_ACCEPTED) {
            String arbitraryValue;
            if (!TextUtils.isEmpty(arbitraryValue = arbitraryDataProvider.getValue(account.name, KEY_PUSH))) {
                Gson gson = new Gson();
                PushConfigurationState pushArbitraryData = gson.fromJson(arbitraryValue, PushConfigurationState.class);
                RemoteOperationResult unregisterResult = new UnregisterAccountDeviceForProxyOperation(context.getResources().getString(R.string.push_server_url), pushArbitraryData.getDeviceIdentifier(), pushArbitraryData.getDeviceIdentifierSignature(), pushArbitraryData.getUserPublicKey()).run();
                if (unregisterResult.isSuccess()) {
                    arbitraryDataProvider.deleteKeyForAccount(account.name, KEY_PUSH);
                }
            }
        }
    } 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");
    }
}
Also used : Context(android.content.Context) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) UnregisterAccountDeviceForProxyOperation(com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForProxyOperation) OperationCanceledException(android.accounts.OperationCanceledException) 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) PushConfigurationState(com.owncloud.android.datamodel.PushConfigurationState) UnregisterAccountDeviceForNotificationsOperation(com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForNotificationsOperation) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient)

Example 10 with OwnCloudClient

use of com.owncloud.android.lib.common.OwnCloudClient in project android by owncloud.

the class FileActivity method requestCredentialsUpdate.

/**
     * Invalidates the credentials stored for the given OC account and requests new credentials to the user,
     * navigating to {@link AuthenticatorActivity}
     *
     * @param context   Android Context needed to access the {@link AccountManager}. Received as a parameter
     *                  to make the method accessible to {@link android.content.BroadcastReceiver}s.
     * @param account   Stored OC account to request credentials update for. If null, current account will
     *                  be used.
     */
protected void requestCredentialsUpdate(Context context, Account account) {
    try {
        /// step 1 - invalidate credentials of current account
        if (account == null) {
            account = getAccount();
        }
        OwnCloudClient client;
        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
        client = (OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount));
        if (client != null) {
            OwnCloudCredentials cred = client.getCredentials();
            if (cred != null) {
                AccountManager am = AccountManager.get(context);
                if (cred.authTokenExpires()) {
                    am.invalidateAuthToken(account.type, cred.getAuthToken());
                } else {
                    am.clearPassword(account);
                }
            }
        }
        /// step 2 - request credentials to user
        Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivityForResult(updateAccountCredentials, REQUEST_CODE__UPDATE_CREDENTIALS);
    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
        showSnackMessage(getString(R.string.auth_account_does_not_exist));
    }
}
Also used : AccountUtils(com.owncloud.android.authentication.AccountUtils) AccountManager(android.accounts.AccountManager) Intent(android.content.Intent) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OwnCloudCredentials(com.owncloud.android.lib.common.OwnCloudCredentials)

Aggregations

OwnCloudClient (com.owncloud.android.lib.common.OwnCloudClient)21 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)15 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)12 Account (android.accounts.Account)9 IOException (java.io.IOException)6 Context (android.content.Context)5 OwnCloudCredentials (com.owncloud.android.lib.common.OwnCloudCredentials)5 AccountManager (android.accounts.AccountManager)4 AuthenticatorException (android.accounts.AuthenticatorException)4 OperationCanceledException (android.accounts.OperationCanceledException)4 User (com.nextcloud.client.account.User)4 ArbitraryDataProvider (com.owncloud.android.datamodel.ArbitraryDataProvider)4 OCFile (com.owncloud.android.datamodel.OCFile)4 Intent (android.content.Intent)3 Uri (android.net.Uri)3 Gson (com.google.gson.Gson)3 ClientFactory (com.nextcloud.client.network.ClientFactory)3 AccountUtils (com.owncloud.android.authentication.AccountUtils)3 FileDataStorageManager (com.owncloud.android.datamodel.FileDataStorageManager)3 PushConfigurationState (com.owncloud.android.datamodel.PushConfigurationState)3