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