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 final Attachment attachment = i.next();
1279 if (attachment.getType() == Attachment.Type.LOCATION) {
1280 attachLocationToConversation(conversation, attachment.getUri());
1281 if (i.hasNext()) runOnUiThread(this);
1282 } else if (attachment.getType() == Attachment.Type.IMAGE) {
1283 Log.d(
1284 Config.LOGTAG,
1285 "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE");
1286 attachImageToConversation(conversation, attachment.getUri(), attachment.getMime(), i.hasNext() ? this : null);
1287 } else {
1288 Log.d(
1289 Config.LOGTAG,
1290 "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1291 attachFileToConversation(conversation, attachment.getUri(), attachment.getMime(), i.hasNext() ? this : null);
1292 }
1293 i.remove();
1294 mediaPreviewAdapter.notifyDataSetChanged();
1295 toggleInputMethod();
1296 }
1297 };
1298 next.run();
1299 };
1300 if (conversation == null
1301 || conversation.getMode() == Conversation.MODE_MULTI
1302 || Attachment.canBeSendInBand(attachments)
1303 || (conversation.getAccount().httpUploadAvailable()
1304 && FileBackend.allFilesUnderSize(
1305 getActivity(), attachments, getMaxHttpUploadSize(conversation)))) {
1306 callback.onPresenceSelected();
1307 } else {
1308 activity.selectPresence(conversation, callback);
1309 }
1310 }
1311
1312 private static boolean anyNeedsExternalStoragePermission(
1313 final Collection<Attachment> attachments) {
1314 for (final Attachment attachment : attachments) {
1315 if (attachment.getType() != Attachment.Type.LOCATION) {
1316 return true;
1317 }
1318 }
1319 return false;
1320 }
1321
1322 public void toggleInputMethod() {
1323 boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
1324 binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
1325 binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
1326 updateSendButton();
1327 }
1328
1329 private void handleNegativeActivityResult(int requestCode) {
1330 switch (requestCode) {
1331 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1332 if (pendingTakePhotoUri.clear()) {
1333 Log.d(
1334 Config.LOGTAG,
1335 "cleared pending photo uri after negative activity result");
1336 }
1337 break;
1338 }
1339 }
1340
1341 @Override
1342 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
1343 super.onActivityResult(requestCode, resultCode, data);
1344 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
1345 if (activity != null && activity.xmppConnectionService != null) {
1346 handleActivityResult(activityResult);
1347 } else {
1348 this.postponedActivityResult.push(activityResult);
1349 }
1350 }
1351
1352 public void unblockConversation(final Blockable conversation) {
1353 activity.xmppConnectionService.sendUnblockRequest(conversation);
1354 }
1355
1356 @Override
1357 public void onAttach(Activity activity) {
1358 super.onAttach(activity);
1359 Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
1360 if (activity instanceof ConversationsActivity) {
1361 this.activity = (ConversationsActivity) activity;
1362 } else {
1363 throw new IllegalStateException(
1364 "Trying to attach fragment to activity that is not the ConversationsActivity");
1365 }
1366 }
1367
1368 @Override
1369 public void onDetach() {
1370 super.onDetach();
1371 this.activity = null; // TODO maybe not a good idea since some callbacks really need it
1372 }
1373
1374 @Override
1375 public void onCreate(Bundle savedInstanceState) {
1376 super.onCreate(savedInstanceState);
1377 setHasOptionsMenu(true);
1378 activity.getOnBackPressedDispatcher().addCallback(this, backPressedLeaveSingleThread);
1379 }
1380
1381 @Override
1382 public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
1383 if (activity != null && activity.xmppConnectionService != null && activity.xmppConnectionService.isOnboarding()) return;
1384
1385 menuInflater.inflate(R.menu.fragment_conversation, menu);
1386 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
1387 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
1388 final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
1389 final MenuItem menuMute = menu.findItem(R.id.action_mute);
1390 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
1391 final MenuItem menuCall = menu.findItem(R.id.action_call);
1392 final MenuItem menuOngoingCall = menu.findItem(R.id.action_ongoing_call);
1393 final MenuItem menuVideoCall = menu.findItem(R.id.action_video_call);
1394 final MenuItem menuTogglePinned = menu.findItem(R.id.action_toggle_pinned);
1395 final MenuItem menuArchiveChat = menu.findItem(R.id.action_archive);
1396
1397 if (conversation != null) {
1398 if (conversation.getMode() == Conversation.MODE_MULTI) {
1399 menuContactDetails.setVisible(false);
1400 menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
1401 menuMucDetails.setTitle(
1402 conversation.getMucOptions().isPrivateAndNonAnonymous()
1403 ? R.string.action_muc_details
1404 : R.string.channel_details);
1405 menuCall.setVisible(false);
1406 menuOngoingCall.setVisible(false);
1407 menuArchiveChat.setTitle("Leave " + (conversation.getMucOptions().isPrivateAndNonAnonymous() ? "group chat" : "Channel"));
1408 } else {
1409 final XmppConnectionService service =
1410 activity == null ? null : activity.xmppConnectionService;
1411 final Optional<OngoingRtpSession> ongoingRtpSession =
1412 service == null
1413 ? Optional.absent()
1414 : service.getJingleConnectionManager()
1415 .getOngoingRtpConnection(conversation.getContact());
1416 if (ongoingRtpSession.isPresent()) {
1417 menuOngoingCall.setVisible(true);
1418 menuCall.setVisible(false);
1419 } else {
1420 menuOngoingCall.setVisible(false);
1421 final RtpCapability.Capability rtpCapability =
1422 RtpCapability.check(conversation.getContact());
1423 final boolean cameraAvailable =
1424 activity != null && activity.isCameraFeatureAvailable();
1425 menuCall.setVisible(rtpCapability != RtpCapability.Capability.NONE);
1426 menuVideoCall.setVisible(
1427 rtpCapability == RtpCapability.Capability.VIDEO && cameraAvailable);
1428 }
1429 menuContactDetails.setVisible(!this.conversation.withSelf());
1430 menuMucDetails.setVisible(false);
1431 menuInviteContact.setVisible(
1432 service != null
1433 && service.findConferenceServer(conversation.getAccount()) != null);
1434 menuArchiveChat.setTitle(R.string.action_archive_chat);
1435 }
1436 if (conversation.isMuted()) {
1437 menuMute.setVisible(false);
1438 } else {
1439 menuUnmute.setVisible(false);
1440 }
1441 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
1442 ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
1443 if (conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false)) {
1444 menuTogglePinned.setTitle(R.string.remove_from_favorites);
1445 } else {
1446 menuTogglePinned.setTitle(R.string.add_to_favorites);
1447 }
1448 }
1449 super.onCreateOptionsMenu(menu, menuInflater);
1450 }
1451
1452 @Override
1453 public View onCreateView(
1454 final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
1455 this.binding =
1456 DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
1457 binding.getRoot().setOnClickListener(null); // TODO why the fuck did we do this?
1458
1459 binding.textinput.setOnEditorActionListener(mEditorActionListener);
1460 binding.textinput.setRichContentListener(new String[] {"image/*"}, mEditorContentListener);
1461 DisplayMetrics displayMetrics = new DisplayMetrics();
1462 activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
1463 if (displayMetrics.heightPixels > 0) binding.textinput.setMaxHeight(displayMetrics.heightPixels / 4);
1464
1465 binding.textSendButton.setOnClickListener(this.mSendButtonListener);
1466 binding.contextPreviewCancel.setOnClickListener((v) -> {
1467 setThread(null);
1468 conversation.setUserSelectedThread(false);
1469 setupReply(null);
1470 });
1471 binding.requestVoice.setOnClickListener((v) -> {
1472 activity.xmppConnectionService.requestVoice(conversation.getAccount(), conversation.getJid());
1473 binding.requestVoice.setVisibility(View.GONE);
1474 Toast.makeText(activity, "Your request has been sent to the moderators", Toast.LENGTH_SHORT).show();
1475 });
1476
1477 binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
1478 binding.messagesView.setOnScrollListener(mOnScrollListener);
1479 binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
1480 mediaPreviewAdapter = new MediaPreviewAdapter(this);
1481 binding.mediaPreview.setAdapter(mediaPreviewAdapter);
1482 messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1483 messageListAdapter.setOnContactPictureClicked(this);
1484 messageListAdapter.setOnContactPictureLongClicked(this);
1485 messageListAdapter.setOnInlineImageLongClicked(this);
1486 messageListAdapter.setConversationFragment(this);
1487 binding.messagesView.setAdapter(messageListAdapter);
1488
1489 binding.textinput.addTextChangedListener(
1490 new StylingHelper.MessageEditorStyler(binding.textinput, messageListAdapter));
1491
1492 registerForContextMenu(binding.messagesView);
1493 registerForContextMenu(binding.textSendButton);
1494
1495 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1496 this.binding.textinput.setCustomInsertionActionModeCallback(
1497 new EditMessageActionModeCallback(this.binding.textinput));
1498 this.binding.textinput.setCustomSelectionActionModeCallback(
1499 new EditMessageSelectionActionModeCallback(this.binding.textinput));
1500 }
1501
1502 messageListAdapter.setOnMessageBoxClicked(message -> {
1503 if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1504 setThread(message.getThread());
1505 conversation.setUserSelectedThread(true);
1506 });
1507
1508 messageListAdapter.setOnMessageBoxSwiped(message -> {
1509 quoteMessage(message);
1510 });
1511
1512 binding.threadIdenticonLayout.setOnClickListener(v -> {
1513 boolean wasLocked = conversation.getLockThread();
1514 conversation.setLockThread(false);
1515 backPressedLeaveSingleThread.setEnabled(false);
1516 if (wasLocked) {
1517 setThread(null);
1518 conversation.setUserSelectedThread(false);
1519 refresh();
1520 updateThreadFromLastMessage();
1521 } else {
1522 newThread();
1523 conversation.setUserSelectedThread(true);
1524 newThreadTutorialToast("Switched to new thread");
1525 }
1526 });
1527
1528 binding.threadIdenticonLayout.setOnLongClickListener(v -> {
1529 boolean wasLocked = conversation.getLockThread();
1530 conversation.setLockThread(false);
1531 backPressedLeaveSingleThread.setEnabled(false);
1532 setThread(null);
1533 conversation.setUserSelectedThread(true);
1534 if (wasLocked) refresh();
1535 newThreadTutorialToast("Cleared thread");
1536 return true;
1537 });
1538
1539 Autocomplete.<MucOptions.User>on(binding.textinput)
1540 .with(activity.getDrawable(R.drawable.background_message_bubble))
1541 .with(new CharPolicy('@'))
1542 .with(new RecyclerViewPresenter<MucOptions.User>(activity) {
1543 protected UserAdapter adapter;
1544
1545 @Override
1546 protected Adapter instantiateAdapter() {
1547 adapter = new UserAdapter(false) {
1548 @Override
1549 public void onBindViewHolder(UserAdapter.ViewHolder viewHolder, int position) {
1550 super.onBindViewHolder(viewHolder, position);
1551 final var item = getItem(position);
1552 viewHolder.binding.getRoot().setOnClickListener(v -> {
1553 dispatchClick(item);
1554 });
1555 }
1556 };
1557 return adapter;
1558 }
1559
1560 @Override
1561 protected void onQuery(@Nullable CharSequence query) {
1562 if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1563
1564 final var allUsers = conversation.getMucOptions().getUsers();
1565 if (!conversation.getMucOptions().getUsersByRole(MucOptions.Role.MODERATOR).isEmpty()) {
1566 final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0role:moderator", "Notify active moderators", new HashSet<>());
1567 u.setRole("participant");
1568 allUsers.add(u);
1569 }
1570 if (!allUsers.isEmpty() && conversation.getMucOptions().getSelf() != null && conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
1571 final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0attention", "Notify active participants", new HashSet<>());
1572 u.setRole("participant");
1573 allUsers.add(u);
1574 }
1575 final String needle = query.toString().toLowerCase(Locale.getDefault());
1576 if (getRecyclerView() != null) getRecyclerView().setItemAnimator(null);
1577 adapter.submitList(
1578 Ordering.natural().immutableSortedCopy(Collections2.filter(
1579 allUsers,
1580 user -> {
1581 if ("mods".contains(needle) && "\0role:moderator".equals(user.getOccupantId())) return true;
1582 if ("here".contains(needle) && "\0attention".equals(user.getOccupantId())) return true;
1583 final String name = user.getNick();
1584 if (name == null) return false;
1585 for (final var hat : user.getHats()) {
1586 if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1587 }
1588 for (final var hat : user.getPseudoHats(activity)) {
1589 if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1590 }
1591 final Contact contact = user.getContact();
1592 return name.toLowerCase(Locale.getDefault()).contains(needle)
1593 || contact != null
1594 && contact.getDisplayName().toLowerCase(Locale.getDefault()).contains(needle);
1595 })));
1596 }
1597
1598 @Override
1599 protected AutocompletePresenter.PopupDimensions getPopupDimensions() {
1600 final var dim = new AutocompletePresenter.PopupDimensions();
1601 dim.width = displayMetrics.widthPixels * 4/5;
1602 return dim;
1603 }
1604 })
1605 .with(new AutocompleteCallback<MucOptions.User>() {
1606 @Override
1607 public boolean onPopupItemClicked(Editable editable, MucOptions.User user) {
1608 int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1609 if (range == null) return false;
1610 range[0] -= 1;
1611 if ("\0attention".equals(user.getOccupantId())) {
1612 editable.delete(Math.max(0, range[0]), Math.min(editable.length(), range[1]));
1613 editable.insert(0, "@here ");
1614 return true;
1615 }
1616 int colon = editable.toString().indexOf(':');
1617 final var beforeColon = range[0] < colon;
1618 String prefix = "";
1619 String suffix = " ";
1620 if (beforeColon) suffix = ", ";
1621 if (colon < 0 && range[0] == 0) suffix = ": ";
1622 if (colon > 0 && colon == range[0] - 2) {
1623 prefix = ", ";
1624 suffix = ": ";
1625 range[0] -= 2;
1626 }
1627 var insert = user.getNick();
1628 if ("\0role:moderator".equals(user.getOccupantId())) {
1629 insert = conversation.getMucOptions().getUsersByRole(MucOptions.Role.MODERATOR).stream().map(MucOptions.User::getNick).collect(Collectors.joining(", "));
1630 }
1631 editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), prefix + insert + suffix);
1632 return true;
1633 }
1634
1635 @Override
1636 public void onPopupVisibilityChanged(boolean shown) {}
1637 }).build();
1638
1639 Handler emojiDebounce = new Handler(Looper.getMainLooper());
1640 setupEmojiSearch();
1641 Autocomplete.<EmojiSearch.Emoji>on(binding.textinput)
1642 .with(activity.getDrawable(R.drawable.background_message_bubble))
1643 .with(new CharPolicy(':'))
1644 .with(new RecyclerViewPresenter<EmojiSearch.Emoji>(activity) {
1645 protected EmojiSearch.EmojiSearchAdapter adapter;
1646
1647 @Override
1648 protected Adapter instantiateAdapter() {
1649 setupEmojiSearch();
1650 adapter = emojiSearch.makeAdapter(item -> dispatchClick(item));
1651 return adapter;
1652 }
1653
1654 @Override
1655 protected void onViewHidden() {
1656 if (getRecyclerView() == null) return;
1657 super.onViewHidden();
1658 }
1659
1660 @Override
1661 protected void onQuery(@Nullable CharSequence query) {
1662 if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1663
1664 emojiDebounce.removeCallbacksAndMessages(null);
1665 emojiDebounce.postDelayed(() -> {
1666 if (getRecyclerView() == null) return;
1667 getRecyclerView().setItemAnimator(null);
1668 adapter.search(activity, getRecyclerView(), query.toString());
1669 }, 100L);
1670 }
1671 })
1672 .with(new AutocompleteCallback<EmojiSearch.Emoji>() {
1673 @Override
1674 public boolean onPopupItemClicked(Editable editable, EmojiSearch.Emoji emoji) {
1675 int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1676 if (range == null) return false;
1677 range[0] -= 1;
1678 final var toInsert = emoji.toInsert();
1679 toInsert.append(" ");
1680 editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), toInsert);
1681 return true;
1682 }
1683
1684 @Override
1685 public void onPopupVisibilityChanged(boolean shown) {}
1686 }).build();
1687
1688 return binding.getRoot();
1689 }
1690
1691 protected void setupEmojiSearch() {
1692 if (activity != null && activity.xmppConnectionService != null) {
1693 if (emojiSearch == null) {
1694 emojiSearch = activity.xmppConnectionService.emojiSearch();
1695 }
1696 }
1697 }
1698
1699 protected void newThreadTutorialToast(String s) {
1700 if (activity == null) return;
1701 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1702 final int tutorialCount = p.getInt("thread_tutorial", 0);
1703 if (tutorialCount < 5) {
1704 Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
1705 p.edit().putInt("thread_tutorial", tutorialCount + 1).apply();
1706 }
1707 }
1708
1709 @Override
1710 public void onDestroyView() {
1711 super.onDestroyView();
1712 Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1713 messageListAdapter.setOnContactPictureClicked(null);
1714 messageListAdapter.setOnContactPictureLongClicked(null);
1715 messageListAdapter.setOnInlineImageLongClicked(null);
1716 messageListAdapter.setConversationFragment(null);
1717 messageListAdapter.setOnMessageBoxClicked(null);
1718 messageListAdapter.setOnMessageBoxSwiped(null);
1719 binding.conversationViewPager.setAdapter(null);
1720 if (conversation != null) conversation.setupViewPager(null, null, false, null);
1721 }
1722
1723 public void quoteText(String text) {
1724 if (binding.textinput.isEnabled()) {
1725 binding.textinput.insertAsQuote(text);
1726 binding.textinput.requestFocus();
1727 InputMethodManager inputMethodManager =
1728 (InputMethodManager)
1729 getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1730 if (inputMethodManager != null) {
1731 inputMethodManager.showSoftInput(
1732 binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1733 }
1734 }
1735 }
1736
1737 private void quoteMessage(Message message) {
1738 if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1739 setThread(message.getThread());
1740 conversation.setUserSelectedThread(true);
1741 if (!forkNullThread(message)) newThread();
1742 setupReply(message);
1743 }
1744
1745 private boolean forkNullThread(Message message) {
1746 if (message.getThread() != null || conversation.getMode() != Conversation.MODE_MULTI) return true;
1747 for (final Message m : conversation.findReplies(message.getServerMsgId())) {
1748 final Element thread = m.getThread();
1749 if (thread != null) {
1750 setThread(thread);
1751 return true;
1752 }
1753 }
1754
1755 return false;
1756 }
1757
1758 private void setupReply(Message message) {
1759 conversation.setReplyTo(message);
1760 if (message == null) {
1761 binding.contextPreview.setVisibility(View.GONE);
1762 binding.textsend.setBackgroundResource(R.drawable.textsend);
1763 return;
1764 }
1765
1766 SpannableStringBuilder body = message.getSpannableBody(null, null);
1767 if (message.isFileOrImage() || message.isOOb()) body.append(" 🖼️");
1768 messageListAdapter.handleTextQuotes(binding.contextPreviewText, body);
1769 binding.contextPreviewText.setText(body);
1770 binding.contextPreview.setVisibility(View.VISIBLE);
1771 }
1772
1773 private void setThread(Element thread) {
1774 this.conversation.setThread(thread);
1775 binding.threadIdenticon.setAlpha(0f);
1776 binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1777 if (thread != null) {
1778 final String threadId = thread.getContent();
1779 if (threadId != null) {
1780 binding.threadIdenticon.setAlpha(1f);
1781 binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1782 binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1783 }
1784 }
1785 updateSendButton();
1786 }
1787
1788 @Override
1789 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1790 // This should cancel any remaining click events that would otherwise trigger links
1791 v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1792
1793 if (v == binding.textSendButton) {
1794 super.onCreateContextMenu(menu, v, menuInfo);
1795 try {
1796 java.lang.reflect.Method m = menu.getClass().getSuperclass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
1797 m.setAccessible(true);
1798 m.invoke(menu, true);
1799 } catch (Exception e) {
1800 e.printStackTrace();
1801 }
1802 Menu tmpMenu = new PopupMenu(activity, null).getMenu();
1803 activity.getMenuInflater().inflate(R.menu.fragment_conversation, tmpMenu);
1804 MenuItem attachMenu = tmpMenu.findItem(R.id.action_attach_file);
1805 for (int i = 0; i < attachMenu.getSubMenu().size(); i++) {
1806 MenuItem item = attachMenu.getSubMenu().getItem(i);
1807 MenuItem newItem = menu.add(item.getGroupId(), item.getItemId(), item.getOrder(), item.getTitle());
1808 newItem.setIcon(item.getIcon());
1809 }
1810 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
1811 return;
1812 }
1813
1814 synchronized (this.messageList) {
1815 super.onCreateContextMenu(menu, v, menuInfo);
1816 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1817 this.selectedMessage = this.messageList.get(acmi.position);
1818 populateContextMenu(menu);
1819 }
1820 }
1821
1822 private void populateContextMenu(ContextMenu menu) {
1823 final Message m = this.selectedMessage;
1824 final Transferable t = m.getTransferable();
1825 Message relevantForCorrection = m;
1826 while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1827 relevantForCorrection = relevantForCorrection.next();
1828 }
1829 if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1830
1831 if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1832 || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1833 return;
1834 }
1835
1836 if (m.getStatus() == Message.STATUS_RECEIVED
1837 && t != null
1838 && (t.getStatus() == Transferable.STATUS_CANCELLED
1839 || t.getStatus() == Transferable.STATUS_FAILED)) {
1840 return;
1841 }
1842
1843 final boolean deleted = m.isDeleted();
1844 final boolean encrypted =
1845 m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1846 || m.getEncryption() == Message.ENCRYPTION_PGP;
1847 final boolean receiving =
1848 m.getStatus() == Message.STATUS_RECEIVED
1849 && (t instanceof JingleFileTransferConnection
1850 || t instanceof HttpDownloadConnection);
1851 activity.getMenuInflater().inflate(R.menu.message_context, menu);
1852 final MenuItem reportAndBlock = menu.findItem(R.id.action_report_and_block);
1853 final MenuItem addReaction = menu.findItem(R.id.action_add_reaction);
1854 MenuItem openWith = menu.findItem(R.id.open_with);
1855 MenuItem copyMessage = menu.findItem(R.id.copy_message);
1856 MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1857 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1858 MenuItem correctMessage = menu.findItem(R.id.correct_message);
1859 MenuItem retractMessage = menu.findItem(R.id.retract_message);
1860 MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
1861 MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1862 MenuItem shareWith = menu.findItem(R.id.share_with);
1863 MenuItem sendAgain = menu.findItem(R.id.send_again);
1864 MenuItem copyUrl = menu.findItem(R.id.copy_url);
1865 MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
1866 MenuItem downloadFile = menu.findItem(R.id.download_file);
1867 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1868 MenuItem blockMedia = menu.findItem(R.id.block_media);
1869 MenuItem deleteFile = menu.findItem(R.id.delete_file);
1870 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1871 onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1872 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1873 final boolean showError =
1874 m.getStatus() == Message.STATUS_SEND_FAILED
1875 && m.getErrorMessage() != null
1876 && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1877 final Conversational conversational = m.getConversation();
1878 if (m.getStatus() == Message.STATUS_RECEIVED && conversational instanceof Conversation c) {
1879 final XmppConnection connection = c.getAccount().getXmppConnection();
1880 if (c.isWithStranger()
1881 && m.getServerMsgId() != null
1882 && !c.isBlocked()
1883 && connection != null
1884 && connection.getFeatures().spamReporting()) {
1885 reportAndBlock.setVisible(true);
1886 }
1887 }
1888 if (!encrypted) {
1889 addReaction.setVisible(!showError && !m.isDeleted());
1890 }
1891 if (!m.isFileOrImage()
1892 && !encrypted
1893 && !m.isGeoUri()
1894 && !m.treatAsDownloadable()
1895 && !unInitiatedButKnownSize
1896 && t == null) {
1897 copyMessage.setVisible(true);
1898 }
1899 quoteMessage.setVisible(!encrypted && !showError);
1900 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1901 retryDecryption.setVisible(true);
1902 }
1903 if (!showError
1904 && relevantForCorrection.getType() == Message.TYPE_TEXT
1905 && relevantForCorrection.isEditable()
1906 && !m.isGeoUri()
1907 && m.getConversation() instanceof Conversation) {
1908 correctMessage.setVisible(true);
1909 if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1910 }
1911 if (relevantForCorrection.getStatus() == Message.STATUS_WAITING) {
1912 correctMessage.setVisible(true);
1913 retractMessage.setVisible(true);
1914 }
1915 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")) {
1916 moderateMessage.setVisible(true);
1917 }
1918 if ((m.isFileOrImage() && !deleted && !receiving)
1919 || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1920 && !unInitiatedButKnownSize
1921 && t == null) {
1922 shareWith.setVisible(true);
1923 }
1924 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1925 sendAgain.setVisible(true);
1926 }
1927 if (m.hasFileOnRemoteHost()
1928 || m.isGeoUri()
1929 || m.treatAsDownloadable()
1930 || unInitiatedButKnownSize
1931 || t instanceof HttpDownloadConnection) {
1932 copyUrl.setVisible(true);
1933 }
1934 if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1935 downloadFile.setVisible(true);
1936 downloadFile.setTitle(
1937 activity.getString(
1938 R.string.download_x_file,
1939 UIHelper.getFileDescriptionString(activity, m)));
1940 }
1941 final boolean waitingOfferedSending =
1942 m.getStatus() == Message.STATUS_WAITING
1943 || m.getStatus() == Message.STATUS_UNSEND
1944 || m.getStatus() == Message.STATUS_OFFERED;
1945 final boolean cancelable =
1946 (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1947 if (cancelable) {
1948 cancelTransmission.setVisible(true);
1949 }
1950 if (m.isFileOrImage() && !deleted && !cancelable) {
1951 final String path = m.getRelativeFilePath();
1952 if (path != null) {
1953 final var file = new File(path);
1954 if (file.canRead()) saveAsSticker.setVisible(true);
1955 blockMedia.setVisible(true);
1956 if (file.canWrite()) deleteFile.setVisible(true);
1957 deleteFile.setTitle(
1958 activity.getString(
1959 R.string.delete_x_file,
1960 UIHelper.getFileDescriptionString(activity, m)));
1961 }
1962 }
1963
1964 if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
1965 // We might be showing a thumbnail worth blocking
1966 blockMedia.setVisible(true);
1967 }
1968 if (showError) {
1969 showErrorMessage.setVisible(true);
1970 }
1971 final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1972 if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1973 || (mime != null && mime.startsWith("audio/"))) {
1974 openWith.setVisible(true);
1975 }
1976 }
1977 }
1978
1979 @Override
1980 public boolean onContextItemSelected(MenuItem item) {
1981 switch (item.getItemId()) {
1982 case R.id.share_with:
1983 ShareUtil.share(activity, selectedMessage);
1984 return true;
1985 case R.id.correct_message:
1986 correctMessage(selectedMessage);
1987 return true;
1988 case R.id.retract_message:
1989 new AlertDialog.Builder(activity)
1990 .setTitle(R.string.retract_message)
1991 .setMessage("Do you really want to retract this message?")
1992 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1993 Message message = selectedMessage;
1994 while (message.mergeable(message.next())) {
1995 message = message.next();
1996 }
1997 if (message.getStatus() == Message.STATUS_WAITING || message.getStatus() == Message.STATUS_OFFERED) {
1998 activity.xmppConnectionService.deleteMessage(message);
1999 return;
2000 }
2001 Element reactions = message.getReactionsEl();
2002 if (reactions != null) {
2003 final Message previousReaction = conversation.findMessageReactingTo(reactions.getAttribute("id"), null);
2004 if (previousReaction != null) reactions = previousReaction.getReactionsEl();
2005 for (Element el : reactions.getChildren()) {
2006 if (message.getRawBody().endsWith(el.getContent())) {
2007 reactions.removeChild(el);
2008 }
2009 }
2010 message.setReactions(reactions);
2011 if (previousReaction != null) {
2012 previousReaction.setReactions(reactions);
2013 activity.xmppConnectionService.updateMessage(previousReaction);
2014 }
2015 } else {
2016 message.setInReplyTo(null);
2017 message.clearPayloads();
2018 }
2019 message.setBody(" ");
2020 message.setSubject(null);
2021 message.putEdited(message.getUuid(), message.getServerMsgId());
2022 message.setServerMsgId(null);
2023 message.setUuid(UUID.randomUUID().toString());
2024 sendMessage(message);
2025 })
2026 .setNegativeButton(R.string.no, null).show();
2027 return true;
2028 case R.id.moderate_message:
2029 activity.quickEdit("Spam", (reason) -> {
2030 Message message = selectedMessage;
2031 do {
2032 activity.xmppConnectionService.moderateMessage(conversation.getAccount(), message, reason);
2033 message = message.mergeable(message.next()) ? message.next() : null;
2034 } while (message != null);
2035 return null;
2036 }, R.string.moderate_reason, false, false, true, true);
2037 return true;
2038 case R.id.copy_message:
2039 ShareUtil.copyToClipboard(activity, selectedMessage);
2040 return true;
2041 case R.id.quote_message:
2042 quoteMessage(selectedMessage);
2043 return true;
2044 case R.id.send_again:
2045 resendMessage(selectedMessage);
2046 return true;
2047 case R.id.copy_url:
2048 ShareUtil.copyUrlToClipboard(activity, selectedMessage);
2049 return true;
2050 case R.id.save_as_sticker:
2051 saveAsSticker(selectedMessage);
2052 return true;
2053 case R.id.download_file:
2054 startDownloadable(selectedMessage);
2055 return true;
2056 case R.id.cancel_transmission:
2057 cancelTransmission(selectedMessage);
2058 return true;
2059 case R.id.retry_decryption:
2060 retryDecryption(selectedMessage);
2061 return true;
2062 case R.id.block_media:
2063 new AlertDialog.Builder(activity)
2064 .setTitle(R.string.block_media)
2065 .setMessage("Do you really want to block this media in all messages?")
2066 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2067 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2068 if (thumbs != null && !thumbs.isEmpty()) {
2069 for (Element thumb : thumbs) {
2070 Uri uri = Uri.parse(thumb.getAttribute("uri"));
2071 if (uri.getScheme().equals("cid")) {
2072 Cid cid = BobTransfer.cid(uri);
2073 if (cid == null) continue;
2074 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2075 activity.xmppConnectionService.blockMedia(f);
2076 activity.xmppConnectionService.evictPreview(f);
2077 f.delete();
2078 }
2079 }
2080 }
2081 File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
2082 activity.xmppConnectionService.blockMedia(f);
2083 activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
2084 activity.xmppConnectionService.evictPreview(f);
2085 activity.xmppConnectionService.updateMessage(selectedMessage, false);
2086 activity.onConversationsListItemUpdated();
2087 refresh();
2088 })
2089 .setNegativeButton(R.string.no, null).show();
2090 return true;
2091 case R.id.delete_file:
2092 deleteFile(selectedMessage);
2093 return true;
2094 case R.id.show_error_message:
2095 showErrorMessage(selectedMessage);
2096 return true;
2097 case R.id.open_with:
2098 openWith(selectedMessage);
2099 return true;
2100 case R.id.only_this_thread:
2101 conversation.setLockThread(true);
2102 backPressedLeaveSingleThread.setEnabled(true);
2103 setThread(selectedMessage.getThread());
2104 refresh();
2105 return true;
2106 case R.id.action_report_and_block:
2107 reportMessage(selectedMessage);
2108 return true;
2109 case R.id.action_add_reaction:
2110 addReaction(selectedMessage);
2111 return true;
2112 default:
2113 return onOptionsItemSelected(item);
2114 }
2115 }
2116
2117 @Override
2118 public boolean onOptionsItemSelected(final MenuItem item) {
2119 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
2120 return false;
2121 } else if (conversation == null) {
2122 return super.onOptionsItemSelected(item);
2123 }
2124 switch (item.getItemId()) {
2125 case R.id.encryption_choice_axolotl:
2126 case R.id.encryption_choice_pgp:
2127 case R.id.encryption_choice_none:
2128 handleEncryptionSelection(item);
2129 break;
2130 case R.id.attach_choose_picture:
2131 //case R.id.attach_take_picture:
2132 //case R.id.attach_record_video:
2133 case R.id.attach_choose_file:
2134 case R.id.attach_record_voice:
2135 case R.id.attach_location:
2136 handleAttachmentSelection(item);
2137 break;
2138 case R.id.attach_webxdc:
2139 final Intent intent = new Intent(getActivity(), WebxdcStore.class);
2140 startActivityForResult(intent, REQUEST_WEBXDC_STORE);
2141 break;
2142 case R.id.attach_subject:
2143 binding.textinputSubject.setVisibility(binding.textinputSubject.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
2144 break;
2145 case R.id.attach_schedule:
2146 scheduleMessage();
2147 break;
2148 case R.id.action_search:
2149 startSearch();
2150 break;
2151 case R.id.action_archive:
2152 activity.xmppConnectionService.archiveConversation(conversation);
2153 break;
2154 case R.id.action_contact_details:
2155 activity.switchToContactDetails(conversation.getContact());
2156 break;
2157 case R.id.action_muc_details:
2158 ConferenceDetailsActivity.open(activity, conversation);
2159 break;
2160 case R.id.action_invite:
2161 startActivityForResult(
2162 ChooseContactActivity.create(activity, conversation),
2163 REQUEST_INVITE_TO_CONVERSATION);
2164 break;
2165 case R.id.action_clear_history:
2166 clearHistoryDialog(conversation);
2167 break;
2168 case R.id.action_mute:
2169 muteConversationDialog(conversation);
2170 break;
2171 case R.id.action_unmute:
2172 unMuteConversation(conversation);
2173 break;
2174 case R.id.action_block:
2175 case R.id.action_unblock:
2176 BlockContactDialog.show(activity, conversation);
2177 break;
2178 case R.id.action_audio_call:
2179 checkPermissionAndTriggerAudioCall();
2180 break;
2181 case R.id.action_video_call:
2182 checkPermissionAndTriggerVideoCall();
2183 break;
2184 case R.id.action_ongoing_call:
2185 returnToOngoingCall();
2186 break;
2187 case R.id.action_toggle_pinned:
2188 togglePinned();
2189 break;
2190 case R.id.action_add_shortcut:
2191 addShortcut();
2192 break;
2193 case R.id.action_block_avatar:
2194 new AlertDialog.Builder(activity)
2195 .setTitle(R.string.block_media)
2196 .setMessage("Do you really want to block this avatar?")
2197 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2198 activity.xmppConnectionService.blockMedia(activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatarFilename()));
2199 activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatarFilename()).delete();
2200 activity.avatarService().clear(conversation);
2201 conversation.getContact().setAvatar(null);
2202 activity.xmppConnectionService.updateConversationUi();
2203 })
2204 .setNegativeButton(R.string.no, null).show();
2205 case R.id.action_refresh_feature_discovery:
2206 refreshFeatureDiscovery();
2207 break;
2208 default:
2209 break;
2210 }
2211 return super.onOptionsItemSelected(item);
2212 }
2213
2214 public boolean onBackPressed() {
2215 boolean wasLocked = conversation.getLockThread();
2216 conversation.setLockThread(false);
2217 backPressedLeaveSingleThread.setEnabled(false);
2218 if (wasLocked) {
2219 setThread(null);
2220 conversation.setUserSelectedThread(false);
2221 refresh();
2222 updateThreadFromLastMessage();
2223 return true;
2224 }
2225 return false;
2226 }
2227
2228 private void startSearch() {
2229 final Intent intent = new Intent(getActivity(), SearchActivity.class);
2230 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
2231 startActivity(intent);
2232 }
2233
2234 private void scheduleMessage() {
2235 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
2236 final var datePicker = com.google.android.material.datepicker.MaterialDatePicker.Builder.datePicker()
2237 .setTitleText("Schedule Message")
2238 .setSelection(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2239 .setCalendarConstraints(
2240 new com.google.android.material.datepicker.CalendarConstraints.Builder()
2241 .setStart(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2242 .build()
2243 )
2244 .build();
2245 datePicker.addOnPositiveButtonClickListener((date) -> {
2246 final Calendar now = Calendar.getInstance();
2247 final var timePicker = new com.google.android.material.timepicker.MaterialTimePicker.Builder()
2248 .setTitleText("Schedule Message")
2249 .setHour(now.get(Calendar.HOUR_OF_DAY))
2250 .setMinute(now.get(Calendar.MINUTE))
2251 .setTimeFormat(android.text.format.DateFormat.is24HourFormat(activity) ? com.google.android.material.timepicker.TimeFormat.CLOCK_24H : com.google.android.material.timepicker.TimeFormat.CLOCK_12H)
2252 .build();
2253 timePicker.addOnPositiveButtonClickListener((v2) -> {
2254 final var dateCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
2255 dateCal.setTimeInMillis(date);
2256 final var time = Calendar.getInstance();
2257 time.set(dateCal.get(Calendar.YEAR), dateCal.get(Calendar.MONTH), dateCal.get(Calendar.DAY_OF_MONTH), timePicker.getHour(), timePicker.getMinute(), 0);
2258 final long timestamp = time.getTimeInMillis();
2259 sendMessage(timestamp);
2260 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": scheduled message for " + timestamp);
2261 });
2262 timePicker.show(activity.getSupportFragmentManager(), "schedulMessageTime");
2263 });
2264 datePicker.show(activity.getSupportFragmentManager(), "schedulMessageDate");
2265 }
2266 }
2267
2268 private void returnToOngoingCall() {
2269 final Optional<OngoingRtpSession> ongoingRtpSession =
2270 activity.xmppConnectionService
2271 .getJingleConnectionManager()
2272 .getOngoingRtpConnection(conversation.getContact());
2273 if (ongoingRtpSession.isPresent()) {
2274 final OngoingRtpSession id = ongoingRtpSession.get();
2275 final Intent intent = new Intent(getActivity(), RtpSessionActivity.class);
2276 intent.setAction(Intent.ACTION_VIEW);
2277 intent.putExtra(
2278 RtpSessionActivity.EXTRA_ACCOUNT,
2279 id.getAccount().getJid().asBareJid().toEscapedString());
2280 intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
2281 if (id instanceof AbstractJingleConnection) {
2282 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
2283 startActivity(intent);
2284 } else if (id instanceof JingleConnectionManager.RtpSessionProposal proposal) {
2285 if (Media.audioOnly(proposal.media)) {
2286 intent.putExtra(
2287 RtpSessionActivity.EXTRA_LAST_ACTION,
2288 RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2289 } else {
2290 intent.putExtra(
2291 RtpSessionActivity.EXTRA_LAST_ACTION,
2292 RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2293 }
2294 intent.putExtra(RtpSessionActivity.EXTRA_PROPOSED_SESSION_ID, proposal.sessionId);
2295 startActivity(intent);
2296 }
2297 }
2298 }
2299
2300 private void refreshFeatureDiscovery() {
2301 Set<Map.Entry<String, Presence>> presences = conversation.getContact().getPresences().getPresencesMap().entrySet();
2302 if (presences.isEmpty()) {
2303 presences = new HashSet<>();
2304 presences.add(new AbstractMap.SimpleEntry("", null));
2305 }
2306 for (Map.Entry<String, Presence> entry : presences) {
2307 Jid jid = conversation.getContact().getJid();
2308 if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
2309 activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
2310 if (activity == null) return;
2311 activity.runOnUiThread(() -> {
2312 refresh();
2313 refreshCommands(true);
2314 });
2315 });
2316 }
2317 }
2318
2319 private void addShortcut() {
2320 ShortcutInfoCompat info;
2321 if (conversation.getMode() == Conversation.MODE_MULTI) {
2322 info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getMucOptions());
2323 } else {
2324 info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getContact());
2325 }
2326 ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2327 }
2328
2329 private void togglePinned() {
2330 final boolean pinned =
2331 conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2332 conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2333 activity.xmppConnectionService.updateConversation(conversation);
2334 activity.invalidateOptionsMenu();
2335 }
2336
2337 private void checkPermissionAndTriggerAudioCall() {
2338 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2339 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2340 return;
2341 }
2342 final List<String> permissions;
2343 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2344 permissions =
2345 Arrays.asList(
2346 Manifest.permission.RECORD_AUDIO,
2347 Manifest.permission.BLUETOOTH_CONNECT);
2348 } else {
2349 permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2350 }
2351 if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2352 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2353 }
2354 }
2355
2356 private void checkPermissionAndTriggerVideoCall() {
2357 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2358 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2359 return;
2360 }
2361 final List<String> permissions;
2362 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2363 permissions =
2364 Arrays.asList(
2365 Manifest.permission.RECORD_AUDIO,
2366 Manifest.permission.CAMERA,
2367 Manifest.permission.BLUETOOTH_CONNECT);
2368 } else {
2369 permissions =
2370 Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2371 }
2372 if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2373 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2374 }
2375 }
2376
2377 private void triggerRtpSession(final String action) {
2378 if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
2379 Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2380 .show();
2381 return;
2382 }
2383 final Account account = conversation.getAccount();
2384 if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
2385 activity.xmppConnectionService.updateAccount(account);
2386 }
2387 final Contact contact = conversation.getContact();
2388 if (Config.USE_JINGLE_MESSAGE_INIT && RtpCapability.jmiSupport(contact)) {
2389 triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2390 } else {
2391 final RtpCapability.Capability capability;
2392 if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2393 capability = RtpCapability.Capability.VIDEO;
2394 } else {
2395 capability = RtpCapability.Capability.AUDIO;
2396 }
2397 PresenceSelector.selectFullJidForDirectRtpConnection(
2398 activity,
2399 contact,
2400 capability,
2401 fullJid -> {
2402 triggerRtpSession(contact.getAccount(), fullJid, action);
2403 });
2404 }
2405 }
2406
2407 private void triggerRtpSession(final Account account, final Jid with, final String action) {
2408 CallIntegrationConnectionService.placeCall(activity.xmppConnectionService, account,with,RtpSessionActivity.actionToMedia(action));
2409 }
2410
2411 private void handleAttachmentSelection(MenuItem item) {
2412 switch (item.getItemId()) {
2413 case R.id.attach_choose_picture:
2414 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2415 break;
2416 /*case R.id.attach_take_picture:
2417 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2418 break;
2419 case R.id.attach_record_video:
2420 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2421 break;*/
2422 case R.id.attach_choose_file:
2423 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2424 break;
2425 case R.id.attach_record_voice:
2426 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2427 break;
2428 case R.id.attach_location:
2429 attachFile(ATTACHMENT_CHOICE_LOCATION);
2430 break;
2431 }
2432 }
2433
2434 private void handleEncryptionSelection(MenuItem item) {
2435 if (conversation == null) {
2436 return;
2437 }
2438 final boolean updated;
2439 switch (item.getItemId()) {
2440 case R.id.encryption_choice_none:
2441 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2442 item.setChecked(true);
2443 break;
2444 case R.id.encryption_choice_pgp:
2445 if (activity.hasPgp()) {
2446 if (conversation.getAccount().getPgpSignature() != null) {
2447 updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2448 item.setChecked(true);
2449 } else {
2450 updated = false;
2451 activity.announcePgp(
2452 conversation.getAccount(),
2453 conversation,
2454 null,
2455 activity.onOpenPGPKeyPublished);
2456 }
2457 } else {
2458 activity.showInstallPgpDialog();
2459 updated = false;
2460 }
2461 break;
2462 case R.id.encryption_choice_axolotl:
2463 Log.d(
2464 Config.LOGTAG,
2465 AxolotlService.getLogprefix(conversation.getAccount())
2466 + "Enabled axolotl for Contact "
2467 + conversation.getContact().getJid());
2468 updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2469 item.setChecked(true);
2470 break;
2471 default:
2472 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2473 break;
2474 }
2475 if (updated) {
2476 activity.xmppConnectionService.updateConversation(conversation);
2477 }
2478 updateChatMsgHint();
2479 getActivity().invalidateOptionsMenu();
2480 activity.refreshUi();
2481 }
2482
2483 public void attachFile(final int attachmentChoice) {
2484 attachFile(attachmentChoice, true);
2485 }
2486
2487 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2488 if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2489 if (!hasPermissions(
2490 attachmentChoice,
2491 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2492 Manifest.permission.RECORD_AUDIO)) {
2493 return;
2494 }
2495 } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2496 || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
2497 if (!hasPermissions(
2498 attachmentChoice,
2499 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2500 Manifest.permission.CAMERA)) {
2501 return;
2502 }
2503 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2504 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2505 return;
2506 }
2507 }
2508 if (updateRecentlyUsed) {
2509 storeRecentlyUsedQuickAction(attachmentChoice);
2510 }
2511 final int encryption = conversation.getNextEncryption();
2512 final int mode = conversation.getMode();
2513 if (encryption == Message.ENCRYPTION_PGP) {
2514 if (activity.hasPgp()) {
2515 if (mode == Conversation.MODE_SINGLE
2516 && conversation.getContact().getPgpKeyId() != 0) {
2517 activity.xmppConnectionService
2518 .getPgpEngine()
2519 .hasKey(
2520 conversation.getContact(),
2521 new UiCallback<Contact>() {
2522
2523 @Override
2524 public void userInputRequired(
2525 PendingIntent pi, Contact contact) {
2526 startPendingIntent(pi, attachmentChoice);
2527 }
2528
2529 @Override
2530 public void success(Contact contact) {
2531 invokeAttachFileIntent(attachmentChoice);
2532 }
2533
2534 @Override
2535 public void error(int error, Contact contact) {
2536 activity.replaceToast(getString(error));
2537 }
2538 });
2539 } else if (mode == Conversation.MODE_MULTI
2540 && conversation.getMucOptions().pgpKeysInUse()) {
2541 if (!conversation.getMucOptions().everybodyHasKeys()) {
2542 Toast warning =
2543 Toast.makeText(
2544 getActivity(),
2545 R.string.missing_public_keys,
2546 Toast.LENGTH_LONG);
2547 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2548 warning.show();
2549 }
2550 invokeAttachFileIntent(attachmentChoice);
2551 } else {
2552 showNoPGPKeyDialog(
2553 false,
2554 (dialog, which) -> {
2555 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2556 activity.xmppConnectionService.updateConversation(conversation);
2557 invokeAttachFileIntent(attachmentChoice);
2558 });
2559 }
2560 } else {
2561 activity.showInstallPgpDialog();
2562 }
2563 } else {
2564 invokeAttachFileIntent(attachmentChoice);
2565 }
2566 }
2567
2568 private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2569 try {
2570 activity.getPreferences()
2571 .edit()
2572 .putString(
2573 RECENTLY_USED_QUICK_ACTION,
2574 SendButtonAction.of(attachmentChoice).toString())
2575 .apply();
2576 } catch (IllegalArgumentException e) {
2577 // just do not save
2578 }
2579 }
2580
2581 @Override
2582 public void onRequestPermissionsResult(
2583 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2584 final PermissionUtils.PermissionResult permissionResult =
2585 PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2586 if (grantResults.length > 0) {
2587 if (allGranted(permissionResult.grantResults)) {
2588 switch (requestCode) {
2589 case REQUEST_START_DOWNLOAD:
2590 if (this.mPendingDownloadableMessage != null) {
2591 startDownloadable(this.mPendingDownloadableMessage);
2592 }
2593 break;
2594 case REQUEST_ADD_EDITOR_CONTENT:
2595 if (this.mPendingEditorContent != null) {
2596 attachEditorContentToConversation(this.mPendingEditorContent);
2597 }
2598 break;
2599 case REQUEST_COMMIT_ATTACHMENTS:
2600 commitAttachments();
2601 break;
2602 case REQUEST_START_AUDIO_CALL:
2603 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2604 break;
2605 case REQUEST_START_VIDEO_CALL:
2606 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2607 break;
2608 default:
2609 attachFile(requestCode);
2610 break;
2611 }
2612 } else {
2613 @StringRes int res;
2614 String firstDenied =
2615 getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2616 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2617 res = R.string.no_microphone_permission;
2618 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2619 res = R.string.no_camera_permission;
2620 } else {
2621 res = R.string.no_storage_permission;
2622 }
2623 Toast.makeText(
2624 getActivity(),
2625 getString(res, getString(R.string.app_name)),
2626 Toast.LENGTH_SHORT)
2627 .show();
2628 }
2629 }
2630 if (writeGranted(grantResults, permissions)) {
2631 if (activity != null && activity.xmppConnectionService != null) {
2632 activity.xmppConnectionService.getDrawableCache().evictAll();
2633 activity.xmppConnectionService.restartFileObserver();
2634 }
2635 refresh();
2636 }
2637 if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
2638 XmppConnectionService.toggleForegroundService(activity);
2639 }
2640 }
2641
2642 public void startDownloadable(Message message) {
2643 if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2644 this.mPendingDownloadableMessage = message;
2645 return;
2646 }
2647 Transferable transferable = message.getTransferable();
2648 if (transferable != null) {
2649 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2650 createNewConnection(message);
2651 return;
2652 }
2653 if (!transferable.start()) {
2654 Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2655 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2656 .show();
2657 }
2658 } else if (message.treatAsDownloadable()
2659 || message.hasFileOnRemoteHost()
2660 || MessageUtils.unInitiatedButKnownSize(message)) {
2661 createNewConnection(message);
2662 } else {
2663 Log.d(
2664 Config.LOGTAG,
2665 message.getConversation().getAccount() + ": unable to start downloadable");
2666 }
2667 }
2668
2669 private void createNewConnection(final Message message) {
2670 if (!activity.xmppConnectionService.hasInternetConnection()) {
2671 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2672 .show();
2673 return;
2674 }
2675 if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2676 try {
2677 BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2678 message.setTransferable(transfer);
2679 transfer.start();
2680 } catch (URISyntaxException e) {
2681 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2682 }
2683 } else {
2684 activity.xmppConnectionService
2685 .getHttpConnectionManager()
2686 .createNewDownloadConnection(message, true);
2687 }
2688 }
2689
2690 @SuppressLint("InflateParams")
2691 protected void clearHistoryDialog(final Conversation conversation) {
2692 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2693 builder.setTitle(R.string.clear_conversation_history);
2694 final View dialogView =
2695 requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2696 final CheckBox endConversationCheckBox =
2697 dialogView.findViewById(R.id.end_conversation_checkbox);
2698 builder.setView(dialogView);
2699 builder.setNegativeButton(getString(R.string.cancel), null);
2700 builder.setPositiveButton(
2701 getString(R.string.confirm),
2702 (dialog, which) -> {
2703 this.activity.xmppConnectionService.clearConversationHistory(conversation);
2704 if (endConversationCheckBox.isChecked()) {
2705 this.activity.xmppConnectionService.archiveConversation(conversation);
2706 this.activity.onConversationArchived(conversation);
2707 } else {
2708 activity.onConversationsListItemUpdated();
2709 refresh();
2710 }
2711 });
2712 builder.create().show();
2713 }
2714
2715 protected void muteConversationDialog(final Conversation conversation) {
2716 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2717 builder.setTitle(R.string.disable_notifications);
2718 final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2719 final CharSequence[] labels = new CharSequence[durations.length];
2720 for (int i = 0; i < durations.length; ++i) {
2721 if (durations[i] == -1) {
2722 labels[i] = activity.getString(R.string.until_further_notice);
2723 } else {
2724 labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2725 }
2726 }
2727 builder.setItems(
2728 labels,
2729 (dialog, which) -> {
2730 final long till;
2731 if (durations[which] == -1) {
2732 till = Long.MAX_VALUE;
2733 } else {
2734 till = System.currentTimeMillis() + (durations[which] * 1000L);
2735 }
2736 conversation.setMutedTill(till);
2737 activity.xmppConnectionService.updateConversation(conversation);
2738 activity.onConversationsListItemUpdated();
2739 refresh();
2740 activity.invalidateOptionsMenu();
2741 });
2742 builder.create().show();
2743 }
2744
2745 private boolean hasPermissions(int requestCode, List<String> permissions) {
2746 final List<String> missingPermissions = new ArrayList<>();
2747 for (String permission : permissions) {
2748 if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU || Config.ONLY_INTERNAL_STORAGE) && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2749 continue;
2750 }
2751 if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2752 missingPermissions.add(permission);
2753 }
2754 }
2755 if (missingPermissions.size() == 0) {
2756 return true;
2757 } else {
2758 requestPermissions(
2759 missingPermissions.toArray(new String[0]),
2760 requestCode);
2761 return false;
2762 }
2763 }
2764
2765 private boolean hasPermissions(int requestCode, String... permissions) {
2766 return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2767 }
2768
2769 public void unMuteConversation(final Conversation conversation) {
2770 conversation.setMutedTill(0);
2771 this.activity.xmppConnectionService.updateConversation(conversation);
2772 this.activity.onConversationsListItemUpdated();
2773 refresh();
2774 this.activity.invalidateOptionsMenu();
2775 }
2776
2777 protected void invokeAttachFileIntent(final int attachmentChoice) {
2778 Intent intent = new Intent();
2779
2780 final var takePhotoIntent = new Intent();
2781 final Uri takePhotoUri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2782 pendingTakePhotoUri.push(takePhotoUri);
2783 takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePhotoUri);
2784 takePhotoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2785 takePhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2786 takePhotoIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2787
2788 final var takeVideoIntent = new Intent();
2789 takeVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2790
2791 switch (attachmentChoice) {
2792 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2793 intent.setAction(Intent.ACTION_GET_CONTENT);
2794 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2795 intent.setType("*/*");
2796 intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"});
2797 intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
2798 intent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent, takeVideoIntent });
2799 break;
2800 case ATTACHMENT_CHOICE_RECORD_VIDEO:
2801 intent = takeVideoIntent;
2802 break;
2803 case ATTACHMENT_CHOICE_TAKE_PHOTO:
2804 intent = takePhotoIntent;
2805 break;
2806 case ATTACHMENT_CHOICE_CHOOSE_FILE:
2807 intent.setAction(Intent.ACTION_GET_CONTENT);
2808 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2809 intent.setType("*/*");
2810 intent.addCategory(Intent.CATEGORY_OPENABLE);
2811 intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
2812 break;
2813 case ATTACHMENT_CHOICE_RECORD_VOICE:
2814 intent = new Intent(getActivity(), RecordingActivity.class);
2815 break;
2816 case ATTACHMENT_CHOICE_LOCATION:
2817 intent = GeoHelper.getFetchIntent(activity);
2818 break;
2819 }
2820 final Context context = getActivity();
2821 if (context == null) {
2822 return;
2823 }
2824 try {
2825 startActivityForResult(intent, attachmentChoice);
2826 } catch (final ActivityNotFoundException e) {
2827 Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2828 }
2829 }
2830
2831 @Override
2832 public void onResume() {
2833 super.onResume();
2834 binding.messagesView.post(this::fireReadEvent);
2835 }
2836
2837 private void fireReadEvent() {
2838 if (activity != null && this.conversation != null) {
2839 String uuid = getLastVisibleMessageUuid();
2840 if (uuid != null) {
2841 activity.onConversationRead(this.conversation, uuid);
2842 }
2843 }
2844 }
2845
2846 private void newSubThread() {
2847 Element oldThread = conversation.getThread();
2848 Element thread = new Element("thread", "jabber:client");
2849 thread.setContent(UUID.randomUUID().toString());
2850 if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2851 setThread(thread);
2852 }
2853
2854 private void newThread() {
2855 Element thread = new Element("thread", "jabber:client");
2856 thread.setContent(UUID.randomUUID().toString());
2857 setThread(thread);
2858 }
2859
2860 private void updateThreadFromLastMessage() {
2861 if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2862 Message message = getLastVisibleMessage();
2863 if (message == null) {
2864 newThread();
2865 } else {
2866 if (conversation.getMode() == Conversation.MODE_MULTI) {
2867 if (activity == null || activity.xmppConnectionService == null) return;
2868 if (message.getStatus() < Message.STATUS_SEND) {
2869 if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
2870 }
2871 }
2872
2873 setThread(message.getThread());
2874 }
2875 }
2876 }
2877
2878 private String getLastVisibleMessageUuid() {
2879 Message message = getLastVisibleMessage();
2880 return message == null ? null : message.getUuid();
2881 }
2882
2883 private Message getLastVisibleMessage() {
2884 if (binding == null) {
2885 return null;
2886 }
2887 synchronized (this.messageList) {
2888 int pos = binding.messagesView.getLastVisiblePosition();
2889 if (pos >= 0) {
2890 Message message = null;
2891 for (int i = pos; i >= 0; --i) {
2892 try {
2893 message = (Message) binding.messagesView.getItemAtPosition(i);
2894 } catch (IndexOutOfBoundsException e) {
2895 // should not happen if we synchronize properly. however if that fails we
2896 // just gonna try item -1
2897 continue;
2898 }
2899 if (message.getType() != Message.TYPE_STATUS) {
2900 break;
2901 }
2902 }
2903 if (message != null) {
2904 while (message.next() != null && message.next().wasMergedIntoPrevious(activity == null ? null : activity.xmppConnectionService)) {
2905 message = message.next();
2906 }
2907 return message;
2908 }
2909 }
2910 }
2911 return null;
2912 }
2913
2914 public void jumpTo(final Message message) {
2915 if (message.getUuid() == null) return;
2916 for (int i = 0; i < messageList.size(); i++) {
2917 final var m = messageList.get(i);
2918 if (m == null) continue;
2919 if (message.getUuid().equals(m.getUuid())) {
2920 binding.messagesView.setSelection(i);
2921 return;
2922 }
2923 }
2924 }
2925
2926 private void openWith(final Message message) {
2927 if (message.isGeoUri()) {
2928 GeoHelper.view(getActivity(), message);
2929 } else {
2930 final DownloadableFile file =
2931 activity.xmppConnectionService.getFileBackend().getFile(message);
2932 ViewUtil.view(activity, file);
2933 }
2934 }
2935
2936 private void addReaction(final Message message) {
2937 activity.addReaction(message, reactions -> activity.xmppConnectionService.sendReactions(message, reactions));
2938 }
2939
2940 private void reportMessage(final Message message) {
2941 BlockContactDialog.show(activity, conversation.getContact(), message.getServerMsgId());
2942 }
2943
2944 private void showErrorMessage(final Message message) {
2945 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2946 builder.setTitle(R.string.error_message);
2947 final String errorMessage = message.getErrorMessage();
2948 final String[] errorMessageParts =
2949 errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2950 final String displayError;
2951 if (errorMessageParts.length == 2) {
2952 displayError = errorMessageParts[1];
2953 } else {
2954 displayError = errorMessage;
2955 }
2956 builder.setMessage(displayError);
2957 builder.setNegativeButton(
2958 R.string.copy_to_clipboard,
2959 (dialog, which) -> {
2960 activity.copyTextToClipboard(displayError, R.string.error_message);
2961 Toast.makeText(
2962 activity,
2963 R.string.error_message_copied_to_clipboard,
2964 Toast.LENGTH_SHORT)
2965 .show();
2966 });
2967 builder.setPositiveButton(R.string.confirm, null);
2968 builder.create().show();
2969 }
2970
2971 public boolean onInlineImageLongClicked(Cid cid) {
2972 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2973 if (f == null) return false;
2974
2975 saveAsSticker(f, null);
2976 return true;
2977 }
2978
2979 private void saveAsSticker(final Message m) {
2980 String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
2981 existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
2982 saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
2983 }
2984
2985 private void saveAsSticker(final File file, final String name) {
2986 savingAsSticker = file;
2987
2988 Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
2989 intent.addCategory(Intent.CATEGORY_OPENABLE);
2990 intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file)));
2991 intent.putExtra(Intent.EXTRA_TITLE, name);
2992
2993 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2994 final String dir = p.getString("sticker_directory", "Stickers");
2995 if (dir.startsWith("content://")) {
2996 intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
2997 } else {
2998 new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
2999 Uri uri;
3000 if (Build.VERSION.SDK_INT >= 29) {
3001 Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
3002 uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
3003 uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
3004 } else {
3005 uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
3006 }
3007 intent.putExtra("android.provider.extra.INITIAL_URI", uri);
3008 intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
3009 }
3010
3011 Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
3012 startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
3013 }
3014
3015 private void deleteFile(final Message message) {
3016 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
3017 builder.setNegativeButton(R.string.cancel, null);
3018 builder.setTitle(R.string.delete_file_dialog);
3019 builder.setMessage(R.string.delete_file_dialog_msg);
3020 builder.setPositiveButton(
3021 R.string.confirm,
3022 (dialog, which) -> {
3023 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
3024 if (thumbs != null && !thumbs.isEmpty()) {
3025 for (Element thumb : thumbs) {
3026 Uri uri = Uri.parse(thumb.getAttribute("uri"));
3027 if (uri.getScheme().equals("cid")) {
3028 Cid cid = BobTransfer.cid(uri);
3029 if (cid == null) continue;
3030 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3031 activity.xmppConnectionService.evictPreview(f);
3032 f.delete();
3033 }
3034 }
3035 }
3036 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
3037 activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
3038 activity.xmppConnectionService.updateMessage(message, false);
3039 activity.onConversationsListItemUpdated();
3040 refresh();
3041 }
3042 });
3043 builder.create().show();
3044 }
3045
3046 private void resendMessage(final Message message) {
3047 if (message.isFileOrImage()) {
3048 if (!(message.getConversation() instanceof Conversation)) {
3049 return;
3050 }
3051 final Conversation conversation = (Conversation) message.getConversation();
3052 final DownloadableFile file =
3053 activity.xmppConnectionService.getFileBackend().getFile(message);
3054 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
3055 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
3056 if (!message.hasFileOnRemoteHost()
3057 && xmppConnection != null
3058 && conversation.getMode() == Conversational.MODE_SINGLE
3059 && !xmppConnection
3060 .getFeatures()
3061 .httpUpload(message.getFileParams().getSize())) {
3062 activity.selectPresence(
3063 conversation,
3064 () -> {
3065 message.setCounterpart(conversation.getNextCounterpart());
3066 activity.xmppConnectionService.resendFailedMessages(message);
3067 new Handler()
3068 .post(
3069 () -> {
3070 int size = messageList.size();
3071 this.binding.messagesView.setSelection(
3072 size - 1);
3073 });
3074 });
3075 return;
3076 }
3077 } else if (!Compatibility.hasStoragePermission(getActivity())) {
3078 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
3079 return;
3080 } else {
3081 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
3082 message.setDeleted(true);
3083 activity.xmppConnectionService.updateMessage(message, false);
3084 activity.onConversationsListItemUpdated();
3085 refresh();
3086 return;
3087 }
3088 }
3089 activity.xmppConnectionService.resendFailedMessages(message);
3090 new Handler()
3091 .post(
3092 () -> {
3093 int size = messageList.size();
3094 this.binding.messagesView.setSelection(size - 1);
3095 });
3096 }
3097
3098 private void cancelTransmission(Message message) {
3099 Transferable transferable = message.getTransferable();
3100 if (transferable != null) {
3101 transferable.cancel();
3102 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
3103 activity.xmppConnectionService.markMessage(
3104 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
3105 }
3106 }
3107
3108 private void retryDecryption(Message message) {
3109 message.setEncryption(Message.ENCRYPTION_PGP);
3110 activity.onConversationsListItemUpdated();
3111 refresh();
3112 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
3113 }
3114
3115 public void privateMessageWith(final Jid counterpart) {
3116 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3117 activity.xmppConnectionService.sendChatState(conversation);
3118 }
3119 this.binding.textinput.setText("");
3120 this.conversation.setNextCounterpart(counterpart);
3121 updateChatMsgHint();
3122 updateSendButton();
3123 updateEditablity();
3124 }
3125
3126 private void correctMessage(Message message) {
3127 while (message.mergeable(message.next())) {
3128 message = message.next();
3129 }
3130 setThread(message.getThread());
3131 conversation.setUserSelectedThread(true);
3132 this.conversation.setCorrectingMessage(message);
3133 final Editable editable = binding.textinput.getText();
3134 this.conversation.setDraftMessage(editable.toString());
3135 this.binding.textinput.setText("");
3136 this.binding.textinput.append(message.getBody(true));
3137 if (message.getSubject() != null && message.getSubject().length() > 0) {
3138 this.binding.textinputSubject.setText(message.getSubject());
3139 this.binding.textinputSubject.setVisibility(View.VISIBLE);
3140 }
3141 final var replyTo = message.getInReplyTo();
3142 if (replyTo != null) {
3143 setupReply(replyTo);
3144 }
3145 }
3146
3147 private void highlightInConference(String nick) {
3148 final Editable editable = this.binding.textinput.getText();
3149 String oldString = editable.toString().trim();
3150 final int pos = this.binding.textinput.getSelectionStart();
3151 if (oldString.isEmpty() || pos == 0) {
3152 editable.insert(0, nick + ": ");
3153 } else {
3154 final char before = editable.charAt(pos - 1);
3155 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
3156 if (before == '\n') {
3157 editable.insert(pos, nick + ": ");
3158 } else {
3159 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
3160 if (NickValidityChecker.check(
3161 conversation,
3162 Arrays.asList(
3163 editable.subSequence(0, pos - 2).toString().split(", ")))) {
3164 editable.insert(pos - 2, ", " + nick);
3165 return;
3166 }
3167 }
3168 editable.insert(
3169 pos,
3170 (Character.isWhitespace(before) ? "" : " ")
3171 + nick
3172 + (Character.isWhitespace(after) ? "" : " "));
3173 if (Character.isWhitespace(after)) {
3174 this.binding.textinput.setSelection(
3175 this.binding.textinput.getSelectionStart() + 1);
3176 }
3177 }
3178 }
3179 }
3180
3181 @Override
3182 public void startActivityForResult(Intent intent, int requestCode) {
3183 final Activity activity = getActivity();
3184 if (activity instanceof ConversationsActivity) {
3185 ((ConversationsActivity) activity).clearPendingViewIntent();
3186 }
3187 super.startActivityForResult(intent, requestCode);
3188 }
3189
3190 @Override
3191 public void onSaveInstanceState(@NonNull Bundle outState) {
3192 super.onSaveInstanceState(outState);
3193 if (conversation != null) {
3194 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
3195 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
3196 final Uri uri = pendingTakePhotoUri.peek();
3197 if (uri != null) {
3198 outState.putString(STATE_PHOTO_URI, uri.toString());
3199 }
3200 final ScrollState scrollState = getScrollPosition();
3201 if (scrollState != null) {
3202 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
3203 }
3204 final ArrayList<Attachment> attachments =
3205 mediaPreviewAdapter == null
3206 ? new ArrayList<>()
3207 : mediaPreviewAdapter.getAttachments();
3208 if (attachments.size() > 0) {
3209 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
3210 }
3211 }
3212 }
3213
3214 @Override
3215 public void onActivityCreated(Bundle savedInstanceState) {
3216 super.onActivityCreated(savedInstanceState);
3217 if (savedInstanceState == null) {
3218 return;
3219 }
3220 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
3221 ArrayList<Attachment> attachments =
3222 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
3223 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
3224 if (uuid != null) {
3225 QuickLoader.set(uuid);
3226 this.pendingConversationsUuid.push(uuid);
3227 if (attachments != null && attachments.size() > 0) {
3228 this.pendingMediaPreviews.push(attachments);
3229 }
3230 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
3231 if (takePhotoUri != null) {
3232 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
3233 }
3234 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
3235 }
3236 }
3237
3238 @Override
3239 public void onStart() {
3240 super.onStart();
3241 if (this.reInitRequiredOnStart && this.conversation != null) {
3242 final Bundle extras = pendingExtras.pop();
3243 reInit(this.conversation, extras != null);
3244 if (extras != null) {
3245 processExtras(extras);
3246 }
3247 } else if (conversation == null
3248 && activity != null
3249 && activity.xmppConnectionService != null) {
3250 final String uuid = pendingConversationsUuid.pop();
3251 Log.d(
3252 Config.LOGTAG,
3253 "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
3254 + uuid);
3255 if (uuid != null) {
3256 findAndReInitByUuidOrArchive(uuid);
3257 }
3258 }
3259 }
3260
3261 @Override
3262 public void onStop() {
3263 super.onStop();
3264 final Activity activity = getActivity();
3265 messageListAdapter.unregisterListenerInAudioPlayer();
3266 if (activity == null || !activity.isChangingConfigurations()) {
3267 hideSoftKeyboard(activity);
3268 messageListAdapter.stopAudioPlayer();
3269 }
3270 if (this.conversation != null) {
3271 final String msg = this.binding.textinput.getText().toString();
3272 storeNextMessage(msg);
3273 updateChatState(this.conversation, msg);
3274 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
3275 }
3276 this.reInitRequiredOnStart = true;
3277 }
3278
3279 private void updateChatState(final Conversation conversation, final String msg) {
3280 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
3281 Account.State status = conversation.getAccount().getStatus();
3282 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
3283 activity.xmppConnectionService.sendChatState(conversation);
3284 }
3285 }
3286
3287 private void saveMessageDraftStopAudioPlayer() {
3288 final Conversation previousConversation = this.conversation;
3289 if (this.activity == null || this.binding == null || previousConversation == null) {
3290 return;
3291 }
3292 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
3293 final String msg = this.binding.textinput.getText().toString();
3294 storeNextMessage(msg);
3295 updateChatState(this.conversation, msg);
3296 messageListAdapter.stopAudioPlayer();
3297 mediaPreviewAdapter.clearPreviews();
3298 toggleInputMethod();
3299 }
3300
3301 public void reInit(final Conversation conversation, final Bundle extras) {
3302 QuickLoader.set(conversation.getUuid());
3303 final boolean changedConversation = this.conversation != conversation;
3304 if (changedConversation) {
3305 this.saveMessageDraftStopAudioPlayer();
3306 }
3307 this.clearPending();
3308 if (this.reInit(conversation, extras != null)) {
3309 if (extras != null) {
3310 processExtras(extras);
3311 }
3312 this.reInitRequiredOnStart = false;
3313 } else {
3314 this.reInitRequiredOnStart = true;
3315 pendingExtras.push(extras);
3316 }
3317 resetUnreadMessagesCount();
3318 }
3319
3320 private void reInit(Conversation conversation) {
3321 reInit(conversation, false);
3322 }
3323
3324 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
3325 if (conversation == null) {
3326 return false;
3327 }
3328 final Conversation originalConversation = this.conversation;
3329 this.conversation = conversation;
3330 // once we set the conversation all is good and it will automatically do the right thing in
3331 // onStart()
3332 if (this.activity == null || this.binding == null) {
3333 return false;
3334 }
3335
3336 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3337 activity.onConversationArchived(this.conversation);
3338 return false;
3339 }
3340
3341 final var cursord = activity.getDrawable(R.drawable.cursor_on_tertiary_container);
3342 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getAccounts().size() > 1) {
3343 final var bg = MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorSurface);
3344 final var accountColor = conversation.getAccount().getColor(activity.isDark());
3345 final var colors = MaterialColors.getColorRoles(activity, accountColor);
3346 final var accent = activity.isDark() ? ColorUtils.blendARGB(colors.getAccentContainer(), bg, 1.0f - Math.max(0.25f, Color.alpha(accountColor) / 255.0f)) : colors.getAccentContainer();
3347 cursord.setTintList(ColorStateList.valueOf(colors.getOnAccentContainer()));
3348 binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(accent));
3349 binding.textinputSubject.setTextColor(colors.getOnAccentContainer());
3350 binding.textinput.setTextColor(colors.getOnAccentContainer());
3351 binding.textinputSubject.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3352 binding.textinput.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3353 binding.textInputHint.setTextColor(colors.getOnAccentContainer());
3354 } else {
3355 cursord.setTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer)));
3356 binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.inputLayout, com.google.android.material.R.attr.colorTertiaryContainer)));
3357 binding.textinputSubject.setTextColor(MaterialColors.getColor(binding.textinputSubject, com.google.android.material.R.attr.colorOnTertiaryContainer));
3358 binding.textinput.setTextColor(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer));
3359 binding.textinputSubject.setHintTextColor(R.color.hint_on_tertiary_container);
3360 binding.textinput.setHintTextColor(R.color.hint_on_tertiary_container);
3361 binding.textInputHint.setTextColor(MaterialColors.getColor(binding.textInputHint, com.google.android.material.R.attr.colorOnTertiaryContainer));
3362 }
3363 if (Build.VERSION.SDK_INT >= 29) {
3364 binding.textinputSubject.setTextCursorDrawable(cursord);
3365 binding.textinput.setTextCursorDrawable(cursord);
3366 }
3367
3368 setThread(conversation.getThread());
3369 setupReply(conversation.getReplyTo());
3370
3371 stopScrolling();
3372 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3373
3374 if (this.conversation.isRead(activity == null ? null : activity.xmppConnectionService) && hasExtras) {
3375 Log.d(Config.LOGTAG, "trimming conversation");
3376 this.conversation.trim();
3377 }
3378
3379 setupIme();
3380
3381 final boolean scrolledToBottomAndNoPending =
3382 this.scrolledToBottom() && pendingScrollState.peek() == null;
3383
3384 this.binding.textSendButton.setContentDescription(
3385 activity.getString(R.string.send_message_to_x, conversation.getName()));
3386 this.binding.textinput.setKeyboardListener(null);
3387 this.binding.textinputSubject.setKeyboardListener(null);
3388 final boolean participating =
3389 conversation.getMode() == Conversational.MODE_SINGLE
3390 || conversation.getMucOptions().participating();
3391 if (participating) {
3392 this.binding.textinput.setText(this.conversation.getNextMessage());
3393 this.binding.textinput.setSelection(this.binding.textinput.length());
3394 } else {
3395 this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3396 }
3397 this.binding.textinput.setKeyboardListener(this);
3398 this.binding.textinputSubject.setKeyboardListener(this);
3399 messageListAdapter.updatePreferences();
3400 refresh(false);
3401 activity.invalidateOptionsMenu();
3402 this.conversation.messagesLoaded.set(true);
3403 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3404
3405 if (hasExtras || scrolledToBottomAndNoPending) {
3406 resetUnreadMessagesCount();
3407 synchronized (this.messageList) {
3408 Log.d(Config.LOGTAG, "jump to first unread message");
3409 final Message first = conversation.getFirstUnreadMessage();
3410 final int bottom = Math.max(0, this.messageList.size() - 1);
3411 final int pos;
3412 final boolean jumpToBottom;
3413 if (first == null) {
3414 pos = bottom;
3415 jumpToBottom = true;
3416 } else {
3417 int i = getIndexOf(first.getUuid(), this.messageList);
3418 pos = i < 0 ? bottom : i;
3419 jumpToBottom = false;
3420 }
3421 setSelection(pos, jumpToBottom);
3422 }
3423 }
3424
3425 this.binding.messagesView.post(this::fireReadEvent);
3426 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3427 // layout which might be unnecessary since we can *see* it
3428 activity.xmppConnectionService
3429 .getNotificationService()
3430 .setOpenConversation(this.conversation);
3431
3432 if (commandAdapter != null && conversation != originalConversation) {
3433 commandAdapter.clear();
3434 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3435 refreshCommands(false);
3436 }
3437 if (commandAdapter == null && conversation != null) {
3438 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3439 commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3440 binding.commandsView.setAdapter(commandAdapter);
3441 binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3442 if (activity == null) return;
3443
3444 commandAdapter.getItem(position).start(activity, ConversationFragment.this.conversation);
3445 });
3446 refreshCommands(false);
3447 }
3448
3449 binding.commandsNote.setVisibility(activity.xmppConnectionService.isOnboarding() ? View.VISIBLE : View.GONE);
3450
3451 return true;
3452 }
3453
3454 @Override
3455 public void refreshForNewCaps(final Set<Jid> newCapsJids) {
3456 if (newCapsJids.isEmpty() || (conversation != null && newCapsJids.contains(conversation.getJid().asBareJid()))) {
3457 refreshCommands(true);
3458 }
3459 }
3460
3461 protected void refreshCommands(boolean delayShow) {
3462 if (commandAdapter == null) return;
3463
3464 final CommandAdapter.MucConfig mucConfig =
3465 conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER) ?
3466 new CommandAdapter.MucConfig() :
3467 null;
3468
3469 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3470 if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3471 commandJid = conversation.getJid().asBareJid();
3472 }
3473 if (commandJid == null && conversation.getJid().isDomainJid()) {
3474 commandJid = conversation.getJid();
3475 }
3476 if (commandJid == null) {
3477 binding.commandsViewProgressbar.setVisibility(View.GONE);
3478 if (mucConfig == null) {
3479 conversation.hideViewPager();
3480 } else {
3481 commandAdapter.clear();
3482 commandAdapter.add(mucConfig);
3483 conversation.showViewPager();
3484 }
3485 } else {
3486 if (!delayShow) conversation.showViewPager();
3487 binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3488 activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (iq) -> {
3489 if (activity == null) return;
3490
3491 activity.runOnUiThread(() -> {
3492 binding.commandsViewProgressbar.setVisibility(View.GONE);
3493 commandAdapter.clear();
3494 if (iq.getType() == Iq.Type.RESULT) {
3495 for (Element child : iq.query().getChildren()) {
3496 if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3497 commandAdapter.add(new CommandAdapter.Command0050(child));
3498 }
3499 }
3500
3501 if (mucConfig != null) commandAdapter.add(mucConfig);
3502
3503 if (commandAdapter.getCount() < 1) {
3504 conversation.hideViewPager();
3505 } else if (delayShow) {
3506 conversation.showViewPager();
3507 }
3508 });
3509 });
3510 }
3511 }
3512
3513 private void resetUnreadMessagesCount() {
3514 lastMessageUuid = null;
3515 hideUnreadMessagesCount();
3516 }
3517
3518 private void hideUnreadMessagesCount() {
3519 if (this.binding == null) {
3520 return;
3521 }
3522 this.binding.scrollToBottomButton.setEnabled(false);
3523 this.binding.scrollToBottomButton.hide();
3524 this.binding.unreadCountCustomView.setVisibility(View.GONE);
3525 }
3526
3527 private void setSelection(int pos, boolean jumpToBottom) {
3528 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3529 this.binding.messagesView.post(
3530 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3531 this.binding.messagesView.post(this::fireReadEvent);
3532 }
3533
3534 private boolean scrolledToBottom() {
3535 return this.binding != null && scrolledToBottom(this.binding.messagesView);
3536 }
3537
3538 private void processExtras(final Bundle extras) {
3539 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3540 final String text = extras.getString(Intent.EXTRA_TEXT);
3541 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3542 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3543 final String postInitAction =
3544 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3545 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3546 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3547 final boolean doNotAppend =
3548 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3549 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3550
3551 final String thread = extras.getString(ConversationsActivity.EXTRA_THREAD);
3552 if (thread != null) {
3553 conversation.setLockThread(true);
3554 backPressedLeaveSingleThread.setEnabled(true);
3555 setThread(new Element("thread").setContent(thread));
3556 refresh();
3557 }
3558
3559 final List<Uri> uris = extractUris(extras);
3560 if (uris != null && uris.size() > 0) {
3561 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3562 mediaPreviewAdapter.addMediaPreviews(
3563 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3564 } else {
3565 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3566 mediaPreviewAdapter.addMediaPreviews(
3567 Attachment.of(getActivity(), cleanedUris, type));
3568 }
3569 toggleInputMethod();
3570 return;
3571 }
3572 if (nick != null) {
3573 if (pm) {
3574 Jid jid = conversation.getJid();
3575 try {
3576 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3577 privateMessageWith(next);
3578 } catch (final IllegalArgumentException ignored) {
3579 // do nothing
3580 }
3581 } else {
3582 final MucOptions mucOptions = conversation.getMucOptions();
3583 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3584 highlightInConference(nick);
3585 }
3586 }
3587 } else {
3588 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3589 mediaPreviewAdapter.addMediaPreviews(
3590 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3591 toggleInputMethod();
3592 return;
3593 } else if (text != null && asQuote) {
3594 quoteText(text);
3595 } else {
3596 appendText(text, doNotAppend);
3597 }
3598 }
3599 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3600 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3601 return;
3602 }
3603 if ("call".equals(postInitAction)) {
3604 checkPermissionAndTriggerAudioCall();
3605 }
3606 if ("message".equals(postInitAction)) {
3607 binding.conversationViewPager.post(() -> {
3608 binding.conversationViewPager.setCurrentItem(0);
3609 });
3610 }
3611 if ("command".equals(postInitAction)) {
3612 binding.conversationViewPager.post(() -> {
3613 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3614 if (adapter != null && adapter.getCount() > 1) {
3615 binding.conversationViewPager.setCurrentItem(1);
3616 }
3617 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3618 Jid commandJid = null;
3619 if (jid != null) {
3620 try {
3621 commandJid = Jid.of(jid);
3622 } catch (final IllegalArgumentException e) { }
3623 }
3624 if (commandJid == null || !commandJid.isFullJid()) {
3625 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3626 if (discoJid != null) commandJid = discoJid;
3627 }
3628 if (node != null && commandJid != null && activity != null) {
3629 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3630 }
3631 });
3632 return;
3633 }
3634 Message message =
3635 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3636 if ("webxdc".equals(postInitAction)) {
3637 if (message == null) {
3638 message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3639 }
3640 if (message == null) return;
3641
3642 Cid webxdcCid = message.getFileParams().getCids().get(0);
3643 WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
3644 Conversation conversation = (Conversation) message.getConversation();
3645 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3646 conversation.startWebxdc(webxdc);
3647 }
3648 }
3649 if (message != null) {
3650 startDownloadable(message);
3651 }
3652 if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3653 if (!conversation.switchToSession("jabber:iq:register")) {
3654 conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3655 }
3656 }
3657 }
3658
3659 private Element commandFor(final Jid jid, final String node) {
3660 if (commandAdapter != null) {
3661 for (int i = 0; i < commandAdapter.getCount(); i++) {
3662 final CommandAdapter.Command c = commandAdapter.getItem(i);
3663 if (!(c instanceof CommandAdapter.Command0050)) continue;
3664
3665 final Element command = ((CommandAdapter.Command0050) c).el;
3666 final String commandNode = command.getAttribute("node");
3667 if (commandNode == null || !commandNode.equals(node)) continue;
3668
3669 final Jid commandJid = command.getAttributeAsJid("jid");
3670 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3671
3672 return command;
3673 }
3674 }
3675
3676 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3677 }
3678
3679 private List<Uri> extractUris(final Bundle extras) {
3680 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3681 if (uris != null) {
3682 return uris;
3683 }
3684 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3685 if (uri != null) {
3686 return Collections.singletonList(uri);
3687 } else {
3688 return null;
3689 }
3690 }
3691
3692 private List<Uri> cleanUris(final List<Uri> uris) {
3693 final Iterator<Uri> iterator = uris.iterator();
3694 while (iterator.hasNext()) {
3695 final Uri uri = iterator.next();
3696 if (FileBackend.dangerousFile(uri)) {
3697 iterator.remove();
3698 Toast.makeText(
3699 requireActivity(),
3700 R.string.security_violation_not_attaching_file,
3701 Toast.LENGTH_SHORT)
3702 .show();
3703 }
3704 }
3705 return uris;
3706 }
3707
3708 private boolean showBlockSubmenu(View view) {
3709 final Jid jid = conversation.getJid();
3710 final int mode = conversation.getMode();
3711 final var contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3712 final boolean showReject = contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3713 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3714 popupMenu.inflate(R.menu.block);
3715 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3716 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3717 popupMenu.getMenu().findItem(R.id.add_contact).setVisible(!contact.showInRoster());
3718 popupMenu.setOnMenuItemClickListener(
3719 menuItem -> {
3720 Blockable blockable;
3721 switch (menuItem.getItemId()) {
3722 case R.id.reject:
3723 activity.xmppConnectionService.stopPresenceUpdatesTo(
3724 conversation.getContact());
3725 updateSnackBar(conversation);
3726 return true;
3727 case R.id.add_contact:
3728 mAddBackClickListener.onClick(view);
3729 return true;
3730 case R.id.block_domain:
3731 blockable =
3732 conversation
3733 .getAccount()
3734 .getRoster()
3735 .getContact(jid.getDomain());
3736 break;
3737 default:
3738 blockable = conversation;
3739 }
3740 BlockContactDialog.show(activity, blockable);
3741 return true;
3742 });
3743 popupMenu.show();
3744 return true;
3745 }
3746
3747 private boolean showBlockMucSubmenu(View view) {
3748 final var jid = conversation.getJid();
3749 final var popupMenu = new PopupMenu(getActivity(), view);
3750 popupMenu.inflate(R.menu.block_muc);
3751 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3752 popupMenu.setOnMenuItemClickListener(
3753 menuItem -> {
3754 Blockable blockable;
3755 switch (menuItem.getItemId()) {
3756 case R.id.reject:
3757 activity.xmppConnectionService.clearConversationHistory(conversation);
3758 activity.xmppConnectionService.archiveConversation(conversation);
3759 return true;
3760 case R.id.add_bookmark:
3761 activity.xmppConnectionService.saveConversationAsBookmark(conversation, "");
3762 updateSnackBar(conversation);
3763 return true;
3764 case R.id.block_contact:
3765 blockable =
3766 conversation
3767 .getAccount()
3768 .getRoster()
3769 .getContact(Jid.of(conversation.getAttribute("inviter")));
3770 break;
3771 default:
3772 blockable = conversation;
3773 }
3774 BlockContactDialog.show(activity, blockable);
3775 activity.xmppConnectionService.archiveConversation(conversation);
3776 return true;
3777 });
3778 popupMenu.show();
3779 return true;
3780 }
3781
3782 private void updateSnackBar(final Conversation conversation) {
3783 final Account account = conversation.getAccount();
3784 final XmppConnection connection = account.getXmppConnection();
3785 final int mode = conversation.getMode();
3786 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3787 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3788 return;
3789 }
3790 if (account.getStatus() == Account.State.DISABLED) {
3791 showSnackbar(
3792 R.string.this_account_is_disabled,
3793 R.string.enable,
3794 this.mEnableAccountListener);
3795 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3796 showSnackbar(R.string.this_account_is_logged_out,R.string.log_in,this.mEnableAccountListener);
3797 } else if (conversation.isBlocked()) {
3798 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3799 } else if (account.getStatus() == Account.State.CONNECTING) {
3800 showSnackbar(R.string.this_account_is_connecting, 0, null);
3801 } else if (account.getStatus() != Account.State.ONLINE) {
3802 showSnackbar(R.string.this_account_is_offline, 0, null);
3803 } else if (contact != null
3804 && !contact.showInRoster()
3805 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3806 showSnackbar(
3807 R.string.contact_added_you,
3808 R.string.options,
3809 this.mBlockClickListener,
3810 this.mLongPressBlockListener);
3811 } else if (contact != null
3812 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3813 showSnackbar(
3814 R.string.contact_asks_for_presence_subscription,
3815 R.string.allow,
3816 this.mAllowPresenceSubscription,
3817 this.mLongPressBlockListener);
3818 } else if (mode == Conversation.MODE_MULTI
3819 && !conversation.getMucOptions().online()
3820 && account.getStatus() == Account.State.ONLINE) {
3821 switch (conversation.getMucOptions().getError()) {
3822 case NICK_IN_USE:
3823 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3824 break;
3825 case NO_RESPONSE:
3826 showSnackbar(R.string.joining_conference, 0, null);
3827 break;
3828 case SERVER_NOT_FOUND:
3829 if (conversation.receivedMessagesCount() > 0) {
3830 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3831 } else {
3832 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3833 }
3834 break;
3835 case REMOTE_SERVER_TIMEOUT:
3836 if (conversation.receivedMessagesCount() > 0) {
3837 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3838 } else {
3839 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3840 }
3841 break;
3842 case PASSWORD_REQUIRED:
3843 showSnackbar(
3844 R.string.conference_requires_password,
3845 R.string.enter_password,
3846 enterPassword);
3847 break;
3848 case BANNED:
3849 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3850 break;
3851 case MEMBERS_ONLY:
3852 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3853 break;
3854 case RESOURCE_CONSTRAINT:
3855 showSnackbar(
3856 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3857 break;
3858 case KICKED:
3859 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3860 break;
3861 case TECHNICAL_PROBLEMS:
3862 showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3863 break;
3864 case UNKNOWN:
3865 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3866 break;
3867 case INVALID_NICK:
3868 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3869 case SHUTDOWN:
3870 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3871 break;
3872 case DESTROYED:
3873 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3874 break;
3875 case NON_ANONYMOUS:
3876 showSnackbar(
3877 R.string.group_chat_will_make_your_jabber_id_public,
3878 R.string.join,
3879 acceptJoin);
3880 break;
3881 default:
3882 hideSnackbar();
3883 break;
3884 }
3885 } else if (account.hasPendingPgpIntent(conversation)) {
3886 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3887 } else if (connection != null
3888 && connection.getFeatures().blocking()
3889 && conversation.strangerInvited()) {
3890 showSnackbar(
3891 R.string.received_invite_from_stranger,
3892 R.string.options,
3893 (v) -> showBlockMucSubmenu(v),
3894 (v) -> showBlockMucSubmenu(v));
3895 } else if (connection != null
3896 && connection.getFeatures().blocking()
3897 && conversation.countMessages() != 0
3898 && !conversation.isBlocked()
3899 && conversation.isWithStranger()) {
3900 showSnackbar(
3901 R.string.received_message_from_stranger,
3902 R.string.options,
3903 this.mBlockClickListener,
3904 this.mLongPressBlockListener);
3905 } else {
3906 hideSnackbar();
3907 }
3908 }
3909
3910 @Override
3911 public void refresh() {
3912 if (this.binding == null) {
3913 Log.d(
3914 Config.LOGTAG,
3915 "ConversationFragment.refresh() skipped updated because view binding was null");
3916 return;
3917 }
3918 if (this.conversation != null
3919 && this.activity != null
3920 && this.activity.xmppConnectionService != null) {
3921 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3922 activity.onConversationArchived(this.conversation);
3923 return;
3924 }
3925 }
3926 this.refresh(true);
3927 }
3928
3929 private void refresh(boolean notifyConversationRead) {
3930 synchronized (this.messageList) {
3931 if (this.conversation != null) {
3932 if (messageListAdapter.hasSelection()) {
3933 if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3934 } else {
3935 conversation.populateWithMessages(this.messageList, activity == null ? null : activity.xmppConnectionService);
3936 updateStatusMessages();
3937 this.messageListAdapter.notifyDataSetChanged();
3938 }
3939 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3940 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3941 binding.unreadCountCustomView.setUnreadCount(
3942 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3943 }
3944 updateSnackBar(conversation);
3945 if (activity != null) updateChatMsgHint();
3946 if (notifyConversationRead && activity != null) {
3947 binding.messagesView.post(this::fireReadEvent);
3948 }
3949 updateSendButton();
3950 updateEditablity();
3951 conversation.refreshSessions();
3952 }
3953 }
3954 }
3955
3956 protected void messageSent() {
3957 binding.textinputSubject.setText("");
3958 binding.textinputSubject.setVisibility(View.GONE);
3959 setThread(null);
3960 setupReply(null);
3961 conversation.setUserSelectedThread(false);
3962 mSendingPgpMessage.set(false);
3963 this.binding.textinput.setText("");
3964 if (conversation.setCorrectingMessage(null)) {
3965 this.binding.textinput.append(conversation.getDraftMessage());
3966 conversation.setDraftMessage(null);
3967 }
3968 storeNextMessage();
3969 updateChatMsgHint();
3970 if (activity == null) return;
3971 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3972 final boolean prefScrollToBottom =
3973 p.getBoolean(
3974 "scroll_to_bottom",
3975 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3976 if (prefScrollToBottom || scrolledToBottom()) {
3977 new Handler()
3978 .post(
3979 () -> {
3980 int size = messageList.size();
3981 this.binding.messagesView.setSelection(size - 1);
3982 });
3983 }
3984 }
3985
3986 private boolean storeNextMessage() {
3987 return storeNextMessage(this.binding.textinput.getText().toString());
3988 }
3989
3990 private boolean storeNextMessage(String msg) {
3991 final boolean participating =
3992 conversation.getMode() == Conversational.MODE_SINGLE
3993 || conversation.getMucOptions().participating();
3994 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3995 && participating
3996 && this.conversation.setNextMessage(msg) && activity != null) {
3997 activity.xmppConnectionService.updateConversation(this.conversation);
3998 return true;
3999 }
4000 return false;
4001 }
4002
4003 public void doneSendingPgpMessage() {
4004 mSendingPgpMessage.set(false);
4005 }
4006
4007 public long getMaxHttpUploadSize(Conversation conversation) {
4008 final XmppConnection connection = conversation.getAccount().getXmppConnection();
4009 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
4010 }
4011
4012 private boolean canWrite() {
4013 return
4014 this.conversation.getMode() == Conversation.MODE_SINGLE
4015 || this.conversation.getMucOptions().participating()
4016 || this.conversation.getNextCounterpart() != null;
4017 }
4018
4019 private void updateEditablity() {
4020 boolean canWrite = canWrite();
4021 this.binding.textinput.setFocusable(canWrite);
4022 this.binding.textinput.setFocusableInTouchMode(canWrite);
4023 this.binding.textSendButton.setEnabled(canWrite);
4024 this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
4025 this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
4026 this.binding.textinput.setCursorVisible(canWrite);
4027 this.binding.textinput.setEnabled(canWrite);
4028 }
4029
4030 public void updateSendButton() {
4031 boolean hasAttachments =
4032 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
4033 final Conversation c = this.conversation;
4034 final Presence.Status status;
4035 final String text =
4036 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
4037 final SendButtonAction action;
4038 if (hasAttachments) {
4039 action = SendButtonAction.TEXT;
4040 } else {
4041 action = SendButtonTool.getAction(getActivity(), c, text, binding.textinputSubject.getText().toString());
4042 }
4043 if (c.getAccount().getStatus() == Account.State.ONLINE) {
4044 if (activity != null
4045 && activity.xmppConnectionService != null
4046 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
4047 status = Presence.Status.OFFLINE;
4048 } else if (c.getMode() == Conversation.MODE_SINGLE) {
4049 status = c.getContact().getShownStatus();
4050 } else {
4051 status =
4052 c.getMucOptions().online()
4053 ? Presence.Status.ONLINE
4054 : Presence.Status.OFFLINE;
4055 }
4056 } else {
4057 status = Presence.Status.OFFLINE;
4058 }
4059 this.binding.textSendButton.setTag(action);
4060 this.binding.textSendButton.setIconTint(ColorStateList.valueOf(SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
4061 // TODO send button color
4062 final Activity activity = getActivity();
4063 if (activity != null) {
4064 this.binding.textSendButton.setIconResource(
4065 SendButtonTool.getSendButtonImageResource(action, text.length() > 0 || hasAttachments || (c.getThread() != null && binding.textinputSubject.getText().length() > 0)));
4066 }
4067
4068 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
4069 if (identiconWidth < 0) identiconWidth = params.width;
4070 if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
4071 binding.conversationViewPager.setCurrentItem(0);
4072 params.width = conversation.getThread() == null ? 0 : identiconWidth;
4073 } else {
4074 params.width = identiconWidth;
4075 }
4076 if (!canWrite()) params.width = 0;
4077 binding.threadIdenticonLayout.setLayoutParams(params);
4078 }
4079
4080 protected void updateStatusMessages() {
4081 DateSeparator.addAll(this.messageList);
4082 if (showLoadMoreMessages(conversation)) {
4083 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
4084 }
4085 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4086 ChatState state = conversation.getIncomingChatState();
4087 if (state == ChatState.COMPOSING) {
4088 this.messageList.add(
4089 Message.createStatusMessage(
4090 conversation,
4091 getString(R.string.contact_is_typing, conversation.getName())));
4092 } else if (state == ChatState.PAUSED) {
4093 this.messageList.add(
4094 Message.createStatusMessage(
4095 conversation,
4096 getString(
4097 R.string.contact_has_stopped_typing,
4098 conversation.getName())));
4099 } else {
4100 for (int i = this.messageList.size() - 1; i >= 0; --i) {
4101 final Message message = this.messageList.get(i);
4102 if (message.getType() != Message.TYPE_STATUS) {
4103 if (message.getStatus() == Message.STATUS_RECEIVED) {
4104 return;
4105 } else {
4106 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
4107 this.messageList.add(
4108 i + 1,
4109 Message.createStatusMessage(
4110 conversation,
4111 getString(
4112 R.string.contact_has_read_up_to_this_point,
4113 conversation.getName())));
4114 return;
4115 }
4116 }
4117 }
4118 }
4119 }
4120 } else {
4121 final MucOptions mucOptions = conversation.getMucOptions();
4122 final List<MucOptions.User> allUsers = mucOptions.getUsers();
4123 final Set<ReadByMarker> addedMarkers = new HashSet<>();
4124 ChatState state = ChatState.COMPOSING;
4125 List<MucOptions.User> users =
4126 conversation.getMucOptions().getUsersWithChatState(state, 5);
4127 if (users.size() == 0) {
4128 state = ChatState.PAUSED;
4129 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
4130 }
4131 if (mucOptions.isPrivateAndNonAnonymous()) {
4132 for (int i = this.messageList.size() - 1; i >= 0; --i) {
4133 final Set<ReadByMarker> markersForMessage =
4134 messageList.get(i).getReadByMarkers();
4135 final List<MucOptions.User> shownMarkers = new ArrayList<>();
4136 for (ReadByMarker marker : markersForMessage) {
4137 if (!ReadByMarker.contains(marker, addedMarkers)) {
4138 addedMarkers.add(
4139 marker); // may be put outside this condition. set should do
4140 // dedup anyway
4141 MucOptions.User user = mucOptions.findUser(marker);
4142 if (user != null && !users.contains(user)) {
4143 shownMarkers.add(user);
4144 }
4145 }
4146 }
4147 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
4148 final Message statusMessage;
4149 final int size = shownMarkers.size();
4150 if (size > 1) {
4151 final String body;
4152 if (size <= 4) {
4153 body =
4154 getString(
4155 R.string.contacts_have_read_up_to_this_point,
4156 UIHelper.concatNames(shownMarkers));
4157 } else if (ReadByMarker.allUsersRepresented(
4158 allUsers, markersForMessage, markerForSender)) {
4159 body = getString(R.string.everyone_has_read_up_to_this_point);
4160 } else {
4161 body =
4162 getString(
4163 R.string.contacts_and_n_more_have_read_up_to_this_point,
4164 UIHelper.concatNames(shownMarkers, 3),
4165 size - 3);
4166 }
4167 statusMessage = Message.createStatusMessage(conversation, body);
4168 statusMessage.setCounterparts(shownMarkers);
4169 } else if (size == 1) {
4170 statusMessage =
4171 Message.createStatusMessage(
4172 conversation,
4173 getString(
4174 R.string.contact_has_read_up_to_this_point,
4175 UIHelper.getDisplayName(shownMarkers.get(0))));
4176 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
4177 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
4178 } else {
4179 statusMessage = null;
4180 }
4181 if (statusMessage != null) {
4182 this.messageList.add(i + 1, statusMessage);
4183 }
4184 addedMarkers.add(markerForSender);
4185 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
4186 break;
4187 }
4188 }
4189 }
4190 if (users.size() > 0) {
4191 Message statusMessage;
4192 if (users.size() == 1) {
4193 MucOptions.User user = users.get(0);
4194 int id =
4195 state == ChatState.COMPOSING
4196 ? R.string.contact_is_typing
4197 : R.string.contact_has_stopped_typing;
4198 statusMessage =
4199 Message.createStatusMessage(
4200 conversation, getString(id, UIHelper.getDisplayName(user)));
4201 statusMessage.setTrueCounterpart(user.getRealJid());
4202 statusMessage.setCounterpart(user.getFullJid());
4203 } else {
4204 int id =
4205 state == ChatState.COMPOSING
4206 ? R.string.contacts_are_typing
4207 : R.string.contacts_have_stopped_typing;
4208 statusMessage =
4209 Message.createStatusMessage(
4210 conversation, getString(id, UIHelper.concatNames(users)));
4211 statusMessage.setCounterparts(users);
4212 }
4213 this.messageList.add(statusMessage);
4214 }
4215 }
4216 }
4217
4218 private void stopScrolling() {
4219 long now = SystemClock.uptimeMillis();
4220 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
4221 binding.messagesView.dispatchTouchEvent(cancel);
4222 }
4223
4224 private boolean showLoadMoreMessages(final Conversation c) {
4225 if (activity == null || activity.xmppConnectionService == null) {
4226 return false;
4227 }
4228 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
4229 final MessageArchiveService service =
4230 activity.xmppConnectionService.getMessageArchiveService();
4231 return mam
4232 && (c.getLastClearHistory().getTimestamp() != 0
4233 || (c.countMessages() == 0
4234 && c.messagesLoaded.get()
4235 && c.hasMessagesLeftOnServer()
4236 && !service.queryInProgress(c)));
4237 }
4238
4239 private boolean hasMamSupport(final Conversation c) {
4240 if (c.getMode() == Conversation.MODE_SINGLE) {
4241 final XmppConnection connection = c.getAccount().getXmppConnection();
4242 return connection != null && connection.getFeatures().mam();
4243 } else {
4244 return c.getMucOptions().mamSupport();
4245 }
4246 }
4247
4248 protected void showSnackbar(
4249 final int message, final int action, final OnClickListener clickListener) {
4250 showSnackbar(message, action, clickListener, null);
4251 }
4252
4253 protected void showSnackbar(
4254 final int message,
4255 final int action,
4256 final OnClickListener clickListener,
4257 final View.OnLongClickListener longClickListener) {
4258 this.binding.snackbar.setVisibility(View.VISIBLE);
4259 this.binding.snackbar.setOnClickListener(null);
4260 this.binding.snackbarMessage.setText(message);
4261 this.binding.snackbarMessage.setOnClickListener(null);
4262 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
4263 if (action != 0) {
4264 this.binding.snackbarAction.setText(action);
4265 }
4266 this.binding.snackbarAction.setOnClickListener(clickListener);
4267 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
4268 }
4269
4270 protected void hideSnackbar() {
4271 this.binding.snackbar.setVisibility(View.GONE);
4272 }
4273
4274 protected void sendMessage(Message message) {
4275 new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
4276 messageSent();
4277 }
4278
4279 protected void sendPgpMessage(final Message message) {
4280 final XmppConnectionService xmppService = activity.xmppConnectionService;
4281 final Contact contact = message.getConversation().getContact();
4282 if (!activity.hasPgp()) {
4283 activity.showInstallPgpDialog();
4284 return;
4285 }
4286 if (conversation.getAccount().getPgpSignature() == null) {
4287 activity.announcePgp(
4288 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
4289 return;
4290 }
4291 if (!mSendingPgpMessage.compareAndSet(false, true)) {
4292 Log.d(Config.LOGTAG, "sending pgp message already in progress");
4293 }
4294 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4295 if (contact.getPgpKeyId() != 0) {
4296 xmppService
4297 .getPgpEngine()
4298 .hasKey(
4299 contact,
4300 new UiCallback<Contact>() {
4301
4302 @Override
4303 public void userInputRequired(
4304 PendingIntent pi, Contact contact) {
4305 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
4306 }
4307
4308 @Override
4309 public void success(Contact contact) {
4310 encryptTextMessage(message);
4311 }
4312
4313 @Override
4314 public void error(int error, Contact contact) {
4315 activity.runOnUiThread(
4316 () ->
4317 Toast.makeText(
4318 activity,
4319 R.string
4320 .unable_to_connect_to_keychain,
4321 Toast.LENGTH_SHORT)
4322 .show());
4323 mSendingPgpMessage.set(false);
4324 }
4325 });
4326
4327 } else {
4328 showNoPGPKeyDialog(
4329 false,
4330 (dialog, which) -> {
4331 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4332 xmppService.updateConversation(conversation);
4333 message.setEncryption(Message.ENCRYPTION_NONE);
4334 xmppService.sendMessage(message);
4335 messageSent();
4336 });
4337 }
4338 } else {
4339 if (conversation.getMucOptions().pgpKeysInUse()) {
4340 if (!conversation.getMucOptions().everybodyHasKeys()) {
4341 Toast warning =
4342 Toast.makeText(
4343 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
4344 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
4345 warning.show();
4346 }
4347 encryptTextMessage(message);
4348 } else {
4349 showNoPGPKeyDialog(
4350 true,
4351 (dialog, which) -> {
4352 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4353 message.setEncryption(Message.ENCRYPTION_NONE);
4354 xmppService.updateConversation(conversation);
4355 xmppService.sendMessage(message);
4356 messageSent();
4357 });
4358 }
4359 }
4360 }
4361
4362 public void encryptTextMessage(Message message) {
4363 activity.xmppConnectionService
4364 .getPgpEngine()
4365 .encrypt(
4366 message,
4367 new UiCallback<Message>() {
4368
4369 @Override
4370 public void userInputRequired(PendingIntent pi, Message message) {
4371 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
4372 }
4373
4374 @Override
4375 public void success(Message message) {
4376 // TODO the following two call can be made before the callback
4377 getActivity().runOnUiThread(() -> messageSent());
4378 }
4379
4380 @Override
4381 public void error(final int error, Message message) {
4382 getActivity()
4383 .runOnUiThread(
4384 () -> {
4385 doneSendingPgpMessage();
4386 Toast.makeText(
4387 getActivity(),
4388 error == 0
4389 ? R.string
4390 .unable_to_connect_to_keychain
4391 : error,
4392 Toast.LENGTH_SHORT)
4393 .show();
4394 });
4395 }
4396 });
4397 }
4398
4399 public void showNoPGPKeyDialog(final boolean plural, final DialogInterface.OnClickListener listener) {
4400 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
4401 if (plural) {
4402 builder.setTitle(getString(R.string.no_pgp_keys));
4403 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
4404 } else {
4405 builder.setTitle(getString(R.string.no_pgp_key));
4406 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
4407 }
4408 builder.setNegativeButton(getString(R.string.cancel), null);
4409 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
4410 builder.create().show();
4411 }
4412
4413 public void appendText(String text, final boolean doNotAppend) {
4414 if (text == null) {
4415 return;
4416 }
4417 final Editable editable = this.binding.textinput.getText();
4418 String previous = editable == null ? "" : editable.toString();
4419 if (doNotAppend && !TextUtils.isEmpty(previous)) {
4420 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
4421 .show();
4422 return;
4423 }
4424 if (UIHelper.isLastLineQuote(previous)) {
4425 text = '\n' + text;
4426 } else if (previous.length() != 0
4427 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4428 text = " " + text;
4429 }
4430 this.binding.textinput.append(text);
4431 }
4432
4433 @Override
4434 public boolean onEnterPressed(final boolean isCtrlPressed) {
4435 if (isCtrlPressed || enterIsSend()) {
4436 sendMessage();
4437 return true;
4438 }
4439 return false;
4440 }
4441
4442 private boolean enterIsSend() {
4443 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4444 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4445 }
4446
4447 public boolean onArrowUpCtrlPressed() {
4448 final Message lastEditableMessage =
4449 conversation == null ? null : conversation.getLastEditableMessage();
4450 if (lastEditableMessage != null) {
4451 correctMessage(lastEditableMessage);
4452 return true;
4453 } else {
4454 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4455 .show();
4456 return false;
4457 }
4458 }
4459
4460 @Override
4461 public void onTypingStarted() {
4462 final XmppConnectionService service =
4463 activity == null ? null : activity.xmppConnectionService;
4464 if (service == null) {
4465 return;
4466 }
4467 final Account.State status = conversation.getAccount().getStatus();
4468 if (status == Account.State.ONLINE
4469 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4470 service.sendChatState(conversation);
4471 }
4472 runOnUiThread(this::updateSendButton);
4473 }
4474
4475 @Override
4476 public void onTypingStopped() {
4477 final XmppConnectionService service =
4478 activity == null ? null : activity.xmppConnectionService;
4479 if (service == null) {
4480 return;
4481 }
4482 final Account.State status = conversation.getAccount().getStatus();
4483 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4484 service.sendChatState(conversation);
4485 }
4486 }
4487
4488 @Override
4489 public void onTextDeleted() {
4490 final XmppConnectionService service =
4491 activity == null ? null : activity.xmppConnectionService;
4492 if (service == null) {
4493 return;
4494 }
4495 final Account.State status = conversation.getAccount().getStatus();
4496 if (status == Account.State.ONLINE
4497 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4498 service.sendChatState(conversation);
4499 }
4500 if (storeNextMessage()) {
4501 runOnUiThread(
4502 () -> {
4503 if (activity == null) {
4504 return;
4505 }
4506 activity.onConversationsListItemUpdated();
4507 });
4508 }
4509 runOnUiThread(this::updateSendButton);
4510 }
4511
4512 @Override
4513 public void onTextChanged() {
4514 if (conversation != null && conversation.getCorrectingMessage() != null) {
4515 runOnUiThread(this::updateSendButton);
4516 }
4517 }
4518
4519 @Override
4520 public boolean onTabPressed(boolean repeated) {
4521 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4522 return false;
4523 }
4524 if (repeated) {
4525 completionIndex++;
4526 } else {
4527 lastCompletionLength = 0;
4528 completionIndex = 0;
4529 final String content = this.binding.textinput.getText().toString();
4530 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4531 int start =
4532 lastCompletionCursor > 0
4533 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4534 : 0;
4535 firstWord = start == 0;
4536 incomplete = content.substring(start, lastCompletionCursor);
4537 }
4538 List<String> completions = new ArrayList<>();
4539 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4540 String name = user.getNick();
4541 if (name != null && name.startsWith(incomplete)) {
4542 completions.add(name + (firstWord ? ": " : " "));
4543 }
4544 }
4545 Collections.sort(completions);
4546 if (completions.size() > completionIndex) {
4547 String completion = completions.get(completionIndex).substring(incomplete.length());
4548 this.binding
4549 .textinput
4550 .getEditableText()
4551 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4552 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4553 lastCompletionLength = completion.length();
4554 } else {
4555 completionIndex = -1;
4556 this.binding
4557 .textinput
4558 .getEditableText()
4559 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4560 lastCompletionLength = 0;
4561 }
4562 return true;
4563 }
4564
4565 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4566 try {
4567 getActivity()
4568 .startIntentSenderForResult(
4569 pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
4570 } catch (final SendIntentException ignored) {
4571 }
4572 }
4573
4574 @Override
4575 public void onBackendConnected() {
4576 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4577 setupEmojiSearch();
4578 String uuid = pendingConversationsUuid.pop();
4579 if (uuid != null) {
4580 if (!findAndReInitByUuidOrArchive(uuid)) {
4581 return;
4582 }
4583 } else {
4584 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4585 clearPending();
4586 activity.onConversationArchived(conversation);
4587 return;
4588 }
4589 }
4590 ActivityResult activityResult = postponedActivityResult.pop();
4591 if (activityResult != null) {
4592 handleActivityResult(activityResult);
4593 }
4594 clearPending();
4595 }
4596
4597 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4598 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4599 if (conversation == null) {
4600 clearPending();
4601 activity.onConversationArchived(null);
4602 return false;
4603 }
4604 reInit(conversation);
4605 ScrollState scrollState = pendingScrollState.pop();
4606 String lastMessageUuid = pendingLastMessageUuid.pop();
4607 List<Attachment> attachments = pendingMediaPreviews.pop();
4608 if (scrollState != null) {
4609 setScrollPosition(scrollState, lastMessageUuid);
4610 }
4611 if (attachments != null && attachments.size() > 0) {
4612 Log.d(Config.LOGTAG, "had attachments on restore");
4613 mediaPreviewAdapter.addMediaPreviews(attachments);
4614 toggleInputMethod();
4615 }
4616 return true;
4617 }
4618
4619 private void clearPending() {
4620 if (postponedActivityResult.clear()) {
4621 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4622 if (pendingTakePhotoUri.clear()) {
4623 Log.e(Config.LOGTAG, "cleared pending photo uri");
4624 }
4625 }
4626 if (pendingScrollState.clear()) {
4627 Log.e(Config.LOGTAG, "cleared scroll state");
4628 }
4629 if (pendingConversationsUuid.clear()) {
4630 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4631 }
4632 if (pendingMediaPreviews.clear()) {
4633 Log.e(Config.LOGTAG, "cleared pending media previews");
4634 }
4635 }
4636
4637 public Conversation getConversation() {
4638 return conversation;
4639 }
4640
4641 @Override
4642 public void onContactPictureLongClicked(View v, final Message message) {
4643 final String fingerprint;
4644 if (message.getEncryption() == Message.ENCRYPTION_PGP
4645 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4646 fingerprint = "pgp";
4647 } else {
4648 fingerprint = message.getFingerprint();
4649 }
4650 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4651 final Contact contact = message.getContact();
4652 if (message.getStatus() <= Message.STATUS_RECEIVED
4653 && (contact == null || !contact.isSelf())) {
4654 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4655 final Jid cp = message.getCounterpart();
4656 if (cp == null || cp.isBareJid()) {
4657 return;
4658 }
4659 final Jid tcp = message.getTrueCounterpart();
4660 final String occupantId = message.getOccupantId();
4661 final User userByRealJid =
4662 tcp != null
4663 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp, occupantId)
4664 : null;
4665 final User userByOccupantId =
4666 occupantId != null
4667 ? conversation.getMucOptions().findUserByOccupantId(occupantId, cp)
4668 : null;
4669 final User user =
4670 userByRealJid != null
4671 ? userByRealJid
4672 : (userByOccupantId != null ? userByOccupantId : conversation.getMucOptions().findUserByFullJid(cp));
4673 if (user == null) return;
4674 popupMenu.inflate(R.menu.muc_details_context);
4675 final Menu menu = popupMenu.getMenu();
4676 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4677 activity, menu, conversation, user);
4678 popupMenu.setOnMenuItemClickListener(
4679 menuItem ->
4680 MucDetailsContextMenuHelper.onContextItemSelected(
4681 menuItem, user, activity, fingerprint));
4682 } else {
4683 popupMenu.inflate(R.menu.one_on_one_context);
4684 popupMenu.setOnMenuItemClickListener(
4685 item -> {
4686 switch (item.getItemId()) {
4687 case R.id.action_contact_details:
4688 activity.switchToContactDetails(
4689 message.getContact(), fingerprint);
4690 break;
4691 case R.id.action_show_qr_code:
4692 activity.showQrCode(
4693 "xmpp:"
4694 + message.getContact()
4695 .getJid()
4696 .asBareJid()
4697 .toEscapedString());
4698 break;
4699 }
4700 return true;
4701 });
4702 }
4703 } else {
4704 popupMenu.inflate(R.menu.account_context);
4705 final Menu menu = popupMenu.getMenu();
4706 menu.findItem(R.id.action_manage_accounts)
4707 .setVisible(QuickConversationsService.isConversations());
4708 popupMenu.setOnMenuItemClickListener(
4709 item -> {
4710 final XmppActivity activity = this.activity;
4711 if (activity == null) {
4712 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4713 return true;
4714 }
4715 switch (item.getItemId()) {
4716 case R.id.action_show_qr_code:
4717 activity.showQrCode(conversation.getAccount().getShareableUri());
4718 break;
4719 case R.id.action_account_details:
4720 activity.switchToAccount(
4721 message.getConversation().getAccount(), fingerprint);
4722 break;
4723 case R.id.action_manage_accounts:
4724 AccountUtils.launchManageAccounts(activity);
4725 break;
4726 }
4727 return true;
4728 });
4729 }
4730 popupMenu.show();
4731 }
4732
4733 @Override
4734 public void onContactPictureClicked(Message message) {
4735 setThread(message.getThread());
4736 if (message.isPrivateMessage()) {
4737 privateMessageWith(message.getCounterpart());
4738 return;
4739 }
4740 forkNullThread(message);
4741 conversation.setUserSelectedThread(true);
4742
4743 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4744 if (received) {
4745 if (message.getConversation() instanceof Conversation
4746 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4747 Jid tcp = message.getTrueCounterpart();
4748 Jid user = message.getCounterpart();
4749 if (user != null && !user.isBareJid()) {
4750 final MucOptions mucOptions =
4751 ((Conversation) message.getConversation()).getMucOptions();
4752 if (mucOptions.participating()
4753 || ((Conversation) message.getConversation()).getNextCounterpart()
4754 != null) {
4755 MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4756 MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4757 if (mucUser == null && tcpMucUser == null) {
4758 Toast.makeText(
4759 getActivity(),
4760 activity.getString(
4761 R.string.user_has_left_conference,
4762 user.getResource()),
4763 Toast.LENGTH_SHORT)
4764 .show();
4765 }
4766 highlightInConference(mucUser == null || mucUser.getNick() == null ? (tcpMucUser == null || tcpMucUser.getNick() == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4767 } else {
4768 Toast.makeText(
4769 getActivity(),
4770 R.string.you_are_not_participating,
4771 Toast.LENGTH_SHORT)
4772 .show();
4773 }
4774 }
4775 }
4776 }
4777 }
4778
4779 private Activity requireActivity() {
4780 Activity activity = getActivity();
4781 if (activity == null) activity = this.activity;
4782 if (activity == null) {
4783 throw new IllegalStateException("Activity not attached");
4784 }
4785 return activity;
4786 }
4787}