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