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.Patterns;
69import eu.siacs.conversations.Config;
70import eu.siacs.conversations.R;
71import eu.siacs.conversations.crypto.axolotl.AxolotlService;
72import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
73import eu.siacs.conversations.databinding.FragmentConversationBinding;
74import eu.siacs.conversations.entities.Account;
75import eu.siacs.conversations.entities.Blockable;
76import eu.siacs.conversations.entities.Contact;
77import eu.siacs.conversations.entities.Conversation;
78import eu.siacs.conversations.entities.Conversational;
79import eu.siacs.conversations.entities.DownloadableFile;
80import eu.siacs.conversations.entities.Message;
81import eu.siacs.conversations.entities.MucOptions;
82import eu.siacs.conversations.entities.MucOptions.User;
83import eu.siacs.conversations.entities.Presence;
84import eu.siacs.conversations.entities.ReadByMarker;
85import eu.siacs.conversations.entities.Transferable;
86import eu.siacs.conversations.entities.TransferablePlaceholder;
87import eu.siacs.conversations.http.HttpDownloadConnection;
88import eu.siacs.conversations.persistance.FileBackend;
89import eu.siacs.conversations.services.CallIntegrationConnectionService;
90import eu.siacs.conversations.services.MessageArchiveService;
91import eu.siacs.conversations.services.QuickConversationsService;
92import eu.siacs.conversations.services.XmppConnectionService;
93import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
94import eu.siacs.conversations.ui.adapter.MessageAdapter;
95import eu.siacs.conversations.ui.util.ActivityResult;
96import eu.siacs.conversations.ui.util.Attachment;
97import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
98import eu.siacs.conversations.ui.util.DateSeparator;
99import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
100import eu.siacs.conversations.ui.util.ListViewUtils;
101import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
102import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
103import eu.siacs.conversations.ui.util.MyLinkify;
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(MyLinkify.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 activity.copyTextToClipboard(displayError, R.string.error_message);
2189 Toast.makeText(
2190 activity,
2191 R.string.error_message_copied_to_clipboard,
2192 Toast.LENGTH_SHORT)
2193 .show();
2194 });
2195 builder.setPositiveButton(R.string.confirm, null);
2196 builder.create().show();
2197 }
2198
2199 private void deleteFile(final Message message) {
2200 final MaterialAlertDialogBuilder builder =
2201 new MaterialAlertDialogBuilder(requireActivity());
2202 builder.setNegativeButton(R.string.cancel, null);
2203 builder.setTitle(R.string.delete_file_dialog);
2204 builder.setMessage(R.string.delete_file_dialog_msg);
2205 builder.setPositiveButton(
2206 R.string.confirm,
2207 (dialog, which) -> {
2208 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2209 message.setDeleted(true);
2210 activity.xmppConnectionService.evictPreview(message.getUuid());
2211 activity.xmppConnectionService.updateMessage(message, false);
2212 activity.onConversationsListItemUpdated();
2213 refresh();
2214 }
2215 });
2216 builder.create().show();
2217 }
2218
2219 private void resendMessage(final Message message, final boolean forceP2P) {
2220 if (message.isFileOrImage()) {
2221 if (!(message.getConversation() instanceof Conversation conversation)) {
2222 return;
2223 }
2224 final DownloadableFile file =
2225 activity.xmppConnectionService.getFileBackend().getFile(message);
2226 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2227 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2228 if (!message.hasFileOnRemoteHost()
2229 && xmppConnection != null
2230 && conversation.getMode() == Conversational.MODE_SINGLE
2231 && (!xmppConnection
2232 .getFeatures()
2233 .httpUpload(message.getFileParams().getSize())
2234 || forceP2P)) {
2235 activity.selectPresence(
2236 conversation,
2237 () -> {
2238 message.setCounterpart(conversation.getNextCounterpart());
2239 activity.xmppConnectionService.resendFailedMessages(
2240 message, forceP2P);
2241 new Handler()
2242 .post(
2243 () -> {
2244 int size = messageList.size();
2245 this.binding.messagesView.setSelection(
2246 size - 1);
2247 });
2248 });
2249 return;
2250 }
2251 } else if (!Compatibility.hasStoragePermission(getActivity())) {
2252 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2253 return;
2254 } else {
2255 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2256 message.setDeleted(true);
2257 activity.xmppConnectionService.updateMessage(message, false);
2258 activity.onConversationsListItemUpdated();
2259 refresh();
2260 return;
2261 }
2262 }
2263 activity.xmppConnectionService.resendFailedMessages(message, false);
2264 new Handler()
2265 .post(
2266 () -> {
2267 int size = messageList.size();
2268 this.binding.messagesView.setSelection(size - 1);
2269 });
2270 }
2271
2272 private void cancelTransmission(Message message) {
2273 Transferable transferable = message.getTransferable();
2274 if (transferable != null) {
2275 transferable.cancel();
2276 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2277 activity.xmppConnectionService.markMessage(
2278 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2279 }
2280 }
2281
2282 private void retryDecryption(Message message) {
2283 message.setEncryption(Message.ENCRYPTION_PGP);
2284 activity.onConversationsListItemUpdated();
2285 refresh();
2286 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2287 }
2288
2289 public void privateMessageWith(final Jid counterpart) {
2290 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2291 activity.xmppConnectionService.sendChatState(conversation);
2292 }
2293 this.binding.textinput.setText("");
2294 this.conversation.setNextCounterpart(counterpart);
2295 updateChatMsgHint();
2296 updateSendButton();
2297 updateEditablity();
2298 }
2299
2300 private void correctMessage(final Message message) {
2301 this.conversation.setCorrectingMessage(message);
2302 final Editable editable = binding.textinput.getText();
2303 this.conversation.setDraftMessage(editable.toString());
2304 this.binding.textinput.setText("");
2305 this.binding.textinput.append(message.getBody());
2306 }
2307
2308 private void highlightInConference(String nick) {
2309 final Editable editable = this.binding.textinput.getText();
2310 String oldString = editable.toString().trim();
2311 final int pos = this.binding.textinput.getSelectionStart();
2312 if (oldString.isEmpty() || pos == 0) {
2313 editable.insert(0, nick + ": ");
2314 } else {
2315 final char before = editable.charAt(pos - 1);
2316 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2317 if (before == '\n') {
2318 editable.insert(pos, nick + ": ");
2319 } else {
2320 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2321 if (NickValidityChecker.check(
2322 conversation,
2323 Arrays.asList(
2324 editable.subSequence(0, pos - 2).toString().split(", ")))) {
2325 editable.insert(pos - 2, ", " + nick);
2326 return;
2327 }
2328 }
2329 editable.insert(
2330 pos,
2331 (Character.isWhitespace(before) ? "" : " ")
2332 + nick
2333 + (Character.isWhitespace(after) ? "" : " "));
2334 if (Character.isWhitespace(after)) {
2335 this.binding.textinput.setSelection(
2336 this.binding.textinput.getSelectionStart() + 1);
2337 }
2338 }
2339 }
2340 }
2341
2342 @Override
2343 public void startActivityForResult(Intent intent, int requestCode) {
2344 final Activity activity = getActivity();
2345 if (activity instanceof ConversationsActivity) {
2346 ((ConversationsActivity) activity).clearPendingViewIntent();
2347 }
2348 super.startActivityForResult(intent, requestCode);
2349 }
2350
2351 @Override
2352 public void onSaveInstanceState(@NonNull Bundle outState) {
2353 super.onSaveInstanceState(outState);
2354 if (conversation != null) {
2355 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2356 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2357 final Uri uri = pendingTakePhotoUri.peek();
2358 if (uri != null) {
2359 outState.putString(STATE_PHOTO_URI, uri.toString());
2360 }
2361 final ScrollState scrollState = getScrollPosition();
2362 if (scrollState != null) {
2363 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2364 }
2365 final ArrayList<Attachment> attachments =
2366 mediaPreviewAdapter == null
2367 ? new ArrayList<>()
2368 : mediaPreviewAdapter.getAttachments();
2369 if (attachments.size() > 0) {
2370 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2371 }
2372 }
2373 }
2374
2375 @Override
2376 public void onActivityCreated(Bundle savedInstanceState) {
2377 super.onActivityCreated(savedInstanceState);
2378 if (savedInstanceState == null) {
2379 return;
2380 }
2381 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2382 ArrayList<Attachment> attachments =
2383 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2384 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2385 if (uuid != null) {
2386 QuickLoader.set(uuid);
2387 this.pendingConversationsUuid.push(uuid);
2388 if (attachments != null && attachments.size() > 0) {
2389 this.pendingMediaPreviews.push(attachments);
2390 }
2391 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2392 if (takePhotoUri != null) {
2393 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2394 }
2395 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2396 }
2397 }
2398
2399 @Override
2400 public void onStart() {
2401 super.onStart();
2402 if (this.reInitRequiredOnStart && this.conversation != null) {
2403 final Bundle extras = pendingExtras.pop();
2404 reInit(this.conversation, extras != null);
2405 if (extras != null) {
2406 processExtras(extras);
2407 }
2408 } else if (conversation == null
2409 && activity != null
2410 && activity.xmppConnectionService != null) {
2411 final String uuid = pendingConversationsUuid.pop();
2412 Log.d(
2413 Config.LOGTAG,
2414 "ConversationFragment.onStart() - activity was bound but no conversation"
2415 + " loaded. uuid="
2416 + uuid);
2417 if (uuid != null) {
2418 findAndReInitByUuidOrArchive(uuid);
2419 }
2420 }
2421 }
2422
2423 @Override
2424 public void onStop() {
2425 super.onStop();
2426 final Activity activity = getActivity();
2427 messageListAdapter.unregisterListenerInAudioPlayer();
2428 if (activity == null || !activity.isChangingConfigurations()) {
2429 hideSoftKeyboard(activity);
2430 messageListAdapter.stopAudioPlayer();
2431 }
2432 if (this.conversation != null) {
2433 final String msg = this.binding.textinput.getText().toString();
2434 storeNextMessage(msg);
2435 updateChatState(this.conversation, msg);
2436 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2437 }
2438 this.reInitRequiredOnStart = true;
2439 }
2440
2441 private void updateChatState(final Conversation conversation, final String msg) {
2442 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2443 Account.State status = conversation.getAccount().getStatus();
2444 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2445 activity.xmppConnectionService.sendChatState(conversation);
2446 }
2447 }
2448
2449 private void saveMessageDraftStopAudioPlayer() {
2450 final Conversation previousConversation = this.conversation;
2451 if (this.activity == null || this.binding == null || previousConversation == null) {
2452 return;
2453 }
2454 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2455 final String msg = this.binding.textinput.getText().toString();
2456 storeNextMessage(msg);
2457 updateChatState(this.conversation, msg);
2458 messageListAdapter.stopAudioPlayer();
2459 mediaPreviewAdapter.clearPreviews();
2460 toggleInputMethod();
2461 }
2462
2463 public void reInit(final Conversation conversation, final Bundle extras) {
2464 QuickLoader.set(conversation.getUuid());
2465 final boolean changedConversation = this.conversation != conversation;
2466 if (changedConversation) {
2467 this.saveMessageDraftStopAudioPlayer();
2468 }
2469 this.clearPending();
2470 if (this.reInit(conversation, extras != null)) {
2471 if (extras != null) {
2472 processExtras(extras);
2473 }
2474 this.reInitRequiredOnStart = false;
2475 } else {
2476 this.reInitRequiredOnStart = true;
2477 pendingExtras.push(extras);
2478 }
2479 resetUnreadMessagesCount();
2480 }
2481
2482 private void reInit(Conversation conversation) {
2483 reInit(conversation, false);
2484 }
2485
2486 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2487 if (conversation == null) {
2488 return false;
2489 }
2490 this.conversation = conversation;
2491 // once we set the conversation all is good and it will automatically do the right thing in
2492 // onStart()
2493 if (this.activity == null || this.binding == null) {
2494 return false;
2495 }
2496
2497 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2498 activity.onConversationArchived(this.conversation);
2499 return false;
2500 }
2501
2502 stopScrolling();
2503 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
2504
2505 if (this.conversation.isRead() && hasExtras) {
2506 Log.d(Config.LOGTAG, "trimming conversation");
2507 this.conversation.trim();
2508 }
2509
2510 setupIme();
2511
2512 final boolean scrolledToBottomAndNoPending =
2513 this.scrolledToBottom() && pendingScrollState.peek() == null;
2514
2515 this.binding.textSendButton.setContentDescription(
2516 activity.getString(R.string.send_message_to_x, conversation.getName()));
2517 this.binding.textinput.setKeyboardListener(null);
2518 final boolean participating =
2519 conversation.getMode() == Conversational.MODE_SINGLE
2520 || conversation.getMucOptions().participating();
2521 if (participating) {
2522 this.binding.textinput.setText(this.conversation.getNextMessage());
2523 this.binding.textinput.setSelection(this.binding.textinput.length());
2524 } else {
2525 this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
2526 }
2527 this.binding.textinput.setKeyboardListener(this);
2528 messageListAdapter.updatePreferences();
2529 refresh(false);
2530 activity.invalidateOptionsMenu();
2531 this.conversation.messagesLoaded.set(true);
2532 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
2533
2534 if (hasExtras || scrolledToBottomAndNoPending) {
2535 resetUnreadMessagesCount();
2536 synchronized (this.messageList) {
2537 Log.d(Config.LOGTAG, "jump to first unread message");
2538 final Message first = conversation.getFirstUnreadMessage();
2539 final int bottom = Math.max(0, this.messageList.size() - 1);
2540 final int pos;
2541 final boolean jumpToBottom;
2542 if (first == null) {
2543 pos = bottom;
2544 jumpToBottom = true;
2545 } else {
2546 int i = getIndexOf(first.getUuid(), this.messageList);
2547 pos = i < 0 ? bottom : i;
2548 jumpToBottom = false;
2549 }
2550 setSelection(pos, jumpToBottom);
2551 }
2552 }
2553
2554 this.binding.messagesView.post(this::fireReadEvent);
2555 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
2556 // layout which might be unnecessary since we can *see* it
2557 activity.xmppConnectionService
2558 .getNotificationService()
2559 .setOpenConversation(this.conversation);
2560 return true;
2561 }
2562
2563 private void resetUnreadMessagesCount() {
2564 lastMessageUuid = null;
2565 hideUnreadMessagesCount();
2566 }
2567
2568 private void hideUnreadMessagesCount() {
2569 if (this.binding == null) {
2570 return;
2571 }
2572 this.binding.scrollToBottomButton.setEnabled(false);
2573 this.binding.scrollToBottomButton.hide();
2574 this.binding.unreadCountCustomView.setVisibility(View.GONE);
2575 }
2576
2577 private void setSelection(int pos, boolean jumpToBottom) {
2578 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2579 this.binding.messagesView.post(
2580 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2581 this.binding.messagesView.post(this::fireReadEvent);
2582 }
2583
2584 private boolean scrolledToBottom() {
2585 return this.binding != null && scrolledToBottom(this.binding.messagesView);
2586 }
2587
2588 private void processExtras(final Bundle extras) {
2589 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2590 final String text = extras.getString(Intent.EXTRA_TEXT);
2591 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2592 final String postInitAction =
2593 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
2594 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2595 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2596 final boolean doNotAppend =
2597 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2598 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
2599 final List<Uri> uris = extractUris(extras);
2600 if (uris != null && uris.size() > 0) {
2601 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2602 mediaPreviewAdapter.addMediaPreviews(
2603 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2604 } else {
2605 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2606 mediaPreviewAdapter.addMediaPreviews(
2607 Attachment.of(getActivity(), cleanedUris, type));
2608 }
2609 toggleInputMethod();
2610 return;
2611 }
2612 if (nick != null) {
2613 if (pm) {
2614 Jid jid = conversation.getJid();
2615 try {
2616 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2617 privateMessageWith(next);
2618 } catch (final IllegalArgumentException ignored) {
2619 // do nothing
2620 }
2621 } else {
2622 final MucOptions mucOptions = conversation.getMucOptions();
2623 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2624 highlightInConference(nick);
2625 }
2626 }
2627 } else {
2628 if (text != null && Patterns.URI_GEO.matcher(text).matches()) {
2629 mediaPreviewAdapter.addMediaPreviews(
2630 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
2631 toggleInputMethod();
2632 return;
2633 } else if (text != null && asQuote) {
2634 quoteText(text);
2635 } else {
2636 appendText(text, doNotAppend);
2637 }
2638 }
2639 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
2640 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
2641 return;
2642 }
2643 final Message message =
2644 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2645 if (message != null) {
2646 startDownloadable(message);
2647 }
2648 }
2649
2650 private List<Uri> extractUris(final Bundle extras) {
2651 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2652 if (uris != null) {
2653 return uris;
2654 }
2655 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2656 if (uri != null) {
2657 return Collections.singletonList(uri);
2658 } else {
2659 return null;
2660 }
2661 }
2662
2663 private List<Uri> cleanUris(final List<Uri> uris) {
2664 final Iterator<Uri> iterator = uris.iterator();
2665 while (iterator.hasNext()) {
2666 final Uri uri = iterator.next();
2667 if (FileBackend.dangerousFile(uri)) {
2668 iterator.remove();
2669 Toast.makeText(
2670 requireActivity(),
2671 R.string.security_violation_not_attaching_file,
2672 Toast.LENGTH_SHORT)
2673 .show();
2674 }
2675 }
2676 return uris;
2677 }
2678
2679 private boolean showBlockSubmenu(View view) {
2680 final Jid jid = conversation.getJid();
2681 final boolean showReject =
2682 !conversation.isWithStranger()
2683 && conversation
2684 .getContact()
2685 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2686 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2687 popupMenu.inflate(R.menu.block);
2688 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2689 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2690 popupMenu.setOnMenuItemClickListener(
2691 menuItem -> {
2692 Blockable blockable;
2693 switch (menuItem.getItemId()) {
2694 case R.id.reject:
2695 activity.xmppConnectionService.stopPresenceUpdatesTo(
2696 conversation.getContact());
2697 updateSnackBar(conversation);
2698 return true;
2699 case R.id.block_domain:
2700 blockable =
2701 conversation
2702 .getAccount()
2703 .getRoster()
2704 .getContact(jid.getDomain());
2705 break;
2706 default:
2707 blockable = conversation;
2708 }
2709 BlockContactDialog.show(activity, blockable);
2710 return true;
2711 });
2712 popupMenu.show();
2713 return true;
2714 }
2715
2716 private void updateSnackBar(final Conversation conversation) {
2717 final Account account = conversation.getAccount();
2718 final XmppConnection connection = account.getXmppConnection();
2719 final int mode = conversation.getMode();
2720 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2721 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2722 return;
2723 }
2724 if (account.getStatus() == Account.State.DISABLED) {
2725 showSnackbar(
2726 R.string.this_account_is_disabled,
2727 R.string.enable,
2728 this.mEnableAccountListener);
2729 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
2730 showSnackbar(
2731 R.string.this_account_is_logged_out,
2732 R.string.log_in,
2733 this.mEnableAccountListener);
2734 } else if (conversation.isBlocked()) {
2735 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2736 } else if (contact != null
2737 && !contact.showInRoster()
2738 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2739 showSnackbar(
2740 R.string.contact_added_you,
2741 R.string.add_back,
2742 this.mAddBackClickListener,
2743 this.mLongPressBlockListener);
2744 } else if (contact != null
2745 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2746 showSnackbar(
2747 R.string.contact_asks_for_presence_subscription,
2748 R.string.allow,
2749 this.mAllowPresenceSubscription,
2750 this.mLongPressBlockListener);
2751 } else if (mode == Conversation.MODE_MULTI
2752 && !conversation.getMucOptions().online()
2753 && account.getStatus() == Account.State.ONLINE) {
2754 switch (conversation.getMucOptions().getError()) {
2755 case NICK_IN_USE:
2756 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2757 break;
2758 case NO_RESPONSE:
2759 showSnackbar(R.string.joining_conference, 0, null);
2760 break;
2761 case SERVER_NOT_FOUND:
2762 if (conversation.receivedMessagesCount() > 0) {
2763 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2764 } else {
2765 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2766 }
2767 break;
2768 case REMOTE_SERVER_TIMEOUT:
2769 if (conversation.receivedMessagesCount() > 0) {
2770 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2771 } else {
2772 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2773 }
2774 break;
2775 case PASSWORD_REQUIRED:
2776 showSnackbar(
2777 R.string.conference_requires_password,
2778 R.string.enter_password,
2779 enterPassword);
2780 break;
2781 case BANNED:
2782 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2783 break;
2784 case MEMBERS_ONLY:
2785 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2786 break;
2787 case RESOURCE_CONSTRAINT:
2788 showSnackbar(
2789 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2790 break;
2791 case KICKED:
2792 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2793 break;
2794 case TECHNICAL_PROBLEMS:
2795 showSnackbar(
2796 R.string.conference_technical_problems, R.string.try_again, joinMuc);
2797 break;
2798 case UNKNOWN:
2799 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2800 break;
2801 case INVALID_NICK:
2802 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2803 case SHUTDOWN:
2804 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2805 break;
2806 case DESTROYED:
2807 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2808 break;
2809 case NON_ANONYMOUS:
2810 showSnackbar(
2811 R.string.group_chat_will_make_your_jabber_id_public,
2812 R.string.join,
2813 acceptJoin);
2814 break;
2815 default:
2816 hideSnackbar();
2817 break;
2818 }
2819 } else if (account.hasPendingPgpIntent(conversation)) {
2820 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2821 } else if (connection != null
2822 && connection.getFeatures().blocking()
2823 && conversation.countMessages() != 0
2824 && !conversation.isBlocked()
2825 && conversation.isWithStranger()) {
2826 showSnackbar(
2827 R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2828 } else {
2829 hideSnackbar();
2830 }
2831 }
2832
2833 @Override
2834 public void refresh() {
2835 if (this.binding == null) {
2836 Log.d(
2837 Config.LOGTAG,
2838 "ConversationFragment.refresh() skipped updated because view binding was null");
2839 return;
2840 }
2841 if (this.conversation != null
2842 && this.activity != null
2843 && this.activity.xmppConnectionService != null) {
2844 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2845 activity.onConversationArchived(this.conversation);
2846 return;
2847 }
2848 }
2849 this.refresh(true);
2850 }
2851
2852 private void refresh(boolean notifyConversationRead) {
2853 synchronized (this.messageList) {
2854 if (this.conversation != null) {
2855 conversation.populateWithMessages(this.messageList);
2856 updateSnackBar(conversation);
2857 updateStatusMessages();
2858 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2859 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2860 binding.unreadCountCustomView.setUnreadCount(
2861 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2862 }
2863 this.messageListAdapter.notifyDataSetChanged();
2864 updateChatMsgHint();
2865 if (notifyConversationRead && activity != null) {
2866 binding.messagesView.post(this::fireReadEvent);
2867 }
2868 updateSendButton();
2869 updateEditablity();
2870 }
2871 }
2872 }
2873
2874 protected void messageSent() {
2875 mSendingPgpMessage.set(false);
2876 this.binding.textinput.setText("");
2877 if (conversation.setCorrectingMessage(null)) {
2878 this.binding.textinput.append(conversation.getDraftMessage());
2879 conversation.setDraftMessage(null);
2880 }
2881 storeNextMessage();
2882 updateChatMsgHint();
2883 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2884 final boolean prefScrollToBottom =
2885 p.getBoolean(
2886 "scroll_to_bottom",
2887 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2888 if (prefScrollToBottom || scrolledToBottom()) {
2889 new Handler()
2890 .post(
2891 () -> {
2892 int size = messageList.size();
2893 this.binding.messagesView.setSelection(size - 1);
2894 });
2895 }
2896 }
2897
2898 private boolean storeNextMessage() {
2899 return storeNextMessage(this.binding.textinput.getText().toString());
2900 }
2901
2902 private boolean storeNextMessage(String msg) {
2903 final boolean participating =
2904 conversation.getMode() == Conversational.MODE_SINGLE
2905 || conversation.getMucOptions().participating();
2906 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
2907 && participating
2908 && this.conversation.setNextMessage(msg)) {
2909 this.activity.xmppConnectionService.updateConversation(this.conversation);
2910 return true;
2911 }
2912 return false;
2913 }
2914
2915 public void doneSendingPgpMessage() {
2916 mSendingPgpMessage.set(false);
2917 }
2918
2919 public long getMaxHttpUploadSize(Conversation conversation) {
2920 final XmppConnection connection = conversation.getAccount().getXmppConnection();
2921 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2922 }
2923
2924 private void updateEditablity() {
2925 boolean canWrite =
2926 this.conversation.getMode() == Conversation.MODE_SINGLE
2927 || this.conversation.getMucOptions().participating()
2928 || this.conversation.getNextCounterpart() != null;
2929 this.binding.textinput.setFocusable(canWrite);
2930 this.binding.textinput.setFocusableInTouchMode(canWrite);
2931 this.binding.textSendButton.setEnabled(canWrite);
2932 this.binding.textinput.setCursorVisible(canWrite);
2933 this.binding.textinput.setEnabled(canWrite);
2934 }
2935
2936 public void updateSendButton() {
2937 boolean hasAttachments =
2938 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2939 final Conversation c = this.conversation;
2940 final Presence.Status status;
2941 final String text =
2942 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2943 final SendButtonAction action;
2944 if (hasAttachments) {
2945 action = SendButtonAction.TEXT;
2946 } else {
2947 action = SendButtonTool.getAction(getActivity(), c, text);
2948 }
2949 if (c.getAccount().getStatus() == Account.State.ONLINE) {
2950 if (activity != null
2951 && activity.xmppConnectionService != null
2952 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2953 status = Presence.Status.OFFLINE;
2954 } else if (c.getMode() == Conversation.MODE_SINGLE) {
2955 status = c.getContact().getShownStatus();
2956 } else {
2957 status =
2958 c.getMucOptions().online()
2959 ? Presence.Status.ONLINE
2960 : Presence.Status.OFFLINE;
2961 }
2962 } else {
2963 status = Presence.Status.OFFLINE;
2964 }
2965 this.binding.textSendButton.setTag(action);
2966 this.binding.textSendButton.setIconResource(
2967 SendButtonTool.getSendButtonImageResource(action));
2968 this.binding.textSendButton.setIconTint(
2969 ColorStateList.valueOf(
2970 SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
2971 // TODO send button color
2972 final Activity activity = getActivity();
2973 if (activity != null) {}
2974 }
2975
2976 protected void updateStatusMessages() {
2977 DateSeparator.addAll(this.messageList);
2978 if (showLoadMoreMessages(conversation)) {
2979 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2980 }
2981 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2982 ChatState state = conversation.getIncomingChatState();
2983 if (state == ChatState.COMPOSING) {
2984 this.messageList.add(
2985 Message.createStatusMessage(
2986 conversation,
2987 getString(R.string.contact_is_typing, conversation.getName())));
2988 } else if (state == ChatState.PAUSED) {
2989 this.messageList.add(
2990 Message.createStatusMessage(
2991 conversation,
2992 getString(
2993 R.string.contact_has_stopped_typing,
2994 conversation.getName())));
2995 } else {
2996 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2997 final Message message = this.messageList.get(i);
2998 if (message.getType() != Message.TYPE_STATUS) {
2999 if (message.getStatus() == Message.STATUS_RECEIVED) {
3000 return;
3001 } else {
3002 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3003 this.messageList.add(
3004 i + 1,
3005 Message.createStatusMessage(
3006 conversation,
3007 getString(
3008 R.string.contact_has_read_up_to_this_point,
3009 conversation.getName())));
3010 return;
3011 }
3012 }
3013 }
3014 }
3015 }
3016 } else {
3017 final MucOptions mucOptions = conversation.getMucOptions();
3018 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3019 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3020 ChatState state = ChatState.COMPOSING;
3021 List<MucOptions.User> users =
3022 conversation.getMucOptions().getUsersWithChatState(state, 5);
3023 if (users.size() == 0) {
3024 state = ChatState.PAUSED;
3025 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3026 }
3027 if (mucOptions.isPrivateAndNonAnonymous()) {
3028 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3029 final Set<ReadByMarker> markersForMessage =
3030 messageList.get(i).getReadByMarkers();
3031 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3032 for (ReadByMarker marker : markersForMessage) {
3033 if (!ReadByMarker.contains(marker, addedMarkers)) {
3034 addedMarkers.add(
3035 marker); // may be put outside this condition. set should do
3036 // dedup anyway
3037 MucOptions.User user = mucOptions.findUser(marker);
3038 if (user != null && !users.contains(user)) {
3039 shownMarkers.add(user);
3040 }
3041 }
3042 }
3043 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3044 final Message statusMessage;
3045 final int size = shownMarkers.size();
3046 if (size > 1) {
3047 final String body;
3048 if (size <= 4) {
3049 body =
3050 getString(
3051 R.string.contacts_have_read_up_to_this_point,
3052 UIHelper.concatNames(shownMarkers));
3053 } else if (ReadByMarker.allUsersRepresented(
3054 allUsers, markersForMessage, markerForSender)) {
3055 body = getString(R.string.everyone_has_read_up_to_this_point);
3056 } else {
3057 body =
3058 getString(
3059 R.string.contacts_and_n_more_have_read_up_to_this_point,
3060 UIHelper.concatNames(shownMarkers, 3),
3061 size - 3);
3062 }
3063 statusMessage = Message.createStatusMessage(conversation, body);
3064 statusMessage.setCounterparts(shownMarkers);
3065 } else if (size == 1) {
3066 statusMessage =
3067 Message.createStatusMessage(
3068 conversation,
3069 getString(
3070 R.string.contact_has_read_up_to_this_point,
3071 UIHelper.getDisplayName(shownMarkers.get(0))));
3072 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3073 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3074 } else {
3075 statusMessage = null;
3076 }
3077 if (statusMessage != null) {
3078 this.messageList.add(i + 1, statusMessage);
3079 }
3080 addedMarkers.add(markerForSender);
3081 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3082 break;
3083 }
3084 }
3085 }
3086 if (users.size() > 0) {
3087 Message statusMessage;
3088 if (users.size() == 1) {
3089 MucOptions.User user = users.get(0);
3090 int id =
3091 state == ChatState.COMPOSING
3092 ? R.string.contact_is_typing
3093 : R.string.contact_has_stopped_typing;
3094 statusMessage =
3095 Message.createStatusMessage(
3096 conversation, getString(id, UIHelper.getDisplayName(user)));
3097 statusMessage.setTrueCounterpart(user.getRealJid());
3098 statusMessage.setCounterpart(user.getFullJid());
3099 } else {
3100 int id =
3101 state == ChatState.COMPOSING
3102 ? R.string.contacts_are_typing
3103 : R.string.contacts_have_stopped_typing;
3104 statusMessage =
3105 Message.createStatusMessage(
3106 conversation, getString(id, UIHelper.concatNames(users)));
3107 statusMessage.setCounterparts(users);
3108 }
3109 this.messageList.add(statusMessage);
3110 }
3111 }
3112 }
3113
3114 private void stopScrolling() {
3115 long now = SystemClock.uptimeMillis();
3116 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3117 binding.messagesView.dispatchTouchEvent(cancel);
3118 }
3119
3120 private boolean showLoadMoreMessages(final Conversation c) {
3121 if (activity == null || activity.xmppConnectionService == null) {
3122 return false;
3123 }
3124 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3125 final MessageArchiveService service =
3126 activity.xmppConnectionService.getMessageArchiveService();
3127 return mam
3128 && (c.getLastClearHistory().getTimestamp() != 0
3129 || (c.countMessages() == 0
3130 && c.messagesLoaded.get()
3131 && c.hasMessagesLeftOnServer()
3132 && !service.queryInProgress(c)));
3133 }
3134
3135 private boolean hasMamSupport(final Conversation c) {
3136 if (c.getMode() == Conversation.MODE_SINGLE) {
3137 final XmppConnection connection = c.getAccount().getXmppConnection();
3138 return connection != null && connection.getFeatures().mam();
3139 } else {
3140 return c.getMucOptions().mamSupport();
3141 }
3142 }
3143
3144 protected void showSnackbar(
3145 final int message, final int action, final OnClickListener clickListener) {
3146 showSnackbar(message, action, clickListener, null);
3147 }
3148
3149 protected void showSnackbar(
3150 final int message,
3151 final int action,
3152 final OnClickListener clickListener,
3153 final View.OnLongClickListener longClickListener) {
3154 this.binding.snackbar.setVisibility(View.VISIBLE);
3155 this.binding.snackbar.setOnClickListener(null);
3156 this.binding.snackbarMessage.setText(message);
3157 this.binding.snackbarMessage.setOnClickListener(null);
3158 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3159 if (action != 0) {
3160 this.binding.snackbarAction.setText(action);
3161 }
3162 this.binding.snackbarAction.setOnClickListener(clickListener);
3163 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3164 }
3165
3166 protected void hideSnackbar() {
3167 this.binding.snackbar.setVisibility(View.GONE);
3168 }
3169
3170 protected void sendMessage(Message message) {
3171 activity.xmppConnectionService.sendMessage(message);
3172 messageSent();
3173 }
3174
3175 protected void sendPgpMessage(final Message message) {
3176 final XmppConnectionService xmppService = activity.xmppConnectionService;
3177 final Contact contact = message.getConversation().getContact();
3178 if (!activity.hasPgp()) {
3179 activity.showInstallPgpDialog();
3180 return;
3181 }
3182 if (conversation.getAccount().getPgpSignature() == null) {
3183 activity.announcePgp(
3184 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3185 return;
3186 }
3187 if (!mSendingPgpMessage.compareAndSet(false, true)) {
3188 Log.d(Config.LOGTAG, "sending pgp message already in progress");
3189 }
3190 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3191 if (contact.getPgpKeyId() != 0) {
3192 xmppService
3193 .getPgpEngine()
3194 .hasKey(
3195 contact,
3196 new UiCallback<Contact>() {
3197
3198 @Override
3199 public void userInputRequired(
3200 PendingIntent pi, Contact contact) {
3201 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3202 }
3203
3204 @Override
3205 public void success(Contact contact) {
3206 encryptTextMessage(message);
3207 }
3208
3209 @Override
3210 public void error(int error, Contact contact) {
3211 activity.runOnUiThread(
3212 () ->
3213 Toast.makeText(
3214 activity,
3215 R.string
3216 .unable_to_connect_to_keychain,
3217 Toast.LENGTH_SHORT)
3218 .show());
3219 mSendingPgpMessage.set(false);
3220 }
3221 });
3222
3223 } else {
3224 showNoPGPKeyDialog(
3225 false,
3226 (dialog, which) -> {
3227 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3228 xmppService.updateConversation(conversation);
3229 message.setEncryption(Message.ENCRYPTION_NONE);
3230 xmppService.sendMessage(message);
3231 messageSent();
3232 });
3233 }
3234 } else {
3235 if (conversation.getMucOptions().pgpKeysInUse()) {
3236 if (!conversation.getMucOptions().everybodyHasKeys()) {
3237 Toast warning =
3238 Toast.makeText(
3239 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3240 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3241 warning.show();
3242 }
3243 encryptTextMessage(message);
3244 } else {
3245 showNoPGPKeyDialog(
3246 true,
3247 (dialog, which) -> {
3248 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3249 message.setEncryption(Message.ENCRYPTION_NONE);
3250 xmppService.updateConversation(conversation);
3251 xmppService.sendMessage(message);
3252 messageSent();
3253 });
3254 }
3255 }
3256 }
3257
3258 public void encryptTextMessage(Message message) {
3259 activity.xmppConnectionService
3260 .getPgpEngine()
3261 .encrypt(
3262 message,
3263 new UiCallback<Message>() {
3264
3265 @Override
3266 public void userInputRequired(PendingIntent pi, Message message) {
3267 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3268 }
3269
3270 @Override
3271 public void success(Message message) {
3272 // TODO the following two call can be made before the callback
3273 getActivity().runOnUiThread(() -> messageSent());
3274 }
3275
3276 @Override
3277 public void error(final int error, Message message) {
3278 getActivity()
3279 .runOnUiThread(
3280 () -> {
3281 doneSendingPgpMessage();
3282 Toast.makeText(
3283 getActivity(),
3284 error == 0
3285 ? R.string
3286 .unable_to_connect_to_keychain
3287 : error,
3288 Toast.LENGTH_SHORT)
3289 .show();
3290 });
3291 }
3292 });
3293 }
3294
3295 public void showNoPGPKeyDialog(
3296 final boolean plural, final DialogInterface.OnClickListener listener) {
3297 final MaterialAlertDialogBuilder builder =
3298 new MaterialAlertDialogBuilder(requireActivity());
3299 if (plural) {
3300 builder.setTitle(getString(R.string.no_pgp_keys));
3301 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3302 } else {
3303 builder.setTitle(getString(R.string.no_pgp_key));
3304 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3305 }
3306 builder.setNegativeButton(getString(R.string.cancel), null);
3307 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3308 builder.create().show();
3309 }
3310
3311 public void appendText(String text, final boolean doNotAppend) {
3312 if (text == null) {
3313 return;
3314 }
3315 final Editable editable = this.binding.textinput.getText();
3316 String previous = editable == null ? "" : editable.toString();
3317 if (doNotAppend && !TextUtils.isEmpty(previous)) {
3318 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3319 .show();
3320 return;
3321 }
3322 if (UIHelper.isLastLineQuote(previous)) {
3323 text = '\n' + text;
3324 } else if (previous.length() != 0
3325 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3326 text = " " + text;
3327 }
3328 this.binding.textinput.append(text);
3329 }
3330
3331 @Override
3332 public boolean onEnterPressed(final boolean isCtrlPressed) {
3333 if (isCtrlPressed || enterIsSend()) {
3334 sendMessage();
3335 return true;
3336 }
3337 return false;
3338 }
3339
3340 private boolean enterIsSend() {
3341 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3342 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3343 }
3344
3345 public boolean onArrowUpCtrlPressed() {
3346 final Message lastEditableMessage =
3347 conversation == null ? null : conversation.getLastEditableMessage();
3348 if (lastEditableMessage != null) {
3349 correctMessage(lastEditableMessage);
3350 return true;
3351 } else {
3352 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3353 .show();
3354 return false;
3355 }
3356 }
3357
3358 @Override
3359 public void onTypingStarted() {
3360 final XmppConnectionService service =
3361 activity == null ? null : activity.xmppConnectionService;
3362 if (service == null) {
3363 return;
3364 }
3365 final Account.State status = conversation.getAccount().getStatus();
3366 if (status == Account.State.ONLINE
3367 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3368 service.sendChatState(conversation);
3369 }
3370 runOnUiThread(this::updateSendButton);
3371 }
3372
3373 @Override
3374 public void onTypingStopped() {
3375 final XmppConnectionService service =
3376 activity == null ? null : activity.xmppConnectionService;
3377 if (service == null) {
3378 return;
3379 }
3380 final Account.State status = conversation.getAccount().getStatus();
3381 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3382 service.sendChatState(conversation);
3383 }
3384 }
3385
3386 @Override
3387 public void onTextDeleted() {
3388 final XmppConnectionService service =
3389 activity == null ? null : activity.xmppConnectionService;
3390 if (service == null) {
3391 return;
3392 }
3393 final Account.State status = conversation.getAccount().getStatus();
3394 if (status == Account.State.ONLINE
3395 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3396 service.sendChatState(conversation);
3397 }
3398 if (storeNextMessage()) {
3399 runOnUiThread(
3400 () -> {
3401 if (activity == null) {
3402 return;
3403 }
3404 activity.onConversationsListItemUpdated();
3405 });
3406 }
3407 runOnUiThread(this::updateSendButton);
3408 }
3409
3410 @Override
3411 public void onTextChanged() {
3412 if (conversation != null && conversation.getCorrectingMessage() != null) {
3413 runOnUiThread(this::updateSendButton);
3414 }
3415 }
3416
3417 @Override
3418 public boolean onTabPressed(boolean repeated) {
3419 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3420 return false;
3421 }
3422 if (repeated) {
3423 completionIndex++;
3424 } else {
3425 lastCompletionLength = 0;
3426 completionIndex = 0;
3427 final String content = this.binding.textinput.getText().toString();
3428 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
3429 int start =
3430 lastCompletionCursor > 0
3431 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
3432 : 0;
3433 firstWord = start == 0;
3434 incomplete = content.substring(start, lastCompletionCursor);
3435 }
3436 List<String> completions = new ArrayList<>();
3437 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
3438 String name = user.getName();
3439 if (name != null && name.startsWith(incomplete)) {
3440 completions.add(name + (firstWord ? ": " : " "));
3441 }
3442 }
3443 Collections.sort(completions);
3444 if (completions.size() > completionIndex) {
3445 String completion = completions.get(completionIndex).substring(incomplete.length());
3446 this.binding
3447 .textinput
3448 .getEditableText()
3449 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3450 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
3451 lastCompletionLength = completion.length();
3452 } else {
3453 completionIndex = -1;
3454 this.binding
3455 .textinput
3456 .getEditableText()
3457 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3458 lastCompletionLength = 0;
3459 }
3460 return true;
3461 }
3462
3463 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
3464 try {
3465 getActivity()
3466 .startIntentSenderForResult(
3467 pendingIntent.getIntentSender(),
3468 requestCode,
3469 null,
3470 0,
3471 0,
3472 0,
3473 Compatibility.pgpStartIntentSenderOptions());
3474 } catch (final SendIntentException ignored) {
3475 }
3476 }
3477
3478 @Override
3479 public void onBackendConnected() {
3480 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
3481 String uuid = pendingConversationsUuid.pop();
3482 if (uuid != null) {
3483 if (!findAndReInitByUuidOrArchive(uuid)) {
3484 return;
3485 }
3486 } else {
3487 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
3488 clearPending();
3489 activity.onConversationArchived(conversation);
3490 return;
3491 }
3492 }
3493 ActivityResult activityResult = postponedActivityResult.pop();
3494 if (activityResult != null) {
3495 handleActivityResult(activityResult);
3496 }
3497 clearPending();
3498 }
3499
3500 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
3501 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
3502 if (conversation == null) {
3503 clearPending();
3504 activity.onConversationArchived(null);
3505 return false;
3506 }
3507 reInit(conversation);
3508 ScrollState scrollState = pendingScrollState.pop();
3509 String lastMessageUuid = pendingLastMessageUuid.pop();
3510 List<Attachment> attachments = pendingMediaPreviews.pop();
3511 if (scrollState != null) {
3512 setScrollPosition(scrollState, lastMessageUuid);
3513 }
3514 if (attachments != null && attachments.size() > 0) {
3515 Log.d(Config.LOGTAG, "had attachments on restore");
3516 mediaPreviewAdapter.addMediaPreviews(attachments);
3517 toggleInputMethod();
3518 }
3519 return true;
3520 }
3521
3522 private void clearPending() {
3523 if (postponedActivityResult.clear()) {
3524 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
3525 if (pendingTakePhotoUri.clear()) {
3526 Log.e(Config.LOGTAG, "cleared pending photo uri");
3527 }
3528 }
3529 if (pendingScrollState.clear()) {
3530 Log.e(Config.LOGTAG, "cleared scroll state");
3531 }
3532 if (pendingConversationsUuid.clear()) {
3533 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
3534 }
3535 if (pendingMediaPreviews.clear()) {
3536 Log.e(Config.LOGTAG, "cleared pending media previews");
3537 }
3538 }
3539
3540 public Conversation getConversation() {
3541 return conversation;
3542 }
3543
3544 @Override
3545 public void onContactPictureLongClicked(View v, final Message message) {
3546 final String fingerprint;
3547 if (message.getEncryption() == Message.ENCRYPTION_PGP
3548 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3549 fingerprint = "pgp";
3550 } else {
3551 fingerprint = message.getFingerprint();
3552 }
3553 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
3554 final Contact contact = message.getContact();
3555 if (message.getStatus() <= Message.STATUS_RECEIVED
3556 && (contact == null || !contact.isSelf())) {
3557 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
3558 final Jid cp = message.getCounterpart();
3559 if (cp == null || cp.isBareJid()) {
3560 return;
3561 }
3562 final Jid tcp = message.getTrueCounterpart();
3563 final User userByRealJid =
3564 tcp != null
3565 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
3566 : null;
3567 final User user =
3568 userByRealJid != null
3569 ? userByRealJid
3570 : conversation.getMucOptions().findUserByFullJid(cp);
3571 popupMenu.inflate(R.menu.muc_details_context);
3572 final Menu menu = popupMenu.getMenu();
3573 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
3574 activity, menu, conversation, user);
3575 popupMenu.setOnMenuItemClickListener(
3576 menuItem ->
3577 MucDetailsContextMenuHelper.onContextItemSelected(
3578 menuItem, user, activity, fingerprint));
3579 } else {
3580 popupMenu.inflate(R.menu.one_on_one_context);
3581 popupMenu.setOnMenuItemClickListener(
3582 item -> {
3583 switch (item.getItemId()) {
3584 case R.id.action_contact_details:
3585 activity.switchToContactDetails(
3586 message.getContact(), fingerprint);
3587 break;
3588 case R.id.action_show_qr_code:
3589 activity.showQrCode(
3590 "xmpp:"
3591 + message.getContact()
3592 .getJid()
3593 .asBareJid()
3594 .toString());
3595 break;
3596 }
3597 return true;
3598 });
3599 }
3600 } else {
3601 popupMenu.inflate(R.menu.account_context);
3602 final Menu menu = popupMenu.getMenu();
3603 menu.findItem(R.id.action_manage_accounts)
3604 .setVisible(QuickConversationsService.isConversations());
3605 popupMenu.setOnMenuItemClickListener(
3606 item -> {
3607 final XmppActivity activity = this.activity;
3608 if (activity == null) {
3609 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
3610 return true;
3611 }
3612 switch (item.getItemId()) {
3613 case R.id.action_show_qr_code:
3614 activity.showQrCode(conversation.getAccount().getShareableUri());
3615 break;
3616 case R.id.action_account_details:
3617 activity.switchToAccount(
3618 message.getConversation().getAccount(), fingerprint);
3619 break;
3620 case R.id.action_manage_accounts:
3621 AccountUtils.launchManageAccounts(activity);
3622 break;
3623 }
3624 return true;
3625 });
3626 }
3627 popupMenu.show();
3628 }
3629
3630 @Override
3631 public void onContactPictureClicked(Message message) {
3632 String fingerprint;
3633 if (message.getEncryption() == Message.ENCRYPTION_PGP
3634 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3635 fingerprint = "pgp";
3636 } else {
3637 fingerprint = message.getFingerprint();
3638 }
3639 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
3640 if (received) {
3641 if (message.getConversation() instanceof Conversation
3642 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
3643 Jid tcp = message.getTrueCounterpart();
3644 Jid user = message.getCounterpart();
3645 if (user != null && !user.isBareJid()) {
3646 final MucOptions mucOptions =
3647 ((Conversation) message.getConversation()).getMucOptions();
3648 if (mucOptions.participating()
3649 || ((Conversation) message.getConversation()).getNextCounterpart()
3650 != null) {
3651 if (!mucOptions.isUserInRoom(user)
3652 && mucOptions.findUserByRealJid(
3653 tcp == null ? null : tcp.asBareJid())
3654 == null) {
3655 Toast.makeText(
3656 getActivity(),
3657 activity.getString(
3658 R.string.user_has_left_conference,
3659 user.getResource()),
3660 Toast.LENGTH_SHORT)
3661 .show();
3662 }
3663 highlightInConference(user.getResource());
3664 } else {
3665 Toast.makeText(
3666 getActivity(),
3667 R.string.you_are_not_participating,
3668 Toast.LENGTH_SHORT)
3669 .show();
3670 }
3671 }
3672 return;
3673 } else {
3674 if (!message.getContact().isSelf()) {
3675 activity.switchToContactDetails(message.getContact(), fingerprint);
3676 return;
3677 }
3678 }
3679 }
3680 activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
3681 }
3682
3683 private Activity requireActivity() {
3684 final Activity activity = getActivity();
3685 if (activity == null) {
3686 throw new IllegalStateException("Activity not attached");
3687 }
3688 return activity;
3689 }
3690}