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.graphics.drawable.Drawable;
10import android.net.Uri;
11import android.os.Build;
12import android.os.Bundle;
13import android.preference.PreferenceManager;
14import android.provider.ContactsContract.CommonDataKinds;
15import android.provider.ContactsContract.Contacts;
16import android.provider.ContactsContract.Intents;
17import android.text.Spannable;
18import android.text.SpannableString;
19import android.text.style.RelativeSizeSpan;
20import android.util.TypedValue;
21import android.view.LayoutInflater;
22import android.view.Menu;
23import android.view.MenuItem;
24import android.view.View;
25import android.view.View.OnClickListener;
26import android.view.ViewGroup;
27import android.widget.ArrayAdapter;
28import android.widget.CompoundButton;
29import android.widget.CompoundButton.OnCheckedChangeListener;
30import android.widget.EditText;
31import android.widget.TextView;
32import android.widget.Toast;
33
34import androidx.annotation.NonNull;
35import androidx.appcompat.app.AlertDialog;
36import androidx.databinding.DataBindingUtil;
37
38import com.cheogram.android.Util;
39
40import org.openintents.openpgp.util.OpenPgpUtils;
41
42import java.util.ArrayList;
43import java.util.Collection;
44import java.util.Collections;
45import java.util.Comparator;
46import java.util.List;
47import java.util.Map;
48import java.util.stream.Collectors;
49
50import eu.siacs.conversations.Config;
51import eu.siacs.conversations.R;
52import eu.siacs.conversations.crypto.axolotl.AxolotlService;
53import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
54import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
55import eu.siacs.conversations.databinding.ActivityContactDetailsBinding;
56import eu.siacs.conversations.databinding.CommandRowBinding;
57import eu.siacs.conversations.entities.Account;
58import eu.siacs.conversations.entities.Bookmark;
59import eu.siacs.conversations.entities.Contact;
60import eu.siacs.conversations.entities.ListItem;
61import eu.siacs.conversations.services.AbstractQuickConversationsService;
62import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
63import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
64import eu.siacs.conversations.ui.adapter.MediaAdapter;
65import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
66import eu.siacs.conversations.ui.util.Attachment;
67import eu.siacs.conversations.ui.util.AvatarWorkerTask;
68import eu.siacs.conversations.ui.util.GridManager;
69import eu.siacs.conversations.ui.util.JidDialog;
70import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
71import eu.siacs.conversations.ui.util.ShareUtil;
72import eu.siacs.conversations.utils.AccountUtils;
73import eu.siacs.conversations.utils.Compatibility;
74import eu.siacs.conversations.utils.Emoticons;
75import eu.siacs.conversations.utils.IrregularUnicodeDetector;
76import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
77import eu.siacs.conversations.utils.UIHelper;
78import eu.siacs.conversations.utils.XmppUri;
79import eu.siacs.conversations.xml.Element;
80import eu.siacs.conversations.xml.Namespace;
81import eu.siacs.conversations.xmpp.Jid;
82import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
83import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
84import eu.siacs.conversations.xmpp.XmppConnection;
85
86public class ContactDetailsActivity extends OmemoActivity implements OnAccountUpdate, OnRosterUpdate, OnUpdateBlocklist, OnKeyStatusUpdated, OnMediaLoaded {
87 public static final String ACTION_VIEW_CONTACT = "view_contact";
88 private final int REQUEST_SYNC_CONTACTS = 0x28cf;
89 ActivityContactDetailsBinding binding;
90 private MediaAdapter mMediaAdapter;
91 protected MenuItem edit = null;
92 protected MenuItem save = null;
93
94 private Contact contact;
95 private final DialogInterface.OnClickListener removeFromRoster = new DialogInterface.OnClickListener() {
96
97 @Override
98 public void onClick(DialogInterface dialog, int which) {
99 xmppConnectionService.deleteContactOnServer(contact);
100 }
101 };
102 private final OnCheckedChangeListener mOnSendCheckedChange = new OnCheckedChangeListener() {
103
104 @Override
105 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
106 if (isChecked) {
107 if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
108 xmppConnectionService.stopPresenceUpdatesTo(contact);
109 } else {
110 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
111 }
112 } else {
113 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
114 xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().stopPresenceUpdatesTo(contact));
115 }
116 }
117 };
118 private final OnCheckedChangeListener mOnReceiveCheckedChange = new OnCheckedChangeListener() {
119
120 @Override
121 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
122 if (isChecked) {
123 xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().requestPresenceUpdatesFrom(contact));
124 } else {
125 xmppConnectionService.sendPresencePacket(contact.getAccount(), xmppConnectionService.getPresenceGenerator().stopPresenceUpdatesFrom(contact));
126 }
127 }
128 };
129 private Jid accountJid;
130 private Jid contactJid;
131 private boolean showDynamicTags = false;
132 private boolean showLastSeen = false;
133 private boolean showInactiveOmemo = false;
134 private String messageFingerprint;
135
136 private void checkContactPermissionAndShowAddDialog() {
137 if (hasContactsPermission()) {
138 showAddToPhoneBookDialog();
139 } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
140 requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
141 }
142 }
143
144 private boolean hasContactsPermission() {
145 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
146 return checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
147 } else {
148 return true;
149 }
150 }
151
152 private void showAddToPhoneBookDialog() {
153 final Jid jid = contact.getJid();
154 final boolean quicksyContact = AbstractQuickConversationsService.isQuicksy()
155 && Config.QUICKSY_DOMAIN.equals(jid.getDomain())
156 && jid.getLocal() != null;
157 final String value;
158 if (quicksyContact) {
159 value = PhoneNumberUtilWrapper.toFormattedPhoneNumber(this, jid);
160 } else {
161 value = jid.toEscapedString();
162 }
163 final AlertDialog.Builder builder = new AlertDialog.Builder(this);
164 builder.setTitle(getString(R.string.action_add_phone_book));
165 builder.setMessage(getString(R.string.add_phone_book_text, value));
166 builder.setNegativeButton(getString(R.string.cancel), null);
167 builder.setPositiveButton(getString(R.string.add), (dialog, which) -> {
168 final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
169 intent.setType(Contacts.CONTENT_ITEM_TYPE);
170 if (quicksyContact) {
171 intent.putExtra(Intents.Insert.PHONE, value);
172 } else {
173 intent.putExtra(Intents.Insert.IM_HANDLE, value);
174 intent.putExtra(Intents.Insert.IM_PROTOCOL, CommonDataKinds.Im.PROTOCOL_JABBER);
175 //TODO for modern use we want PROTOCOL_CUSTOM and an extra field with a value of 'XMPP'
176 // however we don’t have such a field and thus have to use the legacy PROTOCOL_JABBER
177 }
178 intent.putExtra("finishActivityOnSaveCompleted", true);
179 try {
180 startActivityForResult(intent, 0);
181 } catch (ActivityNotFoundException e) {
182 Toast.makeText(ContactDetailsActivity.this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
183 }
184 });
185 builder.create().show();
186 }
187
188 @Override
189 public void onRosterUpdate() {
190 refreshUi();
191 }
192
193 @Override
194 public void onAccountUpdate() {
195 refreshUi();
196 }
197
198 @Override
199 public void OnUpdateBlocklist(final Status status) {
200 refreshUi();
201 }
202
203 @Override
204 protected void refreshUiReal() {
205 invalidateOptionsMenu();
206 populateView();
207 }
208
209 @Override
210 protected String getShareableUri(boolean http) {
211 if (http) {
212 return "https://conversations.im/i/" + XmppUri.lameUrlEncode(contact.getJid().asBareJid().toEscapedString());
213 } else {
214 return "xmpp:" + Uri.encode(contact.getJid().asBareJid().toEscapedString(), "@/+");
215 }
216 }
217
218 @Override
219 protected void onCreate(final Bundle savedInstanceState) {
220 super.onCreate(savedInstanceState);
221 showInactiveOmemo = savedInstanceState != null && savedInstanceState.getBoolean("show_inactive_omemo", false);
222 if (getIntent().getAction().equals(ACTION_VIEW_CONTACT)) {
223 try {
224 this.accountJid = Jid.ofEscaped(getIntent().getExtras().getString(EXTRA_ACCOUNT));
225 } catch (final IllegalArgumentException ignored) {
226 }
227 try {
228 this.contactJid = Jid.ofEscaped(getIntent().getExtras().getString("contact"));
229 } catch (final IllegalArgumentException ignored) {
230 }
231 }
232 this.messageFingerprint = getIntent().getStringExtra("fingerprint");
233 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_details);
234
235 setSupportActionBar(binding.toolbar);
236 configureActionBar(getSupportActionBar());
237 binding.showInactiveDevices.setOnClickListener(v -> {
238 showInactiveOmemo = !showInactiveOmemo;
239 populateView();
240 });
241 binding.addContactButton.setOnClickListener(v -> showAddToRosterDialog(contact));
242
243 mMediaAdapter = new MediaAdapter(this, R.dimen.media_size);
244 this.binding.media.setAdapter(mMediaAdapter);
245 GridManager.setupLayoutManager(this, this.binding.media, R.dimen.media_size);
246 }
247
248 @Override
249 public void onSaveInstanceState(final Bundle savedInstanceState) {
250 savedInstanceState.putBoolean("show_inactive_omemo", showInactiveOmemo);
251 super.onSaveInstanceState(savedInstanceState);
252 }
253
254 @Override
255 public void onStart() {
256 super.onStart();
257 final int theme = findTheme();
258 if (this.mTheme != theme) {
259 recreate();
260 } else {
261 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
262 this.showDynamicTags = preferences.getBoolean(SettingsActivity.SHOW_DYNAMIC_TAGS, getResources().getBoolean(R.bool.show_dynamic_tags));
263 this.showLastSeen = preferences.getBoolean("last_activity", false);
264 }
265 binding.mediaWrapper.setVisibility(Compatibility.hasStoragePermission(this) ? View.VISIBLE : View.GONE);
266 mMediaAdapter.setAttachments(Collections.emptyList());
267 }
268
269 @Override
270 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
271 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
272 if (grantResults.length > 0)
273 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
274 if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {
275 showAddToPhoneBookDialog();
276 xmppConnectionService.loadPhoneContacts();
277 xmppConnectionService.startContactObserver();
278 }
279 }
280 }
281
282 protected void saveEdits() {
283 binding.editTags.setVisibility(View.GONE);
284 if (edit != null) {
285 EditText text = edit.getActionView().findViewById(R.id.search_field);
286 contact.setServerName(text.getText().toString());
287 contact.setGroups(binding.editTags.getObjects().stream().map(tag -> tag.getName()).collect(Collectors.toList()));
288 ContactDetailsActivity.this.xmppConnectionService.pushContactToServer(contact);
289 populateView();
290 edit.collapseActionView();
291 }
292 if (save != null) save.setVisible(false);
293 }
294
295 @Override
296 public boolean onOptionsItemSelected(final MenuItem menuItem) {
297 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
298 return false;
299 }
300 final AlertDialog.Builder builder = new AlertDialog.Builder(this);
301 builder.setNegativeButton(getString(R.string.cancel), null);
302 switch (menuItem.getItemId()) {
303 case android.R.id.home:
304 finish();
305 break;
306 case R.id.action_share_http:
307 shareLink(true);
308 break;
309 case R.id.action_share_uri:
310 shareLink(false);
311 break;
312 case R.id.action_delete_contact:
313 builder.setTitle(getString(R.string.action_delete_contact))
314 .setMessage(JidDialog.style(this, R.string.remove_contact_text, contact.getJid().toEscapedString()))
315 .setPositiveButton(getString(R.string.delete),
316 removeFromRoster).create().show();
317 break;
318 case R.id.action_save:
319 saveEdits();
320 break;
321 case R.id.action_edit_contact:
322 Uri systemAccount = contact.getSystemAccount();
323 if (systemAccount == null) {
324 menuItem.expandActionView();
325 EditText text = menuItem.getActionView().findViewById(R.id.search_field);
326 text.setOnEditorActionListener((v, actionId, event) -> {
327 saveEdits();
328 return true;
329 });
330 text.setText(contact.getServerName());
331 text.requestFocus();
332 binding.tags.setVisibility(View.GONE);
333 binding.editTags.clearSync();
334 for (final ListItem.Tag group : contact.getGroupTags()) {
335 binding.editTags.addObjectSync(group);
336 }
337 ArrayList<ListItem.Tag> tags = new ArrayList<>();
338 for (final Account account : xmppConnectionService.getAccounts()) {
339 for (Contact contact : account.getRoster().getContacts()) {
340 tags.addAll(contact.getTags(this));
341 }
342 for (Bookmark bookmark : account.getBookmarks()) {
343 tags.addAll(bookmark.getTags(this));
344 }
345 }
346 Comparator<Map.Entry<ListItem.Tag,Integer>> sortTagsBy = Map.Entry.comparingByValue(Comparator.reverseOrder());
347 sortTagsBy = sortTagsBy.thenComparing(entry -> entry.getKey().getName());
348
349 ArrayAdapter<ListItem.Tag> adapter = new ArrayAdapter<>(
350 this,
351 android.R.layout.simple_list_item_1,
352 tags.stream()
353 .collect(Collectors.toMap((x) -> x, (t) -> 1, (c1, c2) -> c1 + c2))
354 .entrySet().stream()
355 .sorted(sortTagsBy)
356 .map(e -> e.getKey()).collect(Collectors.toList())
357 );
358 binding.editTags.setAdapter(adapter);
359 if (showDynamicTags) binding.editTags.setVisibility(View.VISIBLE);
360 if (save != null) save.setVisible(true);
361 } else {
362 menuItem.collapseActionView();
363 if (save != null) save.setVisible(false);
364 Intent intent = new Intent(Intent.ACTION_EDIT);
365 intent.setDataAndType(systemAccount, Contacts.CONTENT_ITEM_TYPE);
366 intent.putExtra("finishActivityOnSaveCompleted", true);
367 try {
368 startActivity(intent);
369 } catch (ActivityNotFoundException e) {
370 Toast.makeText(ContactDetailsActivity.this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
371 }
372
373 }
374 break;
375 case R.id.action_block:
376 BlockContactDialog.show(this, contact);
377 break;
378 case R.id.action_unblock:
379 BlockContactDialog.show(this, contact);
380 break;
381 }
382 return super.onOptionsItemSelected(menuItem);
383 }
384
385 @Override
386 public boolean onCreateOptionsMenu(final Menu menu) {
387 getMenuInflater().inflate(R.menu.contact_details, menu);
388 AccountUtils.showHideMenuItems(menu);
389 edit = menu.findItem(R.id.action_edit_contact);
390 save = menu.findItem(R.id.action_save);
391 MenuItem block = menu.findItem(R.id.action_block);
392 MenuItem unblock = menu.findItem(R.id.action_unblock);
393 MenuItem edit = menu.findItem(R.id.action_edit_contact);
394 MenuItem delete = menu.findItem(R.id.action_delete_contact);
395 if (contact == null) {
396 return true;
397 }
398 final XmppConnection connection = contact.getAccount().getXmppConnection();
399 if (connection != null && connection.getFeatures().blocking()) {
400 if (this.contact.isBlocked()) {
401 block.setVisible(false);
402 } else {
403 unblock.setVisible(false);
404 }
405 } else {
406 unblock.setVisible(false);
407 block.setVisible(false);
408 }
409 if (!contact.showInRoster()) {
410 edit.setVisible(false);
411 delete.setVisible(false);
412 }
413 edit.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
414 @Override
415 public boolean onMenuItemActionCollapse(MenuItem item) {
416 binding.editTags.setVisibility(View.GONE);
417 if (save != null) save.setVisible(false);
418 populateView();
419 return true;
420 }
421
422 @Override
423 public boolean onMenuItemActionExpand(MenuItem item) { return true; }
424 });
425 return super.onCreateOptionsMenu(menu);
426 }
427
428 private void populateView() {
429 if (contact == null) {
430 return;
431 }
432 if (binding.editTags.getVisibility() != View.GONE) return;
433 invalidateOptionsMenu();
434 setTitle(contact.getDisplayName());
435 if (contact.showInRoster()) {
436 binding.detailsSendPresence.setVisibility(View.VISIBLE);
437 binding.detailsReceivePresence.setVisibility(View.VISIBLE);
438 binding.addContactButton.setVisibility(View.GONE);
439 binding.detailsSendPresence.setOnCheckedChangeListener(null);
440 binding.detailsReceivePresence.setOnCheckedChangeListener(null);
441
442 List<String> statusMessages = contact.getPresences().getStatusMessages();
443 if (statusMessages.size() == 0) {
444 binding.statusMessage.setVisibility(View.GONE);
445 } else if (statusMessages.size() == 1) {
446 final String message = statusMessages.get(0);
447 binding.statusMessage.setVisibility(View.VISIBLE);
448 final Spannable span = new SpannableString(message);
449 if (Emoticons.isOnlyEmoji(message)) {
450 span.setSpan(new RelativeSizeSpan(2.0f), 0, message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
451 }
452 binding.statusMessage.setText(span);
453 } else {
454 StringBuilder builder = new StringBuilder();
455 binding.statusMessage.setVisibility(View.VISIBLE);
456 int s = statusMessages.size();
457 for (int i = 0; i < s; ++i) {
458 builder.append(statusMessages.get(i));
459 if (i < s - 1) {
460 builder.append("\n");
461 }
462 }
463 binding.statusMessage.setText(builder);
464 }
465
466 if (contact.getOption(Contact.Options.FROM)) {
467 binding.detailsSendPresence.setText(R.string.send_presence_updates);
468 binding.detailsSendPresence.setChecked(true);
469 } else if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
470 binding.detailsSendPresence.setChecked(false);
471 binding.detailsSendPresence.setText(R.string.send_presence_updates);
472 } else {
473 binding.detailsSendPresence.setText(R.string.preemptively_grant);
474 binding.detailsSendPresence.setChecked(contact.getOption(Contact.Options.PREEMPTIVE_GRANT));
475 }
476 if (contact.getOption(Contact.Options.TO)) {
477 binding.detailsReceivePresence.setText(R.string.receive_presence_updates);
478 binding.detailsReceivePresence.setChecked(true);
479 } else {
480 binding.detailsReceivePresence.setText(R.string.ask_for_presence_updates);
481 binding.detailsReceivePresence.setChecked(contact.getOption(Contact.Options.ASKING));
482 }
483 if (contact.getAccount().isOnlineAndConnected()) {
484 binding.detailsReceivePresence.setEnabled(true);
485 binding.detailsSendPresence.setEnabled(true);
486 } else {
487 binding.detailsReceivePresence.setEnabled(false);
488 binding.detailsSendPresence.setEnabled(false);
489 }
490 binding.detailsSendPresence.setOnCheckedChangeListener(this.mOnSendCheckedChange);
491 binding.detailsReceivePresence.setOnCheckedChangeListener(this.mOnReceiveCheckedChange);
492 } else {
493 binding.addContactButton.setVisibility(View.VISIBLE);
494 binding.detailsSendPresence.setVisibility(View.GONE);
495 binding.detailsReceivePresence.setVisibility(View.GONE);
496 binding.statusMessage.setVisibility(View.GONE);
497 }
498
499 if (contact.isBlocked() && !this.showDynamicTags) {
500 binding.detailsLastseen.setVisibility(View.VISIBLE);
501 binding.detailsLastseen.setText(R.string.contact_blocked);
502 } else {
503 if (showLastSeen
504 && contact.getLastseen() > 0
505 && contact.getPresences().allOrNonSupport(Namespace.IDLE)) {
506 binding.detailsLastseen.setVisibility(View.VISIBLE);
507 binding.detailsLastseen.setText(UIHelper.lastseen(getApplicationContext(), contact.isActive(), contact.getLastseen()));
508 } else {
509 binding.detailsLastseen.setVisibility(View.GONE);
510 }
511 }
512
513 binding.detailsContactjid.setText(IrregularUnicodeDetector.style(this, contact.getJid()));
514 String account;
515 if (Config.DOMAIN_LOCK != null) {
516 account = contact.getAccount().getJid().getEscapedLocal();
517 } else {
518 account = contact.getAccount().getJid().asBareJid().toEscapedString();
519 }
520 binding.detailsAccount.setText(getString(R.string.using_account, account));
521 AvatarWorkerTask.loadAvatar(contact, binding.detailsContactBadge, R.dimen.avatar_on_details_screen_size);
522 binding.detailsContactBadge.setOnClickListener(this::onBadgeClick);
523
524 binding.detailsContactKeys.removeAllViews();
525 boolean hasKeys = false;
526 final LayoutInflater inflater = getLayoutInflater();
527 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
528 if (Config.supportOmemo() && axolotlService != null) {
529 final Collection<XmppAxolotlSession> sessions = axolotlService.findSessionsForContact(contact);
530 boolean anyActive = false;
531 for (XmppAxolotlSession session : sessions) {
532 anyActive = session.getTrust().isActive();
533 if (anyActive) {
534 break;
535 }
536 }
537 boolean skippedInactive = false;
538 boolean showsInactive = false;
539 for (final XmppAxolotlSession session : sessions) {
540 final FingerprintStatus trust = session.getTrust();
541 hasKeys |= !trust.isCompromised();
542 if (!trust.isActive() && anyActive) {
543 if (showInactiveOmemo) {
544 showsInactive = true;
545 } else {
546 skippedInactive = true;
547 continue;
548 }
549 }
550 if (!trust.isCompromised()) {
551 boolean highlight = session.getFingerprint().equals(messageFingerprint);
552 addFingerprintRow(binding.detailsContactKeys, session, highlight);
553 }
554 }
555 if (showsInactive || skippedInactive) {
556 binding.showInactiveDevices.setText(showsInactive ? R.string.hide_inactive_devices : R.string.show_inactive_devices);
557 binding.showInactiveDevices.setVisibility(View.VISIBLE);
558 } else {
559 binding.showInactiveDevices.setVisibility(View.GONE);
560 }
561 } else {
562 binding.showInactiveDevices.setVisibility(View.GONE);
563 }
564 binding.scanButton.setVisibility(hasKeys && isCameraFeatureAvailable() ? View.VISIBLE : View.GONE);
565 if (hasKeys) {
566 binding.scanButton.setOnClickListener((v) -> ScanActivity.scan(this));
567 }
568 if (Config.supportOpenPgp() && contact.getPgpKeyId() != 0) {
569 hasKeys = true;
570 View view = inflater.inflate(R.layout.contact_key, binding.detailsContactKeys, false);
571 TextView key = view.findViewById(R.id.key);
572 TextView keyType = view.findViewById(R.id.key_type);
573 keyType.setText(R.string.openpgp_key_id);
574 if ("pgp".equals(messageFingerprint)) {
575 keyType.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
576 }
577 key.setText(OpenPgpUtils.convertKeyIdToHex(contact.getPgpKeyId()));
578 final OnClickListener openKey = v -> launchOpenKeyChain(contact.getPgpKeyId());
579 view.setOnClickListener(openKey);
580 key.setOnClickListener(openKey);
581 keyType.setOnClickListener(openKey);
582 binding.detailsContactKeys.addView(view);
583 }
584 binding.keysWrapper.setVisibility(hasKeys ? View.VISIBLE : View.GONE);
585
586 List<ListItem.Tag> tagList = contact.getTags(this);
587 if (tagList.size() == 0 || !this.showDynamicTags) {
588 binding.tags.setVisibility(View.GONE);
589 } else {
590 binding.tags.setVisibility(View.VISIBLE);
591 binding.tags.removeAllViewsInLayout();
592 for (final ListItem.Tag tag : tagList) {
593 final TextView tv = (TextView) inflater.inflate(R.layout.list_item_tag, binding.tags, false);
594 tv.setText(tag.getName());
595 tv.setBackgroundColor(tag.getColor());
596 binding.tags.addView(tv);
597 }
598 }
599 }
600
601 private void onBadgeClick(View view) {
602 final Uri systemAccount = contact.getSystemAccount();
603 if (systemAccount == null) {
604 checkContactPermissionAndShowAddDialog();
605 } else {
606 final Intent intent = new Intent(Intent.ACTION_VIEW);
607 intent.setData(systemAccount);
608 try {
609 startActivity(intent);
610 } catch (final ActivityNotFoundException e) {
611 Toast.makeText(this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
612 }
613 }
614 }
615
616 public void onBackendConnected() {
617 if (accountJid != null && contactJid != null) {
618 Account account = xmppConnectionService.findAccountByJid(accountJid);
619 if (account == null) {
620 return;
621 }
622 this.contact = account.getRoster().getContact(contactJid);
623 if (mPendingFingerprintVerificationUri != null) {
624 processFingerprintVerification(mPendingFingerprintVerificationUri);
625 mPendingFingerprintVerificationUri = null;
626 }
627
628 if (Compatibility.hasStoragePermission(this)) {
629 final int limit = GridManager.getCurrentColumnCount(this.binding.media);
630 xmppConnectionService.getAttachments(account, contact.getJid().asBareJid(), limit, this);
631 this.binding.showMedia.setOnClickListener((v) -> MediaBrowserActivity.launch(this, contact));
632 }
633
634 final VcardAdapter items = new VcardAdapter();
635 binding.profileItems.setAdapter(items);
636 binding.profileItems.setOnItemClickListener((a0, v, pos, a3) -> {
637 final Uri uri = items.getUri(pos);
638 if (uri == null) return;
639
640 if (uri.getScheme().equals("xmpp")) {
641 switchToConversation(xmppConnectionService.findOrCreateConversation(account, Jid.of(uri.getSchemeSpecificPart()), false, true));
642 } else {
643 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
644 startActivity(intent);
645 }
646 });
647 binding.profileItems.setOnItemLongClickListener((a0, v, pos, a3) -> {
648 String toCopy = null;
649 final Uri uri = items.getUri(pos);
650 if (uri != null) toCopy = uri.toString();
651 if (toCopy == null) {
652 toCopy = items.getItem(pos).findChildContent("text", Namespace.VCARD4);
653 }
654
655 if (toCopy == null) return false;
656 if (ShareUtil.copyTextToClipboard(ContactDetailsActivity.this, toCopy, R.string.message)) {
657 Toast.makeText(ContactDetailsActivity.this, R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
658 }
659 return true;
660 });
661 xmppConnectionService.fetchVcard4(account, contact, (vcard4) -> {
662 if (vcard4 == null) return;
663
664 runOnUiThread(() -> {
665 for (Element el : vcard4.getChildren()) {
666 if (el.findChildEnsureSingle("uri", Namespace.VCARD4) != null || el.findChildEnsureSingle("text", Namespace.VCARD4) != null) {
667 items.add(el);
668 }
669 }
670 Util.justifyListViewHeightBasedOnChildren(binding.profileItems);
671 });
672 });
673
674 populateView();
675 }
676 }
677
678 @Override
679 public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
680 refreshUi();
681 }
682
683 @Override
684 protected void processFingerprintVerification(XmppUri uri) {
685 if (contact != null && contact.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
686 if (xmppConnectionService.verifyFingerprints(contact, uri.getFingerprints())) {
687 Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
688 }
689 } else {
690 Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
691 }
692 }
693
694 @Override
695 public void onMediaLoaded(List<Attachment> attachments) {
696 runOnUiThread(() -> {
697 int limit = GridManager.getCurrentColumnCount(binding.media);
698 mMediaAdapter.setAttachments(attachments.subList(0, Math.min(limit, attachments.size())));
699 binding.mediaWrapper.setVisibility(attachments.size() > 0 ? View.VISIBLE : View.GONE);
700 });
701
702 }
703
704 class VcardAdapter extends ArrayAdapter<Element> {
705 VcardAdapter() { super(ContactDetailsActivity.this, 0); }
706
707 private Drawable getDrawable(int attr) {
708 final TypedValue typedvalueattr = new TypedValue();
709 getTheme().resolveAttribute(attr, typedvalueattr, true);
710 return getResources().getDrawable(typedvalueattr.resourceId);
711 }
712
713 @Override
714 public View getView(int position, View view, @NonNull ViewGroup parent) {
715 final CommandRowBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.command_row, parent, false);
716 final Element item = getItem(position);
717
718 if (item.getName().equals("org")) {
719 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_org), null, null, null);
720 binding.command.setCompoundDrawablePadding(20);
721 } else if (item.getName().equals("impp")) {
722 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_chat), null, null, null);
723 binding.command.setCompoundDrawablePadding(20);
724 } else if (item.getName().equals("url")) {
725 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_link), null, null, null);
726 binding.command.setCompoundDrawablePadding(20);
727 }
728
729 final Uri uri = getUri(position);
730 if (uri != null && uri.getScheme() != null) {
731 if (uri.getScheme().equals("xmpp")) {
732 binding.command.setText(uri.getSchemeSpecificPart());
733 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getResources().getDrawable(R.drawable.jabber), null, null, null);
734 binding.command.setCompoundDrawablePadding(20);
735 } else if (uri.getScheme().equals("tel")) {
736 binding.command.setText(uri.getSchemeSpecificPart());
737 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.ic_make_audio_call), null, null, null);
738 binding.command.setCompoundDrawablePadding(20);
739 } else if (uri.getScheme().equals("mailto")) {
740 binding.command.setText(uri.getSchemeSpecificPart());
741 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_email), null, null, null);
742 binding.command.setCompoundDrawablePadding(20);
743 } else if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) {
744 binding.command.setText(uri.toString());
745 binding.command.setCompoundDrawablesRelativeWithIntrinsicBounds(getDrawable(R.attr.icon_link), null, null, null);
746 binding.command.setCompoundDrawablePadding(20);
747 } else {
748 binding.command.setText(uri.toString());
749 }
750 } else {
751 final String text = item.findChildContent("text", Namespace.VCARD4);
752 binding.command.setText(text);
753 }
754
755 return binding.getRoot();
756 }
757
758 public Uri getUri(int pos) {
759 final Element item = getItem(pos);
760 final String uriS = item.findChildContent("uri", Namespace.VCARD4);
761 if (uriS != null) return Uri.parse(uriS).normalizeScheme();
762 if (item.getName().equals("email")) return Uri.parse("mailto:" + item.findChildContent("text", Namespace.VCARD4));
763 return null;
764 }
765 }
766}