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