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