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