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.databinding.DataBindingUtil;
13import android.net.Uri;
14import android.os.Build;
15import android.os.Bundle;
16import android.support.annotation.DrawableRes;
17import android.support.annotation.NonNull;
18import android.support.annotation.Nullable;
19import android.support.v4.app.Fragment;
20import android.support.v4.app.FragmentManager;
21import android.support.v4.app.FragmentTransaction;
22import android.support.v4.app.ListFragment;
23import android.support.v4.view.PagerAdapter;
24import android.support.v4.view.ViewPager;
25import android.support.v7.app.ActionBar;
26import android.support.v7.app.AlertDialog;
27import android.support.v7.widget.Toolbar;
28import android.text.Editable;
29import android.text.TextWatcher;
30import android.util.Log;
31import android.util.Pair;
32import android.view.ContextMenu;
33import android.view.ContextMenu.ContextMenuInfo;
34import android.view.KeyEvent;
35import android.view.Menu;
36import android.view.MenuItem;
37import android.view.View;
38import android.view.ViewGroup;
39import android.view.inputmethod.InputMethodManager;
40import android.widget.AdapterView;
41import android.widget.AdapterView.AdapterContextMenuInfo;
42import android.widget.ArrayAdapter;
43import android.widget.AutoCompleteTextView;
44import android.widget.CheckBox;
45import android.widget.EditText;
46import android.widget.ListView;
47import android.widget.Spinner;
48import android.widget.TextView;
49import android.widget.Toast;
50
51import java.util.ArrayList;
52import java.util.Collections;
53import java.util.List;
54import java.util.concurrent.atomic.AtomicBoolean;
55
56import eu.siacs.conversations.Config;
57import eu.siacs.conversations.R;
58import eu.siacs.conversations.databinding.ActivityStartConversationBinding;
59import eu.siacs.conversations.entities.Account;
60import eu.siacs.conversations.entities.Bookmark;
61import eu.siacs.conversations.entities.Contact;
62import eu.siacs.conversations.entities.Conversation;
63import eu.siacs.conversations.entities.ListItem;
64import eu.siacs.conversations.entities.Presence;
65import eu.siacs.conversations.services.QuickConversationsService;
66import eu.siacs.conversations.services.XmppConnectionService;
67import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
68import eu.siacs.conversations.ui.adapter.ListItemAdapter;
69import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
70import eu.siacs.conversations.ui.service.EmojiService;
71import eu.siacs.conversations.ui.util.JidDialog;
72import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
73import eu.siacs.conversations.ui.util.PendingItem;
74import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
75import eu.siacs.conversations.utils.AccountUtils;
76import eu.siacs.conversations.utils.XmppUri;
77import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
78import eu.siacs.conversations.xmpp.XmppConnection;
79import rocks.xmpp.addr.Jid;
80
81public class StartConversationActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, CreateConferenceDialog.CreateConferenceDialogListener, JoinConferenceDialog.JoinConferenceDialogListener {
82
83 public static final String EXTRA_INVITE_URI = "eu.siacs.conversations.invite_uri";
84
85 private final int REQUEST_SYNC_CONTACTS = 0x28cf;
86 private final int REQUEST_CREATE_CONFERENCE = 0x39da;
87 private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
88 private final PendingItem<String> mInitialSearchValue = new PendingItem<>();
89 private final AtomicBoolean oneShotKeyboardSuppress = new AtomicBoolean();
90 public int conference_context_id;
91 public int contact_context_id;
92 private ListPagerAdapter mListPagerAdapter;
93 private List<ListItem> contacts = new ArrayList<>();
94 private ListItemAdapter mContactsAdapter;
95 private List<ListItem> conferences = new ArrayList<>();
96 private ListItemAdapter mConferenceAdapter;
97 private List<String> mActivatedAccounts = new ArrayList<>();
98 private EditText mSearchEditText;
99 private AtomicBoolean mRequestedContactsPermission = new AtomicBoolean(false);
100 private boolean mHideOfflineContacts = false;
101 private boolean createdByViewIntent = false;
102 private MenuItem.OnActionExpandListener mOnActionExpandListener = new MenuItem.OnActionExpandListener() {
103
104 @Override
105 public boolean onMenuItemActionExpand(MenuItem item) {
106 mSearchEditText.post(() -> {
107 updateSearchViewHint();
108 mSearchEditText.requestFocus();
109 if (oneShotKeyboardSuppress.compareAndSet(true, false)) {
110 return;
111 }
112 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
113 if (imm != null) {
114 imm.showSoftInput(mSearchEditText, InputMethodManager.SHOW_IMPLICIT);
115 }
116 });
117
118 return true;
119 }
120
121 @Override
122 public boolean onMenuItemActionCollapse(MenuItem item) {
123 SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this);
124 mSearchEditText.setText("");
125 filter(null);
126 return true;
127 }
128 };
129 private TextWatcher mSearchTextWatcher = new TextWatcher() {
130
131 @Override
132 public void afterTextChanged(Editable editable) {
133 filter(editable.toString());
134 }
135
136 @Override
137 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
138 }
139
140 @Override
141 public void onTextChanged(CharSequence s, int start, int before, int count) {
142 }
143 };
144 private MenuItem mMenuSearchView;
145 private ListItemAdapter.OnTagClickedListener mOnTagClickedListener = new ListItemAdapter.OnTagClickedListener() {
146 @Override
147 public void onTagClicked(String tag) {
148 if (mMenuSearchView != null) {
149 mMenuSearchView.expandActionView();
150 mSearchEditText.setText("");
151 mSearchEditText.append(tag);
152 filter(tag);
153 }
154 }
155 };
156 private Pair<Integer, Intent> mPostponedActivityResult;
157 private Toast mToast;
158 private UiCallback<Conversation> mAdhocConferenceCallback = new UiCallback<Conversation>() {
159 @Override
160 public void success(final Conversation conversation) {
161 runOnUiThread(() -> {
162 hideToast();
163 switchToConversation(conversation);
164 });
165 }
166
167 @Override
168 public void error(final int errorCode, Conversation object) {
169 runOnUiThread(() -> replaceToast(getString(errorCode)));
170 }
171
172 @Override
173 public void userInputRequried(PendingIntent pi, Conversation object) {
174
175 }
176 };
177 private ActivityStartConversationBinding binding;
178 private TextView.OnEditorActionListener mSearchDone = new TextView.OnEditorActionListener() {
179 @Override
180 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
181 int pos = binding.startConversationViewPager.getCurrentItem();
182 if (pos == 0) {
183 if (contacts.size() == 1) {
184 openConversationForContact((Contact) contacts.get(0));
185 return true;
186 } else if (contacts.size() == 0 && conferences.size() == 1) {
187 openConversationsForBookmark((Bookmark) conferences.get(0));
188 return true;
189 }
190 } else {
191 if (conferences.size() == 1) {
192 openConversationsForBookmark((Bookmark) conferences.get(0));
193 return true;
194 } else if (conferences.size() == 0 && contacts.size() == 1) {
195 openConversationForContact((Contact) contacts.get(0));
196 return true;
197 }
198 }
199 SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this);
200 mListPagerAdapter.requestFocus(pos);
201 return true;
202 }
203 };
204 private ViewPager.SimpleOnPageChangeListener mOnPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
205 @Override
206 public void onPageSelected(int position) {
207 onTabChanged();
208 }
209 };
210
211 public static void populateAccountSpinner(Context context, List<String> accounts, Spinner spinner) {
212 if (accounts.size() > 0) {
213 ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.simple_list_item, accounts);
214 adapter.setDropDownViewResource(R.layout.simple_list_item);
215 spinner.setAdapter(adapter);
216 spinner.setEnabled(true);
217 } else {
218 ArrayAdapter<String> adapter = new ArrayAdapter<>(context,
219 R.layout.simple_list_item,
220 Collections.singletonList(context.getString(R.string.no_accounts)));
221 adapter.setDropDownViewResource(R.layout.simple_list_item);
222 spinner.setAdapter(adapter);
223 spinner.setEnabled(false);
224 }
225 }
226
227 public static void launch(Context context) {
228 final Intent intent = new Intent(context, StartConversationActivity.class);
229 context.startActivity(intent);
230 }
231
232 private static Intent createLauncherIntent(Context context) {
233 final Intent intent = new Intent(context, StartConversationActivity.class);
234 intent.setAction(Intent.ACTION_MAIN);
235 intent.addCategory(Intent.CATEGORY_LAUNCHER);
236 return intent;
237 }
238
239 private static boolean isViewIntent(final Intent i) {
240 return i != null && (Intent.ACTION_VIEW.equals(i.getAction()) || Intent.ACTION_SENDTO.equals(i.getAction()) || i.hasExtra(EXTRA_INVITE_URI));
241 }
242
243 protected void hideToast() {
244 if (mToast != null) {
245 mToast.cancel();
246 }
247 }
248
249 protected void replaceToast(String msg) {
250 hideToast();
251 mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
252 mToast.show();
253 }
254
255 @Override
256 public void onRosterUpdate() {
257 this.refreshUi();
258 }
259
260 @Override
261 public void onCreate(Bundle savedInstanceState) {
262 super.onCreate(savedInstanceState);
263 new EmojiService(this).init();
264 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_start_conversation);
265 Toolbar toolbar = (Toolbar) binding.toolbar;
266 setSupportActionBar(toolbar);
267 configureActionBar(getSupportActionBar());
268 this.binding.fab.setOnClickListener((v) -> {
269 if (binding.startConversationViewPager.getCurrentItem() == 0) {
270 String searchString = mSearchEditText != null ? mSearchEditText.getText().toString() : null;
271 if (searchString != null && !searchString.trim().isEmpty()) {
272 try {
273 Jid jid = Jid.of(searchString);
274 if (jid.getLocal() != null && jid.isBareJid() && jid.getDomain().contains(".")) {
275 showCreateContactDialog(jid.toString(), null);
276 return;
277 }
278 } catch (IllegalArgumentException ignored) {
279 //ignore and fall through
280 }
281 }
282 showCreateContactDialog(null, null);
283 } else {
284 showCreateConferenceDialog();
285 }
286 });
287 binding.tabLayout.setupWithViewPager(binding.startConversationViewPager);
288 binding.startConversationViewPager.addOnPageChangeListener(mOnPageChangeListener);
289 mListPagerAdapter = new ListPagerAdapter(getSupportFragmentManager());
290 binding.startConversationViewPager.setAdapter(mListPagerAdapter);
291
292 mConferenceAdapter = new ListItemAdapter(this, conferences);
293 mContactsAdapter = new ListItemAdapter(this, contacts);
294 mContactsAdapter.setOnTagClickedListener(this.mOnTagClickedListener);
295
296 final SharedPreferences preferences = getPreferences();
297
298 this.mHideOfflineContacts = QuickConversationsService.isConversations() && preferences.getBoolean("hide_offline", false);
299
300 final boolean startSearching = preferences.getBoolean("start_searching",getResources().getBoolean(R.bool.start_searching));
301
302 final Intent intent;
303 if (savedInstanceState == null) {
304 intent = getIntent();
305 } else {
306 createdByViewIntent = savedInstanceState.getBoolean("created_by_view_intent", false);
307 final String search = savedInstanceState.getString("search");
308 if (search != null) {
309 mInitialSearchValue.push(search);
310 }
311 intent = savedInstanceState.getParcelable("intent");
312 }
313
314 if (isViewIntent(intent)) {
315 pendingViewIntent.push(intent);
316 createdByViewIntent = true;
317 setIntent(createLauncherIntent(this));
318 } else if (startSearching && mInitialSearchValue.peek() == null) {
319 mInitialSearchValue.push("");
320 }
321 }
322
323 @Override
324 public void onSaveInstanceState(Bundle savedInstanceState) {
325 Intent pendingIntent = pendingViewIntent.peek();
326 savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
327 savedInstanceState.putBoolean("created_by_view_intent",createdByViewIntent);
328 if (mMenuSearchView != null && mMenuSearchView.isActionViewExpanded()) {
329 savedInstanceState.putString("search", mSearchEditText != null ? mSearchEditText.getText().toString() : null);
330 }
331 super.onSaveInstanceState(savedInstanceState);
332 }
333
334 @Override
335 public void onStart() {
336 super.onStart();
337 final int theme = findTheme();
338 if (this.mTheme != theme) {
339 recreate();
340 } else {
341 if (pendingViewIntent.peek() == null) {
342 askForContactsPermissions();
343 }
344 }
345 mConferenceAdapter.refreshSettings();
346 mContactsAdapter.refreshSettings();
347 }
348
349 @Override
350 public void onNewIntent(final Intent intent) {
351 if (xmppConnectionServiceBound) {
352 processViewIntent(intent);
353 } else {
354 pendingViewIntent.push(intent);
355 }
356 setIntent(createLauncherIntent(this));
357 }
358
359 protected void openConversationForContact(int position) {
360 Contact contact = (Contact) contacts.get(position);
361 openConversationForContact(contact);
362 }
363
364 protected void openConversationForContact(Contact contact) {
365 Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
366 SoftKeyboardUtils.hideSoftKeyboard(this);
367 switchToConversation(conversation);
368 }
369
370 protected void openConversationForBookmark() {
371 openConversationForBookmark(conference_context_id);
372 }
373
374 protected void openConversationForBookmark(int position) {
375 Bookmark bookmark = (Bookmark) conferences.get(position);
376 openConversationsForBookmark(bookmark);
377 }
378
379 protected void shareBookmarkUri() {
380 shareBookmarkUri(conference_context_id);
381 }
382
383 protected void shareBookmarkUri(int position) {
384 Bookmark bookmark = (Bookmark) conferences.get(position);
385 Intent shareIntent = new Intent();
386 shareIntent.setAction(Intent.ACTION_SEND);
387 shareIntent.putExtra(Intent.EXTRA_TEXT, "xmpp:" + bookmark.getJid().asBareJid().toEscapedString() + "?join");
388 shareIntent.setType("text/plain");
389 try {
390 startActivity(Intent.createChooser(shareIntent, getText(R.string.share_uri_with)));
391 } catch (ActivityNotFoundException e) {
392 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
393 }
394 }
395
396 protected void openConversationsForBookmark(Bookmark bookmark) {
397 Jid jid = bookmark.getJid();
398 if (jid == null) {
399 Toast.makeText(this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
400 return;
401 }
402 Conversation conversation = xmppConnectionService.findOrCreateConversation(bookmark.getAccount(), jid, true, true, true);
403 bookmark.setConversation(conversation);
404 if (!bookmark.autojoin() && getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin))) {
405 bookmark.setAutojoin(true);
406 xmppConnectionService.pushBookmarks(bookmark.getAccount());
407 }
408 SoftKeyboardUtils.hideSoftKeyboard(this);
409 switchToConversation(conversation);
410 }
411
412 protected void openDetailsForContact() {
413 int position = contact_context_id;
414 Contact contact = (Contact) contacts.get(position);
415 switchToContactDetails(contact);
416 }
417
418 protected void showQrForContact() {
419 int position = contact_context_id;
420 Contact contact = (Contact) contacts.get(position);
421 showQrCode("xmpp:"+contact.getJid().asBareJid().toEscapedString());
422 }
423
424 protected void toggleContactBlock() {
425 final int position = contact_context_id;
426 BlockContactDialog.show(this, (Contact) contacts.get(position));
427 }
428
429 protected void deleteContact() {
430 final int position = contact_context_id;
431 final Contact contact = (Contact) contacts.get(position);
432 final AlertDialog.Builder builder = new AlertDialog.Builder(this);
433 builder.setNegativeButton(R.string.cancel, null);
434 builder.setTitle(R.string.action_delete_contact);
435 builder.setMessage(JidDialog.style(this, R.string.remove_contact_text, contact.getJid().toEscapedString()));
436 builder.setPositiveButton(R.string.delete, (dialog, which) -> {
437 xmppConnectionService.deleteContactOnServer(contact);
438 filter(mSearchEditText.getText().toString());
439 });
440 builder.create().show();
441 }
442
443 protected void deleteConference() {
444 int position = conference_context_id;
445 final Bookmark bookmark = (Bookmark) conferences.get(position);
446
447 AlertDialog.Builder builder = new AlertDialog.Builder(this);
448 builder.setNegativeButton(R.string.cancel, null);
449 builder.setTitle(R.string.delete_bookmark);
450 builder.setMessage(JidDialog.style(this, R.string.remove_bookmark_text, bookmark.getJid().toEscapedString()));
451 builder.setPositiveButton(R.string.delete, (dialog, which) -> {
452 bookmark.setConversation(null);
453 Account account = bookmark.getAccount();
454 account.getBookmarks().remove(bookmark);
455 xmppConnectionService.pushBookmarks(account);
456 filter(mSearchEditText.getText().toString());
457 });
458 builder.create().show();
459
460 }
461
462 @SuppressLint("InflateParams")
463 protected void showCreateContactDialog(final String prefilledJid, final Invite invite) {
464 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
465 Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
466 if (prev != null) {
467 ft.remove(prev);
468 }
469 ft.addToBackStack(null);
470 EnterJidDialog dialog = EnterJidDialog.newInstance(
471 mActivatedAccounts,
472 getString(R.string.dialog_title_create_contact),
473 getString(R.string.create),
474 prefilledJid,
475 null,
476 invite == null || !invite.hasFingerprints()
477 );
478
479 dialog.setOnEnterJidDialogPositiveListener((accountJid, contactJid) -> {
480 if (!xmppConnectionServiceBound) {
481 return false;
482 }
483
484 final Account account = xmppConnectionService.findAccountByJid(accountJid);
485 if (account == null) {
486 return true;
487 }
488
489 final Contact contact = account.getRoster().getContact(contactJid);
490 if (invite != null && invite.getName() != null) {
491 contact.setServerName(invite.getName());
492 }
493 if (contact.isSelf()) {
494 switchToConversation(contact);
495 return true;
496 } else if (contact.showInRoster()) {
497 throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists));
498 } else {
499 xmppConnectionService.createContact(contact, true);
500 if (invite != null && invite.hasFingerprints()) {
501 xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
502 }
503 switchToConversationDoNotAppend(contact, invite == null ? null : invite.getBody());
504 return true;
505 }
506 });
507 dialog.show(ft, FRAGMENT_TAG_DIALOG);
508 }
509
510 @SuppressLint("InflateParams")
511 protected void showJoinConferenceDialog(final String prefilledJid) {
512 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
513 Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
514 if (prev != null) {
515 ft.remove(prev);
516 }
517 ft.addToBackStack(null);
518 JoinConferenceDialog joinConferenceFragment = JoinConferenceDialog.newInstance(prefilledJid, mActivatedAccounts);
519 joinConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG);
520 }
521
522 private void showCreateConferenceDialog() {
523 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
524 Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
525 if (prev != null) {
526 ft.remove(prev);
527 }
528 ft.addToBackStack(null);
529 CreateConferenceDialog createConferenceFragment = CreateConferenceDialog.newInstance(mActivatedAccounts);
530 createConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG);
531 }
532
533 private Account getSelectedAccount(Spinner spinner) {
534 if (!spinner.isEnabled()) {
535 return null;
536 }
537 Jid jid;
538 try {
539 if (Config.DOMAIN_LOCK != null) {
540 jid = Jid.of((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null);
541 } else {
542 jid = Jid.of((String) spinner.getSelectedItem());
543 }
544 } catch (final IllegalArgumentException e) {
545 return null;
546 }
547 return xmppConnectionService.findAccountByJid(jid);
548 }
549
550 protected void switchToConversation(Contact contact) {
551 Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
552 switchToConversation(conversation);
553 }
554
555 protected void switchToConversationDoNotAppend(Contact contact, String body) {
556 Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
557 switchToConversationDoNotAppend(conversation, body);
558 }
559
560 @Override
561 public void invalidateOptionsMenu() {
562 boolean isExpanded = mMenuSearchView != null && mMenuSearchView.isActionViewExpanded();
563 String text = mSearchEditText != null ? mSearchEditText.getText().toString() : "";
564 if (isExpanded) {
565 mInitialSearchValue.push(text);
566 oneShotKeyboardSuppress.set(true);
567 }
568 super.invalidateOptionsMenu();
569 }
570
571 private void updateSearchViewHint() {
572 if (binding == null || mSearchEditText == null) {
573 return;
574 }
575 if (binding.startConversationViewPager.getCurrentItem() == 0) {
576 mSearchEditText.setHint(R.string.search_contacts);
577 } else {
578 mSearchEditText.setHint(R.string.search_groups);
579 }
580 }
581
582 @Override
583 public boolean onCreateOptionsMenu(Menu menu) {
584 getMenuInflater().inflate(R.menu.start_conversation, menu);
585 AccountUtils.showHideMenuItems(menu);
586 MenuItem menuHideOffline = menu.findItem(R.id.action_hide_offline);
587 MenuItem joinGroupChat = menu.findItem(R.id.action_join_conference);
588 MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
589 joinGroupChat.setVisible(binding.startConversationViewPager.getCurrentItem() == 1);
590 qrCodeScanMenuItem.setVisible(isCameraFeatureAvailable());
591 if (QuickConversationsService.isQuicksy()) {
592 menuHideOffline.setVisible(false);
593 } else {
594 menuHideOffline.setVisible(true);
595 menuHideOffline.setChecked(this.mHideOfflineContacts);
596 }
597 mMenuSearchView = menu.findItem(R.id.action_search);
598 mMenuSearchView.setOnActionExpandListener(mOnActionExpandListener);
599 View mSearchView = mMenuSearchView.getActionView();
600 mSearchEditText = mSearchView.findViewById(R.id.search_field);
601 mSearchEditText.addTextChangedListener(mSearchTextWatcher);
602 mSearchEditText.setOnEditorActionListener(mSearchDone);
603 String initialSearchValue = mInitialSearchValue.pop();
604 if (initialSearchValue != null) {
605 mMenuSearchView.expandActionView();
606 mSearchEditText.append(initialSearchValue);
607 filter(initialSearchValue);
608 }
609 updateSearchViewHint();
610 return super.onCreateOptionsMenu(menu);
611 }
612
613 @Override
614 public boolean onOptionsItemSelected(MenuItem item) {
615 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
616 return false;
617 }
618 switch (item.getItemId()) {
619 case android.R.id.home:
620 navigateBack();
621 return true;
622 case R.id.action_join_conference:
623 showJoinConferenceDialog(null);
624 return true;
625 case R.id.action_scan_qr_code:
626 UriHandlerActivity.scan(this);
627 return true;
628 case R.id.action_hide_offline:
629 mHideOfflineContacts = !item.isChecked();
630 getPreferences().edit().putBoolean("hide_offline", mHideOfflineContacts).apply();
631 if (mSearchEditText != null) {
632 filter(mSearchEditText.getText().toString());
633 }
634 invalidateOptionsMenu();
635 }
636 return super.onOptionsItemSelected(item);
637 }
638
639 @Override
640 public boolean onKeyUp(int keyCode, KeyEvent event) {
641 if (keyCode == KeyEvent.KEYCODE_SEARCH && !event.isLongPress()) {
642 openSearch();
643 return true;
644 }
645 int c = event.getUnicodeChar();
646 if (c > 32) {
647 if (mSearchEditText != null && !mSearchEditText.isFocused()) {
648 openSearch();
649 mSearchEditText.append(Character.toString((char) c));
650 return true;
651 }
652 }
653 return super.onKeyUp(keyCode, event);
654 }
655
656 private void openSearch() {
657 if (mMenuSearchView != null) {
658 mMenuSearchView.expandActionView();
659 }
660 }
661
662 @Override
663 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
664 if (resultCode == RESULT_OK) {
665 if (xmppConnectionServiceBound) {
666 this.mPostponedActivityResult = null;
667 if (requestCode == REQUEST_CREATE_CONFERENCE) {
668 Account account = extractAccount(intent);
669 final String name = intent.getStringExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME);
670 final List<Jid> jids = ChooseContactActivity.extractJabberIds(intent);
671 if (account != null && jids.size() > 0) {
672 if (xmppConnectionService.createAdhocConference(account, name, jids, mAdhocConferenceCallback)) {
673 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
674 mToast.show();
675 }
676 }
677 }
678 } else {
679 this.mPostponedActivityResult = new Pair<>(requestCode, intent);
680 }
681 }
682 super.onActivityResult(requestCode, requestCode, intent);
683 }
684
685 private void askForContactsPermissions() {
686 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
687 if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
688 if (mRequestedContactsPermission.compareAndSet(false, true)) {
689 if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
690 AlertDialog.Builder builder = new AlertDialog.Builder(this);
691 builder.setTitle(R.string.sync_with_contacts);
692 builder.setMessage(R.string.sync_with_contacts_long);
693 builder.setPositiveButton(R.string.next, (dialog, which) -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS));
694 builder.setOnDismissListener(dialog -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS));
695 builder.create().show();
696 } else {
697 requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
698 }
699 }
700 }
701 }
702 }
703
704 @Override
705 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
706 if (grantResults.length > 0)
707 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
708 ScanActivity.onRequestPermissionResult(this, requestCode, grantResults);
709 if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
710 xmppConnectionService.loadPhoneContacts();
711 xmppConnectionService.startContactObserver();
712 }
713 }
714 }
715
716 private void configureHomeButton() {
717 final ActionBar actionBar = getSupportActionBar();
718 if (actionBar == null) {
719 return;
720 }
721 boolean openConversations = !createdByViewIntent && !xmppConnectionService.isConversationsListEmpty(null);
722 actionBar.setDisplayHomeAsUpEnabled(openConversations);
723 actionBar.setDisplayHomeAsUpEnabled(openConversations);
724
725 }
726
727 @Override
728 protected void onBackendConnected() {
729 xmppConnectionService.getQuickConversationsService().considerSync();
730 if (mPostponedActivityResult != null) {
731 onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
732 this.mPostponedActivityResult = null;
733 }
734 this.mActivatedAccounts.clear();
735 for (Account account : xmppConnectionService.getAccounts()) {
736 if (account.getStatus() != Account.State.DISABLED) {
737 if (Config.DOMAIN_LOCK != null) {
738 this.mActivatedAccounts.add(account.getJid().getLocal());
739 } else {
740 this.mActivatedAccounts.add(account.getJid().asBareJid().toString());
741 }
742 }
743 }
744 configureHomeButton();
745 Intent intent = pendingViewIntent.pop();
746 if (intent != null && processViewIntent(intent)) {
747 filter(null);
748 } else {
749 if (mSearchEditText != null) {
750 filter(mSearchEditText.getText().toString());
751 } else {
752 filter(null);
753 }
754 }
755 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
756 if (fragment instanceof OnBackendConnected) {
757 Log.d(Config.LOGTAG, "calling on backend connected on dialog");
758 ((OnBackendConnected) fragment).onBackendConnected();
759 }
760 }
761
762 protected boolean processViewIntent(@NonNull Intent intent) {
763 final String inviteUri = intent.getStringExtra(EXTRA_INVITE_URI);
764 if (inviteUri != null) {
765 Invite invite = new Invite(inviteUri);
766 if (invite.isJidValid()) {
767 return invite.invite();
768 }
769 }
770 final String action = intent.getAction();
771 if (action == null) {
772 return false;
773 }
774 switch (action) {
775 case Intent.ACTION_SENDTO:
776 case Intent.ACTION_VIEW:
777 Uri uri = intent.getData();
778 if (uri != null) {
779 Invite invite = new Invite(intent.getData(), intent.getBooleanExtra("scanned", false));
780 invite.account = intent.getStringExtra("account");
781 return invite.invite();
782 } else {
783 return false;
784 }
785 }
786 return false;
787 }
788
789 private boolean handleJid(Invite invite) {
790 List<Contact> contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);
791 if (invite.isAction(XmppUri.ACTION_JOIN)) {
792 Conversation muc = xmppConnectionService.findFirstMuc(invite.getJid());
793 if (muc != null) {
794 switchToConversationDoNotAppend(muc, invite.getBody());
795 return true;
796 } else {
797 showJoinConferenceDialog(invite.getJid().asBareJid().toString());
798 return false;
799 }
800 } else if (contacts.size() == 0) {
801 showCreateContactDialog(invite.getJid().toString(), invite);
802 return false;
803 } else if (contacts.size() == 1) {
804 Contact contact = contacts.get(0);
805 if (!invite.isSafeSource() && invite.hasFingerprints()) {
806 displayVerificationWarningDialog(contact, invite);
807 } else {
808 if (invite.hasFingerprints()) {
809 if (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {
810 Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
811 }
812 }
813 if (invite.account != null) {
814 xmppConnectionService.getShortcutService().report(contact);
815 }
816 switchToConversationDoNotAppend(contact, invite.getBody());
817 }
818 return true;
819 } else {
820 if (mMenuSearchView != null) {
821 mMenuSearchView.expandActionView();
822 mSearchEditText.setText("");
823 mSearchEditText.append(invite.getJid().toString());
824 filter(invite.getJid().toString());
825 } else {
826 mInitialSearchValue.push(invite.getJid().toString());
827 }
828 return true;
829 }
830 }
831
832 private void displayVerificationWarningDialog(final Contact contact, final Invite invite) {
833 AlertDialog.Builder builder = new AlertDialog.Builder(this);
834 builder.setTitle(R.string.verify_omemo_keys);
835 View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
836 final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source);
837 TextView warning = view.findViewById(R.id.warning);
838 warning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName()));
839 builder.setView(view);
840 builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
841 if (isTrustedSource.isChecked() && invite.hasFingerprints()) {
842 xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
843 }
844 switchToConversationDoNotAppend(contact, invite.getBody());
845 });
846 builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish());
847 AlertDialog dialog = builder.create();
848 dialog.setCanceledOnTouchOutside(false);
849 dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish());
850 dialog.show();
851 }
852
853 protected void filter(String needle) {
854 if (xmppConnectionServiceBound) {
855 this.filterContacts(needle);
856 this.filterConferences(needle);
857 }
858 }
859
860 protected void filterContacts(String needle) {
861 this.contacts.clear();
862 final List<Account> accounts = xmppConnectionService.getAccounts();
863 for (Account account : accounts) {
864 if (account.getStatus() != Account.State.DISABLED) {
865 for (Contact contact : account.getRoster().getContacts()) {
866 Presence.Status s = contact.getShownStatus();
867 if (contact.showInContactList() && contact.match(this, needle)
868 && (!this.mHideOfflineContacts
869 || (needle != null && !needle.trim().isEmpty())
870 || s.compareTo(Presence.Status.OFFLINE) < 0)) {
871 this.contacts.add(contact);
872 }
873 }
874 }
875 }
876 Collections.sort(this.contacts);
877 mContactsAdapter.notifyDataSetChanged();
878 }
879
880 private static boolean isSingleAccountActive(final List<Account> accounts) {
881 int i = 0;
882 for(Account account : accounts) {
883 if (account.getStatus() != Account.State.DISABLED) {
884 ++i;
885 }
886 }
887 return i == 1;
888 }
889
890 protected void filterConferences(String needle) {
891 this.conferences.clear();
892 for (Account account : xmppConnectionService.getAccounts()) {
893 if (account.getStatus() != Account.State.DISABLED) {
894 for (Bookmark bookmark : account.getBookmarks()) {
895 if (bookmark.match(this, needle)) {
896 this.conferences.add(bookmark);
897 }
898 }
899 }
900 }
901 Collections.sort(this.conferences);
902 mConferenceAdapter.notifyDataSetChanged();
903 }
904
905 private void onTabChanged() {
906 @DrawableRes final int fabDrawable;
907 if (binding.startConversationViewPager.getCurrentItem() == 0) {
908 fabDrawable = R.drawable.ic_person_add_white_24dp;
909 } else {
910 fabDrawable = R.drawable.ic_group_add_white_24dp;
911 }
912 binding.fab.setImageResource(fabDrawable);
913 invalidateOptionsMenu();
914 }
915
916 @Override
917 public void OnUpdateBlocklist(final Status status) {
918 refreshUi();
919 }
920
921 @Override
922 protected void refreshUiReal() {
923 if (mSearchEditText != null) {
924 filter(mSearchEditText.getText().toString());
925 }
926 configureHomeButton();
927 }
928
929 @Override
930 public void onBackPressed() {
931 navigateBack();
932 }
933
934 private void navigateBack() {
935 if (!createdByViewIntent && xmppConnectionService != null && !xmppConnectionService.isConversationsListEmpty(null)) {
936 Intent intent = new Intent(this, ConversationsActivity.class);
937 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
938 startActivity(intent);
939 }
940 finish();
941 }
942
943 @Override
944 public void onCreateDialogPositiveClick(Spinner spinner, String name) {
945 if (!xmppConnectionServiceBound) {
946 return;
947 }
948 final Account account = getSelectedAccount(spinner);
949 if (account == null) {
950 return;
951 }
952 Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class);
953 intent.putExtra(ChooseContactActivity.EXTRA_SHOW_ENTER_JID, false);
954 intent.putExtra(ChooseContactActivity.EXTRA_SELECT_MULTIPLE, true);
955 intent.putExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME, name.trim());
956 intent.putExtra(ChooseContactActivity.EXTRA_ACCOUNT, account.getJid().asBareJid().toString());
957 intent.putExtra(ChooseContactActivity.EXTRA_TITLE_RES_ID, R.string.choose_participants);
958 startActivityForResult(intent, REQUEST_CREATE_CONFERENCE);
959 }
960
961 @Override
962 public void onJoinDialogPositiveClick(Dialog dialog, Spinner spinner, AutoCompleteTextView jid, boolean isBookmarkChecked) {
963 if (!xmppConnectionServiceBound) {
964 return;
965 }
966 final Account account = getSelectedAccount(spinner);
967 if (account == null) {
968 return;
969 }
970 final Jid conferenceJid;
971 try {
972 conferenceJid = Jid.of(jid.getText().toString());
973 } catch (final IllegalArgumentException e) {
974 jid.setError(getString(R.string.invalid_jid));
975 return;
976 }
977
978 if (isBookmarkChecked) {
979 if (account.hasBookmarkFor(conferenceJid)) {
980 jid.setError(getString(R.string.bookmark_already_exists));
981 } else {
982 final Bookmark bookmark = new Bookmark(account, conferenceJid.asBareJid());
983 bookmark.setAutojoin(getBooleanPreference("autojoin", R.bool.autojoin));
984 String nick = conferenceJid.getResource();
985 if (nick != null && !nick.isEmpty()) {
986 bookmark.setNick(nick);
987 }
988 account.getBookmarks().add(bookmark);
989 xmppConnectionService.pushBookmarks(account);
990 final Conversation conversation = xmppConnectionService
991 .findOrCreateConversation(account, conferenceJid, true, true, true);
992 bookmark.setConversation(conversation);
993 dialog.dismiss();
994 switchToConversation(conversation);
995 }
996 } else {
997 final Conversation conversation = xmppConnectionService
998 .findOrCreateConversation(account, conferenceJid, true, true, true);
999 dialog.dismiss();
1000 switchToConversation(conversation);
1001 }
1002 }
1003
1004 @Override
1005 public void onConversationUpdate() {
1006 refreshUi();
1007 }
1008
1009 public static class MyListFragment extends ListFragment {
1010 private AdapterView.OnItemClickListener mOnItemClickListener;
1011 private int mResContextMenu;
1012
1013 public void setContextMenu(final int res) {
1014 this.mResContextMenu = res;
1015 }
1016
1017 @Override
1018 public void onListItemClick(final ListView l, final View v, final int position, final long id) {
1019 if (mOnItemClickListener != null) {
1020 mOnItemClickListener.onItemClick(l, v, position, id);
1021 }
1022 }
1023
1024 public void setOnListItemClickListener(AdapterView.OnItemClickListener l) {
1025 this.mOnItemClickListener = l;
1026 }
1027
1028 @Override
1029 public void onViewCreated(@NonNull final View view, final Bundle savedInstanceState) {
1030 super.onViewCreated(view, savedInstanceState);
1031 registerForContextMenu(getListView());
1032 getListView().setFastScrollEnabled(true);
1033 getListView().setDivider(null);
1034 getListView().setDividerHeight(0);
1035 }
1036
1037 @Override
1038 public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) {
1039 super.onCreateContextMenu(menu, v, menuInfo);
1040 final StartConversationActivity activity = (StartConversationActivity) getActivity();
1041 if (activity == null) {
1042 return;
1043 }
1044 activity.getMenuInflater().inflate(mResContextMenu, menu);
1045 final AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1046 if (mResContextMenu == R.menu.conference_context) {
1047 activity.conference_context_id = acmi.position;
1048 } else if (mResContextMenu == R.menu.contact_context) {
1049 activity.contact_context_id = acmi.position;
1050 final Contact contact = (Contact) activity.contacts.get(acmi.position);
1051 final MenuItem blockUnblockItem = menu.findItem(R.id.context_contact_block_unblock);
1052 final MenuItem showContactDetailsItem = menu.findItem(R.id.context_contact_details);
1053 final MenuItem deleteContactMenuItem = menu.findItem(R.id.context_delete_contact);
1054 if (contact.isSelf()) {
1055 showContactDetailsItem.setVisible(false);
1056 }
1057 deleteContactMenuItem.setVisible(contact.showInRoster());
1058 XmppConnection xmpp = contact.getAccount().getXmppConnection();
1059 if (xmpp != null && xmpp.getFeatures().blocking() && !contact.isSelf()) {
1060 if (contact.isBlocked()) {
1061 blockUnblockItem.setTitle(R.string.unblock_contact);
1062 } else {
1063 blockUnblockItem.setTitle(R.string.block_contact);
1064 }
1065 } else {
1066 blockUnblockItem.setVisible(false);
1067 }
1068 }
1069 }
1070
1071 @Override
1072 public boolean onContextItemSelected(final MenuItem item) {
1073 StartConversationActivity activity = (StartConversationActivity) getActivity();
1074 if (activity == null) {
1075 return true;
1076 }
1077 switch (item.getItemId()) {
1078 case R.id.context_contact_details:
1079 activity.openDetailsForContact();
1080 break;
1081 case R.id.context_show_qr:
1082 activity.showQrForContact();
1083 break;
1084 case R.id.context_contact_block_unblock:
1085 activity.toggleContactBlock();
1086 break;
1087 case R.id.context_delete_contact:
1088 activity.deleteContact();
1089 break;
1090 case R.id.context_join_conference:
1091 activity.openConversationForBookmark();
1092 break;
1093 case R.id.context_share_uri:
1094 activity.shareBookmarkUri();
1095 break;
1096 case R.id.context_delete_conference:
1097 activity.deleteConference();
1098 }
1099 return true;
1100 }
1101 }
1102
1103 public class ListPagerAdapter extends PagerAdapter {
1104 FragmentManager fragmentManager;
1105 MyListFragment[] fragments;
1106
1107 ListPagerAdapter(FragmentManager fm) {
1108 fragmentManager = fm;
1109 fragments = new MyListFragment[2];
1110 }
1111
1112 public void requestFocus(int pos) {
1113 if (fragments.length > pos) {
1114 fragments[pos].getListView().requestFocus();
1115 }
1116 }
1117
1118 @Override
1119 public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
1120 FragmentTransaction trans = fragmentManager.beginTransaction();
1121 trans.remove(fragments[position]);
1122 trans.commit();
1123 fragments[position] = null;
1124 }
1125
1126 @NonNull
1127 @Override
1128 public Fragment instantiateItem(@NonNull ViewGroup container, int position) {
1129 Fragment fragment = getItem(position);
1130 FragmentTransaction trans = fragmentManager.beginTransaction();
1131 trans.add(container.getId(), fragment, "fragment:" + position);
1132 trans.commit();
1133 return fragment;
1134 }
1135
1136 @Override
1137 public int getCount() {
1138 return fragments.length;
1139 }
1140
1141 @Override
1142 public boolean isViewFromObject(@NonNull View view, @NonNull Object fragment) {
1143 return ((Fragment) fragment).getView() == view;
1144 }
1145
1146 @Nullable
1147 @Override
1148 public CharSequence getPageTitle(int position) {
1149 switch (position) {
1150 case 0:
1151 return getResources().getString(R.string.contacts);
1152 case 1:
1153 return getResources().getString(R.string.conferences);
1154 default:
1155 return super.getPageTitle(position);
1156 }
1157 }
1158
1159 Fragment getItem(int position) {
1160 if (fragments[position] == null) {
1161 final MyListFragment listFragment = new MyListFragment();
1162 if (position == 1) {
1163 listFragment.setListAdapter(mConferenceAdapter);
1164 listFragment.setContextMenu(R.menu.conference_context);
1165 listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForBookmark(p));
1166 } else {
1167
1168 listFragment.setListAdapter(mContactsAdapter);
1169 listFragment.setContextMenu(R.menu.contact_context);
1170 listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForContact(p));
1171 }
1172 fragments[position] = listFragment;
1173 }
1174 return fragments[position];
1175 }
1176 }
1177
1178 public static void addInviteUri(Intent to, Intent from) {
1179 if (from != null && from.hasExtra(EXTRA_INVITE_URI)) {
1180 to.putExtra(EXTRA_INVITE_URI, from.getStringExtra(EXTRA_INVITE_URI));
1181 }
1182 }
1183
1184 private class Invite extends XmppUri {
1185
1186 public String account;
1187
1188 public Invite(final Uri uri) {
1189 super(uri);
1190 }
1191
1192 public Invite(final String uri) {
1193 super(uri);
1194 }
1195
1196 public Invite(Uri uri, boolean safeSource) {
1197 super(uri, safeSource);
1198 }
1199
1200 boolean invite() {
1201 if (!isJidValid()) {
1202 Toast.makeText(StartConversationActivity.this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
1203 return false;
1204 }
1205 if (getJid() != null) {
1206 return handleJid(this);
1207 }
1208 return false;
1209 }
1210 }
1211}