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