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