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