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