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