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