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