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