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 public void refreshForNewCaps() {
3291 refreshCommands(true);
3292 }
3293
3294 protected void refreshCommands(boolean delayShow) {
3295 if (commandAdapter == null) return;
3296
3297 final CommandAdapter.MucConfig mucConfig =
3298 conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER) ?
3299 new CommandAdapter.MucConfig() :
3300 null;
3301
3302 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3303 if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3304 commandJid = conversation.getJid().asBareJid();
3305 }
3306 if (commandJid == null && conversation.getJid().isDomainJid()) {
3307 commandJid = conversation.getJid();
3308 }
3309 if (commandJid == null) {
3310 binding.commandsViewProgressbar.setVisibility(View.GONE);
3311 if (mucConfig == null) {
3312 conversation.hideViewPager();
3313 } else {
3314 commandAdapter.clear();
3315 commandAdapter.add(mucConfig);
3316 conversation.showViewPager();
3317 }
3318 } else {
3319 if (!delayShow) conversation.showViewPager();
3320 binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3321 activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
3322 if (activity == null) return;
3323
3324 activity.runOnUiThread(() -> {
3325 binding.commandsViewProgressbar.setVisibility(View.GONE);
3326 commandAdapter.clear();
3327 if (iq.getType() == IqPacket.TYPE.RESULT) {
3328 for (Element child : iq.query().getChildren()) {
3329 if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3330 commandAdapter.add(new CommandAdapter.Command0050(child));
3331 }
3332 }
3333
3334 if (mucConfig != null) commandAdapter.add(mucConfig);
3335
3336 if (commandAdapter.getCount() < 1) {
3337 conversation.hideViewPager();
3338 } else if (delayShow) {
3339 conversation.showViewPager();
3340 }
3341 });
3342 });
3343 }
3344 }
3345
3346 private void resetUnreadMessagesCount() {
3347 lastMessageUuid = null;
3348 hideUnreadMessagesCount();
3349 }
3350
3351 private void hideUnreadMessagesCount() {
3352 if (this.binding == null) {
3353 return;
3354 }
3355 this.binding.scrollToBottomButton.setEnabled(false);
3356 this.binding.scrollToBottomButton.hide();
3357 this.binding.unreadCountCustomView.setVisibility(View.GONE);
3358 }
3359
3360 private void setSelection(int pos, boolean jumpToBottom) {
3361 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3362 this.binding.messagesView.post(
3363 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3364 this.binding.messagesView.post(this::fireReadEvent);
3365 }
3366
3367 private boolean scrolledToBottom() {
3368 return this.binding != null && scrolledToBottom(this.binding.messagesView);
3369 }
3370
3371 private void processExtras(final Bundle extras) {
3372 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3373 final String text = extras.getString(Intent.EXTRA_TEXT);
3374 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3375 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3376 final String postInitAction =
3377 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3378 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3379 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3380 final boolean doNotAppend =
3381 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3382 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3383
3384 final String thread = extras.getString(ConversationsActivity.EXTRA_THREAD);
3385 if (thread != null) {
3386 conversation.setLockThread(true);
3387 backPressedLeaveSingleThread.setEnabled(true);
3388 setThread(new Element("thread").setContent(thread));
3389 refresh();
3390 }
3391
3392 final List<Uri> uris = extractUris(extras);
3393 if (uris != null && uris.size() > 0) {
3394 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3395 mediaPreviewAdapter.addMediaPreviews(
3396 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3397 } else {
3398 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3399 mediaPreviewAdapter.addMediaPreviews(
3400 Attachment.of(getActivity(), cleanedUris, type));
3401 }
3402 toggleInputMethod();
3403 return;
3404 }
3405 if (nick != null) {
3406 if (pm) {
3407 Jid jid = conversation.getJid();
3408 try {
3409 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3410 privateMessageWith(next);
3411 } catch (final IllegalArgumentException ignored) {
3412 // do nothing
3413 }
3414 } else {
3415 final MucOptions mucOptions = conversation.getMucOptions();
3416 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3417 highlightInConference(nick);
3418 }
3419 }
3420 } else {
3421 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3422 mediaPreviewAdapter.addMediaPreviews(
3423 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3424 toggleInputMethod();
3425 return;
3426 } else if (text != null && asQuote) {
3427 quoteText(text);
3428 } else {
3429 appendText(text, doNotAppend);
3430 }
3431 }
3432 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3433 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3434 return;
3435 }
3436 if ("call".equals(postInitAction)) {
3437 checkPermissionAndTriggerAudioCall();
3438 }
3439 if ("message".equals(postInitAction)) {
3440 binding.conversationViewPager.post(() -> {
3441 binding.conversationViewPager.setCurrentItem(0);
3442 });
3443 }
3444 if ("command".equals(postInitAction)) {
3445 binding.conversationViewPager.post(() -> {
3446 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3447 if (adapter != null && adapter.getCount() > 1) {
3448 binding.conversationViewPager.setCurrentItem(1);
3449 }
3450 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3451 Jid commandJid = null;
3452 if (jid != null) {
3453 try {
3454 commandJid = Jid.of(jid);
3455 } catch (final IllegalArgumentException e) { }
3456 }
3457 if (commandJid == null || !commandJid.isFullJid()) {
3458 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3459 if (discoJid != null) commandJid = discoJid;
3460 }
3461 if (node != null && commandJid != null && activity != null) {
3462 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3463 }
3464 });
3465 return;
3466 }
3467 Message message =
3468 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3469 if ("webxdc".equals(postInitAction)) {
3470 if (message == null) {
3471 message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3472 }
3473 if (message == null) return;
3474
3475 Cid webxdcCid = message.getFileParams().getCids().get(0);
3476 WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
3477 Conversation conversation = (Conversation) message.getConversation();
3478 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3479 conversation.startWebxdc(webxdc);
3480 }
3481 }
3482 if (message != null) {
3483 startDownloadable(message);
3484 }
3485 if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3486 if (!conversation.switchToSession("jabber:iq:register")) {
3487 conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3488 }
3489 }
3490 }
3491
3492 private Element commandFor(final Jid jid, final String node) {
3493 if (commandAdapter != null) {
3494 for (int i = 0; i < commandAdapter.getCount(); i++) {
3495 final CommandAdapter.Command c = commandAdapter.getItem(i);
3496 if (!(c instanceof CommandAdapter.Command0050)) continue;
3497
3498 final Element command = ((CommandAdapter.Command0050) c).el;
3499 final String commandNode = command.getAttribute("node");
3500 if (commandNode == null || !commandNode.equals(node)) continue;
3501
3502 final Jid commandJid = command.getAttributeAsJid("jid");
3503 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3504
3505 return command;
3506 }
3507 }
3508
3509 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3510 }
3511
3512 private List<Uri> extractUris(final Bundle extras) {
3513 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3514 if (uris != null) {
3515 return uris;
3516 }
3517 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3518 if (uri != null) {
3519 return Collections.singletonList(uri);
3520 } else {
3521 return null;
3522 }
3523 }
3524
3525 private List<Uri> cleanUris(final List<Uri> uris) {
3526 final Iterator<Uri> iterator = uris.iterator();
3527 while (iterator.hasNext()) {
3528 final Uri uri = iterator.next();
3529 if (FileBackend.dangerousFile(uri)) {
3530 iterator.remove();
3531 Toast.makeText(
3532 requireActivity(),
3533 R.string.security_violation_not_attaching_file,
3534 Toast.LENGTH_SHORT)
3535 .show();
3536 }
3537 }
3538 return uris;
3539 }
3540
3541 private boolean showBlockSubmenu(View view) {
3542 final Jid jid = conversation.getJid();
3543 final int mode = conversation.getMode();
3544 final var contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3545 final boolean showReject = contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3546 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3547 popupMenu.inflate(R.menu.block);
3548 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3549 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3550 popupMenu.getMenu().findItem(R.id.add_contact).setVisible(!contact.showInRoster());
3551 popupMenu.setOnMenuItemClickListener(
3552 menuItem -> {
3553 Blockable blockable;
3554 switch (menuItem.getItemId()) {
3555 case R.id.reject:
3556 activity.xmppConnectionService.stopPresenceUpdatesTo(
3557 conversation.getContact());
3558 updateSnackBar(conversation);
3559 return true;
3560 case R.id.add_contact:
3561 mAddBackClickListener.onClick(view);
3562 return true;
3563 case R.id.block_domain:
3564 blockable =
3565 conversation
3566 .getAccount()
3567 .getRoster()
3568 .getContact(jid.getDomain());
3569 break;
3570 default:
3571 blockable = conversation;
3572 }
3573 BlockContactDialog.show(activity, blockable);
3574 return true;
3575 });
3576 popupMenu.show();
3577 return true;
3578 }
3579
3580 private boolean showBlockMucSubmenu(View view) {
3581 final var jid = conversation.getJid();
3582 final var popupMenu = new PopupMenu(getActivity(), view);
3583 popupMenu.inflate(R.menu.block_muc);
3584 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3585 popupMenu.setOnMenuItemClickListener(
3586 menuItem -> {
3587 Blockable blockable;
3588 switch (menuItem.getItemId()) {
3589 case R.id.reject:
3590 activity.xmppConnectionService.clearConversationHistory(conversation);
3591 activity.xmppConnectionService.archiveConversation(conversation);
3592 return true;
3593 case R.id.add_bookmark:
3594 activity.xmppConnectionService.saveConversationAsBookmark(conversation, "");
3595 updateSnackBar(conversation);
3596 return true;
3597 case R.id.block_contact:
3598 blockable =
3599 conversation
3600 .getAccount()
3601 .getRoster()
3602 .getContact(Jid.of(conversation.getAttribute("inviter")));
3603 break;
3604 default:
3605 blockable = conversation;
3606 }
3607 BlockContactDialog.show(activity, blockable);
3608 activity.xmppConnectionService.archiveConversation(conversation);
3609 return true;
3610 });
3611 popupMenu.show();
3612 return true;
3613 }
3614
3615 private void updateSnackBar(final Conversation conversation) {
3616 final Account account = conversation.getAccount();
3617 final XmppConnection connection = account.getXmppConnection();
3618 final int mode = conversation.getMode();
3619 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3620 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3621 return;
3622 }
3623 if (account.getStatus() == Account.State.DISABLED) {
3624 showSnackbar(
3625 R.string.this_account_is_disabled,
3626 R.string.enable,
3627 this.mEnableAccountListener);
3628 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3629 showSnackbar(R.string.this_account_is_logged_out,R.string.log_in,this.mEnableAccountListener);
3630 } else if (conversation.isBlocked()) {
3631 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3632 } else if (contact != null
3633 && !contact.showInRoster()
3634 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3635 showSnackbar(
3636 R.string.contact_added_you,
3637 R.string.options,
3638 this.mBlockClickListener,
3639 this.mLongPressBlockListener);
3640 } else if (contact != null
3641 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3642 showSnackbar(
3643 R.string.contact_asks_for_presence_subscription,
3644 R.string.allow,
3645 this.mAllowPresenceSubscription,
3646 this.mLongPressBlockListener);
3647 } else if (mode == Conversation.MODE_MULTI
3648 && !conversation.getMucOptions().online()
3649 && account.getStatus() == Account.State.ONLINE) {
3650 switch (conversation.getMucOptions().getError()) {
3651 case NICK_IN_USE:
3652 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3653 break;
3654 case NO_RESPONSE:
3655 showSnackbar(R.string.joining_conference, 0, null);
3656 break;
3657 case SERVER_NOT_FOUND:
3658 if (conversation.receivedMessagesCount() > 0) {
3659 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3660 } else {
3661 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3662 }
3663 break;
3664 case REMOTE_SERVER_TIMEOUT:
3665 if (conversation.receivedMessagesCount() > 0) {
3666 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3667 } else {
3668 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3669 }
3670 break;
3671 case PASSWORD_REQUIRED:
3672 showSnackbar(
3673 R.string.conference_requires_password,
3674 R.string.enter_password,
3675 enterPassword);
3676 break;
3677 case BANNED:
3678 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3679 break;
3680 case MEMBERS_ONLY:
3681 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3682 break;
3683 case RESOURCE_CONSTRAINT:
3684 showSnackbar(
3685 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3686 break;
3687 case KICKED:
3688 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3689 break;
3690 case TECHNICAL_PROBLEMS:
3691 showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3692 break;
3693 case UNKNOWN:
3694 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3695 break;
3696 case INVALID_NICK:
3697 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3698 case SHUTDOWN:
3699 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3700 break;
3701 case DESTROYED:
3702 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3703 break;
3704 case NON_ANONYMOUS:
3705 showSnackbar(
3706 R.string.group_chat_will_make_your_jabber_id_public,
3707 R.string.join,
3708 acceptJoin);
3709 break;
3710 default:
3711 hideSnackbar();
3712 break;
3713 }
3714 } else if (account.hasPendingPgpIntent(conversation)) {
3715 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3716 } else if (connection != null
3717 && connection.getFeatures().blocking()
3718 && conversation.strangerInvited()) {
3719 showSnackbar(
3720 R.string.received_invite_from_stranger,
3721 R.string.options,
3722 (v) -> showBlockMucSubmenu(v),
3723 (v) -> showBlockMucSubmenu(v));
3724 } else if (connection != null
3725 && connection.getFeatures().blocking()
3726 && conversation.countMessages() != 0
3727 && !conversation.isBlocked()
3728 && conversation.isWithStranger()) {
3729 showSnackbar(
3730 R.string.received_message_from_stranger,
3731 R.string.options,
3732 this.mBlockClickListener,
3733 this.mLongPressBlockListener);
3734 } else {
3735 hideSnackbar();
3736 }
3737 }
3738
3739 @Override
3740 public void refresh() {
3741 if (this.binding == null) {
3742 Log.d(
3743 Config.LOGTAG,
3744 "ConversationFragment.refresh() skipped updated because view binding was null");
3745 return;
3746 }
3747 if (this.conversation != null
3748 && this.activity != null
3749 && this.activity.xmppConnectionService != null) {
3750 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3751 activity.onConversationArchived(this.conversation);
3752 return;
3753 }
3754 }
3755 this.refresh(true);
3756 }
3757
3758 private void refresh(boolean notifyConversationRead) {
3759 synchronized (this.messageList) {
3760 if (this.conversation != null) {
3761 if (messageListAdapter.hasSelection()) {
3762 if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3763 } else {
3764 conversation.populateWithMessages(this.messageList, activity == null ? null : activity.xmppConnectionService);
3765 updateStatusMessages();
3766 this.messageListAdapter.notifyDataSetChanged();
3767 }
3768 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3769 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3770 binding.unreadCountCustomView.setUnreadCount(
3771 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3772 }
3773 updateSnackBar(conversation);
3774 if (activity != null) updateChatMsgHint();
3775 if (notifyConversationRead && activity != null) {
3776 binding.messagesView.post(this::fireReadEvent);
3777 }
3778 updateSendButton();
3779 updateEditablity();
3780 conversation.refreshSessions();
3781 }
3782 }
3783 }
3784
3785 protected void messageSent() {
3786 binding.textinputSubject.setText("");
3787 binding.textinputSubject.setVisibility(View.GONE);
3788 setThread(null);
3789 conversation.setUserSelectedThread(false);
3790 mSendingPgpMessage.set(false);
3791 this.binding.textinput.setText("");
3792 if (conversation.setCorrectingMessage(null)) {
3793 this.binding.textinput.append(conversation.getDraftMessage());
3794 conversation.setDraftMessage(null);
3795 }
3796 storeNextMessage();
3797 updateChatMsgHint();
3798 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3799 final boolean prefScrollToBottom =
3800 p.getBoolean(
3801 "scroll_to_bottom",
3802 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3803 if (prefScrollToBottom || scrolledToBottom()) {
3804 new Handler()
3805 .post(
3806 () -> {
3807 int size = messageList.size();
3808 this.binding.messagesView.setSelection(size - 1);
3809 });
3810 }
3811 }
3812
3813 private boolean storeNextMessage() {
3814 return storeNextMessage(this.binding.textinput.getText().toString());
3815 }
3816
3817 private boolean storeNextMessage(String msg) {
3818 final boolean participating =
3819 conversation.getMode() == Conversational.MODE_SINGLE
3820 || conversation.getMucOptions().participating();
3821 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3822 && participating
3823 && this.conversation.setNextMessage(msg) && activity != null) {
3824 activity.xmppConnectionService.updateConversation(this.conversation);
3825 return true;
3826 }
3827 return false;
3828 }
3829
3830 public void doneSendingPgpMessage() {
3831 mSendingPgpMessage.set(false);
3832 }
3833
3834 public long getMaxHttpUploadSize(Conversation conversation) {
3835 final XmppConnection connection = conversation.getAccount().getXmppConnection();
3836 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3837 }
3838
3839 private boolean canWrite() {
3840 return
3841 this.conversation.getMode() == Conversation.MODE_SINGLE
3842 || this.conversation.getMucOptions().participating()
3843 || this.conversation.getNextCounterpart() != null;
3844 }
3845
3846 private void updateEditablity() {
3847 boolean canWrite = canWrite();
3848 this.binding.textinput.setFocusable(canWrite);
3849 this.binding.textinput.setFocusableInTouchMode(canWrite);
3850 this.binding.textSendButton.setEnabled(canWrite);
3851 this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
3852 this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
3853 this.binding.textinput.setCursorVisible(canWrite);
3854 this.binding.textinput.setEnabled(canWrite);
3855 }
3856
3857 public void updateSendButton() {
3858 boolean hasAttachments =
3859 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3860 final Conversation c = this.conversation;
3861 final Presence.Status status;
3862 final String text =
3863 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3864 final SendButtonAction action;
3865 if (hasAttachments) {
3866 action = SendButtonAction.TEXT;
3867 } else {
3868 action = SendButtonTool.getAction(getActivity(), c, text, binding.textinputSubject.getText().toString());
3869 }
3870 if (c.getAccount().getStatus() == Account.State.ONLINE) {
3871 if (activity != null
3872 && activity.xmppConnectionService != null
3873 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3874 status = Presence.Status.OFFLINE;
3875 } else if (c.getMode() == Conversation.MODE_SINGLE) {
3876 status = c.getContact().getShownStatus();
3877 } else {
3878 status =
3879 c.getMucOptions().online()
3880 ? Presence.Status.ONLINE
3881 : Presence.Status.OFFLINE;
3882 }
3883 } else {
3884 status = Presence.Status.OFFLINE;
3885 }
3886 this.binding.textSendButton.setTag(action);
3887 this.binding.textSendButton.setIconTint(ColorStateList.valueOf(SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
3888 // TODO send button color
3889 final Activity activity = getActivity();
3890 if (activity != null) {
3891 this.binding.textSendButton.setIconResource(
3892 SendButtonTool.getSendButtonImageResource(action, text.length() > 0 || hasAttachments || (c.getThread() != null && binding.textinputSubject.getText().length() > 0)));
3893 }
3894
3895 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3896 if (identiconWidth < 0) identiconWidth = params.width;
3897 if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
3898 binding.conversationViewPager.setCurrentItem(0);
3899 params.width = conversation.getThread() == null ? 0 : identiconWidth;
3900 } else {
3901 params.width = identiconWidth;
3902 }
3903 if (!canWrite()) params.width = 0;
3904 binding.threadIdenticonLayout.setLayoutParams(params);
3905 }
3906
3907 protected void updateStatusMessages() {
3908 DateSeparator.addAll(this.messageList);
3909 if (showLoadMoreMessages(conversation)) {
3910 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3911 }
3912 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3913 ChatState state = conversation.getIncomingChatState();
3914 if (state == ChatState.COMPOSING) {
3915 this.messageList.add(
3916 Message.createStatusMessage(
3917 conversation,
3918 getString(R.string.contact_is_typing, conversation.getName())));
3919 } else if (state == ChatState.PAUSED) {
3920 this.messageList.add(
3921 Message.createStatusMessage(
3922 conversation,
3923 getString(
3924 R.string.contact_has_stopped_typing,
3925 conversation.getName())));
3926 } else {
3927 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3928 final Message message = this.messageList.get(i);
3929 if (message.getType() != Message.TYPE_STATUS) {
3930 if (message.getStatus() == Message.STATUS_RECEIVED) {
3931 return;
3932 } else {
3933 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3934 this.messageList.add(
3935 i + 1,
3936 Message.createStatusMessage(
3937 conversation,
3938 getString(
3939 R.string.contact_has_read_up_to_this_point,
3940 conversation.getName())));
3941 return;
3942 }
3943 }
3944 }
3945 }
3946 }
3947 } else {
3948 final MucOptions mucOptions = conversation.getMucOptions();
3949 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3950 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3951 ChatState state = ChatState.COMPOSING;
3952 List<MucOptions.User> users =
3953 conversation.getMucOptions().getUsersWithChatState(state, 5);
3954 if (users.size() == 0) {
3955 state = ChatState.PAUSED;
3956 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3957 }
3958 if (mucOptions.isPrivateAndNonAnonymous()) {
3959 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3960 final Set<ReadByMarker> markersForMessage =
3961 messageList.get(i).getReadByMarkers();
3962 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3963 for (ReadByMarker marker : markersForMessage) {
3964 if (!ReadByMarker.contains(marker, addedMarkers)) {
3965 addedMarkers.add(
3966 marker); // may be put outside this condition. set should do
3967 // dedup anyway
3968 MucOptions.User user = mucOptions.findUser(marker);
3969 if (user != null && !users.contains(user)) {
3970 shownMarkers.add(user);
3971 }
3972 }
3973 }
3974 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3975 final Message statusMessage;
3976 final int size = shownMarkers.size();
3977 if (size > 1) {
3978 final String body;
3979 if (size <= 4) {
3980 body =
3981 getString(
3982 R.string.contacts_have_read_up_to_this_point,
3983 UIHelper.concatNames(shownMarkers));
3984 } else if (ReadByMarker.allUsersRepresented(
3985 allUsers, markersForMessage, markerForSender)) {
3986 body = getString(R.string.everyone_has_read_up_to_this_point);
3987 } else {
3988 body =
3989 getString(
3990 R.string.contacts_and_n_more_have_read_up_to_this_point,
3991 UIHelper.concatNames(shownMarkers, 3),
3992 size - 3);
3993 }
3994 statusMessage = Message.createStatusMessage(conversation, body);
3995 statusMessage.setCounterparts(shownMarkers);
3996 } else if (size == 1) {
3997 statusMessage =
3998 Message.createStatusMessage(
3999 conversation,
4000 getString(
4001 R.string.contact_has_read_up_to_this_point,
4002 UIHelper.getDisplayName(shownMarkers.get(0))));
4003 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
4004 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
4005 } else {
4006 statusMessage = null;
4007 }
4008 if (statusMessage != null) {
4009 this.messageList.add(i + 1, statusMessage);
4010 }
4011 addedMarkers.add(markerForSender);
4012 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
4013 break;
4014 }
4015 }
4016 }
4017 if (users.size() > 0) {
4018 Message statusMessage;
4019 if (users.size() == 1) {
4020 MucOptions.User user = users.get(0);
4021 int id =
4022 state == ChatState.COMPOSING
4023 ? R.string.contact_is_typing
4024 : R.string.contact_has_stopped_typing;
4025 statusMessage =
4026 Message.createStatusMessage(
4027 conversation, getString(id, UIHelper.getDisplayName(user)));
4028 statusMessage.setTrueCounterpart(user.getRealJid());
4029 statusMessage.setCounterpart(user.getFullJid());
4030 } else {
4031 int id =
4032 state == ChatState.COMPOSING
4033 ? R.string.contacts_are_typing
4034 : R.string.contacts_have_stopped_typing;
4035 statusMessage =
4036 Message.createStatusMessage(
4037 conversation, getString(id, UIHelper.concatNames(users)));
4038 statusMessage.setCounterparts(users);
4039 }
4040 this.messageList.add(statusMessage);
4041 }
4042 }
4043 }
4044
4045 private void stopScrolling() {
4046 long now = SystemClock.uptimeMillis();
4047 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
4048 binding.messagesView.dispatchTouchEvent(cancel);
4049 }
4050
4051 private boolean showLoadMoreMessages(final Conversation c) {
4052 if (activity == null || activity.xmppConnectionService == null) {
4053 return false;
4054 }
4055 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
4056 final MessageArchiveService service =
4057 activity.xmppConnectionService.getMessageArchiveService();
4058 return mam
4059 && (c.getLastClearHistory().getTimestamp() != 0
4060 || (c.countMessages() == 0
4061 && c.messagesLoaded.get()
4062 && c.hasMessagesLeftOnServer()
4063 && !service.queryInProgress(c)));
4064 }
4065
4066 private boolean hasMamSupport(final Conversation c) {
4067 if (c.getMode() == Conversation.MODE_SINGLE) {
4068 final XmppConnection connection = c.getAccount().getXmppConnection();
4069 return connection != null && connection.getFeatures().mam();
4070 } else {
4071 return c.getMucOptions().mamSupport();
4072 }
4073 }
4074
4075 protected void showSnackbar(
4076 final int message, final int action, final OnClickListener clickListener) {
4077 showSnackbar(message, action, clickListener, null);
4078 }
4079
4080 protected void showSnackbar(
4081 final int message,
4082 final int action,
4083 final OnClickListener clickListener,
4084 final View.OnLongClickListener longClickListener) {
4085 this.binding.snackbar.setVisibility(View.VISIBLE);
4086 this.binding.snackbar.setOnClickListener(null);
4087 this.binding.snackbarMessage.setText(message);
4088 this.binding.snackbarMessage.setOnClickListener(null);
4089 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
4090 if (action != 0) {
4091 this.binding.snackbarAction.setText(action);
4092 }
4093 this.binding.snackbarAction.setOnClickListener(clickListener);
4094 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
4095 }
4096
4097 protected void hideSnackbar() {
4098 this.binding.snackbar.setVisibility(View.GONE);
4099 }
4100
4101 protected void sendMessage(Message message) {
4102 new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
4103 messageSent();
4104 }
4105
4106 protected void sendPgpMessage(final Message message) {
4107 final XmppConnectionService xmppService = activity.xmppConnectionService;
4108 final Contact contact = message.getConversation().getContact();
4109 if (!activity.hasPgp()) {
4110 activity.showInstallPgpDialog();
4111 return;
4112 }
4113 if (conversation.getAccount().getPgpSignature() == null) {
4114 activity.announcePgp(
4115 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
4116 return;
4117 }
4118 if (!mSendingPgpMessage.compareAndSet(false, true)) {
4119 Log.d(Config.LOGTAG, "sending pgp message already in progress");
4120 }
4121 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4122 if (contact.getPgpKeyId() != 0) {
4123 xmppService
4124 .getPgpEngine()
4125 .hasKey(
4126 contact,
4127 new UiCallback<Contact>() {
4128
4129 @Override
4130 public void userInputRequired(
4131 PendingIntent pi, Contact contact) {
4132 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
4133 }
4134
4135 @Override
4136 public void success(Contact contact) {
4137 encryptTextMessage(message);
4138 }
4139
4140 @Override
4141 public void error(int error, Contact contact) {
4142 activity.runOnUiThread(
4143 () ->
4144 Toast.makeText(
4145 activity,
4146 R.string
4147 .unable_to_connect_to_keychain,
4148 Toast.LENGTH_SHORT)
4149 .show());
4150 mSendingPgpMessage.set(false);
4151 }
4152 });
4153
4154 } else {
4155 showNoPGPKeyDialog(
4156 false,
4157 (dialog, which) -> {
4158 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4159 xmppService.updateConversation(conversation);
4160 message.setEncryption(Message.ENCRYPTION_NONE);
4161 xmppService.sendMessage(message);
4162 messageSent();
4163 });
4164 }
4165 } else {
4166 if (conversation.getMucOptions().pgpKeysInUse()) {
4167 if (!conversation.getMucOptions().everybodyHasKeys()) {
4168 Toast warning =
4169 Toast.makeText(
4170 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
4171 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
4172 warning.show();
4173 }
4174 encryptTextMessage(message);
4175 } else {
4176 showNoPGPKeyDialog(
4177 true,
4178 (dialog, which) -> {
4179 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4180 message.setEncryption(Message.ENCRYPTION_NONE);
4181 xmppService.updateConversation(conversation);
4182 xmppService.sendMessage(message);
4183 messageSent();
4184 });
4185 }
4186 }
4187 }
4188
4189 public void encryptTextMessage(Message message) {
4190 activity.xmppConnectionService
4191 .getPgpEngine()
4192 .encrypt(
4193 message,
4194 new UiCallback<Message>() {
4195
4196 @Override
4197 public void userInputRequired(PendingIntent pi, Message message) {
4198 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
4199 }
4200
4201 @Override
4202 public void success(Message message) {
4203 // TODO the following two call can be made before the callback
4204 getActivity().runOnUiThread(() -> messageSent());
4205 }
4206
4207 @Override
4208 public void error(final int error, Message message) {
4209 getActivity()
4210 .runOnUiThread(
4211 () -> {
4212 doneSendingPgpMessage();
4213 Toast.makeText(
4214 getActivity(),
4215 error == 0
4216 ? R.string
4217 .unable_to_connect_to_keychain
4218 : error,
4219 Toast.LENGTH_SHORT)
4220 .show();
4221 });
4222 }
4223 });
4224 }
4225
4226 public void showNoPGPKeyDialog(final boolean plural, final DialogInterface.OnClickListener listener) {
4227 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
4228 if (plural) {
4229 builder.setTitle(getString(R.string.no_pgp_keys));
4230 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
4231 } else {
4232 builder.setTitle(getString(R.string.no_pgp_key));
4233 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
4234 }
4235 builder.setNegativeButton(getString(R.string.cancel), null);
4236 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
4237 builder.create().show();
4238 }
4239
4240 public void appendText(String text, final boolean doNotAppend) {
4241 if (text == null) {
4242 return;
4243 }
4244 final Editable editable = this.binding.textinput.getText();
4245 String previous = editable == null ? "" : editable.toString();
4246 if (doNotAppend && !TextUtils.isEmpty(previous)) {
4247 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
4248 .show();
4249 return;
4250 }
4251 if (UIHelper.isLastLineQuote(previous)) {
4252 text = '\n' + text;
4253 } else if (previous.length() != 0
4254 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4255 text = " " + text;
4256 }
4257 this.binding.textinput.append(text);
4258 }
4259
4260 @Override
4261 public boolean onEnterPressed(final boolean isCtrlPressed) {
4262 if (isCtrlPressed || enterIsSend()) {
4263 sendMessage();
4264 return true;
4265 }
4266 return false;
4267 }
4268
4269 private boolean enterIsSend() {
4270 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4271 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4272 }
4273
4274 public boolean onArrowUpCtrlPressed() {
4275 final Message lastEditableMessage =
4276 conversation == null ? null : conversation.getLastEditableMessage();
4277 if (lastEditableMessage != null) {
4278 correctMessage(lastEditableMessage);
4279 return true;
4280 } else {
4281 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4282 .show();
4283 return false;
4284 }
4285 }
4286
4287 @Override
4288 public void onTypingStarted() {
4289 final XmppConnectionService service =
4290 activity == null ? null : activity.xmppConnectionService;
4291 if (service == null) {
4292 return;
4293 }
4294 final Account.State status = conversation.getAccount().getStatus();
4295 if (status == Account.State.ONLINE
4296 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4297 service.sendChatState(conversation);
4298 }
4299 runOnUiThread(this::updateSendButton);
4300 }
4301
4302 @Override
4303 public void onTypingStopped() {
4304 final XmppConnectionService service =
4305 activity == null ? null : activity.xmppConnectionService;
4306 if (service == null) {
4307 return;
4308 }
4309 final Account.State status = conversation.getAccount().getStatus();
4310 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4311 service.sendChatState(conversation);
4312 }
4313 }
4314
4315 @Override
4316 public void onTextDeleted() {
4317 final XmppConnectionService service =
4318 activity == null ? null : activity.xmppConnectionService;
4319 if (service == null) {
4320 return;
4321 }
4322 final Account.State status = conversation.getAccount().getStatus();
4323 if (status == Account.State.ONLINE
4324 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4325 service.sendChatState(conversation);
4326 }
4327 if (storeNextMessage()) {
4328 runOnUiThread(
4329 () -> {
4330 if (activity == null) {
4331 return;
4332 }
4333 activity.onConversationsListItemUpdated();
4334 });
4335 }
4336 runOnUiThread(this::updateSendButton);
4337 }
4338
4339 @Override
4340 public void onTextChanged() {
4341 if (conversation != null && conversation.getCorrectingMessage() != null) {
4342 runOnUiThread(this::updateSendButton);
4343 }
4344 }
4345
4346 @Override
4347 public boolean onTabPressed(boolean repeated) {
4348 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4349 return false;
4350 }
4351 if (repeated) {
4352 completionIndex++;
4353 } else {
4354 lastCompletionLength = 0;
4355 completionIndex = 0;
4356 final String content = this.binding.textinput.getText().toString();
4357 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4358 int start =
4359 lastCompletionCursor > 0
4360 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4361 : 0;
4362 firstWord = start == 0;
4363 incomplete = content.substring(start, lastCompletionCursor);
4364 }
4365 List<String> completions = new ArrayList<>();
4366 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4367 String name = user.getNick();
4368 if (name != null && name.startsWith(incomplete)) {
4369 completions.add(name + (firstWord ? ": " : " "));
4370 }
4371 }
4372 Collections.sort(completions);
4373 if (completions.size() > completionIndex) {
4374 String completion = completions.get(completionIndex).substring(incomplete.length());
4375 this.binding
4376 .textinput
4377 .getEditableText()
4378 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4379 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4380 lastCompletionLength = completion.length();
4381 } else {
4382 completionIndex = -1;
4383 this.binding
4384 .textinput
4385 .getEditableText()
4386 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4387 lastCompletionLength = 0;
4388 }
4389 return true;
4390 }
4391
4392 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4393 try {
4394 getActivity()
4395 .startIntentSenderForResult(
4396 pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
4397 } catch (final SendIntentException ignored) {
4398 }
4399 }
4400
4401 @Override
4402 public void onBackendConnected() {
4403 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4404 setupEmojiSearch();
4405 String uuid = pendingConversationsUuid.pop();
4406 if (uuid != null) {
4407 if (!findAndReInitByUuidOrArchive(uuid)) {
4408 return;
4409 }
4410 } else {
4411 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4412 clearPending();
4413 activity.onConversationArchived(conversation);
4414 return;
4415 }
4416 }
4417 ActivityResult activityResult = postponedActivityResult.pop();
4418 if (activityResult != null) {
4419 handleActivityResult(activityResult);
4420 }
4421 clearPending();
4422 }
4423
4424 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4425 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4426 if (conversation == null) {
4427 clearPending();
4428 activity.onConversationArchived(null);
4429 return false;
4430 }
4431 reInit(conversation);
4432 ScrollState scrollState = pendingScrollState.pop();
4433 String lastMessageUuid = pendingLastMessageUuid.pop();
4434 List<Attachment> attachments = pendingMediaPreviews.pop();
4435 if (scrollState != null) {
4436 setScrollPosition(scrollState, lastMessageUuid);
4437 }
4438 if (attachments != null && attachments.size() > 0) {
4439 Log.d(Config.LOGTAG, "had attachments on restore");
4440 mediaPreviewAdapter.addMediaPreviews(attachments);
4441 toggleInputMethod();
4442 }
4443 return true;
4444 }
4445
4446 private void clearPending() {
4447 if (postponedActivityResult.clear()) {
4448 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4449 if (pendingTakePhotoUri.clear()) {
4450 Log.e(Config.LOGTAG, "cleared pending photo uri");
4451 }
4452 }
4453 if (pendingScrollState.clear()) {
4454 Log.e(Config.LOGTAG, "cleared scroll state");
4455 }
4456 if (pendingConversationsUuid.clear()) {
4457 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4458 }
4459 if (pendingMediaPreviews.clear()) {
4460 Log.e(Config.LOGTAG, "cleared pending media previews");
4461 }
4462 }
4463
4464 public Conversation getConversation() {
4465 return conversation;
4466 }
4467
4468 @Override
4469 public void onContactPictureLongClicked(View v, final Message message) {
4470 final String fingerprint;
4471 if (message.getEncryption() == Message.ENCRYPTION_PGP
4472 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4473 fingerprint = "pgp";
4474 } else {
4475 fingerprint = message.getFingerprint();
4476 }
4477 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4478 final Contact contact = message.getContact();
4479 if (message.getStatus() <= Message.STATUS_RECEIVED
4480 && (contact == null || !contact.isSelf())) {
4481 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4482 final Jid cp = message.getCounterpart();
4483 if (cp == null || cp.isBareJid()) {
4484 return;
4485 }
4486 final Jid tcp = message.getTrueCounterpart();
4487 final String occupantId = message.getOccupantId();
4488 final User userByRealJid =
4489 tcp != null
4490 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp, occupantId)
4491 : null;
4492 final User userByOccupantId =
4493 occupantId != null
4494 ? conversation.getMucOptions().findUserByOccupantId(occupantId, cp)
4495 : null;
4496 final User user =
4497 userByRealJid != null
4498 ? userByRealJid
4499 : (userByOccupantId != null ? userByOccupantId : conversation.getMucOptions().findUserByFullJid(cp));
4500 if (user == null) return;
4501 popupMenu.inflate(R.menu.muc_details_context);
4502 final Menu menu = popupMenu.getMenu();
4503 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4504 activity, menu, conversation, user);
4505 popupMenu.setOnMenuItemClickListener(
4506 menuItem ->
4507 MucDetailsContextMenuHelper.onContextItemSelected(
4508 menuItem, user, activity, fingerprint));
4509 } else {
4510 popupMenu.inflate(R.menu.one_on_one_context);
4511 popupMenu.setOnMenuItemClickListener(
4512 item -> {
4513 switch (item.getItemId()) {
4514 case R.id.action_contact_details:
4515 activity.switchToContactDetails(
4516 message.getContact(), fingerprint);
4517 break;
4518 case R.id.action_show_qr_code:
4519 activity.showQrCode(
4520 "xmpp:"
4521 + message.getContact()
4522 .getJid()
4523 .asBareJid()
4524 .toEscapedString());
4525 break;
4526 }
4527 return true;
4528 });
4529 }
4530 } else {
4531 popupMenu.inflate(R.menu.account_context);
4532 final Menu menu = popupMenu.getMenu();
4533 menu.findItem(R.id.action_manage_accounts)
4534 .setVisible(QuickConversationsService.isConversations());
4535 popupMenu.setOnMenuItemClickListener(
4536 item -> {
4537 final XmppActivity activity = this.activity;
4538 if (activity == null) {
4539 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4540 return true;
4541 }
4542 switch (item.getItemId()) {
4543 case R.id.action_show_qr_code:
4544 activity.showQrCode(conversation.getAccount().getShareableUri());
4545 break;
4546 case R.id.action_account_details:
4547 activity.switchToAccount(
4548 message.getConversation().getAccount(), fingerprint);
4549 break;
4550 case R.id.action_manage_accounts:
4551 AccountUtils.launchManageAccounts(activity);
4552 break;
4553 }
4554 return true;
4555 });
4556 }
4557 popupMenu.show();
4558 }
4559
4560 @Override
4561 public void onContactPictureClicked(Message message) {
4562 setThread(message.getThread());
4563 if (message.isPrivateMessage()) {
4564 privateMessageWith(message.getCounterpart());
4565 return;
4566 }
4567 forkNullThread(message);
4568 conversation.setUserSelectedThread(true);
4569
4570 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4571 if (received) {
4572 if (message.getConversation() instanceof Conversation
4573 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4574 Jid tcp = message.getTrueCounterpart();
4575 Jid user = message.getCounterpart();
4576 if (user != null && !user.isBareJid()) {
4577 final MucOptions mucOptions =
4578 ((Conversation) message.getConversation()).getMucOptions();
4579 if (mucOptions.participating()
4580 || ((Conversation) message.getConversation()).getNextCounterpart()
4581 != null) {
4582 MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4583 MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4584 if (mucUser == null && tcpMucUser == null) {
4585 Toast.makeText(
4586 getActivity(),
4587 activity.getString(
4588 R.string.user_has_left_conference,
4589 user.getResource()),
4590 Toast.LENGTH_SHORT)
4591 .show();
4592 }
4593 highlightInConference(mucUser == null || mucUser.getNick() == null ? (tcpMucUser == null || tcpMucUser.getNick() == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4594 } else {
4595 Toast.makeText(
4596 getActivity(),
4597 R.string.you_are_not_participating,
4598 Toast.LENGTH_SHORT)
4599 .show();
4600 }
4601 }
4602 }
4603 }
4604 }
4605
4606 private Activity requireActivity() {
4607 Activity activity = getActivity();
4608 if (activity == null) activity = this.activity;
4609 if (activity == null) {
4610 throw new IllegalStateException("Activity not attached");
4611 }
4612 return activity;
4613 }
4614}