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