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