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