XmppActivity.java

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