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