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