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