Search in sources :

Example 21 with AuthenticatorException

use of android.accounts.AuthenticatorException in project apps-android-commons by commons-app.

the class ModificationsSyncAdapter method onPerformSync.

@Override
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
    // This code is fraught with possibilities of race conditions, but lalalalala I can't hear you!
    Cursor allModifications;
    try {
        allModifications = contentProviderClient.query(ModificationsContentProvider.BASE_URI, null, null, null, null);
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    }
    // Exit early if nothing to do
    if (allModifications == null || allModifications.getCount() == 0) {
        Timber.d("No modifications to perform");
        return;
    }
    String authCookie;
    try {
        authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false);
    } catch (OperationCanceledException | AuthenticatorException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.d("Could not authenticate :(");
        return;
    }
    if (Utils.isNullOrWhiteSpace(authCookie)) {
        Timber.d("Could not authenticate :(");
        return;
    }
    MWApi api = CommonsApplication.getInstance().getMWApi();
    api.setAuthCookie(authCookie);
    String editToken;
    ApiResult requestResult, responseResult;
    try {
        editToken = api.getEditToken();
    } catch (IOException e) {
        Timber.d("Can not retreive edit token!");
        return;
    }
    allModifications.moveToFirst();
    Timber.d("Found %d modifications to execute", allModifications.getCount());
    ContentProviderClient contributionsClient = null;
    try {
        contributionsClient = getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
        while (!allModifications.isAfterLast()) {
            ModifierSequence sequence = ModifierSequence.fromCursor(allModifications);
            sequence.setContentProviderClient(contentProviderClient);
            Contribution contrib;
            Cursor contributionCursor;
            try {
                contributionCursor = contributionsClient.query(sequence.getMediaUri(), null, null, null, null);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
            contributionCursor.moveToFirst();
            contrib = Contribution.fromCursor(contributionCursor);
            if (contrib.getState() == Contribution.STATE_COMPLETED) {
                try {
                    requestResult = api.action("query").param("prop", "revisions").param("rvprop", "timestamp|content").param("titles", contrib.getFilename()).get();
                } catch (IOException e) {
                    Timber.d("Network fuckup on modifications sync!");
                    continue;
                }
                Timber.d("Page content is %s", Utils.getStringFromDOM(requestResult.getDocument()));
                String pageContent = requestResult.getString("/api/query/pages/page/revisions/rev");
                String processedPageContent = sequence.executeModifications(contrib.getFilename(), pageContent);
                try {
                    responseResult = api.action("edit").param("title", contrib.getFilename()).param("token", editToken).param("text", processedPageContent).param("summary", sequence.getEditSummary()).post();
                } catch (IOException e) {
                    Timber.d("Network fuckup on modifications sync!");
                    continue;
                }
                Timber.d("Response is %s", Utils.getStringFromDOM(responseResult.getDocument()));
                String result = responseResult.getString("/api/edit/@result");
                if (!result.equals("Success")) {
                    // FIXME: Log this somewhere else
                    Timber.d("Non success result! %s", result);
                } else {
                    sequence.delete();
                }
            }
            allModifications.moveToNext();
        }
    } finally {
        if (contributionsClient != null) {
            contributionsClient.release();
        }
    }
}
Also used : OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) IOException(java.io.IOException) Cursor(android.database.Cursor) ApiResult(org.mediawiki.api.ApiResult) MWApi(fr.free.nrw.commons.MWApi) RemoteException(android.os.RemoteException) ContentProviderClient(android.content.ContentProviderClient) Contribution(fr.free.nrw.commons.contributions.Contribution)

Example 22 with AuthenticatorException

use of android.accounts.AuthenticatorException in project android by nextcloud.

the class ConnectivityUtils method isInternetWalled.

public static boolean isInternetWalled(Context context) {
    if (isOnlineWithWifi(context)) {
        try {
            Account account = AccountUtils.getCurrentOwnCloudAccount(context);
            if (account != null) {
                OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
                OwnCloudVersion serverVersion = AccountUtils.getServerVersion(account);
                String url;
                if (serverVersion.compareTo(OwnCloudVersion.nextcloud_13) > 0) {
                    url = ocAccount.getBaseUri() + "/index.php/204";
                } else {
                    url = ocAccount.getBaseUri() + "/status.php";
                }
                GetMethod get = new GetMethod(url);
                OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(account, context);
                int status = client.executeMethod(get);
                if (serverVersion.compareTo(OwnCloudVersion.nextcloud_13) > 0) {
                    return !(status == 204 && (get.getResponseContentLength() == -1 || get.getResponseContentLength() == 0));
                } else {
                    if (status == 200) {
                        try {
                            // try parsing json to verify response
                            // check if json contains maintenance and it should be false
                            String json = get.getResponseBodyAsString();
                            return new JSONObject(json).getBoolean("maintenance");
                        } catch (Exception e) {
                            return true;
                        }
                    } else {
                        return true;
                    }
                }
            }
        } catch (IOException e) {
            Log_OC.e(TAG, "Error checking internet connection", e);
        } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
            Log_OC.e(TAG, "Account not found", e);
        } catch (OperationCanceledException e) {
            Log_OC.e(TAG, e.getMessage());
        } catch (AuthenticatorException e) {
            Log_OC.e(TAG, e.getMessage());
        }
    } else if (!Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY)) {
        return false;
    }
    return true;
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OperationCanceledException(android.accounts.OperationCanceledException) AccountUtils(com.owncloud.android.authentication.AccountUtils) AuthenticatorException(android.accounts.AuthenticatorException) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) IOException(java.io.IOException) OperationCanceledException(android.accounts.OperationCanceledException) IOException(java.io.IOException) AuthenticatorException(android.accounts.AuthenticatorException) JSONObject(org.json.JSONObject) GetMethod(org.apache.commons.httpclient.methods.GetMethod) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) OwnCloudVersion(com.owncloud.android.lib.resources.status.OwnCloudVersion)

