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		this.mTheme = findTheme();
 395		if(isDarkTheme()) {
 396			mPrimaryTextColor = ContextCompat.getColor(this, R.color.white);
 397			mSecondaryTextColor = ContextCompat.getColor(this, R.color.white70);
 398			mTertiaryTextColor = ContextCompat.getColor(this, R.color.white12);
 399			mPrimaryBackgroundColor = ContextCompat.getColor(this, R.color.grey800);
 400			mSecondaryBackgroundColor = ContextCompat.getColor(this, R.color.grey900);
 401		}
 402		setTheme(this.mTheme);
 403
 404		this.mUsingEnterKey = usingEnterKey();
 405		mUseSubject = getPreferences().getBoolean("use_subject", getResources().getBoolean(R.bool.use_subject));
 406		final ActionBar ab = getActionBar();
 407		if (ab!=null) {
 408			ab.setDisplayHomeAsUpEnabled(true);
 409		}
 410	}
 411
 412	public boolean isDarkTheme() {
 413		return this.mTheme == R.style.ConversationsTheme_Dark || this.mTheme == R.style.ConversationsTheme_Dark_LargerText;
 414	}
 415
 416	public int getThemeResource(int r_attr_name, int r_drawable_def) {
 417		int[] attrs = {	r_attr_name };
 418		TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 419
 420		int res = ta.getResourceId(0, r_drawable_def);
 421		ta.recycle();
 422
 423		return res;
 424	}
 425
 426	protected boolean isOptimizingBattery() {
 427		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 428			PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 429			return !pm.isIgnoringBatteryOptimizations(getPackageName());
 430		} else {
 431			return false;
 432		}
 433	}
 434
 435	protected boolean isAffectedByDataSaver() {
 436		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 437			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 438			return cm.isActiveNetworkMetered()
 439					&& cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 440		} else {
 441			return false;
 442		}
 443	}
 444
 445	protected boolean usingEnterKey() {
 446		return getPreferences().getBoolean("display_enter_key", getResources().getBoolean(R.bool.display_enter_key));
 447	}
 448
 449	protected SharedPreferences getPreferences() {
 450		return PreferenceManager
 451			.getDefaultSharedPreferences(getApplicationContext());
 452	}
 453
 454	public boolean useSubjectToIdentifyConference() {
 455		return mUseSubject;
 456	}
 457
 458	public void switchToConversation(Conversation conversation) {
 459		switchToConversation(conversation, null, false);
 460	}
 461
 462	public void switchToConversation(Conversation conversation, String text,
 463			boolean newTask) {
 464		switchToConversation(conversation,text,null,false,newTask);
 465	}
 466
 467	public void highlightInMuc(Conversation conversation, String nick) {
 468		switchToConversation(conversation, null, nick, false, false);
 469	}
 470
 471	public void privateMsgInMuc(Conversation conversation, String nick) {
 472		switchToConversation(conversation, null, nick, true, false);
 473	}
 474
 475	private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
 476		Intent viewConversationIntent = new Intent(this,
 477				ConversationActivity.class);
 478		viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
 479		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
 480				conversation.getUuid());
 481		if (text != null) {
 482			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
 483		}
 484		if (nick != null) {
 485			viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
 486			viewConversationIntent.putExtra(ConversationActivity.PRIVATE_MESSAGE,pm);
 487		}
 488		if (newTask) {
 489			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 490					| Intent.FLAG_ACTIVITY_NEW_TASK
 491					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
 492		} else {
 493			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 494					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
 495		}
 496		startActivity(viewConversationIntent);
 497		finish();
 498	}
 499
 500	public void switchToContactDetails(Contact contact) {
 501		switchToContactDetails(contact, null);
 502	}
 503
 504	public void switchToContactDetails(Contact contact, String messageFingerprint) {
 505		Intent intent = new Intent(this, ContactDetailsActivity.class);
 506		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 507		intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().toBareJid().toString());
 508		intent.putExtra("contact", contact.getJid().toString());
 509		intent.putExtra("fingerprint", messageFingerprint);
 510		startActivity(intent);
 511	}
 512
 513	public void switchToAccount(Account account) {
 514		switchToAccount(account, false);
 515	}
 516
 517	public void switchToAccount(Account account, boolean init) {
 518		Intent intent = new Intent(this, EditAccountActivity.class);
 519		intent.putExtra("jid", account.getJid().toBareJid().toString());
 520		intent.putExtra("init", init);
 521		startActivity(intent);
 522	}
 523
 524	protected void inviteToConversation(Conversation conversation) {
 525		Intent intent = new Intent(getApplicationContext(),
 526				ChooseContactActivity.class);
 527		List<String> contacts = new ArrayList<>();
 528		if (conversation.getMode() == Conversation.MODE_MULTI) {
 529			for (MucOptions.User user : conversation.getMucOptions().getUsers(false)) {
 530				Jid jid = user.getRealJid();
 531				if (jid != null) {
 532					contacts.add(jid.toBareJid().toString());
 533				}
 534			}
 535		} else {
 536			contacts.add(conversation.getJid().toBareJid().toString());
 537		}
 538		intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
 539		intent.putExtra("conversation", conversation.getUuid());
 540		intent.putExtra("multiple", true);
 541		intent.putExtra("show_enter_jid", true);
 542		intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 543		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
 544	}
 545
 546	protected void announcePgp(Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 547		if (account.getPgpId() == 0) {
 548			choosePgpSignId(account);
 549		} else {
 550			String status = null;
 551			if (manuallyChangePresence()) {
 552				status = account.getPresenceStatusMessage();
 553			}
 554			if (status == null) {
 555				status = "";
 556			}
 557			xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<Account>() {
 558
 559				@Override
 560				public void userInputRequried(PendingIntent pi, Account account) {
 561					try {
 562						startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 563					} catch (final SendIntentException ignored) {
 564					}
 565				}
 566
 567				@Override
 568				public void success(Account account) {
 569					xmppConnectionService.databaseBackend.updateAccount(account);
 570					xmppConnectionService.sendPresence(account);
 571					if (conversation != null) {
 572						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 573						xmppConnectionService.updateConversation(conversation);
 574						refreshUi();
 575					}
 576					if (onSuccess != null) {
 577						runOnUiThread(onSuccess);
 578					}
 579				}
 580
 581				@Override
 582				public void error(int error, Account account) {
 583					if (error == 0 && account != null) {
 584						account.setPgpSignId(0);
 585						account.unsetPgpSignature();
 586						xmppConnectionService.databaseBackend.updateAccount(account);
 587						choosePgpSignId(account);
 588					} else {
 589						displayErrorDialog(error);
 590					}
 591				}
 592			});
 593		}
 594	}
 595
 596	protected  boolean noAccountUsesPgp() {
 597		if (!hasPgp()) {
 598			return true;
 599		}
 600		for(Account account : xmppConnectionService.getAccounts()) {
 601			if (account.getPgpId() != 0) {
 602				return false;
 603			}
 604		}
 605		return true;
 606	}
 607
 608	@SuppressWarnings("deprecation")
 609	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 610	protected void setListItemBackgroundOnView(View view) {
 611		int sdk = android.os.Build.VERSION.SDK_INT;
 612		if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 613			view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 614		} else {
 615			view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 616		}
 617	}
 618
 619	protected void choosePgpSignId(Account account) {
 620		xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 621			@Override
 622			public void success(Account account1) {
 623			}
 624
 625			@Override
 626			public void error(int errorCode, Account object) {
 627
 628			}
 629
 630			@Override
 631			public void userInputRequried(PendingIntent pi, Account object) {
 632				try {
 633					startIntentSenderForResult(pi.getIntentSender(),
 634							REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 635				} catch (final SendIntentException ignored) {
 636				}
 637			}
 638		});
 639	}
 640
 641	protected void displayErrorDialog(final int errorCode) {
 642		runOnUiThread(new Runnable() {
 643
 644			@Override
 645			public void run() {
 646				AlertDialog.Builder builder = new AlertDialog.Builder(
 647						XmppActivity.this);
 648				builder.setIconAttribute(android.R.attr.alertDialogIcon);
 649				builder.setTitle(getString(R.string.error));
 650				builder.setMessage(errorCode);
 651				builder.setNeutralButton(R.string.accept, null);
 652				builder.create().show();
 653			}
 654		});
 655
 656	}
 657
 658	protected void showAddToRosterDialog(final Conversation conversation) {
 659		showAddToRosterDialog(conversation.getContact());
 660	}
 661
 662	protected void showAddToRosterDialog(final Contact contact) {
 663		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 664		builder.setTitle(contact.getJid().toString());
 665		builder.setMessage(getString(R.string.not_in_roster));
 666		builder.setNegativeButton(getString(R.string.cancel), null);
 667		builder.setPositiveButton(getString(R.string.add_contact),
 668				new DialogInterface.OnClickListener() {
 669
 670					@Override
 671					public void onClick(DialogInterface dialog, int which) {
 672						final Jid jid = contact.getJid();
 673						Account account = contact.getAccount();
 674						Contact contact = account.getRoster().getContact(jid);
 675						xmppConnectionService.createContact(contact);
 676					}
 677				});
 678		builder.create().show();
 679	}
 680
 681	private void showAskForPresenceDialog(final Contact contact) {
 682		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 683		builder.setTitle(contact.getJid().toString());
 684		builder.setMessage(R.string.request_presence_updates);
 685		builder.setNegativeButton(R.string.cancel, null);
 686		builder.setPositiveButton(R.string.request_now,
 687				new DialogInterface.OnClickListener() {
 688
 689					@Override
 690					public void onClick(DialogInterface dialog, int which) {
 691						if (xmppConnectionServiceBound) {
 692							xmppConnectionService.sendPresencePacket(contact
 693									.getAccount(), xmppConnectionService
 694									.getPresenceGenerator()
 695									.requestPresenceUpdatesFrom(contact));
 696						}
 697					}
 698				});
 699		builder.create().show();
 700	}
 701
 702	private void warnMutalPresenceSubscription(final Conversation conversation,
 703			final OnPresenceSelected listener) {
 704		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 705		builder.setTitle(conversation.getContact().getJid().toString());
 706		builder.setMessage(R.string.without_mutual_presence_updates);
 707		builder.setNegativeButton(R.string.cancel, null);
 708		builder.setPositiveButton(R.string.ignore, new OnClickListener() {
 709
 710			@Override
 711			public void onClick(DialogInterface dialog, int which) {
 712				conversation.setNextCounterpart(null);
 713				if (listener != null) {
 714					listener.onPresenceSelected();
 715				}
 716			}
 717		});
 718		builder.create().show();
 719	}
 720
 721	protected void quickEdit(String previousValue, int hint, OnValueEdited callback) {
 722		quickEdit(previousValue, callback, hint, false);
 723	}
 724
 725	protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 726		quickEdit(previousValue, callback, R.string.password, true);
 727	}
 728
 729	@SuppressLint("InflateParams")
 730	private void quickEdit(final String previousValue,
 731						   final OnValueEdited callback,
 732						   final int hint,
 733						   boolean password) {
 734		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 735		View view = getLayoutInflater().inflate(R.layout.quickedit, null);
 736		final EditText editor = (EditText) view.findViewById(R.id.editor);
 737		OnClickListener mClickListener = new OnClickListener() {
 738
 739			@Override
 740			public void onClick(DialogInterface dialog, int which) {
 741				String value = editor.getText().toString();
 742				if (!value.equals(previousValue) && value.trim().length() > 0) {
 743					callback.onValueEdited(value);
 744				}
 745			}
 746		};
 747		if (password) {
 748			editor.setInputType(InputType.TYPE_CLASS_TEXT
 749					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
 750			builder.setPositiveButton(R.string.accept, mClickListener);
 751		} else {
 752			builder.setPositiveButton(R.string.edit, mClickListener);
 753		}
 754		if (hint != 0) {
 755			editor.setHint(hint);
 756		}
 757		editor.requestFocus();
 758		editor.setText("");
 759		if (previousValue != null) {
 760			editor.getText().append(previousValue);
 761		}
 762		builder.setView(view);
 763		builder.setNegativeButton(R.string.cancel, null);
 764		builder.create().show();
 765	}
 766
 767	public boolean hasStoragePermission(int requestCode) {
 768		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 769			if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 770				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 771				return false;
 772			} else {
 773				return true;
 774			}
 775		} else {
 776			return true;
 777		}
 778	}
 779
 780	public void selectPresence(final Conversation conversation,
 781			final OnPresenceSelected listener) {
 782		final Contact contact = conversation.getContact();
 783		if (conversation.hasValidOtrSession()) {
 784			SessionID id = conversation.getOtrSession().getSessionID();
 785			Jid jid;
 786			try {
 787				jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
 788			} catch (InvalidJidException e) {
 789				jid = null;
 790			}
 791			conversation.setNextCounterpart(jid);
 792			listener.onPresenceSelected();
 793		} else 	if (!contact.showInRoster()) {
 794			showAddToRosterDialog(conversation);
 795		} else {
 796			final Presences presences = contact.getPresences();
 797			if (presences.size() == 0) {
 798				if (!contact.getOption(Contact.Options.TO)
 799						&& !contact.getOption(Contact.Options.ASKING)
 800						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 801					showAskForPresenceDialog(contact);
 802				} else if (!contact.getOption(Contact.Options.TO)
 803						|| !contact.getOption(Contact.Options.FROM)) {
 804					warnMutalPresenceSubscription(conversation, listener);
 805				} else {
 806					conversation.setNextCounterpart(null);
 807					listener.onPresenceSelected();
 808				}
 809			} else if (presences.size() == 1) {
 810				String presence = presences.toResourceArray()[0];
 811				try {
 812					conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
 813				} catch (InvalidJidException e) {
 814					conversation.setNextCounterpart(null);
 815				}
 816				listener.onPresenceSelected();
 817			} else {
 818				showPresenceSelectionDialog(presences,conversation,listener);
 819			}
 820		}
 821	}
 822
 823	private void showPresenceSelectionDialog(Presences presences, final Conversation conversation, final OnPresenceSelected listener) {
 824		final Contact contact = conversation.getContact();
 825		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 826		builder.setTitle(getString(R.string.choose_presence));
 827		final String[] resourceArray = presences.toResourceArray();
 828		Pair<Map<String, String>, Map<String, String>> typeAndName = presences.toTypeAndNameMap();
 829		final Map<String,String> resourceTypeMap = typeAndName.first;
 830		final Map<String,String> resourceNameMap = typeAndName.second;
 831		final String[] readableIdentities = new String[resourceArray.length];
 832		final AtomicInteger selectedResource = new AtomicInteger(0);
 833		for (int i = 0; i < resourceArray.length; ++i) {
 834			String resource = resourceArray[i];
 835			if (resource.equals(contact.getLastResource())) {
 836				selectedResource.set(i);
 837			}
 838			String type = resourceTypeMap.get(resource);
 839			String name = resourceNameMap.get(resource);
 840			if (type != null) {
 841				if (Collections.frequency(resourceTypeMap.values(),type) == 1) {
 842					readableIdentities[i] = UIHelper.tranlasteType(this,type);
 843				} else if (name != null) {
 844					if (Collections.frequency(resourceNameMap.values(), name) == 1
 845							|| CryptoHelper.UUID_PATTERN.matcher(resource).matches()) {
 846						readableIdentities[i] = UIHelper.tranlasteType(this,type) + "  (" + name+")";
 847					} else {
 848						readableIdentities[i] = UIHelper.tranlasteType(this,type) + " (" + name +" / " + resource+")";
 849					}
 850				} else {
 851					readableIdentities[i] = UIHelper.tranlasteType(this,type) + " (" + resource+")";
 852				}
 853			} else {
 854				readableIdentities[i] = resource;
 855			}
 856		}
 857		builder.setSingleChoiceItems(readableIdentities,
 858				selectedResource.get(),
 859				new DialogInterface.OnClickListener() {
 860
 861					@Override
 862					public void onClick(DialogInterface dialog, int which) {
 863						selectedResource.set(which);
 864					}
 865				});
 866		builder.setNegativeButton(R.string.cancel, null);
 867		builder.setPositiveButton(R.string.ok, new OnClickListener() {
 868
 869			@Override
 870			public void onClick(DialogInterface dialog, int which) {
 871				try {
 872					Jid next = Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),resourceArray[selectedResource.get()]);
 873					conversation.setNextCounterpart(next);
 874				} catch (InvalidJidException e) {
 875					conversation.setNextCounterpart(null);
 876				}
 877				listener.onPresenceSelected();
 878			}
 879		});
 880		builder.create().show();
 881	}
 882
 883	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 884		super.onActivityResult(requestCode, resultCode, data);
 885		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 886			mPendingConferenceInvite = ConferenceInvite.parse(data);
 887			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 888				if (mPendingConferenceInvite.execute(this)) {
 889					mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 890					mToast.show();
 891				}
 892				mPendingConferenceInvite = null;
 893			}
 894		}
 895	}
 896
 897
 898	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 899		@Override
 900		public void success(final Conversation conversation) {
 901			runOnUiThread(new Runnable() {
 902				@Override
 903				public void run() {
 904					switchToConversation(conversation);
 905					hideToast();
 906				}
 907			});
 908		}
 909
 910		@Override
 911		public void error(final int errorCode, Conversation object) {
 912			runOnUiThread(new Runnable() {
 913				@Override
 914				public void run() {
 915					replaceToast(getString(errorCode));
 916				}
 917			});
 918		}
 919
 920		@Override
 921		public void userInputRequried(PendingIntent pi, Conversation object) {
 922
 923		}
 924	};
 925
 926	public int getTertiaryTextColor() {
 927		return this.mTertiaryTextColor;
 928	}
 929
 930	public int getSecondaryTextColor() {
 931		return this.mSecondaryTextColor;
 932	}
 933
 934	public int getPrimaryTextColor() {
 935		return this.mPrimaryTextColor;
 936	}
 937
 938	public int getWarningTextColor() {
 939		return this.mColorRed;
 940	}
 941
 942	public int getOnlineColor() {
 943		return this.mColorGreen;
 944	}
 945
 946	public int getPrimaryBackgroundColor() {
 947		return this.mPrimaryBackgroundColor;
 948	}
 949
 950	public int getSecondaryBackgroundColor() {
 951		return this.mSecondaryBackgroundColor;
 952	}
 953
 954	public int getPixel(int dp) {
 955		DisplayMetrics metrics = getResources().getDisplayMetrics();
 956		return ((int) (dp * metrics.density));
 957	}
 958
 959	public boolean copyTextToClipboard(String text, int labelResId) {
 960		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 961		String label = getResources().getString(labelResId);
 962		if (mClipBoardManager != null) {
 963			ClipData mClipData = ClipData.newPlainText(label, text);
 964			mClipBoardManager.setPrimaryClip(mClipData);
 965			return true;
 966		}
 967		return false;
 968	}
 969
 970	protected void registerNdefPushMessageCallback() {
 971		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 972		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 973			nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
 974				@Override
 975				public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
 976					return new NdefMessage(new NdefRecord[]{
 977							NdefRecord.createUri(getShareableUri()),
 978							NdefRecord.createApplicationRecord("eu.siacs.conversations")
 979					});
 980				}
 981			}, this);
 982		}
 983	}
 984
 985	protected boolean neverCompressPictures() {
 986		return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
 987	}
 988
 989	protected boolean manuallyChangePresence() {
 990		return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
 991	}
 992
 993	protected void unregisterNdefPushMessageCallback() {
 994		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 995		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 996			nfcAdapter.setNdefPushMessageCallback(null,this);
 997		}
 998	}
 999
