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