StartConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.app.Dialog;
   6import android.app.PendingIntent;
   7import android.content.ActivityNotFoundException;
   8import android.content.Context;
   9import android.content.Intent;
  10import android.content.SharedPreferences;
  11import android.content.pm.PackageManager;
  12import android.net.Uri;
  13import android.os.Build;
  14import android.os.Bundle;
  15import android.preference.PreferenceManager;
  16import android.text.Editable;
  17import android.text.Html;
  18import android.text.TextWatcher;
  19import android.text.method.LinkMovementMethod;
  20import android.util.Log;
  21import android.util.Pair;
  22import android.view.ContextMenu;
  23import android.view.ContextMenu.ContextMenuInfo;
  24import android.view.KeyEvent;
  25import android.view.LayoutInflater;
  26import android.view.Menu;
  27import android.view.MenuItem;
  28import android.view.View;
  29import android.view.ViewGroup;
  30import android.view.inputmethod.InputMethodManager;
  31import android.widget.AdapterView;
  32import android.widget.AdapterView.AdapterContextMenuInfo;
  33import android.widget.ArrayAdapter;
  34import android.widget.AutoCompleteTextView;
  35import android.widget.CheckBox;
  36import android.widget.EditText;
  37import android.widget.ListView;
  38import android.widget.Spinner;
  39import android.widget.TextView;
  40import android.widget.Toast;
  41
  42import androidx.annotation.MenuRes;
  43import androidx.annotation.NonNull;
  44import androidx.annotation.Nullable;
  45import androidx.annotation.StringRes;
  46import androidx.appcompat.app.ActionBar;
  47import androidx.appcompat.app.AlertDialog;
  48import androidx.appcompat.widget.PopupMenu;
  49import androidx.core.content.ContextCompat;
  50import androidx.databinding.DataBindingUtil;
  51import androidx.fragment.app.Fragment;
  52import androidx.fragment.app.FragmentManager;
  53import androidx.fragment.app.FragmentTransaction;
  54import androidx.recyclerview.widget.RecyclerView;
  55import androidx.recyclerview.widget.LinearLayoutManager;
  56import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
  57import androidx.viewpager.widget.PagerAdapter;
  58import androidx.viewpager.widget.ViewPager;
  59
  60import com.google.android.material.textfield.TextInputLayout;
  61import com.leinardi.android.speeddial.SpeedDialActionItem;
  62import com.leinardi.android.speeddial.SpeedDialView;
  63
  64import java.util.Arrays;
  65import java.util.ArrayList;
  66import java.util.Collections;
  67import java.util.Comparator;
  68import java.util.HashSet;
  69import java.util.List;
  70import java.util.Locale;
  71import java.util.Map;
  72import java.util.concurrent.atomic.AtomicBoolean;
  73import java.util.stream.Collectors;
  74
  75import eu.siacs.conversations.Config;
  76import eu.siacs.conversations.R;
  77import eu.siacs.conversations.databinding.ActivityStartConversationBinding;
  78import eu.siacs.conversations.entities.Account;
  79import eu.siacs.conversations.entities.Bookmark;
  80import eu.siacs.conversations.entities.Contact;
  81import eu.siacs.conversations.entities.Conversation;
  82import eu.siacs.conversations.entities.ListItem;
  83import eu.siacs.conversations.entities.MucOptions;
  84import eu.siacs.conversations.entities.Presence;
  85import eu.siacs.conversations.services.QuickConversationsService;
  86import eu.siacs.conversations.services.XmppConnectionService;
  87import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  88import eu.siacs.conversations.ui.adapter.ListItemAdapter;
  89import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
  90import eu.siacs.conversations.ui.util.JidDialog;
  91import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  92import eu.siacs.conversations.ui.util.PendingItem;
  93import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
  94import eu.siacs.conversations.ui.widget.SwipeRefreshListFragment;
  95import eu.siacs.conversations.utils.AccountUtils;
  96import eu.siacs.conversations.utils.UIHelper;
  97import eu.siacs.conversations.utils.XmppUri;
  98import eu.siacs.conversations.xml.Element;
  99import eu.siacs.conversations.xml.Namespace;
 100import eu.siacs.conversations.xmpp.Jid;
 101import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 102import eu.siacs.conversations.xmpp.XmppConnection;
 103import eu.siacs.conversations.xmpp.forms.Data;
 104import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 105
 106public class StartConversationActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, CreatePrivateGroupChatDialog.CreateConferenceDialogListener, JoinConferenceDialog.JoinConferenceDialogListener, SwipeRefreshLayout.OnRefreshListener, CreatePublicChannelDialog.CreatePublicChannelDialogListener {
 107
 108    public static final String EXTRA_INVITE_URI = "eu.siacs.conversations.invite_uri";
 109
 110    private final int REQUEST_SYNC_CONTACTS = 0x28cf;
 111    private final int REQUEST_CREATE_CONFERENCE = 0x39da;
 112    private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
 113    private final PendingItem<String> mInitialSearchValue = new PendingItem<>();
 114    private final AtomicBoolean oneShotKeyboardSuppress = new AtomicBoolean();
 115    public ListItem contextItem;
 116    private ListPagerAdapter mListPagerAdapter;
 117    private final List<ListItem> contacts = new ArrayList<>();
 118    private ListItemAdapter mContactsAdapter;
 119    private TagsAdapter mTagsAdapter = new TagsAdapter();
 120    private final List<ListItem> conferences = new ArrayList<>();
 121    private ListItemAdapter mConferenceAdapter;
 122    private final List<String> mActivatedAccounts = new ArrayList<>();
 123    private EditText mSearchEditText;
 124    private final AtomicBoolean mRequestedContactsPermission = new AtomicBoolean(false);
 125    private final AtomicBoolean mOpenedFab = new AtomicBoolean(false);
 126    private boolean mHideOfflineContacts = false;
 127    private boolean createdByViewIntent = false;
 128    private final MenuItem.OnActionExpandListener mOnActionExpandListener = new MenuItem.OnActionExpandListener() {
 129
 130        @Override
 131        public boolean onMenuItemActionExpand(MenuItem item) {
 132            mSearchEditText.post(() -> {
 133                updateSearchViewHint();
 134                mSearchEditText.requestFocus();
 135                if (oneShotKeyboardSuppress.compareAndSet(true, false)) {
 136                    return;
 137                }
 138                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 139                if (imm != null) {
 140                    imm.showSoftInput(mSearchEditText, InputMethodManager.SHOW_IMPLICIT);
 141                }
 142            });
 143            if (binding.speedDial.isOpen()) {
 144                binding.speedDial.close();
 145            }
 146            return true;
 147        }
 148
 149        @Override
 150        public boolean onMenuItemActionCollapse(MenuItem item) {
 151            SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this);
 152            mSearchEditText.setText("");
 153            filter(null);
 154            navigateBack();
 155            return true;
 156        }
 157    };
 158    private final TextWatcher mSearchTextWatcher = new TextWatcher() {
 159
 160        @Override
 161        public void afterTextChanged(Editable editable) {
 162            filter(editable.toString());
 163        }
 164
 165        @Override
 166        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
 167        }
 168
 169        @Override
 170        public void onTextChanged(CharSequence s, int start, int before, int count) {
 171        }
 172    };
 173    private MenuItem mMenuSearchView;
 174    private final ListItemAdapter.OnTagClickedListener mOnTagClickedListener = new ListItemAdapter.OnTagClickedListener() {
 175        @Override
 176        public void onTagClicked(String tag) {
 177            if (mMenuSearchView != null) {
 178                mMenuSearchView.expandActionView();
 179                mSearchEditText.setText("");
 180                mSearchEditText.append(tag);
 181                filter(tag);
 182            }
 183        }
 184    };
 185    private Pair<Integer, Intent> mPostponedActivityResult;
 186    private Toast mToast;
 187    private final UiCallback<Conversation> mAdhocConferenceCallback = new UiCallback<Conversation>() {
 188        @Override
 189        public void success(final Conversation conversation) {
 190            runOnUiThread(() -> {
 191                hideToast();
 192                switchToConversation(conversation);
 193            });
 194        }
 195
 196        @Override
 197        public void error(final int errorCode, Conversation object) {
 198            runOnUiThread(() -> replaceToast(getString(errorCode)));
 199        }
 200
 201        @Override
 202        public void userInputRequired(PendingIntent pi, Conversation object) {
 203
 204        }
 205    };
 206    private ActivityStartConversationBinding binding;
 207    private final TextView.OnEditorActionListener mSearchDone = new TextView.OnEditorActionListener() {
 208        @Override
 209        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
 210            int pos = binding.startConversationViewPager.getCurrentItem();
 211            if (pos == 0) {
 212                if (contacts.size() == 1) {
 213                    openConversation(contacts.get(0));
 214                    return true;
 215                } else if (contacts.size() == 0 && conferences.size() == 1) {
 216                    openConversationsForBookmark((Bookmark) conferences.get(0));
 217                    return true;
 218                }
 219            } else {
 220                if (conferences.size() == 1) {
 221                    openConversationsForBookmark((Bookmark) conferences.get(0));
 222                    return true;
 223                } else if (conferences.size() == 0 && contacts.size() == 1) {
 224                    openConversation(contacts.get(0));
 225                    return true;
 226                }
 227            }
 228            SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this);
 229            mListPagerAdapter.requestFocus(pos);
 230            return true;
 231        }
 232    };
 233
 234    public static void populateAccountSpinner(Context context, List<String> accounts, Spinner spinner) {
 235        if (accounts.size() > 0) {
 236            ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.simple_list_item, accounts);
 237            adapter.setDropDownViewResource(R.layout.simple_list_item);
 238            spinner.setAdapter(adapter);
 239            spinner.setEnabled(true);
 240        } else {
 241            ArrayAdapter<String> adapter = new ArrayAdapter<>(context,
 242                    R.layout.simple_list_item,
 243                    Collections.singletonList(context.getString(R.string.no_accounts)));
 244            adapter.setDropDownViewResource(R.layout.simple_list_item);
 245            spinner.setAdapter(adapter);
 246            spinner.setEnabled(false);
 247        }
 248    }
 249
 250    public static void launch(Context context) {
 251        final Intent intent = new Intent(context, StartConversationActivity.class);
 252        context.startActivity(intent);
 253    }
 254
 255    private static Intent createLauncherIntent(Context context) {
 256        final Intent intent = new Intent(context, StartConversationActivity.class);
 257        intent.setAction(Intent.ACTION_MAIN);
 258        intent.addCategory(Intent.CATEGORY_LAUNCHER);
 259        return intent;
 260    }
 261
 262    private static boolean isViewIntent(final Intent i) {
 263        return i != null && (Intent.ACTION_VIEW.equals(i.getAction()) || Intent.ACTION_SENDTO.equals(i.getAction()) || i.hasExtra(EXTRA_INVITE_URI));
 264    }
 265
 266    protected void hideToast() {
 267        if (mToast != null) {
 268            mToast.cancel();
 269        }
 270    }
 271
 272    protected void replaceToast(String msg) {
 273        hideToast();
 274        mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
 275        mToast.show();
 276    }
 277
 278    @Override
 279    public void onRosterUpdate() {
 280        this.refreshUi();
 281    }
 282
 283    @Override
 284    public void onCreate(Bundle savedInstanceState) {
 285        super.onCreate(savedInstanceState);
 286        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_start_conversation);
 287        setSupportActionBar(binding.toolbar);
 288        configureActionBar(getSupportActionBar());
 289
 290        inflateFab(binding.speedDial, R.menu.start_conversation_fab_submenu);
 291        binding.tabLayout.setupWithViewPager(binding.startConversationViewPager);
 292        binding.startConversationViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
 293            @Override
 294            public void onPageSelected(int position) {
 295                updateSearchViewHint();
 296            }
 297        });
 298        mListPagerAdapter = new ListPagerAdapter(getSupportFragmentManager());
 299        binding.startConversationViewPager.setAdapter(mListPagerAdapter);
 300
 301        mConferenceAdapter = new ListItemAdapter(this, conferences);
 302        mContactsAdapter = new ListItemAdapter(this, contacts);
 303        mContactsAdapter.setOnTagClickedListener(this.mOnTagClickedListener);
 304
 305        final SharedPreferences preferences = getPreferences();
 306
 307        this.mHideOfflineContacts = QuickConversationsService.isConversations() && preferences.getBoolean("hide_offline", false);
 308
 309        final boolean startSearching = preferences.getBoolean("start_searching", getResources().getBoolean(R.bool.start_searching));
 310
 311        final Intent intent;
 312        if (savedInstanceState == null) {
 313            intent = getIntent();
 314        } else {
 315            createdByViewIntent = savedInstanceState.getBoolean("created_by_view_intent", false);
 316            final String search = savedInstanceState.getString("search");
 317            if (search != null) {
 318                mInitialSearchValue.push(search);
 319            }
 320            intent = savedInstanceState.getParcelable("intent");
 321        }
 322
 323        if (intent.getBooleanExtra("init", false)) {
 324            pendingViewIntent.push(intent);
 325        }
 326
 327        if (isViewIntent(intent)) {
 328            pendingViewIntent.push(intent);
 329            createdByViewIntent = true;
 330            setIntent(createLauncherIntent(this));
 331        } else if (startSearching && mInitialSearchValue.peek() == null) {
 332            mInitialSearchValue.push("");
 333        }
 334        mRequestedContactsPermission.set(savedInstanceState != null && savedInstanceState.getBoolean("requested_contacts_permission", false));
 335        mOpenedFab.set(savedInstanceState != null && savedInstanceState.getBoolean("opened_fab", false));
 336        binding.speedDial.setOnActionSelectedListener(actionItem -> {
 337            final String searchString = mSearchEditText != null ? mSearchEditText.getText().toString() : null;
 338            final String prefilled;
 339            if (isValidJid(searchString)) {
 340                prefilled = Jid.ofEscaped(searchString).toEscapedString();
 341            } else {
 342                prefilled = null;
 343            }
 344            switch (actionItem.getId()) {
 345                case R.id.discover_public_channels:
 346                    startActivity(new Intent(this, ChannelDiscoveryActivity.class));
 347                    break;
 348                case R.id.create_private_group_chat:
 349                    showCreatePrivateGroupChatDialog();
 350                    break;
 351                case R.id.create_public_channel:
 352                    showPublicChannelDialog();
 353                    break;
 354                case R.id.create_contact:
 355                    showCreateContactDialog(prefilled, null);
 356                    break;
 357            }
 358            return false;
 359        });
 360    }
 361
 362    private void inflateFab(final SpeedDialView speedDialView, final @MenuRes int menuRes) {
 363        speedDialView.clearActionItems();
 364        final PopupMenu popupMenu = new PopupMenu(this, new View(this));
 365        popupMenu.inflate(menuRes);
 366        final Menu menu = popupMenu.getMenu();
 367        for (int i = 0; i < menu.size(); i++) {
 368            final MenuItem menuItem = menu.getItem(i);
 369            final SpeedDialActionItem actionItem = new SpeedDialActionItem.Builder(menuItem.getItemId(), menuItem.getIcon())
 370                    .setLabel(menuItem.getTitle() != null ? menuItem.getTitle().toString() : null)
 371                    .setFabImageTintColor(ContextCompat.getColor(this, R.color.white))
 372                    .create();
 373            speedDialView.addActionItem(actionItem);
 374        }
 375    }
 376
 377    public static boolean isValidJid(String input) {
 378        try {
 379            Jid jid = Jid.ofEscaped(input);
 380            return !jid.isDomainJid();
 381        } catch (IllegalArgumentException e) {
 382            return false;
 383        }
 384    }
 385
 386    @Override
 387    public void onSaveInstanceState(Bundle savedInstanceState) {
 388        Intent pendingIntent = pendingViewIntent.peek();
 389        savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
 390        savedInstanceState.putBoolean("requested_contacts_permission", mRequestedContactsPermission.get());
 391        savedInstanceState.putBoolean("opened_fab", mOpenedFab.get());
 392        savedInstanceState.putBoolean("created_by_view_intent", createdByViewIntent);
 393        if (mMenuSearchView != null && mMenuSearchView.isActionViewExpanded()) {
 394            savedInstanceState.putString("search", mSearchEditText != null ? mSearchEditText.getText().toString() : null);
 395        }
 396        super.onSaveInstanceState(savedInstanceState);
 397    }
 398
 399    @Override
 400    public void onStart() {
 401        super.onStart();
 402        final int theme = findTheme();
 403        if (this.mTheme != theme) {
 404            recreate();
 405        } else {
 406            if (pendingViewIntent.peek() == null) {
 407                askForContactsPermissions();
 408            }
 409        }
 410        mConferenceAdapter.refreshSettings();
 411        mContactsAdapter.refreshSettings();
 412    }
 413
 414    @Override
 415    public void onNewIntent(final Intent intent) {
 416        super.onNewIntent(intent);
 417        if (xmppConnectionServiceBound) {
 418            processViewIntent(intent);
 419        } else {
 420            pendingViewIntent.push(intent);
 421        }
 422        setIntent(createLauncherIntent(this));
 423    }
 424
 425    protected void openConversationForContact(int position) {
 426        openConversation(contacts.get(position));
 427    }
 428
 429    protected void openConversation(ListItem item) {
 430        if (item instanceof Contact) {
 431            openConversationForContact((Contact) item);
 432        } else {
 433            openConversationsForBookmark((Bookmark) item);
 434        }
 435    }
 436
 437    protected void openConversationForContact(Contact contact) {
 438        Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
 439        SoftKeyboardUtils.hideSoftKeyboard(this);
 440        switchToConversation(conversation);
 441    }
 442
 443    protected void openConversationForBookmark(int position) {
 444        Bookmark bookmark = (Bookmark) conferences.get(position);
 445        openConversationsForBookmark(bookmark);
 446    }
 447
 448    protected void shareBookmarkUri() {
 449        shareAsChannel(this, contextItem.getJid().asBareJid().toEscapedString());
 450    }
 451
 452    protected void shareBookmarkUri(int position) {
 453        Bookmark bookmark = (Bookmark) conferences.get(position);
 454        shareAsChannel(this, bookmark.getJid().asBareJid().toEscapedString());
 455    }
 456
 457    public static void shareAsChannel(final Context context, final String address) {
 458        Intent shareIntent = new Intent();
 459        shareIntent.setAction(Intent.ACTION_SEND);
 460        shareIntent.putExtra(Intent.EXTRA_TEXT, "xmpp:" + Uri.encode(address, "@/+") + "?join");
 461        shareIntent.setType("text/plain");
 462        try {
 463            context.startActivity(Intent.createChooser(shareIntent, context.getText(R.string.share_uri_with)));
 464        } catch (ActivityNotFoundException e) {
 465            Toast.makeText(context, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 466        }
 467    }
 468
 469    protected void openConversationsForBookmark(Bookmark bookmark) {
 470        final Jid jid = bookmark.getFullJid();
 471        if (jid == null) {
 472            Toast.makeText(this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
 473            return;
 474        }
 475        Conversation conversation = xmppConnectionService.findOrCreateConversation(bookmark.getAccount(), jid, true, true, true);
 476        bookmark.setConversation(conversation);
 477        if (!bookmark.autojoin() && getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin))) {
 478            bookmark.setAutojoin(true);
 479            xmppConnectionService.createBookmark(bookmark.getAccount(), bookmark);
 480        }
 481        SoftKeyboardUtils.hideSoftKeyboard(this);
 482        switchToConversation(conversation);
 483    }
 484
 485    protected void openDetailsForContact() {
 486        switchToContactDetails((Contact) contextItem);
 487    }
 488
 489    protected void showQrForContact() {
 490        showQrCode("xmpp:" + contextItem.getJid().asBareJid().toEscapedString());
 491    }
 492
 493    protected void toggleContactBlock() {
 494        BlockContactDialog.show(this, (Contact) contextItem);
 495    }
 496
 497    protected void deleteContact() {
 498        final Contact contact = (Contact) contextItem;
 499        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
 500        builder.setNegativeButton(R.string.cancel, null);
 501        builder.setTitle(R.string.action_delete_contact);
 502        builder.setMessage(JidDialog.style(this, R.string.remove_contact_text, contact.getJid().toEscapedString()));
 503        builder.setPositiveButton(R.string.delete, (dialog, which) -> {
 504            xmppConnectionService.deleteContactOnServer(contact);
 505            filter(mSearchEditText.getText().toString());
 506        });
 507        builder.create().show();
 508    }
 509
 510    protected void deleteConference() {
 511        final Bookmark bookmark = (Bookmark) contextItem;
 512
 513        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 514        builder.setNegativeButton(R.string.cancel, null);
 515        builder.setTitle(R.string.delete_bookmark);
 516        builder.setMessage(JidDialog.style(this, R.string.remove_bookmark_text, bookmark.getJid().toEscapedString()));
 517        builder.setPositiveButton(R.string.delete, (dialog, which) -> {
 518            bookmark.setConversation(null);
 519            final Account account = bookmark.getAccount();
 520            xmppConnectionService.deleteBookmark(account, bookmark);
 521            filter(mSearchEditText.getText().toString());
 522        });
 523        builder.create().show();
 524
 525    }
 526
 527    @SuppressLint("InflateParams")
 528    protected void showCreateContactDialog(final String prefilledJid, final Invite invite) {
 529        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
 530        Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
 531        if (prev != null) {
 532            ft.remove(prev);
 533        }
 534        ft.addToBackStack(null);
 535        EnterJidDialog dialog = EnterJidDialog.newInstance(
 536                mActivatedAccounts,
 537                getString(R.string.start_conversation),
 538                getString(R.string.message),
 539                "Call",
 540                prefilledJid,
 541                invite == null ? null : invite.account,
 542                invite == null || !invite.hasFingerprints(),
 543                true,
 544                EnterJidDialog.SanityCheck.ALLOW_MUC
 545        );
 546
 547        dialog.setOnEnterJidDialogPositiveListener((accountJid, contactJid, call, save) -> {
 548            if (!xmppConnectionServiceBound) {
 549                return false;
 550            }
 551
 552            final Account account = xmppConnectionService.findAccountByJid(accountJid);
 553            if (account == null) {
 554                return true;
 555            }
 556            final Contact contact = account.getRoster().getContact(contactJid);
 557
 558            if (invite != null && invite.getName() != null) {
 559                contact.setServerName(invite.getName());
 560            }
 561
 562            if (contact.isSelf() || contact.showInRoster()) {
 563                switchToConversationDoNotAppend(contact, invite == null ? null : invite.getBody(), call ? "call" : null);
 564                return true;
 565            }
 566
 567            xmppConnectionService.checkIfMuc(account, contactJid, (isMuc) -> {
 568                runOnUiThread(() -> {
 569                    if (isMuc) {
 570                        if (save) {
 571                            Bookmark bookmark = account.getBookmark(contactJid);
 572                            if (bookmark != null) {
 573                                openConversationsForBookmark(bookmark);
 574                            } else {
 575                                bookmark = new Bookmark(account, contactJid.asBareJid());
 576                                bookmark.setAutojoin(getBooleanPreference("autojoin", R.bool.autojoin));
 577                                final String nick = contactJid.getResource();
 578                                if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
 579                                    bookmark.setNick(nick);
 580                                }
 581                                xmppConnectionService.createBookmark(account, bookmark);
 582                                final Conversation conversation = xmppConnectionService
 583                                        .findOrCreateConversation(account, contactJid, true, true, true);
 584                                bookmark.setConversation(conversation);
 585                                switchToConversationDoNotAppend(conversation, invite == null ? null : invite.getBody());
 586                            }
 587                        } else {
 588                            final Conversation conversation = xmppConnectionService.findOrCreateConversation(account, contactJid, true, true, true);
 589                            switchToConversationDoNotAppend(conversation, invite == null ? null : invite.getBody());
 590                        }
 591                    } else {
 592                        if (save) {
 593                            final String preAuth = invite == null ? null : invite.getParameter(XmppUri.PARAMETER_PRE_AUTH);
 594                            xmppConnectionService.createContact(contact, true, preAuth);
 595                            if (invite != null && invite.hasFingerprints()) {
 596                                xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
 597                            }
 598                        }
 599                        switchToConversationDoNotAppend(contact, invite == null ? null : invite.getBody(), call ? "call" : null);
 600                    }
 601
 602                    try {
 603                        dialog.dismiss();
 604                    } catch (final IllegalStateException e) { }
 605                });
 606            });
 607
 608            return false;
 609        });
 610        dialog.show(ft, FRAGMENT_TAG_DIALOG);
 611    }
 612
 613    @SuppressLint("InflateParams")
 614    protected void showJoinConferenceDialog(final String prefilledJid) {
 615        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
 616        Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
 617        if (prev != null) {
 618            ft.remove(prev);
 619        }
 620        ft.addToBackStack(null);
 621        JoinConferenceDialog joinConferenceFragment = JoinConferenceDialog.newInstance(prefilledJid, mActivatedAccounts);
 622        joinConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG);
 623    }
 624
 625    private void showCreatePrivateGroupChatDialog() {
 626        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
 627        Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
 628        if (prev != null) {
 629            ft.remove(prev);
 630        }
 631        ft.addToBackStack(null);
 632        CreatePrivateGroupChatDialog createConferenceFragment = CreatePrivateGroupChatDialog.newInstance(mActivatedAccounts);
 633        createConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG);
 634    }
 635
 636    private void showPublicChannelDialog() {
 637        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
 638        Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
 639        if (prev != null) {
 640            ft.remove(prev);
 641        }
 642        ft.addToBackStack(null);
 643        CreatePublicChannelDialog dialog = CreatePublicChannelDialog.newInstance(mActivatedAccounts);
 644        dialog.show(ft, FRAGMENT_TAG_DIALOG);
 645    }
 646
 647    public static Account getSelectedAccount(Context context, Spinner spinner) {
 648        if (spinner == null || !spinner.isEnabled()) {
 649            return null;
 650        }
 651        if (context instanceof XmppActivity) {
 652            Jid jid;
 653            try {
 654                if (Config.DOMAIN_LOCK != null) {
 655                    jid = Jid.ofEscaped((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null);
 656                } else {
 657                    jid = Jid.ofEscaped((String) spinner.getSelectedItem());
 658                }
 659            } catch (final IllegalArgumentException e) {
 660                return null;
 661            }
 662            final XmppConnectionService service = ((XmppActivity) context).xmppConnectionService;
 663            if (service == null) {
 664                return null;
 665            }
 666            return service.findAccountByJid(jid);
 667        } else {
 668            return null;
 669        }
 670    }
 671
 672    protected void switchToConversation(Contact contact) {
 673        Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
 674        switchToConversation(conversation);
 675    }
 676
 677    protected void switchToConversationDoNotAppend(Contact contact, String body) {
 678        switchToConversationDoNotAppend(contact, body, null);
 679    }
 680
 681    protected void switchToConversationDoNotAppend(Contact contact, String body, String postInit) {
 682        Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
 683        switchToConversation(conversation, body, false, null, false, true, postInit);
 684    }
 685
 686    @Override
 687    public void invalidateOptionsMenu() {
 688        boolean isExpanded = mMenuSearchView != null && mMenuSearchView.isActionViewExpanded();
 689        String text = mSearchEditText != null ? mSearchEditText.getText().toString() : "";
 690        if (isExpanded) {
 691            mInitialSearchValue.push(text);
 692            oneShotKeyboardSuppress.set(true);
 693        }
 694        super.invalidateOptionsMenu();
 695    }
 696
 697    private void updateSearchViewHint() {
 698        if (binding == null || mSearchEditText == null) {
 699            return;
 700        }
 701        if (binding.startConversationViewPager.getCurrentItem() == 0) {
 702            mSearchEditText.setHint(R.string.search_contacts);
 703            mSearchEditText.setContentDescription(getString(R.string.search_contacts));
 704        } else {
 705            mSearchEditText.setHint(R.string.search_bookmarks);
 706            mSearchEditText.setContentDescription(getString(R.string.search_bookmarks));
 707        }
 708    }
 709
 710    @Override
 711    public boolean onCreateOptionsMenu(Menu menu) {
 712        getMenuInflater().inflate(R.menu.start_conversation, menu);
 713        AccountUtils.showHideMenuItems(menu);
 714        MenuItem menuHideOffline = menu.findItem(R.id.action_hide_offline);
 715        MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
 716        qrCodeScanMenuItem.setVisible(isCameraFeatureAvailable());
 717        if (QuickConversationsService.isQuicksy()) {
 718            menuHideOffline.setVisible(false);
 719        } else {
 720            menuHideOffline.setVisible(true);
 721            menuHideOffline.setChecked(this.mHideOfflineContacts);
 722        }
 723        mMenuSearchView = menu.findItem(R.id.action_search);
 724        mMenuSearchView.setOnActionExpandListener(mOnActionExpandListener);
 725        View mSearchView = mMenuSearchView.getActionView();
 726        mSearchEditText = mSearchView.findViewById(R.id.search_field);
 727        mSearchEditText.addTextChangedListener(mSearchTextWatcher);
 728        mSearchEditText.setOnEditorActionListener(mSearchDone);
 729
 730        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
 731        boolean showDynamicTags = preferences.getBoolean(SettingsActivity.SHOW_DYNAMIC_TAGS, getResources().getBoolean(R.bool.show_dynamic_tags));
 732        if (showDynamicTags) {
 733            RecyclerView tags = mSearchView.findViewById(R.id.tags);
 734            tags.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
 735            tags.setAdapter(mTagsAdapter);
 736        }
 737
 738        String initialSearchValue = mInitialSearchValue.pop();
 739        if (initialSearchValue != null) {
 740            mMenuSearchView.expandActionView();
 741            mSearchEditText.append(initialSearchValue);
 742            filter(initialSearchValue);
 743        }
 744        updateSearchViewHint();
 745        return super.onCreateOptionsMenu(menu);
 746    }
 747
 748    @Override
 749    public boolean onOptionsItemSelected(MenuItem item) {
 750        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
 751            return false;
 752        }
 753        switch (item.getItemId()) {
 754            case android.R.id.home:
 755                navigateBack();
 756                return true;
 757            case R.id.action_scan_qr_code:
 758                UriHandlerActivity.scan(this);
 759                return true;
 760            case R.id.action_hide_offline:
 761                mHideOfflineContacts = !item.isChecked();
 762                getPreferences().edit().putBoolean("hide_offline", mHideOfflineContacts).apply();
 763                if (mSearchEditText != null) {
 764                    filter(mSearchEditText.getText().toString());
 765                }
 766                invalidateOptionsMenu();
 767        }
 768        return super.onOptionsItemSelected(item);
 769    }
 770
 771    @Override
 772    public boolean onKeyUp(int keyCode, KeyEvent event) {
 773        if (keyCode == KeyEvent.KEYCODE_SEARCH && !event.isLongPress()) {
 774            openSearch();
 775            return true;
 776        }
 777        int c = event.getUnicodeChar();
 778        if (c > 32) {
 779            if (mSearchEditText != null && !mSearchEditText.isFocused()) {
 780                openSearch();
 781                mSearchEditText.append(Character.toString((char) c));
 782                return true;
 783            }
 784        }
 785        return super.onKeyUp(keyCode, event);
 786    }
 787
 788    private void openSearch() {
 789        if (mMenuSearchView != null) {
 790            mMenuSearchView.expandActionView();
 791        }
 792    }
 793
 794    @Override
 795    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
 796        if (resultCode == RESULT_OK) {
 797            if (xmppConnectionServiceBound) {
 798                this.mPostponedActivityResult = null;
 799                if (requestCode == REQUEST_CREATE_CONFERENCE) {
 800                    Account account = extractAccount(intent);
 801                    final String name = intent.getStringExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME);
 802                    final List<Jid> jids = ChooseContactActivity.extractJabberIds(intent);
 803                    if (account != null && jids.size() > 0) {
 804                        // This hardcodes cheogram.com and is in general a terrible hack
 805                        // Ideally this would be based around XEP-0033 but until we think of a good fallback behaviour we keep using this gross commas thing
 806                        if (jids.stream().allMatch(jid -> jid.getDomain().toString().equals("cheogram.com"))) {
 807                            new AlertDialog.Builder(this)
 808                                .setMessage("You appear to be creating a group with only SMS contacts. Would you like to create a channel or an MMS group text?")
 809                                .setNeutralButton("Channel", (d, w) -> {
 810                                    if (xmppConnectionService.createAdhocConference(account, name, jids, mAdhocConferenceCallback)) {
 811                                        mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 812                                        mToast.show();
 813                                    }
 814                                }).setPositiveButton("Group Text", (d, w) -> {
 815                                    Jid groupJid = Jid.ofLocalAndDomain(jids.stream().map(jid -> jid.getLocal()).sorted().collect(Collectors.joining(",")), "cheogram.com");
 816                                    Contact group = account.getRoster().getContact(groupJid);
 817                                    if (name != null && !name.equals("")) group.setServerName(name);
 818                                    xmppConnectionService.createContact(group, true);
 819                                    switchToConversation(group);
 820                                }).create().show();
 821                        } else {
 822                            if (xmppConnectionService.createAdhocConference(account, name, jids, mAdhocConferenceCallback)) {
 823                                mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 824                                mToast.show();
 825                            }
 826                        }
 827                    }
 828                }
 829            } else {
 830                this.mPostponedActivityResult = new Pair<>(requestCode, intent);
 831            }
 832        }
 833        super.onActivityResult(requestCode, requestCode, intent);
 834    }
 835
 836    private void askForContactsPermissions() {
 837        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 838            if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
 839                if (mRequestedContactsPermission.compareAndSet(false, true)) {
 840                    if (QuickConversationsService.isQuicksy() || shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
 841                        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
 842                        final AtomicBoolean requestPermission = new AtomicBoolean(false);
 843                        builder.setTitle(R.string.sync_with_contacts);
 844                        if (QuickConversationsService.isQuicksy()) {
 845                            builder.setMessage(Html.fromHtml(getString(R.string.sync_with_contacts_quicksy)));
 846                        } else {
 847                            builder.setMessage(getString(R.string.sync_with_contacts_long, getString(R.string.app_name)));
 848                        }
 849                        @StringRes int confirmButtonText;
 850                        if (QuickConversationsService.isConversations()) {
 851                            confirmButtonText = R.string.next;
 852                        } else {
 853                            confirmButtonText = R.string.confirm;
 854                        }
 855                        builder.setPositiveButton(confirmButtonText, (dialog, which) -> {
 856                            if (requestPermission.compareAndSet(false, true)) {
 857                                requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
 858                            }
 859                        });
 860                        builder.setOnDismissListener(dialog -> {
 861                            if (QuickConversationsService.isConversations() && requestPermission.compareAndSet(false, true)) {
 862                                requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
 863
 864                            }
 865                        });
 866                        builder.setCancelable(QuickConversationsService.isQuicksy());
 867                        final AlertDialog dialog = builder.create();
 868                        dialog.setCanceledOnTouchOutside(QuickConversationsService.isQuicksy());
 869                        dialog.setOnShowListener(dialogInterface -> {
 870                            final TextView tv = dialog.findViewById(android.R.id.message);
 871                            if (tv != null) {
 872                                tv.setMovementMethod(LinkMovementMethod.getInstance());
 873                            }
 874                        });
 875                        dialog.show();
 876                    } else {
 877                        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
 878                    }
 879                }
 880            }
 881        }
 882    }
 883
 884    @Override
 885    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
 886        if (grantResults.length > 0)
 887            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 888                ScanActivity.onRequestPermissionResult(this, requestCode, grantResults);
 889                if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
 890                    if (QuickConversationsService.isQuicksy()) {
 891                        setRefreshing(true);
 892                    }
 893                    xmppConnectionService.loadPhoneContacts();
 894                    xmppConnectionService.startContactObserver();
 895                }
 896            }
 897    }
 898
 899    private void configureHomeButton() {
 900        final ActionBar actionBar = getSupportActionBar();
 901        if (actionBar == null) {
 902            return;
 903        }
 904        boolean openConversations = !createdByViewIntent && !xmppConnectionService.isConversationsListEmpty(null);
 905        actionBar.setDisplayHomeAsUpEnabled(openConversations);
 906        actionBar.setDisplayHomeAsUpEnabled(openConversations);
 907
 908    }
 909
 910    @Override
 911    protected void onBackendConnected() {
 912
 913        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
 914            xmppConnectionService.getQuickConversationsService().considerSyncBackground(false);
 915        }
 916        if (mPostponedActivityResult != null) {
 917            onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
 918            this.mPostponedActivityResult = null;
 919        }
 920        this.mActivatedAccounts.clear();
 921        this.mActivatedAccounts.addAll(AccountUtils.getEnabledAccounts(xmppConnectionService));
 922        configureHomeButton();
 923        Intent intent = pendingViewIntent.pop();
 924
 925        final boolean onboardingCancel = xmppConnectionService.getPreferences().getString("onboarding_action", "").equals("cancel");
 926        if (onboardingCancel) xmppConnectionService.getPreferences().edit().remove("onboarding_action").commit();
 927
 928        if (intent != null && intent.getBooleanExtra("init", false) && !onboardingCancel && !xmppConnectionService.getAccounts().isEmpty()) {
 929            Account selectedAccount = xmppConnectionService.getAccounts().get(0);
 930            final String accountJid = intent.getStringExtra(EXTRA_ACCOUNT);
 931            intent = null;
 932            boolean hasPstnOrSms = false;
 933            Account onboardingAccount = null;
 934            outer:
 935            for (Account account : xmppConnectionService.getAccounts()) {
 936                if (onboardingAccount == null && account.getJid().getDomain().equals(Config.ONBOARDING_DOMAIN)) onboardingAccount = account;
 937
 938                if (accountJid != null) {
 939                    if(account.getJid().asBareJid().toEscapedString().equals(accountJid)) {
 940                        selectedAccount = account;
 941                    } else {
 942                        continue;
 943                    }
 944                }
 945
 946                for (Contact contact : account.getRoster().getContacts()) {
 947                    if (contact.getPresences().anyIdentity("gateway", "pstn")) {
 948                        hasPstnOrSms = true;
 949                        break outer;
 950                    }
 951                    if (contact.getPresences().anyIdentity("gateway", "sms")) {
 952                        hasPstnOrSms = true;
 953                        break outer;
 954                    }
 955                }
 956            }
 957
 958            if (!hasPstnOrSms) {
 959                if (onboardingAccount != null && !selectedAccount.getJid().equals(onboardingAccount.getJid())) {
 960                    final Account onboardAccount = onboardingAccount;
 961                    final Account newAccount = selectedAccount;
 962                    final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
 963                    packet.setTo(Jid.of("cheogram.com"));
 964                    final Element c = packet.addChild("command", Namespace.COMMANDS);
 965                    c.setAttribute("node", "change jabber id");
 966                    c.setAttribute("action", "execute");
 967
 968                    xmppConnectionService.sendIqPacket(onboardingAccount, packet, (a, iq) -> {
 969                        Element command = iq.findChild("command", "http://jabber.org/protocol/commands");
 970                        if (command == null) {
 971                            Log.e(Config.LOGTAG, "Did not get expected data form from cheogram, got: " + iq);
 972                            return;
 973                        }
 974
 975                        Element form = command.findChild("x", "jabber:x:data");
 976                        Data dataForm = form == null ? null : Data.parse(form);
 977                        if (dataForm == null || dataForm.getFieldByName("new-jid") == null) {
 978                            Log.e(Config.LOGTAG, "Did not get expected data form from cheogram, got: " + iq);
 979                            return;
 980                        }
 981
 982                        dataForm.put("new-jid", newAccount.getJid().toEscapedString());
 983                        dataForm.submit();
 984                        command.setAttribute("action", "execute");
 985                        iq.setTo(iq.getFrom());
 986                        iq.setAttribute("type", "set");
 987                        iq.removeAttribute("from");
 988                        iq.removeAttribute("id");
 989                        xmppConnectionService.sendIqPacket(a, iq, (a2, iq2) -> {
 990                            Element command2 = iq2.findChild("command", "http://jabber.org/protocol/commands");
 991                            if (command2 != null && command2.getAttribute("status") != null && command2.getAttribute("status").equals("completed")) {
 992                                final IqPacket regPacket = new IqPacket(IqPacket.TYPE.SET);
 993                                regPacket.setTo(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"));
 994                                final Element c2 = regPacket.addChild("command", Namespace.COMMANDS);
 995                                c2.setAttribute("node", "jabber:iq:register");
 996                                c2.setAttribute("action", "execute");
 997                                xmppConnectionService.sendIqPacket(newAccount, regPacket, (a3, iq3) -> {
 998                                    Element command3 = iq3.findChild("command", "http://jabber.org/protocol/commands");
 999                                    if (command3 == null) {
1000                                        Log.e(Config.LOGTAG, "Did not get expected data form from cheogram, got: " + iq3);
1001                                        return;
1002                                    }
1003
1004                                    Element form3 = command3.findChild("x", "jabber:x:data");
1005                                    Data dataForm3 = form3 == null ? null : Data.parse(form3);
1006                                    if (dataForm3 == null || dataForm3.getFieldByName("confirm") == null) {
1007                                        Log.e(Config.LOGTAG, "Did not get expected data form from cheogram, got: " + iq3);
1008                                        return;
1009                                    }
1010
1011                                    dataForm3.put("confirm", "true");
1012                                    dataForm3.submit();
1013                                    command3.setAttribute("action", "execute");
1014                                    iq3.setTo(iq3.getFrom());
1015                                    iq3.setAttribute("type", "set");
1016                                    iq3.removeAttribute("from");
1017                                    iq3.removeAttribute("id");
1018                                    xmppConnectionService.sendIqPacket(newAccount, iq3, (a4, iq4) -> {
1019                                        Element command4 = iq2.findChild("command", "http://jabber.org/protocol/commands");
1020                                        if (command4 != null && command4.getAttribute("status") != null && command4.getAttribute("status").equals("completed")) {
1021                                            xmppConnectionService.createContact(newAccount.getRoster().getContact(iq4.getFrom().asBareJid()), true);
1022                                            Conversation withCheogram = xmppConnectionService.findOrCreateConversation(newAccount, iq4.getFrom().asBareJid(), true, true, true);
1023                                            xmppConnectionService.markRead(withCheogram);
1024                                            xmppConnectionService.clearConversationHistory(withCheogram);
1025                                            xmppConnectionService.deleteAccount(onboardAccount);
1026                                        } else {
1027                                            Log.e(Config.LOGTAG, "Error confirming jid switch, got: " + iq4);
1028                                        }
1029                                    });
1030                                });
1031                            } else {
1032                                Log.e(Config.LOGTAG, "Error during jid switch, got: " + iq2);
1033                            }
1034                        });
1035                    });
1036                } else {
1037                    startCommand(selectedAccount, Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register");
1038                    finish();
1039                    return;
1040                }
1041            }
1042        }
1043
1044        if (intent != null && processViewIntent(intent)) {
1045            filter(null);
1046        } else {
1047            if (mSearchEditText != null) {
1048                filter(mSearchEditText.getText().toString());
1049            } else {
1050                filter(null);
1051            }
1052        }
1053        Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
1054        if (fragment instanceof OnBackendConnected) {
1055            Log.d(Config.LOGTAG, "calling on backend connected on dialog");
1056            ((OnBackendConnected) fragment).onBackendConnected();
1057        }
1058        if (QuickConversationsService.isQuicksy()) {
1059            setRefreshing(xmppConnectionService.getQuickConversationsService().isSynchronizing());
1060        }
1061        if (QuickConversationsService.isConversations() && AccountUtils.hasEnabledAccounts(xmppConnectionService) && this.contacts.size() == 0 && this.conferences.size() == 0 && mOpenedFab.compareAndSet(false, true)) {
1062            binding.speedDial.open();
1063        }
1064    }
1065
1066    protected boolean processViewIntent(@NonNull Intent intent) {
1067        final String inviteUri = intent.getStringExtra(EXTRA_INVITE_URI);
1068        if (inviteUri != null) {
1069            final Invite invite = new Invite(inviteUri);
1070            invite.account = intent.getStringExtra(EXTRA_ACCOUNT);
1071            if (invite.isValidJid()) {
1072                return invite.invite();
1073            }
1074        }
1075        final String action = intent.getAction();
1076        if (action == null) {
1077            return false;
1078        }
1079        switch (action) {
1080            case Intent.ACTION_SENDTO:
1081            case Intent.ACTION_VIEW:
1082                Uri uri = intent.getData();
1083                if (uri != null) {
1084                    Invite invite = new Invite(intent.getData(), intent.getBooleanExtra("scanned", false));
1085                    invite.account = intent.getStringExtra(EXTRA_ACCOUNT);
1086                    invite.forceDialog = intent.getBooleanExtra("force_dialog", false);
1087                    return invite.invite();
1088                } else {
1089                    return false;
1090                }
1091        }
1092        return false;
1093    }
1094
1095    private boolean handleJid(Invite invite) {
1096        List<Contact> contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);
1097        if (invite.isAction(XmppUri.ACTION_JOIN)) {
1098            Conversation muc = xmppConnectionService.findFirstMuc(invite.getJid());
1099            if (muc != null && !invite.forceDialog) {
1100                switchToConversationDoNotAppend(muc, invite.getBody());
1101                return true;
1102            } else {
1103                showJoinConferenceDialog(invite.getJid().asBareJid().toEscapedString());
1104                return false;
1105            }
1106        } else if (contacts.size() == 0) {
1107            showCreateContactDialog(invite.getJid().toEscapedString(), invite);
1108            return false;
1109        } else if (contacts.size() == 1) {
1110            Contact contact = contacts.get(0);
1111            if (!invite.isSafeSource() && invite.hasFingerprints()) {
1112                displayVerificationWarningDialog(contact, invite);
1113            } else {
1114                if (invite.hasFingerprints()) {
1115                    if (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {
1116                        Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
1117                    }
1118                }
1119                if (invite.account != null) {
1120                    xmppConnectionService.getShortcutService().report(contact);
1121                }
1122                switchToConversationDoNotAppend(contact, invite.getBody());
1123            }
1124            return true;
1125        } else {
1126            if (mMenuSearchView != null) {
1127                mMenuSearchView.expandActionView();
1128                mSearchEditText.setText("");
1129                mSearchEditText.append(invite.getJid().toEscapedString());
1130                filter(invite.getJid().toEscapedString());
1131            } else {
1132                mInitialSearchValue.push(invite.getJid().toEscapedString());
1133            }
1134            return true;
1135        }
1136    }
1137
1138    private void displayVerificationWarningDialog(final Contact contact, final Invite invite) {
1139        AlertDialog.Builder builder = new AlertDialog.Builder(this);
1140        builder.setTitle(R.string.verify_omemo_keys);
1141        View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
1142        final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source);
1143        TextView warning = view.findViewById(R.id.warning);
1144        warning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName()));
1145        builder.setView(view);
1146        builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
1147            if (isTrustedSource.isChecked() && invite.hasFingerprints()) {
1148                xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
1149            }
1150            switchToConversationDoNotAppend(contact, invite.getBody());
1151        });
1152        builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish());
1153        AlertDialog dialog = builder.create();
1154        dialog.setCanceledOnTouchOutside(false);
1155        dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish());
1156        dialog.show();
1157    }
1158
1159    protected void filter(String needle) {
1160        if (xmppConnectionServiceBound) {
1161            this.filterContacts(needle);
1162            this.filterConferences(needle);
1163        }
1164    }
1165
1166    protected void filterContacts(String needle) {
1167        this.contacts.clear();
1168        ArrayList<ListItem.Tag> tags = new ArrayList<>();
1169        final List<Account> accounts = xmppConnectionService.getAccounts();
1170        boolean foundSopranica = false;
1171        for (Account account : accounts) {
1172            if (account.getStatus() != Account.State.DISABLED) {
1173                for (Contact contact : account.getRoster().getContacts()) {
1174                    Presence.Status s = contact.getShownStatus();
1175                    if (contact.showInContactList() && contact.match(this, needle)
1176                            && (!this.mHideOfflineContacts
1177                            || (needle != null && !needle.trim().isEmpty())
1178                            || s.compareTo(Presence.Status.OFFLINE) < 0)) {
1179                        this.contacts.add(contact);
1180                        tags.addAll(contact.getTags(this));
1181                    }
1182                }
1183
1184                final Contact self = new Contact(account.getSelfContact());
1185                self.setSystemName("Note to Self");
1186                if (self.match(this, needle)) {
1187                    this.contacts.add(self);
1188                }
1189
1190                for (Bookmark bookmark : account.getBookmarks()) {
1191                    if (bookmark.match(this, needle)) {
1192                        if (bookmark.getJid().toString().equals("discuss@conference.soprani.ca")) {
1193                            foundSopranica = true;
1194                        }
1195                        this.contacts.add(bookmark);
1196                        tags.addAll(bookmark.getTags(this));
1197                    }
1198                }
1199            }
1200        }
1201
1202        Comparator<Map.Entry<ListItem.Tag,Integer>> sortTagsBy = Map.Entry.comparingByValue(Comparator.reverseOrder());
1203        sortTagsBy = sortTagsBy.thenComparing(entry -> entry.getKey().getName());
1204
1205        mTagsAdapter.setTags(
1206            tags.stream()
1207            .collect(Collectors.toMap((x) -> x, (t) -> 1, (c1, c2) -> c1 + c2))
1208            .entrySet().stream()
1209            .sorted(sortTagsBy)
1210            .map(e -> e.getKey()).collect(Collectors.toList())
1211        );
1212        Collections.sort(this.contacts);
1213
1214        final boolean sopranicaDeleted = getPreferences().getBoolean("cheogram_sopranica_bookmark_deleted", false);
1215
1216        if (!sopranicaDeleted && !foundSopranica && (needle == null || needle.equals("")) && xmppConnectionService.getAccounts().size() > 0) {
1217            Bookmark bookmark = new Bookmark(
1218                xmppConnectionService.getAccounts().get(0),
1219                Jid.of("discuss@conference.soprani.ca")
1220            );
1221            bookmark.setBookmarkName("Soprani.ca / Cheogram Discussion");
1222            bookmark.addChild("group").setContent("support");
1223            this.contacts.add(0, bookmark);
1224        }
1225
1226        mContactsAdapter.notifyDataSetChanged();
1227    }
1228
1229    protected void filterConferences(String needle) {
1230        this.conferences.clear();
1231        for (final Account account : xmppConnectionService.getAccounts()) {
1232            if (account.getStatus() != Account.State.DISABLED) {
1233                for (final Bookmark bookmark : account.getBookmarks()) {
1234                    if (bookmark.match(this, needle)) {
1235                        this.conferences.add(bookmark);
1236                    }
1237                }
1238            }
1239        }
1240        Collections.sort(this.conferences);
1241        mConferenceAdapter.notifyDataSetChanged();
1242    }
1243
1244    @Override
1245    public void OnUpdateBlocklist(final Status status) {
1246        refreshUi();
1247    }
1248
1249    @Override
1250    protected void refreshUiReal() {
1251        if (mSearchEditText != null) {
1252            filter(mSearchEditText.getText().toString());
1253        }
1254        configureHomeButton();
1255        if (QuickConversationsService.isQuicksy()) {
1256            setRefreshing(xmppConnectionService.getQuickConversationsService().isSynchronizing());
1257        }
1258    }
1259
1260    @Override
1261    public void onBackPressed() {
1262        if (binding.speedDial.isOpen()) {
1263            binding.speedDial.close();
1264            return;
1265        }
1266        navigateBack();
1267    }
1268
1269    private void navigateBack() {
1270        if (!createdByViewIntent && xmppConnectionService != null && !xmppConnectionService.isConversationsListEmpty(null)) {
1271            Intent intent = new Intent(this, ConversationsActivity.class);
1272            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
1273            startActivity(intent);
1274        }
1275        finish();
1276    }
1277
1278    @Override
1279    public void onCreateDialogPositiveClick(Spinner spinner, String name) {
1280        if (!xmppConnectionServiceBound) {
1281            return;
1282        }
1283        final Account account = getSelectedAccount(this, spinner);
1284        if (account == null) {
1285            return;
1286        }
1287        Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class);
1288        intent.putExtra(ChooseContactActivity.EXTRA_SHOW_ENTER_JID, false);
1289        intent.putExtra(ChooseContactActivity.EXTRA_SELECT_MULTIPLE, true);
1290        intent.putExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME, name.trim());
1291        intent.putExtra(ChooseContactActivity.EXTRA_ACCOUNT, account.getJid().asBareJid().toEscapedString());
1292        intent.putExtra(ChooseContactActivity.EXTRA_TITLE_RES_ID, R.string.choose_participants);
1293        startActivityForResult(intent, REQUEST_CREATE_CONFERENCE);
1294    }
1295
1296    @Override
1297    public void onJoinDialogPositiveClick(Dialog dialog, Spinner spinner, TextInputLayout layout, AutoCompleteTextView jid, boolean isBookmarkChecked) {
1298        if (!xmppConnectionServiceBound) {
1299            return;
1300        }
1301        final Account account = getSelectedAccount(this, spinner);
1302        if (account == null) {
1303            return;
1304        }
1305        final String input = jid.getText().toString().trim();
1306        Jid conferenceJid;
1307        try {
1308            conferenceJid = Jid.ofEscaped(input);
1309        } catch (final IllegalArgumentException e) {
1310            final XmppUri xmppUri = new XmppUri(input);
1311            if (xmppUri.isValidJid() && xmppUri.isAction(XmppUri.ACTION_JOIN)) {
1312                final Editable editable = jid.getEditableText();
1313                editable.clear();
1314                editable.append(xmppUri.getJid().toEscapedString());
1315                conferenceJid = xmppUri.getJid();
1316            } else {
1317                layout.setError(getString(R.string.invalid_jid));
1318                return;
1319            }
1320        }
1321
1322        if (isBookmarkChecked) {
1323            Bookmark bookmark = account.getBookmark(conferenceJid);
1324            if (bookmark != null) {
1325                dialog.dismiss();
1326                openConversationsForBookmark(bookmark);
1327            } else {
1328                bookmark = new Bookmark(account, conferenceJid.asBareJid());
1329                bookmark.setAutojoin(getBooleanPreference("autojoin", R.bool.autojoin));
1330                final String nick = conferenceJid.getResource();
1331                if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
1332                    bookmark.setNick(nick);
1333                }
1334                xmppConnectionService.createBookmark(account, bookmark);
1335                final Conversation conversation = xmppConnectionService
1336                        .findOrCreateConversation(account, conferenceJid, true, true, true);
1337                bookmark.setConversation(conversation);
1338                dialog.dismiss();
1339                switchToConversation(conversation);
1340            }
1341        } else {
1342            final Conversation conversation = xmppConnectionService
1343                    .findOrCreateConversation(account, conferenceJid, true, true, true);
1344            dialog.dismiss();
1345            switchToConversation(conversation);
1346        }
1347    }
1348
1349    @Override
1350    public void onConversationUpdate() {
1351        refreshUi();
1352    }
1353
1354    @Override
1355    public void onRefresh() {
1356        Log.d(Config.LOGTAG, "user requested to refresh");
1357        if (QuickConversationsService.isQuicksy() && xmppConnectionService != null) {
1358            xmppConnectionService.getQuickConversationsService().considerSyncBackground(true);
1359        }
1360    }
1361
1362
1363    private void setRefreshing(boolean refreshing) {
1364        MyListFragment fragment = (MyListFragment) mListPagerAdapter.getItem(0);
1365        if (fragment != null) {
1366            fragment.setRefreshing(refreshing);
1367        }
1368    }
1369
1370    @Override
1371    public void onCreatePublicChannel(Account account, String name, Jid address) {
1372        mToast = Toast.makeText(this, R.string.creating_channel, Toast.LENGTH_LONG);
1373        mToast.show();
1374        xmppConnectionService.createPublicChannel(account, name, address, new UiCallback<Conversation>() {
1375            @Override
1376            public void success(Conversation conversation) {
1377                runOnUiThread(() -> {
1378                    hideToast();
1379                    switchToConversation(conversation);
1380                });
1381
1382            }
1383
1384            @Override
1385            public void error(int errorCode, Conversation conversation) {
1386                runOnUiThread(() -> {
1387                    replaceToast(getString(errorCode));
1388                    switchToConversation(conversation);
1389                });
1390            }
1391
1392            @Override
1393            public void userInputRequired(PendingIntent pi, Conversation object) {
1394
1395            }
1396        });
1397    }
1398
1399    public static class MyListFragment extends SwipeRefreshListFragment {
1400        private AdapterView.OnItemClickListener mOnItemClickListener;
1401        private int mResContextMenu;
1402
1403        public void setContextMenu(final int res) {
1404            this.mResContextMenu = res;
1405        }
1406
1407        @Override
1408        public void onListItemClick(final ListView l, final View v, final int position, final long id) {
1409            if (mOnItemClickListener != null) {
1410                mOnItemClickListener.onItemClick(l, v, position, id);
1411            }
1412        }
1413
1414        public void setOnListItemClickListener(AdapterView.OnItemClickListener l) {
1415            this.mOnItemClickListener = l;
1416        }
1417
1418        @Override
1419        public void onViewCreated(@NonNull final View view, final Bundle savedInstanceState) {
1420            super.onViewCreated(view, savedInstanceState);
1421            registerForContextMenu(getListView());
1422            getListView().setFastScrollEnabled(true);
1423            getListView().setDivider(null);
1424            getListView().setDividerHeight(0);
1425        }
1426
1427        @Override
1428        public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) {
1429            super.onCreateContextMenu(menu, v, menuInfo);
1430            final StartConversationActivity activity = (StartConversationActivity) getActivity();
1431            if (activity == null) {
1432                return;
1433            }
1434            final AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1435            activity.contextItem = null;
1436            if (mResContextMenu == R.menu.contact_context) {
1437                activity.contextItem = activity.contacts.get(acmi.position);
1438            } else if (mResContextMenu == R.menu.conference_context) {
1439                activity.contextItem = activity.conferences.get(acmi.position);
1440            }
1441            if (activity.contextItem instanceof Bookmark) {
1442                activity.getMenuInflater().inflate(R.menu.conference_context, menu);
1443                final Bookmark bookmark = (Bookmark) activity.contextItem;
1444                final Conversation conversation = bookmark.getConversation();
1445                final MenuItem share = menu.findItem(R.id.context_share_uri);
1446                share.setVisible(conversation == null || !conversation.isPrivateAndNonAnonymous());
1447            } else if (activity.contextItem instanceof Contact) {
1448                activity.getMenuInflater().inflate(R.menu.contact_context, menu);
1449                final Contact contact = (Contact) activity.contextItem;
1450                final MenuItem blockUnblockItem = menu.findItem(R.id.context_contact_block_unblock);
1451                final MenuItem showContactDetailsItem = menu.findItem(R.id.context_contact_details);
1452                final MenuItem deleteContactMenuItem = menu.findItem(R.id.context_delete_contact);
1453                if (contact.isSelf()) {
1454                    showContactDetailsItem.setVisible(false);
1455                }
1456                deleteContactMenuItem.setVisible(contact.showInRoster() && !contact.getOption(Contact.Options.SYNCED_VIA_OTHER));
1457                final XmppConnection xmpp = contact.getAccount().getXmppConnection();
1458                if (xmpp != null && xmpp.getFeatures().blocking() && !contact.isSelf()) {
1459                    if (contact.isBlocked()) {
1460                        blockUnblockItem.setTitle(R.string.unblock_contact);
1461                    } else {
1462                        blockUnblockItem.setTitle(R.string.block_contact);
1463                    }
1464                } else {
1465                    blockUnblockItem.setVisible(false);
1466                }
1467            }
1468        }
1469
1470        @Override
1471        public boolean onContextItemSelected(final MenuItem item) {
1472            StartConversationActivity activity = (StartConversationActivity) getActivity();
1473            if (activity == null) {
1474                return true;
1475            }
1476            switch (item.getItemId()) {
1477                case R.id.context_contact_details:
1478                    activity.openDetailsForContact();
1479                    break;
1480                case R.id.context_show_qr:
1481                    activity.showQrForContact();
1482                    break;
1483                case R.id.context_contact_block_unblock:
1484                    activity.toggleContactBlock();
1485                    break;
1486                case R.id.context_delete_contact:
1487                    activity.deleteContact();
1488                    break;
1489                case R.id.context_share_uri:
1490                    activity.shareBookmarkUri();
1491                    break;
1492                case R.id.context_delete_conference:
1493                    activity.deleteConference();
1494            }
1495            return true;
1496        }
1497    }
1498
1499    public class ListPagerAdapter extends PagerAdapter {
1500        private final FragmentManager fragmentManager;
1501        private final MyListFragment[] fragments;
1502
1503        ListPagerAdapter(FragmentManager fm) {
1504            fragmentManager = fm;
1505            fragments = new MyListFragment[2];
1506        }
1507
1508        public void requestFocus(int pos) {
1509            if (fragments.length > pos) {
1510                fragments[pos].getListView().requestFocus();
1511            }
1512        }
1513
1514        @Override
1515        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
1516            FragmentTransaction trans = fragmentManager.beginTransaction();
1517            trans.remove(fragments[position]);
1518            trans.commit();
1519            fragments[position] = null;
1520        }
1521
1522        @NonNull
1523        @Override
1524        public Fragment instantiateItem(@NonNull ViewGroup container, int position) {
1525            final Fragment fragment = getItem(position);
1526            final FragmentTransaction trans = fragmentManager.beginTransaction();
1527            trans.add(container.getId(), fragment, "fragment:" + position);
1528            try {
1529                trans.commit();
1530            } catch (IllegalStateException e) {
1531                //ignore
1532            }
1533            return fragment;
1534        }
1535
1536        @Override
1537        public int getCount() {
1538            return fragments.length;
1539        }
1540
1541        @Override
1542        public boolean isViewFromObject(@NonNull View view, @NonNull Object fragment) {
1543            return ((Fragment) fragment).getView() == view;
1544        }
1545
1546        @Nullable
1547        @Override
1548        public CharSequence getPageTitle(int position) {
1549            switch (position) {
1550                case 0:
1551                    return getResources().getString(R.string.contacts);
1552                case 1:
1553                    return getResources().getString(R.string.bookmarks);
1554                default:
1555                    return super.getPageTitle(position);
1556            }
1557        }
1558
1559        Fragment getItem(int position) {
1560            if (fragments[position] == null) {
1561                final MyListFragment listFragment = new MyListFragment();
1562                if (position == 1) {
1563                    listFragment.setListAdapter(mConferenceAdapter);
1564                    listFragment.setContextMenu(R.menu.conference_context);
1565                    listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForBookmark(p));
1566                } else {
1567                    listFragment.setListAdapter(mContactsAdapter);
1568                    listFragment.setContextMenu(R.menu.contact_context);
1569                    listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForContact(p));
1570                    if (QuickConversationsService.isQuicksy()) {
1571                        listFragment.setOnRefreshListener(StartConversationActivity.this);
1572                    }
1573                }
1574                fragments[position] = listFragment;
1575            }
1576            return fragments[position];
1577        }
1578    }
1579
1580    public static void addInviteUri(Intent to, Intent from) {
1581        if (from != null && from.hasExtra(EXTRA_INVITE_URI)) {
1582            final String invite = from.getStringExtra(EXTRA_INVITE_URI);
1583            to.putExtra(EXTRA_INVITE_URI, invite);
1584        }
1585    }
1586
1587    private class Invite extends XmppUri {
1588
1589        public String account;
1590
1591        boolean forceDialog = false;
1592
1593
1594        Invite(final String uri) {
1595            super(uri);
1596        }
1597
1598        Invite(Uri uri, boolean safeSource) {
1599            super(uri, safeSource);
1600        }
1601
1602        boolean invite() {
1603            if (!isValidJid()) {
1604                Toast.makeText(StartConversationActivity.this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
1605                return false;
1606            }
1607            if (getJid() != null) {
1608                return handleJid(this);
1609            }
1610            return false;
1611        }
1612    }
1613
1614    class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.ViewHolder> {
1615        class ViewHolder extends RecyclerView.ViewHolder {
1616            protected TextView tv;
1617
1618            public ViewHolder(View v) {
1619                super(v);
1620                tv = (TextView) v;
1621                tv.setOnClickListener(view -> {
1622                    String needle = mSearchEditText.getText().toString();
1623                    String tag = tv.getText().toString();
1624                    String[] parts = needle.split("[,\\s]+");
1625                    if(needle.isEmpty()) {
1626                        needle = tag;
1627                    } else if (tag.toLowerCase(Locale.US).contains(parts[parts.length-1])) {
1628                        needle = needle.replace(parts[parts.length-1], tag);
1629                    } else {
1630                        needle += ", " + tag;
1631                    }
1632                    mSearchEditText.setText("");
1633                    mSearchEditText.append(needle);
1634                    filter(needle);
1635                });
1636            }
1637
1638            public void setTag(ListItem.Tag tag) {
1639                tv.setText(tag.getName());
1640                tv.setBackgroundColor(tag.getColor());
1641            }
1642        }
1643
1644        protected List<ListItem.Tag> tags = new ArrayList<>();
1645
1646        @Override
1647        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
1648            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_tag, null);
1649            return new ViewHolder(view);
1650        }
1651
1652        @Override
1653        public void onBindViewHolder(ViewHolder viewHolder, int i) {
1654            viewHolder.setTag(tags.get(i));
1655        }
1656
1657        @Override
1658        public int getItemCount() {
1659            return tags.size();
1660        }
1661
1662        public void setTags(final List<ListItem.Tag> tags) {
1663            ListItem.Tag channelTag = new ListItem.Tag("Channel", UIHelper.getColorForName("Channel", true));
1664            String needle = mSearchEditText == null ? "" : mSearchEditText.getText().toString().toLowerCase(Locale.US).trim();
1665            HashSet<String> parts = new HashSet<>(Arrays.asList(needle.split("[,\\s]+")));
1666            this.tags = tags.stream().filter(
1667                tag -> !tag.equals(channelTag) && !parts.contains(tag.getName().toLowerCase(Locale.US))
1668            ).collect(Collectors.toList());
1669            if (!parts.contains("channel") && tags.contains(channelTag)) this.tags.add(0, channelTag);
1670            notifyDataSetChanged();
1671        }
1672    }
1673}