XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.annotation.TargetApi;
   6import android.app.ActionBar;
   7import android.app.Activity;
   8import android.app.AlertDialog;
   9import android.app.AlertDialog.Builder;
  10import android.app.PendingIntent;
  11import android.content.ActivityNotFoundException;
  12import android.content.ClipData;
  13import android.content.ClipboardManager;
  14import android.content.ComponentName;
  15import android.content.Context;
  16import android.content.DialogInterface;
  17import android.content.Intent;
  18import android.content.IntentSender.SendIntentException;
  19import android.content.ServiceConnection;
  20import android.content.SharedPreferences;
  21import android.content.pm.PackageManager;
  22import android.content.pm.ResolveInfo;
  23import android.content.res.Resources;
  24import android.content.res.TypedArray;
  25import android.graphics.Bitmap;
  26import android.graphics.Color;
  27import android.graphics.Point;
  28import android.graphics.drawable.BitmapDrawable;
  29import android.graphics.drawable.Drawable;
  30import android.net.ConnectivityManager;
  31import android.net.Uri;
  32import android.os.AsyncTask;
  33import android.os.Build;
  34import android.os.Bundle;
  35import android.os.Handler;
  36import android.os.IBinder;
  37import android.os.PowerManager;
  38import android.os.SystemClock;
  39import android.preference.PreferenceManager;
  40import android.support.v4.content.ContextCompat;
  41import android.text.InputType;
  42import android.util.DisplayMetrics;
  43import android.util.Pair;
  44import android.view.MenuItem;
  45import android.view.View;
  46import android.view.inputmethod.InputMethodManager;
  47import android.widget.EditText;
  48import android.widget.ImageView;
  49import android.widget.Toast;
  50
  51import net.java.otr4j.session.SessionID;
  52
  53import java.io.FileNotFoundException;
  54import java.lang.ref.WeakReference;
  55import java.util.ArrayList;
  56import java.util.Collections;
  57import java.util.List;
  58import java.util.Map;
  59import java.util.concurrent.RejectedExecutionException;
  60import java.util.concurrent.atomic.AtomicInteger;
  61
  62import eu.siacs.conversations.Config;
  63import eu.siacs.conversations.R;
  64import eu.siacs.conversations.crypto.PgpEngine;
  65import eu.siacs.conversations.entities.Account;
  66import eu.siacs.conversations.entities.Contact;
  67import eu.siacs.conversations.entities.Conversation;
  68import eu.siacs.conversations.entities.Message;
  69import eu.siacs.conversations.entities.MucOptions;
  70import eu.siacs.conversations.entities.Presences;
  71import eu.siacs.conversations.services.AvatarService;
  72import eu.siacs.conversations.services.BarcodeProvider;
  73import eu.siacs.conversations.services.XmppConnectionService;
  74import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  75import eu.siacs.conversations.utils.CryptoHelper;
  76import eu.siacs.conversations.utils.ExceptionHelper;
  77import eu.siacs.conversations.utils.UIHelper;
  78import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  79import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  80import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  81import eu.siacs.conversations.xmpp.jid.Jid;
  82
  83public abstract class XmppActivity extends Activity {
  84
  85	public static final String EXTRA_ACCOUNT = "account";
  86	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
  87	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
  88	protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
  89	protected static final int REQUEST_BATTERY_OP = 0x13849ff;
  90	public XmppConnectionService xmppConnectionService;
  91	public boolean xmppConnectionServiceBound = false;
  92	protected boolean registeredListeners = false;
  93
  94	protected int mPrimaryTextColor;
  95	protected int mSecondaryTextColor;
  96	protected int mTertiaryTextColor;
  97	protected int mPrimaryBackgroundColor;
  98	protected int mSecondaryBackgroundColor;
  99	protected int mColorRed;
 100	protected int mColorOrange;
 101	protected int mColorGreen;
 102	protected int mPrimaryColor;
 103
 104	protected boolean mUseSubject = true;
 105	protected int mTheme;
 106	protected boolean mUsingEnterKey = false;
 107	protected Toast mToast;
 108	protected Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
 109	protected ConferenceInvite mPendingConferenceInvite = null;
 110	protected ServiceConnection mConnection = new ServiceConnection() {
 111
 112		@Override
 113		public void onServiceConnected(ComponentName className, IBinder service) {
 114			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 115			xmppConnectionService = binder.getService();
 116			xmppConnectionServiceBound = true;
 117			if (!registeredListeners && shouldRegisterListeners()) {
 118				registerListeners();
 119				registeredListeners = true;
 120			}
 121			onBackendConnected();
 122		}
 123
 124		@Override
 125		public void onServiceDisconnected(ComponentName arg0) {
 126			xmppConnectionServiceBound = false;
 127		}
 128	};
 129	private DisplayMetrics metrics;
 130	private long mLastUiRefresh = 0;
 131	private Handler mRefreshUiHandler = new Handler();
 132	private Runnable mRefreshUiRunnable = () -> {
 133		mLastUiRefresh = SystemClock.elapsedRealtime();
 134		refreshUiReal();
 135	};
 136	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 137		@Override
 138		public void success(final Conversation conversation) {
 139			runOnUiThread(() -> {
 140				switchToConversation(conversation);
 141				hideToast();
 142			});
 143		}
 144
 145		@Override
 146		public void error(final int errorCode, Conversation object) {
 147			runOnUiThread(() -> replaceToast(getString(errorCode)));
 148		}
 149
 150		@Override
 151		public void userInputRequried(PendingIntent pi, Conversation object) {
 152
 153		}
 154	};
 155
 156	public static boolean cancelPotentialWork(Message message, ImageView imageView) {
 157		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
 158
 159		if (bitmapWorkerTask != null) {
 160			final Message oldMessage = bitmapWorkerTask.message;
 161			if (oldMessage == null || message != oldMessage) {
 162				bitmapWorkerTask.cancel(true);
 163			} else {
 164				return false;
 165			}
 166		}
 167		return true;
 168	}
 169
 170	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
 171		if (imageView != null) {
 172			final Drawable drawable = imageView.getDrawable();
 173			if (drawable instanceof AsyncDrawable) {
 174				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
 175				return asyncDrawable.getBitmapWorkerTask();
 176			}
 177		}
 178		return null;
 179	}
 180
 181	protected void hideToast() {
 182		if (mToast != null) {
 183			mToast.cancel();
 184		}
 185	}
 186
 187	protected void replaceToast(String msg) {
 188		replaceToast(msg, true);
 189	}
 190
 191	protected void replaceToast(String msg, boolean showlong) {
 192		hideToast();
 193		mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
 194		mToast.show();
 195	}
 196
 197	protected final void refreshUi() {
 198		final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 199		if (diff > Config.REFRESH_UI_INTERVAL) {
 200			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 201			runOnUiThread(mRefreshUiRunnable);
 202		} else {
 203			final long next = Config.REFRESH_UI_INTERVAL - diff;
 204			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 205			mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
 206		}
 207	}
 208
 209	abstract protected void refreshUiReal();
 210
 211	@Override
 212	protected void onStart() {
 213		super.onStart();
 214		if (!xmppConnectionServiceBound) {
 215			connectToBackend();
 216		} else {
 217			if (!registeredListeners) {
 218				this.registerListeners();
 219				this.registeredListeners = true;
 220			}
 221			this.onBackendConnected();
 222		}
 223	}
 224
 225	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
 226	protected boolean shouldRegisterListeners() {
 227		if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
 228			return !isDestroyed() && !isFinishing();
 229		} else {
 230			return !isFinishing();
 231		}
 232	}
 233
 234	public void connectToBackend() {
 235		Intent intent = new Intent(this, XmppConnectionService.class);
 236		intent.setAction("ui");
 237		startService(intent);
 238		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 239	}
 240
 241	@Override
 242	protected void onStop() {
 243		super.onStop();
 244		if (xmppConnectionServiceBound) {
 245			if (registeredListeners) {
 246				this.unregisterListeners();
 247				this.registeredListeners = false;
 248			}
 249			unbindService(mConnection);
 250			xmppConnectionServiceBound = false;
 251		}
 252	}
 253
 254	protected void hideKeyboard() {
 255		final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 256		View focus = getCurrentFocus();
 257		if (focus != null && inputManager != null) {
 258			inputManager.hideSoftInputFromWindow(focus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
 259		}
 260	}
 261
 262	public boolean hasPgp() {
 263		return xmppConnectionService.getPgpEngine() != null;
 264	}
 265
 266	public void showInstallPgpDialog() {
 267		Builder builder = new AlertDialog.Builder(this);
 268		builder.setTitle(getString(R.string.openkeychain_required));
 269		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 270		builder.setMessage(getText(R.string.openkeychain_required_long));
 271		builder.setNegativeButton(getString(R.string.cancel), null);
 272		builder.setNeutralButton(getString(R.string.restart),
 273				(dialog, which) -> {
 274					if (xmppConnectionServiceBound) {
 275						unbindService(mConnection);
 276						xmppConnectionServiceBound = false;
 277					}
 278					stopService(new Intent(XmppActivity.this,
 279							XmppConnectionService.class));
 280					finish();
 281				});
 282		builder.setPositiveButton(getString(R.string.install),
 283				(dialog, which) -> {
 284					Uri uri = Uri
 285							.parse("market://details?id=org.sufficientlysecure.keychain");
 286					Intent marketIntent = new Intent(Intent.ACTION_VIEW,
 287							uri);
 288					PackageManager manager = getApplicationContext()
 289							.getPackageManager();
 290					List<ResolveInfo> infos = manager
 291							.queryIntentActivities(marketIntent, 0);
 292					if (infos.size() > 0) {
 293						startActivity(marketIntent);
 294					} else {
 295						uri = Uri.parse("http://www.openkeychain.org/");
 296						Intent browserIntent = new Intent(
 297								Intent.ACTION_VIEW, uri);
 298						startActivity(browserIntent);
 299					}
 300					finish();
 301				});
 302		builder.create().show();
 303	}
 304
 305	abstract void onBackendConnected();
 306
 307	protected void registerListeners() {
 308		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 309			this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 310		}
 311		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 312			this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 313		}
 314		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 315			this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 316		}
 317		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 318			this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 319		}
 320		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 321			this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 322		}
 323		if (this instanceof OnUpdateBlocklist) {
 324			this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 325		}
 326		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 327			this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 328		}
 329		if (this instanceof OnKeyStatusUpdated) {
 330			this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 331		}
 332	}
 333
 334	protected void unregisterListeners() {
 335		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 336			this.xmppConnectionService.removeOnConversationListChangedListener();
 337		}
 338		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 339			this.xmppConnectionService.removeOnAccountListChangedListener();
 340		}
 341		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 342			this.xmppConnectionService.removeOnCaptchaRequestedListener();
 343		}
 344		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 345			this.xmppConnectionService.removeOnRosterUpdateListener();
 346		}
 347		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 348			this.xmppConnectionService.removeOnMucRosterUpdateListener();
 349		}
 350		if (this instanceof OnUpdateBlocklist) {
 351			this.xmppConnectionService.removeOnUpdateBlocklistListener();
 352		}
 353		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 354			this.xmppConnectionService.removeOnShowErrorToastListener();
 355		}
 356		if (this instanceof OnKeyStatusUpdated) {
 357			this.xmppConnectionService.removeOnNewKeysAvailableListener();
 358		}
 359	}
 360
 361	@Override
 362	public boolean onOptionsItemSelected(final MenuItem item) {
 363		switch (item.getItemId()) {
 364			case R.id.action_settings:
 365				startActivity(new Intent(this, SettingsActivity.class));
 366				break;
 367			case R.id.action_accounts:
 368				startActivity(new Intent(this, ManageAccountActivity.class));
 369				break;
 370			case android.R.id.home:
 371				finish();
 372				break;
 373			case R.id.action_show_qr_code:
 374				showQrCode();
 375				break;
 376		}
 377		return super.onOptionsItemSelected(item);
 378	}
 379
 380	@Override
 381	protected void onCreate(Bundle savedInstanceState) {
 382		super.onCreate(savedInstanceState);
 383		metrics = getResources().getDisplayMetrics();
 384		ExceptionHelper.init(getApplicationContext());
 385
 386		mPrimaryTextColor = ContextCompat.getColor(this, R.color.black87);
 387		mSecondaryTextColor = ContextCompat.getColor(this, R.color.black54);
 388		mTertiaryTextColor = ContextCompat.getColor(this, R.color.black12);
 389		mColorRed = ContextCompat.getColor(this, R.color.red800);
 390		mColorOrange = ContextCompat.getColor(this, R.color.orange500);
 391		mColorGreen = ContextCompat.getColor(this, R.color.green500);
 392		mPrimaryColor = ContextCompat.getColor(this, R.color.primary500);
 393		mPrimaryBackgroundColor = ContextCompat.getColor(this, R.color.grey50);
 394		mSecondaryBackgroundColor = ContextCompat.getColor(this, R.color.grey200);
 395
 396		this.mTheme = findTheme();
 397		if (isDarkTheme()) {
 398			mPrimaryTextColor = ContextCompat.getColor(this, R.color.white);
 399			mSecondaryTextColor = ContextCompat.getColor(this, R.color.white70);
 400			mTertiaryTextColor = ContextCompat.getColor(this, R.color.white12);
 401			mPrimaryBackgroundColor = ContextCompat.getColor(this, R.color.grey800);
 402			mSecondaryBackgroundColor = ContextCompat.getColor(this, R.color.grey900);
 403		}
 404		setTheme(this.mTheme);
 405
 406		this.mUsingEnterKey = usingEnterKey();
 407		mUseSubject = getPreferences().getBoolean("use_subject", getResources().getBoolean(R.bool.use_subject));
 408		final ActionBar ab = getActionBar();
 409		if (ab != null) {
 410			ab.setDisplayHomeAsUpEnabled(true);
 411		}
 412	}
 413
 414	public boolean isDarkTheme() {
 415		return this.mTheme == R.style.ConversationsTheme_Dark || this.mTheme == R.style.ConversationsTheme_Dark_LargerText;
 416	}
 417
 418	public int getThemeResource(int r_attr_name, int r_drawable_def) {
 419		int[] attrs = {r_attr_name};
 420		TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 421
 422		int res = ta.getResourceId(0, r_drawable_def);
 423		ta.recycle();
 424
 425		return res;
 426	}
 427
 428	protected boolean isOptimizingBattery() {
 429		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 430			final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 431			return pm != null
 432					&& !pm.isIgnoringBatteryOptimizations(getPackageName());
 433		} else {
 434			return false;
 435		}
 436	}
 437
 438	protected boolean isAffectedByDataSaver() {
 439		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 440			final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 441			return cm != null
 442					&& cm.isActiveNetworkMetered()
 443					&& cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 444		} else {
 445			return false;
 446		}
 447	}
 448
 449	protected boolean usingEnterKey() {
 450		return getPreferences().getBoolean("display_enter_key", getResources().getBoolean(R.bool.display_enter_key));
 451	}
 452
 453	protected SharedPreferences getPreferences() {
 454		return PreferenceManager
 455				.getDefaultSharedPreferences(getApplicationContext());
 456	}
 457
 458	public boolean useSubjectToIdentifyConference() {
 459		return mUseSubject;
 460	}
 461
 462	public void switchToConversation(Conversation conversation) {
 463		switchToConversation(conversation, null, false);
 464	}
 465
 466	public void switchToConversation(Conversation conversation, String text,
 467	                                 boolean newTask) {
 468		switchToConversation(conversation, text, null, false, newTask);
 469	}
 470
 471	public void highlightInMuc(Conversation conversation, String nick) {
 472		switchToConversation(conversation, null, nick, false, false);
 473	}
 474
 475	public void privateMsgInMuc(Conversation conversation, String nick) {
 476		switchToConversation(conversation, null, nick, true, false);
 477	}
 478
 479	private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
 480		Intent viewConversationIntent = new Intent(this,
 481				ConversationActivity.class);
 482		viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
 483		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
 484				conversation.getUuid());
 485		if (text != null) {
 486			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
 487		}
 488		if (nick != null) {
 489			viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
 490			viewConversationIntent.putExtra(ConversationActivity.PRIVATE_MESSAGE, pm);
 491		}
 492		if (newTask) {
 493			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 494					| Intent.FLAG_ACTIVITY_NEW_TASK
 495					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
 496		} else {
 497			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 498					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
 499		}
 500		startActivity(viewConversationIntent);
 501		finish();
 502	}
 503
 504	public void switchToContactDetails(Contact contact) {
 505		switchToContactDetails(contact, null);
 506	}
 507
 508	public void switchToContactDetails(Contact contact, String messageFingerprint) {
 509		Intent intent = new Intent(this, ContactDetailsActivity.class);
 510		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 511		intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().toBareJid().toString());
 512		intent.putExtra("contact", contact.getJid().toString());
 513		intent.putExtra("fingerprint", messageFingerprint);
 514		startActivity(intent);
 515	}
 516
 517	public void switchToAccount(Account account) {
 518		switchToAccount(account, false);
 519	}
 520
 521	public void switchToAccount(Account account, boolean init) {
 522		Intent intent = new Intent(this, EditAccountActivity.class);
 523		intent.putExtra("jid", account.getJid().toBareJid().toString());
 524		intent.putExtra("init", init);
 525		startActivity(intent);
 526	}
 527
 528	protected void delegateUriPermissionsToService(Uri uri) {
 529		Intent intent = new Intent(this,XmppConnectionService.class);
 530		intent.setAction(Intent.ACTION_SEND);
 531		intent.setData(uri);
 532		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 533		startService(intent);
 534	}
 535
 536	protected void inviteToConversation(Conversation conversation) {
 537		Intent intent = new Intent(getApplicationContext(),
 538				ChooseContactActivity.class);
 539		List<String> contacts = new ArrayList<>();
 540		if (conversation.getMode() == Conversation.MODE_MULTI) {
 541			for (MucOptions.User user : conversation.getMucOptions().getUsers(false)) {
 542				Jid jid = user.getRealJid();
 543				if (jid != null) {
 544					contacts.add(jid.toBareJid().toString());
 545				}
 546			}
 547		} else {
 548			contacts.add(conversation.getJid().toBareJid().toString());
 549		}
 550		intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
 551		intent.putExtra("conversation", conversation.getUuid());
 552		intent.putExtra("multiple", true);
 553		intent.putExtra("show_enter_jid", true);
 554		intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 555		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
 556	}
 557
 558	protected void announcePgp(Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 559		if (account.getPgpId() == 0) {
 560			choosePgpSignId(account);
 561		} else {
 562			String status = null;
 563			if (manuallyChangePresence()) {
 564				status = account.getPresenceStatusMessage();
 565			}
 566			if (status == null) {
 567				status = "";
 568			}
 569			xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<Account>() {
 570
 571				@Override
 572				public void userInputRequried(PendingIntent pi, Account account) {
 573					try {
 574						startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 575					} catch (final SendIntentException ignored) {
 576					}
 577				}
 578
 579				@Override
 580				public void success(Account account) {
 581					xmppConnectionService.databaseBackend.updateAccount(account);
 582					xmppConnectionService.sendPresence(account);
 583					if (conversation != null) {
 584						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 585						xmppConnectionService.updateConversation(conversation);
 586						refreshUi();
 587					}
 588					if (onSuccess != null) {
 589						runOnUiThread(onSuccess);
 590					}
 591				}
 592
 593				@Override
 594				public void error(int error, Account account) {
 595					if (error == 0 && account != null) {
 596						account.setPgpSignId(0);
 597						account.unsetPgpSignature();
 598						xmppConnectionService.databaseBackend.updateAccount(account);
 599						choosePgpSignId(account);
 600					} else {
 601						displayErrorDialog(error);
 602					}
 603				}
 604			});
 605		}
 606	}
 607
 608	protected boolean noAccountUsesPgp() {
 609		if (!hasPgp()) {
 610			return true;
 611		}
 612		for (Account account : xmppConnectionService.getAccounts()) {
 613			if (account.getPgpId() != 0) {
 614				return false;
 615			}
 616		}
 617		return true;
 618	}
 619
 620	@SuppressWarnings("deprecation")
 621	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 622	protected void setListItemBackgroundOnView(View view) {
 623		int sdk = android.os.Build.VERSION.SDK_INT;
 624		if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 625			view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 626		} else {
 627			view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 628		}
 629	}
 630
 631	protected void choosePgpSignId(Account account) {
 632		xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 633			@Override
 634			public void success(Account account1) {
 635			}
 636
 637			@Override
 638			public void error(int errorCode, Account object) {
 639
 640			}
 641
 642			@Override
 643			public void userInputRequried(PendingIntent pi, Account object) {
 644				try {
 645					startIntentSenderForResult(pi.getIntentSender(),
 646							REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 647				} catch (final SendIntentException ignored) {
 648				}
 649			}
 650		});
 651	}
 652
 653	protected void displayErrorDialog(final int errorCode) {
 654		runOnUiThread(() -> {
 655			Builder builder = new Builder(XmppActivity.this);
 656			builder.setIconAttribute(android.R.attr.alertDialogIcon);
 657			builder.setTitle(getString(R.string.error));
 658			builder.setMessage(errorCode);
 659			builder.setNeutralButton(R.string.accept, null);
 660			builder.create().show();
 661		});
 662
 663	}
 664
 665	protected void showAddToRosterDialog(final Conversation conversation) {
 666		showAddToRosterDialog(conversation.getContact());
 667	}
 668
 669	protected void showAddToRosterDialog(final Contact contact) {
 670		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 671		builder.setTitle(contact.getJid().toString());
 672		builder.setMessage(getString(R.string.not_in_roster));
 673		builder.setNegativeButton(getString(R.string.cancel), null);
 674		builder.setPositiveButton(getString(R.string.add_contact),
 675				(dialog, which) -> {
 676					final Jid jid = contact.getJid();
 677					Account account = contact.getAccount();
 678					Contact contact1 = account.getRoster().getContact(jid);
 679					xmppConnectionService.createContact(contact1);
 680				});
 681		builder.create().show();
 682	}
 683
 684	private void showAskForPresenceDialog(final Contact contact) {
 685		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 686		builder.setTitle(contact.getJid().toString());
 687		builder.setMessage(R.string.request_presence_updates);
 688		builder.setNegativeButton(R.string.cancel, null);
 689		builder.setPositiveButton(R.string.request_now,
 690				(dialog, which) -> {
 691					if (xmppConnectionServiceBound) {
 692						xmppConnectionService.sendPresencePacket(contact
 693								.getAccount(), xmppConnectionService
 694								.getPresenceGenerator()
 695								.requestPresenceUpdatesFrom(contact));
 696					}
 697				});
 698		builder.create().show();
 699	}
 700
 701	private void warnMutalPresenceSubscription(final Conversation conversation,
 702	                                           final OnPresenceSelected listener) {
 703		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 704		builder.setTitle(conversation.getContact().getJid().toString());
 705		builder.setMessage(R.string.without_mutual_presence_updates);
 706		builder.setNegativeButton(R.string.cancel, null);
 707		builder.setPositiveButton(R.string.ignore, (dialog, which) -> {
 708			conversation.setNextCounterpart(null);
 709			if (listener != null) {
 710				listener.onPresenceSelected();
 711			}
 712		});
 713		builder.create().show();
 714	}
 715
 716	protected void quickEdit(String previousValue, int hint, OnValueEdited callback) {
 717		quickEdit(previousValue, callback, hint, false);
 718	}
 719
 720	protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 721		quickEdit(previousValue, callback, R.string.password, true);
 722	}
 723
 724	@SuppressLint("InflateParams")
 725	private void quickEdit(final String previousValue,
 726	                       final OnValueEdited callback,
 727	                       final int hint,
 728	                       boolean password) {
 729		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 730		View view = getLayoutInflater().inflate(R.layout.quickedit, null);
 731		final EditText editor = view.findViewById(R.id.editor);
 732		if (password) {
 733			editor.setInputType(InputType.TYPE_CLASS_TEXT
 734					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
 735		}
 736		builder.setPositiveButton(R.string.accept, null);
 737		if (hint != 0) {
 738			editor.setHint(hint);
 739		}
 740		editor.requestFocus();
 741		editor.setText("");
 742		if (previousValue != null) {
 743			editor.getText().append(previousValue);
 744		}
 745		builder.setView(view);
 746		builder.setNegativeButton(R.string.cancel, null);
 747		final AlertDialog dialog = builder.create();
 748		dialog.show();
 749		View.OnClickListener clickListener = v -> {
 750			String value = editor.getText().toString();
 751			if (!value.equals(previousValue) && value.trim().length() > 0) {
 752				String error = callback.onValueEdited(value);
 753				if (error != null) {
 754					editor.setError(error);
 755					return;
 756				}
 757			}
 758			dialog.dismiss();
 759		};
 760		dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 761	}
 762
 763	public boolean hasStoragePermission(int requestCode) {
 764		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 765			if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 766				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 767				return false;
 768			} else {
 769				return true;
 770			}
 771		} else {
 772			return true;
 773		}
 774	}
 775
 776	public void selectPresence(final Conversation conversation,
 777	                           final OnPresenceSelected listener) {
 778		final Contact contact = conversation.getContact();
 779		if (conversation.hasValidOtrSession()) {
 780			SessionID id = conversation.getOtrSession().getSessionID();
 781			Jid jid;
 782			try {
 783				jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
 784			} catch (InvalidJidException e) {
 785				jid = null;
 786			}
 787			conversation.setNextCounterpart(jid);
 788			listener.onPresenceSelected();
 789		} else if (!contact.showInRoster()) {
 790			showAddToRosterDialog(conversation);
 791		} else {
 792			final Presences presences = contact.getPresences();
 793			if (presences.size() == 0) {
 794				if (!contact.getOption(Contact.Options.TO)
 795						&& !contact.getOption(Contact.Options.ASKING)
 796						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 797					showAskForPresenceDialog(contact);
 798				} else if (!contact.getOption(Contact.Options.TO)
 799						|| !contact.getOption(Contact.Options.FROM)) {
 800					warnMutalPresenceSubscription(conversation, listener);
 801				} else {
 802					conversation.setNextCounterpart(null);
 803					listener.onPresenceSelected();
 804				}
 805			} else if (presences.size() == 1) {
 806				String presence = presences.toResourceArray()[0];
 807				try {
 808					conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
 809				} catch (InvalidJidException e) {
 810					conversation.setNextCounterpart(null);
 811				}
 812				listener.onPresenceSelected();
 813			} else {
 814				showPresenceSelectionDialog(presences, conversation, listener);
 815			}
 816		}
 817	}
 818
 819	private void showPresenceSelectionDialog(Presences presences, final Conversation conversation, final OnPresenceSelected listener) {
 820		final Contact contact = conversation.getContact();
 821		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 822		builder.setTitle(getString(R.string.choose_presence));
 823		final String[] resourceArray = presences.toResourceArray();
 824		Pair<Map<String, String>, Map<String, String>> typeAndName = presences.toTypeAndNameMap();
 825		final Map<String, String> resourceTypeMap = typeAndName.first;
 826		final Map<String, String> resourceNameMap = typeAndName.second;
 827		final String[] readableIdentities = new String[resourceArray.length];
 828		final AtomicInteger selectedResource = new AtomicInteger(0);
 829		for (int i = 0; i < resourceArray.length; ++i) {
 830			String resource = resourceArray[i];
 831			if (resource.equals(contact.getLastResource())) {
 832				selectedResource.set(i);
 833			}
 834			String type = resourceTypeMap.get(resource);
 835			String name = resourceNameMap.get(resource);
 836			if (type != null) {
 837				if (Collections.frequency(resourceTypeMap.values(), type) == 1) {
 838					readableIdentities[i] = UIHelper.tranlasteType(this, type);
 839				} else if (name != null) {
 840					if (Collections.frequency(resourceNameMap.values(), name) == 1
 841							|| CryptoHelper.UUID_PATTERN.matcher(resource).matches()) {
 842						readableIdentities[i] = UIHelper.tranlasteType(this, type) + "  (" + name + ")";
 843					} else {
 844						readableIdentities[i] = UIHelper.tranlasteType(this, type) + " (" + name + " / " + resource + ")";
 845					}
 846				} else {
 847					readableIdentities[i] = UIHelper.tranlasteType(this, type) + " (" + resource + ")";
 848				}
 849			} else {
 850				readableIdentities[i] = resource;
 851			}
 852		}
 853		builder.setSingleChoiceItems(readableIdentities,
 854				selectedResource.get(),
 855				(dialog, which) -> selectedResource.set(which));
 856		builder.setNegativeButton(R.string.cancel, null);
 857		builder.setPositiveButton(R.string.ok, (dialog, which) -> {
 858			try {
 859				Jid next = Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), resourceArray[selectedResource.get()]);
 860				conversation.setNextCounterpart(next);
 861			} catch (InvalidJidException e) {
 862				conversation.setNextCounterpart(null);
 863			}
 864			listener.onPresenceSelected();
 865		});
 866		builder.create().show();
 867	}
 868
 869	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 870		super.onActivityResult(requestCode, resultCode, data);
 871		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 872			mPendingConferenceInvite = ConferenceInvite.parse(data);
 873			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 874				if (mPendingConferenceInvite.execute(this)) {
 875					mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 876					mToast.show();
 877				}
 878				mPendingConferenceInvite = null;
 879			}
 880		}
 881	}
 882
 883	public int getTertiaryTextColor() {
 884		return this.mTertiaryTextColor;
 885	}
 886
 887	public int getSecondaryTextColor() {
 888		return this.mSecondaryTextColor;
 889	}
 890
 891	public int getPrimaryTextColor() {
 892		return this.mPrimaryTextColor;
 893	}
 894
 895	public int getWarningTextColor() {
 896		return this.mColorRed;
 897	}
 898
 899	public int getOnlineColor() {
 900		return this.mColorGreen;
 901	}
 902
 903	public int getPrimaryBackgroundColor() {
 904		return this.mPrimaryBackgroundColor;
 905	}
 906
 907	public int getSecondaryBackgroundColor() {
 908		return this.mSecondaryBackgroundColor;
 909	}
 910
 911	public int getPixel(int dp) {
 912		DisplayMetrics metrics = getResources().getDisplayMetrics();
 913		return ((int) (dp * metrics.density));
 914	}
 915
 916	public boolean copyTextToClipboard(String text, int labelResId) {
 917		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 918		String label = getResources().getString(labelResId);
 919		if (mClipBoardManager != null) {
 920			ClipData mClipData = ClipData.newPlainText(label, text);
 921			mClipBoardManager.setPrimaryClip(mClipData);
 922			return true;
 923		}
 924		return false;
 925	}
 926
 927	protected boolean neverCompressPictures() {
 928		return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
 929	}
 930
 931	protected boolean manuallyChangePresence() {
 932		return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
 933	}
 934
 935	protected String getShareableUri() {
 936		return getShareableUri(false);
 937	}
 938
 939	protected String getShareableUri(boolean http) {
 940		return null;
 941	}
 942
 943	protected void shareLink(boolean http) {
 944		String uri = getShareableUri(http);
 945		if (uri == null || uri.isEmpty()) {
 946			return;
 947		}
 948		Intent intent = new Intent(Intent.ACTION_SEND);
 949		intent.setType("text/plain");
 950		intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 951		try {
 952			startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 953		} catch (ActivityNotFoundException e) {
 954			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 955		}
 956	}
 957
 958	protected void launchOpenKeyChain(long keyId) {
 959		PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 960		try {
 961			startIntentSenderForResult(
 962					pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 963					0, 0);
 964		} catch (Throwable e) {
 965			Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 966		}
 967	}
 968
 969	@Override
 970	public void onResume() {
 971		super.onResume();
 972	}
 973
 974	protected int findTheme() {
 975		Boolean dark = getPreferences().getString(SettingsActivity.THEME, getResources().getString(R.string.theme)).equals("dark");
 976		Boolean larger = getPreferences().getBoolean("use_larger_font", getResources().getBoolean(R.bool.use_larger_font));
 977
 978		if (dark) {
 979			if (larger)
 980				return R.style.ConversationsTheme_Dark_LargerText;
 981			else
 982				return R.style.ConversationsTheme_Dark;
 983		} else {
 984			if (larger)
 985				return R.style.ConversationsTheme_LargerText;
 986			else
 987				return R.style.ConversationsTheme;
 988		}
 989	}
 990
 991	@Override
 992	public void onPause() {
 993		super.onPause();
 994	}
 995
 996	protected void showQrCode() {
 997		final String uri = getShareableUri();
 998		if (uri == null || uri.isEmpty()) {
 999			return;
1000		}
1001		Point size = new Point();
1002		getWindowManager().getDefaultDisplay().getSize(size);
1003		final int width = (size.x < size.y ? size.x : size.y);
1004		Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
1005		ImageView view = new ImageView(this);
1006		view.setBackgroundColor(Color.WHITE);
1007		view.setImageBitmap(bitmap);
1008		AlertDialog.Builder builder = new AlertDialog.Builder(this);
1009		builder.setView(view);
1010		builder.create().show();
1011	}
1012
1013	protected Account extractAccount(Intent intent) {
1014		String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1015		try {
1016			return jid != null ? xmppConnectionService.findAccountByJid(Jid.fromString(jid)) : null;
1017		} catch (InvalidJidException e) {
1018			return null;
1019		}
1020	}
1021
1022	public AvatarService avatarService() {
1023		return xmppConnectionService.getAvatarService();
1024	}
1025
1026	public void loadBitmap(Message message, ImageView imageView) {
1027		Bitmap bm;
1028		try {
1029			bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
1030		} catch (FileNotFoundException e) {
1031			bm = null;
1032		}
1033		if (bm != null) {
1034			cancelPotentialWork(message, imageView);
1035			imageView.setImageBitmap(bm);
1036			imageView.setBackgroundColor(0x00000000);
1037		} else {
1038			if (cancelPotentialWork(message, imageView)) {
1039				imageView.setBackgroundColor(0xff333333);
1040				imageView.setImageDrawable(null);
1041				final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
1042				final AsyncDrawable asyncDrawable = new AsyncDrawable(
1043						getResources(), null, task);
1044				imageView.setImageDrawable(asyncDrawable);
1045				try {
1046					task.execute(message);
1047				} catch (final RejectedExecutionException ignored) {
1048					ignored.printStackTrace();
1049				}
1050			}
1051		}
1052	}
1053
1054	protected interface OnValueEdited {
1055		String onValueEdited(String value);
1056	}
1057
1058	public interface OnPresenceSelected {
1059		void onPresenceSelected();
1060	}
1061
1062	public static class ConferenceInvite {
1063		private String uuid;
1064		private List<Jid> jids = new ArrayList<>();
1065
1066		public static ConferenceInvite parse(Intent data) {
1067			ConferenceInvite invite = new ConferenceInvite();
1068			invite.uuid = data.getStringExtra("conversation");
1069			if (invite.uuid == null) {
1070				return null;
1071			}
1072			try {
1073				if (data.getBooleanExtra("multiple", false)) {
1074					String[] toAdd = data.getStringArrayExtra("contacts");
1075					for (String item : toAdd) {
1076						invite.jids.add(Jid.fromString(item));
1077					}
1078				} else {
1079					invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
1080				}
1081			} catch (final InvalidJidException ignored) {
1082				return null;
1083			}
1084			return invite;
1085		}
1086
1087		public boolean execute(XmppActivity activity) {
1088			XmppConnectionService service = activity.xmppConnectionService;
1089			Conversation conversation = service.findConversationByUuid(this.uuid);
1090			if (conversation == null) {
1091				return false;
1092			}
1093			if (conversation.getMode() == Conversation.MODE_MULTI) {
1094				for (Jid jid : jids) {
1095					service.invite(conversation, jid);
1096				}
1097				return false;
1098			} else {
1099				jids.add(conversation.getJid().toBareJid());
1100				return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1101			}
1102		}
1103	}
1104
1105	static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1106		private final WeakReference<ImageView> imageViewReference;
1107		private final WeakReference<XmppActivity> activity;
1108		private Message message = null;
1109
1110		private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
1111			this.activity = new WeakReference<>(activity);
1112			this.imageViewReference = new WeakReference<>(imageView);
1113		}
1114
1115		@Override
1116		protected Bitmap doInBackground(Message... params) {
1117			if (isCancelled()) {
1118				return null;
1119			}
1120			message = params[0];
1121			try {
1122				XmppActivity activity = this.activity.get();
1123				if (activity != null && activity.xmppConnectionService != null) {
1124					return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
1125				} else {
1126					return null;
1127				}
1128			} catch (FileNotFoundException e) {
1129				return null;
1130			}
1131		}
1132
1133		@Override
1134		protected void onPostExecute(Bitmap bitmap) {
1135			if (bitmap != null && !isCancelled()) {
1136				final ImageView imageView = imageViewReference.get();
1137				if (imageView != null) {
1138					imageView.setImageBitmap(bitmap);
1139					imageView.setBackgroundColor(0x00000000);
1140				}
1141			}
1142		}
1143	}
1144
1145	private static class AsyncDrawable extends BitmapDrawable {
1146		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1147
1148		private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1149			super(res, bitmap);
1150			bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1151		}
1152
1153		private BitmapWorkerTask getBitmapWorkerTask() {
1154			return bitmapWorkerTaskReference.get();
1155		}
1156	}
1157}