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