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