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