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