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