ContactDetailsActivity.java

  1package eu.siacs.conversations.ui;
  2
  3import android.Manifest;
  4import android.content.ActivityNotFoundException;
  5import android.content.DialogInterface;
  6import android.content.Intent;
  7import android.content.SharedPreferences;
  8import android.content.pm.PackageManager;
  9import android.content.res.ColorStateList;
 10import android.net.Uri;
 11import android.os.Build;
 12import android.os.Bundle;
 13import android.preference.PreferenceManager;
 14import android.provider.ContactsContract.CommonDataKinds;
 15import android.provider.ContactsContract.Contacts;
 16import android.provider.ContactsContract.Intents;
 17import android.provider.Settings;
 18import android.text.Spannable;
 19import android.text.SpannableString;
 20import android.text.style.RelativeSizeSpan;
 21import android.util.Log;
 22import android.view.LayoutInflater;
 23import android.view.Menu;
 24import android.view.MenuItem;
 25import android.view.View;
 26import android.view.View.OnClickListener;
 27import android.widget.CompoundButton;
 28import android.widget.CompoundButton.OnCheckedChangeListener;
 29import android.widget.TextView;
 30import android.widget.Toast;
 31import androidx.annotation.NonNull;
 32import androidx.core.content.ContextCompat;
 33import androidx.core.view.ViewCompat;
 34import androidx.databinding.DataBindingUtil;
 35import com.google.android.material.color.MaterialColors;
 36import com.google.android.material.dialog.MaterialAlertDialogBuilder;
 37import com.google.common.base.Joiner;
 38import com.google.common.collect.ImmutableList;
 39import com.google.common.collect.Iterables;
 40import com.google.common.primitives.Ints;
 41import eu.siacs.conversations.AppSettings;
 42import eu.siacs.conversations.Config;
 43import eu.siacs.conversations.R;
 44import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 45import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
 46import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
 47import eu.siacs.conversations.databinding.ActivityContactDetailsBinding;
 48import eu.siacs.conversations.entities.Account;
 49import eu.siacs.conversations.entities.Contact;
 50import eu.siacs.conversations.entities.ListItem;
 51import eu.siacs.conversations.services.AbstractQuickConversationsService;
 52import eu.siacs.conversations.services.QuickConversationsService;
 53import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
 54import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
 55import eu.siacs.conversations.ui.adapter.MediaAdapter;
 56import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
 57import eu.siacs.conversations.ui.util.Attachment;
 58import eu.siacs.conversations.ui.util.AvatarWorkerTask;
 59import eu.siacs.conversations.ui.util.GridManager;
 60import eu.siacs.conversations.ui.util.JidDialog;
 61import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 62import eu.siacs.conversations.utils.AccountUtils;
 63import eu.siacs.conversations.utils.Compatibility;
 64import eu.siacs.conversations.utils.Emoticons;
 65import eu.siacs.conversations.utils.IrregularUnicodeDetector;
 66import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
 67import eu.siacs.conversations.utils.UIHelper;
 68import eu.siacs.conversations.utils.XEP0392Helper;
 69import eu.siacs.conversations.utils.XmppUri;
 70import eu.siacs.conversations.xml.Namespace;
 71import eu.siacs.conversations.xmpp.Jid;
 72import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 73import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 74import eu.siacs.conversations.xmpp.XmppConnection;
 75import eu.siacs.conversations.xmpp.manager.PresenceManager;
 76import eu.siacs.conversations.xmpp.manager.RosterManager;
 77import im.conversations.android.xmpp.model.stanza.Presence;
 78import java.util.Collection;
 79import java.util.Collections;
 80import java.util.List;
 81import org.openintents.openpgp.util.OpenPgpUtils;
 82
 83public class ContactDetailsActivity extends OmemoActivity
 84        implements OnAccountUpdate,
 85                OnRosterUpdate,
 86                OnUpdateBlocklist,
 87                OnKeyStatusUpdated,
 88                OnMediaLoaded {
 89    public static final String ACTION_VIEW_CONTACT = "view_contact";
 90    private final int REQUEST_SYNC_CONTACTS = 0x28cf;
 91    ActivityContactDetailsBinding binding;
 92    private MediaAdapter mMediaAdapter;
 93
 94    private Contact contact;
 95    private final DialogInterface.OnClickListener removeFromRoster =
 96            new DialogInterface.OnClickListener() {
 97
 98                @Override
 99                public void onClick(DialogInterface dialog, int which) {
100                    xmppConnectionService.deleteContactOnServer(contact);
101                }
102            };
103    private final OnCheckedChangeListener mOnSendCheckedChange =
104            new OnCheckedChangeListener() {
105
106                @Override
107                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
108                    if (isChecked) {
109                        if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
110                            xmppConnectionService.stopPresenceUpdatesTo(contact);
111                        } else {
112                            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
113                        }
114                    } else {
115                        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
116                        final var connection = contact.getAccount().getXmppConnection();
117                        connection
118                                .getManager(PresenceManager.class)
119                                .unsubscribed(contact.getJid().asBareJid());
120                    }
121                }
122            };
123    private final OnCheckedChangeListener mOnReceiveCheckedChange =
124            new OnCheckedChangeListener() {
125
126                @Override
127                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
128                    final var connection = contact.getAccount().getXmppConnection();
129                    if (isChecked) {
130                        connection
131                                .getManager(PresenceManager.class)
132                                .subscribe(contact.getJid().asBareJid());
133                    } else {
134                        connection
135                                .getManager(PresenceManager.class)
136                                .unsubscribe(contact.getJid().asBareJid());
137                    }
138                }
139            };
140    private Jid accountJid;
141    private Jid contactJid;
142    private boolean showDynamicTags = false;
143    private boolean showLastSeen = false;
144    private boolean showInactiveOmemo = false;
145    private String messageFingerprint;
146
147    private void checkContactPermissionAndShowAddDialog() {
148        if (hasContactsPermission()) {
149            showAddToPhoneBookDialog();
150        } else if (QuickConversationsService.isContactListIntegration(this)) {
151            requestPermissions(
152                    new String[] {Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
153        }
154    }
155
156    private boolean hasContactsPermission() {
157        if (QuickConversationsService.isContactListIntegration(this)) {
158            return checkSelfPermission(Manifest.permission.READ_CONTACTS)
159                    == PackageManager.PERMISSION_GRANTED;
160        } else {
161            return true;
162        }
163    }
164
165    private void showAddToPhoneBookDialog() {
166        final Jid jid = contact.getJid();
167        final boolean quicksyContact =
168                AbstractQuickConversationsService.isQuicksy()
169                        && Config.QUICKSY_DOMAIN.equals(jid.getDomain())
170                        && jid.getLocal() != null;
171        final String value;
172        if (quicksyContact) {
173            value = PhoneNumberUtilWrapper.toFormattedPhoneNumber(this, jid);
174        } else {
175            value = jid.toString();
176        }
177        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
178        builder.setTitle(getString(R.string.save_to_contact));
179        builder.setMessage(getString(R.string.add_phone_book_text, value));
180        builder.setNegativeButton(getString(R.string.cancel), null);
181        builder.setPositiveButton(
182                getString(R.string.add),
183                (dialog, which) -> {
184                    final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
185                    intent.setType(Contacts.CONTENT_ITEM_TYPE);
186                    if (quicksyContact) {
187                        intent.putExtra(Intents.Insert.PHONE, value);
188                    } else {
189                        intent.putExtra(Intents.Insert.IM_HANDLE, value);
190                        intent.putExtra(
191                                Intents.Insert.IM_PROTOCOL, CommonDataKinds.Im.PROTOCOL_JABBER);
192                        // TODO for modern use we want PROTOCOL_CUSTOM and an extra field with a
193                        // value of 'XMPP'
194                        // however we don’t have such a field and thus have to use the legacy
195                        // PROTOCOL_JABBER
196                    }
197                    intent.putExtra("finishActivityOnSaveCompleted", true);
198                    try {
199                        startActivityForResult(intent, 0);
200                    } catch (ActivityNotFoundException e) {
201                        Toast.makeText(
202                                        ContactDetailsActivity.this,
203                                        R.string.no_application_found_to_view_contact,
204                                        Toast.LENGTH_SHORT)
205                                .show();
206                    }
207                });
208        builder.create().show();
209    }
210
211    @Override
212    public void onRosterUpdate() {
213        refreshUi();
214    }
215
216    @Override
217    public void onAccountUpdate() {
218        refreshUi();
219    }
220
221    @Override
222    public void OnUpdateBlocklist(final Status status) {
223        refreshUi();
224    }
225
226    @Override
227    protected void refreshUiReal() {
228        invalidateOptionsMenu();
229        populateView();
230    }
231
232    @Override
233    protected String getShareableUri(boolean http) {
234        if (http) {
235            return "https://conversations.im/i/"
236                    + XmppUri.lameUrlEncode(contact.getJid().asBareJid().toString());
237        } else {
238            return "xmpp:" + contact.getJid().asBareJid().toString();
239        }
240    }
241
242    @Override
243    protected void onCreate(final Bundle savedInstanceState) {
244        super.onCreate(savedInstanceState);
245        showInactiveOmemo =
246                savedInstanceState != null
247                        && savedInstanceState.getBoolean("show_inactive_omemo", false);
248        if (getIntent().getAction().equals(ACTION_VIEW_CONTACT)) {
249            try {
250                this.accountJid = Jid.of(getIntent().getExtras().getString(EXTRA_ACCOUNT));
251            } catch (final IllegalArgumentException ignored) {
252            }
253            try {
254                this.contactJid = Jid.of(getIntent().getExtras().getString("contact"));
255            } catch (final IllegalArgumentException ignored) {
256            }
257        }
258        this.messageFingerprint = getIntent().getStringExtra("fingerprint");
259        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_details);
260        Activities.setStatusAndNavigationBarColors(this, binding.getRoot());
261
262        setSupportActionBar(binding.toolbar);
263        configureActionBar(getSupportActionBar());
264        binding.showInactiveDevices.setOnClickListener(
265                v -> {
266                    showInactiveOmemo = !showInactiveOmemo;
267                    populateView();
268                });
269        binding.addContactButton.setOnClickListener(v -> showAddToRosterDialog(contact));
270
271        mMediaAdapter = new MediaAdapter(this, R.dimen.media_size);
272        this.binding.media.setAdapter(mMediaAdapter);
273        GridManager.setupLayoutManager(this, this.binding.media, R.dimen.media_size);
274    }
275
276    @Override
277    public void onSaveInstanceState(final Bundle savedInstanceState) {
278        savedInstanceState.putBoolean("show_inactive_omemo", showInactiveOmemo);
279        super.onSaveInstanceState(savedInstanceState);
280    }
281
282    @Override
283    public void onStart() {
284        super.onStart();
285        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
286        this.showDynamicTags = preferences.getBoolean(AppSettings.SHOW_DYNAMIC_TAGS, false);
287        this.showLastSeen = preferences.getBoolean("last_activity", false);
288        binding.mediaWrapper.setVisibility(
289                Compatibility.hasStoragePermission(this) ? View.VISIBLE : View.GONE);
290        mMediaAdapter.setAttachments(Collections.emptyList());
291    }
292
293    @Override
294    public void onRequestPermissionsResult(
295            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
296        // TODO check for Camera / Scan permission
297        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
298        if (grantResults.length == 0) {
299            return;
300        }
301        if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
302            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
303                showAddToPhoneBookDialog();
304                xmppConnectionService.loadPhoneContacts();
305                xmppConnectionService.startContactObserver();
306            } else {
307                showRedirectToAppSettings();
308            }
309        }
310    }
311
312    private void showRedirectToAppSettings() {
313        final var dialogBuilder = new MaterialAlertDialogBuilder(this);
314        dialogBuilder.setTitle(R.string.save_to_contact);
315        dialogBuilder.setMessage(
316                getString(R.string.no_contacts_permission, getString(R.string.app_name)));
317        dialogBuilder.setPositiveButton(
318                R.string.continue_btn,
319                (d, w) -> {
320                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
321                    Uri uri = Uri.fromParts("package", getPackageName(), null);
322                    intent.setData(uri);
323                    startActivity(intent);
324                });
325        dialogBuilder.setNegativeButton(R.string.cancel, null);
326        dialogBuilder.create().show();
327    }
328
329    @Override
330    public boolean onOptionsItemSelected(final MenuItem menuItem) {
331        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
332            return false;
333        }
334        switch (menuItem.getItemId()) {
335            case android.R.id.home:
336                finish();
337                break;
338            case R.id.action_share_http:
339                shareLink(true);
340                break;
341            case R.id.action_share_uri:
342                shareLink(false);
343                break;
344            case R.id.action_delete_contact:
345                final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
346                builder.setNegativeButton(getString(R.string.cancel), null);
347                builder.setTitle(getString(R.string.action_delete_contact))
348                        .setMessage(
349                                JidDialog.style(
350                                        this,
351                                        R.string.remove_contact_text,
352                                        contact.getJid().toString()))
353                        .setPositiveButton(getString(R.string.delete), removeFromRoster)
354                        .create()
355                        .show();
356                break;
357            case R.id.action_edit_contact:
358                final Uri systemAccount = contact.getSystemAccount();
359                if (systemAccount == null) {
360                    quickEdit(
361                            contact.getServerName(),
362                            R.string.contact_name,
363                            value -> {
364                                contact.setServerName(value);
365                                final var connection = contact.getAccount().getXmppConnection();
366                                connection
367                                        .getManager(RosterManager.class)
368                                        .addRosterItem(contact, null);
369                                populateView();
370                                return null;
371                            },
372                            true);
373                } else {
374                    Intent intent = new Intent(Intent.ACTION_EDIT);
375                    intent.setDataAndType(systemAccount, Contacts.CONTENT_ITEM_TYPE);
376                    intent.putExtra("finishActivityOnSaveCompleted", true);
377                    try {
378                        startActivity(intent);
379                    } catch (ActivityNotFoundException e) {
380                        Toast.makeText(
381                                        ContactDetailsActivity.this,
382                                        R.string.no_application_found_to_view_contact,
383                                        Toast.LENGTH_SHORT)
384                                .show();
385                    }
386                }
387                break;
388            case R.id.action_block, R.id.action_unblock:
389                BlockContactDialog.show(this, contact);
390                break;
391            case R.id.action_custom_notifications:
392                configureCustomNotifications(contact);
393                break;
394        }
395        return super.onOptionsItemSelected(menuItem);
396    }
397
398    private void configureCustomNotifications(final Contact contact) {
399        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
400            return;
401        }
402        final var shortcut = xmppConnectionService.getShortcutService().getShortcutInfo(contact);
403        configureCustomNotification(shortcut);
404    }
405
406    @Override
407    public boolean onCreateOptionsMenu(final Menu menu) {
408        getMenuInflater().inflate(R.menu.contact_details, menu);
409        AccountUtils.showHideMenuItems(menu);
410        final MenuItem block = menu.findItem(R.id.action_block);
411        final MenuItem unblock = menu.findItem(R.id.action_unblock);
412        final MenuItem edit = menu.findItem(R.id.action_edit_contact);
413        final MenuItem delete = menu.findItem(R.id.action_delete_contact);
414        final MenuItem customNotifications = menu.findItem(R.id.action_custom_notifications);
415        customNotifications.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R);
416        if (contact == null) {
417            return true;
418        }
419        final XmppConnection connection = contact.getAccount().getXmppConnection();
420        if (connection != null && connection.getFeatures().blocking()) {
421            if (this.contact.isBlocked()) {
422                block.setVisible(false);
423            } else {
424                unblock.setVisible(false);
425            }
426        } else {
427            unblock.setVisible(false);
428            block.setVisible(false);
429        }
430        if (!contact.showInRoster()) {
431            edit.setVisible(false);
432            delete.setVisible(false);
433        }
434        return super.onCreateOptionsMenu(menu);
435    }
436
437    private void populateView() {
438        if (contact == null) {
439            return;
440        }
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            Collection<String> statusMessages = contact.getPresences().getStatusMessages();
451            if (statusMessages.isEmpty()) {
452                binding.statusMessage.setVisibility(View.GONE);
453            } else if (statusMessages.size() == 1) {
454                final String message = Iterables.getOnlyElement(statusMessages);
455                binding.statusMessage.setVisibility(View.VISIBLE);
456                final Spannable span = new SpannableString(message);
457                if (Emoticons.isOnlyEmoji(message)) {
458                    span.setSpan(
459                            new RelativeSizeSpan(2.0f),
460                            0,
461                            message.length(),
462                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
463                }
464                binding.statusMessage.setText(span);
465            } else {
466                binding.statusMessage.setText(Joiner.on('\n').join(statusMessages));
467            }
468
469            if (contact.getOption(Contact.Options.FROM)) {
470                binding.detailsSendPresence.setText(R.string.send_presence_updates);
471                binding.detailsSendPresence.setChecked(true);
472            } else if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
473                binding.detailsSendPresence.setChecked(false);
474                binding.detailsSendPresence.setText(R.string.send_presence_updates);
475            } else {
476                binding.detailsSendPresence.setText(R.string.preemptively_grant);
477                binding.detailsSendPresence.setChecked(
478                        contact.getOption(Contact.Options.PREEMPTIVE_GRANT));
479            }
480            if (contact.getOption(Contact.Options.TO)) {
481                binding.detailsReceivePresence.setText(R.string.receive_presence_updates);
482                binding.detailsReceivePresence.setChecked(true);
483            } else {
484                binding.detailsReceivePresence.setText(R.string.ask_for_presence_updates);
485                binding.detailsReceivePresence.setChecked(
486                        contact.getOption(Contact.Options.ASKING));
487            }
488            if (contact.getAccount().isOnlineAndConnected()) {
489                binding.detailsReceivePresence.setEnabled(true);
490                binding.detailsSendPresence.setEnabled(true);
491            } else {
492                binding.detailsReceivePresence.setEnabled(false);
493                binding.detailsSendPresence.setEnabled(false);
494            }
495            binding.detailsSendPresence.setOnCheckedChangeListener(this.mOnSendCheckedChange);
496            binding.detailsReceivePresence.setOnCheckedChangeListener(this.mOnReceiveCheckedChange);
497        } else {
498            binding.addContactButton.setVisibility(View.VISIBLE);
499            binding.detailsSendPresence.setVisibility(View.GONE);
500            binding.detailsReceivePresence.setVisibility(View.GONE);
501            binding.statusMessage.setVisibility(View.GONE);
502        }
503
504        if (contact.isBlocked() && !this.showDynamicTags) {
505            binding.detailsLastSeen.setVisibility(View.VISIBLE);
506            binding.detailsLastSeen.setText(R.string.contact_blocked);
507        } else {
508            if (showLastSeen
509                    && contact.getLastseen() > 0
510                    && contact.getPresences().allOrNonSupport(Namespace.IDLE)) {
511                binding.detailsLastSeen.setVisibility(View.VISIBLE);
512                binding.detailsLastSeen.setText(
513                        UIHelper.lastseen(
514                                getApplicationContext(),
515                                contact.isActive(),
516                                contact.getLastseen()));
517            } else {
518                binding.detailsLastSeen.setVisibility(View.GONE);
519            }
520        }
521
522        binding.detailsContactXmppAddress.setText(
523                IrregularUnicodeDetector.style(this, contact.getJid()));
524        final String account = contact.getAccount().getJid().asBareJid().toString();
525        binding.detailsAccount.setText(getString(R.string.using_account, account));
526        AvatarWorkerTask.loadAvatar(
527                contact, binding.detailsContactBadge, R.dimen.avatar_on_details_screen_size);
528        binding.detailsContactBadge.setOnClickListener(this::onBadgeClick);
529        if (QuickConversationsService.isContactListIntegration(this)) {
530            if (contact.getSystemAccount() == null) {
531                binding.addAddressBook.setText(R.string.save_to_contact);
532            } else {
533                binding.addAddressBook.setText(R.string.show_in_contacts);
534            }
535            binding.addAddressBook.setVisibility(View.VISIBLE);
536            binding.addAddressBook.setOnClickListener(this::onAddToAddressBookClick);
537        } else {
538            binding.addAddressBook.setVisibility(View.GONE);
539        }
540
541        binding.detailsContactKeys.removeAllViews();
542        boolean hasKeys = false;
543        final LayoutInflater inflater = getLayoutInflater();
544        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
545        if (Config.supportOmemo() && axolotlService != null) {
546            final Collection<XmppAxolotlSession> sessions =
547                    axolotlService.findSessionsForContact(contact);
548            boolean anyActive = false;
549            for (XmppAxolotlSession session : sessions) {
550                anyActive = session.getTrust().isActive();
551                if (anyActive) {
552                    break;
553                }
554            }
555            boolean skippedInactive = false;
556            boolean showsInactive = false;
557            boolean showUnverifiedWarning = false;
558            for (final XmppAxolotlSession session : sessions) {
559                final FingerprintStatus trust = session.getTrust();
560                hasKeys |= !trust.isCompromised();
561                if (!trust.isActive() && anyActive) {
562                    if (showInactiveOmemo) {
563                        showsInactive = true;
564                    } else {
565                        skippedInactive = true;
566                        continue;
567                    }
568                }
569                if (!trust.isCompromised()) {
570                    boolean highlight = session.getFingerprint().equals(messageFingerprint);
571                    addFingerprintRow(binding.detailsContactKeys, session, highlight);
572                }
573                if (trust.isUnverified()) {
574                    showUnverifiedWarning = true;
575                }
576            }
577            binding.unverifiedWarning.setVisibility(
578                    showUnverifiedWarning ? View.VISIBLE : View.GONE);
579            if (showsInactive || skippedInactive) {
580                binding.showInactiveDevices.setText(
581                        showsInactive
582                                ? R.string.hide_inactive_devices
583                                : R.string.show_inactive_devices);
584                binding.showInactiveDevices.setVisibility(View.VISIBLE);
585            } else {
586                binding.showInactiveDevices.setVisibility(View.GONE);
587            }
588        } else {
589            binding.showInactiveDevices.setVisibility(View.GONE);
590        }
591        final boolean isCameraFeatureAvailable = isCameraFeatureAvailable();
592        binding.scanButton.setVisibility(
593                hasKeys && isCameraFeatureAvailable ? View.VISIBLE : View.GONE);
594        if (hasKeys) {
595            binding.scanButton.setOnClickListener((v) -> ScanActivity.scan(this));
596        }
597        if (Config.supportOpenPgp() && contact.getPgpKeyId() != 0) {
598            hasKeys = true;
599            View view =
600                    inflater.inflate(
601                            R.layout.item_device_fingerprint, binding.detailsContactKeys, false);
602            TextView key = view.findViewById(R.id.key);
603            TextView keyType = view.findViewById(R.id.key_type);
604            keyType.setText(R.string.openpgp_key_id);
605            if ("pgp".equals(messageFingerprint)) {
606                keyType.setTextColor(
607                        MaterialColors.getColor(
608                                keyType, com.google.android.material.R.attr.colorPrimaryVariant));
609            }
610            key.setText(OpenPgpUtils.convertKeyIdToHex(contact.getPgpKeyId()));
611            final OnClickListener openKey = v -> launchOpenKeyChain(contact.getPgpKeyId());
612            view.setOnClickListener(openKey);
613            key.setOnClickListener(openKey);
614            keyType.setOnClickListener(openKey);
615            binding.detailsContactKeys.addView(view);
616        }
617        binding.keysWrapper.setVisibility(hasKeys ? View.VISIBLE : View.GONE);
618
619        final List<ListItem.Tag> tagList = contact.getTags(this);
620        final boolean hasMetaTags =
621                contact.isBlocked() || contact.getShownStatus() != Presence.Availability.OFFLINE;
622        if ((tagList.isEmpty() && !hasMetaTags) || !this.showDynamicTags) {
623            binding.tags.setVisibility(View.GONE);
624        } else {
625            binding.tags.setVisibility(View.VISIBLE);
626            binding.tags.removeViews(1, binding.tags.getChildCount() - 1);
627            final ImmutableList.Builder<Integer> viewIdBuilder = new ImmutableList.Builder<>();
628            for (final ListItem.Tag tag : tagList) {
629                final String name = tag.getName();
630                final TextView tv =
631                        (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
632                tv.setText(name);
633                tv.setBackgroundTintList(
634                        ColorStateList.valueOf(
635                                MaterialColors.harmonizeWithPrimary(
636                                        this, XEP0392Helper.rgbFromNick(name))));
637                final int id = ViewCompat.generateViewId();
638                tv.setId(id);
639                viewIdBuilder.add(id);
640                binding.tags.addView(tv);
641            }
642            if (contact.isBlocked()) {
643                final TextView tv =
644                        (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
645                tv.setText(R.string.blocked);
646                tv.setBackgroundTintList(
647                        ColorStateList.valueOf(
648                                MaterialColors.harmonizeWithPrimary(
649                                        tv.getContext(),
650                                        ContextCompat.getColor(
651                                                tv.getContext(), R.color.gray_800))));
652                final int id = ViewCompat.generateViewId();
653                tv.setId(id);
654                viewIdBuilder.add(id);
655                binding.tags.addView(tv);
656            } else {
657                final Presence.Availability status = contact.getShownStatus();
658                if (status != Presence.Availability.OFFLINE) {
659                    final TextView tv =
660                            (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
661                    UIHelper.setStatus(tv, status);
662                    final int id = ViewCompat.generateViewId();
663                    tv.setId(id);
664                    viewIdBuilder.add(id);
665                    binding.tags.addView(tv);
666                }
667            }
668            binding.flowWidget.setReferencedIds(Ints.toArray(viewIdBuilder.build()));
669        }
670    }
671
672    private void onBadgeClick(final View view) {
673        final var intent = new Intent(this, ViewProfilePictureActivity.class);
674        intent.setData(Uri.fromParts("avatar", contact.getAvatar(), null));
675        intent.putExtra(ViewProfilePictureActivity.EXTRA_DISPLAY_NAME, contact.getDisplayName());
676        startActivity(intent);
677    }
678
679    private void onAddToAddressBookClick(final View view) {
680        if (QuickConversationsService.isContactListIntegration(this)) {
681            final Uri systemAccount = contact.getSystemAccount();
682            if (systemAccount == null) {
683                checkContactPermissionAndShowAddDialog();
684            } else {
685                final Intent intent = new Intent(Intent.ACTION_VIEW);
686                intent.setData(systemAccount);
687                try {
688                    startActivity(intent);
689                } catch (final ActivityNotFoundException e) {
690                    Toast.makeText(
691                                    this,
692                                    R.string.no_application_found_to_view_contact,
693                                    Toast.LENGTH_SHORT)
694                            .show();
695                }
696            }
697        } else {
698            Toast.makeText(
699                            this,
700                            R.string.contact_list_integration_not_available,
701                            Toast.LENGTH_SHORT)
702                    .show();
703        }
704    }
705
706    public void onBackendConnected() {
707        if (accountJid != null && contactJid != null) {
708            Account account = xmppConnectionService.findAccountByJid(accountJid);
709            if (account == null) {
710                return;
711            }
712            this.contact = account.getRoster().getContact(contactJid);
713            if (mPendingFingerprintVerificationUri != null) {
714                processFingerprintVerification(mPendingFingerprintVerificationUri);
715                mPendingFingerprintVerificationUri = null;
716            }
717
718            if (Compatibility.hasStoragePermission(this)) {
719                final int limit = GridManager.getCurrentColumnCount(this.binding.media);
720                xmppConnectionService.getAttachments(
721                        account, contact.getJid().asBareJid(), limit, this);
722                this.binding.showMedia.setOnClickListener(
723                        (v) -> MediaBrowserActivity.launch(this, contact));
724            }
725            populateView();
726        }
727    }
728
729    @Override
730    public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
731        refreshUi();
732    }
733
734    @Override
735    protected void processFingerprintVerification(XmppUri uri) {
736        if (contact != null
737                && contact.getJid().asBareJid().equals(uri.getJid())
738                && uri.hasFingerprints()) {
739            if (xmppConnectionService.verifyFingerprints(contact, uri.getFingerprints())) {
740                Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
741            }
742        } else {
743            Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
744        }
745    }
746
747    @Override
748    public void onMediaLoaded(List<Attachment> attachments) {
749        runOnUiThread(
750                () -> {
751                    int limit = GridManager.getCurrentColumnCount(binding.media);
752                    mMediaAdapter.setAttachments(
753                            attachments.subList(0, Math.min(limit, attachments.size())));
754                    binding.mediaWrapper.setVisibility(
755                            attachments.size() > 0 ? View.VISIBLE : View.GONE);
756                });
757    }
758}