Search in sources :

Example 11 with OperationCanceledException

use of android.accounts.OperationCanceledException in project Reader by TheKeeperOfPie.

the class Receiver method checkInbox.

public void checkInbox(final Context context, @Nullable final ArrayList<String> names) {
    final ArrayList<String> readNames;
    if (names == null) {
        readNames = new ArrayList<>();
    } else {
        readNames = names;
    }
    new Thread(new Runnable() {

        @Override
        public void run() {
            final Listing messages = new Listing();
            Account[] accounts = accountManager.getAccountsByType(Reddit.ACCOUNT_TYPE);
            for (Account account : accounts) {
                final AccountManagerFuture<Bundle> futureAuth = accountManager.getAuthToken(account, Reddit.AUTH_TOKEN_FULL_ACCESS, null, true, null, null);
                try {
                    Bundle bundle = futureAuth.getResult();
                    final String tokenAuth = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    Request request = new Request.Builder().url(Reddit.OAUTH_URL + "/message/unread").header(Reddit.USER_AGENT, Reddit.CUSTOM_USER_AGENT).header(Reddit.AUTHORIZATION, Reddit.BEARER + tokenAuth).header(Reddit.CONTENT_TYPE, Reddit.CONTENT_TYPE_APP_JSON).get().build();
                    String response = okHttpClient.newCall(request).execute().body().string();
                    Listing listing = Listing.fromJson(ComponentStatic.getObjectMapper().readValue(response, JsonNode.class));
                    messages.addChildren(listing.getChildren());
                    Log.d(TAG, account.name + " checkInbox response: " + response);
                } catch (OperationCanceledException | AuthenticatorException | IOException e) {
                    e.printStackTrace();
                }
            }
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
            Thing thing = null;
            for (int index = 0; index < messages.getChildren().size(); index++) {
                thing = messages.getChildren().get(index);
                if (readNames.contains(thing.getName())) {
                    reddit.markRead(thing.getName()).subscribe(new ObserverEmpty<>());
                    thing = null;
                } else {
                    readNames.add(thing.getName());
                    break;
                }
            }
            if (thing == null) {
                notificationManager.cancel(NOTIFICATION_INBOX);
                return;
            }
            int titleSuffixResource = messages.getChildren().size() == 1 ? R.string.new_message : R.string.new_messages;
            CharSequence content = "";
            CharSequence author = "";
            CharSequence dest = "";
            if (thing instanceof Message) {
                content = ((Message) thing).getBodyHtml();
                author = ((Message) thing).getAuthor();
                dest = ((Message) thing).getDest();
            } else if (thing instanceof Comment) {
                content = ((Comment) thing).getBodyHtml();
                author = ((Comment) thing).getAuthor();
                dest = ((Comment) thing).getDest();
            }
            Intent intentActivity = new Intent(context, ActivityMain.class);
            intentActivity.putExtra(ActivityMain.ACCOUNT, dest);
            intentActivity.putExtra(ActivityMain.NAV_ID, R.id.item_inbox);
            intentActivity.putExtra(ActivityMain.NAV_PAGE, ControllerInbox.UNREAD);
            PendingIntent pendingIntentActivity = PendingIntent.getActivity(context, 0, intentActivity, PendingIntent.FLAG_CANCEL_CURRENT);
            Intent intentRecheckInbox = new Intent(INTENT_INBOX);
            intentRecheckInbox.putExtra(READ_NAMES, readNames);
            PendingIntent pendingIntentRecheckInbox = PendingIntent.getBroadcast(context, 0, intentRecheckInbox, PendingIntent.FLAG_CANCEL_CURRENT);
            Themer themer = new Themer(context);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.app_icon_white_outline).setContentTitle(messages.getChildren().size() + " " + context.getResources().getString(titleSuffixResource)).setContentText(context.getString(R.string.expand_to_read_first_message)).setStyle(new NotificationCompat.BigTextStyle().setSummaryText(context.getString(R.string.from) + " /u/" + author).bigText(content)).setContentIntent(pendingIntentActivity).addAction(new NotificationCompat.Action(R.drawable.ic_check_white_24dp, context.getString(R.string.mark_read), pendingIntentRecheckInbox)).setDeleteIntent(pendingIntentRecheckInbox).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_EMAIL).setColor(themer.getColorPrimary()).setLights(themer.getColorPrimary(), LED_MS_ON, LED_MS_OFF);
            notificationManager.notify(NOTIFICATION_INBOX, builder.build());
        }
    }).start();
}
Also used : Account(android.accounts.Account) Message(com.winsonchiu.reader.data.reddit.Message) OperationCanceledException(android.accounts.OperationCanceledException) NotificationManagerCompat(android.support.v4.app.NotificationManagerCompat) JsonNode(com.fasterxml.jackson.databind.JsonNode) NotificationCompat(android.support.v4.app.NotificationCompat) Thing(com.winsonchiu.reader.data.reddit.Thing) Comment(com.winsonchiu.reader.data.reddit.Comment) Bundle(android.os.Bundle) Request(okhttp3.Request) AuthenticatorException(android.accounts.AuthenticatorException) Themer(com.winsonchiu.reader.theme.Themer) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) IOException(java.io.IOException) Listing(com.winsonchiu.reader.data.reddit.Listing) PendingIntent(android.app.PendingIntent)

