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