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