Example 12 with OperationCanceledException

use of android.accounts.OperationCanceledException in project httpclient by pixmob.

the class AbstractAccountAuthenticator method generateAuthToken.

/**
     * Generate an authentication token. The user must grant credential access
     * when an application is using it for the first time. In this case,
     * {@link UserInteractionRequiredException} is thrown, the
     * {@link UserInteractionRequiredException#getUserIntent()} must be used
     * with <code>startActivityForResult</code> to start a system activity, in
     * order to get access to user credential. The user is free to deny
     * credential access. If credential access is granted, the next call to this
     * method should not throw any error.
     * @see UserInteractionRequiredException#getUserIntent()
     * @throws UserInteractionRequiredException
     *             if user interaction is required in order to perform
     *             authentication
     * @throws HttpClientException
     *             if authentication failed (network error, bad credentials,
     *             etc...)
     */
protected final String generateAuthToken(String authTokenType) throws HttpClientException {
    // Get an authentication token from the AccountManager:
    // this call is asynchronous, as the user may not respond immediately.
    final AccountManager am = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    final AccountManagerFuture<Bundle> authResultFuture;
    // Ice Cream Sandwich.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        authResultFuture = GetTokenLegacy.INSTANCE.get(am, account, authTokenType);
    } else {
        authResultFuture = GetTokenICS.INSTANCE.get(am, account, authTokenType);
    }
    final Bundle authResult;
    try {
        authResult = authResultFuture.getResult();
    } catch (OperationCanceledException e) {
        throw new HttpClientException("Authentication failed: canceled by user", e);
    } catch (AuthenticatorException e) {
        throw new HttpClientException("Authentication failed", e);
    } catch (IOException e) {
        throw new HttpClientException("Authentication failed: network error", e);
    }
    if (authResult == null) {
        throw new HttpClientException("Authentication failed");
    }
    final String authToken = authResult.getString(AccountManager.KEY_AUTHTOKEN);
    if (authToken == null) {
        // No authentication token found:
        // the user must allow this application to use his account.
        final Intent authPermIntent = (Intent) authResult.get(AccountManager.KEY_INTENT);
        int flags = authPermIntent.getFlags();
        flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
        authPermIntent.setFlags(flags);
        // The request is aborted: the application should retry later.
        throw new UserInteractionRequiredException(authPermIntent);
    }
    return authToken;
}
Also used : Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) AccountManager(android.accounts.AccountManager) Intent(android.content.Intent) IOException(java.io.IOException)

Example 13 with OperationCanceledException

use of android.accounts.OperationCanceledException in project newsrob by marianokamp.

the class AccountManagementUtilsImplementation method getAuthToken.

