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 MenuItem openWith = menu.findItem(R.id.open_with);
1657 MenuItem copyMessage = menu.findItem(R.id.copy_message);
1658 MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1659 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1660 MenuItem correctMessage = menu.findItem(R.id.correct_message);
1661 MenuItem retractMessage = menu.findItem(R.id.retract_message);
1662 MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
1663 MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1664 MenuItem shareWith = menu.findItem(R.id.share_with);
1665 MenuItem sendAgain = menu.findItem(R.id.send_again);
1666 MenuItem copyUrl = menu.findItem(R.id.copy_url);
1667 MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
1668 MenuItem downloadFile = menu.findItem(R.id.download_file);
1669 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1670 MenuItem blockMedia = menu.findItem(R.id.block_media);
1671 MenuItem deleteFile = menu.findItem(R.id.delete_file);
1672 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1673 onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1674 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1675 final boolean showError =
1676 m.getStatus() == Message.STATUS_SEND_FAILED
1677 && m.getErrorMessage() != null
1678 && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1679 if (!encrypted && !m.getBody().equals("")) {
1680 copyMessage.setVisible(true);
1681 }
1682 quoteMessage.setVisible(!encrypted && !showError);
1683 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1684 retryDecryption.setVisible(true);
1685 }
1686 if (!showError
1687 && relevantForCorrection.getType() == Message.TYPE_TEXT
1688 && !m.isGeoUri()
1689 && relevantForCorrection.isLastCorrectableMessage()
1690 && m.getConversation() instanceof Conversation) {
1691 correctMessage.setVisible(true);
1692 if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1693 }
1694 if (relevantForCorrection.getReactions() != null) {
1695 correctMessage.setVisible(false);
1696 retractMessage.setVisible(true);
1697 }
1698 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")) {
1699 moderateMessage.setVisible(true);
1700 }
1701 if ((m.isFileOrImage() && !deleted && !receiving)
1702 || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1703 && !unInitiatedButKnownSize
1704 && t == null) {
1705 shareWith.setVisible(true);
1706 }
1707 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1708 sendAgain.setVisible(true);
1709 }
1710 if (m.hasFileOnRemoteHost()
1711 || m.isGeoUri()
1712 || m.treatAsDownloadable()
1713 || unInitiatedButKnownSize
1714 || t instanceof HttpDownloadConnection) {
1715 copyUrl.setVisible(true);
1716 }
1717 if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1718 downloadFile.setVisible(true);
1719 downloadFile.setTitle(
1720 activity.getString(
1721 R.string.download_x_file,
1722 UIHelper.getFileDescriptionString(activity, m)));
1723 }
1724 final boolean waitingOfferedSending =
1725 m.getStatus() == Message.STATUS_WAITING
1726 || m.getStatus() == Message.STATUS_UNSEND
1727 || m.getStatus() == Message.STATUS_OFFERED;
1728 final boolean cancelable =
1729 (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1730 if (cancelable) {
1731 cancelTransmission.setVisible(true);
1732 }
1733 if (m.isFileOrImage() && !deleted && !cancelable) {
1734 final String path = m.getRelativeFilePath();
1735 if (path == null
1736 || !path.startsWith("/")
1737 || FileBackend.inConversationsDirectory(requireActivity(), path)) {
1738 saveAsSticker.setVisible(true);
1739 blockMedia.setVisible(true);
1740 deleteFile.setVisible(true);
1741 deleteFile.setTitle(
1742 activity.getString(
1743 R.string.delete_x_file,
1744 UIHelper.getFileDescriptionString(activity, m)));
1745 }
1746 }
1747
1748 if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
1749 // We might be showing a thumbnail worth blocking
1750 blockMedia.setVisible(true);
1751 }
1752 if (showError) {
1753 showErrorMessage.setVisible(true);
1754 }
1755 final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1756 if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1757 || (mime != null && mime.startsWith("audio/"))) {
1758 openWith.setVisible(true);
1759 }
1760 }
1761 }
1762
1763 @Override
1764 public boolean onContextItemSelected(MenuItem item) {
1765 switch (item.getItemId()) {
1766 case R.id.share_with:
1767 ShareUtil.share(activity, selectedMessage);
1768 return true;
1769 case R.id.correct_message:
1770 correctMessage(selectedMessage);
1771 return true;
1772 case R.id.retract_message:
1773 new AlertDialog.Builder(activity)
1774 .setTitle(R.string.retract_message)
1775 .setMessage("Do you really want to retract this message?")
1776 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1777 Message message = selectedMessage;
1778 while (message.mergeable(message.next())) {
1779 message = message.next();
1780 }
1781 Element reactions = message.getReactions();
1782 if (reactions != null) {
1783 final Message previousReaction = conversation.findMessageReactingTo(reactions.getAttribute("id"), null);
1784 if (previousReaction != null) reactions = previousReaction.getReactions();
1785 for (Element el : reactions.getChildren()) {
1786 if (message.getQuoteableBody().endsWith(el.getContent())) {
1787 reactions.removeChild(el);
1788 }
1789 }
1790 message.setReactions(reactions);
1791 if (previousReaction != null) {
1792 previousReaction.setReactions(reactions);
1793 activity.xmppConnectionService.updateMessage(previousReaction);
1794 }
1795 }
1796 message.setBody(" ");
1797 message.putEdited(message.getUuid(), message.getServerMsgId());
1798 message.setServerMsgId(null);
1799 message.setUuid(UUID.randomUUID().toString());
1800 sendMessage(message);
1801 })
1802 .setNegativeButton(R.string.no, null).show();
1803 return true;
1804 case R.id.moderate_message:
1805 activity.quickEdit("Spam", (reason) -> {
1806 Message message = selectedMessage;
1807 do {
1808 activity.xmppConnectionService.moderateMessage(conversation.getAccount(), message, reason);
1809 message = message.mergeable(message.next()) ? message.next() : null;
1810 } while (message != null);
1811 return null;
1812 }, R.string.moderate_reason, false, false, true);
1813 return true;
1814 case R.id.copy_message:
1815 ShareUtil.copyToClipboard(activity, selectedMessage);
1816 return true;
1817 case R.id.quote_message:
1818 quoteMessage(selectedMessage);
1819 return true;
1820 case R.id.send_again:
1821 resendMessage(selectedMessage);
1822 return true;
1823 case R.id.copy_url:
1824 ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1825 return true;
1826 case R.id.save_as_sticker:
1827 saveAsSticker(selectedMessage);
1828 return true;
1829 case R.id.download_file:
1830 startDownloadable(selectedMessage);
1831 return true;
1832 case R.id.cancel_transmission:
1833 cancelTransmission(selectedMessage);
1834 return true;
1835 case R.id.retry_decryption:
1836 retryDecryption(selectedMessage);
1837 return true;
1838 case R.id.block_media:
1839 new AlertDialog.Builder(activity)
1840 .setTitle(R.string.block_media)
1841 .setMessage("Do you really want to block this media in all messages?")
1842 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1843 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
1844 if (thumbs != null && !thumbs.isEmpty()) {
1845 for (Element thumb : thumbs) {
1846 Uri uri = Uri.parse(thumb.getAttribute("uri"));
1847 if (uri.getScheme().equals("cid")) {
1848 Cid cid = BobTransfer.cid(uri);
1849 if (cid == null) continue;
1850 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
1851 activity.xmppConnectionService.blockMedia(f);
1852 activity.xmppConnectionService.evictPreview(f);
1853 f.delete();
1854 }
1855 }
1856 }
1857 File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
1858 activity.xmppConnectionService.blockMedia(f);
1859 activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
1860 activity.xmppConnectionService.evictPreview(f);
1861 activity.xmppConnectionService.updateMessage(selectedMessage, false);
1862 activity.onConversationsListItemUpdated();
1863 refresh();
1864 })
1865 .setNegativeButton(R.string.no, null).show();
1866 return true;
1867 case R.id.delete_file:
1868 deleteFile(selectedMessage);
1869 return true;
1870 case R.id.show_error_message:
1871 showErrorMessage(selectedMessage);
1872 return true;
1873 case R.id.open_with:
1874 openWith(selectedMessage);
1875 return true;
1876 case R.id.only_this_thread:
1877 conversation.setLockThread(true);
1878 backPressedLeaveSingleThread.setEnabled(true);
1879 setThread(selectedMessage.getThread());
1880 refresh();
1881 return true;
1882 default:
1883 return onOptionsItemSelected(item);
1884 }
1885 }
1886
1887 @Override
1888 public boolean onOptionsItemSelected(final MenuItem item) {
1889 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1890 return false;
1891 } else if (conversation == null) {
1892 return super.onOptionsItemSelected(item);
1893 }
1894 switch (item.getItemId()) {
1895 case R.id.encryption_choice_axolotl:
1896 case R.id.encryption_choice_pgp:
1897 case R.id.encryption_choice_none:
1898 handleEncryptionSelection(item);
1899 break;
1900 case R.id.attach_choose_picture:
1901 case R.id.attach_take_picture:
1902 case R.id.attach_record_video:
1903 case R.id.attach_choose_file:
1904 case R.id.attach_record_voice:
1905 case R.id.attach_location:
1906 handleAttachmentSelection(item);
1907 break;
1908 case R.id.action_search:
1909 startSearch();
1910 break;
1911 case R.id.action_archive:
1912 activity.xmppConnectionService.archiveConversation(conversation);
1913 break;
1914 case R.id.action_contact_details:
1915 activity.switchToContactDetails(conversation.getContact());
1916 break;
1917 case R.id.action_muc_details:
1918 ConferenceDetailsActivity.open(activity, conversation);
1919 break;
1920 case R.id.action_invite:
1921 startActivityForResult(
1922 ChooseContactActivity.create(activity, conversation),
1923 REQUEST_INVITE_TO_CONVERSATION);
1924 break;
1925 case R.id.action_clear_history:
1926 clearHistoryDialog(conversation);
1927 break;
1928 case R.id.action_mute:
1929 muteConversationDialog(conversation);
1930 break;
1931 case R.id.action_unmute:
1932 unMuteConversation(conversation);
1933 break;
1934 case R.id.action_block:
1935 case R.id.action_unblock:
1936 final Activity activity = getActivity();
1937 if (activity instanceof XmppActivity) {
1938 BlockContactDialog.show((XmppActivity) activity, conversation);
1939 }
1940 break;
1941 case R.id.action_audio_call:
1942 checkPermissionAndTriggerAudioCall();
1943 break;
1944 case R.id.action_video_call:
1945 checkPermissionAndTriggerVideoCall();
1946 break;
1947 case R.id.action_ongoing_call:
1948 returnToOngoingCall();
1949 break;
1950 case R.id.action_toggle_pinned:
1951 togglePinned();
1952 break;
1953 case R.id.action_add_shortcut:
1954 addShortcut();
1955 break;
1956 case R.id.action_refresh_feature_discovery:
1957 refreshFeatureDiscovery();
1958 break;
1959 default:
1960 break;
1961 }
1962 return super.onOptionsItemSelected(item);
1963 }
1964
1965 public boolean onBackPressed() {
1966 boolean wasLocked = conversation.getLockThread();
1967 conversation.setLockThread(false);
1968 backPressedLeaveSingleThread.setEnabled(false);
1969 if (wasLocked) {
1970 setThread(null);
1971 conversation.setUserSelectedThread(false);
1972 refresh();
1973 updateThreadFromLastMessage();
1974 return true;
1975 }
1976 return false;
1977 }
1978
1979 private void startSearch() {
1980 final Intent intent = new Intent(getActivity(), SearchActivity.class);
1981 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
1982 startActivity(intent);
1983 }
1984
1985 private void returnToOngoingCall() {
1986 final Optional<OngoingRtpSession> ongoingRtpSession =
1987 activity.xmppConnectionService
1988 .getJingleConnectionManager()
1989 .getOngoingRtpConnection(conversation.getContact());
1990 if (ongoingRtpSession.isPresent()) {
1991 final OngoingRtpSession id = ongoingRtpSession.get();
1992 final Intent intent = new Intent(activity, RtpSessionActivity.class);
1993 intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.getAccount().getJid().asBareJid().toEscapedString());
1994 intent.putExtra(
1995 RtpSessionActivity.EXTRA_ACCOUNT,
1996 id.getAccount().getJid().asBareJid().toEscapedString());
1997 intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
1998 if (id instanceof AbstractJingleConnection.Id) {
1999 intent.setAction(Intent.ACTION_VIEW);
2000 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
2001 } else if (id instanceof JingleConnectionManager.RtpSessionProposal) {
2002 if (((JingleConnectionManager.RtpSessionProposal) id).media.contains(Media.VIDEO)) {
2003 intent.setAction(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2004 } else {
2005 intent.setAction(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2006 }
2007 }
2008 activity.startActivity(intent);
2009 }
2010 }
2011
2012 private void refreshFeatureDiscovery() {
2013 Set<Map.Entry<String, Presence>> presences = conversation.getContact().getPresences().getPresencesMap().entrySet();
2014 if (presences.isEmpty()) {
2015 presences = new HashSet<>();
2016 presences.add(new AbstractMap.SimpleEntry("", null));
2017 }
2018 for (Map.Entry<String, Presence> entry : presences) {
2019 Jid jid = conversation.getContact().getJid();
2020 if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
2021 activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
2022 if (activity == null) return;
2023 activity.runOnUiThread(() -> {
2024 refresh();
2025 refreshCommands(true);
2026 });
2027 });
2028 }
2029 }
2030
2031 private void addShortcut() {
2032 ShortcutInfoCompat info;
2033 if (conversation.getMode() == Conversation.MODE_MULTI) {
2034 info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getMucOptions());
2035 } else {
2036 info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getContact());
2037 }
2038 ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2039 }
2040
2041 private void togglePinned() {
2042 final boolean pinned =
2043 conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2044 conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2045 activity.xmppConnectionService.updateConversation(conversation);
2046 activity.invalidateOptionsMenu();
2047 }
2048
2049 private void checkPermissionAndTriggerAudioCall() {
2050 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2051 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2052 return;
2053 }
2054 final List<String> permissions;
2055 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2056 permissions =
2057 Arrays.asList(
2058 Manifest.permission.RECORD_AUDIO,
2059 Manifest.permission.BLUETOOTH_CONNECT);
2060 } else {
2061 permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2062 }
2063 if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2064 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2065 }
2066 }
2067
2068 private void checkPermissionAndTriggerVideoCall() {
2069 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2070 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2071 return;
2072 }
2073 final List<String> permissions;
2074 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2075 permissions =
2076 Arrays.asList(
2077 Manifest.permission.RECORD_AUDIO,
2078 Manifest.permission.CAMERA,
2079 Manifest.permission.BLUETOOTH_CONNECT);
2080 } else {
2081 permissions =
2082 Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2083 }
2084 if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2085 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2086 }
2087 }
2088
2089 private void triggerRtpSession(final String action) {
2090 if (activity.xmppConnectionService.getJingleConnectionManager().isBusy() != null) {
2091 Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2092 .show();
2093 return;
2094 }
2095 final Account account = conversation.getAccount();
2096 if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
2097 activity.xmppConnectionService.updateAccount(account);
2098 }
2099 final Contact contact = conversation.getContact();
2100 if (RtpCapability.jmiSupport(contact)) {
2101 triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2102 } else {
2103 final RtpCapability.Capability capability;
2104 if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2105 capability = RtpCapability.Capability.VIDEO;
2106 } else {
2107 capability = RtpCapability.Capability.AUDIO;
2108 }
2109 PresenceSelector.selectFullJidForDirectRtpConnection(
2110 activity,
2111 contact,
2112 capability,
2113 fullJid -> {
2114 triggerRtpSession(contact.getAccount(), fullJid, action);
2115 });
2116 }
2117 }
2118
2119 private void triggerRtpSession(final Account account, final Jid with, final String action) {
2120 final Intent intent = new Intent(activity, RtpSessionActivity.class);
2121 intent.setAction(action);
2122 intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, account.getJid().toEscapedString());
2123 intent.putExtra(RtpSessionActivity.EXTRA_WITH, with.toEscapedString());
2124 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2125 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
2126 startActivity(intent);
2127 }
2128
2129 private void handleAttachmentSelection(MenuItem item) {
2130 switch (item.getItemId()) {
2131 case R.id.attach_choose_picture:
2132 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2133 break;
2134 case R.id.attach_take_picture:
2135 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2136 break;
2137 case R.id.attach_record_video:
2138 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2139 break;
2140 case R.id.attach_choose_file:
2141 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2142 break;
2143 case R.id.attach_record_voice:
2144 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2145 break;
2146 case R.id.attach_location:
2147 attachFile(ATTACHMENT_CHOICE_LOCATION);
2148 break;
2149 }
2150 }
2151
2152 private void handleEncryptionSelection(MenuItem item) {
2153 if (conversation == null) {
2154 return;
2155 }
2156 final boolean updated;
2157 switch (item.getItemId()) {
2158 case R.id.encryption_choice_none:
2159 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2160 item.setChecked(true);
2161 break;
2162 case R.id.encryption_choice_pgp:
2163 if (activity.hasPgp()) {
2164 if (conversation.getAccount().getPgpSignature() != null) {
2165 updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2166 item.setChecked(true);
2167 } else {
2168 updated = false;
2169 activity.announcePgp(
2170 conversation.getAccount(),
2171 conversation,
2172 null,
2173 activity.onOpenPGPKeyPublished);
2174 }
2175 } else {
2176 activity.showInstallPgpDialog();
2177 updated = false;
2178 }
2179 break;
2180 case R.id.encryption_choice_axolotl:
2181 Log.d(
2182 Config.LOGTAG,
2183 AxolotlService.getLogprefix(conversation.getAccount())
2184 + "Enabled axolotl for Contact "
2185 + conversation.getContact().getJid());
2186 updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2187 item.setChecked(true);
2188 break;
2189 default:
2190 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2191 break;
2192 }
2193 if (updated) {
2194 activity.xmppConnectionService.updateConversation(conversation);
2195 }
2196 updateChatMsgHint();
2197 getActivity().invalidateOptionsMenu();
2198 activity.refreshUi();
2199 }
2200
2201 public void attachFile(final int attachmentChoice) {
2202 attachFile(attachmentChoice, true);
2203 }
2204
2205 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2206 if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2207 if (!hasPermissions(
2208 attachmentChoice,
2209 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2210 Manifest.permission.RECORD_AUDIO)) {
2211 return;
2212 }
2213 } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2214 || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
2215 if (!hasPermissions(
2216 attachmentChoice,
2217 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2218 Manifest.permission.CAMERA)) {
2219 return;
2220 }
2221 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2222 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2223 return;
2224 }
2225 }
2226 if (updateRecentlyUsed) {
2227 storeRecentlyUsedQuickAction(attachmentChoice);
2228 }
2229 final int encryption = conversation.getNextEncryption();
2230 final int mode = conversation.getMode();
2231 if (encryption == Message.ENCRYPTION_PGP) {
2232 if (activity.hasPgp()) {
2233 if (mode == Conversation.MODE_SINGLE
2234 && conversation.getContact().getPgpKeyId() != 0) {
2235 activity.xmppConnectionService
2236 .getPgpEngine()
2237 .hasKey(
2238 conversation.getContact(),
2239 new UiCallback<Contact>() {
2240
2241 @Override
2242 public void userInputRequired(
2243 PendingIntent pi, Contact contact) {
2244 startPendingIntent(pi, attachmentChoice);
2245 }
2246
2247 @Override
2248 public void success(Contact contact) {
2249 invokeAttachFileIntent(attachmentChoice);
2250 }
2251
2252 @Override
2253 public void error(int error, Contact contact) {
2254 activity.replaceToast(getString(error));
2255 }
2256 });
2257 } else if (mode == Conversation.MODE_MULTI
2258 && conversation.getMucOptions().pgpKeysInUse()) {
2259 if (!conversation.getMucOptions().everybodyHasKeys()) {
2260 Toast warning =
2261 Toast.makeText(
2262 getActivity(),
2263 R.string.missing_public_keys,
2264 Toast.LENGTH_LONG);
2265 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2266 warning.show();
2267 }
2268 invokeAttachFileIntent(attachmentChoice);
2269 } else {
2270 showNoPGPKeyDialog(
2271 false,
2272 (dialog, which) -> {
2273 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2274 activity.xmppConnectionService.updateConversation(conversation);
2275 invokeAttachFileIntent(attachmentChoice);
2276 });
2277 }
2278 } else {
2279 activity.showInstallPgpDialog();
2280 }
2281 } else {
2282 invokeAttachFileIntent(attachmentChoice);
2283 }
2284 }
2285
2286 private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2287 try {
2288 activity.getPreferences()
2289 .edit()
2290 .putString(
2291 RECENTLY_USED_QUICK_ACTION,
2292 SendButtonAction.of(attachmentChoice).toString())
2293 .apply();
2294 } catch (IllegalArgumentException e) {
2295 // just do not save
2296 }
2297 }
2298
2299 @Override
2300 public void onRequestPermissionsResult(
2301 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2302 final PermissionUtils.PermissionResult permissionResult =
2303 PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2304 if (grantResults.length > 0) {
2305 if (allGranted(permissionResult.grantResults)) {
2306 switch (requestCode) {
2307 case REQUEST_START_DOWNLOAD:
2308 if (this.mPendingDownloadableMessage != null) {
2309 startDownloadable(this.mPendingDownloadableMessage);
2310 }
2311 break;
2312 case REQUEST_ADD_EDITOR_CONTENT:
2313 if (this.mPendingEditorContent != null) {
2314 attachEditorContentToConversation(this.mPendingEditorContent);
2315 }
2316 break;
2317 case REQUEST_COMMIT_ATTACHMENTS:
2318 commitAttachments();
2319 break;
2320 case REQUEST_START_AUDIO_CALL:
2321 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2322 break;
2323 case REQUEST_START_VIDEO_CALL:
2324 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2325 break;
2326 default:
2327 attachFile(requestCode);
2328 break;
2329 }
2330 } else {
2331 @StringRes int res;
2332 String firstDenied =
2333 getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2334 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2335 res = R.string.no_microphone_permission;
2336 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2337 res = R.string.no_camera_permission;
2338 } else {
2339 res = R.string.no_storage_permission;
2340 }
2341 Toast.makeText(
2342 getActivity(),
2343 getString(res, getString(R.string.app_name)),
2344 Toast.LENGTH_SHORT)
2345 .show();
2346 }
2347 }
2348 if (writeGranted(grantResults, permissions)) {
2349 if (activity != null && activity.xmppConnectionService != null) {
2350 activity.xmppConnectionService.getDrawableCache().evictAll();
2351 activity.xmppConnectionService.restartFileObserver();
2352 }
2353 refresh();
2354 }
2355 if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
2356 XmppConnectionService.toggleForegroundService(activity);
2357 }
2358 }
2359
2360 public void startDownloadable(Message message) {
2361 if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2362 this.mPendingDownloadableMessage = message;
2363 return;
2364 }
2365 Transferable transferable = message.getTransferable();
2366 if (transferable != null) {
2367 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2368 createNewConnection(message);
2369 return;
2370 }
2371 if (!transferable.start()) {
2372 Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2373 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2374 .show();
2375 }
2376 } else if (message.treatAsDownloadable()
2377 || message.hasFileOnRemoteHost()
2378 || MessageUtils.unInitiatedButKnownSize(message)) {
2379 createNewConnection(message);
2380 } else {
2381 Log.d(
2382 Config.LOGTAG,
2383 message.getConversation().getAccount() + ": unable to start downloadable");
2384 }
2385 }
2386
2387 private void createNewConnection(final Message message) {
2388 if (!activity.xmppConnectionService.hasInternetConnection()) {
2389 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2390 .show();
2391 return;
2392 }
2393 if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2394 try {
2395 BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2396 message.setTransferable(transfer);
2397 transfer.start();
2398 } catch (URISyntaxException e) {
2399 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2400 }
2401 } else {
2402 activity.xmppConnectionService
2403 .getHttpConnectionManager()
2404 .createNewDownloadConnection(message, true);
2405 }
2406 }
2407
2408 @SuppressLint("InflateParams")
2409 protected void clearHistoryDialog(final Conversation conversation) {
2410 final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2411 builder.setTitle(getString(R.string.clear_conversation_history));
2412 final View dialogView =
2413 requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2414 final CheckBox endConversationCheckBox =
2415 dialogView.findViewById(R.id.end_conversation_checkbox);
2416 builder.setView(dialogView);
2417 builder.setNegativeButton(getString(R.string.cancel), null);
2418 builder.setPositiveButton(
2419 getString(R.string.confirm),
2420 (dialog, which) -> {
2421 this.activity.xmppConnectionService.clearConversationHistory(conversation);
2422 if (endConversationCheckBox.isChecked()) {
2423 this.activity.xmppConnectionService.archiveConversation(conversation);
2424 this.activity.onConversationArchived(conversation);
2425 } else {
2426 activity.onConversationsListItemUpdated();
2427 refresh();
2428 }
2429 });
2430 builder.create().show();
2431 }
2432
2433 protected void muteConversationDialog(final Conversation conversation) {
2434 final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
2435 builder.setTitle(R.string.disable_notifications);
2436 final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2437 final CharSequence[] labels = new CharSequence[durations.length];
2438 for (int i = 0; i < durations.length; ++i) {
2439 if (durations[i] == -1) {
2440 labels[i] = activity.getString(R.string.until_further_notice);
2441 } else {
2442 labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2443 }
2444 }
2445 builder.setItems(
2446 labels,
2447 (dialog, which) -> {
2448 final long till;
2449 if (durations[which] == -1) {
2450 till = Long.MAX_VALUE;
2451 } else {
2452 till = System.currentTimeMillis() + (durations[which] * 1000L);
2453 }
2454 conversation.setMutedTill(till);
2455 activity.xmppConnectionService.updateConversation(conversation);
2456 activity.onConversationsListItemUpdated();
2457 refresh();
2458 activity.invalidateOptionsMenu();
2459 });
2460 builder.create().show();
2461 }
2462
2463 private boolean hasPermissions(int requestCode, List<String> permissions) {
2464 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
2465 final List<String> missingPermissions = new ArrayList<>();
2466 for (String permission : permissions) {
2467 if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU || Config.ONLY_INTERNAL_STORAGE) && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2468 continue;
2469 }
2470 if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2471 missingPermissions.add(permission);
2472 }
2473 }
2474 if (missingPermissions.size() == 0) {
2475 return true;
2476 } else {
2477 requestPermissions(
2478 missingPermissions.toArray(new String[0]),
2479 requestCode);
2480 return false;
2481 }
2482 } else {
2483 return true;
2484 }
2485 }
2486
2487 private boolean hasPermissions(int requestCode, String... permissions) {
2488 return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2489 }
2490
2491 public void unMuteConversation(final Conversation conversation) {
2492 conversation.setMutedTill(0);
2493 this.activity.xmppConnectionService.updateConversation(conversation);
2494 this.activity.onConversationsListItemUpdated();
2495 refresh();
2496 this.activity.invalidateOptionsMenu();
2497 }
2498
2499 protected void invokeAttachFileIntent(final int attachmentChoice) {
2500 Intent intent = new Intent();
2501 boolean chooser = false;
2502 switch (attachmentChoice) {
2503 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2504 intent.setAction(Intent.ACTION_GET_CONTENT);
2505 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2506 intent.setType("image/*");
2507 chooser = true;
2508 break;
2509 case ATTACHMENT_CHOICE_RECORD_VIDEO:
2510 intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2511 break;
2512 case ATTACHMENT_CHOICE_TAKE_PHOTO:
2513 final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2514 pendingTakePhotoUri.push(uri);
2515 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2516 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2517 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2518 intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2519 break;
2520 case ATTACHMENT_CHOICE_CHOOSE_FILE:
2521 chooser = true;
2522 intent.setType("*/*");
2523 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2524 intent.addCategory(Intent.CATEGORY_OPENABLE);
2525 intent.setAction(Intent.ACTION_GET_CONTENT);
2526 break;
2527 case ATTACHMENT_CHOICE_RECORD_VOICE:
2528 intent = new Intent(getActivity(), RecordingActivity.class);
2529 break;
2530 case ATTACHMENT_CHOICE_LOCATION:
2531 intent = GeoHelper.getFetchIntent(activity);
2532 break;
2533 }
2534 final Context context = getActivity();
2535 if (context == null) {
2536 return;
2537 }
2538 try {
2539 if (chooser) {
2540 startActivityForResult(
2541 Intent.createChooser(intent, getString(R.string.perform_action_with)),
2542 attachmentChoice);
2543 } else {
2544 startActivityForResult(intent, attachmentChoice);
2545 }
2546 } catch (final ActivityNotFoundException e) {
2547 Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2548 }
2549 }
2550
2551 @Override
2552 public void onResume() {
2553 super.onResume();
2554 binding.messagesView.post(this::fireReadEvent);
2555 }
2556
2557 private void fireReadEvent() {
2558 if (activity != null && this.conversation != null) {
2559 String uuid = getLastVisibleMessageUuid();
2560 if (uuid != null) {
2561 activity.onConversationRead(this.conversation, uuid);
2562 }
2563 }
2564 }
2565
2566 private void newSubThread() {
2567 Element oldThread = conversation.getThread();
2568 Element thread = new Element("thread", "jabber:client");
2569 thread.setContent(UUID.randomUUID().toString());
2570 if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2571 setThread(thread);
2572 }
2573
2574 private void newThread() {
2575 Element thread = new Element("thread", "jabber:client");
2576 thread.setContent(UUID.randomUUID().toString());
2577 setThread(thread);
2578 }
2579
2580 private void updateThreadFromLastMessage() {
2581 if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2582 Message message = getLastVisibleMessage();
2583 if (message == null) {
2584 newThread();
2585 } else {
2586 if (conversation.getMode() == Conversation.MODE_MULTI) {
2587 if (activity == null || activity.xmppConnectionService == null) return;
2588 if (message.getStatus() < Message.STATUS_SEND) {
2589 if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
2590 }
2591 }
2592
2593 setThread(message.getThread());
2594 }
2595 }
2596 }
2597
2598 private String getLastVisibleMessageUuid() {
2599 Message message = getLastVisibleMessage();
2600 return message == null ? null : message.getUuid();
2601 }
2602
2603 private Message getLastVisibleMessage() {
2604 if (binding == null) {
2605 return null;
2606 }
2607 synchronized (this.messageList) {
2608 int pos = binding.messagesView.getLastVisiblePosition();
2609 if (pos >= 0) {
2610 Message message = null;
2611 for (int i = pos; i >= 0; --i) {
2612 try {
2613 message = (Message) binding.messagesView.getItemAtPosition(i);
2614 } catch (IndexOutOfBoundsException e) {
2615 // should not happen if we synchronize properly. however if that fails we
2616 // just gonna try item -1
2617 continue;
2618 }
2619 if (message.getType() != Message.TYPE_STATUS) {
2620 break;
2621 }
2622 }
2623 if (message != null) {
2624 while (message.next() != null && message.next().wasMergedIntoPrevious()) {
2625 message = message.next();
2626 }
2627 return message;
2628 }
2629 }
2630 }
2631 return null;
2632 }
2633
2634 private void openWith(final Message message) {
2635 if (message.isGeoUri()) {
2636 GeoHelper.view(getActivity(), message);
2637 } else {
2638 final DownloadableFile file =
2639 activity.xmppConnectionService.getFileBackend().getFile(message);
2640 ViewUtil.view(activity, file);
2641 }
2642 }
2643
2644 private void showErrorMessage(final Message message) {
2645 AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2646 builder.setTitle(R.string.error_message);
2647 final String errorMessage = message.getErrorMessage();
2648 final String[] errorMessageParts =
2649 errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2650 final String displayError;
2651 if (errorMessageParts.length == 2) {
2652 displayError = errorMessageParts[1];
2653 } else {
2654 displayError = errorMessage;
2655 }
2656 builder.setMessage(displayError);
2657 builder.setNegativeButton(
2658 R.string.copy_to_clipboard,
2659 (dialog, which) -> {
2660 activity.copyTextToClipboard(displayError, R.string.error_message);
2661 Toast.makeText(
2662 activity,
2663 R.string.error_message_copied_to_clipboard,
2664 Toast.LENGTH_SHORT)
2665 .show();
2666 });
2667 builder.setPositiveButton(R.string.confirm, null);
2668 builder.create().show();
2669 }
2670
2671 public boolean onInlineImageLongClicked(Cid cid) {
2672 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2673 if (f == null) return false;
2674
2675 saveAsSticker(f, null);
2676 return true;
2677 }
2678
2679 private void saveAsSticker(final Message m) {
2680 String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
2681 existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
2682 saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
2683 }
2684
2685 private void saveAsSticker(final File file, final String name) {
2686 savingAsSticker = file;
2687
2688 Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
2689 intent.addCategory(Intent.CATEGORY_OPENABLE);
2690 intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file)));
2691 intent.putExtra(Intent.EXTRA_TITLE, name);
2692
2693 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2694 final String dir = p.getString("sticker_directory", "Stickers");
2695 if (dir.startsWith("content://")) {
2696 intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
2697 } else {
2698 new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
2699 Uri uri;
2700 if (Build.VERSION.SDK_INT >= 29) {
2701 Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
2702 uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
2703 uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
2704 } else {
2705 uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
2706 }
2707 intent.putExtra("android.provider.extra.INITIAL_URI", uri);
2708 intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
2709 }
2710
2711 Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
2712 startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
2713 }
2714
2715 private void deleteFile(final Message message) {
2716 AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2717 builder.setNegativeButton(R.string.cancel, null);
2718 builder.setTitle(R.string.delete_file_dialog);
2719 builder.setMessage(R.string.delete_file_dialog_msg);
2720 builder.setPositiveButton(
2721 R.string.confirm,
2722 (dialog, which) -> {
2723 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2724 if (thumbs != null && !thumbs.isEmpty()) {
2725 for (Element thumb : thumbs) {
2726 Uri uri = Uri.parse(thumb.getAttribute("uri"));
2727 if (uri.getScheme().equals("cid")) {
2728 Cid cid = BobTransfer.cid(uri);
2729 if (cid == null) continue;
2730 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2731 activity.xmppConnectionService.evictPreview(f);
2732 f.delete();
2733 }
2734 }
2735 }
2736 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2737 activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
2738 activity.xmppConnectionService.updateMessage(message, false);
2739 activity.onConversationsListItemUpdated();
2740 refresh();
2741 }
2742 });
2743 builder.create().show();
2744 }
2745
2746 private void resendMessage(final Message message) {
2747 if (message.isFileOrImage()) {
2748 if (!(message.getConversation() instanceof Conversation)) {
2749 return;
2750 }
2751 final Conversation conversation = (Conversation) message.getConversation();
2752 final DownloadableFile file =
2753 activity.xmppConnectionService.getFileBackend().getFile(message);
2754 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2755 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2756 if (!message.hasFileOnRemoteHost()
2757 && xmppConnection != null
2758 && conversation.getMode() == Conversational.MODE_SINGLE
2759 && !xmppConnection
2760 .getFeatures()
2761 .httpUpload(message.getFileParams().getSize())) {
2762 activity.selectPresence(
2763 conversation,
2764 () -> {
2765 message.setCounterpart(conversation.getNextCounterpart());
2766 activity.xmppConnectionService.resendFailedMessages(message);
2767 new Handler()
2768 .post(
2769 () -> {
2770 int size = messageList.size();
2771 this.binding.messagesView.setSelection(
2772 size - 1);
2773 });
2774 });
2775 return;
2776 }
2777 } else if (!Compatibility.hasStoragePermission(getActivity())) {
2778 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2779 return;
2780 } else {
2781 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2782 message.setDeleted(true);
2783 activity.xmppConnectionService.updateMessage(message, false);
2784 activity.onConversationsListItemUpdated();
2785 refresh();
2786 return;
2787 }
2788 }
2789 activity.xmppConnectionService.resendFailedMessages(message);
2790 new Handler()
2791 .post(
2792 () -> {
2793 int size = messageList.size();
2794 this.binding.messagesView.setSelection(size - 1);
2795 });
2796 }
2797
2798 private void cancelTransmission(Message message) {
2799 Transferable transferable = message.getTransferable();
2800 if (transferable != null) {
2801 transferable.cancel();
2802 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2803 activity.xmppConnectionService.markMessage(
2804 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2805 }
2806 }
2807
2808 private void retryDecryption(Message message) {
2809 message.setEncryption(Message.ENCRYPTION_PGP);
2810 activity.onConversationsListItemUpdated();
2811 refresh();
2812 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2813 }
2814
2815 public void privateMessageWith(final Jid counterpart) {
2816 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2817 activity.xmppConnectionService.sendChatState(conversation);
2818 }
2819 this.binding.textinput.setText("");
2820 this.conversation.setNextCounterpart(counterpart);
2821 updateChatMsgHint();
2822 updateSendButton();
2823 updateEditablity();
2824 }
2825
2826 private void correctMessage(Message message) {
2827 while (message.mergeable(message.next())) {
2828 message = message.next();
2829 }
2830 setThread(message.getThread());
2831 conversation.setUserSelectedThread(true);
2832 this.conversation.setCorrectingMessage(message);
2833 final Editable editable = binding.textinput.getText();
2834 this.conversation.setDraftMessage(editable.toString());
2835 this.binding.textinput.setText("");
2836 this.binding.textinput.append(message.getBody());
2837 }
2838
2839 private void highlightInConference(String nick) {
2840 final Editable editable = this.binding.textinput.getText();
2841 String oldString = editable.toString().trim();
2842 final int pos = this.binding.textinput.getSelectionStart();
2843 if (oldString.isEmpty() || pos == 0) {
2844 editable.insert(0, nick + ": ");
2845 } else {
2846 final char before = editable.charAt(pos - 1);
2847 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2848 if (before == '\n') {
2849 editable.insert(pos, nick + ": ");
2850 } else {
2851 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2852 if (NickValidityChecker.check(
2853 conversation,
2854 Arrays.asList(
2855 editable.subSequence(0, pos - 2).toString().split(", ")))) {
2856 editable.insert(pos - 2, ", " + nick);
2857 return;
2858 }
2859 }
2860 editable.insert(
2861 pos,
2862 (Character.isWhitespace(before) ? "" : " ")
2863 + nick
2864 + (Character.isWhitespace(after) ? "" : " "));
2865 if (Character.isWhitespace(after)) {
2866 this.binding.textinput.setSelection(
2867 this.binding.textinput.getSelectionStart() + 1);
2868 }
2869 }
2870 }
2871 }
2872
2873 @Override
2874 public void startActivityForResult(Intent intent, int requestCode) {
2875 final Activity activity = getActivity();
2876 if (activity instanceof ConversationsActivity) {
2877 ((ConversationsActivity) activity).clearPendingViewIntent();
2878 }
2879 super.startActivityForResult(intent, requestCode);
2880 }
2881
2882 @Override
2883 public void onSaveInstanceState(@NotNull Bundle outState) {
2884 super.onSaveInstanceState(outState);
2885 if (conversation != null) {
2886 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2887 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2888 final Uri uri = pendingTakePhotoUri.peek();
2889 if (uri != null) {
2890 outState.putString(STATE_PHOTO_URI, uri.toString());
2891 }
2892 final ScrollState scrollState = getScrollPosition();
2893 if (scrollState != null) {
2894 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2895 }
2896 final ArrayList<Attachment> attachments =
2897 mediaPreviewAdapter == null
2898 ? new ArrayList<>()
2899 : mediaPreviewAdapter.getAttachments();
2900 if (attachments.size() > 0) {
2901 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2902 }
2903 }
2904 }
2905
2906 @Override
2907 public void onActivityCreated(Bundle savedInstanceState) {
2908 super.onActivityCreated(savedInstanceState);
2909 if (savedInstanceState == null) {
2910 return;
2911 }
2912 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2913 ArrayList<Attachment> attachments =
2914 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2915 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2916 if (uuid != null) {
2917 QuickLoader.set(uuid);
2918 this.pendingConversationsUuid.push(uuid);
2919 if (attachments != null && attachments.size() > 0) {
2920 this.pendingMediaPreviews.push(attachments);
2921 }
2922 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2923 if (takePhotoUri != null) {
2924 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2925 }
2926 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2927 }
2928 }
2929
2930 @Override
2931 public void onStart() {
2932 super.onStart();
2933 if (this.reInitRequiredOnStart && this.conversation != null) {
2934 final Bundle extras = pendingExtras.pop();
2935 reInit(this.conversation, extras != null);
2936 if (extras != null) {
2937 processExtras(extras);
2938 }
2939 } else if (conversation == null
2940 && activity != null
2941 && activity.xmppConnectionService != null) {
2942 final String uuid = pendingConversationsUuid.pop();
2943 Log.d(
2944 Config.LOGTAG,
2945 "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
2946 + uuid);
2947 if (uuid != null) {
2948 findAndReInitByUuidOrArchive(uuid);
2949 }
2950 }
2951 }
2952
2953 @Override
2954 public void onStop() {
2955 super.onStop();
2956 final Activity activity = getActivity();
2957 messageListAdapter.unregisterListenerInAudioPlayer();
2958 if (activity == null || !activity.isChangingConfigurations()) {
2959 hideSoftKeyboard(activity);
2960 messageListAdapter.stopAudioPlayer();
2961 }
2962 if (this.conversation != null) {
2963 final String msg = this.binding.textinput.getText().toString();
2964 storeNextMessage(msg);
2965 updateChatState(this.conversation, msg);
2966 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2967 }
2968 this.reInitRequiredOnStart = true;
2969 if (emojiPopup != null) emojiPopup.dismiss();
2970 }
2971
2972 private void updateChatState(final Conversation conversation, final String msg) {
2973 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2974 Account.State status = conversation.getAccount().getStatus();
2975 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2976 activity.xmppConnectionService.sendChatState(conversation);
2977 }
2978 }
2979
2980 private void saveMessageDraftStopAudioPlayer() {
2981 final Conversation previousConversation = this.conversation;
2982 if (this.activity == null || this.binding == null || previousConversation == null) {
2983 return;
2984 }
2985 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2986 final String msg = this.binding.textinput.getText().toString();
2987 storeNextMessage(msg);
2988 updateChatState(this.conversation, msg);
2989 messageListAdapter.stopAudioPlayer();
2990 mediaPreviewAdapter.clearPreviews();
2991 toggleInputMethod();
2992 }
2993
2994 public void reInit(final Conversation conversation, final Bundle extras) {
2995 QuickLoader.set(conversation.getUuid());
2996 final boolean changedConversation = this.conversation != conversation;
2997 if (changedConversation) {
2998 this.saveMessageDraftStopAudioPlayer();
2999 }
3000 this.clearPending();
3001 if (this.reInit(conversation, extras != null)) {
3002 if (extras != null) {
3003 processExtras(extras);
3004 }
3005 this.reInitRequiredOnStart = false;
3006 } else {
3007 this.reInitRequiredOnStart = true;
3008 pendingExtras.push(extras);
3009 }
3010 resetUnreadMessagesCount();
3011 }
3012
3013 private void reInit(Conversation conversation) {
3014 reInit(conversation, false);
3015 }
3016
3017 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
3018 if (conversation == null) {
3019 return false;
3020 }
3021 final Conversation originalConversation = this.conversation;
3022 this.conversation = conversation;
3023 // once we set the conversation all is good and it will automatically do the right thing in
3024 // onStart()
3025 if (this.activity == null || this.binding == null) {
3026 return false;
3027 }
3028
3029 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3030 activity.onConversationArchived(this.conversation);
3031 return false;
3032 }
3033
3034 setThread(conversation.getThread());
3035 setupReply(conversation.getReplyTo());
3036
3037 stopScrolling();
3038 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3039
3040 if (this.conversation.isRead() && hasExtras) {
3041 Log.d(Config.LOGTAG, "trimming conversation");
3042 this.conversation.trim();
3043 }
3044
3045 setupIme();
3046
3047 final boolean scrolledToBottomAndNoPending =
3048 this.scrolledToBottom() && pendingScrollState.peek() == null;
3049
3050 this.binding.textSendButton.setContentDescription(
3051 activity.getString(R.string.send_message_to_x, conversation.getName()));
3052 this.binding.textinput.setKeyboardListener(null);
3053 final boolean participating =
3054 conversation.getMode() == Conversational.MODE_SINGLE
3055 || conversation.getMucOptions().participating();
3056 if (participating) {
3057 this.binding.textinput.setText(this.conversation.getNextMessage());
3058 this.binding.textinput.setSelection(this.binding.textinput.length());
3059 } else {
3060 this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3061 }
3062 this.binding.textinput.setKeyboardListener(this);
3063 messageListAdapter.updatePreferences();
3064 refresh(false);
3065 activity.invalidateOptionsMenu();
3066 this.conversation.messagesLoaded.set(true);
3067 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3068
3069 if (hasExtras || scrolledToBottomAndNoPending) {
3070 resetUnreadMessagesCount();
3071 synchronized (this.messageList) {
3072 Log.d(Config.LOGTAG, "jump to first unread message");
3073 final Message first = conversation.getFirstUnreadMessage();
3074 final int bottom = Math.max(0, this.messageList.size() - 1);
3075 final int pos;
3076 final boolean jumpToBottom;
3077 if (first == null) {
3078 pos = bottom;
3079 jumpToBottom = true;
3080 } else {
3081 int i = getIndexOf(first.getUuid(), this.messageList);
3082 pos = i < 0 ? bottom : i;
3083 jumpToBottom = false;
3084 }
3085 setSelection(pos, jumpToBottom);
3086 }
3087 }
3088
3089 this.binding.messagesView.post(this::fireReadEvent);
3090 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3091 // layout which might be unnecessary since we can *see* it
3092 activity.xmppConnectionService
3093 .getNotificationService()
3094 .setOpenConversation(this.conversation);
3095
3096 if (commandAdapter != null && conversation != originalConversation) {
3097 commandAdapter.clear();
3098 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3099 refreshCommands(false);
3100 }
3101 if (commandAdapter == null && conversation != null) {
3102 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3103 commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3104 binding.commandsView.setAdapter(commandAdapter);
3105 binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3106 if (activity == null) return;
3107
3108 final Element command = commandAdapter.getItem(position);
3109 activity.startCommand(ConversationFragment.this.conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
3110 });
3111 refreshCommands(false);
3112 }
3113
3114 return true;
3115 }
3116
3117 public void refreshForNewCaps() {
3118 refreshCommands(true);
3119 }
3120
3121 protected void refreshCommands(boolean delayShow) {
3122 if (commandAdapter == null) return;
3123
3124 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3125 if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3126 commandJid = conversation.getJid().asBareJid();
3127 }
3128 if (commandJid == null && conversation.getJid().isDomainJid()) {
3129 commandJid = conversation.getJid();
3130 }
3131 if (commandJid == null) {
3132 conversation.hideViewPager();
3133 } else {
3134 if (!delayShow) conversation.showViewPager();
3135 binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3136 activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
3137 if (activity == null) return;
3138
3139 activity.runOnUiThread(() -> {
3140 if (iq.getType() == IqPacket.TYPE.RESULT) {
3141 binding.commandsViewProgressbar.setVisibility(View.GONE);
3142 commandAdapter.clear();
3143 for (Element child : iq.query().getChildren()) {
3144 if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3145 commandAdapter.add(child);
3146 }
3147 }
3148
3149 if (commandAdapter.getCount() < 1) {
3150 conversation.hideViewPager();
3151 } else if (delayShow) {
3152 conversation.showViewPager();
3153 }
3154 });
3155 });
3156 }
3157 }
3158
3159 private void resetUnreadMessagesCount() {
3160 lastMessageUuid = null;
3161 hideUnreadMessagesCount();
3162 }
3163
3164 private void hideUnreadMessagesCount() {
3165 if (this.binding == null) {
3166 return;
3167 }
3168 this.binding.scrollToBottomButton.setEnabled(false);
3169 this.binding.scrollToBottomButton.hide();
3170 this.binding.unreadCountCustomView.setVisibility(View.GONE);
3171 }
3172
3173 private void setSelection(int pos, boolean jumpToBottom) {
3174 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3175 this.binding.messagesView.post(
3176 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3177 this.binding.messagesView.post(this::fireReadEvent);
3178 }
3179
3180 private boolean scrolledToBottom() {
3181 return this.binding != null && scrolledToBottom(this.binding.messagesView);
3182 }
3183
3184 private void processExtras(final Bundle extras) {
3185 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3186 final String text = extras.getString(Intent.EXTRA_TEXT);
3187 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3188 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3189 final String postInitAction =
3190 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3191 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3192 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3193 final boolean doNotAppend =
3194 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3195 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3196 final List<Uri> uris = extractUris(extras);
3197 if (uris != null && uris.size() > 0) {
3198 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3199 mediaPreviewAdapter.addMediaPreviews(
3200 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3201 } else {
3202 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3203 mediaPreviewAdapter.addMediaPreviews(
3204 Attachment.of(getActivity(), cleanedUris, type));
3205 }
3206 toggleInputMethod();
3207 return;
3208 }
3209 if (nick != null) {
3210 if (pm) {
3211 Jid jid = conversation.getJid();
3212 try {
3213 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3214 privateMessageWith(next);
3215 } catch (final IllegalArgumentException ignored) {
3216 // do nothing
3217 }
3218 } else {
3219 final MucOptions mucOptions = conversation.getMucOptions();
3220 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3221 highlightInConference(nick);
3222 }
3223 }
3224 } else {
3225 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3226 mediaPreviewAdapter.addMediaPreviews(
3227 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3228 toggleInputMethod();
3229 return;
3230 } else if (text != null && asQuote) {
3231 quoteText(text);
3232 } else {
3233 appendText(text, doNotAppend);
3234 }
3235 }
3236 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3237 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3238 return;
3239 }
3240 if ("call".equals(postInitAction)) {
3241 checkPermissionAndTriggerAudioCall();
3242 }
3243 if ("message".equals(postInitAction)) {
3244 binding.conversationViewPager.post(() -> {
3245 binding.conversationViewPager.setCurrentItem(0);
3246 });
3247 }
3248 if ("command".equals(postInitAction)) {
3249 binding.conversationViewPager.post(() -> {
3250 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3251 if (adapter != null && adapter.getCount() > 1) {
3252 binding.conversationViewPager.setCurrentItem(1);
3253 }
3254 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3255 Jid commandJid = null;
3256 if (jid != null) {
3257 try {
3258 commandJid = Jid.of(jid);
3259 } catch (final IllegalArgumentException e) { }
3260 }
3261 if (commandJid == null || !commandJid.isFullJid()) {
3262 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3263 if (discoJid != null) commandJid = discoJid;
3264 }
3265 if (node != null && commandJid != null) {
3266 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3267 }
3268 });
3269 return;
3270 }
3271 Message message =
3272 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3273 if ("webxdc".equals(postInitAction)) {
3274 if (message == null) {
3275 message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3276 }
3277 if (message == null) return;
3278
3279 Cid webxdcCid = message.getFileParams().getCids().get(0);
3280 WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
3281 Conversation conversation = (Conversation) message.getConversation();
3282 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3283 conversation.startWebxdc(webxdc);
3284 }
3285 }
3286 if (message != null) {
3287 startDownloadable(message);
3288 }
3289 if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3290 if (!conversation.switchToSession("jabber:iq:register")) {
3291 conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3292 }
3293 }
3294 }
3295
3296 private Element commandFor(final Jid jid, final String node) {
3297 if (commandAdapter != null) {
3298 for (int i = 0; i < commandAdapter.getCount(); i++) {
3299 Element command = commandAdapter.getItem(i);
3300 final String commandNode = command.getAttribute("node");
3301 if (commandNode == null || !commandNode.equals(node)) continue;
3302
3303 final Jid commandJid = command.getAttributeAsJid("jid");
3304 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3305
3306 return command;
3307 }
3308 }
3309
3310 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3311 }
3312
3313 private List<Uri> extractUris(final Bundle extras) {
3314 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3315 if (uris != null) {
3316 return uris;
3317 }
3318 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3319 if (uri != null) {
3320 return Collections.singletonList(uri);
3321 } else {
3322 return null;
3323 }
3324 }
3325
3326 private List<Uri> cleanUris(final List<Uri> uris) {
3327 final Iterator<Uri> iterator = uris.iterator();
3328 while (iterator.hasNext()) {
3329 final Uri uri = iterator.next();
3330 if (FileBackend.weOwnFile(uri)) {
3331 iterator.remove();
3332 Toast.makeText(
3333 getActivity(),
3334 R.string.security_violation_not_attaching_file,
3335 Toast.LENGTH_SHORT)
3336 .show();
3337 }
3338 }
3339 return uris;
3340 }
3341
3342 private boolean showBlockSubmenu(View view) {
3343 final Jid jid = conversation.getJid();
3344 final boolean showReject =
3345 !conversation.isWithStranger()
3346 && conversation
3347 .getContact()
3348 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3349 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3350 popupMenu.inflate(R.menu.block);
3351 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3352 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3353 popupMenu.setOnMenuItemClickListener(
3354 menuItem -> {
3355 Blockable blockable;
3356 switch (menuItem.getItemId()) {
3357 case R.id.reject:
3358 activity.xmppConnectionService.stopPresenceUpdatesTo(
3359 conversation.getContact());
3360 updateSnackBar(conversation);
3361 return true;
3362 case R.id.block_domain:
3363 blockable =
3364 conversation
3365 .getAccount()
3366 .getRoster()
3367 .getContact(jid.getDomain());
3368 break;
3369 default:
3370 blockable = conversation;
3371 }
3372 BlockContactDialog.show(activity, blockable);
3373 return true;
3374 });
3375 popupMenu.show();
3376 return true;
3377 }
3378
3379 private void updateSnackBar(final Conversation conversation) {
3380 final Account account = conversation.getAccount();
3381 final XmppConnection connection = account.getXmppConnection();
3382 final int mode = conversation.getMode();
3383 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3384 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3385 return;
3386 }
3387 if (account.getStatus() == Account.State.DISABLED) {
3388 showSnackbar(
3389 R.string.this_account_is_disabled,
3390 R.string.enable,
3391 this.mEnableAccountListener);
3392 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3393 showSnackbar(R.string.this_account_is_logged_out,R.string.log_in,this.mEnableAccountListener);
3394 } else if (conversation.isBlocked()) {
3395 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3396 } else if (contact != null
3397 && !contact.showInRoster()
3398 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3399 showSnackbar(
3400 R.string.contact_added_you,
3401 R.string.add_back,
3402 this.mAddBackClickListener,
3403 this.mLongPressBlockListener);
3404 } else if (contact != null
3405 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3406 showSnackbar(
3407 R.string.contact_asks_for_presence_subscription,
3408 R.string.allow,
3409 this.mAllowPresenceSubscription,
3410 this.mLongPressBlockListener);
3411 } else if (mode == Conversation.MODE_MULTI
3412 && !conversation.getMucOptions().online()
3413 && account.getStatus() == Account.State.ONLINE) {
3414 switch (conversation.getMucOptions().getError()) {
3415 case NICK_IN_USE:
3416 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3417 break;
3418 case NO_RESPONSE:
3419 showSnackbar(R.string.joining_conference, 0, null);
3420 break;
3421 case SERVER_NOT_FOUND:
3422 if (conversation.receivedMessagesCount() > 0) {
3423 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3424 } else {
3425 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3426 }
3427 break;
3428 case REMOTE_SERVER_TIMEOUT:
3429 if (conversation.receivedMessagesCount() > 0) {
3430 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3431 } else {
3432 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3433 }
3434 break;
3435 case PASSWORD_REQUIRED:
3436 showSnackbar(
3437 R.string.conference_requires_password,
3438 R.string.enter_password,
3439 enterPassword);
3440 break;
3441 case BANNED:
3442 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3443 break;
3444 case MEMBERS_ONLY:
3445 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3446 break;
3447 case RESOURCE_CONSTRAINT:
3448 showSnackbar(
3449 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3450 break;
3451 case KICKED:
3452 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3453 break;
3454 case TECHNICAL_PROBLEMS:
3455 showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3456 break;
3457 case UNKNOWN:
3458 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3459 break;
3460 case INVALID_NICK:
3461 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3462 case SHUTDOWN:
3463 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3464 break;
3465 case DESTROYED:
3466 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3467 break;
3468 case NON_ANONYMOUS:
3469 showSnackbar(
3470 R.string.group_chat_will_make_your_jabber_id_public,
3471 R.string.join,
3472 acceptJoin);
3473 break;
3474 default:
3475 hideSnackbar();
3476 break;
3477 }
3478 } else if (account.hasPendingPgpIntent(conversation)) {
3479 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3480 } else if (connection != null
3481 && connection.getFeatures().blocking()
3482 && conversation.countMessages() != 0
3483 && !conversation.isBlocked()
3484 && conversation.isWithStranger()) {
3485 showSnackbar(
3486 R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
3487 } else {
3488 hideSnackbar();
3489 }
3490 }
3491
3492 @Override
3493 public void refresh() {
3494 if (this.binding == null) {
3495 Log.d(
3496 Config.LOGTAG,
3497 "ConversationFragment.refresh() skipped updated because view binding was null");
3498 return;
3499 }
3500 if (this.conversation != null
3501 && this.activity != null
3502 && this.activity.xmppConnectionService != null) {
3503 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3504 activity.onConversationArchived(this.conversation);
3505 return;
3506 }
3507 }
3508 this.refresh(true);
3509 }
3510
3511 private void refresh(boolean notifyConversationRead) {
3512 synchronized (this.messageList) {
3513 if (this.conversation != null) {
3514 if (messageListAdapter.hasSelection()) {
3515 if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3516 } else {
3517 conversation.populateWithMessages(this.messageList);
3518 updateStatusMessages();
3519 this.messageListAdapter.notifyDataSetChanged();
3520 }
3521 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3522 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3523 binding.unreadCountCustomView.setUnreadCount(
3524 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3525 }
3526 updateSnackBar(conversation);
3527 if (activity != null) updateChatMsgHint();
3528 if (notifyConversationRead && activity != null) {
3529 binding.messagesView.post(this::fireReadEvent);
3530 }
3531 updateSendButton();
3532 updateEditablity();
3533 conversation.refreshSessions();
3534 }
3535 }
3536 }
3537
3538 protected void messageSent() {
3539 setThread(null);
3540 conversation.setUserSelectedThread(false);
3541 mSendingPgpMessage.set(false);
3542 this.binding.textinput.setText("");
3543 if (conversation.setCorrectingMessage(null)) {
3544 this.binding.textinput.append(conversation.getDraftMessage());
3545 conversation.setDraftMessage(null);
3546 }
3547 storeNextMessage();
3548 updateChatMsgHint();
3549 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3550 final boolean prefScrollToBottom =
3551 p.getBoolean(
3552 "scroll_to_bottom",
3553 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3554 if (prefScrollToBottom || scrolledToBottom()) {
3555 new Handler()
3556 .post(
3557 () -> {
3558 int size = messageList.size();
3559 this.binding.messagesView.setSelection(size - 1);
3560 });
3561 }
3562 }
3563
3564 private boolean storeNextMessage() {
3565 return storeNextMessage(this.binding.textinput.getText().toString());
3566 }
3567
3568 private boolean storeNextMessage(String msg) {
3569 final boolean participating =
3570 conversation.getMode() == Conversational.MODE_SINGLE
3571 || conversation.getMucOptions().participating();
3572 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3573 && participating
3574 && this.conversation.setNextMessage(msg)) {
3575 this.activity.xmppConnectionService.updateConversation(this.conversation);
3576 return true;
3577 }
3578 return false;
3579 }
3580
3581 public void doneSendingPgpMessage() {
3582 mSendingPgpMessage.set(false);
3583 }
3584
3585 public long getMaxHttpUploadSize(Conversation conversation) {
3586 final XmppConnection connection = conversation.getAccount().getXmppConnection();
3587 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3588 }
3589
3590 private boolean canWrite() {
3591 return
3592 this.conversation.getMode() == Conversation.MODE_SINGLE
3593 || this.conversation.getMucOptions().participating()
3594 || this.conversation.getNextCounterpart() != null;
3595 }
3596
3597 private void updateEditablity() {
3598 boolean canWrite = canWrite();
3599 this.binding.textinput.setFocusable(canWrite);
3600 this.binding.textinput.setFocusableInTouchMode(canWrite);
3601 this.binding.textSendButton.setEnabled(canWrite);
3602 this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
3603 this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
3604 this.binding.textinput.setCursorVisible(canWrite);
3605 this.binding.textinput.setEnabled(canWrite);
3606 }
3607
3608 public void updateSendButton() {
3609 boolean hasAttachments =
3610 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3611 final Conversation c = this.conversation;
3612 final Presence.Status status;
3613 final String text =
3614 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3615 final SendButtonAction action;
3616 if (hasAttachments) {
3617 action = SendButtonAction.TEXT;
3618 } else {
3619 action = SendButtonTool.getAction(getActivity(), c, text);
3620 }
3621 if (c.getAccount().getStatus() == Account.State.ONLINE) {
3622 if (activity != null
3623 && activity.xmppConnectionService != null
3624 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3625 status = Presence.Status.OFFLINE;
3626 } else if (c.getMode() == Conversation.MODE_SINGLE) {
3627 status = c.getContact().getShownStatus();
3628 } else {
3629 status =
3630 c.getMucOptions().online()
3631 ? Presence.Status.ONLINE
3632 : Presence.Status.OFFLINE;
3633 }
3634 } else {
3635 status = Presence.Status.OFFLINE;
3636 }
3637 this.binding.textSendButton.setTag(action);
3638 final Activity activity = getActivity();
3639 if (activity != null) {
3640 this.binding.textSendButton.setImageResource(
3641 SendButtonTool.getSendButtonImageResource(activity, action, status));
3642 }
3643
3644 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3645 if (identiconWidth < 0) identiconWidth = params.width;
3646 if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
3647 binding.conversationViewPager.setCurrentItem(0);
3648 params.width = conversation.getThread() == null ? 0 : identiconWidth;
3649 } else {
3650 params.width = identiconWidth;
3651 }
3652 if (!canWrite()) params.width = 0;
3653 binding.threadIdenticonLayout.setLayoutParams(params);
3654 }
3655
3656 protected void updateStatusMessages() {
3657 DateSeparator.addAll(this.messageList);
3658 if (showLoadMoreMessages(conversation)) {
3659 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3660 }
3661 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3662 ChatState state = conversation.getIncomingChatState();
3663 if (state == ChatState.COMPOSING) {
3664 this.messageList.add(
3665 Message.createStatusMessage(
3666 conversation,
3667 getString(R.string.contact_is_typing, conversation.getName())));
3668 } else if (state == ChatState.PAUSED) {
3669 this.messageList.add(
3670 Message.createStatusMessage(
3671 conversation,
3672 getString(
3673 R.string.contact_has_stopped_typing,
3674 conversation.getName())));
3675 } else {
3676 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3677 final Message message = this.messageList.get(i);
3678 if (message.getType() != Message.TYPE_STATUS) {
3679 if (message.getStatus() == Message.STATUS_RECEIVED) {
3680 return;
3681 } else {
3682 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3683 this.messageList.add(
3684 i + 1,
3685 Message.createStatusMessage(
3686 conversation,
3687 getString(
3688 R.string.contact_has_read_up_to_this_point,
3689 conversation.getName())));
3690 return;
3691 }
3692 }
3693 }
3694 }
3695 }
3696 } else {
3697 final MucOptions mucOptions = conversation.getMucOptions();
3698 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3699 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3700 ChatState state = ChatState.COMPOSING;
3701 List<MucOptions.User> users =
3702 conversation.getMucOptions().getUsersWithChatState(state, 5);
3703 if (users.size() == 0) {
3704 state = ChatState.PAUSED;
3705 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3706 }
3707 if (mucOptions.isPrivateAndNonAnonymous()) {
3708 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3709 final Set<ReadByMarker> markersForMessage =
3710 messageList.get(i).getReadByMarkers();
3711 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3712 for (ReadByMarker marker : markersForMessage) {
3713 if (!ReadByMarker.contains(marker, addedMarkers)) {
3714 addedMarkers.add(
3715 marker); // may be put outside this condition. set should do
3716 // dedup anyway
3717 MucOptions.User user = mucOptions.findUser(marker);
3718 if (user != null && !users.contains(user)) {
3719 shownMarkers.add(user);
3720 }
3721 }
3722 }
3723 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3724 final Message statusMessage;
3725 final int size = shownMarkers.size();
3726 if (size > 1) {
3727 final String body;
3728 if (size <= 4) {
3729 body =
3730 getString(
3731 R.string.contacts_have_read_up_to_this_point,
3732 UIHelper.concatNames(shownMarkers));
3733 } else if (ReadByMarker.allUsersRepresented(
3734 allUsers, markersForMessage, markerForSender)) {
3735 body = getString(R.string.everyone_has_read_up_to_this_point);
3736 } else {
3737 body =
3738 getString(
3739 R.string.contacts_and_n_more_have_read_up_to_this_point,
3740 UIHelper.concatNames(shownMarkers, 3),
3741 size - 3);
3742 }
3743 statusMessage = Message.createStatusMessage(conversation, body);
3744 statusMessage.setCounterparts(shownMarkers);
3745 } else if (size == 1) {
3746 statusMessage =
3747 Message.createStatusMessage(
3748 conversation,
3749 getString(
3750 R.string.contact_has_read_up_to_this_point,
3751 UIHelper.getDisplayName(shownMarkers.get(0))));
3752 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3753 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3754 } else {
3755 statusMessage = null;
3756 }
3757 if (statusMessage != null) {
3758 this.messageList.add(i + 1, statusMessage);
3759 }
3760 addedMarkers.add(markerForSender);
3761 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3762 break;
3763 }
3764 }
3765 }
3766 if (users.size() > 0) {
3767 Message statusMessage;
3768 if (users.size() == 1) {
3769 MucOptions.User user = users.get(0);
3770 int id =
3771 state == ChatState.COMPOSING
3772 ? R.string.contact_is_typing
3773 : R.string.contact_has_stopped_typing;
3774 statusMessage =
3775 Message.createStatusMessage(
3776 conversation, getString(id, UIHelper.getDisplayName(user)));
3777 statusMessage.setTrueCounterpart(user.getRealJid());
3778 statusMessage.setCounterpart(user.getFullJid());
3779 } else {
3780 int id =
3781 state == ChatState.COMPOSING
3782 ? R.string.contacts_are_typing
3783 : R.string.contacts_have_stopped_typing;
3784 statusMessage =
3785 Message.createStatusMessage(
3786 conversation, getString(id, UIHelper.concatNames(users)));
3787 statusMessage.setCounterparts(users);
3788 }
3789 this.messageList.add(statusMessage);
3790 }
3791 }
3792 }
3793
3794 private void stopScrolling() {
3795 long now = SystemClock.uptimeMillis();
3796 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3797 binding.messagesView.dispatchTouchEvent(cancel);
3798 }
3799
3800 private boolean showLoadMoreMessages(final Conversation c) {
3801 if (activity == null || activity.xmppConnectionService == null) {
3802 return false;
3803 }
3804 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3805 final MessageArchiveService service =
3806 activity.xmppConnectionService.getMessageArchiveService();
3807 return mam
3808 && (c.getLastClearHistory().getTimestamp() != 0
3809 || (c.countMessages() == 0
3810 && c.messagesLoaded.get()
3811 && c.hasMessagesLeftOnServer()
3812 && !service.queryInProgress(c)));
3813 }
3814
3815 private boolean hasMamSupport(final Conversation c) {
3816 if (c.getMode() == Conversation.MODE_SINGLE) {
3817 final XmppConnection connection = c.getAccount().getXmppConnection();
3818 return connection != null && connection.getFeatures().mam();
3819 } else {
3820 return c.getMucOptions().mamSupport();
3821 }
3822 }
3823
3824 protected void showSnackbar(
3825 final int message, final int action, final OnClickListener clickListener) {
3826 showSnackbar(message, action, clickListener, null);
3827 }
3828
3829 protected void showSnackbar(
3830 final int message,
3831 final int action,
3832 final OnClickListener clickListener,
3833 final View.OnLongClickListener longClickListener) {
3834 this.binding.snackbar.setVisibility(View.VISIBLE);
3835 this.binding.snackbar.setOnClickListener(null);
3836 this.binding.snackbarMessage.setText(message);
3837 this.binding.snackbarMessage.setOnClickListener(null);
3838 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3839 if (action != 0) {
3840 this.binding.snackbarAction.setText(action);
3841 }
3842 this.binding.snackbarAction.setOnClickListener(clickListener);
3843 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3844 }
3845
3846 protected void hideSnackbar() {
3847 this.binding.snackbar.setVisibility(View.GONE);
3848 }
3849
3850 protected void sendMessage(Message message) {
3851 new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
3852 messageSent();
3853 }
3854
3855 protected void sendPgpMessage(final Message message) {
3856 final XmppConnectionService xmppService = activity.xmppConnectionService;
3857 final Contact contact = message.getConversation().getContact();
3858 if (!activity.hasPgp()) {
3859 activity.showInstallPgpDialog();
3860 return;
3861 }
3862 if (conversation.getAccount().getPgpSignature() == null) {
3863 activity.announcePgp(
3864 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3865 return;
3866 }
3867 if (!mSendingPgpMessage.compareAndSet(false, true)) {
3868 Log.d(Config.LOGTAG, "sending pgp message already in progress");
3869 }
3870 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3871 if (contact.getPgpKeyId() != 0) {
3872 xmppService
3873 .getPgpEngine()
3874 .hasKey(
3875 contact,
3876 new UiCallback<Contact>() {
3877
3878 @Override
3879 public void userInputRequired(
3880 PendingIntent pi, Contact contact) {
3881 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3882 }
3883
3884 @Override
3885 public void success(Contact contact) {
3886 encryptTextMessage(message);
3887 }
3888
3889 @Override
3890 public void error(int error, Contact contact) {
3891 activity.runOnUiThread(
3892 () ->
3893 Toast.makeText(
3894 activity,
3895 R.string
3896 .unable_to_connect_to_keychain,
3897 Toast.LENGTH_SHORT)
3898 .show());
3899 mSendingPgpMessage.set(false);
3900 }
3901 });
3902
3903 } else {
3904 showNoPGPKeyDialog(
3905 false,
3906 (dialog, which) -> {
3907 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3908 xmppService.updateConversation(conversation);
3909 message.setEncryption(Message.ENCRYPTION_NONE);
3910 xmppService.sendMessage(message);
3911 messageSent();
3912 });
3913 }
3914 } else {
3915 if (conversation.getMucOptions().pgpKeysInUse()) {
3916 if (!conversation.getMucOptions().everybodyHasKeys()) {
3917 Toast warning =
3918 Toast.makeText(
3919 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3920 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3921 warning.show();
3922 }
3923 encryptTextMessage(message);
3924 } else {
3925 showNoPGPKeyDialog(
3926 true,
3927 (dialog, which) -> {
3928 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3929 message.setEncryption(Message.ENCRYPTION_NONE);
3930 xmppService.updateConversation(conversation);
3931 xmppService.sendMessage(message);
3932 messageSent();
3933 });
3934 }
3935 }
3936 }
3937
3938 public void encryptTextMessage(Message message) {
3939 activity.xmppConnectionService
3940 .getPgpEngine()
3941 .encrypt(
3942 message,
3943 new UiCallback<Message>() {
3944
3945 @Override
3946 public void userInputRequired(PendingIntent pi, Message message) {
3947 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3948 }
3949
3950 @Override
3951 public void success(Message message) {
3952 // TODO the following two call can be made before the callback
3953 getActivity().runOnUiThread(() -> messageSent());
3954 }
3955
3956 @Override
3957 public void error(final int error, Message message) {
3958 getActivity()
3959 .runOnUiThread(
3960 () -> {
3961 doneSendingPgpMessage();
3962 Toast.makeText(
3963 getActivity(),
3964 error == 0
3965 ? R.string
3966 .unable_to_connect_to_keychain
3967 : error,
3968 Toast.LENGTH_SHORT)
3969 .show();
3970 });
3971 }
3972 });
3973 }
3974
3975 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3976 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3977 builder.setIconAttribute(android.R.attr.alertDialogIcon);
3978 if (plural) {
3979 builder.setTitle(getString(R.string.no_pgp_keys));
3980 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3981 } else {
3982 builder.setTitle(getString(R.string.no_pgp_key));
3983 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3984 }
3985 builder.setNegativeButton(getString(R.string.cancel), null);
3986 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3987 builder.create().show();
3988 }
3989
3990 public void appendText(String text, final boolean doNotAppend) {
3991 if (text == null) {
3992 return;
3993 }
3994 final Editable editable = this.binding.textinput.getText();
3995 String previous = editable == null ? "" : editable.toString();
3996 if (doNotAppend && !TextUtils.isEmpty(previous)) {
3997 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3998 .show();
3999 return;
4000 }
4001 if (UIHelper.isLastLineQuote(previous)) {
4002 text = '\n' + text;
4003 } else if (previous.length() != 0
4004 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4005 text = " " + text;
4006 }
4007 this.binding.textinput.append(text);
4008 }
4009
4010 @Override
4011 public boolean onEnterPressed(final boolean isCtrlPressed) {
4012 if (isCtrlPressed || enterIsSend()) {
4013 sendMessage();
4014 return true;
4015 }
4016 return false;
4017 }
4018
4019 private boolean enterIsSend() {
4020 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4021 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4022 }
4023
4024 public boolean onArrowUpCtrlPressed() {
4025 final Message lastEditableMessage =
4026 conversation == null ? null : conversation.getLastEditableMessage();
4027 if (lastEditableMessage != null) {
4028 correctMessage(lastEditableMessage);
4029 return true;
4030 } else {
4031 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4032 .show();
4033 return false;
4034 }
4035 }
4036
4037 @Override
4038 public void onTypingStarted() {
4039 final XmppConnectionService service =
4040 activity == null ? null : activity.xmppConnectionService;
4041 if (service == null) {
4042 return;
4043 }
4044 final Account.State status = conversation.getAccount().getStatus();
4045 if (status == Account.State.ONLINE
4046 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4047 service.sendChatState(conversation);
4048 }
4049 runOnUiThread(this::updateSendButton);
4050 }
4051
4052 @Override
4053 public void onTypingStopped() {
4054 final XmppConnectionService service =
4055 activity == null ? null : activity.xmppConnectionService;
4056 if (service == null) {
4057 return;
4058 }
4059 final Account.State status = conversation.getAccount().getStatus();
4060 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4061 service.sendChatState(conversation);
4062 }
4063 }
4064
4065 @Override
4066 public void onTextDeleted() {
4067 final XmppConnectionService service =
4068 activity == null ? null : activity.xmppConnectionService;
4069 if (service == null) {
4070 return;
4071 }
4072 final Account.State status = conversation.getAccount().getStatus();
4073 if (status == Account.State.ONLINE
4074 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4075 service.sendChatState(conversation);
4076 }
4077 if (storeNextMessage()) {
4078 runOnUiThread(
4079 () -> {
4080 if (activity == null) {
4081 return;
4082 }
4083 activity.onConversationsListItemUpdated();
4084 });
4085 }
4086 runOnUiThread(this::updateSendButton);
4087 }
4088
4089 @Override
4090 public void onTextChanged() {
4091 if (conversation != null && conversation.getCorrectingMessage() != null) {
4092 runOnUiThread(this::updateSendButton);
4093 }
4094 }
4095
4096 @Override
4097 public boolean onTabPressed(boolean repeated) {
4098 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4099 return false;
4100 }
4101 if (repeated) {
4102 completionIndex++;
4103 } else {
4104 lastCompletionLength = 0;
4105 completionIndex = 0;
4106 final String content = this.binding.textinput.getText().toString();
4107 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4108 int start =
4109 lastCompletionCursor > 0
4110 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4111 : 0;
4112 firstWord = start == 0;
4113 incomplete = content.substring(start, lastCompletionCursor);
4114 }
4115 List<String> completions = new ArrayList<>();
4116 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4117 String name = user.getNick();
4118 if (name != null && name.startsWith(incomplete)) {
4119 completions.add(name + (firstWord ? ": " : " "));
4120 }
4121 }
4122 Collections.sort(completions);
4123 if (completions.size() > completionIndex) {
4124 String completion = completions.get(completionIndex).substring(incomplete.length());
4125 this.binding
4126 .textinput
4127 .getEditableText()
4128 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4129 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4130 lastCompletionLength = completion.length();
4131 } else {
4132 completionIndex = -1;
4133 this.binding
4134 .textinput
4135 .getEditableText()
4136 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4137 lastCompletionLength = 0;
4138 }
4139 return true;
4140 }
4141
4142 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4143 try {
4144 getActivity()
4145 .startIntentSenderForResult(
4146 pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
4147 } catch (final SendIntentException ignored) {
4148 }
4149 }
4150
4151 @Override
4152 public void onBackendConnected() {
4153 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4154 setupEmojiSearch();
4155 String uuid = pendingConversationsUuid.pop();
4156 if (uuid != null) {
4157 if (!findAndReInitByUuidOrArchive(uuid)) {
4158 return;
4159 }
4160 } else {
4161 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4162 clearPending();
4163 activity.onConversationArchived(conversation);
4164 return;
4165 }
4166 }
4167 ActivityResult activityResult = postponedActivityResult.pop();
4168 if (activityResult != null) {
4169 handleActivityResult(activityResult);
4170 }
4171 clearPending();
4172 }
4173
4174 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4175 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4176 if (conversation == null) {
4177 clearPending();
4178 activity.onConversationArchived(null);
4179 return false;
4180 }
4181 reInit(conversation);
4182 ScrollState scrollState = pendingScrollState.pop();
4183 String lastMessageUuid = pendingLastMessageUuid.pop();
4184 List<Attachment> attachments = pendingMediaPreviews.pop();
4185 if (scrollState != null) {
4186 setScrollPosition(scrollState, lastMessageUuid);
4187 }
4188 if (attachments != null && attachments.size() > 0) {
4189 Log.d(Config.LOGTAG, "had attachments on restore");
4190 mediaPreviewAdapter.addMediaPreviews(attachments);
4191 toggleInputMethod();
4192 }
4193 return true;
4194 }
4195
4196 private void clearPending() {
4197 if (postponedActivityResult.clear()) {
4198 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4199 if (pendingTakePhotoUri.clear()) {
4200 Log.e(Config.LOGTAG, "cleared pending photo uri");
4201 }
4202 }
4203 if (pendingScrollState.clear()) {
4204 Log.e(Config.LOGTAG, "cleared scroll state");
4205 }
4206 if (pendingConversationsUuid.clear()) {
4207 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4208 }
4209 if (pendingMediaPreviews.clear()) {
4210 Log.e(Config.LOGTAG, "cleared pending media previews");
4211 }
4212 }
4213
4214 public Conversation getConversation() {
4215 return conversation;
4216 }
4217
4218 @Override
4219 public void onContactPictureLongClicked(View v, final Message message) {
4220 final String fingerprint;
4221 if (message.getEncryption() == Message.ENCRYPTION_PGP
4222 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4223 fingerprint = "pgp";
4224 } else {
4225 fingerprint = message.getFingerprint();
4226 }
4227 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4228 final Contact contact = message.getContact();
4229 if (message.getStatus() <= Message.STATUS_RECEIVED
4230 && (contact == null || !contact.isSelf())) {
4231 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4232 final Jid cp = message.getCounterpart();
4233 if (cp == null || cp.isBareJid()) {
4234 return;
4235 }
4236 final Jid tcp = message.getTrueCounterpart();
4237 final User userByRealJid =
4238 tcp != null
4239 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
4240 : null;
4241 final User user =
4242 userByRealJid != null
4243 ? userByRealJid
4244 : conversation.getMucOptions().findUserByFullJid(cp);
4245 if (user == null) return;
4246 popupMenu.inflate(R.menu.muc_details_context);
4247 final Menu menu = popupMenu.getMenu();
4248 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4249 activity, menu, conversation, user);
4250 popupMenu.setOnMenuItemClickListener(
4251 menuItem ->
4252 MucDetailsContextMenuHelper.onContextItemSelected(
4253 menuItem, user, activity, fingerprint));
4254 } else {
4255 popupMenu.inflate(R.menu.one_on_one_context);
4256 popupMenu.setOnMenuItemClickListener(
4257 item -> {
4258 switch (item.getItemId()) {
4259 case R.id.action_contact_details:
4260 activity.switchToContactDetails(
4261 message.getContact(), fingerprint);
4262 break;
4263 case R.id.action_show_qr_code:
4264 activity.showQrCode(
4265 "xmpp:"
4266 + message.getContact()
4267 .getJid()
4268 .asBareJid()
4269 .toEscapedString());
4270 break;
4271 }
4272 return true;
4273 });
4274 }
4275 } else {
4276 popupMenu.inflate(R.menu.account_context);
4277 final Menu menu = popupMenu.getMenu();
4278 menu.findItem(R.id.action_manage_accounts)
4279 .setVisible(QuickConversationsService.isConversations());
4280 popupMenu.setOnMenuItemClickListener(
4281 item -> {
4282 final XmppActivity activity = this.activity;
4283 if (activity == null) {
4284 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4285 return true;
4286 }
4287 switch (item.getItemId()) {
4288 case R.id.action_show_qr_code:
4289 activity.showQrCode(conversation.getAccount().getShareableUri());
4290 break;
4291 case R.id.action_account_details:
4292 activity.switchToAccount(
4293 message.getConversation().getAccount(), fingerprint);
4294 break;
4295 case R.id.action_manage_accounts:
4296 AccountUtils.launchManageAccounts(activity);
4297 break;
4298 }
4299 return true;
4300 });
4301 }
4302 popupMenu.show();
4303 }
4304
4305 @Override
4306 public void onContactPictureClicked(Message message) {
4307 setThread(message.getThread());
4308 if (message.isPrivateMessage()) {
4309 privateMessageWith(message.getCounterpart());
4310 return;
4311 }
4312 forkNullThread(message);
4313 conversation.setUserSelectedThread(true);
4314
4315 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4316 if (received) {
4317 if (message.getConversation() instanceof Conversation
4318 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4319 Jid tcp = message.getTrueCounterpart();
4320 Jid user = message.getCounterpart();
4321 if (user != null && !user.isBareJid()) {
4322 final MucOptions mucOptions =
4323 ((Conversation) message.getConversation()).getMucOptions();
4324 if (mucOptions.participating()
4325 || ((Conversation) message.getConversation()).getNextCounterpart()
4326 != null) {
4327 MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4328 MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4329 if (mucUser == null && tcpMucUser == null) {
4330 Toast.makeText(
4331 getActivity(),
4332 activity.getString(
4333 R.string.user_has_left_conference,
4334 user.getResource()),
4335 Toast.LENGTH_SHORT)
4336 .show();
4337 }
4338 highlightInConference(mucUser == null ? (tcpMucUser == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4339 } else {
4340 Toast.makeText(
4341 getActivity(),
4342 R.string.you_are_not_participating,
4343 Toast.LENGTH_SHORT)
4344 .show();
4345 }
4346 }
4347 }
4348 }
4349 }
4350
4351 private Activity requireActivity() {
4352 final Activity activity = getActivity();
4353 if (activity == null) {
4354 throw new IllegalStateException("Activity not attached");
4355 }
4356 return activity;
4357 }
4358}