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