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