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.provider.Settings;
  20import android.text.Spannable;
  21import android.text.SpannableString;
  22import android.text.style.RelativeSizeSpan;
  23import android.util.TypedValue;
  24import android.view.inputmethod.InputMethodManager;
  25import android.view.LayoutInflater;
  26import android.view.Menu;
  27import android.view.MenuItem;
  28import android.view.View;
  29import android.view.View.OnClickListener;
  30import android.view.ViewGroup;
  31import android.widget.ArrayAdapter;
  32import android.widget.CompoundButton;
  33import android.widget.CompoundButton.OnCheckedChangeListener;
  34import android.widget.EditText;
  35import android.widget.TextView;
  36import android.widget.Toast;
  37import androidx.annotation.NonNull;
  38import androidx.core.content.ContextCompat;
  39import androidx.core.view.ViewCompat;
  40import androidx.databinding.DataBindingUtil;
  41
  42import com.cheogram.android.Util;
  43
  44import com.google.android.material.color.MaterialColors;
  45import com.google.android.material.dialog.MaterialAlertDialogBuilder;
  46import com.google.common.base.Joiner;
  47import com.google.common.collect.ImmutableList;
  48import com.google.common.collect.Iterables;
  49import com.google.common.primitives.Ints;
  50
  51import org.openintents.openpgp.util.OpenPgpUtils;
  52
  53import java.util.ArrayList;
  54import java.util.Collection;
  55import java.util.Collections;
  56import java.util.Comparator;
  57import java.util.List;
  58import java.util.Map;
  59import java.util.stream.Collectors;
  60
  61import eu.siacs.conversations.AppSettings;
  62import eu.siacs.conversations.Config;
  63import eu.siacs.conversations.R;
  64import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  65import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  66import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  67import eu.siacs.conversations.databinding.ActivityContactDetailsBinding;
  68import eu.siacs.conversations.databinding.CommandRowBinding;
  69import eu.siacs.conversations.entities.Account;
  70import eu.siacs.conversations.entities.Bookmark;
  71import eu.siacs.conversations.entities.Contact;
  72import eu.siacs.conversations.entities.ListItem;
  73import eu.siacs.conversations.services.AbstractQuickConversationsService;
  74import eu.siacs.conversations.services.QuickConversationsService;
  75import eu.siacs.conversations.services.XmppConnectionService;
  76import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  77import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  78import eu.siacs.conversations.ui.adapter.MediaAdapter;
  79import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
  80import eu.siacs.conversations.ui.text.FixedURLSpan;
  81import eu.siacs.conversations.ui.util.Attachment;
  82import eu.siacs.conversations.ui.util.AvatarWorkerTask;
  83import eu.siacs.conversations.ui.util.GridManager;
  84import eu.siacs.conversations.ui.util.JidDialog;
  85import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  86import eu.siacs.conversations.ui.util.ShareUtil;
  87import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
  88import eu.siacs.conversations.utils.AccountUtils;
  89import eu.siacs.conversations.utils.Compatibility;
  90import eu.siacs.conversations.utils.Emoticons;
  91import eu.siacs.conversations.utils.IrregularUnicodeDetector;
  92import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
  93import eu.siacs.conversations.utils.UIHelper;
  94import eu.siacs.conversations.utils.XEP0392Helper;
  95import eu.siacs.conversations.utils.XmppUri;
  96import eu.siacs.conversations.xml.Element;
  97import eu.siacs.conversations.xml.Namespace;
  98import eu.siacs.conversations.xmpp.Jid;
  99import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 100import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 101import eu.siacs.conversations.xmpp.XmppConnection;
 102import eu.siacs.conversations.xmpp.manager.DiscoManager;
 103import eu.siacs.conversations.xmpp.manager.PresenceManager;
 104import eu.siacs.conversations.xmpp.manager.RosterManager;
 105import im.conversations.android.xmpp.model.stanza.Presence;
 106import java.util.Collection;
 107import java.util.Collections;
 108import java.util.List;
 109import org.openintents.openpgp.util.OpenPgpUtils;
 110
 111public class ContactDetailsActivity extends OmemoActivity
 112        implements OnAccountUpdate,
 113                OnRosterUpdate,
 114                OnUpdateBlocklist,
 115                OnKeyStatusUpdated,
 116                OnMediaLoaded {
 117    public static final String ACTION_VIEW_CONTACT = "view_contact";
 118    private final int REQUEST_SYNC_CONTACTS = 0x28cf;
 119    ActivityContactDetailsBinding binding;
 120    private MediaAdapter mMediaAdapter;
 121    protected MenuItem edit = null;
 122    protected MenuItem save = null;
 123
 124    private Contact contact;
 125    private final DialogInterface.OnClickListener removeFromRoster =
 126            new DialogInterface.OnClickListener() {
 127
 128                @Override
 129                public void onClick(DialogInterface dialog, int which) {
 130                    xmppConnectionService.deleteContactOnServer(contact);
 131                }
 132            };
 133    private final OnCheckedChangeListener mOnSendCheckedChange =
 134            new OnCheckedChangeListener() {
 135
 136                @Override
 137                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 138                    if (isChecked) {
 139                        if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
 140                            xmppConnectionService.stopPresenceUpdatesTo(contact);
 141                        } else {
 142                            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
 143                        }
 144                    } else {
 145                        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
 146                        final var connection = contact.getAccount().getXmppConnection();
 147                        connection
 148                                .getManager(PresenceManager.class)
 149                                .unsubscribed(contact.getJid().asBareJid());
 150                    }
 151                }
 152            };
 153    private final OnCheckedChangeListener mOnReceiveCheckedChange =
 154            new OnCheckedChangeListener() {
 155
 156                @Override
 157                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 158                    final var connection = contact.getAccount().getXmppConnection();
 159                    if (isChecked) {
 160                        connection
 161                                .getManager(PresenceManager.class)
 162                                .subscribe(contact.getJid().asBareJid());
 163                    } else {
 164                        connection
 165                                .getManager(PresenceManager.class)
 166                                .unsubscribe(contact.getJid().asBareJid());
 167                    }
 168                }
 169            };
 170    private Jid accountJid;
 171    private Jid contactJid;
 172    private boolean showDynamicTags = false;
 173    private boolean showLastSeen = false;
 174    private boolean showInactiveOmemo = false;
 175    private String messageFingerprint;
 176
 177    private void checkContactPermissionAndShowAddDialog() {
 178        if (hasContactsPermission()) {
 179            showAddToPhoneBookDialog();
 180        } else if (QuickConversationsService.isContactListIntegration(this)) {
 181            requestPermissions(
 182                    new String[] {Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
 183        }
 184    }
 185
 186    private boolean hasContactsPermission() {
 187        if (QuickConversationsService.isContactListIntegration(this)) {
 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.save_to_contact));
 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            return;
 329        }
 330        if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
 331            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 332                showAddToPhoneBookDialog();
 333                xmppConnectionService.loadPhoneContacts();
 334                xmppConnectionService.startContactObserver();
 335            } else {
 336                showRedirectToAppSettings();
 337            }
 338        }
 339    }
 340
 341    private void showRedirectToAppSettings() {
 342        final var dialogBuilder = new MaterialAlertDialogBuilder(this);
 343        dialogBuilder.setTitle(R.string.save_to_contact);
 344        dialogBuilder.setMessage(
 345                getString(R.string.no_contacts_permission, getString(R.string.app_name)));
 346        dialogBuilder.setPositiveButton(
 347                R.string.continue_btn,
 348                (d, w) -> {
 349                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
 350                    Uri uri = Uri.fromParts("package", getPackageName(), null);
 351                    intent.setData(uri);
 352                    startActivity(intent);
 353                });
 354        dialogBuilder.setNegativeButton(R.string.cancel, null);
 355        dialogBuilder.create().show();
 356    }
 357
 358    protected void saveEdits() {
 359        binding.editTags.setVisibility(View.GONE);
 360        if (edit != null) {
 361            EditText text = edit.getActionView().findViewById(R.id.search_field);
 362            contact.setServerName(text.getText().toString());
 363            contact.setGroups(binding.editTags.getObjects().stream().map(tag -> tag.getName()).collect(Collectors.toList()));
 364            final var connection = contact.getAccount().getXmppConnection();
 365            connection.getManager(RosterManager.class).addRosterItem(contact, null);
 366            populateView();
 367            edit.collapseActionView();
 368        }
 369        if (save != null) save.setVisible(false);
 370    }
 371
 372    @Override
 373    public boolean onOptionsItemSelected(final MenuItem menuItem) {
 374        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
 375            return false;
 376        }
 377        switch (menuItem.getItemId()) {
 378            case android.R.id.home:
 379                finish();
 380                break;
 381            case R.id.action_share_http:
 382                shareLink(true);
 383                break;
 384            case R.id.action_share_uri:
 385                shareLink(false);
 386                break;
 387            case R.id.action_delete_contact:
 388                final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 389                builder.setNegativeButton(getString(R.string.cancel), null);
 390                builder.setTitle(getString(R.string.action_delete_contact))
 391                        .setMessage(
 392                                JidDialog.style(
 393                                        this,
 394                                        R.string.remove_contact_text,
 395                                        contact.getJid().toString()))
 396                        .setPositiveButton(getString(R.string.delete), removeFromRoster)
 397                        .create()
 398                        .show();
 399                break;
 400            case R.id.action_save:
 401                saveEdits();
 402                break;
 403            case R.id.action_edit_contact:
 404                final Uri systemAccount = contact.getSystemAccount();
 405                if (systemAccount == null) {
 406                    menuItem.expandActionView();
 407                    EditText text = menuItem.getActionView().findViewById(R.id.search_field);
 408                    text.setOnEditorActionListener((v, actionId, event) -> {
 409                        saveEdits();
 410                        return true;
 411                    });
 412                    text.setText(contact.getServerName());
 413                    text.requestFocus();
 414                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 415                    if (imm != null) {
 416                        imm.showSoftInput(text, InputMethodManager.SHOW_IMPLICIT);
 417                    }
 418                    binding.tags.setVisibility(View.GONE);
 419                    binding.editTags.clearSync();
 420                    for (final ListItem.Tag group : contact.getGroupTags()) {
 421                        binding.editTags.addObjectSync(group);
 422                    }
 423                    ArrayList<ListItem.Tag> tags = new ArrayList<>();
 424                    for (final Account account : xmppConnectionService.getAccounts()) {
 425                        for (Contact contact : account.getRoster().getContacts()) {
 426                            tags.addAll(contact.getTags(this));
 427                        }
 428                        for (Bookmark bookmark : account.getBookmarks()) {
 429                            tags.addAll(bookmark.getTags(this));
 430                        }
 431                    }
 432                    Comparator<Map.Entry<ListItem.Tag,Integer>> sortTagsBy = Map.Entry.comparingByValue(Comparator.reverseOrder());
 433                    sortTagsBy = sortTagsBy.thenComparing(entry -> entry.getKey().getName());
 434
 435                    ArrayAdapter<ListItem.Tag> adapter = new ArrayAdapter<>(
 436                        this,
 437                        android.R.layout.simple_list_item_1,
 438                        tags.stream()
 439                        .collect(Collectors.toMap((x) -> x, (t) -> 1, (c1, c2) -> c1 + c2))
 440                        .entrySet().stream()
 441                       .sorted(sortTagsBy)
 442                       .map(e -> e.getKey()).collect(Collectors.toList())
 443                    );
 444                    binding.editTags.setAdapter(adapter);
 445                    if (showDynamicTags) binding.editTags.setVisibility(View.VISIBLE);
 446                    if (save != null) save.setVisible(true);
 447                } else {
 448                    menuItem.collapseActionView();
 449                    if (save != null) save.setVisible(false);
 450                    Intent intent = new Intent(Intent.ACTION_EDIT);
 451                    intent.setDataAndType(systemAccount, Contacts.CONTENT_ITEM_TYPE);
 452                    intent.putExtra("finishActivityOnSaveCompleted", true);
 453                    try {
 454                        startActivity(intent);
 455                    } catch (ActivityNotFoundException e) {
 456                        Toast.makeText(
 457                                        ContactDetailsActivity.this,
 458                                        R.string.no_application_found_to_view_contact,
 459                                        Toast.LENGTH_SHORT)
 460                                .show();
 461                    }
 462                }
 463                break;
 464            case R.id.action_block, R.id.action_unblock:
 465                BlockContactDialog.show(this, contact);
 466                break;
 467            case R.id.action_custom_notifications:
 468                configureCustomNotifications(contact);
 469                break;
 470        }
 471        return super.onOptionsItemSelected(menuItem);
 472    }
 473
 474    private void configureCustomNotifications(final Contact contact) {
 475        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
 476            return;
 477        }
 478        final var shortcut = xmppConnectionService.getShortcutService().getShortcutInfo(contact);
 479        configureCustomNotification(shortcut);
 480    }
 481
 482    @Override
 483    public boolean onCreateOptionsMenu(final Menu menu) {
 484        getMenuInflater().inflate(R.menu.contact_details, menu);
 485        AccountUtils.showHideMenuItems(menu);
 486        final MenuItem block = menu.findItem(R.id.action_block);
 487        final MenuItem unblock = menu.findItem(R.id.action_unblock);
 488        edit = menu.findItem(R.id.action_edit_contact);
 489        save = menu.findItem(R.id.action_save);
 490        final MenuItem delete = menu.findItem(R.id.action_delete_contact);
 491        final MenuItem customNotifications = menu.findItem(R.id.action_custom_notifications);
 492        customNotifications.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R);
 493        if (contact == null) {
 494            return true;
 495        }
 496        final XmppConnection connection = contact.getAccount().getXmppConnection();
 497        if (connection != null && connection.getFeatures().blocking()) {
 498            if (this.contact.isBlocked()) {
 499                block.setVisible(false);
 500            } else {
 501                unblock.setVisible(false);
 502            }
 503        } else {
 504            unblock.setVisible(false);
 505            block.setVisible(false);
 506        }
 507        if (!contact.showInRoster()) {
 508            edit.setVisible(false);
 509            delete.setVisible(false);
 510        }
 511        edit.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
 512            @Override
 513            public boolean onMenuItemActionCollapse(MenuItem item) {
 514                SoftKeyboardUtils.hideSoftKeyboard(ContactDetailsActivity.this);
 515                binding.editTags.setVisibility(View.GONE);
 516                if (save != null) save.setVisible(false);
 517                populateView();
 518                return true;
 519            }
 520
 521            @Override
 522            public boolean onMenuItemActionExpand(MenuItem item) { return true; }
 523        });
 524        return super.onCreateOptionsMenu(menu);
 525    }
 526
 527    private void populateView() {
 528        if (contact == null) {
 529            return;
 530        }
 531        if (binding.editTags.getVisibility() != View.GONE) return;
 532        invalidateOptionsMenu();
 533        setTitle(contact.getDisplayName());
 534        if (contact.showInRoster()) {
 535            binding.detailsSendPresence.setVisibility(View.VISIBLE);
 536            binding.detailsReceivePresence.setVisibility(View.VISIBLE);
 537            binding.addContactButton.setVisibility(View.GONE);
 538            binding.detailsSendPresence.setOnCheckedChangeListener(null);
 539            binding.detailsReceivePresence.setOnCheckedChangeListener(null);
 540
 541            Collection<String> statusMessages = contact.getPresences().getStatusMessages();
 542            if (statusMessages.isEmpty()) {
 543                binding.statusMessage.setVisibility(View.GONE);
 544            } else if (statusMessages.size() == 1) {
 545                final String message = Iterables.getOnlyElement(statusMessages);
 546                binding.statusMessage.setVisibility(View.VISIBLE);
 547                final Spannable span = new SpannableString(message);
 548                if (Emoticons.isOnlyEmoji(message)) {
 549                    span.setSpan(
 550                            new RelativeSizeSpan(2.0f),
 551                            0,
 552                            message.length(),
 553                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 554                }
 555                binding.statusMessage.setText(span);
 556            } else {
 557                binding.statusMessage.setText(Joiner.on('\n').join(statusMessages));
 558            }
 559
 560            if (contact.getOption(Contact.Options.FROM)) {
 561                binding.detailsSendPresence.setText(R.string.send_presence_updates);
 562                binding.detailsSendPresence.setChecked(true);
 563            } else if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
 564                binding.detailsSendPresence.setChecked(false);
 565                binding.detailsSendPresence.setText(R.string.send_presence_updates);
 566            } else {
 567                binding.detailsSendPresence.setText(R.string.preemptively_grant);
 568                binding.detailsSendPresence.setChecked(
 569                        contact.getOption(Contact.Options.PREEMPTIVE_GRANT));
 570            }
 571            if (contact.getOption(Contact.Options.TO)) {
 572                binding.detailsReceivePresence.setText(R.string.receive_presence_updates);
 573                binding.detailsReceivePresence.setChecked(true);
 574            } else {
 575                binding.detailsReceivePresence.setText(R.string.ask_for_presence_updates);
 576                binding.detailsReceivePresence.setChecked(
 577                        contact.getOption(Contact.Options.ASKING));
 578            }
 579            if (contact.getAccount().isOnlineAndConnected()) {
 580                binding.detailsReceivePresence.setEnabled(true);
 581                binding.detailsSendPresence.setEnabled(true);
 582            } else {
 583                binding.detailsReceivePresence.setEnabled(false);
 584                binding.detailsSendPresence.setEnabled(false);
 585            }
 586            binding.detailsSendPresence.setOnCheckedChangeListener(this.mOnSendCheckedChange);
 587            binding.detailsReceivePresence.setOnCheckedChangeListener(this.mOnReceiveCheckedChange);
 588        } else {
 589            binding.addContactButton.setVisibility(View.VISIBLE);
 590            binding.detailsSendPresence.setVisibility(View.GONE);
 591            binding.detailsReceivePresence.setVisibility(View.GONE);
 592            binding.statusMessage.setVisibility(View.GONE);
 593        }
 594
 595        if (contact.isBlocked() && !this.showDynamicTags) {
 596            binding.detailsLastSeen.setVisibility(View.VISIBLE);
 597            binding.detailsLastSeen.setText(R.string.contact_blocked);
 598        } else {
 599            if (showLastSeen
 600                    && contact.getLastseen() > 0
 601                    && contact.getPresences().allOrNonSupport(Namespace.IDLE)) {
 602                binding.detailsLastSeen.setVisibility(View.VISIBLE);
 603                binding.detailsLastSeen.setText(
 604                        UIHelper.lastseen(
 605                                getApplicationContext(),
 606                                contact.isActive(),
 607                                contact.getLastseen()));
 608            } else {
 609                binding.detailsLastSeen.setVisibility(View.GONE);
 610            }
 611        }
 612
 613        binding.detailsContactXmppAddress.setText(
 614                IrregularUnicodeDetector.style(this, contact.getJid()));
 615        final String account = contact.getAccount().getJid().asBareJid().toString();
 616        binding.detailsAccount.setOnClickListener(this::onDetailsAccountClicked);
 617        binding.detailsAccount.setText(getString(R.string.using_account, account));
 618        AvatarWorkerTask.loadAvatar(contact, binding.detailsAvatar, R.dimen.publish_avatar_size);
 619        binding.detailsAvatar.setOnClickListener(this::onAvatarClicked);
 620        if (QuickConversationsService.isContactListIntegration(this)) {
 621            if (contact.getSystemAccount() == null) {
 622                binding.addAddressBook.setText(R.string.save_to_contact);
 623            } else {
 624                binding.addAddressBook.setText(R.string.show_in_contacts);
 625            }
 626            binding.addAddressBook.setVisibility(View.VISIBLE);
 627            binding.addAddressBook.setOnClickListener(this::onAddToAddressBookClick);
 628        } else {
 629            binding.addAddressBook.setVisibility(View.GONE);
 630        }
 631
 632        binding.detailsContactKeys.removeAllViews();
 633        boolean hasKeys = false;
 634        final LayoutInflater inflater = getLayoutInflater();
 635        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
 636        if (Config.supportOmemo() && axolotlService != null) {
 637            final Collection<XmppAxolotlSession> sessions =
 638                    axolotlService.findSessionsForContact(contact);
 639            boolean anyActive = false;
 640            for (XmppAxolotlSession session : sessions) {
 641                anyActive = session.getTrust().isActive();
 642                if (anyActive) {
 643                    break;
 644                }
 645            }
 646            boolean skippedInactive = false;
 647            boolean showsInactive = false;
 648            boolean showUnverifiedWarning = false;
 649            for (final XmppAxolotlSession session : sessions) {
 650                final FingerprintStatus trust = session.getTrust();
 651                hasKeys |= !trust.isCompromised();
 652                if (!trust.isActive() && anyActive) {
 653                    if (showInactiveOmemo) {
 654                        showsInactive = true;
 655                    } else {
 656                        skippedInactive = true;
 657                        continue;
 658                    }
 659                }
 660                if (!trust.isCompromised()) {
 661                    boolean highlight = session.getFingerprint().equals(messageFingerprint);
 662                    addFingerprintRow(binding.detailsContactKeys, session, highlight);
 663                }
 664                if (trust.isUnverified()) {
 665                    showUnverifiedWarning = true;
 666                }
 667            }
 668            binding.unverifiedWarning.setVisibility(
 669                    showUnverifiedWarning ? View.VISIBLE : View.GONE);
 670            if (showsInactive || skippedInactive) {
 671                binding.showInactiveDevices.setText(
 672                        showsInactive
 673                                ? R.string.hide_inactive_devices
 674                                : R.string.show_inactive_devices);
 675                binding.showInactiveDevices.setVisibility(View.VISIBLE);
 676            } else {
 677                binding.showInactiveDevices.setVisibility(View.GONE);
 678            }
 679        } else {
 680            binding.showInactiveDevices.setVisibility(View.GONE);
 681        }
 682        final boolean isCameraFeatureAvailable = isCameraFeatureAvailable();
 683        binding.scanButton.setVisibility(
 684                hasKeys && isCameraFeatureAvailable ? View.VISIBLE : View.GONE);
 685        if (hasKeys) {
 686            binding.scanButton.setOnClickListener((v) -> ScanActivity.scan(this));
 687        }
 688        if (Config.supportOpenPgp() && contact.getPgpKeyId() != 0) {
 689            hasKeys = true;
 690            View view =
 691                    inflater.inflate(
 692                            R.layout.item_device_fingerprint, binding.detailsContactKeys, false);
 693            TextView key = view.findViewById(R.id.key);
 694            TextView keyType = view.findViewById(R.id.key_type);
 695            keyType.setText(R.string.openpgp_key_id);
 696            if ("pgp".equals(messageFingerprint)) {
 697                keyType.setTextColor(
 698                        MaterialColors.getColor(
 699                                keyType, com.google.android.material.R.attr.colorPrimaryVariant));
 700            }
 701            key.setText(OpenPgpUtils.convertKeyIdToHex(contact.getPgpKeyId()));
 702            final OnClickListener openKey = v -> launchOpenKeyChain(contact.getPgpKeyId());
 703            view.setOnClickListener(openKey);
 704            key.setOnClickListener(openKey);
 705            keyType.setOnClickListener(openKey);
 706            binding.detailsContactKeys.addView(view);
 707        }
 708        binding.keysWrapper.setVisibility(hasKeys ? View.VISIBLE : View.GONE);
 709
 710        final List<ListItem.Tag> tagList = contact.getTags(this);
 711        final boolean hasMetaTags =
 712                contact.isBlocked() || contact.getShownStatus() != Presence.Availability.OFFLINE;
 713        if ((tagList.isEmpty() && !hasMetaTags) || !this.showDynamicTags) {
 714            binding.tags.setVisibility(View.GONE);
 715        } else {
 716            binding.tags.setVisibility(View.VISIBLE);
 717            binding.tags.removeViews(1, binding.tags.getChildCount() - 1);
 718            final ImmutableList.Builder<Integer> viewIdBuilder = new ImmutableList.Builder<>();
 719            for (final ListItem.Tag tag : tagList) {
 720                final String name = tag.getName();
 721                final TextView tv =
 722                        (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
 723                tv.setText(name);
 724                tv.setBackgroundTintList(
 725                        ColorStateList.valueOf(
 726                                MaterialColors.harmonizeWithPrimary(
 727                                        this, XEP0392Helper.rgbFromNick(name))));
 728                final int id = ViewCompat.generateViewId();
 729                tv.setId(id);
 730                viewIdBuilder.add(id);
 731                binding.tags.addView(tv);
 732            }
 733            if (contact.isBlocked()) {
 734                final TextView tv =
 735                        (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
 736                tv.setText(R.string.blocked);
 737                tv.setBackgroundTintList(
 738                        ColorStateList.valueOf(
 739                                MaterialColors.harmonizeWithPrimary(
 740                                        tv.getContext(),
 741                                        ContextCompat.getColor(
 742                                                tv.getContext(), R.color.gray_800))));
 743                final int id = ViewCompat.generateViewId();
 744                tv.setId(id);
 745                viewIdBuilder.add(id);
 746                binding.tags.addView(tv);
 747            } else {
 748                final Presence.Availability status = contact.getShownStatus();
 749                if (status != Presence.Availability.OFFLINE) {
 750                    final TextView tv =
 751                            (TextView) inflater.inflate(R.layout.item_tag, binding.tags, false);
 752                    UIHelper.setStatus(tv, status);
 753                    final int id = ViewCompat.generateViewId();
 754                    tv.setId(id);
 755                    viewIdBuilder.add(id);
 756                    binding.tags.addView(tv);
 757                }
 758            }
 759            final var connection = contact.getAccount().getXmppConnection();
 760            if (contact.getJid().isDomainJid() && connection != null) {
 761                for (final var jid : contact.getPresences().getFullJids()) {
 762                    final var disco = connection.getManager(DiscoManager.class).get(jid);
 763                    if (disco == null) continue;
 764                    for (final var identity : disco.getIdentities()) {
 765                        final var txt = identity.getCategory() + "/" + identity.getType();
 766                        final TextView tv =
 767                            (TextView)
 768                                    inflater.inflate(
 769                                            R.layout.item_tag, binding.tags, false);
 770                        tv.setText(txt);
 771                        tv.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.harmonizeWithPrimary(this,XEP0392Helper.rgbFromNick(txt))));
 772                        final int id = ViewCompat.generateViewId();
 773                        tv.setId(id);
 774                        viewIdBuilder.add(id);
 775                        binding.tags.addView(tv);
 776                    }
 777                }
 778            }
 779            binding.flowWidget.setReferencedIds(Ints.toArray(viewIdBuilder.build()));
 780        }
 781    }
 782
 783    private void onDetailsAccountClicked(final View view) {
 784        final var contact = this.contact;
 785        if (contact == null) {
 786            return;
 787        }
 788        switchToAccount(contact.getAccount());
 789    }
 790
 791    private void onAvatarClicked(final View view) {
 792        final var contact = this.contact;
 793        if (contact == null) {
 794            return;
 795        }
 796        final var avatar = contact.getAvatar();
 797        if (avatar == null) {
 798            return;
 799        }
 800        final var intent = new Intent(this, ViewProfilePictureActivity.class);
 801        intent.setData(Uri.fromParts("avatar", avatar, null));
 802        intent.putExtra(ViewProfilePictureActivity.EXTRA_DISPLAY_NAME, contact.getDisplayName());
 803        startActivity(intent);
 804    }
 805
 806    private void onAddToAddressBookClick(final View view) {
 807        if (QuickConversationsService.isContactListIntegration(this)) {
 808            final Uri systemAccount = contact.getSystemAccount();
 809            if (systemAccount == null) {
 810                checkContactPermissionAndShowAddDialog();
 811            } else {
 812                final Intent intent = new Intent(Intent.ACTION_VIEW);
 813                intent.setData(systemAccount);
 814                try {
 815                    startActivity(intent);
 816                } catch (final ActivityNotFoundException e) {
 817                    Toast.makeText(
 818                                    this,
 819                                    R.string.no_application_found_to_view_contact,
 820                                    Toast.LENGTH_SHORT)
 821                            .show();
 822                }
 823            }
 824        } else {
 825            Toast.makeText(
 826                            this,
 827                            R.string.contact_list_integration_not_available,
 828                            Toast.LENGTH_SHORT)
 829                    .show();
 830        }
 831    }
 832
 833    public void onBackendConnected() {
 834        if (accountJid != null && contactJid != null) {
 835            Account account = xmppConnectionService.findAccountByJid(accountJid);
 836            if (account == null) {
 837                return;
 838            }
 839            this.contact = account.getRoster().getContact(contactJid);
 840            if (mPendingFingerprintVerificationUri != null) {
 841                processFingerprintVerification(mPendingFingerprintVerificationUri);
 842                mPendingFingerprintVerificationUri = null;
 843            }
 844
 845            if (Compatibility.hasStoragePermission(this)) {
 846                final int limit = GridManager.getCurrentColumnCount(this.binding.media);
 847                xmppConnectionService.getAttachments(
 848                        account, contact.getJid().asBareJid(), limit, this);
 849                this.binding.showMedia.setOnClickListener(
 850                        (v) -> MediaBrowserActivity.launch(this, contact));
 851            }
 852
 853            final VcardAdapter items = new VcardAdapter();
 854            binding.profileItems.setAdapter(items);
 855            binding.profileItems.setOnItemClickListener((a0, v, pos, a3) -> {
 856                final Uri uri = items.getUri(pos);
 857                if (uri == null) return;
 858                new FixedURLSpan(uri.toString()).onClick(v);
 859            });
 860            binding.profileItems.setOnItemLongClickListener((a0, v, pos, a3) -> {
 861                String toCopy = null;
 862                final Uri uri = items.getUri(pos);
 863                if (uri != null) toCopy = uri.toString();
 864                if (toCopy == null) {
 865                    toCopy = items.getItem(pos).findChildContent("text", Namespace.VCARD4);
 866                }
 867
 868                if (toCopy == null) return false;
 869                if (ShareUtil.copyTextToClipboard(ContactDetailsActivity.this, toCopy, R.string.message)) {
 870                    Toast.makeText(ContactDetailsActivity.this, R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
 871                }
 872                return true;
 873            });
 874            xmppConnectionService.fetchVcard4(account, contact, (vcard4) -> {
 875                if (vcard4 == null) return;
 876
 877                runOnUiThread(() -> {
 878                    for (Element el : vcard4.getChildren()) {
 879                        if (el.findChildEnsureSingle("uri", Namespace.VCARD4) != null || el.findChildEnsureSingle("text", Namespace.VCARD4) != null) {
 880                            items.add(el);
 881                        }
 882                    }
 883                    Util.justifyListViewHeightBasedOnChildren(binding.profileItems);
 884                });
 885            });
 886
 887            final var conversation = xmppConnectionService.findOrCreateConversation(account, contact.getJid(), false, true);
 888            binding.storeInCache.setChecked(conversation.storeInCache());
 889            binding.storeInCache.setOnCheckedChangeListener((v, checked) -> {
 890                conversation.setStoreInCache(checked);
 891                xmppConnectionService.updateConversation(conversation);
 892            });
 893
 894            populateView();
 895        }
 896    }
 897
 898    @Override
 899    public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
 900        refreshUi();
 901    }
 902
 903    @Override
 904    protected void processFingerprintVerification(XmppUri uri) {
 905        if (contact != null
 906                && contact.getJid().asBareJid().equals(uri.getJid())
 907                && uri.hasFingerprints()) {
 908            if (xmppConnectionService.verifyFingerprints(contact, uri.getFingerprints())) {
 909                Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
 910            }
 911        } else {
 912            Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
 913        }
 914    }
 915
 916    @Override
 917    public void onMediaLoaded(List<Attachment> attachments) {
 918        runOnUiThread(
 919                () -> {
 920                    int limit = GridManager.getCurrentColumnCount(binding.media);
 921                    mMediaAdapter.setAttachments(
 922                            attachments.subList(0, Math.min(limit, attachments.size())));
 923                    binding.mediaWrapper.setVisibility(
 924                            attachments.size() > 0 ? View.VISIBLE : View.GONE);
 925                });
 926    }
 927
 928    class VcardAdapter extends ArrayAdapter<Element> {
 929        VcardAdapter() { super(ContactDetailsActivity.this, 0); }
 930
 931        private Drawable getDrawable(int d) {
 932            return ContactDetailsActivity.this.getDrawable(d);
 933        }
 934
 935        @Override
 936        public View getView(int position, View view, @NonNull ViewGroup parent) {
 937            final CommandRowBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.command_row, parent, false);
 938            final Element item = getItem(position);
 939
 940            if (item.getName().equals("org")) {
 941                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_business_24dp), null, null, null);
 942                binding.command.setCompoundDrawablePadding(20);
 943            } else if (item.getName().equals("impp")) {
 944                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_chat_black_24dp), null, null, null);
 945                binding.command.setCompoundDrawablePadding(20);
 946            } else if (item.getName().equals("url")) {
 947                binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_link_24dp), null, null, null);
 948                binding.command.setCompoundDrawablePadding(20);
 949            }
 950
 951            final Uri uri = getUri(position);
 952            if (uri != null && uri.getScheme() != null) {
 953                if (uri.getScheme().equals("xmpp")) {
 954                    binding.command.setText(uri.getSchemeSpecificPart());
 955                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.jabber), null, null, null);
 956                    binding.command.setCompoundDrawablePadding(20);
 957                } else if (uri.getScheme().equals("tel")) {
 958                    binding.command.setText(uri.getSchemeSpecificPart());
 959                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_call_24dp), null, null, null);
 960                    binding.command.setCompoundDrawablePadding(20);
 961                } else if (uri.getScheme().equals("mailto")) {
 962                    binding.command.setText(uri.getSchemeSpecificPart());
 963                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_email_24dp), null, null, null);
 964                    binding.command.setCompoundDrawablePadding(20);
 965                } else if (uri.getScheme().equals("bitcoin")) {
 966                    binding.command.setText(uri.getSchemeSpecificPart());
 967                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.bitcoin_24dp), null, null, null);
 968                    binding.command.setCompoundDrawablePadding(20);
 969                } else if (uri.getScheme().equals("bitcoincash")) {
 970                    binding.command.setText(uri.getSchemeSpecificPart());
 971                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.bitcoin_cash_24dp), null, null, null);
 972                    binding.command.setCompoundDrawablePadding(20);
 973                } else if (uri.getScheme().equals("ethereum")) {
 974                    binding.command.setText(uri.getSchemeSpecificPart());
 975                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.eth_24dp), null, null, null);
 976                    binding.command.setCompoundDrawablePadding(20);
 977                } else if (uri.getScheme().equals("monero")) {
 978                    binding.command.setText(uri.getSchemeSpecificPart());
 979                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.monero_24dp), null, null, null);
 980                    binding.command.setCompoundDrawablePadding(20);
 981                } else if (uri.getScheme().equals("wownero")) {
 982                    binding.command.setText(uri.getSchemeSpecificPart());
 983                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.wownero_24dp), null, null, null);
 984                    binding.command.setCompoundDrawablePadding(20);
 985                } else if (uri.getScheme().equals("https") && "liberapay.com".equals(uri.getHost())) {
 986                    binding.command.setText(uri.getPath().substring(1));
 987                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.liberapay), null, null, null);
 988                    binding.command.setCompoundDrawablePadding(20);
 989                } else if (uri.getScheme().equals("https") && ("www.patreon.com".equals(uri.getHost()) || "patreon.com".equals(uri.getHost()))) {
 990                    binding.command.setText(uri.getPath().replaceAll("^/(?:c/)?", ""));
 991                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.patreon), null, null, null);
 992                    binding.command.setCompoundDrawablePadding(20);
 993                } else if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) {
 994                    binding.command.setText(uri.toString());
 995                    binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.drawable.ic_link_24dp), null, null, null);
 996                    binding.command.setCompoundDrawablePadding(20);
 997                } else {
 998                    binding.command.setText(uri.toString());
 999                }
1000            } else {
1001                final String text = item.findChildContent("text", Namespace.VCARD4);
1002                binding.command.setText(text);
1003            }
1004
1005            return binding.getRoot();
1006        }
1007
1008        public Uri getUri(int pos) {
1009            final Element item = getItem(pos);
1010            final String uriS = item.findChildContent("uri", Namespace.VCARD4);
1011            if (uriS != null) return Uri.parse(uriS).normalizeScheme();
1012            if (item.getName().equals("email")) return Uri.parse("mailto:" + item.findChildContent("text", Namespace.VCARD4));
1013            return null;
1014        }
1015    }
1016}