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