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