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