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