ContactDetailsActivity.java

  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.PorterDuff;
 11import android.graphics.drawable.Drawable;
 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;
 36
 37import androidx.annotation.NonNull;
 38import androidx.appcompat.app.AlertDialog;
 39import androidx.databinding.DataBindingUtil;
 40
 41import com.cheogram.android.Util;
 42
 43import org.openintents.openpgp.util.OpenPgpUtils;
 44
 45import java.util.ArrayList;
 46import java.util.Collection;
 47import java.util.Collections;
 48import java.util.Comparator;
 49import java.util.List;
 50import java.util.Map;
 51import java.util.stream.Collectors;
 52
 53import eu.siacs.conversations.Config;
 54import eu.siacs.conversations.R;
 55import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 56import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
 57import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
 58import eu.siacs.conversations.databinding.ActivityContactDetailsBinding;
 59import eu.siacs.conversations.databinding.CommandRowBinding;
 60import eu.siacs.conversations.entities.Account;
 61import eu.siacs.conversations.entities.Bookmark;
 62import eu.siacs.conversations.entities.Contact;
 63import eu.siacs.conversations.entities.ListItem;
 64import eu.siacs.conversations.services.AbstractQuickConversationsService;
 65import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
 66import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
 67import eu.siacs.conversations.ui.adapter.MediaAdapter;
 68import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
 69import eu.siacs.conversations.ui.util.Attachment;
 70import eu.siacs.conversations.ui.util.AvatarWorkerTask;
 71import eu.siacs.conversations.ui.util.GridManager;
 72import eu.siacs.conversations.ui.util.JidDialog;
 73import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 74import eu.siacs.conversations.ui.util.ShareUtil;
 75import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
 76import eu.siacs.conversations.utils.AccountUtils;
 77import eu.siacs.conversations.utils.Compatibility;
 78import eu.siacs.conversations.utils.Emoticons;
 79import eu.siacs.conversations.utils.IrregularUnicodeDetector;
 80import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
 81import eu.siacs.conversations.utils.UIHelper;
 82import eu.siacs.conversations.utils.XmppUri;
 83import eu.siacs.conversations.xml.Element;
 84import eu.siacs.conversations.xml.Namespace;
 85import eu.siacs.conversations.xmpp.Jid;
 86import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 87import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 88import eu.siacs.conversations.xmpp.XmppConnection;
 89
 90public class ContactDetailsActivity extends OmemoActivity implements OnAccountUpdate, OnRosterUpdate, OnUpdateBlocklist, OnKeyStatusUpdated, OnMediaLoaded {
 91    public static final String ACTION_VIEW_CONTACT = "view_contact";
 92    private final int REQUEST_SYNC_CONTACTS = 0x28cf;
 93    ActivityContactDetailsBinding binding;
 94    private MediaAdapter mMediaAdapter;
 95    protected MenuItem edit = null;
 96    protected MenuItem save = null;
 97
 98    private Contact contact;
 99    private final DialogInterface.OnClickListener removeFromRoster = new DialogInterface.OnClickListener() {
100
101        @Override
102        public void onClick(DialogInterface dialog, int which) {
103            xmppConnectionService.deleteContactOnServer(contact);
104        }
105    };
106    private final OnCheckedChangeListener mOnSendCheckedChange = new OnCheckedChangeListener() {
107
108        @Override
109        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
110            if (isChecked) {
111                if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
112                    xmppConnectionService.stopPresenceUpdatesTo(contact);
113                } else {
114                    contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
115                }
116            } else {
117                contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
118                xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().stopPresenceUpdatesTo(contact));
119            }
120        }
121    };
122    private final OnCheckedChangeListener mOnReceiveCheckedChange = new OnCheckedChangeListener() {
123
124        @Override
125        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
126            if (isChecked) {
127                xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().requestPresenceUpdatesFrom(contact));
128            } else {
129                xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().stopPresenceUpdatesFrom(contact));
130            }
131        }
132    };
133    private Jid accountJid;
134    private Jid contactJid;
135    private boolean showDynamicTags = false;
136    private boolean showLastSeen = false;
137    private boolean showInactiveOmemo = false;
138    private String messageFingerprint;
139
140    private void checkContactPermissionAndShowAddDialog() {
141        if (hasContactsPermission()) {
142            showAddToPhoneBookDialog();
143        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
144            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
145        }
146    }
147
148    private boolean hasContactsPermission() {
149        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
150            return checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
151        } else {
152            return true;
153        }
154    }
155
156    private void showAddToPhoneBookDialog() {
157        final Jid jid = contact.getJid();
158        final boolean quicksyContact = AbstractQuickConversationsService.isQuicksy()
159                && Config.QUICKSY_DOMAIN.equals(jid.getDomain())
160                && jid.getLocal() != null;
161        final String value;
162        if (quicksyContact) {
163            value = PhoneNumberUtilWrapper.toFormattedPhoneNumber(this, jid);
164        } else {
165            value = jid.toEscapedString();
166        }
167        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
168        builder.setTitle(getString(R.string.action_add_phone_book));
169        builder.setMessage(getString(R.string.add_phone_book_text, value));
170        builder.setNegativeButton(getString(R.string.cancel), null);
171        builder.setPositiveButton(getString(R.string.add), (dialog, which) -> {
172            final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
173            intent.setType(Contacts.CONTENT_ITEM_TYPE);
174            if (quicksyContact) {
175                intent.putExtra(Intents.Insert.PHONE, value);
176            } else {
177                intent.putExtra(Intents.Insert.IM_HANDLE, value);
178                intent.putExtra(Intents.Insert.IM_PROTOCOL, CommonDataKinds.Im.PROTOCOL_JABBER);
179                //TODO for modern use we want PROTOCOL_CUSTOM and an extra field with a value of 'XMPP'
180                // however we don’t have such a field and thus have to use the legacy PROTOCOL_JABBER
181            }
182            intent.putExtra("finishActivityOnSaveCompleted", true);
183            try {
184                startActivityForResult(intent, 0);
185            } catch (ActivityNotFoundException e) {
186                Toast.makeText(ContactDetailsActivity.this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
187            }
188        });
189        builder.create().show();
190    }
191
192    @Override
193    public void onRosterUpdate() {
194        refreshUi();
195    }
196
197    @Override
198    public void onAccountUpdate() {
199        refreshUi();
200    }
201
202    @Override
203    public void OnUpdateBlocklist(final Status status) {
204        refreshUi();
205    }
206
207    @Override
208    protected void refreshUiReal() {
209        populateView();
210    }
211
212    @Override
213    protected String getShareableUri(boolean http) {
214        if (http) {
215            return "https://conversations.im/i/" + XmppUri.lameUrlEncode(contact.getJid().asBareJid().toEscapedString());
216        } else {
217            return "xmpp:" + Uri.encode(contact.getJid().asBareJid().toEscapedString(), "@/+");
218        }
219    }
220
221    @Override
222    protected void onCreate(final Bundle savedInstanceState) {
223        super.onCreate(savedInstanceState);
224        showInactiveOmemo = savedInstanceState != null && savedInstanceState.getBoolean("show_inactive_omemo", false);
225        if (getIntent().getAction().equals(ACTION_VIEW_CONTACT)) {
226            try {
227                this.accountJid = Jid.ofEscaped(getIntent().getExtras().getString(EXTRA_ACCOUNT));
228            } catch (final IllegalArgumentException ignored) {
229            }
230            try {
231                this.contactJid = Jid.ofEscaped(getIntent().getExtras().getString("contact"));
232            } catch (final IllegalArgumentException ignored) {
233            }
234        }
235        this.messageFingerprint = getIntent().getStringExtra("fingerprint");
236        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_details);
237
238        setSupportActionBar(binding.toolbar);
239        configureActionBar(getSupportActionBar());
240        binding.showInactiveDevices.setOnClickListener(v -> {
241            showInactiveOmemo = !showInactiveOmemo;
242            populateView();
243        });
244        binding.addContactButton.setOnClickListener(v -> showAddToRosterDialog(contact));
245
246        mMediaAdapter = new MediaAdapter(this, R.dimen.media_size);
247        this.binding.media.setAdapter(mMediaAdapter);
248        GridManager.setupLayoutManager(this, this.binding.media, R.dimen.media_size);
249    }
250
251    @Override
252    public void onSaveInstanceState(final Bundle savedInstanceState) {
253        savedInstanceState.putBoolean("show_inactive_omemo", showInactiveOmemo);
254        super.onSaveInstanceState(savedInstanceState);
255    }
256
257    @Override
258    public void onStart() {
259        super.onStart();
260        final int theme = findTheme();
261        if (this.mTheme != theme) {
262            recreate();
263        } else {
264            final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
265            this.showDynamicTags = preferences.getBoolean(SettingsActivity.SHOW_DYNAMIC_TAGS, getResources().getBoolean(R.bool.show_dynamic_tags));
266            this.showLastSeen = preferences.getBoolean("last_activity", false);
267        }
268        binding.mediaWrapper.setVisibility(Compatibility.hasStoragePermission(this) ? View.VISIBLE : View.GONE);
269        mMediaAdapter.setAttachments(Collections.emptyList());
270    }
271
272    @Override
273    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
274        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
275        if (grantResults.length > 0)
276            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
277                if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
278                    showAddToPhoneBookDialog();
279                    xmppConnectionService.loadPhoneContacts();
280                    xmppConnectionService.startContactObserver();
281                }
282            }
283    }
284
285    protected void saveEdits() {
286        binding.editTags.setVisibility(View.GONE);
287        if (edit != null) {
288            EditText text = edit.getActionView().findViewById(R.id.search_field);
289            contact.setServerName(text.getText().toString());
290            contact.setGroups(binding.editTags.getObjects().stream().map(tag -> tag.getName()).collect(Collectors.toList()));
291            ContactDetailsActivity.this.xmppConnectionService.pushContactToServer(contact);
292            populateView();
293            edit.collapseActionView();
294        }
295        if (save != null) save.setVisible(false);
296    }
297
298    @Override
299    public boolean onOptionsItemSelected(final MenuItem menuItem) {
300        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
301            return false;
302        }
303        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
304        builder.setNegativeButton(getString(R.string.cancel), null);
305        switch (menuItem.getItemId()) {
306            case android.R.id.home:
307                finish();
308                break;
309            case R.id.action_share_http:
310                shareLink(true);
311                break;
312            case R.id.action_share_uri:
313                shareLink(false);
314                break;
315            case R.id.action_delete_contact:
316                builder.setTitle(getString(R.string.action_delete_contact))
317                        .setMessage(JidDialog.style(this, R.string.remove_contact_text, contact.getJid().toEscapedString()))
318                        .setPositiveButton(getString(R.string.delete),
319                                removeFromRoster).create().show();
320                break;
321            case R.id.action_save:
322                saveEdits();
323                break;
324            case R.id.action_edit_contact:
325                Uri systemAccount = contact.getSystemAccount();
326                if (systemAccount == null) {
327                    menuItem.expandActionView();
328                    EditText text = menuItem.getActionView().findViewById(R.id.search_field);
329                    text.setOnEditorActionListener((v, actionId, event) -> {
330                        saveEdits();
331                        return true;
332                    });
333                    text.setText(contact.getServerName());
334                    text.requestFocus();
335                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
336                    if (imm != null) {
337                        imm.showSoftInput(text, InputMethodManager.SHOW_IMPLICIT);
338                    }
339                    binding.tags.setVisibility(View.GONE);
340                    binding.editTags.clearSync();
341                    for (final ListItem.Tag group : contact.getGroupTags()) {
342                        binding.editTags.addObjectSync(group);
343                    }
344                    ArrayList<ListItem.Tag> tags = new ArrayList<>();
345                    for (final Account account : xmppConnectionService.getAccounts()) {
346                        for (Contact contact : account.getRoster().getContacts()) {
347                            tags.addAll(contact.getTags(this));
348                        }
349                        for (Bookmark bookmark : account.getBookmarks()) {
350                            tags.addAll(bookmark.getTags(this));
351                        }
352                    }
353                    Comparator<Map.Entry<ListItem.Tag,Integer>> sortTagsBy = Map.Entry.comparingByValue(Comparator.reverseOrder());
354                    sortTagsBy = sortTagsBy.thenComparing(entry -> entry.getKey().getName());
355
356                    ArrayAdapter<ListItem.Tag> adapter = new ArrayAdapter<>(
357                        this,
358                        android.R.layout.simple_list_item_1,
359                        tags.stream()
360                        .collect(Collectors.toMap((x) -> x, (t) -> 1, (c1, c2) -> c1 + c2))
361                        .entrySet().stream()
362                       .sorted(sortTagsBy)
363                       .map(e -> e.getKey()).collect(Collectors.toList())
364                    );
365                    binding.editTags.setAdapter(adapter);
366                    if (showDynamicTags) binding.editTags.setVisibility(View.VISIBLE);
367                    if (save != null) save.setVisible(true);
368                } else {
369                    menuItem.collapseActionView();
370                    if (save != null) save.setVisible(false);
371                    Intent intent = new Intent(Intent.ACTION_EDIT);
372                    intent.setDataAndType(systemAccount, Contacts.CONTENT_ITEM_TYPE);
373                    intent.putExtra("finishActivityOnSaveCompleted", true);
374                    try {
375                        startActivity(intent);
376                    } catch (ActivityNotFoundException e) {
377                        Toast.makeText(ContactDetailsActivity.this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
378                    }
379
380                }
381                break;
382            case R.id.action_block:
383                BlockContactDialog.show(this, contact);
384                break;
385            case R.id.action_unblock:
386                BlockContactDialog.show(this, contact);
387                break;
388        }
389        return super.onOptionsItemSelected(menuItem);
390    }
391
392    @Override
393    public boolean onCreateOptionsMenu(final Menu menu) {
394        getMenuInflater().inflate(R.menu.contact_details, menu);
395        AccountUtils.showHideMenuItems(menu);
396        edit = menu.findItem(R.id.action_edit_contact);
397        save = menu.findItem(R.id.action_save);
398        MenuItem block = menu.findItem(R.id.action_block);
399        MenuItem unblock = menu.findItem(R.id.action_unblock);
400        MenuItem edit = menu.findItem(R.id.action_edit_contact);
401        MenuItem delete = menu.findItem(R.id.action_delete_contact);
402        if (contact == null) {
403            return true;
404        }
405        final XmppConnection connection = contact.getAccount().getXmppConnection();
406        if (connection != null && connection.getFeatures().blocking()) {
407            if (this.contact.isBlocked()) {
408                block.setVisible(false);
409            } else {
410                unblock.setVisible(false);
411            }
412        } else {
413            unblock.setVisible(false);
414            block.setVisible(false);
415        }
416        if (!contact.showInRoster()) {
417            edit.setVisible(false);
418            delete.setVisible(false);
419        }
420        edit.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
421            @Override
422            public boolean onMenuItemActionCollapse(MenuItem item) {
423                SoftKeyboardUtils.hideSoftKeyboard(ContactDetailsActivity.this);
424                binding.editTags.setVisibility(View.GONE);
425                if (save != null) save.setVisible(false);
426                populateView();
427                return true;
428            }
429
430            @Override
431            public boolean onMenuItemActionExpand(MenuItem item) { return true; }
432        });
433        return super.onCreateOptionsMenu(menu);
434    }
435
436    private void populateView() {
437        if (contact == null) {
438            return;
439        }
440        if (binding.editTags.getVisibility() != View.GONE) return;
441        invalidateOptionsMenu();
442        setTitle(contact.getDisplayName());
443        if (contact.showInRoster()) {
444            binding.detailsSendPresence.setVisibility(View.VISIBLE);
445            binding.detailsReceivePresence.setVisibility(View.VISIBLE);
446            binding.addContactButton.setVisibility(View.GONE);
447            binding.detailsSendPresence.setOnCheckedChangeListener(null);
448            binding.detailsReceivePresence.setOnCheckedChangeListener(null);
449
450            List<String> statusMessages = contact.getPresences().getStatusMessages();
451            if (statusMessages.size() == 0) {
452                binding.statusMessage.setVisibility(View.GONE);
453            } else if (statusMessages.size() == 1) {
454                final String message = statusMessages.get(0);
455                binding.statusMessage.setVisibility(View.VISIBLE);
456                final Spannable span = new SpannableString(message);
457                if (Emoticons.isOnlyEmoji(message)) {
458                    span.setSpan(new RelativeSizeSpan(2.0f), 0, message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
459                }
460                binding.statusMessage.setText(span);
461            } else {
462                StringBuilder builder = new StringBuilder();
463                binding.statusMessage.setVisibility(View.VISIBLE);
464                int s = statusMessages.size();
465                for (int i = 0; i < s; ++i) {
466                    builder.append(statusMessages.get(i));
467                    if (i < s - 1) {
468                        builder.append("\n");
469                    }
470                }
471                binding.statusMessage.setText(builder);
472            }
473
474            if (contact.getOption(Contact.Options.FROM)) {
475                binding.detailsSendPresence.setText(R.string.send_presence_updates);
476                binding.detailsSendPresence.setChecked(true);
477            } else if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
478                binding.detailsSendPresence.setChecked(false);
479                binding.detailsSendPresence.setText(R.string.send_presence_updates);
480            } else {
481                binding.detailsSendPresence.setText(R.string.preemptively_grant);
482                binding.detailsSendPresence.setChecked(contact.getOption(Contact.Options.PREEMPTIVE_GRANT));
483            }
484            if (contact.getOption(Contact.Options.TO)) {
485                binding.detailsReceivePresence.setText(R.string.receive_presence_updates);
486                binding.detailsReceivePresence.setChecked(true);
487            } else {
488                binding.detailsReceivePresence.setText(R.string.ask_for_presence_updates);
489                binding.detailsReceivePresence.setChecked(contact.getOption(Contact.Options.ASKING));
490            }
491            if (contact.getAccount().isOnlineAndConnected()) {
492                binding.detailsReceivePresence.setEnabled(true);
493                binding.detailsSendPresence.setEnabled(true);
494            } else {
495                binding.detailsReceivePresence.setEnabled(false);
496                binding.detailsSendPresence.setEnabled(false);
497            }
498            binding.detailsSendPresence.setOnCheckedChangeListener(this.mOnSendCheckedChange);
499            binding.detailsReceivePresence.setOnCheckedChangeListener(this.mOnReceiveCheckedChange);
500        } else {
501            binding.addContactButton.setVisibility(View.VISIBLE);
502            binding.detailsSendPresence.setVisibility(View.GONE);
503            binding.detailsReceivePresence.setVisibility(View.GONE);
504            binding.statusMessage.setVisibility(View.GONE);
505        }
506
507        if (contact.isBlocked() && !this.showDynamicTags) {
508            binding.detailsLastseen.setVisibility(View.VISIBLE);
509            binding.detailsLastseen.setText(R.string.contact_blocked);
510        } else {
511            if (showLastSeen
512                    && contact.getLastseen() > 0
513                    && contact.getPresences().allOrNonSupport(Namespace.IDLE)) {
514                binding.detailsLastseen.setVisibility(View.VISIBLE);
515                binding.detailsLastseen.setText(UIHelper.lastseen(getApplicationContext(), contact.isActive(), contact.getLastseen()));
516            } else {
517                binding.detailsLastseen.setVisibility(View.GONE);
518            }
519        }
520
521        binding.detailsContactjid.setText(IrregularUnicodeDetector.style(this, contact.getJid()));
522        String account;
523        if (Config.DOMAIN_LOCK != null) {
524            account = contact.getAccount().getJid().getEscapedLocal();
525        } else {
526            account = contact.getAccount().getJid().asBareJid().toEscapedString();
527        }
528        binding.detailsAccount.setText(getString(R.string.using_account, account));
529        AvatarWorkerTask.loadAvatar(contact, binding.detailsContactBadge, R.dimen.avatar_on_details_screen_size);
530        binding.detailsContactBadge.setOnClickListener(this::onBadgeClick);
531
532        binding.detailsContactKeys.removeAllViews();
533        boolean hasKeys = false;
534        final LayoutInflater inflater = getLayoutInflater();
535        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
536        if (Config.supportOmemo() && axolotlService != null) {
537            final Collection<XmppAxolotlSession> sessions = axolotlService.findSessionsForContact(contact);
538            boolean anyActive = false;
539            for (XmppAxolotlSession session : sessions) {
540                anyActive = session.getTrust().isActive();
541                if (anyActive) {
542                    break;
543                }
544            }
545            boolean skippedInactive = false;
546            boolean showsInactive = false;
547            boolean showUnverifiedWarning = false;
548            for (final XmppAxolotlSession session : sessions) {
549                final FingerprintStatus trust = session.getTrust();
550                hasKeys |= !trust.isCompromised();
551                if (!trust.isActive() && anyActive) {
552                    if (showInactiveOmemo) {
553                        showsInactive = true;
554                    } else {
555                        skippedInactive = true;
556                        continue;
557                    }
558                }
559                if (!trust.isCompromised()) {
560                    boolean highlight = session.getFingerprint().equals(messageFingerprint);
561                    addFingerprintRow(binding.detailsContactKeys, session, highlight);
562                }
563                if (trust.isUnverified()) {
564                    showUnverifiedWarning = true;
565                }
566            }
567            binding.unverifiedWarning.setVisibility(showUnverifiedWarning ? View.VISIBLE : View.GONE);
568            if (showsInactive || skippedInactive) {
569                binding.showInactiveDevices.setText(showsInactive ? R.string.hide_inactive_devices : R.string.show_inactive_devices);
570                binding.showInactiveDevices.setVisibility(View.VISIBLE);
571            } else {
572                binding.showInactiveDevices.setVisibility(View.GONE);
573            }
574        } else {
575            binding.showInactiveDevices.setVisibility(View.GONE);
576        }
577        final boolean isCameraFeatureAvailable = isCameraFeatureAvailable();
578        binding.scanButton.setVisibility(hasKeys && isCameraFeatureAvailable ? View.VISIBLE : View.GONE);
579        if (hasKeys) {
580            binding.scanButton.setOnClickListener((v) -> ScanActivity.scan(this));
581        }
582        if (Config.supportOpenPgp() && contact.getPgpKeyId() != 0) {
583            hasKeys = true;
584            View view = inflater.inflate(R.layout.contact_key, binding.detailsContactKeys, false);
585            TextView key = view.findViewById(R.id.key);
586            TextView keyType = view.findViewById(R.id.key_type);
587            keyType.setText(R.string.openpgp_key_id);
588            if ("pgp".equals(messageFingerprint)) {
589                keyType.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
590            }
591            key.setText(OpenPgpUtils.convertKeyIdToHex(contact.getPgpKeyId()));
592            final OnClickListener openKey = v -> launchOpenKeyChain(contact.getPgpKeyId());
593            view.setOnClickListener(openKey);
594            key.setOnClickListener(openKey);
595            keyType.setOnClickListener(openKey);
596            binding.detailsContactKeys.addView(view);
597        }
598        binding.keysWrapper.setVisibility(hasKeys ? View.VISIBLE : View.GONE);
599
600        List<ListItem.Tag> tagList = contact.getTags(this);
601        if (tagList.size() == 0 || !this.showDynamicTags) {
602            binding.tags.setVisibility(View.GONE);
603        } else {
604            binding.tags.setVisibility(View.VISIBLE);
605            binding.tags.removeAllViewsInLayout();
606            for (final ListItem.Tag tag : tagList) {
607                final TextView tv = (TextView) inflater.inflate(R.layout.list_item_tag, binding.tags, false);
608                tv.setText(tag.getName());
609                tv.getBackground().mutate().setColorFilter(tag.getColor(), PorterDuff.Mode.SRC_IN);
610                binding.tags.addView(tv);
611            }
612        }
613    }
614
615    private void onBadgeClick(View view) {
616        final Uri systemAccount = contact.getSystemAccount();
617        if (systemAccount == null) {
618            checkContactPermissionAndShowAddDialog();
619        } else {
620            final Intent intent = new Intent(Intent.ACTION_VIEW);
621            intent.setData(systemAccount);
622            try {
623                startActivity(intent);
624            } catch (final ActivityNotFoundException e) {
625                Toast.makeText(this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
626            }
627        }
628    }
629
630    public void onBackendConnected() {
631        if (accountJid != null && contactJid != null) {
632            Account account = xmppConnectionService.findAccountByJid(accountJid);
633            if (account == null) {
634                return;
635            }
636            this.contact = account.getRoster().getContact(contactJid);
637            if (mPendingFingerprintVerificationUri != null) {
638                processFingerprintVerification(mPendingFingerprintVerificationUri);
639                mPendingFingerprintVerificationUri = null;
640            }
641
642            if (Compatibility.hasStoragePermission(this)) {
643                final int limit = GridManager.getCurrentColumnCount(this.binding.media);
644                xmppConnectionService.getAttachments(account, contact.getJid().asBareJid(), limit, this);
645                this.binding.showMedia.setOnClickListener((v) -> MediaBrowserActivity.launch(this, contact));
646            }
647
648            final VcardAdapter items = new VcardAdapter();
649            binding.profileItems.setAdapter(items);
650            binding.profileItems.setOnItemClickListener((a0, v, pos, a3) -> {
651                final Uri uri = items.getUri(pos);
652                if (uri == null) return;
653
654                if ("xmpp".equals(uri.getScheme())) {
655                    switchToConversation(xmppConnectionService.findOrCreateConversation(account, Jid.of(uri.getSchemeSpecificPart()), false, true));
656                } else {
657                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
658                    try {
659                        startActivity(intent);
660                    } catch (ActivityNotFoundException e) {
661                        Toast.makeText(this, R.string.no_application_found_to_open_link, Toast.LENGTH_SHORT).show();
662                    }
663                }
664            });
665            binding.profileItems.setOnItemLongClickListener((a0, v, pos, a3) -> {
666                String toCopy = null;
667                final Uri uri = items.getUri(pos);
668                if (uri != null) toCopy = uri.toString();
669                if (toCopy == null) {
670                    toCopy = items.getItem(pos).findChildContent("text", Namespace.VCARD4);
671                }
672
673                if (toCopy == null) return false;
674                if (ShareUtil.copyTextToClipboard(ContactDetailsActivity.this, toCopy, R.string.message)) {
675                    Toast.makeText(ContactDetailsActivity.this, R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
676                }
677                return true;
678            });
679            xmppConnectionService.fetchVcard4(account, contact, (vcard4) -> {
680                if (vcard4 == null) return;
681
682                runOnUiThread(() -> {
683                    for (Element el : vcard4.getChildren()) {
684                        if (el.findChildEnsureSingle("uri", Namespace.VCARD4) != null || el.findChildEnsureSingle("text", Namespace.VCARD4) != null) {
685                            items.add(el);
686                        }
687                    }
688                    Util.justifyListViewHeightBasedOnChildren(binding.profileItems);
689                });
690            });
691
692            populateView();
693        }
694    }
695
696    @Override
697    public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
698        refreshUi();
699    }
700
701    @Override
702    protected void processFingerprintVerification(XmppUri uri) {
703        if (contact != null && contact.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
704            if (xmppConnectionService.verifyFingerprints(contact, uri.getFingerprints())) {
705                Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
706            }
707        } else {
708            Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
709        }
710    }
711
712    @Override
713    public void onMediaLoaded(List<Attachment> attachments) {
714        runOnUiThread(() -> {
715            int limit = GridManager.getCurrentColumnCount(binding.media);
716            mMediaAdapter.setAttachments(attachments.subList(0, Math.min(limit, attachments.size())));
717            binding.mediaWrapper.setVisibility(attachments.size() > 0 ? View.VISIBLE : View.GONE);
718        });
719
720    }
721
722    class VcardAdapter extends ArrayAdapter<Element> {
723        VcardAdapter() { super(ContactDetailsActivity.this, 0); }
724
725        private Drawable getDrawable(int attr) {
726            final TypedValue typedvalueattr = new TypedValue();
727            getTheme().resolveAttribute(attr, typedvalueattr, true);
728            return getResources().getDrawable(typedvalueattr.resourceId);
729        }
730
731        @Override
732        public View getView(int position, View view, @NonNull ViewGroup parent) {
733            final CommandRowBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.command_row, parent, false);
734            final Element item = getItem(position);
735
736            if (item.getName().equals("org")) {
737                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_org), null, null, null);
738                binding.command.setCompoundDrawablePadding(20);
739            } else if (item.getName().equals("impp")) {
740                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_chat), null, null, null);
741                binding.command.setCompoundDrawablePadding(20);
742            } else if (item.getName().equals("url")) {
743                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_link), null, null, null);
744                binding.command.setCompoundDrawablePadding(20);
745            }
746
747            final Uri uri = getUri(position);
748            if (uri != null && uri.getScheme() != null) {
749                if (uri.getScheme().equals("xmpp")) {
750                    binding.command.setText(uri.getSchemeSpecificPart());
751                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.drawable.jabber), null, null, null);
752                    binding.command.setCompoundDrawablePadding(20);
753                } else if (uri.getScheme().equals("tel")) {
754                    binding.command.setText(uri.getSchemeSpecificPart());
755                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.ic_make_audio_call), null, null, null);
756                    binding.command.setCompoundDrawablePadding(20);
757                } else if (uri.getScheme().equals("mailto")) {
758                    binding.command.setText(uri.getSchemeSpecificPart());
759                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_email), null, null, null);
760                    binding.command.setCompoundDrawablePadding(20);
761                } else if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) {
762                    binding.command.setText(uri.toString());
763                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_link), null, null, null);
764                    binding.command.setCompoundDrawablePadding(20);
765                } else {
766                    binding.command.setText(uri.toString());
767                }
768            } else {
769                final String text = item.findChildContent("text", Namespace.VCARD4);
770                binding.command.setText(text);
771            }
772
773            return binding.getRoot();
774        }
775
776        public Uri getUri(int pos) {
777            final Element item = getItem(pos);
778            final String uriS = item.findChildContent("uri", Namespace.VCARD4);
779            if (uriS != null) return Uri.parse(uriS).normalizeScheme();
780            if (item.getName().equals("email")) return Uri.parse("mailto:" + item.findChildContent("text", Namespace.VCARD4));
781            return null;
782        }
783    }
784}