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