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