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