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