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