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