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