ConversationFragment.java

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