1000	protected String getShareableUri() {
1001		return getShareableUri(false);
1002	}
1003
1004	protected String getShareableUri(boolean http) {
1005		return null;
1006	}
1007
1008	protected void shareLink(boolean http) {
1009		String uri = getShareableUri(http);
1010		if (uri == null || uri.isEmpty()) {
1011			return;
1012		}
1013		Intent intent = new Intent(Intent.ACTION_SEND);
1014		intent.setType("text/plain");
1015		intent.putExtra(Intent.EXTRA_TEXT,getShareableUri(http));
1016		try {
1017			startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
1018		} catch (ActivityNotFoundException e) {
1019			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
1020		}
1021	}
1022
1023	protected void launchOpenKeyChain(long keyId) {
1024		PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
1025		try {
1026			startIntentSenderForResult(
1027					pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
1028					0, 0);
1029		} catch (Throwable e) {
1030			Toast.makeText(XmppActivity.this,R.string.openpgp_error,Toast.LENGTH_SHORT).show();
1031		}
1032	}
1033
1034	@Override
1035	public void onResume() {
1036		super.onResume();
1037		if (this.getShareableUri() != null) {
1038			this.registerNdefPushMessageCallback();
1039		}
1040	}
1041
1042	protected int findTheme() {
1043		Boolean dark   = getPreferences().getString(SettingsActivity.THEME, getResources().getString(R.string.theme)).equals("dark");
1044		Boolean larger = getPreferences().getBoolean("use_larger_font", getResources().getBoolean(R.bool.use_larger_font));
1045
1046		if(dark) {
1047			if(larger)
1048				return R.style.ConversationsTheme_Dark_LargerText;
1049			else
1050				return R.style.ConversationsTheme_Dark;
1051		} else {
1052			if (larger)
1053				return R.style.ConversationsTheme_LargerText;
1054			else
1055				return R.style.ConversationsTheme;
1056		}
1057	}
1058
1059	@Override
1060	public void onPause() {
1061		super.onPause();
1062		this.unregisterNdefPushMessageCallback();
1063	}
1064
1065	protected void showQrCode() {
1066		final String uri = getShareableUri();
1067		if (uri == null || uri.isEmpty()) {
1068			return;
1069		}
1070		Point size = new Point();
1071		getWindowManager().getDefaultDisplay().getSize(size);
1072		final int width = (size.x < size.y ? size.x : size.y);
1073		Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
1074		ImageView view = new ImageView(this);
1075		view.setBackgroundColor(Color.WHITE);
1076		view.setImageBitmap(bitmap);
1077		AlertDialog.Builder builder = new AlertDialog.Builder(this);
1078		builder.setView(view);
1079		builder.create().show();
1080	}
1081
1082	protected Account extractAccount(Intent intent) {
1083		String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1084		try {
1085			return jid != null ? xmppConnectionService.findAccountByJid(Jid.fromString(jid)) : null;
1086		} catch (InvalidJidException e) {
1087			return null;
1088		}
1089	}
1090
1091	public static class ConferenceInvite {
1092		private String uuid;
1093		private List<Jid> jids = new ArrayList<>();
1094
1095		public static ConferenceInvite parse(Intent data) {
1096			ConferenceInvite invite = new ConferenceInvite();
1097			invite.uuid = data.getStringExtra("conversation");
1098			if (invite.uuid == null) {
1099				return null;
1100			}
1101			try {
1102				if (data.getBooleanExtra("multiple", false)) {
1103					String[] toAdd = data.getStringArrayExtra("contacts");
1104					for (String item : toAdd) {
1105						invite.jids.add(Jid.fromString(item));
1106					}
1107				} else {
1108					invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
1109				}
1110			} catch (final InvalidJidException ignored) {
1111				return null;
1112			}
1113			return invite;
1114		}
1115
1116		public boolean execute(XmppActivity activity) {
1117			XmppConnectionService service = activity.xmppConnectionService;
1118			Conversation conversation = service.findConversationByUuid(this.uuid);
1119			if (conversation == null) {
1120				return false;
1121			}
1122			if (conversation.getMode() == Conversation.MODE_MULTI) {
1123				for (Jid jid : jids) {
1124					service.invite(conversation, jid);
1125				}
1126				return false;
1127			} else {
1128				jids.add(conversation.getJid().toBareJid());
1129				return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1130			}
1131		}
1132	}
1133
1134	public AvatarService avatarService() {
1135		return xmppConnectionService.getAvatarService();
1136	}
1137
1138	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1139		private final WeakReference<ImageView> imageViewReference;
1140		private Message message = null;
1141
1142		public BitmapWorkerTask(ImageView imageView) {
1143			imageViewReference = new WeakReference<>(imageView);
1144		}
1145
1146		@Override
1147		protected Bitmap doInBackground(Message... params) {
1148			if (isCancelled()) {
1149				return null;
1150			}
1151			message = params[0];
1152			try {
1153				return xmppConnectionService.getFileBackend().getThumbnail(
1154						message, (int) (metrics.density * 288), false);
1155			} catch (FileNotFoundException e) {
1156				return null;
1157			}
1158		}
1159
1160		@Override
1161		protected void onPostExecute(Bitmap bitmap) {
1162			if (bitmap != null && !isCancelled()) {
1163				final ImageView imageView = imageViewReference.get();
1164				if (imageView != null) {
1165					imageView.setImageBitmap(bitmap);
1166					imageView.setBackgroundColor(0x00000000);
1167				}
1168			}
1169		}
1170	}
1171
1172	public void loadBitmap(Message message, ImageView imageView) {
1173		Bitmap bm;
1174		try {
1175			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1176					(int) (metrics.density * 288), true);
1177		} catch (FileNotFoundException e) {
1178			bm = null;
1179		}
1180		if (bm != null) {
1181			cancelPotentialWork(message, imageView);
1182			imageView.setImageBitmap(bm);
1183			imageView.setBackgroundColor(0x00000000);
1184		} else {
1185			if (cancelPotentialWork(message, imageView)) {
1186				imageView.setBackgroundColor(0xff333333);
1187				imageView.setImageDrawable(null);
1188				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1189				final AsyncDrawable asyncDrawable = new AsyncDrawable(
1190						getResources(), null, task);
1191				imageView.setImageDrawable(asyncDrawable);
1192				try {
1193					task.execute(message);
1194				} catch (final RejectedExecutionException ignored) {
1195					ignored.printStackTrace();
1196				}
1197			}
1198		}
1199	}
1200
1201	public static boolean cancelPotentialWork(Message message, ImageView imageView) {
1202		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1203
1204		if (bitmapWorkerTask != null) {
1205			final Message oldMessage = bitmapWorkerTask.message;
1206			if (oldMessage == null || message != oldMessage) {
1207				bitmapWorkerTask.cancel(true);
1208			} else {
1209				return false;
1210			}
1211		}
1212		return true;
1213	}
1214
1215	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1216		if (imageView != null) {
1217			final Drawable drawable = imageView.getDrawable();
1218			if (drawable instanceof AsyncDrawable) {
1219				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1220				return asyncDrawable.getBitmapWorkerTask();
1221			}
1222		}
1223		return null;
1224	}
1225
1226	static class AsyncDrawable extends BitmapDrawable {
1227		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1228
1229		public AsyncDrawable(Resources res, Bitmap bitmap,
1230				BitmapWorkerTask bitmapWorkerTask) {
1231			super(res, bitmap);
1232			bitmapWorkerTaskReference = new WeakReference<>(
1233					bitmapWorkerTask);
1234		}
1235
1236		public BitmapWorkerTask getBitmapWorkerTask() {
1237			return bitmapWorkerTaskReference.get();
1238		}
1239	}
1240}