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