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