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();
}
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;
}
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);
}
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()));
}
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();
}
}
}
Aggregations