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