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