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