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