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