XmppActivity.java

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