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