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