Example 23 with AuthenticatorException

use of android.accounts.AuthenticatorException 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 24 with AuthenticatorException

use of android.accounts.AuthenticatorException in project VirtualApp by asLody.

the class ChooseTypeAndAccountActivity method run.

@Override
public void run(final AccountManagerFuture<Bundle> accountManagerFuture) {
    try {
        final Bundle accountManagerResult = accountManagerFuture.getResult();
        final Intent intent = accountManagerResult.getParcelable(AccountManager.KEY_INTENT);
        if (intent != null) {
            mPendingRequest = REQUEST_ADD_ACCOUNT;
            mExistingAccounts = VAccountManager.get().getAccounts(mCallingUserId, null);
            intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent, REQUEST_ADD_ACCOUNT);
            return;
        }
    } catch (OperationCanceledException e) {
        setResult(Activity.RESULT_CANCELED);
        finish();
        return;
    } catch (IOException e) {
    } catch (AuthenticatorException e) {
    }
    Bundle bundle = new Bundle();
    bundle.putString(AccountManager.KEY_ERROR_MESSAGE, "error communicating with server");
    setResult(Activity.RESULT_OK, new Intent().putExtras(bundle));
    finish();
}
Also used : Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) Intent(android.content.Intent) IOException(java.io.IOException)

Example 25 with AuthenticatorException

use of android.accounts.AuthenticatorException in project android by owncloud.

the class PrepareVideoPlayerAsyncTask method buildHttpDataSourceFactory.

/**
 * Returns a new HttpDataSource factory.
 *
 * @param bandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
 *                       DataSource factory.
 * @return A new HttpDataSource factory.
 */
private HttpDataSource.Factory buildHttpDataSourceFactory(DefaultBandwidthMeter bandwidthMeter, OCFile file, Account account) {
    if (file.isDown()) {
        return new DefaultHttpDataSourceFactory(MainApp.Companion.getUserAgent(), bandwidthMeter);
    } else {
        try {
            OwnCloudCredentials credentials = AccountUtils.getCredentialsForAccount(MainApp.Companion.getAppContext(), account);
            String login = credentials.getUsername();
            String password = credentials.getAuthToken();
            Map<String, String> params = new HashMap<String, String>(1);
            if (credentials instanceof OwnCloudBasicCredentials) {
                // Basic auth
                String cred = login + ":" + password;
                String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.URL_SAFE);
                params.put("Authorization", auth);
            } else if (credentials instanceof OwnCloudBearerCredentials) {
                // OAuth
                String bearerToken = credentials.getAuthToken();
                String auth = "Bearer " + bearerToken;
                params.put("Authorization", auth);
            }
            return new CustomHttpDataSourceFactory(MainApp.Companion.getUserAgent(), bandwidthMeter, params);
        } catch (AuthenticatorException | IOException | OperationCanceledException e) {
            Timber.e(e);
        }
    }
    return null;
}
Also used : OwnCloudBearerCredentials(com.owncloud.android.lib.common.authentication.OwnCloudBearerCredentials) OwnCloudBasicCredentials(com.owncloud.android.lib.common.authentication.OwnCloudBasicCredentials) DefaultHttpDataSourceFactory(com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory) HashMap(java.util.HashMap) OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) IOException(java.io.IOException) OwnCloudCredentials(com.owncloud.android.lib.common.authentication.OwnCloudCredentials)

Aggregations

AuthenticatorException (android.accounts.AuthenticatorException)28 OperationCanceledException (android.accounts.OperationCanceledException)22 IOException (java.io.IOException)22 Bundle (android.os.Bundle)15 Account (android.accounts.Account)13 Intent (android.content.Intent)7 AccountManager (android.accounts.AccountManager)6 Context (android.content.Context)5 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)5 OwnCloudClient (com.owncloud.android.lib.common.OwnCloudClient)4 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)4 Test (org.junit.Test)4 Gson (com.google.gson.Gson)3 User (com.nextcloud.client.account.User)3 AccountUtils (com.owncloud.android.authentication.AccountUtils)3 ArbitraryDataProvider (com.owncloud.android.datamodel.ArbitraryDataProvider)3 PushConfigurationState (com.owncloud.android.datamodel.PushConfigurationState)3 ActivityNotFoundException (android.content.ActivityNotFoundException)2 UserHandle (android.os.UserHandle)2 GoogleHeaders (com.google.api.client.googleapis.GoogleHeaders)2