ContactDetailsActivity.java

  1package eu.siacs.conversations.ui;
  2
  3import android.content.ActivityNotFoundException;
  4import android.content.DialogInterface;
  5import android.content.Intent;
  6import android.content.SharedPreferences;
  7import android.databinding.DataBindingUtil;
  8import android.net.Uri;
  9import android.os.Bundle;
 10import android.preference.PreferenceManager;
 11import android.provider.ContactsContract.CommonDataKinds;
 12import android.provider.ContactsContract.Contacts;
 13import android.provider.ContactsContract.Intents;
 14import android.support.v7.app.AlertDialog;
 15import android.support.v7.widget.Toolbar;
 16import android.view.LayoutInflater;
 17import android.view.Menu;
 18import android.view.MenuItem;
 19import android.view.View;
 20import android.view.View.OnClickListener;
 21import android.widget.CompoundButton;
 22import android.widget.CompoundButton.OnCheckedChangeListener;
 23import android.widget.TextView;
 24import android.widget.Toast;
 25
 26import org.openintents.openpgp.util.OpenPgpUtils;
 27
 28import java.util.Collection;
 29import java.util.Collections;
 30import java.util.List;
 31
 32import eu.siacs.conversations.Config;
 33import eu.siacs.conversations.R;
 34import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 35import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
 36import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
 37import eu.siacs.conversations.databinding.ActivityContactDetailsBinding;
 38import eu.siacs.conversations.entities.Account;
 39import eu.siacs.conversations.entities.Contact;
 40import eu.siacs.conversations.entities.ListItem;
 41import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
 42import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
 43import eu.siacs.conversations.ui.adapter.MediaAdapter;
 44import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
 45import eu.siacs.conversations.ui.util.Attachment;
 46import eu.siacs.conversations.ui.util.GridManager;
 47import eu.siacs.conversations.ui.util.JidDialog;
 48import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 49import eu.siacs.conversations.utils.AccountUtils;
 50import eu.siacs.conversations.utils.Compatibility;
 51import eu.siacs.conversations.utils.IrregularUnicodeDetector;
 52import eu.siacs.conversations.utils.UIHelper;
 53import eu.siacs.conversations.utils.XmppUri;
 54import eu.siacs.conversations.xml.Namespace;
 55import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 56import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 57import eu.siacs.conversations.xmpp.XmppConnection;
 58import rocks.xmpp.addr.Jid;
 59
 60public class ContactDetailsActivity extends OmemoActivity implements OnAccountUpdate, OnRosterUpdate, OnUpdateBlocklist, OnKeyStatusUpdated, OnMediaLoaded {
 61    public static final String ACTION_VIEW_CONTACT = "view_contact";
 62    ActivityContactDetailsBinding binding;
 63
 64    private MediaAdapter mMediaAdapter;
 65
 66    private Contact contact;
 67    private DialogInterface.OnClickListener removeFromRoster = new DialogInterface.OnClickListener() {
 68
 69        @Override
 70        public void onClick(DialogInterface dialog, int which) {
 71            xmppConnectionService.deleteContactOnServer(contact);
 72        }
 73    };
 74    private OnCheckedChangeListener mOnSendCheckedChange = new OnCheckedChangeListener() {
 75
 76        @Override
 77        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 78            if (isChecked) {
 79                if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
 80                    xmppConnectionService.stopPresenceUpdatesTo(contact);
 81                } else {
 82                    contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
 83                }
 84            } else {
 85                contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
 86                xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().stopPresenceUpdatesTo(contact));
 87            }
 88        }
 89    };
 90    private OnCheckedChangeListener mOnReceiveCheckedChange = new OnCheckedChangeListener() {
 91
 92        @Override
 93        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 94            if (isChecked) {
 95                xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().requestPresenceUpdatesFrom(contact));
 96            } else {
 97                xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().stopPresenceUpdatesFrom(contact));
 98            }
 99        }
