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