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