StartConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.content.res.TypedArray;
   6import android.databinding.DataBindingUtil;
   7import android.databinding.ViewDataBinding;
   8import android.graphics.drawable.Drawable;
   9import android.support.annotation.AttrRes;
  10import android.support.annotation.DrawableRes;
  11import android.support.annotation.NonNull;
  12import android.support.v4.content.ContextCompat;
  13import android.support.v7.app.AlertDialog;
  14import android.app.Dialog;
  15import android.app.PendingIntent;
  16import android.content.ActivityNotFoundException;
  17import android.content.Context;
  18import android.content.DialogInterface;
  19import android.content.DialogInterface.OnClickListener;
  20import android.content.Intent;
  21import android.content.pm.PackageManager;
  22import android.net.Uri;
  23import android.os.Build;
  24import android.os.Bundle;
  25import android.support.v4.app.Fragment;
  26import android.support.v4.app.FragmentManager;
  27import android.support.v4.app.FragmentTransaction;
  28import android.support.v4.app.ListFragment;
  29import android.support.v4.view.MenuItemCompat;
  30import android.support.v4.view.PagerAdapter;
  31import android.support.v4.view.ViewPager;
  32import android.support.v7.app.ActionBar;
  33import android.text.Editable;
  34import android.text.SpannableString;
  35import android.text.Spanned;
  36import android.text.TextWatcher;
  37import android.text.style.TypefaceSpan;
  38import android.util.Pair;
  39import android.view.ContextMenu;
  40import android.view.ContextMenu.ContextMenuInfo;
  41import android.view.KeyEvent;
  42import android.view.Menu;
  43import android.view.MenuItem;
  44import android.view.View;
  45import android.view.ViewGroup;
  46import android.view.inputmethod.InputMethodManager;
  47import android.widget.AdapterView;
  48import android.widget.AdapterView.AdapterContextMenuInfo;
  49import android.widget.AdapterView.OnItemClickListener;
  50import android.widget.ArrayAdapter;
  51import android.widget.AutoCompleteTextView;
  52import android.widget.CheckBox;
  53import android.widget.Checkable;
  54import android.widget.EditText;
  55import android.widget.ListView;
  56import android.widget.Spinner;
  57import android.widget.TextView;
  58import android.widget.Toast;
  59
  60import java.util.ArrayList;
  61import java.util.Arrays;
  62import java.util.Collections;
  63import java.util.List;
  64import java.util.concurrent.atomic.AtomicBoolean;
  65
  66import eu.siacs.conversations.Config;
  67import eu.siacs.conversations.R;
  68import eu.siacs.conversations.databinding.ActivityStartConversationBinding;
  69import eu.siacs.conversations.entities.Account;
  70import eu.siacs.conversations.entities.Bookmark;
  71import eu.siacs.conversations.entities.Contact;
  72import eu.siacs.conversations.entities.Conversation;
  73import eu.siacs.conversations.entities.ListItem;
  74import eu.siacs.conversations.entities.Presence;
  75import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  76import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
  77import eu.siacs.conversations.ui.adapter.ListItemAdapter;
  78import eu.siacs.conversations.ui.service.EmojiService;
  79import eu.siacs.conversations.utils.XmppUri;
  80import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  81import eu.siacs.conversations.xmpp.XmppConnection;
  82import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  83import eu.siacs.conversations.xmpp.jid.Jid;
  84
  85public class StartConversationActivity extends XmppActivity implements OnRosterUpdate, OnUpdateBlocklist {
  86
  87	private final int REQUEST_SYNC_CONTACTS = 0x28cf;
  88	private final int REQUEST_CREATE_CONFERENCE = 0x39da;
  89	public int conference_context_id;
  90	public int contact_context_id;
  91	private ListPagerAdapter mListPagerAdapter;
  92	private List<ListItem> contacts = new ArrayList<>();
  93	private ListItemAdapter mContactsAdapter;
  94	private List<ListItem> conferences = new ArrayList<>();
  95	private ListItemAdapter mConferenceAdapter;
  96	private List<String> mActivatedAccounts = new ArrayList<>();
  97	private List<String> mKnownHosts;
  98	private List<String> mKnownConferenceHosts;
  99	private Invite mPendingInvite = null;
 100	private EditText mSearchEditText;
 101	private AtomicBoolean mRequestedContactsPermission = new AtomicBoolean(false);
 102	private Dialog mCurrentDialog = null;
 103	private boolean mHideOfflineContacts = false;
 104	private MenuItem.OnActionExpandListener mOnActionExpandListener = new MenuItem.OnActionExpandListener() {
 105
 106		@Override
 107		public boolean onMenuItemActionExpand(MenuItem item) {
 108			mSearchEditText.post(() -> {
 109				mSearchEditText.requestFocus();
 110				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 111				imm.showSoftInput(mSearchEditText, InputMethodManager.SHOW_IMPLICIT);
 112			});
 113
 114			return true;
 115		}
 116
 117		@Override
 118		public boolean onMenuItemActionCollapse(MenuItem item) {
 119			hideKeyboard();
 120			mSearchEditText.setText("");
 121			filter(null);
 122			return true;
 123		}
 124	};
 125	private TextWatcher mSearchTextWatcher = new TextWatcher() {
 126
 127		@Override
 128		public void afterTextChanged(Editable editable) {
 129			filter(editable.toString());
 130		}
 131
 132		@Override
 133		public void beforeTextChanged(CharSequence s, int start, int count,
 134		                              int after) {
 135		}
 136
 137		@Override
 138		public void onTextChanged(CharSequence s, int start, int before, int count) {
 139		}
 140	};
 141	private TextView.OnEditorActionListener mSearchDone = new TextView.OnEditorActionListener() {
 142		@Override
 143		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
 144			int pos = getSupportActionBar().getSelectedNavigationIndex();
 145			if (pos == 0) {
 146				if (contacts.size() == 1) {
 147					openConversationForContact((Contact) contacts.get(0));
 148					return true;
 149				}
 150			} else {
 151				if (conferences.size() == 1) {
 152					openConversationsForBookmark((Bookmark) conferences.get(0));
 153					return true;
 154				}
 155			}
 156			hideKeyboard();
 157			mListPagerAdapter.requestFocus(pos);
 158			return true;
 159		}
 160	};
 161	private MenuItem mMenuSearchView;
 162	private ListItemAdapter.OnTagClickedListener mOnTagClickedListener = new ListItemAdapter.OnTagClickedListener() {
 163		@Override
 164		public void onTagClicked(String tag) {
 165			if (mMenuSearchView != null) {
 166				mMenuSearchView.expandActionView();
 167				mSearchEditText.setText("");
 168				mSearchEditText.append(tag);
 169				filter(tag);
 170			}
 171		}
 172	};
 173	private String mInitialJid;
 174	private Pair<Integer, Intent> mPostponedActivityResult;
 175	private Toast mToast;
 176	private UiCallback<Conversation> mAdhocConferenceCallback = new UiCallback<Conversation>() {
 177		@Override
 178		public void success(final Conversation conversation) {
 179			runOnUiThread(() -> {
 180				hideToast();
 181				switchToConversation(conversation);
 182			});
 183		}
 184
 185		@Override
 186		public void error(final int errorCode, Conversation object) {
 187			runOnUiThread(() -> replaceToast(getString(errorCode)));
 188		}
 189
 190		@Override
 191		public void userInputRequried(PendingIntent pi, Conversation object) {
 192
 193		}
 194	};
 195	private ActivityStartConversationBinding binding;
 196	private ActionBar.TabListener mTabListener = new ActionBar.TabListener() {
 197
 198		@Override
 199		public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
 200			return;
 201		}
 202
 203		@Override
 204		public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
 205			binding.startConversationViewPager.setCurrentItem(tab.getPosition());
 206			onTabChanged();
 207		}
 208
 209		@Override
 210		public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
 211			return;
 212		}
 213	};
 214	private ViewPager.SimpleOnPageChangeListener mOnPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
 215		@Override
 216		public void onPageSelected(int position) {
 217			ActionBar actionBar = getSupportActionBar();
 218			if (actionBar != null) {
 219				actionBar.setSelectedNavigationItem(position);
 220			}
 221			onTabChanged();
 222		}
 223	};
 224
 225	public static void populateAccountSpinner(Context context, List<String> accounts, Spinner spinner) {
 226		if (accounts.size() > 0) {
 227			ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.simple_list_item, accounts);
 228			adapter.setDropDownViewResource(R.layout.simple_list_item);
 229			spinner.setAdapter(adapter);
 230			spinner.setEnabled(true);
 231		} else {
 232			ArrayAdapter<String> adapter = new ArrayAdapter<>(context,
 233					R.layout.simple_list_item,
 234					Arrays.asList(context.getString(R.string.no_accounts)));
 235			adapter.setDropDownViewResource(R.layout.simple_list_item);
 236			spinner.setAdapter(adapter);
 237			spinner.setEnabled(false);
 238		}
 239	}
 240
 241	public static void launch(Context context) {
 242		final Intent intent = new Intent(context, StartConversationActivity.class);
 243		context.startActivity(intent);
 244	}
 245
 246	protected void hideToast() {
 247		if (mToast != null) {
 248			mToast.cancel();
 249		}
 250	}
 251
 252	protected void replaceToast(String msg) {
 253		hideToast();
 254		mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
 255		mToast.show();
 256	}
 257
 258	@Override
 259	public void onRosterUpdate() {
 260		this.refreshUi();
 261	}
 262
 263	@Override
 264	public void onCreate(Bundle savedInstanceState) {
 265		super.onCreate(savedInstanceState);
 266		new EmojiService(this).init();
 267		this.binding = DataBindingUtil.setContentView(this, R.layout.activity_start_conversation);
 268		this.binding.fab.setOnClickListener((v) -> {
 269			if (getSupportActionBar().getSelectedNavigationIndex() == 0) {
 270				String searchString = mSearchEditText != null ? mSearchEditText.getText().toString() : null;
 271				if (searchString != null && !searchString.trim().isEmpty()) {
 272					try {
 273						Jid jid = Jid.fromString(searchString);
 274						if (!jid.isDomainJid() && jid.isBareJid() && jid.getDomainpart().contains(".")) {
 275							showCreateContactDialog(jid.toString(),null);
 276							return;
 277						}
 278					} catch (InvalidJidException ignored) {
 279						//ignore and fall through
 280					}
 281				}
 282				showCreateContactDialog(null, null);
 283			} else {
 284				showCreateConferenceDialog();
 285			}
 286		});
 287		ActionBar actionBar = getSupportActionBar();
 288		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
 289
 290		ActionBar.Tab mContactsTab = actionBar.newTab().setText(R.string.contacts).setTabListener(mTabListener);
 291		ActionBar.Tab mConferencesTab = actionBar.newTab().setText(R.string.conferences).setTabListener(mTabListener);
 292		actionBar.addTab(mContactsTab);
 293		actionBar.addTab(mConferencesTab);
 294
 295		binding.startConversationViewPager.setOnPageChangeListener(mOnPageChangeListener);
 296		mListPagerAdapter = new ListPagerAdapter(getSupportFragmentManager());
 297		binding.startConversationViewPager.setAdapter(mListPagerAdapter);
 298
 299		mConferenceAdapter = new ListItemAdapter(this, conferences);
 300		mContactsAdapter = new ListItemAdapter(this, contacts);
 301		mContactsAdapter.setOnTagClickedListener(this.mOnTagClickedListener);
 302		this.mHideOfflineContacts = getPreferences().getBoolean("hide_offline", false);
 303
 304	}
 305
 306	@Override
 307	public void onStart() {
 308		super.onStart();
 309		final int theme = findTheme();
 310		if (this.mTheme != theme) {
 311			recreate();
 312		} else {
 313			Intent i = getIntent();
 314			if (i == null || !i.hasExtra(WelcomeActivity.EXTRA_INVITE_URI)) {
 315				askForContactsPermissions();
 316			}
 317		}
 318		mConferenceAdapter.refreshSettings();
 319		mContactsAdapter.refreshSettings();
 320	}
 321
 322	@Override
 323	public void onStop() {
 324		if (mCurrentDialog != null) {
 325			mCurrentDialog.dismiss();
 326		}
 327		super.onStop();
 328	}
 329
 330	@Override
 331	public void onNewIntent(Intent intent) {
 332		if (xmppConnectionServiceBound) {
 333			handleIntent(intent);
 334		} else {
 335			setIntent(intent);
 336		}
 337	}
 338
 339	protected void openConversationForContact(int position) {
 340		Contact contact = (Contact) contacts.get(position);
 341		openConversationForContact(contact);
 342	}
 343
 344	protected void openConversationForContact(Contact contact) {
 345		Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
 346		switchToConversation(conversation);
 347	}
 348
 349	protected void openConversationForContact() {
 350		int position = contact_context_id;
 351		openConversationForContact(position);
 352	}
 353
 354	protected void openConversationForBookmark() {
 355		openConversationForBookmark(conference_context_id);
 356	}
 357
 358	protected void openConversationForBookmark(int position) {
 359		Bookmark bookmark = (Bookmark) conferences.get(position);
 360		openConversationsForBookmark(bookmark);
 361	}
 362
 363	protected void shareBookmarkUri() {
 364		shareBookmarkUri(conference_context_id);
 365	}
 366
 367	protected void shareBookmarkUri(int position) {
 368		Bookmark bookmark = (Bookmark) conferences.get(position);
 369		Intent shareIntent = new Intent();
 370		shareIntent.setAction(Intent.ACTION_SEND);
 371		shareIntent.putExtra(Intent.EXTRA_TEXT, "xmpp:" + bookmark.getJid().toBareJid().toString() + "?join");
 372		shareIntent.setType("text/plain");
 373		try {
 374			startActivity(Intent.createChooser(shareIntent, getText(R.string.share_uri_with)));
 375		} catch (ActivityNotFoundException e) {
 376			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 377		}
 378	}
 379
 380	protected void openConversationsForBookmark(Bookmark bookmark) {
 381		Jid jid = bookmark.getJid();
 382		if (jid == null) {
 383			Toast.makeText(this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
 384			return;
 385		}
 386		Conversation conversation = xmppConnectionService.findOrCreateConversation(bookmark.getAccount(), jid, true, true, true);
 387		bookmark.setConversation(conversation);
 388		if (!bookmark.autojoin() && getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin))) {
 389			bookmark.setAutojoin(true);
 390			xmppConnectionService.pushBookmarks(bookmark.getAccount());
 391		}
 392		switchToConversation(conversation);
 393	}
 394
 395	protected void openDetailsForContact() {
 396		int position = contact_context_id;
 397		Contact contact = (Contact) contacts.get(position);
 398		switchToContactDetails(contact);
 399	}
 400
 401	protected void toggleContactBlock() {
 402		final int position = contact_context_id;
 403		BlockContactDialog.show(this, (Contact) contacts.get(position));
 404	}
 405
 406	protected void deleteContact() {
 407		final int position = contact_context_id;
 408		final Contact contact = (Contact) contacts.get(position);
 409		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
 410		builder.setNegativeButton(R.string.cancel, null);
 411		builder.setTitle(R.string.action_delete_contact);
 412		builder.setMessage(getString(R.string.remove_contact_text,
 413				contact.getJid()));
 414		builder.setPositiveButton(R.string.delete, new OnClickListener() {
 415
 416			@Override
 417			public void onClick(DialogInterface dialog, int which) {
 418				xmppConnectionService.deleteContactOnServer(contact);
 419				filter(mSearchEditText.getText().toString());
 420			}
 421		});
 422		builder.create().show();
 423	}
 424
 425	protected void deleteConference() {
 426		int position = conference_context_id;
 427		final Bookmark bookmark = (Bookmark) conferences.get(position);
 428
 429		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 430		builder.setNegativeButton(R.string.cancel, null);
 431		builder.setTitle(R.string.delete_bookmark);
 432		builder.setMessage(getString(R.string.remove_bookmark_text,
 433				bookmark.getJid()));
 434		builder.setPositiveButton(R.string.delete, new OnClickListener() {
 435
 436			@Override
 437			public void onClick(DialogInterface dialog, int which) {
 438				bookmark.setConversation(null);
 439				Account account = bookmark.getAccount();
 440				account.getBookmarks().remove(bookmark);
 441				xmppConnectionService.pushBookmarks(account);
 442				filter(mSearchEditText.getText().toString());
 443			}
 444		});
 445		builder.create().show();
 446
 447	}
 448
 449	@SuppressLint("InflateParams")
 450	protected void showCreateContactDialog(final String prefilledJid, final Invite invite) {
 451		EnterJidDialog dialog = new EnterJidDialog(
 452				this, mKnownHosts, mActivatedAccounts,
 453				getString(R.string.dialog_title_create_contact), getString(R.string.create),
 454				prefilledJid, null, invite == null || !invite.hasFingerprints()
 455		);
 456
 457		dialog.setOnEnterJidDialogPositiveListener((accountJid, contactJid) -> {
 458			if (!xmppConnectionServiceBound) {
 459				return false;
 460			}
 461
 462			final Account account = xmppConnectionService.findAccountByJid(accountJid);
 463			if (account == null) {
 464				return true;
 465			}
 466
 467			final Contact contact = account.getRoster().getContact(contactJid);
 468			if (invite != null && invite.getName() != null) {
 469				contact.setServerName(invite.getName());
 470			}
 471			if (contact.isSelf()) {
 472				switchToConversation(contact, null);
 473				return true;
 474			} else if (contact.showInRoster()) {
 475				throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists));
 476			} else {
 477				xmppConnectionService.createContact(contact,true);
 478				if (invite != null && invite.hasFingerprints()) {
 479					xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
 480				}
 481				switchToConversation(contact, invite == null ? null : invite.getBody());
 482				return true;
 483			}
 484		});
 485
 486		mCurrentDialog = dialog.show();
 487	}
 488
 489	@SuppressLint("InflateParams")
 490	protected void showJoinConferenceDialog(final String prefilledJid) {
 491		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
 492		builder.setTitle(R.string.dialog_title_join_conference);
 493		final View dialogView = getLayoutInflater().inflate(R.layout.join_conference_dialog, null);
 494		final Spinner spinner = dialogView.findViewById(R.id.account);
 495		final AutoCompleteTextView jid = dialogView.findViewById(R.id.jid);
 496		final TextView jabberIdDesc = dialogView.findViewById(R.id.jabber_id);
 497		jabberIdDesc.setText(R.string.conference_address);
 498		jid.setHint(R.string.conference_address_example);
 499		jid.setAdapter(new KnownHostsAdapter(this, R.layout.simple_list_item, mKnownConferenceHosts));
 500		if (prefilledJid != null) {
 501			jid.append(prefilledJid);
 502		}
 503		populateAccountSpinner(this, mActivatedAccounts, spinner);
 504		final Checkable bookmarkCheckBox = (CheckBox) dialogView
 505				.findViewById(R.id.bookmark);
 506		builder.setView(dialogView);
 507		builder.setNegativeButton(R.string.cancel, null);
 508		builder.setPositiveButton(R.string.join, null);
 509		final AlertDialog dialog = builder.create();
 510		dialog.show();
 511		mCurrentDialog = dialog;
 512		dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
 513			if (!xmppConnectionServiceBound) {
 514				return;
 515			}
 516			final Account account = getSelectedAccount(spinner);
 517			if (account == null) {
 518				return;
 519			}
 520			final Jid conferenceJid;
 521			try {
 522				conferenceJid = Jid.fromString(jid.getText().toString());
 523			} catch (final InvalidJidException e) {
 524				jid.setError(getString(R.string.invalid_jid));
 525				return;
 526			}
 527
 528			if (bookmarkCheckBox.isChecked()) {
 529				if (account.hasBookmarkFor(conferenceJid)) {
 530					jid.setError(getString(R.string.bookmark_already_exists));
 531				} else {
 532					final Bookmark bookmark = new Bookmark(account, conferenceJid.toBareJid());
 533					bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
 534					String nick = conferenceJid.getResourcepart();
 535					if (nick != null && !nick.isEmpty()) {
 536						bookmark.setNick(nick);
 537					}
 538					account.getBookmarks().add(bookmark);
 539					xmppConnectionService.pushBookmarks(account);
 540					final Conversation conversation = xmppConnectionService
 541							.findOrCreateConversation(account, conferenceJid, true, true, true);
 542					bookmark.setConversation(conversation);
 543					dialog.dismiss();
 544					mCurrentDialog = null;
 545					switchToConversation(conversation);
 546				}
 547			} else {
 548				final Conversation conversation = xmppConnectionService
 549						.findOrCreateConversation(account, conferenceJid, true, true, true);
 550				dialog.dismiss();
 551				mCurrentDialog = null;
 552				switchToConversation(conversation);
 553			}
 554		});
 555	}
 556
 557	private void showCreateConferenceDialog() {
 558		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
 559		builder.setTitle(R.string.dialog_title_create_conference);
 560		final View dialogView = getLayoutInflater().inflate(R.layout.create_conference_dialog, null);
 561		final Spinner spinner = dialogView.findViewById(R.id.account);
 562		final EditText subject = dialogView.findViewById(R.id.subject);
 563		populateAccountSpinner(this, mActivatedAccounts, spinner);
 564		builder.setView(dialogView);
 565		builder.setPositiveButton(R.string.choose_participants, new OnClickListener() {
 566			@Override
 567			public void onClick(DialogInterface dialog, int which) {
 568				if (!xmppConnectionServiceBound) {
 569					return;
 570				}
 571				final Account account = getSelectedAccount(spinner);
 572				if (account == null) {
 573					return;
 574				}
 575				Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class);
 576				intent.putExtra("multiple", true);
 577				intent.putExtra("show_enter_jid", true);
 578				intent.putExtra("subject", subject.getText().toString());
 579				intent.putExtra(EXTRA_ACCOUNT, account.getJid().toBareJid().toString());
 580				intent.putExtra(ChooseContactActivity.EXTRA_TITLE_RES_ID, R.string.choose_participants);
 581				startActivityForResult(intent, REQUEST_CREATE_CONFERENCE);
 582			}
 583		});
 584		builder.setNegativeButton(R.string.cancel, null);
 585		mCurrentDialog = builder.create();
 586		mCurrentDialog.show();
 587	}
 588
 589	private Account getSelectedAccount(Spinner spinner) {
 590		if (!spinner.isEnabled()) {
 591			return null;
 592		}
 593		Jid jid;
 594		try {
 595			if (Config.DOMAIN_LOCK != null) {
 596				jid = Jid.fromParts((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null);
 597			} else {
 598				jid = Jid.fromString((String) spinner.getSelectedItem());
 599			}
 600		} catch (final InvalidJidException e) {
 601			return null;
 602		}
 603		return xmppConnectionService.findAccountByJid(jid);
 604	}
 605
 606	protected void switchToConversation(Contact contact, String body) {
 607		Conversation conversation = xmppConnectionService
 608				.findOrCreateConversation(contact.getAccount(),
 609						contact.getJid(), false, true);
 610		switchToConversation(conversation, body, false);
 611	}
 612
 613	@Override
 614	public boolean onCreateOptionsMenu(Menu menu) {
 615		getMenuInflater().inflate(R.menu.start_conversation, menu);
 616		MenuItem menuHideOffline = menu.findItem(R.id.action_hide_offline);
 617		MenuItem joinGroupChat = menu.findItem(R.id.action_join_conference);
 618		ActionBar bar = getSupportActionBar();
 619		joinGroupChat.setVisible(bar != null && bar.getSelectedNavigationIndex() == 1);
 620		menuHideOffline.setChecked(this.mHideOfflineContacts);
 621		mMenuSearchView = menu.findItem(R.id.action_search);
 622		mMenuSearchView.setOnActionExpandListener(mOnActionExpandListener);
 623		View mSearchView = mMenuSearchView.getActionView();
 624		mSearchEditText = mSearchView.findViewById(R.id.search_field);
 625		mSearchEditText.addTextChangedListener(mSearchTextWatcher);
 626		mSearchEditText.setOnEditorActionListener(mSearchDone);
 627		if (mInitialJid != null) {
 628			MenuItemCompat.expandActionView(mMenuSearchView);
 629			mSearchEditText.append(mInitialJid);
 630			filter(mInitialJid);
 631		}
 632		return super.onCreateOptionsMenu(menu);
 633	}
 634
 635	@Override
 636	public boolean onOptionsItemSelected(MenuItem item) {
 637		switch (item.getItemId()) {
 638			case R.id.action_join_conference:
 639				showJoinConferenceDialog(null);
 640				return true;
 641			case R.id.action_scan_qr_code:
 642				UriHandlerActivity.scan(this);
 643				return true;
 644			case R.id.action_hide_offline:
 645				mHideOfflineContacts = !item.isChecked();
 646				getPreferences().edit().putBoolean("hide_offline", mHideOfflineContacts).commit();
 647				if (mSearchEditText != null) {
 648					filter(mSearchEditText.getText().toString());
 649				}
 650				invalidateOptionsMenu();
 651		}
 652		return super.onOptionsItemSelected(item);
 653	}
 654
 655	@Override
 656	public boolean onKeyUp(int keyCode, KeyEvent event) {
 657		if (keyCode == KeyEvent.KEYCODE_SEARCH && !event.isLongPress()) {
 658			openSearch();
 659			return true;
 660		}
 661		int c = event.getUnicodeChar();
 662		if (c > 32) {
 663			if (mSearchEditText != null && !mSearchEditText.isFocused()) {
 664				openSearch();
 665				mSearchEditText.append(Character.toString((char) c));
 666				return true;
 667			}
 668		}
 669		return super.onKeyUp(keyCode, event);
 670	}
 671
 672	private void openSearch() {
 673		if (mMenuSearchView != null) {
 674			mMenuSearchView.expandActionView();
 675		}
 676	}
 677
 678	@Override
 679	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
 680		if (resultCode == RESULT_OK) {
 681			if (xmppConnectionServiceBound) {
 682				this.mPostponedActivityResult = null;
 683				if (requestCode == REQUEST_CREATE_CONFERENCE) {
 684					Account account = extractAccount(intent);
 685					final String subject = intent.getStringExtra("subject");
 686					List<Jid> jids = new ArrayList<>();
 687					if (intent.getBooleanExtra("multiple", false)) {
 688						String[] toAdd = intent.getStringArrayExtra("contacts");
 689						for (String item : toAdd) {
 690							try {
 691								jids.add(Jid.fromString(item));
 692							} catch (InvalidJidException e) {
 693								//ignored
 694							}
 695						}
 696					} else {
 697						try {
 698							jids.add(Jid.fromString(intent.getStringExtra("contact")));
 699						} catch (Exception e) {
 700							//ignored
 701						}
 702					}
 703					if (account != null && jids.size() > 0) {
 704						if (xmppConnectionService.createAdhocConference(account, subject, jids, mAdhocConferenceCallback)) {
 705							mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 706							mToast.show();
 707						}
 708					}
 709				}
 710			} else {
 711				this.mPostponedActivityResult = new Pair<>(requestCode, intent);
 712			}
 713		}
 714		super.onActivityResult(requestCode, requestCode, intent);
 715	}
 716
 717	private void askForContactsPermissions() {
 718		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 719			if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
 720				if (mRequestedContactsPermission.compareAndSet(false, true)) {
 721					if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
 722						AlertDialog.Builder builder = new AlertDialog.Builder(this);
 723						builder.setTitle(R.string.sync_with_contacts);
 724						builder.setMessage(R.string.sync_with_contacts_long);
 725						builder.setPositiveButton(R.string.next, new OnClickListener() {
 726							@Override
 727							public void onClick(DialogInterface dialog, int which) {
 728								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 729									requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
 730								}
 731							}
 732						});
 733						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 734							builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
 735								@Override
 736								public void onDismiss(DialogInterface dialog) {
 737									if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 738										requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
 739									}
 740								}
 741							});
 742						}
 743						builder.create().show();
 744					} else {
 745						requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 0);
 746					}
 747				}
 748			}
 749		}
 750	}
 751
 752	@Override
 753	public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
 754		if (grantResults.length > 0)
 755			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 756				if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
 757					xmppConnectionService.loadPhoneContacts();
 758				}
 759			}
 760	}
 761
 762	@Override
 763	protected void onBackendConnected() {
 764		if (mPostponedActivityResult != null) {
 765			onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
 766			this.mPostponedActivityResult = null;
 767		}
 768		this.mActivatedAccounts.clear();
 769		for (Account account : xmppConnectionService.getAccounts()) {
 770			if (account.getStatus() != Account.State.DISABLED) {
 771				if (Config.DOMAIN_LOCK != null) {
 772					this.mActivatedAccounts.add(account.getJid().getLocalpart());
 773				} else {
 774					this.mActivatedAccounts.add(account.getJid().toBareJid().toString());
 775				}
 776			}
 777		}
 778		final Intent intent = getIntent();
 779		final ActionBar ab = getSupportActionBar();
 780		boolean init = intent != null && intent.getBooleanExtra("init", false);
 781		boolean noConversations = xmppConnectionService.getConversations().size() == 0;
 782		if ((init || noConversations) && ab != null) {
 783			ab.setDisplayShowHomeEnabled(false);
 784			ab.setDisplayHomeAsUpEnabled(false);
 785			ab.setHomeButtonEnabled(false);
 786		}
 787		this.mKnownHosts = xmppConnectionService.getKnownHosts();
 788		this.mKnownConferenceHosts = xmppConnectionService.getKnownConferenceHosts();
 789		if (this.mPendingInvite != null) {
 790			mPendingInvite.invite();
 791			this.mPendingInvite = null;
 792			filter(null);
 793		} else if (!handleIntent(getIntent())) {
 794			if (mSearchEditText != null) {
 795				filter(mSearchEditText.getText().toString());
 796			} else {
 797				filter(null);
 798			}
 799		} else {
 800			filter(null);
 801		}
 802		setIntent(null);
 803	}
 804
 805	protected boolean handleIntent(Intent intent) {
 806		if (intent == null) {
 807			return false;
 808		}
 809		final String inviteUri = intent.getStringExtra(WelcomeActivity.EXTRA_INVITE_URI);
 810		if (inviteUri != null) {
 811			Invite invite = new Invite(inviteUri);
 812			if (invite.isJidValid()) {
 813				return invite.invite();
 814			}
 815		}
 816		if (intent.getAction() == null) {
 817			return false;
 818		}
 819		switch (intent.getAction()) {
 820			case Intent.ACTION_SENDTO:
 821			case Intent.ACTION_VIEW:
 822				Uri uri = intent.getData();
 823				if (uri != null) {
 824					Invite invite = new Invite(intent.getData(), false);
 825					invite.account = intent.getStringExtra("account");
 826					return invite.invite();
 827				} else {
 828					return false;
 829				}
 830		}
 831		return false;
 832	}
 833
 834	private boolean handleJid(Invite invite) {
 835		List<Contact> contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);
 836		if (invite.isAction(XmppUri.ACTION_JOIN)) {
 837			Conversation muc = xmppConnectionService.findFirstMuc(invite.getJid());
 838			if (muc != null) {
 839				switchToConversation(muc, invite.getBody(), false);
 840				return true;
 841			} else {
 842				showJoinConferenceDialog(invite.getJid().toBareJid().toString());
 843				return false;
 844			}
 845		} else if (contacts.size() == 0) {
 846			showCreateContactDialog(invite.getJid().toString(), invite);
 847			return false;
 848		} else if (contacts.size() == 1) {
 849			Contact contact = contacts.get(0);
 850			if (!invite.isSafeSource() && invite.hasFingerprints()) {
 851				displayVerificationWarningDialog(contact, invite);
 852			} else {
 853				if (invite.hasFingerprints()) {
 854					if (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {
 855						Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
 856					}
 857				}
 858				if (invite.account != null) {
 859					xmppConnectionService.getShortcutService().report(contact);
 860				}
 861				switchToConversation(contact, invite.getBody());
 862			}
 863			return true;
 864		} else {
 865			if (mMenuSearchView != null) {
 866				mMenuSearchView.expandActionView();
 867				mSearchEditText.setText("");
 868				mSearchEditText.append(invite.getJid().toString());
 869				filter(invite.getJid().toString());
 870			} else {
 871				mInitialJid = invite.getJid().toString();
 872			}
 873			return true;
 874		}
 875	}
 876
 877	private void displayVerificationWarningDialog(final Contact contact, final Invite invite) {
 878		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 879		builder.setTitle(R.string.verify_omemo_keys);
 880		View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
 881		final CheckBox isTrustedSource = (CheckBox) view.findViewById(R.id.trusted_source);
 882		TextView warning = (TextView) view.findViewById(R.id.warning);
 883		String jid = contact.getJid().toBareJid().toString();
 884		SpannableString spannable = new SpannableString(getString(R.string.verifying_omemo_keys_trusted_source, jid, contact.getDisplayName()));
 885		int start = spannable.toString().indexOf(jid);
 886		if (start >= 0) {
 887			spannable.setSpan(new TypefaceSpan("monospace"), start, start + jid.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 888		}
 889		warning.setText(spannable);
 890		builder.setView(view);
 891		builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
 892			if (isTrustedSource.isChecked() && invite.hasFingerprints()) {
 893				xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
 894			}
 895			switchToConversation(contact, invite.getBody());
 896		});
 897		builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish());
 898		AlertDialog dialog = builder.create();
 899		dialog.setCanceledOnTouchOutside(false);
 900		dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish());
 901		dialog.show();
 902	}
 903
 904	protected void filter(String needle) {
 905		if (xmppConnectionServiceBound) {
 906			this.filterContacts(needle);
 907			this.filterConferences(needle);
 908		}
 909	}
 910
 911	protected void filterContacts(String needle) {
 912		this.contacts.clear();
 913		for (Account account : xmppConnectionService.getAccounts()) {
 914			if (account.getStatus() != Account.State.DISABLED) {
 915				for (Contact contact : account.getRoster().getContacts()) {
 916					Presence.Status s = contact.getShownStatus();
 917					if (contact.showInRoster() && contact.match(this, needle)
 918							&& (!this.mHideOfflineContacts
 919							|| (needle != null && !needle.trim().isEmpty())
 920							|| s.compareTo(Presence.Status.OFFLINE) < 0)) {
 921						this.contacts.add(contact);
 922					}
 923				}
 924			}
 925		}
 926		Collections.sort(this.contacts);
 927		mContactsAdapter.notifyDataSetChanged();
 928	}
 929
 930	protected void filterConferences(String needle) {
 931		this.conferences.clear();
 932		for (Account account : xmppConnectionService.getAccounts()) {
 933			if (account.getStatus() != Account.State.DISABLED) {
 934				for (Bookmark bookmark : account.getBookmarks()) {
 935					if (bookmark.match(this, needle)) {
 936						this.conferences.add(bookmark);
 937					}
 938				}
 939			}
 940		}
 941		Collections.sort(this.conferences);
 942		mConferenceAdapter.notifyDataSetChanged();
 943	}
 944
 945	private void onTabChanged() {
 946		@DrawableRes final int fabDrawable;
 947		if (getSupportActionBar().getSelectedNavigationIndex() == 0) {
 948			fabDrawable = R.drawable.ic_person_add_white_24dp;
 949		} else {
 950			fabDrawable = R.drawable.ic_group_add_white_24dp;
 951		}
 952		binding.fab.setImageResource(fabDrawable);
 953		invalidateOptionsMenu();
 954	}
 955
 956	@Override
 957	public void OnUpdateBlocklist(final Status status) {
 958		refreshUi();
 959	}
 960
 961	@Override
 962	protected void refreshUiReal() {
 963		if (mSearchEditText != null) {
 964			filter(mSearchEditText.getText().toString());
 965		}
 966	}
 967
 968	public static class MyListFragment extends ListFragment {
 969		private AdapterView.OnItemClickListener mOnItemClickListener;
 970		private int mResContextMenu;
 971
 972		public void setContextMenu(final int res) {
 973			this.mResContextMenu = res;
 974		}
 975
 976		@Override
 977		public void onListItemClick(final ListView l, final View v, final int position, final long id) {
 978			if (mOnItemClickListener != null) {
 979				mOnItemClickListener.onItemClick(l, v, position, id);
 980			}
 981		}
 982
 983		public void setOnListItemClickListener(AdapterView.OnItemClickListener l) {
 984			this.mOnItemClickListener = l;
 985		}
 986
 987		@Override
 988		public void onViewCreated(@NonNull final View view, final Bundle savedInstanceState) {
 989			super.onViewCreated(view, savedInstanceState);
 990			registerForContextMenu(getListView());
 991			getListView().setFastScrollEnabled(true);
 992			getListView().setDivider(null);
 993			getListView().setDividerHeight(0);
 994		}
 995
 996		@Override
 997		public void onCreateContextMenu(final ContextMenu menu, final View v,
 998		                                final ContextMenuInfo menuInfo) {
 999			super.onCreateContextMenu(menu, v, menuInfo);
1000			final StartConversationActivity activity = (StartConversationActivity) getActivity();
1001			if (activity == null) {
1002				return;
1003			}
1004			activity.getMenuInflater().inflate(mResContextMenu, menu);
1005			final AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1006			if (mResContextMenu == R.menu.conference_context) {
1007				activity.conference_context_id = acmi.position;
1008			} else if (mResContextMenu == R.menu.contact_context) {
1009				activity.contact_context_id = acmi.position;
1010				final Contact contact = (Contact) activity.contacts.get(acmi.position);
1011				final MenuItem blockUnblockItem = menu.findItem(R.id.context_contact_block_unblock);
1012				final MenuItem showContactDetailsItem = menu.findItem(R.id.context_contact_details);
1013				if (contact.isSelf()) {
1014					showContactDetailsItem.setVisible(false);
1015				}
1016				XmppConnection xmpp = contact.getAccount().getXmppConnection();
1017				if (xmpp != null && xmpp.getFeatures().blocking() && !contact.isSelf()) {
1018					if (contact.isBlocked()) {
1019						blockUnblockItem.setTitle(R.string.unblock_contact);
1020					} else {
1021						blockUnblockItem.setTitle(R.string.block_contact);
1022					}
1023				} else {
1024					blockUnblockItem.setVisible(false);
1025				}
1026			}
1027		}
1028
1029		@Override
1030		public boolean onContextItemSelected(final MenuItem item) {
1031			StartConversationActivity activity = (StartConversationActivity) getActivity();
1032			if (activity == null) {
1033				return true;
1034			}
1035			switch (item.getItemId()) {
1036				case R.id.context_start_conversation:
1037					activity.openConversationForContact();
1038					break;
1039				case R.id.context_contact_details:
1040					activity.openDetailsForContact();
1041					break;
1042				case R.id.context_contact_block_unblock:
1043					activity.toggleContactBlock();
1044					break;
1045				case R.id.context_delete_contact:
1046					activity.deleteContact();
1047					break;
1048				case R.id.context_join_conference:
1049					activity.openConversationForBookmark();
1050					break;
1051				case R.id.context_share_uri:
1052					activity.shareBookmarkUri();
1053					break;
1054				case R.id.context_delete_conference:
1055					activity.deleteConference();
1056			}
1057			return true;
1058		}
1059	}
1060
1061	public class ListPagerAdapter extends PagerAdapter {
1062		FragmentManager fragmentManager;
1063		MyListFragment[] fragments;
1064
1065		public ListPagerAdapter(FragmentManager fm) {
1066			fragmentManager = fm;
1067			fragments = new MyListFragment[2];
1068		}
1069
1070		public void requestFocus(int pos) {
1071			if (fragments.length > pos) {
1072				fragments[pos].getListView().requestFocus();
1073			}
1074		}
1075
1076		@Override
1077		public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
1078			assert (0 <= position && position < fragments.length);
1079			FragmentTransaction trans = fragmentManager.beginTransaction();
1080			trans.remove(fragments[position]);
1081			trans.commit();
1082			fragments[position] = null;
1083		}
1084
1085		@Override
1086		public Fragment instantiateItem(@NonNull ViewGroup container, int position) {
1087			Fragment fragment = getItem(position);
1088			FragmentTransaction trans = fragmentManager.beginTransaction();
1089			trans.add(container.getId(), fragment, "fragment:" + position);
1090			trans.commit();
1091			return fragment;
1092		}
1093
1094		@Override
1095		public int getCount() {
1096			return fragments.length;
1097		}
1098
1099		@Override
1100		public boolean isViewFromObject(@NonNull View view, @NonNull Object fragment) {
1101			return ((Fragment) fragment).getView() == view;
1102		}
1103
1104		public Fragment getItem(int position) {
1105			assert (0 <= position && position < fragments.length);
1106			if (fragments[position] == null) {
1107				final MyListFragment listFragment = new MyListFragment();
1108				if (position == 1) {
1109					listFragment.setListAdapter(mConferenceAdapter);
1110					listFragment.setContextMenu(R.menu.conference_context);
1111					listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForBookmark(p));
1112				} else {
1113
1114					listFragment.setListAdapter(mContactsAdapter);
1115					listFragment.setContextMenu(R.menu.contact_context);
1116					listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForContact(p));
1117				}
1118				fragments[position] = listFragment;
1119			}
1120			return fragments[position];
1121		}
1122	}
1123
1124	private class Invite extends XmppUri {
1125
1126		public String account;
1127
1128		public Invite(final Uri uri) {
1129			super(uri);
1130		}
1131
1132		public Invite(final String uri) {
1133			super(uri);
1134		}
1135
1136		public Invite(Uri uri, boolean safeSource) {
1137			super(uri, safeSource);
1138		}
1139
1140		boolean invite() {
1141			if (!isJidValid()) {
1142				Toast.makeText(StartConversationActivity.this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
1143				return false;
1144			}
1145			if (getJid() != null) {
1146				return handleJid(this);
1147			}
1148			return false;
1149		}
1150	}
1151}