XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.annotation.TargetApi;
   6import android.app.ActionBar;
   7import android.app.Activity;
   8import android.app.AlertDialog;
   9import android.app.AlertDialog.Builder;
  10import android.app.PendingIntent;
  11import android.content.ActivityNotFoundException;
  12import android.content.ClipData;
  13import android.content.ClipboardManager;
  14import android.content.ComponentName;
  15import android.content.Context;
  16import android.content.DialogInterface;
  17import android.content.DialogInterface.OnClickListener;
  18import android.content.Intent;
  19import android.content.IntentSender.SendIntentException;
  20import android.content.ServiceConnection;
  21import android.content.SharedPreferences;
  22import android.content.pm.PackageManager;
  23import android.content.pm.ResolveInfo;
  24import android.content.res.Resources;
  25import android.content.res.TypedArray;
  26import android.graphics.Bitmap;
  27import android.graphics.Color;
  28import android.graphics.Point;
  29import android.graphics.drawable.BitmapDrawable;
  30import android.graphics.drawable.Drawable;
  31import android.net.ConnectivityManager;
  32import android.net.Uri;
  33import android.nfc.NdefMessage;
  34import android.nfc.NdefRecord;
  35import android.nfc.NfcAdapter;
  36import android.nfc.NfcEvent;
  37import android.os.AsyncTask;
  38import android.os.Build;
  39import android.os.Bundle;
  40import android.os.Handler;
  41import android.os.IBinder;
  42import android.os.PowerManager;
  43import android.os.SystemClock;
  44import android.preference.PreferenceManager;
  45import android.text.InputType;
  46import android.util.DisplayMetrics;
  47import android.util.Pair;
  48import android.view.MenuItem;
  49import android.view.View;
  50import android.view.inputmethod.InputMethodManager;
  51import android.widget.EditText;
  52import android.widget.ImageView;
  53import android.widget.Toast;
  54
  55import net.java.otr4j.session.SessionID;
  56
  57import java.io.FileNotFoundException;
  58import java.lang.ref.WeakReference;
  59import java.util.ArrayList;
  60import java.util.Collections;
  61import java.util.List;
  62import java.util.Map;
  63import java.util.concurrent.RejectedExecutionException;
  64import java.util.concurrent.atomic.AtomicInteger;
  65
  66import eu.siacs.conversations.Config;
  67import eu.siacs.conversations.R;
  68import eu.siacs.conversations.entities.Account;
  69import eu.siacs.conversations.entities.Contact;
  70import eu.siacs.conversations.entities.Conversation;
  71import eu.siacs.conversations.entities.Message;
  72import eu.siacs.conversations.entities.MucOptions;
  73import eu.siacs.conversations.entities.Presences;
  74import eu.siacs.conversations.services.AvatarService;
  75import eu.siacs.conversations.services.BarcodeProvider;
  76import eu.siacs.conversations.services.XmppConnectionService;
  77import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  78import eu.siacs.conversations.utils.CryptoHelper;
  79import eu.siacs.conversations.utils.ExceptionHelper;
  80import eu.siacs.conversations.utils.UIHelper;
  81import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  82import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  83import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  84import eu.siacs.conversations.xmpp.jid.Jid;
  85
  86public abstract class XmppActivity extends Activity {
  87
  88	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
  89	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
  90	protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
  91	protected static final int REQUEST_BATTERY_OP = 0x13849ff;
  92
  93	public static final String EXTRA_ACCOUNT = "account";
  94
  95	public XmppConnectionService xmppConnectionService;
  96	public boolean xmppConnectionServiceBound = false;
  97	protected boolean registeredListeners = false;
  98
  99	protected int mPrimaryTextColor;
 100	protected int mSecondaryTextColor;
 101	protected int mTertiaryTextColor;
 102	protected int mPrimaryBackgroundColor;
 103	protected int mSecondaryBackgroundColor;
 104	protected int mColorRed;
 105	protected int mColorOrange;
 106	protected int mColorGreen;
 107	protected int mPrimaryColor;
 108
 109	protected boolean mUseSubject = true;
 110
 111	private DisplayMetrics metrics;
 112	protected int mTheme;
 113	protected boolean mUsingEnterKey = false;
 114
 115	protected Toast mToast;
 116
 117	protected void hideToast() {
 118		if (mToast != null) {
 119			mToast.cancel();
 120		}
 121	}
 122
 123	protected void replaceToast(String msg) {
 124		replaceToast(msg, true);
 125	}
 126
 127	protected void replaceToast(String msg, boolean showlong) {
 128		hideToast();
 129		mToast = Toast.makeText(this, msg ,showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
 130		mToast.show();
 131	}
 132
 133	protected Runnable onOpenPGPKeyPublished = new Runnable() {
 134		@Override
 135		public void run() {
 136			Toast.makeText(XmppActivity.this,R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
 137		}
 138	};
 139
 140	private long mLastUiRefresh = 0;
 141	private Handler mRefreshUiHandler = new Handler();
 142	private Runnable mRefreshUiRunnable = new Runnable() {
 143		@Override
 144		public void run() {
 145			mLastUiRefresh = SystemClock.elapsedRealtime();
 146			refreshUiReal();
 147		}
 148	};
 149
 150	protected ConferenceInvite mPendingConferenceInvite = null;
 151
 152
 153	protected final void refreshUi() {
 154		final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 155		if (diff > Config.REFRESH_UI_INTERVAL) {
 156			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 157			runOnUiThread(mRefreshUiRunnable);
 158		} else {
 159			final long next = Config.REFRESH_UI_INTERVAL - diff;
 160			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 161			mRefreshUiHandler.postDelayed(mRefreshUiRunnable,next);
 162		}
 163	}
 164
 165	abstract protected void refreshUiReal();
 166
 167	protected interface OnValueEdited {
 168		public void onValueEdited(String value);
 169	}
 170
 171	public interface OnPresenceSelected {
 172		public void onPresenceSelected();
 173	}
 174
 175	protected ServiceConnection mConnection = new ServiceConnection() {
 176
 177		@Override
 178		public void onServiceConnected(ComponentName className, IBinder service) {
 179			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 180			xmppConnectionService = binder.getService();
 181			xmppConnectionServiceBound = true;
 182			if (!registeredListeners && shouldRegisterListeners()) {
 183				registerListeners();
 184				registeredListeners = true;
 185			}
 186			onBackendConnected();
 187		}
 188
 189		@Override
 190		public void onServiceDisconnected(ComponentName arg0) {
 191			xmppConnectionServiceBound = false;
 192		}
 193	};
 194
 195	@Override
 196	protected void onStart() {
 197		super.onStart();
 198		if (!xmppConnectionServiceBound) {
 199			connectToBackend();
 200		} else {
 201			if (!registeredListeners) {
 202				this.registerListeners();
 203				this.registeredListeners = true;
 204			}
 205			this.onBackendConnected();
 206		}
 207	}
 208
 209	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
 210	protected boolean shouldRegisterListeners() {
 211		if  (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
 212			return !isDestroyed() && !isFinishing();
 213		} else {
 214			return !isFinishing();
 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) {
 230				this.unregisterListeners();
 231				this.registeredListeners = false;
 232			}
 233			unbindService(mConnection);
 234			xmppConnectionServiceBound = false;
 235		}
 236	}
 237
 238	protected void hideKeyboard() {
 239		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 240
 241		View focus = getCurrentFocus();
 242
 243		if (focus != null) {
 244
 245			inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
 246					InputMethodManager.HIDE_NOT_ALWAYS);
 247		}
 248	}
 249
 250	public boolean hasPgp() {
 251		return xmppConnectionService.getPgpEngine() != null;
 252	}
 253
 254	public void showInstallPgpDialog() {
 255		Builder builder = new AlertDialog.Builder(this);
 256		builder.setTitle(getString(R.string.openkeychain_required));
 257		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 258		builder.setMessage(getText(R.string.openkeychain_required_long));
 259		builder.setNegativeButton(getString(R.string.cancel), null);
 260		builder.setNeutralButton(getString(R.string.restart),
 261				new OnClickListener() {
 262
 263					@Override
 264					public void onClick(DialogInterface dialog, int which) {
 265						if (xmppConnectionServiceBound) {
 266							unbindService(mConnection);
 267							xmppConnectionServiceBound = false;
 268						}
 269						stopService(new Intent(XmppActivity.this,
 270									XmppConnectionService.class));
 271						finish();
 272					}
 273				});
 274		builder.setPositiveButton(getString(R.string.install),
 275				new OnClickListener() {
 276
 277					@Override
 278					public void onClick(DialogInterface dialog, int 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				});
 298		builder.create().show();
 299	}
 300
 301	abstract void onBackendConnected();
 302
 303	protected void registerListeners() {
 304		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 305			this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 306		}
 307		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 308			this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 309		}
 310		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 311			this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 312		}
 313		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 314			this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 315		}
 316		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 317			this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 318		}
 319		if (this instanceof OnUpdateBlocklist) {
 320			this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 321		}
 322		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 323			this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 324		}
 325		if (this instanceof OnKeyStatusUpdated) {
 326			this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 327		}
 328	}
 329
 330	protected void unregisterListeners() {
 331		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 332			this.xmppConnectionService.removeOnConversationListChangedListener();
 333		}
 334		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 335			this.xmppConnectionService.removeOnAccountListChangedListener();
 336		}
 337		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 338			this.xmppConnectionService.removeOnCaptchaRequestedListener();
 339		}
 340		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 341			this.xmppConnectionService.removeOnRosterUpdateListener();
 342		}
 343		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 344			this.xmppConnectionService.removeOnMucRosterUpdateListener();
 345		}
 346		if (this instanceof OnUpdateBlocklist) {
 347			this.xmppConnectionService.removeOnUpdateBlocklistListener();
 348		}
 349		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 350			this.xmppConnectionService.removeOnShowErrorToastListener();
 351		}
 352		if (this instanceof OnKeyStatusUpdated) {
 353			this.xmppConnectionService.removeOnNewKeysAvailableListener();
 354		}
 355	}
 356
 357	@Override
 358	public boolean onOptionsItemSelected(final MenuItem item) {
 359		switch (item.getItemId()) {
 360			case R.id.action_settings:
 361				startActivity(new Intent(this, SettingsActivity.class));
 362				break;
 363			case R.id.action_accounts:
 364				startActivity(new Intent(this, ManageAccountActivity.class));
 365				break;
 366			case android.R.id.home:
 367				finish();
 368				break;
 369			case R.id.action_show_qr_code:
 370				showQrCode();
 371				break;
 372		}
 373		return super.onOptionsItemSelected(item);
 374	}
 375
 376	@Override
 377	protected void onCreate(Bundle savedInstanceState) {
 378		super.onCreate(savedInstanceState);
 379		metrics = getResources().getDisplayMetrics();
 380		ExceptionHelper.init(getApplicationContext());
 381
 382		mPrimaryTextColor = getResources().getColor(R.color.black87);
 383		mSecondaryTextColor = getResources().getColor(R.color.black54);
 384		mTertiaryTextColor = getResources().getColor(R.color.black12);
 385		mColorRed = getResources().getColor(R.color.red800);
 386		mColorOrange = getResources().getColor(R.color.orange500);
 387		mColorGreen = getResources().getColor(R.color.green500);
 388		mPrimaryColor = getResources().getColor(R.color.primary500);
 389		mPrimaryBackgroundColor = getResources().getColor(R.color.grey50);
 390		mSecondaryBackgroundColor = getResources().getColor(R.color.grey200);
 391
 392		if(isDarkTheme()) {
 393			mPrimaryTextColor = getResources().getColor(R.color.white);
 394			mSecondaryTextColor = getResources().getColor(R.color.white70);
 395			mTertiaryTextColor = getResources().getColor(R.color.white12);
 396			mPrimaryBackgroundColor = getResources().getColor(R.color.grey800);
 397			mSecondaryBackgroundColor = getResources().getColor(R.color.grey900);
 398		}
 399
 400		this.mTheme = findTheme();
 401		setTheme(this.mTheme);
 402
 403		this.mUsingEnterKey = usingEnterKey();
 404		mUseSubject = getPreferences().getBoolean("use_subject", true);
 405		final ActionBar ab = getActionBar();
 406		if (ab!=null) {
 407			ab.setDisplayHomeAsUpEnabled(true);
 408		}
 409	}
 410
 411	public boolean isDarkTheme() {
 412		return getPreferences().getString("theme", "light").equals("dark");
 413	}
 414
 415	public int getThemeResource(int r_attr_name, int r_drawable_def) {
 416		int[] attrs = {	r_attr_name };
 417		TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 418
 419		int res = ta.getResourceId(0, r_drawable_def);
 420		ta.recycle();
 421
 422		return res;
 423	}
 424
 425	protected boolean isOptimizingBattery() {
 426		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 427			PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 428			return !pm.isIgnoringBatteryOptimizations(getPackageName());
 429		} else {
 430			return false;
 431		}
 432	}
 433
 434	protected boolean isAffectedByDataSaver() {
 435		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 436			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 437			return cm.isActiveNetworkMetered()
 438					&& cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 439		} else {
 440			return false;
 441		}
 442	}
 443
 444	protected boolean usingEnterKey() {
 445		return getPreferences().getBoolean("display_enter_key", false);
 446	}
 447
 448	protected SharedPreferences getPreferences() {
 449		return PreferenceManager
 450			.getDefaultSharedPreferences(getApplicationContext());
 451	}
 452
 453	public boolean useSubjectToIdentifyConference() {
 454		return mUseSubject;
 455	}
 456
 457	public void switchToConversation(Conversation conversation) {
 458		switchToConversation(conversation, null, false);
 459	}
 460
 461	public void switchToConversation(Conversation conversation, String text,
 462			boolean newTask) {
 463		switchToConversation(conversation,text,null,false,newTask);
 464	}
 465
 466	public void highlightInMuc(Conversation conversation, String nick) {
 467		switchToConversation(conversation, null, nick, false, false);
 468	}
 469
 470	public void privateMsgInMuc(Conversation conversation, String nick) {
 471		switchToConversation(conversation, null, nick, true, false);
 472	}
 473
 474	private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
 475		Intent viewConversationIntent = new Intent(this,
 476				ConversationActivity.class);
 477		viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
 478		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
 479				conversation.getUuid());
 480		if (text != null) {
 481			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
 482		}
 483		if (nick != null) {
 484			viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
 485			viewConversationIntent.putExtra(ConversationActivity.PRIVATE_MESSAGE,pm);
 486		}
 487		if (newTask) {
 488			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 489					| Intent.FLAG_ACTIVITY_NEW_TASK
 490					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
 491		} else {
 492			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 493					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
 494		}
 495		startActivity(viewConversationIntent);
 496		finish();
 497	}
 498
 499	public void switchToContactDetails(Contact contact) {
 500		switchToContactDetails(contact, null);
 501	}
 502
 503	public void switchToContactDetails(Contact contact, String messageFingerprint) {
 504		Intent intent = new Intent(this, ContactDetailsActivity.class);
 505		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 506		intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().toBareJid().toString());
 507		intent.putExtra("contact", contact.getJid().toString());
 508		intent.putExtra("fingerprint", messageFingerprint);
 509		startActivity(intent);
 510	}
 511
 512	public void switchToAccount(Account account) {
 513		switchToAccount(account, false);
 514	}
 515
 516	public void switchToAccount(Account account, boolean init) {
 517		Intent intent = new Intent(this, EditAccountActivity.class);
 518		intent.putExtra("jid", account.getJid().toBareJid().toString());
 519		intent.putExtra("init", init);
 520		startActivity(intent);
 521	}
 522
 523	protected void inviteToConversation(Conversation conversation) {
 524		Intent intent = new Intent(getApplicationContext(),
 525				ChooseContactActivity.class);
 526		List<String> contacts = new ArrayList<>();
 527		if (conversation.getMode() == Conversation.MODE_MULTI) {
 528			for (MucOptions.User user : conversation.getMucOptions().getUsers(false)) {
 529				Jid jid = user.getRealJid();
 530				if (jid != null) {
 531					contacts.add(jid.toBareJid().toString());
 532				}
 533			}
 534		} else {
 535			contacts.add(conversation.getJid().toBareJid().toString());
 536		}
 537		intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
 538		intent.putExtra("conversation", conversation.getUuid());
 539		intent.putExtra("multiple", true);
 540		intent.putExtra("show_enter_jid", true);
 541		intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 542		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
 543	}
 544
 545	protected void announcePgp(Account account, final Conversation conversation, final Runnable onSuccess) {
 546		if (account.getPgpId() == 0) {
 547			choosePgpSignId(account);
 548		} else {
 549			String status = null;
 550			if (manuallyChangePresence()) {
 551				status = account.getPresenceStatusMessage();
 552			}
 553			if (status == null) {
 554				status = "";
 555			}
 556			xmppConnectionService.getPgpEngine().generateSignature(account, status, new UiCallback<Account>() {
 557
 558				@Override
 559				public void userInputRequried(PendingIntent pi, Account account) {
 560					try {
 561						startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 562					} catch (final SendIntentException ignored) {
 563					}
 564				}
 565
 566				@Override
 567				public void success(Account account) {
 568					xmppConnectionService.databaseBackend.updateAccount(account);
 569					xmppConnectionService.sendPresence(account);
 570					if (conversation != null) {
 571						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 572						xmppConnectionService.updateConversation(conversation);
 573						refreshUi();
 574					}
 575					if (onSuccess != null) {
 576						runOnUiThread(onSuccess);
 577					}
 578				}
 579
 580				@Override
 581				public void error(int error, Account account) {
 582					if (error == 0 && account != null) {
 583						account.setPgpSignId(0);
 584						account.unsetPgpSignature();
 585						xmppConnectionService.databaseBackend.updateAccount(account);
 586						choosePgpSignId(account);
 587					} else {
 588						displayErrorDialog(error);
 589					}
 590				}
 591			});
 592		}
 593	}
 594
 595	protected  boolean noAccountUsesPgp() {
 596		if (!hasPgp()) {
 597			return true;
 598		}
 599		for(Account account : xmppConnectionService.getAccounts()) {
 600			if (account.getPgpId() != 0) {
 601				return false;
 602			}
 603		}
 604		return true;
 605	}
 606
 607	@SuppressWarnings("deprecation")
 608	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 609	protected void setListItemBackgroundOnView(View view) {
 610		int sdk = android.os.Build.VERSION.SDK_INT;
 611		if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 612			view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 613		} else {
 614			view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 615		}
 616	}
 617
 618	protected void choosePgpSignId(Account account) {
 619		xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 620			@Override
 621			public void success(Account account1) {
 622			}
 623
 624			@Override
 625			public void error(int errorCode, Account object) {
 626
 627			}
 628
 629			@Override
 630			public void userInputRequried(PendingIntent pi, Account object) {
 631				try {
 632					startIntentSenderForResult(pi.getIntentSender(),
 633							REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 634				} catch (final SendIntentException ignored) {
 635				}
 636			}
 637		});
 638	}
 639
 640	protected void displayErrorDialog(final int errorCode) {
 641		runOnUiThread(new Runnable() {
 642
 643			@Override
 644			public void run() {
 645				AlertDialog.Builder builder = new AlertDialog.Builder(
 646						XmppActivity.this);
 647				builder.setIconAttribute(android.R.attr.alertDialogIcon);
 648				builder.setTitle(getString(R.string.error));
 649				builder.setMessage(errorCode);
 650				builder.setNeutralButton(R.string.accept, null);
 651				builder.create().show();
 652			}
 653		});
 654
 655	}
 656
 657	protected void showAddToRosterDialog(final Conversation conversation) {
 658		showAddToRosterDialog(conversation.getContact());
 659	}
 660
 661	protected void showAddToRosterDialog(final Contact contact) {
 662		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 663		builder.setTitle(contact.getJid().toString());
 664		builder.setMessage(getString(R.string.not_in_roster));
 665		builder.setNegativeButton(getString(R.string.cancel), null);
 666		builder.setPositiveButton(getString(R.string.add_contact),
 667				new DialogInterface.OnClickListener() {
 668
 669					@Override
 670					public void onClick(DialogInterface dialog, int which) {
 671						final Jid jid = contact.getJid();
 672						Account account = contact.getAccount();
 673						Contact contact = account.getRoster().getContact(jid);
 674						xmppConnectionService.createContact(contact);
 675					}
 676				});
 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				new DialogInterface.OnClickListener() {
 687
 688					@Override
 689					public void onClick(DialogInterface dialog, int which) {
 690						if (xmppConnectionServiceBound) {
 691							xmppConnectionService.sendPresencePacket(contact
 692									.getAccount(), xmppConnectionService
 693									.getPresenceGenerator()
 694									.requestPresenceUpdatesFrom(contact));
 695						}
 696					}
 697				});
 698		builder.create().show();
 699	}
 700
 701	private void warnMutalPresenceSubscription(final Conversation conversation,
 702			final OnPresenceSelected listener) {
 703		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 704		builder.setTitle(conversation.getContact().getJid().toString());
 705		builder.setMessage(R.string.without_mutual_presence_updates);
 706		builder.setNegativeButton(R.string.cancel, null);
 707		builder.setPositiveButton(R.string.ignore, new OnClickListener() {
 708
 709			@Override
 710			public void onClick(DialogInterface dialog, int which) {
 711				conversation.setNextCounterpart(null);
 712				if (listener != null) {
 713					listener.onPresenceSelected();
 714				}
 715			}
 716		});
 717		builder.create().show();
 718	}
 719
 720	protected void quickEdit(String previousValue, int hint, OnValueEdited callback) {
 721		quickEdit(previousValue, callback, hint, false);
 722	}
 723
 724	protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 725		quickEdit(previousValue, callback, R.string.password, true);
 726	}
 727
 728	@SuppressLint("InflateParams")
 729	private void quickEdit(final String previousValue,
 730						   final OnValueEdited callback,
 731						   final int hint,
 732						   boolean password) {
 733		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 734		View view = getLayoutInflater().inflate(R.layout.quickedit, null);
 735		final EditText editor = (EditText) view.findViewById(R.id.editor);
 736		OnClickListener mClickListener = new OnClickListener() {
 737
 738			@Override
 739			public void onClick(DialogInterface dialog, int which) {
 740				String value = editor.getText().toString();
 741				if (!value.equals(previousValue) && value.trim().length() > 0) {
 742					callback.onValueEdited(value);
 743				}
 744			}
 745		};
 746		if (password) {
 747			editor.setInputType(InputType.TYPE_CLASS_TEXT
 748					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
 749			builder.setPositiveButton(R.string.accept, mClickListener);
 750		} else {
 751			builder.setPositiveButton(R.string.edit, mClickListener);
 752		}
 753		if (hint != 0) {
 754			editor.setHint(hint);
 755		}
 756		editor.requestFocus();
 757		editor.setText("");
 758		if (previousValue != null) {
 759			editor.getText().append(previousValue);
 760		}
 761		builder.setView(view);
 762		builder.setNegativeButton(R.string.cancel, null);
 763		builder.create().show();
 764	}
 765
 766	public boolean hasStoragePermission(int requestCode) {
 767		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 768			if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 769				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 770				return false;
 771			} else {
 772				return true;
 773			}
 774		} else {
 775			return true;
 776		}
 777	}
 778
 779	public void selectPresence(final Conversation conversation,
 780			final OnPresenceSelected listener) {
 781		final Contact contact = conversation.getContact();
 782		if (conversation.hasValidOtrSession()) {
 783			SessionID id = conversation.getOtrSession().getSessionID();
 784			Jid jid;
 785			try {
 786				jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
 787			} catch (InvalidJidException e) {
 788				jid = null;
 789			}
 790			conversation.setNextCounterpart(jid);
 791			listener.onPresenceSelected();
 792		} else 	if (!contact.showInRoster()) {
 793			showAddToRosterDialog(conversation);
 794		} else {
 795			final Presences presences = contact.getPresences();
 796			if (presences.size() == 0) {
 797				if (!contact.getOption(Contact.Options.TO)
 798						&& !contact.getOption(Contact.Options.ASKING)
 799						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 800					showAskForPresenceDialog(contact);
 801				} else if (!contact.getOption(Contact.Options.TO)
 802						|| !contact.getOption(Contact.Options.FROM)) {
 803					warnMutalPresenceSubscription(conversation, listener);
 804				} else {
 805					conversation.setNextCounterpart(null);
 806					listener.onPresenceSelected();
 807				}
 808			} else if (presences.size() == 1) {
 809				String presence = presences.toResourceArray()[0];
 810				try {
 811					conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
 812				} catch (InvalidJidException e) {
 813					conversation.setNextCounterpart(null);
 814				}
 815				listener.onPresenceSelected();
 816			} else {
 817				showPresenceSelectionDialog(presences,conversation,listener);
 818			}
 819		}
 820	}
 821
 822	private void showPresenceSelectionDialog(Presences presences, final Conversation conversation, final OnPresenceSelected listener) {
 823		final Contact contact = conversation.getContact();
 824		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 825		builder.setTitle(getString(R.string.choose_presence));
 826		final String[] resourceArray = presences.toResourceArray();
 827		Pair<Map<String, String>, Map<String, String>> typeAndName = presences.toTypeAndNameMap();
 828		final Map<String,String> resourceTypeMap = typeAndName.first;
 829		final Map<String,String> resourceNameMap = typeAndName.second;
 830		final String[] readableIdentities = new String[resourceArray.length];
 831		final AtomicInteger selectedResource = new AtomicInteger(0);
 832		for (int i = 0; i < resourceArray.length; ++i) {
 833			String resource = resourceArray[i];
 834			if (resource.equals(contact.getLastResource())) {
 835				selectedResource.set(i);
 836			}
 837			String type = resourceTypeMap.get(resource);
 838			String name = resourceNameMap.get(resource);
 839			if (type != null) {
 840				if (Collections.frequency(resourceTypeMap.values(),type) == 1) {
 841					readableIdentities[i] = UIHelper.tranlasteType(this,type);
 842				} else if (name != null) {
 843					if (Collections.frequency(resourceNameMap.values(), name) == 1
 844							|| CryptoHelper.UUID_PATTERN.matcher(resource).matches()) {
 845						readableIdentities[i] = UIHelper.tranlasteType(this,type) + "  (" + name+")";
 846					} else {
 847						readableIdentities[i] = UIHelper.tranlasteType(this,type) + " (" + name +" / " + resource+")";
 848					}
 849				} else {
 850					readableIdentities[i] = UIHelper.tranlasteType(this,type) + " (" + resource+")";
 851				}
 852			} else {
 853				readableIdentities[i] = resource;
 854			}
 855		}
 856		builder.setSingleChoiceItems(readableIdentities,
 857				selectedResource.get(),
 858				new DialogInterface.OnClickListener() {
 859
 860					@Override
 861					public void onClick(DialogInterface dialog, int which) {
 862						selectedResource.set(which);
 863					}
 864				});
 865		builder.setNegativeButton(R.string.cancel, null);
 866		builder.setPositiveButton(R.string.ok, new OnClickListener() {
 867
 868			@Override
 869			public void onClick(DialogInterface dialog, int which) {
 870				try {
 871					Jid next = Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),resourceArray[selectedResource.get()]);
 872					conversation.setNextCounterpart(next);
 873				} catch (InvalidJidException e) {
 874					conversation.setNextCounterpart(null);
 875				}
 876				listener.onPresenceSelected();
 877			}
 878		});
 879		builder.create().show();
 880	}
 881
 882	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 883		super.onActivityResult(requestCode, resultCode, data);
 884		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 885			mPendingConferenceInvite = ConferenceInvite.parse(data);
 886			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 887				if (mPendingConferenceInvite.execute(this)) {
 888					mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 889					mToast.show();
 890				}
 891				mPendingConferenceInvite = null;
 892			}
 893		}
 894	}
 895
 896
 897	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 898		@Override
 899		public void success(final Conversation conversation) {
 900			runOnUiThread(new Runnable() {
 901				@Override
 902				public void run() {
 903					switchToConversation(conversation);
 904					hideToast();
 905				}
 906			});
 907		}
 908
 909		@Override
 910		public void error(final int errorCode, Conversation object) {
 911			runOnUiThread(new Runnable() {
 912				@Override
 913				public void run() {
 914					replaceToast(getString(errorCode));
 915				}
 916			});
 917		}
 918
 919		@Override
 920		public void userInputRequried(PendingIntent pi, Conversation object) {
 921
 922		}
 923	};
 924
 925	public int getTertiaryTextColor() {
 926		return this.mTertiaryTextColor;
 927	}
 928
 929	public int getSecondaryTextColor() {
 930		return this.mSecondaryTextColor;
 931	}
 932
 933	public int getPrimaryTextColor() {
 934		return this.mPrimaryTextColor;
 935	}
 936
 937	public int getWarningTextColor() {
 938		return this.mColorRed;
 939	}
 940
 941	public int getOnlineColor() {
 942		return this.mColorGreen;
 943	}
 944
 945	public int getPrimaryBackgroundColor() {
 946		return this.mPrimaryBackgroundColor;
 947	}
 948
 949	public int getSecondaryBackgroundColor() {
 950		return this.mSecondaryBackgroundColor;
 951	}
 952
 953	public int getPixel(int dp) {
 954		DisplayMetrics metrics = getResources().getDisplayMetrics();
 955		return ((int) (dp * metrics.density));
 956	}
 957
 958	public boolean copyTextToClipboard(String text, int labelResId) {
 959		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 960		String label = getResources().getString(labelResId);
 961		if (mClipBoardManager != null) {
 962			ClipData mClipData = ClipData.newPlainText(label, text);
 963			mClipBoardManager.setPrimaryClip(mClipData);
 964			return true;
 965		}
 966		return false;
 967	}
 968
 969	protected void registerNdefPushMessageCallback() {
 970		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 971		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 972			nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
 973				@Override
 974				public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
 975					return new NdefMessage(new NdefRecord[]{
 976							NdefRecord.createUri(getShareableUri()),
 977							NdefRecord.createApplicationRecord("eu.siacs.conversations")
 978					});
 979				}
 980			}, this);
 981		}
 982	}
 983
 984	protected boolean neverCompressPictures() {
 985		return getPreferences().getString("picture_compression", "auto").equals("never");
 986	}
 987
 988	protected boolean manuallyChangePresence() {
 989		return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, false);
 990	}
 991
 992	protected void unregisterNdefPushMessageCallback() {
 993		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 994		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 995			nfcAdapter.setNdefPushMessageCallback(null,this);
 996		}
 997	}
 998
 999	protected String getShareableUri() {
1000		return null;
1001	}
1002
1003	protected void shareUri() {
1004		String uri = getShareableUri();
1005		if (uri == null || uri.isEmpty()) {
1006			return;
1007		}
1008		Intent shareIntent = new Intent();
1009		shareIntent.setAction(Intent.ACTION_SEND);
1010		shareIntent.putExtra(Intent.EXTRA_TEXT, getShareableUri());
1011		shareIntent.setType("text/plain");
1012		try {
1013			startActivity(Intent.createChooser(shareIntent, getText(R.string.share_uri_with)));
1014		} catch (ActivityNotFoundException e) {
1015			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
1016		}
1017	}
1018
1019	@Override
1020	public void onResume() {
1021		super.onResume();
1022		if (this.getShareableUri()!=null) {
1023			this.registerNdefPushMessageCallback();
1024		}
1025	}
1026
1027	protected int findTheme() {
1028		Boolean dark   = getPreferences().getString("theme", "light").equals("dark");
1029		Boolean larger = getPreferences().getBoolean("use_larger_font", false);
1030
1031		if(dark) {
1032			if(larger)
1033				return R.style.ConversationsTheme_Dark_LargerText;
1034			else
1035				return R.style.ConversationsTheme_Dark;
1036		} else {
1037			if (larger)
1038				return R.style.ConversationsTheme_LargerText;
1039			else
1040				return R.style.ConversationsTheme;
1041		}
1042	}
1043
1044	@Override
1045	public void onPause() {
1046		super.onPause();
1047		this.unregisterNdefPushMessageCallback();
1048	}
1049
1050	protected void showQrCode() {
1051		String uri = getShareableUri();
1052		if (uri!=null) {
1053			Point size = new Point();
1054			getWindowManager().getDefaultDisplay().getSize(size);
1055			final int width = (size.x < size.y ? size.x : size.y);
1056			Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
1057			ImageView view = new ImageView(this);
1058			view.setBackgroundColor(Color.WHITE);
1059			view.setImageBitmap(bitmap);
1060			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1061			builder.setView(view);
1062			builder.create().show();
1063		}
1064	}
1065
1066	protected Account extractAccount(Intent intent) {
1067		String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1068		try {
1069			return jid != null ? xmppConnectionService.findAccountByJid(Jid.fromString(jid)) : null;
1070		} catch (InvalidJidException e) {
1071			return null;
1072		}
1073	}
1074
1075	public static class ConferenceInvite {
1076		private String uuid;
1077		private List<Jid> jids = new ArrayList<>();
1078
1079		public static ConferenceInvite parse(Intent data) {
1080			ConferenceInvite invite = new ConferenceInvite();
1081			invite.uuid = data.getStringExtra("conversation");
1082			if (invite.uuid == null) {
1083				return null;
1084			}
1085			try {
1086				if (data.getBooleanExtra("multiple", false)) {
1087					String[] toAdd = data.getStringArrayExtra("contacts");
1088					for (String item : toAdd) {
1089						invite.jids.add(Jid.fromString(item));
1090					}
1091				} else {
1092					invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
1093				}
1094			} catch (final InvalidJidException ignored) {
1095				return null;
1096			}
1097			return invite;
1098		}
1099
1100		public boolean execute(XmppActivity activity) {
1101			XmppConnectionService service = activity.xmppConnectionService;
1102			Conversation conversation = service.findConversationByUuid(this.uuid);
1103			if (conversation == null) {
1104				return false;
1105			}
1106			if (conversation.getMode() == Conversation.MODE_MULTI) {
1107				for (Jid jid : jids) {
1108					service.invite(conversation, jid);
1109				}
1110				return false;
1111			} else {
1112				jids.add(conversation.getJid().toBareJid());
1113				return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1114			}
1115		}
1116	}
1117
1118	public AvatarService avatarService() {
1119		return xmppConnectionService.getAvatarService();
1120	}
1121
1122	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1123		private final WeakReference<ImageView> imageViewReference;
1124		private Message message = null;
1125
1126		public BitmapWorkerTask(ImageView imageView) {
1127			imageViewReference = new WeakReference<>(imageView);
1128		}
1129
1130		@Override
1131		protected Bitmap doInBackground(Message... params) {
1132			if (isCancelled()) {
1133				return null;
1134			}
1135			message = params[0];
1136			try {
1137				return xmppConnectionService.getFileBackend().getThumbnail(
1138						message, (int) (metrics.density * 288), false);
1139			} catch (FileNotFoundException e) {
1140				return null;
1141			}
1142		}
1143
1144		@Override
1145		protected void onPostExecute(Bitmap bitmap) {
1146			if (bitmap != null && !isCancelled()) {
1147				final ImageView imageView = imageViewReference.get();
1148				if (imageView != null) {
1149					imageView.setImageBitmap(bitmap);
1150					imageView.setBackgroundColor(0x00000000);
1151				}
1152			}
1153		}
1154	}
1155
1156	public void loadBitmap(Message message, ImageView imageView) {
1157		Bitmap bm;
1158		try {
1159			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1160					(int) (metrics.density * 288), true);
1161		} catch (FileNotFoundException e) {
1162			bm = null;
1163		}
1164		if (bm != null) {
1165			cancelPotentialWork(message, imageView);
1166			imageView.setImageBitmap(bm);
1167			imageView.setBackgroundColor(0x00000000);
1168		} else {
1169			if (cancelPotentialWork(message, imageView)) {
1170				imageView.setBackgroundColor(0xff333333);
1171				imageView.setImageDrawable(null);
1172				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1173				final AsyncDrawable asyncDrawable = new AsyncDrawable(
1174						getResources(), null, task);
1175				imageView.setImageDrawable(asyncDrawable);
1176				try {
1177					task.execute(message);
1178				} catch (final RejectedExecutionException ignored) {
1179					ignored.printStackTrace();
1180				}
1181			}
1182		}
1183	}
1184
1185	public static boolean cancelPotentialWork(Message message, ImageView imageView) {
1186		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1187
1188		if (bitmapWorkerTask != null) {
1189			final Message oldMessage = bitmapWorkerTask.message;
1190			if (oldMessage == null || message != oldMessage) {
1191				bitmapWorkerTask.cancel(true);
1192			} else {
1193				return false;
1194			}
1195		}
1196		return true;
1197	}
1198
1199	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1200		if (imageView != null) {
1201			final Drawable drawable = imageView.getDrawable();
1202			if (drawable instanceof AsyncDrawable) {
1203				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1204				return asyncDrawable.getBitmapWorkerTask();
1205			}
1206		}
1207		return null;
1208	}
1209
1210	static class AsyncDrawable extends BitmapDrawable {
1211		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1212
1213		public AsyncDrawable(Resources res, Bitmap bitmap,
1214				BitmapWorkerTask bitmapWorkerTask) {
1215			super(res, bitmap);
1216			bitmapWorkerTaskReference = new WeakReference<>(
1217					bitmapWorkerTask);
1218		}
1219
1220		public BitmapWorkerTask getBitmapWorkerTask() {
1221			return bitmapWorkerTaskReference.get();
1222		}
1223	}
1224}