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 return true;
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 return true;
2210 case R.id.attach_webxdc:
2211 final Intent intent = new Intent(getActivity(), WebxdcStore.class);
2212 startActivityForResult(intent, REQUEST_WEBXDC_STORE);
2213 return true;
2214 case R.id.attach_subject:
2215 binding.textinputSubject.setVisibility(binding.textinputSubject.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
2216 return true;
2217 case R.id.attach_schedule:
2218 scheduleMessage();
2219 return true;
2220 case R.id.action_search:
2221 startSearch();
2222 return true;
2223 case R.id.action_archive:
2224 activity.xmppConnectionService.archiveConversation(conversation);
2225 return true;
2226 case R.id.action_contact_details:
2227 activity.switchToContactDetails(conversation.getContact());
2228 return true;
2229 case R.id.action_muc_details:
2230 ConferenceDetailsActivity.open(activity, conversation);
2231 return true;
2232 case R.id.action_invite:
2233 startActivityForResult(
2234 ChooseContactActivity.create(activity, conversation),
2235 REQUEST_INVITE_TO_CONVERSATION);
2236 return true;
2237 case R.id.action_clear_history:
2238 clearHistoryDialog(conversation);
2239 return true;
2240 case R.id.action_mute:
2241 muteConversationDialog(conversation);
2242 return true;
2243 case R.id.action_unmute:
2244 unMuteConversation(conversation);
2245 return true;
2246 case R.id.action_block:
2247 case R.id.action_unblock:
2248 BlockContactDialog.show(activity, conversation);
2249 return true;
2250 case R.id.action_audio_call:
2251 checkPermissionAndTriggerAudioCall();
2252 return true;
2253 case R.id.action_video_call:
2254 checkPermissionAndTriggerVideoCall();
2255 return true;
2256 case R.id.action_ongoing_call:
2257 returnToOngoingCall();
2258 return true;
2259 case R.id.action_toggle_pinned:
2260 togglePinned();
2261 return true;
2262 case R.id.action_add_shortcut:
2263 addShortcut();
2264 return true;
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 return true;
2278 case R.id.action_refresh_feature_discovery:
2279 refreshFeatureDiscovery();
2280 return true;
2281 default:
2282 break;
2283 }
2284 return super.onOptionsItemSelected(item);
2285 }
2286
2287 public boolean onBackPressed() {
2288 boolean wasLocked = conversation.getLockThread();
2289 conversation.setLockThread(false);
2290 backPressedLeaveSingleThread.setEnabled(false);
2291 if (wasLocked) {
2292 setThread(null);
2293 conversation.setUserSelectedThread(false);
2294 refresh();
2295 updateThreadFromLastMessage();
2296 return true;
2297 }
2298 return false;
2299 }
2300
2301 private void startSearch() {
2302 final Intent intent = new Intent(getActivity(), SearchActivity.class);
2303 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
2304 startActivity(intent);
2305 }
2306
2307 private void scheduleMessage() {
2308 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
2309 final var datePicker = com.google.android.material.datepicker.MaterialDatePicker.Builder.datePicker()
2310 .setTitleText("Schedule Message")
2311 .setSelection(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2312 .setCalendarConstraints(
2313 new com.google.android.material.datepicker.CalendarConstraints.Builder()
2314 .setStart(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2315 .build()
2316 )
2317 .build();
2318 datePicker.addOnPositiveButtonClickListener((date) -> {
2319 final Calendar now = Calendar.getInstance();
2320 final var timePicker = new com.google.android.material.timepicker.MaterialTimePicker.Builder()
2321 .setTitleText("Schedule Message")
2322 .setHour(now.get(Calendar.HOUR_OF_DAY))
2323 .setMinute(now.get(Calendar.MINUTE))
2324 .setTimeFormat(android.text.format.DateFormat.is24HourFormat(activity) ? com.google.android.material.timepicker.TimeFormat.CLOCK_24H : com.google.android.material.timepicker.TimeFormat.CLOCK_12H)
2325 .build();
2326 timePicker.addOnPositiveButtonClickListener((v2) -> {
2327 final var dateCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
2328 dateCal.setTimeInMillis(date);
2329 final var time = Calendar.getInstance();
2330 time.set(dateCal.get(Calendar.YEAR), dateCal.get(Calendar.MONTH), dateCal.get(Calendar.DAY_OF_MONTH), timePicker.getHour(), timePicker.getMinute(), 0);
2331 final long timestamp = time.getTimeInMillis();
2332 sendMessage(timestamp);
2333 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": scheduled message for " + timestamp);
2334 });
2335 timePicker.show(activity.getSupportFragmentManager(), "schedulMessageTime");
2336 });
2337 datePicker.show(activity.getSupportFragmentManager(), "schedulMessageDate");
2338 }
2339 }
2340
2341 private void returnToOngoingCall() {
2342 final Optional<OngoingRtpSession> ongoingRtpSession =
2343 activity.xmppConnectionService
2344 .getJingleConnectionManager()
2345 .getOngoingRtpConnection(conversation.getContact());
2346 if (ongoingRtpSession.isPresent()) {
2347 final OngoingRtpSession id = ongoingRtpSession.get();
2348 final Intent intent = new Intent(getActivity(), RtpSessionActivity.class);
2349 intent.setAction(Intent.ACTION_VIEW);
2350 intent.putExtra(
2351 RtpSessionActivity.EXTRA_ACCOUNT,
2352 id.getAccount().getJid().asBareJid().toString());
2353 intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toString());
2354 if (id instanceof AbstractJingleConnection) {
2355 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
2356 startActivity(intent);
2357 } else if (id instanceof JingleConnectionManager.RtpSessionProposal proposal) {
2358 if (Media.audioOnly(proposal.media)) {
2359 intent.putExtra(
2360 RtpSessionActivity.EXTRA_LAST_ACTION,
2361 RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2362 } else {
2363 intent.putExtra(
2364 RtpSessionActivity.EXTRA_LAST_ACTION,
2365 RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2366 }
2367 intent.putExtra(RtpSessionActivity.EXTRA_PROPOSED_SESSION_ID, proposal.sessionId);
2368 startActivity(intent);
2369 }
2370 }
2371 }
2372
2373 private void refreshFeatureDiscovery() {
2374 final var connection = conversation.getContact().getAccount().getXmppConnection();
2375 if (connection == null) return;
2376
2377 var jids = conversation.getContact().getPresences().getFullJids();
2378 if (jids.isEmpty()) {
2379 jids = new HashSet<>();
2380 jids.add(conversation.getContact().getJid());
2381 }
2382 for (final var jid : jids) {
2383 Futures.addCallback(
2384 connection.getManager(DiscoManager.class).info(Entity.presence(jid), null, null),
2385 new FutureCallback<>() {
2386 @Override
2387 public void onSuccess(InfoQuery disco) {
2388 if (activity == null) return;
2389 activity.runOnUiThread(() -> {
2390 refresh();
2391 refreshCommands(true);
2392 });
2393 }
2394
2395 @Override
2396 public void onFailure(@NonNull Throwable throwable) {}
2397 },
2398 MoreExecutors.directExecutor()
2399 );
2400 }
2401 }
2402
2403 private void addShortcut() {
2404 ShortcutInfoCompat info;
2405 if (conversation.getMode() == Conversation.MODE_MULTI) {
2406 info = activity.xmppConnectionService.getShortcutService().getShortcutInfo(conversation.getMucOptions());
2407 } else {
2408 info = activity.xmppConnectionService.getShortcutService().getShortcutInfo(conversation.getContact());
2409 }
2410 ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2411 }
2412
2413 private void togglePinned() {
2414 final boolean pinned =
2415 conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2416 conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2417 activity.xmppConnectionService.updateConversation(conversation);
2418 activity.invalidateOptionsMenu();
2419 }
2420
2421 private void checkPermissionAndTriggerAudioCall() {
2422 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2423 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2424 return;
2425 }
2426 final List<String> permissions;
2427 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2428 permissions =
2429 Arrays.asList(
2430 Manifest.permission.RECORD_AUDIO,
2431 Manifest.permission.BLUETOOTH_CONNECT);
2432 } else {
2433 permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2434 }
2435 if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2436 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2437 }
2438 }
2439
2440 private void checkPermissionAndTriggerVideoCall() {
2441 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2442 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2443 return;
2444 }
2445 final List<String> permissions;
2446 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2447 permissions =
2448 Arrays.asList(
2449 Manifest.permission.RECORD_AUDIO,
2450 Manifest.permission.CAMERA,
2451 Manifest.permission.BLUETOOTH_CONNECT);
2452 } else {
2453 permissions =
2454 Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2455 }
2456 if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2457 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2458 }
2459 }
2460
2461 private void triggerRtpSession(final String action) {
2462 if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
2463 Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2464 .show();
2465 return;
2466 }
2467 final Account account = conversation.getAccount();
2468 if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
2469 activity.xmppConnectionService.updateAccount(account);
2470 }
2471 final Contact contact = conversation.getContact();
2472 if (Config.USE_JINGLE_MESSAGE_INIT && RtpCapability.jmiSupport(contact)) {
2473 triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2474 } else {
2475 final RtpCapability.Capability capability;
2476 if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2477 capability = RtpCapability.Capability.VIDEO;
2478 } else {
2479 capability = RtpCapability.Capability.AUDIO;
2480 }
2481 PresenceSelector.selectFullJidForDirectRtpConnection(
2482 activity,
2483 contact,
2484 capability,
2485 fullJid -> {
2486 triggerRtpSession(contact.getAccount(), fullJid, action);
2487 });
2488 }
2489 }
2490
2491 private void triggerRtpSession(final Account account, final Jid with, final String action) {
2492 CallIntegrationConnectionService.placeCall(
2493 activity.xmppConnectionService,
2494 account,
2495 with,
2496 RtpSessionActivity.actionToMedia(action));
2497 }
2498
2499 private void handleAttachmentSelection(MenuItem item) {
2500 switch (item.getItemId()) {
2501 case R.id.attach_choose_picture:
2502 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2503 break;
2504 /*case R.id.attach_take_picture:
2505 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2506 break;
2507 case R.id.attach_record_video:
2508 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2509 break;*/
2510 case R.id.attach_choose_file:
2511 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2512 break;
2513 case R.id.attach_record_voice:
2514 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2515 break;
2516 case R.id.attach_location:
2517 attachFile(ATTACHMENT_CHOICE_LOCATION);
2518 break;
2519 }
2520 }
2521
2522 private void handleEncryptionSelection(MenuItem item) {
2523 if (conversation == null) {
2524 return;
2525 }
2526 final boolean updated;
2527 switch (item.getItemId()) {
2528 case R.id.encryption_choice_none:
2529 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2530 item.setChecked(true);
2531 break;
2532 case R.id.encryption_choice_pgp:
2533 if (activity.hasPgp()) {
2534 if (conversation.getAccount().getPgpSignature() != null) {
2535 updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2536 item.setChecked(true);
2537 } else {
2538 updated = false;
2539 activity.announcePgp(
2540 conversation.getAccount(),
2541 conversation,
2542 null,
2543 activity.onOpenPGPKeyPublished);
2544 }
2545 } else {
2546 activity.showInstallPgpDialog();
2547 updated = false;
2548 }
2549 break;
2550 case R.id.encryption_choice_axolotl:
2551 Log.d(
2552 Config.LOGTAG,
2553 AxolotlService.getLogprefix(conversation.getAccount())
2554 + "Enabled axolotl for Contact "
2555 + conversation.getContact().getJid());
2556 updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2557 item.setChecked(true);
2558 break;
2559 default:
2560 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2561 break;
2562 }
2563 if (updated) {
2564 activity.xmppConnectionService.updateConversation(conversation);
2565 }
2566 updateChatMsgHint();
2567 getActivity().invalidateOptionsMenu();
2568 activity.refreshUi();
2569 }
2570
2571 public void attachFile(final int attachmentChoice) {
2572 attachFile(attachmentChoice, true, false);
2573 }
2574
2575 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2576 attachFile(attachmentChoice, updateRecentlyUsed, false);
2577 }
2578
2579 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed, final boolean fromPermissions) {
2580 if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2581 if (!hasPermissions(
2582 attachmentChoice,
2583 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2584 Manifest.permission.RECORD_AUDIO)) {
2585 return;
2586 }
2587 } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2588 || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO
2589 || (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE && !fromPermissions)) {
2590 if (!hasPermissions(
2591 attachmentChoice,
2592 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2593 Manifest.permission.CAMERA)) {
2594 return;
2595 }
2596 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2597 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2598 return;
2599 }
2600 }
2601 if (updateRecentlyUsed) {
2602 storeRecentlyUsedQuickAction(attachmentChoice);
2603 }
2604 final int encryption = conversation.getNextEncryption();
2605 final int mode = conversation.getMode();
2606 if (encryption == Message.ENCRYPTION_PGP) {
2607 if (activity.hasPgp()) {
2608 if (mode == Conversation.MODE_SINGLE
2609 && conversation.getContact().getPgpKeyId() != 0) {
2610 activity.xmppConnectionService
2611 .getPgpEngine()
2612 .hasKey(
2613 conversation.getContact(),
2614 new UiCallback<Contact>() {
2615
2616 @Override
2617 public void userInputRequired(
2618 PendingIntent pi, Contact contact) {
2619 startPendingIntent(pi, attachmentChoice);
2620 }
2621
2622 @Override
2623 public void success(Contact contact) {
2624 invokeAttachFileIntent(attachmentChoice);
2625 }
2626
2627 @Override
2628 public void error(int error, Contact contact) {
2629 activity.replaceToast(getString(error));
2630 }
2631 });
2632 } else if (mode == Conversation.MODE_MULTI
2633 && conversation.getMucOptions().pgpKeysInUse()) {
2634 if (!conversation.getMucOptions().everybodyHasKeys()) {
2635 Toast warning =
2636 Toast.makeText(
2637 getActivity(),
2638 R.string.missing_public_keys,
2639 Toast.LENGTH_LONG);
2640 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2641 warning.show();
2642 }
2643 invokeAttachFileIntent(attachmentChoice);
2644 } else {
2645 showNoPGPKeyDialog(
2646 false,
2647 (dialog, which) -> {
2648 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2649 activity.xmppConnectionService.updateConversation(conversation);
2650 invokeAttachFileIntent(attachmentChoice);
2651 });
2652 }
2653 } else {
2654 activity.showInstallPgpDialog();
2655 }
2656 } else {
2657 invokeAttachFileIntent(attachmentChoice);
2658 }
2659 }
2660
2661 private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2662 try {
2663 activity.getPreferences()
2664 .edit()
2665 .putString(
2666 RECENTLY_USED_QUICK_ACTION,
2667 SendButtonAction.of(attachmentChoice).toString())
2668 .apply();
2669 } catch (IllegalArgumentException e) {
2670 // just do not save
2671 }
2672 }
2673
2674 @Override
2675 public void onRequestPermissionsResult(
2676 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2677 final PermissionUtils.PermissionResult permissionResult =
2678 PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2679 if (grantResults.length > 0) {
2680 if (allGranted(permissionResult.grantResults) || requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
2681 switch (requestCode) {
2682 case REQUEST_START_DOWNLOAD:
2683 if (this.mPendingDownloadableMessage != null) {
2684 startDownloadable(this.mPendingDownloadableMessage);
2685 }
2686 break;
2687 case REQUEST_ADD_EDITOR_CONTENT:
2688 if (this.mPendingEditorContent != null) {
2689 attachEditorContentToConversation(this.mPendingEditorContent);
2690 }
2691 break;
2692 case REQUEST_COMMIT_ATTACHMENTS:
2693 commitAttachments();
2694 break;
2695 case REQUEST_START_AUDIO_CALL:
2696 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2697 break;
2698 case REQUEST_START_VIDEO_CALL:
2699 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2700 break;
2701 default:
2702 attachFile(requestCode, true, true);
2703 break;
2704 }
2705 } else {
2706 @StringRes int res;
2707 String firstDenied =
2708 getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2709 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2710 res = R.string.no_microphone_permission;
2711 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2712 res = R.string.no_camera_permission;
2713 } else {
2714 res = R.string.no_storage_permission;
2715 }
2716 Toast.makeText(
2717 getActivity(),
2718 getString(res, getString(R.string.app_name)),
2719 Toast.LENGTH_SHORT)
2720 .show();
2721 }
2722 }
2723 if (writeGranted(grantResults, permissions)) {
2724 if (activity != null && activity.xmppConnectionService != null) {
2725 activity.xmppConnectionService.getDrawableCache().evictAll();
2726 activity.xmppConnectionService.restartFileObserver();
2727 }
2728 refresh();
2729 }
2730 if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
2731 XmppConnectionService.toggleForegroundService(activity);
2732 }
2733 }
2734
2735 public void startDownloadable(Message message) {
2736 if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2737 this.mPendingDownloadableMessage = message;
2738 return;
2739 }
2740 Transferable transferable = message.getTransferable();
2741 if (transferable != null) {
2742 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2743 createNewConnection(message);
2744 return;
2745 }
2746 if (!transferable.start()) {
2747 Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2748 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2749 .show();
2750 }
2751 } else if (message.treatAsDownloadable()
2752 || message.hasFileOnRemoteHost()
2753 || MessageUtils.unInitiatedButKnownSize(message)) {
2754 createNewConnection(message);
2755 } else {
2756 Log.d(
2757 Config.LOGTAG,
2758 message.getConversation().getAccount() + ": unable to start downloadable");
2759 }
2760 }
2761
2762 private void createNewConnection(final Message message) {
2763 if (!activity.xmppConnectionService.hasInternetConnection()) {
2764 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2765 .show();
2766 return;
2767 }
2768 if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2769 try {
2770 BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2771 message.setTransferable(transfer);
2772 transfer.start();
2773 } catch (URISyntaxException e) {
2774 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2775 }
2776 } else {
2777 activity.xmppConnectionService
2778 .getHttpConnectionManager()
2779 .createNewDownloadConnection(message, true);
2780 }
2781 }
2782
2783 @SuppressLint("InflateParams")
2784 protected void clearHistoryDialog(final Conversation conversation) {
2785 final MaterialAlertDialogBuilder builder =
2786 new MaterialAlertDialogBuilder(requireActivity());
2787 builder.setTitle(R.string.clear_conversation_history);
2788 final View dialogView =
2789 requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2790 final CheckBox endConversationCheckBox =
2791 dialogView.findViewById(R.id.end_conversation_checkbox);
2792 builder.setView(dialogView);
2793 builder.setNegativeButton(getString(R.string.cancel), null);
2794 builder.setPositiveButton(
2795 getString(R.string.confirm),
2796 (dialog, which) -> {
2797 this.activity.xmppConnectionService.clearConversationHistory(conversation);
2798 if (endConversationCheckBox.isChecked()) {
2799 this.activity.xmppConnectionService.archiveConversation(conversation);
2800 this.activity.onConversationArchived(conversation);
2801 } else {
2802 activity.onConversationsListItemUpdated();
2803 refresh();
2804 }
2805 });
2806 builder.create().show();
2807 }
2808
2809 protected void muteConversationDialog(final Conversation conversation) {
2810 final MaterialAlertDialogBuilder builder =
2811 new MaterialAlertDialogBuilder(requireActivity());
2812 builder.setTitle(R.string.disable_notifications);
2813 final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2814 final CharSequence[] labels = new CharSequence[durations.length];
2815 for (int i = 0; i < durations.length; ++i) {
2816 if (durations[i] == -1) {
2817 labels[i] = activity.getString(R.string.until_further_notice);
2818 } else {
2819 labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2820 }
2821 }
2822 builder.setItems(
2823 labels,
2824 (dialog, which) -> {
2825 final long till;
2826 if (durations[which] == -1) {
2827 till = Long.MAX_VALUE;
2828 } else {
2829 till = System.currentTimeMillis() + (durations[which] * 1000L);
2830 }
2831 conversation.setMutedTill(till);
2832 activity.xmppConnectionService.updateConversation(conversation);
2833 activity.onConversationsListItemUpdated();
2834 refresh();
2835 activity.invalidateOptionsMenu();
2836 });
2837 builder.create().show();
2838 }
2839
2840 private boolean hasPermissions(int requestCode, List<String> permissions) {
2841 final List<String> missingPermissions = new ArrayList<>();
2842 for (String permission : permissions) {
2843 if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
2844 || Config.ONLY_INTERNAL_STORAGE)
2845 && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2846 continue;
2847 }
2848 if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2849 missingPermissions.add(permission);
2850 }
2851 }
2852 if (missingPermissions.size() == 0) {
2853 return true;
2854 } else {
2855 requestPermissions(missingPermissions.toArray(new String[0]), requestCode);
2856 return false;
2857 }
2858 }
2859
2860 private boolean hasPermissions(int requestCode, String... permissions) {
2861 return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2862 }
2863
2864 public void unMuteConversation(final Conversation conversation) {
2865 conversation.setMutedTill(0);
2866 this.activity.xmppConnectionService.updateConversation(conversation);
2867 this.activity.onConversationsListItemUpdated();
2868 refresh();
2869 this.activity.invalidateOptionsMenu();
2870 }
2871
2872 protected void invokeAttachFileIntent(final int attachmentChoice) {
2873 Intent intent = new Intent();
2874
2875 final var takePhotoIntent = new Intent();
2876 final Uri takePhotoUri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2877 pendingTakePhotoUri.push(takePhotoUri);
2878 takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePhotoUri);
2879 takePhotoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2880 takePhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2881 takePhotoIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2882
2883 final var takeVideoIntent = new Intent();
2884 takeVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2885
2886 switch (attachmentChoice) {
2887 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2888 intent.setAction(Intent.ACTION_GET_CONTENT);
2889 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2890 intent.setType("*/*");
2891 intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"});
2892 intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
2893 if (activity.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
2894 intent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent, takeVideoIntent });
2895 }
2896 break;
2897 case ATTACHMENT_CHOICE_RECORD_VIDEO:
2898 intent = takeVideoIntent;
2899 break;
2900 case ATTACHMENT_CHOICE_TAKE_PHOTO:
2901 intent = takePhotoIntent;
2902 break;
2903 case ATTACHMENT_CHOICE_CHOOSE_FILE:
2904 intent.setAction(Intent.ACTION_GET_CONTENT);
2905 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2906 intent.setType("*/*");
2907 intent.addCategory(Intent.CATEGORY_OPENABLE);
2908 intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
2909 break;
2910 case ATTACHMENT_CHOICE_RECORD_VOICE:
2911 intent = new Intent(getActivity(), RecordingActivity.class);
2912 break;
2913 case ATTACHMENT_CHOICE_LOCATION:
2914 intent = GeoHelper.getFetchIntent(activity);
2915 break;
2916 }
2917 final Context context = getActivity();
2918 if (context == null) {
2919 return;
2920 }
2921 try {
2922 startActivityForResult(intent, attachmentChoice);
2923 } catch (final ActivityNotFoundException e) {
2924 Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2925 }
2926 }
2927
2928 @Override
2929 public void onResume() {
2930 super.onResume();
2931 binding.messagesView.post(this::fireReadEvent);
2932 }
2933
2934 private void fireReadEvent() {
2935 if (activity != null && this.conversation != null) {
2936 String uuid = getLastVisibleMessageUuid();
2937 if (uuid != null) {
2938 activity.onConversationRead(this.conversation, uuid);
2939 }
2940 }
2941 }
2942
2943 private void newSubThread() {
2944 Element oldThread = conversation.getThread();
2945 Element thread = new Element("thread", "jabber:client");
2946 thread.setContent(UUID.randomUUID().toString());
2947 if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2948 setThread(thread);
2949 }
2950
2951 private void newThread() {
2952 Element thread = new Element("thread", "jabber:client");
2953 thread.setContent(UUID.randomUUID().toString());
2954 setThread(thread);
2955 }
2956
2957 private void updateThreadFromLastMessage() {
2958 if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2959 Message message = getLastVisibleMessage();
2960 if (message == null) {
2961 newThread();
2962 } else {
2963 if (conversation.getMode() == Conversation.MODE_MULTI) {
2964 if (activity == null || activity.xmppConnectionService == null) return;
2965 if (message.getStatus() < Message.STATUS_SEND) {
2966 if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
2967 }
2968 }
2969
2970 setThread(message.getThread());
2971 }
2972 }
2973 }
2974
2975 private String getLastVisibleMessageUuid() {
2976 Message message = getLastVisibleMessage();
2977 return message == null ? null : message.getUuid();
2978 }
2979
2980 private Message getLastVisibleMessage() {
2981 if (binding == null) {
2982 return null;
2983 }
2984 synchronized (this.messageList) {
2985 int pos = binding.messagesView.getLastVisiblePosition();
2986 if (pos >= 0) {
2987 Message message = null;
2988 for (int i = pos; i >= 0; --i) {
2989 try {
2990 message = (Message) binding.messagesView.getItemAtPosition(i);
2991 } catch (IndexOutOfBoundsException e) {
2992 // should not happen if we synchronize properly. however if that fails we
2993 // just gonna try item -1
2994 continue;
2995 }
2996 if (message.getType() != Message.TYPE_STATUS) {
2997 break;
2998 }
2999 }
3000 if (message != null) {
3001 return message;
3002 }
3003 }
3004 }
3005 return null;
3006 }
3007
3008 public void jumpTo(final Message message) {
3009 if (message.getUuid() == null) return;
3010 for (int i = 0; i < messageList.size(); i++) {
3011 final var m = messageList.get(i);
3012 if (m == null) continue;
3013 if (message.getUuid().equals(m.getUuid())) {
3014 binding.messagesView.setSelection(i);
3015 return;
3016 }
3017 }
3018 }
3019
3020 private void openWith(final Message message) {
3021 if (message.isGeoUri()) {
3022 GeoHelper.view(getActivity(), message);
3023 } else {
3024 final DownloadableFile file =
3025 activity.xmppConnectionService.getFileBackend().getFile(message);
3026 final var fp = message.getFileParams();
3027 final var name = fp == null ? null : fp.getName();
3028 final var displayName = name == null ? file.getName() : name;
3029 ViewUtil.view(activity, file, displayName);
3030 }
3031 }
3032
3033 public void addReaction(final Message message) {
3034 activity.addReaction(emoji -> {
3035 setupReply(message);
3036 binding.textinput.setText(emoji.toInsert());
3037 sendMessage();
3038 });
3039 }
3040
3041 private void reportMessage(final Message message) {
3042 BlockContactDialog.show(activity, conversation.getContact(), message.getServerMsgId());
3043 }
3044
3045 private void showErrorMessage(final Message message) {
3046 final MaterialAlertDialogBuilder builder =
3047 new MaterialAlertDialogBuilder(requireActivity());
3048 builder.setTitle(R.string.error_message);
3049 final String errorMessage = message.getErrorMessage();
3050 final String[] errorMessageParts =
3051 errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
3052 final String displayError;
3053 if (errorMessageParts.length == 2) {
3054 displayError = errorMessageParts[1];
3055 } else {
3056 displayError = errorMessage;
3057 }
3058 builder.setMessage(displayError);
3059 builder.setNegativeButton(
3060 R.string.copy_to_clipboard,
3061 (dialog, which) -> {
3062 if (activity.copyTextToClipboard(displayError, R.string.error_message)
3063 && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
3064 Toast.makeText(
3065 activity,
3066 R.string.error_message_copied_to_clipboard,
3067 Toast.LENGTH_SHORT)
3068 .show();
3069 }
3070 });
3071 builder.setPositiveButton(R.string.confirm, null);
3072 builder.create().show();
3073 }
3074
3075 public boolean onInlineImageLongClicked(Cid cid) {
3076 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3077 if (f == null) return false;
3078
3079 saveAsSticker(f, null);
3080 return true;
3081 }
3082
3083 private void saveAsSticker(final Message m) {
3084 String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
3085 existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
3086 saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
3087 }
3088
3089 private void saveAsSticker(final File file, final String name) {
3090 savingAsSticker = file;
3091
3092 Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
3093 intent.addCategory(Intent.CATEGORY_OPENABLE);
3094 intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file, file.getName())));
3095 intent.putExtra(Intent.EXTRA_TITLE, name);
3096
3097 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3098 final String dir = p.getString("sticker_directory", "Stickers");
3099 if (dir.startsWith("content://")) {
3100 intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
3101 } else {
3102 new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
3103 Uri uri;
3104 if (Build.VERSION.SDK_INT >= 29) {
3105 Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
3106 uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
3107 uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
3108 } else {
3109 uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
3110 }
3111 intent.putExtra("android.provider.extra.INITIAL_URI", uri);
3112 intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
3113 }
3114
3115 Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
3116 startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
3117 }
3118
3119 private void deleteFile(final Message message) {
3120 final MaterialAlertDialogBuilder builder =
3121 new MaterialAlertDialogBuilder(requireActivity());
3122 builder.setNegativeButton(R.string.cancel, null);
3123 builder.setTitle(R.string.delete_file_dialog);
3124 builder.setMessage(R.string.delete_file_dialog_msg);
3125 builder.setPositiveButton(
3126 R.string.confirm,
3127 (dialog, which) -> {
3128 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
3129 if (thumbs != null && !thumbs.isEmpty()) {
3130 for (Element thumb : thumbs) {
3131 Uri uri = Uri.parse(thumb.getAttribute("uri"));
3132 if (uri.getScheme().equals("cid")) {
3133 Cid cid = BobTransfer.cid(uri);
3134 if (cid == null) continue;
3135 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3136 activity.xmppConnectionService.evictPreview(f);
3137 f.delete();
3138 }
3139 }
3140 }
3141 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
3142 activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
3143 activity.xmppConnectionService.updateMessage(message, false);
3144 activity.onConversationsListItemUpdated();
3145 refresh();
3146 }
3147 });
3148 builder.create().show();
3149 }
3150
3151 private void resendMessage(final Message message, final boolean forceP2P) {
3152 if (message.isFileOrImage()) {
3153 if (!(message.getConversation() instanceof Conversation conversation)) {
3154 return;
3155 }
3156 final DownloadableFile file =
3157 activity.xmppConnectionService.getFileBackend().getFile(message);
3158 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
3159 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
3160 if (!message.hasFileOnRemoteHost()
3161 && xmppConnection != null
3162 && conversation.getMode() == Conversational.MODE_SINGLE
3163 && (!xmppConnection
3164 .getManager(HttpUploadManager.class)
3165 .isAvailableForSize(message.getFileParams().getSize())
3166 || forceP2P)) {
3167 activity.selectPresence(
3168 conversation,
3169 () -> {
3170 message.setCounterpart(conversation.getNextCounterpart());
3171 activity.xmppConnectionService.resendFailedMessages(
3172 message, forceP2P);
3173 new Handler()
3174 .post(
3175 () -> {
3176 int size = messageList.size();
3177 this.binding.messagesView.setSelection(
3178 size - 1);
3179 });
3180 });
3181 return;
3182 }
3183 } else if (!Compatibility.hasStoragePermission(getActivity())) {
3184 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
3185 return;
3186 } else {
3187 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
3188 message.setDeleted(true);
3189 activity.xmppConnectionService.updateMessage(message, false);
3190 activity.onConversationsListItemUpdated();
3191 refresh();
3192 return;
3193 }
3194 }
3195 activity.xmppConnectionService.resendFailedMessages(message, false);
3196 new Handler()
3197 .post(
3198 () -> {
3199 int size = messageList.size();
3200 this.binding.messagesView.setSelection(size - 1);
3201 });
3202 }
3203
3204 private void cancelTransmission(Message message) {
3205 Transferable transferable = message.getTransferable();
3206 if (transferable != null) {
3207 transferable.cancel();
3208 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
3209 activity.xmppConnectionService.markMessage(
3210 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
3211 }
3212 }
3213
3214 private void retryDecryption(Message message) {
3215 message.setEncryption(Message.ENCRYPTION_PGP);
3216 activity.onConversationsListItemUpdated();
3217 refresh();
3218 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
3219 }
3220
3221 public void privateMessageWith(final Jid counterpart) {
3222 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3223 activity.xmppConnectionService.sendChatState(conversation);
3224 }
3225 this.binding.textinput.setText("");
3226 this.conversation.setNextCounterpart(counterpart);
3227 updateChatMsgHint();
3228 updateSendButton();
3229 updateEditablity();
3230 }
3231
3232 private void correctMessage(final Message message) {
3233 setThread(message.getThread());
3234 conversation.setUserSelectedThread(true);
3235 this.conversation.setCorrectingMessage(message);
3236 final Editable editable = binding.textinput.getText();
3237 this.conversation.setDraftMessage(editable.toString());
3238 this.binding.textinput.setText("");
3239 this.binding.textinput.append(message.getBody(true));
3240 if (message.getSubject() != null && message.getSubject().length() > 0) {
3241 this.binding.textinputSubject.setText(message.getSubject());
3242 this.binding.textinputSubject.setVisibility(View.VISIBLE);
3243 }
3244 setupReply(message.getInReplyTo());
3245 }
3246
3247 private void highlightInConference(String nick) {
3248 final Editable editable = this.binding.textinput.getText();
3249 String oldString = editable.toString().trim();
3250 final int pos = this.binding.textinput.getSelectionStart();
3251 if (oldString.isEmpty() || pos == 0) {
3252 editable.insert(0, nick + ": ");
3253 } else {
3254 final char before = editable.charAt(pos - 1);
3255 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
3256 if (before == '\n') {
3257 editable.insert(pos, nick + ": ");
3258 } else {
3259 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
3260 if (NickValidityChecker.check(
3261 conversation,
3262 Arrays.asList(
3263 editable.subSequence(0, pos - 2).toString().split(", ")))) {
3264 editable.insert(pos - 2, ", " + nick);
3265 return;
3266 }
3267 }
3268 editable.insert(
3269 pos,
3270 (Character.isWhitespace(before) ? "" : " ")
3271 + nick
3272 + (Character.isWhitespace(after) ? "" : " "));
3273 if (Character.isWhitespace(after)) {
3274 this.binding.textinput.setSelection(
3275 this.binding.textinput.getSelectionStart() + 1);
3276 }
3277 }
3278 }
3279 }
3280
3281 @Override
3282 public void startActivityForResult(Intent intent, int requestCode) {
3283 final Activity activity = getActivity();
3284 if (activity instanceof ConversationsActivity) {
3285 ((ConversationsActivity) activity).clearPendingViewIntent();
3286 }
3287 super.startActivityForResult(intent, requestCode);
3288 }
3289
3290 @Override
3291 public void onSaveInstanceState(@NonNull Bundle outState) {
3292 super.onSaveInstanceState(outState);
3293 if (conversation != null) {
3294 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
3295 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
3296 final Uri uri = pendingTakePhotoUri.peek();
3297 if (uri != null) {
3298 outState.putString(STATE_PHOTO_URI, uri.toString());
3299 }
3300 final ScrollState scrollState = getScrollPosition();
3301 if (scrollState != null) {
3302 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
3303 }
3304 final ArrayList<Attachment> attachments =
3305 mediaPreviewAdapter == null
3306 ? new ArrayList<>()
3307 : mediaPreviewAdapter.getAttachments();
3308 if (attachments.size() > 0) {
3309 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
3310 }
3311 }
3312 }
3313
3314 @Override
3315 public void onActivityCreated(Bundle savedInstanceState) {
3316 super.onActivityCreated(savedInstanceState);
3317 if (savedInstanceState == null) {
3318 return;
3319 }
3320 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
3321 ArrayList<Attachment> attachments =
3322 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
3323 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
3324 if (uuid != null) {
3325 QuickLoader.set(uuid);
3326 this.pendingConversationsUuid.push(uuid);
3327 if (attachments != null && attachments.size() > 0) {
3328 this.pendingMediaPreviews.push(attachments);
3329 }
3330 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
3331 if (takePhotoUri != null) {
3332 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
3333 }
3334 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
3335 }
3336 }
3337
3338 @Override
3339 public void onStart() {
3340 super.onStart();
3341 if (this.reInitRequiredOnStart && this.conversation != null) {
3342 final Bundle extras = pendingExtras.pop();
3343 reInit(this.conversation, extras != null);
3344 if (extras != null) {
3345 processExtras(extras);
3346 }
3347 } else if (conversation == null
3348 && activity != null
3349 && activity.xmppConnectionService != null) {
3350 final String uuid = pendingConversationsUuid.pop();
3351 Log.d(
3352 Config.LOGTAG,
3353 "ConversationFragment.onStart() - activity was bound but no conversation"
3354 + " loaded. uuid="
3355 + uuid);
3356 if (uuid != null) {
3357 findAndReInitByUuidOrArchive(uuid);
3358 }
3359 }
3360 }
3361
3362 @Override
3363 public void onStop() {
3364 super.onStop();
3365 final Activity activity = getActivity();
3366 messageListAdapter.unregisterListenerInAudioPlayer();
3367 if (activity == null || !activity.isChangingConfigurations()) {
3368 hideSoftKeyboard(activity);
3369 messageListAdapter.stopAudioPlayer();
3370 }
3371 if (this.conversation != null) {
3372 final String msg = this.binding.textinput.getText().toString();
3373 storeNextMessage(msg);
3374 updateChatState(this.conversation, msg);
3375 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
3376 }
3377 this.reInitRequiredOnStart = true;
3378 }
3379
3380 private void updateChatState(final Conversation conversation, final String msg) {
3381 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
3382 Account.State status = conversation.getAccount().getStatus();
3383 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
3384 activity.xmppConnectionService.sendChatState(conversation);
3385 }
3386 }
3387
3388 private void saveMessageDraftStopAudioPlayer() {
3389 final Conversation previousConversation = this.conversation;
3390 if (this.activity == null || this.binding == null || previousConversation == null) {
3391 return;
3392 }
3393 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
3394 final String msg = this.binding.textinput.getText().toString();
3395 storeNextMessage(msg);
3396 updateChatState(this.conversation, msg);
3397 messageListAdapter.stopAudioPlayer();
3398 mediaPreviewAdapter.clearPreviews();
3399 toggleInputMethod();
3400 }
3401
3402 public void reInit(final Conversation conversation, final Bundle extras) {
3403 QuickLoader.set(conversation.getUuid());
3404 final boolean changedConversation = this.conversation != conversation;
3405 if (changedConversation) {
3406 this.saveMessageDraftStopAudioPlayer();
3407 }
3408 this.clearPending();
3409 if (this.reInit(conversation, extras != null)) {
3410 if (extras != null) {
3411 processExtras(extras);
3412 }
3413 this.reInitRequiredOnStart = false;
3414 } else {
3415 this.reInitRequiredOnStart = true;
3416 pendingExtras.push(extras);
3417 }
3418 resetUnreadMessagesCount();
3419 }
3420
3421 private void reInit(Conversation conversation) {
3422 reInit(conversation, false);
3423 }
3424
3425 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
3426 if (conversation == null) {
3427 return false;
3428 }
3429 final Conversation originalConversation = this.conversation;
3430 this.conversation = conversation;
3431 // once we set the conversation all is good and it will automatically do the right thing in
3432 // onStart()
3433 if (this.activity == null || this.binding == null) {
3434 return false;
3435 }
3436
3437 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3438 activity.onConversationArchived(this.conversation);
3439 return false;
3440 }
3441
3442 final var cursord = activity.getDrawable(R.drawable.cursor_on_tertiary_container);
3443 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getAccounts().size() > 1) {
3444 final var bg = MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorSurface);
3445 final var accountColor = conversation.getAccount().getColor(activity.isDark());
3446 final var colors = MaterialColors.getColorRoles(activity, accountColor);
3447 final var accent = activity.isDark() ? ColorUtils.blendARGB(colors.getAccentContainer(), bg, 1.0f - Math.max(0.25f, Color.alpha(accountColor) / 255.0f)) : colors.getAccentContainer();
3448 cursord.setTintList(ColorStateList.valueOf(colors.getOnAccentContainer()));
3449 binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(accent));
3450 binding.textinputSubject.setTextColor(colors.getOnAccentContainer());
3451 binding.textinput.setTextColor(colors.getOnAccentContainer());
3452 binding.textinputSubject.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3453 binding.textinput.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3454 binding.textInputHint.setTextColor(colors.getOnAccentContainer());
3455 } else {
3456 cursord.setTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer)));
3457 binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.inputLayout, com.google.android.material.R.attr.colorTertiaryContainer)));
3458 binding.textinputSubject.setTextColor(MaterialColors.getColor(binding.textinputSubject, com.google.android.material.R.attr.colorOnTertiaryContainer));
3459 binding.textinput.setTextColor(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer));
3460 binding.textinputSubject.setHintTextColor(R.color.hint_on_tertiary_container);
3461 binding.textinput.setHintTextColor(R.color.hint_on_tertiary_container);
3462 binding.textInputHint.setTextColor(MaterialColors.getColor(binding.textInputHint, com.google.android.material.R.attr.colorOnTertiaryContainer));
3463 }
3464 if (Build.VERSION.SDK_INT >= 29) {
3465 binding.textinputSubject.setTextCursorDrawable(cursord);
3466 binding.textinput.setTextCursorDrawable(cursord);
3467 }
3468
3469 setThread(conversation.getThread());
3470 setupReply(conversation.getReplyTo());
3471
3472 stopScrolling();
3473 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3474
3475 if (this.conversation.isRead(activity == null ? null : activity.xmppConnectionService) && hasExtras) {
3476 Log.d(Config.LOGTAG, "trimming conversation");
3477 this.conversation.trim();
3478 }
3479
3480 setupIme();
3481
3482 final boolean scrolledToBottomAndNoPending =
3483 this.scrolledToBottom() && pendingScrollState.peek() == null;
3484
3485 this.binding.textSendButton.setContentDescription(
3486 activity.getString(R.string.send_message_to_x, conversation.getName()));
3487 this.binding.textinput.setKeyboardListener(null);
3488 this.binding.textinputSubject.setKeyboardListener(null);
3489 final boolean participating =
3490 conversation.getMode() == Conversational.MODE_SINGLE
3491 || conversation.getMucOptions().participating();
3492 if (participating) {
3493 this.binding.textinput.setText(this.conversation.getNextMessage());
3494 this.binding.textinput.setSelection(this.binding.textinput.length());
3495 } else {
3496 this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3497 }
3498 this.binding.textinput.setKeyboardListener(this);
3499 this.binding.textinputSubject.setKeyboardListener(this);
3500 messageListAdapter.updatePreferences();
3501 refresh(false);
3502 activity.invalidateOptionsMenu();
3503 this.conversation.messagesLoaded.set(true);
3504 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3505
3506 if (hasExtras || scrolledToBottomAndNoPending) {
3507 resetUnreadMessagesCount();
3508 synchronized (this.messageList) {
3509 Log.d(Config.LOGTAG, "jump to first unread message");
3510 final Message first = conversation.getFirstUnreadMessage();
3511 final int bottom = Math.max(0, this.messageList.size() - 1);
3512 final int pos;
3513 final boolean jumpToBottom;
3514 if (first == null) {
3515 pos = bottom;
3516 jumpToBottom = true;
3517 } else {
3518 int i = getIndexOf(first.getUuid(), this.messageList);
3519 pos = i < 0 ? bottom : i;
3520 jumpToBottom = false;
3521 }
3522 setSelection(pos, jumpToBottom);
3523 }
3524 }
3525
3526 this.binding.messagesView.post(this::fireReadEvent);
3527 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3528 // layout which might be unnecessary since we can *see* it
3529 activity.xmppConnectionService
3530 .getNotificationService()
3531 .setOpenConversation(this.conversation);
3532
3533 if (commandAdapter != null && conversation != originalConversation) {
3534 commandAdapter.clear();
3535 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3536 refreshCommands(false);
3537 }
3538 if (commandAdapter == null && conversation != null) {
3539 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3540 commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3541 binding.commandsView.setAdapter(commandAdapter);
3542 binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3543 if (activity == null) return;
3544
3545 commandAdapter.getItem(position).start(activity, ConversationFragment.this.conversation);
3546 });
3547 refreshCommands(false);
3548 }
3549
3550 binding.commandsNote.setVisibility(activity.xmppConnectionService.isOnboarding() ? View.VISIBLE : View.GONE);
3551
3552 return true;
3553 }
3554
3555 @Override
3556 public void refreshForNewCaps(final Set<Jid> newCapsJids) {
3557 if (newCapsJids.isEmpty() || (conversation != null && newCapsJids.contains(conversation.getJid().asBareJid()))) {
3558 refreshCommands(true);
3559 }
3560 }
3561
3562 protected void refreshCommands(boolean delayShow) {
3563 if (commandAdapter == null) return;
3564
3565 final CommandAdapter.MucConfig mucConfig =
3566 conversation.getMucOptions().getSelf().ranks(Affiliation.OWNER) ?
3567 new CommandAdapter.MucConfig() :
3568 null;
3569
3570 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3571 if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3572 commandJid = conversation.getJid().asBareJid();
3573 }
3574 if (commandJid == null && conversation.getJid().isDomainJid()) {
3575 commandJid = conversation.getJid();
3576 }
3577 if (commandJid == null) {
3578 binding.commandsViewProgressbar.setVisibility(View.GONE);
3579 if (mucConfig == null) {
3580 conversation.hideViewPager();
3581 } else {
3582 commandAdapter.clear();
3583 commandAdapter.add(mucConfig);
3584 conversation.showViewPager();
3585 }
3586 } else {
3587 if (!delayShow) conversation.showViewPager();
3588 binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3589 final var discoManager = conversation.getAccount().getXmppConnection().getManager(DiscoManager.class);
3590 final var future = discoManager.items(Entity.discoItem(commandJid), Namespace.COMMANDS);
3591 Futures.addCallback(
3592 future,
3593 new FutureCallback<>() {
3594 @Override
3595 public void onSuccess(Collection<Item> result) {
3596 if (activity == null) return;
3597
3598 activity.runOnUiThread(() -> {
3599 binding.commandsViewProgressbar.setVisibility(View.GONE);
3600 commandAdapter.clear();
3601 for (final var command : result) {
3602 commandAdapter.add(new CommandAdapter.Command0050(command));
3603 }
3604
3605 if (mucConfig != null) commandAdapter.add(mucConfig);
3606
3607 if (commandAdapter.getCount() < 1) {
3608 conversation.hideViewPager();
3609 } else if (delayShow) {
3610 conversation.showViewPager();
3611 }
3612 });
3613
3614 }
3615
3616 @Override
3617 public void onFailure(@NonNull Throwable throwable) {
3618 Log.d(Config.LOGTAG, "Failed to get commands: " + throwable);
3619
3620 if (activity == null) return;
3621
3622 activity.runOnUiThread(() -> {
3623 binding.commandsViewProgressbar.setVisibility(View.GONE);
3624 commandAdapter.clear();
3625
3626 if (mucConfig != null) commandAdapter.add(mucConfig);
3627
3628 if (commandAdapter.getCount() < 1) {
3629 conversation.hideViewPager();
3630 } else if (delayShow) {
3631 conversation.showViewPager();
3632 }
3633 });
3634 }
3635 },
3636 MoreExecutors.directExecutor()
3637 );
3638 }
3639 }
3640
3641 private void resetUnreadMessagesCount() {
3642 lastMessageUuid = null;
3643 hideUnreadMessagesCount();
3644 }
3645
3646 private void hideUnreadMessagesCount() {
3647 if (this.binding == null) {
3648 return;
3649 }
3650 this.binding.scrollToBottomButton.setEnabled(false);
3651 this.binding.scrollToBottomButton.hide();
3652 this.binding.unreadCountCustomView.setVisibility(View.GONE);
3653 }
3654
3655 private void setSelection(int pos, boolean jumpToBottom) {
3656 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3657 this.binding.messagesView.post(
3658 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3659 this.binding.messagesView.post(this::fireReadEvent);
3660 }
3661
3662 private boolean scrolledToBottom() {
3663 return this.binding != null && scrolledToBottom(this.binding.messagesView);
3664 }
3665
3666 private void processExtras(final Bundle extras) {
3667 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3668 final String text = extras.getString(Intent.EXTRA_TEXT);
3669 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3670 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3671 final String postInitAction =
3672 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3673 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3674 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3675 final boolean doNotAppend =
3676 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3677 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3678
3679 final String thread = extras.getString(ConversationsActivity.EXTRA_THREAD);
3680 if (thread != null) {
3681 conversation.setLockThread(true);
3682 backPressedLeaveSingleThread.setEnabled(true);
3683 setThread(new Element("thread").setContent(thread));
3684 refresh();
3685 }
3686
3687 final List<Uri> uris = extractUris(extras);
3688 if (uris != null && uris.size() > 0) {
3689 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3690 mediaPreviewAdapter.addMediaPreviews(
3691 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3692 } else {
3693 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3694 mediaPreviewAdapter.addMediaPreviews(
3695 Attachment.of(getActivity(), cleanedUris, type));
3696 }
3697 toggleInputMethod();
3698 return;
3699 }
3700 if (nick != null) {
3701 if (pm) {
3702 Jid jid = conversation.getJid();
3703 try {
3704 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3705 privateMessageWith(next);
3706 } catch (final IllegalArgumentException ignored) {
3707 // do nothing
3708 }
3709 } else {
3710 final MucOptions mucOptions = conversation.getMucOptions();
3711 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3712 highlightInConference(nick);
3713 }
3714 }
3715 } else {
3716 if (text != null && Patterns.URI_GEO.matcher(text).matches()) {
3717 mediaPreviewAdapter.addMediaPreviews(
3718 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3719 toggleInputMethod();
3720 return;
3721 } else if (text != null && asQuote) {
3722 quoteText(text);
3723 } else {
3724 appendText(text, doNotAppend);
3725 }
3726 }
3727 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3728 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3729 return;
3730 }
3731 if ("call".equals(postInitAction)) {
3732 checkPermissionAndTriggerAudioCall();
3733 }
3734 if ("message".equals(postInitAction)) {
3735 binding.conversationViewPager.post(() -> {
3736 binding.conversationViewPager.setCurrentItem(0);
3737 });
3738 }
3739 if ("command".equals(postInitAction)) {
3740 binding.conversationViewPager.post(() -> {
3741 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3742 if (adapter != null && adapter.getCount() > 1) {
3743 binding.conversationViewPager.setCurrentItem(1);
3744 }
3745 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3746 Jid commandJid = null;
3747 if (jid != null) {
3748 try {
3749 commandJid = Jid.of(jid);
3750 } catch (final IllegalArgumentException e) { }
3751 }
3752 if (commandJid == null || !commandJid.isFullJid()) {
3753 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3754 if (discoJid != null) commandJid = discoJid;
3755 }
3756 if (node != null && commandJid != null && activity != null) {
3757 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3758 }
3759 });
3760 return;
3761 }
3762 Message message =
3763 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3764 if ("webxdc".equals(postInitAction)) {
3765 if (message == null) {
3766 message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3767 }
3768 if (message == null) return;
3769
3770 Cid webxdcCid = message.getFileParams().getCids().get(0);
3771 WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message);
3772 Conversation conversation = (Conversation) message.getConversation();
3773 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3774 conversation.startWebxdc(webxdc);
3775 }
3776 }
3777 if (message != null) {
3778 startDownloadable(message);
3779 }
3780 if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3781 if (!conversation.switchToSession("jabber:iq:register")) {
3782 conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3783 }
3784 }
3785 }
3786
3787 private Element commandFor(final Jid jid, final String node) {
3788 if (commandAdapter != null) {
3789 for (int i = 0; i < commandAdapter.getCount(); i++) {
3790 final CommandAdapter.Command c = commandAdapter.getItem(i);
3791 if (!(c instanceof CommandAdapter.Command0050)) continue;
3792
3793 final Element command = ((CommandAdapter.Command0050) c).el;
3794 final String commandNode = command.getAttribute("node");
3795 if (commandNode == null || !commandNode.equals(node)) continue;
3796
3797 final Jid commandJid = command.getAttributeAsJid("jid");
3798 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3799
3800 return command;
3801 }
3802 }
3803
3804 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3805 }
3806
3807 private List<Uri> extractUris(final Bundle extras) {
3808 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3809 if (uris != null) {
3810 return uris;
3811 }
3812 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3813 if (uri != null) {
3814 return Collections.singletonList(uri);
3815 } else {
3816 return null;
3817 }
3818 }
3819
3820 private List<Uri> cleanUris(final List<Uri> uris) {
3821 final Iterator<Uri> iterator = uris.iterator();
3822 while (iterator.hasNext()) {
3823 final Uri uri = iterator.next();
3824 if (FileBackend.dangerousFile(uri)) {
3825 iterator.remove();
3826 Toast.makeText(
3827 requireActivity(),
3828 R.string.security_violation_not_attaching_file,
3829 Toast.LENGTH_SHORT)
3830 .show();
3831 }
3832 }
3833 return uris;
3834 }
3835
3836 private boolean showBlockSubmenu(View view) {
3837 final Jid jid = conversation.getJid();
3838 final int mode = conversation.getMode();
3839 final var contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3840 final boolean showReject = contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3841 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3842 popupMenu.inflate(R.menu.block);
3843 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3844 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3845 popupMenu.getMenu().findItem(R.id.add_contact).setVisible(!contact.showInRoster());
3846 popupMenu.setOnMenuItemClickListener(
3847 menuItem -> {
3848 Blockable blockable;
3849 switch (menuItem.getItemId()) {
3850 case R.id.reject:
3851 activity.xmppConnectionService.stopPresenceUpdatesTo(
3852 conversation.getContact());
3853 updateSnackBar(conversation);
3854 return true;
3855 case R.id.add_contact:
3856 mAddBackClickListener.onClick(view);
3857 return true;
3858 // case R.id.block_domain:
3859 // blockable =
3860 // conversation
3861 // .getAccount()
3862 // .getRoster()
3863 // .getContact(jid.getDomain());
3864 // break;
3865 default:
3866 blockable = conversation;
3867 }
3868 BlockContactDialog.show(activity, blockable);
3869 return true;
3870 });
3871 popupMenu.show();
3872 return true;
3873 }
3874
3875 private boolean showBlockMucSubmenu(View view) {
3876 final var jid = conversation.getJid();
3877 final var popupMenu = new PopupMenu(getActivity(), view);
3878 popupMenu.inflate(R.menu.block_muc);
3879 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3880 popupMenu.setOnMenuItemClickListener(
3881 menuItem -> {
3882 Blockable blockable;
3883 switch (menuItem.getItemId()) {
3884 case R.id.reject:
3885 activity.xmppConnectionService.clearConversationHistory(conversation);
3886 activity.xmppConnectionService.archiveConversation(conversation);
3887 return true;
3888 case R.id.add_bookmark:
3889 conversation.getAccount().getXmppConnection().getManager(BookmarkManager.class).save(conversation, "");
3890 updateSnackBar(conversation);
3891 return true;
3892 case R.id.block_contact:
3893 blockable =
3894 conversation
3895 .getAccount()
3896 .getRoster()
3897 .getContact(Jid.of(conversation.getAttribute("inviter")));
3898 break;
3899 default:
3900 blockable = conversation;
3901 }
3902 BlockContactDialog.show(activity, blockable);
3903 activity.xmppConnectionService.archiveConversation(conversation);
3904 return true;
3905 });
3906 popupMenu.show();
3907 return true;
3908 }
3909
3910 private void updateSnackBar(final Conversation conversation) {
3911 final Account account = conversation.getAccount();
3912 final XmppConnection connection = account.getXmppConnection();
3913 final int mode = conversation.getMode();
3914 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3915 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3916 return;
3917 }
3918 if (account.getStatus() == Account.State.DISABLED) {
3919 showSnackbar(
3920 R.string.this_account_is_disabled,
3921 R.string.enable,
3922 this.mEnableAccountListener);
3923 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3924 showSnackbar(
3925 R.string.this_account_is_logged_out,
3926 R.string.log_in,
3927 this.mEnableAccountListener);
3928 } else if (conversation.isBlocked()) {
3929 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3930 } else if (account.getStatus() == Account.State.CONNECTING) {
3931 showSnackbar(R.string.this_account_is_connecting, 0, null);
3932 } else if (account.getStatus() != Account.State.ONLINE) {
3933 showSnackbar(R.string.this_account_is_offline, 0, null);
3934 } else if (contact != null
3935 && !contact.showInRoster()
3936 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3937 showSnackbar(
3938 R.string.contact_added_you,
3939 R.string.options,
3940 this.mBlockClickListener,
3941 this.mLongPressBlockListener);
3942 } else if (contact != null
3943 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3944 showSnackbar(
3945 R.string.contact_asks_for_presence_subscription,
3946 R.string.allow,
3947 this.mAllowPresenceSubscription,
3948 this.mLongPressBlockListener);
3949 } else if (mode == Conversation.MODE_MULTI
3950 && !conversation.getMucOptions().online()
3951 && account.getStatus() == Account.State.ONLINE) {
3952 switch (conversation.getMucOptions().getError()) {
3953 case NICK_IN_USE:
3954 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3955 break;
3956 case NO_RESPONSE:
3957 showSnackbar(R.string.joining_conference, 0, null);
3958 break;
3959 case SERVER_NOT_FOUND:
3960 if (conversation.receivedMessagesCount() > 0) {
3961 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3962 } else {
3963 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3964 }
3965 break;
3966 case REMOTE_SERVER_TIMEOUT:
3967 if (conversation.receivedMessagesCount() > 0) {
3968 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3969 } else {
3970 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3971 }
3972 break;
3973 case PASSWORD_REQUIRED:
3974 showSnackbar(
3975 R.string.conference_requires_password,
3976 R.string.enter_password,
3977 enterPassword);
3978 break;
3979 case BANNED:
3980 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3981 break;
3982 case MEMBERS_ONLY:
3983 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3984 break;
3985 case RESOURCE_CONSTRAINT:
3986 showSnackbar(
3987 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3988 break;
3989 case KICKED:
3990 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3991 break;
3992 case TECHNICAL_PROBLEMS:
3993 showSnackbar(
3994 R.string.conference_technical_problems, R.string.try_again, joinMuc);
3995 break;
3996 case UNKNOWN:
3997 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3998 break;
3999 case INVALID_NICK:
4000 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
4001 case SHUTDOWN:
4002 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
4003 break;
4004 case DESTROYED:
4005 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
4006 break;
4007 case NON_ANONYMOUS:
4008 showSnackbar(
4009 R.string.group_chat_will_make_your_jabber_id_public,
4010 R.string.join,
4011 acceptJoin);
4012 break;
4013 default:
4014 hideSnackbar();
4015 break;
4016 }
4017 } else if (account.hasPendingPgpIntent(conversation)) {
4018 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
4019 } else if (connection != null
4020 && connection.getFeatures().blocking()
4021 && conversation.strangerInvited()) {
4022 showSnackbar(
4023 R.string.received_invite_from_stranger,
4024 R.string.options,
4025 (v) -> showBlockMucSubmenu(v),
4026 (v) -> showBlockMucSubmenu(v));
4027 } else if (connection != null
4028 && connection.getFeatures().blocking()
4029 && conversation.countMessages() != 0
4030 && !conversation.isBlocked()
4031 && conversation.isWithStranger()) {
4032 showSnackbar(
4033 R.string.received_message_from_stranger,
4034 R.string.options,
4035 this.mBlockClickListener,
4036 this.mLongPressBlockListener);
4037 } else {
4038 hideSnackbar();
4039 }
4040 }
4041
4042 @Override
4043 public void refresh() {
4044 if (this.binding == null) {
4045 Log.d(
4046 Config.LOGTAG,
4047 "ConversationFragment.refresh() skipped updated because view binding was null");
4048 return;
4049 }
4050 if (this.conversation != null
4051 && this.activity != null
4052 && this.activity.xmppConnectionService != null) {
4053 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
4054 activity.onConversationArchived(this.conversation);
4055 return;
4056 }
4057 }
4058 this.refresh(true);
4059 }
4060
4061 private void refresh(boolean notifyConversationRead) {
4062 synchronized (this.messageList) {
4063 if (this.conversation != null) {
4064 if (messageListAdapter.hasSelection()) {
4065 if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
4066 } else {
4067 conversation.populateWithMessages(this.messageList, activity == null ? null : activity.xmppConnectionService);
4068 try {
4069 updateStatusMessages();
4070 } catch (IllegalStateException e) {
4071 Log.e(Config.LOGTAG, "Problem updating status messages on refresh: " + e);
4072 }
4073 this.messageListAdapter.notifyDataSetChanged();
4074 }
4075 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
4076 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
4077 binding.unreadCountCustomView.setUnreadCount(
4078 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
4079 }
4080 updateSnackBar(conversation);
4081 if (activity != null) updateChatMsgHint();
4082 if (notifyConversationRead && activity != null) {
4083 binding.messagesView.post(this::fireReadEvent);
4084 }
4085 updateSendButton();
4086 updateEditablity();
4087 conversation.refreshSessions();
4088 }
4089 }
4090 }
4091
4092 protected void messageSent() {
4093 binding.textinputSubject.setText("");
4094 binding.textinputSubject.setVisibility(View.GONE);
4095 setThread(null);
4096 setupReply(null);
4097 conversation.setUserSelectedThread(false);
4098 mSendingPgpMessage.set(false);
4099 this.binding.textinput.setText("");
4100 if (conversation.setCorrectingMessage(null)) {
4101 this.binding.textinput.append(conversation.getDraftMessage());
4102 conversation.setDraftMessage(null);
4103 }
4104 storeNextMessage();
4105 updateChatMsgHint();
4106 if (activity == null) return;
4107 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
4108 final boolean prefScrollToBottom =
4109 p.getBoolean(
4110 "scroll_to_bottom",
4111 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
4112 if (prefScrollToBottom || scrolledToBottom()) {
4113 new Handler()
4114 .post(
4115 () -> {
4116 int size = messageList.size();
4117 this.binding.messagesView.setSelection(size - 1);
4118 });
4119 }
4120 }
4121
4122 private boolean storeNextMessage() {
4123 return storeNextMessage(this.binding.textinput.getText().toString());
4124 }
4125
4126 private boolean storeNextMessage(String msg) {
4127 final boolean participating =
4128 conversation.getMode() == Conversational.MODE_SINGLE
4129 || conversation.getMucOptions().participating();
4130 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
4131 && participating
4132 && this.conversation.setNextMessage(msg) && activity != null) {
4133 activity.xmppConnectionService.updateConversation(this.conversation);
4134 return true;
4135 }
4136 return false;
4137 }
4138
4139 public void doneSendingPgpMessage() {
4140 mSendingPgpMessage.set(false);
4141 }
4142
4143 public Long getMaxHttpUploadSize(final Conversation conversation) {
4144
4145 final var connection = conversation.getAccount().getXmppConnection();
4146 final var httpUploadService = connection.getManager(HttpUploadManager.class).getService();
4147 if (httpUploadService == null) {
4148 return -1L;
4149 }
4150 return httpUploadService.getMaxFileSize();
4151 }
4152
4153 private boolean canWrite() {
4154 return
4155 this.conversation.getMode() == Conversation.MODE_SINGLE
4156 || this.conversation.getMucOptions().participating()
4157 || this.conversation.getNextCounterpart() != null;
4158 }
4159
4160 private void updateEditablity() {
4161 boolean canWrite = canWrite();
4162 this.binding.textinput.setFocusable(canWrite);
4163 this.binding.textinput.setFocusableInTouchMode(canWrite);
4164 this.binding.textSendButton.setEnabled(canWrite);
4165 this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
4166 this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
4167 this.binding.textinput.setCursorVisible(canWrite);
4168 this.binding.textinput.setEnabled(canWrite);
4169 }
4170
4171 public void updateSendButton() {
4172 boolean hasAttachments =
4173 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
4174 final Conversation c = this.conversation;
4175 final Presence.Availability status;
4176 final String text =
4177 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
4178 final SendButtonAction action;
4179 if (hasAttachments) {
4180 action = SendButtonAction.TEXT;
4181 } else {
4182 action = SendButtonTool.getAction(getActivity(), c, text, binding.textinputSubject.getText().toString());
4183 }
4184 if (c.getAccount().getStatus() == Account.State.ONLINE) {
4185 if (activity != null
4186 && activity.xmppConnectionService != null
4187 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
4188 status = Presence.Availability.OFFLINE;
4189 } else if (c.getMode() == Conversation.MODE_SINGLE) {
4190 status = c.getContact().getShownStatus();
4191 } else {
4192 status =
4193 c.getMucOptions().online()
4194 ? Presence.Availability.ONLINE
4195 : Presence.Availability.OFFLINE;
4196 }
4197 } else {
4198 status = Presence.Availability.OFFLINE;
4199 }
4200 this.binding.textSendButton.setTag(action);
4201 this.binding.textSendButton.setIconTint(ColorStateList.valueOf(SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
4202 // TODO send button color
4203 final Activity activity = getActivity();
4204 if (activity != null) {
4205 this.binding.textSendButton.setIconResource(
4206 SendButtonTool.getSendButtonImageResource(action, text.length() > 0 || hasAttachments || (c.getThread() != null && binding.textinputSubject.getText().length() > 0)));
4207 }
4208
4209 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
4210 if (identiconWidth < 0) identiconWidth = params.width;
4211 if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
4212 binding.conversationViewPager.setCurrentItem(0);
4213 params.width = conversation.getThread() == null ? 0 : identiconWidth;
4214 } else {
4215 params.width = identiconWidth;
4216 }
4217 if (!canWrite()) params.width = 0;
4218 binding.threadIdenticonLayout.setLayoutParams(params);
4219 }
4220
4221 protected void updateStatusMessages() {
4222 DateSeparator.addAll(this.messageList);
4223 if (showLoadMoreMessages(conversation)) {
4224 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
4225 }
4226 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4227 ChatState state = conversation.getIncomingChatState();
4228 if (state == ChatState.COMPOSING) {
4229 this.messageList.add(
4230 Message.createStatusMessage(
4231 conversation,
4232 getString(R.string.contact_is_typing, conversation.getName())));
4233 } else if (state == ChatState.PAUSED) {
4234 this.messageList.add(
4235 Message.createStatusMessage(
4236 conversation,
4237 getString(
4238 R.string.contact_has_stopped_typing,
4239 conversation.getName())));
4240 } else {
4241 for (int i = this.messageList.size() - 1; i >= 0; --i) {
4242 final Message message = this.messageList.get(i);
4243 if (message.getType() != Message.TYPE_STATUS) {
4244 if (message.getStatus() == Message.STATUS_RECEIVED) {
4245 return;
4246 } else {
4247 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
4248 this.messageList.add(
4249 i + 1,
4250 Message.createStatusMessage(
4251 conversation,
4252 getString(
4253 R.string.contact_has_read_up_to_this_point,
4254 conversation.getName())));
4255 return;
4256 }
4257 }
4258 }
4259 }
4260 }
4261 } else {
4262 final MucOptions mucOptions = conversation.getMucOptions();
4263 final List<MucOptions.User> allUsers = mucOptions.getUsers();
4264 final Set<ReadByMarker> addedMarkers = new HashSet<>();
4265 ChatState state = ChatState.COMPOSING;
4266 List<MucOptions.User> users =
4267 conversation.getMucOptions().getUsersWithChatState(state, 5);
4268 if (users.size() == 0) {
4269 state = ChatState.PAUSED;
4270 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
4271 }
4272 if (mucOptions.isPrivateAndNonAnonymous()) {
4273 for (int i = this.messageList.size() - 1; i >= 0; --i) {
4274 final Set<ReadByMarker> markersForMessage =
4275 messageList.get(i).getReadByMarkers();
4276 final List<MucOptions.User> shownMarkers = new ArrayList<>();
4277 for (ReadByMarker marker : markersForMessage) {
4278 if (!ReadByMarker.contains(marker, addedMarkers)) {
4279 addedMarkers.add(
4280 marker); // may be put outside this condition. set should do
4281 // dedup anyway
4282 MucOptions.User user = mucOptions.findUser(marker);
4283 if (user != null && !users.contains(user)) {
4284 shownMarkers.add(user);
4285 }
4286 }
4287 }
4288 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
4289 final Message statusMessage;
4290 final int size = shownMarkers.size();
4291 if (size > 1) {
4292 final String body;
4293 if (size <= 4) {
4294 body =
4295 getString(
4296 R.string.contacts_have_read_up_to_this_point,
4297 UIHelper.concatNames(shownMarkers));
4298 } else if (ReadByMarker.allUsersRepresented(
4299 allUsers, markersForMessage, markerForSender)) {
4300 body = getString(R.string.everyone_has_read_up_to_this_point);
4301 } else {
4302 body =
4303 getString(
4304 R.string.contacts_and_n_more_have_read_up_to_this_point,
4305 UIHelper.concatNames(shownMarkers, 3),
4306 size - 3);
4307 }
4308 statusMessage = Message.createStatusMessage(conversation, body);
4309 statusMessage.setCounterparts(shownMarkers);
4310 } else if (size == 1) {
4311 statusMessage =
4312 Message.createStatusMessage(
4313 conversation,
4314 getString(
4315 R.string.contact_has_read_up_to_this_point,
4316 UIHelper.getDisplayName(shownMarkers.get(0))));
4317 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
4318 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
4319 } else {
4320 statusMessage = null;
4321 }
4322 if (statusMessage != null) {
4323 this.messageList.add(i + 1, statusMessage);
4324 }
4325 addedMarkers.add(markerForSender);
4326 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
4327 break;
4328 }
4329 }
4330 }
4331 if (users.size() > 0) {
4332 Message statusMessage;
4333 if (users.size() == 1) {
4334 MucOptions.User user = users.get(0);
4335 int id =
4336 state == ChatState.COMPOSING
4337 ? R.string.contact_is_typing
4338 : R.string.contact_has_stopped_typing;
4339 statusMessage =
4340 Message.createStatusMessage(
4341 conversation, getString(id, UIHelper.getDisplayName(user)));
4342 statusMessage.setTrueCounterpart(user.getRealJid());
4343 statusMessage.setCounterpart(user.getFullJid());
4344 } else {
4345 int id =
4346 state == ChatState.COMPOSING
4347 ? R.string.contacts_are_typing
4348 : R.string.contacts_have_stopped_typing;
4349 statusMessage =
4350 Message.createStatusMessage(
4351 conversation, getString(id, UIHelper.concatNames(users)));
4352 statusMessage.setCounterparts(users);
4353 }
4354 this.messageList.add(statusMessage);
4355 }
4356 }
4357 }
4358
4359 private void stopScrolling() {
4360 long now = SystemClock.uptimeMillis();
4361 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
4362 binding.messagesView.dispatchTouchEvent(cancel);
4363 }
4364
4365 private boolean showLoadMoreMessages(final Conversation c) {
4366 if (activity == null || activity.xmppConnectionService == null) {
4367 return false;
4368 }
4369 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
4370 final MessageArchiveService service =
4371 activity.xmppConnectionService.getMessageArchiveService();
4372 return mam
4373 && (c.getLastClearHistory().getTimestamp() != 0
4374 || (c.countMessages() == 0
4375 && c.messagesLoaded.get()
4376 && c.hasMessagesLeftOnServer()
4377 && !service.queryInProgress(c)));
4378 }
4379
4380 private boolean hasMamSupport(final Conversation c) {
4381 if (c.getMode() == Conversation.MODE_SINGLE) {
4382 final XmppConnection connection = c.getAccount().getXmppConnection();
4383 return connection != null && connection.getFeatures().mam();
4384 } else {
4385 return c.getMucOptions().mamSupport();
4386 }
4387 }
4388
4389 protected void showSnackbar(
4390 final int message, final int action, final OnClickListener clickListener) {
4391 showSnackbar(message, action, clickListener, null);
4392 }
4393
4394 protected void showSnackbar(
4395 final int message,
4396 final int action,
4397 final OnClickListener clickListener,
4398 final View.OnLongClickListener longClickListener) {
4399 this.binding.snackbar.setVisibility(View.VISIBLE);
4400 this.binding.snackbar.setOnClickListener(null);
4401 this.binding.snackbarMessage.setText(message);
4402 this.binding.snackbarMessage.setOnClickListener(null);
4403 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
4404 if (action != 0) {
4405 this.binding.snackbarAction.setText(action);
4406 }
4407 this.binding.snackbarAction.setOnClickListener(clickListener);
4408 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
4409 }
4410
4411 protected void hideSnackbar() {
4412 this.binding.snackbar.setVisibility(View.GONE);
4413 }
4414
4415 protected void sendMessage(Message message) {
4416 new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
4417 messageSent();
4418 }
4419
4420 protected void sendPgpMessage(final Message message) {
4421 final XmppConnectionService xmppService = activity.xmppConnectionService;
4422 final Contact contact = message.getConversation().getContact();
4423 if (!activity.hasPgp()) {
4424 activity.showInstallPgpDialog();
4425 return;
4426 }
4427 if (conversation.getAccount().getPgpSignature() == null) {
4428 activity.announcePgp(
4429 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
4430 return;
4431 }
4432 if (!mSendingPgpMessage.compareAndSet(false, true)) {
4433 Log.d(Config.LOGTAG, "sending pgp message already in progress");
4434 }
4435 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4436 if (contact.getPgpKeyId() != 0) {
4437 xmppService
4438 .getPgpEngine()
4439 .hasKey(
4440 contact,
4441 new UiCallback<Contact>() {
4442
4443 @Override
4444 public void userInputRequired(
4445 PendingIntent pi, Contact contact) {
4446 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
4447 }
4448
4449 @Override
4450 public void success(Contact contact) {
4451 encryptTextMessage(message);
4452 }
4453
4454 @Override
4455 public void error(int error, Contact contact) {
4456 activity.runOnUiThread(
4457 () ->
4458 Toast.makeText(
4459 activity,
4460 R.string
4461 .unable_to_connect_to_keychain,
4462 Toast.LENGTH_SHORT)
4463 .show());
4464 mSendingPgpMessage.set(false);
4465 }
4466 });
4467
4468 } else {
4469 showNoPGPKeyDialog(
4470 false,
4471 (dialog, which) -> {
4472 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4473 xmppService.updateConversation(conversation);
4474 message.setEncryption(Message.ENCRYPTION_NONE);
4475 xmppService.sendMessage(message);
4476 messageSent();
4477 });
4478 }
4479 } else {
4480 if (conversation.getMucOptions().pgpKeysInUse()) {
4481 if (!conversation.getMucOptions().everybodyHasKeys()) {
4482 Toast warning =
4483 Toast.makeText(
4484 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
4485 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
4486 warning.show();
4487 }
4488 encryptTextMessage(message);
4489 } else {
4490 showNoPGPKeyDialog(
4491 true,
4492 (dialog, which) -> {
4493 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4494 message.setEncryption(Message.ENCRYPTION_NONE);
4495 xmppService.updateConversation(conversation);
4496 xmppService.sendMessage(message);
4497 messageSent();
4498 });
4499 }
4500 }
4501 }
4502
4503 public void encryptTextMessage(Message message) {
4504 activity.xmppConnectionService
4505 .getPgpEngine()
4506 .encrypt(
4507 message,
4508 new UiCallback<Message>() {
4509
4510 @Override
4511 public void userInputRequired(PendingIntent pi, Message message) {
4512 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
4513 }
4514
4515 @Override
4516 public void success(Message message) {
4517 // TODO the following two call can be made before the callback
4518 getActivity().runOnUiThread(() -> messageSent());
4519 }
4520
4521 @Override
4522 public void error(final int error, Message message) {
4523 getActivity()
4524 .runOnUiThread(
4525 () -> {
4526 doneSendingPgpMessage();
4527 Toast.makeText(
4528 getActivity(),
4529 error == 0
4530 ? R.string
4531 .unable_to_connect_to_keychain
4532 : error,
4533 Toast.LENGTH_SHORT)
4534 .show();
4535 });
4536 }
4537 });
4538 }
4539
4540 public void showNoPGPKeyDialog(
4541 final boolean plural, final DialogInterface.OnClickListener listener) {
4542 final MaterialAlertDialogBuilder builder =
4543 new MaterialAlertDialogBuilder(requireActivity());
4544 if (plural) {
4545 builder.setTitle(getString(R.string.no_pgp_keys));
4546 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
4547 } else {
4548 builder.setTitle(getString(R.string.no_pgp_key));
4549 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
4550 }
4551 builder.setNegativeButton(getString(R.string.cancel), null);
4552 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
4553 builder.create().show();
4554 }
4555
4556 public void appendText(String text, final boolean doNotAppend) {
4557 if (text == null) {
4558 return;
4559 }
4560 final Editable editable = this.binding.textinput.getText();
4561 String previous = editable == null ? "" : editable.toString();
4562 if (doNotAppend && !TextUtils.isEmpty(previous)) {
4563 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
4564 .show();
4565 return;
4566 }
4567 if (UIHelper.isLastLineQuote(previous)) {
4568 text = '\n' + text;
4569 } else if (previous.length() != 0
4570 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4571 text = " " + text;
4572 }
4573 this.binding.textinput.append(text);
4574 }
4575
4576 @Override
4577 public boolean onEnterPressed(final boolean isCtrlPressed) {
4578 if (isCtrlPressed || enterIsSend()) {
4579 sendMessage();
4580 return true;
4581 }
4582 return false;
4583 }
4584
4585 private boolean enterIsSend() {
4586 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4587 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4588 }
4589
4590 public boolean onArrowUpCtrlPressed() {
4591 final Message lastEditableMessage =
4592 conversation == null ? null : conversation.getLastEditableMessage();
4593 if (lastEditableMessage != null) {
4594 correctMessage(lastEditableMessage);
4595 return true;
4596 } else {
4597 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4598 .show();
4599 return false;
4600 }
4601 }
4602
4603 @Override
4604 public void onTypingStarted() {
4605 final XmppConnectionService service =
4606 activity == null ? null : activity.xmppConnectionService;
4607 if (service == null) {
4608 return;
4609 }
4610 final Account.State status = conversation.getAccount().getStatus();
4611 if (status == Account.State.ONLINE
4612 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4613 service.sendChatState(conversation);
4614 }
4615 runOnUiThread(this::updateSendButton);
4616 }
4617
4618 @Override
4619 public void onTypingStopped() {
4620 final XmppConnectionService service =
4621 activity == null ? null : activity.xmppConnectionService;
4622 if (service == null) {
4623 return;
4624 }
4625 final Account.State status = conversation.getAccount().getStatus();
4626 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4627 service.sendChatState(conversation);
4628 }
4629 }
4630
4631 @Override
4632 public void onTextDeleted() {
4633 final XmppConnectionService service =
4634 activity == null ? null : activity.xmppConnectionService;
4635 if (service == null) {
4636 return;
4637 }
4638 final Account.State status = conversation.getAccount().getStatus();
4639 if (status == Account.State.ONLINE
4640 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4641 service.sendChatState(conversation);
4642 }
4643 if (storeNextMessage()) {
4644 runOnUiThread(
4645 () -> {
4646 if (activity == null) {
4647 return;
4648 }
4649 activity.onConversationsListItemUpdated();
4650 });
4651 }
4652 runOnUiThread(this::updateSendButton);
4653 }
4654
4655 @Override
4656 public void onTextChanged() {
4657 if (conversation != null && conversation.getCorrectingMessage() != null) {
4658 runOnUiThread(this::updateSendButton);
4659 }
4660 }
4661
4662 @Override
4663 public boolean onTabPressed(boolean repeated) {
4664 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4665 return false;
4666 }
4667 if (repeated) {
4668 completionIndex++;
4669 } else {
4670 lastCompletionLength = 0;
4671 completionIndex = 0;
4672 final String content = this.binding.textinput.getText().toString();
4673 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4674 int start =
4675 lastCompletionCursor > 0
4676 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4677 : 0;
4678 firstWord = start == 0;
4679 incomplete = content.substring(start, lastCompletionCursor);
4680 }
4681 List<String> completions = new ArrayList<>();
4682 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4683 String name = user.getNick();
4684 if (name != null && name.startsWith(incomplete)) {
4685 completions.add(name + (firstWord ? ": " : " "));
4686 }
4687 }
4688 Collections.sort(completions);
4689 if (completions.size() > completionIndex) {
4690 String completion = completions.get(completionIndex).substring(incomplete.length());
4691 this.binding
4692 .textinput
4693 .getEditableText()
4694 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4695 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4696 lastCompletionLength = completion.length();
4697 } else {
4698 completionIndex = -1;
4699 this.binding
4700 .textinput
4701 .getEditableText()
4702 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4703 lastCompletionLength = 0;
4704 }
4705 return true;
4706 }
4707
4708 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4709 try {
4710 getActivity()
4711 .startIntentSenderForResult(
4712 pendingIntent.getIntentSender(),
4713 requestCode,
4714 null,
4715 0,
4716 0,
4717 0,
4718 Compatibility.pgpStartIntentSenderOptions());
4719 } catch (final SendIntentException ignored) {
4720 }
4721 }
4722
4723 @Override
4724 public void onBackendConnected() {
4725 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4726 setupEmojiSearch();
4727 String uuid = pendingConversationsUuid.pop();
4728 if (uuid != null) {
4729 if (!findAndReInitByUuidOrArchive(uuid)) {
4730 return;
4731 }
4732 } else {
4733 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4734 clearPending();
4735 activity.onConversationArchived(conversation);
4736 return;
4737 }
4738 }
4739 ActivityResult activityResult = postponedActivityResult.pop();
4740 if (activityResult != null) {
4741 handleActivityResult(activityResult);
4742 }
4743 clearPending();
4744 }
4745
4746 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4747 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4748 if (conversation == null) {
4749 clearPending();
4750 activity.onConversationArchived(null);
4751 return false;
4752 }
4753 reInit(conversation);
4754 ScrollState scrollState = pendingScrollState.pop();
4755 String lastMessageUuid = pendingLastMessageUuid.pop();
4756 List<Attachment> attachments = pendingMediaPreviews.pop();
4757 if (scrollState != null) {
4758 setScrollPosition(scrollState, lastMessageUuid);
4759 }
4760 if (attachments != null && attachments.size() > 0) {
4761 Log.d(Config.LOGTAG, "had attachments on restore");
4762 mediaPreviewAdapter.addMediaPreviews(attachments);
4763 toggleInputMethod();
4764 }
4765 return true;
4766 }
4767
4768 private void clearPending() {
4769 if (postponedActivityResult.clear()) {
4770 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4771 if (pendingTakePhotoUri.clear()) {
4772 Log.e(Config.LOGTAG, "cleared pending photo uri");
4773 }
4774 }
4775 if (pendingScrollState.clear()) {
4776 Log.e(Config.LOGTAG, "cleared scroll state");
4777 }
4778 if (pendingConversationsUuid.clear()) {
4779 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4780 }
4781 if (pendingMediaPreviews.clear()) {
4782 Log.e(Config.LOGTAG, "cleared pending media previews");
4783 }
4784 }
4785
4786 public Conversation getConversation() {
4787 return conversation;
4788 }
4789
4790 @Override
4791 public void onContactPictureLongClicked(View v, final Message message) {
4792 final String fingerprint;
4793 if (message.getEncryption() == Message.ENCRYPTION_PGP
4794 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4795 fingerprint = "pgp";
4796 } else {
4797 fingerprint = message.getFingerprint();
4798 }
4799 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4800 final Contact contact = message.getContact();
4801 if (message.getStatus() <= Message.STATUS_RECEIVED
4802 && (contact == null || !contact.isSelf())) {
4803 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4804 final Jid cp = message.getCounterpart();
4805 if (cp == null || cp.isBareJid()) {
4806 return;
4807 }
4808 final Jid tcp = message.getTrueCounterpart();
4809 final String occupantId = message.getOccupantId();
4810 final User userByRealJid =
4811 tcp != null
4812 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp, occupantId)
4813 : null;
4814 final User userByOccupantId =
4815 occupantId != null
4816 ? conversation.getMucOptions().findUserByOccupantId(occupantId, cp)
4817 : null;
4818 final User user =
4819 userByRealJid != null
4820 ? userByRealJid
4821 : (userByOccupantId != null ? userByOccupantId : conversation.getMucOptions().findUserByFullJid(cp));
4822 if (user == null) return;
4823 popupMenu.inflate(R.menu.muc_details_context);
4824 final Menu menu = popupMenu.getMenu();
4825 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4826 activity, menu, conversation, user);
4827 popupMenu.setOnMenuItemClickListener(
4828 menuItem ->
4829 MucDetailsContextMenuHelper.onContextItemSelected(
4830 menuItem, user, activity, fingerprint));
4831 } else {
4832 popupMenu.inflate(R.menu.one_on_one_context);
4833 popupMenu.setOnMenuItemClickListener(
4834 item -> {
4835 switch (item.getItemId()) {
4836 case R.id.action_contact_details:
4837 activity.switchToContactDetails(
4838 message.getContact(), fingerprint);
4839 break;
4840 case R.id.action_show_qr_code:
4841 activity.showQrCode(
4842 "xmpp:"
4843 + message.getContact()
4844 .getJid()
4845 .asBareJid()
4846 .toString());
4847 break;
4848 }
4849 return true;
4850 });
4851 }
4852 } else {
4853 popupMenu.inflate(R.menu.account_context);
4854 final Menu menu = popupMenu.getMenu();
4855 menu.findItem(R.id.action_manage_accounts)
4856 .setVisible(QuickConversationsService.isConversations());
4857 popupMenu.setOnMenuItemClickListener(
4858 item -> {
4859 final XmppActivity activity = this.activity;
4860 if (activity == null) {
4861 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4862 return true;
4863 }
4864 switch (item.getItemId()) {
4865 case R.id.action_show_qr_code:
4866 activity.showQrCode(conversation.getAccount().getShareableUri());
4867 break;
4868 case R.id.action_account_details:
4869 activity.switchToAccount(
4870 message.getConversation().getAccount(), fingerprint);
4871 break;
4872 case R.id.action_manage_accounts:
4873 AccountUtils.launchManageAccounts(activity);
4874 break;
4875 }
4876 return true;
4877 });
4878 }
4879 popupMenu.show();
4880 }
4881
4882 @Override
4883 public void onContactPictureClicked(Message message) {
4884 setThread(message.getThread());
4885 if (message.isPrivateMessage()) {
4886 privateMessageWith(message.getCounterpart());
4887 return;
4888 }
4889 forkNullThread(message);
4890 conversation.setUserSelectedThread(true);
4891
4892 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4893 if (received) {
4894 if (message.getConversation() instanceof Conversation
4895 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4896 Jid tcp = message.getTrueCounterpart();
4897 Jid user = message.getCounterpart();
4898 if (user != null && !user.isBareJid()) {
4899 final MucOptions mucOptions =
4900 ((Conversation) message.getConversation()).getMucOptions();
4901 if (mucOptions.participating()
4902 || ((Conversation) message.getConversation()).getNextCounterpart()
4903 != null) {
4904 MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4905 MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4906 if (mucUser == null && tcpMucUser == null) {
4907 Toast.makeText(
4908 getActivity(),
4909 activity.getString(
4910 R.string.user_has_left_conference,
4911 user.getResource()),
4912 Toast.LENGTH_SHORT)
4913 .show();
4914 }
4915 highlightInConference(mucUser == null || mucUser.getNick() == null ? (tcpMucUser == null || tcpMucUser.getNick() == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4916 } else {
4917 Toast.makeText(
4918 getActivity(),
4919 R.string.you_are_not_participating,
4920 Toast.LENGTH_SHORT)
4921 .show();
4922 }
4923 }
4924 }
4925 }
4926 }
4927
4928 private Activity requireActivity() {
4929 Activity activity = getActivity();
4930 if (activity == null) activity = this.activity;
4931 if (activity == null) {
4932 throw new IllegalStateException("Activity not attached");
4933 }
4934 return activity;
4935 }
4936}