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