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