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(this, 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 (!contact.showInRoster()) {
 783			showAddToRosterDialog(conversation);
 784		} else {
 785			final Presences presences = contact.getPresences();
 786			if (presences.size() == 0) {
 787				if (!contact.getOption(Contact.Options.TO)
 788						&& !contact.getOption(Contact.Options.ASKING)
 789						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 790					showAskForPresenceDialog(contact);
 791				} else if (!contact.getOption(Contact.Options.TO)
 792						|| !contact.getOption(Contact.Options.FROM)) {
 793					warnMutalPresenceSubscription(conversation, listener);
 794				} else {
 795					conversation.setNextCounterpart(null);
 796					listener.onPresenceSelected();
 797				}
 798			} else if (presences.size() == 1) {
 799				String presence = presences.toResourceArray()[0];
 800				try {
 801					conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
 802				} catch (InvalidJidException e) {
 803					conversation.setNextCounterpart(null);
 804				}
 805				listener.onPresenceSelected();
 806			} else {
 807				showPresenceSelectionDialog(presences, conversation, listener);
 808			}
 809		}
 810	}
 811
 812	private void showPresenceSelectionDialog(Presences presences, final Conversation conversation, final OnPresenceSelected listener) {
 813		final Contact contact = conversation.getContact();
 814		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 815		builder.setTitle(getString(R.string.choose_presence));
 816		final String[] resourceArray = presences.toResourceArray();
 817		Pair<Map<String, String>, Map<String, String>> typeAndName = presences.toTypeAndNameMap();
 818		final Map<String, String> resourceTypeMap = typeAndName.first;
 819		final Map<String, String> resourceNameMap = typeAndName.second;
 820		final String[] readableIdentities = new String[resourceArray.length];
 821		final AtomicInteger selectedResource = new AtomicInteger(0);
 822		for (int i = 0; i < resourceArray.length; ++i) {
 823			String resource = resourceArray[i];
 824			if (resource.equals(contact.getLastResource())) {
 825				selectedResource.set(i);
 826			}
 827			String type = resourceTypeMap.get(resource);
 828			String name = resourceNameMap.get(resource);
 829			if (type != null) {
 830				if (Collections.frequency(resourceTypeMap.values(), type) == 1) {
 831					readableIdentities[i] = UIHelper.tranlasteType(this, type);
 832				} else if (name != null) {
 833					if (Collections.frequency(resourceNameMap.values(), name) == 1
 834							|| CryptoHelper.UUID_PATTERN.matcher(resource).matches()) {
 835						readableIdentities[i] = UIHelper.tranlasteType(this, type) + "  (" + name + ")";
 836					} else {
 837						readableIdentities[i] = UIHelper.tranlasteType(this, type) + " (" + name + " / " + resource + ")";
 838					}
 839				} else {
 840					readableIdentities[i] = UIHelper.tranlasteType(this, type) + " (" + resource + ")";
 841				}
 842			} else {
 843				readableIdentities[i] = resource;
 844			}
 845		}
 846		builder.setSingleChoiceItems(readableIdentities,
 847				selectedResource.get(),
 848				(dialog, which) -> selectedResource.set(which));
 849		builder.setNegativeButton(R.string.cancel, null);
 850		builder.setPositiveButton(R.string.ok, (dialog, which) -> {
 851			try {
 852				Jid next = Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), resourceArray[selectedResource.get()]);
 853				conversation.setNextCounterpart(next);
 854			} catch (InvalidJidException e) {
 855				conversation.setNextCounterpart(null);
 856			}
 857			listener.onPresenceSelected();
 858		});
 859		builder.create().show();
 860	}
 861
 862	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 863		super.onActivityResult(requestCode, resultCode, data);
 864		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 865			mPendingConferenceInvite = ConferenceInvite.parse(data);
 866			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 867				if (mPendingConferenceInvite.execute(this)) {
 868					mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 869					mToast.show();
 870				}
 871				mPendingConferenceInvite = null;
 872			}
 873		}
 874	}
 875
 876	public int getTertiaryTextColor() {
 877		return this.mTertiaryTextColor;
 878	}
 879
 880	public int getSecondaryTextColor() {
 881		return this.mSecondaryTextColor;
 882	}
 883
 884	public int getPrimaryTextColor() {
 885		return this.mPrimaryTextColor;
 886	}
 887
 888	public int getWarningTextColor() {
 889		return this.mColorRed;
 890	}
 891
 892	public int getOnlineColor() {
 893		return this.mColorGreen;
 894	}
 895
 896	public int getPrimaryBackgroundColor() {
 897		return this.mPrimaryBackgroundColor;
 898	}
 899
 900	public int getSecondaryBackgroundColor() {
 901		return this.mSecondaryBackgroundColor;
 902	}
 903
 904	public int getPixel(int dp) {
 905		DisplayMetrics metrics = getResources().getDisplayMetrics();
 906		return ((int) (dp * metrics.density));
 907	}
 908
 909	public boolean copyTextToClipboard(String text, int labelResId) {
 910		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 911		String label = getResources().getString(labelResId);
 912		if (mClipBoardManager != null) {
 913			ClipData mClipData = ClipData.newPlainText(label, text);
 914			mClipBoardManager.setPrimaryClip(mClipData);
 915			return true;
 916		}
 917		return false;
 918	}
 919
 920	protected boolean neverCompressPictures() {
 921		return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
 922	}
 923
 924	protected boolean manuallyChangePresence() {
 925		return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
 926	}
 927
 928	protected String getShareableUri() {
 929		return getShareableUri(false);
 930	}
 931
 932	protected String getShareableUri(boolean http) {
 933		return null;
 934	}
 935
 936	protected void shareLink(boolean http) {
 937		String uri = getShareableUri(http);
 938		if (uri == null || uri.isEmpty()) {
 939			return;
 940		}
 941		Intent intent = new Intent(Intent.ACTION_SEND);
 942		intent.setType("text/plain");
 943		intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 944		try {
 945			startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 946		} catch (ActivityNotFoundException e) {
 947			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 948		}
 949	}
 950
 951	protected void launchOpenKeyChain(long keyId) {
 952		PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 953		try {
 954			startIntentSenderForResult(
 955					pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 956					0, 0);
 957		} catch (Throwable e) {
 958			Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 959		}
 960	}
 961
 962	@Override
 963	public void onResume() {
 964		super.onResume();
 965	}
 966
 967	protected int findTheme() {
 968		Boolean dark = getPreferences().getString(SettingsActivity.THEME, getResources().getString(R.string.theme)).equals("dark");
 969		Boolean larger = getPreferences().getBoolean("use_larger_font", getResources().getBoolean(R.bool.use_larger_font));
 970
 971		if (dark) {
 972			if (larger)
 973				return R.style.ConversationsTheme_Dark_LargerText;
 974			else
 975				return R.style.ConversationsTheme_Dark;
 976		} else {
 977			if (larger)
 978				return R.style.ConversationsTheme_LargerText;
 979			else
 980				return R.style.ConversationsTheme;
 981		}
 982	}
 983
 984	@Override
 985	public void onPause() {
 986		super.onPause();
 987	}
 988
 989	protected void showQrCode() {
 990		final String uri = getShareableUri();
 991		if (uri == null || uri.isEmpty()) {
 992			return;
 993		}
 994		Point size = new Point();
 995		getWindowManager().getDefaultDisplay().getSize(size);
 996		final int width = (size.x < size.y ? size.x : size.y);
 997		Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
 998		ImageView view = new ImageView(this);
 999		view.setBackgroundColor(Color.WHITE);
1000		view.setImageBitmap(bitmap);
1001		AlertDialog.Builder builder = new AlertDialog.Builder(this);
1002		builder.setView(view);
1003		builder.create().show();
1004	}
1005
1006	protected Account extractAccount(Intent intent) {
1007		String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1008		try {
1009			return jid != null ? xmppConnectionService.findAccountByJid(Jid.fromString(jid)) : null;
1010		} catch (InvalidJidException e) {
1011			return null;
1012		}
1013	}
1014
1015	public AvatarService avatarService() {
1016		return xmppConnectionService.getAvatarService();
1017	}
1018
1019	public void loadBitmap(Message message, ImageView imageView) {
1020		Bitmap bm;
1021		try {
1022			bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
1023		} catch (FileNotFoundException e) {
1024			bm = null;
1025		}
1026		if (bm != null) {
1027			cancelPotentialWork(message, imageView);
1028			imageView.setImageBitmap(bm);
1029			imageView.setBackgroundColor(0x00000000);
1030		} else {
1031			if (cancelPotentialWork(message, imageView)) {
1032				imageView.setBackgroundColor(0xff333333);
1033				imageView.setImageDrawable(null);
1034				final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
1035				final AsyncDrawable asyncDrawable = new AsyncDrawable(
1036						getResources(), null, task);
1037				imageView.setImageDrawable(asyncDrawable);
1038				try {
1039					task.execute(message);
1040				} catch (final RejectedExecutionException ignored) {
1041					ignored.printStackTrace();
1042				}
1043			}
1044		}
1045	}
1046
1047	protected interface OnValueEdited {
1048		String onValueEdited(String value);
1049	}
1050
1051	public interface OnPresenceSelected {
1052		void onPresenceSelected();
1053	}
1054
1055	public static class ConferenceInvite {
1056		private String uuid;
1057		private List<Jid> jids = new ArrayList<>();
1058
1059		public static ConferenceInvite parse(Intent data) {
1060			ConferenceInvite invite = new ConferenceInvite();
1061			invite.uuid = data.getStringExtra("conversation");
1062			if (invite.uuid == null) {
1063				return null;
1064			}
1065			try {
1066				if (data.getBooleanExtra("multiple", false)) {
1067					String[] toAdd = data.getStringArrayExtra("contacts");
1068					for (String item : toAdd) {
1069						invite.jids.add(Jid.fromString(item));
1070					}
1071				} else {
1072					invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
1073				}
1074			} catch (final InvalidJidException ignored) {
1075				return null;
1076			}
1077			return invite;
1078		}
1079
1080		public boolean execute(XmppActivity activity) {
1081			XmppConnectionService service = activity.xmppConnectionService;
1082			Conversation conversation = service.findConversationByUuid(this.uuid);
1083			if (conversation == null) {
1084				return false;
1085			}
1086			if (conversation.getMode() == Conversation.MODE_MULTI) {
1087				for (Jid jid : jids) {
1088					service.invite(conversation, jid);
1089				}
1090				return false;
1091			} else {
1092				jids.add(conversation.getJid().toBareJid());
1093				return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1094			}
1095		}
1096	}
1097
1098	static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1099		private final WeakReference<ImageView> imageViewReference;
1100		private final WeakReference<XmppActivity> activity;
1101		private Message message = null;
1102
1103		private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
1104			this.activity = new WeakReference<>(activity);
1105			this.imageViewReference = new WeakReference<>(imageView);
1106		}
1107
1108		@Override
1109		protected Bitmap doInBackground(Message... params) {
1110			if (isCancelled()) {
1111				return null;
1112			}
1113			message = params[0];
1114			try {
1115				XmppActivity activity = this.activity.get();
1116				if (activity != null && activity.xmppConnectionService != null) {
1117					return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
1118				} else {
1119					return null;
1120				}
1121			} catch (FileNotFoundException e) {
1122				return null;
1123			}
1124		}
1125
1126		@Override
1127		protected void onPostExecute(Bitmap bitmap) {
1128			if (bitmap != null && !isCancelled()) {
1129				final ImageView imageView = imageViewReference.get();
1130				if (imageView != null) {
1131					imageView.setImageBitmap(bitmap);
1132					imageView.setBackgroundColor(0x00000000);
1133				}
1134			}
1135		}
1136	}
1137
1138	private static class AsyncDrawable extends BitmapDrawable {
1139		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1140
1141		private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1142			super(res, bitmap);
1143			bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1144		}
1145
1146		private BitmapWorkerTask getBitmapWorkerTask() {
1147			return bitmapWorkerTaskReference.get();
1148		}
1149	}
1150}