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