XmppActivity.java

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