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