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