XmppActivity.java

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