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