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