1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.content.ActivityNotFoundException;
5import android.content.Context;
6import android.content.DialogInterface;
7import android.content.Intent;
8import android.content.SharedPreferences;
9import android.content.pm.PackageManager;
10import android.graphics.drawable.Drawable;
11import android.content.res.ColorStateList;
12import android.net.Uri;
13import android.os.Build;
14import android.os.Bundle;
15import android.preference.PreferenceManager;
16import android.provider.ContactsContract.CommonDataKinds;
17import android.provider.ContactsContract.Contacts;
18import android.provider.ContactsContract.Intents;
19import android.text.Spannable;
20import android.text.SpannableString;
21import android.text.style.RelativeSizeSpan;
22import android.util.TypedValue;
23import android.view.inputmethod.InputMethodManager;
24import android.view.LayoutInflater;
25import android.view.Menu;
26import android.view.MenuItem;
27import android.view.View;
28import android.view.View.OnClickListener;
29import android.view.ViewGroup;
30import android.widget.ArrayAdapter;
31import android.widget.CompoundButton;
32import android.widget.CompoundButton.OnCheckedChangeListener;
33import android.widget.EditText;
34import android.widget.TextView;
35import android.widget.Toast;
36import androidx.annotation.NonNull;
37import androidx.core.content.ContextCompat;
38import androidx.core.view.ViewCompat;
39import androidx.databinding.DataBindingUtil;
40
41import com.cheogram.android.Util;
42
43import com.google.android.material.color.MaterialColors;
44import com.google.android.material.dialog.MaterialAlertDialogBuilder;
45import com.google.common.collect.ImmutableList;
46import com.google.common.primitives.Ints;
47
48import org.openintents.openpgp.util.OpenPgpUtils;
49
50import java.util.ArrayList;
51import java.util.Collection;
52import java.util.Collections;
53import java.util.Comparator;
54import java.util.List;
55import java.util.Map;
56import java.util.stream.Collectors;
57
58import eu.siacs.conversations.AppSettings;
59import eu.siacs.conversations.Config;
60import eu.siacs.conversations.R;
61import eu.siacs.conversations.crypto.axolotl.AxolotlService;
62import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
63import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
64import eu.siacs.conversations.databinding.ActivityContactDetailsBinding;
65import eu.siacs.conversations.databinding.CommandRowBinding;
66import eu.siacs.conversations.entities.Account;
67import eu.siacs.conversations.entities.Bookmark;
68import eu.siacs.conversations.entities.Contact;
69import eu.siacs.conversations.entities.ListItem;
70import eu.siacs.conversations.entities.Presence;
71import eu.siacs.conversations.services.AbstractQuickConversationsService;
72import eu.siacs.conversations.services.QuickConversationsService;
73import eu.siacs.conversations.services.XmppConnectionService;
74import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
75import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
76import eu.siacs.conversations.ui.adapter.MediaAdapter;
77import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
78import eu.siacs.conversations.ui.text.FixedURLSpan;
79import eu.siacs.conversations.ui.util.Attachment;
80import eu.siacs.conversations.ui.util.AvatarWorkerTask;
81import eu.siacs.conversations.ui.util.GridManager;
82import eu.siacs.conversations.ui.util.JidDialog;
83import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
84import eu.siacs.conversations.ui.util.ShareUtil;
85import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
86import eu.siacs.conversations.utils.AccountUtils;
87import eu.siacs.conversations.utils.Compatibility;
88import eu.siacs.conversations.utils.Emoticons;
89import eu.siacs.conversations.utils.IrregularUnicodeDetector;
90import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
91import eu.siacs.conversations.utils.UIHelper;
92import eu.siacs.conversations.utils.XEP0392Helper;
93import eu.siacs.conversations.utils.XmppUri;
94import eu.siacs.conversations.xml.Element;
95import eu.siacs.conversations.xml.Namespace;
96import eu.siacs.conversations.xmpp.Jid;
97import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
98import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
99import eu.siacs.conversations.xmpp.XmppConnection;
100import java.util.Collection;
101import java.util.Collections;
102import java.util.List;
103import org.openintents.openpgp.util.OpenPgpUtils;
104
105public class ContactDetailsActivity extends OmemoActivity
106 implements OnAccountUpdate,
107 OnRosterUpdate,
108 OnUpdateBlocklist,
109 OnKeyStatusUpdated,
110 OnMediaLoaded {
111 public static final String ACTION_VIEW_CONTACT = "view_contact";
112 private final int REQUEST_SYNC_CONTACTS = 0x28cf;
113 ActivityContactDetailsBinding binding;
114 private MediaAdapter mMediaAdapter;
115 protected MenuItem edit = null;
116 protected MenuItem save = null;
117
118 private Contact contact;
119 private final DialogInterface.OnClickListener removeFromRoster =
120 new DialogInterface.OnClickListener() {
121
122 @Override
123 public void onClick(DialogInterface dialog, int which) {
124 xmppConnectionService.deleteContactOnServer(contact);
125 }
126 };
127 private final OnCheckedChangeListener mOnSendCheckedChange =
128 new OnCheckedChangeListener() {
129
130 @Override
131 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
132 if (isChecked) {
133 if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
134 xmppConnectionService.stopPresenceUpdatesTo(contact);
135 } else {
136 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
137 }
138 } else {
139 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
140 xmppConnectionService.sendPresencePacket(
141 contact.getAccount(),
142 xmppConnectionService
143 .getPresenceGenerator()
144 .stopPresenceUpdatesTo(contact));
145 }
146 }
147 };
148 private final OnCheckedChangeListener mOnReceiveCheckedChange =
149 new OnCheckedChangeListener() {
150
151 @Override
152 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
153 if (isChecked) {
154 xmppConnectionService.sendPresencePacket(
155 contact.getAccount(),
156 xmppConnectionService
157 .getPresenceGenerator()
158 .requestPresenceUpdatesFrom(contact));
159 } else {
160 xmppConnectionService.sendPresencePacket(
161 contact.getAccount(),
162 xmppConnectionService
163 .getPresenceGenerator()
164 .stopPresenceUpdatesFrom(contact));
165 }
166 }
167 };
168 private Jid accountJid;
169 private Jid contactJid;
170 private boolean showDynamicTags = false;
171 private boolean showLastSeen = false;
172 private boolean showInactiveOmemo = false;
173 private String messageFingerprint;
174
175 private void checkContactPermissionAndShowAddDialog() {
176 if (hasContactsPermission()) {
177 showAddToPhoneBookDialog();
178 } else if (QuickConversationsService.isContactListIntegration(this)
179 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
180 requestPermissions(
181 new String[] {Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
182 }
183 }
184
185 private boolean hasContactsPermission() {
186 if (QuickConversationsService.isContactListIntegration(this)
187 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
188 return checkSelfPermission(Manifest.permission.READ_CONTACTS)
189 == PackageManager.PERMISSION_GRANTED;
190 } else {
191 return true;
192 }
193 }
194
195 private void showAddToPhoneBookDialog() {
196 final Jid jid = contact.getJid();
197 final boolean quicksyContact =
198 AbstractQuickConversationsService.isQuicksy()
199 && Config.QUICKSY_DOMAIN.equals(jid.getDomain())
200 && jid.getLocal() != null;
201 final String value;
202 if (quicksyContact) {
203 value = PhoneNumberUtilWrapper.toFormattedPhoneNumber(this, jid);
204 } else {
205 value = jid.toEscapedString();
206 }
207 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
208 builder.setTitle(getString(R.string.action_add_phone_book));
209 builder.setMessage(getString(R.string.add_phone_book_text, value));
210 builder.setNegativeButton(getString(R.string.cancel), null);
211 builder.setPositiveButton(
212 getString(R.string.add),
213 (dialog, which) -> {
214 final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
215 intent.setType(Contacts.CONTENT_ITEM_TYPE);
216 if (quicksyContact) {
217 intent.putExtra(Intents.Insert.PHONE, value);
218 } else {
219 intent.putExtra(Intents.Insert.IM_HANDLE, value);
220 intent.putExtra(
221 Intents.Insert.IM_PROTOCOL, CommonDataKinds.Im.PROTOCOL_JABBER);
222 // TODO for modern use we want PROTOCOL_CUSTOM and an extra field with a
223 // value of 'XMPP'
224 // however we don’t have such a field and thus have to use the legacy
225 // PROTOCOL_JABBER
226 }
227 intent.putExtra("finishActivityOnSaveCompleted", true);
228 try {
229 startActivityForResult(intent, 0);
230 } catch (ActivityNotFoundException e) {
231 Toast.makeText(
232 ContactDetailsActivity.this,
233 R.string.no_application_found_to_view_contact,
234 Toast.LENGTH_SHORT)
235 .show();
236 }
237 });
238 builder.create().show();
239 }
240
241 @Override
242 public void onRosterUpdate(final XmppConnectionService.UpdateRosterReason reason, final Contact contact) {
243 refreshUi();
244 }
245
246 @Override
247 public void onAccountUpdate() {
248 refreshUi();
249 }
250
251 @Override
252 public void OnUpdateBlocklist(final Status status) {
253 refreshUi();
254 }
255
256 @Override
257 protected void refreshUiReal() {
258 populateView();
259 }
260
261 @Override
262 protected String getShareableUri(boolean http) {
263 if (http) {
264 return "https://conversations.im/i/"
265 + XmppUri.lameUrlEncode(contact.getJid().asBareJid().toEscapedString());
266 } else {
267 return "xmpp:" + Uri.encode(contact.getJid().asBareJid().toEscapedString(), "@/+");
268 }
269 }
270
271 @Override
272 protected void onCreate(final Bundle savedInstanceState) {
273 super.onCreate(savedInstanceState);
274 showInactiveOmemo =
275 savedInstanceState != null
276 && savedInstanceState.getBoolean("show_inactive_omemo", false);
277 if (getIntent().getAction().equals(ACTION_VIEW_CONTACT)) {
278 try {
279 this.accountJid = Jid.ofEscaped(getIntent().getExtras().getString(EXTRA_ACCOUNT));
280 } catch (final IllegalArgumentException ignored) {
281 }
282 try {
283 this.contactJid = Jid.ofEscaped(getIntent().getExtras().getString("contact"));
284 } catch (final IllegalArgumentException ignored) {
285 }
286 }
287 this.messageFingerprint = getIntent().getStringExtra("fingerprint");
288 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_details);
289 Activities.setStatusAndNavigationBarColors(this, binding.getRoot());
290
291 setSupportActionBar(binding.toolbar);
292 configureActionBar(getSupportActionBar());
293 binding.showInactiveDevices.setOnClickListener(
294 v -> {
295 showInactiveOmemo = !showInactiveOmemo;
296 populateView();
297 });
298 binding.addContactButton.setOnClickListener(v -> showAddToRosterDialog(contact));
299
300 mMediaAdapter = new MediaAdapter(this, R.dimen.media_size);
301 this.binding.media.setAdapter(mMediaAdapter);
302 GridManager.setupLayoutManager(this, this.binding.media, R.dimen.media_size);
303 }
304
305 @Override
306 public void onSaveInstanceState(final Bundle savedInstanceState) {
307 savedInstanceState.putBoolean("show_inactive_omemo", showInactiveOmemo);
308 super.onSaveInstanceState(savedInstanceState);
309 }
310
311 @Override
312 public void onStart() {
313 super.onStart();
314 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
315 this.showDynamicTags = preferences.getBoolean(AppSettings.SHOW_DYNAMIC_TAGS, false);
316 this.showLastSeen = preferences.getBoolean("last_activity", false);
317 binding.mediaWrapper.setVisibility(
318 Compatibility.hasStoragePermission(this) ? View.VISIBLE : View.GONE);
319 mMediaAdapter.setAttachments(Collections.emptyList());
320 }
321
322 @Override
323 public void onRequestPermissionsResult(
324 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
325 // TODO check for Camera / Scan permission
326 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
327 if (grantResults.length > 0)
328 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
329 if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
330 showAddToPhoneBookDialog();
331 xmppConnectionService.loadPhoneContacts();
332 xmppConnectionService.startContactObserver();
333 }
334 }
335 }
336
337 protected void saveEdits() {
338 binding.editTags.setVisibility(View.GONE);
339 if (edit != null) {
340 EditText text = edit.getActionView().findViewById(R.id.search_field);
341 contact.setServerName(text.getText().toString());
342 contact.setGroups(binding.editTags.getObjects().stream().map(tag -> tag.getName()).collect(Collectors.toList()));
343 ContactDetailsActivity.this.xmppConnectionService.pushContactToServer(contact);
344 populateView();
345 edit.collapseActionView();
346 }
347 if (save != null) save.setVisible(false);
348 }
349
350 @Override
351 public boolean onOptionsItemSelected(final MenuItem menuItem) {
352 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
353 return false;
354 }
355 switch (menuItem.getItemId()) {
356 case android.R.id.home:
357 finish();
358 break;
359 case R.id.action_share_http:
360 shareLink(true);
361 break;
362 case R.id.action_share_uri:
363 shareLink(false);
364 break;
365 case R.id.action_delete_contact:
366 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
367 builder.setNegativeButton(getString(R.string.cancel), null);
368 builder.setTitle(getString(R.string.action_delete_contact))
369 .setMessage(
370 JidDialog.style(
371 this,
372 R.string.remove_contact_text,
373 contact.getJid().toEscapedString()))
374 .setPositiveButton(getString(R.string.delete), removeFromRoster)
375 .create()
376 .show();
377 break;
378 case R.id.action_save:
379 saveEdits();
380 break;
381 case R.id.action_edit_contact:
382 final Uri systemAccount = contact.getSystemAccount();
383 if (systemAccount == null) {
384 menuItem.expandActionView();
385 EditText text = menuItem.getActionView().findViewById(R.id.search_field);
386 text.setOnEditorActionListener((v, actionId, event) -> {
387 saveEdits();
388 return true;
389 });
390 text.setText(contact.getServerName());
391 text.requestFocus();
392 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
393 if (imm != null) {
394 imm.showSoftInput(text, InputMethodManager.SHOW_IMPLICIT);
395 }
396 binding.tags.setVisibility(View.GONE);
397 binding.editTags.clearSync();
398 for (final ListItem.Tag group : contact.getGroupTags()) {
399 binding.editTags.addObjectSync(group);
400 }
401 ArrayList<ListItem.Tag> tags = new ArrayList<>();
402 for (final Account account : xmppConnectionService.getAccounts()) {
403 for (Contact contact : account.getRoster().getContacts()) {
404 tags.addAll(contact.getTags(this));
405 }
406 for (Bookmark bookmark : account.getBookmarks()) {
407 tags.addAll(bookmark.getTags(this));
408 }
409 }
410 Comparator<Map.Entry<ListItem.Tag,Integer>> sortTagsBy = Map.Entry.comparingByValue(Comparator.reverseOrder());
411 sortTagsBy = sortTagsBy.thenComparing(entry -> entry.getKey().getName());
412
413 ArrayAdapter<ListItem.Tag> adapter = new ArrayAdapter<>(
414 this,
415 android.R.layout.simple_list_item_1,
416 tags.stream()
417 .collect(Collectors.toMap((x) -> x, (t) -> 1, (c1, c2) -> c1 + c2))
418 .entrySet().stream()
419 .sorted(sortTagsBy)
420 .map(e -> e.getKey()).collect(Collectors.toList())
421 );
422 binding.editTags.setAdapter(adapter);
423 if (showDynamicTags) binding.editTags.setVisibility(View.VISIBLE);
424 if (save != null) save.setVisible(true);
425 } else {
426 menuItem.collapseActionView();
427 if (save != null) save.setVisible(false);
428 Intent intent = new Intent(Intent.ACTION_EDIT);
429 intent.setDataAndType(systemAccount, Contacts.CONTENT_ITEM_TYPE);
430 intent.putExtra("finishActivityOnSaveCompleted", true);
431 try {
432 startActivity(intent);
433 } catch (ActivityNotFoundException e) {
434 Toast.makeText(
435 ContactDetailsActivity.this,
436 R.string.no_application_found_to_view_contact,
437 Toast.LENGTH_SHORT)
438 .show();
439 }
440 }
441 break;
442 case R.id.action_block, R.id.action_unblock:
443 BlockContactDialog.show(this, contact);
444 break;
445 case R.id.action_custom_notifications:
446 configureCustomNotifications(contact);
447 break;
448 }
449 return super.onOptionsItemSelected(menuItem);
450 }
451
452 private void configureCustomNotifications(final Contact contact) {
453 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
454 return;
455 }
456 final var shortcut = xmppConnectionService.getShortcutService().getShortcutInfo(contact);
457 configureCustomNotification(shortcut);
458 }
459
460 @Override
461 public boolean onCreateOptionsMenu(final Menu menu) {
462 getMenuInflater().inflate(R.menu.contact_details, menu);
463 AccountUtils.showHideMenuItems(menu);
464 final MenuItem block = menu.findItem(R.id.action_block);
465 final MenuItem unblock = menu.findItem(R.id.action_unblock);
466 final MenuItem edit = menu.findItem(R.id.action_edit_contact);
467 final MenuItem save = menu.findItem(R.id.action_save);
468 final MenuItem delete = menu.findItem(R.id.action_delete_contact);
469 final MenuItem customNotifications = menu.findItem(R.id.action_custom_notifications);
470 customNotifications.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R);
471 if (contact == null) {
472 return true;
473 }
474 final XmppConnection connection = contact.getAccount().getXmppConnection();
475 if (connection != null && connection.getFeatures().blocking()) {
476 if (this.contact.isBlocked()) {
477 block.setVisible(false);
478 } else {
479 unblock.setVisible(false);
480 }
481 } else {
482 unblock.setVisible(false);
483 block.setVisible(false);
484 }
485 if (!contact.showInRoster()) {
486 edit.setVisible(false);
487 delete.setVisible(false);
488 }
489 edit.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
490 @Override
491 public boolean onMenuItemActionCollapse(MenuItem item) {
492 SoftKeyboardUtils.hideSoftKeyboard(ContactDetailsActivity.this);
493 binding.editTags.setVisibility(View.GONE);
494 if (save != null) save.setVisible(false);
495 populateView();
496 return true;
497 }
498
499 @Override
500 public boolean onMenuItemActionExpand(MenuItem item) { return true; }
501 });
502 return super.onCreateOptionsMenu(menu);
503 }
504
505 private void populateView() {
506 if (contact == null) {
507 return;
508 }
509 if (binding.editTags.getVisibility() != View.GONE) return;
510 invalidateOptionsMenu();
511 setTitle(contact.getDisplayName());
512 if (contact.showInRoster()) {
513 binding.detailsSendPresence.setVisibility(View.VISIBLE);
514 binding.detailsReceivePresence.setVisibility(View.VISIBLE);
515 binding.addContactButton.setVisibility(View.GONE);
516 binding.detailsSendPresence.setOnCheckedChangeListener(null);
517 binding.detailsReceivePresence.setOnCheckedChangeListener(null);
518
519 List<String> statusMessages = contact.getPresences().getStatusMessages();
520 if (statusMessages.size() == 0) {
521 binding.statusMessage.setVisibility(View.GONE);
522 } else if (statusMessages.size() == 1) {
523 final String message = statusMessages.get(0);
524 binding.statusMessage.setVisibility(View.VISIBLE);
525 final Spannable span = new SpannableString(message);
526 if (Emoticons.isOnlyEmoji(message)) {
527 span.setSpan(
528 new RelativeSizeSpan(2.0f),
529 0,
530 message.length(),
531 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
532 }
533 binding.statusMessage.setText(span);
534 } else {
535 StringBuilder builder = new StringBuilder();
536 binding.statusMessage.setVisibility(View.VISIBLE);
537 int s = statusMessages.size();
538 for (int i = 0; i < s; ++i) {
539 builder.append(statusMessages.get(i));
540 if (i < s - 1) {
541 builder.append("\n");
542 }
543 }
544 binding.statusMessage.setText(builder);
545 }
546
547 if (contact.getOption(Contact.Options.FROM)) {
548 binding.detailsSendPresence.setText(R.string.send_presence_updates);
549 binding.detailsSendPresence.setChecked(true);
550 } else if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
551 binding.detailsSendPresence.setChecked(false);
552 binding.detailsSendPresence.setText(R.string.send_presence_updates);
553 } else {
554 binding.detailsSendPresence.setText(R.string.preemptively_grant);
555 binding.detailsSendPresence.setChecked(
556 contact.getOption(Contact.Options.PREEMPTIVE_GRANT));
557 }
558 if (contact.getOption(Contact.Options.TO)) {
559 binding.detailsReceivePresence.setText(R.string.receive_presence_updates);
560 binding.detailsReceivePresence.setChecked(true);
561 } else {
562 binding.detailsReceivePresence.setText(R.string.ask_for_presence_updates);
563 binding.detailsReceivePresence.setChecked(
564 contact.getOption(Contact.Options.ASKING));
565 }
566 if (contact.getAccount().isOnlineAndConnected()) {
567 binding.detailsReceivePresence.setEnabled(true);
568 binding.detailsSendPresence.setEnabled(true);
569 } else {
570 binding.detailsReceivePresence.setEnabled(false);
571 binding.detailsSendPresence.setEnabled(false);
572 }
573 binding.detailsSendPresence.setOnCheckedChangeListener(this.mOnSendCheckedChange);
574 binding.detailsReceivePresence.setOnCheckedChangeListener(this.mOnReceiveCheckedChange);
575 } else {
576 binding.addContactButton.setVisibility(View.VISIBLE);
577 binding.detailsSendPresence.setVisibility(View.GONE);
578 binding.detailsReceivePresence.setVisibility(View.GONE);
579 binding.statusMessage.setVisibility(View.GONE);
580 }
581
582 if (contact.isBlocked() && !this.showDynamicTags) {
583 binding.detailsLastseen.setVisibility(View.VISIBLE);
584 binding.detailsLastseen.setText(R.string.contact_blocked);
585 } else {
586 if (showLastSeen
587 && contact.getLastseen() > 0
588 && contact.getPresences().allOrNonSupport(Namespace.IDLE)) {
589 binding.detailsLastseen.setVisibility(View.VISIBLE);
590 binding.detailsLastseen.setText(
591 UIHelper.lastseen(
592 getApplicationContext(),
593 contact.isActive(),
594 contact.getLastseen()));
595 } else {
596 binding.detailsLastseen.setVisibility(View.GONE);
597 }
598 }
599
600 binding.detailsContactjid.setText(IrregularUnicodeDetector.style(this, contact.getJid()));
601 final String account = contact.getAccount().getJid().asBareJid().toEscapedString();
602 binding.detailsAccount.setText(getString(R.string.using_account, account));
603 AvatarWorkerTask.loadAvatar(
604 contact, binding.detailsContactBadge, R.dimen.avatar_on_details_screen_size);
605 binding.detailsContactBadge.setOnClickListener(this::onBadgeClick);
606
607 binding.detailsContactKeys.removeAllViews();
608 boolean hasKeys = false;
609 final LayoutInflater inflater = getLayoutInflater();
610 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
611 if (Config.supportOmemo() && axolotlService != null) {
612 final Collection<XmppAxolotlSession> sessions =
613 axolotlService.findSessionsForContact(contact);
614 boolean anyActive = false;
615 for (XmppAxolotlSession session : sessions) {
616 anyActive = session.getTrust().isActive();
617 if (anyActive) {
618 break;
619 }
620 }
621 boolean skippedInactive = false;
622 boolean showsInactive = false;
623 boolean showUnverifiedWarning = false;
624 for (final XmppAxolotlSession session : sessions) {
625 final FingerprintStatus trust = session.getTrust();
626 hasKeys |= !trust.isCompromised();
627 if (!trust.isActive() && anyActive) {
628 if (showInactiveOmemo) {
629 showsInactive = true;
630 } else {
631 skippedInactive = true;
632 continue;
633 }
634 }
635 if (!trust.isCompromised()) {
636 boolean highlight = session.getFingerprint().equals(messageFingerprint);
637 addFingerprintRow(binding.detailsContactKeys, session, highlight);
638 }
639 if (trust.isUnverified()) {
640 showUnverifiedWarning = true;
641 }
642 }
643 binding.unverifiedWarning.setVisibility(
644 showUnverifiedWarning ? View.VISIBLE : View.GONE);
645 if (showsInactive || skippedInactive) {
646 binding.showInactiveDevices.setText(
647 showsInactive
648 ? R.string.hide_inactive_devices
649 : R.string.show_inactive_devices);
650 binding.showInactiveDevices.setVisibility(View.VISIBLE);
651 } else {
652 binding.showInactiveDevices.setVisibility(View.GONE);
653 }
654 } else {
655 binding.showInactiveDevices.setVisibility(View.GONE);
656 }
657 final boolean isCameraFeatureAvailable = isCameraFeatureAvailable();
658 binding.scanButton.setVisibility(
659 hasKeys && isCameraFeatureAvailable ? View.VISIBLE : View.GONE);
660 if (hasKeys) {
661 binding.scanButton.setOnClickListener((v) -> ScanActivity.scan(this));
662 }
663 if (Config.supportOpenPgp() && contact.getPgpKeyId() != 0) {
664 hasKeys = true;
665 View view = inflater.inflate(R.layout.contact_key, binding.detailsContactKeys, false);
666 TextView key = view.findViewById(R.id.key);
667 TextView keyType = view.findViewById(R.id.key_type);
668 keyType.setText(R.string.openpgp_key_id);
669 if ("pgp".equals(messageFingerprint)) {
670 keyType.setTextColor(
671 MaterialColors.getColor(
672 keyType, com.google.android.material.R.attr.colorPrimaryVariant));
673 }
674 key.setText(OpenPgpUtils.convertKeyIdToHex(contact.getPgpKeyId()));
675 final OnClickListener openKey = v -> launchOpenKeyChain(contact.getPgpKeyId());
676 view.setOnClickListener(openKey);
677 key.setOnClickListener(openKey);
678 keyType.setOnClickListener(openKey);
679 binding.detailsContactKeys.addView(view);
680 }
681 binding.keysWrapper.setVisibility(hasKeys ? View.VISIBLE : View.GONE);
682
683 final List<ListItem.Tag> tagList = contact.getTags(this);
684 final boolean hasMetaTags =
685 contact.isBlocked() || contact.getShownStatus() != Presence.Status.OFFLINE;
686 if ((tagList.isEmpty() && !hasMetaTags) || !this.showDynamicTags) {
687 binding.tags.setVisibility(View.GONE);
688 } else {
689 binding.tags.setVisibility(View.VISIBLE);
690 binding.tags.removeViews(1, binding.tags.getChildCount() - 1);
691 final ImmutableList.Builder<Integer> viewIdBuilder = new ImmutableList.Builder<>();
692 for (final ListItem.Tag tag : tagList) {
693 final String name = tag.getName();
694 final TextView tv =
695 (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
696 tv.setText(name);
697 tv.setBackgroundTintList(
698 ColorStateList.valueOf(
699 MaterialColors.harmonizeWithPrimary(
700 this, XEP0392Helper.rgbFromNick(name))));
701 final int id = ViewCompat.generateViewId();
702 tv.setId(id);
703 viewIdBuilder.add(id);
704 binding.tags.addView(tv);
705 }
706 if (contact.isBlocked()) {
707 final TextView tv =
708 (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
709 tv.setText(R.string.blocked);
710 tv.setBackgroundTintList(
711 ColorStateList.valueOf(
712 MaterialColors.harmonizeWithPrimary(
713 tv.getContext(),
714 ContextCompat.getColor(
715 tv.getContext(), R.color.gray_800))));
716 final int id = ViewCompat.generateViewId();
717 tv.setId(id);
718 viewIdBuilder.add(id);
719 binding.tags.addView(tv);
720 } else {
721 final Presence.Status status = contact.getShownStatus();
722 if (status != Presence.Status.OFFLINE) {
723 final TextView tv =
724 (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
725 UIHelper.setStatus(tv, status);
726 final int id = ViewCompat.generateViewId();
727 tv.setId(id);
728 viewIdBuilder.add(id);
729 binding.tags.addView(tv);
730 }
731 }
732 if (contact.getJid().isDomainJid()) {
733 for (final var p : contact.getPresences().getPresences()) {
734 final var disco = p.getServiceDiscoveryResult();
735 if (disco == null) continue;
736 for (final var identity : disco.getIdentities()) {
737 final var txt = identity.getCategory() + "/" + identity.getType();
738 final TextView tv =
739 (TextView)
740 inflater.inflate(
741 R.layout.item_tag, binding.tags, false);
742 tv.setText(txt);
743 tv.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.harmonizeWithPrimary(this,XEP0392Helper.rgbFromNick(txt))));
744 final int id = ViewCompat.generateViewId();
745 tv.setId(id);
746 viewIdBuilder.add(id);
747 binding.tags.addView(tv);
748 }
749 }
750 }
751 binding.flowWidget.setReferencedIds(Ints.toArray(viewIdBuilder.build()));
752 }
753 }
754
755 private void onBadgeClick(final View view) {
756 if (QuickConversationsService.isContactListIntegration(this)) {
757 final Uri systemAccount = contact.getSystemAccount();
758 if (systemAccount == null) {
759 checkContactPermissionAndShowAddDialog();
760 } else {
761 final Intent intent = new Intent(Intent.ACTION_VIEW);
762 intent.setData(systemAccount);
763 try {
764 startActivity(intent);
765 } catch (final ActivityNotFoundException e) {
766 Toast.makeText(
767 this,
768 R.string.no_application_found_to_view_contact,
769 Toast.LENGTH_SHORT)
770 .show();
771 }
772 }
773 } else {
774 Toast.makeText(
775 this,
776 R.string.contact_list_integration_not_available,
777 Toast.LENGTH_SHORT)
778 .show();
779 }
780 }
781
782 public void onBackendConnected() {
783 if (accountJid != null && contactJid != null) {
784 Account account = xmppConnectionService.findAccountByJid(accountJid);
785 if (account == null) {
786 return;
787 }
788 this.contact = account.getRoster().getContact(contactJid);
789 if (mPendingFingerprintVerificationUri != null) {
790 processFingerprintVerification(mPendingFingerprintVerificationUri);
791 mPendingFingerprintVerificationUri = null;
792 }
793
794 if (Compatibility.hasStoragePermission(this)) {
795 final int limit = GridManager.getCurrentColumnCount(this.binding.media);
796 xmppConnectionService.getAttachments(
797 account, contact.getJid().asBareJid(), limit, this);
798 this.binding.showMedia.setOnClickListener(
799 (v) -> MediaBrowserActivity.launch(this, contact));
800 }
801
802 final VcardAdapter items = new VcardAdapter();
803 binding.profileItems.setAdapter(items);
804 binding.profileItems.setOnItemClickListener((a0, v, pos, a3) -> {
805 final Uri uri = items.getUri(pos);
806 if (uri == null) return;
807 new FixedURLSpan(uri.toString()).onClick(v);
808 });
809 binding.profileItems.setOnItemLongClickListener((a0, v, pos, a3) -> {
810 String toCopy = null;
811 final Uri uri = items.getUri(pos);
812 if (uri != null) toCopy = uri.toString();
813 if (toCopy == null) {
814 toCopy = items.getItem(pos).findChildContent("text", Namespace.VCARD4);
815 }
816
817 if (toCopy == null) return false;
818 if (ShareUtil.copyTextToClipboard(ContactDetailsActivity.this, toCopy, R.string.message)) {
819 Toast.makeText(ContactDetailsActivity.this, R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
820 }
821 return true;
822 });
823 xmppConnectionService.fetchVcard4(account, contact, (vcard4) -> {
824 if (vcard4 == null) return;
825
826 runOnUiThread(() -> {
827 for (Element el : vcard4.getChildren()) {
828 if (el.findChildEnsureSingle("uri", Namespace.VCARD4) != null || el.findChildEnsureSingle("text", Namespace.VCARD4) != null) {
829 items.add(el);
830 }
831 }
832 Util.justifyListViewHeightBasedOnChildren(binding.profileItems);
833 });
834 });
835
836 final var conversation = xmppConnectionService.findOrCreateConversation(account, contact.getJid(), false, true);
837 binding.storeInCache.setChecked(conversation.storeInCache());
838 binding.storeInCache.setOnCheckedChangeListener((v, checked) -> {
839 conversation.setStoreInCache(checked);
840 xmppConnectionService.updateConversation(conversation);
841 });
842
843 populateView();
844 }
845 }
846
847 @Override
848 public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
849 refreshUi();
850 }
851
852 @Override
853 protected void processFingerprintVerification(XmppUri uri) {
854 if (contact != null
855 && contact.getJid().asBareJid().equals(uri.getJid())
856 && uri.hasFingerprints()) {
857 if (xmppConnectionService.verifyFingerprints(contact, uri.getFingerprints())) {
858 Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
859 }
860 } else {
861 Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
862 }
863 }
864
865 @Override
866 public void onMediaLoaded(List<Attachment> attachments) {
867 runOnUiThread(
868 () -> {
869 int limit = GridManager.getCurrentColumnCount(binding.media);
870 mMediaAdapter.setAttachments(
871 attachments.subList(0, Math.min(limit, attachments.size())));
872 binding.mediaWrapper.setVisibility(
873 attachments.size() > 0 ? View.VISIBLE : View.GONE);
874 });
875 }
876
877 class VcardAdapter extends ArrayAdapter<Element> {
878 VcardAdapter() { super(ContactDetailsActivity.this, 0); }
879
880 private Drawable getDrawable(int d) {
881 return ContactDetailsActivity.this.getDrawable(d);
882 }
883
884 @Override
885 public View getView(int position, View view, @NonNull ViewGroup parent) {
886 final CommandRowBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.command_row, parent, false);
887 final Element item = getItem(position);
888
889 if (item.getName().equals("org")) {
890 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_business_24dp), null, null, null);
891 binding.command.setCompoundDrawablePadding(20);
892 } else if (item.getName().equals("impp")) {
893 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_chat_black_24dp), null, null, null);
894 binding.command.setCompoundDrawablePadding(20);
895 } else if (item.getName().equals("url")) {
896 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_link_24dp), null, null, null);
897 binding.command.setCompoundDrawablePadding(20);
898 }
899
900 final Uri uri = getUri(position);
901 if (uri != null && uri.getScheme() != null) {
902 if (uri.getScheme().equals("xmpp")) {
903 binding.command.setText(uri.getSchemeSpecificPart());
904 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.jabber), null, null, null);
905 binding.command.setCompoundDrawablePadding(20);
906 } else if (uri.getScheme().equals("tel")) {
907 binding.command.setText(uri.getSchemeSpecificPart());
908 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_call_24dp), null, null, null);
909 binding.command.setCompoundDrawablePadding(20);
910 } else if (uri.getScheme().equals("mailto")) {
911 binding.command.setText(uri.getSchemeSpecificPart());
912 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_email_24dp), null, null, null);
913 binding.command.setCompoundDrawablePadding(20);
914 } else if (uri.getScheme().equals("bitcoin")) {
915 binding.command.setText(uri.getSchemeSpecificPart());
916 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.bitcoin_24dp), null, null, null);
917 binding.command.setCompoundDrawablePadding(20);
918 } else if (uri.getScheme().equals("bitcoincash")) {
919 binding.command.setText(uri.getSchemeSpecificPart());
920 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.bitcoin_cash_24dp), null, null, null);
921 binding.command.setCompoundDrawablePadding(20);
922 } else if (uri.getScheme().equals("ethereum")) {
923 binding.command.setText(uri.getSchemeSpecificPart());
924 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.eth_24dp), null, null, null);
925 binding.command.setCompoundDrawablePadding(20);
926 } else if (uri.getScheme().equals("monero")) {
927 binding.command.setText(uri.getSchemeSpecificPart());
928 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.monero_24dp), null, null, null);
929 binding.command.setCompoundDrawablePadding(20);
930 } else if (uri.getScheme().equals("wownero")) {
931 binding.command.setText(uri.getSchemeSpecificPart());
932 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.wownero_24dp), null, null, null);
933 binding.command.setCompoundDrawablePadding(20);
934 } else if (uri.getScheme().equals("https") && "liberapay.com".equals(uri.getHost())) {
935 binding.command.setText(uri.getPath().substring(1));
936 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.liberapay), null, null, null);
937 binding.command.setCompoundDrawablePadding(20);
938 } else if (uri.getScheme().equals("https") && ("www.patreon.com".equals(uri.getHost()) || "patreon.com".equals(uri.getHost()))) {
939 binding.command.setText(uri.getPath().replaceAll("^/(?:c/)?", ""));
940 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.patreon), null, null, null);
941 binding.command.setCompoundDrawablePadding(20);
942 } else if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) {
943 binding.command.setText(uri.toString());
944 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_link_24dp), null, null, null);
945 binding.command.setCompoundDrawablePadding(20);
946 } else {
947 binding.command.setText(uri.toString());
948 }
949 } else {
950 final String text = item.findChildContent("text", Namespace.VCARD4);
951 binding.command.setText(text);
952 }
953
954 return binding.getRoot();
955 }
956
957 public Uri getUri(int pos) {
958 final Element item = getItem(pos);
959 final String uriS = item.findChildContent("uri", Namespace.VCARD4);
960 if (uriS != null) return Uri.parse(uriS).normalizeScheme();
961 if (item.getName().equals("email")) return Uri.parse("mailto:" + item.findChildContent("text", Namespace.VCARD4));
962 return null;
963 }
964 }
965}