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.Arrays;
53import java.util.Collections;
54import java.util.List;
55import java.util.concurrent.atomic.AtomicBoolean;
56
57import eu.siacs.conversations.Config;
58import eu.siacs.conversations.R;
59import eu.siacs.conversations.databinding.ActivityStartConversationBinding;
60import eu.siacs.conversations.entities.Account;
61import eu.siacs.conversations.entities.Bookmark;
62import eu.siacs.conversations.entities.Contact;
63import eu.siacs.conversations.entities.Conversation;
64import eu.siacs.conversations.entities.ListItem;
65import eu.siacs.conversations.entities.Presence;
66import eu.siacs.conversations.services.QuickConversationsService;
67import eu.siacs.conversations.services.XmppConnectionService;
68import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
69import eu.siacs.conversations.ui.adapter.ListItemAdapter;
70import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
71import eu.siacs.conversations.ui.service.EmojiService;
72import eu.siacs.conversations.ui.util.JidDialog;
73import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
74import eu.siacs.conversations.ui.util.PendingItem;
75import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
76import eu.siacs.conversations.utils.AccountUtils;
77import eu.siacs.conversations.utils.XmppUri;
78import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
79import eu.siacs.conversations.xmpp.XmppConnection;
80import rocks.xmpp.addr.Jid;
81
82public class StartConversationActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, CreateConferenceDialog.CreateConferenceDialogListener, JoinConferenceDialog.JoinConferenceDialogListener {
83
84 public static final String EXTRA_INVITE_URI = "eu.siacs.conversations.invite_uri";
85
86 private final int REQUEST_SYNC_CONTACTS = 0x28cf;
87 private final int REQUEST_CREATE_CONFERENCE = 0x39da;
88 private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
89 private final PendingItem<String> mInitialSearchValue = new PendingItem<>();
90 private final AtomicBoolean oneShotKeyboardSuppress = new AtomicBoolean();
91 public int conference_context_id;
92 public int contact_context_id;
93 private ListPagerAdapter mListPagerAdapter;
94 private List<ListItem> contacts = new ArrayList<>();
95 private ListItemAdapter mContactsAdapter;
96 private List<ListItem> conferences = new ArrayList<>();
97 private ListItemAdapter mConferenceAdapter;
98 private List<String> mActivatedAccounts = new ArrayList<>();
99 private EditText mSearchEditText;
100 private AtomicBoolean mRequestedContactsPermission = new AtomicBoolean(false);
101 private boolean mHideOfflineContacts = false;
102 private boolean createdByViewIntent = false;
103 private MenuItem.OnActionExpandListener mOnActionExpandListener = new MenuItem.OnActionExpandListener() {
104
105 @Override
106 public boolean onMenuItemActionExpand(MenuItem item) {
107 mSearchEditText.post(() -> {
108 updateSearchViewHint();
109 mSearchEditText.requestFocus();
110 if (oneShotKeyboardSuppress.compareAndSet(true, false)) {
111 return;
112 }
113 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
114 if (imm != null) {
115 imm.showSoftInput(mSearchEditText, InputMethodManager.SHOW_IMPLICIT);
116 }
117 });
118
119 return true;
120 }
121
122 @Override
123 public boolean onMenuItemActionCollapse(MenuItem item) {
124 SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this);
125 mSearchEditText.setText("");
126 filter(null);
127 return true;
128 }
129 };
130 private TextWatcher mSearchTextWatcher = new TextWatcher() {
131
132 @Override
133 public void afterTextChanged(Editable editable) {
134 filter(editable.toString());
135 }
136
137 @Override
138 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
139 }
140
141 @Override
142 public void onTextChanged(CharSequence s, int start, int before, int count) {
143 }
144 };
145 private MenuItem mMenuSearchView;
146 private ListItemAdapter.OnTagClickedListener mOnTagClickedListener = new ListItemAdapter.OnTagClickedListener() {
147 @Override
148 public void onTagClicked(String tag) {
149 if (mMenuSearchView != null) {
150 mMenuSearchView.expandActionView();
151 mSearchEditText.setText("");
152 mSearchEditText.append(tag);
153 filter(tag);
154 }
155 }
156 };
157 private Pair<Integer, Intent> mPostponedActivityResult;
158 private Toast mToast;
159 private UiCallback<Conversation> mAdhocConferenceCallback = new UiCallback<Conversation>() {
160 @Override
161 public void success(final Conversation conversation) {
162 runOnUiThread(() -> {
163 hideToast();
164 switchToConversation(conversation);
165 });
166 }
167
168 @Override
169 public void error(final int errorCode, Conversation object) {
170 runOnUiThread(() -> replaceToast(getString(errorCode)));
171 }
172
173 @Override
174 public void userInputRequried(PendingIntent pi, Conversation object) {
175
176 }
177 };
178 private ActivityStartConversationBinding binding;
179 private TextView.OnEditorActionListener mSearchDone = new TextView.OnEditorActionListener() {
180 @Override
181 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
182 int pos = binding.startConversationViewPager.getCurrentItem();
183 if (pos == 0) {
184 if (contacts.size() == 1) {
185 openConversationForContact((Contact) contacts.get(0));
186 return true;
187 } else if (contacts.size() == 0 && conferences.size() == 1) {
188 openConversationsForBookmark((Bookmark) conferences.get(0));
189 return true;
190 }
191 } else {
192 if (conferences.size() == 1) {
193 openConversationsForBookmark((Bookmark) conferences.get(0));
194 return true;
195 } else if (conferences.size() == 0 && contacts.size() == 1) {
196 openConversationForContact((Contact) contacts.get(0));
197 return true;
198 }
199 }
200 SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this);
201 mListPagerAdapter.requestFocus(pos);
202 return true;
203 }
204 };
205 private ViewPager.SimpleOnPageChangeListener mOnPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
206 @Override
207 public void onPageSelected(int position) {
208 onTabChanged();
209 }
210 };
211
212 public static void populateAccountSpinner(Context context, List<String> accounts, Spinner spinner) {
213 if (accounts.size() > 0) {
214 ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.simple_list_item, accounts);
215 adapter.setDropDownViewResource(R.layout.simple_list_item);
216 spinner.setAdapter(adapter);
217 spinner.setEnabled(true);
218 } else {
219 ArrayAdapter<String> adapter = new ArrayAdapter<>(context,
220 R.layout.simple_list_item,
221 Collections.singletonList(context.getString(R.string.no_accounts)));
222 adapter.setDropDownViewResource(R.layout.simple_list_item);
223 spinner.setAdapter(adapter);
224 spinner.setEnabled(false);
225 }
226 }
227
228 public static void launch(Context context) {
229 final Intent intent = new Intent(context, StartConversationActivity.class);
230 context.startActivity(intent);
231 }
232
233 private static Intent createLauncherIntent(Context context) {
234 final Intent intent = new Intent(context, StartConversationActivity.class);
235 intent.setAction(Intent.ACTION_MAIN);
236 intent.addCategory(Intent.CATEGORY_LAUNCHER);
237 return intent;
238 }
239
240 private static boolean isViewIntent(final Intent i) {
241 return i != null && (Intent.ACTION_VIEW.equals(i.getAction()) || Intent.ACTION_SENDTO.equals(i.getAction()) || i.hasExtra(EXTRA_INVITE_URI));
242 }
243
244 protected void hideToast() {
245 if (mToast != null) {
246 mToast.cancel();
247 }
248 }
249
250 protected void replaceToast(String msg) {
251 hideToast();
252 mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
253 mToast.show();
254 }
255
256 @Override
257 public void onRosterUpdate() {
258 this.refreshUi();
259 }
260
261 @Override
262 public void onCreate(Bundle savedInstanceState) {
263 super.onCreate(savedInstanceState);
264 new EmojiService(this).init();
265 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_start_conversation);
266 Toolbar toolbar = (Toolbar) binding.toolbar;
267 setSupportActionBar(toolbar);
268 configureActionBar(getSupportActionBar());
269 this.binding.fab.setOnClickListener((v) -> {
270 if (binding.startConversationViewPager.getCurrentItem() == 0) {
271 String searchString = mSearchEditText != null ? mSearchEditText.getText().toString() : null;
272 if (searchString != null && !searchString.trim().isEmpty()) {
273 try {
274 Jid jid = Jid.of(searchString);
275 if (jid.getLocal() != null && jid.isBareJid() && jid.getDomain().contains(".")) {
276 showCreateContactDialog(jid.toString(), null);
277 return;
278 }
279 } catch (IllegalArgumentException ignored) {
280 //ignore and fall through
281 }
282 }
283 showCreateContactDialog(null, null);
284 } else {
285 showCreateConferenceDialog();
286 }
287 });
288 binding.tabLayout.setupWithViewPager(binding.startConversationViewPager);
289 binding.startConversationViewPager.addOnPageChangeListener(mOnPageChangeListener);
290 mListPagerAdapter = new ListPagerAdapter(getSupportFragmentManager());
291 binding.startConversationViewPager.setAdapter(mListPagerAdapter);
292
293 mConferenceAdapter = new ListItemAdapter(this, conferences);
294 mContactsAdapter = new ListItemAdapter(this, contacts);
295 mContactsAdapter.setOnTagClickedListener(this.mOnTagClickedListener);
296
297 final SharedPreferences preferences = getPreferences();
298
299 this.mHideOfflineContacts = !QuickConversationsService.isQuicksy() && preferences.getBoolean("hide_offline", false);
300
301 final boolean startSearching = preferences.getBoolean("start_searching",getResources().getBoolean(R.bool.start_searching));
302
303 final Intent intent;
304 if (savedInstanceState == null) {
305 intent = getIntent();
306 } else {
307 createdByViewIntent = savedInstanceState.getBoolean("created_by_view_intent", false);
308 final String search = savedInstanceState.getString("search");
309 if (search != null) {
310 mInitialSearchValue.push(search);
311 }
312 intent = savedInstanceState.getParcelable("intent");
313 }
314
315 if (isViewIntent(intent)) {
316 pendingViewIntent.push(intent);
317 createdByViewIntent = true;
318 setIntent(createLauncherIntent(this));
319 } else if (startSearching && mInitialSearchValue.peek() == null) {
320 mInitialSearchValue.push("");
321 }
322 }
323
324 @Override
325 public void onSaveInstanceState(Bundle savedInstanceState) {
326 Intent pendingIntent = pendingViewIntent.peek();
327 savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
328 savedInstanceState.putBoolean("created_by_view_intent",createdByViewIntent);
329 if (mMenuSearchView != null && mMenuSearchView.isActionViewExpanded()) {
330 savedInstanceState.putString("search", mSearchEditText != null ? mSearchEditText.getText().toString() : null);
331 }
332 super.onSaveInstanceState(savedInstanceState);
333 }
334
335 @Override
336 public void onStart() {
337 super.onStart();
338 final int theme = findTheme();
339 if (this.mTheme != theme) {
340 recreate();
341 } else {
342 if (pendingViewIntent.peek() == null) {
343 askForContactsPermissions();
344 }
345 }
346 mConferenceAdapter.refreshSettings();
347 mContactsAdapter.refreshSettings();
348 }
349
350 @Override
351 public void onNewIntent(final Intent intent) {
352 if (xmppConnectionServiceBound) {
353 processViewIntent(intent);
354 } else {
355 pendingViewIntent.push(intent);
356 }
357 setIntent(createLauncherIntent(this));
358 }
359
360 protected void openConversationForContact(int position) {
361 Contact contact = (Contact) contacts.get(position);
362 openConversationForContact(contact);
363 }
364
365 protected void openConversationForContact(Contact contact) {
366 Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
367 SoftKeyboardUtils.hideSoftKeyboard(this);
368 switchToConversation(conversation);
369 }
370
371 protected void openConversationForBookmark() {
372 openConversationForBookmark(conference_context_id);
373 }
374
375 protected void openConversationForBookmark(int position) {
376 Bookmark bookmark = (Bookmark) conferences.get(position);
377 openConversationsForBookmark(bookmark);
378 }
379
380 protected void shareBookmarkUri() {
381 shareBookmarkUri(conference_context_id);
382 }
383
384 protected void shareBookmarkUri(int position) {
385 Bookmark bookmark = (Bookmark) conferences.get(position);
386 Intent shareIntent = new Intent();
387 shareIntent.setAction(Intent.ACTION_SEND);
388 shareIntent.putExtra(Intent.EXTRA_TEXT, "xmpp:" + bookmark.getJid().asBareJid().toEscapedString() + "?join");
389 shareIntent.setType("text/plain");
390 try {
391 startActivity(Intent.createChooser(shareIntent, getText(R.string.share_uri_with)));
392 } catch (ActivityNotFoundException e) {
393 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
394 }
395 }
396
397 protected void openConversationsForBookmark(Bookmark bookmark) {
398 Jid jid = bookmark.getJid();
399 if (jid == null) {
400 Toast.makeText(this, R.string.invalid_jid, Toast.LENGTH_SHORT).show();
401 return;
402 }
403 Conversation conversation = xmppConnectionService.findOrCreateConversation(bookmark.getAccount(), jid, true, true, true);
404 bookmark.setConversation(conversation);
405 if (!bookmark.autojoin() && getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin))) {
406 bookmark.setAutojoin(true);
407 xmppConnectionService.pushBookmarks(bookmark.getAccount());
408 }
409 SoftKeyboardUtils.hideSoftKeyboard(this);
410 switchToConversation(conversation);
411 }
412
413 protected void openDetailsForContact() {
414 int position = contact_context_id;
415 Contact contact = (Contact) contacts.get(position);
416 switchToContactDetails(contact);
417 }
418
419 protected void showQrForContact() {
420 int position = contact_context_id;
421 Contact contact = (Contact) contacts.get(position);
422 showQrCode("xmpp:"+contact.getJid().asBareJid().toEscapedString());
423 }
424
425 protected void toggleContactBlock() {
426 final int position = contact_context_id;
427 BlockContactDialog.show(this, (Contact) contacts.get(position));
428 }
429
430 protected void deleteContact() {
431 final int position = contact_context_id;
432 final Contact contact = (Contact) contacts.get(position);
433 final AlertDialog.Builder builder = new AlertDialog.Builder(this);
434 builder.setNegativeButton(R.string.cancel, null);
435 builder.setTitle(R.string.action_delete_contact);
436 builder.setMessage(JidDialog.style(this, R.string.remove_contact_text, contact.getJid().toEscapedString()));
437 builder.setPositiveButton(R.string.delete, (dialog, which) -> {
438 xmppConnectionService.deleteContactOnServer(contact);
439 filter(mSearchEditText.getText().toString());
440 });
441 builder.create().show();
442 }
443
444 protected void deleteConference() {
445 int position = conference_context_id;
446 final Bookmark bookmark = (Bookmark) conferences.get(position);
447
448 AlertDialog.Builder builder = new AlertDialog.Builder(this);
449 builder.setNegativeButton(R.string.cancel, null);
450 builder.setTitle(R.string.delete_bookmark);
451 builder.setMessage(JidDialog.style(this, R.string.remove_bookmark_text, bookmark.getJid().toEscapedString()));
452 builder.setPositiveButton(R.string.delete, (dialog, which) -> {
453 bookmark.setConversation(null);
454 Account account = bookmark.getAccount();
455 account.getBookmarks().remove(bookmark);
456 xmppConnectionService.pushBookmarks(account);
457 filter(mSearchEditText.getText().toString());
458 });
459 builder.create().show();
460
461 }
462
463 @SuppressLint("InflateParams")
464 protected void showCreateContactDialog(final String prefilledJid, final Invite invite) {
465 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
466 Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
467 if (prev != null) {
468 ft.remove(prev);
469 }
470 ft.addToBackStack(null);
471 EnterJidDialog dialog = EnterJidDialog.newInstance(
472 mActivatedAccounts,
473 getString(R.string.dialog_title_create_contact),
474 getString(R.string.create),
475 prefilledJid,
476 null,
477 invite == null || !invite.hasFingerprints()
478 );
479
480 dialog.setOnEnterJidDialogPositiveListener((accountJid, contactJid) -> {
481 if (!xmppConnectionServiceBound) {
482 return false;
483 }
484
485 final Account account = xmppConnectionService.findAccountByJid(accountJid);
486 if (account == null) {
487 return true;
488 }
489
490 final Contact contact = account.getRoster().getContact(contactJid);
491 if (invite != null && invite.getName() != null) {
492 contact.setServerName(invite.getName());
493 }
494 if (contact.isSelf()) {
495 switchToConversation(contact);
496 return true;
497 } else if (contact.showInRoster()) {
498 throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists));
499 } else {
500 xmppConnectionService.createContact(contact, true);
501 if (invite != null && invite.hasFingerprints()) {
502 xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
503 }
504 switchToConversationDoNotAppend(contact, invite == null ? null : invite.getBody());
505 return true;
506 }
507 });
508 dialog.show(ft, FRAGMENT_TAG_DIALOG);
509 }
510
511 @SuppressLint("InflateParams")
512 protected void showJoinConferenceDialog(final String prefilledJid) {
513 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
514 Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
515 if (prev != null) {
516 ft.remove(prev);
517 }
518 ft.addToBackStack(null);
519 JoinConferenceDialog joinConferenceFragment = JoinConferenceDialog.newInstance(prefilledJid, mActivatedAccounts);
520 joinConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG);
521 }
522
523 private void showCreateConferenceDialog() {
524 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
525 Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
526 if (prev != null) {
527 ft.remove(prev);
528 }
529 ft.addToBackStack(null);
530 CreateConferenceDialog createConferenceFragment = CreateConferenceDialog.newInstance(mActivatedAccounts);
531 createConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG);
532 }
533
534 private Account getSelectedAccount(Spinner spinner) {
535 if (!spinner.isEnabled()) {
536 return null;
537 }
538 Jid jid;
539 try {
540 if (Config.DOMAIN_LOCK != null) {
541 jid = Jid.of((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null);
542 } else {
543 jid = Jid.of((String) spinner.getSelectedItem());
544 }
545 } catch (final IllegalArgumentException e) {
546 return null;
547 }
548 return xmppConnectionService.findAccountByJid(jid);
549 }
550
551 protected void switchToConversation(Contact contact) {
552 Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
553 switchToConversation(conversation);
554 }
555
556 protected void switchToConversationDoNotAppend(Contact contact, String body) {
557 Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
558 switchToConversationDoNotAppend(conversation, body);
559 }
560
561 @Override
562 public void invalidateOptionsMenu() {
563 boolean isExpanded = mMenuSearchView != null && mMenuSearchView.isActionViewExpanded();
564 String text = mSearchEditText != null ? mSearchEditText.getText().toString() : "";
565 if (isExpanded) {
566 mInitialSearchValue.push(text);
567 oneShotKeyboardSuppress.set(true);
568 }
569 super.invalidateOptionsMenu();
570 }
571
572 private void updateSearchViewHint() {
573 if (binding == null || mSearchEditText == null) {
574 return;
575 }
576 if (binding.startConversationViewPager.getCurrentItem() == 0) {
577 mSearchEditText.setHint(R.string.search_contacts);
578 } else {
579 mSearchEditText.setHint(R.string.search_groups);
580 }
581 }
582
583 @Override
584 public boolean onCreateOptionsMenu(Menu menu) {
585 getMenuInflater().inflate(R.menu.start_conversation, menu);
586 AccountUtils.showHideMenuItems(menu);
587 MenuItem menuHideOffline = menu.findItem(R.id.action_hide_offline);
588 MenuItem joinGroupChat = menu.findItem(R.id.action_join_conference);
589 MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
590 joinGroupChat.setVisible(binding.startConversationViewPager.getCurrentItem() == 1);
591 qrCodeScanMenuItem.setVisible(isCameraFeatureAvailable());
592 if (QuickConversationsService.isQuicksy()) {
593 menuHideOffline.setVisible(false);
594 } else {
595 menuHideOffline.setVisible(true);
596 menuHideOffline.setChecked(this.mHideOfflineContacts);
597 }
598 mMenuSearchView = menu.findItem(R.id.action_search);
599 mMenuSearchView.setOnActionExpandListener(mOnActionExpandListener);
600 View mSearchView = mMenuSearchView.getActionView();
601 mSearchEditText = mSearchView.findViewById(R.id.search_field);
602 mSearchEditText.addTextChangedListener(mSearchTextWatcher);
603 mSearchEditText.setOnEditorActionListener(mSearchDone);
604 String initialSearchValue = mInitialSearchValue.pop();
605 if (initialSearchValue != null) {
606 mMenuSearchView.expandActionView();
607 mSearchEditText.append(initialSearchValue);
608 filter(initialSearchValue);
609 }
610 updateSearchViewHint();
611 return super.onCreateOptionsMenu(menu);
612 }
613
614 @Override
615 public boolean onOptionsItemSelected(MenuItem item) {
616 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
617 return false;
618 }
619 switch (item.getItemId()) {
620 case android.R.id.home:
621 navigateBack();
622 return true;
623 case R.id.action_join_conference:
624 showJoinConferenceDialog(null);
625 return true;
626 case R.id.action_scan_qr_code:
627 UriHandlerActivity.scan(this);
628 return true;
629 case R.id.action_hide_offline:
630 mHideOfflineContacts = !item.isChecked();
631 getPreferences().edit().putBoolean("hide_offline", mHideOfflineContacts).apply();
632 if (mSearchEditText != null) {
633 filter(mSearchEditText.getText().toString());
634 }
635 invalidateOptionsMenu();
636 }
637 return super.onOptionsItemSelected(item);
638 }
639
640 @Override
641 public boolean onKeyUp(int keyCode, KeyEvent event) {
642 if (keyCode == KeyEvent.KEYCODE_SEARCH && !event.isLongPress()) {
643 openSearch();
644 return true;
645 }
646 int c = event.getUnicodeChar();
647 if (c > 32) {
648 if (mSearchEditText != null && !mSearchEditText.isFocused()) {
649 openSearch();
650 mSearchEditText.append(Character.toString((char) c));
651 return true;
652 }
653 }
654 return super.onKeyUp(keyCode, event);
655 }
656
657 private void openSearch() {
658 if (mMenuSearchView != null) {
659 mMenuSearchView.expandActionView();
660 }
661 }
662
663 @Override
664 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
665 if (resultCode == RESULT_OK) {
666 if (xmppConnectionServiceBound) {
667 this.mPostponedActivityResult = null;
668 if (requestCode == REQUEST_CREATE_CONFERENCE) {
669 Account account = extractAccount(intent);
670 final String name = intent.getStringExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME);
671 final List<Jid> jids = ChooseContactActivity.extractJabberIds(intent);
672 if (account != null && jids.size() > 0) {
673 if (xmppConnectionService.createAdhocConference(account, name, jids, mAdhocConferenceCallback)) {
674 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
675 mToast.show();
676 }
677 }
678 }
679 } else {
680 this.mPostponedActivityResult = new Pair<>(requestCode, intent);
681 }
682 }
683 super.onActivityResult(requestCode, requestCode, intent);
684 }
685
686 private void askForContactsPermissions() {
687 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
688 if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
689 if (mRequestedContactsPermission.compareAndSet(false, true)) {
690 if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
691 AlertDialog.Builder builder = new AlertDialog.Builder(this);
692 builder.setTitle(R.string.sync_with_contacts);
693 builder.setMessage(R.string.sync_with_contacts_long);
694 builder.setPositiveButton(R.string.next, (dialog, which) -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS));
695 builder.setOnDismissListener(dialog -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS));
696 builder.create().show();
697 } else {
698 requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
699 }
700 }
701 }
702 }
703 }
704
705 @Override
706 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
707 if (grantResults.length > 0)
708 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
709 ScanActivity.onRequestPermissionResult(this, requestCode, grantResults);
710 if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
711 xmppConnectionService.loadPhoneContacts();
712 xmppConnectionService.startContactObserver();
713 }
714 }
715 }
716
717 private void configureHomeButton() {
718 final ActionBar actionBar = getSupportActionBar();
719 if (actionBar == null) {
720 return;
721 }
722 boolean openConversations = !createdByViewIntent && !xmppConnectionService.isConversationsListEmpty(null);
723 actionBar.setDisplayHomeAsUpEnabled(openConversations);
724 actionBar.setDisplayHomeAsUpEnabled(openConversations);
725
726 }
727
728 @Override
729 protected void onBackendConnected() {
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}