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