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.Presence;
85import eu.siacs.conversations.entities.ReadByMarker;
86import eu.siacs.conversations.entities.Transferable;
87import eu.siacs.conversations.entities.TransferablePlaceholder;
88import eu.siacs.conversations.http.HttpDownloadConnection;
89import eu.siacs.conversations.persistance.FileBackend;
90import eu.siacs.conversations.services.CallIntegrationConnectionService;
91import eu.siacs.conversations.services.MessageArchiveService;
92import eu.siacs.conversations.services.QuickConversationsService;
93import eu.siacs.conversations.services.XmppConnectionService;
94import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
95import eu.siacs.conversations.ui.adapter.MessageAdapter;
96import eu.siacs.conversations.ui.util.ActivityResult;
97import eu.siacs.conversations.ui.util.Attachment;
98import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
99import eu.siacs.conversations.ui.util.DateSeparator;
100import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
101import eu.siacs.conversations.ui.util.ListViewUtils;
102import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
103import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
104import eu.siacs.conversations.ui.util.PendingItem;
105import eu.siacs.conversations.ui.util.PresenceSelector;
106import eu.siacs.conversations.ui.util.ScrollState;
107import eu.siacs.conversations.ui.util.SendButtonAction;
108import eu.siacs.conversations.ui.util.SendButtonTool;
109import eu.siacs.conversations.ui.util.ShareUtil;
110import eu.siacs.conversations.ui.util.ViewUtil;
111import eu.siacs.conversations.ui.widget.EditMessage;
112import eu.siacs.conversations.utils.AccountUtils;
113import eu.siacs.conversations.utils.Compatibility;
114import eu.siacs.conversations.utils.GeoHelper;
115import eu.siacs.conversations.utils.MessageUtils;
116import eu.siacs.conversations.utils.NickValidityChecker;
117import eu.siacs.conversations.utils.PermissionUtils;
118import eu.siacs.conversations.utils.QuickLoader;
119import eu.siacs.conversations.utils.StylingHelper;
120import eu.siacs.conversations.utils.TimeFrameUtils;
121import eu.siacs.conversations.utils.UIHelper;
122import eu.siacs.conversations.xmpp.Jid;
123import eu.siacs.conversations.xmpp.XmppConnection;
124import eu.siacs.conversations.xmpp.chatstate.ChatState;
125import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
126import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
127import eu.siacs.conversations.xmpp.jingle.JingleFileTransferConnection;
128import eu.siacs.conversations.xmpp.jingle.Media;
129import eu.siacs.conversations.xmpp.jingle.OngoingRtpSession;
130import eu.siacs.conversations.xmpp.jingle.RtpCapability;
131import java.util.ArrayList;
132import java.util.Arrays;
133import java.util.Collection;
134import java.util.Collections;
135import java.util.HashSet;
136import java.util.Iterator;
137import java.util.List;
138import java.util.Set;
139import java.util.UUID;
140import java.util.concurrent.atomic.AtomicBoolean;
141
142public class ConversationFragment extends XmppFragment
143 implements EditMessage.KeyboardListener,
144 MessageAdapter.OnContactPictureLongClicked,
145 MessageAdapter.OnContactPictureClicked {
146
147 public static final int REQUEST_SEND_MESSAGE = 0x0201;
148 public static final int REQUEST_DECRYPT_PGP = 0x0202;
149 public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
150 public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
151 public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209;
152 public static final int REQUEST_START_DOWNLOAD = 0x0210;
153 public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
154 public static final int REQUEST_COMMIT_ATTACHMENTS = 0x0212;
155 public static final int REQUEST_START_AUDIO_CALL = 0x213;
156 public static final int REQUEST_START_VIDEO_CALL = 0x214;
157 public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
158 public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
159 public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
160 public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
161 public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
162 public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
163 public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
164
165 public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
166 public static final String STATE_CONVERSATION_UUID =
167 ConversationFragment.class.getName() + ".uuid";
168 public static final String STATE_SCROLL_POSITION =
169 ConversationFragment.class.getName() + ".scroll_position";
170 public static final String STATE_PHOTO_URI =
171 ConversationFragment.class.getName() + ".media_previews";
172 public static final String STATE_MEDIA_PREVIEWS =
173 ConversationFragment.class.getName() + ".take_photo_uri";
174 private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid";
175
176 private final List<Message> messageList = new ArrayList<>();
177 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
178 private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
179 private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>();
180 private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
181 private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
182 private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
183 private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>();
184 private final PendingItem<Message> pendingMessage = new PendingItem<>();
185 public Uri mPendingEditorContent = null;
186 protected MessageAdapter messageListAdapter;
187 private MediaPreviewAdapter mediaPreviewAdapter;
188 private String lastMessageUuid = null;
189 private Conversation conversation;
190 private FragmentConversationBinding binding;
191 private Toast messageLoaderToast;
192 private ConversationsActivity activity;
193 private boolean reInitRequiredOnStart = true;
194 private final OnClickListener clickToMuc =
195 new OnClickListener() {
196
197 @Override
198 public void onClick(View v) {
199 ConferenceDetailsActivity.open(getActivity(), conversation);
200 }
201 };
202 private final OnClickListener leaveMuc =
203 new OnClickListener() {
204
205 @Override
206 public void onClick(View v) {
207 activity.xmppConnectionService.archiveConversation(conversation);
208 }
209 };
210 private final OnClickListener joinMuc =
211 new OnClickListener() {
212
213 @Override
214 public void onClick(View v) {
215 activity.xmppConnectionService.joinMuc(conversation);
216 }
217 };
218
219 private final OnClickListener acceptJoin =
220 new OnClickListener() {
221 @Override
222 public void onClick(View v) {
223 conversation.setAttribute("accept_non_anonymous", true);
224 activity.xmppConnectionService.updateConversation(conversation);
225 activity.xmppConnectionService.joinMuc(conversation);
226 }
227 };
228
229 private final OnClickListener enterPassword =
230 new OnClickListener() {
231
232 @Override
233 public void onClick(View v) {
234 MucOptions muc = conversation.getMucOptions();
235 String password = muc.getPassword();
236 if (password == null) {
237 password = "";
238 }
239 activity.quickPasswordEdit(
240 password,
241 value -> {
242 activity.xmppConnectionService.providePasswordForMuc(
243 conversation, value);
244 return null;
245 });
246 }
247 };
248 private final OnScrollListener mOnScrollListener =
249 new OnScrollListener() {
250
251 @Override
252 public void onScrollStateChanged(AbsListView view, int scrollState) {
253 if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
254 fireReadEvent();
255 }
256 }
257
258 @Override
259 public void onScroll(
260 final AbsListView view,
261 int firstVisibleItem,
262 int visibleItemCount,
263 int totalItemCount) {
264 toggleScrollDownButton(view);
265 synchronized (ConversationFragment.this.messageList) {
266 if (firstVisibleItem < 5
267 && conversation != null
268 && conversation.messagesLoaded.compareAndSet(true, false)
269 && messageList.size() > 0) {
270 long timestamp;
271 if (messageList.get(0).getType() == Message.TYPE_STATUS
272 && messageList.size() >= 2) {
273 timestamp = messageList.get(1).getTimeSent();
274 } else {
275 timestamp = messageList.get(0).getTimeSent();
276 }
277 activity.xmppConnectionService.loadMoreMessages(
278 conversation,
279 timestamp,
280 new XmppConnectionService.OnMoreMessagesLoaded() {
281 @Override
282 public void onMoreMessagesLoaded(
283 final int c, final Conversation conversation) {
284 if (ConversationFragment.this.conversation
285 != conversation) {
286 conversation.messagesLoaded.set(true);
287 return;
288 }
289 runOnUiThread(
290 () -> {
291 synchronized (messageList) {
292 final int oldPosition =
293 binding.messagesView
294 .getFirstVisiblePosition();
295 Message message = null;
296 int childPos;
297 for (childPos = 0;
298 childPos + oldPosition
299 < messageList.size();
300 ++childPos) {
301 message =
302 messageList.get(
303 oldPosition
304 + childPos);
305 if (message.getType()
306 != Message.TYPE_STATUS) {
307 break;
308 }
309 }
310 final String uuid =
311 message != null
312 ? message.getUuid()
313 : null;
314 View v =
315 binding.messagesView.getChildAt(
316 childPos);
317 final int pxOffset =
318 (v == null) ? 0 : v.getTop();
319 ConversationFragment.this.conversation
320 .populateWithMessages(
321 ConversationFragment
322 .this
323 .messageList);
324 try {
325 updateStatusMessages();
326 } catch (IllegalStateException e) {
327 Log.d(
328 Config.LOGTAG,
329 "caught illegal state"
330 + " exception while"
331 + " updating status"
332 + " messages");
333 }
334 messageListAdapter
335 .notifyDataSetChanged();
336 int pos =
337 Math.max(
338 getIndexOf(
339 uuid,
340 messageList),
341 0);
342 binding.messagesView
343 .setSelectionFromTop(
344 pos, pxOffset);
345 if (messageLoaderToast != null) {
346 messageLoaderToast.cancel();
347 }
348 conversation.messagesLoaded.set(true);
349 }
350 });
351 }
352
353 @Override
354 public void informUser(final int resId) {
355
356 runOnUiThread(
357 () -> {
358 if (messageLoaderToast != null) {
359 messageLoaderToast.cancel();
360 }
361 if (ConversationFragment.this.conversation
362 != conversation) {
363 return;
364 }
365 messageLoaderToast =
366 Toast.makeText(
367 view.getContext(),
368 resId,
369 Toast.LENGTH_LONG);
370 messageLoaderToast.show();
371 });
372 }
373 });
374 }
375 }
376 }
377 };
378 private final EditMessage.OnCommitContentListener mEditorContentListener =
379 new EditMessage.OnCommitContentListener() {
380 @Override
381 public boolean onCommitContent(
382 InputContentInfoCompat inputContentInfo,
383 int flags,
384 Bundle opts,
385 String[] contentMimeTypes) {
386 // try to get permission to read the image, if applicable
387 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION)
388 != 0) {
389 try {
390 inputContentInfo.requestPermission();
391 } catch (Exception e) {
392 Log.e(
393 Config.LOGTAG,
394 "InputContentInfoCompat#requestPermission() failed.",
395 e);
396 Toast.makeText(
397 getActivity(),
398 activity.getString(
399 R.string.no_permission_to_access_x,
400 inputContentInfo.getDescription()),
401 Toast.LENGTH_LONG)
402 .show();
403 return false;
404 }
405 }
406 if (hasPermissions(
407 REQUEST_ADD_EDITOR_CONTENT,
408 Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
409 attachEditorContentToConversation(inputContentInfo.getContentUri());
410 } else {
411 mPendingEditorContent = inputContentInfo.getContentUri();
412 }
413 return true;
414 }
415 };
416 private Message selectedMessage;
417 private final OnClickListener mEnableAccountListener =
418 new OnClickListener() {
419 @Override
420 public void onClick(View v) {
421 final Account account = conversation == null ? null : conversation.getAccount();
422 if (account != null) {
423 account.setOption(Account.OPTION_SOFT_DISABLED, false);
424 account.setOption(Account.OPTION_DISABLED, false);
425 activity.xmppConnectionService.updateAccount(account);
426 }
427 }
428 };
429 private final OnClickListener mUnblockClickListener =
430 new OnClickListener() {
431 @Override
432 public void onClick(final View v) {
433 v.post(() -> v.setVisibility(View.INVISIBLE));
434 if (conversation.isDomainBlocked()) {
435 BlockContactDialog.show(activity, conversation);
436 } else {
437 unblockConversation(conversation);
438 }
439 }
440 };
441 private final OnClickListener mBlockClickListener = this::showBlockSubmenu;
442 private final OnClickListener mAddBackClickListener =
443 new OnClickListener() {
444
445 @Override
446 public void onClick(View v) {
447 final Contact contact = conversation == null ? null : conversation.getContact();
448 if (contact != null) {
449 activity.xmppConnectionService.createContact(contact, true);
450 activity.switchToContactDetails(contact);
451 }
452 }
453 };
454 private final View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
455 private final OnClickListener mAllowPresenceSubscription =
456 new OnClickListener() {
457 @Override
458 public void onClick(View v) {
459 final Contact contact = conversation == null ? null : conversation.getContact();
460 if (contact != null) {
461 activity.xmppConnectionService.sendPresencePacket(
462 contact.getAccount(),
463 activity.xmppConnectionService
464 .getPresenceGenerator()
465 .sendPresenceUpdatesTo(contact));
466 hideSnackbar();
467 }
468 }
469 };
470 protected OnClickListener clickToDecryptListener =
471 new OnClickListener() {
472
473 @Override
474 public void onClick(View v) {
475 PendingIntent pendingIntent =
476 conversation.getAccount().getPgpDecryptionService().getPendingIntent();
477 if (pendingIntent != null) {
478 try {
479 getActivity()
480 .startIntentSenderForResult(
481 pendingIntent.getIntentSender(),
482 REQUEST_DECRYPT_PGP,
483 null,
484 0,
485 0,
486 0,
487 Compatibility.pgpStartIntentSenderOptions());
488 } catch (SendIntentException e) {
489 Toast.makeText(
490 getActivity(),
491 R.string.unable_to_connect_to_keychain,
492 Toast.LENGTH_SHORT)
493 .show();
494 conversation
495 .getAccount()
496 .getPgpDecryptionService()
497 .continueDecryption(true);
498 }
499 }
500 updateSnackBar(conversation);
501 }
502 };
503 private final AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
504 private final OnEditorActionListener mEditorActionListener =
505 (v, actionId, event) -> {
506 if (actionId == EditorInfo.IME_ACTION_SEND) {
507 InputMethodManager imm =
508 (InputMethodManager)
509 activity.getSystemService(Context.INPUT_METHOD_SERVICE);
510 if (imm != null && imm.isFullscreenMode()) {
511 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
512 }
513 sendMessage();
514 return true;
515 } else {
516 return false;
517 }
518 };
519 private final OnClickListener mScrollButtonListener =
520 new OnClickListener() {
521
522 @Override
523 public void onClick(View v) {
524 stopScrolling();
525 setSelection(binding.messagesView.getCount() - 1, true);
526 }
527 };
528 private final OnClickListener mSendButtonListener =
529 new OnClickListener() {
530
531 @Override
532 public void onClick(View v) {
533 Object tag = v.getTag();
534 if (tag instanceof SendButtonAction) {
535 SendButtonAction action = (SendButtonAction) tag;
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 && (!xmppConnection
2234 .getFeatures()
2235 .httpUpload(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(Conversation conversation) {
2922 final XmppConnection connection = conversation.getAccount().getXmppConnection();
2923 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2924 }
2925
2926 private void updateEditablity() {
2927 boolean canWrite =
2928 this.conversation.getMode() == Conversation.MODE_SINGLE
2929 || this.conversation.getMucOptions().participating()
2930 || this.conversation.getNextCounterpart() != null;
2931 this.binding.textinput.setFocusable(canWrite);
2932 this.binding.textinput.setFocusableInTouchMode(canWrite);
2933 this.binding.textSendButton.setEnabled(canWrite);
2934 this.binding.textinput.setCursorVisible(canWrite);
2935 this.binding.textinput.setEnabled(canWrite);
2936 }
2937
2938 public void updateSendButton() {
2939 boolean hasAttachments =
2940 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2941 final Conversation c = this.conversation;
2942 final Presence.Status status;
2943 final String text =
2944 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2945 final SendButtonAction action;
2946 if (hasAttachments) {
2947 action = SendButtonAction.TEXT;
2948 } else {
2949 action = SendButtonTool.getAction(getActivity(), c, text);
2950 }
2951 if (c.getAccount().getStatus() == Account.State.ONLINE) {
2952 if (activity != null
2953 && activity.xmppConnectionService != null
2954 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2955 status = Presence.Status.OFFLINE;
2956 } else if (c.getMode() == Conversation.MODE_SINGLE) {
2957 status = c.getContact().getShownStatus();
2958 } else {
2959 status =
2960 c.getMucOptions().online()
2961 ? Presence.Status.ONLINE
2962 : Presence.Status.OFFLINE;
2963 }
2964 } else {
2965 status = Presence.Status.OFFLINE;
2966 }
2967 this.binding.textSendButton.setTag(action);
2968 this.binding.textSendButton.setIconResource(
2969 SendButtonTool.getSendButtonImageResource(action));
2970 this.binding.textSendButton.setIconTint(
2971 ColorStateList.valueOf(
2972 SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
2973 // TODO send button color
2974 final Activity activity = getActivity();
2975 if (activity != null) {}
2976 }
2977
2978 protected void updateStatusMessages() {
2979 DateSeparator.addAll(this.messageList);
2980 if (showLoadMoreMessages(conversation)) {
2981 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2982 }
2983 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2984 ChatState state = conversation.getIncomingChatState();
2985 if (state == ChatState.COMPOSING) {
2986 this.messageList.add(
2987 Message.createStatusMessage(
2988 conversation,
2989 getString(R.string.contact_is_typing, conversation.getName())));
2990 } else if (state == ChatState.PAUSED) {
2991 this.messageList.add(
2992 Message.createStatusMessage(
2993 conversation,
2994 getString(
2995 R.string.contact_has_stopped_typing,
2996 conversation.getName())));
2997 } else {
2998 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2999 final Message message = this.messageList.get(i);
3000 if (message.getType() != Message.TYPE_STATUS) {
3001 if (message.getStatus() == Message.STATUS_RECEIVED) {
3002 return;
3003 } else {
3004 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3005 this.messageList.add(
3006 i + 1,
3007 Message.createStatusMessage(
3008 conversation,
3009 getString(
3010 R.string.contact_has_read_up_to_this_point,
3011 conversation.getName())));
3012 return;
3013 }
3014 }
3015 }
3016 }
3017 }
3018 } else {
3019 final MucOptions mucOptions = conversation.getMucOptions();
3020 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3021 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3022 ChatState state = ChatState.COMPOSING;
3023 List<MucOptions.User> users =
3024 conversation.getMucOptions().getUsersWithChatState(state, 5);
3025 if (users.size() == 0) {
3026 state = ChatState.PAUSED;
3027 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3028 }
3029 if (mucOptions.isPrivateAndNonAnonymous()) {
3030 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3031 final Set<ReadByMarker> markersForMessage =
3032 messageList.get(i).getReadByMarkers();
3033 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3034 for (ReadByMarker marker : markersForMessage) {
3035 if (!ReadByMarker.contains(marker, addedMarkers)) {
3036 addedMarkers.add(
3037 marker); // may be put outside this condition. set should do
3038 // dedup anyway
3039 MucOptions.User user = mucOptions.findUser(marker);
3040 if (user != null && !users.contains(user)) {
3041 shownMarkers.add(user);
3042 }
3043 }
3044 }
3045 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3046 final Message statusMessage;
3047 final int size = shownMarkers.size();
3048 if (size > 1) {
3049 final String body;
3050 if (size <= 4) {
3051 body =
3052 getString(
3053 R.string.contacts_have_read_up_to_this_point,
3054 UIHelper.concatNames(shownMarkers));
3055 } else if (ReadByMarker.allUsersRepresented(
3056 allUsers, markersForMessage, markerForSender)) {
3057 body = getString(R.string.everyone_has_read_up_to_this_point);
3058 } else {
3059 body =
3060 getString(
3061 R.string.contacts_and_n_more_have_read_up_to_this_point,
3062 UIHelper.concatNames(shownMarkers, 3),
3063 size - 3);
3064 }
3065 statusMessage = Message.createStatusMessage(conversation, body);
3066 statusMessage.setCounterparts(shownMarkers);
3067 } else if (size == 1) {
3068 statusMessage =
3069 Message.createStatusMessage(
3070 conversation,
3071 getString(
3072 R.string.contact_has_read_up_to_this_point,
3073 UIHelper.getDisplayName(shownMarkers.get(0))));
3074 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3075 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3076 } else {
3077 statusMessage = null;
3078 }
3079 if (statusMessage != null) {
3080 this.messageList.add(i + 1, statusMessage);
3081 }
3082 addedMarkers.add(markerForSender);
3083 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3084 break;
3085 }
3086 }
3087 }
3088 if (users.size() > 0) {
3089 Message statusMessage;
3090 if (users.size() == 1) {
3091 MucOptions.User user = users.get(0);
3092 int id =
3093 state == ChatState.COMPOSING
3094 ? R.string.contact_is_typing
3095 : R.string.contact_has_stopped_typing;
3096 statusMessage =
3097 Message.createStatusMessage(
3098 conversation, getString(id, UIHelper.getDisplayName(user)));
3099 statusMessage.setTrueCounterpart(user.getRealJid());
3100 statusMessage.setCounterpart(user.getFullJid());
3101 } else {
3102 int id =
3103 state == ChatState.COMPOSING
3104 ? R.string.contacts_are_typing
3105 : R.string.contacts_have_stopped_typing;
3106 statusMessage =
3107 Message.createStatusMessage(
3108 conversation, getString(id, UIHelper.concatNames(users)));
3109 statusMessage.setCounterparts(users);
3110 }
3111 this.messageList.add(statusMessage);
3112 }
3113 }
3114 }
3115
3116 private void stopScrolling() {
3117 long now = SystemClock.uptimeMillis();
3118 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3119 binding.messagesView.dispatchTouchEvent(cancel);
3120 }
3121
3122 private boolean showLoadMoreMessages(final Conversation c) {
3123 if (activity == null || activity.xmppConnectionService == null) {
3124 return false;
3125 }
3126 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3127 final MessageArchiveService service =
3128 activity.xmppConnectionService.getMessageArchiveService();
3129 return mam
3130 && (c.getLastClearHistory().getTimestamp() != 0
3131 || (c.countMessages() == 0
3132 && c.messagesLoaded.get()
3133 && c.hasMessagesLeftOnServer()
3134 && !service.queryInProgress(c)));
3135 }
3136
3137 private boolean hasMamSupport(final Conversation c) {
3138 if (c.getMode() == Conversation.MODE_SINGLE) {
3139 final XmppConnection connection = c.getAccount().getXmppConnection();
3140 return connection != null && connection.getFeatures().mam();
3141 } else {
3142 return c.getMucOptions().mamSupport();
3143 }
3144 }
3145
3146 protected void showSnackbar(
3147 final int message, final int action, final OnClickListener clickListener) {
3148 showSnackbar(message, action, clickListener, null);
3149 }
3150
3151 protected void showSnackbar(
3152 final int message,
3153 final int action,
3154 final OnClickListener clickListener,
3155 final View.OnLongClickListener longClickListener) {
3156 this.binding.snackbar.setVisibility(View.VISIBLE);
3157 this.binding.snackbar.setOnClickListener(null);
3158 this.binding.snackbarMessage.setText(message);
3159 this.binding.snackbarMessage.setOnClickListener(null);
3160 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3161 if (action != 0) {
3162 this.binding.snackbarAction.setText(action);
3163 }
3164 this.binding.snackbarAction.setOnClickListener(clickListener);
3165 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3166 }
3167
3168 protected void hideSnackbar() {
3169 this.binding.snackbar.setVisibility(View.GONE);
3170 }
3171
3172 protected void sendMessage(Message message) {
3173 activity.xmppConnectionService.sendMessage(message);
3174 messageSent();
3175 }
3176
3177 protected void sendPgpMessage(final Message message) {
3178 final XmppConnectionService xmppService = activity.xmppConnectionService;
3179 final Contact contact = message.getConversation().getContact();
3180 if (!activity.hasPgp()) {
3181 activity.showInstallPgpDialog();
3182 return;
3183 }
3184 if (conversation.getAccount().getPgpSignature() == null) {
3185 activity.announcePgp(
3186 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3187 return;
3188 }
3189 if (!mSendingPgpMessage.compareAndSet(false, true)) {
3190 Log.d(Config.LOGTAG, "sending pgp message already in progress");
3191 }
3192 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3193 if (contact.getPgpKeyId() != 0) {
3194 xmppService
3195 .getPgpEngine()
3196 .hasKey(
3197 contact,
3198 new UiCallback<Contact>() {
3199
3200 @Override
3201 public void userInputRequired(
3202 PendingIntent pi, Contact contact) {
3203 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3204 }
3205
3206 @Override
3207 public void success(Contact contact) {
3208 encryptTextMessage(message);
3209 }
3210
3211 @Override
3212 public void error(int error, Contact contact) {
3213 activity.runOnUiThread(
3214 () ->
3215 Toast.makeText(
3216 activity,
3217 R.string
3218 .unable_to_connect_to_keychain,
3219 Toast.LENGTH_SHORT)
3220 .show());
3221 mSendingPgpMessage.set(false);
3222 }
3223 });
3224
3225 } else {
3226 showNoPGPKeyDialog(
3227 false,
3228 (dialog, which) -> {
3229 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3230 xmppService.updateConversation(conversation);
3231 message.setEncryption(Message.ENCRYPTION_NONE);
3232 xmppService.sendMessage(message);
3233 messageSent();
3234 });
3235 }
3236 } else {
3237 if (conversation.getMucOptions().pgpKeysInUse()) {
3238 if (!conversation.getMucOptions().everybodyHasKeys()) {
3239 Toast warning =
3240 Toast.makeText(
3241 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3242 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3243 warning.show();
3244 }
3245 encryptTextMessage(message);
3246 } else {
3247 showNoPGPKeyDialog(
3248 true,
3249 (dialog, which) -> {
3250 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3251 message.setEncryption(Message.ENCRYPTION_NONE);
3252 xmppService.updateConversation(conversation);
3253 xmppService.sendMessage(message);
3254 messageSent();
3255 });
3256 }
3257 }
3258 }
3259
3260 public void encryptTextMessage(Message message) {
3261 activity.xmppConnectionService
3262 .getPgpEngine()
3263 .encrypt(
3264 message,
3265 new UiCallback<Message>() {
3266
3267 @Override
3268 public void userInputRequired(PendingIntent pi, Message message) {
3269 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3270 }
3271
3272 @Override
3273 public void success(Message message) {
3274 // TODO the following two call can be made before the callback
3275 getActivity().runOnUiThread(() -> messageSent());
3276 }
3277
3278 @Override
3279 public void error(final int error, Message message) {
3280 getActivity()
3281 .runOnUiThread(
3282 () -> {
3283 doneSendingPgpMessage();
3284 Toast.makeText(
3285 getActivity(),
3286 error == 0
3287 ? R.string
3288 .unable_to_connect_to_keychain
3289 : error,
3290 Toast.LENGTH_SHORT)
3291 .show();
3292 });
3293 }
3294 });
3295 }
3296
3297 public void showNoPGPKeyDialog(
3298 final boolean plural, final DialogInterface.OnClickListener listener) {
3299 final MaterialAlertDialogBuilder builder =
3300 new MaterialAlertDialogBuilder(requireActivity());
3301 if (plural) {
3302 builder.setTitle(getString(R.string.no_pgp_keys));
3303 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3304 } else {
3305 builder.setTitle(getString(R.string.no_pgp_key));
3306 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3307 }
3308 builder.setNegativeButton(getString(R.string.cancel), null);
3309 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3310 builder.create().show();
3311 }
3312
3313 public void appendText(String text, final boolean doNotAppend) {
3314 if (text == null) {
3315 return;
3316 }
3317 final Editable editable = this.binding.textinput.getText();
3318 String previous = editable == null ? "" : editable.toString();
3319 if (doNotAppend && !TextUtils.isEmpty(previous)) {
3320 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3321 .show();
3322 return;
3323 }
3324 if (UIHelper.isLastLineQuote(previous)) {
3325 text = '\n' + text;
3326 } else if (previous.length() != 0
3327 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3328 text = " " + text;
3329 }
3330 this.binding.textinput.append(text);
3331 }
3332
3333 @Override
3334 public boolean onEnterPressed(final boolean isCtrlPressed) {
3335 if (isCtrlPressed || enterIsSend()) {
3336 sendMessage();
3337 return true;
3338 }
3339 return false;
3340 }
3341
3342 private boolean enterIsSend() {
3343 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3344 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3345 }
3346
3347 public boolean onArrowUpCtrlPressed() {
3348 final Message lastEditableMessage =
3349 conversation == null ? null : conversation.getLastEditableMessage();
3350 if (lastEditableMessage != null) {
3351 correctMessage(lastEditableMessage);
3352 return true;
3353 } else {
3354 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3355 .show();
3356 return false;
3357 }
3358 }
3359
3360 @Override
3361 public void onTypingStarted() {
3362 final XmppConnectionService service =
3363 activity == null ? null : activity.xmppConnectionService;
3364 if (service == null) {
3365 return;
3366 }
3367 final Account.State status = conversation.getAccount().getStatus();
3368 if (status == Account.State.ONLINE
3369 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3370 service.sendChatState(conversation);
3371 }
3372 runOnUiThread(this::updateSendButton);
3373 }
3374
3375 @Override
3376 public void onTypingStopped() {
3377 final XmppConnectionService service =
3378 activity == null ? null : activity.xmppConnectionService;
3379 if (service == null) {
3380 return;
3381 }
3382 final Account.State status = conversation.getAccount().getStatus();
3383 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3384 service.sendChatState(conversation);
3385 }
3386 }
3387
3388 @Override
3389 public void onTextDeleted() {
3390 final XmppConnectionService service =
3391 activity == null ? null : activity.xmppConnectionService;
3392 if (service == null) {
3393 return;
3394 }
3395 final Account.State status = conversation.getAccount().getStatus();
3396 if (status == Account.State.ONLINE
3397 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3398 service.sendChatState(conversation);
3399 }
3400 if (storeNextMessage()) {
3401 runOnUiThread(
3402 () -> {
3403 if (activity == null) {
3404 return;
3405 }
3406 activity.onConversationsListItemUpdated();
3407 });
3408 }
3409 runOnUiThread(this::updateSendButton);
3410 }
3411
3412 @Override
3413 public void onTextChanged() {
3414 if (conversation != null && conversation.getCorrectingMessage() != null) {
3415 runOnUiThread(this::updateSendButton);
3416 }
3417 }
3418
3419 @Override
3420 public boolean onTabPressed(boolean repeated) {
3421 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3422 return false;
3423 }
3424 if (repeated) {
3425 completionIndex++;
3426 } else {
3427 lastCompletionLength = 0;
3428 completionIndex = 0;
3429 final String content = this.binding.textinput.getText().toString();
3430 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
3431 int start =
3432 lastCompletionCursor > 0
3433 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
3434 : 0;
3435 firstWord = start == 0;
3436 incomplete = content.substring(start, lastCompletionCursor);
3437 }
3438 List<String> completions = new ArrayList<>();
3439 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
3440 String name = user.getName();
3441 if (name != null && name.startsWith(incomplete)) {
3442 completions.add(name + (firstWord ? ": " : " "));
3443 }
3444 }
3445 Collections.sort(completions);
3446 if (completions.size() > completionIndex) {
3447 String completion = completions.get(completionIndex).substring(incomplete.length());
3448 this.binding
3449 .textinput
3450 .getEditableText()
3451 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3452 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
3453 lastCompletionLength = completion.length();
3454 } else {
3455 completionIndex = -1;
3456 this.binding
3457 .textinput
3458 .getEditableText()
3459 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3460 lastCompletionLength = 0;
3461 }
3462 return true;
3463 }
3464
3465 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
3466 try {
3467 getActivity()
3468 .startIntentSenderForResult(
3469 pendingIntent.getIntentSender(),
3470 requestCode,
3471 null,
3472 0,
3473 0,
3474 0,
3475 Compatibility.pgpStartIntentSenderOptions());
3476 } catch (final SendIntentException ignored) {
3477 }
3478 }
3479
3480 @Override
3481 public void onBackendConnected() {
3482 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
3483 String uuid = pendingConversationsUuid.pop();
3484 if (uuid != null) {
3485 if (!findAndReInitByUuidOrArchive(uuid)) {
3486 return;
3487 }
3488 } else {
3489 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
3490 clearPending();
3491 activity.onConversationArchived(conversation);
3492 return;
3493 }
3494 }
3495 ActivityResult activityResult = postponedActivityResult.pop();
3496 if (activityResult != null) {
3497 handleActivityResult(activityResult);
3498 }
3499 clearPending();
3500 }
3501
3502 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
3503 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
3504 if (conversation == null) {
3505 clearPending();
3506 activity.onConversationArchived(null);
3507 return false;
3508 }
3509 reInit(conversation);
3510 ScrollState scrollState = pendingScrollState.pop();
3511 String lastMessageUuid = pendingLastMessageUuid.pop();
3512 List<Attachment> attachments = pendingMediaPreviews.pop();
3513 if (scrollState != null) {
3514 setScrollPosition(scrollState, lastMessageUuid);
3515 }
3516 if (attachments != null && attachments.size() > 0) {
3517 Log.d(Config.LOGTAG, "had attachments on restore");
3518 mediaPreviewAdapter.addMediaPreviews(attachments);
3519 toggleInputMethod();
3520 }
3521 return true;
3522 }
3523
3524 private void clearPending() {
3525 if (postponedActivityResult.clear()) {
3526 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
3527 if (pendingTakePhotoUri.clear()) {
3528 Log.e(Config.LOGTAG, "cleared pending photo uri");
3529 }
3530 }
3531 if (pendingScrollState.clear()) {
3532 Log.e(Config.LOGTAG, "cleared scroll state");
3533 }
3534 if (pendingConversationsUuid.clear()) {
3535 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
3536 }
3537 if (pendingMediaPreviews.clear()) {
3538 Log.e(Config.LOGTAG, "cleared pending media previews");
3539 }
3540 }
3541
3542 public Conversation getConversation() {
3543 return conversation;
3544 }
3545
3546 @Override
3547 public void onContactPictureLongClicked(View v, final Message message) {
3548 final String fingerprint;
3549 if (message.getEncryption() == Message.ENCRYPTION_PGP
3550 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3551 fingerprint = "pgp";
3552 } else {
3553 fingerprint = message.getFingerprint();
3554 }
3555 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
3556 final Contact contact = message.getContact();
3557 if (message.getStatus() <= Message.STATUS_RECEIVED
3558 && (contact == null || !contact.isSelf())) {
3559 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
3560 final Jid cp = message.getCounterpart();
3561 if (cp == null || cp.isBareJid()) {
3562 return;
3563 }
3564 final Jid tcp = message.getTrueCounterpart();
3565 final User userByRealJid =
3566 tcp != null
3567 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
3568 : null;
3569 final User user =
3570 userByRealJid != null
3571 ? userByRealJid
3572 : conversation.getMucOptions().findUserByFullJid(cp);
3573 popupMenu.inflate(R.menu.muc_details_context);
3574 final Menu menu = popupMenu.getMenu();
3575 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
3576 activity, menu, conversation, user);
3577 popupMenu.setOnMenuItemClickListener(
3578 menuItem ->
3579 MucDetailsContextMenuHelper.onContextItemSelected(
3580 menuItem, user, activity, fingerprint));
3581 } else {
3582 popupMenu.inflate(R.menu.one_on_one_context);
3583 popupMenu.setOnMenuItemClickListener(
3584 item -> {
3585 switch (item.getItemId()) {
3586 case R.id.action_contact_details:
3587 activity.switchToContactDetails(
3588 message.getContact(), fingerprint);
3589 break;
3590 case R.id.action_show_qr_code:
3591 activity.showQrCode(
3592 "xmpp:"
3593 + message.getContact()
3594 .getJid()
3595 .asBareJid()
3596 .toString());
3597 break;
3598 }
3599 return true;
3600 });
3601 }
3602 } else {
3603 popupMenu.inflate(R.menu.account_context);
3604 final Menu menu = popupMenu.getMenu();
3605 menu.findItem(R.id.action_manage_accounts)
3606 .setVisible(QuickConversationsService.isConversations());
3607 popupMenu.setOnMenuItemClickListener(
3608 item -> {
3609 final XmppActivity activity = this.activity;
3610 if (activity == null) {
3611 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
3612 return true;
3613 }
3614 switch (item.getItemId()) {
3615 case R.id.action_show_qr_code:
3616 activity.showQrCode(conversation.getAccount().getShareableUri());
3617 break;
3618 case R.id.action_account_details:
3619 activity.switchToAccount(
3620 message.getConversation().getAccount(), fingerprint);
3621 break;
3622 case R.id.action_manage_accounts:
3623 AccountUtils.launchManageAccounts(activity);
3624 break;
3625 }
3626 return true;
3627 });
3628 }
3629 popupMenu.show();
3630 }
3631
3632 @Override
3633 public void onContactPictureClicked(Message message) {
3634 String fingerprint;
3635 if (message.getEncryption() == Message.ENCRYPTION_PGP
3636 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3637 fingerprint = "pgp";
3638 } else {
3639 fingerprint = message.getFingerprint();
3640 }
3641 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
3642 if (received) {
3643 if (message.getConversation() instanceof Conversation
3644 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
3645 Jid tcp = message.getTrueCounterpart();
3646 Jid user = message.getCounterpart();
3647 if (user != null && !user.isBareJid()) {
3648 final MucOptions mucOptions =
3649 ((Conversation) message.getConversation()).getMucOptions();
3650 if (mucOptions.participating()
3651 || ((Conversation) message.getConversation()).getNextCounterpart()
3652 != null) {
3653 if (!mucOptions.isUserInRoom(user)
3654 && mucOptions.findUserByRealJid(
3655 tcp == null ? null : tcp.asBareJid())
3656 == null) {
3657 Toast.makeText(
3658 getActivity(),
3659 activity.getString(
3660 R.string.user_has_left_conference,
3661 user.getResource()),
3662 Toast.LENGTH_SHORT)
3663 .show();
3664 }
3665 highlightInConference(user.getResource());
3666 } else {
3667 Toast.makeText(
3668 getActivity(),
3669 R.string.you_are_not_participating,
3670 Toast.LENGTH_SHORT)
3671 .show();
3672 }
3673 }
3674 return;
3675 } else {
3676 if (!message.getContact().isSelf()) {
3677 activity.switchToContactDetails(message.getContact(), fingerprint);
3678 return;
3679 }
3680 }
3681 }
3682 activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
3683 }
3684
3685 private Activity requireActivity() {
3686 final Activity activity = getActivity();
3687 if (activity == null) {
3688 throw new IllegalStateException("Activity not attached");
3689 }
3690 return activity;
3691 }
3692}