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