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		Intent intent = new Intent(this, ChooseContactActivity.class);
 572		List<String> contacts = new ArrayList<>();
 573		if (conversation.getMode() == Conversation.MODE_MULTI) {
 574			for (MucOptions.User user : conversation.getMucOptions().getUsers(false)) {
 575				Jid jid = user.getRealJid();
 576				if (jid != null) {
 577					contacts.add(jid.toBareJid().toString());
 578				}
 579			}
 580		} else {
 581			contacts.add(conversation.getJid().toBareJid().toString());
 582		}
 583		intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
 584		intent.putExtra("conversation", conversation.getUuid());
 585		intent.putExtra("multiple", true);
 586		intent.putExtra("show_enter_jid", true);
 587		intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 588		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
 589	}
 590
 591	protected void announcePgp(Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 592		if (account.getPgpId() == 0) {
 593			choosePgpSignId(account);
 594		} else {
 595			String status = null;
 596			if (manuallyChangePresence()) {
 597				status = account.getPresenceStatusMessage();
 598			}
 599			if (status == null) {
 600				status = "";
 601			}
 602			xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<Account>() {
 603
 604				@Override
 605				public void userInputRequried(PendingIntent pi, Account account) {
 606					try {
 607						startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 608					} catch (final SendIntentException ignored) {
 609					}
 610				}
 611
 612				@Override
 613				public void success(Account account) {
 614					xmppConnectionService.databaseBackend.updateAccount(account);
 615					xmppConnectionService.sendPresence(account);
 616					if (conversation != null) {
 617						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 618						xmppConnectionService.updateConversation(conversation);
 619						refreshUi();
 620					}
 621					if (onSuccess != null) {
 622						runOnUiThread(onSuccess);
 623					}
 624				}
 625
 626				@Override
 627				public void error(int error, Account account) {
 628					if (error == 0 && account != null) {
 629						account.setPgpSignId(0);
 630						account.unsetPgpSignature();
 631						xmppConnectionService.databaseBackend.updateAccount(account);
 632						choosePgpSignId(account);
 633					} else {
 634						displayErrorDialog(error);
 635					}
 636				}
 637			});
 638		}
 639	}
 640
 641	protected boolean noAccountUsesPgp() {
 642		if (!hasPgp()) {
 643			return true;
 644		}
 645		for (Account account : xmppConnectionService.getAccounts()) {
 646			if (account.getPgpId() != 0) {
 647				return false;
 648			}
 649		}
 650		return true;
 651	}
 652
 653	@SuppressWarnings("deprecation")
 654	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 655	protected void setListItemBackgroundOnView(View view) {
 656		int sdk = android.os.Build.VERSION.SDK_INT;
 657		if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 658			view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 659		} else {
 660			view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 661		}
 662	}
 663
 664	protected void choosePgpSignId(Account account) {
 665		xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 666			@Override
 667			public void success(Account account1) {
 668			}
 669
 670			@Override
 671			public void error(int errorCode, Account object) {
 672
 673			}
 674
 675			@Override
 676			public void userInputRequried(PendingIntent pi, Account object) {
 677				try {
 678					startIntentSenderForResult(pi.getIntentSender(),
 679							REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 680				} catch (final SendIntentException ignored) {
 681				}
 682			}
 683		});
 684	}
 685
 686	protected void displayErrorDialog(final int errorCode) {
 687		runOnUiThread(() -> {
 688			Builder builder = new Builder(XmppActivity.this);
 689			builder.setIconAttribute(android.R.attr.alertDialogIcon);
 690			builder.setTitle(getString(R.string.error));
 691			builder.setMessage(errorCode);
 692			builder.setNeutralButton(R.string.accept, null);
 693			builder.create().show();
 694		});
 695
 696	}
 697
 698	protected void showAddToRosterDialog(final Contact contact) {
 699		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 700		builder.setTitle(contact.getJid().toString());
 701		builder.setMessage(getString(R.string.not_in_roster));
 702		builder.setNegativeButton(getString(R.string.cancel), null);
 703		builder.setPositiveButton(getString(R.string.add_contact),
 704				(dialog, which) -> {
 705					final Jid jid = contact.getJid();
 706					Account account = contact.getAccount();
 707					Contact contact1 = account.getRoster().getContact(jid);
 708					xmppConnectionService.createContact(contact1);
 709				});
 710		builder.create().show();
 711	}
 712
 713	private void showAskForPresenceDialog(final Contact contact) {
 714		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 715		builder.setTitle(contact.getJid().toString());
 716		builder.setMessage(R.string.request_presence_updates);
 717		builder.setNegativeButton(R.string.cancel, null);
 718		builder.setPositiveButton(R.string.request_now,
 719				(dialog, which) -> {
 720					if (xmppConnectionServiceBound) {
 721						xmppConnectionService.sendPresencePacket(contact
 722								.getAccount(), xmppConnectionService
 723								.getPresenceGenerator()
 724								.requestPresenceUpdatesFrom(contact));
 725					}
 726				});
 727		builder.create().show();
 728	}
 729
 730	protected void quickEdit(String previousValue, int hint, OnValueEdited callback) {
 731		quickEdit(previousValue, callback, hint, false);
 732	}
 733
 734	protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 735		quickEdit(previousValue, callback, R.string.password, true);
 736	}
 737
 738	@SuppressLint("InflateParams")
 739	private void quickEdit(final String previousValue,
 740	                       final OnValueEdited callback,
 741	                       final int hint,
 742	                       boolean password) {
 743		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 744		View view = getLayoutInflater().inflate(R.layout.quickedit, null);
 745		final EditText editor = view.findViewById(R.id.editor);
 746		if (password) {
 747			editor.setInputType(InputType.TYPE_CLASS_TEXT
 748					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
 749		}
 750		builder.setPositiveButton(R.string.accept, null);
 751		if (hint != 0) {
 752			editor.setHint(hint);
 753		}
 754		editor.requestFocus();
 755		editor.setText("");
 756		if (previousValue != null) {
 757			editor.getText().append(previousValue);
 758		}
 759		builder.setView(view);
 760		builder.setNegativeButton(R.string.cancel, null);
 761		final AlertDialog dialog = builder.create();
 762		dialog.show();
 763		View.OnClickListener clickListener = v -> {
 764			String value = editor.getText().toString();
 765			if (!value.equals(previousValue) && value.trim().length() > 0) {
 766				String error = callback.onValueEdited(value);
 767				if (error != null) {
 768					editor.setError(error);
 769					return;
 770				}
 771			}
 772			dialog.dismiss();
 773		};
 774		dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 775	}
 776
 777	protected boolean hasStoragePermission(int requestCode) {
 778		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 779			if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 780				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 781				return false;
 782			} else {
 783				return true;
 784			}
 785		} else {
 786			return true;
 787		}
 788	}
 789
 790	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 791		super.onActivityResult(requestCode, resultCode, data);
 792		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 793			mPendingConferenceInvite = ConferenceInvite.parse(data);
 794			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 795				if (mPendingConferenceInvite.execute(this)) {
 796					mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 797					mToast.show();
 798				}
 799				mPendingConferenceInvite = null;
 800			}
 801		}
 802	}
 803
 804	public int getTertiaryTextColor() {
 805		return this.mTertiaryTextColor;
 806	}
 807
 808	public int getSecondaryTextColor() {
 809		return this.mSecondaryTextColor;
 810	}
 811
 812	public int getPrimaryTextColor() {
 813		return this.mPrimaryTextColor;
 814	}
 815
 816	public int getWarningTextColor() {
 817		return this.mColorRed;
 818	}
 819
 820	public int getOnlineColor() {
 821		return this.mColorGreen;
 822	}
 823
 824	public int getPixel(int dp) {
 825		DisplayMetrics metrics = getResources().getDisplayMetrics();
 826		return ((int) (dp * metrics.density));
 827	}
 828
 829	public boolean copyTextToClipboard(String text, int labelResId) {
 830		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 831		String label = getResources().getString(labelResId);
 832		if (mClipBoardManager != null) {
 833			ClipData mClipData = ClipData.newPlainText(label, text);
 834			mClipBoardManager.setPrimaryClip(mClipData);
 835			return true;
 836		}
 837		return false;
 838	}
 839
 840	protected boolean neverCompressPictures() {
 841		return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
 842	}
 843
 844	protected boolean manuallyChangePresence() {
 845		return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
 846	}
 847
 848	protected String getShareableUri() {
 849		return getShareableUri(false);
 850	}
 851
 852	protected String getShareableUri(boolean http) {
 853		return null;
 854	}
 855
 856	protected void shareLink(boolean http) {
 857		String uri = getShareableUri(http);
 858		if (uri == null || uri.isEmpty()) {
 859			return;
 860		}
 861		Intent intent = new Intent(Intent.ACTION_SEND);
 862		intent.setType("text/plain");
 863		intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 864		try {
 865			startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 866		} catch (ActivityNotFoundException e) {
 867			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 868		}
 869	}
 870
 871	protected void launchOpenKeyChain(long keyId) {
 872		PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 873		try {
 874			startIntentSenderForResult(
 875					pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 876					0, 0);
 877		} catch (Throwable e) {
 878			Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 879		}
 880	}
 881
 882	@Override
 883	public void onResume() {
 884		super.onResume();
 885	}
 886
 887	protected int findTheme() {
 888		Boolean dark = getPreferences().getString(SettingsActivity.THEME, getResources().getString(R.string.theme)).equals("dark");
 889		Boolean larger = getPreferences().getBoolean("use_larger_font", getResources().getBoolean(R.bool.use_larger_font));
 890
 891		if (dark) {
 892			if (larger)
 893				return R.style.ConversationsTheme_Dark_LargerText;
 894			else
 895				return R.style.ConversationsTheme_Dark;
 896		} else {
 897			if (larger)
 898				return R.style.ConversationsTheme_LargerText;
 899			else
 900				return R.style.ConversationsTheme;
 901		}
 902	}
 903
 904	@Override
 905	public void onPause() {
 906		super.onPause();
 907	}
 908
 909	protected void showQrCode() {
 910		showQrCode(getShareableUri());
 911	}
 912
 913	protected void showQrCode(final String uri) {
 914		if (uri == null || uri.isEmpty()) {
 915			return;
 916		}
 917		Point size = new Point();
 918		getWindowManager().getDefaultDisplay().getSize(size);
 919		final int width = (size.x < size.y ? size.x : size.y);
 920		Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
 921		ImageView view = new ImageView(this);
 922		view.setBackgroundColor(Color.WHITE);
 923		view.setImageBitmap(bitmap);
 924		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 925		builder.setView(view);
 926		builder.create().show();
 927	}
 928
 929	protected Account extractAccount(Intent intent) {
 930		String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
 931		try {
 932			return jid != null ? xmppConnectionService.findAccountByJid(Jid.fromString(jid)) : null;
 933		} catch (InvalidJidException e) {
 934			return null;
 935		}
 936	}
 937
 938	public AvatarService avatarService() {
 939		return xmppConnectionService.getAvatarService();
 940	}
 941
 942	public void loadBitmap(Message message, ImageView imageView) {
 943		Bitmap bm;
 944		try {
 945			bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
 946		} catch (FileNotFoundException e) {
 947			bm = null;
 948		}
 949		if (bm != null) {
 950			cancelPotentialWork(message, imageView);
 951			imageView.setImageBitmap(bm);
 952			imageView.setBackgroundColor(0x00000000);
 953		} else {
 954			if (cancelPotentialWork(message, imageView)) {
 955				imageView.setBackgroundColor(0xff333333);
 956				imageView.setImageDrawable(null);
 957				final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
 958				final AsyncDrawable asyncDrawable = new AsyncDrawable(
 959						getResources(), null, task);
 960				imageView.setImageDrawable(asyncDrawable);
 961				try {
 962					task.execute(message);
 963				} catch (final RejectedExecutionException ignored) {
 964					ignored.printStackTrace();
 965				}
 966			}
 967		}
 968	}
 969
 970	protected interface OnValueEdited {
 971		String onValueEdited(String value);
 972	}
 973
 974	public static class ConferenceInvite {
 975		private String uuid;
 976		private List<Jid> jids = new ArrayList<>();
 977
 978		public static ConferenceInvite parse(Intent data) {
 979			ConferenceInvite invite = new ConferenceInvite();
 980			invite.uuid = data.getStringExtra("conversation");
 981			if (invite.uuid == null) {
 982				return null;
 983			}
 984			try {
 985				if (data.getBooleanExtra("multiple", false)) {
 986					String[] toAdd = data.getStringArrayExtra("contacts");
 987					for (String item : toAdd) {
 988						invite.jids.add(Jid.fromString(item));
 989					}
 990				} else {
 991					invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
 992				}
 993			} catch (final InvalidJidException ignored) {
 994				return null;
 995			}
 996			return invite;
 997		}
 998
 999		public boolean execute(XmppActivity activity) {
1000			XmppConnectionService service = activity.xmppConnectionService;
1001			Conversation conversation = service.findConversationByUuid(this.uuid);
1002			if (conversation == null) {
1003				return false;
1004			}
1005			if (conversation.getMode() == Conversation.MODE_MULTI) {
1006				for (Jid jid : jids) {
1007					service.invite(conversation, jid);
1008				}
1009				return false;
1010			} else {
1011				jids.add(conversation.getJid().toBareJid());
1012				return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1013			}
1014		}
1015	}
1016
1017	static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1018		private final WeakReference<ImageView> imageViewReference;
1019		private final WeakReference<XmppActivity> activity;
1020		private Message message = null;
1021
1022		private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
1023			this.activity = new WeakReference<>(activity);
1024			this.imageViewReference = new WeakReference<>(imageView);
1025		}
1026
1027		@Override
1028		protected Bitmap doInBackground(Message... params) {
1029			if (isCancelled()) {
1030				return null;
1031			}
1032			message = params[0];
1033			try {
1034				XmppActivity activity = this.activity.get();
1035				if (activity != null && activity.xmppConnectionService != null) {
1036					return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
1037				} else {
1038					return null;
1039				}
1040			} catch (FileNotFoundException e) {
1041				return null;
1042			}
1043		}
1044
1045		@Override
1046		protected void onPostExecute(Bitmap bitmap) {
1047			if (bitmap != null && !isCancelled()) {
1048				final ImageView imageView = imageViewReference.get();
1049				if (imageView != null) {
1050					imageView.setImageBitmap(bitmap);
1051					imageView.setBackgroundColor(0x00000000);
1052				}
1053			}
1054		}
1055	}
1056
1057	private static class AsyncDrawable extends BitmapDrawable {
1058		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1059
1060		private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1061			super(res, bitmap);
1062			bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1063		}
1064
1065		private BitmapWorkerTask getBitmapWorkerTask() {
1066			return bitmapWorkerTaskReference.get();
1067		}
1068	}
1069}