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