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