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