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.Fragment;
16import android.app.FragmentManager;
17import android.app.PendingIntent;
18import android.content.ActivityNotFoundException;
19import android.content.Context;
20import android.content.DialogInterface;
21import android.content.Intent;
22import android.content.IntentSender.SendIntentException;
23import android.content.SharedPreferences;
24import android.content.pm.PackageManager;
25import android.content.res.ColorStateList;
26import android.net.Uri;
27import android.os.Build;
28import android.os.Bundle;
29import android.os.Handler;
30import android.os.SystemClock;
31import android.preference.PreferenceManager;
32import android.provider.MediaStore;
33import android.text.Editable;
34import android.text.SpannableStringBuilder;
35import android.text.TextUtils;
36import android.util.Log;
37import android.view.ContextMenu;
38import android.view.ContextMenu.ContextMenuInfo;
39import android.view.Gravity;
40import android.view.LayoutInflater;
41import android.view.Menu;
42import android.view.MenuInflater;
43import android.view.MenuItem;
44import android.view.MotionEvent;
45import android.view.View;
46import android.view.View.OnClickListener;
47import android.view.ViewGroup;
48import android.view.inputmethod.EditorInfo;
49import android.view.inputmethod.InputMethodManager;
50import android.widget.AbsListView;
51import android.widget.AbsListView.OnScrollListener;
52import android.widget.AdapterView;
53import android.widget.AdapterView.AdapterContextMenuInfo;
54import android.widget.CheckBox;
55import android.widget.ListView;
56import android.widget.PopupMenu;
57import android.widget.TextView.OnEditorActionListener;
58import android.widget.Toast;
59import androidx.annotation.IdRes;
60import androidx.annotation.NonNull;
61import androidx.annotation.StringRes;
62import androidx.core.view.inputmethod.InputConnectionCompat;
63import androidx.core.view.inputmethod.InputContentInfoCompat;
64import androidx.databinding.DataBindingUtil;
65import com.google.android.material.dialog.MaterialAlertDialogBuilder;
66import com.google.common.base.Optional;
67import com.google.common.collect.ImmutableList;
68import eu.siacs.conversations.Config;
69import eu.siacs.conversations.R;
70import eu.siacs.conversations.crypto.axolotl.AxolotlService;
71import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
72import eu.siacs.conversations.databinding.FragmentConversationBinding;
73import eu.siacs.conversations.entities.Account;
74import eu.siacs.conversations.entities.Blockable;
75import eu.siacs.conversations.entities.Contact;
76import eu.siacs.conversations.entities.Conversation;
77import eu.siacs.conversations.entities.Conversational;
78import eu.siacs.conversations.entities.DownloadableFile;
79import eu.siacs.conversations.entities.Message;
80import eu.siacs.conversations.entities.MucOptions;
81import eu.siacs.conversations.entities.MucOptions.User;
82import eu.siacs.conversations.entities.Presence;
83import eu.siacs.conversations.entities.ReadByMarker;
84import eu.siacs.conversations.entities.Transferable;
85import eu.siacs.conversations.entities.TransferablePlaceholder;
86import eu.siacs.conversations.http.HttpDownloadConnection;
87import eu.siacs.conversations.persistance.FileBackend;
88import eu.siacs.conversations.services.CallIntegrationConnectionService;
89import eu.siacs.conversations.services.MessageArchiveService;
90import eu.siacs.conversations.services.QuickConversationsService;
91import eu.siacs.conversations.services.XmppConnectionService;
92import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
93import eu.siacs.conversations.ui.adapter.MessageAdapter;
94import eu.siacs.conversations.ui.util.ActivityResult;
95import eu.siacs.conversations.ui.util.Attachment;
96import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
97import eu.siacs.conversations.ui.util.DateSeparator;
98import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
99import eu.siacs.conversations.ui.util.ListViewUtils;
100import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
101import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
102import eu.siacs.conversations.ui.util.PendingItem;
103import eu.siacs.conversations.ui.util.PresenceSelector;
104import eu.siacs.conversations.ui.util.ScrollState;
105import eu.siacs.conversations.ui.util.SendButtonAction;
106import eu.siacs.conversations.ui.util.SendButtonTool;
107import eu.siacs.conversations.ui.util.ShareUtil;
108import eu.siacs.conversations.ui.util.ViewUtil;
109import eu.siacs.conversations.ui.widget.EditMessage;
110import eu.siacs.conversations.utils.AccountUtils;
111import eu.siacs.conversations.utils.Compatibility;
112import eu.siacs.conversations.utils.GeoHelper;
113import eu.siacs.conversations.utils.MessageUtils;
114import eu.siacs.conversations.utils.NickValidityChecker;
115import eu.siacs.conversations.utils.Patterns;
116import eu.siacs.conversations.utils.PermissionUtils;
117import eu.siacs.conversations.utils.QuickLoader;
118import eu.siacs.conversations.utils.StylingHelper;
119import eu.siacs.conversations.utils.TimeFrameUtils;
120import eu.siacs.conversations.utils.UIHelper;
121import eu.siacs.conversations.xmpp.Jid;
122import eu.siacs.conversations.xmpp.XmppConnection;
123import eu.siacs.conversations.xmpp.chatstate.ChatState;
124import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
125import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
126import eu.siacs.conversations.xmpp.jingle.JingleFileTransferConnection;
127import eu.siacs.conversations.xmpp.jingle.Media;
128import eu.siacs.conversations.xmpp.jingle.OngoingRtpSession;
129import eu.siacs.conversations.xmpp.jingle.RtpCapability;
130import java.util.ArrayList;
131import java.util.Arrays;
132import java.util.Collection;
133import java.util.Collections;
134import java.util.HashSet;
135import java.util.Iterator;
136import java.util.List;
137import java.util.Set;
138import java.util.UUID;
139import java.util.concurrent.atomic.AtomicBoolean;
140
141public class ConversationFragment extends XmppFragment
142 implements EditMessage.KeyboardListener,
143 MessageAdapter.OnContactPictureLongClicked,
144 MessageAdapter.OnContactPictureClicked {
145
146 public static final int REQUEST_SEND_MESSAGE = 0x0201;
147 public static final int REQUEST_DECRYPT_PGP = 0x0202;
148 public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
149 public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
150 public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209;
151 public static final int REQUEST_START_DOWNLOAD = 0x0210;
152 public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
153 public static final int REQUEST_COMMIT_ATTACHMENTS = 0x0212;
154 public static final int REQUEST_START_AUDIO_CALL = 0x213;
155 public static final int REQUEST_START_VIDEO_CALL = 0x214;
156 public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
157 public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
158 public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
159 public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
160 public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
161 public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
162 public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
163
164 public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
165 public static final String STATE_CONVERSATION_UUID =
166 ConversationFragment.class.getName() + ".uuid";
167 public static final String STATE_SCROLL_POSITION =
168 ConversationFragment.class.getName() + ".scroll_position";
169 public static final String STATE_PHOTO_URI =
170 ConversationFragment.class.getName() + ".media_previews";
171 public static final String STATE_MEDIA_PREVIEWS =
172 ConversationFragment.class.getName() + ".take_photo_uri";
173 private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid";
174
175 private final List<Message> messageList = new ArrayList<>();
176 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
177 private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
178 private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>();
179 private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
180 private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
181 private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
182 private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>();
183 private final PendingItem<Message> pendingMessage = new PendingItem<>();
184 public Uri mPendingEditorContent = null;
185 protected MessageAdapter messageListAdapter;
186 private MediaPreviewAdapter mediaPreviewAdapter;
187 private String lastMessageUuid = null;
188 private Conversation conversation;
189 private FragmentConversationBinding binding;
190 private Toast messageLoaderToast;
191 private ConversationsActivity activity;
192 private boolean reInitRequiredOnStart = true;
193 private final OnClickListener clickToMuc =
194 new OnClickListener() {
195
196 @Override
197 public void onClick(View v) {
198 ConferenceDetailsActivity.open(getActivity(), conversation);
199 }
200 };
201 private final OnClickListener leaveMuc =
202 new OnClickListener() {
203
204 @Override
205 public void onClick(View v) {
206 activity.xmppConnectionService.archiveConversation(conversation);
207 }
208 };
209 private final OnClickListener joinMuc =
210 new OnClickListener() {
211
212 @Override
213 public void onClick(View v) {
214 activity.xmppConnectionService.joinMuc(conversation);
215 }
216 };
217
218 private final OnClickListener acceptJoin =
219 new OnClickListener() {
220 @Override
221 public void onClick(View v) {
222 conversation.setAttribute("accept_non_anonymous", true);
223 activity.xmppConnectionService.updateConversation(conversation);
224 activity.xmppConnectionService.joinMuc(conversation);
225 }
226 };
227
228 private final OnClickListener enterPassword =
229 new OnClickListener() {
230
231 @Override
232 public void onClick(View v) {
233 MucOptions muc = conversation.getMucOptions();
234 String password = muc.getPassword();
235 if (password == null) {
236 password = "";
237 }
238 activity.quickPasswordEdit(
239 password,
240 value -> {
241 activity.xmppConnectionService.providePasswordForMuc(
242 conversation, value);
243 return null;
244 });
245 }
246 };
247 private final OnScrollListener mOnScrollListener =
248 new OnScrollListener() {
249
250 @Override
251 public void onScrollStateChanged(AbsListView view, int scrollState) {
252 if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
253 fireReadEvent();
254 }
255 }
256
257 @Override
258 public void onScroll(
259 final AbsListView view,
260 int firstVisibleItem,
261 int visibleItemCount,
262 int totalItemCount) {
263 toggleScrollDownButton(view);
264 synchronized (ConversationFragment.this.messageList) {
265 if (firstVisibleItem < 5
266 && conversation != null
267 && conversation.messagesLoaded.compareAndSet(true, false)
268 && messageList.size() > 0) {
269 long timestamp;
270 if (messageList.get(0).getType() == Message.TYPE_STATUS
271 && messageList.size() >= 2) {
272 timestamp = messageList.get(1).getTimeSent();
273 } else {
274 timestamp = messageList.get(0).getTimeSent();
275 }
276 activity.xmppConnectionService.loadMoreMessages(
277 conversation,
278 timestamp,
279 new XmppConnectionService.OnMoreMessagesLoaded() {
280 @Override
281 public void onMoreMessagesLoaded(
282 final int c, final Conversation conversation) {
283 if (ConversationFragment.this.conversation
284 != conversation) {
285 conversation.messagesLoaded.set(true);
286 return;
287 }
288 runOnUiThread(
289 () -> {
290 synchronized (messageList) {
291 final int oldPosition =
292 binding.messagesView
293 .getFirstVisiblePosition();
294 Message message = null;
295 int childPos;
296 for (childPos = 0;
297 childPos + oldPosition
298 < messageList.size();
299 ++childPos) {
300 message =
301 messageList.get(
302 oldPosition
303 + childPos);
304 if (message.getType()
305 != Message.TYPE_STATUS) {
306 break;
307 }
308 }
309 final String uuid =
310 message != null
311 ? message.getUuid()
312 : null;
313 View v =
314 binding.messagesView.getChildAt(
315 childPos);
316 final int pxOffset =
317 (v == null) ? 0 : v.getTop();
318 ConversationFragment.this.conversation
319 .populateWithMessages(
320 ConversationFragment
321 .this
322 .messageList);
323 try {
324 updateStatusMessages();
325 } catch (IllegalStateException e) {
326 Log.d(
327 Config.LOGTAG,
328 "caught illegal state"
329 + " exception while"
330 + " updating status"
331 + " messages");
332 }
333 messageListAdapter
334 .notifyDataSetChanged();
335 int pos =
336 Math.max(
337 getIndexOf(
338 uuid,
339 messageList),
340 0);
341 binding.messagesView
342 .setSelectionFromTop(
343 pos, pxOffset);
344 if (messageLoaderToast != null) {
345 messageLoaderToast.cancel();
346 }
347 conversation.messagesLoaded.set(true);
348 }
349 });
350 }
351
352 @Override
353 public void informUser(final int resId) {
354
355 runOnUiThread(
356 () -> {
357 if (messageLoaderToast != null) {
358 messageLoaderToast.cancel();
359 }
360 if (ConversationFragment.this.conversation
361 != conversation) {
362 return;
363 }
364 messageLoaderToast =
365 Toast.makeText(
366 view.getContext(),
367 resId,
368 Toast.LENGTH_LONG);
369 messageLoaderToast.show();
370 });
371 }
372 });
373 }
374 }
375 }
376 };
377 private final EditMessage.OnCommitContentListener mEditorContentListener =
378 new EditMessage.OnCommitContentListener() {
379 @Override
380 public boolean onCommitContent(
381 InputContentInfoCompat inputContentInfo,
382 int flags,
383 Bundle opts,
384 String[] contentMimeTypes) {
385 // try to get permission to read the image, if applicable
386 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION)
387 != 0) {
388 try {
389 inputContentInfo.requestPermission();
390 } catch (Exception e) {
391 Log.e(
392 Config.LOGTAG,
393 "InputContentInfoCompat#requestPermission() failed.",
394 e);
395 Toast.makeText(
396 getActivity(),
397 activity.getString(
398 R.string.no_permission_to_access_x,
399 inputContentInfo.getDescription()),
400 Toast.LENGTH_LONG)
401 .show();
402 return false;
403 }
404 }
405 if (hasPermissions(
406 REQUEST_ADD_EDITOR_CONTENT,
407 Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
408 attachEditorContentToConversation(inputContentInfo.getContentUri());
409 } else {
410 mPendingEditorContent = inputContentInfo.getContentUri();
411 }
412 return true;
413 }
414 };
415 private Message selectedMessage;
416 private final OnClickListener mEnableAccountListener =
417 new OnClickListener() {
418 @Override
419 public void onClick(View v) {
420 final Account account = conversation == null ? null : conversation.getAccount();
421 if (account != null) {
422 account.setOption(Account.OPTION_SOFT_DISABLED, false);
423 account.setOption(Account.OPTION_DISABLED, false);
424 activity.xmppConnectionService.updateAccount(account);
425 }
426 }
427 };
428 private final OnClickListener mUnblockClickListener =
429 new OnClickListener() {
430 @Override
431 public void onClick(final View v) {
432 v.post(() -> v.setVisibility(View.INVISIBLE));
433 if (conversation.isDomainBlocked()) {
434 BlockContactDialog.show(activity, conversation);
435 } else {
436 unblockConversation(conversation);
437 }
438 }
439 };
440 private final OnClickListener mBlockClickListener = this::showBlockSubmenu;
441 private final OnClickListener mAddBackClickListener =
442 new OnClickListener() {
443
444 @Override
445 public void onClick(View v) {
446 final Contact contact = conversation == null ? null : conversation.getContact();
447 if (contact != null) {
448 activity.xmppConnectionService.createContact(contact, true);
449 activity.switchToContactDetails(contact);
450 }
451 }
452 };
453 private final View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
454 private final OnClickListener mAllowPresenceSubscription =
455 new OnClickListener() {
456 @Override
457 public void onClick(View v) {
458 final Contact contact = conversation == null ? null : conversation.getContact();
459 if (contact != null) {
460 activity.xmppConnectionService.sendPresencePacket(
461 contact.getAccount(),
462 activity.xmppConnectionService
463 .getPresenceGenerator()
464 .sendPresenceUpdatesTo(contact));
465 hideSnackbar();
466 }
467 }
468 };
469 protected OnClickListener clickToDecryptListener =
470 new OnClickListener() {
471
472 @Override
473 public void onClick(View v) {
474 PendingIntent pendingIntent =
475 conversation.getAccount().getPgpDecryptionService().getPendingIntent();
476 if (pendingIntent != null) {
477 try {
478 getActivity()
479 .startIntentSenderForResult(
480 pendingIntent.getIntentSender(),
481 REQUEST_DECRYPT_PGP,
482 null,
483 0,
484 0,
485 0,
486 Compatibility.pgpStartIntentSenderOptions());
487 } catch (SendIntentException e) {
488 Toast.makeText(
489 getActivity(),
490 R.string.unable_to_connect_to_keychain,
491 Toast.LENGTH_SHORT)
492 .show();
493 conversation
494 .getAccount()
495 .getPgpDecryptionService()
496 .continueDecryption(true);
497 }
498 }
499 updateSnackBar(conversation);
500 }
501 };
502 private final AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
503 private final OnEditorActionListener mEditorActionListener =
504 (v, actionId, event) -> {
505 if (actionId == EditorInfo.IME_ACTION_SEND) {
506 InputMethodManager imm =
507 (InputMethodManager)
508 activity.getSystemService(Context.INPUT_METHOD_SERVICE);
509 if (imm != null && imm.isFullscreenMode()) {
510 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
511 }
512 sendMessage();
513 return true;
514 } else {
515 return false;
516 }
517 };
518 private final OnClickListener mScrollButtonListener =
519 new OnClickListener() {
520
521 @Override
522 public void onClick(View v) {
523 stopScrolling();
524 setSelection(binding.messagesView.getCount() - 1, true);
525 }
526 };
527 private final OnClickListener mSendButtonListener =
528 new OnClickListener() {
529
530 @Override
531 public void onClick(View v) {
532 Object tag = v.getTag();
533 if (tag instanceof SendButtonAction) {
534 SendButtonAction action = (SendButtonAction) tag;
535 switch (action) {
536 case TAKE_PHOTO:
537 case RECORD_VIDEO:
538 case SEND_LOCATION:
539 case RECORD_VOICE:
540 case CHOOSE_PICTURE:
541 attachFile(action.toChoice());
542 break;
543 case CANCEL:
544 if (conversation != null) {
545 if (conversation.setCorrectingMessage(null)) {
546 binding.textinput.setText("");
547 binding.textinput.append(conversation.getDraftMessage());
548 conversation.setDraftMessage(null);
549 } else if (conversation.getMode() == Conversation.MODE_MULTI) {
550 conversation.setNextCounterpart(null);
551 binding.textinput.setText("");
552 } else {
553 binding.textinput.setText("");
554 }
555 updateChatMsgHint();
556 updateSendButton();
557 updateEditablity();
558 }
559 break;
560 default:
561 sendMessage();
562 }
563 } else {
564 sendMessage();
565 }
566 }
567 };
568 private int completionIndex = 0;
569 private int lastCompletionLength = 0;
570 private String incomplete;
571 private int lastCompletionCursor;
572 private boolean firstWord = false;
573 private Message mPendingDownloadableMessage;
574
575 private static ConversationFragment findConversationFragment(Activity activity) {
576 Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
577 if (fragment instanceof ConversationFragment) {
578 return (ConversationFragment) fragment;
579 }
580 fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
581 if (fragment instanceof ConversationFragment) {
582 return (ConversationFragment) fragment;
583 }
584 return null;
585 }
586
587 public static void startStopPending(Activity activity) {
588 ConversationFragment fragment = findConversationFragment(activity);
589 if (fragment != null) {
590 fragment.messageListAdapter.startStopPending();
591 }
592 }
593
594 public static void downloadFile(Activity activity, Message message) {
595 ConversationFragment fragment = findConversationFragment(activity);
596 if (fragment != null) {
597 fragment.startDownloadable(message);
598 }
599 }
600
601 public static void registerPendingMessage(Activity activity, Message message) {
602 ConversationFragment fragment = findConversationFragment(activity);
603 if (fragment != null) {
604 fragment.pendingMessage.push(message);
605 }
606 }
607
608 public static void openPendingMessage(Activity activity) {
609 ConversationFragment fragment = findConversationFragment(activity);
610 if (fragment != null) {
611 Message message = fragment.pendingMessage.pop();
612 if (message != null) {
613 fragment.messageListAdapter.openDownloadable(message);
614 }
615 }
616 }
617
618 public static Conversation getConversation(Activity activity) {
619 return getConversation(activity, R.id.secondary_fragment);
620 }
621
622 private static Conversation getConversation(Activity activity, @IdRes int res) {
623 final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
624 if (fragment instanceof ConversationFragment) {
625 return ((ConversationFragment) fragment).getConversation();
626 } else {
627 return null;
628 }
629 }
630
631 public static ConversationFragment get(Activity activity) {
632 FragmentManager fragmentManager = activity.getFragmentManager();
633 Fragment fragment = fragmentManager.findFragmentById(R.id.main_fragment);
634 if (fragment instanceof ConversationFragment) {
635 return (ConversationFragment) fragment;
636 } else {
637 fragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
638 return fragment instanceof ConversationFragment
639 ? (ConversationFragment) fragment
640 : null;
641 }
642 }
643
644 public static Conversation getConversationReliable(Activity activity) {
645 final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
646 if (conversation != null) {
647 return conversation;
648 }
649 return getConversation(activity, R.id.main_fragment);
650 }
651
652 private static boolean scrolledToBottom(AbsListView listView) {
653 final int count = listView.getCount();
654 if (count == 0) {
655 return true;
656 } else if (listView.getLastVisiblePosition() == count - 1) {
657 final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
658 return lastChild != null && lastChild.getBottom() <= listView.getHeight();
659 } else {
660 return false;
661 }
662 }
663
664 private void toggleScrollDownButton() {
665 toggleScrollDownButton(binding.messagesView);
666 }
667
668 private void toggleScrollDownButton(AbsListView listView) {
669 if (conversation == null) {
670 return;
671 }
672 if (scrolledToBottom(listView)) {
673 lastMessageUuid = null;
674 hideUnreadMessagesCount();
675 } else {
676 binding.scrollToBottomButton.setEnabled(true);
677 binding.scrollToBottomButton.show();
678 if (lastMessageUuid == null) {
679 lastMessageUuid = conversation.getLatestMessage().getUuid();
680 }
681 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) > 0) {
682 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
683 }
684 }
685 }
686
687 private int getIndexOf(String uuid, List<Message> messages) {
688 if (uuid == null) {
689 return messages.size() - 1;
690 }
691 for (int i = 0; i < messages.size(); ++i) {
692 if (uuid.equals(messages.get(i).getUuid())) {
693 return i;
694 }
695 }
696 return -1;
697 }
698
699 private ScrollState getScrollPosition() {
700 final ListView listView = this.binding == null ? null : this.binding.messagesView;
701 if (listView == null
702 || listView.getCount() == 0
703 || listView.getLastVisiblePosition() == listView.getCount() - 1) {
704 return null;
705 } else {
706 final int pos = listView.getFirstVisiblePosition();
707 final View view = listView.getChildAt(0);
708 if (view == null) {
709 return null;
710 } else {
711 return new ScrollState(pos, view.getTop());
712 }
713 }
714 }
715
716 private void setScrollPosition(ScrollState scrollPosition, String lastMessageUuid) {
717 if (scrollPosition != null) {
718
719 this.lastMessageUuid = lastMessageUuid;
720 if (lastMessageUuid != null) {
721 binding.unreadCountCustomView.setUnreadCount(
722 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
723 }
724 // TODO maybe this needs a 'post'
725 this.binding.messagesView.setSelectionFromTop(
726 scrollPosition.position, scrollPosition.offset);
727 toggleScrollDownButton();
728 }
729 }
730
731 private void attachLocationToConversation(Conversation conversation, Uri uri) {
732 if (conversation == null) {
733 return;
734 }
735 activity.xmppConnectionService.attachLocationToConversation(
736 conversation,
737 uri,
738 new UiCallback<Message>() {
739
740 @Override
741 public void success(Message message) {}
742
743 @Override
744 public void error(int errorCode, Message object) {
745 // TODO show possible pgp error
746 }
747
748 @Override
749 public void userInputRequired(PendingIntent pi, Message object) {}
750 });
751 }
752
753 private void attachFileToConversation(Conversation conversation, Uri uri, String type) {
754 if (conversation == null) {
755 return;
756 }
757 final Toast prepareFileToast =
758 Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
759 prepareFileToast.show();
760 activity.delegateUriPermissionsToService(uri);
761 activity.xmppConnectionService.attachFileToConversation(
762 conversation,
763 uri,
764 type,
765 new UiInformableCallback<Message>() {
766 @Override
767 public void inform(final String text) {
768 hidePrepareFileToast(prepareFileToast);
769 runOnUiThread(() -> activity.replaceToast(text));
770 }
771
772 @Override
773 public void success(Message message) {
774 runOnUiThread(() -> activity.hideToast());
775 hidePrepareFileToast(prepareFileToast);
776 }
777
778 @Override
779 public void error(final int errorCode, Message message) {
780 hidePrepareFileToast(prepareFileToast);
781 runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
782 }
783
784 @Override
785 public void userInputRequired(PendingIntent pi, Message message) {
786 hidePrepareFileToast(prepareFileToast);
787 }
788 });
789 }
790
791 public void attachEditorContentToConversation(Uri uri) {
792 mediaPreviewAdapter.addMediaPreviews(
793 Attachment.of(getActivity(), uri, Attachment.Type.FILE));
794 toggleInputMethod();
795 }
796
797 private void attachImageToConversation(Conversation conversation, Uri uri, String type) {
798 if (conversation == null) {
799 return;
800 }
801 final Toast prepareFileToast =
802 Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
803 prepareFileToast.show();
804 activity.delegateUriPermissionsToService(uri);
805 activity.xmppConnectionService.attachImageToConversation(
806 conversation,
807 uri,
808 type,
809 new UiCallback<Message>() {
810
811 @Override
812 public void userInputRequired(PendingIntent pi, Message object) {
813 hidePrepareFileToast(prepareFileToast);
814 }
815
816 @Override
817 public void success(Message message) {
818 hidePrepareFileToast(prepareFileToast);
819 }
820
821 @Override
822 public void error(final int error, final Message message) {
823 hidePrepareFileToast(prepareFileToast);
824 final ConversationsActivity activity = ConversationFragment.this.activity;
825 if (activity == null) {
826 return;
827 }
828 activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
829 }
830 });
831 }
832
833 private void hidePrepareFileToast(final Toast prepareFileToast) {
834 if (prepareFileToast != null && activity != null) {
835 activity.runOnUiThread(prepareFileToast::cancel);
836 }
837 }
838
839 private void sendMessage() {
840 if (mediaPreviewAdapter.hasAttachments()) {
841 commitAttachments();
842 return;
843 }
844 final Editable text = this.binding.textinput.getText();
845 final String body = text == null ? "" : text.toString();
846 final Conversation conversation = this.conversation;
847 if (body.isEmpty() || conversation == null) {
848 return;
849 }
850 if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_TEXT)) {
851 return;
852 }
853 final Message message;
854 if (conversation.getCorrectingMessage() == null) {
855 message = new Message(conversation, body, conversation.getNextEncryption());
856 Message.configurePrivateMessage(message);
857 } else {
858 message = conversation.getCorrectingMessage();
859 message.setBody(body);
860 message.putEdited(message.getUuid(), message.getServerMsgId());
861 message.setUuid(UUID.randomUUID().toString());
862 }
863 switch (conversation.getNextEncryption()) {
864 case Message.ENCRYPTION_PGP:
865 sendPgpMessage(message);
866 break;
867 default:
868 sendMessage(message);
869 }
870 }
871
872 private boolean trustKeysIfNeeded(final Conversation conversation, final int requestCode) {
873 return conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL
874 && trustKeysIfNeeded(requestCode);
875 }
876
877 protected boolean trustKeysIfNeeded(int requestCode) {
878 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
879 final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
880 boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
881 boolean hasUndecidedOwn =
882 !axolotlService
883 .getKeysWithTrust(FingerprintStatus.createActiveUndecided())
884 .isEmpty();
885 boolean hasUndecidedContacts =
886 !axolotlService
887 .getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets)
888 .isEmpty();
889 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
890 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
891 boolean downloadInProgress = axolotlService.hasPendingKeyFetches(targets);
892 if (hasUndecidedOwn
893 || hasUndecidedContacts
894 || hasPendingKeys
895 || hasNoTrustedKeys
896 || hasUnaccepted
897 || downloadInProgress) {
898 axolotlService.createSessionsIfNeeded(conversation);
899 Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
900 String[] contacts = new String[targets.size()];
901 for (int i = 0; i < contacts.length; ++i) {
902 contacts[i] = targets.get(i).toString();
903 }
904 intent.putExtra("contacts", contacts);
905 intent.putExtra(
906 EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString());
907 intent.putExtra("conversation", conversation.getUuid());
908 startActivityForResult(intent, requestCode);
909 return true;
910 } else {
911 return false;
912 }
913 }
914
915 public void updateChatMsgHint() {
916 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
917 if (conversation.getCorrectingMessage() != null) {
918 this.binding.textInputHint.setVisibility(View.GONE);
919 this.binding.textinput.setHint(R.string.send_corrected_message);
920 } else if (multi && conversation.getNextCounterpart() != null) {
921 this.binding.textinput.setHint(R.string.send_unencrypted_message);
922 this.binding.textInputHint.setVisibility(View.VISIBLE);
923 this.binding.textInputHint.setText(
924 getString(
925 R.string.send_private_message_to,
926 conversation.getNextCounterpart().getResource()));
927 } else if (multi && !conversation.getMucOptions().participating()) {
928 this.binding.textInputHint.setVisibility(View.GONE);
929 this.binding.textinput.setHint(R.string.you_are_not_participating);
930 } else {
931 this.binding.textInputHint.setVisibility(View.GONE);
932 this.binding.textinput.setHint(UIHelper.getMessageHint(getActivity(), conversation));
933 getActivity().invalidateOptionsMenu();
934 }
935 }
936
937 public void setupIme() {
938 this.binding.textinput.refreshIme();
939 }
940
941 private void handleActivityResult(ActivityResult activityResult) {
942 if (activityResult.resultCode == Activity.RESULT_OK) {
943 handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
944 } else {
945 handleNegativeActivityResult(activityResult.requestCode);
946 }
947 }
948
949 private void handlePositiveActivityResult(int requestCode, final Intent data) {
950 switch (requestCode) {
951 case REQUEST_TRUST_KEYS_TEXT:
952 sendMessage();
953 break;
954 case REQUEST_TRUST_KEYS_ATTACHMENTS:
955 commitAttachments();
956 break;
957 case REQUEST_START_AUDIO_CALL:
958 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
959 break;
960 case REQUEST_START_VIDEO_CALL:
961 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
962 break;
963 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
964 final List<Attachment> imageUris =
965 Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE);
966 mediaPreviewAdapter.addMediaPreviews(imageUris);
967 toggleInputMethod();
968 break;
969 case ATTACHMENT_CHOICE_TAKE_PHOTO:
970 final Uri takePhotoUri = pendingTakePhotoUri.pop();
971 if (takePhotoUri != null) {
972 mediaPreviewAdapter.addMediaPreviews(
973 Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
974 toggleInputMethod();
975 } else {
976 Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
977 }
978 break;
979 case ATTACHMENT_CHOICE_CHOOSE_FILE:
980 case ATTACHMENT_CHOICE_RECORD_VIDEO:
981 case ATTACHMENT_CHOICE_RECORD_VOICE:
982 final Attachment.Type type =
983 requestCode == ATTACHMENT_CHOICE_RECORD_VOICE
984 ? Attachment.Type.RECORDING
985 : Attachment.Type.FILE;
986 final List<Attachment> fileUris =
987 Attachment.extractAttachments(getActivity(), data, type);
988 mediaPreviewAdapter.addMediaPreviews(fileUris);
989 toggleInputMethod();
990 break;
991 case ATTACHMENT_CHOICE_LOCATION:
992 final double latitude = data.getDoubleExtra("latitude", 0);
993 final double longitude = data.getDoubleExtra("longitude", 0);
994 final int accuracy = data.getIntExtra("accuracy", 0);
995 final Uri geo;
996 if (accuracy > 0) {
997 geo = Uri.parse(String.format("geo:%s,%s;u=%s", latitude, longitude, accuracy));
998 } else {
999 geo = Uri.parse(String.format("geo:%s,%s", latitude, longitude));
1000 }
1001 mediaPreviewAdapter.addMediaPreviews(
1002 Attachment.of(getActivity(), geo, Attachment.Type.LOCATION));
1003 toggleInputMethod();
1004 break;
1005 case REQUEST_INVITE_TO_CONVERSATION:
1006 XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data);
1007 if (invite != null) {
1008 if (invite.execute(activity)) {
1009 activity.mToast =
1010 Toast.makeText(
1011 activity, R.string.creating_conference, Toast.LENGTH_LONG);
1012 activity.mToast.show();
1013 }
1014 }
1015 break;
1016 }
1017 }
1018
1019 private void commitAttachments() {
1020 final List<Attachment> attachments = mediaPreviewAdapter.getAttachments();
1021 if (anyNeedsExternalStoragePermission(attachments)
1022 && !hasPermissions(
1023 REQUEST_COMMIT_ATTACHMENTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1024 return;
1025 }
1026 if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_ATTACHMENTS)) {
1027 return;
1028 }
1029 final PresenceSelector.OnPresenceSelected callback =
1030 () -> {
1031 for (Iterator<Attachment> i = attachments.iterator(); i.hasNext(); i.remove()) {
1032 final Attachment attachment = i.next();
1033 if (attachment.getType() == Attachment.Type.LOCATION) {
1034 attachLocationToConversation(conversation, attachment.getUri());
1035 } else if (attachment.getType() == Attachment.Type.IMAGE) {
1036 Log.d(
1037 Config.LOGTAG,
1038 "ConversationsActivity.commitAttachments() - attaching image to"
1039 + " conversations. CHOOSE_IMAGE");
1040 attachImageToConversation(
1041 conversation, attachment.getUri(), attachment.getMime());
1042 } else {
1043 Log.d(
1044 Config.LOGTAG,
1045 "ConversationsActivity.commitAttachments() - attaching file to"
1046 + " conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1047 attachFileToConversation(
1048 conversation, attachment.getUri(), attachment.getMime());
1049 }
1050 }
1051 mediaPreviewAdapter.notifyDataSetChanged();
1052 toggleInputMethod();
1053 };
1054 if (conversation == null
1055 || conversation.getMode() == Conversation.MODE_MULTI
1056 || Attachment.canBeSendInBand(attachments)
1057 || (conversation.getAccount().httpUploadAvailable()
1058 && FileBackend.allFilesUnderSize(
1059 getActivity(), attachments, getMaxHttpUploadSize(conversation)))) {
1060 callback.onPresenceSelected();
1061 } else {
1062 activity.selectPresence(conversation, callback);
1063 }
1064 }
1065
1066 private static boolean anyNeedsExternalStoragePermission(
1067 final Collection<Attachment> attachments) {
1068 for (final Attachment attachment : attachments) {
1069 if (attachment.getType() != Attachment.Type.LOCATION) {
1070 return true;
1071 }
1072 }
1073 return false;
1074 }
1075
1076 public void toggleInputMethod() {
1077 boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
1078 binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
1079 binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
1080 updateSendButton();
1081 }
1082
1083 private void handleNegativeActivityResult(int requestCode) {
1084 switch (requestCode) {
1085 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1086 if (pendingTakePhotoUri.clear()) {
1087 Log.d(
1088 Config.LOGTAG,
1089 "cleared pending photo uri after negative activity result");
1090 }
1091 break;
1092 }
1093 }
1094
1095 @Override
1096 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
1097 super.onActivityResult(requestCode, resultCode, data);
1098 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
1099 if (activity != null && activity.xmppConnectionService != null) {
1100 handleActivityResult(activityResult);
1101 } else {
1102 this.postponedActivityResult.push(activityResult);
1103 }
1104 }
1105
1106 public void unblockConversation(final Blockable conversation) {
1107 activity.xmppConnectionService.sendUnblockRequest(conversation);
1108 }
1109
1110 @Override
1111 public void onAttach(Activity activity) {
1112 super.onAttach(activity);
1113 Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
1114 if (activity instanceof ConversationsActivity) {
1115 this.activity = (ConversationsActivity) activity;
1116 } else {
1117 throw new IllegalStateException(
1118 "Trying to attach fragment to activity that is not the ConversationsActivity");
1119 }
1120 }
1121
1122 @Override
1123 public void onDetach() {
1124 super.onDetach();
1125 this.activity = null; // TODO maybe not a good idea since some callbacks really need it
1126 }
1127
1128 @Override
1129 public void onCreate(Bundle savedInstanceState) {
1130 super.onCreate(savedInstanceState);
1131 setHasOptionsMenu(true);
1132 }
1133
1134 @Override
1135 public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
1136 menuInflater.inflate(R.menu.fragment_conversation, menu);
1137 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
1138 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
1139 final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
1140 final MenuItem menuMute = menu.findItem(R.id.action_mute);
1141 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
1142 final MenuItem menuCall = menu.findItem(R.id.action_call);
1143 final MenuItem menuOngoingCall = menu.findItem(R.id.action_ongoing_call);
1144 final MenuItem menuVideoCall = menu.findItem(R.id.action_video_call);
1145 final MenuItem menuTogglePinned = menu.findItem(R.id.action_toggle_pinned);
1146
1147 if (conversation != null) {
1148 if (conversation.getMode() == Conversation.MODE_MULTI) {
1149 menuContactDetails.setVisible(false);
1150 menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
1151 menuMucDetails.setTitle(
1152 conversation.getMucOptions().isPrivateAndNonAnonymous()
1153 ? R.string.action_muc_details
1154 : R.string.channel_details);
1155 menuCall.setVisible(false);
1156 menuOngoingCall.setVisible(false);
1157 } else {
1158 final XmppConnectionService service =
1159 activity == null ? null : activity.xmppConnectionService;
1160 final Optional<OngoingRtpSession> ongoingRtpSession =
1161 service == null
1162 ? Optional.absent()
1163 : service.getJingleConnectionManager()
1164 .getOngoingRtpConnection(conversation.getContact());
1165 if (ongoingRtpSession.isPresent()) {
1166 menuOngoingCall.setVisible(true);
1167 menuCall.setVisible(false);
1168 } else {
1169 menuOngoingCall.setVisible(false);
1170 // use RtpCapability.check(conversation.getContact()); to check if contact
1171 // actually has support
1172 final boolean cameraAvailable =
1173 activity != null && activity.isCameraFeatureAvailable();
1174 menuCall.setVisible(true);
1175 menuVideoCall.setVisible(cameraAvailable);
1176 }
1177 menuContactDetails.setVisible(!this.conversation.withSelf());
1178 menuMucDetails.setVisible(false);
1179 menuInviteContact.setVisible(
1180 service != null
1181 && service.findConferenceServer(conversation.getAccount()) != null);
1182 }
1183 if (conversation.isMuted()) {
1184 menuMute.setVisible(false);
1185 } else {
1186 menuUnmute.setVisible(false);
1187 }
1188 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
1189 ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
1190 if (conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false)) {
1191 menuTogglePinned.setTitle(R.string.remove_from_favorites);
1192 } else {
1193 menuTogglePinned.setTitle(R.string.add_to_favorites);
1194 }
1195 }
1196 super.onCreateOptionsMenu(menu, menuInflater);
1197 }
1198
1199 @Override
1200 public View onCreateView(
1201 final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
1202 this.binding =
1203 DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
1204 binding.getRoot().setOnClickListener(null); // TODO why the fuck did we do this?
1205
1206 binding.textinput.addTextChangedListener(
1207 new StylingHelper.MessageEditorStyler(binding.textinput));
1208
1209 binding.textinput.setOnEditorActionListener(mEditorActionListener);
1210 binding.textinput.setRichContentListener(new String[] {"image/*"}, mEditorContentListener);
1211
1212 binding.textSendButton.setOnClickListener(this.mSendButtonListener);
1213
1214 binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
1215 binding.messagesView.setOnScrollListener(mOnScrollListener);
1216 binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
1217 mediaPreviewAdapter = new MediaPreviewAdapter(this);
1218 binding.mediaPreview.setAdapter(mediaPreviewAdapter);
1219 messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1220 messageListAdapter.setOnContactPictureClicked(this);
1221 messageListAdapter.setOnContactPictureLongClicked(this);
1222 binding.messagesView.setAdapter(messageListAdapter);
1223
1224 registerForContextMenu(binding.messagesView);
1225
1226 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1227 this.binding.textinput.setCustomInsertionActionModeCallback(
1228 new EditMessageActionModeCallback(this.binding.textinput));
1229 }
1230
1231 return binding.getRoot();
1232 }
1233
1234 @Override
1235 public void onDestroyView() {
1236 super.onDestroyView();
1237 Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1238 messageListAdapter.setOnContactPictureClicked(null);
1239 messageListAdapter.setOnContactPictureLongClicked(null);
1240 }
1241
1242 private void quoteText(String text) {
1243 if (binding.textinput.isEnabled()) {
1244 binding.textinput.insertAsQuote(text);
1245 binding.textinput.requestFocus();
1246 InputMethodManager inputMethodManager =
1247 (InputMethodManager)
1248 getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1249 if (inputMethodManager != null) {
1250 inputMethodManager.showSoftInput(
1251 binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1252 }
1253 }
1254 }
1255
1256 private void quoteMessage(Message message) {
1257 quoteText(MessageUtils.prepareQuote(message));
1258 }
1259
1260 @Override
1261 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1262 // This should cancel any remaining click events that would otherwise trigger links
1263 v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1264 synchronized (this.messageList) {
1265 super.onCreateContextMenu(menu, v, menuInfo);
1266 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1267 this.selectedMessage = this.messageList.get(acmi.position);
1268 populateContextMenu(menu);
1269 }
1270 }
1271
1272 private void populateContextMenu(final ContextMenu menu) {
1273 final Message m = this.selectedMessage;
1274 final Transferable t = m.getTransferable();
1275 if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1276
1277 if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1278 || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1279 return;
1280 }
1281
1282 if (m.getStatus() == Message.STATUS_RECEIVED
1283 && t != null
1284 && (t.getStatus() == Transferable.STATUS_CANCELLED
1285 || t.getStatus() == Transferable.STATUS_FAILED)) {
1286 return;
1287 }
1288
1289 final boolean deleted = m.isDeleted();
1290 final boolean encrypted =
1291 m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1292 || m.getEncryption() == Message.ENCRYPTION_PGP;
1293 final boolean receiving =
1294 m.getStatus() == Message.STATUS_RECEIVED
1295 && (t instanceof JingleFileTransferConnection
1296 || t instanceof HttpDownloadConnection);
1297 activity.getMenuInflater().inflate(R.menu.message_context, menu);
1298 menu.setHeaderTitle(R.string.message_options);
1299 final MenuItem addReaction = menu.findItem(R.id.action_add_reaction);
1300 final MenuItem reportAndBlock = menu.findItem(R.id.action_report_and_block);
1301 final MenuItem openWith = menu.findItem(R.id.open_with);
1302 final MenuItem copyMessage = menu.findItem(R.id.copy_message);
1303 final MenuItem copyLink = menu.findItem(R.id.copy_link);
1304 final MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1305 final MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1306 final MenuItem correctMessage = menu.findItem(R.id.correct_message);
1307 final MenuItem shareWith = menu.findItem(R.id.share_with);
1308 final MenuItem sendAgain = menu.findItem(R.id.send_again);
1309 final MenuItem retryAsP2P = menu.findItem(R.id.send_again_as_p2p);
1310 final MenuItem copyUrl = menu.findItem(R.id.copy_url);
1311 final MenuItem downloadFile = menu.findItem(R.id.download_file);
1312 final MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1313 final MenuItem deleteFile = menu.findItem(R.id.delete_file);
1314 final MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1315 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1316 final boolean showError =
1317 m.getStatus() == Message.STATUS_SEND_FAILED
1318 && m.getErrorMessage() != null
1319 && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1320 final Conversational conversational = m.getConversation();
1321 if (m.getStatus() == Message.STATUS_RECEIVED
1322 && conversational instanceof Conversation c) {
1323 final XmppConnection connection = c.getAccount().getXmppConnection();
1324 if (c.isWithStranger()
1325 && m.getServerMsgId() != null
1326 && !c.isBlocked()
1327 && connection != null
1328 && connection.getFeatures().spamReporting()) {
1329 reportAndBlock.setVisible(true);
1330 }
1331 }
1332 if (conversational instanceof Conversation c) {
1333 addReaction.setVisible(
1334 !showError
1335 && !m.isDeleted()
1336 && (c.getMode() == Conversational.MODE_SINGLE
1337 || (c.getMucOptions().occupantId()
1338 && c.getMucOptions().participating())));
1339 } else {
1340 addReaction.setVisible(false);
1341 }
1342 if (!m.isFileOrImage()
1343 && !encrypted
1344 && !m.isGeoUri()
1345 && !m.treatAsDownloadable()
1346 && !unInitiatedButKnownSize
1347 && t == null) {
1348 copyMessage.setVisible(true);
1349 quoteMessage.setVisible(!showError && !MessageUtils.prepareQuote(m).isEmpty());
1350 final String scheme =
1351 ShareUtil.getLinkScheme(new SpannableStringBuilder(m.getBody()));
1352 if ("xmpp".equals(scheme)) {
1353 copyLink.setTitle(R.string.copy_jabber_id);
1354 copyLink.setVisible(true);
1355 } else if (scheme != null) {
1356 copyLink.setVisible(true);
1357 }
1358 }
1359 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1360 retryDecryption.setVisible(true);
1361 }
1362 if (!showError
1363 && m.getType() == Message.TYPE_TEXT
1364 && !m.isGeoUri()
1365 && m.isLastCorrectableMessage()
1366 && m.getConversation() instanceof Conversation) {
1367 correctMessage.setVisible(true);
1368 }
1369 if ((m.isFileOrImage() && !deleted && !receiving)
1370 || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1371 && !unInitiatedButKnownSize
1372 && t == null) {
1373 shareWith.setVisible(true);
1374 }
1375 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1376 sendAgain.setVisible(true);
1377 final var fileNotUploaded = m.isFileOrImage() && !m.hasFileOnRemoteHost();
1378 final var isPeerOnline =
1379 conversational.getMode() == Conversation.MODE_SINGLE
1380 && (conversational instanceof Conversation c)
1381 && !c.getContact().getPresences().isEmpty();
1382 retryAsP2P.setVisible(fileNotUploaded && isPeerOnline);
1383 }
1384 if (m.hasFileOnRemoteHost()
1385 || m.isGeoUri()
1386 || m.treatAsDownloadable()
1387 || unInitiatedButKnownSize
1388 || t instanceof HttpDownloadConnection) {
1389 copyUrl.setVisible(true);
1390 }
1391 if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1392 downloadFile.setVisible(true);
1393 downloadFile.setTitle(
1394 activity.getString(
1395 R.string.download_x_file,
1396 UIHelper.getFileDescriptionString(activity, m)));
1397 }
1398 final boolean waitingOfferedSending =
1399 m.getStatus() == Message.STATUS_WAITING
1400 || m.getStatus() == Message.STATUS_UNSEND
1401 || m.getStatus() == Message.STATUS_OFFERED;
1402 final boolean cancelable =
1403 (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1404 if (cancelable) {
1405 cancelTransmission.setVisible(true);
1406 }
1407 if (m.isFileOrImage() && !deleted && !cancelable) {
1408 final String path = m.getRelativeFilePath();
1409 if (path == null
1410 || !path.startsWith("/")
1411 || FileBackend.inConversationsDirectory(requireActivity(), path)) {
1412 deleteFile.setVisible(true);
1413 deleteFile.setTitle(
1414 activity.getString(
1415 R.string.delete_x_file,
1416 UIHelper.getFileDescriptionString(activity, m)));
1417 }
1418 }
1419 if (showError) {
1420 showErrorMessage.setVisible(true);
1421 }
1422 final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1423 if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1424 || (mime != null && mime.startsWith("audio/"))) {
1425 openWith.setVisible(true);
1426 }
1427 }
1428 }
1429
1430 @Override
1431 public boolean onContextItemSelected(MenuItem item) {
1432 switch (item.getItemId()) {
1433 case R.id.share_with:
1434 ShareUtil.share(activity, selectedMessage);
1435 return true;
1436 case R.id.correct_message:
1437 correctMessage(selectedMessage);
1438 return true;
1439 case R.id.copy_message:
1440 ShareUtil.copyToClipboard(activity, selectedMessage);
1441 return true;
1442 case R.id.copy_link:
1443 ShareUtil.copyLinkToClipboard(activity, selectedMessage);
1444 return true;
1445 case R.id.quote_message:
1446 quoteMessage(selectedMessage);
1447 return true;
1448 case R.id.send_again:
1449 resendMessage(selectedMessage, false);
1450 return true;
1451 case R.id.send_again_as_p2p:
1452 resendMessage(selectedMessage, true);
1453 return true;
1454 case R.id.copy_url:
1455 ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1456 return true;
1457 case R.id.download_file:
1458 startDownloadable(selectedMessage);
1459 return true;
1460 case R.id.cancel_transmission:
1461 cancelTransmission(selectedMessage);
1462 return true;
1463 case R.id.retry_decryption:
1464 retryDecryption(selectedMessage);
1465 return true;
1466 case R.id.delete_file:
1467 deleteFile(selectedMessage);
1468 return true;
1469 case R.id.show_error_message:
1470 showErrorMessage(selectedMessage);
1471 return true;
1472 case R.id.open_with:
1473 openWith(selectedMessage);
1474 return true;
1475 case R.id.action_report_and_block:
1476 reportMessage(selectedMessage);
1477 return true;
1478 case R.id.action_add_reaction:
1479 addReaction(selectedMessage);
1480 return true;
1481 default:
1482 return super.onContextItemSelected(item);
1483 }
1484 }
1485
1486 @Override
1487 public boolean onOptionsItemSelected(final MenuItem item) {
1488 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1489 return false;
1490 } else if (conversation == null) {
1491 return super.onOptionsItemSelected(item);
1492 }
1493 switch (item.getItemId()) {
1494 case R.id.encryption_choice_axolotl:
1495 case R.id.encryption_choice_pgp:
1496 case R.id.encryption_choice_none:
1497 handleEncryptionSelection(item);
1498 break;
1499 case R.id.attach_choose_picture:
1500 case R.id.attach_take_picture:
1501 case R.id.attach_record_video:
1502 case R.id.attach_choose_file:
1503 case R.id.attach_record_voice:
1504 case R.id.attach_location:
1505 handleAttachmentSelection(item);
1506 break;
1507 case R.id.action_search:
1508 startSearch();
1509 break;
1510 case R.id.action_archive:
1511 activity.xmppConnectionService.archiveConversation(conversation);
1512 break;
1513 case R.id.action_contact_details:
1514 activity.switchToContactDetails(conversation.getContact());
1515 break;
1516 case R.id.action_muc_details:
1517 ConferenceDetailsActivity.open(getActivity(), conversation);
1518 break;
1519 case R.id.action_invite:
1520 startActivityForResult(
1521 ChooseContactActivity.create(activity, conversation),
1522 REQUEST_INVITE_TO_CONVERSATION);
1523 break;
1524 case R.id.action_clear_history:
1525 clearHistoryDialog(conversation);
1526 break;
1527 case R.id.action_mute:
1528 muteConversationDialog(conversation);
1529 break;
1530 case R.id.action_unmute:
1531 unMuteConversation(conversation);
1532 break;
1533 case R.id.action_block:
1534 case R.id.action_unblock:
1535 final Activity activity = getActivity();
1536 if (activity instanceof XmppActivity) {
1537 BlockContactDialog.show((XmppActivity) activity, conversation);
1538 }
1539 break;
1540 case R.id.action_audio_call:
1541 checkPermissionAndTriggerAudioCall();
1542 break;
1543 case R.id.action_video_call:
1544 checkPermissionAndTriggerVideoCall();
1545 break;
1546 case R.id.action_ongoing_call:
1547 returnToOngoingCall();
1548 break;
1549 case R.id.action_toggle_pinned:
1550 togglePinned();
1551 break;
1552 default:
1553 break;
1554 }
1555 return super.onOptionsItemSelected(item);
1556 }
1557
1558 private void startSearch() {
1559 final Intent intent = new Intent(getActivity(), SearchActivity.class);
1560 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
1561 startActivity(intent);
1562 }
1563
1564 private void returnToOngoingCall() {
1565 final Optional<OngoingRtpSession> ongoingRtpSession =
1566 activity.xmppConnectionService
1567 .getJingleConnectionManager()
1568 .getOngoingRtpConnection(conversation.getContact());
1569 if (ongoingRtpSession.isPresent()) {
1570 final OngoingRtpSession id = ongoingRtpSession.get();
1571 final Intent intent = new Intent(getActivity(), RtpSessionActivity.class);
1572 intent.setAction(Intent.ACTION_VIEW);
1573 intent.putExtra(
1574 RtpSessionActivity.EXTRA_ACCOUNT,
1575 id.getAccount().getJid().asBareJid().toString());
1576 intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toString());
1577 if (id instanceof AbstractJingleConnection) {
1578 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
1579 startActivity(intent);
1580 } else if (id instanceof JingleConnectionManager.RtpSessionProposal proposal) {
1581 if (Media.audioOnly(proposal.media)) {
1582 intent.putExtra(
1583 RtpSessionActivity.EXTRA_LAST_ACTION,
1584 RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1585 } else {
1586 intent.putExtra(
1587 RtpSessionActivity.EXTRA_LAST_ACTION,
1588 RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1589 }
1590 intent.putExtra(RtpSessionActivity.EXTRA_PROPOSED_SESSION_ID, proposal.sessionId);
1591 startActivity(intent);
1592 }
1593 }
1594 }
1595
1596 private void togglePinned() {
1597 final boolean pinned =
1598 conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
1599 conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
1600 activity.xmppConnectionService.updateConversation(conversation);
1601 activity.invalidateOptionsMenu();
1602 }
1603
1604 private void checkPermissionAndTriggerAudioCall() {
1605 if (activity.mUseTor || conversation.getAccount().isOnion()) {
1606 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1607 return;
1608 }
1609 final List<String> permissions;
1610 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1611 permissions =
1612 Arrays.asList(
1613 Manifest.permission.RECORD_AUDIO,
1614 Manifest.permission.BLUETOOTH_CONNECT);
1615 } else {
1616 permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
1617 }
1618 if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
1619 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1620 }
1621 }
1622
1623 private void checkPermissionAndTriggerVideoCall() {
1624 if (activity.mUseTor || conversation.getAccount().isOnion()) {
1625 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1626 return;
1627 }
1628 final List<String> permissions;
1629 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1630 permissions =
1631 Arrays.asList(
1632 Manifest.permission.RECORD_AUDIO,
1633 Manifest.permission.CAMERA,
1634 Manifest.permission.BLUETOOTH_CONNECT);
1635 } else {
1636 permissions =
1637 Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
1638 }
1639 if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
1640 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1641 }
1642 }
1643
1644 private void triggerRtpSession(final String action) {
1645 if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
1646 Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
1647 .show();
1648 return;
1649 }
1650 final Account account = conversation.getAccount();
1651 if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
1652 activity.xmppConnectionService.updateAccount(account);
1653 }
1654 final Contact contact = conversation.getContact();
1655 if (Config.USE_JINGLE_MESSAGE_INIT && RtpCapability.jmiSupport(contact)) {
1656 triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
1657 } else {
1658 final RtpCapability.Capability capability;
1659 if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
1660 capability = RtpCapability.Capability.VIDEO;
1661 } else {
1662 capability = RtpCapability.Capability.AUDIO;
1663 }
1664 PresenceSelector.selectFullJidForDirectRtpConnection(
1665 activity,
1666 contact,
1667 capability,
1668 fullJid -> {
1669 triggerRtpSession(contact.getAccount(), fullJid, action);
1670 });
1671 }
1672 }
1673
1674 private void triggerRtpSession(final Account account, final Jid with, final String action) {
1675 CallIntegrationConnectionService.placeCall(
1676 activity.xmppConnectionService,
1677 account,
1678 with,
1679 RtpSessionActivity.actionToMedia(action));
1680 }
1681
1682 private void handleAttachmentSelection(MenuItem item) {
1683 switch (item.getItemId()) {
1684 case R.id.attach_choose_picture:
1685 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1686 break;
1687 case R.id.attach_take_picture:
1688 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1689 break;
1690 case R.id.attach_record_video:
1691 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1692 break;
1693 case R.id.attach_choose_file:
1694 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1695 break;
1696 case R.id.attach_record_voice:
1697 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1698 break;
1699 case R.id.attach_location:
1700 attachFile(ATTACHMENT_CHOICE_LOCATION);
1701 break;
1702 }
1703 }
1704
1705 private void handleEncryptionSelection(MenuItem item) {
1706 if (conversation == null) {
1707 return;
1708 }
1709 final boolean updated;
1710 switch (item.getItemId()) {
1711 case R.id.encryption_choice_none:
1712 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1713 item.setChecked(true);
1714 break;
1715 case R.id.encryption_choice_pgp:
1716 if (activity.hasPgp()) {
1717 if (conversation.getAccount().getPgpSignature() != null) {
1718 updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1719 item.setChecked(true);
1720 } else {
1721 updated = false;
1722 activity.announcePgp(
1723 conversation.getAccount(),
1724 conversation,
1725 null,
1726 activity.onOpenPGPKeyPublished);
1727 }
1728 } else {
1729 activity.showInstallPgpDialog();
1730 updated = false;
1731 }
1732 break;
1733 case R.id.encryption_choice_axolotl:
1734 Log.d(
1735 Config.LOGTAG,
1736 AxolotlService.getLogprefix(conversation.getAccount())
1737 + "Enabled axolotl for Contact "
1738 + conversation.getContact().getJid());
1739 updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1740 item.setChecked(true);
1741 break;
1742 default:
1743 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1744 break;
1745 }
1746 if (updated) {
1747 activity.xmppConnectionService.updateConversation(conversation);
1748 }
1749 updateChatMsgHint();
1750 getActivity().invalidateOptionsMenu();
1751 activity.refreshUi();
1752 }
1753
1754 public void attachFile(final int attachmentChoice) {
1755 attachFile(attachmentChoice, true);
1756 }
1757
1758 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
1759 if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1760 if (!hasPermissions(
1761 attachmentChoice,
1762 Manifest.permission.WRITE_EXTERNAL_STORAGE,
1763 Manifest.permission.RECORD_AUDIO)) {
1764 return;
1765 }
1766 } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
1767 || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1768 if (!hasPermissions(
1769 attachmentChoice,
1770 Manifest.permission.WRITE_EXTERNAL_STORAGE,
1771 Manifest.permission.CAMERA)) {
1772 return;
1773 }
1774 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1775 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1776 return;
1777 }
1778 }
1779 if (updateRecentlyUsed) {
1780 storeRecentlyUsedQuickAction(attachmentChoice);
1781 }
1782 final int encryption = conversation.getNextEncryption();
1783 final int mode = conversation.getMode();
1784 if (encryption == Message.ENCRYPTION_PGP) {
1785 if (activity.hasPgp()) {
1786 if (mode == Conversation.MODE_SINGLE
1787 && conversation.getContact().getPgpKeyId() != 0) {
1788 activity.xmppConnectionService
1789 .getPgpEngine()
1790 .hasKey(
1791 conversation.getContact(),
1792 new UiCallback<Contact>() {
1793
1794 @Override
1795 public void userInputRequired(
1796 PendingIntent pi, Contact contact) {
1797 startPendingIntent(pi, attachmentChoice);
1798 }
1799
1800 @Override
1801 public void success(Contact contact) {
1802 invokeAttachFileIntent(attachmentChoice);
1803 }
1804
1805 @Override
1806 public void error(int error, Contact contact) {
1807 activity.replaceToast(getString(error));
1808 }
1809 });
1810 } else if (mode == Conversation.MODE_MULTI
1811 && conversation.getMucOptions().pgpKeysInUse()) {
1812 if (!conversation.getMucOptions().everybodyHasKeys()) {
1813 Toast warning =
1814 Toast.makeText(
1815 getActivity(),
1816 R.string.missing_public_keys,
1817 Toast.LENGTH_LONG);
1818 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1819 warning.show();
1820 }
1821 invokeAttachFileIntent(attachmentChoice);
1822 } else {
1823 showNoPGPKeyDialog(
1824 false,
1825 (dialog, which) -> {
1826 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1827 activity.xmppConnectionService.updateConversation(conversation);
1828 invokeAttachFileIntent(attachmentChoice);
1829 });
1830 }
1831 } else {
1832 activity.showInstallPgpDialog();
1833 }
1834 } else {
1835 invokeAttachFileIntent(attachmentChoice);
1836 }
1837 }
1838
1839 private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
1840 try {
1841 activity.getPreferences()
1842 .edit()
1843 .putString(
1844 RECENTLY_USED_QUICK_ACTION,
1845 SendButtonAction.of(attachmentChoice).toString())
1846 .apply();
1847 } catch (IllegalArgumentException e) {
1848 // just do not save
1849 }
1850 }
1851
1852 @Override
1853 public void onRequestPermissionsResult(
1854 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
1855 final PermissionUtils.PermissionResult permissionResult =
1856 PermissionUtils.removeBluetoothConnect(permissions, grantResults);
1857 if (grantResults.length > 0) {
1858 if (allGranted(permissionResult.grantResults)) {
1859 switch (requestCode) {
1860 case REQUEST_START_DOWNLOAD:
1861 if (this.mPendingDownloadableMessage != null) {
1862 startDownloadable(this.mPendingDownloadableMessage);
1863 }
1864 break;
1865 case REQUEST_ADD_EDITOR_CONTENT:
1866 if (this.mPendingEditorContent != null) {
1867 attachEditorContentToConversation(this.mPendingEditorContent);
1868 }
1869 break;
1870 case REQUEST_COMMIT_ATTACHMENTS:
1871 commitAttachments();
1872 break;
1873 case REQUEST_START_AUDIO_CALL:
1874 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1875 break;
1876 case REQUEST_START_VIDEO_CALL:
1877 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1878 break;
1879 default:
1880 attachFile(requestCode);
1881 break;
1882 }
1883 } else {
1884 @StringRes int res;
1885 String firstDenied =
1886 getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
1887 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1888 res = R.string.no_microphone_permission;
1889 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1890 res = R.string.no_camera_permission;
1891 } else {
1892 res = R.string.no_storage_permission;
1893 }
1894 Toast.makeText(
1895 getActivity(),
1896 getString(res, getString(R.string.app_name)),
1897 Toast.LENGTH_SHORT)
1898 .show();
1899 }
1900 }
1901 if (writeGranted(grantResults, permissions)) {
1902 if (activity != null && activity.xmppConnectionService != null) {
1903 activity.xmppConnectionService.getBitmapCache().evictAll();
1904 activity.xmppConnectionService.restartFileObserver();
1905 }
1906 refresh();
1907 }
1908 if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
1909 XmppConnectionService.toggleForegroundService(activity);
1910 }
1911 }
1912
1913 public void startDownloadable(Message message) {
1914 if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1915 this.mPendingDownloadableMessage = message;
1916 return;
1917 }
1918 Transferable transferable = message.getTransferable();
1919 if (transferable != null) {
1920 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1921 createNewConnection(message);
1922 return;
1923 }
1924 if (!transferable.start()) {
1925 Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1926 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
1927 .show();
1928 }
1929 } else if (message.treatAsDownloadable()
1930 || message.hasFileOnRemoteHost()
1931 || MessageUtils.unInitiatedButKnownSize(message)) {
1932 createNewConnection(message);
1933 } else {
1934 Log.d(
1935 Config.LOGTAG,
1936 message.getConversation().getAccount() + ": unable to start downloadable");
1937 }
1938 }
1939
1940 private void createNewConnection(final Message message) {
1941 if (!activity.xmppConnectionService.hasInternetConnection()) {
1942 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
1943 .show();
1944 return;
1945 }
1946 activity.xmppConnectionService
1947 .getHttpConnectionManager()
1948 .createNewDownloadConnection(message, true);
1949 }
1950
1951 @SuppressLint("InflateParams")
1952 protected void clearHistoryDialog(final Conversation conversation) {
1953 final MaterialAlertDialogBuilder builder =
1954 new MaterialAlertDialogBuilder(requireActivity());
1955 builder.setTitle(R.string.clear_conversation_history);
1956 final View dialogView =
1957 requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1958 final CheckBox endConversationCheckBox =
1959 dialogView.findViewById(R.id.end_conversation_checkbox);
1960 builder.setView(dialogView);
1961 builder.setNegativeButton(getString(R.string.cancel), null);
1962 builder.setPositiveButton(
1963 getString(R.string.confirm),
1964 (dialog, which) -> {
1965 this.activity.xmppConnectionService.clearConversationHistory(conversation);
1966 if (endConversationCheckBox.isChecked()) {
1967 this.activity.xmppConnectionService.archiveConversation(conversation);
1968 this.activity.onConversationArchived(conversation);
1969 } else {
1970 activity.onConversationsListItemUpdated();
1971 refresh();
1972 }
1973 });
1974 builder.create().show();
1975 }
1976
1977 protected void muteConversationDialog(final Conversation conversation) {
1978 final MaterialAlertDialogBuilder builder =
1979 new MaterialAlertDialogBuilder(requireActivity());
1980 builder.setTitle(R.string.disable_notifications);
1981 final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1982 final CharSequence[] labels = new CharSequence[durations.length];
1983 for (int i = 0; i < durations.length; ++i) {
1984 if (durations[i] == -1) {
1985 labels[i] = getString(R.string.until_further_notice);
1986 } else {
1987 labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
1988 }
1989 }
1990 builder.setItems(
1991 labels,
1992 (dialog, which) -> {
1993 final long till;
1994 if (durations[which] == -1) {
1995 till = Long.MAX_VALUE;
1996 } else {
1997 till = System.currentTimeMillis() + (durations[which] * 1000L);
1998 }
1999 conversation.setMutedTill(till);
2000 activity.xmppConnectionService.updateConversation(conversation);
2001 activity.onConversationsListItemUpdated();
2002 refresh();
2003 requireActivity().invalidateOptionsMenu();
2004 });
2005 builder.create().show();
2006 }
2007
2008 private boolean hasPermissions(int requestCode, List<String> permissions) {
2009 final List<String> missingPermissions = new ArrayList<>();
2010 for (String permission : permissions) {
2011 if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
2012 || Config.ONLY_INTERNAL_STORAGE)
2013 && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2014 continue;
2015 }
2016 if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2017 missingPermissions.add(permission);
2018 }
2019 }
2020 if (missingPermissions.size() == 0) {
2021 return true;
2022 } else {
2023 requestPermissions(missingPermissions.toArray(new String[0]), requestCode);
2024 return false;
2025 }
2026 }
2027
2028 private boolean hasPermissions(int requestCode, String... permissions) {
2029 return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2030 }
2031
2032 public void unMuteConversation(final Conversation conversation) {
2033 conversation.setMutedTill(0);
2034 this.activity.xmppConnectionService.updateConversation(conversation);
2035 this.activity.onConversationsListItemUpdated();
2036 refresh();
2037 requireActivity().invalidateOptionsMenu();
2038 }
2039
2040 protected void invokeAttachFileIntent(final int attachmentChoice) {
2041 Intent intent = new Intent();
2042 boolean chooser = false;
2043 switch (attachmentChoice) {
2044 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2045 intent.setAction(Intent.ACTION_GET_CONTENT);
2046 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2047 intent.setType("image/*");
2048 chooser = true;
2049 break;
2050 case ATTACHMENT_CHOICE_RECORD_VIDEO:
2051 intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2052 break;
2053 case ATTACHMENT_CHOICE_TAKE_PHOTO:
2054 final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2055 pendingTakePhotoUri.push(uri);
2056 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2057 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2058 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2059 intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2060 break;
2061 case ATTACHMENT_CHOICE_CHOOSE_FILE:
2062 chooser = true;
2063 intent.setType("*/*");
2064 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2065 intent.addCategory(Intent.CATEGORY_OPENABLE);
2066 intent.setAction(Intent.ACTION_GET_CONTENT);
2067 break;
2068 case ATTACHMENT_CHOICE_RECORD_VOICE:
2069 intent = new Intent(getActivity(), RecordingActivity.class);
2070 break;
2071 case ATTACHMENT_CHOICE_LOCATION:
2072 intent = GeoHelper.getFetchIntent(activity);
2073 break;
2074 }
2075 final Context context = getActivity();
2076 if (context == null) {
2077 return;
2078 }
2079 try {
2080 if (chooser) {
2081 startActivityForResult(
2082 Intent.createChooser(intent, getString(R.string.perform_action_with)),
2083 attachmentChoice);
2084 } else {
2085 startActivityForResult(intent, attachmentChoice);
2086 }
2087 } catch (final ActivityNotFoundException e) {
2088 Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2089 }
2090 }
2091
2092 @Override
2093 public void onResume() {
2094 super.onResume();
2095 binding.messagesView.post(this::fireReadEvent);
2096 }
2097
2098 private void fireReadEvent() {
2099 if (activity != null && this.conversation != null) {
2100 String uuid = getLastVisibleMessageUuid();
2101 if (uuid != null) {
2102 activity.onConversationRead(this.conversation, uuid);
2103 }
2104 }
2105 }
2106
2107 private String getLastVisibleMessageUuid() {
2108 if (binding == null) {
2109 return null;
2110 }
2111 synchronized (this.messageList) {
2112 int pos = binding.messagesView.getLastVisiblePosition();
2113 if (pos >= 0) {
2114 Message message = null;
2115 for (int i = pos; i >= 0; --i) {
2116 try {
2117 message = (Message) binding.messagesView.getItemAtPosition(i);
2118 } catch (IndexOutOfBoundsException e) {
2119 // should not happen if we synchronize properly. however if that fails we
2120 // just gonna try item -1
2121 continue;
2122 }
2123 if (message.getType() != Message.TYPE_STATUS) {
2124 break;
2125 }
2126 }
2127 if (message != null) {
2128 return message.getUuid();
2129 }
2130 }
2131 }
2132 return null;
2133 }
2134
2135 private void openWith(final Message message) {
2136 if (message.isGeoUri()) {
2137 GeoHelper.view(getActivity(), message);
2138 } else {
2139 final DownloadableFile file =
2140 activity.xmppConnectionService.getFileBackend().getFile(message);
2141 ViewUtil.view(activity, file);
2142 }
2143 }
2144
2145 private void addReaction(final Message message) {
2146 activity.addReaction(
2147 message,
2148 reactions -> {
2149 if (activity.xmppConnectionService.sendReactions(message, reactions)) {
2150 return;
2151 }
2152 Toast.makeText(activity, R.string.could_not_add_reaction, Toast.LENGTH_LONG)
2153 .show();
2154 });
2155 }
2156
2157 private void reportMessage(final Message message) {
2158 BlockContactDialog.show(activity, conversation.getContact(), message.getServerMsgId());
2159 }
2160
2161 private void showErrorMessage(final Message message) {
2162 final MaterialAlertDialogBuilder builder =
2163 new MaterialAlertDialogBuilder(requireActivity());
2164 builder.setTitle(R.string.error_message);
2165 final String errorMessage = message.getErrorMessage();
2166 final String[] errorMessageParts =
2167 errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2168 final String displayError;
2169 if (errorMessageParts.length == 2) {
2170 displayError = errorMessageParts[1];
2171 } else {
2172 displayError = errorMessage;
2173 }
2174 builder.setMessage(displayError);
2175 builder.setNegativeButton(
2176 R.string.copy_to_clipboard,
2177 (dialog, which) -> {
2178 activity.copyTextToClipboard(displayError, R.string.error_message);
2179 Toast.makeText(
2180 activity,
2181 R.string.error_message_copied_to_clipboard,
2182 Toast.LENGTH_SHORT)
2183 .show();
2184 });
2185 builder.setPositiveButton(R.string.confirm, null);
2186 builder.create().show();
2187 }
2188
2189 private void deleteFile(final Message message) {
2190 final MaterialAlertDialogBuilder builder =
2191 new MaterialAlertDialogBuilder(requireActivity());
2192 builder.setNegativeButton(R.string.cancel, null);
2193 builder.setTitle(R.string.delete_file_dialog);
2194 builder.setMessage(R.string.delete_file_dialog_msg);
2195 builder.setPositiveButton(
2196 R.string.confirm,
2197 (dialog, which) -> {
2198 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2199 message.setDeleted(true);
2200 activity.xmppConnectionService.evictPreview(message.getUuid());
2201 activity.xmppConnectionService.updateMessage(message, false);
2202 activity.onConversationsListItemUpdated();
2203 refresh();
2204 }
2205 });
2206 builder.create().show();
2207 }
2208
2209 private void resendMessage(final Message message, final boolean forceP2P) {
2210 if (message.isFileOrImage()) {
2211 if (!(message.getConversation() instanceof Conversation conversation)) {
2212 return;
2213 }
2214 final DownloadableFile file =
2215 activity.xmppConnectionService.getFileBackend().getFile(message);
2216 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2217 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2218 if (!message.hasFileOnRemoteHost()
2219 && xmppConnection != null
2220 && conversation.getMode() == Conversational.MODE_SINGLE
2221 && (!xmppConnection
2222 .getFeatures()
2223 .httpUpload(message.getFileParams().getSize())
2224 || forceP2P)) {
2225 activity.selectPresence(
2226 conversation,
2227 () -> {
2228 message.setCounterpart(conversation.getNextCounterpart());
2229 activity.xmppConnectionService.resendFailedMessages(
2230 message, forceP2P);
2231 new Handler()
2232 .post(
2233 () -> {
2234 int size = messageList.size();
2235 this.binding.messagesView.setSelection(
2236 size - 1);
2237 });
2238 });
2239 return;
2240 }
2241 } else if (!Compatibility.hasStoragePermission(getActivity())) {
2242 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2243 return;
2244 } else {
2245 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2246 message.setDeleted(true);
2247 activity.xmppConnectionService.updateMessage(message, false);
2248 activity.onConversationsListItemUpdated();
2249 refresh();
2250 return;
2251 }
2252 }
2253 activity.xmppConnectionService.resendFailedMessages(message, false);
2254 new Handler()
2255 .post(
2256 () -> {
2257 int size = messageList.size();
2258 this.binding.messagesView.setSelection(size - 1);
2259 });
2260 }
2261
2262 private void cancelTransmission(Message message) {
2263 Transferable transferable = message.getTransferable();
2264 if (transferable != null) {
2265 transferable.cancel();
2266 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2267 activity.xmppConnectionService.markMessage(
2268 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2269 }
2270 }
2271
2272 private void retryDecryption(Message message) {
2273 message.setEncryption(Message.ENCRYPTION_PGP);
2274 activity.onConversationsListItemUpdated();
2275 refresh();
2276 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2277 }
2278
2279 public void privateMessageWith(final Jid counterpart) {
2280 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2281 activity.xmppConnectionService.sendChatState(conversation);
2282 }
2283 this.binding.textinput.setText("");
2284 this.conversation.setNextCounterpart(counterpart);
2285 updateChatMsgHint();
2286 updateSendButton();
2287 updateEditablity();
2288 }
2289
2290 private void correctMessage(final Message message) {
2291 this.conversation.setCorrectingMessage(message);
2292 final Editable editable = binding.textinput.getText();
2293 this.conversation.setDraftMessage(editable.toString());
2294 this.binding.textinput.setText("");
2295 this.binding.textinput.append(message.getBody());
2296 }
2297
2298 private void highlightInConference(String nick) {
2299 final Editable editable = this.binding.textinput.getText();
2300 String oldString = editable.toString().trim();
2301 final int pos = this.binding.textinput.getSelectionStart();
2302 if (oldString.isEmpty() || pos == 0) {
2303 editable.insert(0, nick + ": ");
2304 } else {
2305 final char before = editable.charAt(pos - 1);
2306 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2307 if (before == '\n') {
2308 editable.insert(pos, nick + ": ");
2309 } else {
2310 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2311 if (NickValidityChecker.check(
2312 conversation,
2313 Arrays.asList(
2314 editable.subSequence(0, pos - 2).toString().split(", ")))) {
2315 editable.insert(pos - 2, ", " + nick);
2316 return;
2317 }
2318 }
2319 editable.insert(
2320 pos,
2321 (Character.isWhitespace(before) ? "" : " ")
2322 + nick
2323 + (Character.isWhitespace(after) ? "" : " "));
2324 if (Character.isWhitespace(after)) {
2325 this.binding.textinput.setSelection(
2326 this.binding.textinput.getSelectionStart() + 1);
2327 }
2328 }
2329 }
2330 }
2331
2332 @Override
2333 public void startActivityForResult(Intent intent, int requestCode) {
2334 final Activity activity = getActivity();
2335 if (activity instanceof ConversationsActivity) {
2336 ((ConversationsActivity) activity).clearPendingViewIntent();
2337 }
2338 super.startActivityForResult(intent, requestCode);
2339 }
2340
2341 @Override
2342 public void onSaveInstanceState(@NonNull Bundle outState) {
2343 super.onSaveInstanceState(outState);
2344 if (conversation != null) {
2345 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2346 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2347 final Uri uri = pendingTakePhotoUri.peek();
2348 if (uri != null) {
2349 outState.putString(STATE_PHOTO_URI, uri.toString());
2350 }
2351 final ScrollState scrollState = getScrollPosition();
2352 if (scrollState != null) {
2353 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2354 }
2355 final ArrayList<Attachment> attachments =
2356 mediaPreviewAdapter == null
2357 ? new ArrayList<>()
2358 : mediaPreviewAdapter.getAttachments();
2359 if (attachments.size() > 0) {
2360 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2361 }
2362 }
2363 }
2364
2365 @Override
2366 public void onActivityCreated(Bundle savedInstanceState) {
2367 super.onActivityCreated(savedInstanceState);
2368 if (savedInstanceState == null) {
2369 return;
2370 }
2371 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2372 ArrayList<Attachment> attachments =
2373 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2374 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2375 if (uuid != null) {
2376 QuickLoader.set(uuid);
2377 this.pendingConversationsUuid.push(uuid);
2378 if (attachments != null && attachments.size() > 0) {
2379 this.pendingMediaPreviews.push(attachments);
2380 }
2381 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2382 if (takePhotoUri != null) {
2383 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2384 }
2385 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2386 }
2387 }
2388
2389 @Override
2390 public void onStart() {
2391 super.onStart();
2392 if (this.reInitRequiredOnStart && this.conversation != null) {
2393 final Bundle extras = pendingExtras.pop();
2394 reInit(this.conversation, extras != null);
2395 if (extras != null) {
2396 processExtras(extras);
2397 }
2398 } else if (conversation == null
2399 && activity != null
2400 && activity.xmppConnectionService != null) {
2401 final String uuid = pendingConversationsUuid.pop();
2402 Log.d(
2403 Config.LOGTAG,
2404 "ConversationFragment.onStart() - activity was bound but no conversation"
2405 + " loaded. uuid="
2406 + uuid);
2407 if (uuid != null) {
2408 findAndReInitByUuidOrArchive(uuid);
2409 }
2410 }
2411 }
2412
2413 @Override
2414 public void onStop() {
2415 super.onStop();
2416 final Activity activity = getActivity();
2417 messageListAdapter.unregisterListenerInAudioPlayer();
2418 if (activity == null || !activity.isChangingConfigurations()) {
2419 hideSoftKeyboard(activity);
2420 messageListAdapter.stopAudioPlayer();
2421 }
2422 if (this.conversation != null) {
2423 final String msg = this.binding.textinput.getText().toString();
2424 storeNextMessage(msg);
2425 updateChatState(this.conversation, msg);
2426 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2427 }
2428 this.reInitRequiredOnStart = true;
2429 }
2430
2431 private void updateChatState(final Conversation conversation, final String msg) {
2432 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2433 Account.State status = conversation.getAccount().getStatus();
2434 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2435 activity.xmppConnectionService.sendChatState(conversation);
2436 }
2437 }
2438
2439 private void saveMessageDraftStopAudioPlayer() {
2440 final Conversation previousConversation = this.conversation;
2441 if (this.activity == null || this.binding == null || previousConversation == null) {
2442 return;
2443 }
2444 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2445 final String msg = this.binding.textinput.getText().toString();
2446 storeNextMessage(msg);
2447 updateChatState(this.conversation, msg);
2448 messageListAdapter.stopAudioPlayer();
2449 mediaPreviewAdapter.clearPreviews();
2450 toggleInputMethod();
2451 }
2452
2453 public void reInit(final Conversation conversation, final Bundle extras) {
2454 QuickLoader.set(conversation.getUuid());
2455 final boolean changedConversation = this.conversation != conversation;
2456 if (changedConversation) {
2457 this.saveMessageDraftStopAudioPlayer();
2458 }
2459 this.clearPending();
2460 if (this.reInit(conversation, extras != null)) {
2461 if (extras != null) {
2462 processExtras(extras);
2463 }
2464 this.reInitRequiredOnStart = false;
2465 } else {
2466 this.reInitRequiredOnStart = true;
2467 pendingExtras.push(extras);
2468 }
2469 resetUnreadMessagesCount();
2470 }
2471
2472 private void reInit(Conversation conversation) {
2473 reInit(conversation, false);
2474 }
2475
2476 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2477 if (conversation == null) {
2478 return false;
2479 }
2480 this.conversation = conversation;
2481 // once we set the conversation all is good and it will automatically do the right thing in
2482 // onStart()
2483 if (this.activity == null || this.binding == null) {
2484 return false;
2485 }
2486
2487 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2488 activity.onConversationArchived(this.conversation);
2489 return false;
2490 }
2491
2492 stopScrolling();
2493 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
2494
2495 if (this.conversation.isRead() && hasExtras) {
2496 Log.d(Config.LOGTAG, "trimming conversation");
2497 this.conversation.trim();
2498 }
2499
2500 setupIme();
2501
2502 final boolean scrolledToBottomAndNoPending =
2503 this.scrolledToBottom() && pendingScrollState.peek() == null;
2504
2505 this.binding.textSendButton.setContentDescription(
2506 activity.getString(R.string.send_message_to_x, conversation.getName()));
2507 this.binding.textinput.setKeyboardListener(null);
2508 final boolean participating =
2509 conversation.getMode() == Conversational.MODE_SINGLE
2510 || conversation.getMucOptions().participating();
2511 if (participating) {
2512 this.binding.textinput.setText(this.conversation.getNextMessage());
2513 this.binding.textinput.setSelection(this.binding.textinput.length());
2514 } else {
2515 this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
2516 }
2517 this.binding.textinput.setKeyboardListener(this);
2518 messageListAdapter.updatePreferences();
2519 refresh(false);
2520 activity.invalidateOptionsMenu();
2521 this.conversation.messagesLoaded.set(true);
2522 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
2523
2524 if (hasExtras || scrolledToBottomAndNoPending) {
2525 resetUnreadMessagesCount();
2526 synchronized (this.messageList) {
2527 Log.d(Config.LOGTAG, "jump to first unread message");
2528 final Message first = conversation.getFirstUnreadMessage();
2529 final int bottom = Math.max(0, this.messageList.size() - 1);
2530 final int pos;
2531 final boolean jumpToBottom;
2532 if (first == null) {
2533 pos = bottom;
2534 jumpToBottom = true;
2535 } else {
2536 int i = getIndexOf(first.getUuid(), this.messageList);
2537 pos = i < 0 ? bottom : i;
2538 jumpToBottom = false;
2539 }
2540 setSelection(pos, jumpToBottom);
2541 }
2542 }
2543
2544 this.binding.messagesView.post(this::fireReadEvent);
2545 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
2546 // layout which might be unnecessary since we can *see* it
2547 activity.xmppConnectionService
2548 .getNotificationService()
2549 .setOpenConversation(this.conversation);
2550 return true;
2551 }
2552
2553 private void resetUnreadMessagesCount() {
2554 lastMessageUuid = null;
2555 hideUnreadMessagesCount();
2556 }
2557
2558 private void hideUnreadMessagesCount() {
2559 if (this.binding == null) {
2560 return;
2561 }
2562 this.binding.scrollToBottomButton.setEnabled(false);
2563 this.binding.scrollToBottomButton.hide();
2564 this.binding.unreadCountCustomView.setVisibility(View.GONE);
2565 }
2566
2567 private void setSelection(int pos, boolean jumpToBottom) {
2568 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2569 this.binding.messagesView.post(
2570 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2571 this.binding.messagesView.post(this::fireReadEvent);
2572 }
2573
2574 private boolean scrolledToBottom() {
2575 return this.binding != null && scrolledToBottom(this.binding.messagesView);
2576 }
2577
2578 private void processExtras(final Bundle extras) {
2579 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2580 final String text = extras.getString(Intent.EXTRA_TEXT);
2581 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2582 final String postInitAction =
2583 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
2584 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2585 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2586 final boolean doNotAppend =
2587 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2588 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
2589 final List<Uri> uris = extractUris(extras);
2590 if (uris != null && uris.size() > 0) {
2591 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2592 mediaPreviewAdapter.addMediaPreviews(
2593 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2594 } else {
2595 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2596 mediaPreviewAdapter.addMediaPreviews(
2597 Attachment.of(getActivity(), cleanedUris, type));
2598 }
2599 toggleInputMethod();
2600 return;
2601 }
2602 if (nick != null) {
2603 if (pm) {
2604 Jid jid = conversation.getJid();
2605 try {
2606 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2607 privateMessageWith(next);
2608 } catch (final IllegalArgumentException ignored) {
2609 // do nothing
2610 }
2611 } else {
2612 final MucOptions mucOptions = conversation.getMucOptions();
2613 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2614 highlightInConference(nick);
2615 }
2616 }
2617 } else {
2618 if (text != null && Patterns.URI_GEO.matcher(text).matches()) {
2619 mediaPreviewAdapter.addMediaPreviews(
2620 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
2621 toggleInputMethod();
2622 return;
2623 } else if (text != null && asQuote) {
2624 quoteText(text);
2625 } else {
2626 appendText(text, doNotAppend);
2627 }
2628 }
2629 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
2630 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
2631 return;
2632 }
2633 final Message message =
2634 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2635 if (message != null) {
2636 startDownloadable(message);
2637 }
2638 }
2639
2640 private List<Uri> extractUris(final Bundle extras) {
2641 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2642 if (uris != null) {
2643 return uris;
2644 }
2645 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2646 if (uri != null) {
2647 return Collections.singletonList(uri);
2648 } else {
2649 return null;
2650 }
2651 }
2652
2653 private List<Uri> cleanUris(final List<Uri> uris) {
2654 final Iterator<Uri> iterator = uris.iterator();
2655 while (iterator.hasNext()) {
2656 final Uri uri = iterator.next();
2657 if (FileBackend.dangerousFile(uri)) {
2658 iterator.remove();
2659 Toast.makeText(
2660 requireActivity(),
2661 R.string.security_violation_not_attaching_file,
2662 Toast.LENGTH_SHORT)
2663 .show();
2664 }
2665 }
2666 return uris;
2667 }
2668
2669 private boolean showBlockSubmenu(View view) {
2670 final Jid jid = conversation.getJid();
2671 final boolean showReject =
2672 !conversation.isWithStranger()
2673 && conversation
2674 .getContact()
2675 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2676 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2677 popupMenu.inflate(R.menu.block);
2678 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2679 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2680 popupMenu.setOnMenuItemClickListener(
2681 menuItem -> {
2682 Blockable blockable;
2683 switch (menuItem.getItemId()) {
2684 case R.id.reject:
2685 activity.xmppConnectionService.stopPresenceUpdatesTo(
2686 conversation.getContact());
2687 updateSnackBar(conversation);
2688 return true;
2689 case R.id.block_domain:
2690 blockable =
2691 conversation
2692 .getAccount()
2693 .getRoster()
2694 .getContact(jid.getDomain());
2695 break;
2696 default:
2697 blockable = conversation;
2698 }
2699 BlockContactDialog.show(activity, blockable);
2700 return true;
2701 });
2702 popupMenu.show();
2703 return true;
2704 }
2705
2706 private void updateSnackBar(final Conversation conversation) {
2707 final Account account = conversation.getAccount();
2708 final XmppConnection connection = account.getXmppConnection();
2709 final int mode = conversation.getMode();
2710 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2711 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2712 return;
2713 }
2714 if (account.getStatus() == Account.State.DISABLED) {
2715 showSnackbar(
2716 R.string.this_account_is_disabled,
2717 R.string.enable,
2718 this.mEnableAccountListener);
2719 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
2720 showSnackbar(
2721 R.string.this_account_is_logged_out,
2722 R.string.log_in,
2723 this.mEnableAccountListener);
2724 } else if (conversation.isBlocked()) {
2725 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2726 } else if (contact != null
2727 && !contact.showInRoster()
2728 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2729 showSnackbar(
2730 R.string.contact_added_you,
2731 R.string.add_back,
2732 this.mAddBackClickListener,
2733 this.mLongPressBlockListener);
2734 } else if (contact != null
2735 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2736 showSnackbar(
2737 R.string.contact_asks_for_presence_subscription,
2738 R.string.allow,
2739 this.mAllowPresenceSubscription,
2740 this.mLongPressBlockListener);
2741 } else if (mode == Conversation.MODE_MULTI
2742 && !conversation.getMucOptions().online()
2743 && account.getStatus() == Account.State.ONLINE) {
2744 switch (conversation.getMucOptions().getError()) {
2745 case NICK_IN_USE:
2746 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2747 break;
2748 case NO_RESPONSE:
2749 showSnackbar(R.string.joining_conference, 0, null);
2750 break;
2751 case SERVER_NOT_FOUND:
2752 if (conversation.receivedMessagesCount() > 0) {
2753 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2754 } else {
2755 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2756 }
2757 break;
2758 case REMOTE_SERVER_TIMEOUT:
2759 if (conversation.receivedMessagesCount() > 0) {
2760 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2761 } else {
2762 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2763 }
2764 break;
2765 case PASSWORD_REQUIRED:
2766 showSnackbar(
2767 R.string.conference_requires_password,
2768 R.string.enter_password,
2769 enterPassword);
2770 break;
2771 case BANNED:
2772 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2773 break;
2774 case MEMBERS_ONLY:
2775 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2776 break;
2777 case RESOURCE_CONSTRAINT:
2778 showSnackbar(
2779 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2780 break;
2781 case KICKED:
2782 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2783 break;
2784 case TECHNICAL_PROBLEMS:
2785 showSnackbar(
2786 R.string.conference_technical_problems, R.string.try_again, joinMuc);
2787 break;
2788 case UNKNOWN:
2789 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2790 break;
2791 case INVALID_NICK:
2792 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2793 case SHUTDOWN:
2794 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2795 break;
2796 case DESTROYED:
2797 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2798 break;
2799 case NON_ANONYMOUS:
2800 showSnackbar(
2801 R.string.group_chat_will_make_your_jabber_id_public,
2802 R.string.join,
2803 acceptJoin);
2804 break;
2805 default:
2806 hideSnackbar();
2807 break;
2808 }
2809 } else if (account.hasPendingPgpIntent(conversation)) {
2810 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2811 } else if (connection != null
2812 && connection.getFeatures().blocking()
2813 && conversation.countMessages() != 0
2814 && !conversation.isBlocked()
2815 && conversation.isWithStranger()) {
2816 showSnackbar(
2817 R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2818 } else {
2819 hideSnackbar();
2820 }
2821 }
2822
2823 @Override
2824 public void refresh() {
2825 if (this.binding == null) {
2826 Log.d(
2827 Config.LOGTAG,
2828 "ConversationFragment.refresh() skipped updated because view binding was null");
2829 return;
2830 }
2831 if (this.conversation != null
2832 && this.activity != null
2833 && this.activity.xmppConnectionService != null) {
2834 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2835 activity.onConversationArchived(this.conversation);
2836 return;
2837 }
2838 }
2839 this.refresh(true);
2840 }
2841
2842 private void refresh(boolean notifyConversationRead) {
2843 synchronized (this.messageList) {
2844 if (this.conversation != null) {
2845 conversation.populateWithMessages(this.messageList);
2846 updateSnackBar(conversation);
2847 updateStatusMessages();
2848 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2849 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2850 binding.unreadCountCustomView.setUnreadCount(
2851 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2852 }
2853 this.messageListAdapter.notifyDataSetChanged();
2854 updateChatMsgHint();
2855 if (notifyConversationRead && activity != null) {
2856 binding.messagesView.post(this::fireReadEvent);
2857 }
2858 updateSendButton();
2859 updateEditablity();
2860 }
2861 }
2862 }
2863
2864 protected void messageSent() {
2865 mSendingPgpMessage.set(false);
2866 this.binding.textinput.setText("");
2867 if (conversation.setCorrectingMessage(null)) {
2868 this.binding.textinput.append(conversation.getDraftMessage());
2869 conversation.setDraftMessage(null);
2870 }
2871 storeNextMessage();
2872 updateChatMsgHint();
2873 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2874 final boolean prefScrollToBottom =
2875 p.getBoolean(
2876 "scroll_to_bottom",
2877 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2878 if (prefScrollToBottom || scrolledToBottom()) {
2879 new Handler()
2880 .post(
2881 () -> {
2882 int size = messageList.size();
2883 this.binding.messagesView.setSelection(size - 1);
2884 });
2885 }
2886 }
2887
2888 private boolean storeNextMessage() {
2889 return storeNextMessage(this.binding.textinput.getText().toString());
2890 }
2891
2892 private boolean storeNextMessage(String msg) {
2893 final boolean participating =
2894 conversation.getMode() == Conversational.MODE_SINGLE
2895 || conversation.getMucOptions().participating();
2896 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
2897 && participating
2898 && this.conversation.setNextMessage(msg)) {
2899 this.activity.xmppConnectionService.updateConversation(this.conversation);
2900 return true;
2901 }
2902 return false;
2903 }
2904
2905 public void doneSendingPgpMessage() {
2906 mSendingPgpMessage.set(false);
2907 }
2908
2909 public long getMaxHttpUploadSize(Conversation conversation) {
2910 final XmppConnection connection = conversation.getAccount().getXmppConnection();
2911 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2912 }
2913
2914 private void updateEditablity() {
2915 boolean canWrite =
2916 this.conversation.getMode() == Conversation.MODE_SINGLE
2917 || this.conversation.getMucOptions().participating()
2918 || this.conversation.getNextCounterpart() != null;
2919 this.binding.textinput.setFocusable(canWrite);
2920 this.binding.textinput.setFocusableInTouchMode(canWrite);
2921 this.binding.textSendButton.setEnabled(canWrite);
2922 this.binding.textinput.setCursorVisible(canWrite);
2923 this.binding.textinput.setEnabled(canWrite);
2924 }
2925
2926 public void updateSendButton() {
2927 boolean hasAttachments =
2928 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2929 final Conversation c = this.conversation;
2930 final Presence.Status status;
2931 final String text =
2932 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2933 final SendButtonAction action;
2934 if (hasAttachments) {
2935 action = SendButtonAction.TEXT;
2936 } else {
2937 action = SendButtonTool.getAction(getActivity(), c, text);
2938 }
2939 if (c.getAccount().getStatus() == Account.State.ONLINE) {
2940 if (activity != null
2941 && activity.xmppConnectionService != null
2942 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2943 status = Presence.Status.OFFLINE;
2944 } else if (c.getMode() == Conversation.MODE_SINGLE) {
2945 status = c.getContact().getShownStatus();
2946 } else {
2947 status =
2948 c.getMucOptions().online()
2949 ? Presence.Status.ONLINE
2950 : Presence.Status.OFFLINE;
2951 }
2952 } else {
2953 status = Presence.Status.OFFLINE;
2954 }
2955 this.binding.textSendButton.setTag(action);
2956 this.binding.textSendButton.setIconResource(
2957 SendButtonTool.getSendButtonImageResource(action));
2958 this.binding.textSendButton.setIconTint(
2959 ColorStateList.valueOf(
2960 SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
2961 // TODO send button color
2962 final Activity activity = getActivity();
2963 if (activity != null) {}
2964 }
2965
2966 protected void updateStatusMessages() {
2967 DateSeparator.addAll(this.messageList);
2968 if (showLoadMoreMessages(conversation)) {
2969 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2970 }
2971 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2972 ChatState state = conversation.getIncomingChatState();
2973 if (state == ChatState.COMPOSING) {
2974 this.messageList.add(
2975 Message.createStatusMessage(
2976 conversation,
2977 getString(R.string.contact_is_typing, conversation.getName())));
2978 } else if (state == ChatState.PAUSED) {
2979 this.messageList.add(
2980 Message.createStatusMessage(
2981 conversation,
2982 getString(
2983 R.string.contact_has_stopped_typing,
2984 conversation.getName())));
2985 } else {
2986 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2987 final Message message = this.messageList.get(i);
2988 if (message.getType() != Message.TYPE_STATUS) {
2989 if (message.getStatus() == Message.STATUS_RECEIVED) {
2990 return;
2991 } else {
2992 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
2993 this.messageList.add(
2994 i + 1,
2995 Message.createStatusMessage(
2996 conversation,
2997 getString(
2998 R.string.contact_has_read_up_to_this_point,
2999 conversation.getName())));
3000 return;
3001 }
3002 }
3003 }
3004 }
3005 }
3006 } else {
3007 final MucOptions mucOptions = conversation.getMucOptions();
3008 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3009 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3010 ChatState state = ChatState.COMPOSING;
3011 List<MucOptions.User> users =
3012 conversation.getMucOptions().getUsersWithChatState(state, 5);
3013 if (users.size() == 0) {
3014 state = ChatState.PAUSED;
3015 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3016 }
3017 if (mucOptions.isPrivateAndNonAnonymous()) {
3018 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3019 final Set<ReadByMarker> markersForMessage =
3020 messageList.get(i).getReadByMarkers();
3021 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3022 for (ReadByMarker marker : markersForMessage) {
3023 if (!ReadByMarker.contains(marker, addedMarkers)) {
3024 addedMarkers.add(
3025 marker); // may be put outside this condition. set should do
3026 // dedup anyway
3027 MucOptions.User user = mucOptions.findUser(marker);
3028 if (user != null && !users.contains(user)) {
3029 shownMarkers.add(user);
3030 }
3031 }
3032 }
3033 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3034 final Message statusMessage;
3035 final int size = shownMarkers.size();
3036 if (size > 1) {
3037 final String body;
3038 if (size <= 4) {
3039 body =
3040 getString(
3041 R.string.contacts_have_read_up_to_this_point,
3042 UIHelper.concatNames(shownMarkers));
3043 } else if (ReadByMarker.allUsersRepresented(
3044 allUsers, markersForMessage, markerForSender)) {
3045 body = getString(R.string.everyone_has_read_up_to_this_point);
3046 } else {
3047 body =
3048 getString(
3049 R.string.contacts_and_n_more_have_read_up_to_this_point,
3050 UIHelper.concatNames(shownMarkers, 3),
3051 size - 3);
3052 }
3053 statusMessage = Message.createStatusMessage(conversation, body);
3054 statusMessage.setCounterparts(shownMarkers);
3055 } else if (size == 1) {
3056 statusMessage =
3057 Message.createStatusMessage(
3058 conversation,
3059 getString(
3060 R.string.contact_has_read_up_to_this_point,
3061 UIHelper.getDisplayName(shownMarkers.get(0))));
3062 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3063 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3064 } else {
3065 statusMessage = null;
3066 }
3067 if (statusMessage != null) {
3068 this.messageList.add(i + 1, statusMessage);
3069 }
3070 addedMarkers.add(markerForSender);
3071 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3072 break;
3073 }
3074 }
3075 }
3076 if (users.size() > 0) {
3077 Message statusMessage;
3078 if (users.size() == 1) {
3079 MucOptions.User user = users.get(0);
3080 int id =
3081 state == ChatState.COMPOSING
3082 ? R.string.contact_is_typing
3083 : R.string.contact_has_stopped_typing;
3084 statusMessage =
3085 Message.createStatusMessage(
3086 conversation, getString(id, UIHelper.getDisplayName(user)));
3087 statusMessage.setTrueCounterpart(user.getRealJid());
3088 statusMessage.setCounterpart(user.getFullJid());
3089 } else {
3090 int id =
3091 state == ChatState.COMPOSING
3092 ? R.string.contacts_are_typing
3093 : R.string.contacts_have_stopped_typing;
3094 statusMessage =
3095 Message.createStatusMessage(
3096 conversation, getString(id, UIHelper.concatNames(users)));
3097 statusMessage.setCounterparts(users);
3098 }
3099 this.messageList.add(statusMessage);
3100 }
3101 }
3102 }
3103
3104 private void stopScrolling() {
3105 long now = SystemClock.uptimeMillis();
3106 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3107 binding.messagesView.dispatchTouchEvent(cancel);
3108 }
3109
3110 private boolean showLoadMoreMessages(final Conversation c) {
3111 if (activity == null || activity.xmppConnectionService == null) {
3112 return false;
3113 }
3114 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3115 final MessageArchiveService service =
3116 activity.xmppConnectionService.getMessageArchiveService();
3117 return mam
3118 && (c.getLastClearHistory().getTimestamp() != 0
3119 || (c.countMessages() == 0
3120 && c.messagesLoaded.get()
3121 && c.hasMessagesLeftOnServer()
3122 && !service.queryInProgress(c)));
3123 }
3124
3125 private boolean hasMamSupport(final Conversation c) {
3126 if (c.getMode() == Conversation.MODE_SINGLE) {
3127 final XmppConnection connection = c.getAccount().getXmppConnection();
3128 return connection != null && connection.getFeatures().mam();
3129 } else {
3130 return c.getMucOptions().mamSupport();
3131 }
3132 }
3133
3134 protected void showSnackbar(
3135 final int message, final int action, final OnClickListener clickListener) {
3136 showSnackbar(message, action, clickListener, null);
3137 }
3138
3139 protected void showSnackbar(
3140 final int message,
3141 final int action,
3142 final OnClickListener clickListener,
3143 final View.OnLongClickListener longClickListener) {
3144 this.binding.snackbar.setVisibility(View.VISIBLE);
3145 this.binding.snackbar.setOnClickListener(null);
3146 this.binding.snackbarMessage.setText(message);
3147 this.binding.snackbarMessage.setOnClickListener(null);
3148 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3149 if (action != 0) {
3150 this.binding.snackbarAction.setText(action);
3151 }
3152 this.binding.snackbarAction.setOnClickListener(clickListener);
3153 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3154 }
3155
3156 protected void hideSnackbar() {
3157 this.binding.snackbar.setVisibility(View.GONE);
3158 }
3159
3160 protected void sendMessage(Message message) {
3161 activity.xmppConnectionService.sendMessage(message);
3162 messageSent();
3163 }
3164
3165 protected void sendPgpMessage(final Message message) {
3166 final XmppConnectionService xmppService = activity.xmppConnectionService;
3167 final Contact contact = message.getConversation().getContact();
3168 if (!activity.hasPgp()) {
3169 activity.showInstallPgpDialog();
3170 return;
3171 }
3172 if (conversation.getAccount().getPgpSignature() == null) {
3173 activity.announcePgp(
3174 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3175 return;
3176 }
3177 if (!mSendingPgpMessage.compareAndSet(false, true)) {
3178 Log.d(Config.LOGTAG, "sending pgp message already in progress");
3179 }
3180 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3181 if (contact.getPgpKeyId() != 0) {
3182 xmppService
3183 .getPgpEngine()
3184 .hasKey(
3185 contact,
3186 new UiCallback<Contact>() {
3187
3188 @Override
3189 public void userInputRequired(
3190 PendingIntent pi, Contact contact) {
3191 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3192 }
3193
3194 @Override
3195 public void success(Contact contact) {
3196 encryptTextMessage(message);
3197 }
3198
3199 @Override
3200 public void error(int error, Contact contact) {
3201 activity.runOnUiThread(
3202 () ->
3203 Toast.makeText(
3204 activity,
3205 R.string
3206 .unable_to_connect_to_keychain,
3207 Toast.LENGTH_SHORT)
3208 .show());
3209 mSendingPgpMessage.set(false);
3210 }
3211 });
3212
3213 } else {
3214 showNoPGPKeyDialog(
3215 false,
3216 (dialog, which) -> {
3217 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3218 xmppService.updateConversation(conversation);
3219 message.setEncryption(Message.ENCRYPTION_NONE);
3220 xmppService.sendMessage(message);
3221 messageSent();
3222 });
3223 }
3224 } else {
3225 if (conversation.getMucOptions().pgpKeysInUse()) {
3226 if (!conversation.getMucOptions().everybodyHasKeys()) {
3227 Toast warning =
3228 Toast.makeText(
3229 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3230 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3231 warning.show();
3232 }
3233 encryptTextMessage(message);
3234 } else {
3235 showNoPGPKeyDialog(
3236 true,
3237 (dialog, which) -> {
3238 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3239 message.setEncryption(Message.ENCRYPTION_NONE);
3240 xmppService.updateConversation(conversation);
3241 xmppService.sendMessage(message);
3242 messageSent();
3243 });
3244 }
3245 }
3246 }
3247
3248 public void encryptTextMessage(Message message) {
3249 activity.xmppConnectionService
3250 .getPgpEngine()
3251 .encrypt(
3252 message,
3253 new UiCallback<Message>() {
3254
3255 @Override
3256 public void userInputRequired(PendingIntent pi, Message message) {
3257 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3258 }
3259
3260 @Override
3261 public void success(Message message) {
3262 // TODO the following two call can be made before the callback
3263 getActivity().runOnUiThread(() -> messageSent());
3264 }
3265
3266 @Override
3267 public void error(final int error, Message message) {
3268 getActivity()
3269 .runOnUiThread(
3270 () -> {
3271 doneSendingPgpMessage();
3272 Toast.makeText(
3273 getActivity(),
3274 error == 0
3275 ? R.string
3276 .unable_to_connect_to_keychain
3277 : error,
3278 Toast.LENGTH_SHORT)
3279 .show();
3280 });
3281 }
3282 });
3283 }
3284
3285 public void showNoPGPKeyDialog(
3286 final boolean plural, final DialogInterface.OnClickListener listener) {
3287 final MaterialAlertDialogBuilder builder =
3288 new MaterialAlertDialogBuilder(requireActivity());
3289 if (plural) {
3290 builder.setTitle(getString(R.string.no_pgp_keys));
3291 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3292 } else {
3293 builder.setTitle(getString(R.string.no_pgp_key));
3294 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3295 }
3296 builder.setNegativeButton(getString(R.string.cancel), null);
3297 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3298 builder.create().show();
3299 }
3300
3301 public void appendText(String text, final boolean doNotAppend) {
3302 if (text == null) {
3303 return;
3304 }
3305 final Editable editable = this.binding.textinput.getText();
3306 String previous = editable == null ? "" : editable.toString();
3307 if (doNotAppend && !TextUtils.isEmpty(previous)) {
3308 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3309 .show();
3310 return;
3311 }
3312 if (UIHelper.isLastLineQuote(previous)) {
3313 text = '\n' + text;
3314 } else if (previous.length() != 0
3315 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3316 text = " " + text;
3317 }
3318 this.binding.textinput.append(text);
3319 }
3320
3321 @Override
3322 public boolean onEnterPressed(final boolean isCtrlPressed) {
3323 if (isCtrlPressed || enterIsSend()) {
3324 sendMessage();
3325 return true;
3326 }
3327 return false;
3328 }
3329
3330 private boolean enterIsSend() {
3331 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3332 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3333 }
3334
3335 public boolean onArrowUpCtrlPressed() {
3336 final Message lastEditableMessage =
3337 conversation == null ? null : conversation.getLastEditableMessage();
3338 if (lastEditableMessage != null) {
3339 correctMessage(lastEditableMessage);
3340 return true;
3341 } else {
3342 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3343 .show();
3344 return false;
3345 }
3346 }
3347
3348 @Override
3349 public void onTypingStarted() {
3350 final XmppConnectionService service =
3351 activity == null ? null : activity.xmppConnectionService;
3352 if (service == null) {
3353 return;
3354 }
3355 final Account.State status = conversation.getAccount().getStatus();
3356 if (status == Account.State.ONLINE
3357 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3358 service.sendChatState(conversation);
3359 }
3360 runOnUiThread(this::updateSendButton);
3361 }
3362
3363 @Override
3364 public void onTypingStopped() {
3365 final XmppConnectionService service =
3366 activity == null ? null : activity.xmppConnectionService;
3367 if (service == null) {
3368 return;
3369 }
3370 final Account.State status = conversation.getAccount().getStatus();
3371 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3372 service.sendChatState(conversation);
3373 }
3374 }
3375
3376 @Override
3377 public void onTextDeleted() {
3378 final XmppConnectionService service =
3379 activity == null ? null : activity.xmppConnectionService;
3380 if (service == null) {
3381 return;
3382 }
3383 final Account.State status = conversation.getAccount().getStatus();
3384 if (status == Account.State.ONLINE
3385 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3386 service.sendChatState(conversation);
3387 }
3388 if (storeNextMessage()) {
3389 runOnUiThread(
3390 () -> {
3391 if (activity == null) {
3392 return;
3393 }
3394 activity.onConversationsListItemUpdated();
3395 });
3396 }
3397 runOnUiThread(this::updateSendButton);
3398 }
3399
3400 @Override
3401 public void onTextChanged() {
3402 if (conversation != null && conversation.getCorrectingMessage() != null) {
3403 runOnUiThread(this::updateSendButton);
3404 }
3405 }
3406
3407 @Override
3408 public boolean onTabPressed(boolean repeated) {
3409 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3410 return false;
3411 }
3412 if (repeated) {
3413 completionIndex++;
3414 } else {
3415 lastCompletionLength = 0;
3416 completionIndex = 0;
3417 final String content = this.binding.textinput.getText().toString();
3418 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
3419 int start =
3420 lastCompletionCursor > 0
3421 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
3422 : 0;
3423 firstWord = start == 0;
3424 incomplete = content.substring(start, lastCompletionCursor);
3425 }
3426 List<String> completions = new ArrayList<>();
3427 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
3428 String name = user.getName();
3429 if (name != null && name.startsWith(incomplete)) {
3430 completions.add(name + (firstWord ? ": " : " "));
3431 }
3432 }
3433 Collections.sort(completions);
3434 if (completions.size() > completionIndex) {
3435 String completion = completions.get(completionIndex).substring(incomplete.length());
3436 this.binding
3437 .textinput
3438 .getEditableText()
3439 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3440 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
3441 lastCompletionLength = completion.length();
3442 } else {
3443 completionIndex = -1;
3444 this.binding
3445 .textinput
3446 .getEditableText()
3447 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3448 lastCompletionLength = 0;
3449 }
3450 return true;
3451 }
3452
3453 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
3454 try {
3455 getActivity()
3456 .startIntentSenderForResult(
3457 pendingIntent.getIntentSender(),
3458 requestCode,
3459 null,
3460 0,
3461 0,
3462 0,
3463 Compatibility.pgpStartIntentSenderOptions());
3464 } catch (final SendIntentException ignored) {
3465 }
3466 }
3467
3468 @Override
3469 public void onBackendConnected() {
3470 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
3471 String uuid = pendingConversationsUuid.pop();
3472 if (uuid != null) {
3473 if (!findAndReInitByUuidOrArchive(uuid)) {
3474 return;
3475 }
3476 } else {
3477 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
3478 clearPending();
3479 activity.onConversationArchived(conversation);
3480 return;
3481 }
3482 }
3483 ActivityResult activityResult = postponedActivityResult.pop();
3484 if (activityResult != null) {
3485 handleActivityResult(activityResult);
3486 }
3487 clearPending();
3488 }
3489
3490 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
3491 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
3492 if (conversation == null) {
3493 clearPending();
3494 activity.onConversationArchived(null);
3495 return false;
3496 }
3497 reInit(conversation);
3498 ScrollState scrollState = pendingScrollState.pop();
3499 String lastMessageUuid = pendingLastMessageUuid.pop();
3500 List<Attachment> attachments = pendingMediaPreviews.pop();
3501 if (scrollState != null) {
3502 setScrollPosition(scrollState, lastMessageUuid);
3503 }
3504 if (attachments != null && attachments.size() > 0) {
3505 Log.d(Config.LOGTAG, "had attachments on restore");
3506 mediaPreviewAdapter.addMediaPreviews(attachments);
3507 toggleInputMethod();
3508 }
3509 return true;
3510 }
3511
3512 private void clearPending() {
3513 if (postponedActivityResult.clear()) {
3514 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
3515 if (pendingTakePhotoUri.clear()) {
3516 Log.e(Config.LOGTAG, "cleared pending photo uri");
3517 }
3518 }
3519 if (pendingScrollState.clear()) {
3520 Log.e(Config.LOGTAG, "cleared scroll state");
3521 }
3522 if (pendingConversationsUuid.clear()) {
3523 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
3524 }
3525 if (pendingMediaPreviews.clear()) {
3526 Log.e(Config.LOGTAG, "cleared pending media previews");
3527 }
3528 }
3529
3530 public Conversation getConversation() {
3531 return conversation;
3532 }
3533
3534 @Override
3535 public void onContactPictureLongClicked(View v, final Message message) {
3536 final String fingerprint;
3537 if (message.getEncryption() == Message.ENCRYPTION_PGP
3538 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3539 fingerprint = "pgp";
3540 } else {
3541 fingerprint = message.getFingerprint();
3542 }
3543 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
3544 final Contact contact = message.getContact();
3545 if (message.getStatus() <= Message.STATUS_RECEIVED
3546 && (contact == null || !contact.isSelf())) {
3547 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
3548 final Jid cp = message.getCounterpart();
3549 if (cp == null || cp.isBareJid()) {
3550 return;
3551 }
3552 final Jid tcp = message.getTrueCounterpart();
3553 final User userByRealJid =
3554 tcp != null
3555 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
3556 : null;
3557 final User user =
3558 userByRealJid != null
3559 ? userByRealJid
3560 : conversation.getMucOptions().findUserByFullJid(cp);
3561 popupMenu.inflate(R.menu.muc_details_context);
3562 final Menu menu = popupMenu.getMenu();
3563 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
3564 activity, menu, conversation, user);
3565 popupMenu.setOnMenuItemClickListener(
3566 menuItem ->
3567 MucDetailsContextMenuHelper.onContextItemSelected(
3568 menuItem, user, activity, fingerprint));
3569 } else {
3570 popupMenu.inflate(R.menu.one_on_one_context);
3571 popupMenu.setOnMenuItemClickListener(
3572 item -> {
3573 switch (item.getItemId()) {
3574 case R.id.action_contact_details:
3575 activity.switchToContactDetails(
3576 message.getContact(), fingerprint);
3577 break;
3578 case R.id.action_show_qr_code:
3579 activity.showQrCode(
3580 "xmpp:"
3581 + message.getContact()
3582 .getJid()
3583 .asBareJid()
3584 .toString());
3585 break;
3586 }
3587 return true;
3588 });
3589 }
3590 } else {
3591 popupMenu.inflate(R.menu.account_context);
3592 final Menu menu = popupMenu.getMenu();
3593 menu.findItem(R.id.action_manage_accounts)
3594 .setVisible(QuickConversationsService.isConversations());
3595 popupMenu.setOnMenuItemClickListener(
3596 item -> {
3597 final XmppActivity activity = this.activity;
3598 if (activity == null) {
3599 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
3600 return true;
3601 }
3602 switch (item.getItemId()) {
3603 case R.id.action_show_qr_code:
3604 activity.showQrCode(conversation.getAccount().getShareableUri());
3605 break;
3606 case R.id.action_account_details:
3607 activity.switchToAccount(
3608 message.getConversation().getAccount(), fingerprint);
3609 break;
3610 case R.id.action_manage_accounts:
3611 AccountUtils.launchManageAccounts(activity);
3612 break;
3613 }
3614 return true;
3615 });
3616 }
3617 popupMenu.show();
3618 }
3619
3620 @Override
3621 public void onContactPictureClicked(Message message) {
3622 String fingerprint;
3623 if (message.getEncryption() == Message.ENCRYPTION_PGP
3624 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3625 fingerprint = "pgp";
3626 } else {
3627 fingerprint = message.getFingerprint();
3628 }
3629 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
3630 if (received) {
3631 if (message.getConversation() instanceof Conversation
3632 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
3633 Jid tcp = message.getTrueCounterpart();
3634 Jid user = message.getCounterpart();
3635 if (user != null && !user.isBareJid()) {
3636 final MucOptions mucOptions =
3637 ((Conversation) message.getConversation()).getMucOptions();
3638 if (mucOptions.participating()
3639 || ((Conversation) message.getConversation()).getNextCounterpart()
3640 != null) {
3641 if (!mucOptions.isUserInRoom(user)
3642 && mucOptions.findUserByRealJid(
3643 tcp == null ? null : tcp.asBareJid())
3644 == null) {
3645 Toast.makeText(
3646 getActivity(),
3647 activity.getString(
3648 R.string.user_has_left_conference,
3649 user.getResource()),
3650 Toast.LENGTH_SHORT)
3651 .show();
3652 }
3653 highlightInConference(user.getResource());
3654 } else {
3655 Toast.makeText(
3656 getActivity(),
3657 R.string.you_are_not_participating,
3658 Toast.LENGTH_SHORT)
3659 .show();
3660 }
3661 }
3662 return;
3663 } else {
3664 if (!message.getContact().isSelf()) {
3665 activity.switchToContactDetails(message.getContact(), fingerprint);
3666 return;
3667 }
3668 }
3669 }
3670 activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
3671 }
3672
3673 private Activity requireActivity() {
3674 final Activity activity = getActivity();
3675 if (activity == null) {
3676 throw new IllegalStateException("Activity not attached");
3677 }
3678 return activity;
3679 }
3680}