public void getAuthToken(final Activity waitingActivity, Handler handler, final IAuthenticationCallback callback, String googleAccount) {
    PL.log("AMU.getAuthToken for " + googleAccount + ".", waitingActivity);
    AccountManager accountManager = AccountManager.get(waitingActivity);
    // find the selected account
    Account selectedAccount = findAccountByGoogleAccountId(waitingActivity, accountManager, googleAccount);
    if (selectedAccount == null)
        throw new RuntimeException("No account found for " + googleAccount + ".");
    final Account selAccount = selectedAccount;
    if (false)
        accountManager.getAuthTokenByFeatures(GOOGLE_ACCOUNT_TYPE, "reader", GOOGLE_ACCOUNT, waitingActivity, new Bundle(), null, new AccountManagerCallback<Bundle>() {

            public void run(android.accounts.AccountManagerFuture<Bundle> f) {
                try {
                    Bundle b = f.getResult();
                    for (String key : b.keySet()) System.out.println("key " + key + " value " + b.getByte(key));
                    String authToken = f.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                    if (authToken == null)
                        throw new RuntimeException("AuthToken was null.");
                    callback.onAuthTokenReceived(selAccount.name, authToken);
                } catch (Exception e) {
                    e.printStackTrace();
                    if (e instanceof OperationCanceledException)
                        e = new Exception("Operation canceled by user.");
                    callback.onError(e);
                }
            }
        }, handler);
    if (true)
        accountManager.getAuthToken(selectedAccount, AUTH_TOKEN_TYPE_READER, null, waitingActivity, new AccountManagerCallback<Bundle>() {

            public void run(android.accounts.AccountManagerFuture<Bundle> f) {
                try {
                    String authToken = f.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                    if (authToken == null)
                        throw new RuntimeException("AuthToken was null.");
                    PL.log("AMU.getAuthToken for " + selAccount.name + "received token=" + authToken.substring(0, 4) + "(2).", waitingActivity);
                    callback.onAuthTokenReceived(selAccount.name, authToken);
                } catch (Exception e) {
                    e.printStackTrace();
                    if (e instanceof OperationCanceledException)
                        e = new Exception("Operation canceled by user.");
                    callback.onError(e);
                }
            }
        }, handler);
}
Also used : Account(android.accounts.Account) AccountManagerCallback(android.accounts.AccountManagerCallback) Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) AccountManager(android.accounts.AccountManager) OperationCanceledException(android.accounts.OperationCanceledException) IOException(java.io.IOException) AuthenticatorException(android.accounts.AuthenticatorException)

Example 14 with OperationCanceledException

use of android.accounts.OperationCanceledException in project Resurrection_packages_apps_Settings by ResurrectionRemix.

the class ProtectedAccountView method asyncCheckPassword.

private void asyncCheckPassword() {
    final String login = mLogin.getText().toString();
    final String password = mPassword.getText().toString();
    Account account = findIntendedAccount(login);
    if (account == null) {
        postOnCheckPasswordResult(false);
        return;
    }
    getProgressDialog().show();
    Bundle options = new Bundle();
    options.putString(AccountManager.KEY_PASSWORD, password);
    AccountManager.get(mContext).confirmCredentialsAsUser(account, options, null, /* activity */
    new AccountManagerCallback<Bundle>() {

        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                final boolean verified = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
                postOnCheckPasswordResult(verified);
            } catch (OperationCanceledException e) {
                postOnCheckPasswordResult(false);
            } catch (IOException e) {
                postOnCheckPasswordResult(false);
            } catch (AuthenticatorException e) {
                postOnCheckPasswordResult(false);
            } finally {
                mLogin.post(new Runnable() {

                    public void run() {
                        getProgressDialog().hide();
                    }
                });
            }
        }
    }, null, /* handler */
    new UserHandle(ActivityManager.getCurrentUser()));
}
Also used : Account(android.accounts.Account) Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) UserHandle(android.os.UserHandle) AuthenticatorException(android.accounts.AuthenticatorException) IOException(java.io.IOException)

Example 15 with OperationCanceledException

use of android.accounts.OperationCanceledException 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)

Aggregations

OperationCanceledException (android.accounts.OperationCanceledException)15 IOException (java.io.IOException)13 AuthenticatorException (android.accounts.AuthenticatorException)11 Bundle (android.os.Bundle)11 Account (android.accounts.Account)8 AccountManager (android.accounts.AccountManager)7 Intent (android.content.Intent)3 AccountsException (android.accounts.AccountsException)2 Cursor (android.database.Cursor)2 UserHandle (android.os.UserHandle)2 GoogleHeaders (com.google.api.client.googleapis.GoogleHeaders)2 HttpRequest (com.google.api.client.http.HttpRequest)2 AtomParser (com.google.api.client.xml.atom.AtomParser)2 AccountManagerCallback (android.accounts.AccountManagerCallback)1 PendingIntent (android.app.PendingIntent)1 ContentProviderClient (android.content.ContentProviderClient)1 ContentProviderOperation (android.content.ContentProviderOperation)1 Bitmap (android.graphics.Bitmap)1 Uri (android.net.Uri)1 RemoteException (android.os.RemoteException)1