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