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