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 ("message".equals(postInitAction)) {
2914 binding.conversationViewPager.post(() -> {
2915 binding.conversationViewPager.setCurrentItem(0);
2916 });
2917 }
2918 if ("command".equals(postInitAction)) {
2919 binding.conversationViewPager.post(() -> {
2920 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
2921 if (adapter != null && adapter.getCount() > 1) {
2922 binding.conversationViewPager.setCurrentItem(1);
2923 }
2924 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
2925 Jid commandJid = null;
2926 if (jid != null) {
2927 try {
2928 commandJid = Jid.of(jid);
2929 } catch (final IllegalArgumentException e) { }
2930 }
2931 if (commandJid == null || !commandJid.isFullJid()) {
2932 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
2933 if (discoJid != null) commandJid = discoJid;
2934 }
2935 if (node != null && commandJid != null) {
2936 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
2937 }
2938 });
2939 return;
2940 }
2941 final Message message =
2942 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2943 if (message != null) {
2944 startDownloadable(message);
2945 }
2946 }
2947
2948 private Element commandFor(final Jid jid, final String node) {
2949 if (commandAdapter != null) {
2950 for (int i = 0; i < commandAdapter.getCount(); i++) {
2951 Element command = commandAdapter.getItem(i);
2952 final String commandNode = command.getAttribute("node");
2953 if (commandNode == null || !commandNode.equals(node)) continue;
2954
2955 final Jid commandJid = command.getAttributeAsJid("jid");
2956 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
2957
2958 return command;
2959 }
2960 }
2961
2962 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
2963 }
2964
2965 private List<Uri> extractUris(final Bundle extras) {
2966 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2967 if (uris != null) {
2968 return uris;
2969 }
2970 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2971 if (uri != null) {
2972 return Collections.singletonList(uri);
2973 } else {
2974 return null;
2975 }
2976 }
2977
2978 private List<Uri> cleanUris(final List<Uri> uris) {
2979 final Iterator<Uri> iterator = uris.iterator();
2980 while (iterator.hasNext()) {
2981 final Uri uri = iterator.next();
2982 if (FileBackend.weOwnFile(uri)) {
2983 iterator.remove();
2984 Toast.makeText(
2985 getActivity(),
2986 R.string.security_violation_not_attaching_file,
2987 Toast.LENGTH_SHORT)
2988 .show();
2989 }
2990 }
2991 return uris;
2992 }
2993
2994 private boolean showBlockSubmenu(View view) {
2995 final Jid jid = conversation.getJid();
2996 final boolean showReject =
2997 !conversation.isWithStranger()
2998 && conversation
2999 .getContact()
3000 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3001 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3002 popupMenu.inflate(R.menu.block);
3003 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3004 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3005 popupMenu.setOnMenuItemClickListener(
3006 menuItem -> {
3007 Blockable blockable;
3008 switch (menuItem.getItemId()) {
3009 case R.id.reject:
3010 activity.xmppConnectionService.stopPresenceUpdatesTo(
3011 conversation.getContact());
3012 updateSnackBar(conversation);
3013 return true;
3014 case R.id.block_domain:
3015 blockable =
3016 conversation
3017 .getAccount()
3018 .getRoster()
3019 .getContact(jid.getDomain());
3020 break;
3021 default:
3022 blockable = conversation;
3023 }
3024 BlockContactDialog.show(activity, blockable);
3025 return true;
3026 });
3027 popupMenu.show();
3028 return true;
3029 }
3030
3031 private void updateSnackBar(final Conversation conversation) {
3032 final Account account = conversation.getAccount();
3033 final XmppConnection connection = account.getXmppConnection();
3034 final int mode = conversation.getMode();
3035 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3036 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3037 return;
3038 }
3039 if (account.getStatus() == Account.State.DISABLED) {
3040 showSnackbar(
3041 R.string.this_account_is_disabled,
3042 R.string.enable,
3043 this.mEnableAccountListener);
3044 } else if (conversation.isBlocked()) {
3045 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3046 } else if (contact != null
3047 && !contact.showInRoster()
3048 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3049 showSnackbar(
3050 R.string.contact_added_you,
3051 R.string.add_back,
3052 this.mAddBackClickListener,
3053 this.mLongPressBlockListener);
3054 } else if (contact != null
3055 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3056 showSnackbar(
3057 R.string.contact_asks_for_presence_subscription,
3058 R.string.allow,
3059 this.mAllowPresenceSubscription,
3060 this.mLongPressBlockListener);
3061 } else if (mode == Conversation.MODE_MULTI
3062 && !conversation.getMucOptions().online()
3063 && account.getStatus() == Account.State.ONLINE) {
3064 switch (conversation.getMucOptions().getError()) {
3065 case NICK_IN_USE:
3066 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3067 break;
3068 case NO_RESPONSE:
3069 showSnackbar(R.string.joining_conference, 0, null);
3070 break;
3071 case SERVER_NOT_FOUND:
3072 if (conversation.receivedMessagesCount() > 0) {
3073 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3074 } else {
3075 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3076 }
3077 break;
3078 case REMOTE_SERVER_TIMEOUT:
3079 if (conversation.receivedMessagesCount() > 0) {
3080 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3081 } else {
3082 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3083 }
3084 break;
3085 case PASSWORD_REQUIRED:
3086 showSnackbar(
3087 R.string.conference_requires_password,
3088 R.string.enter_password,
3089 enterPassword);
3090 break;
3091 case BANNED:
3092 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3093 break;
3094 case MEMBERS_ONLY:
3095 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3096 break;
3097 case RESOURCE_CONSTRAINT:
3098 showSnackbar(
3099 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3100 break;
3101 case KICKED:
3102 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3103 break;
3104 case TECHNICAL_PROBLEMS:
3105 showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3106 break;
3107 case UNKNOWN:
3108 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3109 break;
3110 case INVALID_NICK:
3111 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3112 case SHUTDOWN:
3113 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3114 break;
3115 case DESTROYED:
3116 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3117 break;
3118 case NON_ANONYMOUS:
3119 showSnackbar(
3120 R.string.group_chat_will_make_your_jabber_id_public,
3121 R.string.join,
3122 acceptJoin);
3123 break;
3124 default:
3125 hideSnackbar();
3126 break;
3127 }
3128 } else if (account.hasPendingPgpIntent(conversation)) {
3129 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3130 } else if (connection != null
3131 && connection.getFeatures().blocking()
3132 && conversation.countMessages() != 0
3133 && !conversation.isBlocked()
3134 && conversation.isWithStranger()) {
3135 showSnackbar(
3136 R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
3137 } else {
3138 hideSnackbar();
3139 }
3140 }
3141
3142 @Override
3143 public void refresh() {
3144 if (this.binding == null) {
3145 Log.d(
3146 Config.LOGTAG,
3147 "ConversationFragment.refresh() skipped updated because view binding was null");
3148 return;
3149 }
3150 if (this.conversation != null
3151 && this.activity != null
3152 && this.activity.xmppConnectionService != null) {
3153 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3154 activity.onConversationArchived(this.conversation);
3155 return;
3156 }
3157 }
3158 this.refresh(true);
3159 }
3160
3161 private void refresh(boolean notifyConversationRead) {
3162 synchronized (this.messageList) {
3163 if (this.conversation != null) {
3164 conversation.populateWithMessages(this.messageList);
3165 updateSnackBar(conversation);
3166 updateStatusMessages();
3167 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3168 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3169 binding.unreadCountCustomView.setUnreadCount(
3170 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3171 }
3172 this.messageListAdapter.notifyDataSetChanged();
3173 updateChatMsgHint();
3174 if (notifyConversationRead && activity != null) {
3175 binding.messagesView.post(this::fireReadEvent);
3176 }
3177 updateSendButton();
3178 updateEditablity();
3179 }
3180 }
3181 }
3182
3183 protected void messageSent() {
3184 mSendingPgpMessage.set(false);
3185 this.binding.textinput.setText("");
3186 if (conversation.setCorrectingMessage(null)) {
3187 this.binding.textinput.append(conversation.getDraftMessage());
3188 conversation.setDraftMessage(null);
3189 }
3190 storeNextMessage();
3191 updateChatMsgHint();
3192 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3193 final boolean prefScrollToBottom =
3194 p.getBoolean(
3195 "scroll_to_bottom",
3196 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3197 if (prefScrollToBottom || scrolledToBottom()) {
3198 new Handler()
3199 .post(
3200 () -> {
3201 int size = messageList.size();
3202 this.binding.messagesView.setSelection(size - 1);
3203 });
3204 }
3205 }
3206
3207 private boolean storeNextMessage() {
3208 return storeNextMessage(this.binding.textinput.getText().toString());
3209 }
3210
3211 private boolean storeNextMessage(String msg) {
3212 final boolean participating =
3213 conversation.getMode() == Conversational.MODE_SINGLE
3214 || conversation.getMucOptions().participating();
3215 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3216 && participating
3217 && this.conversation.setNextMessage(msg)) {
3218 this.activity.xmppConnectionService.updateConversation(this.conversation);
3219 return true;
3220 }
3221 return false;
3222 }
3223
3224 public void doneSendingPgpMessage() {
3225 mSendingPgpMessage.set(false);
3226 }
3227
3228 public long getMaxHttpUploadSize(Conversation conversation) {
3229 final XmppConnection connection = conversation.getAccount().getXmppConnection();
3230 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3231 }
3232
3233 private void updateEditablity() {
3234 boolean canWrite =
3235 this.conversation.getMode() == Conversation.MODE_SINGLE
3236 || this.conversation.getMucOptions().participating()
3237 || this.conversation.getNextCounterpart() != null;
3238 this.binding.textinput.setFocusable(canWrite);
3239 this.binding.textinput.setFocusableInTouchMode(canWrite);
3240 this.binding.textSendButton.setEnabled(canWrite);
3241 this.binding.textinput.setCursorVisible(canWrite);
3242 this.binding.textinput.setEnabled(canWrite);
3243 }
3244
3245 public void updateSendButton() {
3246 boolean hasAttachments =
3247 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3248 final Conversation c = this.conversation;
3249 final Presence.Status status;
3250 final String text =
3251 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3252 final SendButtonAction action;
3253 if (hasAttachments) {
3254 action = SendButtonAction.TEXT;
3255 } else {
3256 action = SendButtonTool.getAction(getActivity(), c, text);
3257 }
3258 if (c.getAccount().getStatus() == Account.State.ONLINE) {
3259 if (activity != null
3260 && activity.xmppConnectionService != null
3261 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3262 status = Presence.Status.OFFLINE;
3263 } else if (c.getMode() == Conversation.MODE_SINGLE) {
3264 status = c.getContact().getShownStatus();
3265 } else {
3266 status =
3267 c.getMucOptions().online()
3268 ? Presence.Status.ONLINE
3269 : Presence.Status.OFFLINE;
3270 }
3271 } else {
3272 status = Presence.Status.OFFLINE;
3273 }
3274 this.binding.textSendButton.setTag(action);
3275 final Activity activity = getActivity();
3276 if (activity != null) {
3277 this.binding.textSendButton.setImageResource(
3278 SendButtonTool.getSendButtonImageResource(activity, action, status));
3279 }
3280
3281 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3282 if (identiconWidth < 0) identiconWidth = params.width;
3283 if (hasAttachments || binding.textinput.getText().length() > 0) {
3284 binding.conversationViewPager.setCurrentItem(0);
3285 params.width = conversation.getThread() == null ? 0 : identiconWidth;
3286 } else {
3287 params.width = identiconWidth;
3288 }
3289 binding.threadIdenticonLayout.setLayoutParams(params);
3290 }
3291
3292 protected void updateStatusMessages() {
3293 DateSeparator.addAll(this.messageList);
3294 if (showLoadMoreMessages(conversation)) {
3295 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3296 }
3297 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3298 ChatState state = conversation.getIncomingChatState();
3299 if (state == ChatState.COMPOSING) {
3300 this.messageList.add(
3301 Message.createStatusMessage(
3302 conversation,
3303 getString(R.string.contact_is_typing, conversation.getName())));
3304 } else if (state == ChatState.PAUSED) {
3305 this.messageList.add(
3306 Message.createStatusMessage(
3307 conversation,
3308 getString(
3309 R.string.contact_has_stopped_typing,
3310 conversation.getName())));
3311 } else {
3312 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3313 final Message message = this.messageList.get(i);
3314 if (message.getType() != Message.TYPE_STATUS) {
3315 if (message.getStatus() == Message.STATUS_RECEIVED) {
3316 return;
3317 } else {
3318 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3319 this.messageList.add(
3320 i + 1,
3321 Message.createStatusMessage(
3322 conversation,
3323 getString(
3324 R.string.contact_has_read_up_to_this_point,
3325 conversation.getName())));
3326 return;
3327 }
3328 }
3329 }
3330 }
3331 }
3332 } else {
3333 final MucOptions mucOptions = conversation.getMucOptions();
3334 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3335 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3336 ChatState state = ChatState.COMPOSING;
3337 List<MucOptions.User> users =
3338 conversation.getMucOptions().getUsersWithChatState(state, 5);
3339 if (users.size() == 0) {
3340 state = ChatState.PAUSED;
3341 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3342 }
3343 if (mucOptions.isPrivateAndNonAnonymous()) {
3344 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3345 final Set<ReadByMarker> markersForMessage =
3346 messageList.get(i).getReadByMarkers();
3347 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3348 for (ReadByMarker marker : markersForMessage) {
3349 if (!ReadByMarker.contains(marker, addedMarkers)) {
3350 addedMarkers.add(
3351 marker); // may be put outside this condition. set should do
3352 // dedup anyway
3353 MucOptions.User user = mucOptions.findUser(marker);
3354 if (user != null && !users.contains(user)) {
3355 shownMarkers.add(user);
3356 }
3357 }
3358 }
3359 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3360 final Message statusMessage;
3361 final int size = shownMarkers.size();
3362 if (size > 1) {
3363 final String body;
3364 if (size <= 4) {
3365 body =
3366 getString(
3367 R.string.contacts_have_read_up_to_this_point,
3368 UIHelper.concatNames(shownMarkers));
3369 } else if (ReadByMarker.allUsersRepresented(
3370 allUsers, markersForMessage, markerForSender)) {
3371 body = getString(R.string.everyone_has_read_up_to_this_point);
3372 } else {
3373 body =
3374 getString(
3375 R.string.contacts_and_n_more_have_read_up_to_this_point,
3376 UIHelper.concatNames(shownMarkers, 3),
3377 size - 3);
3378 }
3379 statusMessage = Message.createStatusMessage(conversation, body);
3380 statusMessage.setCounterparts(shownMarkers);
3381 } else if (size == 1) {
3382 statusMessage =
3383 Message.createStatusMessage(
3384 conversation,
3385 getString(
3386 R.string.contact_has_read_up_to_this_point,
3387 UIHelper.getDisplayName(shownMarkers.get(0))));
3388 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3389 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3390 } else {
3391 statusMessage = null;
3392 }
3393 if (statusMessage != null) {
3394 this.messageList.add(i + 1, statusMessage);
3395 }
3396 addedMarkers.add(markerForSender);
3397 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3398 break;
3399 }
3400 }
3401 }
3402 if (users.size() > 0) {
3403 Message statusMessage;
3404 if (users.size() == 1) {
3405 MucOptions.User user = users.get(0);
3406 int id =
3407 state == ChatState.COMPOSING
3408 ? R.string.contact_is_typing
3409 : R.string.contact_has_stopped_typing;
3410 statusMessage =
3411 Message.createStatusMessage(
3412 conversation, getString(id, UIHelper.getDisplayName(user)));
3413 statusMessage.setTrueCounterpart(user.getRealJid());
3414 statusMessage.setCounterpart(user.getFullJid());
3415 } else {
3416 int id =
3417 state == ChatState.COMPOSING
3418 ? R.string.contacts_are_typing
3419 : R.string.contacts_have_stopped_typing;
3420 statusMessage =
3421 Message.createStatusMessage(
3422 conversation, getString(id, UIHelper.concatNames(users)));
3423 statusMessage.setCounterparts(users);
3424 }
3425 this.messageList.add(statusMessage);
3426 }
3427 }
3428 }
3429
3430 private void stopScrolling() {
3431 long now = SystemClock.uptimeMillis();
3432 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3433 binding.messagesView.dispatchTouchEvent(cancel);
3434 }
3435
3436 private boolean showLoadMoreMessages(final Conversation c) {
3437 if (activity == null || activity.xmppConnectionService == null) {
3438 return false;
3439 }
3440 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3441 final MessageArchiveService service =
3442 activity.xmppConnectionService.getMessageArchiveService();
3443 return mam
3444 && (c.getLastClearHistory().getTimestamp() != 0
3445 || (c.countMessages() == 0
3446 && c.messagesLoaded.get()
3447 && c.hasMessagesLeftOnServer()
3448 && !service.queryInProgress(c)));
3449 }
3450
3451 private boolean hasMamSupport(final Conversation c) {
3452 if (c.getMode() == Conversation.MODE_SINGLE) {
3453 final XmppConnection connection = c.getAccount().getXmppConnection();
3454 return connection != null && connection.getFeatures().mam();
3455 } else {
3456 return c.getMucOptions().mamSupport();
3457 }
3458 }
3459
3460 protected void showSnackbar(
3461 final int message, final int action, final OnClickListener clickListener) {
3462 showSnackbar(message, action, clickListener, null);
3463 }
3464
3465 protected void showSnackbar(
3466 final int message,
3467 final int action,
3468 final OnClickListener clickListener,
3469 final View.OnLongClickListener longClickListener) {
3470 this.binding.snackbar.setVisibility(View.VISIBLE);
3471 this.binding.snackbar.setOnClickListener(null);
3472 this.binding.snackbarMessage.setText(message);
3473 this.binding.snackbarMessage.setOnClickListener(null);
3474 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3475 if (action != 0) {
3476 this.binding.snackbarAction.setText(action);
3477 }
3478 this.binding.snackbarAction.setOnClickListener(clickListener);
3479 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3480 }
3481
3482 protected void hideSnackbar() {
3483 this.binding.snackbar.setVisibility(View.GONE);
3484 }
3485
3486 protected void sendMessage(Message message) {
3487 activity.xmppConnectionService.sendMessage(message);
3488 messageSent();
3489 }
3490
3491 protected void sendPgpMessage(final Message message) {
3492 final XmppConnectionService xmppService = activity.xmppConnectionService;
3493 final Contact contact = message.getConversation().getContact();
3494 if (!activity.hasPgp()) {
3495 activity.showInstallPgpDialog();
3496 return;
3497 }
3498 if (conversation.getAccount().getPgpSignature() == null) {
3499 activity.announcePgp(
3500 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3501 return;
3502 }
3503 if (!mSendingPgpMessage.compareAndSet(false, true)) {
3504 Log.d(Config.LOGTAG, "sending pgp message already in progress");
3505 }
3506 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3507 if (contact.getPgpKeyId() != 0) {
3508 xmppService
3509 .getPgpEngine()
3510 .hasKey(
3511 contact,
3512 new UiCallback<Contact>() {
3513
3514 @Override
3515 public void userInputRequired(
3516 PendingIntent pi, Contact contact) {
3517 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3518 }
3519
3520 @Override
3521 public void success(Contact contact) {
3522 encryptTextMessage(message);
3523 }
3524
3525 @Override
3526 public void error(int error, Contact contact) {
3527 activity.runOnUiThread(
3528 () ->
3529 Toast.makeText(
3530 activity,
3531 R.string
3532 .unable_to_connect_to_keychain,
3533 Toast.LENGTH_SHORT)
3534 .show());
3535 mSendingPgpMessage.set(false);
3536 }
3537 });
3538
3539 } else {
3540 showNoPGPKeyDialog(
3541 false,
3542 (dialog, which) -> {
3543 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3544 xmppService.updateConversation(conversation);
3545 message.setEncryption(Message.ENCRYPTION_NONE);
3546 xmppService.sendMessage(message);
3547 messageSent();
3548 });
3549 }
3550 } else {
3551 if (conversation.getMucOptions().pgpKeysInUse()) {
3552 if (!conversation.getMucOptions().everybodyHasKeys()) {
3553 Toast warning =
3554 Toast.makeText(
3555 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3556 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3557 warning.show();
3558 }
3559 encryptTextMessage(message);
3560 } else {
3561 showNoPGPKeyDialog(
3562 true,
3563 (dialog, which) -> {
3564 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3565 message.setEncryption(Message.ENCRYPTION_NONE);
3566 xmppService.updateConversation(conversation);
3567 xmppService.sendMessage(message);
3568 messageSent();
3569 });
3570 }
3571 }
3572 }
3573
3574 public void encryptTextMessage(Message message) {
3575 activity.xmppConnectionService
3576 .getPgpEngine()
3577 .encrypt(
3578 message,
3579 new UiCallback<Message>() {
3580
3581 @Override
3582 public void userInputRequired(PendingIntent pi, Message message) {
3583 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3584 }
3585
3586 @Override
3587 public void success(Message message) {
3588 // TODO the following two call can be made before the callback
3589 getActivity().runOnUiThread(() -> messageSent());
3590 }
3591
3592 @Override
3593 public void error(final int error, Message message) {
3594 getActivity()
3595 .runOnUiThread(
3596 () -> {
3597 doneSendingPgpMessage();
3598 Toast.makeText(
3599 getActivity(),
3600 error == 0
3601 ? R.string
3602 .unable_to_connect_to_keychain
3603 : error,
3604 Toast.LENGTH_SHORT)
3605 .show();
3606 });
3607 }
3608 });
3609 }
3610
3611 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3612 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3613 builder.setIconAttribute(android.R.attr.alertDialogIcon);
3614 if (plural) {
3615 builder.setTitle(getString(R.string.no_pgp_keys));
3616 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3617 } else {
3618 builder.setTitle(getString(R.string.no_pgp_key));
3619 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3620 }
3621 builder.setNegativeButton(getString(R.string.cancel), null);
3622 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3623 builder.create().show();
3624 }
3625
3626 public void appendText(String text, final boolean doNotAppend) {
3627 if (text == null) {
3628 return;
3629 }
3630 final Editable editable = this.binding.textinput.getText();
3631 String previous = editable == null ? "" : editable.toString();
3632 if (doNotAppend && !TextUtils.isEmpty(previous)) {
3633 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3634 .show();
3635 return;
3636 }
3637 if (UIHelper.isLastLineQuote(previous)) {
3638 text = '\n' + text;
3639 } else if (previous.length() != 0
3640 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3641 text = " " + text;
3642 }
3643 this.binding.textinput.append(text);
3644 }
3645
3646 @Override
3647 public boolean onEnterPressed(final boolean isCtrlPressed) {
3648 if (isCtrlPressed || enterIsSend()) {
3649 sendMessage();
3650 return true;
3651 }
3652 return false;
3653 }
3654
3655 private boolean enterIsSend() {
3656 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3657 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3658 }
3659
3660 public boolean onArrowUpCtrlPressed() {
3661 final Message lastEditableMessage =
3662 conversation == null ? null : conversation.getLastEditableMessage();
3663 if (lastEditableMessage != null) {
3664 correctMessage(lastEditableMessage);
3665 return true;
3666 } else {
3667 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3668 .show();
3669 return false;
3670 }
3671 }
3672
3673 @Override
3674 public void onTypingStarted() {
3675 final XmppConnectionService service =
3676 activity == null ? null : activity.xmppConnectionService;
3677 if (service == null) {
3678 return;
3679 }
3680 final Account.State status = conversation.getAccount().getStatus();
3681 if (status == Account.State.ONLINE
3682 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3683 service.sendChatState(conversation);
3684 }
3685 runOnUiThread(this::updateSendButton);
3686 }
3687
3688 @Override
3689 public void onTypingStopped() {
3690 final XmppConnectionService service =
3691 activity == null ? null : activity.xmppConnectionService;
3692 if (service == null) {
3693 return;
3694 }
3695 final Account.State status = conversation.getAccount().getStatus();
3696 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3697 service.sendChatState(conversation);
3698 }
3699 }
3700
3701 @Override
3702 public void onTextDeleted() {
3703 final XmppConnectionService service =
3704 activity == null ? null : activity.xmppConnectionService;
3705 if (service == null) {
3706 return;
3707 }
3708 final Account.State status = conversation.getAccount().getStatus();
3709 if (status == Account.State.ONLINE
3710 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3711 service.sendChatState(conversation);
3712 }
3713 if (storeNextMessage()) {
3714 runOnUiThread(
3715 () -> {
3716 if (activity == null) {
3717 return;
3718 }
3719 activity.onConversationsListItemUpdated();
3720 });
3721 }
3722 runOnUiThread(this::updateSendButton);
3723 }
3724
3725 @Override
3726 public void onTextChanged() {
3727 if (conversation != null && conversation.getCorrectingMessage() != null) {
3728 runOnUiThread(this::updateSendButton);
3729 }
3730 }
3731
3732 @Override
3733 public boolean onTabPressed(boolean repeated) {
3734 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3735 return false;
3736 }
3737 if (repeated) {
3738 completionIndex++;
3739 } else {
3740 lastCompletionLength = 0;
3741 completionIndex = 0;
3742 final String content = this.binding.textinput.getText().toString();
3743 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
3744 int start =
3745 lastCompletionCursor > 0
3746 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
3747 : 0;
3748 firstWord = start == 0;
3749 incomplete = content.substring(start, lastCompletionCursor);
3750 }
3751 List<String> completions = new ArrayList<>();
3752 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
3753 String name = user.getName();
3754 if (name != null && name.startsWith(incomplete)) {
3755 completions.add(name + (firstWord ? ": " : " "));
3756 }
3757 }
3758 Collections.sort(completions);
3759 if (completions.size() > completionIndex) {
3760 String completion = completions.get(completionIndex).substring(incomplete.length());
3761 this.binding
3762 .textinput
3763 .getEditableText()
3764 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3765 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
3766 lastCompletionLength = completion.length();
3767 } else {
3768 completionIndex = -1;
3769 this.binding
3770 .textinput
3771 .getEditableText()
3772 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3773 lastCompletionLength = 0;
3774 }
3775 return true;
3776 }
3777
3778 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
3779 try {
3780 getActivity()
3781 .startIntentSenderForResult(
3782 pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
3783 } catch (final SendIntentException ignored) {
3784 }
3785 }
3786
3787 @Override
3788 public void onBackendConnected() {
3789 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
3790 String uuid = pendingConversationsUuid.pop();
3791 if (uuid != null) {
3792 if (!findAndReInitByUuidOrArchive(uuid)) {
3793 return;
3794 }
3795 } else {
3796 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
3797 clearPending();
3798 activity.onConversationArchived(conversation);
3799 return;
3800 }
3801 }
3802 ActivityResult activityResult = postponedActivityResult.pop();
3803 if (activityResult != null) {
3804 handleActivityResult(activityResult);
3805 }
3806 clearPending();
3807 }
3808
3809 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
3810 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
3811 if (conversation == null) {
3812 clearPending();
3813 activity.onConversationArchived(null);
3814 return false;
3815 }
3816 reInit(conversation);
3817 ScrollState scrollState = pendingScrollState.pop();
3818 String lastMessageUuid = pendingLastMessageUuid.pop();
3819 List<Attachment> attachments = pendingMediaPreviews.pop();
3820 if (scrollState != null) {
3821 setScrollPosition(scrollState, lastMessageUuid);
3822 }
3823 if (attachments != null && attachments.size() > 0) {
3824 Log.d(Config.LOGTAG, "had attachments on restore");
3825 mediaPreviewAdapter.addMediaPreviews(attachments);
3826 toggleInputMethod();
3827 }
3828 return true;
3829 }
3830
3831 private void clearPending() {
3832 if (postponedActivityResult.clear()) {
3833 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
3834 if (pendingTakePhotoUri.clear()) {
3835 Log.e(Config.LOGTAG, "cleared pending photo uri");
3836 }
3837 }
3838 if (pendingScrollState.clear()) {
3839 Log.e(Config.LOGTAG, "cleared scroll state");
3840 }
3841 if (pendingConversationsUuid.clear()) {
3842 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
3843 }
3844 if (pendingMediaPreviews.clear()) {
3845 Log.e(Config.LOGTAG, "cleared pending media previews");
3846 }
3847 }
3848
3849 public Conversation getConversation() {
3850 return conversation;
3851 }
3852
3853 @Override
3854 public void onContactPictureLongClicked(View v, final Message message) {
3855 final String fingerprint;
3856 if (message.getEncryption() == Message.ENCRYPTION_PGP
3857 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3858 fingerprint = "pgp";
3859 } else {
3860 fingerprint = message.getFingerprint();
3861 }
3862 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
3863 final Contact contact = message.getContact();
3864 if (message.getStatus() <= Message.STATUS_RECEIVED
3865 && (contact == null || !contact.isSelf())) {
3866 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
3867 final Jid cp = message.getCounterpart();
3868 if (cp == null || cp.isBareJid()) {
3869 return;
3870 }
3871 final Jid tcp = message.getTrueCounterpart();
3872 final User userByRealJid =
3873 tcp != null
3874 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
3875 : null;
3876 final User user =
3877 userByRealJid != null
3878 ? userByRealJid
3879 : conversation.getMucOptions().findUserByFullJid(cp);
3880 popupMenu.inflate(R.menu.muc_details_context);
3881 final Menu menu = popupMenu.getMenu();
3882 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
3883 activity, menu, conversation, user);
3884 popupMenu.setOnMenuItemClickListener(
3885 menuItem ->
3886 MucDetailsContextMenuHelper.onContextItemSelected(
3887 menuItem, user, activity, fingerprint));
3888 } else {
3889 popupMenu.inflate(R.menu.one_on_one_context);
3890 popupMenu.setOnMenuItemClickListener(
3891 item -> {
3892 switch (item.getItemId()) {
3893 case R.id.action_contact_details:
3894 activity.switchToContactDetails(
3895 message.getContact(), fingerprint);
3896 break;
3897 case R.id.action_show_qr_code:
3898 activity.showQrCode(
3899 "xmpp:"
3900 + message.getContact()
3901 .getJid()
3902 .asBareJid()
3903 .toEscapedString());
3904 break;
3905 }
3906 return true;
3907 });
3908 }
3909 } else {
3910 popupMenu.inflate(R.menu.account_context);
3911 final Menu menu = popupMenu.getMenu();
3912 menu.findItem(R.id.action_manage_accounts)
3913 .setVisible(QuickConversationsService.isConversations());
3914 popupMenu.setOnMenuItemClickListener(
3915 item -> {
3916 final XmppActivity activity = this.activity;
3917 if (activity == null) {
3918 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
3919 return true;
3920 }
3921 switch (item.getItemId()) {
3922 case R.id.action_show_qr_code:
3923 activity.showQrCode(conversation.getAccount().getShareableUri());
3924 break;
3925 case R.id.action_account_details:
3926 activity.switchToAccount(
3927 message.getConversation().getAccount(), fingerprint);
3928 break;
3929 case R.id.action_manage_accounts:
3930 AccountUtils.launchManageAccounts(activity);
3931 break;
3932 }
3933 return true;
3934 });
3935 }
3936 popupMenu.show();
3937 }
3938
3939 @Override
3940 public void onContactPictureClicked(Message message) {
3941 setThread(message.getThread());
3942 conversation.setUserSelectedThread(true);
3943
3944 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
3945 if (received) {
3946 if (message.getConversation() instanceof Conversation
3947 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
3948 Jid tcp = message.getTrueCounterpart();
3949 Jid user = message.getCounterpart();
3950 if (user != null && !user.isBareJid()) {
3951 final MucOptions mucOptions =
3952 ((Conversation) message.getConversation()).getMucOptions();
3953 if (mucOptions.participating()
3954 || ((Conversation) message.getConversation()).getNextCounterpart()
3955 != null) {
3956 if (!mucOptions.isUserInRoom(user)
3957 && mucOptions.findUserByRealJid(
3958 tcp == null ? null : tcp.asBareJid())
3959 == null) {
3960 Toast.makeText(
3961 getActivity(),
3962 activity.getString(
3963 R.string.user_has_left_conference,
3964 user.getResource()),
3965 Toast.LENGTH_SHORT)
3966 .show();
3967 }
3968 highlightInConference(user.getResource());
3969 } else {
3970 Toast.makeText(
3971 getActivity(),
3972 R.string.you_are_not_participating,
3973 Toast.LENGTH_SHORT)
3974 .show();
3975 }
3976 }
3977 }
3978 }
3979 }
3980
3981 private Activity requireActivity() {
3982 final Activity activity = getActivity();
3983 if (activity == null) {
3984 throw new IllegalStateException("Activity not attached");
3985 }
3986 return activity;
3987 }
3988}