100    };
101    private Jid accountJid;
102    private Jid contactJid;
103    private boolean showDynamicTags = false;
104    private boolean showLastSeen = false;
105    private boolean showInactiveOmemo = false;
106    private String messageFingerprint;
107
108    private DialogInterface.OnClickListener addToPhonebook = new DialogInterface.OnClickListener() {
109
110        @Override
111        public void onClick(DialogInterface dialog, int which) {
112            Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
113            intent.setType(Contacts.CONTENT_ITEM_TYPE);
114            intent.putExtra(Intents.Insert.IM_HANDLE, contact.getJid().toEscapedString());
115            intent.putExtra(Intents.Insert.IM_PROTOCOL, CommonDataKinds.Im.PROTOCOL_JABBER);
116            intent.putExtra("finishActivityOnSaveCompleted", true);
117            try {
118                ContactDetailsActivity.this.startActivityForResult(intent, 0);
119            } catch (ActivityNotFoundException e) {
120                Toast.makeText(ContactDetailsActivity.this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
121            }
122        }
123    };
124
125    private OnClickListener onBadgeClick = new OnClickListener() {
126
127        @Override
128        public void onClick(View v) {
129            Uri systemAccount = contact.getSystemAccount();
130            if (systemAccount == null) {
131                AlertDialog.Builder builder = new AlertDialog.Builder(
132                        ContactDetailsActivity.this);
133                builder.setTitle(getString(R.string.action_add_phone_book));
134                builder.setMessage(getString(R.string.add_phone_book_text, contact.getJid().toString()));
135                builder.setNegativeButton(getString(R.string.cancel), null);
136                builder.setPositiveButton(getString(R.string.add), addToPhonebook);
137                builder.create().show();
138            } else {
139                Intent intent = new Intent(Intent.ACTION_VIEW);
140                intent.setData(systemAccount);
141                startActivity(intent);
142            }
143        }
144    };
145
146    @Override
147    public void onRosterUpdate() {
148        refreshUi();
149    }
150
151    @Override
152    public void onAccountUpdate() {
153        refreshUi();
154    }
155
156    @Override
157    public void OnUpdateBlocklist(final Status status) {
158        refreshUi();
159    }
160
161    @Override
162    protected void refreshUiReal() {
163        invalidateOptionsMenu();
164        populateView();
165    }
166
167    @Override
168    protected String getShareableUri(boolean http) {
169        if (http) {
170            return "https://conversations.im/i/" + XmppUri.lameUrlEncode(contact.getJid().asBareJid().toEscapedString());
171        } else {
172            return "xmpp:" + contact.getJid().asBareJid().toEscapedString();
173        }
174    }
175
176    @Override
177    protected void onCreate(final Bundle savedInstanceState) {
178        super.onCreate(savedInstanceState);
179        showInactiveOmemo = savedInstanceState != null && savedInstanceState.getBoolean("show_inactive_omemo", false);
180        if (getIntent().getAction().equals(ACTION_VIEW_CONTACT)) {
181            try {
182                this.accountJid = Jid.of(getIntent().getExtras().getString(EXTRA_ACCOUNT));
183            } catch (final IllegalArgumentException ignored) {
184            }
185            try {
186                this.contactJid = Jid.of(getIntent().getExtras().getString("contact"));
187            } catch (final IllegalArgumentException ignored) {
188            }
189        }
190        this.messageFingerprint = getIntent().getStringExtra("fingerprint");
191        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_details);
192
193        setSupportActionBar((Toolbar) binding.toolbar);
194        configureActionBar(getSupportActionBar());
195        binding.showInactiveDevices.setOnClickListener(v -> {
196            showInactiveOmemo = !showInactiveOmemo;
197            populateView();
198        });
199        binding.addContactButton.setOnClickListener(v -> showAddToRosterDialog(contact));
200
201        mMediaAdapter = new MediaAdapter(this,R.dimen.media_size);
202        this.binding.media.setAdapter(mMediaAdapter);
203        GridManager.setupLayoutManager(this, this.binding.media, R.dimen.media_size);
204    }
205
206    @Override
207    public void onSaveInstanceState(final Bundle savedInstanceState) {
208        savedInstanceState.putBoolean("show_inactive_omemo", showInactiveOmemo);
209        super.onSaveInstanceState(savedInstanceState);
210    }
211
212    @Override
213    public void onStart() {
214        super.onStart();
215        final int theme = findTheme();
216        if (this.mTheme != theme) {
217            recreate();
218        } else {
219            final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
220            this.showDynamicTags = preferences.getBoolean(SettingsActivity.SHOW_DYNAMIC_TAGS, false);
221            this.showLastSeen = preferences.getBoolean("last_activity", false);
222        }
223        binding.mediaWrapper.setVisibility(Compatibility.hasStoragePermission(this) ? View.VISIBLE : View.GONE);
224        mMediaAdapter.setAttachments(Collections.emptyList());
225    }
226
227    @Override
228    public boolean onOptionsItemSelected(final MenuItem menuItem) {
229        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
230            return false;
231        }
232        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
233        builder.setNegativeButton(getString(R.string.cancel), null);
234        switch (menuItem.getItemId()) {
235            case android.R.id.home:
236                finish();
237                break;
238            case R.id.action_share_http:
239                shareLink(true);
240                break;
241            case R.id.action_share_uri:
242                shareLink(false);
243                break;
244            case R.id.action_delete_contact:
245                builder.setTitle(getString(R.string.action_delete_contact))
246                        .setMessage(JidDialog.style(this, R.string.remove_contact_text, contact.getJid().toEscapedString()))
247                        .setPositiveButton(getString(R.string.delete),
248                                removeFromRoster).create().show();
249                break;
250            case R.id.action_edit_contact:
251                Uri systemAccount = contact.getSystemAccount();
252                if (systemAccount == null) {
253                    quickEdit(contact.getServerName(), R.string.contact_name, value -> {
254                        contact.setServerName(value);
255                        ContactDetailsActivity.this.xmppConnectionService.pushContactToServer(contact);
256                        populateView();
257                        return null;
258                    }, true);
259                } else {
260                    Intent intent = new Intent(Intent.ACTION_EDIT);
261                    intent.setDataAndType(systemAccount, Contacts.CONTENT_ITEM_TYPE);
262                    intent.putExtra("finishActivityOnSaveCompleted", true);
263                    try {
264                        startActivity(intent);
265                    } catch (ActivityNotFoundException e) {
266                        Toast.makeText(ContactDetailsActivity.this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
267                    }
268
269                }
270                break;
271            case R.id.action_block:
272                BlockContactDialog.show(this, contact);
273                break;
274            case R.id.action_unblock:
275                BlockContactDialog.show(this, contact);
276                break;
277        }
278        return super.onOptionsItemSelected(menuItem);
279    }
280
281    @Override
282    public boolean onCreateOptionsMenu(final Menu menu) {
283        getMenuInflater().inflate(R.menu.contact_details, menu);
284        AccountUtils.showHideMenuItems(menu);
285        MenuItem block = menu.findItem(R.id.action_block);
286        MenuItem unblock = menu.findItem(R.id.action_unblock);
287        MenuItem edit = menu.findItem(R.id.action_edit_contact);
288        MenuItem delete = menu.findItem(R.id.action_delete_contact);
289        if (contact == null) {
290            return true;
291        }
292        final XmppConnection connection = contact.getAccount().getXmppConnection();
293        if (connection != null && connection.getFeatures().blocking()) {
294            if (this.contact.isBlocked()) {
295                block.setVisible(false);
296            } else {
297                unblock.setVisible(false);
298            }
299        } else {
300            unblock.setVisible(false);
301            block.setVisible(false);
302        }
303        if (!contact.showInRoster()) {
304            edit.setVisible(false);
305            delete.setVisible(false);
306        }
307        return super.onCreateOptionsMenu(menu);
308    }
309
310    private void populateView() {
311        if (contact == null) {
312            return;
313        }
314        invalidateOptionsMenu();
315        setTitle(contact.getDisplayName());
316        if (contact.showInRoster()) {
317            binding.detailsSendPresence.setVisibility(View.VISIBLE);
318            binding.detailsReceivePresence.setVisibility(View.VISIBLE);
319            binding.addContactButton.setVisibility(View.GONE);
320            binding.detailsSendPresence.setOnCheckedChangeListener(null);
321            binding.detailsReceivePresence.setOnCheckedChangeListener(null);
322
323            List<String> statusMessages = contact.getPresences().getStatusMessages();
324            if (statusMessages.size() == 0) {
325                binding.statusMessage.setVisibility(View.GONE);
326            } else {
327                StringBuilder builder = new StringBuilder();
328                binding.statusMessage.setVisibility(View.VISIBLE);
329                int s = statusMessages.size();
330                for (int i = 0; i < s; ++i) {
331                    if (s > 1) {
332                        builder.append("");
333                    }
334                    builder.append(statusMessages.get(i));
335                    if (i < s - 1) {
336                        builder.append("\n");
337                    }
338                }
339                binding.statusMessage.setText(builder);
340            }
341
342            if (contact.getOption(Contact.Options.FROM)) {
343                binding.detailsSendPresence.setText(R.string.send_presence_updates);
344                binding.detailsSendPresence.setChecked(true);
345            } else if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
346                binding.detailsSendPresence.setChecked(false);
347                binding.detailsSendPresence.setText(R.string.send_presence_updates);
348            } else {
349                binding.detailsSendPresence.setText(R.string.preemptively_grant);
350                if (contact.getOption(Contact.Options.PREEMPTIVE_GRANT)) {
351                    binding.detailsSendPresence.setChecked(true);
352                } else {
353                    binding.detailsSendPresence.setChecked(false);
354                }
355            }
356            if (contact.getOption(Contact.Options.TO)) {
357                binding.detailsReceivePresence.setText(R.string.receive_presence_updates);
358                binding.detailsReceivePresence.setChecked(true);
359            } else {
360                binding.detailsReceivePresence.setText(R.string.ask_for_presence_updates);
361                if (contact.getOption(Contact.Options.ASKING)) {
362                    binding.detailsReceivePresence.setChecked(true);
363                } else {
364                    binding.detailsReceivePresence.setChecked(false);
365                }
366            }
367            if (contact.getAccount().isOnlineAndConnected()) {
368                binding.detailsReceivePresence.setEnabled(true);
369                binding.detailsSendPresence.setEnabled(true);
370            } else {
371                binding.detailsReceivePresence.setEnabled(false);
372                binding.detailsSendPresence.setEnabled(false);
373            }
374            binding.detailsSendPresence.setOnCheckedChangeListener(this.mOnSendCheckedChange);
375            binding.detailsReceivePresence.setOnCheckedChangeListener(this.mOnReceiveCheckedChange);
376        } else {
377            binding.addContactButton.setVisibility(View.VISIBLE);
378            binding.detailsSendPresence.setVisibility(View.GONE);
379            binding.detailsReceivePresence.setVisibility(View.GONE);
380            binding.statusMessage.setVisibility(View.GONE);
381        }
382
383        if (contact.isBlocked() && !this.showDynamicTags) {
384            binding.detailsLastseen.setVisibility(View.VISIBLE);
385            binding.detailsLastseen.setText(R.string.contact_blocked);
386        } else {
387            if (showLastSeen
388                    && contact.getLastseen() > 0
389                    && contact.getPresences().allOrNonSupport(Namespace.IDLE)) {
390                binding.detailsLastseen.setVisibility(View.VISIBLE);
391                binding.detailsLastseen.setText(UIHelper.lastseen(getApplicationContext(), contact.isActive(), contact.getLastseen()));
392            } else {
393                binding.detailsLastseen.setVisibility(View.GONE);
394            }
395        }
396
397        binding.detailsContactjid.setText(IrregularUnicodeDetector.style(this, contact.getJid()));
398        String account;
399        if (Config.DOMAIN_LOCK != null) {
400            account = contact.getAccount().getJid().getLocal();
401        } else {
402            account = contact.getAccount().getJid().asBareJid().toString();
403        }
404        binding.detailsAccount.setText(getString(R.string.using_account, account));
405        binding.detailsContactBadge.setImageBitmap(avatarService().get(contact, (int) getResources().getDimension(R.dimen.avatar_on_details_screen_size)));
406        binding.detailsContactBadge.setOnClickListener(this.onBadgeClick);
407
408        binding.detailsContactKeys.removeAllViews();
409        boolean hasKeys = false;
410        final LayoutInflater inflater = getLayoutInflater();
411        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
412        if (Config.supportOmemo() && axolotlService != null) {
413            final Collection<XmppAxolotlSession> sessions = axolotlService.findSessionsForContact(contact);
414            boolean anyActive = false;
415            for(XmppAxolotlSession session : sessions) {
416                anyActive = session.getTrust().isActive();
417                if (anyActive) {
418                    break;
419                }
420            }
421            boolean skippedInactive = false;
422            boolean showsInactive = false;
423            for (final XmppAxolotlSession session :sessions) {
424                final FingerprintStatus trust = session.getTrust();
425                hasKeys |= !trust.isCompromised();
426                if (!trust.isActive() && anyActive) {
427                    if (showInactiveOmemo) {
428                        showsInactive = true;
429                    } else {
430                        skippedInactive = true;
431                        continue;
432                    }
433                }
434                if (!trust.isCompromised()) {
435                    boolean highlight = session.getFingerprint().equals(messageFingerprint);
436                    addFingerprintRow(binding.detailsContactKeys, session, highlight);
437                }
438            }
439            if (showsInactive || skippedInactive) {
440                binding.showInactiveDevices.setText(showsInactive ? R.string.hide_inactive_devices : R.string.show_inactive_devices);
441                binding.showInactiveDevices.setVisibility(View.VISIBLE);
442            } else {
443                binding.showInactiveDevices.setVisibility(View.GONE);
444            }
445        } else {
446            binding.showInactiveDevices.setVisibility(View.GONE);
447        }
448        binding.scanButton.setVisibility(hasKeys && isCameraFeatureAvailable() ? View.VISIBLE : View.GONE);
449        if (hasKeys) {
450            binding.scanButton.setOnClickListener((v) -> ScanActivity.scan(this));
451        }
452        if (Config.supportOpenPgp() && contact.getPgpKeyId() != 0) {
453            hasKeys = true;
454            View view = inflater.inflate(R.layout.contact_key, binding.detailsContactKeys, false);
455            TextView key = (TextView) view.findViewById(R.id.key);
456            TextView keyType = (TextView) view.findViewById(R.id.key_type);
457            keyType.setText(R.string.openpgp_key_id);
458            if ("pgp".equals(messageFingerprint)) {
459                keyType.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
460            }
461            key.setText(OpenPgpUtils.convertKeyIdToHex(contact.getPgpKeyId()));
462            final OnClickListener openKey = v -> launchOpenKeyChain(contact.getPgpKeyId());
463            view.setOnClickListener(openKey);
464            key.setOnClickListener(openKey);
465            keyType.setOnClickListener(openKey);
466            binding.detailsContactKeys.addView(view);
467        }
468        binding.keysWrapper.setVisibility(hasKeys ? View.VISIBLE : View.GONE);
469
470        List<ListItem.Tag> tagList = contact.getTags(this);
471        if (tagList.size() == 0 || !this.showDynamicTags) {
472            binding.tags.setVisibility(View.GONE);
473        } else {
474            binding.tags.setVisibility(View.VISIBLE);
475            binding.tags.removeAllViewsInLayout();
476            for (final ListItem.Tag tag : tagList) {
477                final TextView tv = (TextView) inflater.inflate(R.layout.list_item_tag, binding.tags, false);
478                tv.setText(tag.getName());
479                tv.setBackgroundColor(tag.getColor());
480                binding.tags.addView(tv);
481            }
482        }
483    }
484
485    public void onBackendConnected() {
486        if (accountJid != null && contactJid != null) {
487            Account account = xmppConnectionService.findAccountByJid(accountJid);
488            if (account == null) {
489                return;
490            }
491            this.contact = account.getRoster().getContact(contactJid);
492            if (mPendingFingerprintVerificationUri != null) {
493                processFingerprintVerification(mPendingFingerprintVerificationUri);
494                mPendingFingerprintVerificationUri = null;
495            }
496
497            if (Compatibility.hasStoragePermission(this)) {
498                final int limit = GridManager.getCurrentColumnCount(this.binding.media);
499                xmppConnectionService.getAttachments(account, contact.getJid().asBareJid(), limit, this);
500                this.binding.showMedia.setOnClickListener((v) -> MediaBrowserActivity.launch(this, contact));
501            }
502            populateView();
503        }
504    }
505
506    @Override
507    public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
508        refreshUi();
509    }
510
511    @Override
512    protected void processFingerprintVerification(XmppUri uri) {
513        if (contact != null && contact.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
514            if (xmppConnectionService.verifyFingerprints(contact, uri.getFingerprints())) {
515                Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
516            }
517        } else {
518            Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
519        }
520    }
521
522    @Override
523    public void onMediaLoaded(List<Attachment> attachments) {
524        runOnUiThread(() -> {
525            int limit = GridManager.getCurrentColumnCount(binding.media);
526            mMediaAdapter.setAttachments(attachments.subList(0, Math.min(limit,attachments.size())));
527            binding.mediaWrapper.setVisibility(attachments.size() > 0 ? View.VISIBLE : View.GONE);
528        });
529
530    }
531}