1package eu.siacs.conversations.ui;
2
3import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
4import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION;
5import static eu.siacs.conversations.ui.util.SoftKeyboardUtils.hideSoftKeyboard;
6import static eu.siacs.conversations.utils.PermissionUtils.allGranted;
7import static eu.siacs.conversations.utils.PermissionUtils.audioGranted;
8import static eu.siacs.conversations.utils.PermissionUtils.cameraGranted;
9import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
10import static eu.siacs.conversations.utils.PermissionUtils.writeGranted;
11
12import android.Manifest;
13import android.annotation.SuppressLint;
14import android.app.Activity;
15import android.app.DatePickerDialog;
16import android.app.Fragment;
17import android.app.FragmentManager;
18import android.app.PendingIntent;
19import android.app.TimePickerDialog;
20import android.content.ActivityNotFoundException;
21import android.content.Context;
22import android.content.DialogInterface;
23import android.content.Intent;
24import android.content.IntentSender.SendIntentException;
25import android.content.SharedPreferences;
26import android.content.pm.PackageManager;
27import android.content.res.ColorStateList;
28import android.graphics.Color;
29import android.icu.util.Calendar;
30import android.icu.util.TimeZone;
31import android.net.Uri;
32import android.os.Build;
33import android.os.Bundle;
34import android.os.Environment;
35import android.os.Handler;
36import android.os.Looper;
37import android.os.storage.StorageManager;
38import android.os.SystemClock;
39import android.preference.PreferenceManager;
40import android.provider.MediaStore;
41import android.text.Editable;
42import android.text.SpannableStringBuilder;
43import android.text.TextUtils;
44import android.text.TextWatcher;
45import android.text.style.ImageSpan;
46import android.util.DisplayMetrics;
47import android.util.Log;
48import android.view.ContextMenu;
49import android.view.ContextMenu.ContextMenuInfo;
50import android.view.Gravity;
51import android.view.LayoutInflater;
52import android.view.Menu;
53import android.view.MenuInflater;
54import android.view.MenuItem;
55import android.view.MotionEvent;
56import android.view.View;
57import android.view.View.OnClickListener;
58import android.view.ViewGroup;
59import android.view.inputmethod.EditorInfo;
60import android.view.inputmethod.InputMethodManager;
61import android.view.WindowManager;
62import android.widget.AbsListView;
63import android.widget.AbsListView.OnScrollListener;
64import android.widget.AdapterView;
65import android.widget.AdapterView.AdapterContextMenuInfo;
66import android.widget.CheckBox;
67import android.widget.ListView;
68import android.widget.PopupMenu;
69import android.widget.PopupWindow;
70import android.widget.TextView.OnEditorActionListener;
71import android.widget.Toast;
72
73import androidx.activity.OnBackPressedCallback;
74import androidx.annotation.IdRes;
75import androidx.annotation.NonNull;
76import androidx.annotation.Nullable;
77import androidx.annotation.StringRes;
78import androidx.appcompat.app.AlertDialog;
79import androidx.core.content.pm.ShortcutInfoCompat;
80import androidx.core.content.pm.ShortcutManagerCompat;
81import androidx.core.graphics.ColorUtils;
82import androidx.core.view.inputmethod.InputConnectionCompat;
83import androidx.core.view.inputmethod.InputContentInfoCompat;
84import androidx.databinding.DataBindingUtil;
85import androidx.documentfile.provider.DocumentFile;
86import androidx.recyclerview.widget.RecyclerView.Adapter;
87import androidx.viewpager.widget.PagerAdapter;
88import androidx.viewpager.widget.ViewPager;
89
90import com.cheogram.android.BobTransfer;
91import com.cheogram.android.EmojiSearch;
92import com.cheogram.android.EditMessageSelectionActionModeCallback;
93import com.cheogram.android.WebxdcPage;
94import com.cheogram.android.WebxdcStore;
95
96import com.google.android.material.color.MaterialColors;
97import com.google.android.material.dialog.MaterialAlertDialogBuilder;
98import com.google.common.base.Optional;
99import com.google.common.collect.Collections2;
100import com.google.common.collect.ImmutableList;
101import com.google.common.collect.ImmutableSet;
102import com.google.common.collect.Lists;
103import com.google.common.collect.Ordering;
104import com.google.common.io.Files;
105
106import com.otaliastudios.autocomplete.Autocomplete;
107import com.otaliastudios.autocomplete.AutocompleteCallback;
108import com.otaliastudios.autocomplete.AutocompletePresenter;
109import com.otaliastudios.autocomplete.CharPolicy;
110import com.otaliastudios.autocomplete.RecyclerViewPresenter;
111
112import org.jetbrains.annotations.NotNull;
113
114import io.ipfs.cid.Cid;
115
116import java.io.File;
117import java.net.URISyntaxException;
118import java.util.AbstractMap;
119import java.util.ArrayList;
120import java.util.Arrays;
121import java.util.Collection;
122import java.util.Collections;
123import java.util.HashSet;
124import java.util.Iterator;
125import java.util.List;
126import java.util.Locale;
127import java.util.Map;
128import java.util.Set;
129import java.util.UUID;
130import java.util.concurrent.atomic.AtomicBoolean;
131import java.util.regex.Matcher;
132import java.util.regex.Pattern;
133import java.util.stream.Collectors;
134
135import eu.siacs.conversations.Config;
136import eu.siacs.conversations.R;
137import eu.siacs.conversations.crypto.axolotl.AxolotlService;
138import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
139import eu.siacs.conversations.databinding.FragmentConversationBinding;
140import eu.siacs.conversations.entities.Account;
141import eu.siacs.conversations.entities.Blockable;
142import eu.siacs.conversations.entities.Contact;
143import eu.siacs.conversations.entities.Conversation;
144import eu.siacs.conversations.entities.Conversational;
145import eu.siacs.conversations.entities.DownloadableFile;
146import eu.siacs.conversations.entities.Message;
147import eu.siacs.conversations.entities.MucOptions;
148import eu.siacs.conversations.entities.MucOptions.User;
149import eu.siacs.conversations.entities.Presence;
150import eu.siacs.conversations.entities.Presences;
151import eu.siacs.conversations.entities.ReadByMarker;
152import eu.siacs.conversations.entities.Transferable;
153import eu.siacs.conversations.entities.TransferablePlaceholder;
154import eu.siacs.conversations.http.HttpDownloadConnection;
155import eu.siacs.conversations.persistance.FileBackend;
156import eu.siacs.conversations.services.CallIntegrationConnectionService;
157import eu.siacs.conversations.services.MessageArchiveService;
158import eu.siacs.conversations.services.QuickConversationsService;
159import eu.siacs.conversations.services.XmppConnectionService;
160import eu.siacs.conversations.ui.adapter.CommandAdapter;
161import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
162import eu.siacs.conversations.ui.adapter.MessageAdapter;
163import eu.siacs.conversations.ui.adapter.UserAdapter;
164import eu.siacs.conversations.ui.util.ActivityResult;
165import eu.siacs.conversations.ui.util.Attachment;
166import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
167import eu.siacs.conversations.ui.util.DateSeparator;
168import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
169import eu.siacs.conversations.ui.util.ListViewUtils;
170import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
171import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
172import eu.siacs.conversations.ui.util.PendingItem;
173import eu.siacs.conversations.ui.util.PresenceSelector;
174import eu.siacs.conversations.ui.util.ScrollState;
175import eu.siacs.conversations.ui.util.SendButtonAction;
176import eu.siacs.conversations.ui.util.SendButtonTool;
177import eu.siacs.conversations.ui.util.ShareUtil;
178import eu.siacs.conversations.ui.util.ViewUtil;
179import eu.siacs.conversations.ui.widget.EditMessage;
180import eu.siacs.conversations.utils.AccountUtils;
181import eu.siacs.conversations.utils.Compatibility;
182import eu.siacs.conversations.utils.Emoticons;
183import eu.siacs.conversations.utils.GeoHelper;
184import eu.siacs.conversations.utils.MessageUtils;
185import eu.siacs.conversations.utils.MimeUtils;
186import eu.siacs.conversations.utils.NickValidityChecker;
187import eu.siacs.conversations.utils.PermissionUtils;
188import eu.siacs.conversations.utils.QuickLoader;
189import eu.siacs.conversations.utils.StylingHelper;
190import eu.siacs.conversations.utils.TimeFrameUtils;
191import eu.siacs.conversations.utils.UIHelper;
192import eu.siacs.conversations.xml.Element;
193import eu.siacs.conversations.xml.Namespace;
194import eu.siacs.conversations.xmpp.Jid;
195import eu.siacs.conversations.xmpp.XmppConnection;
196import eu.siacs.conversations.xmpp.chatstate.ChatState;
197import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
198import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
199import eu.siacs.conversations.xmpp.jingle.JingleFileTransferConnection;
200import eu.siacs.conversations.xmpp.jingle.Media;
201import eu.siacs.conversations.xmpp.jingle.OngoingRtpSession;
202import eu.siacs.conversations.xmpp.jingle.RtpCapability;
203import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
204
205import im.conversations.android.xmpp.model.stanza.Iq;
206
207import org.jetbrains.annotations.NotNull;
208
209public class ConversationFragment extends XmppFragment
210 implements EditMessage.KeyboardListener,
211 MessageAdapter.OnContactPictureLongClicked,
212 MessageAdapter.OnContactPictureClicked,
213 MessageAdapter.OnInlineImageLongClicked {
214
215 public static final int REQUEST_SEND_MESSAGE = 0x0201;
216 public static final int REQUEST_DECRYPT_PGP = 0x0202;
217 public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
218 public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
219 public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209;
220 public static final int REQUEST_START_DOWNLOAD = 0x0210;
221 public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
222 public static final int REQUEST_COMMIT_ATTACHMENTS = 0x0212;
223 public static final int REQUEST_START_AUDIO_CALL = 0x213;
224 public static final int REQUEST_START_VIDEO_CALL = 0x214;
225 public static final int REQUEST_SAVE_STICKER = 0x215;
226 public static final int REQUEST_WEBXDC_STORE = 0x216;
227 public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
228 public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
229 public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
230 public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
231 public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
232 public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
233 public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
234
235 public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
236 public static final String STATE_CONVERSATION_UUID =
237 ConversationFragment.class.getName() + ".uuid";
238 public static final String STATE_SCROLL_POSITION =
239 ConversationFragment.class.getName() + ".scroll_position";
240 public static final String STATE_PHOTO_URI =
241 ConversationFragment.class.getName() + ".media_previews";
242 public static final String STATE_MEDIA_PREVIEWS =
243 ConversationFragment.class.getName() + ".take_photo_uri";
244 private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid";
245
246 private final List<Message> messageList = new ArrayList<>();
247 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
248 private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
249 private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>();
250 private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
251 private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
252 private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
253 private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>();
254 private final PendingItem<Message> pendingMessage = new PendingItem<>();
255 public Uri mPendingEditorContent = null;
256 protected ArrayList<WebxdcPage> extensions = new ArrayList<>();
257 protected MessageAdapter messageListAdapter;
258 protected CommandAdapter commandAdapter;
259 private MediaPreviewAdapter mediaPreviewAdapter;
260 private String lastMessageUuid = null;
261 private Conversation conversation;
262 private FragmentConversationBinding binding;
263 private Toast messageLoaderToast;
264 private ConversationsActivity activity;
265 private boolean reInitRequiredOnStart = true;
266 private int identiconWidth = -1;
267 private File savingAsSticker = null;
268 private EmojiSearch emojiSearch = null;
269 private final OnClickListener clickToMuc =
270 new OnClickListener() {
271
272 @Override
273 public void onClick(View v) {
274 ConferenceDetailsActivity.open(getActivity(), conversation);
275 }
276 };
277 private final OnClickListener leaveMuc =
278 new OnClickListener() {
279
280 @Override
281 public void onClick(View v) {
282 activity.xmppConnectionService.archiveConversation(conversation);
283 }
284 };
285 private final OnClickListener joinMuc =
286 new OnClickListener() {
287
288 @Override
289 public void onClick(View v) {
290 activity.xmppConnectionService.joinMuc(conversation);
291 }
292 };
293
294 private final OnClickListener acceptJoin =
295 new OnClickListener() {
296 @Override
297 public void onClick(View v) {
298 conversation.setAttribute("accept_non_anonymous", true);
299 activity.xmppConnectionService.updateConversation(conversation);
300 activity.xmppConnectionService.joinMuc(conversation);
301 }
302 };
303
304 private final OnClickListener enterPassword =
305 new OnClickListener() {
306
307 @Override
308 public void onClick(View v) {
309 MucOptions muc = conversation.getMucOptions();
310 String password = muc.getPassword();
311 if (password == null) {
312 password = "";
313 }
314 activity.quickPasswordEdit(
315 password,
316 value -> {
317 activity.xmppConnectionService.providePasswordForMuc(
318 conversation, value);
319 return null;
320 });
321 }
322 };
323 private final OnScrollListener mOnScrollListener =
324 new OnScrollListener() {
325
326 @Override
327 public void onScrollStateChanged(AbsListView view, int scrollState) {
328 if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
329 updateThreadFromLastMessage();
330 fireReadEvent();
331 }
332 }
333
334 @Override
335 public void onScroll(
336 final AbsListView view,
337 int firstVisibleItem,
338 int visibleItemCount,
339 int totalItemCount) {
340 toggleScrollDownButton(view);
341 synchronized (ConversationFragment.this.messageList) {
342 if (firstVisibleItem < 5
343 && conversation != null
344 && conversation.messagesLoaded.compareAndSet(true, false)
345 && messageList.size() > 0) {
346 long timestamp = conversation.loadMoreTimestamp();
347 activity.xmppConnectionService.loadMoreMessages(
348 conversation,
349 timestamp,
350 new XmppConnectionService.OnMoreMessagesLoaded() {
351 @Override
352 public void onMoreMessagesLoaded(
353 final int c, final Conversation conversation) {
354 if (ConversationFragment.this.conversation
355 != conversation) {
356 conversation.messagesLoaded.set(true);
357 return;
358 }
359 runOnUiThread(
360 () -> {
361 synchronized (messageList) {
362 final int oldPosition =
363 binding.messagesView
364 .getFirstVisiblePosition();
365 Message message = null;
366 int childPos;
367 for (childPos = 0;
368 childPos + oldPosition
369 < messageList.size();
370 ++childPos) {
371 message =
372 messageList.get(
373 oldPosition
374 + childPos);
375 if (message.getType()
376 != Message.TYPE_STATUS) {
377 break;
378 }
379 }
380 final String uuid =
381 message != null
382 ? message.getUuid()
383 : null;
384 View v =
385 binding.messagesView.getChildAt(
386 childPos);
387 final int pxOffset =
388 (v == null) ? 0 : v.getTop();
389 ConversationFragment.this.conversation
390 .populateWithMessages(
391 ConversationFragment
392 .this
393 .messageList, activity == null ? null : activity.xmppConnectionService);
394 try {
395 updateStatusMessages();
396 } catch (IllegalStateException e) {
397 Log.d(
398 Config.LOGTAG,
399 "caught illegal state"
400 + " exception while"
401 + " updating status"
402 + " messages");
403 }
404 messageListAdapter
405 .notifyDataSetChanged();
406 int pos =
407 Math.max(
408 getIndexOf(
409 uuid,
410 messageList),
411 0);
412 binding.messagesView
413 .setSelectionFromTop(
414 pos, pxOffset);
415 if (messageLoaderToast != null) {
416 messageLoaderToast.cancel();
417 }
418 conversation.messagesLoaded.set(true);
419 }
420 });
421 }
422
423 @Override
424 public void informUser(final int resId) {
425
426 runOnUiThread(
427 () -> {
428 if (messageLoaderToast != null) {
429 messageLoaderToast.cancel();
430 }
431 if (ConversationFragment.this.conversation
432 != conversation) {
433 return;
434 }
435 messageLoaderToast =
436 Toast.makeText(
437 view.getContext(),
438 resId,
439 Toast.LENGTH_LONG);
440 messageLoaderToast.show();
441 });
442 }
443 });
444 }
445 }
446 }
447 };
448 private final EditMessage.OnCommitContentListener mEditorContentListener =
449 new EditMessage.OnCommitContentListener() {
450 @Override
451 public boolean onCommitContent(
452 InputContentInfoCompat inputContentInfo,
453 int flags,
454 Bundle opts,
455 String[] contentMimeTypes) {
456 // try to get permission to read the image, if applicable
457 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION)
458 != 0) {
459 try {
460 inputContentInfo.requestPermission();
461 } catch (Exception e) {
462 Log.e(
463 Config.LOGTAG,
464 "InputContentInfoCompat#requestPermission() failed.",
465 e);
466 Toast.makeText(
467 getActivity(),
468 activity.getString(
469 R.string.no_permission_to_access_x,
470 inputContentInfo.getDescription()),
471 Toast.LENGTH_LONG)
472 .show();
473 return false;
474 }
475 }
476 if (hasPermissions(
477 REQUEST_ADD_EDITOR_CONTENT,
478 Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
479 attachEditorContentToConversation(inputContentInfo.getContentUri());
480 } else {
481 mPendingEditorContent = inputContentInfo.getContentUri();
482 }
483 return true;
484 }
485 };
486 private Message selectedMessage;
487 private final OnClickListener mEnableAccountListener =
488 new OnClickListener() {
489 @Override
490 public void onClick(View v) {
491 final Account account = conversation == null ? null : conversation.getAccount();
492 if (account != null) {
493 account.setOption(Account.OPTION_SOFT_DISABLED, false);
494 account.setOption(Account.OPTION_DISABLED, false);
495 activity.xmppConnectionService.updateAccount(account);
496 }
497 }
498 };
499 private final OnClickListener mUnblockClickListener =
500 new OnClickListener() {
501 @Override
502 public void onClick(final View v) {
503 v.post(() -> v.setVisibility(View.INVISIBLE));
504 if (conversation.isDomainBlocked()) {
505 BlockContactDialog.show(activity, conversation);
506 } else {
507 unblockConversation(conversation);
508 }
509 }
510 };
511 private final OnClickListener mBlockClickListener = this::showBlockSubmenu;
512 private final OnClickListener mAddBackClickListener =
513 new OnClickListener() {
514
515 @Override
516 public void onClick(View v) {
517 final Contact contact = conversation == null ? null : conversation.getContact();
518 if (contact != null) {
519 activity.xmppConnectionService.createContact(contact, true);
520 activity.switchToContactDetails(contact);
521 }
522 }
523 };
524 private final View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
525 private final OnClickListener mAllowPresenceSubscription =
526 new OnClickListener() {
527 @Override
528 public void onClick(View v) {
529 final Contact contact = conversation == null ? null : conversation.getContact();
530 if (contact != null) {
531 activity.xmppConnectionService.sendPresencePacket(
532 contact.getAccount(),
533 activity.xmppConnectionService
534 .getPresenceGenerator()
535 .sendPresenceUpdatesTo(contact));
536 hideSnackbar();
537 }
538 }
539 };
540 protected OnClickListener clickToDecryptListener =
541 new OnClickListener() {
542
543 @Override
544 public void onClick(View v) {
545 PendingIntent pendingIntent =
546 conversation.getAccount().getPgpDecryptionService().getPendingIntent();
547 if (pendingIntent != null) {
548 try {
549 getActivity()
550 .startIntentSenderForResult(
551 pendingIntent.getIntentSender(),
552 REQUEST_DECRYPT_PGP,
553 null,
554 0,
555 0,
556 0,
557 Compatibility.pgpStartIntentSenderOptions());
558 } catch (SendIntentException e) {
559 Toast.makeText(
560 getActivity(),
561 R.string.unable_to_connect_to_keychain,
562 Toast.LENGTH_SHORT)
563 .show();
564 conversation
565 .getAccount()
566 .getPgpDecryptionService()
567 .continueDecryption(true);
568 }
569 }
570 updateSnackBar(conversation);
571 }
572 };
573 private final AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
574 private final OnEditorActionListener mEditorActionListener =
575 (v, actionId, event) -> {
576 if (actionId == EditorInfo.IME_ACTION_SEND) {
577 InputMethodManager imm =
578 (InputMethodManager)
579 activity.getSystemService(Context.INPUT_METHOD_SERVICE);
580 if (imm != null && imm.isFullscreenMode()) {
581 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
582 }
583 sendMessage();
584 return true;
585 } else {
586 return false;
587 }
588 };
589 private final OnClickListener mScrollButtonListener =
590 new OnClickListener() {
591
592 @Override
593 public void onClick(View v) {
594 stopScrolling();
595 setSelection(binding.messagesView.getCount() - 1, true);
596 }
597 };
598 private final OnClickListener mSendButtonListener =
599 new OnClickListener() {
600
601 @Override
602 public void onClick(View v) {
603 Object tag = v.getTag();
604 if (tag instanceof SendButtonAction) {
605 SendButtonAction action = (SendButtonAction) tag;
606 switch (action) {
607 case TAKE_PHOTO:
608 case RECORD_VIDEO:
609 case SEND_LOCATION:
610 case RECORD_VOICE:
611 case CHOOSE_PICTURE:
612 attachFile(action.toChoice());
613 break;
614 case CANCEL:
615 if (conversation != null) {
616 conversation.setUserSelectedThread(false);
617 if (conversation.setCorrectingMessage(null)) {
618 binding.textinput.setText("");
619 binding.textinput.append(conversation.getDraftMessage());
620 conversation.setDraftMessage(null);
621 } else if (conversation.getMode() == Conversation.MODE_MULTI) {
622 conversation.setNextCounterpart(null);
623 binding.textinput.setText("");
624 } else {
625 binding.textinput.setText("");
626 }
627 binding.textinputSubject.setText("");
628 binding.textinputSubject.setVisibility(View.GONE);
629 updateChatMsgHint();
630 updateSendButton();
631 updateEditablity();
632 }
633 break;
634 default:
635 sendMessage();
636 }
637 } else {
638 sendMessage();
639 }
640 }
641 };
642 private OnBackPressedCallback backPressedLeaveSingleThread = new OnBackPressedCallback(false) {
643 @Override
644 public void handleOnBackPressed() {
645 conversation.setLockThread(false);
646 this.setEnabled(false);
647 conversation.setUserSelectedThread(false);
648 setThread(null);
649 refresh();
650 updateThreadFromLastMessage();
651 }
652 };
653 private int completionIndex = 0;
654 private int lastCompletionLength = 0;
655 private String incomplete;
656 private int lastCompletionCursor;
657 private boolean firstWord = false;
658 private Message mPendingDownloadableMessage;
659
660 private static ConversationFragment findConversationFragment(Activity activity) {
661 Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
662 if (fragment instanceof ConversationFragment) {
663 return (ConversationFragment) fragment;
664 }
665 fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
666 if (fragment instanceof ConversationFragment) {
667 return (ConversationFragment) fragment;
668 }
669 return null;
670 }
671
672 public static void startStopPending(Activity activity) {
673 ConversationFragment fragment = findConversationFragment(activity);
674 if (fragment != null) {
675 fragment.messageListAdapter.startStopPending();
676 }
677 }
678
679 public static void downloadFile(Activity activity, Message message) {
680 ConversationFragment fragment = findConversationFragment(activity);
681 if (fragment != null) {
682 fragment.startDownloadable(message);
683 }
684 }
685
686 public static void registerPendingMessage(Activity activity, Message message) {
687 ConversationFragment fragment = findConversationFragment(activity);
688 if (fragment != null) {
689 fragment.pendingMessage.push(message);
690 }
691 }
692
693 public static void openPendingMessage(Activity activity) {
694 ConversationFragment fragment = findConversationFragment(activity);
695 if (fragment != null) {
696 Message message = fragment.pendingMessage.pop();
697 if (message != null) {
698 fragment.messageListAdapter.openDownloadable(message);
699 }
700 }
701 }
702
703 public static Conversation getConversation(Activity activity) {
704 return getConversation(activity, R.id.secondary_fragment);
705 }
706
707 private static Conversation getConversation(Activity activity, @IdRes int res) {
708 final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
709 if (fragment instanceof ConversationFragment) {
710 return ((ConversationFragment) fragment).getConversation();
711 } else {
712 return null;
713 }
714 }
715
716 public static ConversationFragment get(Activity activity) {
717 FragmentManager fragmentManager = activity.getFragmentManager();
718 Fragment fragment = fragmentManager.findFragmentById(R.id.main_fragment);
719 if (fragment instanceof ConversationFragment) {
720 return (ConversationFragment) fragment;
721 } else {
722 fragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
723 return fragment instanceof ConversationFragment
724 ? (ConversationFragment) fragment
725 : null;
726 }
727 }
728
729 public static Conversation getConversationReliable(Activity activity) {
730 final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
731 if (conversation != null) {
732 return conversation;
733 }
734 return getConversation(activity, R.id.main_fragment);
735 }
736
737 private static boolean scrolledToBottom(AbsListView listView) {
738 final int count = listView.getCount();
739 if (count == 0) {
740 return true;
741 } else if (listView.getLastVisiblePosition() == count - 1) {
742 final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
743 return lastChild != null && lastChild.getBottom() <= listView.getHeight();
744 } else {
745 return false;
746 }
747 }
748
749 private void toggleScrollDownButton() {
750 toggleScrollDownButton(binding.messagesView);
751 }
752
753 private void toggleScrollDownButton(AbsListView listView) {
754 if (conversation == null) {
755 return;
756 }
757 if (scrolledToBottom(listView)) {
758 lastMessageUuid = null;
759 hideUnreadMessagesCount();
760 } else {
761 binding.scrollToBottomButton.setEnabled(true);
762 binding.scrollToBottomButton.show();
763 if (lastMessageUuid == null) {
764 lastMessageUuid = conversation.getLatestMessage().getUuid();
765 }
766 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) > 0) {
767 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
768 }
769 }
770 }
771
772 private int getIndexOf(String uuid, List<Message> messages) {
773 if (uuid == null) {
774 return messages.size() - 1;
775 }
776 for (int i = 0; i < messages.size(); ++i) {
777 if (uuid.equals(messages.get(i).getUuid())) {
778 return i;
779 }
780 }
781 return -1;
782 }
783
784 private ScrollState getScrollPosition() {
785 final ListView listView = this.binding == null ? null : this.binding.messagesView;
786 if (listView == null
787 || listView.getCount() == 0
788 || listView.getLastVisiblePosition() == listView.getCount() - 1) {
789 return null;
790 } else {
791 final int pos = listView.getFirstVisiblePosition();
792 final View view = listView.getChildAt(0);
793 if (view == null) {
794 return null;
795 } else {
796 return new ScrollState(pos, view.getTop());
797 }
798 }
799 }
800
801 private void setScrollPosition(ScrollState scrollPosition, String lastMessageUuid) {
802 if (scrollPosition != null) {
803
804 this.lastMessageUuid = lastMessageUuid;
805 if (lastMessageUuid != null) {
806 binding.unreadCountCustomView.setUnreadCount(
807 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
808 }
809 // TODO maybe this needs a 'post'
810 this.binding.messagesView.setSelectionFromTop(
811 scrollPosition.position, scrollPosition.offset);
812 toggleScrollDownButton();
813 }
814 }
815
816 private void attachLocationToConversation(Conversation conversation, Uri uri) {
817 if (conversation == null) {
818 return;
819 }
820 final String subject = binding.textinputSubject.getText().toString();
821 activity.xmppConnectionService.attachLocationToConversation(
822 conversation,
823 uri,
824 subject,
825 new UiCallback<Message>() {
826
827 @Override
828 public void success(Message message) {
829 messageSent();
830 }
831
832 @Override
833 public void error(int errorCode, Message object) {
834 // TODO show possible pgp error
835 }
836
837 @Override
838 public void userInputRequired(PendingIntent pi, Message object) {}
839 });
840 }
841
842 private void attachFileToConversation(Conversation conversation, Uri uri, String type, Runnable next) {
843 if (conversation == null) {
844 return;
845 }
846 final String subject = binding.textinputSubject.getText().toString();
847 if ("application/webxdc+zip".equals(type)) newSubThread();
848 final Toast prepareFileToast =
849 Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
850 prepareFileToast.show();
851 activity.delegateUriPermissionsToService(uri);
852 activity.xmppConnectionService.attachFileToConversation(
853 conversation,
854 uri,
855 type,
856 subject,
857 new UiInformableCallback<Message>() {
858 @Override
859 public void inform(final String text) {
860 hidePrepareFileToast(prepareFileToast);
861 runOnUiThread(() -> activity.replaceToast(text));
862 }
863
864 @Override
865 public void success(Message message) {
866 if (next == null) {
867 runOnUiThread(() -> {
868 activity.hideToast();
869 messageSent();
870 });
871 } else {
872 runOnUiThread(next);
873 }
874 hidePrepareFileToast(prepareFileToast);
875 }
876
877 @Override
878 public void error(final int errorCode, Message message) {
879 hidePrepareFileToast(prepareFileToast);
880 runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
881 }
882
883 @Override
884 public void userInputRequired(PendingIntent pi, Message message) {
885 hidePrepareFileToast(prepareFileToast);
886 }
887 });
888 }
889
890 public void attachEditorContentToConversation(Uri uri) {
891 mediaPreviewAdapter.addMediaPreviews(
892 Attachment.of(getActivity(), uri, Attachment.Type.FILE));
893 toggleInputMethod();
894 }
895
896 private void attachImageToConversation(Conversation conversation, Uri uri, String type, Runnable next) {
897 if (conversation == null) {
898 return;
899 }
900 final String subject = binding.textinputSubject.getText().toString();
901 final Toast prepareFileToast =
902 Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
903 prepareFileToast.show();
904 activity.delegateUriPermissionsToService(uri);
905 activity.xmppConnectionService.attachImageToConversation(
906 conversation,
907 uri,
908 type,
909 subject,
910 new UiCallback<Message>() {
911
912 @Override
913 public void userInputRequired(PendingIntent pi, Message object) {
914 hidePrepareFileToast(prepareFileToast);
915 }
916
917 @Override
918 public void success(Message message) {
919 hidePrepareFileToast(prepareFileToast);
920 if (next == null) {
921 runOnUiThread(() -> messageSent());
922 } else {
923 runOnUiThread(next);
924 }
925 }
926
927 @Override
928 public void error(final int error, final Message message) {
929 hidePrepareFileToast(prepareFileToast);
930 final ConversationsActivity activity = ConversationFragment.this.activity;
931 if (activity == null) {
932 return;
933 }
934 activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
935 }
936 });
937 }
938
939 private void hidePrepareFileToast(final Toast prepareFileToast) {
940 if (prepareFileToast != null && activity != null) {
941 activity.runOnUiThread(prepareFileToast::cancel);
942 }
943 }
944
945 private void sendMessage() {
946 sendMessage((Long) null);
947 }
948
949 private void sendMessage(Long sendAt) {
950 if (sendAt != null && sendAt < System.currentTimeMillis()) sendAt = null; // No sending in past plz
951 if (mediaPreviewAdapter.hasAttachments()) {
952 commitAttachments();
953 return;
954 }
955 Editable body = this.binding.textinput.getText();
956 if (body == null) body = new SpannableStringBuilder("");
957 if (body.length() > Config.MAX_DISPLAY_MESSAGE_CHARS) {
958 Toast.makeText(activity, "Message is too long", Toast.LENGTH_SHORT).show();
959 return;
960 }
961 final Conversation conversation = this.conversation;
962 final boolean hasSubject = binding.textinputSubject.getText().length() > 0;
963 if (conversation == null || (body.length() == 0 && (conversation.getThread() == null || !hasSubject))) {
964 if (Build.VERSION.SDK_INT >= 24) {
965 binding.textSendButton.showContextMenu(0, 0);
966 } else {
967 binding.textSendButton.showContextMenu();
968 }
969 return;
970 }
971 if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_TEXT)) {
972 return;
973 }
974 final Message message;
975 if (conversation.getCorrectingMessage() == null) {
976 boolean attention = false;
977 if (Pattern.compile("\\A@here\\s.*").matcher(body).find()) {
978 attention = true;
979 body.delete(0, 6);
980 while (body.length() > 0 && Character.isWhitespace(body.charAt(0))) body.delete(0, 1);
981 }
982 if (conversation.getReplyTo() != null) {
983 if (Emoticons.isEmoji(body.toString().replaceAll("\\s", "")) && conversation.getNextCounterpart() == null && !conversation.getReplyTo().isPrivateMessage()) {
984 final var aggregated = conversation.getReplyTo().getAggregatedReactions();
985 final ImmutableSet.Builder<String> reactionBuilder = new ImmutableSet.Builder<>();
986 reactionBuilder.addAll(aggregated.ourReactions);
987 reactionBuilder.add(body.toString().replaceAll("\\s", ""));
988 activity.xmppConnectionService.sendReactions(conversation.getReplyTo(), reactionBuilder.build());
989 messageSent();
990 return;
991 } else {
992 message = conversation.getReplyTo().reply();
993 message.appendBody(body);
994 }
995 message.setEncryption(conversation.getNextEncryption());
996 } else {
997 message = new Message(conversation, body.toString(), conversation.getNextEncryption());
998 message.setBody(hasSubject && body.length() == 0 ? null : body);
999 if (message.bodyIsOnlyEmojis()) {
1000 SpannableStringBuilder spannable = message.getSpannableBody(null, null);
1001 ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
1002 for (ImageSpan span : imageSpans) {
1003 final int start = spannable.getSpanStart(span);
1004 final int end = spannable.getSpanEnd(span);
1005 spannable.delete(start, end);
1006 }
1007 if (imageSpans.length == 1 && spannable.toString().replaceAll("\\s", "").length() < 1) {
1008 // Only one inline image, so it's a sticker
1009 String source = imageSpans[0].getSource();
1010 if (source != null && source.length() > 0 && source.substring(0, 4).equals("cid:")) {
1011 try {
1012 final Cid cid = BobTransfer.cid(Uri.parse(source));
1013 final String url = activity.xmppConnectionService.getUrlForCid(cid);
1014 final File f = activity.xmppConnectionService.getFileForCid(cid);
1015 if (url != null) {
1016 message.setBody("");
1017 message.setRelativeFilePath(f.getAbsolutePath());
1018 activity.xmppConnectionService.getFileBackend().updateFileParams(message);
1019 }
1020 } catch (final Exception e) { }
1021 }
1022 }
1023 }
1024 }
1025 if (hasSubject) message.setSubject(binding.textinputSubject.getText().toString());
1026 message.setThread(conversation.getThread());
1027 if (attention) {
1028 message.addPayload(new Element("attention", "urn:xmpp:attention:0"));
1029 }
1030 Message.configurePrivateMessage(message);
1031 } else {
1032 message = conversation.getCorrectingMessage();
1033 if (hasSubject) message.setSubject(binding.textinputSubject.getText().toString());
1034 message.setThread(conversation.getThread());
1035 if (conversation.getReplyTo() != null) {
1036 if (Emoticons.isEmoji(body.toString().replaceAll("\\s", ""))) {
1037 message.updateReaction(conversation.getReplyTo(), body.toString().replaceAll("\\s", ""));
1038 } else {
1039 message.updateReplyTo(conversation.getReplyTo(), body);
1040 }
1041 } else {
1042 message.clearReplyReact();
1043 message.setBody(hasSubject && body.length() == 0 ? null : body);
1044 }
1045 if (message.getStatus() == Message.STATUS_WAITING) {
1046 if (sendAt != null) message.setTime(sendAt);
1047 activity.xmppConnectionService.updateMessage(message);
1048 messageSent();
1049 return;
1050 } else {
1051 message.putEdited(message.getUuid(), message.getServerMsgId());
1052 message.setServerMsgId(null);
1053 message.setUuid(UUID.randomUUID().toString());
1054 }
1055 }
1056 if (sendAt != null) message.setTime(sendAt);
1057 switch (conversation.getNextEncryption()) {
1058 case Message.ENCRYPTION_PGP:
1059 sendPgpMessage(message);
1060 break;
1061 default:
1062 sendMessage(message);
1063 }
1064 setupReply(null);
1065 }
1066
1067 private boolean trustKeysIfNeeded(final Conversation conversation, final int requestCode) {
1068 return conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL
1069 && trustKeysIfNeeded(requestCode);
1070 }
1071
1072 protected boolean trustKeysIfNeeded(int requestCode) {
1073 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
1074 if (axolotlService == null) return false;
1075 final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
1076 boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
1077 boolean hasUndecidedOwn =
1078 !axolotlService
1079 .getKeysWithTrust(FingerprintStatus.createActiveUndecided())
1080 .isEmpty();
1081 boolean hasUndecidedContacts =
1082 !axolotlService
1083 .getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets)
1084 .isEmpty();
1085 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
1086 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1087 boolean downloadInProgress = axolotlService.hasPendingKeyFetches(targets);
1088 if (hasUndecidedOwn
1089 || hasUndecidedContacts
1090 || hasPendingKeys
1091 || hasNoTrustedKeys
1092 || hasUnaccepted
1093 || downloadInProgress) {
1094 axolotlService.createSessionsIfNeeded(conversation);
1095 Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
1096 String[] contacts = new String[targets.size()];
1097 for (int i = 0; i < contacts.length; ++i) {
1098 contacts[i] = targets.get(i).toString();
1099 }
1100 intent.putExtra("contacts", contacts);
1101 intent.putExtra(
1102 EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString());
1103 intent.putExtra("conversation", conversation.getUuid());
1104 startActivityForResult(intent, requestCode);
1105 return true;
1106 } else {
1107 return false;
1108 }
1109 }
1110
1111 public void updateChatMsgHint() {
1112 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
1113 if (conversation.getCorrectingMessage() != null) {
1114 this.binding.textInputHint.setVisibility(View.GONE);
1115 this.binding.textinput.setHint(R.string.send_corrected_message);
1116 binding.conversationViewPager.setCurrentItem(0);
1117 } else if (multi && conversation.getNextCounterpart() != null) {
1118 this.binding.textinput.setHint(R.string.send_message);
1119 this.binding.textInputHint.setVisibility(View.VISIBLE);
1120 final MucOptions.User user = conversation.getMucOptions().findUserByName(conversation.getNextCounterpart().getResource());
1121 String nick = user == null ? null : user.getNick();
1122 if (nick == null) nick = conversation.getNextCounterpart().getResource();
1123 this.binding.textInputHint.setText(
1124 getString(
1125 R.string.send_private_message_to,
1126 nick));
1127 binding.conversationViewPager.setCurrentItem(0);
1128 } else if (multi && !conversation.getMucOptions().participating()) {
1129 this.binding.textInputHint.setVisibility(View.GONE);
1130 this.binding.textinput.setHint(R.string.you_are_not_participating);
1131 this.binding.inputLayout.setBackgroundColor(android.R.color.transparent);
1132 } else {
1133 this.binding.textInputHint.setVisibility(View.GONE);
1134 if (activity == null) return;
1135 this.binding.textinput.setHint(UIHelper.getMessageHint(activity, conversation));
1136 this.binding.inputLayout.setBackground(activity.getDrawable(R.drawable.background_message_bubble));
1137 activity.invalidateOptionsMenu();
1138 }
1139
1140 binding.messagesView.post(this::updateThreadFromLastMessage);
1141 }
1142
1143 public void setupIme() {
1144 this.binding.textinput.refreshIme();
1145 }
1146
1147 private void handleActivityResult(ActivityResult activityResult) {
1148 if (activityResult.resultCode == Activity.RESULT_OK) {
1149 handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
1150 } else {
1151 handleNegativeActivityResult(activityResult.requestCode);
1152 }
1153 }
1154
1155 private void handlePositiveActivityResult(int requestCode, final Intent data) {
1156 switch (requestCode) {
1157 case REQUEST_WEBXDC_STORE:
1158 mediaPreviewAdapter.addMediaPreviews(Attachment.of(activity, data.getData(), Attachment.Type.FILE));
1159 toggleInputMethod();
1160 break;
1161 case REQUEST_SAVE_STICKER:
1162 final DocumentFile df = DocumentFile.fromSingleUri(activity, data.getData());
1163 final File f = savingAsSticker;
1164 savingAsSticker = null;
1165 try {
1166 activity.xmppConnectionService.getFileBackend().copyFileToDocumentFile(activity, f, df);
1167 Toast.makeText(activity, "Sticker saved", Toast.LENGTH_SHORT).show();
1168 } catch (final FileBackend.FileCopyException e) {
1169 Toast.makeText(activity, e.getResId(), Toast.LENGTH_SHORT).show();
1170 }
1171 break;
1172 case REQUEST_TRUST_KEYS_TEXT:
1173 sendMessage();
1174 break;
1175 case REQUEST_TRUST_KEYS_ATTACHMENTS:
1176 commitAttachments();
1177 break;
1178 case REQUEST_START_AUDIO_CALL:
1179 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1180 break;
1181 case REQUEST_START_VIDEO_CALL:
1182 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1183 break;
1184 case ATTACHMENT_CHOICE_CHOOSE_IMAGE: {
1185 final Uri takePhotoUri = pendingTakePhotoUri.pop();
1186 if (takePhotoUri != null && (data == null || (data.getData() == null && data.getClipData() == null))) {
1187 mediaPreviewAdapter.addMediaPreviews(
1188 Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
1189 }
1190 final List<Attachment> imageUris =
1191 Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE);
1192 mediaPreviewAdapter.addMediaPreviews(imageUris);
1193 toggleInputMethod();
1194 break;
1195 }
1196 case ATTACHMENT_CHOICE_TAKE_PHOTO: {
1197 final Uri takePhotoUri = pendingTakePhotoUri.pop();
1198 if (takePhotoUri != null) {
1199 mediaPreviewAdapter.addMediaPreviews(
1200 Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
1201 toggleInputMethod();
1202 } else {
1203 Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
1204 }
1205 break;
1206 }
1207 case ATTACHMENT_CHOICE_CHOOSE_FILE:
1208 case ATTACHMENT_CHOICE_RECORD_VIDEO:
1209 case ATTACHMENT_CHOICE_RECORD_VOICE:
1210 final Attachment.Type type =
1211 requestCode == ATTACHMENT_CHOICE_RECORD_VOICE
1212 ? Attachment.Type.RECORDING
1213 : Attachment.Type.FILE;
1214 final List<Attachment> fileUris =
1215 Attachment.extractAttachments(getActivity(), data, type);
1216 mediaPreviewAdapter.addMediaPreviews(fileUris);
1217 toggleInputMethod();
1218 break;
1219 case ATTACHMENT_CHOICE_LOCATION:
1220 final double latitude = data.getDoubleExtra("latitude", 0);
1221 final double longitude = data.getDoubleExtra("longitude", 0);
1222 final int accuracy = data.getIntExtra("accuracy", 0);
1223 final Uri geo;
1224 if (accuracy > 0) {
1225 geo = Uri.parse(String.format("geo:%s,%s;u=%s", latitude, longitude, accuracy));
1226 } else {
1227 geo = Uri.parse(String.format("geo:%s,%s", latitude, longitude));
1228 }
1229 mediaPreviewAdapter.addMediaPreviews(
1230 Attachment.of(getActivity(), geo, Attachment.Type.LOCATION));
1231 toggleInputMethod();
1232 break;
1233 case REQUEST_INVITE_TO_CONVERSATION:
1234 XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data);
1235 if (invite != null) {
1236 if (invite.execute(activity)) {
1237 activity.mToast =
1238 Toast.makeText(
1239 activity, R.string.creating_conference, Toast.LENGTH_LONG);
1240 activity.mToast.show();
1241 }
1242 }
1243 break;
1244 }
1245 }
1246
1247 private void commitAttachments() {
1248 final List<Attachment> attachments = mediaPreviewAdapter.getAttachments();
1249 if (anyNeedsExternalStoragePermission(attachments)
1250 && !hasPermissions(
1251 REQUEST_COMMIT_ATTACHMENTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1252 return;
1253 }
1254 if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_ATTACHMENTS)) {
1255 return;
1256 }
1257 final PresenceSelector.OnPresenceSelected callback =
1258 () -> {
1259 final Iterator<Attachment> i = attachments.iterator();
1260 final Runnable next = new Runnable() {
1261 @Override
1262 public void run() {
1263 try {
1264 if (!i.hasNext()) return;
1265 final Attachment attachment = i.next();
1266 if (attachment.getType() == Attachment.Type.LOCATION) {
1267 attachLocationToConversation(conversation, attachment.getUri());
1268 if (i.hasNext()) runOnUiThread(this);
1269 } else if (attachment.getType() == Attachment.Type.IMAGE) {
1270 Log.d(
1271 Config.LOGTAG,
1272 "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE");
1273 attachImageToConversation(conversation, attachment.getUri(), attachment.getMime(), this);
1274 } else {
1275 Log.d(
1276 Config.LOGTAG,
1277 "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1278 attachFileToConversation(conversation, attachment.getUri(), attachment.getMime(), this);
1279 }
1280 i.remove();
1281 if (!i.hasNext()) messageSent();
1282 } catch (final java.util.ConcurrentModificationException e) {
1283 // Abort, leave any unsent attachments alone for the user to try again
1284 Toast.makeText(activity, "Sometimes went wrong with some attachments. Try again?", Toast.LENGTH_SHORT).show();
1285 }
1286 mediaPreviewAdapter.notifyDataSetChanged();
1287 toggleInputMethod();
1288 }
1289 };
1290 next.run();
1291 };
1292 if (conversation == null
1293 || conversation.getMode() == Conversation.MODE_MULTI
1294 || Attachment.canBeSendInBand(attachments)
1295 || (conversation.getAccount().httpUploadAvailable()
1296 && FileBackend.allFilesUnderSize(
1297 getActivity(), attachments, getMaxHttpUploadSize(conversation)))) {
1298 callback.onPresenceSelected();
1299 } else {
1300 activity.selectPresence(conversation, callback);
1301 }
1302 }
1303
1304 private static boolean anyNeedsExternalStoragePermission(
1305 final Collection<Attachment> attachments) {
1306 for (final Attachment attachment : attachments) {
1307 if (attachment.getType() != Attachment.Type.LOCATION) {
1308 return true;
1309 }
1310 }
1311 return false;
1312 }
1313
1314 public void toggleInputMethod() {
1315 boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
1316 binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
1317 binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
1318 updateSendButton();
1319 }
1320
1321 private void handleNegativeActivityResult(int requestCode) {
1322 switch (requestCode) {
1323 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1324 if (pendingTakePhotoUri.clear()) {
1325 Log.d(
1326 Config.LOGTAG,
1327 "cleared pending photo uri after negative activity result");
1328 }
1329 break;
1330 }
1331 }
1332
1333 @Override
1334 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
1335 super.onActivityResult(requestCode, resultCode, data);
1336 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
1337 if (activity != null && activity.xmppConnectionService != null) {
1338 handleActivityResult(activityResult);
1339 } else {
1340 this.postponedActivityResult.push(activityResult);
1341 }
1342 }
1343
1344 public void unblockConversation(final Blockable conversation) {
1345 activity.xmppConnectionService.sendUnblockRequest(conversation);
1346 }
1347
1348 @Override
1349 public void onAttach(Activity activity) {
1350 super.onAttach(activity);
1351 Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
1352 if (activity instanceof ConversationsActivity) {
1353 this.activity = (ConversationsActivity) activity;
1354 } else {
1355 throw new IllegalStateException(
1356 "Trying to attach fragment to activity that is not the ConversationsActivity");
1357 }
1358 }
1359
1360 @Override
1361 public void onDetach() {
1362 super.onDetach();
1363 this.activity = null; // TODO maybe not a good idea since some callbacks really need it
1364 }
1365
1366 @Override
1367 public void onCreate(Bundle savedInstanceState) {
1368 super.onCreate(savedInstanceState);
1369 setHasOptionsMenu(true);
1370 activity.getOnBackPressedDispatcher().addCallback(this, backPressedLeaveSingleThread);
1371 }
1372
1373 @Override
1374 public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
1375 if (activity != null && activity.xmppConnectionService != null && activity.xmppConnectionService.isOnboarding()) return;
1376
1377 menuInflater.inflate(R.menu.fragment_conversation, menu);
1378 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
1379 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
1380 final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
1381 final MenuItem menuMute = menu.findItem(R.id.action_mute);
1382 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
1383 final MenuItem menuCall = menu.findItem(R.id.action_call);
1384 final MenuItem menuOngoingCall = menu.findItem(R.id.action_ongoing_call);
1385 final MenuItem menuVideoCall = menu.findItem(R.id.action_video_call);
1386 final MenuItem menuTogglePinned = menu.findItem(R.id.action_toggle_pinned);
1387 final MenuItem menuArchiveChat = menu.findItem(R.id.action_archive);
1388
1389 if (conversation != null) {
1390 if (conversation.getMode() == Conversation.MODE_MULTI) {
1391 menuContactDetails.setVisible(false);
1392 menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
1393 menuMucDetails.setTitle(
1394 conversation.getMucOptions().isPrivateAndNonAnonymous()
1395 ? R.string.action_muc_details
1396 : R.string.channel_details);
1397 menuCall.setVisible(false);
1398 menuOngoingCall.setVisible(false);
1399 menuArchiveChat.setTitle("Leave " + (conversation.getMucOptions().isPrivateAndNonAnonymous() ? "group chat" : "Channel"));
1400 } else {
1401 final XmppConnectionService service =
1402 activity == null ? null : activity.xmppConnectionService;
1403 final Optional<OngoingRtpSession> ongoingRtpSession =
1404 service == null
1405 ? Optional.absent()
1406 : service.getJingleConnectionManager()
1407 .getOngoingRtpConnection(conversation.getContact());
1408 if (ongoingRtpSession.isPresent()) {
1409 menuOngoingCall.setVisible(true);
1410 menuCall.setVisible(false);
1411 } else {
1412 menuOngoingCall.setVisible(false);
1413 final RtpCapability.Capability rtpCapability =
1414 RtpCapability.check(conversation.getContact());
1415 final boolean cameraAvailable =
1416 activity != null && activity.isCameraFeatureAvailable();
1417 menuCall.setVisible(true);
1418 menuVideoCall.setVisible(rtpCapability != RtpCapability.Capability.AUDIO && cameraAvailable);
1419 }
1420 menuContactDetails.setVisible(!this.conversation.withSelf());
1421 menuMucDetails.setVisible(false);
1422 menuInviteContact.setVisible(
1423 service != null
1424 && service.findConferenceServer(conversation.getAccount()) != null);
1425 menuArchiveChat.setTitle(R.string.action_archive_chat);
1426 }
1427 if (conversation.isMuted()) {
1428 menuMute.setVisible(false);
1429 } else {
1430 menuUnmute.setVisible(false);
1431 }
1432 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
1433 ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
1434 if (conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false)) {
1435 menuTogglePinned.setTitle(R.string.remove_from_favorites);
1436 } else {
1437 menuTogglePinned.setTitle(R.string.add_to_favorites);
1438 }
1439 }
1440 super.onCreateOptionsMenu(menu, menuInflater);
1441 }
1442
1443 @Override
1444 public View onCreateView(
1445 final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
1446 this.binding =
1447 DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
1448 binding.getRoot().setOnClickListener(null); // TODO why the fuck did we do this?
1449
1450 binding.textinput.setOnEditorActionListener(mEditorActionListener);
1451 binding.textinput.setRichContentListener(new String[] {"image/*"}, mEditorContentListener);
1452 DisplayMetrics displayMetrics = new DisplayMetrics();
1453 activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
1454 if (displayMetrics.heightPixels > 0) binding.textinput.setMaxHeight(displayMetrics.heightPixels / 4);
1455
1456 binding.textSendButton.setOnClickListener(this.mSendButtonListener);
1457 binding.contextPreviewCancel.setOnClickListener((v) -> {
1458 setThread(null);
1459 conversation.setUserSelectedThread(false);
1460 setupReply(null);
1461 });
1462 binding.requestVoice.setOnClickListener((v) -> {
1463 activity.xmppConnectionService.requestVoice(conversation.getAccount(), conversation.getJid());
1464 binding.requestVoice.setVisibility(View.GONE);
1465 Toast.makeText(activity, "Your request has been sent to the moderators", Toast.LENGTH_SHORT).show();
1466 });
1467
1468 binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
1469 binding.messagesView.setOnScrollListener(mOnScrollListener);
1470 binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
1471 mediaPreviewAdapter = new MediaPreviewAdapter(this);
1472 binding.mediaPreview.setAdapter(mediaPreviewAdapter);
1473 messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1474 messageListAdapter.setOnContactPictureClicked(this);
1475 messageListAdapter.setOnContactPictureLongClicked(this);
1476 messageListAdapter.setOnInlineImageLongClicked(this);
1477 messageListAdapter.setConversationFragment(this);
1478 binding.messagesView.setAdapter(messageListAdapter);
1479
1480 binding.textinput.addTextChangedListener(
1481 new StylingHelper.MessageEditorStyler(binding.textinput, messageListAdapter));
1482
1483 registerForContextMenu(binding.messagesView);
1484 registerForContextMenu(binding.textSendButton);
1485
1486 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1487 this.binding.textinput.setCustomInsertionActionModeCallback(
1488 new EditMessageActionModeCallback(this.binding.textinput));
1489 this.binding.textinput.setCustomSelectionActionModeCallback(
1490 new EditMessageSelectionActionModeCallback(this.binding.textinput));
1491 }
1492
1493 messageListAdapter.setOnMessageBoxClicked(message -> {
1494 if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1495 setThread(message.getThread());
1496 conversation.setUserSelectedThread(true);
1497 });
1498
1499 messageListAdapter.setOnMessageBoxSwiped(message -> {
1500 quoteMessage(message);
1501 });
1502
1503 binding.threadIdenticonLayout.setOnClickListener(v -> {
1504 boolean wasLocked = conversation.getLockThread();
1505 conversation.setLockThread(false);
1506 backPressedLeaveSingleThread.setEnabled(false);
1507 if (wasLocked) {
1508 setThread(null);
1509 conversation.setUserSelectedThread(false);
1510 refresh();
1511 updateThreadFromLastMessage();
1512 } else {
1513 newThread();
1514 conversation.setUserSelectedThread(true);
1515 newThreadTutorialToast("Switched to new thread");
1516 }
1517 });
1518
1519 binding.threadIdenticonLayout.setOnLongClickListener(v -> {
1520 boolean wasLocked = conversation.getLockThread();
1521 conversation.setLockThread(false);
1522 backPressedLeaveSingleThread.setEnabled(false);
1523 setThread(null);
1524 conversation.setUserSelectedThread(true);
1525 if (wasLocked) refresh();
1526 newThreadTutorialToast("Cleared thread");
1527 return true;
1528 });
1529
1530 Autocomplete.<MucOptions.User>on(binding.textinput)
1531 .with(activity.getDrawable(R.drawable.background_message_bubble))
1532 .with(new CharPolicy('@'))
1533 .with(new RecyclerViewPresenter<MucOptions.User>(activity) {
1534 protected UserAdapter adapter;
1535
1536 @Override
1537 protected Adapter instantiateAdapter() {
1538 adapter = new UserAdapter(false) {
1539 @Override
1540 public void onBindViewHolder(UserAdapter.ViewHolder viewHolder, int position) {
1541 super.onBindViewHolder(viewHolder, position);
1542 final var item = getItem(position);
1543 viewHolder.binding.getRoot().setOnClickListener(v -> {
1544 dispatchClick(item);
1545 });
1546 }
1547 };
1548 return adapter;
1549 }
1550
1551 @Override
1552 protected void onQuery(@Nullable CharSequence query) {
1553 if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1554
1555 final var allUsers = conversation.getMucOptions().getUsers();
1556 if (!conversation.getMucOptions().getUsersByRole(MucOptions.Role.MODERATOR).isEmpty()) {
1557 final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0role:moderator", "Notify active moderators", new HashSet<>());
1558 u.setRole("participant");
1559 allUsers.add(u);
1560 }
1561 if (!allUsers.isEmpty() && conversation.getMucOptions().getSelf() != null && conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
1562 final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0attention", "Notify active participants", new HashSet<>());
1563 u.setRole("participant");
1564 allUsers.add(u);
1565 }
1566 final String needle = query.toString().toLowerCase(Locale.getDefault());
1567 if (getRecyclerView() != null) getRecyclerView().setItemAnimator(null);
1568 adapter.submitList(
1569 Ordering.natural().immutableSortedCopy(Collections2.filter(
1570 allUsers,
1571 user -> {
1572 if ("mods".contains(needle) && "\0role:moderator".equals(user.getOccupantId())) return true;
1573 if ("here".contains(needle) && "\0attention".equals(user.getOccupantId())) return true;
1574 final String name = user.getNick();
1575 if (name == null) return false;
1576 for (final var hat : user.getHats()) {
1577 if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1578 }
1579 for (final var hat : user.getPseudoHats(activity)) {
1580 if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1581 }
1582 final Contact contact = user.getContact();
1583 return name.toLowerCase(Locale.getDefault()).contains(needle)
1584 || contact != null
1585 && contact.getDisplayName().toLowerCase(Locale.getDefault()).contains(needle);
1586 })));
1587 }
1588
1589 @Override
1590 protected AutocompletePresenter.PopupDimensions getPopupDimensions() {
1591 final var dim = new AutocompletePresenter.PopupDimensions();
1592 dim.width = displayMetrics.widthPixels * 4/5;
1593 return dim;
1594 }
1595 })
1596 .with(new AutocompleteCallback<MucOptions.User>() {
1597 @Override
1598 public boolean onPopupItemClicked(Editable editable, MucOptions.User user) {
1599 int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1600 if (range == null) return false;
1601 range[0] -= 1;
1602 if ("\0attention".equals(user.getOccupantId())) {
1603 editable.delete(Math.max(0, range[0]), Math.min(editable.length(), range[1]));
1604 editable.insert(0, "@here ");
1605 return true;
1606 }
1607 int colon = editable.toString().indexOf(':');
1608 final var beforeColon = range[0] < colon;
1609 String prefix = "";
1610 String suffix = " ";
1611 if (beforeColon) suffix = ", ";
1612 if (colon < 0 && range[0] == 0) suffix = ": ";
1613 if (colon > 0 && colon == range[0] - 2) {
1614 prefix = ", ";
1615 suffix = ": ";
1616 range[0] -= 2;
1617 }
1618 var insert = user.getNick();
1619 if ("\0role:moderator".equals(user.getOccupantId())) {
1620 insert = conversation.getMucOptions().getUsersByRole(MucOptions.Role.MODERATOR).stream().map(MucOptions.User::getNick).collect(Collectors.joining(", "));
1621 }
1622 editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), prefix + insert + suffix);
1623 return true;
1624 }
1625
1626 @Override
1627 public void onPopupVisibilityChanged(boolean shown) {}
1628 }).build();
1629
1630 Handler emojiDebounce = new Handler(Looper.getMainLooper());
1631 setupEmojiSearch();
1632 Autocomplete.<EmojiSearch.Emoji>on(binding.textinput)
1633 .with(activity.getDrawable(R.drawable.background_message_bubble))
1634 .with(new CharPolicy(':'))
1635 .with(new RecyclerViewPresenter<EmojiSearch.Emoji>(activity) {
1636 protected EmojiSearch.EmojiSearchAdapter adapter;
1637
1638 @Override
1639 protected Adapter instantiateAdapter() {
1640 setupEmojiSearch();
1641 adapter = emojiSearch.makeAdapter(item -> dispatchClick(item));
1642 return adapter;
1643 }
1644
1645 @Override
1646 protected void onViewHidden() {
1647 if (getRecyclerView() == null) return;
1648 super.onViewHidden();
1649 }
1650
1651 @Override
1652 protected void onQuery(@Nullable CharSequence query) {
1653 if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1654
1655 emojiDebounce.removeCallbacksAndMessages(null);
1656 emojiDebounce.postDelayed(() -> {
1657 if (getRecyclerView() == null) return;
1658 getRecyclerView().setItemAnimator(null);
1659 adapter.search(activity, getRecyclerView(), query.toString());
1660 }, 100L);
1661 }
1662 })
1663 .with(new AutocompleteCallback<EmojiSearch.Emoji>() {
1664 @Override
1665 public boolean onPopupItemClicked(Editable editable, EmojiSearch.Emoji emoji) {
1666 int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1667 if (range == null) return false;
1668 range[0] -= 1;
1669 final var toInsert = emoji.toInsert();
1670 toInsert.append(" ");
1671 editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), toInsert);
1672 return true;
1673 }
1674
1675 @Override
1676 public void onPopupVisibilityChanged(boolean shown) {}
1677 }).build();
1678
1679 return binding.getRoot();
1680 }
1681
1682 protected void setupEmojiSearch() {
1683 if (activity != null && activity.xmppConnectionService != null) {
1684 if (emojiSearch == null) {
1685 emojiSearch = activity.xmppConnectionService.emojiSearch();
1686 }
1687 }
1688 }
1689
1690 protected void newThreadTutorialToast(String s) {
1691 if (activity == null) return;
1692 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1693 final int tutorialCount = p.getInt("thread_tutorial", 0);
1694 if (tutorialCount < 5) {
1695 Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
1696 p.edit().putInt("thread_tutorial", tutorialCount + 1).apply();
1697 }
1698 }
1699
1700 @Override
1701 public void onDestroyView() {
1702 super.onDestroyView();
1703 Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1704 messageListAdapter.setOnContactPictureClicked(null);
1705 messageListAdapter.setOnContactPictureLongClicked(null);
1706 messageListAdapter.setOnInlineImageLongClicked(null);
1707 messageListAdapter.setConversationFragment(null);
1708 messageListAdapter.setOnMessageBoxClicked(null);
1709 messageListAdapter.setOnMessageBoxSwiped(null);
1710 binding.conversationViewPager.setAdapter(null);
1711 if (conversation != null) conversation.setupViewPager(null, null, false, null);
1712 }
1713
1714 public void quoteText(String text) {
1715 if (binding.textinput.isEnabled()) {
1716 binding.textinput.insertAsQuote(text);
1717 binding.textinput.requestFocus();
1718 InputMethodManager inputMethodManager =
1719 (InputMethodManager)
1720 getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1721 if (inputMethodManager != null) {
1722 inputMethodManager.showSoftInput(
1723 binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1724 }
1725 }
1726 }
1727
1728 private void quoteMessage(Message message) {
1729 if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1730 setThread(message.getThread());
1731 conversation.setUserSelectedThread(true);
1732 if (!forkNullThread(message)) newThread();
1733 setupReply(message);
1734 }
1735
1736 private boolean forkNullThread(Message message) {
1737 if (message.getThread() != null || conversation.getMode() != Conversation.MODE_MULTI) return true;
1738 for (final Message m : conversation.findReplies(message.getServerMsgId())) {
1739 final Element thread = m.getThread();
1740 if (thread != null) {
1741 setThread(thread);
1742 return true;
1743 }
1744 }
1745
1746 return false;
1747 }
1748
1749 private void setupReply(Message message) {
1750 if (message != null) {
1751 final var correcting = conversation.getCorrectingMessage();
1752 if (correcting != null && correcting.getUuid().equals(message.getUuid())) return;
1753 }
1754 conversation.setReplyTo(message);
1755 if (message == null) {
1756 binding.contextPreview.setVisibility(View.GONE);
1757 binding.textsend.setBackgroundResource(R.drawable.textsend);
1758 return;
1759 }
1760
1761 SpannableStringBuilder body = message.getSpannableBody(null, null);
1762 if (message.isFileOrImage() || message.isOOb()) body.append(" 🖼️");
1763 messageListAdapter.handleTextQuotes(binding.contextPreviewText, body);
1764 binding.contextPreviewText.setText(body);
1765 binding.contextPreview.setVisibility(View.VISIBLE);
1766 }
1767
1768 private void setThread(Element thread) {
1769 this.conversation.setThread(thread);
1770 binding.threadIdenticon.setAlpha(0f);
1771 binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1772 if (thread != null) {
1773 final String threadId = thread.getContent();
1774 if (threadId != null) {
1775 binding.threadIdenticon.setAlpha(1f);
1776 binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1777 binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1778 }
1779 }
1780 updateSendButton();
1781 }
1782
1783 @Override
1784 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1785 // This should cancel any remaining click events that would otherwise trigger links
1786 v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1787
1788 if (v == binding.textSendButton) {
1789 super.onCreateContextMenu(menu, v, menuInfo);
1790 try {
1791 java.lang.reflect.Method m = menu.getClass().getSuperclass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
1792 m.setAccessible(true);
1793 m.invoke(menu, true);
1794 } catch (Exception e) {
1795 e.printStackTrace();
1796 }
1797 Menu tmpMenu = new PopupMenu(activity, null).getMenu();
1798 activity.getMenuInflater().inflate(R.menu.fragment_conversation, tmpMenu);
1799 MenuItem attachMenu = tmpMenu.findItem(R.id.action_attach_file);
1800 for (int i = 0; i < attachMenu.getSubMenu().size(); i++) {
1801 MenuItem item = attachMenu.getSubMenu().getItem(i);
1802 MenuItem newItem = menu.add(item.getGroupId(), item.getItemId(), item.getOrder(), item.getTitle());
1803 newItem.setIcon(item.getIcon());
1804 }
1805
1806 extensions.clear();
1807 final var xmppConnectionService = activity.xmppConnectionService;
1808 final var dir = new File(xmppConnectionService.getExternalFilesDir(null), "extensions");
1809 for (File file : Files.fileTraverser().breadthFirst(dir)) {
1810 if (file.isFile() && file.canRead()) {
1811 final var dummy = new Message(conversation, null, conversation.getNextEncryption());
1812 dummy.setStatus(Message.STATUS_DUMMY);
1813 dummy.setThread(conversation.getThread());
1814 dummy.setUuid(file.getName());
1815 final var xdc = new WebxdcPage(activity, file, dummy);
1816 extensions.add(xdc);
1817 final var item = menu.add(0x1, extensions.size() - 1, 0, xdc.getName());
1818 item.setIcon(xdc.getIcon(24));
1819 }
1820 }
1821 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
1822 return;
1823 }
1824
1825 synchronized (this.messageList) {
1826 super.onCreateContextMenu(menu, v, menuInfo);
1827 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1828 this.selectedMessage = this.messageList.get(acmi.position);
1829 populateContextMenu(menu);
1830 }
1831 }
1832
1833 private void populateContextMenu(final ContextMenu menu) {
1834 final Message m = this.selectedMessage;
1835 final Transferable t = m.getTransferable();
1836 if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1837
1838 if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1839 || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1840 return;
1841 }
1842
1843 if (m.getStatus() == Message.STATUS_RECEIVED
1844 && t != null
1845 && (t.getStatus() == Transferable.STATUS_CANCELLED
1846 || t.getStatus() == Transferable.STATUS_FAILED)) {
1847 return;
1848 }
1849
1850 final boolean deleted = m.isDeleted();
1851 final boolean encrypted =
1852 m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1853 || m.getEncryption() == Message.ENCRYPTION_PGP;
1854 final boolean receiving =
1855 m.getStatus() == Message.STATUS_RECEIVED
1856 && (t instanceof JingleFileTransferConnection
1857 || t instanceof HttpDownloadConnection);
1858 activity.getMenuInflater().inflate(R.menu.message_context, menu);
1859 final MenuItem reportAndBlock = menu.findItem(R.id.action_report_and_block);
1860 final MenuItem addReaction = menu.findItem(R.id.action_add_reaction);
1861 final MenuItem openWith = menu.findItem(R.id.open_with);
1862 final MenuItem copyMessage = menu.findItem(R.id.copy_message);
1863 final MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1864 final MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1865 final MenuItem correctMessage = menu.findItem(R.id.correct_message);
1866 final MenuItem retractMessage = menu.findItem(R.id.retract_message);
1867 final MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
1868 final MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1869 final MenuItem shareWith = menu.findItem(R.id.share_with);
1870 final MenuItem sendAgain = menu.findItem(R.id.send_again);
1871 final MenuItem retryAsP2P = menu.findItem(R.id.send_again_as_p2p);
1872 final MenuItem copyUrl = menu.findItem(R.id.copy_url);
1873 final MenuItem copyLink = menu.findItem(R.id.copy_link);
1874 final MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
1875 final MenuItem downloadFile = menu.findItem(R.id.download_file);
1876 final MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1877 final MenuItem blockMedia = menu.findItem(R.id.block_media);
1878 final MenuItem deleteFile = menu.findItem(R.id.delete_file);
1879 final MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1880 onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1881 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1882 final boolean showError =
1883 m.getStatus() == Message.STATUS_SEND_FAILED
1884 && m.getErrorMessage() != null
1885 && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1886 final Conversational conversational = m.getConversation();
1887 if (m.getStatus() == Message.STATUS_RECEIVED
1888 && conversational instanceof Conversation c) {
1889 final XmppConnection connection = c.getAccount().getXmppConnection();
1890 if (c.isWithStranger()
1891 && m.getServerMsgId() != null
1892 && !c.isBlocked()
1893 && connection != null
1894 && connection.getFeatures().spamReporting()) {
1895 reportAndBlock.setVisible(true);
1896 }
1897 }
1898 if (conversational instanceof Conversation c) {
1899 addReaction.setVisible(
1900 !showError
1901 && !m.isDeleted()
1902 && !m.isPrivateMessage()
1903 && (c.getMode() == Conversational.MODE_SINGLE
1904 || (c.getMucOptions().occupantId()
1905 && c.getMucOptions().participating())));
1906 } else {
1907 addReaction.setVisible(false);
1908 }
1909 if (!m.isFileOrImage()
1910 && !encrypted
1911 && !m.isGeoUri()
1912 && !m.treatAsDownloadable()
1913 && !unInitiatedButKnownSize
1914 && t == null) {
1915 copyMessage.setVisible(true);
1916 quoteMessage.setVisible(!showError && !MessageUtils.prepareQuote(m).isEmpty());
1917 final String scheme =
1918 ShareUtil.getLinkScheme(new SpannableStringBuilder(m.getBody()));
1919 if ("xmpp".equals(scheme)) {
1920 copyLink.setTitle(R.string.copy_jabber_id);
1921 copyLink.setVisible(true);
1922 } else if (scheme != null) {
1923 copyLink.setVisible(true);
1924 }
1925 }
1926 quoteMessage.setVisible(!encrypted && !showError);
1927 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1928 retryDecryption.setVisible(true);
1929 }
1930 if (!showError
1931 && m.getType() == Message.TYPE_TEXT
1932 && m.isEditable()
1933 && !m.isGeoUri()
1934 && m.getConversation() instanceof Conversation) {
1935 correctMessage.setVisible(true);
1936 if (!m.getBody().equals("") && !m.getBody().equals(" ")) retractMessage.setVisible(true);
1937 }
1938 if (m.getStatus() == Message.STATUS_WAITING) {
1939 correctMessage.setVisible(true);
1940 retractMessage.setVisible(true);
1941 }
1942 if (conversation.getMode() == Conversation.MODE_MULTI && m.getServerMsgId() != null && m.getModerated() == null && conversation.getMucOptions().getSelf().getRole().ranks(MucOptions.Role.MODERATOR) && conversation.getMucOptions().hasFeature("urn:xmpp:message-moderate:0")) {
1943 moderateMessage.setVisible(true);
1944 }
1945 if ((m.isFileOrImage() && !deleted && !receiving)
1946 || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1947 && !unInitiatedButKnownSize
1948 && t == null) {
1949 shareWith.setVisible(true);
1950 }
1951 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1952 sendAgain.setVisible(true);
1953 final var fileNotUploaded = m.isFileOrImage() && !m.hasFileOnRemoteHost();
1954 final var isPeerOnline =
1955 conversational.getMode() == Conversation.MODE_SINGLE
1956 && (conversational instanceof Conversation c)
1957 && !c.getContact().getPresences().isEmpty();
1958 retryAsP2P.setVisible(fileNotUploaded && isPeerOnline);
1959 }
1960 if (m.hasFileOnRemoteHost()
1961 || m.isGeoUri()
1962 || m.treatAsDownloadable()
1963 || unInitiatedButKnownSize
1964 || t instanceof HttpDownloadConnection) {
1965 copyUrl.setVisible(true);
1966 }
1967 if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1968 downloadFile.setVisible(true);
1969 downloadFile.setTitle(
1970 activity.getString(
1971 R.string.download_x_file,
1972 UIHelper.getFileDescriptionString(activity, m)));
1973 }
1974 final boolean waitingOfferedSending =
1975 m.getStatus() == Message.STATUS_WAITING
1976 || m.getStatus() == Message.STATUS_UNSEND
1977 || m.getStatus() == Message.STATUS_OFFERED;
1978 final boolean cancelable =
1979 (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1980 if (cancelable) {
1981 cancelTransmission.setVisible(true);
1982 }
1983 if (m.isFileOrImage() && !deleted && !cancelable) {
1984 final String path = m.getRelativeFilePath();
1985 if (path != null) {
1986 final var file = new File(path);
1987 if (file.canRead()) saveAsSticker.setVisible(true);
1988 blockMedia.setVisible(true);
1989 if (file.canWrite()) deleteFile.setVisible(true);
1990 deleteFile.setTitle(
1991 activity.getString(
1992 R.string.delete_x_file,
1993 UIHelper.getFileDescriptionString(activity, m)));
1994 }
1995 }
1996
1997 if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
1998 // We might be showing a thumbnail worth blocking
1999 blockMedia.setVisible(true);
2000 }
2001 if (showError) {
2002 showErrorMessage.setVisible(true);
2003 }
2004 final String mime = m.isFileOrImage() ? m.getMimeType() : null;
2005 if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
2006 || (mime != null && mime.startsWith("audio/"))) {
2007 openWith.setVisible(true);
2008 }
2009 }
2010 }
2011
2012 @Override
2013 public boolean onContextItemSelected(MenuItem item) {
2014 switch (item.getItemId()) {
2015 case R.id.share_with:
2016 ShareUtil.share(activity, selectedMessage);
2017 return true;
2018 case R.id.correct_message:
2019 correctMessage(selectedMessage);
2020 return true;
2021 case R.id.retract_message:
2022 new AlertDialog.Builder(activity)
2023 .setTitle(R.string.retract_message)
2024 .setMessage("Do you really want to retract this message?")
2025 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2026 final var message = selectedMessage;
2027 if (message.getStatus() == Message.STATUS_WAITING || message.getStatus() == Message.STATUS_OFFERED) {
2028 activity.xmppConnectionService.deleteMessage(message);
2029 return;
2030 }
2031 Element reactions = message.getReactionsEl();
2032 if (reactions != null) {
2033 final Message previousReaction = conversation.findMessageReactingTo(reactions.getAttribute("id"), null);
2034 if (previousReaction != null) reactions = previousReaction.getReactionsEl();
2035 for (Element el : reactions.getChildren()) {
2036 if (message.getRawBody().endsWith(el.getContent())) {
2037 reactions.removeChild(el);
2038 }
2039 }
2040 message.setReactions(reactions);
2041 if (previousReaction != null) {
2042 previousReaction.setReactions(reactions);
2043 activity.xmppConnectionService.updateMessage(previousReaction);
2044 }
2045 } else {
2046 message.setInReplyTo(null);
2047 message.clearPayloads();
2048 }
2049 message.setBody(" ");
2050 message.setSubject(null);
2051 message.putEdited(message.getUuid(), message.getServerMsgId());
2052 message.setServerMsgId(null);
2053 message.setUuid(UUID.randomUUID().toString());
2054 sendMessage(message);
2055 })
2056 .setNegativeButton(R.string.no, null).show();
2057 return true;
2058 case R.id.moderate_message:
2059 activity.quickEdit("Spam", (reason) -> {
2060 activity.xmppConnectionService.moderateMessage(conversation.getAccount(), selectedMessage, reason);
2061 return null;
2062 }, R.string.moderate_reason, false, false, true, true);
2063 return true;
2064 case R.id.copy_message:
2065 ShareUtil.copyToClipboard(activity, selectedMessage);
2066 return true;
2067 case R.id.quote_message:
2068 quoteMessage(selectedMessage);
2069 return true;
2070 case R.id.send_again:
2071 resendMessage(selectedMessage, false);
2072 return true;
2073 case R.id.send_again_as_p2p:
2074 resendMessage(selectedMessage, true);
2075 return true;
2076 case R.id.copy_url:
2077 ShareUtil.copyUrlToClipboard(activity, selectedMessage);
2078 return true;
2079 case R.id.save_as_sticker:
2080 saveAsSticker(selectedMessage);
2081 return true;
2082 case R.id.download_file:
2083 startDownloadable(selectedMessage);
2084 return true;
2085 case R.id.cancel_transmission:
2086 cancelTransmission(selectedMessage);
2087 return true;
2088 case R.id.retry_decryption:
2089 retryDecryption(selectedMessage);
2090 return true;
2091 case R.id.block_media:
2092 new AlertDialog.Builder(activity)
2093 .setTitle(R.string.block_media)
2094 .setMessage("Do you really want to block this media in all messages?")
2095 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2096 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2097 if (thumbs != null && !thumbs.isEmpty()) {
2098 for (Element thumb : thumbs) {
2099 Uri uri = Uri.parse(thumb.getAttribute("uri"));
2100 if (uri.getScheme().equals("cid")) {
2101 Cid cid = BobTransfer.cid(uri);
2102 if (cid == null) continue;
2103 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2104 activity.xmppConnectionService.blockMedia(f);
2105 activity.xmppConnectionService.evictPreview(f);
2106 f.delete();
2107 }
2108 }
2109 }
2110 File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
2111 activity.xmppConnectionService.blockMedia(f);
2112 activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
2113 activity.xmppConnectionService.evictPreview(f);
2114 activity.xmppConnectionService.updateMessage(selectedMessage, false);
2115 activity.onConversationsListItemUpdated();
2116 refresh();
2117 })
2118 .setNegativeButton(R.string.no, null).show();
2119 return true;
2120 case R.id.delete_file:
2121 deleteFile(selectedMessage);
2122 return true;
2123 case R.id.show_error_message:
2124 showErrorMessage(selectedMessage);
2125 return true;
2126 case R.id.open_with:
2127 openWith(selectedMessage);
2128 return true;
2129 case R.id.only_this_thread:
2130 conversation.setLockThread(true);
2131 backPressedLeaveSingleThread.setEnabled(true);
2132 setThread(selectedMessage.getThread());
2133 refresh();
2134 return true;
2135 case R.id.action_report_and_block:
2136 reportMessage(selectedMessage);
2137 return true;
2138 case R.id.action_add_reaction:
2139 addReaction(selectedMessage);
2140 return true;
2141 default:
2142 return onOptionsItemSelected(item);
2143 }
2144 }
2145
2146 @Override
2147 public boolean onOptionsItemSelected(final MenuItem item) {
2148 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
2149 return false;
2150 } else if (conversation == null) {
2151 return super.onOptionsItemSelected(item);
2152 }
2153 if (item.getGroupId() == 0x1) {
2154 conversation.startWebxdc(extensions.get(item.getItemId()));
2155 return true;
2156 }
2157 switch (item.getItemId()) {
2158 case R.id.encryption_choice_axolotl:
2159 case R.id.encryption_choice_pgp:
2160 case R.id.encryption_choice_none:
2161 handleEncryptionSelection(item);
2162 break;
2163 case R.id.attach_choose_picture:
2164 //case R.id.attach_take_picture:
2165 //case R.id.attach_record_video:
2166 case R.id.attach_choose_file:
2167 case R.id.attach_record_voice:
2168 case R.id.attach_location:
2169 handleAttachmentSelection(item);
2170 break;
2171 case R.id.attach_webxdc:
2172 final Intent intent = new Intent(getActivity(), WebxdcStore.class);
2173 startActivityForResult(intent, REQUEST_WEBXDC_STORE);
2174 break;
2175 case R.id.attach_subject:
2176 binding.textinputSubject.setVisibility(binding.textinputSubject.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
2177 break;
2178 case R.id.attach_schedule:
2179 scheduleMessage();
2180 break;
2181 case R.id.action_search:
2182 startSearch();
2183 break;
2184 case R.id.action_archive:
2185 activity.xmppConnectionService.archiveConversation(conversation);
2186 break;
2187 case R.id.action_contact_details:
2188 activity.switchToContactDetails(conversation.getContact());
2189 break;
2190 case R.id.action_muc_details:
2191 ConferenceDetailsActivity.open(activity, conversation);
2192 break;
2193 case R.id.action_invite:
2194 startActivityForResult(
2195 ChooseContactActivity.create(activity, conversation),
2196 REQUEST_INVITE_TO_CONVERSATION);
2197 break;
2198 case R.id.action_clear_history:
2199 clearHistoryDialog(conversation);
2200 break;
2201 case R.id.action_mute:
2202 muteConversationDialog(conversation);
2203 break;
2204 case R.id.action_unmute:
2205 unMuteConversation(conversation);
2206 break;
2207 case R.id.action_block:
2208 case R.id.action_unblock:
2209 BlockContactDialog.show(activity, conversation);
2210 break;
2211 case R.id.action_audio_call:
2212 checkPermissionAndTriggerAudioCall();
2213 break;
2214 case R.id.action_video_call:
2215 checkPermissionAndTriggerVideoCall();
2216 break;
2217 case R.id.action_ongoing_call:
2218 returnToOngoingCall();
2219 break;
2220 case R.id.action_toggle_pinned:
2221 togglePinned();
2222 break;
2223 case R.id.action_add_shortcut:
2224 addShortcut();
2225 break;
2226 case R.id.action_block_avatar:
2227 new AlertDialog.Builder(activity)
2228 .setTitle(R.string.block_media)
2229 .setMessage("Do you really want to block this avatar?")
2230 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2231 activity.xmppConnectionService.blockMedia(activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatarFilename()));
2232 activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatarFilename()).delete();
2233 activity.avatarService().clear(conversation);
2234 conversation.getContact().setAvatar(null);
2235 activity.xmppConnectionService.updateConversationUi();
2236 })
2237 .setNegativeButton(R.string.no, null).show();
2238 case R.id.action_refresh_feature_discovery:
2239 refreshFeatureDiscovery();
2240 break;
2241 default:
2242 break;
2243 }
2244 return super.onOptionsItemSelected(item);
2245 }
2246
2247 public boolean onBackPressed() {
2248 boolean wasLocked = conversation.getLockThread();
2249 conversation.setLockThread(false);
2250 backPressedLeaveSingleThread.setEnabled(false);
2251 if (wasLocked) {
2252 setThread(null);
2253 conversation.setUserSelectedThread(false);
2254 refresh();
2255 updateThreadFromLastMessage();
2256 return true;
2257 }
2258 return false;
2259 }
2260
2261 private void startSearch() {
2262 final Intent intent = new Intent(getActivity(), SearchActivity.class);
2263 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
2264 startActivity(intent);
2265 }
2266
2267 private void scheduleMessage() {
2268 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
2269 final var datePicker = com.google.android.material.datepicker.MaterialDatePicker.Builder.datePicker()
2270 .setTitleText("Schedule Message")
2271 .setSelection(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2272 .setCalendarConstraints(
2273 new com.google.android.material.datepicker.CalendarConstraints.Builder()
2274 .setStart(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2275 .build()
2276 )
2277 .build();
2278 datePicker.addOnPositiveButtonClickListener((date) -> {
2279 final Calendar now = Calendar.getInstance();
2280 final var timePicker = new com.google.android.material.timepicker.MaterialTimePicker.Builder()
2281 .setTitleText("Schedule Message")
2282 .setHour(now.get(Calendar.HOUR_OF_DAY))
2283 .setMinute(now.get(Calendar.MINUTE))
2284 .setTimeFormat(android.text.format.DateFormat.is24HourFormat(activity) ? com.google.android.material.timepicker.TimeFormat.CLOCK_24H : com.google.android.material.timepicker.TimeFormat.CLOCK_12H)
2285 .build();
2286 timePicker.addOnPositiveButtonClickListener((v2) -> {
2287 final var dateCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
2288 dateCal.setTimeInMillis(date);
2289 final var time = Calendar.getInstance();
2290 time.set(dateCal.get(Calendar.YEAR), dateCal.get(Calendar.MONTH), dateCal.get(Calendar.DAY_OF_MONTH), timePicker.getHour(), timePicker.getMinute(), 0);
2291 final long timestamp = time.getTimeInMillis();
2292 sendMessage(timestamp);
2293 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": scheduled message for " + timestamp);
2294 });
2295 timePicker.show(activity.getSupportFragmentManager(), "schedulMessageTime");
2296 });
2297 datePicker.show(activity.getSupportFragmentManager(), "schedulMessageDate");
2298 }
2299 }
2300
2301 private void returnToOngoingCall() {
2302 final Optional<OngoingRtpSession> ongoingRtpSession =
2303 activity.xmppConnectionService
2304 .getJingleConnectionManager()
2305 .getOngoingRtpConnection(conversation.getContact());
2306 if (ongoingRtpSession.isPresent()) {
2307 final OngoingRtpSession id = ongoingRtpSession.get();
2308 final Intent intent = new Intent(getActivity(), RtpSessionActivity.class);
2309 intent.setAction(Intent.ACTION_VIEW);
2310 intent.putExtra(
2311 RtpSessionActivity.EXTRA_ACCOUNT,
2312 id.getAccount().getJid().asBareJid().toString());
2313 intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toString());
2314 if (id instanceof AbstractJingleConnection) {
2315 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
2316 startActivity(intent);
2317 } else if (id instanceof JingleConnectionManager.RtpSessionProposal proposal) {
2318 if (Media.audioOnly(proposal.media)) {
2319 intent.putExtra(
2320 RtpSessionActivity.EXTRA_LAST_ACTION,
2321 RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2322 } else {
2323 intent.putExtra(
2324 RtpSessionActivity.EXTRA_LAST_ACTION,
2325 RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2326 }
2327 intent.putExtra(RtpSessionActivity.EXTRA_PROPOSED_SESSION_ID, proposal.sessionId);
2328 startActivity(intent);
2329 }
2330 }
2331 }
2332
2333 private void refreshFeatureDiscovery() {
2334 Set<Map.Entry<String, Presence>> presences = conversation.getContact().getPresences().getPresencesMap().entrySet();
2335 if (presences.isEmpty()) {
2336 presences = new HashSet<>();
2337 presences.add(new AbstractMap.SimpleEntry("", null));
2338 }
2339 for (Map.Entry<String, Presence> entry : presences) {
2340 Jid jid = conversation.getContact().getJid();
2341 if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
2342 activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
2343 if (activity == null) return;
2344 activity.runOnUiThread(() -> {
2345 refresh();
2346 refreshCommands(true);
2347 });
2348 });
2349 }
2350 }
2351
2352 private void addShortcut() {
2353 ShortcutInfoCompat info;
2354 if (conversation.getMode() == Conversation.MODE_MULTI) {
2355 info = activity.xmppConnectionService.getShortcutService().getShortcutInfo(conversation.getMucOptions());
2356 } else {
2357 info = activity.xmppConnectionService.getShortcutService().getShortcutInfo(conversation.getContact());
2358 }
2359 ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2360 }
2361
2362 private void togglePinned() {
2363 final boolean pinned =
2364 conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2365 conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2366 activity.xmppConnectionService.updateConversation(conversation);
2367 activity.invalidateOptionsMenu();
2368 }
2369
2370 private void checkPermissionAndTriggerAudioCall() {
2371 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2372 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2373 return;
2374 }
2375 final List<String> permissions;
2376 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2377 permissions =
2378 Arrays.asList(
2379 Manifest.permission.RECORD_AUDIO,
2380 Manifest.permission.BLUETOOTH_CONNECT);
2381 } else {
2382 permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2383 }
2384 if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2385 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2386 }
2387 }
2388
2389 private void checkPermissionAndTriggerVideoCall() {
2390 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2391 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2392 return;
2393 }
2394 final List<String> permissions;
2395 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2396 permissions =
2397 Arrays.asList(
2398 Manifest.permission.RECORD_AUDIO,
2399 Manifest.permission.CAMERA,
2400 Manifest.permission.BLUETOOTH_CONNECT);
2401 } else {
2402 permissions =
2403 Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2404 }
2405 if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2406 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2407 }
2408 }
2409
2410 private void triggerRtpSession(final String action) {
2411 if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
2412 Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2413 .show();
2414 return;
2415 }
2416 final Account account = conversation.getAccount();
2417 if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
2418 activity.xmppConnectionService.updateAccount(account);
2419 }
2420 final Contact contact = conversation.getContact();
2421 if (Config.USE_JINGLE_MESSAGE_INIT && RtpCapability.jmiSupport(contact)) {
2422 triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2423 } else {
2424 final RtpCapability.Capability capability;
2425 if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2426 capability = RtpCapability.Capability.VIDEO;
2427 } else {
2428 capability = RtpCapability.Capability.AUDIO;
2429 }
2430 PresenceSelector.selectFullJidForDirectRtpConnection(
2431 activity,
2432 contact,
2433 capability,
2434 fullJid -> {
2435 triggerRtpSession(contact.getAccount(), fullJid, action);
2436 });
2437 }
2438 }
2439
2440 private void triggerRtpSession(final Account account, final Jid with, final String action) {
2441 CallIntegrationConnectionService.placeCall(
2442 activity.xmppConnectionService,
2443 account,
2444 with,
2445 RtpSessionActivity.actionToMedia(action));
2446 }
2447
2448 private void handleAttachmentSelection(MenuItem item) {
2449 switch (item.getItemId()) {
2450 case R.id.attach_choose_picture:
2451 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2452 break;
2453 /*case R.id.attach_take_picture:
2454 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2455 break;
2456 case R.id.attach_record_video:
2457 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2458 break;*/
2459 case R.id.attach_choose_file:
2460 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2461 break;
2462 case R.id.attach_record_voice:
2463 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2464 break;
2465 case R.id.attach_location:
2466 attachFile(ATTACHMENT_CHOICE_LOCATION);
2467 break;
2468 }
2469 }
2470
2471 private void handleEncryptionSelection(MenuItem item) {
2472 if (conversation == null) {
2473 return;
2474 }
2475 final boolean updated;
2476 switch (item.getItemId()) {
2477 case R.id.encryption_choice_none:
2478 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2479 item.setChecked(true);
2480 break;
2481 case R.id.encryption_choice_pgp:
2482 if (activity.hasPgp()) {
2483 if (conversation.getAccount().getPgpSignature() != null) {
2484 updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2485 item.setChecked(true);
2486 } else {
2487 updated = false;
2488 activity.announcePgp(
2489 conversation.getAccount(),
2490 conversation,
2491 null,
2492 activity.onOpenPGPKeyPublished);
2493 }
2494 } else {
2495 activity.showInstallPgpDialog();
2496 updated = false;
2497 }
2498 break;
2499 case R.id.encryption_choice_axolotl:
2500 Log.d(
2501 Config.LOGTAG,
2502 AxolotlService.getLogprefix(conversation.getAccount())
2503 + "Enabled axolotl for Contact "
2504 + conversation.getContact().getJid());
2505 updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2506 item.setChecked(true);
2507 break;
2508 default:
2509 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2510 break;
2511 }
2512 if (updated) {
2513 activity.xmppConnectionService.updateConversation(conversation);
2514 }
2515 updateChatMsgHint();
2516 getActivity().invalidateOptionsMenu();
2517 activity.refreshUi();
2518 }
2519
2520 public void attachFile(final int attachmentChoice) {
2521 attachFile(attachmentChoice, true, false);
2522 }
2523
2524 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2525 attachFile(attachmentChoice, updateRecentlyUsed, false);
2526 }
2527
2528 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed, final boolean fromPermissions) {
2529 if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2530 if (!hasPermissions(
2531 attachmentChoice,
2532 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2533 Manifest.permission.RECORD_AUDIO)) {
2534 return;
2535 }
2536 } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2537 || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO
2538 || (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE && !fromPermissions)) {
2539 if (!hasPermissions(
2540 attachmentChoice,
2541 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2542 Manifest.permission.CAMERA)) {
2543 return;
2544 }
2545 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2546 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2547 return;
2548 }
2549 }
2550 if (updateRecentlyUsed) {
2551 storeRecentlyUsedQuickAction(attachmentChoice);
2552 }
2553 final int encryption = conversation.getNextEncryption();
2554 final int mode = conversation.getMode();
2555 if (encryption == Message.ENCRYPTION_PGP) {
2556 if (activity.hasPgp()) {
2557 if (mode == Conversation.MODE_SINGLE
2558 && conversation.getContact().getPgpKeyId() != 0) {
2559 activity.xmppConnectionService
2560 .getPgpEngine()
2561 .hasKey(
2562 conversation.getContact(),
2563 new UiCallback<Contact>() {
2564
2565 @Override
2566 public void userInputRequired(
2567 PendingIntent pi, Contact contact) {
2568 startPendingIntent(pi, attachmentChoice);
2569 }
2570
2571 @Override
2572 public void success(Contact contact) {
2573 invokeAttachFileIntent(attachmentChoice);
2574 }
2575
2576 @Override
2577 public void error(int error, Contact contact) {
2578 activity.replaceToast(getString(error));
2579 }
2580 });
2581 } else if (mode == Conversation.MODE_MULTI
2582 && conversation.getMucOptions().pgpKeysInUse()) {
2583 if (!conversation.getMucOptions().everybodyHasKeys()) {
2584 Toast warning =
2585 Toast.makeText(
2586 getActivity(),
2587 R.string.missing_public_keys,
2588 Toast.LENGTH_LONG);
2589 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2590 warning.show();
2591 }
2592 invokeAttachFileIntent(attachmentChoice);
2593 } else {
2594 showNoPGPKeyDialog(
2595 false,
2596 (dialog, which) -> {
2597 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2598 activity.xmppConnectionService.updateConversation(conversation);
2599 invokeAttachFileIntent(attachmentChoice);
2600 });
2601 }
2602 } else {
2603 activity.showInstallPgpDialog();
2604 }
2605 } else {
2606 invokeAttachFileIntent(attachmentChoice);
2607 }
2608 }
2609
2610 private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2611 try {
2612 activity.getPreferences()
2613 .edit()
2614 .putString(
2615 RECENTLY_USED_QUICK_ACTION,
2616 SendButtonAction.of(attachmentChoice).toString())
2617 .apply();
2618 } catch (IllegalArgumentException e) {
2619 // just do not save
2620 }
2621 }
2622
2623 @Override
2624 public void onRequestPermissionsResult(
2625 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2626 final PermissionUtils.PermissionResult permissionResult =
2627 PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2628 if (grantResults.length > 0) {
2629 if (allGranted(permissionResult.grantResults) || requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
2630 switch (requestCode) {
2631 case REQUEST_START_DOWNLOAD:
2632 if (this.mPendingDownloadableMessage != null) {
2633 startDownloadable(this.mPendingDownloadableMessage);
2634 }
2635 break;
2636 case REQUEST_ADD_EDITOR_CONTENT:
2637 if (this.mPendingEditorContent != null) {
2638 attachEditorContentToConversation(this.mPendingEditorContent);
2639 }
2640 break;
2641 case REQUEST_COMMIT_ATTACHMENTS:
2642 commitAttachments();
2643 break;
2644 case REQUEST_START_AUDIO_CALL:
2645 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2646 break;
2647 case REQUEST_START_VIDEO_CALL:
2648 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2649 break;
2650 default:
2651 attachFile(requestCode, true, true);
2652 break;
2653 }
2654 } else {
2655 @StringRes int res;
2656 String firstDenied =
2657 getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2658 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2659 res = R.string.no_microphone_permission;
2660 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2661 res = R.string.no_camera_permission;
2662 } else {
2663 res = R.string.no_storage_permission;
2664 }
2665 Toast.makeText(
2666 getActivity(),
2667 getString(res, getString(R.string.app_name)),
2668 Toast.LENGTH_SHORT)
2669 .show();
2670 }
2671 }
2672 if (writeGranted(grantResults, permissions)) {
2673 if (activity != null && activity.xmppConnectionService != null) {
2674 activity.xmppConnectionService.getDrawableCache().evictAll();
2675 activity.xmppConnectionService.restartFileObserver();
2676 }
2677 refresh();
2678 }
2679 if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
2680 XmppConnectionService.toggleForegroundService(activity);
2681 }
2682 }
2683
2684 public void startDownloadable(Message message) {
2685 if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2686 this.mPendingDownloadableMessage = message;
2687 return;
2688 }
2689 Transferable transferable = message.getTransferable();
2690 if (transferable != null) {
2691 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2692 createNewConnection(message);
2693 return;
2694 }
2695 if (!transferable.start()) {
2696 Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2697 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2698 .show();
2699 }
2700 } else if (message.treatAsDownloadable()
2701 || message.hasFileOnRemoteHost()
2702 || MessageUtils.unInitiatedButKnownSize(message)) {
2703 createNewConnection(message);
2704 } else {
2705 Log.d(
2706 Config.LOGTAG,
2707 message.getConversation().getAccount() + ": unable to start downloadable");
2708 }
2709 }
2710
2711 private void createNewConnection(final Message message) {
2712 if (!activity.xmppConnectionService.hasInternetConnection()) {
2713 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2714 .show();
2715 return;
2716 }
2717 if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2718 try {
2719 BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2720 message.setTransferable(transfer);
2721 transfer.start();
2722 } catch (URISyntaxException e) {
2723 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2724 }
2725 } else {
2726 activity.xmppConnectionService
2727 .getHttpConnectionManager()
2728 .createNewDownloadConnection(message, true);
2729 }
2730 }
2731
2732 @SuppressLint("InflateParams")
2733 protected void clearHistoryDialog(final Conversation conversation) {
2734 final MaterialAlertDialogBuilder builder =
2735 new MaterialAlertDialogBuilder(requireActivity());
2736 builder.setTitle(R.string.clear_conversation_history);
2737 final View dialogView =
2738 requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2739 final CheckBox endConversationCheckBox =
2740 dialogView.findViewById(R.id.end_conversation_checkbox);
2741 builder.setView(dialogView);
2742 builder.setNegativeButton(getString(R.string.cancel), null);
2743 builder.setPositiveButton(
2744 getString(R.string.confirm),
2745 (dialog, which) -> {
2746 this.activity.xmppConnectionService.clearConversationHistory(conversation);
2747 if (endConversationCheckBox.isChecked()) {
2748 this.activity.xmppConnectionService.archiveConversation(conversation);
2749 this.activity.onConversationArchived(conversation);
2750 } else {
2751 activity.onConversationsListItemUpdated();
2752 refresh();
2753 }
2754 });
2755 builder.create().show();
2756 }
2757
2758 protected void muteConversationDialog(final Conversation conversation) {
2759 final MaterialAlertDialogBuilder builder =
2760 new MaterialAlertDialogBuilder(requireActivity());
2761 builder.setTitle(R.string.disable_notifications);
2762 final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2763 final CharSequence[] labels = new CharSequence[durations.length];
2764 for (int i = 0; i < durations.length; ++i) {
2765 if (durations[i] == -1) {
2766 labels[i] = activity.getString(R.string.until_further_notice);
2767 } else {
2768 labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2769 }
2770 }
2771 builder.setItems(
2772 labels,
2773 (dialog, which) -> {
2774 final long till;
2775 if (durations[which] == -1) {
2776 till = Long.MAX_VALUE;
2777 } else {
2778 till = System.currentTimeMillis() + (durations[which] * 1000L);
2779 }
2780 conversation.setMutedTill(till);
2781 activity.xmppConnectionService.updateConversation(conversation);
2782 activity.onConversationsListItemUpdated();
2783 refresh();
2784 activity.invalidateOptionsMenu();
2785 });
2786 builder.create().show();
2787 }
2788
2789 private boolean hasPermissions(int requestCode, List<String> permissions) {
2790 final List<String> missingPermissions = new ArrayList<>();
2791 for (String permission : permissions) {
2792 if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
2793 || Config.ONLY_INTERNAL_STORAGE)
2794 && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2795 continue;
2796 }
2797 if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2798 missingPermissions.add(permission);
2799 }
2800 }
2801 if (missingPermissions.size() == 0) {
2802 return true;
2803 } else {
2804 requestPermissions(missingPermissions.toArray(new String[0]), requestCode);
2805 return false;
2806 }
2807 }
2808
2809 private boolean hasPermissions(int requestCode, String... permissions) {
2810 return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2811 }
2812
2813 public void unMuteConversation(final Conversation conversation) {
2814 conversation.setMutedTill(0);
2815 this.activity.xmppConnectionService.updateConversation(conversation);
2816 this.activity.onConversationsListItemUpdated();
2817 refresh();
2818 this.activity.invalidateOptionsMenu();
2819 }
2820
2821 protected void invokeAttachFileIntent(final int attachmentChoice) {
2822 Intent intent = new Intent();
2823
2824 final var takePhotoIntent = new Intent();
2825 final Uri takePhotoUri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2826 pendingTakePhotoUri.push(takePhotoUri);
2827 takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePhotoUri);
2828 takePhotoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2829 takePhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2830 takePhotoIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2831
2832 final var takeVideoIntent = new Intent();
2833 takeVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2834
2835 switch (attachmentChoice) {
2836 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2837 intent.setAction(Intent.ACTION_GET_CONTENT);
2838 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2839 intent.setType("*/*");
2840 intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"});
2841 intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
2842 if (activity.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
2843 intent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent, takeVideoIntent });
2844 }
2845 break;
2846 case ATTACHMENT_CHOICE_RECORD_VIDEO:
2847 intent = takeVideoIntent;
2848 break;
2849 case ATTACHMENT_CHOICE_TAKE_PHOTO:
2850 intent = takePhotoIntent;
2851 break;
2852 case ATTACHMENT_CHOICE_CHOOSE_FILE:
2853 intent.setAction(Intent.ACTION_GET_CONTENT);
2854 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2855 intent.setType("*/*");
2856 intent.addCategory(Intent.CATEGORY_OPENABLE);
2857 intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
2858 break;
2859 case ATTACHMENT_CHOICE_RECORD_VOICE:
2860 intent = new Intent(getActivity(), RecordingActivity.class);
2861 break;
2862 case ATTACHMENT_CHOICE_LOCATION:
2863 intent = GeoHelper.getFetchIntent(activity);
2864 break;
2865 }
2866 final Context context = getActivity();
2867 if (context == null) {
2868 return;
2869 }
2870 try {
2871 startActivityForResult(intent, attachmentChoice);
2872 } catch (final ActivityNotFoundException e) {
2873 Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2874 }
2875 }
2876
2877 @Override
2878 public void onResume() {
2879 super.onResume();
2880 binding.messagesView.post(this::fireReadEvent);
2881 }
2882
2883 private void fireReadEvent() {
2884 if (activity != null && this.conversation != null) {
2885 String uuid = getLastVisibleMessageUuid();
2886 if (uuid != null) {
2887 activity.onConversationRead(this.conversation, uuid);
2888 }
2889 }
2890 }
2891
2892 private void newSubThread() {
2893 Element oldThread = conversation.getThread();
2894 Element thread = new Element("thread", "jabber:client");
2895 thread.setContent(UUID.randomUUID().toString());
2896 if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2897 setThread(thread);
2898 }
2899
2900 private void newThread() {
2901 Element thread = new Element("thread", "jabber:client");
2902 thread.setContent(UUID.randomUUID().toString());
2903 setThread(thread);
2904 }
2905
2906 private void updateThreadFromLastMessage() {
2907 if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2908 Message message = getLastVisibleMessage();
2909 if (message == null) {
2910 newThread();
2911 } else {
2912 if (conversation.getMode() == Conversation.MODE_MULTI) {
2913 if (activity == null || activity.xmppConnectionService == null) return;
2914 if (message.getStatus() < Message.STATUS_SEND) {
2915 if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
2916 }
2917 }
2918
2919 setThread(message.getThread());
2920 }
2921 }
2922 }
2923
2924 private String getLastVisibleMessageUuid() {
2925 Message message = getLastVisibleMessage();
2926 return message == null ? null : message.getUuid();
2927 }
2928
2929 private Message getLastVisibleMessage() {
2930 if (binding == null) {
2931 return null;
2932 }
2933 synchronized (this.messageList) {
2934 int pos = binding.messagesView.getLastVisiblePosition();
2935 if (pos >= 0) {
2936 Message message = null;
2937 for (int i = pos; i >= 0; --i) {
2938 try {
2939 message = (Message) binding.messagesView.getItemAtPosition(i);
2940 } catch (IndexOutOfBoundsException e) {
2941 // should not happen if we synchronize properly. however if that fails we
2942 // just gonna try item -1
2943 continue;
2944 }
2945 if (message.getType() != Message.TYPE_STATUS) {
2946 break;
2947 }
2948 }
2949 if (message != null) {
2950 return message;
2951 }
2952 }
2953 }
2954 return null;
2955 }
2956
2957 public void jumpTo(final Message message) {
2958 if (message.getUuid() == null) return;
2959 for (int i = 0; i < messageList.size(); i++) {
2960 final var m = messageList.get(i);
2961 if (m == null) continue;
2962 if (message.getUuid().equals(m.getUuid())) {
2963 binding.messagesView.setSelection(i);
2964 return;
2965 }
2966 }
2967 }
2968
2969 private void openWith(final Message message) {
2970 if (message.isGeoUri()) {
2971 GeoHelper.view(getActivity(), message);
2972 } else {
2973 final DownloadableFile file =
2974 activity.xmppConnectionService.getFileBackend().getFile(message);
2975 final var fp = message.getFileParams();
2976 final var name = fp == null ? null : fp.getName();
2977 final var displayName = name == null ? file.getName() : name;
2978 ViewUtil.view(activity, file, displayName);
2979 }
2980 }
2981
2982 public void addReaction(final Message message) {
2983 activity.addReaction(emoji -> {
2984 setupReply(message);
2985 binding.textinput.setText(emoji.toInsert());
2986 sendMessage();
2987 });
2988 }
2989
2990 private void reportMessage(final Message message) {
2991 BlockContactDialog.show(activity, conversation.getContact(), message.getServerMsgId());
2992 }
2993
2994 private void showErrorMessage(final Message message) {
2995 final MaterialAlertDialogBuilder builder =
2996 new MaterialAlertDialogBuilder(requireActivity());
2997 builder.setTitle(R.string.error_message);
2998 final String errorMessage = message.getErrorMessage();
2999 final String[] errorMessageParts =
3000 errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
3001 final String displayError;
3002 if (errorMessageParts.length == 2) {
3003 displayError = errorMessageParts[1];
3004 } else {
3005 displayError = errorMessage;
3006 }
3007 builder.setMessage(displayError);
3008 builder.setNegativeButton(
3009 R.string.copy_to_clipboard,
3010 (dialog, which) -> {
3011 activity.copyTextToClipboard(displayError, R.string.error_message);
3012 Toast.makeText(
3013 activity,
3014 R.string.error_message_copied_to_clipboard,
3015 Toast.LENGTH_SHORT)
3016 .show();
3017 });
3018 builder.setPositiveButton(R.string.confirm, null);
3019 builder.create().show();
3020 }
3021
3022 public boolean onInlineImageLongClicked(Cid cid) {
3023 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3024 if (f == null) return false;
3025
3026 saveAsSticker(f, null);
3027 return true;
3028 }
3029
3030 private void saveAsSticker(final Message m) {
3031 String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
3032 existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
3033 saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
3034 }
3035
3036 private void saveAsSticker(final File file, final String name) {
3037 savingAsSticker = file;
3038
3039 Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
3040 intent.addCategory(Intent.CATEGORY_OPENABLE);
3041 intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file, file.getName())));
3042 intent.putExtra(Intent.EXTRA_TITLE, name);
3043
3044 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3045 final String dir = p.getString("sticker_directory", "Stickers");
3046 if (dir.startsWith("content://")) {
3047 intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
3048 } else {
3049 new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
3050 Uri uri;
3051 if (Build.VERSION.SDK_INT >= 29) {
3052 Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
3053 uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
3054 uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
3055 } else {
3056 uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
3057 }
3058 intent.putExtra("android.provider.extra.INITIAL_URI", uri);
3059 intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
3060 }
3061
3062 Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
3063 startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
3064 }
3065
3066 private void deleteFile(final Message message) {
3067 final MaterialAlertDialogBuilder builder =
3068 new MaterialAlertDialogBuilder(requireActivity());
3069 builder.setNegativeButton(R.string.cancel, null);
3070 builder.setTitle(R.string.delete_file_dialog);
3071 builder.setMessage(R.string.delete_file_dialog_msg);
3072 builder.setPositiveButton(
3073 R.string.confirm,
3074 (dialog, which) -> {
3075 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
3076 if (thumbs != null && !thumbs.isEmpty()) {
3077 for (Element thumb : thumbs) {
3078 Uri uri = Uri.parse(thumb.getAttribute("uri"));
3079 if (uri.getScheme().equals("cid")) {
3080 Cid cid = BobTransfer.cid(uri);
3081 if (cid == null) continue;
3082 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3083 activity.xmppConnectionService.evictPreview(f);
3084 f.delete();
3085 }
3086 }
3087 }
3088 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
3089 activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
3090 activity.xmppConnectionService.updateMessage(message, false);
3091 activity.onConversationsListItemUpdated();
3092 refresh();
3093 }
3094 });
3095 builder.create().show();
3096 }
3097
3098 private void resendMessage(final Message message, final boolean forceP2P) {
3099 if (message.isFileOrImage()) {
3100 if (!(message.getConversation() instanceof Conversation conversation)) {
3101 return;
3102 }
3103 final DownloadableFile file =
3104 activity.xmppConnectionService.getFileBackend().getFile(message);
3105 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
3106 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
3107 if (!message.hasFileOnRemoteHost()
3108 && xmppConnection != null
3109 && conversation.getMode() == Conversational.MODE_SINGLE
3110 && (!xmppConnection
3111 .getFeatures()
3112 .httpUpload(message.getFileParams().getSize())
3113 || forceP2P)) {
3114 activity.selectPresence(
3115 conversation,
3116 () -> {
3117 message.setCounterpart(conversation.getNextCounterpart());
3118 activity.xmppConnectionService.resendFailedMessages(
3119 message, forceP2P);
3120 new Handler()
3121 .post(
3122 () -> {
3123 int size = messageList.size();
3124 this.binding.messagesView.setSelection(
3125 size - 1);
3126 });
3127 });
3128 return;
3129 }
3130 } else if (!Compatibility.hasStoragePermission(getActivity())) {
3131 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
3132 return;
3133 } else {
3134 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
3135 message.setDeleted(true);
3136 activity.xmppConnectionService.updateMessage(message, false);
3137 activity.onConversationsListItemUpdated();
3138 refresh();
3139 return;
3140 }
3141 }
3142 activity.xmppConnectionService.resendFailedMessages(message, false);
3143 new Handler()
3144 .post(
3145 () -> {
3146 int size = messageList.size();
3147 this.binding.messagesView.setSelection(size - 1);
3148 });
3149 }
3150
3151 private void cancelTransmission(Message message) {
3152 Transferable transferable = message.getTransferable();
3153 if (transferable != null) {
3154 transferable.cancel();
3155 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
3156 activity.xmppConnectionService.markMessage(
3157 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
3158 }
3159 }
3160
3161 private void retryDecryption(Message message) {
3162 message.setEncryption(Message.ENCRYPTION_PGP);
3163 activity.onConversationsListItemUpdated();
3164 refresh();
3165 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
3166 }
3167
3168 public void privateMessageWith(final Jid counterpart) {
3169 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3170 activity.xmppConnectionService.sendChatState(conversation);
3171 }
3172 this.binding.textinput.setText("");
3173 this.conversation.setNextCounterpart(counterpart);
3174 updateChatMsgHint();
3175 updateSendButton();
3176 updateEditablity();
3177 }
3178
3179 private void correctMessage(final Message message) {
3180 setThread(message.getThread());
3181 conversation.setUserSelectedThread(true);
3182 this.conversation.setCorrectingMessage(message);
3183 final Editable editable = binding.textinput.getText();
3184 this.conversation.setDraftMessage(editable.toString());
3185 this.binding.textinput.setText("");
3186 this.binding.textinput.append(message.getBody(true));
3187 if (message.getSubject() != null && message.getSubject().length() > 0) {
3188 this.binding.textinputSubject.setText(message.getSubject());
3189 this.binding.textinputSubject.setVisibility(View.VISIBLE);
3190 }
3191 setupReply(message.getInReplyTo());
3192 }
3193
3194 private void highlightInConference(String nick) {
3195 final Editable editable = this.binding.textinput.getText();
3196 String oldString = editable.toString().trim();
3197 final int pos = this.binding.textinput.getSelectionStart();
3198 if (oldString.isEmpty() || pos == 0) {
3199 editable.insert(0, nick + ": ");
3200 } else {
3201 final char before = editable.charAt(pos - 1);
3202 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
3203 if (before == '\n') {
3204 editable.insert(pos, nick + ": ");
3205 } else {
3206 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
3207 if (NickValidityChecker.check(
3208 conversation,
3209 Arrays.asList(
3210 editable.subSequence(0, pos - 2).toString().split(", ")))) {
3211 editable.insert(pos - 2, ", " + nick);
3212 return;
3213 }
3214 }
3215 editable.insert(
3216 pos,
3217 (Character.isWhitespace(before) ? "" : " ")
3218 + nick
3219 + (Character.isWhitespace(after) ? "" : " "));
3220 if (Character.isWhitespace(after)) {
3221 this.binding.textinput.setSelection(
3222 this.binding.textinput.getSelectionStart() + 1);
3223 }
3224 }
3225 }
3226 }
3227
3228 @Override
3229 public void startActivityForResult(Intent intent, int requestCode) {
3230 final Activity activity = getActivity();
3231 if (activity instanceof ConversationsActivity) {
3232 ((ConversationsActivity) activity).clearPendingViewIntent();
3233 }
3234 super.startActivityForResult(intent, requestCode);
3235 }
3236
3237 @Override
3238 public void onSaveInstanceState(@NonNull Bundle outState) {
3239 super.onSaveInstanceState(outState);
3240 if (conversation != null) {
3241 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
3242 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
3243 final Uri uri = pendingTakePhotoUri.peek();
3244 if (uri != null) {
3245 outState.putString(STATE_PHOTO_URI, uri.toString());
3246 }
3247 final ScrollState scrollState = getScrollPosition();
3248 if (scrollState != null) {
3249 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
3250 }
3251 final ArrayList<Attachment> attachments =
3252 mediaPreviewAdapter == null
3253 ? new ArrayList<>()
3254 : mediaPreviewAdapter.getAttachments();
3255 if (attachments.size() > 0) {
3256 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
3257 }
3258 }
3259 }
3260
3261 @Override
3262 public void onActivityCreated(Bundle savedInstanceState) {
3263 super.onActivityCreated(savedInstanceState);
3264 if (savedInstanceState == null) {
3265 return;
3266 }
3267 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
3268 ArrayList<Attachment> attachments =
3269 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
3270 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
3271 if (uuid != null) {
3272 QuickLoader.set(uuid);
3273 this.pendingConversationsUuid.push(uuid);
3274 if (attachments != null && attachments.size() > 0) {
3275 this.pendingMediaPreviews.push(attachments);
3276 }
3277 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
3278 if (takePhotoUri != null) {
3279 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
3280 }
3281 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
3282 }
3283 }
3284
3285 @Override
3286 public void onStart() {
3287 super.onStart();
3288 if (this.reInitRequiredOnStart && this.conversation != null) {
3289 final Bundle extras = pendingExtras.pop();
3290 reInit(this.conversation, extras != null);
3291 if (extras != null) {
3292 processExtras(extras);
3293 }
3294 } else if (conversation == null
3295 && activity != null
3296 && activity.xmppConnectionService != null) {
3297 final String uuid = pendingConversationsUuid.pop();
3298 Log.d(
3299 Config.LOGTAG,
3300 "ConversationFragment.onStart() - activity was bound but no conversation"
3301 + " loaded. uuid="
3302 + uuid);
3303 if (uuid != null) {
3304 findAndReInitByUuidOrArchive(uuid);
3305 }
3306 }
3307 }
3308
3309 @Override
3310 public void onStop() {
3311 super.onStop();
3312 final Activity activity = getActivity();
3313 messageListAdapter.unregisterListenerInAudioPlayer();
3314 if (activity == null || !activity.isChangingConfigurations()) {
3315 hideSoftKeyboard(activity);
3316 messageListAdapter.stopAudioPlayer();
3317 }
3318 if (this.conversation != null) {
3319 final String msg = this.binding.textinput.getText().toString();
3320 storeNextMessage(msg);
3321 updateChatState(this.conversation, msg);
3322 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
3323 }
3324 this.reInitRequiredOnStart = true;
3325 }
3326
3327 private void updateChatState(final Conversation conversation, final String msg) {
3328 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
3329 Account.State status = conversation.getAccount().getStatus();
3330 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
3331 activity.xmppConnectionService.sendChatState(conversation);
3332 }
3333 }
3334
3335 private void saveMessageDraftStopAudioPlayer() {
3336 final Conversation previousConversation = this.conversation;
3337 if (this.activity == null || this.binding == null || previousConversation == null) {
3338 return;
3339 }
3340 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
3341 final String msg = this.binding.textinput.getText().toString();
3342 storeNextMessage(msg);
3343 updateChatState(this.conversation, msg);
3344 messageListAdapter.stopAudioPlayer();
3345 mediaPreviewAdapter.clearPreviews();
3346 toggleInputMethod();
3347 }
3348
3349 public void reInit(final Conversation conversation, final Bundle extras) {
3350 QuickLoader.set(conversation.getUuid());
3351 final boolean changedConversation = this.conversation != conversation;
3352 if (changedConversation) {
3353 this.saveMessageDraftStopAudioPlayer();
3354 }
3355 this.clearPending();
3356 if (this.reInit(conversation, extras != null)) {
3357 if (extras != null) {
3358 processExtras(extras);
3359 }
3360 this.reInitRequiredOnStart = false;
3361 } else {
3362 this.reInitRequiredOnStart = true;
3363 pendingExtras.push(extras);
3364 }
3365 resetUnreadMessagesCount();
3366 }
3367
3368 private void reInit(Conversation conversation) {
3369 reInit(conversation, false);
3370 }
3371
3372 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
3373 if (conversation == null) {
3374 return false;
3375 }
3376 final Conversation originalConversation = this.conversation;
3377 this.conversation = conversation;
3378 // once we set the conversation all is good and it will automatically do the right thing in
3379 // onStart()
3380 if (this.activity == null || this.binding == null) {
3381 return false;
3382 }
3383
3384 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3385 activity.onConversationArchived(this.conversation);
3386 return false;
3387 }
3388
3389 final var cursord = activity.getDrawable(R.drawable.cursor_on_tertiary_container);
3390 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getAccounts().size() > 1) {
3391 final var bg = MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorSurface);
3392 final var accountColor = conversation.getAccount().getColor(activity.isDark());
3393 final var colors = MaterialColors.getColorRoles(activity, accountColor);
3394 final var accent = activity.isDark() ? ColorUtils.blendARGB(colors.getAccentContainer(), bg, 1.0f - Math.max(0.25f, Color.alpha(accountColor) / 255.0f)) : colors.getAccentContainer();
3395 cursord.setTintList(ColorStateList.valueOf(colors.getOnAccentContainer()));
3396 binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(accent));
3397 binding.textinputSubject.setTextColor(colors.getOnAccentContainer());
3398 binding.textinput.setTextColor(colors.getOnAccentContainer());
3399 binding.textinputSubject.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3400 binding.textinput.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3401 binding.textInputHint.setTextColor(colors.getOnAccentContainer());
3402 } else {
3403 cursord.setTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer)));
3404 binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.inputLayout, com.google.android.material.R.attr.colorTertiaryContainer)));
3405 binding.textinputSubject.setTextColor(MaterialColors.getColor(binding.textinputSubject, com.google.android.material.R.attr.colorOnTertiaryContainer));
3406 binding.textinput.setTextColor(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer));
3407 binding.textinputSubject.setHintTextColor(R.color.hint_on_tertiary_container);
3408 binding.textinput.setHintTextColor(R.color.hint_on_tertiary_container);
3409 binding.textInputHint.setTextColor(MaterialColors.getColor(binding.textInputHint, com.google.android.material.R.attr.colorOnTertiaryContainer));
3410 }
3411 if (Build.VERSION.SDK_INT >= 29) {
3412 binding.textinputSubject.setTextCursorDrawable(cursord);
3413 binding.textinput.setTextCursorDrawable(cursord);
3414 }
3415
3416 setThread(conversation.getThread());
3417 setupReply(conversation.getReplyTo());
3418
3419 stopScrolling();
3420 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3421
3422 if (this.conversation.isRead(activity == null ? null : activity.xmppConnectionService) && hasExtras) {
3423 Log.d(Config.LOGTAG, "trimming conversation");
3424 this.conversation.trim();
3425 }
3426
3427 setupIme();
3428
3429 final boolean scrolledToBottomAndNoPending =
3430 this.scrolledToBottom() && pendingScrollState.peek() == null;
3431
3432 this.binding.textSendButton.setContentDescription(
3433 activity.getString(R.string.send_message_to_x, conversation.getName()));
3434 this.binding.textinput.setKeyboardListener(null);
3435 this.binding.textinputSubject.setKeyboardListener(null);
3436 final boolean participating =
3437 conversation.getMode() == Conversational.MODE_SINGLE
3438 || conversation.getMucOptions().participating();
3439 if (participating) {
3440 this.binding.textinput.setText(this.conversation.getNextMessage());
3441 this.binding.textinput.setSelection(this.binding.textinput.length());
3442 } else {
3443 this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3444 }
3445 this.binding.textinput.setKeyboardListener(this);
3446 this.binding.textinputSubject.setKeyboardListener(this);
3447 messageListAdapter.updatePreferences();
3448 refresh(false);
3449 activity.invalidateOptionsMenu();
3450 this.conversation.messagesLoaded.set(true);
3451 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3452
3453 if (hasExtras || scrolledToBottomAndNoPending) {
3454 resetUnreadMessagesCount();
3455 synchronized (this.messageList) {
3456 Log.d(Config.LOGTAG, "jump to first unread message");
3457 final Message first = conversation.getFirstUnreadMessage();
3458 final int bottom = Math.max(0, this.messageList.size() - 1);
3459 final int pos;
3460 final boolean jumpToBottom;
3461 if (first == null) {
3462 pos = bottom;
3463 jumpToBottom = true;
3464 } else {
3465 int i = getIndexOf(first.getUuid(), this.messageList);
3466 pos = i < 0 ? bottom : i;
3467 jumpToBottom = false;
3468 }
3469 setSelection(pos, jumpToBottom);
3470 }
3471 }
3472
3473 this.binding.messagesView.post(this::fireReadEvent);
3474 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3475 // layout which might be unnecessary since we can *see* it
3476 activity.xmppConnectionService
3477 .getNotificationService()
3478 .setOpenConversation(this.conversation);
3479
3480 if (commandAdapter != null && conversation != originalConversation) {
3481 commandAdapter.clear();
3482 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3483 refreshCommands(false);
3484 }
3485 if (commandAdapter == null && conversation != null) {
3486 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3487 commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3488 binding.commandsView.setAdapter(commandAdapter);
3489 binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3490 if (activity == null) return;
3491
3492 commandAdapter.getItem(position).start(activity, ConversationFragment.this.conversation);
3493 });
3494 refreshCommands(false);
3495 }
3496
3497 binding.commandsNote.setVisibility(activity.xmppConnectionService.isOnboarding() ? View.VISIBLE : View.GONE);
3498
3499 return true;
3500 }
3501
3502 @Override
3503 public void refreshForNewCaps(final Set<Jid> newCapsJids) {
3504 if (newCapsJids.isEmpty() || (conversation != null && newCapsJids.contains(conversation.getJid().asBareJid()))) {
3505 refreshCommands(true);
3506 }
3507 }
3508
3509 protected void refreshCommands(boolean delayShow) {
3510 if (commandAdapter == null) return;
3511
3512 final CommandAdapter.MucConfig mucConfig =
3513 conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER) ?
3514 new CommandAdapter.MucConfig() :
3515 null;
3516
3517 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3518 if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3519 commandJid = conversation.getJid().asBareJid();
3520 }
3521 if (commandJid == null && conversation.getJid().isDomainJid()) {
3522 commandJid = conversation.getJid();
3523 }
3524 if (commandJid == null) {
3525 binding.commandsViewProgressbar.setVisibility(View.GONE);
3526 if (mucConfig == null) {
3527 conversation.hideViewPager();
3528 } else {
3529 commandAdapter.clear();
3530 commandAdapter.add(mucConfig);
3531 conversation.showViewPager();
3532 }
3533 } else {
3534 if (!delayShow) conversation.showViewPager();
3535 binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3536 activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (iq) -> {
3537 if (activity == null) return;
3538
3539 activity.runOnUiThread(() -> {
3540 binding.commandsViewProgressbar.setVisibility(View.GONE);
3541 commandAdapter.clear();
3542 if (iq.getType() == Iq.Type.RESULT) {
3543 for (Element child : iq.query().getChildren()) {
3544 if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3545 commandAdapter.add(new CommandAdapter.Command0050(child));
3546 }
3547 }
3548
3549 if (mucConfig != null) commandAdapter.add(mucConfig);
3550
3551 if (commandAdapter.getCount() < 1) {
3552 conversation.hideViewPager();
3553 } else if (delayShow) {
3554 conversation.showViewPager();
3555 }
3556 });
3557 });
3558 }
3559 }
3560
3561 private void resetUnreadMessagesCount() {
3562 lastMessageUuid = null;
3563 hideUnreadMessagesCount();
3564 }
3565
3566 private void hideUnreadMessagesCount() {
3567 if (this.binding == null) {
3568 return;
3569 }
3570 this.binding.scrollToBottomButton.setEnabled(false);
3571 this.binding.scrollToBottomButton.hide();
3572 this.binding.unreadCountCustomView.setVisibility(View.GONE);
3573 }
3574
3575 private void setSelection(int pos, boolean jumpToBottom) {
3576 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3577 this.binding.messagesView.post(
3578 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3579 this.binding.messagesView.post(this::fireReadEvent);
3580 }
3581
3582 private boolean scrolledToBottom() {
3583 return this.binding != null && scrolledToBottom(this.binding.messagesView);
3584 }
3585
3586 private void processExtras(final Bundle extras) {
3587 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3588 final String text = extras.getString(Intent.EXTRA_TEXT);
3589 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3590 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3591 final String postInitAction =
3592 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3593 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3594 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3595 final boolean doNotAppend =
3596 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3597 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3598
3599 final String thread = extras.getString(ConversationsActivity.EXTRA_THREAD);
3600 if (thread != null) {
3601 conversation.setLockThread(true);
3602 backPressedLeaveSingleThread.setEnabled(true);
3603 setThread(new Element("thread").setContent(thread));
3604 refresh();
3605 }
3606
3607 final List<Uri> uris = extractUris(extras);
3608 if (uris != null && uris.size() > 0) {
3609 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3610 mediaPreviewAdapter.addMediaPreviews(
3611 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3612 } else {
3613 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3614 mediaPreviewAdapter.addMediaPreviews(
3615 Attachment.of(getActivity(), cleanedUris, type));
3616 }
3617 toggleInputMethod();
3618 return;
3619 }
3620 if (nick != null) {
3621 if (pm) {
3622 Jid jid = conversation.getJid();
3623 try {
3624 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3625 privateMessageWith(next);
3626 } catch (final IllegalArgumentException ignored) {
3627 // do nothing
3628 }
3629 } else {
3630 final MucOptions mucOptions = conversation.getMucOptions();
3631 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3632 highlightInConference(nick);
3633 }
3634 }
3635 } else {
3636 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3637 mediaPreviewAdapter.addMediaPreviews(
3638 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3639 toggleInputMethod();
3640 return;
3641 } else if (text != null && asQuote) {
3642 quoteText(text);
3643 } else {
3644 appendText(text, doNotAppend);
3645 }
3646 }
3647 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3648 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3649 return;
3650 }
3651 if ("call".equals(postInitAction)) {
3652 checkPermissionAndTriggerAudioCall();
3653 }
3654 if ("message".equals(postInitAction)) {
3655 binding.conversationViewPager.post(() -> {
3656 binding.conversationViewPager.setCurrentItem(0);
3657 });
3658 }
3659 if ("command".equals(postInitAction)) {
3660 binding.conversationViewPager.post(() -> {
3661 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3662 if (adapter != null && adapter.getCount() > 1) {
3663 binding.conversationViewPager.setCurrentItem(1);
3664 }
3665 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3666 Jid commandJid = null;
3667 if (jid != null) {
3668 try {
3669 commandJid = Jid.of(jid);
3670 } catch (final IllegalArgumentException e) { }
3671 }
3672 if (commandJid == null || !commandJid.isFullJid()) {
3673 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3674 if (discoJid != null) commandJid = discoJid;
3675 }
3676 if (node != null && commandJid != null && activity != null) {
3677 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3678 }
3679 });
3680 return;
3681 }
3682 Message message =
3683 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3684 if ("webxdc".equals(postInitAction)) {
3685 if (message == null) {
3686 message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3687 }
3688 if (message == null) return;
3689
3690 Cid webxdcCid = message.getFileParams().getCids().get(0);
3691 WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message);
3692 Conversation conversation = (Conversation) message.getConversation();
3693 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3694 conversation.startWebxdc(webxdc);
3695 }
3696 }
3697 if (message != null) {
3698 startDownloadable(message);
3699 }
3700 if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3701 if (!conversation.switchToSession("jabber:iq:register")) {
3702 conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3703 }
3704 }
3705 }
3706
3707 private Element commandFor(final Jid jid, final String node) {
3708 if (commandAdapter != null) {
3709 for (int i = 0; i < commandAdapter.getCount(); i++) {
3710 final CommandAdapter.Command c = commandAdapter.getItem(i);
3711 if (!(c instanceof CommandAdapter.Command0050)) continue;
3712
3713 final Element command = ((CommandAdapter.Command0050) c).el;
3714 final String commandNode = command.getAttribute("node");
3715 if (commandNode == null || !commandNode.equals(node)) continue;
3716
3717 final Jid commandJid = command.getAttributeAsJid("jid");
3718 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3719
3720 return command;
3721 }
3722 }
3723
3724 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3725 }
3726
3727 private List<Uri> extractUris(final Bundle extras) {
3728 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3729 if (uris != null) {
3730 return uris;
3731 }
3732 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3733 if (uri != null) {
3734 return Collections.singletonList(uri);
3735 } else {
3736 return null;
3737 }
3738 }
3739
3740 private List<Uri> cleanUris(final List<Uri> uris) {
3741 final Iterator<Uri> iterator = uris.iterator();
3742 while (iterator.hasNext()) {
3743 final Uri uri = iterator.next();
3744 if (FileBackend.dangerousFile(uri)) {
3745 iterator.remove();
3746 Toast.makeText(
3747 requireActivity(),
3748 R.string.security_violation_not_attaching_file,
3749 Toast.LENGTH_SHORT)
3750 .show();
3751 }
3752 }
3753 return uris;
3754 }
3755
3756 private boolean showBlockSubmenu(View view) {
3757 final Jid jid = conversation.getJid();
3758 final int mode = conversation.getMode();
3759 final var contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3760 final boolean showReject = contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3761 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3762 popupMenu.inflate(R.menu.block);
3763 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3764 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3765 popupMenu.getMenu().findItem(R.id.add_contact).setVisible(!contact.showInRoster());
3766 popupMenu.setOnMenuItemClickListener(
3767 menuItem -> {
3768 Blockable blockable;
3769 switch (menuItem.getItemId()) {
3770 case R.id.reject:
3771 activity.xmppConnectionService.stopPresenceUpdatesTo(
3772 conversation.getContact());
3773 updateSnackBar(conversation);
3774 return true;
3775 case R.id.add_contact:
3776 mAddBackClickListener.onClick(view);
3777 return true;
3778 case R.id.block_domain:
3779 blockable =
3780 conversation
3781 .getAccount()
3782 .getRoster()
3783 .getContact(jid.getDomain());
3784 break;
3785 default:
3786 blockable = conversation;
3787 }
3788 BlockContactDialog.show(activity, blockable);
3789 return true;
3790 });
3791 popupMenu.show();
3792 return true;
3793 }
3794
3795 private boolean showBlockMucSubmenu(View view) {
3796 final var jid = conversation.getJid();
3797 final var popupMenu = new PopupMenu(getActivity(), view);
3798 popupMenu.inflate(R.menu.block_muc);
3799 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3800 popupMenu.setOnMenuItemClickListener(
3801 menuItem -> {
3802 Blockable blockable;
3803 switch (menuItem.getItemId()) {
3804 case R.id.reject:
3805 activity.xmppConnectionService.clearConversationHistory(conversation);
3806 activity.xmppConnectionService.archiveConversation(conversation);
3807 return true;
3808 case R.id.add_bookmark:
3809 activity.xmppConnectionService.saveConversationAsBookmark(conversation, "");
3810 updateSnackBar(conversation);
3811 return true;
3812 case R.id.block_contact:
3813 blockable =
3814 conversation
3815 .getAccount()
3816 .getRoster()
3817 .getContact(Jid.of(conversation.getAttribute("inviter")));
3818 break;
3819 default:
3820 blockable = conversation;
3821 }
3822 BlockContactDialog.show(activity, blockable);
3823 activity.xmppConnectionService.archiveConversation(conversation);
3824 return true;
3825 });
3826 popupMenu.show();
3827 return true;
3828 }
3829
3830 private void updateSnackBar(final Conversation conversation) {
3831 final Account account = conversation.getAccount();
3832 final XmppConnection connection = account.getXmppConnection();
3833 final int mode = conversation.getMode();
3834 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3835 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3836 return;
3837 }
3838 if (account.getStatus() == Account.State.DISABLED) {
3839 showSnackbar(
3840 R.string.this_account_is_disabled,
3841 R.string.enable,
3842 this.mEnableAccountListener);
3843 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3844 showSnackbar(
3845 R.string.this_account_is_logged_out,
3846 R.string.log_in,
3847 this.mEnableAccountListener);
3848 } else if (conversation.isBlocked()) {
3849 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3850 } else if (account.getStatus() == Account.State.CONNECTING) {
3851 showSnackbar(R.string.this_account_is_connecting, 0, null);
3852 } else if (account.getStatus() != Account.State.ONLINE) {
3853 showSnackbar(R.string.this_account_is_offline, 0, null);
3854 } else if (contact != null
3855 && !contact.showInRoster()
3856 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3857 showSnackbar(
3858 R.string.contact_added_you,
3859 R.string.options,
3860 this.mBlockClickListener,
3861 this.mLongPressBlockListener);
3862 } else if (contact != null
3863 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3864 showSnackbar(
3865 R.string.contact_asks_for_presence_subscription,
3866 R.string.allow,
3867 this.mAllowPresenceSubscription,
3868 this.mLongPressBlockListener);
3869 } else if (mode == Conversation.MODE_MULTI
3870 && !conversation.getMucOptions().online()
3871 && account.getStatus() == Account.State.ONLINE) {
3872 switch (conversation.getMucOptions().getError()) {
3873 case NICK_IN_USE:
3874 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3875 break;
3876 case NO_RESPONSE:
3877 showSnackbar(R.string.joining_conference, 0, null);
3878 break;
3879 case SERVER_NOT_FOUND:
3880 if (conversation.receivedMessagesCount() > 0) {
3881 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3882 } else {
3883 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3884 }
3885 break;
3886 case REMOTE_SERVER_TIMEOUT:
3887 if (conversation.receivedMessagesCount() > 0) {
3888 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3889 } else {
3890 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3891 }
3892 break;
3893 case PASSWORD_REQUIRED:
3894 showSnackbar(
3895 R.string.conference_requires_password,
3896 R.string.enter_password,
3897 enterPassword);
3898 break;
3899 case BANNED:
3900 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3901 break;
3902 case MEMBERS_ONLY:
3903 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3904 break;
3905 case RESOURCE_CONSTRAINT:
3906 showSnackbar(
3907 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3908 break;
3909 case KICKED:
3910 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3911 break;
3912 case TECHNICAL_PROBLEMS:
3913 showSnackbar(
3914 R.string.conference_technical_problems, R.string.try_again, joinMuc);
3915 break;
3916 case UNKNOWN:
3917 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3918 break;
3919 case INVALID_NICK:
3920 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3921 case SHUTDOWN:
3922 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3923 break;
3924 case DESTROYED:
3925 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3926 break;
3927 case NON_ANONYMOUS:
3928 showSnackbar(
3929 R.string.group_chat_will_make_your_jabber_id_public,
3930 R.string.join,
3931 acceptJoin);
3932 break;
3933 default:
3934 hideSnackbar();
3935 break;
3936 }
3937 } else if (account.hasPendingPgpIntent(conversation)) {
3938 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3939 } else if (connection != null
3940 && connection.getFeatures().blocking()
3941 && conversation.strangerInvited()) {
3942 showSnackbar(
3943 R.string.received_invite_from_stranger,
3944 R.string.options,
3945 (v) -> showBlockMucSubmenu(v),
3946 (v) -> showBlockMucSubmenu(v));
3947 } else if (connection != null
3948 && connection.getFeatures().blocking()
3949 && conversation.countMessages() != 0
3950 && !conversation.isBlocked()
3951 && conversation.isWithStranger()) {
3952 showSnackbar(
3953 R.string.received_message_from_stranger,
3954 R.string.options,
3955 this.mBlockClickListener,
3956 this.mLongPressBlockListener);
3957 } else {
3958 hideSnackbar();
3959 }
3960 }
3961
3962 @Override
3963 public void refresh() {
3964 if (this.binding == null) {
3965 Log.d(
3966 Config.LOGTAG,
3967 "ConversationFragment.refresh() skipped updated because view binding was null");
3968 return;
3969 }
3970 if (this.conversation != null
3971 && this.activity != null
3972 && this.activity.xmppConnectionService != null) {
3973 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3974 activity.onConversationArchived(this.conversation);
3975 return;
3976 }
3977 }
3978 this.refresh(true);
3979 }
3980
3981 private void refresh(boolean notifyConversationRead) {
3982 synchronized (this.messageList) {
3983 if (this.conversation != null) {
3984 if (messageListAdapter.hasSelection()) {
3985 if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3986 } else {
3987 conversation.populateWithMessages(this.messageList, activity == null ? null : activity.xmppConnectionService);
3988 try {
3989 updateStatusMessages();
3990 } catch (IllegalStateException e) {
3991 Log.e(Config.LOGTAG, "Problem updating status messages on refresh: " + e);
3992 }
3993 this.messageListAdapter.notifyDataSetChanged();
3994 }
3995 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3996 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3997 binding.unreadCountCustomView.setUnreadCount(
3998 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3999 }
4000 updateSnackBar(conversation);
4001 if (activity != null) updateChatMsgHint();
4002 if (notifyConversationRead && activity != null) {
4003 binding.messagesView.post(this::fireReadEvent);
4004 }
4005 updateSendButton();
4006 updateEditablity();
4007 conversation.refreshSessions();
4008 }
4009 }
4010 }
4011
4012 protected void messageSent() {
4013 binding.textinputSubject.setText("");
4014 binding.textinputSubject.setVisibility(View.GONE);
4015 setThread(null);
4016 setupReply(null);
4017 conversation.setUserSelectedThread(false);
4018 mSendingPgpMessage.set(false);
4019 this.binding.textinput.setText("");
4020 if (conversation.setCorrectingMessage(null)) {
4021 this.binding.textinput.append(conversation.getDraftMessage());
4022 conversation.setDraftMessage(null);
4023 }
4024 storeNextMessage();
4025 updateChatMsgHint();
4026 if (activity == null) return;
4027 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
4028 final boolean prefScrollToBottom =
4029 p.getBoolean(
4030 "scroll_to_bottom",
4031 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
4032 if (prefScrollToBottom || scrolledToBottom()) {
4033 new Handler()
4034 .post(
4035 () -> {
4036 int size = messageList.size();
4037 this.binding.messagesView.setSelection(size - 1);
4038 });
4039 }
4040 }
4041
4042 private boolean storeNextMessage() {
4043 return storeNextMessage(this.binding.textinput.getText().toString());
4044 }
4045
4046 private boolean storeNextMessage(String msg) {
4047 final boolean participating =
4048 conversation.getMode() == Conversational.MODE_SINGLE
4049 || conversation.getMucOptions().participating();
4050 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
4051 && participating
4052 && this.conversation.setNextMessage(msg) && activity != null) {
4053 activity.xmppConnectionService.updateConversation(this.conversation);
4054 return true;
4055 }
4056 return false;
4057 }
4058
4059 public void doneSendingPgpMessage() {
4060 mSendingPgpMessage.set(false);
4061 }
4062
4063 public long getMaxHttpUploadSize(Conversation conversation) {
4064 final XmppConnection connection = conversation.getAccount().getXmppConnection();
4065 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
4066 }
4067
4068 private boolean canWrite() {
4069 return
4070 this.conversation.getMode() == Conversation.MODE_SINGLE
4071 || this.conversation.getMucOptions().participating()
4072 || this.conversation.getNextCounterpart() != null;
4073 }
4074
4075 private void updateEditablity() {
4076 boolean canWrite = canWrite();
4077 this.binding.textinput.setFocusable(canWrite);
4078 this.binding.textinput.setFocusableInTouchMode(canWrite);
4079 this.binding.textSendButton.setEnabled(canWrite);
4080 this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
4081 this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
4082 this.binding.textinput.setCursorVisible(canWrite);
4083 this.binding.textinput.setEnabled(canWrite);
4084 }
4085
4086 public void updateSendButton() {
4087 boolean hasAttachments =
4088 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
4089 final Conversation c = this.conversation;
4090 final Presence.Status status;
4091 final String text =
4092 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
4093 final SendButtonAction action;
4094 if (hasAttachments) {
4095 action = SendButtonAction.TEXT;
4096 } else {
4097 action = SendButtonTool.getAction(getActivity(), c, text, binding.textinputSubject.getText().toString());
4098 }
4099 if (c.getAccount().getStatus() == Account.State.ONLINE) {
4100 if (activity != null
4101 && activity.xmppConnectionService != null
4102 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
4103 status = Presence.Status.OFFLINE;
4104 } else if (c.getMode() == Conversation.MODE_SINGLE) {
4105 status = c.getContact().getShownStatus();
4106 } else {
4107 status =
4108 c.getMucOptions().online()
4109 ? Presence.Status.ONLINE
4110 : Presence.Status.OFFLINE;
4111 }
4112 } else {
4113 status = Presence.Status.OFFLINE;
4114 }
4115 this.binding.textSendButton.setTag(action);
4116 this.binding.textSendButton.setIconTint(ColorStateList.valueOf(SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
4117 // TODO send button color
4118 final Activity activity = getActivity();
4119 if (activity != null) {
4120 this.binding.textSendButton.setIconResource(
4121 SendButtonTool.getSendButtonImageResource(action, text.length() > 0 || hasAttachments || (c.getThread() != null && binding.textinputSubject.getText().length() > 0)));
4122 }
4123
4124 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
4125 if (identiconWidth < 0) identiconWidth = params.width;
4126 if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
4127 binding.conversationViewPager.setCurrentItem(0);
4128 params.width = conversation.getThread() == null ? 0 : identiconWidth;
4129 } else {
4130 params.width = identiconWidth;
4131 }
4132 if (!canWrite()) params.width = 0;
4133 binding.threadIdenticonLayout.setLayoutParams(params);
4134 }
4135
4136 protected void updateStatusMessages() {
4137 DateSeparator.addAll(this.messageList);
4138 if (showLoadMoreMessages(conversation)) {
4139 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
4140 }
4141 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4142 ChatState state = conversation.getIncomingChatState();
4143 if (state == ChatState.COMPOSING) {
4144 this.messageList.add(
4145 Message.createStatusMessage(
4146 conversation,
4147 getString(R.string.contact_is_typing, conversation.getName())));
4148 } else if (state == ChatState.PAUSED) {
4149 this.messageList.add(
4150 Message.createStatusMessage(
4151 conversation,
4152 getString(
4153 R.string.contact_has_stopped_typing,
4154 conversation.getName())));
4155 } else {
4156 for (int i = this.messageList.size() - 1; i >= 0; --i) {
4157 final Message message = this.messageList.get(i);
4158 if (message.getType() != Message.TYPE_STATUS) {
4159 if (message.getStatus() == Message.STATUS_RECEIVED) {
4160 return;
4161 } else {
4162 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
4163 this.messageList.add(
4164 i + 1,
4165 Message.createStatusMessage(
4166 conversation,
4167 getString(
4168 R.string.contact_has_read_up_to_this_point,
4169 conversation.getName())));
4170 return;
4171 }
4172 }
4173 }
4174 }
4175 }
4176 } else {
4177 final MucOptions mucOptions = conversation.getMucOptions();
4178 final List<MucOptions.User> allUsers = mucOptions.getUsers();
4179 final Set<ReadByMarker> addedMarkers = new HashSet<>();
4180 ChatState state = ChatState.COMPOSING;
4181 List<MucOptions.User> users =
4182 conversation.getMucOptions().getUsersWithChatState(state, 5);
4183 if (users.size() == 0) {
4184 state = ChatState.PAUSED;
4185 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
4186 }
4187 if (mucOptions.isPrivateAndNonAnonymous()) {
4188 for (int i = this.messageList.size() - 1; i >= 0; --i) {
4189 final Set<ReadByMarker> markersForMessage =
4190 messageList.get(i).getReadByMarkers();
4191 final List<MucOptions.User> shownMarkers = new ArrayList<>();
4192 for (ReadByMarker marker : markersForMessage) {
4193 if (!ReadByMarker.contains(marker, addedMarkers)) {
4194 addedMarkers.add(
4195 marker); // may be put outside this condition. set should do
4196 // dedup anyway
4197 MucOptions.User user = mucOptions.findUser(marker);
4198 if (user != null && !users.contains(user)) {
4199 shownMarkers.add(user);
4200 }
4201 }
4202 }
4203 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
4204 final Message statusMessage;
4205 final int size = shownMarkers.size();
4206 if (size > 1) {
4207 final String body;
4208 if (size <= 4) {
4209 body =
4210 getString(
4211 R.string.contacts_have_read_up_to_this_point,
4212 UIHelper.concatNames(shownMarkers));
4213 } else if (ReadByMarker.allUsersRepresented(
4214 allUsers, markersForMessage, markerForSender)) {
4215 body = getString(R.string.everyone_has_read_up_to_this_point);
4216 } else {
4217 body =
4218 getString(
4219 R.string.contacts_and_n_more_have_read_up_to_this_point,
4220 UIHelper.concatNames(shownMarkers, 3),
4221 size - 3);
4222 }
4223 statusMessage = Message.createStatusMessage(conversation, body);
4224 statusMessage.setCounterparts(shownMarkers);
4225 } else if (size == 1) {
4226 statusMessage =
4227 Message.createStatusMessage(
4228 conversation,
4229 getString(
4230 R.string.contact_has_read_up_to_this_point,
4231 UIHelper.getDisplayName(shownMarkers.get(0))));
4232 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
4233 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
4234 } else {
4235 statusMessage = null;
4236 }
4237 if (statusMessage != null) {
4238 this.messageList.add(i + 1, statusMessage);
4239 }
4240 addedMarkers.add(markerForSender);
4241 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
4242 break;
4243 }
4244 }
4245 }
4246 if (users.size() > 0) {
4247 Message statusMessage;
4248 if (users.size() == 1) {
4249 MucOptions.User user = users.get(0);
4250 int id =
4251 state == ChatState.COMPOSING
4252 ? R.string.contact_is_typing
4253 : R.string.contact_has_stopped_typing;
4254 statusMessage =
4255 Message.createStatusMessage(
4256 conversation, getString(id, UIHelper.getDisplayName(user)));
4257 statusMessage.setTrueCounterpart(user.getRealJid());
4258 statusMessage.setCounterpart(user.getFullJid());
4259 } else {
4260 int id =
4261 state == ChatState.COMPOSING
4262 ? R.string.contacts_are_typing
4263 : R.string.contacts_have_stopped_typing;
4264 statusMessage =
4265 Message.createStatusMessage(
4266 conversation, getString(id, UIHelper.concatNames(users)));
4267 statusMessage.setCounterparts(users);
4268 }
4269 this.messageList.add(statusMessage);
4270 }
4271 }
4272 }
4273
4274 private void stopScrolling() {
4275 long now = SystemClock.uptimeMillis();
4276 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
4277 binding.messagesView.dispatchTouchEvent(cancel);
4278 }
4279
4280 private boolean showLoadMoreMessages(final Conversation c) {
4281 if (activity == null || activity.xmppConnectionService == null) {
4282 return false;
4283 }
4284 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
4285 final MessageArchiveService service =
4286 activity.xmppConnectionService.getMessageArchiveService();
4287 return mam
4288 && (c.getLastClearHistory().getTimestamp() != 0
4289 || (c.countMessages() == 0
4290 && c.messagesLoaded.get()
4291 && c.hasMessagesLeftOnServer()
4292 && !service.queryInProgress(c)));
4293 }
4294
4295 private boolean hasMamSupport(final Conversation c) {
4296 if (c.getMode() == Conversation.MODE_SINGLE) {
4297 final XmppConnection connection = c.getAccount().getXmppConnection();
4298 return connection != null && connection.getFeatures().mam();
4299 } else {
4300 return c.getMucOptions().mamSupport();
4301 }
4302 }
4303
4304 protected void showSnackbar(
4305 final int message, final int action, final OnClickListener clickListener) {
4306 showSnackbar(message, action, clickListener, null);
4307 }
4308
4309 protected void showSnackbar(
4310 final int message,
4311 final int action,
4312 final OnClickListener clickListener,
4313 final View.OnLongClickListener longClickListener) {
4314 this.binding.snackbar.setVisibility(View.VISIBLE);
4315 this.binding.snackbar.setOnClickListener(null);
4316 this.binding.snackbarMessage.setText(message);
4317 this.binding.snackbarMessage.setOnClickListener(null);
4318 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
4319 if (action != 0) {
4320 this.binding.snackbarAction.setText(action);
4321 }
4322 this.binding.snackbarAction.setOnClickListener(clickListener);
4323 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
4324 }
4325
4326 protected void hideSnackbar() {
4327 this.binding.snackbar.setVisibility(View.GONE);
4328 }
4329
4330 protected void sendMessage(Message message) {
4331 new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
4332 messageSent();
4333 }
4334
4335 protected void sendPgpMessage(final Message message) {
4336 final XmppConnectionService xmppService = activity.xmppConnectionService;
4337 final Contact contact = message.getConversation().getContact();
4338 if (!activity.hasPgp()) {
4339 activity.showInstallPgpDialog();
4340 return;
4341 }
4342 if (conversation.getAccount().getPgpSignature() == null) {
4343 activity.announcePgp(
4344 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
4345 return;
4346 }
4347 if (!mSendingPgpMessage.compareAndSet(false, true)) {
4348 Log.d(Config.LOGTAG, "sending pgp message already in progress");
4349 }
4350 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4351 if (contact.getPgpKeyId() != 0) {
4352 xmppService
4353 .getPgpEngine()
4354 .hasKey(
4355 contact,
4356 new UiCallback<Contact>() {
4357
4358 @Override
4359 public void userInputRequired(
4360 PendingIntent pi, Contact contact) {
4361 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
4362 }
4363
4364 @Override
4365 public void success(Contact contact) {
4366 encryptTextMessage(message);
4367 }
4368
4369 @Override
4370 public void error(int error, Contact contact) {
4371 activity.runOnUiThread(
4372 () ->
4373 Toast.makeText(
4374 activity,
4375 R.string
4376 .unable_to_connect_to_keychain,
4377 Toast.LENGTH_SHORT)
4378 .show());
4379 mSendingPgpMessage.set(false);
4380 }
4381 });
4382
4383 } else {
4384 showNoPGPKeyDialog(
4385 false,
4386 (dialog, which) -> {
4387 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4388 xmppService.updateConversation(conversation);
4389 message.setEncryption(Message.ENCRYPTION_NONE);
4390 xmppService.sendMessage(message);
4391 messageSent();
4392 });
4393 }
4394 } else {
4395 if (conversation.getMucOptions().pgpKeysInUse()) {
4396 if (!conversation.getMucOptions().everybodyHasKeys()) {
4397 Toast warning =
4398 Toast.makeText(
4399 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
4400 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
4401 warning.show();
4402 }
4403 encryptTextMessage(message);
4404 } else {
4405 showNoPGPKeyDialog(
4406 true,
4407 (dialog, which) -> {
4408 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4409 message.setEncryption(Message.ENCRYPTION_NONE);
4410 xmppService.updateConversation(conversation);
4411 xmppService.sendMessage(message);
4412 messageSent();
4413 });
4414 }
4415 }
4416 }
4417
4418 public void encryptTextMessage(Message message) {
4419 activity.xmppConnectionService
4420 .getPgpEngine()
4421 .encrypt(
4422 message,
4423 new UiCallback<Message>() {
4424
4425 @Override
4426 public void userInputRequired(PendingIntent pi, Message message) {
4427 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
4428 }
4429
4430 @Override
4431 public void success(Message message) {
4432 // TODO the following two call can be made before the callback
4433 getActivity().runOnUiThread(() -> messageSent());
4434 }
4435
4436 @Override
4437 public void error(final int error, Message message) {
4438 getActivity()
4439 .runOnUiThread(
4440 () -> {
4441 doneSendingPgpMessage();
4442 Toast.makeText(
4443 getActivity(),
4444 error == 0
4445 ? R.string
4446 .unable_to_connect_to_keychain
4447 : error,
4448 Toast.LENGTH_SHORT)
4449 .show();
4450 });
4451 }
4452 });
4453 }
4454
4455 public void showNoPGPKeyDialog(
4456 final boolean plural, final DialogInterface.OnClickListener listener) {
4457 final MaterialAlertDialogBuilder builder =
4458 new MaterialAlertDialogBuilder(requireActivity());
4459 if (plural) {
4460 builder.setTitle(getString(R.string.no_pgp_keys));
4461 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
4462 } else {
4463 builder.setTitle(getString(R.string.no_pgp_key));
4464 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
4465 }
4466 builder.setNegativeButton(getString(R.string.cancel), null);
4467 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
4468 builder.create().show();
4469 }
4470
4471 public void appendText(String text, final boolean doNotAppend) {
4472 if (text == null) {
4473 return;
4474 }
4475 final Editable editable = this.binding.textinput.getText();
4476 String previous = editable == null ? "" : editable.toString();
4477 if (doNotAppend && !TextUtils.isEmpty(previous)) {
4478 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
4479 .show();
4480 return;
4481 }
4482 if (UIHelper.isLastLineQuote(previous)) {
4483 text = '\n' + text;
4484 } else if (previous.length() != 0
4485 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4486 text = " " + text;
4487 }
4488 this.binding.textinput.append(text);
4489 }
4490
4491 @Override
4492 public boolean onEnterPressed(final boolean isCtrlPressed) {
4493 if (isCtrlPressed || enterIsSend()) {
4494 sendMessage();
4495 return true;
4496 }
4497 return false;
4498 }
4499
4500 private boolean enterIsSend() {
4501 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4502 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4503 }
4504
4505 public boolean onArrowUpCtrlPressed() {
4506 final Message lastEditableMessage =
4507 conversation == null ? null : conversation.getLastEditableMessage();
4508 if (lastEditableMessage != null) {
4509 correctMessage(lastEditableMessage);
4510 return true;
4511 } else {
4512 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4513 .show();
4514 return false;
4515 }
4516 }
4517
4518 @Override
4519 public void onTypingStarted() {
4520 final XmppConnectionService service =
4521 activity == null ? null : activity.xmppConnectionService;
4522 if (service == null) {
4523 return;
4524 }
4525 final Account.State status = conversation.getAccount().getStatus();
4526 if (status == Account.State.ONLINE
4527 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4528 service.sendChatState(conversation);
4529 }
4530 runOnUiThread(this::updateSendButton);
4531 }
4532
4533 @Override
4534 public void onTypingStopped() {
4535 final XmppConnectionService service =
4536 activity == null ? null : activity.xmppConnectionService;
4537 if (service == null) {
4538 return;
4539 }
4540 final Account.State status = conversation.getAccount().getStatus();
4541 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4542 service.sendChatState(conversation);
4543 }
4544 }
4545
4546 @Override
4547 public void onTextDeleted() {
4548 final XmppConnectionService service =
4549 activity == null ? null : activity.xmppConnectionService;
4550 if (service == null) {
4551 return;
4552 }
4553 final Account.State status = conversation.getAccount().getStatus();
4554 if (status == Account.State.ONLINE
4555 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4556 service.sendChatState(conversation);
4557 }
4558 if (storeNextMessage()) {
4559 runOnUiThread(
4560 () -> {
4561 if (activity == null) {
4562 return;
4563 }
4564 activity.onConversationsListItemUpdated();
4565 });
4566 }
4567 runOnUiThread(this::updateSendButton);
4568 }
4569
4570 @Override
4571 public void onTextChanged() {
4572 if (conversation != null && conversation.getCorrectingMessage() != null) {
4573 runOnUiThread(this::updateSendButton);
4574 }
4575 }
4576
4577 @Override
4578 public boolean onTabPressed(boolean repeated) {
4579 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4580 return false;
4581 }
4582 if (repeated) {
4583 completionIndex++;
4584 } else {
4585 lastCompletionLength = 0;
4586 completionIndex = 0;
4587 final String content = this.binding.textinput.getText().toString();
4588 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4589 int start =
4590 lastCompletionCursor > 0
4591 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4592 : 0;
4593 firstWord = start == 0;
4594 incomplete = content.substring(start, lastCompletionCursor);
4595 }
4596 List<String> completions = new ArrayList<>();
4597 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4598 String name = user.getNick();
4599 if (name != null && name.startsWith(incomplete)) {
4600 completions.add(name + (firstWord ? ": " : " "));
4601 }
4602 }
4603 Collections.sort(completions);
4604 if (completions.size() > completionIndex) {
4605 String completion = completions.get(completionIndex).substring(incomplete.length());
4606 this.binding
4607 .textinput
4608 .getEditableText()
4609 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4610 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4611 lastCompletionLength = completion.length();
4612 } else {
4613 completionIndex = -1;
4614 this.binding
4615 .textinput
4616 .getEditableText()
4617 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4618 lastCompletionLength = 0;
4619 }
4620 return true;
4621 }
4622
4623 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4624 try {
4625 getActivity()
4626 .startIntentSenderForResult(
4627 pendingIntent.getIntentSender(),
4628 requestCode,
4629 null,
4630 0,
4631 0,
4632 0,
4633 Compatibility.pgpStartIntentSenderOptions());
4634 } catch (final SendIntentException ignored) {
4635 }
4636 }
4637
4638 @Override
4639 public void onBackendConnected() {
4640 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4641 setupEmojiSearch();
4642 String uuid = pendingConversationsUuid.pop();
4643 if (uuid != null) {
4644 if (!findAndReInitByUuidOrArchive(uuid)) {
4645 return;
4646 }
4647 } else {
4648 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4649 clearPending();
4650 activity.onConversationArchived(conversation);
4651 return;
4652 }
4653 }
4654 ActivityResult activityResult = postponedActivityResult.pop();
4655 if (activityResult != null) {
4656 handleActivityResult(activityResult);
4657 }
4658 clearPending();
4659 }
4660
4661 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4662 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4663 if (conversation == null) {
4664 clearPending();
4665 activity.onConversationArchived(null);
4666 return false;
4667 }
4668 reInit(conversation);
4669 ScrollState scrollState = pendingScrollState.pop();
4670 String lastMessageUuid = pendingLastMessageUuid.pop();
4671 List<Attachment> attachments = pendingMediaPreviews.pop();
4672 if (scrollState != null) {
4673 setScrollPosition(scrollState, lastMessageUuid);
4674 }
4675 if (attachments != null && attachments.size() > 0) {
4676 Log.d(Config.LOGTAG, "had attachments on restore");
4677 mediaPreviewAdapter.addMediaPreviews(attachments);
4678 toggleInputMethod();
4679 }
4680 return true;
4681 }
4682
4683 private void clearPending() {
4684 if (postponedActivityResult.clear()) {
4685 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4686 if (pendingTakePhotoUri.clear()) {
4687 Log.e(Config.LOGTAG, "cleared pending photo uri");
4688 }
4689 }
4690 if (pendingScrollState.clear()) {
4691 Log.e(Config.LOGTAG, "cleared scroll state");
4692 }
4693 if (pendingConversationsUuid.clear()) {
4694 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4695 }
4696 if (pendingMediaPreviews.clear()) {
4697 Log.e(Config.LOGTAG, "cleared pending media previews");
4698 }
4699 }
4700
4701 public Conversation getConversation() {
4702 return conversation;
4703 }
4704
4705 @Override
4706 public void onContactPictureLongClicked(View v, final Message message) {
4707 final String fingerprint;
4708 if (message.getEncryption() == Message.ENCRYPTION_PGP
4709 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4710 fingerprint = "pgp";
4711 } else {
4712 fingerprint = message.getFingerprint();
4713 }
4714 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4715 final Contact contact = message.getContact();
4716 if (message.getStatus() <= Message.STATUS_RECEIVED
4717 && (contact == null || !contact.isSelf())) {
4718 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4719 final Jid cp = message.getCounterpart();
4720 if (cp == null || cp.isBareJid()) {
4721 return;
4722 }
4723 final Jid tcp = message.getTrueCounterpart();
4724 final String occupantId = message.getOccupantId();
4725 final User userByRealJid =
4726 tcp != null
4727 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp, occupantId)
4728 : null;
4729 final User userByOccupantId =
4730 occupantId != null
4731 ? conversation.getMucOptions().findUserByOccupantId(occupantId, cp)
4732 : null;
4733 final User user =
4734 userByRealJid != null
4735 ? userByRealJid
4736 : (userByOccupantId != null ? userByOccupantId : conversation.getMucOptions().findUserByFullJid(cp));
4737 if (user == null) return;
4738 popupMenu.inflate(R.menu.muc_details_context);
4739 final Menu menu = popupMenu.getMenu();
4740 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4741 activity, menu, conversation, user);
4742 popupMenu.setOnMenuItemClickListener(
4743 menuItem ->
4744 MucDetailsContextMenuHelper.onContextItemSelected(
4745 menuItem, user, activity, fingerprint));
4746 } else {
4747 popupMenu.inflate(R.menu.one_on_one_context);
4748 popupMenu.setOnMenuItemClickListener(
4749 item -> {
4750 switch (item.getItemId()) {
4751 case R.id.action_contact_details:
4752 activity.switchToContactDetails(
4753 message.getContact(), fingerprint);
4754 break;
4755 case R.id.action_show_qr_code:
4756 activity.showQrCode(
4757 "xmpp:"
4758 + message.getContact()
4759 .getJid()
4760 .asBareJid()
4761 .toString());
4762 break;
4763 }
4764 return true;
4765 });
4766 }
4767 } else {
4768 popupMenu.inflate(R.menu.account_context);
4769 final Menu menu = popupMenu.getMenu();
4770 menu.findItem(R.id.action_manage_accounts)
4771 .setVisible(QuickConversationsService.isConversations());
4772 popupMenu.setOnMenuItemClickListener(
4773 item -> {
4774 final XmppActivity activity = this.activity;
4775 if (activity == null) {
4776 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4777 return true;
4778 }
4779 switch (item.getItemId()) {
4780 case R.id.action_show_qr_code:
4781 activity.showQrCode(conversation.getAccount().getShareableUri());
4782 break;
4783 case R.id.action_account_details:
4784 activity.switchToAccount(
4785 message.getConversation().getAccount(), fingerprint);
4786 break;
4787 case R.id.action_manage_accounts:
4788 AccountUtils.launchManageAccounts(activity);
4789 break;
4790 }
4791 return true;
4792 });
4793 }
4794 popupMenu.show();
4795 }
4796
4797 @Override
4798 public void onContactPictureClicked(Message message) {
4799 setThread(message.getThread());
4800 if (message.isPrivateMessage()) {
4801 privateMessageWith(message.getCounterpart());
4802 return;
4803 }
4804 forkNullThread(message);
4805 conversation.setUserSelectedThread(true);
4806
4807 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4808 if (received) {
4809 if (message.getConversation() instanceof Conversation
4810 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4811 Jid tcp = message.getTrueCounterpart();
4812 Jid user = message.getCounterpart();
4813 if (user != null && !user.isBareJid()) {
4814 final MucOptions mucOptions =
4815 ((Conversation) message.getConversation()).getMucOptions();
4816 if (mucOptions.participating()
4817 || ((Conversation) message.getConversation()).getNextCounterpart()
4818 != null) {
4819 MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4820 MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4821 if (mucUser == null && tcpMucUser == null) {
4822 Toast.makeText(
4823 getActivity(),
4824 activity.getString(
4825 R.string.user_has_left_conference,
4826 user.getResource()),
4827 Toast.LENGTH_SHORT)
4828 .show();
4829 }
4830 highlightInConference(mucUser == null || mucUser.getNick() == null ? (tcpMucUser == null || tcpMucUser.getNick() == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4831 } else {
4832 Toast.makeText(
4833 getActivity(),
4834 R.string.you_are_not_participating,
4835 Toast.LENGTH_SHORT)
4836 .show();
4837 }
4838 }
4839 }
4840 }
4841 }
4842
4843 private Activity requireActivity() {
4844 Activity activity = getActivity();
4845 if (activity == null) activity = this.activity;
4846 if (activity == null) {
4847 throw new IllegalStateException("Activity not attached");
4848 }
4849 return activity;
4850 }
4851}