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