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 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2519 if (thumbs != null && !thumbs.isEmpty()) {
2520 for (Element thumb : thumbs) {
2521 Uri uri = Uri.parse(thumb.getAttribute("uri"));
2522 if (uri.getScheme().equals("cid")) {
2523 Cid cid = BobTransfer.cid(uri);
2524 if (cid == null) continue;
2525 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2526 activity.xmppConnectionService.evictPreview(f);
2527 f.delete();
2528 }
2529 }
2530 }
2531 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2532 message.setDeleted(true);
2533 activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
2534 activity.xmppConnectionService.updateMessage(message, false);
2535 activity.onConversationsListItemUpdated();
2536 refresh();
2537 }
2538 });
2539 builder.create().show();
2540 }
2541
2542 private void resendMessage(final Message message) {
2543 if (message.isFileOrImage()) {
2544 if (!(message.getConversation() instanceof Conversation)) {
2545 return;
2546 }
2547 final Conversation conversation = (Conversation) message.getConversation();
2548 final DownloadableFile file =
2549 activity.xmppConnectionService.getFileBackend().getFile(message);
2550 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2551 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2552 if (!message.hasFileOnRemoteHost()
2553 && xmppConnection != null
2554 && conversation.getMode() == Conversational.MODE_SINGLE
2555 && !xmppConnection
2556 .getFeatures()
2557 .httpUpload(message.getFileParams().getSize())) {
2558 activity.selectPresence(
2559 conversation,
2560 () -> {
2561 message.setCounterpart(conversation.getNextCounterpart());
2562 activity.xmppConnectionService.resendFailedMessages(message);
2563 new Handler()
2564 .post(
2565 () -> {
2566 int size = messageList.size();
2567 this.binding.messagesView.setSelection(
2568 size - 1);
2569 });
2570 });
2571 return;
2572 }
2573 } else if (!Compatibility.hasStoragePermission(getActivity())) {
2574 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2575 return;
2576 } else {
2577 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2578 message.setDeleted(true);
2579 activity.xmppConnectionService.updateMessage(message, false);
2580 activity.onConversationsListItemUpdated();
2581 refresh();
2582 return;
2583 }
2584 }
2585 activity.xmppConnectionService.resendFailedMessages(message);
2586 new Handler()
2587 .post(
2588 () -> {
2589 int size = messageList.size();
2590 this.binding.messagesView.setSelection(size - 1);
2591 });
2592 }
2593
2594 private void cancelTransmission(Message message) {
2595 Transferable transferable = message.getTransferable();
2596 if (transferable != null) {
2597 transferable.cancel();
2598 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2599 activity.xmppConnectionService.markMessage(
2600 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2601 }
2602 }
2603
2604 private void retryDecryption(Message message) {
2605 message.setEncryption(Message.ENCRYPTION_PGP);
2606 activity.onConversationsListItemUpdated();
2607 refresh();
2608 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2609 }
2610
2611 public void privateMessageWith(final Jid counterpart) {
2612 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2613 activity.xmppConnectionService.sendChatState(conversation);
2614 }
2615 this.binding.textinput.setText("");
2616 this.conversation.setNextCounterpart(counterpart);
2617 updateChatMsgHint();
2618 updateSendButton();
2619 updateEditablity();
2620 }
2621
2622 private void correctMessage(Message message) {
2623 while (message.mergeable(message.next())) {
2624 message = message.next();
2625 }
2626 setThread(message.getThread());
2627 conversation.setUserSelectedThread(true);
2628 this.conversation.setCorrectingMessage(message);
2629 final Editable editable = binding.textinput.getText();
2630 this.conversation.setDraftMessage(editable.toString());
2631 this.binding.textinput.setText("");
2632 this.binding.textinput.append(message.getBody());
2633 }
2634
2635 private void highlightInConference(String nick) {
2636 final Editable editable = this.binding.textinput.getText();
2637 String oldString = editable.toString().trim();
2638 final int pos = this.binding.textinput.getSelectionStart();
2639 if (oldString.isEmpty() || pos == 0) {
2640 editable.insert(0, nick + ": ");
2641 } else {
2642 final char before = editable.charAt(pos - 1);
2643 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2644 if (before == '\n') {
2645 editable.insert(pos, nick + ": ");
2646 } else {
2647 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2648 if (NickValidityChecker.check(
2649 conversation,
2650 Arrays.asList(
2651 editable.subSequence(0, pos - 2).toString().split(", ")))) {
2652 editable.insert(pos - 2, ", " + nick);
2653 return;
2654 }
2655 }
2656 editable.insert(
2657 pos,
2658 (Character.isWhitespace(before) ? "" : " ")
2659 + nick
2660 + (Character.isWhitespace(after) ? "" : " "));
2661 if (Character.isWhitespace(after)) {
2662 this.binding.textinput.setSelection(
2663 this.binding.textinput.getSelectionStart() + 1);
2664 }
2665 }
2666 }
2667 }
2668
2669 @Override
2670 public void startActivityForResult(Intent intent, int requestCode) {
2671 final Activity activity = getActivity();
2672 if (activity instanceof ConversationsActivity) {
2673 ((ConversationsActivity) activity).clearPendingViewIntent();
2674 }
2675 super.startActivityForResult(intent, requestCode);
2676 }
2677
2678 @Override
2679 public void onSaveInstanceState(@NotNull Bundle outState) {
2680 super.onSaveInstanceState(outState);
2681 if (conversation != null) {
2682 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2683 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2684 final Uri uri = pendingTakePhotoUri.peek();
2685 if (uri != null) {
2686 outState.putString(STATE_PHOTO_URI, uri.toString());
2687 }
2688 final ScrollState scrollState = getScrollPosition();
2689 if (scrollState != null) {
2690 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2691 }
2692 final ArrayList<Attachment> attachments =
2693 mediaPreviewAdapter == null
2694 ? new ArrayList<>()
2695 : mediaPreviewAdapter.getAttachments();
2696 if (attachments.size() > 0) {
2697 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2698 }
2699 }
2700 }
2701
2702 @Override
2703 public void onActivityCreated(Bundle savedInstanceState) {
2704 super.onActivityCreated(savedInstanceState);
2705 if (savedInstanceState == null) {
2706 return;
2707 }
2708 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2709 ArrayList<Attachment> attachments =
2710 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2711 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2712 if (uuid != null) {
2713 QuickLoader.set(uuid);
2714 this.pendingConversationsUuid.push(uuid);
2715 if (attachments != null && attachments.size() > 0) {
2716 this.pendingMediaPreviews.push(attachments);
2717 }
2718 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2719 if (takePhotoUri != null) {
2720 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2721 }
2722 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2723 }
2724 }
2725
2726 @Override
2727 public void onStart() {
2728 super.onStart();
2729 if (this.reInitRequiredOnStart && this.conversation != null) {
2730 final Bundle extras = pendingExtras.pop();
2731 reInit(this.conversation, extras != null);
2732 if (extras != null) {
2733 processExtras(extras);
2734 }
2735 } else if (conversation == null
2736 && activity != null
2737 && activity.xmppConnectionService != null) {
2738 final String uuid = pendingConversationsUuid.pop();
2739 Log.d(
2740 Config.LOGTAG,
2741 "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
2742 + uuid);
2743 if (uuid != null) {
2744 findAndReInitByUuidOrArchive(uuid);
2745 }
2746 }
2747 }
2748
2749 @Override
2750 public void onStop() {
2751 super.onStop();
2752 final Activity activity = getActivity();
2753 messageListAdapter.unregisterListenerInAudioPlayer();
2754 if (activity == null || !activity.isChangingConfigurations()) {
2755 hideSoftKeyboard(activity);
2756 messageListAdapter.stopAudioPlayer();
2757 }
2758 if (this.conversation != null) {
2759 final String msg = this.binding.textinput.getText().toString();
2760 storeNextMessage(msg);
2761 updateChatState(this.conversation, msg);
2762 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2763 }
2764 this.reInitRequiredOnStart = true;
2765 }
2766
2767 private void updateChatState(final Conversation conversation, final String msg) {
2768 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2769 Account.State status = conversation.getAccount().getStatus();
2770 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2771 activity.xmppConnectionService.sendChatState(conversation);
2772 }
2773 }
2774
2775 private void saveMessageDraftStopAudioPlayer() {
2776 final Conversation previousConversation = this.conversation;
2777 if (this.activity == null || this.binding == null || previousConversation == null) {
2778 return;
2779 }
2780 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2781 final String msg = this.binding.textinput.getText().toString();
2782 storeNextMessage(msg);
2783 updateChatState(this.conversation, msg);
2784 messageListAdapter.stopAudioPlayer();
2785 mediaPreviewAdapter.clearPreviews();
2786 toggleInputMethod();
2787 }
2788
2789 public void reInit(final Conversation conversation, final Bundle extras) {
2790 QuickLoader.set(conversation.getUuid());
2791 final boolean changedConversation = this.conversation != conversation;
2792 if (changedConversation) {
2793 this.saveMessageDraftStopAudioPlayer();
2794 }
2795 this.clearPending();
2796 if (this.reInit(conversation, extras != null)) {
2797 if (extras != null) {
2798 processExtras(extras);
2799 }
2800 this.reInitRequiredOnStart = false;
2801 } else {
2802 this.reInitRequiredOnStart = true;
2803 pendingExtras.push(extras);
2804 }
2805 resetUnreadMessagesCount();
2806 }
2807
2808 private void reInit(Conversation conversation) {
2809 reInit(conversation, false);
2810 }
2811
2812 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2813 if (conversation == null) {
2814 return false;
2815 }
2816 final Conversation originalConversation = this.conversation;
2817 this.conversation = conversation;
2818 // once we set the conversation all is good and it will automatically do the right thing in
2819 // onStart()
2820 if (this.activity == null || this.binding == null) {
2821 return false;
2822 }
2823
2824 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2825 activity.onConversationArchived(this.conversation);
2826 return false;
2827 }
2828
2829 setThread(conversation.getThread());
2830 setupReply(conversation.getReplyTo());
2831
2832 stopScrolling();
2833 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
2834
2835 if (this.conversation.isRead() && hasExtras) {
2836 Log.d(Config.LOGTAG, "trimming conversation");
2837 this.conversation.trim();
2838 }
2839
2840 setupIme();
2841
2842 final boolean scrolledToBottomAndNoPending =
2843 this.scrolledToBottom() && pendingScrollState.peek() == null;
2844
2845 this.binding.textSendButton.setContentDescription(
2846 activity.getString(R.string.send_message_to_x, conversation.getName()));
2847 this.binding.textinput.setKeyboardListener(null);
2848 final boolean participating =
2849 conversation.getMode() == Conversational.MODE_SINGLE
2850 || conversation.getMucOptions().participating();
2851 if (participating) {
2852 this.binding.textinput.setText(this.conversation.getNextMessage());
2853 this.binding.textinput.setSelection(this.binding.textinput.length());
2854 } else {
2855 this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
2856 }
2857 this.binding.textinput.setKeyboardListener(this);
2858 messageListAdapter.updatePreferences();
2859 refresh(false);
2860 activity.invalidateOptionsMenu();
2861 this.conversation.messagesLoaded.set(true);
2862 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
2863
2864 if (hasExtras || scrolledToBottomAndNoPending) {
2865 resetUnreadMessagesCount();
2866 synchronized (this.messageList) {
2867 Log.d(Config.LOGTAG, "jump to first unread message");
2868 final Message first = conversation.getFirstUnreadMessage();
2869 final int bottom = Math.max(0, this.messageList.size() - 1);
2870 final int pos;
2871 final boolean jumpToBottom;
2872 if (first == null) {
2873 pos = bottom;
2874 jumpToBottom = true;
2875 } else {
2876 int i = getIndexOf(first.getUuid(), this.messageList);
2877 pos = i < 0 ? bottom : i;
2878 jumpToBottom = false;
2879 }
2880 setSelection(pos, jumpToBottom);
2881 }
2882 }
2883
2884 this.binding.messagesView.post(this::fireReadEvent);
2885 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
2886 // layout which might be unnecessary since we can *see* it
2887 activity.xmppConnectionService
2888 .getNotificationService()
2889 .setOpenConversation(this.conversation);
2890
2891 if (commandAdapter != null && conversation != originalConversation) {
2892 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
2893 refreshCommands(false);
2894 }
2895 if (commandAdapter == null && conversation != null) {
2896 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
2897 commandAdapter = new CommandAdapter((XmppActivity) getActivity());
2898 binding.commandsView.setAdapter(commandAdapter);
2899 binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
2900 if (activity == null) return;
2901
2902 final Element command = commandAdapter.getItem(position);
2903 activity.startCommand(conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
2904 });
2905 refreshCommands(false);
2906 }
2907
2908 return true;
2909 }
2910
2911 public void refreshForNewCaps() {
2912 refreshCommands(true);
2913 }
2914
2915 protected void refreshCommands(boolean delayShow) {
2916 if (commandAdapter == null) return;
2917
2918 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
2919 if (commandJid == null && conversation.getJid().isDomainJid()) {
2920 commandJid = conversation.getJid();
2921 }
2922 if (commandJid == null) {
2923 conversation.hideViewPager();
2924 } else {
2925 if (!delayShow) conversation.showViewPager();
2926 activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
2927 if (activity == null) return;
2928
2929 activity.runOnUiThread(() -> {
2930 if (iq.getType() == IqPacket.TYPE.RESULT) {
2931 binding.commandsViewProgressbar.setVisibility(View.GONE);
2932 commandAdapter.clear();
2933 for (Element child : iq.query().getChildren()) {
2934 if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
2935 commandAdapter.add(child);
2936 }
2937 }
2938
2939 if (commandAdapter.getCount() < 1) {
2940 conversation.hideViewPager();
2941 } else if (delayShow) {
2942 conversation.showViewPager();
2943 }
2944 });
2945 });
2946 }
2947 }
2948
2949 private void resetUnreadMessagesCount() {
2950 lastMessageUuid = null;
2951 hideUnreadMessagesCount();
2952 }
2953
2954 private void hideUnreadMessagesCount() {
2955 if (this.binding == null) {
2956 return;
2957 }
2958 this.binding.scrollToBottomButton.setEnabled(false);
2959 this.binding.scrollToBottomButton.hide();
2960 this.binding.unreadCountCustomView.setVisibility(View.GONE);
2961 }
2962
2963 private void setSelection(int pos, boolean jumpToBottom) {
2964 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2965 this.binding.messagesView.post(
2966 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2967 this.binding.messagesView.post(this::fireReadEvent);
2968 }
2969
2970 private boolean scrolledToBottom() {
2971 return this.binding != null && scrolledToBottom(this.binding.messagesView);
2972 }
2973
2974 private void processExtras(final Bundle extras) {
2975 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2976 final String text = extras.getString(Intent.EXTRA_TEXT);
2977 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2978 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
2979 final String postInitAction =
2980 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
2981 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2982 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2983 final boolean doNotAppend =
2984 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2985 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
2986 final List<Uri> uris = extractUris(extras);
2987 if (uris != null && uris.size() > 0) {
2988 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2989 mediaPreviewAdapter.addMediaPreviews(
2990 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2991 } else {
2992 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2993 mediaPreviewAdapter.addMediaPreviews(
2994 Attachment.of(getActivity(), cleanedUris, type));
2995 }
2996 toggleInputMethod();
2997 return;
2998 }
2999 if (nick != null) {
3000 if (pm) {
3001 Jid jid = conversation.getJid();
3002 try {
3003 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3004 privateMessageWith(next);
3005 } catch (final IllegalArgumentException ignored) {
3006 // do nothing
3007 }
3008 } else {
3009 final MucOptions mucOptions = conversation.getMucOptions();
3010 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3011 highlightInConference(nick);
3012 }
3013 }
3014 } else {
3015 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3016 mediaPreviewAdapter.addMediaPreviews(
3017 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3018 toggleInputMethod();
3019 return;
3020 } else if (text != null && asQuote) {
3021 quoteText(text);
3022 } else {
3023 appendText(text, doNotAppend);
3024 }
3025 }
3026 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3027 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3028 return;
3029 }
3030 if ("call".equals(postInitAction)) {
3031 checkPermissionAndTriggerAudioCall();
3032 }
3033 if ("message".equals(postInitAction)) {
3034 binding.conversationViewPager.post(() -> {
3035 binding.conversationViewPager.setCurrentItem(0);
3036 });
3037 }
3038 if ("command".equals(postInitAction)) {
3039 binding.conversationViewPager.post(() -> {
3040 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3041 if (adapter != null && adapter.getCount() > 1) {
3042 binding.conversationViewPager.setCurrentItem(1);
3043 }
3044 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3045 Jid commandJid = null;
3046 if (jid != null) {
3047 try {
3048 commandJid = Jid.of(jid);
3049 } catch (final IllegalArgumentException e) { }
3050 }
3051 if (commandJid == null || !commandJid.isFullJid()) {
3052 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3053 if (discoJid != null) commandJid = discoJid;
3054 }
3055 if (node != null && commandJid != null) {
3056 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3057 }
3058 });
3059 return;
3060 }
3061 final Message message =
3062 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3063 if ("webxdc".equals(postInitAction)) {
3064 if (message == null) return;
3065
3066 Cid webxdcCid = message.getFileParams().getCids().get(0);
3067 WebxdcPage webxdc = new WebxdcPage(webxdcCid, message, activity.xmppConnectionService);
3068 Conversation conversation = (Conversation) message.getConversation();
3069 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3070 conversation.startWebxdc(webxdc);
3071 }
3072 }
3073 if (message != null) {
3074 startDownloadable(message);
3075 }
3076 if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3077 if (!conversation.switchToSession("jabber:iq:register")) {
3078 conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3079 }
3080 }
3081 }
3082
3083 private Element commandFor(final Jid jid, final String node) {
3084 if (commandAdapter != null) {
3085 for (int i = 0; i < commandAdapter.getCount(); i++) {
3086 Element command = commandAdapter.getItem(i);
3087 final String commandNode = command.getAttribute("node");
3088 if (commandNode == null || !commandNode.equals(node)) continue;
3089
3090 final Jid commandJid = command.getAttributeAsJid("jid");
3091 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3092
3093 return command;
3094 }
3095 }
3096
3097 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3098 }
3099
3100 private List<Uri> extractUris(final Bundle extras) {
3101 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3102 if (uris != null) {
3103 return uris;
3104 }
3105 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3106 if (uri != null) {
3107 return Collections.singletonList(uri);
3108 } else {
3109 return null;
3110 }
3111 }
3112
3113 private List<Uri> cleanUris(final List<Uri> uris) {
3114 final Iterator<Uri> iterator = uris.iterator();
3115 while (iterator.hasNext()) {
3116 final Uri uri = iterator.next();
3117 if (FileBackend.weOwnFile(uri)) {
3118 iterator.remove();
3119 Toast.makeText(
3120 getActivity(),
3121 R.string.security_violation_not_attaching_file,
3122 Toast.LENGTH_SHORT)
3123 .show();
3124 }
3125 }
3126 return uris;
3127 }
3128
3129 private boolean showBlockSubmenu(View view) {
3130 final Jid jid = conversation.getJid();
3131 final boolean showReject =
3132 !conversation.isWithStranger()
3133 && conversation
3134 .getContact()
3135 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3136 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3137 popupMenu.inflate(R.menu.block);
3138 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3139 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3140 popupMenu.setOnMenuItemClickListener(
3141 menuItem -> {
3142 Blockable blockable;
3143 switch (menuItem.getItemId()) {
3144 case R.id.reject:
3145 activity.xmppConnectionService.stopPresenceUpdatesTo(
3146 conversation.getContact());
3147 updateSnackBar(conversation);
3148 return true;
3149 case R.id.block_domain:
3150 blockable =
3151 conversation
3152 .getAccount()
3153 .getRoster()
3154 .getContact(jid.getDomain());
3155 break;
3156 default:
3157 blockable = conversation;
3158 }
3159 BlockContactDialog.show(activity, blockable);
3160 return true;
3161 });
3162 popupMenu.show();
3163 return true;
3164 }
3165
3166 private void updateSnackBar(final Conversation conversation) {
3167 final Account account = conversation.getAccount();
3168 final XmppConnection connection = account.getXmppConnection();
3169 final int mode = conversation.getMode();
3170 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3171 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3172 return;
3173 }
3174 if (account.getStatus() == Account.State.DISABLED) {
3175 showSnackbar(
3176 R.string.this_account_is_disabled,
3177 R.string.enable,
3178 this.mEnableAccountListener);
3179 } else if (conversation.isBlocked()) {
3180 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3181 } else if (contact != null
3182 && !contact.showInRoster()
3183 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3184 showSnackbar(
3185 R.string.contact_added_you,
3186 R.string.add_back,
3187 this.mAddBackClickListener,
3188 this.mLongPressBlockListener);
3189 } else if (contact != null
3190 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3191 showSnackbar(
3192 R.string.contact_asks_for_presence_subscription,
3193 R.string.allow,
3194 this.mAllowPresenceSubscription,
3195 this.mLongPressBlockListener);
3196 } else if (mode == Conversation.MODE_MULTI
3197 && !conversation.getMucOptions().online()
3198 && account.getStatus() == Account.State.ONLINE) {
3199 switch (conversation.getMucOptions().getError()) {
3200 case NICK_IN_USE:
3201 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3202 break;
3203 case NO_RESPONSE:
3204 showSnackbar(R.string.joining_conference, 0, null);
3205 break;
3206 case SERVER_NOT_FOUND:
3207 if (conversation.receivedMessagesCount() > 0) {
3208 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3209 } else {
3210 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3211 }
3212 break;
3213 case REMOTE_SERVER_TIMEOUT:
3214 if (conversation.receivedMessagesCount() > 0) {
3215 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3216 } else {
3217 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3218 }
3219 break;
3220 case PASSWORD_REQUIRED:
3221 showSnackbar(
3222 R.string.conference_requires_password,
3223 R.string.enter_password,
3224 enterPassword);
3225 break;
3226 case BANNED:
3227 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3228 break;
3229 case MEMBERS_ONLY:
3230 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3231 break;
3232 case RESOURCE_CONSTRAINT:
3233 showSnackbar(
3234 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3235 break;
3236 case KICKED:
3237 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3238 break;
3239 case TECHNICAL_PROBLEMS:
3240 showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3241 break;
3242 case UNKNOWN:
3243 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3244 break;
3245 case INVALID_NICK:
3246 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3247 case SHUTDOWN:
3248 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3249 break;
3250 case DESTROYED:
3251 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3252 break;
3253 case NON_ANONYMOUS:
3254 showSnackbar(
3255 R.string.group_chat_will_make_your_jabber_id_public,
3256 R.string.join,
3257 acceptJoin);
3258 break;
3259 default:
3260 hideSnackbar();
3261 break;
3262 }
3263 } else if (account.hasPendingPgpIntent(conversation)) {
3264 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3265 } else if (connection != null
3266 && connection.getFeatures().blocking()
3267 && conversation.countMessages() != 0
3268 && !conversation.isBlocked()
3269 && conversation.isWithStranger()) {
3270 showSnackbar(
3271 R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
3272 } else {
3273 hideSnackbar();
3274 }
3275 }
3276
3277 @Override
3278 public void refresh() {
3279 if (this.binding == null) {
3280 Log.d(
3281 Config.LOGTAG,
3282 "ConversationFragment.refresh() skipped updated because view binding was null");
3283 return;
3284 }
3285 if (this.conversation != null
3286 && this.activity != null
3287 && this.activity.xmppConnectionService != null) {
3288 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3289 activity.onConversationArchived(this.conversation);
3290 return;
3291 }
3292 }
3293 this.refresh(true);
3294 }
3295
3296 private void refresh(boolean notifyConversationRead) {
3297 synchronized (this.messageList) {
3298 if (this.conversation != null) {
3299 conversation.populateWithMessages(this.messageList);
3300 updateSnackBar(conversation);
3301 updateStatusMessages();
3302 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3303 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3304 binding.unreadCountCustomView.setUnreadCount(
3305 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3306 }
3307 this.messageListAdapter.notifyDataSetChanged();
3308 updateChatMsgHint();
3309 if (notifyConversationRead && activity != null) {
3310 binding.messagesView.post(this::fireReadEvent);
3311 }
3312 updateSendButton();
3313 updateEditablity();
3314 }
3315 }
3316 conversation.refreshSessions();
3317 }
3318
3319 protected void messageSent() {
3320 conversation.setUserSelectedThread(false);
3321 mSendingPgpMessage.set(false);
3322 this.binding.textinput.setText("");
3323 if (conversation.setCorrectingMessage(null)) {
3324 this.binding.textinput.append(conversation.getDraftMessage());
3325 conversation.setDraftMessage(null);
3326 }
3327 storeNextMessage();
3328 updateChatMsgHint();
3329 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3330 final boolean prefScrollToBottom =
3331 p.getBoolean(
3332 "scroll_to_bottom",
3333 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3334 if (prefScrollToBottom || scrolledToBottom()) {
3335 new Handler()
3336 .post(
3337 () -> {
3338 int size = messageList.size();
3339 this.binding.messagesView.setSelection(size - 1);
3340 });
3341 }
3342 }
3343
3344 private boolean storeNextMessage() {
3345 return storeNextMessage(this.binding.textinput.getText().toString());
3346 }
3347
3348 private boolean storeNextMessage(String msg) {
3349 final boolean participating =
3350 conversation.getMode() == Conversational.MODE_SINGLE
3351 || conversation.getMucOptions().participating();
3352 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3353 && participating
3354 && this.conversation.setNextMessage(msg)) {
3355 this.activity.xmppConnectionService.updateConversation(this.conversation);
3356 return true;
3357 }
3358 return false;
3359 }
3360
3361 public void doneSendingPgpMessage() {
3362 mSendingPgpMessage.set(false);
3363 }
3364
3365 public long getMaxHttpUploadSize(Conversation conversation) {
3366 final XmppConnection connection = conversation.getAccount().getXmppConnection();
3367 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3368 }
3369
3370 private void updateEditablity() {
3371 boolean canWrite =
3372 this.conversation.getMode() == Conversation.MODE_SINGLE
3373 || this.conversation.getMucOptions().participating()
3374 || this.conversation.getNextCounterpart() != null;
3375 this.binding.textinput.setFocusable(canWrite);
3376 this.binding.textinput.setFocusableInTouchMode(canWrite);
3377 this.binding.textSendButton.setEnabled(canWrite);
3378 this.binding.textinput.setCursorVisible(canWrite);
3379 this.binding.textinput.setEnabled(canWrite);
3380 }
3381
3382 public void updateSendButton() {
3383 boolean hasAttachments =
3384 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3385 final Conversation c = this.conversation;
3386 final Presence.Status status;
3387 final String text =
3388 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3389 final SendButtonAction action;
3390 if (hasAttachments) {
3391 action = SendButtonAction.TEXT;
3392 } else {
3393 action = SendButtonTool.getAction(getActivity(), c, text);
3394 }
3395 if (c.getAccount().getStatus() == Account.State.ONLINE) {
3396 if (activity != null
3397 && activity.xmppConnectionService != null
3398 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3399 status = Presence.Status.OFFLINE;
3400 } else if (c.getMode() == Conversation.MODE_SINGLE) {
3401 status = c.getContact().getShownStatus();
3402 } else {
3403 status =
3404 c.getMucOptions().online()
3405 ? Presence.Status.ONLINE
3406 : Presence.Status.OFFLINE;
3407 }
3408 } else {
3409 status = Presence.Status.OFFLINE;
3410 }
3411 this.binding.textSendButton.setTag(action);
3412 final Activity activity = getActivity();
3413 if (activity != null) {
3414 this.binding.textSendButton.setImageResource(
3415 SendButtonTool.getSendButtonImageResource(activity, action, status));
3416 }
3417
3418 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3419 if (identiconWidth < 0) identiconWidth = params.width;
3420 if (hasAttachments || binding.textinput.getText().length() > 0) {
3421 binding.conversationViewPager.setCurrentItem(0);
3422 params.width = conversation.getThread() == null ? 0 : identiconWidth;
3423 } else {
3424 params.width = identiconWidth;
3425 }
3426 binding.threadIdenticonLayout.setLayoutParams(params);
3427 }
3428
3429 protected void updateStatusMessages() {
3430 DateSeparator.addAll(this.messageList);
3431 if (showLoadMoreMessages(conversation)) {
3432 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3433 }
3434 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3435 ChatState state = conversation.getIncomingChatState();
3436 if (state == ChatState.COMPOSING) {
3437 this.messageList.add(
3438 Message.createStatusMessage(
3439 conversation,
3440 getString(R.string.contact_is_typing, conversation.getName())));
3441 } else if (state == ChatState.PAUSED) {
3442 this.messageList.add(
3443 Message.createStatusMessage(
3444 conversation,
3445 getString(
3446 R.string.contact_has_stopped_typing,
3447 conversation.getName())));
3448 } else {
3449 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3450 final Message message = this.messageList.get(i);
3451 if (message.getType() != Message.TYPE_STATUS) {
3452 if (message.getStatus() == Message.STATUS_RECEIVED) {
3453 return;
3454 } else {
3455 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3456 this.messageList.add(
3457 i + 1,
3458 Message.createStatusMessage(
3459 conversation,
3460 getString(
3461 R.string.contact_has_read_up_to_this_point,
3462 conversation.getName())));
3463 return;
3464 }
3465 }
3466 }
3467 }
3468 }
3469 } else {
3470 final MucOptions mucOptions = conversation.getMucOptions();
3471 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3472 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3473 ChatState state = ChatState.COMPOSING;
3474 List<MucOptions.User> users =
3475 conversation.getMucOptions().getUsersWithChatState(state, 5);
3476 if (users.size() == 0) {
3477 state = ChatState.PAUSED;
3478 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3479 }
3480 if (mucOptions.isPrivateAndNonAnonymous()) {
3481 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3482 final Set<ReadByMarker> markersForMessage =
3483 messageList.get(i).getReadByMarkers();
3484 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3485 for (ReadByMarker marker : markersForMessage) {
3486 if (!ReadByMarker.contains(marker, addedMarkers)) {
3487 addedMarkers.add(
3488 marker); // may be put outside this condition. set should do
3489 // dedup anyway
3490 MucOptions.User user = mucOptions.findUser(marker);
3491 if (user != null && !users.contains(user)) {
3492 shownMarkers.add(user);
3493 }
3494 }
3495 }
3496 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3497 final Message statusMessage;
3498 final int size = shownMarkers.size();
3499 if (size > 1) {
3500 final String body;
3501 if (size <= 4) {
3502 body =
3503 getString(
3504 R.string.contacts_have_read_up_to_this_point,
3505 UIHelper.concatNames(shownMarkers));
3506 } else if (ReadByMarker.allUsersRepresented(
3507 allUsers, markersForMessage, markerForSender)) {
3508 body = getString(R.string.everyone_has_read_up_to_this_point);
3509 } else {
3510 body =
3511 getString(
3512 R.string.contacts_and_n_more_have_read_up_to_this_point,
3513 UIHelper.concatNames(shownMarkers, 3),
3514 size - 3);
3515 }
3516 statusMessage = Message.createStatusMessage(conversation, body);
3517 statusMessage.setCounterparts(shownMarkers);
3518 } else if (size == 1) {
3519 statusMessage =
3520 Message.createStatusMessage(
3521 conversation,
3522 getString(
3523 R.string.contact_has_read_up_to_this_point,
3524 UIHelper.getDisplayName(shownMarkers.get(0))));
3525 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3526 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3527 } else {
3528 statusMessage = null;
3529 }
3530 if (statusMessage != null) {
3531 this.messageList.add(i + 1, statusMessage);
3532 }
3533 addedMarkers.add(markerForSender);
3534 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3535 break;
3536 }
3537 }
3538 }
3539 if (users.size() > 0) {
3540 Message statusMessage;
3541 if (users.size() == 1) {
3542 MucOptions.User user = users.get(0);
3543 int id =
3544 state == ChatState.COMPOSING
3545 ? R.string.contact_is_typing
3546 : R.string.contact_has_stopped_typing;
3547 statusMessage =
3548 Message.createStatusMessage(
3549 conversation, getString(id, UIHelper.getDisplayName(user)));
3550 statusMessage.setTrueCounterpart(user.getRealJid());
3551 statusMessage.setCounterpart(user.getFullJid());
3552 } else {
3553 int id =
3554 state == ChatState.COMPOSING
3555 ? R.string.contacts_are_typing
3556 : R.string.contacts_have_stopped_typing;
3557 statusMessage =
3558 Message.createStatusMessage(
3559 conversation, getString(id, UIHelper.concatNames(users)));
3560 statusMessage.setCounterparts(users);
3561 }
3562 this.messageList.add(statusMessage);
3563 }
3564 }
3565 }
3566
3567 private void stopScrolling() {
3568 long now = SystemClock.uptimeMillis();
3569 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3570 binding.messagesView.dispatchTouchEvent(cancel);
3571 }
3572
3573 private boolean showLoadMoreMessages(final Conversation c) {
3574 if (activity == null || activity.xmppConnectionService == null) {
3575 return false;
3576 }
3577 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3578 final MessageArchiveService service =
3579 activity.xmppConnectionService.getMessageArchiveService();
3580 return mam
3581 && (c.getLastClearHistory().getTimestamp() != 0
3582 || (c.countMessages() == 0
3583 && c.messagesLoaded.get()
3584 && c.hasMessagesLeftOnServer()
3585 && !service.queryInProgress(c)));
3586 }
3587
3588 private boolean hasMamSupport(final Conversation c) {
3589 if (c.getMode() == Conversation.MODE_SINGLE) {
3590 final XmppConnection connection = c.getAccount().getXmppConnection();
3591 return connection != null && connection.getFeatures().mam();
3592 } else {
3593 return c.getMucOptions().mamSupport();
3594 }
3595 }
3596
3597 protected void showSnackbar(
3598 final int message, final int action, final OnClickListener clickListener) {
3599 showSnackbar(message, action, clickListener, null);
3600 }
3601
3602 protected void showSnackbar(
3603 final int message,
3604 final int action,
3605 final OnClickListener clickListener,
3606 final View.OnLongClickListener longClickListener) {
3607 this.binding.snackbar.setVisibility(View.VISIBLE);
3608 this.binding.snackbar.setOnClickListener(null);
3609 this.binding.snackbarMessage.setText(message);
3610 this.binding.snackbarMessage.setOnClickListener(null);
3611 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3612 if (action != 0) {
3613 this.binding.snackbarAction.setText(action);
3614 }
3615 this.binding.snackbarAction.setOnClickListener(clickListener);
3616 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3617 }
3618
3619 protected void hideSnackbar() {
3620 this.binding.snackbar.setVisibility(View.GONE);
3621 }
3622
3623 protected void sendMessage(Message message) {
3624 activity.xmppConnectionService.sendMessage(message);
3625 messageSent();
3626 }
3627
3628 protected void sendPgpMessage(final Message message) {
3629 final XmppConnectionService xmppService = activity.xmppConnectionService;
3630 final Contact contact = message.getConversation().getContact();
3631 if (!activity.hasPgp()) {
3632 activity.showInstallPgpDialog();
3633 return;
3634 }
3635 if (conversation.getAccount().getPgpSignature() == null) {
3636 activity.announcePgp(
3637 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3638 return;
3639 }
3640 if (!mSendingPgpMessage.compareAndSet(false, true)) {
3641 Log.d(Config.LOGTAG, "sending pgp message already in progress");
3642 }
3643 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3644 if (contact.getPgpKeyId() != 0) {
3645 xmppService
3646 .getPgpEngine()
3647 .hasKey(
3648 contact,
3649 new UiCallback<Contact>() {
3650
3651 @Override
3652 public void userInputRequired(
3653 PendingIntent pi, Contact contact) {
3654 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3655 }
3656
3657 @Override
3658 public void success(Contact contact) {
3659 encryptTextMessage(message);
3660 }
3661
3662 @Override
3663 public void error(int error, Contact contact) {
3664 activity.runOnUiThread(
3665 () ->
3666 Toast.makeText(
3667 activity,
3668 R.string
3669 .unable_to_connect_to_keychain,
3670 Toast.LENGTH_SHORT)
3671 .show());
3672 mSendingPgpMessage.set(false);
3673 }
3674 });
3675
3676 } else {
3677 showNoPGPKeyDialog(
3678 false,
3679 (dialog, which) -> {
3680 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3681 xmppService.updateConversation(conversation);
3682 message.setEncryption(Message.ENCRYPTION_NONE);
3683 xmppService.sendMessage(message);
3684 messageSent();
3685 });
3686 }
3687 } else {
3688 if (conversation.getMucOptions().pgpKeysInUse()) {
3689 if (!conversation.getMucOptions().everybodyHasKeys()) {
3690 Toast warning =
3691 Toast.makeText(
3692 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3693 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3694 warning.show();
3695 }
3696 encryptTextMessage(message);
3697 } else {
3698 showNoPGPKeyDialog(
3699 true,
3700 (dialog, which) -> {
3701 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3702 message.setEncryption(Message.ENCRYPTION_NONE);
3703 xmppService.updateConversation(conversation);
3704 xmppService.sendMessage(message);
3705 messageSent();
3706 });
3707 }
3708 }
3709 }
3710
3711 public void encryptTextMessage(Message message) {
3712 activity.xmppConnectionService
3713 .getPgpEngine()
3714 .encrypt(
3715 message,
3716 new UiCallback<Message>() {
3717
3718 @Override
3719 public void userInputRequired(PendingIntent pi, Message message) {
3720 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3721 }
3722
3723 @Override
3724 public void success(Message message) {
3725 // TODO the following two call can be made before the callback
3726 getActivity().runOnUiThread(() -> messageSent());
3727 }
3728
3729 @Override
3730 public void error(final int error, Message message) {
3731 getActivity()
3732 .runOnUiThread(
3733 () -> {
3734 doneSendingPgpMessage();
3735 Toast.makeText(
3736 getActivity(),
3737 error == 0
3738 ? R.string
3739 .unable_to_connect_to_keychain
3740 : error,
3741 Toast.LENGTH_SHORT)
3742 .show();
3743 });
3744 }
3745 });
3746 }
3747
3748 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3749 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3750 builder.setIconAttribute(android.R.attr.alertDialogIcon);
3751 if (plural) {
3752 builder.setTitle(getString(R.string.no_pgp_keys));
3753 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3754 } else {
3755 builder.setTitle(getString(R.string.no_pgp_key));
3756 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3757 }
3758 builder.setNegativeButton(getString(R.string.cancel), null);
3759 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3760 builder.create().show();
3761 }
3762
3763 public void appendText(String text, final boolean doNotAppend) {
3764 if (text == null) {
3765 return;
3766 }
3767 final Editable editable = this.binding.textinput.getText();
3768 String previous = editable == null ? "" : editable.toString();
3769 if (doNotAppend && !TextUtils.isEmpty(previous)) {
3770 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3771 .show();
3772 return;
3773 }
3774 if (UIHelper.isLastLineQuote(previous)) {
3775 text = '\n' + text;
3776 } else if (previous.length() != 0
3777 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3778 text = " " + text;
3779 }
3780 this.binding.textinput.append(text);
3781 }
3782
3783 @Override
3784 public boolean onEnterPressed(final boolean isCtrlPressed) {
3785 if (isCtrlPressed || enterIsSend()) {
3786 sendMessage();
3787 return true;
3788 }
3789 return false;
3790 }
3791
3792 private boolean enterIsSend() {
3793 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3794 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3795 }
3796
3797 public boolean onArrowUpCtrlPressed() {
3798 final Message lastEditableMessage =
3799 conversation == null ? null : conversation.getLastEditableMessage();
3800 if (lastEditableMessage != null) {
3801 correctMessage(lastEditableMessage);
3802 return true;
3803 } else {
3804 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3805 .show();
3806 return false;
3807 }
3808 }
3809
3810 @Override
3811 public void onTypingStarted() {
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
3819 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3820 service.sendChatState(conversation);
3821 }
3822 runOnUiThread(this::updateSendButton);
3823 }
3824
3825 @Override
3826 public void onTypingStopped() {
3827 final XmppConnectionService service =
3828 activity == null ? null : activity.xmppConnectionService;
3829 if (service == null) {
3830 return;
3831 }
3832 final Account.State status = conversation.getAccount().getStatus();
3833 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3834 service.sendChatState(conversation);
3835 }
3836 }
3837
3838 @Override
3839 public void onTextDeleted() {
3840 final XmppConnectionService service =
3841 activity == null ? null : activity.xmppConnectionService;
3842 if (service == null) {
3843 return;
3844 }
3845 final Account.State status = conversation.getAccount().getStatus();
3846 if (status == Account.State.ONLINE
3847 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3848 service.sendChatState(conversation);
3849 }
3850 if (storeNextMessage()) {
3851 runOnUiThread(
3852 () -> {
3853 if (activity == null) {
3854 return;
3855 }
3856 activity.onConversationsListItemUpdated();
3857 });
3858 }
3859 runOnUiThread(this::updateSendButton);
3860 }
3861
3862 @Override
3863 public void onTextChanged() {
3864 if (conversation != null && conversation.getCorrectingMessage() != null) {
3865 runOnUiThread(this::updateSendButton);
3866 }
3867 }
3868
3869 @Override
3870 public boolean onTabPressed(boolean repeated) {
3871 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3872 return false;
3873 }
3874 if (repeated) {
3875 completionIndex++;
3876 } else {
3877 lastCompletionLength = 0;
3878 completionIndex = 0;
3879 final String content = this.binding.textinput.getText().toString();
3880 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
3881 int start =
3882 lastCompletionCursor > 0
3883 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
3884 : 0;
3885 firstWord = start == 0;
3886 incomplete = content.substring(start, lastCompletionCursor);
3887 }
3888 List<String> completions = new ArrayList<>();
3889 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
3890 String name = user.getName();
3891 if (name != null && name.startsWith(incomplete)) {
3892 completions.add(name + (firstWord ? ": " : " "));
3893 }
3894 }
3895 Collections.sort(completions);
3896 if (completions.size() > completionIndex) {
3897 String completion = completions.get(completionIndex).substring(incomplete.length());
3898 this.binding
3899 .textinput
3900 .getEditableText()
3901 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3902 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
3903 lastCompletionLength = completion.length();
3904 } else {
3905 completionIndex = -1;
3906 this.binding
3907 .textinput
3908 .getEditableText()
3909 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3910 lastCompletionLength = 0;
3911 }
3912 return true;
3913 }
3914
3915 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
3916 try {
3917 getActivity()
3918 .startIntentSenderForResult(
3919 pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
3920 } catch (final SendIntentException ignored) {
3921 }
3922 }
3923
3924 @Override
3925 public void onBackendConnected() {
3926 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
3927 String uuid = pendingConversationsUuid.pop();
3928 if (uuid != null) {
3929 if (!findAndReInitByUuidOrArchive(uuid)) {
3930 return;
3931 }
3932 } else {
3933 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
3934 clearPending();
3935 activity.onConversationArchived(conversation);
3936 return;
3937 }
3938 }
3939 ActivityResult activityResult = postponedActivityResult.pop();
3940 if (activityResult != null) {
3941 handleActivityResult(activityResult);
3942 }
3943 clearPending();
3944 }
3945
3946 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
3947 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
3948 if (conversation == null) {
3949 clearPending();
3950 activity.onConversationArchived(null);
3951 return false;
3952 }
3953 reInit(conversation);
3954 ScrollState scrollState = pendingScrollState.pop();
3955 String lastMessageUuid = pendingLastMessageUuid.pop();
3956 List<Attachment> attachments = pendingMediaPreviews.pop();
3957 if (scrollState != null) {
3958 setScrollPosition(scrollState, lastMessageUuid);
3959 }
3960 if (attachments != null && attachments.size() > 0) {
3961 Log.d(Config.LOGTAG, "had attachments on restore");
3962 mediaPreviewAdapter.addMediaPreviews(attachments);
3963 toggleInputMethod();
3964 }
3965 return true;
3966 }
3967
3968 private void clearPending() {
3969 if (postponedActivityResult.clear()) {
3970 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
3971 if (pendingTakePhotoUri.clear()) {
3972 Log.e(Config.LOGTAG, "cleared pending photo uri");
3973 }
3974 }
3975 if (pendingScrollState.clear()) {
3976 Log.e(Config.LOGTAG, "cleared scroll state");
3977 }
3978 if (pendingConversationsUuid.clear()) {
3979 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
3980 }
3981 if (pendingMediaPreviews.clear()) {
3982 Log.e(Config.LOGTAG, "cleared pending media previews");
3983 }
3984 }
3985
3986 public Conversation getConversation() {
3987 return conversation;
3988 }
3989
3990 @Override
3991 public void onContactPictureLongClicked(View v, final Message message) {
3992 final String fingerprint;
3993 if (message.getEncryption() == Message.ENCRYPTION_PGP
3994 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3995 fingerprint = "pgp";
3996 } else {
3997 fingerprint = message.getFingerprint();
3998 }
3999 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4000 final Contact contact = message.getContact();
4001 if (message.getStatus() <= Message.STATUS_RECEIVED
4002 && (contact == null || !contact.isSelf())) {
4003 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4004 final Jid cp = message.getCounterpart();
4005 if (cp == null || cp.isBareJid()) {
4006 return;
4007 }
4008 final Jid tcp = message.getTrueCounterpart();
4009 final User userByRealJid =
4010 tcp != null
4011 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
4012 : null;
4013 final User user =
4014 userByRealJid != null
4015 ? userByRealJid
4016 : conversation.getMucOptions().findUserByFullJid(cp);
4017 popupMenu.inflate(R.menu.muc_details_context);
4018 final Menu menu = popupMenu.getMenu();
4019 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4020 activity, menu, conversation, user);
4021 popupMenu.setOnMenuItemClickListener(
4022 menuItem ->
4023 MucDetailsContextMenuHelper.onContextItemSelected(
4024 menuItem, user, activity, fingerprint));
4025 } else {
4026 popupMenu.inflate(R.menu.one_on_one_context);
4027 popupMenu.setOnMenuItemClickListener(
4028 item -> {
4029 switch (item.getItemId()) {
4030 case R.id.action_contact_details:
4031 activity.switchToContactDetails(
4032 message.getContact(), fingerprint);
4033 break;
4034 case R.id.action_show_qr_code:
4035 activity.showQrCode(
4036 "xmpp:"
4037 + message.getContact()
4038 .getJid()
4039 .asBareJid()
4040 .toEscapedString());
4041 break;
4042 }
4043 return true;
4044 });
4045 }
4046 } else {
4047 popupMenu.inflate(R.menu.account_context);
4048 final Menu menu = popupMenu.getMenu();
4049 menu.findItem(R.id.action_manage_accounts)
4050 .setVisible(QuickConversationsService.isConversations());
4051 popupMenu.setOnMenuItemClickListener(
4052 item -> {
4053 final XmppActivity activity = this.activity;
4054 if (activity == null) {
4055 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4056 return true;
4057 }
4058 switch (item.getItemId()) {
4059 case R.id.action_show_qr_code:
4060 activity.showQrCode(conversation.getAccount().getShareableUri());
4061 break;
4062 case R.id.action_account_details:
4063 activity.switchToAccount(
4064 message.getConversation().getAccount(), fingerprint);
4065 break;
4066 case R.id.action_manage_accounts:
4067 AccountUtils.launchManageAccounts(activity);
4068 break;
4069 }
4070 return true;
4071 });
4072 }
4073 popupMenu.show();
4074 }
4075
4076 @Override
4077 public void onContactPictureClicked(Message message) {
4078 setThread(message.getThread());
4079 conversation.setUserSelectedThread(true);
4080
4081 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4082 if (received) {
4083 if (message.getConversation() instanceof Conversation
4084 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4085 Jid tcp = message.getTrueCounterpart();
4086 Jid user = message.getCounterpart();
4087 if (user != null && !user.isBareJid()) {
4088 final MucOptions mucOptions =
4089 ((Conversation) message.getConversation()).getMucOptions();
4090 if (mucOptions.participating()
4091 || ((Conversation) message.getConversation()).getNextCounterpart()
4092 != null) {
4093 if (!mucOptions.isUserInRoom(user)
4094 && mucOptions.findUserByRealJid(
4095 tcp == null ? null : tcp.asBareJid())
4096 == null) {
4097 Toast.makeText(
4098 getActivity(),
4099 activity.getString(
4100 R.string.user_has_left_conference,
4101 user.getResource()),
4102 Toast.LENGTH_SHORT)
4103 .show();
4104 }
4105 highlightInConference(user.getResource());
4106 } else {
4107 Toast.makeText(
4108 getActivity(),
4109 R.string.you_are_not_participating,
4110 Toast.LENGTH_SHORT)
4111 .show();
4112 }
4113 }
4114 }
4115 }
4116 }
4117
4118 private Activity requireActivity() {
4119 final Activity activity = getActivity();
4120 if (activity == null) {
4121 throw new IllegalStateException("Activity not attached");
4122 }
4123 return activity;
4124 }
4125}