XmppActivity.java

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