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