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