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