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