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