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