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