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