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            for (final XmppAxolotlSession session : sessions) {
547                final FingerprintStatus trust = session.getTrust();
548                hasKeys |= !trust.isCompromised();
549                if (!trust.isActive() && anyActive) {
550                    if (showInactiveOmemo) {
551                        showsInactive = true;
552                    } else {
553                        skippedInactive = true;
554                        continue;
555                    }
556                }
557                if (!trust.isCompromised()) {
558                    boolean highlight = session.getFingerprint().equals(messageFingerprint);
559                    addFingerprintRow(binding.detailsContactKeys, session, highlight);
560                }
561            }
562            if (showsInactive || skippedInactive) {
563                binding.showInactiveDevices.setText(showsInactive ? R.string.hide_inactive_devices : R.string.show_inactive_devices);
564                binding.showInactiveDevices.setVisibility(View.VISIBLE);
565            } else {
566                binding.showInactiveDevices.setVisibility(View.GONE);
567            }
568        } else {
569            binding.showInactiveDevices.setVisibility(View.GONE);
570        }
571        binding.scanButton.setVisibility(hasKeys && isCameraFeatureAvailable() ? View.VISIBLE : View.GONE);
572        if (hasKeys) {
573            binding.scanButton.setOnClickListener((v) -> ScanActivity.scan(this));
574        }
575        if (Config.supportOpenPgp() && contact.getPgpKeyId() != 0) {
576            hasKeys = true;
577            View view = inflater.inflate(R.layout.contact_key, binding.detailsContactKeys, false);
578            TextView key = view.findViewById(R.id.key);
579            TextView keyType = view.findViewById(R.id.key_type);
580            keyType.setText(R.string.openpgp_key_id);
581            if ("pgp".equals(messageFingerprint)) {
582                keyType.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
583            }
584            key.setText(OpenPgpUtils.convertKeyIdToHex(contact.getPgpKeyId()));
585            final OnClickListener openKey = v -> launchOpenKeyChain(contact.getPgpKeyId());
586            view.setOnClickListener(openKey);
587            key.setOnClickListener(openKey);
588            keyType.setOnClickListener(openKey);
589            binding.detailsContactKeys.addView(view);
590        }
591        binding.keysWrapper.setVisibility(hasKeys ? View.VISIBLE : View.GONE);
592
593        List<ListItem.Tag> tagList = contact.getTags(this);
594        if (tagList.size() == 0 || !this.showDynamicTags) {
595            binding.tags.setVisibility(View.GONE);
596        } else {
597            binding.tags.setVisibility(View.VISIBLE);
598            binding.tags.removeAllViewsInLayout();
599            for (final ListItem.Tag tag : tagList) {
600                final TextView tv = (TextView) inflater.inflate(R.layout.list_item_tag, binding.tags, false);
601                tv.setText(tag.getName());
602                tv.setBackgroundColor(tag.getColor());
603                binding.tags.addView(tv);
604            }
605        }
606    }
607
608    private void onBadgeClick(View view) {
609        final Uri systemAccount = contact.getSystemAccount();
610        if (systemAccount == null) {
611            checkContactPermissionAndShowAddDialog();
612        } else {
613            final Intent intent = new Intent(Intent.ACTION_VIEW);
614            intent.setData(systemAccount);
615            try {
616                startActivity(intent);
617            } catch (final ActivityNotFoundException e) {
618                Toast.makeText(this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
619            }
620        }
621    }
622
623    public void onBackendConnected() {
624        if (accountJid != null && contactJid != null) {
625            Account account = xmppConnectionService.findAccountByJid(accountJid);
626            if (account == null) {
627                return;
628            }
629            this.contact = account.getRoster().getContact(contactJid);
630            if (mPendingFingerprintVerificationUri != null) {
631                processFingerprintVerification(mPendingFingerprintVerificationUri);
632                mPendingFingerprintVerificationUri = null;
633            }
634
635            if (Compatibility.hasStoragePermission(this)) {
636                final int limit = GridManager.getCurrentColumnCount(this.binding.media);
637                xmppConnectionService.getAttachments(account, contact.getJid().asBareJid(), limit, this);
638                this.binding.showMedia.setOnClickListener((v) -> MediaBrowserActivity.launch(this, contact));
639            }
640
641            final VcardAdapter items = new VcardAdapter();
642            binding.profileItems.setAdapter(items);
643            binding.profileItems.setOnItemClickListener((a0, v, pos, a3) -> {
644                final Uri uri = items.getUri(pos);
645                if (uri == null) return;
646
647                if ("xmpp".equals(uri.getScheme())) {
648                    switchToConversation(xmppConnectionService.findOrCreateConversation(account, Jid.of(uri.getSchemeSpecificPart()), false, true));
649                } else {
650                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
651                    try {
652                        startActivity(intent);
653                    } catch (ActivityNotFoundException e) {
654                        Toast.makeText(this, R.string.no_application_found_to_open_link, Toast.LENGTH_SHORT).show();
655                    }
656                }
657            });
658            binding.profileItems.setOnItemLongClickListener((a0, v, pos, a3) -> {
659                String toCopy = null;
660                final Uri uri = items.getUri(pos);
661                if (uri != null) toCopy = uri.toString();
662                if (toCopy == null) {
663                    toCopy = items.getItem(pos).findChildContent("text", Namespace.VCARD4);
664                }
665
666                if (toCopy == null) return false;
667                if (ShareUtil.copyTextToClipboard(ContactDetailsActivity.this, toCopy, R.string.message)) {
668                    Toast.makeText(ContactDetailsActivity.this, R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
669                }
670                return true;
671            });
672            xmppConnectionService.fetchVcard4(account, contact, (vcard4) -> {
673                if (vcard4 == null) return;
674
675                runOnUiThread(() -> {
676                    for (Element el : vcard4.getChildren()) {
677                        if (el.findChildEnsureSingle("uri", Namespace.VCARD4) != null || el.findChildEnsureSingle("text", Namespace.VCARD4) != null) {
678                            items.add(el);
679                        }
680                    }
681                    Util.justifyListViewHeightBasedOnChildren(binding.profileItems);
682                });
683            });
684
685            populateView();
686        }
687    }
688
689    @Override
690    public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
691        refreshUi();
692    }
693
694    @Override
695    protected void processFingerprintVerification(XmppUri uri) {
696        if (contact != null && contact.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
697            if (xmppConnectionService.verifyFingerprints(contact, uri.getFingerprints())) {
698                Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
699            }
700        } else {
701            Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
702        }
703    }
704
705    @Override
706    public void onMediaLoaded(List<Attachment> attachments) {
707        runOnUiThread(() -> {
708            int limit = GridManager.getCurrentColumnCount(binding.media);
709            mMediaAdapter.setAttachments(attachments.subList(0, Math.min(limit, attachments.size())));
710            binding.mediaWrapper.setVisibility(attachments.size() > 0 ? View.VISIBLE : View.GONE);
711        });
712
713    }
714
715    class VcardAdapter extends ArrayAdapter<Element> {
716        VcardAdapter() { super(ContactDetailsActivity.this, 0); }
717
718        private Drawable getDrawable(int attr) {
719            final TypedValue typedvalueattr = new TypedValue();
720            getTheme().resolveAttribute(attr, typedvalueattr, true);
721            return getResources().getDrawable(typedvalueattr.resourceId);
722        }
723
724        @Override
725        public View getView(int position, View view, @NonNull ViewGroup parent) {
726            final CommandRowBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.command_row, parent, false);
727            final Element item = getItem(position);
728
729            if (item.getName().equals("org")) {
730                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_org), null, null, null);
731                binding.command.setCompoundDrawablePadding(20);
732            } else if (item.getName().equals("impp")) {
733                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_chat), null, null, null);
734                binding.command.setCompoundDrawablePadding(20);
735            } else if (item.getName().equals("url")) {
736                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_link), null, null, null);
737                binding.command.setCompoundDrawablePadding(20);
738            }
739
740            final Uri uri = getUri(position);
741            if (uri != null && uri.getScheme() != null) {
742                if (uri.getScheme().equals("xmpp")) {
743                    binding.command.setText(uri.getSchemeSpecificPart());
744                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.drawable.jabber), null, null, null);
745                    binding.command.setCompoundDrawablePadding(20);
746                } else if (uri.getScheme().equals("tel")) {
747                    binding.command.setText(uri.getSchemeSpecificPart());
748                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.ic_make_audio_call), null, null, null);
749                    binding.command.setCompoundDrawablePadding(20);
750                } else if (uri.getScheme().equals("mailto")) {
751                    binding.command.setText(uri.getSchemeSpecificPart());
752                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_email), null, null, null);
753                    binding.command.setCompoundDrawablePadding(20);
754                } else if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) {
755                    binding.command.setText(uri.toString());
756                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_link), null, null, null);
757                    binding.command.setCompoundDrawablePadding(20);
758                } else {
759                    binding.command.setText(uri.toString());
760                }
761            } else {
762                final String text = item.findChildContent("text", Namespace.VCARD4);
763                binding.command.setText(text);
764            }
765
766            return binding.getRoot();
767        }
768
769        public Uri getUri(int pos) {
770            final Element item = getItem(pos);
771            final String uriS = item.findChildContent("uri", Namespace.VCARD4);
772            if (uriS != null) return Uri.parse(uriS).normalizeScheme();
773            if (item.getName().equals("email")) return Uri.parse("mailto:" + item.findChildContent("text", Namespace.VCARD4));
774            return null;
775        }
776    }
777}