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