XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.annotation.TargetApi;
   6import android.app.PendingIntent;
   7import android.content.ActivityNotFoundException;
   8import android.content.ClipData;
   9import android.content.ClipboardManager;
  10import android.content.ComponentName;
  11import android.content.Context;
  12import android.content.ContextWrapper;
  13import android.content.DialogInterface;
  14import android.content.Intent;
  15import android.content.IntentSender.SendIntentException;
  16import android.content.ServiceConnection;
  17import android.content.SharedPreferences;
  18import android.content.pm.PackageManager;
  19import android.content.pm.ResolveInfo;
  20import android.content.res.Resources;
  21import android.content.res.TypedArray;
  22import android.databinding.DataBindingUtil;
  23import android.graphics.Bitmap;
  24import android.graphics.Color;
  25import android.graphics.Point;
  26import android.graphics.drawable.BitmapDrawable;
  27import android.graphics.drawable.Drawable;
  28import android.media.AudioManager;
  29import android.net.ConnectivityManager;
  30import android.net.Uri;
  31import android.os.AsyncTask;
  32import android.os.Build;
  33import android.os.Bundle;
  34import android.os.Handler;
  35import android.os.IBinder;
  36import android.os.PowerManager;
  37import android.os.SystemClock;
  38import android.preference.PreferenceManager;
  39import android.support.annotation.BoolRes;
  40import android.support.annotation.NonNull;
  41import android.support.annotation.StringRes;
  42import android.support.v4.content.ContextCompat;
  43import android.support.v7.app.AlertDialog;
  44import android.support.v7.app.AlertDialog.Builder;
  45import android.support.v7.app.AppCompatDelegate;
  46import android.text.InputType;
  47import android.util.DisplayMetrics;
  48import android.util.Log;
  49import android.view.Menu;
  50import android.view.MenuItem;
  51import android.view.View;
  52import android.widget.ImageView;
  53import android.widget.Toast;
  54
  55import java.io.IOException;
  56import java.lang.ref.WeakReference;
  57import java.util.ArrayList;
  58import java.util.List;
  59import java.util.concurrent.RejectedExecutionException;
  60
  61import eu.siacs.conversations.Config;
  62import eu.siacs.conversations.R;
  63import eu.siacs.conversations.crypto.PgpEngine;
  64import eu.siacs.conversations.databinding.DialogQuickeditBinding;
  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.Presences;
  70import eu.siacs.conversations.services.AvatarService;
  71import eu.siacs.conversations.services.BarcodeProvider;
  72import eu.siacs.conversations.services.XmppConnectionService;
  73import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  74import eu.siacs.conversations.ui.service.EmojiService;
  75import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  76import eu.siacs.conversations.ui.util.PresenceSelector;
  77import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
  78import eu.siacs.conversations.utils.AccountUtils;
  79import eu.siacs.conversations.utils.ExceptionHelper;
  80import eu.siacs.conversations.utils.ThemeHelper;
  81import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  82import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  83import rocks.xmpp.addr.Jid;
  84
  85public abstract class XmppActivity extends ActionBarActivity {
  86
  87	public static final String EXTRA_ACCOUNT = "account";
  88	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
  89	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
  90	protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
  91	protected static final int REQUEST_BATTERY_OP = 0x49ff;
  92	public XmppConnectionService xmppConnectionService;
  93	public boolean xmppConnectionServiceBound = false;
  94
  95	protected int mColorRed;
  96
  97	protected static final String FRAGMENT_TAG_DIALOG = "dialog";
  98
  99	private boolean isCameraFeatureAvailable = false;
 100
 101	protected int mTheme;
 102	protected boolean mUsingEnterKey = false;
 103	protected Toast mToast;
 104	public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
 105	protected ConferenceInvite mPendingConferenceInvite = null;
 106	protected ServiceConnection mConnection = new ServiceConnection() {
 107
 108		@Override
 109		public void onServiceConnected(ComponentName className, IBinder service) {
 110			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 111			xmppConnectionService = binder.getService();
 112			xmppConnectionServiceBound = true;
 113			registerListeners();
 114			onBackendConnected();
 115		}
 116
 117		@Override
 118		public void onServiceDisconnected(ComponentName arg0) {
 119			xmppConnectionServiceBound = false;
 120		}
 121	};
 122	private DisplayMetrics metrics;
 123	private long mLastUiRefresh = 0;
 124	private Handler mRefreshUiHandler = new Handler();
 125	private Runnable mRefreshUiRunnable = () -> {
 126		mLastUiRefresh = SystemClock.elapsedRealtime();
 127		refreshUiReal();
 128	};
 129	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 130		@Override
 131		public void success(final Conversation conversation) {
 132			runOnUiThread(() -> {
 133				switchToConversation(conversation);
 134				hideToast();
 135			});
 136		}
 137
 138		@Override
 139		public void error(final int errorCode, Conversation object) {
 140			runOnUiThread(() -> replaceToast(getString(errorCode)));
 141		}
 142
 143		@Override
 144		public void userInputRequried(PendingIntent pi, Conversation object) {
 145
 146		}
 147	};
 148	public boolean mSkipBackgroundBinding = false;
 149
 150	public static boolean cancelPotentialWork(Message message, ImageView imageView) {
 151		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
 152
 153		if (bitmapWorkerTask != null) {
 154			final Message oldMessage = bitmapWorkerTask.message;
 155			if (oldMessage == null || message != oldMessage) {
 156				bitmapWorkerTask.cancel(true);
 157			} else {
 158				return false;
 159			}
 160		}
 161		return true;
 162	}
 163
 164	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
 165		if (imageView != null) {
 166			final Drawable drawable = imageView.getDrawable();
 167			if (drawable instanceof AsyncDrawable) {
 168				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
 169				return asyncDrawable.getBitmapWorkerTask();
 170			}
 171		}
 172		return null;
 173	}
 174
 175	protected void hideToast() {
 176		if (mToast != null) {
 177			mToast.cancel();
 178		}
 179	}
 180
 181	protected void replaceToast(String msg) {
 182		replaceToast(msg, true);
 183	}
 184
 185	protected void replaceToast(String msg, boolean showlong) {
 186		hideToast();
 187		mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
 188		mToast.show();
 189	}
 190
 191	protected final void refreshUi() {
 192		final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 193		if (diff > Config.REFRESH_UI_INTERVAL) {
 194			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 195			runOnUiThread(mRefreshUiRunnable);
 196		} else {
 197			final long next = Config.REFRESH_UI_INTERVAL - diff;
 198			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 199			mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
 200		}
 201	}
 202
 203	abstract protected void refreshUiReal();
 204
 205	@Override
 206	protected void onStart() {
 207		super.onStart();
 208		if (!xmppConnectionServiceBound) {
 209			if (this.mSkipBackgroundBinding) {
 210				Log.d(Config.LOGTAG,"skipping background binding");
 211			} else {
 212				connectToBackend();
 213			}
 214		} else {
 215			this.registerListeners();
 216			this.onBackendConnected();
 217		}
 218	}
 219
 220	public void connectToBackend() {
 221		Intent intent = new Intent(this, XmppConnectionService.class);
 222		intent.setAction("ui");
 223		try {
 224			startService(intent);
 225		} catch (IllegalStateException e) {
 226			Log.w(Config.LOGTAG,"unable to start service from "+getClass().getSimpleName());
 227		}
 228		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 229	}
 230
 231	@Override
 232	protected void onStop() {
 233		super.onStop();
 234		if (xmppConnectionServiceBound) {
 235			this.unregisterListeners();
 236			unbindService(mConnection);
 237			xmppConnectionServiceBound = false;
 238		}
 239	}
 240
 241
 242	public boolean hasPgp() {
 243		return xmppConnectionService.getPgpEngine() != null;
 244	}
 245
 246	public void showInstallPgpDialog() {
 247		Builder builder = new AlertDialog.Builder(this);
 248		builder.setTitle(getString(R.string.openkeychain_required));
 249		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 250		builder.setMessage(getText(R.string.openkeychain_required_long));
 251		builder.setNegativeButton(getString(R.string.cancel), null);
 252		builder.setNeutralButton(getString(R.string.restart),
 253				(dialog, which) -> {
 254					if (xmppConnectionServiceBound) {
 255						unbindService(mConnection);
 256						xmppConnectionServiceBound = false;
 257					}
 258					stopService(new Intent(XmppActivity.this,
 259							XmppConnectionService.class));
 260					finish();
 261				});
 262		builder.setPositiveButton(getString(R.string.install),
 263				(dialog, which) -> {
 264					Uri uri = Uri
 265							.parse("market://details?id=org.sufficientlysecure.keychain");
 266					Intent marketIntent = new Intent(Intent.ACTION_VIEW,
 267							uri);
 268					PackageManager manager = getApplicationContext()
 269							.getPackageManager();
 270					List<ResolveInfo> infos = manager
 271							.queryIntentActivities(marketIntent, 0);
 272					if (infos.size() > 0) {
 273						startActivity(marketIntent);
 274					} else {
 275						uri = Uri.parse("http://www.openkeychain.org/");
 276						Intent browserIntent = new Intent(
 277								Intent.ACTION_VIEW, uri);
 278						startActivity(browserIntent);
 279					}
 280					finish();
 281				});
 282		builder.create().show();
 283	}
 284
 285	abstract void onBackendConnected();
 286
 287	protected void registerListeners() {
 288		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 289			this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 290		}
 291		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 292			this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 293		}
 294		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 295			this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 296		}
 297		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 298			this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 299		}
 300		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 301			this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 302		}
 303		if (this instanceof OnUpdateBlocklist) {
 304			this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 305		}
 306		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 307			this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 308		}
 309		if (this instanceof OnKeyStatusUpdated) {
 310			this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 311		}
 312	}
 313
 314	protected void unregisterListeners() {
 315		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 316			this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 317		}
 318		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 319			this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 320		}
 321		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 322			this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 323		}
 324		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 325			this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 326		}
 327		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 328			this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 329		}
 330		if (this instanceof OnUpdateBlocklist) {
 331			this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 332		}
 333		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 334			this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 335		}
 336		if (this instanceof OnKeyStatusUpdated) {
 337			this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
 338		}
 339	}
 340
 341	@Override
 342	public boolean onOptionsItemSelected(final MenuItem item) {
 343		switch (item.getItemId()) {
 344			case R.id.action_settings:
 345				startActivity(new Intent(this, SettingsActivity.class));
 346				break;
 347			case R.id.action_accounts:
 348				AccountUtils.launchManageAccounts(this);
 349				break;
 350			case R.id.action_account:
 351				AccountUtils.launchManageAccount(this);
 352				break;
 353			case android.R.id.home:
 354				finish();
 355				break;
 356			case R.id.action_show_qr_code:
 357				showQrCode();
 358				break;
 359		}
 360		return super.onOptionsItemSelected(item);
 361	}
 362
 363	public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
 364		final Contact contact = conversation.getContact();
 365		if (!contact.showInRoster()) {
 366			showAddToRosterDialog(conversation.getContact());
 367		} else {
 368			final Presences presences = contact.getPresences();
 369			if (presences.size() == 0) {
 370				if (!contact.getOption(Contact.Options.TO)
 371						&& !contact.getOption(Contact.Options.ASKING)
 372						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 373					showAskForPresenceDialog(contact);
 374				} else if (!contact.getOption(Contact.Options.TO)
 375						|| !contact.getOption(Contact.Options.FROM)) {
 376					PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
 377				} else {
 378					conversation.setNextCounterpart(null);
 379					listener.onPresenceSelected();
 380				}
 381			} else if (presences.size() == 1) {
 382				String presence = presences.toResourceArray()[0];
 383				try {
 384					conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence));
 385				} catch (IllegalArgumentException e) {
 386					conversation.setNextCounterpart(null);
 387				}
 388				listener.onPresenceSelected();
 389			} else {
 390				PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
 391			}
 392		}
 393	}
 394
 395	@Override
 396	protected void onCreate(Bundle savedInstanceState) {
 397		super.onCreate(savedInstanceState);
 398		setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
 399		metrics = getResources().getDisplayMetrics();
 400		ExceptionHelper.init(getApplicationContext());
 401		new EmojiService(this).init();
 402		this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
 403
 404		mColorRed = ContextCompat.getColor(this, R.color.red800);
 405
 406		this.mTheme = findTheme();
 407		setTheme(this.mTheme);
 408
 409		this.mUsingEnterKey = usingEnterKey();
 410	}
 411
 412	protected boolean isCameraFeatureAvailable() {
 413		return this.isCameraFeatureAvailable;
 414	}
 415
 416	public boolean isDarkTheme() {
 417		return ThemeHelper.isDark(mTheme);
 418	}
 419
 420	public int getThemeResource(int r_attr_name, int r_drawable_def) {
 421		int[] attrs = {r_attr_name};
 422		TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 423
 424		int res = ta.getResourceId(0, r_drawable_def);
 425		ta.recycle();
 426
 427		return res;
 428	}
 429
 430	protected boolean isOptimizingBattery() {
 431		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 432			final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 433			return pm != null
 434					&& !pm.isIgnoringBatteryOptimizations(getPackageName());
 435		} else {
 436			return false;
 437		}
 438	}
 439
 440	protected boolean isAffectedByDataSaver() {
 441		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 442			final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 443			return cm != null
 444					&& cm.isActiveNetworkMetered()
 445					&& cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 446		} else {
 447			return false;
 448		}
 449	}
 450
 451	protected boolean usingEnterKey() {
 452		return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 453	}
 454
 455	protected SharedPreferences getPreferences() {
 456		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 457	}
 458
 459	protected boolean getBooleanPreference(String name, @BoolRes int res) {
 460		return getPreferences().getBoolean(name, getResources().getBoolean(res));
 461	}
 462
 463	public void switchToConversation(Conversation conversation) {
 464		switchToConversation(conversation, null);
 465	}
 466
 467	public void switchToConversationAndQuote(Conversation conversation, String text) {
 468		switchToConversation(conversation, text, true, null, false, false);
 469	}
 470
 471	public void switchToConversation(Conversation conversation, String text) {
 472		switchToConversation(conversation, text, false, null, false, false);
 473	}
 474
 475	public void switchToConversationDoNotAppend(Conversation conversation, String text) {
 476		switchToConversation(conversation, text, false, null, false, true);
 477	}
 478
 479	public void highlightInMuc(Conversation conversation, String nick) {
 480		switchToConversation(conversation, null, false, nick, false, false);
 481	}
 482
 483	public void privateMsgInMuc(Conversation conversation, String nick) {
 484		switchToConversation(conversation, null, false, nick, true, false);
 485	}
 486
 487	private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
 488		Intent intent = new Intent(this, ConversationsActivity.class);
 489		intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 490		intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 491		if (text != null) {
 492			intent.putExtra(Intent.EXTRA_TEXT, text);
 493			if (asQuote) {
 494				intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
 495			}
 496		}
 497		if (nick != null) {
 498			intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 499			intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 500		}
 501		if (doNotAppend) {
 502			intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
 503		}
 504		intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
 505		startActivity(intent);
 506		finish();
 507	}
 508
 509	public void switchToContactDetails(Contact contact) {
 510		switchToContactDetails(contact, null);
 511	}
 512
 513	public void switchToContactDetails(Contact contact, String messageFingerprint) {
 514		Intent intent = new Intent(this, ContactDetailsActivity.class);
 515		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 516		intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString());
 517		intent.putExtra("contact", contact.getJid().toString());
 518		intent.putExtra("fingerprint", messageFingerprint);
 519		startActivity(intent);
 520	}
 521
 522	public void switchToAccount(Account account, String fingerprint) {
 523		switchToAccount(account, false, fingerprint);
 524	}
 525
 526	public void switchToAccount(Account account) {
 527		switchToAccount(account, false, null);
 528	}
 529
 530	public void switchToAccount(Account account, boolean init, String fingerprint) {
 531		Intent intent = new Intent(this, EditAccountActivity.class);
 532		intent.putExtra("jid", account.getJid().asBareJid().toString());
 533		intent.putExtra("init", init);
 534		if (init) {
 535			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 536		}
 537		if (fingerprint != null) {
 538			intent.putExtra("fingerprint", fingerprint);
 539		}
 540		startActivity(intent);
 541		if (init) {
 542			overridePendingTransition(0, 0);
 543		}
 544	}
 545
 546	protected void delegateUriPermissionsToService(Uri uri) {
 547		Intent intent = new Intent(this, XmppConnectionService.class);
 548		intent.setAction(Intent.ACTION_SEND);
 549		intent.setData(uri);
 550		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 551		try {
 552			startService(intent);
 553		} catch (Exception e) {
 554			Log.e(Config.LOGTAG,"unable to delegate uri permission",e);
 555		}
 556	}
 557
 558	protected void inviteToConversation(Conversation conversation) {
 559		startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION);
 560	}
 561
 562	protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 563		if (account.getPgpId() == 0) {
 564			choosePgpSignId(account);
 565		} else {
 566			String status = null;
 567			if (manuallyChangePresence()) {
 568				status = account.getPresenceStatusMessage();
 569			}
 570			if (status == null) {
 571				status = "";
 572			}
 573			xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
 574
 575				@Override
 576				public void userInputRequried(PendingIntent pi, String signature) {
 577					try {
 578						startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 579					} catch (final SendIntentException ignored) {
 580					}
 581				}
 582
 583				@Override
 584				public void success(String signature) {
 585					account.setPgpSignature(signature);
 586					xmppConnectionService.databaseBackend.updateAccount(account);
 587					xmppConnectionService.sendPresence(account);
 588					if (conversation != null) {
 589						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 590						xmppConnectionService.updateConversation(conversation);
 591						refreshUi();
 592					}
 593					if (onSuccess != null) {
 594						runOnUiThread(onSuccess);
 595					}
 596				}
 597
 598				@Override
 599				public void error(int error, String signature) {
 600					if (error == 0) {
 601						account.setPgpSignId(0);
 602						account.unsetPgpSignature();
 603						xmppConnectionService.databaseBackend.updateAccount(account);
 604						choosePgpSignId(account);
 605					} else {
 606						displayErrorDialog(error);
 607					}
 608				}
 609			});
 610		}
 611	}
 612
 613	@SuppressWarnings("deprecation")
 614	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 615	protected void setListItemBackgroundOnView(View view) {
 616		int sdk = android.os.Build.VERSION.SDK_INT;
 617		if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 618			view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 619		} else {
 620			view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 621		}
 622	}
 623
 624	protected void choosePgpSignId(Account account) {
 625		xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 626			@Override
 627			public void success(Account account1) {
 628			}
 629
 630			@Override
 631			public void error(int errorCode, Account object) {
 632
 633			}
 634
 635			@Override
 636			public void userInputRequried(PendingIntent pi, Account object) {
 637				try {
 638					startIntentSenderForResult(pi.getIntentSender(),
 639							REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 640				} catch (final SendIntentException ignored) {
 641				}
 642			}
 643		});
 644	}
 645
 646	protected void displayErrorDialog(final int errorCode) {
 647		runOnUiThread(() -> {
 648			Builder builder = new Builder(XmppActivity.this);
 649			builder.setIconAttribute(android.R.attr.alertDialogIcon);
 650			builder.setTitle(getString(R.string.error));
 651			builder.setMessage(errorCode);
 652			builder.setNeutralButton(R.string.accept, null);
 653			builder.create().show();
 654		});
 655
 656	}
 657
 658	protected void showAddToRosterDialog(final Contact contact) {
 659		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 660		builder.setTitle(contact.getJid().toString());
 661		builder.setMessage(getString(R.string.not_in_roster));
 662		builder.setNegativeButton(getString(R.string.cancel), null);
 663		builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
 664		builder.create().show();
 665	}
 666
 667	private void showAskForPresenceDialog(final Contact contact) {
 668		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 669		builder.setTitle(contact.getJid().toString());
 670		builder.setMessage(R.string.request_presence_updates);
 671		builder.setNegativeButton(R.string.cancel, null);
 672		builder.setPositiveButton(R.string.request_now,
 673				(dialog, which) -> {
 674					if (xmppConnectionServiceBound) {
 675						xmppConnectionService.sendPresencePacket(contact
 676								.getAccount(), xmppConnectionService
 677								.getPresenceGenerator()
 678								.requestPresenceUpdatesFrom(contact));
 679					}
 680				});
 681		builder.create().show();
 682	}
 683
 684	protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
 685		quickEdit(previousValue, callback, hint, false, false);
 686	}
 687
 688	protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
 689		quickEdit(previousValue, callback, hint, false, permitEmpty);
 690	}
 691
 692	protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 693		quickEdit(previousValue, callback, R.string.password, true, false);
 694	}
 695
 696	@SuppressLint("InflateParams")
 697	private void quickEdit(final String previousValue,
 698	                       final OnValueEdited callback,
 699	                       final @StringRes int hint,
 700	                       boolean password,
 701	                       boolean permitEmpty) {
 702		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 703		DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false);
 704		if (password) {
 705			binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
 706		}
 707		builder.setPositiveButton(R.string.accept, null);
 708		if (hint != 0) {
 709			binding.inputLayout.setHint(getString(hint));
 710		}
 711		binding.inputEditText.requestFocus();
 712		if (previousValue != null) {
 713			binding.inputEditText.getText().append(previousValue);
 714		}
 715		builder.setView(binding.getRoot());
 716		builder.setNegativeButton(R.string.cancel, null);
 717		final AlertDialog dialog = builder.create();
 718		dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
 719		dialog.show();
 720		View.OnClickListener clickListener = v -> {
 721			String value = binding.inputEditText.getText().toString();
 722			if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
 723				String error = callback.onValueEdited(value);
 724				if (error != null) {
 725					binding.inputLayout.setError(error);
 726					return;
 727				}
 728			}
 729			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 730			dialog.dismiss();
 731		};
 732		dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 733		dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
 734			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 735			dialog.dismiss();
 736		}));
 737		dialog.setCanceledOnTouchOutside(false);
 738		dialog.setOnDismissListener(dialog1 -> {
 739			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 740        });
 741	}
 742
 743	protected boolean hasStoragePermission(int requestCode) {
 744		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 745			if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 746				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 747				return false;
 748			} else {
 749				return true;
 750			}
 751		} else {
 752			return true;
 753		}
 754	}
 755
 756	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 757		super.onActivityResult(requestCode, resultCode, data);
 758		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 759			mPendingConferenceInvite = ConferenceInvite.parse(data);
 760			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 761				if (mPendingConferenceInvite.execute(this)) {
 762					mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 763					mToast.show();
 764				}
 765				mPendingConferenceInvite = null;
 766			}
 767		}
 768	}
 769
 770	public int getWarningTextColor() {
 771		return this.mColorRed;
 772	}
 773
 774	public int getPixel(int dp) {
 775		DisplayMetrics metrics = getResources().getDisplayMetrics();
 776		return ((int) (dp * metrics.density));
 777	}
 778
 779	public boolean copyTextToClipboard(String text, int labelResId) {
 780		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 781		String label = getResources().getString(labelResId);
 782		if (mClipBoardManager != null) {
 783			ClipData mClipData = ClipData.newPlainText(label, text);
 784			mClipBoardManager.setPrimaryClip(mClipData);
 785			return true;
 786		}
 787		return false;
 788	}
 789
 790	protected boolean manuallyChangePresence() {
 791		return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 792	}
 793
 794	protected String getShareableUri() {
 795		return getShareableUri(false);
 796	}
 797
 798	protected String getShareableUri(boolean http) {
 799		return null;
 800	}
 801
 802	protected void shareLink(boolean http) {
 803		String uri = getShareableUri(http);
 804		if (uri == null || uri.isEmpty()) {
 805			return;
 806		}
 807		Intent intent = new Intent(Intent.ACTION_SEND);
 808		intent.setType("text/plain");
 809		intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 810		try {
 811			startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 812		} catch (ActivityNotFoundException e) {
 813			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 814		}
 815	}
 816
 817	protected void launchOpenKeyChain(long keyId) {
 818		PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 819		try {
 820			startIntentSenderForResult(
 821					pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 822					0, 0);
 823		} catch (Throwable e) {
 824			Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 825		}
 826	}
 827
 828	@Override
 829	public void onResume() {
 830		super.onResume();
 831	}
 832
 833	protected int findTheme() {
 834		return ThemeHelper.find(this);
 835	}
 836
 837	@Override
 838	public void onPause() {
 839		super.onPause();
 840	}
 841
 842	@Override
 843	public boolean onMenuOpened(int id, Menu menu) {
 844		if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
 845			MenuDoubleTabUtil.recordMenuOpen();
 846		}
 847		return super.onMenuOpened(id, menu);
 848	}
 849
 850	protected void showQrCode() {
 851		showQrCode(getShareableUri());
 852	}
 853
 854	protected void showQrCode(final String uri) {
 855		if (uri == null || uri.isEmpty()) {
 856			return;
 857		}
 858		Point size = new Point();
 859		getWindowManager().getDefaultDisplay().getSize(size);
 860		final int width = (size.x < size.y ? size.x : size.y);
 861		Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
 862		ImageView view = new ImageView(this);
 863		view.setBackgroundColor(Color.WHITE);
 864		view.setImageBitmap(bitmap);
 865		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 866		builder.setView(view);
 867		builder.create().show();
 868	}
 869
 870	protected Account extractAccount(Intent intent) {
 871		String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
 872		try {
 873			return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
 874		} catch (IllegalArgumentException e) {
 875			return null;
 876		}
 877	}
 878
 879	public AvatarService avatarService() {
 880		return xmppConnectionService.getAvatarService();
 881	}
 882
 883	public void loadBitmap(Message message, ImageView imageView) {
 884		Bitmap bm;
 885		try {
 886			bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
 887		} catch (IOException e) {
 888			bm = null;
 889		}
 890		if (bm != null) {
 891			cancelPotentialWork(message, imageView);
 892			imageView.setImageBitmap(bm);
 893			imageView.setBackgroundColor(0x00000000);
 894		} else {
 895			if (cancelPotentialWork(message, imageView)) {
 896				imageView.setBackgroundColor(0xff333333);
 897				imageView.setImageDrawable(null);
 898				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
 899				final AsyncDrawable asyncDrawable = new AsyncDrawable(
 900						getResources(), null, task);
 901				imageView.setImageDrawable(asyncDrawable);
 902				try {
 903					task.execute(message);
 904				} catch (final RejectedExecutionException ignored) {
 905					ignored.printStackTrace();
 906				}
 907			}
 908		}
 909	}
 910
 911	protected interface OnValueEdited {
 912		String onValueEdited(String value);
 913	}
 914
 915	public static class ConferenceInvite {
 916		private String uuid;
 917		private List<Jid> jids = new ArrayList<>();
 918
 919		public static ConferenceInvite parse(Intent data) {
 920			ConferenceInvite invite = new ConferenceInvite();
 921			invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
 922			if (invite.uuid == null) {
 923				return null;
 924			}
 925			invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
 926			return invite;
 927		}
 928
 929		public boolean execute(XmppActivity activity) {
 930			XmppConnectionService service = activity.xmppConnectionService;
 931			Conversation conversation = service.findConversationByUuid(this.uuid);
 932			if (conversation == null) {
 933				return false;
 934			}
 935			if (conversation.getMode() == Conversation.MODE_MULTI) {
 936				for (Jid jid : jids) {
 937					service.invite(conversation, jid);
 938				}
 939				return false;
 940			} else {
 941				jids.add(conversation.getJid().asBareJid());
 942				return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
 943			}
 944		}
 945	}
 946
 947	static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
 948		private final WeakReference<ImageView> imageViewReference;
 949		private Message message = null;
 950
 951		private BitmapWorkerTask(ImageView imageView) {
 952			this.imageViewReference = new WeakReference<>(imageView);
 953		}
 954
 955		@Override
 956		protected Bitmap doInBackground(Message... params) {
 957			if (isCancelled()) {
 958				return null;
 959			}
 960			message = params[0];
 961			try {
 962				final XmppActivity activity = find(imageViewReference);
 963				if (activity != null && activity.xmppConnectionService != null) {
 964					return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
 965				} else {
 966					return null;
 967				}
 968			} catch (IOException e) {
 969				return null;
 970			}
 971		}
 972
 973		@Override
 974		protected void onPostExecute(final Bitmap bitmap) {
 975			if (!isCancelled()) {
 976				final ImageView imageView = imageViewReference.get();
 977				if (imageView != null) {
 978					imageView.setImageBitmap(bitmap);
 979					imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
 980				}
 981			}
 982		}
 983	}
 984
 985	private static class AsyncDrawable extends BitmapDrawable {
 986		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
 987
 988		private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
 989			super(res, bitmap);
 990			bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
 991		}
 992
 993		private BitmapWorkerTask getBitmapWorkerTask() {
 994			return bitmapWorkerTaskReference.get();
 995		}
 996	}
 997
 998	public static XmppActivity find(@NonNull  WeakReference<ImageView> viewWeakReference) {
 999		final View view = viewWeakReference.get();
1000		return view == null ? null : find(view);
1001	}
1002
1003	public static XmppActivity find(@NonNull final View view) {
1004		Context context = view.getContext();
1005		while (context instanceof ContextWrapper) {
1006			if (context instanceof XmppActivity) {
1007				return (XmppActivity) context;
1008			}
1009			context = ((ContextWrapper)context).getBaseContext();
1010		}
1011		return null;
1012	}
1013}