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