XmppActivity.java

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