ConversationFragment.java

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