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 final boolean singleAccountActive = isSingleAccountActive(accounts);
864 for (Account account : accounts) {
865 if (account.getStatus() != Account.State.DISABLED) {
866 for (Contact contact : account.getRoster().getContacts()) {
867 Presence.Status s = contact.getShownStatus();
868 if ((contact.showInRoster() || (singleAccountActive && contact.showInPhoneBook())) && contact.match(this, needle)
869 && (!this.mHideOfflineContacts
870 || (needle != null && !needle.trim().isEmpty())
871 || s.compareTo(Presence.Status.OFFLINE) < 0)) {
872 this.contacts.add(contact);
873 }
874 }
875 }
876 }
877 Collections.sort(this.contacts);
878 mContactsAdapter.notifyDataSetChanged();
879 }
880
881 private static boolean isSingleAccountActive(final List<Account> accounts) {
882 int i = 0;
883 for(Account account : accounts) {
884 if (account.getStatus() != Account.State.DISABLED) {
885 ++i;
886 }
887 }
888 return i == 1;
889 }
890
891 protected void filterConferences(String needle) {
892 this.conferences.clear();
893 for (Account account : xmppConnectionService.getAccounts()) {
894 if (account.getStatus() != Account.State.DISABLED) {
895 for (Bookmark bookmark : account.getBookmarks()) {
896 if (bookmark.match(this, needle)) {
897 this.conferences.add(bookmark);
898 }
899 }
900 }
901 }
902 Collections.sort(this.conferences);
903 mConferenceAdapter.notifyDataSetChanged();
904 }
905
906 private void onTabChanged() {
907 @DrawableRes final int fabDrawable;
908 if (binding.startConversationViewPager.getCurrentItem() == 0) {
909 fabDrawable = R.drawable.ic_person_add_white_24dp;
910 } else {
911 fabDrawable = R.drawable.ic_group_add_white_24dp;
912 }
913 binding.fab.setImageResource(fabDrawable);
914 invalidateOptionsMenu();
915 }
916
917 @Override
918 public void OnUpdateBlocklist(final Status status) {
919 refreshUi();
920 }
921
922 @Override
923 protected void refreshUiReal() {
924 if (mSearchEditText != null) {
925 filter(mSearchEditText.getText().toString());
926 }
927 configureHomeButton();
928 }
929
930 @Override
931 public void onBackPressed() {
932 navigateBack();
933 }
934
935 private void navigateBack() {
936 if (!createdByViewIntent && xmppConnectionService != null && !xmppConnectionService.isConversationsListEmpty(null)) {
937 Intent intent = new Intent(this, ConversationsActivity.class);
938 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
939 startActivity(intent);
940 }
941 finish();
942 }
943
944 @Override
945 public void onCreateDialogPositiveClick(Spinner spinner, String name) {
946 if (!xmppConnectionServiceBound) {
947 return;
948 }
949 final Account account = getSelectedAccount(spinner);
950 if (account == null) {
951 return;
952 }
953 Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class);
954 intent.putExtra(ChooseContactActivity.EXTRA_SHOW_ENTER_JID, false);
955 intent.putExtra(ChooseContactActivity.EXTRA_SELECT_MULTIPLE, true);
956 intent.putExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME, name.trim());
957 intent.putExtra(ChooseContactActivity.EXTRA_ACCOUNT, account.getJid().asBareJid().toString());
958 intent.putExtra(ChooseContactActivity.EXTRA_TITLE_RES_ID, R.string.choose_participants);
959 startActivityForResult(intent, REQUEST_CREATE_CONFERENCE);
960 }
961
962 @Override
963 public void onJoinDialogPositiveClick(Dialog dialog, Spinner spinner, AutoCompleteTextView jid, boolean isBookmarkChecked) {
964 if (!xmppConnectionServiceBound) {
965 return;
966 }
967 final Account account = getSelectedAccount(spinner);
968 if (account == null) {
969 return;
970 }
971 final Jid conferenceJid;
972 try {
973 conferenceJid = Jid.of(jid.getText().toString());
974 } catch (final IllegalArgumentException e) {
975 jid.setError(getString(R.string.invalid_jid));
976 return;
977 }
978
979 if (isBookmarkChecked) {
980 if (account.hasBookmarkFor(conferenceJid)) {
981 jid.setError(getString(R.string.bookmark_already_exists));
982 } else {
983 final Bookmark bookmark = new Bookmark(account, conferenceJid.asBareJid());
984 bookmark.setAutojoin(getBooleanPreference("autojoin", R.bool.autojoin));
985 String nick = conferenceJid.getResource();
986 if (nick != null && !nick.isEmpty()) {
987 bookmark.setNick(nick);
988 }
989 account.getBookmarks().add(bookmark);
990 xmppConnectionService.pushBookmarks(account);
991 final Conversation conversation = xmppConnectionService
992 .findOrCreateConversation(account, conferenceJid, true, true, true);
993 bookmark.setConversation(conversation);
994 dialog.dismiss();
995 switchToConversation(conversation);
996 }
997 } else {
998 final Conversation conversation = xmppConnectionService
999 .findOrCreateConversation(account, conferenceJid, true, true, true);
1000 dialog.dismiss();
1001 switchToConversation(conversation);
1002 }
1003 }
1004
1005 @Override
1006 public void onConversationUpdate() {
1007 refreshUi();
1008 }
1009
1010 public static class MyListFragment extends ListFragment {
1011 private AdapterView.OnItemClickListener mOnItemClickListener;
1012 private int mResContextMenu;
1013
1014 public void setContextMenu(final int res) {
1015 this.mResContextMenu = res;
1016 }
1017
1018 @Override
1019 public void onListItemClick(final ListView l, final View v, final int position, final long id) {
1020 if (mOnItemClickListener != null) {
1021 mOnItemClickListener.onItemClick(l, v, position, id);
1022 }
1023 }
1024
1025 public void setOnListItemClickListener(AdapterView.OnItemClickListener l) {
1026 this.mOnItemClickListener = l;
1027 }
1028
1029 @Override
1030 public void onViewCreated(@NonNull final View view, final Bundle savedInstanceState) {
1031 super.onViewCreated(view, savedInstanceState);
1032 registerForContextMenu(getListView());
1033 getListView().setFastScrollEnabled(true);
1034 getListView().setDivider(null);
1035 getListView().setDividerHeight(0);
1036 }
1037
1038 @Override
1039 public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) {
1040 super.onCreateContextMenu(menu, v, menuInfo);
1041 final StartConversationActivity activity = (StartConversationActivity) getActivity();
1042 if (activity == null) {
1043 return;
1044 }
1045 activity.getMenuInflater().inflate(mResContextMenu, menu);
1046 final AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1047 if (mResContextMenu == R.menu.conference_context) {
1048 activity.conference_context_id = acmi.position;
1049 } else if (mResContextMenu == R.menu.contact_context) {
1050 activity.contact_context_id = acmi.position;
1051 final Contact contact = (Contact) activity.contacts.get(acmi.position);
1052 final MenuItem blockUnblockItem = menu.findItem(R.id.context_contact_block_unblock);
1053 final MenuItem showContactDetailsItem = menu.findItem(R.id.context_contact_details);
1054 final MenuItem deleteContactMenuItem = menu.findItem(R.id.context_delete_contact);
1055 if (contact.isSelf()) {
1056 showContactDetailsItem.setVisible(false);
1057 }
1058 deleteContactMenuItem.setVisible(contact.showInRoster());
1059 XmppConnection xmpp = contact.getAccount().getXmppConnection();
1060 if (xmpp != null && xmpp.getFeatures().blocking() && !contact.isSelf()) {
1061 if (contact.isBlocked()) {
1062 blockUnblockItem.setTitle(R.string.unblock_contact);
1063 } else {
1064 blockUnblockItem.setTitle(R.string.block_contact);
1065 }
1066 } else {
1067 blockUnblockItem.setVisible(false);
1068 }
1069 }
1070 }
1071
1072 @Override
1073 public boolean onContextItemSelected(final MenuItem item) {
1074 StartConversationActivity activity = (StartConversationActivity) getActivity();
1075 if (activity == null) {
1076 return true;
1077 }
1078 switch (item.getItemId()) {
1079 case R.id.context_contact_details:
1080 activity.openDetailsForContact();
1081 break;
1082 case R.id.context_show_qr:
1083 activity.showQrForContact();
1084 break;
1085 case R.id.context_contact_block_unblock:
1086 activity.toggleContactBlock();
1087 break;
1088 case R.id.context_delete_contact:
1089 activity.deleteContact();
1090 break;
1091 case R.id.context_join_conference:
1092 activity.openConversationForBookmark();
1093 break;
1094 case R.id.context_share_uri:
1095 activity.shareBookmarkUri();
1096 break;
1097 case R.id.context_delete_conference:
1098 activity.deleteConference();
1099 }
1100 return true;
1101 }
1102 }
1103
1104 public class ListPagerAdapter extends PagerAdapter {
1105 FragmentManager fragmentManager;
1106 MyListFragment[] fragments;
1107
1108 ListPagerAdapter(FragmentManager fm) {
1109 fragmentManager = fm;
1110 fragments = new MyListFragment[2];
1111 }
1112
1113 public void requestFocus(int pos) {
1114 if (fragments.length > pos) {
1115 fragments[pos].getListView().requestFocus();
1116 }
1117 }
1118
1119 @Override
1120 public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
1121 FragmentTransaction trans = fragmentManager.beginTransaction();
1122 trans.remove(fragments[position]);
1123 trans.commit();
1124 fragments[position] = null;
1125 }
1126
1127 @NonNull
1128 @Override
1129 public Fragment instantiateItem(@NonNull ViewGroup container, int position) {
1130 Fragment fragment = getItem(position);
1131 FragmentTransaction trans = fragmentManager.beginTransaction();
1132 trans.add(container.getId(), fragment, "fragment:" + position);
1133 trans.commit();
1134 return fragment;
1135 }
1136
1137 @Override
1138 public int getCount() {
1139 return fragments.length;
1140 }
1141
1142 @Override
1143 public boolean isViewFromObject(@NonNull View view, @NonNull Object fragment) {
1144 return ((Fragment) fragment).getView() == view;
1145 }
1146
1147 @Nullable
1148 @Override
1149 public CharSequence getPageTitle(int position) {
1150 switch (position) {
1151 case 0:
1152 return getResources().getString(R.string.contacts);
1153 case 1:
1154 return getResources().getString(R.string.conferences);
1155 default:
1156 return super.getPageTitle(position);
1157 }
1158 }
1159
1160 Fragment getItem(int position) {
1161 if (fragments[position] == null) {
1162 final MyListFragment listFragment = new MyListFragment();
1163 if (position == 1) {
1164 listFragment.setListAdapter(mConferenceAdapter);
1165 listFragment.setContextMenu(R.menu.conference_context);
1166 listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForBookmark(p));
1167 } else {
1168
1169 listFragment.setListAdapter(mContactsAdapter);
1170 listFragment.setContextMenu(R.menu.contact_context);
1171 listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForContact(p));
1172 }
1173 fragments[position] = listFragment;
1174 }
1175 return fragments[position];
1176 }
1177 }
1178
1179 public static void addInviteUri(Intent to, Intent from) {
1180 if (from != null && from.hasExtra(EXTRA_INVITE_URI)) {
1181 to.putExtra(EXTRA_INVITE_URI, from.getStringExtra(EXTRA_INVITE_URI));
1182 }
1183 }
1184
1185 private class Invite extends XmppUri {
1186
1187 public String account;
1188
1189 public Invite(final Uri uri) {
1190 super(uri);
1191 }
1192
1193 public Invite(final String uri) {
1194 super(uri);
1195 }
1196
1197 public Invite(Uri uri, boolean safeSource) {
1198 super(uri, safeSource);
1199 }
1200
1201 boolean invite() {
1202 if (!isJidValid()) {
1203 Toast.makeText(StartConversationActivity.this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
1204 return false;
1205 }
1206 if (getJid() != null) {
1207 return handleJid(this);
1208 }
1209 return false;
1210 }
1211 }
1212}