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