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