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