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