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