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 return true;
3134 }
3135
3136 public void refreshForNewCaps() {
3137 refreshCommands(true);
3138 }
3139
3140 protected void refreshCommands(boolean delayShow) {
3141 if (commandAdapter == null) return;
3142
3143 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3144 if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3145 commandJid = conversation.getJid().asBareJid();
3146 }
3147 if (commandJid == null && conversation.getJid().isDomainJid()) {
3148 commandJid = conversation.getJid();
3149 }
3150 if (commandJid == null) {
3151 conversation.hideViewPager();
3152 } else {
3153 if (!delayShow) conversation.showViewPager();
3154 binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3155 activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
3156 if (activity == null) return;
3157
3158 activity.runOnUiThread(() -> {
3159 if (iq.getType() == IqPacket.TYPE.RESULT) {
3160 binding.commandsViewProgressbar.setVisibility(View.GONE);
3161 commandAdapter.clear();
3162 for (Element child : iq.query().getChildren()) {
3163 if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3164 commandAdapter.add(child);
3165 }
3166 }
3167
3168 if (commandAdapter.getCount() < 1) {
3169 conversation.hideViewPager();
3170 } else if (delayShow) {
3171 conversation.showViewPager();
3172 }
3173 });
3174 });
3175 }
3176 }
3177
3178 private void resetUnreadMessagesCount() {
3179 lastMessageUuid = null;
3180 hideUnreadMessagesCount();
3181 }
3182
3183 private void hideUnreadMessagesCount() {
3184 if (this.binding == null) {
3185 return;
3186 }
3187 this.binding.scrollToBottomButton.setEnabled(false);
3188 this.binding.scrollToBottomButton.hide();
3189 this.binding.unreadCountCustomView.setVisibility(View.GONE);
3190 }
3191
3192 private void setSelection(int pos, boolean jumpToBottom) {
3193 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3194 this.binding.messagesView.post(
3195 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3196 this.binding.messagesView.post(this::fireReadEvent);
3197 }
3198
3199 private boolean scrolledToBottom() {
3200 return this.binding != null && scrolledToBottom(this.binding.messagesView);
3201 }
3202
3203 private void processExtras(final Bundle extras) {
3204 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3205 final String text = extras.getString(Intent.EXTRA_TEXT);
3206 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3207 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3208 final String postInitAction =
3209 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3210 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3211 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3212 final boolean doNotAppend =
3213 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3214 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3215 final List<Uri> uris = extractUris(extras);
3216 if (uris != null && uris.size() > 0) {
3217 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3218 mediaPreviewAdapter.addMediaPreviews(
3219 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3220 } else {
3221 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3222 mediaPreviewAdapter.addMediaPreviews(
3223 Attachment.of(getActivity(), cleanedUris, type));
3224 }
3225 toggleInputMethod();
3226 return;
3227 }
3228 if (nick != null) {
3229 if (pm) {
3230 Jid jid = conversation.getJid();
3231 try {
3232 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3233 privateMessageWith(next);
3234 } catch (final IllegalArgumentException ignored) {
3235 // do nothing
3236 }
3237 } else {
3238 final MucOptions mucOptions = conversation.getMucOptions();
3239 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3240 highlightInConference(nick);
3241 }
3242 }
3243 } else {
3244 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3245 mediaPreviewAdapter.addMediaPreviews(
3246 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3247 toggleInputMethod();
3248 return;
3249 } else if (text != null && asQuote) {
3250 quoteText(text);
3251 } else {
3252 appendText(text, doNotAppend);
3253 }
3254 }
3255 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3256 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3257 return;
3258 }
3259 if ("call".equals(postInitAction)) {
3260 checkPermissionAndTriggerAudioCall();
3261 }
3262 if ("message".equals(postInitAction)) {
3263 binding.conversationViewPager.post(() -> {
3264 binding.conversationViewPager.setCurrentItem(0);
3265 });
3266 }
3267 if ("command".equals(postInitAction)) {
3268 binding.conversationViewPager.post(() -> {
3269 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3270 if (adapter != null && adapter.getCount() > 1) {
3271 binding.conversationViewPager.setCurrentItem(1);
3272 }
3273 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3274 Jid commandJid = null;
3275 if (jid != null) {
3276 try {
3277 commandJid = Jid.of(jid);
3278 } catch (final IllegalArgumentException e) { }
3279 }
3280 if (commandJid == null || !commandJid.isFullJid()) {
3281 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3282 if (discoJid != null) commandJid = discoJid;
3283 }
3284 if (node != null && commandJid != null) {
3285 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3286 }
3287 });
3288 return;
3289 }
3290 Message message =
3291 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3292 if ("webxdc".equals(postInitAction)) {
3293 if (message == null) {
3294 message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3295 }
3296 if (message == null) return;
3297
3298 Cid webxdcCid = message.getFileParams().getCids().get(0);
3299 WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
3300 Conversation conversation = (Conversation) message.getConversation();
3301 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3302 conversation.startWebxdc(webxdc);
3303 }
3304 }
3305 if (message != null) {
3306 startDownloadable(message);
3307 }
3308 if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3309 if (!conversation.switchToSession("jabber:iq:register")) {
3310 conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3311 }
3312 }
3313 }
3314
3315 private Element commandFor(final Jid jid, final String node) {
3316 if (commandAdapter != null) {
3317 for (int i = 0; i < commandAdapter.getCount(); i++) {
3318 Element command = commandAdapter.getItem(i);
3319 final String commandNode = command.getAttribute("node");
3320 if (commandNode == null || !commandNode.equals(node)) continue;
3321
3322 final Jid commandJid = command.getAttributeAsJid("jid");
3323 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3324
3325 return command;
3326 }
3327 }
3328
3329 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3330 }
3331
3332 private List<Uri> extractUris(final Bundle extras) {
3333 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3334 if (uris != null) {
3335 return uris;
3336 }
3337 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3338 if (uri != null) {
3339 return Collections.singletonList(uri);
3340 } else {
3341 return null;
3342 }
3343 }
3344
3345 private List<Uri> cleanUris(final List<Uri> uris) {
3346 final Iterator<Uri> iterator = uris.iterator();
3347 while (iterator.hasNext()) {
3348 final Uri uri = iterator.next();
3349 if (FileBackend.weOwnFile(uri)) {
3350 iterator.remove();
3351 Toast.makeText(
3352 getActivity(),
3353 R.string.security_violation_not_attaching_file,
3354 Toast.LENGTH_SHORT)
3355 .show();
3356 }
3357 }
3358 return uris;
3359 }
3360
3361 private boolean showBlockSubmenu(View view) {
3362 final Jid jid = conversation.getJid();
3363 final boolean showReject =
3364 !conversation.isWithStranger()
3365 && conversation
3366 .getContact()
3367 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3368 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3369 popupMenu.inflate(R.menu.block);
3370 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3371 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3372 popupMenu.setOnMenuItemClickListener(
3373 menuItem -> {
3374 Blockable blockable;
3375 switch (menuItem.getItemId()) {
3376 case R.id.reject:
3377 activity.xmppConnectionService.stopPresenceUpdatesTo(
3378 conversation.getContact());
3379 updateSnackBar(conversation);
3380 return true;
3381 case R.id.block_domain:
3382 blockable =
3383 conversation
3384 .getAccount()
3385 .getRoster()
3386 .getContact(jid.getDomain());
3387 break;
3388 default:
3389 blockable = conversation;
3390 }
3391 BlockContactDialog.show(activity, blockable);
3392 return true;
3393 });
3394 popupMenu.show();
3395 return true;
3396 }
3397
3398 private void updateSnackBar(final Conversation conversation) {
3399 final Account account = conversation.getAccount();
3400 final XmppConnection connection = account.getXmppConnection();
3401 final int mode = conversation.getMode();
3402 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3403 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3404 return;
3405 }
3406 if (account.getStatus() == Account.State.DISABLED) {
3407 showSnackbar(
3408 R.string.this_account_is_disabled,
3409 R.string.enable,
3410 this.mEnableAccountListener);
3411 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3412 showSnackbar(R.string.this_account_is_logged_out,R.string.log_in,this.mEnableAccountListener);
3413 } else if (conversation.isBlocked()) {
3414 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3415 } else if (contact != null
3416 && !contact.showInRoster()
3417 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3418 showSnackbar(
3419 R.string.contact_added_you,
3420 R.string.add_back,
3421 this.mAddBackClickListener,
3422 this.mLongPressBlockListener);
3423 } else if (contact != null
3424 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3425 showSnackbar(
3426 R.string.contact_asks_for_presence_subscription,
3427 R.string.allow,
3428 this.mAllowPresenceSubscription,
3429 this.mLongPressBlockListener);
3430 } else if (mode == Conversation.MODE_MULTI
3431 && !conversation.getMucOptions().online()
3432 && account.getStatus() == Account.State.ONLINE) {
3433 switch (conversation.getMucOptions().getError()) {
3434 case NICK_IN_USE:
3435 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3436 break;
3437 case NO_RESPONSE:
3438 showSnackbar(R.string.joining_conference, 0, null);
3439 break;
3440 case SERVER_NOT_FOUND:
3441 if (conversation.receivedMessagesCount() > 0) {
3442 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3443 } else {
3444 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3445 }
3446 break;
3447 case REMOTE_SERVER_TIMEOUT:
3448 if (conversation.receivedMessagesCount() > 0) {
3449 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3450 } else {
3451 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3452 }
3453 break;
3454 case PASSWORD_REQUIRED:
3455 showSnackbar(
3456 R.string.conference_requires_password,
3457 R.string.enter_password,
3458 enterPassword);
3459 break;
3460 case BANNED:
3461 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3462 break;
3463 case MEMBERS_ONLY:
3464 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3465 break;
3466 case RESOURCE_CONSTRAINT:
3467 showSnackbar(
3468 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3469 break;
3470 case KICKED:
3471 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3472 break;
3473 case TECHNICAL_PROBLEMS:
3474 showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3475 break;
3476 case UNKNOWN:
3477 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3478 break;
3479 case INVALID_NICK:
3480 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3481 case SHUTDOWN:
3482 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3483 break;
3484 case DESTROYED:
3485 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3486 break;
3487 case NON_ANONYMOUS:
3488 showSnackbar(
3489 R.string.group_chat_will_make_your_jabber_id_public,
3490 R.string.join,
3491 acceptJoin);
3492 break;
3493 default:
3494 hideSnackbar();
3495 break;
3496 }
3497 } else if (account.hasPendingPgpIntent(conversation)) {
3498 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3499 } else if (connection != null
3500 && connection.getFeatures().blocking()
3501 && conversation.countMessages() != 0
3502 && !conversation.isBlocked()
3503 && conversation.isWithStranger()) {
3504 showSnackbar(
3505 R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
3506 } else {
3507 hideSnackbar();
3508 }
3509 }
3510
3511 @Override
3512 public void refresh() {
3513 if (this.binding == null) {
3514 Log.d(
3515 Config.LOGTAG,
3516 "ConversationFragment.refresh() skipped updated because view binding was null");
3517 return;
3518 }
3519 if (this.conversation != null
3520 && this.activity != null
3521 && this.activity.xmppConnectionService != null) {
3522 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3523 activity.onConversationArchived(this.conversation);
3524 return;
3525 }
3526 }
3527 this.refresh(true);
3528 }
3529
3530 private void refresh(boolean notifyConversationRead) {
3531 synchronized (this.messageList) {
3532 if (this.conversation != null) {
3533 if (messageListAdapter.hasSelection()) {
3534 if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3535 } else {
3536 conversation.populateWithMessages(this.messageList);
3537 updateStatusMessages();
3538 this.messageListAdapter.notifyDataSetChanged();
3539 }
3540 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3541 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3542 binding.unreadCountCustomView.setUnreadCount(
3543 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3544 }
3545 updateSnackBar(conversation);
3546 if (activity != null) updateChatMsgHint();
3547 if (notifyConversationRead && activity != null) {
3548 binding.messagesView.post(this::fireReadEvent);
3549 }
3550 updateSendButton();
3551 updateEditablity();
3552 conversation.refreshSessions();
3553 }
3554 }
3555 }
3556
3557 protected void messageSent() {
3558 setThread(null);
3559 conversation.setUserSelectedThread(false);
3560 mSendingPgpMessage.set(false);
3561 this.binding.textinput.setText("");
3562 if (conversation.setCorrectingMessage(null)) {
3563 this.binding.textinput.append(conversation.getDraftMessage());
3564 conversation.setDraftMessage(null);
3565 }
3566 storeNextMessage();
3567 updateChatMsgHint();
3568 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3569 final boolean prefScrollToBottom =
3570 p.getBoolean(
3571 "scroll_to_bottom",
3572 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3573 if (prefScrollToBottom || scrolledToBottom()) {
3574 new Handler()
3575 .post(
3576 () -> {
3577 int size = messageList.size();
3578 this.binding.messagesView.setSelection(size - 1);
3579 });
3580 }
3581 }
3582
3583 private boolean storeNextMessage() {
3584 return storeNextMessage(this.binding.textinput.getText().toString());
3585 }
3586
3587 private boolean storeNextMessage(String msg) {
3588 final boolean participating =
3589 conversation.getMode() == Conversational.MODE_SINGLE
3590 || conversation.getMucOptions().participating();
3591 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3592 && participating
3593 && this.conversation.setNextMessage(msg)) {
3594 this.activity.xmppConnectionService.updateConversation(this.conversation);
3595 return true;
3596 }
3597 return false;
3598 }
3599
3600 public void doneSendingPgpMessage() {
3601 mSendingPgpMessage.set(false);
3602 }
3603
3604 public long getMaxHttpUploadSize(Conversation conversation) {
3605 final XmppConnection connection = conversation.getAccount().getXmppConnection();
3606 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3607 }
3608
3609 private boolean canWrite() {
3610 return
3611 this.conversation.getMode() == Conversation.MODE_SINGLE
3612 || this.conversation.getMucOptions().participating()
3613 || this.conversation.getNextCounterpart() != null;
3614 }
3615
3616 private void updateEditablity() {
3617 boolean canWrite = canWrite();
3618 this.binding.textinput.setFocusable(canWrite);
3619 this.binding.textinput.setFocusableInTouchMode(canWrite);
3620 this.binding.textSendButton.setEnabled(canWrite);
3621 this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
3622 this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
3623 this.binding.textinput.setCursorVisible(canWrite);
3624 this.binding.textinput.setEnabled(canWrite);
3625 }
3626
3627 public void updateSendButton() {
3628 boolean hasAttachments =
3629 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3630 final Conversation c = this.conversation;
3631 final Presence.Status status;
3632 final String text =
3633 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3634 final SendButtonAction action;
3635 if (hasAttachments) {
3636 action = SendButtonAction.TEXT;
3637 } else {
3638 action = SendButtonTool.getAction(getActivity(), c, text);
3639 }
3640 if (c.getAccount().getStatus() == Account.State.ONLINE) {
3641 if (activity != null
3642 && activity.xmppConnectionService != null
3643 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3644 status = Presence.Status.OFFLINE;
3645 } else if (c.getMode() == Conversation.MODE_SINGLE) {
3646 status = c.getContact().getShownStatus();
3647 } else {
3648 status =
3649 c.getMucOptions().online()
3650 ? Presence.Status.ONLINE
3651 : Presence.Status.OFFLINE;
3652 }
3653 } else {
3654 status = Presence.Status.OFFLINE;
3655 }
3656 this.binding.textSendButton.setTag(action);
3657 final Activity activity = getActivity();
3658 if (activity != null) {
3659 this.binding.textSendButton.setImageResource(
3660 SendButtonTool.getSendButtonImageResource(activity, action, status));
3661 }
3662
3663 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3664 if (identiconWidth < 0) identiconWidth = params.width;
3665 if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
3666 binding.conversationViewPager.setCurrentItem(0);
3667 params.width = conversation.getThread() == null ? 0 : identiconWidth;
3668 } else {
3669 params.width = identiconWidth;
3670 }
3671 if (!canWrite()) params.width = 0;
3672 binding.threadIdenticonLayout.setLayoutParams(params);
3673 }
3674
3675 protected void updateStatusMessages() {
3676 DateSeparator.addAll(this.messageList);
3677 if (showLoadMoreMessages(conversation)) {
3678 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3679 }
3680 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3681 ChatState state = conversation.getIncomingChatState();
3682 if (state == ChatState.COMPOSING) {
3683 this.messageList.add(
3684 Message.createStatusMessage(
3685 conversation,
3686 getString(R.string.contact_is_typing, conversation.getName())));
3687 } else if (state == ChatState.PAUSED) {
3688 this.messageList.add(
3689 Message.createStatusMessage(
3690 conversation,
3691 getString(
3692 R.string.contact_has_stopped_typing,
3693 conversation.getName())));
3694 } else {
3695 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3696 final Message message = this.messageList.get(i);
3697 if (message.getType() != Message.TYPE_STATUS) {
3698 if (message.getStatus() == Message.STATUS_RECEIVED) {
3699 return;
3700 } else {
3701 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3702 this.messageList.add(
3703 i + 1,
3704 Message.createStatusMessage(
3705 conversation,
3706 getString(
3707 R.string.contact_has_read_up_to_this_point,
3708 conversation.getName())));
3709 return;
3710 }
3711 }
3712 }
3713 }
3714 }
3715 } else {
3716 final MucOptions mucOptions = conversation.getMucOptions();
3717 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3718 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3719 ChatState state = ChatState.COMPOSING;
3720 List<MucOptions.User> users =
3721 conversation.getMucOptions().getUsersWithChatState(state, 5);
3722 if (users.size() == 0) {
3723 state = ChatState.PAUSED;
3724 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3725 }
3726 if (mucOptions.isPrivateAndNonAnonymous()) {
3727 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3728 final Set<ReadByMarker> markersForMessage =
3729 messageList.get(i).getReadByMarkers();
3730 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3731 for (ReadByMarker marker : markersForMessage) {
3732 if (!ReadByMarker.contains(marker, addedMarkers)) {
3733 addedMarkers.add(
3734 marker); // may be put outside this condition. set should do
3735 // dedup anyway
3736 MucOptions.User user = mucOptions.findUser(marker);
3737 if (user != null && !users.contains(user)) {
3738 shownMarkers.add(user);
3739 }
3740 }
3741 }
3742 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3743 final Message statusMessage;
3744 final int size = shownMarkers.size();
3745 if (size > 1) {
3746 final String body;
3747 if (size <= 4) {
3748 body =
3749 getString(
3750 R.string.contacts_have_read_up_to_this_point,
3751 UIHelper.concatNames(shownMarkers));
3752 } else if (ReadByMarker.allUsersRepresented(
3753 allUsers, markersForMessage, markerForSender)) {
3754 body = getString(R.string.everyone_has_read_up_to_this_point);
3755 } else {
3756 body =
3757 getString(
3758 R.string.contacts_and_n_more_have_read_up_to_this_point,
3759 UIHelper.concatNames(shownMarkers, 3),
3760 size - 3);
3761 }
3762 statusMessage = Message.createStatusMessage(conversation, body);
3763 statusMessage.setCounterparts(shownMarkers);
3764 } else if (size == 1) {
3765 statusMessage =
3766 Message.createStatusMessage(
3767 conversation,
3768 getString(
3769 R.string.contact_has_read_up_to_this_point,
3770 UIHelper.getDisplayName(shownMarkers.get(0))));
3771 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3772 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3773 } else {
3774 statusMessage = null;
3775 }
3776 if (statusMessage != null) {
3777 this.messageList.add(i + 1, statusMessage);
3778 }
3779 addedMarkers.add(markerForSender);
3780 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3781 break;
3782 }
3783 }
3784 }
3785 if (users.size() > 0) {
3786 Message statusMessage;
3787 if (users.size() == 1) {
3788 MucOptions.User user = users.get(0);
3789 int id =
3790 state == ChatState.COMPOSING
3791 ? R.string.contact_is_typing
3792 : R.string.contact_has_stopped_typing;
3793 statusMessage =
3794 Message.createStatusMessage(
3795 conversation, getString(id, UIHelper.getDisplayName(user)));
3796 statusMessage.setTrueCounterpart(user.getRealJid());
3797 statusMessage.setCounterpart(user.getFullJid());
3798 } else {
3799 int id =
3800 state == ChatState.COMPOSING
3801 ? R.string.contacts_are_typing
3802 : R.string.contacts_have_stopped_typing;
3803 statusMessage =
3804 Message.createStatusMessage(
3805 conversation, getString(id, UIHelper.concatNames(users)));
3806 statusMessage.setCounterparts(users);
3807 }
3808 this.messageList.add(statusMessage);
3809 }
3810 }
3811 }
3812
3813 private void stopScrolling() {
3814 long now = SystemClock.uptimeMillis();
3815 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3816 binding.messagesView.dispatchTouchEvent(cancel);
3817 }
3818
3819 private boolean showLoadMoreMessages(final Conversation c) {
3820 if (activity == null || activity.xmppConnectionService == null) {
3821 return false;
3822 }
3823 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3824 final MessageArchiveService service =
3825 activity.xmppConnectionService.getMessageArchiveService();
3826 return mam
3827 && (c.getLastClearHistory().getTimestamp() != 0
3828 || (c.countMessages() == 0
3829 && c.messagesLoaded.get()
3830 && c.hasMessagesLeftOnServer()
3831 && !service.queryInProgress(c)));
3832 }
3833
3834 private boolean hasMamSupport(final Conversation c) {
3835 if (c.getMode() == Conversation.MODE_SINGLE) {
3836 final XmppConnection connection = c.getAccount().getXmppConnection();
3837 return connection != null && connection.getFeatures().mam();
3838 } else {
3839 return c.getMucOptions().mamSupport();
3840 }
3841 }
3842
3843 protected void showSnackbar(
3844 final int message, final int action, final OnClickListener clickListener) {
3845 showSnackbar(message, action, clickListener, null);
3846 }
3847
3848 protected void showSnackbar(
3849 final int message,
3850 final int action,
3851 final OnClickListener clickListener,
3852 final View.OnLongClickListener longClickListener) {
3853 this.binding.snackbar.setVisibility(View.VISIBLE);
3854 this.binding.snackbar.setOnClickListener(null);
3855 this.binding.snackbarMessage.setText(message);
3856 this.binding.snackbarMessage.setOnClickListener(null);
3857 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3858 if (action != 0) {
3859 this.binding.snackbarAction.setText(action);
3860 }
3861 this.binding.snackbarAction.setOnClickListener(clickListener);
3862 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3863 }
3864
3865 protected void hideSnackbar() {
3866 this.binding.snackbar.setVisibility(View.GONE);
3867 }
3868
3869 protected void sendMessage(Message message) {
3870 new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
3871 messageSent();
3872 }
3873
3874 protected void sendPgpMessage(final Message message) {
3875 final XmppConnectionService xmppService = activity.xmppConnectionService;
3876 final Contact contact = message.getConversation().getContact();
3877 if (!activity.hasPgp()) {
3878 activity.showInstallPgpDialog();
3879 return;
3880 }
3881 if (conversation.getAccount().getPgpSignature() == null) {
3882 activity.announcePgp(
3883 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3884 return;
3885 }
3886 if (!mSendingPgpMessage.compareAndSet(false, true)) {
3887 Log.d(Config.LOGTAG, "sending pgp message already in progress");
3888 }
3889 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3890 if (contact.getPgpKeyId() != 0) {
3891 xmppService
3892 .getPgpEngine()
3893 .hasKey(
3894 contact,
3895 new UiCallback<Contact>() {
3896
3897 @Override
3898 public void userInputRequired(
3899 PendingIntent pi, Contact contact) {
3900 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3901 }
3902
3903 @Override
3904 public void success(Contact contact) {
3905 encryptTextMessage(message);
3906 }
3907
3908 @Override
3909 public void error(int error, Contact contact) {
3910 activity.runOnUiThread(
3911 () ->
3912 Toast.makeText(
3913 activity,
3914 R.string
3915 .unable_to_connect_to_keychain,
3916 Toast.LENGTH_SHORT)
3917 .show());
3918 mSendingPgpMessage.set(false);
3919 }
3920 });
3921
3922 } else {
3923 showNoPGPKeyDialog(
3924 false,
3925 (dialog, which) -> {
3926 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3927 xmppService.updateConversation(conversation);
3928 message.setEncryption(Message.ENCRYPTION_NONE);
3929 xmppService.sendMessage(message);
3930 messageSent();
3931 });
3932 }
3933 } else {
3934 if (conversation.getMucOptions().pgpKeysInUse()) {
3935 if (!conversation.getMucOptions().everybodyHasKeys()) {
3936 Toast warning =
3937 Toast.makeText(
3938 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3939 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3940 warning.show();
3941 }
3942 encryptTextMessage(message);
3943 } else {
3944 showNoPGPKeyDialog(
3945 true,
3946 (dialog, which) -> {
3947 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3948 message.setEncryption(Message.ENCRYPTION_NONE);
3949 xmppService.updateConversation(conversation);
3950 xmppService.sendMessage(message);
3951 messageSent();
3952 });
3953 }
3954 }
3955 }
3956
3957 public void encryptTextMessage(Message message) {
3958 activity.xmppConnectionService
3959 .getPgpEngine()
3960 .encrypt(
3961 message,
3962 new UiCallback<Message>() {
3963
3964 @Override
3965 public void userInputRequired(PendingIntent pi, Message message) {
3966 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3967 }
3968
3969 @Override
3970 public void success(Message message) {
3971 // TODO the following two call can be made before the callback
3972 getActivity().runOnUiThread(() -> messageSent());
3973 }
3974
3975 @Override
3976 public void error(final int error, Message message) {
3977 getActivity()
3978 .runOnUiThread(
3979 () -> {
3980 doneSendingPgpMessage();
3981 Toast.makeText(
3982 getActivity(),
3983 error == 0
3984 ? R.string
3985 .unable_to_connect_to_keychain
3986 : error,
3987 Toast.LENGTH_SHORT)
3988 .show();
3989 });
3990 }
3991 });
3992 }
3993
3994 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3995 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3996 builder.setIconAttribute(android.R.attr.alertDialogIcon);
3997 if (plural) {
3998 builder.setTitle(getString(R.string.no_pgp_keys));
3999 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
4000 } else {
4001 builder.setTitle(getString(R.string.no_pgp_key));
4002 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
4003 }
4004 builder.setNegativeButton(getString(R.string.cancel), null);
4005 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
4006 builder.create().show();
4007 }
4008
4009 public void appendText(String text, final boolean doNotAppend) {
4010 if (text == null) {
4011 return;
4012 }
4013 final Editable editable = this.binding.textinput.getText();
4014 String previous = editable == null ? "" : editable.toString();
4015 if (doNotAppend && !TextUtils.isEmpty(previous)) {
4016 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
4017 .show();
4018 return;
4019 }
4020 if (UIHelper.isLastLineQuote(previous)) {
4021 text = '\n' + text;
4022 } else if (previous.length() != 0
4023 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4024 text = " " + text;
4025 }
4026 this.binding.textinput.append(text);
4027 }
4028
4029 @Override
4030 public boolean onEnterPressed(final boolean isCtrlPressed) {
4031 if (isCtrlPressed || enterIsSend()) {
4032 sendMessage();
4033 return true;
4034 }
4035 return false;
4036 }
4037
4038 private boolean enterIsSend() {
4039 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4040 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4041 }
4042
4043 public boolean onArrowUpCtrlPressed() {
4044 final Message lastEditableMessage =
4045 conversation == null ? null : conversation.getLastEditableMessage();
4046 if (lastEditableMessage != null) {
4047 correctMessage(lastEditableMessage);
4048 return true;
4049 } else {
4050 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4051 .show();
4052 return false;
4053 }
4054 }
4055
4056 @Override
4057 public void onTypingStarted() {
4058 final XmppConnectionService service =
4059 activity == null ? null : activity.xmppConnectionService;
4060 if (service == null) {
4061 return;
4062 }
4063 final Account.State status = conversation.getAccount().getStatus();
4064 if (status == Account.State.ONLINE
4065 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4066 service.sendChatState(conversation);
4067 }
4068 runOnUiThread(this::updateSendButton);
4069 }
4070
4071 @Override
4072 public void onTypingStopped() {
4073 final XmppConnectionService service =
4074 activity == null ? null : activity.xmppConnectionService;
4075 if (service == null) {
4076 return;
4077 }
4078 final Account.State status = conversation.getAccount().getStatus();
4079 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4080 service.sendChatState(conversation);
4081 }
4082 }
4083
4084 @Override
4085 public void onTextDeleted() {
4086 final XmppConnectionService service =
4087 activity == null ? null : activity.xmppConnectionService;
4088 if (service == null) {
4089 return;
4090 }
4091 final Account.State status = conversation.getAccount().getStatus();
4092 if (status == Account.State.ONLINE
4093 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4094 service.sendChatState(conversation);
4095 }
4096 if (storeNextMessage()) {
4097 runOnUiThread(
4098 () -> {
4099 if (activity == null) {
4100 return;
4101 }
4102 activity.onConversationsListItemUpdated();
4103 });
4104 }
4105 runOnUiThread(this::updateSendButton);
4106 }
4107
4108 @Override
4109 public void onTextChanged() {
4110 if (conversation != null && conversation.getCorrectingMessage() != null) {
4111 runOnUiThread(this::updateSendButton);
4112 }
4113 }
4114
4115 @Override
4116 public boolean onTabPressed(boolean repeated) {
4117 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4118 return false;
4119 }
4120 if (repeated) {
4121 completionIndex++;
4122 } else {
4123 lastCompletionLength = 0;
4124 completionIndex = 0;
4125 final String content = this.binding.textinput.getText().toString();
4126 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4127 int start =
4128 lastCompletionCursor > 0
4129 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4130 : 0;
4131 firstWord = start == 0;
4132 incomplete = content.substring(start, lastCompletionCursor);
4133 }
4134 List<String> completions = new ArrayList<>();
4135 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4136 String name = user.getNick();
4137 if (name != null && name.startsWith(incomplete)) {
4138 completions.add(name + (firstWord ? ": " : " "));
4139 }
4140 }
4141 Collections.sort(completions);
4142 if (completions.size() > completionIndex) {
4143 String completion = completions.get(completionIndex).substring(incomplete.length());
4144 this.binding
4145 .textinput
4146 .getEditableText()
4147 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4148 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4149 lastCompletionLength = completion.length();
4150 } else {
4151 completionIndex = -1;
4152 this.binding
4153 .textinput
4154 .getEditableText()
4155 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4156 lastCompletionLength = 0;
4157 }
4158 return true;
4159 }
4160
4161 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4162 try {
4163 getActivity()
4164 .startIntentSenderForResult(
4165 pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
4166 } catch (final SendIntentException ignored) {
4167 }
4168 }
4169
4170 @Override
4171 public void onBackendConnected() {
4172 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4173 setupEmojiSearch();
4174 String uuid = pendingConversationsUuid.pop();
4175 if (uuid != null) {
4176 if (!findAndReInitByUuidOrArchive(uuid)) {
4177 return;
4178 }
4179 } else {
4180 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4181 clearPending();
4182 activity.onConversationArchived(conversation);
4183 return;
4184 }
4185 }
4186 ActivityResult activityResult = postponedActivityResult.pop();
4187 if (activityResult != null) {
4188 handleActivityResult(activityResult);
4189 }
4190 clearPending();
4191 }
4192
4193 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4194 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4195 if (conversation == null) {
4196 clearPending();
4197 activity.onConversationArchived(null);
4198 return false;
4199 }
4200 reInit(conversation);
4201 ScrollState scrollState = pendingScrollState.pop();
4202 String lastMessageUuid = pendingLastMessageUuid.pop();
4203 List<Attachment> attachments = pendingMediaPreviews.pop();
4204 if (scrollState != null) {
4205 setScrollPosition(scrollState, lastMessageUuid);
4206 }
4207 if (attachments != null && attachments.size() > 0) {
4208 Log.d(Config.LOGTAG, "had attachments on restore");
4209 mediaPreviewAdapter.addMediaPreviews(attachments);
4210 toggleInputMethod();
4211 }
4212 return true;
4213 }
4214
4215 private void clearPending() {
4216 if (postponedActivityResult.clear()) {
4217 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4218 if (pendingTakePhotoUri.clear()) {
4219 Log.e(Config.LOGTAG, "cleared pending photo uri");
4220 }
4221 }
4222 if (pendingScrollState.clear()) {
4223 Log.e(Config.LOGTAG, "cleared scroll state");
4224 }
4225 if (pendingConversationsUuid.clear()) {
4226 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4227 }
4228 if (pendingMediaPreviews.clear()) {
4229 Log.e(Config.LOGTAG, "cleared pending media previews");
4230 }
4231 }
4232
4233 public Conversation getConversation() {
4234 return conversation;
4235 }
4236
4237 @Override
4238 public void onContactPictureLongClicked(View v, final Message message) {
4239 final String fingerprint;
4240 if (message.getEncryption() == Message.ENCRYPTION_PGP
4241 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4242 fingerprint = "pgp";
4243 } else {
4244 fingerprint = message.getFingerprint();
4245 }
4246 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4247 final Contact contact = message.getContact();
4248 if (message.getStatus() <= Message.STATUS_RECEIVED
4249 && (contact == null || !contact.isSelf())) {
4250 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4251 final Jid cp = message.getCounterpart();
4252 if (cp == null || cp.isBareJid()) {
4253 return;
4254 }
4255 final Jid tcp = message.getTrueCounterpart();
4256 final User userByRealJid =
4257 tcp != null
4258 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
4259 : null;
4260 final User user =
4261 userByRealJid != null
4262 ? userByRealJid
4263 : conversation.getMucOptions().findUserByFullJid(cp);
4264 if (user == null) return;
4265 popupMenu.inflate(R.menu.muc_details_context);
4266 final Menu menu = popupMenu.getMenu();
4267 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4268 activity, menu, conversation, user);
4269 popupMenu.setOnMenuItemClickListener(
4270 menuItem ->
4271 MucDetailsContextMenuHelper.onContextItemSelected(
4272 menuItem, user, activity, fingerprint));
4273 } else {
4274 popupMenu.inflate(R.menu.one_on_one_context);
4275 popupMenu.setOnMenuItemClickListener(
4276 item -> {
4277 switch (item.getItemId()) {
4278 case R.id.action_contact_details:
4279 activity.switchToContactDetails(
4280 message.getContact(), fingerprint);
4281 break;
4282 case R.id.action_show_qr_code:
4283 activity.showQrCode(
4284 "xmpp:"
4285 + message.getContact()
4286 .getJid()
4287 .asBareJid()
4288 .toEscapedString());
4289 break;
4290 }
4291 return true;
4292 });
4293 }
4294 } else {
4295 popupMenu.inflate(R.menu.account_context);
4296 final Menu menu = popupMenu.getMenu();
4297 menu.findItem(R.id.action_manage_accounts)
4298 .setVisible(QuickConversationsService.isConversations());
4299 popupMenu.setOnMenuItemClickListener(
4300 item -> {
4301 final XmppActivity activity = this.activity;
4302 if (activity == null) {
4303 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4304 return true;
4305 }
4306 switch (item.getItemId()) {
4307 case R.id.action_show_qr_code:
4308 activity.showQrCode(conversation.getAccount().getShareableUri());
4309 break;
4310 case R.id.action_account_details:
4311 activity.switchToAccount(
4312 message.getConversation().getAccount(), fingerprint);
4313 break;
4314 case R.id.action_manage_accounts:
4315 AccountUtils.launchManageAccounts(activity);
4316 break;
4317 }
4318 return true;
4319 });
4320 }
4321 popupMenu.show();
4322 }
4323
4324 @Override
4325 public void onContactPictureClicked(Message message) {
4326 setThread(message.getThread());
4327 if (message.isPrivateMessage()) {
4328 privateMessageWith(message.getCounterpart());
4329 return;
4330 }
4331 forkNullThread(message);
4332 conversation.setUserSelectedThread(true);
4333
4334 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4335 if (received) {
4336 if (message.getConversation() instanceof Conversation
4337 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4338 Jid tcp = message.getTrueCounterpart();
4339 Jid user = message.getCounterpart();
4340 if (user != null && !user.isBareJid()) {
4341 final MucOptions mucOptions =
4342 ((Conversation) message.getConversation()).getMucOptions();
4343 if (mucOptions.participating()
4344 || ((Conversation) message.getConversation()).getNextCounterpart()
4345 != null) {
4346 MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4347 MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4348 if (mucUser == null && tcpMucUser == null) {
4349 Toast.makeText(
4350 getActivity(),
4351 activity.getString(
4352 R.string.user_has_left_conference,
4353 user.getResource()),
4354 Toast.LENGTH_SHORT)
4355 .show();
4356 }
4357 highlightInConference(mucUser == null ? (tcpMucUser == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4358 } else {
4359 Toast.makeText(
4360 getActivity(),
4361 R.string.you_are_not_participating,
4362 Toast.LENGTH_SHORT)
4363 .show();
4364 }
4365 }
4366 }
4367 }
4368 }
4369
4370 private Activity requireActivity() {
4371 final Activity activity = getActivity();
4372 if (activity == null) {
4373 throw new IllegalStateException("Activity not attached");
4374 }
4375 return activity;
4376 }
4377}