XmppActivity.java

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