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