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);
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);
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: also gate menu option in UI behind version check
2027        // TODO: upgrade to material you/3
2028        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
2029            final Calendar now = Calendar.getInstance();
2030            new DatePickerDialog(activity, (view, year, month, day) -> {
2031                new TimePickerDialog(activity, (view1, hour, minute) -> {
2032                    final Calendar c = Calendar.getInstance();
2033                    c.set(year, month, day, hour, minute);
2034                    final long timestamp = c.getTimeInMillis();
2035                    sendMessage(timestamp);
2036                    Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": scheduled message for " + timestamp);
2037                }, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), true).show();
2038            }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)).show();
2039        }
2040    }
2041
2042    private void returnToOngoingCall() {
2043        final Optional<OngoingRtpSession> ongoingRtpSession =
2044                activity.xmppConnectionService
2045                        .getJingleConnectionManager()
2046                        .getOngoingRtpConnection(conversation.getContact());
2047        if (ongoingRtpSession.isPresent()) {
2048            final OngoingRtpSession id = ongoingRtpSession.get();
2049            final Intent intent = new Intent(getActivity(), RtpSessionActivity.class);
2050            intent.setAction(Intent.ACTION_VIEW);
2051            intent.putExtra(
2052                    RtpSessionActivity.EXTRA_ACCOUNT,
2053                    id.getAccount().getJid().asBareJid().toEscapedString());
2054            intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
2055            if (id instanceof AbstractJingleConnection) {
2056                intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
2057                startActivity(intent);
2058            } else if (id instanceof JingleConnectionManager.RtpSessionProposal proposal) {
2059                if (Media.audioOnly(proposal.media)) {
2060                    intent.putExtra(
2061                            RtpSessionActivity.EXTRA_LAST_ACTION,
2062                            RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2063                } else {
2064                    intent.putExtra(
2065                            RtpSessionActivity.EXTRA_LAST_ACTION,
2066                            RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2067                }
2068                intent.putExtra(RtpSessionActivity.EXTRA_PROPOSED_SESSION_ID, proposal.sessionId);
2069                startActivity(intent);
2070            }
2071        }
2072    }
2073
2074    private void refreshFeatureDiscovery() {
2075        Set<Map.Entry<String, Presence>> presences = conversation.getContact().getPresences().getPresencesMap().entrySet();
2076        if (presences.isEmpty()) {
2077            presences = new HashSet<>();
2078            presences.add(new AbstractMap.SimpleEntry("", null));
2079        }
2080        for (Map.Entry<String, Presence> entry : presences) {
2081            Jid jid = conversation.getContact().getJid();
2082            if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
2083            activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
2084                if (activity == null) return;
2085                activity.runOnUiThread(() -> {
2086                    refresh();
2087                    refreshCommands(true);
2088                });
2089            });
2090        }
2091    }
2092
2093    private void addShortcut() {
2094        ShortcutInfoCompat info;
2095        if (conversation.getMode() == Conversation.MODE_MULTI) {
2096            info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getMucOptions());
2097        } else {
2098            info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getContact());
2099        }
2100        ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2101    }
2102
2103    private void togglePinned() {
2104        final boolean pinned =
2105                conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2106        conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2107        activity.xmppConnectionService.updateConversation(conversation);
2108        activity.invalidateOptionsMenu();
2109    }
2110
2111    private void checkPermissionAndTriggerAudioCall() {
2112        if (activity.mUseTor || conversation.getAccount().isOnion()) {
2113            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2114            return;
2115        }
2116        final List<String> permissions;
2117        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2118            permissions =
2119                    Arrays.asList(
2120                            Manifest.permission.RECORD_AUDIO,
2121                            Manifest.permission.BLUETOOTH_CONNECT);
2122        } else {
2123            permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2124        }
2125        if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2126            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2127        }
2128    }
2129
2130    private void checkPermissionAndTriggerVideoCall() {
2131        if (activity.mUseTor || conversation.getAccount().isOnion()) {
2132            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2133            return;
2134        }
2135        final List<String> permissions;
2136        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2137            permissions =
2138                    Arrays.asList(
2139                            Manifest.permission.RECORD_AUDIO,
2140                            Manifest.permission.CAMERA,
2141                            Manifest.permission.BLUETOOTH_CONNECT);
2142        } else {
2143            permissions =
2144                    Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2145        }
2146        if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2147            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2148        }
2149    }
2150
2151    private void triggerRtpSession(final String action) {
2152        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
2153            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2154                    .show();
2155            return;
2156        }
2157        final Account account = conversation.getAccount();
2158        if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
2159            activity.xmppConnectionService.updateAccount(account);
2160        }
2161        final Contact contact = conversation.getContact();
2162        if (Config.USE_JINGLE_MESSAGE_INIT && RtpCapability.jmiSupport(contact)) {
2163            triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2164        } else {
2165            final RtpCapability.Capability capability;
2166            if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2167                capability = RtpCapability.Capability.VIDEO;
2168            } else {
2169                capability = RtpCapability.Capability.AUDIO;
2170            }
2171            PresenceSelector.selectFullJidForDirectRtpConnection(
2172                    activity,
2173                    contact,
2174                    capability,
2175                    fullJid -> {
2176                        triggerRtpSession(contact.getAccount(), fullJid, action);
2177                    });
2178        }
2179    }
2180
2181    private void triggerRtpSession(final Account account, final Jid with, final String action) {
2182        CallIntegrationConnectionService.placeCall(activity.xmppConnectionService, account,with,RtpSessionActivity.actionToMedia(action));
2183    }
2184
2185    private void handleAttachmentSelection(MenuItem item) {
2186        switch (item.getItemId()) {
2187            case R.id.attach_choose_picture:
2188                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2189                break;
2190            case R.id.attach_take_picture:
2191                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2192                break;
2193            case R.id.attach_record_video:
2194                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2195                break;
2196            case R.id.attach_choose_file:
2197                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2198                break;
2199            case R.id.attach_record_voice:
2200                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2201                break;
2202            case R.id.attach_location:
2203                attachFile(ATTACHMENT_CHOICE_LOCATION);
2204                break;
2205        }
2206    }
2207
2208    private void handleEncryptionSelection(MenuItem item) {
2209        if (conversation == null) {
2210            return;
2211        }
2212        final boolean updated;
2213        switch (item.getItemId()) {
2214            case R.id.encryption_choice_none:
2215                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2216                item.setChecked(true);
2217                break;
2218            case R.id.encryption_choice_pgp:
2219                if (activity.hasPgp()) {
2220                    if (conversation.getAccount().getPgpSignature() != null) {
2221                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2222                        item.setChecked(true);
2223                    } else {
2224                        updated = false;
2225                        activity.announcePgp(
2226                                conversation.getAccount(),
2227                                conversation,
2228                                null,
2229                                activity.onOpenPGPKeyPublished);
2230                    }
2231                } else {
2232                    activity.showInstallPgpDialog();
2233                    updated = false;
2234                }
2235                break;
2236            case R.id.encryption_choice_axolotl:
2237                Log.d(
2238                        Config.LOGTAG,
2239                        AxolotlService.getLogprefix(conversation.getAccount())
2240                                + "Enabled axolotl for Contact "
2241                                + conversation.getContact().getJid());
2242                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2243                item.setChecked(true);
2244                break;
2245            default:
2246                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2247                break;
2248        }
2249        if (updated) {
2250            activity.xmppConnectionService.updateConversation(conversation);
2251        }
2252        updateChatMsgHint();
2253        getActivity().invalidateOptionsMenu();
2254        activity.refreshUi();
2255    }
2256
2257    public void attachFile(final int attachmentChoice) {
2258        attachFile(attachmentChoice, true);
2259    }
2260
2261    public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2262        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2263            if (!hasPermissions(
2264                    attachmentChoice,
2265                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2266                    Manifest.permission.RECORD_AUDIO)) {
2267                return;
2268            }
2269        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2270                || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
2271            if (!hasPermissions(
2272                    attachmentChoice,
2273                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2274                    Manifest.permission.CAMERA)) {
2275                return;
2276            }
2277        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2278            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2279                return;
2280            }
2281        }
2282        if (updateRecentlyUsed) {
2283            storeRecentlyUsedQuickAction(attachmentChoice);
2284        }
2285        final int encryption = conversation.getNextEncryption();
2286        final int mode = conversation.getMode();
2287        if (encryption == Message.ENCRYPTION_PGP) {
2288            if (activity.hasPgp()) {
2289                if (mode == Conversation.MODE_SINGLE
2290                        && conversation.getContact().getPgpKeyId() != 0) {
2291                    activity.xmppConnectionService
2292                            .getPgpEngine()
2293                            .hasKey(
2294                                    conversation.getContact(),
2295                                    new UiCallback<Contact>() {
2296
2297                                        @Override
2298                                        public void userInputRequired(
2299                                                PendingIntent pi, Contact contact) {
2300                                            startPendingIntent(pi, attachmentChoice);
2301                                        }
2302
2303                                        @Override
2304                                        public void success(Contact contact) {
2305                                            invokeAttachFileIntent(attachmentChoice);
2306                                        }
2307
2308                                        @Override
2309                                        public void error(int error, Contact contact) {
2310                                            activity.replaceToast(getString(error));
2311                                        }
2312                                    });
2313                } else if (mode == Conversation.MODE_MULTI
2314                        && conversation.getMucOptions().pgpKeysInUse()) {
2315                    if (!conversation.getMucOptions().everybodyHasKeys()) {
2316                        Toast warning =
2317                                Toast.makeText(
2318                                        getActivity(),
2319                                        R.string.missing_public_keys,
2320                                        Toast.LENGTH_LONG);
2321                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2322                        warning.show();
2323                    }
2324                    invokeAttachFileIntent(attachmentChoice);
2325                } else {
2326                    showNoPGPKeyDialog(
2327                            false,
2328                            (dialog, which) -> {
2329                                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2330                                activity.xmppConnectionService.updateConversation(conversation);
2331                                invokeAttachFileIntent(attachmentChoice);
2332                            });
2333                }
2334            } else {
2335                activity.showInstallPgpDialog();
2336            }
2337        } else {
2338            invokeAttachFileIntent(attachmentChoice);
2339        }
2340    }
2341
2342    private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2343        try {
2344            activity.getPreferences()
2345                    .edit()
2346                    .putString(
2347                            RECENTLY_USED_QUICK_ACTION,
2348                            SendButtonAction.of(attachmentChoice).toString())
2349                    .apply();
2350        } catch (IllegalArgumentException e) {
2351            // just do not save
2352        }
2353    }
2354
2355    @Override
2356    public void onRequestPermissionsResult(
2357            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2358        final PermissionUtils.PermissionResult permissionResult =
2359                PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2360        if (grantResults.length > 0) {
2361            if (allGranted(permissionResult.grantResults)) {
2362                switch (requestCode) {
2363                    case REQUEST_START_DOWNLOAD:
2364                        if (this.mPendingDownloadableMessage != null) {
2365                            startDownloadable(this.mPendingDownloadableMessage);
2366                        }
2367                        break;
2368                    case REQUEST_ADD_EDITOR_CONTENT:
2369                        if (this.mPendingEditorContent != null) {
2370                            attachEditorContentToConversation(this.mPendingEditorContent);
2371                        }
2372                        break;
2373                    case REQUEST_COMMIT_ATTACHMENTS:
2374                        commitAttachments();
2375                        break;
2376                    case REQUEST_START_AUDIO_CALL:
2377                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2378                        break;
2379                    case REQUEST_START_VIDEO_CALL:
2380                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2381                        break;
2382                    default:
2383                        attachFile(requestCode);
2384                        break;
2385                }
2386            } else {
2387                @StringRes int res;
2388                String firstDenied =
2389                        getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2390                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2391                    res = R.string.no_microphone_permission;
2392                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2393                    res = R.string.no_camera_permission;
2394                } else {
2395                    res = R.string.no_storage_permission;
2396                }
2397                Toast.makeText(
2398                                getActivity(),
2399                                getString(res, getString(R.string.app_name)),
2400                                Toast.LENGTH_SHORT)
2401                        .show();
2402            }
2403        }
2404        if (writeGranted(grantResults, permissions)) {
2405            if (activity != null && activity.xmppConnectionService != null) {
2406                activity.xmppConnectionService.getDrawableCache().evictAll();
2407                activity.xmppConnectionService.restartFileObserver();
2408            }
2409            refresh();
2410        }
2411        if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
2412            XmppConnectionService.toggleForegroundService(activity);
2413        }
2414    }
2415
2416    public void startDownloadable(Message message) {
2417        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2418            this.mPendingDownloadableMessage = message;
2419            return;
2420        }
2421        Transferable transferable = message.getTransferable();
2422        if (transferable != null) {
2423            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2424                createNewConnection(message);
2425                return;
2426            }
2427            if (!transferable.start()) {
2428                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2429                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2430                        .show();
2431            }
2432        } else if (message.treatAsDownloadable()
2433                || message.hasFileOnRemoteHost()
2434                || MessageUtils.unInitiatedButKnownSize(message)) {
2435            createNewConnection(message);
2436        } else {
2437            Log.d(
2438                    Config.LOGTAG,
2439                    message.getConversation().getAccount() + ": unable to start downloadable");
2440        }
2441    }
2442
2443    private void createNewConnection(final Message message) {
2444        if (!activity.xmppConnectionService.hasInternetConnection()) {
2445            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2446                    .show();
2447            return;
2448        }
2449        if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2450            try {
2451                BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2452                message.setTransferable(transfer);
2453                transfer.start();
2454            } catch (URISyntaxException e) {
2455                Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2456            }
2457        } else {
2458            activity.xmppConnectionService
2459                    .getHttpConnectionManager()
2460                    .createNewDownloadConnection(message, true);
2461        }
2462    }
2463
2464    @SuppressLint("InflateParams")
2465    protected void clearHistoryDialog(final Conversation conversation) {
2466        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2467        builder.setTitle(R.string.clear_conversation_history);
2468        final View dialogView =
2469                requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2470        final CheckBox endConversationCheckBox =
2471                dialogView.findViewById(R.id.end_conversation_checkbox);
2472        builder.setView(dialogView);
2473        builder.setNegativeButton(getString(R.string.cancel), null);
2474        builder.setPositiveButton(
2475                getString(R.string.confirm),
2476                (dialog, which) -> {
2477                    this.activity.xmppConnectionService.clearConversationHistory(conversation);
2478                    if (endConversationCheckBox.isChecked()) {
2479                        this.activity.xmppConnectionService.archiveConversation(conversation);
2480                        this.activity.onConversationArchived(conversation);
2481                    } else {
2482                        activity.onConversationsListItemUpdated();
2483                        refresh();
2484                    }
2485                });
2486        builder.create().show();
2487    }
2488
2489    protected void muteConversationDialog(final Conversation conversation) {
2490        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2491        builder.setTitle(R.string.disable_notifications);
2492        final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2493        final CharSequence[] labels = new CharSequence[durations.length];
2494        for (int i = 0; i < durations.length; ++i) {
2495            if (durations[i] == -1) {
2496                labels[i] = activity.getString(R.string.until_further_notice);
2497            } else {
2498                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2499            }
2500        }
2501        builder.setItems(
2502                labels,
2503                (dialog, which) -> {
2504                    final long till;
2505                    if (durations[which] == -1) {
2506                        till = Long.MAX_VALUE;
2507                    } else {
2508                        till = System.currentTimeMillis() + (durations[which] * 1000L);
2509                    }
2510                    conversation.setMutedTill(till);
2511                    activity.xmppConnectionService.updateConversation(conversation);
2512                    activity.onConversationsListItemUpdated();
2513                    refresh();
2514                    activity.invalidateOptionsMenu();
2515                });
2516        builder.create().show();
2517    }
2518
2519    private boolean hasPermissions(int requestCode, List<String> permissions) {
2520        final List<String> missingPermissions = new ArrayList<>();
2521        for (String permission : permissions) {
2522            if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU || Config.ONLY_INTERNAL_STORAGE) && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2523                continue;
2524            }
2525            if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2526                missingPermissions.add(permission);
2527            }
2528        }
2529        if (missingPermissions.size() == 0) {
2530            return true;
2531        } else {
2532            requestPermissions(
2533                    missingPermissions.toArray(new String[0]),
2534                    requestCode);
2535            return false;
2536        }
2537    }
2538
2539    private boolean hasPermissions(int requestCode, String... permissions) {
2540        return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2541    }
2542
2543    public void unMuteConversation(final Conversation conversation) {
2544        conversation.setMutedTill(0);
2545        this.activity.xmppConnectionService.updateConversation(conversation);
2546        this.activity.onConversationsListItemUpdated();
2547        refresh();
2548        this.activity.invalidateOptionsMenu();
2549    }
2550
2551    protected void invokeAttachFileIntent(final int attachmentChoice) {
2552        Intent intent = new Intent();
2553        boolean chooser = false;
2554        switch (attachmentChoice) {
2555            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2556                intent.setAction(Intent.ACTION_GET_CONTENT);
2557                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2558                intent.setType("image/*");
2559                chooser = true;
2560                break;
2561            case ATTACHMENT_CHOICE_RECORD_VIDEO:
2562                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2563                break;
2564            case ATTACHMENT_CHOICE_TAKE_PHOTO:
2565                final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2566                pendingTakePhotoUri.push(uri);
2567                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2568                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2569                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2570                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2571                break;
2572            case ATTACHMENT_CHOICE_CHOOSE_FILE:
2573                chooser = true;
2574                intent.setType("*/*");
2575                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2576                intent.addCategory(Intent.CATEGORY_OPENABLE);
2577                intent.setAction(Intent.ACTION_GET_CONTENT);
2578                break;
2579            case ATTACHMENT_CHOICE_RECORD_VOICE:
2580                intent = new Intent(getActivity(), RecordingActivity.class);
2581                break;
2582            case ATTACHMENT_CHOICE_LOCATION:
2583                intent = GeoHelper.getFetchIntent(activity);
2584                break;
2585        }
2586        final Context context = getActivity();
2587        if (context == null) {
2588            return;
2589        }
2590        try {
2591            if (chooser) {
2592                startActivityForResult(
2593                        Intent.createChooser(intent, getString(R.string.perform_action_with)),
2594                        attachmentChoice);
2595            } else {
2596                startActivityForResult(intent, attachmentChoice);
2597            }
2598        } catch (final ActivityNotFoundException e) {
2599            Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2600        }
2601    }
2602
2603    @Override
2604    public void onResume() {
2605        super.onResume();
2606        binding.messagesView.post(this::fireReadEvent);
2607    }
2608
2609    private void fireReadEvent() {
2610        if (activity != null && this.conversation != null) {
2611            String uuid = getLastVisibleMessageUuid();
2612            if (uuid != null) {
2613                activity.onConversationRead(this.conversation, uuid);
2614            }
2615        }
2616    }
2617
2618    private void newSubThread() {
2619        Element oldThread = conversation.getThread();
2620        Element thread = new Element("thread", "jabber:client");
2621        thread.setContent(UUID.randomUUID().toString());
2622        if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2623        setThread(thread);
2624    }
2625
2626    private void newThread() {
2627        Element thread = new Element("thread", "jabber:client");
2628        thread.setContent(UUID.randomUUID().toString());
2629        setThread(thread);
2630    }
2631
2632    private void updateThreadFromLastMessage() {
2633        if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2634            Message message = getLastVisibleMessage();
2635            if (message == null) {
2636                newThread();
2637            } else {
2638                if (conversation.getMode() == Conversation.MODE_MULTI) {
2639                    if (activity == null || activity.xmppConnectionService == null) return;
2640                    if (message.getStatus() < Message.STATUS_SEND) {
2641                        if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
2642                    }
2643                }
2644
2645                setThread(message.getThread());
2646            }
2647        }
2648    }
2649
2650    private String getLastVisibleMessageUuid() {
2651        Message message =  getLastVisibleMessage();
2652        return message == null ? null : message.getUuid();
2653    }
2654
2655    private Message getLastVisibleMessage() {
2656        if (binding == null) {
2657            return null;
2658        }
2659        synchronized (this.messageList) {
2660            int pos = binding.messagesView.getLastVisiblePosition();
2661            if (pos >= 0) {
2662                Message message = null;
2663                for (int i = pos; i >= 0; --i) {
2664                    try {
2665                        message = (Message) binding.messagesView.getItemAtPosition(i);
2666                    } catch (IndexOutOfBoundsException e) {
2667                        // should not happen if we synchronize properly. however if that fails we
2668                        // just gonna try item -1
2669                        continue;
2670                    }
2671                    if (message.getType() != Message.TYPE_STATUS) {
2672                        break;
2673                    }
2674                }
2675                if (message != null) {
2676                    while (message.next() != null && message.next().wasMergedIntoPrevious(activity == null ? null : activity.xmppConnectionService)) {
2677                        message = message.next();
2678                    }
2679                    return message;
2680                }
2681            }
2682        }
2683        return null;
2684    }
2685
2686    private void openWith(final Message message) {
2687        if (message.isGeoUri()) {
2688            GeoHelper.view(getActivity(), message);
2689        } else {
2690            final DownloadableFile file =
2691                    activity.xmppConnectionService.getFileBackend().getFile(message);
2692            ViewUtil.view(activity, file);
2693        }
2694    }
2695
2696    private void reportMessage(final Message message) {
2697        BlockContactDialog.show(activity, conversation.getContact(), message.getServerMsgId());
2698    }
2699
2700    private void showErrorMessage(final Message message) {
2701        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2702        builder.setTitle(R.string.error_message);
2703        final String errorMessage = message.getErrorMessage();
2704        final String[] errorMessageParts =
2705                errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2706        final String displayError;
2707        if (errorMessageParts.length == 2) {
2708            displayError = errorMessageParts[1];
2709        } else {
2710            displayError = errorMessage;
2711        }
2712        builder.setMessage(displayError);
2713        builder.setNegativeButton(
2714                R.string.copy_to_clipboard,
2715                (dialog, which) -> {
2716                    activity.copyTextToClipboard(displayError, R.string.error_message);
2717                    Toast.makeText(
2718                                    activity,
2719                                    R.string.error_message_copied_to_clipboard,
2720                                    Toast.LENGTH_SHORT)
2721                            .show();
2722                });
2723        builder.setPositiveButton(R.string.confirm, null);
2724        builder.create().show();
2725    }
2726
2727    public boolean onInlineImageLongClicked(Cid cid) {
2728        DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2729        if (f == null) return false;
2730
2731        saveAsSticker(f, null);
2732        return true;
2733    }
2734
2735    private void saveAsSticker(final Message m) {
2736        String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
2737        existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
2738        saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
2739    }
2740
2741    private void saveAsSticker(final File file, final String name) {
2742        savingAsSticker = file;
2743
2744        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
2745        intent.addCategory(Intent.CATEGORY_OPENABLE);
2746        intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file)));
2747        intent.putExtra(Intent.EXTRA_TITLE, name);
2748
2749        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2750        final String dir = p.getString("sticker_directory", "Stickers");
2751        if (dir.startsWith("content://")) {
2752            intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
2753        } else {
2754            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
2755            Uri uri;
2756            if (Build.VERSION.SDK_INT >= 29) {
2757                Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
2758                uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
2759                uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
2760            } else {
2761                uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
2762            }
2763            intent.putExtra("android.provider.extra.INITIAL_URI", uri);
2764            intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
2765        }
2766
2767        Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
2768        startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
2769    }
2770
2771    private void deleteFile(final Message message) {
2772        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2773        builder.setNegativeButton(R.string.cancel, null);
2774        builder.setTitle(R.string.delete_file_dialog);
2775        builder.setMessage(R.string.delete_file_dialog_msg);
2776        builder.setPositiveButton(
2777                R.string.confirm,
2778                (dialog, which) -> {
2779                    List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2780                    if (thumbs != null && !thumbs.isEmpty()) {
2781                        for (Element thumb : thumbs) {
2782                            Uri uri = Uri.parse(thumb.getAttribute("uri"));
2783                            if (uri.getScheme().equals("cid")) {
2784                                Cid cid = BobTransfer.cid(uri);
2785                                if (cid == null) continue;
2786                                DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2787                                activity.xmppConnectionService.evictPreview(f);
2788                                f.delete();
2789                            }
2790                        }
2791                    }
2792                    if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2793                        activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
2794                        activity.xmppConnectionService.updateMessage(message, false);
2795                        activity.onConversationsListItemUpdated();
2796                        refresh();
2797                    }
2798                });
2799        builder.create().show();
2800    }
2801
2802    private void resendMessage(final Message message) {
2803        if (message.isFileOrImage()) {
2804            if (!(message.getConversation() instanceof Conversation)) {
2805                return;
2806            }
2807            final Conversation conversation = (Conversation) message.getConversation();
2808            final DownloadableFile file =
2809                    activity.xmppConnectionService.getFileBackend().getFile(message);
2810            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2811                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2812                if (!message.hasFileOnRemoteHost()
2813                        && xmppConnection != null
2814                        && conversation.getMode() == Conversational.MODE_SINGLE
2815                        && !xmppConnection
2816                                .getFeatures()
2817                                .httpUpload(message.getFileParams().getSize())) {
2818                    activity.selectPresence(
2819                            conversation,
2820                            () -> {
2821                                message.setCounterpart(conversation.getNextCounterpart());
2822                                activity.xmppConnectionService.resendFailedMessages(message);
2823                                new Handler()
2824                                        .post(
2825                                                () -> {
2826                                                    int size = messageList.size();
2827                                                    this.binding.messagesView.setSelection(
2828                                                            size - 1);
2829                                                });
2830                            });
2831                    return;
2832                }
2833            } else if (!Compatibility.hasStoragePermission(getActivity())) {
2834                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2835                return;
2836            } else {
2837                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2838                message.setDeleted(true);
2839                activity.xmppConnectionService.updateMessage(message, false);
2840                activity.onConversationsListItemUpdated();
2841                refresh();
2842                return;
2843            }
2844        }
2845        activity.xmppConnectionService.resendFailedMessages(message);
2846        new Handler()
2847                .post(
2848                        () -> {
2849                            int size = messageList.size();
2850                            this.binding.messagesView.setSelection(size - 1);
2851                        });
2852    }
2853
2854    private void cancelTransmission(Message message) {
2855        Transferable transferable = message.getTransferable();
2856        if (transferable != null) {
2857            transferable.cancel();
2858        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2859            activity.xmppConnectionService.markMessage(
2860                    message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2861        }
2862    }
2863
2864    private void retryDecryption(Message message) {
2865        message.setEncryption(Message.ENCRYPTION_PGP);
2866        activity.onConversationsListItemUpdated();
2867        refresh();
2868        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2869    }
2870
2871    public void privateMessageWith(final Jid counterpart) {
2872        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2873            activity.xmppConnectionService.sendChatState(conversation);
2874        }
2875        this.binding.textinput.setText("");
2876        this.conversation.setNextCounterpart(counterpart);
2877        updateChatMsgHint();
2878        updateSendButton();
2879        updateEditablity();
2880    }
2881
2882    private void correctMessage(Message message) {
2883        while (message.mergeable(message.next())) {
2884            message = message.next();
2885        }
2886        setThread(message.getThread());
2887        conversation.setUserSelectedThread(true);
2888        this.conversation.setCorrectingMessage(message);
2889        final Editable editable = binding.textinput.getText();
2890        this.conversation.setDraftMessage(editable.toString());
2891        this.binding.textinput.setText("");
2892        this.binding.textinput.append(message.getBody());
2893        if (message.getSubject() != null && message.getSubject().length() > 0) {
2894            this.binding.textinputSubject.setText(message.getSubject());
2895            this.binding.textinputSubject.setVisibility(View.VISIBLE);
2896        }
2897    }
2898
2899    private void highlightInConference(String nick) {
2900        final Editable editable = this.binding.textinput.getText();
2901        String oldString = editable.toString().trim();
2902        final int pos = this.binding.textinput.getSelectionStart();
2903        if (oldString.isEmpty() || pos == 0) {
2904            editable.insert(0, nick + ": ");
2905        } else {
2906            final char before = editable.charAt(pos - 1);
2907            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2908            if (before == '\n') {
2909                editable.insert(pos, nick + ": ");
2910            } else {
2911                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2912                    if (NickValidityChecker.check(
2913                            conversation,
2914                            Arrays.asList(
2915                                    editable.subSequence(0, pos - 2).toString().split(", ")))) {
2916                        editable.insert(pos - 2, ", " + nick);
2917                        return;
2918                    }
2919                }
2920                editable.insert(
2921                        pos,
2922                        (Character.isWhitespace(before) ? "" : " ")
2923                                + nick
2924                                + (Character.isWhitespace(after) ? "" : " "));
2925                if (Character.isWhitespace(after)) {
2926                    this.binding.textinput.setSelection(
2927                            this.binding.textinput.getSelectionStart() + 1);
2928                }
2929            }
2930        }
2931    }
2932
2933    @Override
2934    public void startActivityForResult(Intent intent, int requestCode) {
2935        final Activity activity = getActivity();
2936        if (activity instanceof ConversationsActivity) {
2937            ((ConversationsActivity) activity).clearPendingViewIntent();
2938        }
2939        super.startActivityForResult(intent, requestCode);
2940    }
2941
2942    @Override
2943    public void onSaveInstanceState(@NonNull Bundle outState) {
2944        super.onSaveInstanceState(outState);
2945        if (conversation != null) {
2946            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2947            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2948            final Uri uri = pendingTakePhotoUri.peek();
2949            if (uri != null) {
2950                outState.putString(STATE_PHOTO_URI, uri.toString());
2951            }
2952            final ScrollState scrollState = getScrollPosition();
2953            if (scrollState != null) {
2954                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2955            }
2956            final ArrayList<Attachment> attachments =
2957                    mediaPreviewAdapter == null
2958                            ? new ArrayList<>()
2959                            : mediaPreviewAdapter.getAttachments();
2960            if (attachments.size() > 0) {
2961                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2962            }
2963        }
2964    }
2965
2966    @Override
2967    public void onActivityCreated(Bundle savedInstanceState) {
2968        super.onActivityCreated(savedInstanceState);
2969        if (savedInstanceState == null) {
2970            return;
2971        }
2972        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2973        ArrayList<Attachment> attachments =
2974                savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2975        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2976        if (uuid != null) {
2977            QuickLoader.set(uuid);
2978            this.pendingConversationsUuid.push(uuid);
2979            if (attachments != null && attachments.size() > 0) {
2980                this.pendingMediaPreviews.push(attachments);
2981            }
2982            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2983            if (takePhotoUri != null) {
2984                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2985            }
2986            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2987        }
2988    }
2989
2990    @Override
2991    public void onStart() {
2992        super.onStart();
2993        if (this.reInitRequiredOnStart && this.conversation != null) {
2994            final Bundle extras = pendingExtras.pop();
2995            reInit(this.conversation, extras != null);
2996            if (extras != null) {
2997                processExtras(extras);
2998            }
2999        } else if (conversation == null
3000                && activity != null
3001                && activity.xmppConnectionService != null) {
3002            final String uuid = pendingConversationsUuid.pop();
3003            Log.d(
3004                    Config.LOGTAG,
3005                    "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
3006                            + uuid);
3007            if (uuid != null) {
3008                findAndReInitByUuidOrArchive(uuid);
3009            }
3010        }
3011    }
3012
3013    @Override
3014    public void onStop() {
3015        super.onStop();
3016        final Activity activity = getActivity();
3017        messageListAdapter.unregisterListenerInAudioPlayer();
3018        if (activity == null || !activity.isChangingConfigurations()) {
3019            hideSoftKeyboard(activity);
3020            messageListAdapter.stopAudioPlayer();
3021        }
3022        if (this.conversation != null) {
3023            final String msg = this.binding.textinput.getText().toString();
3024            storeNextMessage(msg);
3025            updateChatState(this.conversation, msg);
3026            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
3027        }
3028        this.reInitRequiredOnStart = true;
3029        if (emojiPopup != null) emojiPopup.dismiss();
3030    }
3031
3032    private void updateChatState(final Conversation conversation, final String msg) {
3033        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
3034        Account.State status = conversation.getAccount().getStatus();
3035        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
3036            activity.xmppConnectionService.sendChatState(conversation);
3037        }
3038    }
3039
3040    private void saveMessageDraftStopAudioPlayer() {
3041        final Conversation previousConversation = this.conversation;
3042        if (this.activity == null || this.binding == null || previousConversation == null) {
3043            return;
3044        }
3045        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
3046        final String msg = this.binding.textinput.getText().toString();
3047        storeNextMessage(msg);
3048        updateChatState(this.conversation, msg);
3049        messageListAdapter.stopAudioPlayer();
3050        mediaPreviewAdapter.clearPreviews();
3051        toggleInputMethod();
3052    }
3053
3054    public void reInit(final Conversation conversation, final Bundle extras) {
3055        QuickLoader.set(conversation.getUuid());
3056        final boolean changedConversation = this.conversation != conversation;
3057        if (changedConversation) {
3058            this.saveMessageDraftStopAudioPlayer();
3059        }
3060        this.clearPending();
3061        if (this.reInit(conversation, extras != null)) {
3062            if (extras != null) {
3063                processExtras(extras);
3064            }
3065            this.reInitRequiredOnStart = false;
3066        } else {
3067            this.reInitRequiredOnStart = true;
3068            pendingExtras.push(extras);
3069        }
3070        resetUnreadMessagesCount();
3071    }
3072
3073    private void reInit(Conversation conversation) {
3074        reInit(conversation, false);
3075    }
3076
3077    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
3078        if (conversation == null) {
3079            return false;
3080        }
3081        final Conversation originalConversation = this.conversation;
3082        this.conversation = conversation;
3083        // once we set the conversation all is good and it will automatically do the right thing in
3084        // onStart()
3085        if (this.activity == null || this.binding == null) {
3086            return false;
3087        }
3088
3089        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3090            activity.onConversationArchived(this.conversation);
3091            return false;
3092        }
3093
3094        final var cursord = getResources().getDrawable(R.drawable.cursor_on_tertiary_container);
3095        if (activity.xmppConnectionService != null && activity.xmppConnectionService.getAccounts().size() > 1) {
3096            final var colors = MaterialColors.getColorRoles(activity, conversation.getAccount().getColor(activity.isDark()));
3097            cursord.setTintList(ColorStateList.valueOf(colors.getOnAccentContainer()));
3098            binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(colors.getAccentContainer()));
3099            binding.textinputSubject.setTextColor(colors.getOnAccentContainer());
3100            binding.textinput.setTextColor(colors.getOnAccentContainer());
3101            binding.textinputSubject.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3102            binding.textinput.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3103        } else {
3104            cursord.setTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer)));
3105            binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.inputLayout, com.google.android.material.R.attr.colorTertiaryContainer)));
3106            binding.textinputSubject.setTextColor(MaterialColors.getColor(binding.textinputSubject, com.google.android.material.R.attr.colorOnTertiaryContainer));
3107            binding.textinput.setTextColor(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer));
3108            binding.textinputSubject.setHintTextColor(R.color.hint_on_tertiary_container);
3109            binding.textinput.setHintTextColor(R.color.hint_on_tertiary_container);
3110        }
3111        binding.textinputSubject.setTextCursorDrawable(cursord);
3112        binding.textinput.setTextCursorDrawable(cursord);
3113
3114        setThread(conversation.getThread());
3115        setupReply(conversation.getReplyTo());
3116
3117        stopScrolling();
3118        Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3119
3120        if (this.conversation.isRead() && hasExtras) {
3121            Log.d(Config.LOGTAG, "trimming conversation");
3122            this.conversation.trim();
3123        }
3124
3125        setupIme();
3126
3127        final boolean scrolledToBottomAndNoPending =
3128                this.scrolledToBottom() && pendingScrollState.peek() == null;
3129
3130        this.binding.textSendButton.setContentDescription(
3131                activity.getString(R.string.send_message_to_x, conversation.getName()));
3132        this.binding.textinput.setKeyboardListener(null);
3133        this.binding.textinputSubject.setKeyboardListener(null);
3134        final boolean participating =
3135                conversation.getMode() == Conversational.MODE_SINGLE
3136                        || conversation.getMucOptions().participating();
3137        if (participating) {
3138            this.binding.textinput.setText(this.conversation.getNextMessage());
3139            this.binding.textinput.setSelection(this.binding.textinput.length());
3140        } else {
3141            this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3142        }
3143        this.binding.textinput.setKeyboardListener(this);
3144        this.binding.textinputSubject.setKeyboardListener(this);
3145        messageListAdapter.updatePreferences();
3146        refresh(false);
3147        activity.invalidateOptionsMenu();
3148        this.conversation.messagesLoaded.set(true);
3149        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3150
3151        if (hasExtras || scrolledToBottomAndNoPending) {
3152            resetUnreadMessagesCount();
3153            synchronized (this.messageList) {
3154                Log.d(Config.LOGTAG, "jump to first unread message");
3155                final Message first = conversation.getFirstUnreadMessage();
3156                final int bottom = Math.max(0, this.messageList.size() - 1);
3157                final int pos;
3158                final boolean jumpToBottom;
3159                if (first == null) {
3160                    pos = bottom;
3161                    jumpToBottom = true;
3162                } else {
3163                    int i = getIndexOf(first.getUuid(), this.messageList);
3164                    pos = i < 0 ? bottom : i;
3165                    jumpToBottom = false;
3166                }
3167                setSelection(pos, jumpToBottom);
3168            }
3169        }
3170
3171        this.binding.messagesView.post(this::fireReadEvent);
3172        // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3173        // layout which might be unnecessary since we can *see* it
3174        activity.xmppConnectionService
3175                .getNotificationService()
3176                .setOpenConversation(this.conversation);
3177
3178        if (commandAdapter != null && conversation != originalConversation) {
3179            commandAdapter.clear();
3180            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3181            refreshCommands(false);
3182        }
3183        if (commandAdapter == null && conversation != null) {
3184            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3185            commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3186            binding.commandsView.setAdapter(commandAdapter);
3187            binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3188                if (activity == null) return;
3189
3190                commandAdapter.getItem(position).start(activity, ConversationFragment.this.conversation);
3191            });
3192            refreshCommands(false);
3193        }
3194
3195        binding.commandsNote.setVisibility(activity.xmppConnectionService.isOnboarding() ? View.VISIBLE : View.GONE);
3196
3197        return true;
3198    }
3199
3200    public void refreshForNewCaps() {
3201        refreshCommands(true);
3202    }
3203
3204    protected void refreshCommands(boolean delayShow) {
3205        if (commandAdapter == null) return;
3206
3207        final CommandAdapter.MucConfig mucConfig =
3208            conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER) ?
3209            new CommandAdapter.MucConfig() :
3210            null;
3211
3212        Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3213        if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3214            commandJid = conversation.getJid().asBareJid();
3215        }
3216        if (commandJid == null && conversation.getJid().isDomainJid()) {
3217            commandJid = conversation.getJid();
3218        }
3219        if (commandJid == null) {
3220            binding.commandsViewProgressbar.setVisibility(View.GONE);
3221            if (mucConfig == null) {
3222                conversation.hideViewPager();
3223            } else {
3224                commandAdapter.clear();
3225                commandAdapter.add(mucConfig);
3226                conversation.showViewPager();
3227            }
3228        } else {
3229            if (!delayShow) conversation.showViewPager();
3230            binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3231            activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
3232                if (activity == null) return;
3233
3234                activity.runOnUiThread(() -> {
3235                    binding.commandsViewProgressbar.setVisibility(View.GONE);
3236                    commandAdapter.clear();
3237                    if (iq.getType() == IqPacket.TYPE.RESULT) {
3238                        for (Element child : iq.query().getChildren()) {
3239                            if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3240                            commandAdapter.add(new CommandAdapter.Command0050(child));
3241                        }
3242                    }
3243
3244                    if (mucConfig != null) commandAdapter.add(mucConfig);
3245
3246                    if (commandAdapter.getCount() < 1) {
3247                        conversation.hideViewPager();
3248                    } else if (delayShow) {
3249                        conversation.showViewPager();
3250                    }
3251                });
3252            });
3253        }
3254    }
3255
3256    private void resetUnreadMessagesCount() {
3257        lastMessageUuid = null;
3258        hideUnreadMessagesCount();
3259    }
3260
3261    private void hideUnreadMessagesCount() {
3262        if (this.binding == null) {
3263            return;
3264        }
3265        this.binding.scrollToBottomButton.setEnabled(false);
3266        this.binding.scrollToBottomButton.hide();
3267        this.binding.unreadCountCustomView.setVisibility(View.GONE);
3268    }
3269
3270    private void setSelection(int pos, boolean jumpToBottom) {
3271        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3272        this.binding.messagesView.post(
3273                () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3274        this.binding.messagesView.post(this::fireReadEvent);
3275    }
3276
3277    private boolean scrolledToBottom() {
3278        return this.binding != null && scrolledToBottom(this.binding.messagesView);
3279    }
3280
3281    private void processExtras(final Bundle extras) {
3282        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3283        final String text = extras.getString(Intent.EXTRA_TEXT);
3284        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3285        final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3286        final String postInitAction =
3287                extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3288        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3289        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3290        final boolean doNotAppend =
3291                extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3292        final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3293
3294        final String thread = extras.getString(ConversationsActivity.EXTRA_THREAD);
3295        if (thread != null) {
3296            conversation.setLockThread(true);
3297            backPressedLeaveSingleThread.setEnabled(true);
3298            setThread(new Element("thread").setContent(thread));
3299            refresh();
3300        }
3301
3302        final List<Uri> uris = extractUris(extras);
3303        if (uris != null && uris.size() > 0) {
3304            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3305                mediaPreviewAdapter.addMediaPreviews(
3306                        Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3307            } else {
3308                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3309                mediaPreviewAdapter.addMediaPreviews(
3310                        Attachment.of(getActivity(), cleanedUris, type));
3311            }
3312            toggleInputMethod();
3313            return;
3314        }
3315        if (nick != null) {
3316            if (pm) {
3317                Jid jid = conversation.getJid();
3318                try {
3319                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3320                    privateMessageWith(next);
3321                } catch (final IllegalArgumentException ignored) {
3322                    // do nothing
3323                }
3324            } else {
3325                final MucOptions mucOptions = conversation.getMucOptions();
3326                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3327                    highlightInConference(nick);
3328                }
3329            }
3330        } else {
3331            if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3332                mediaPreviewAdapter.addMediaPreviews(
3333                        Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3334                toggleInputMethod();
3335                return;
3336            } else if (text != null && asQuote) {
3337                quoteText(text);
3338            } else {
3339                appendText(text, doNotAppend);
3340            }
3341        }
3342        if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3343            attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3344            return;
3345        }
3346        if ("call".equals(postInitAction)) {
3347            checkPermissionAndTriggerAudioCall();
3348        }
3349        if ("message".equals(postInitAction)) {
3350            binding.conversationViewPager.post(() -> {
3351                binding.conversationViewPager.setCurrentItem(0);
3352            });
3353        }
3354        if ("command".equals(postInitAction)) {
3355            binding.conversationViewPager.post(() -> {
3356                PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3357                if (adapter != null && adapter.getCount() > 1) {
3358                    binding.conversationViewPager.setCurrentItem(1);
3359                }
3360                final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3361                Jid commandJid = null;
3362                if (jid != null) {
3363                    try {
3364                        commandJid = Jid.of(jid);
3365                    } catch (final IllegalArgumentException e) { }
3366                }
3367                if (commandJid == null || !commandJid.isFullJid()) {
3368                    final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3369                    if (discoJid != null) commandJid = discoJid;
3370                }
3371                if (node != null && commandJid != null) {
3372                    conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3373                }
3374            });
3375            return;
3376        }
3377        Message message =
3378                downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3379        if ("webxdc".equals(postInitAction)) {
3380            if (message == null) {
3381                message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3382            }
3383            if (message == null) return;
3384
3385            Cid webxdcCid = message.getFileParams().getCids().get(0);
3386            WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message, activity.xmppConnectionService);
3387            Conversation conversation = (Conversation) message.getConversation();
3388            if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3389                conversation.startWebxdc(webxdc);
3390            }
3391        }
3392        if (message != null) {
3393            startDownloadable(message);
3394        }
3395        if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3396            if (!conversation.switchToSession("jabber:iq:register")) {
3397                conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3398            }
3399        }
3400    }
3401
3402    private Element commandFor(final Jid jid, final String node) {
3403        if (commandAdapter != null) {
3404            for (int i = 0; i < commandAdapter.getCount(); i++) {
3405                final CommandAdapter.Command c = commandAdapter.getItem(i);
3406                if (!(c instanceof CommandAdapter.Command0050)) continue;
3407
3408                final Element command = ((CommandAdapter.Command0050) c).el;
3409                final String commandNode = command.getAttribute("node");
3410                if (commandNode == null || !commandNode.equals(node)) continue;
3411
3412                final Jid commandJid = command.getAttributeAsJid("jid");
3413                if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3414
3415                return command;
3416            }
3417        }
3418
3419        return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3420    }
3421
3422    private List<Uri> extractUris(final Bundle extras) {
3423        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3424        if (uris != null) {
3425            return uris;
3426        }
3427        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3428        if (uri != null) {
3429            return Collections.singletonList(uri);
3430        } else {
3431            return null;
3432        }
3433    }
3434
3435    private List<Uri> cleanUris(final List<Uri> uris) {
3436        final Iterator<Uri> iterator = uris.iterator();
3437        while (iterator.hasNext()) {
3438            final Uri uri = iterator.next();
3439            if (FileBackend.dangerousFile(uri)) {
3440                iterator.remove();
3441                Toast.makeText(
3442                                requireActivity(),
3443                                R.string.security_violation_not_attaching_file,
3444                                Toast.LENGTH_SHORT)
3445                        .show();
3446            }
3447        }
3448        return uris;
3449    }
3450
3451    private boolean showBlockSubmenu(View view) {
3452        final Jid jid = conversation.getJid();
3453        final boolean showReject = conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3454        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3455        popupMenu.inflate(R.menu.block);
3456        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3457        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3458        popupMenu.setOnMenuItemClickListener(
3459                menuItem -> {
3460                    Blockable blockable;
3461                    switch (menuItem.getItemId()) {
3462                        case R.id.reject:
3463                            activity.xmppConnectionService.stopPresenceUpdatesTo(
3464                                    conversation.getContact());
3465                            updateSnackBar(conversation);
3466                            return true;
3467                        case R.id.block_domain:
3468                            blockable =
3469                                    conversation
3470                                            .getAccount()
3471                                            .getRoster()
3472                                            .getContact(jid.getDomain());
3473                            break;
3474                        default:
3475                            blockable = conversation;
3476                    }
3477                    BlockContactDialog.show(activity, blockable);
3478                    return true;
3479                });
3480        popupMenu.show();
3481        return true;
3482    }
3483
3484    private void updateSnackBar(final Conversation conversation) {
3485        final Account account = conversation.getAccount();
3486        final XmppConnection connection = account.getXmppConnection();
3487        final int mode = conversation.getMode();
3488        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3489        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3490            return;
3491        }
3492        if (account.getStatus() == Account.State.DISABLED) {
3493            showSnackbar(
3494                    R.string.this_account_is_disabled,
3495                    R.string.enable,
3496                    this.mEnableAccountListener);
3497        } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3498            showSnackbar(R.string.this_account_is_logged_out,R.string.log_in,this.mEnableAccountListener);
3499        } else if (conversation.isBlocked()) {
3500            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3501        } else if (contact != null
3502                && !contact.showInRoster()
3503                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3504            showSnackbar(
3505                    R.string.contact_added_you,
3506                    R.string.add_back,
3507                    this.mAddBackClickListener,
3508                    this.mLongPressBlockListener);
3509        } else if (contact != null
3510                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3511            showSnackbar(
3512                    R.string.contact_asks_for_presence_subscription,
3513                    R.string.allow,
3514                    this.mAllowPresenceSubscription,
3515                    this.mLongPressBlockListener);
3516        } else if (mode == Conversation.MODE_MULTI
3517                && !conversation.getMucOptions().online()
3518                && account.getStatus() == Account.State.ONLINE) {
3519            switch (conversation.getMucOptions().getError()) {
3520                case NICK_IN_USE:
3521                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3522                    break;
3523                case NO_RESPONSE:
3524                    showSnackbar(R.string.joining_conference, 0, null);
3525                    break;
3526                case SERVER_NOT_FOUND:
3527                    if (conversation.receivedMessagesCount() > 0) {
3528                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3529                    } else {
3530                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3531                    }
3532                    break;
3533                case REMOTE_SERVER_TIMEOUT:
3534                    if (conversation.receivedMessagesCount() > 0) {
3535                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3536                    } else {
3537                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3538                    }
3539                    break;
3540                case PASSWORD_REQUIRED:
3541                    showSnackbar(
3542                            R.string.conference_requires_password,
3543                            R.string.enter_password,
3544                            enterPassword);
3545                    break;
3546                case BANNED:
3547                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3548                    break;
3549                case MEMBERS_ONLY:
3550                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3551                    break;
3552                case RESOURCE_CONSTRAINT:
3553                    showSnackbar(
3554                            R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3555                    break;
3556                case KICKED:
3557                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3558                    break;
3559                case TECHNICAL_PROBLEMS:
3560                    showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3561                    break;
3562                case UNKNOWN:
3563                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3564                    break;
3565                case INVALID_NICK:
3566                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3567                case SHUTDOWN:
3568                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3569                    break;
3570                case DESTROYED:
3571                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3572                    break;
3573                case NON_ANONYMOUS:
3574                    showSnackbar(
3575                            R.string.group_chat_will_make_your_jabber_id_public,
3576                            R.string.join,
3577                            acceptJoin);
3578                    break;
3579                default:
3580                    hideSnackbar();
3581                    break;
3582            }
3583        } else if (account.hasPendingPgpIntent(conversation)) {
3584            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3585        } else if (connection != null
3586                && connection.getFeatures().blocking()
3587                && conversation.countMessages() != 0
3588                && !conversation.isBlocked()
3589                && conversation.isWithStranger()) {
3590            showSnackbar(
3591                    R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
3592        } else {
3593            hideSnackbar();
3594        }
3595    }
3596
3597    @Override
3598    public void refresh() {
3599        if (this.binding == null) {
3600            Log.d(
3601                    Config.LOGTAG,
3602                    "ConversationFragment.refresh() skipped updated because view binding was null");
3603            return;
3604        }
3605        if (this.conversation != null
3606                && this.activity != null
3607                && this.activity.xmppConnectionService != null) {
3608            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3609                activity.onConversationArchived(this.conversation);
3610                return;
3611            }
3612        }
3613        this.refresh(true);
3614    }
3615
3616    private void refresh(boolean notifyConversationRead) {
3617        synchronized (this.messageList) {
3618            if (this.conversation != null) {
3619                if (messageListAdapter.hasSelection()) {
3620                    if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3621                } else {
3622                    conversation.populateWithMessages(this.messageList, activity == null ? null : activity.xmppConnectionService);
3623                    updateStatusMessages();
3624                    this.messageListAdapter.notifyDataSetChanged();
3625                }
3626                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3627                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3628                    binding.unreadCountCustomView.setUnreadCount(
3629                            conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3630                }
3631                updateSnackBar(conversation);
3632                if (activity != null) updateChatMsgHint();
3633                if (notifyConversationRead && activity != null) {
3634                    binding.messagesView.post(this::fireReadEvent);
3635                }
3636                updateSendButton();
3637                updateEditablity();
3638                conversation.refreshSessions();
3639            }
3640        }
3641    }
3642
3643    protected void messageSent() {
3644        binding.textinputSubject.setText("");
3645        binding.textinputSubject.setVisibility(View.GONE);
3646        setThread(null);
3647        conversation.setUserSelectedThread(false);
3648        mSendingPgpMessage.set(false);
3649        this.binding.textinput.setText("");
3650        if (conversation.setCorrectingMessage(null)) {
3651            this.binding.textinput.append(conversation.getDraftMessage());
3652            conversation.setDraftMessage(null);
3653        }
3654        storeNextMessage();
3655        updateChatMsgHint();
3656        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3657        final boolean prefScrollToBottom =
3658                p.getBoolean(
3659                        "scroll_to_bottom",
3660                        activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3661        if (prefScrollToBottom || scrolledToBottom()) {
3662            new Handler()
3663                    .post(
3664                            () -> {
3665                                int size = messageList.size();
3666                                this.binding.messagesView.setSelection(size - 1);
3667                            });
3668        }
3669    }
3670
3671    private boolean storeNextMessage() {
3672        return storeNextMessage(this.binding.textinput.getText().toString());
3673    }
3674
3675    private boolean storeNextMessage(String msg) {
3676        final boolean participating =
3677                conversation.getMode() == Conversational.MODE_SINGLE
3678                        || conversation.getMucOptions().participating();
3679        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3680                && participating
3681                && this.conversation.setNextMessage(msg) && activity != null) {
3682            activity.xmppConnectionService.updateConversation(this.conversation);
3683            return true;
3684        }
3685        return false;
3686    }
3687
3688    public void doneSendingPgpMessage() {
3689        mSendingPgpMessage.set(false);
3690    }
3691
3692    public long getMaxHttpUploadSize(Conversation conversation) {
3693        final XmppConnection connection = conversation.getAccount().getXmppConnection();
3694        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3695    }
3696
3697    private boolean canWrite() {
3698        return
3699                this.conversation.getMode() == Conversation.MODE_SINGLE
3700                        || this.conversation.getMucOptions().participating()
3701                        || this.conversation.getNextCounterpart() != null;
3702    }
3703
3704    private void updateEditablity() {
3705        boolean canWrite = canWrite();
3706        this.binding.textinput.setFocusable(canWrite);
3707        this.binding.textinput.setFocusableInTouchMode(canWrite);
3708        this.binding.textSendButton.setEnabled(canWrite);
3709        this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
3710        this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
3711        this.binding.textinput.setCursorVisible(canWrite);
3712        this.binding.textinput.setEnabled(canWrite);
3713    }
3714
3715    public void updateSendButton() {
3716        boolean hasAttachments =
3717                mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3718        final Conversation c = this.conversation;
3719        final Presence.Status status;
3720        final String text =
3721                this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3722        final SendButtonAction action;
3723        if (hasAttachments) {
3724            action = SendButtonAction.TEXT;
3725        } else {
3726            action = SendButtonTool.getAction(getActivity(), c, text, binding.textinputSubject.getText().toString());
3727        }
3728        if (c.getAccount().getStatus() == Account.State.ONLINE) {
3729            if (activity != null
3730                    && activity.xmppConnectionService != null
3731                    && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3732                status = Presence.Status.OFFLINE;
3733            } else if (c.getMode() == Conversation.MODE_SINGLE) {
3734                status = c.getContact().getShownStatus();
3735            } else {
3736                status =
3737                        c.getMucOptions().online()
3738                                ? Presence.Status.ONLINE
3739                                : Presence.Status.OFFLINE;
3740            }
3741        } else {
3742            status = Presence.Status.OFFLINE;
3743        }
3744        this.binding.textSendButton.setTag(action);
3745        this.binding.textSendButton.setIconTint(ColorStateList.valueOf(SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
3746        // TODO send button color
3747        final Activity activity = getActivity();
3748        if (activity != null) {
3749            this.binding.textSendButton.setIconResource(
3750                    SendButtonTool.getSendButtonImageResource(action, text.length() > 0 || hasAttachments || (c.getThread() != null && binding.textinputSubject.getText().length() > 0)));
3751        }
3752
3753        ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3754        if (identiconWidth < 0) identiconWidth = params.width;
3755        if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
3756            binding.conversationViewPager.setCurrentItem(0);
3757            params.width = conversation.getThread() == null ? 0 : identiconWidth;
3758        } else {
3759            params.width = identiconWidth;
3760        }
3761        if (!canWrite()) params.width = 0;
3762        binding.threadIdenticonLayout.setLayoutParams(params);
3763    }
3764
3765    protected void updateStatusMessages() {
3766        DateSeparator.addAll(this.messageList);
3767        if (showLoadMoreMessages(conversation)) {
3768            this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3769        }
3770        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3771            ChatState state = conversation.getIncomingChatState();
3772            if (state == ChatState.COMPOSING) {
3773                this.messageList.add(
3774                        Message.createStatusMessage(
3775                                conversation,
3776                                getString(R.string.contact_is_typing, conversation.getName())));
3777            } else if (state == ChatState.PAUSED) {
3778                this.messageList.add(
3779                        Message.createStatusMessage(
3780                                conversation,
3781                                getString(
3782                                        R.string.contact_has_stopped_typing,
3783                                        conversation.getName())));
3784            } else {
3785                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3786                    final Message message = this.messageList.get(i);
3787                    if (message.getType() != Message.TYPE_STATUS) {
3788                        if (message.getStatus() == Message.STATUS_RECEIVED) {
3789                            return;
3790                        } else {
3791                            if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3792                                this.messageList.add(
3793                                        i + 1,
3794                                        Message.createStatusMessage(
3795                                                conversation,
3796                                                getString(
3797                                                        R.string.contact_has_read_up_to_this_point,
3798                                                        conversation.getName())));
3799                                return;
3800                            }
3801                        }
3802                    }
3803                }
3804            }
3805        } else {
3806            final MucOptions mucOptions = conversation.getMucOptions();
3807            final List<MucOptions.User> allUsers = mucOptions.getUsers();
3808            final Set<ReadByMarker> addedMarkers = new HashSet<>();
3809            ChatState state = ChatState.COMPOSING;
3810            List<MucOptions.User> users =
3811                    conversation.getMucOptions().getUsersWithChatState(state, 5);
3812            if (users.size() == 0) {
3813                state = ChatState.PAUSED;
3814                users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3815            }
3816            if (mucOptions.isPrivateAndNonAnonymous()) {
3817                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3818                    final Set<ReadByMarker> markersForMessage =
3819                            messageList.get(i).getReadByMarkers();
3820                    final List<MucOptions.User> shownMarkers = new ArrayList<>();
3821                    for (ReadByMarker marker : markersForMessage) {
3822                        if (!ReadByMarker.contains(marker, addedMarkers)) {
3823                            addedMarkers.add(
3824                                    marker); // may be put outside this condition. set should do
3825                                             // dedup anyway
3826                            MucOptions.User user = mucOptions.findUser(marker);
3827                            if (user != null && !users.contains(user)) {
3828                                shownMarkers.add(user);
3829                            }
3830                        }
3831                    }
3832                    final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3833                    final Message statusMessage;
3834                    final int size = shownMarkers.size();
3835                    if (size > 1) {
3836                        final String body;
3837                        if (size <= 4) {
3838                            body =
3839                                    getString(
3840                                            R.string.contacts_have_read_up_to_this_point,
3841                                            UIHelper.concatNames(shownMarkers));
3842                        } else if (ReadByMarker.allUsersRepresented(
3843                                allUsers, markersForMessage, markerForSender)) {
3844                            body = getString(R.string.everyone_has_read_up_to_this_point);
3845                        } else {
3846                            body =
3847                                    getString(
3848                                            R.string.contacts_and_n_more_have_read_up_to_this_point,
3849                                            UIHelper.concatNames(shownMarkers, 3),
3850                                            size - 3);
3851                        }
3852                        statusMessage = Message.createStatusMessage(conversation, body);
3853                        statusMessage.setCounterparts(shownMarkers);
3854                    } else if (size == 1) {
3855                        statusMessage =
3856                                Message.createStatusMessage(
3857                                        conversation,
3858                                        getString(
3859                                                R.string.contact_has_read_up_to_this_point,
3860                                                UIHelper.getDisplayName(shownMarkers.get(0))));
3861                        statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3862                        statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3863                    } else {
3864                        statusMessage = null;
3865                    }
3866                    if (statusMessage != null) {
3867                        this.messageList.add(i + 1, statusMessage);
3868                    }
3869                    addedMarkers.add(markerForSender);
3870                    if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3871                        break;
3872                    }
3873                }
3874            }
3875            if (users.size() > 0) {
3876                Message statusMessage;
3877                if (users.size() == 1) {
3878                    MucOptions.User user = users.get(0);
3879                    int id =
3880                            state == ChatState.COMPOSING
3881                                    ? R.string.contact_is_typing
3882                                    : R.string.contact_has_stopped_typing;
3883                    statusMessage =
3884                            Message.createStatusMessage(
3885                                    conversation, getString(id, UIHelper.getDisplayName(user)));
3886                    statusMessage.setTrueCounterpart(user.getRealJid());
3887                    statusMessage.setCounterpart(user.getFullJid());
3888                } else {
3889                    int id =
3890                            state == ChatState.COMPOSING
3891                                    ? R.string.contacts_are_typing
3892                                    : R.string.contacts_have_stopped_typing;
3893                    statusMessage =
3894                            Message.createStatusMessage(
3895                                    conversation, getString(id, UIHelper.concatNames(users)));
3896                    statusMessage.setCounterparts(users);
3897                }
3898                this.messageList.add(statusMessage);
3899            }
3900        }
3901    }
3902
3903    private void stopScrolling() {
3904        long now = SystemClock.uptimeMillis();
3905        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3906        binding.messagesView.dispatchTouchEvent(cancel);
3907    }
3908
3909    private boolean showLoadMoreMessages(final Conversation c) {
3910        if (activity == null || activity.xmppConnectionService == null) {
3911            return false;
3912        }
3913        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3914        final MessageArchiveService service =
3915                activity.xmppConnectionService.getMessageArchiveService();
3916        return mam
3917                && (c.getLastClearHistory().getTimestamp() != 0
3918                        || (c.countMessages() == 0
3919                                && c.messagesLoaded.get()
3920                                && c.hasMessagesLeftOnServer()
3921                                && !service.queryInProgress(c)));
3922    }
3923
3924    private boolean hasMamSupport(final Conversation c) {
3925        if (c.getMode() == Conversation.MODE_SINGLE) {
3926            final XmppConnection connection = c.getAccount().getXmppConnection();
3927            return connection != null && connection.getFeatures().mam();
3928        } else {
3929            return c.getMucOptions().mamSupport();
3930        }
3931    }
3932
3933    protected void showSnackbar(
3934            final int message, final int action, final OnClickListener clickListener) {
3935        showSnackbar(message, action, clickListener, null);
3936    }
3937
3938    protected void showSnackbar(
3939            final int message,
3940            final int action,
3941            final OnClickListener clickListener,
3942            final View.OnLongClickListener longClickListener) {
3943        this.binding.snackbar.setVisibility(View.VISIBLE);
3944        this.binding.snackbar.setOnClickListener(null);
3945        this.binding.snackbarMessage.setText(message);
3946        this.binding.snackbarMessage.setOnClickListener(null);
3947        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3948        if (action != 0) {
3949            this.binding.snackbarAction.setText(action);
3950        }
3951        this.binding.snackbarAction.setOnClickListener(clickListener);
3952        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3953    }
3954
3955    protected void hideSnackbar() {
3956        this.binding.snackbar.setVisibility(View.GONE);
3957    }
3958
3959    protected void sendMessage(Message message) {
3960        new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
3961        messageSent();
3962    }
3963
3964    protected void sendPgpMessage(final Message message) {
3965        final XmppConnectionService xmppService = activity.xmppConnectionService;
3966        final Contact contact = message.getConversation().getContact();
3967        if (!activity.hasPgp()) {
3968            activity.showInstallPgpDialog();
3969            return;
3970        }
3971        if (conversation.getAccount().getPgpSignature() == null) {
3972            activity.announcePgp(
3973                    conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3974            return;
3975        }
3976        if (!mSendingPgpMessage.compareAndSet(false, true)) {
3977            Log.d(Config.LOGTAG, "sending pgp message already in progress");
3978        }
3979        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3980            if (contact.getPgpKeyId() != 0) {
3981                xmppService
3982                        .getPgpEngine()
3983                        .hasKey(
3984                                contact,
3985                                new UiCallback<Contact>() {
3986
3987                                    @Override
3988                                    public void userInputRequired(
3989                                            PendingIntent pi, Contact contact) {
3990                                        startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3991                                    }
3992
3993                                    @Override
3994                                    public void success(Contact contact) {
3995                                        encryptTextMessage(message);
3996                                    }
3997
3998                                    @Override
3999                                    public void error(int error, Contact contact) {
4000                                        activity.runOnUiThread(
4001                                                () ->
4002                                                        Toast.makeText(
4003                                                                        activity,
4004                                                                        R.string
4005                                                                                .unable_to_connect_to_keychain,
4006                                                                        Toast.LENGTH_SHORT)
4007                                                                .show());
4008                                        mSendingPgpMessage.set(false);
4009                                    }
4010                                });
4011
4012            } else {
4013                showNoPGPKeyDialog(
4014                        false,
4015                        (dialog, which) -> {
4016                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4017                            xmppService.updateConversation(conversation);
4018                            message.setEncryption(Message.ENCRYPTION_NONE);
4019                            xmppService.sendMessage(message);
4020                            messageSent();
4021                        });
4022            }
4023        } else {
4024            if (conversation.getMucOptions().pgpKeysInUse()) {
4025                if (!conversation.getMucOptions().everybodyHasKeys()) {
4026                    Toast warning =
4027                            Toast.makeText(
4028                                    getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
4029                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
4030                    warning.show();
4031                }
4032                encryptTextMessage(message);
4033            } else {
4034                showNoPGPKeyDialog(
4035                        true,
4036                        (dialog, which) -> {
4037                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4038                            message.setEncryption(Message.ENCRYPTION_NONE);
4039                            xmppService.updateConversation(conversation);
4040                            xmppService.sendMessage(message);
4041                            messageSent();
4042                        });
4043            }
4044        }
4045    }
4046
4047    public void encryptTextMessage(Message message) {
4048        activity.xmppConnectionService
4049                .getPgpEngine()
4050                .encrypt(
4051                        message,
4052                        new UiCallback<Message>() {
4053
4054                            @Override
4055                            public void userInputRequired(PendingIntent pi, Message message) {
4056                                startPendingIntent(pi, REQUEST_SEND_MESSAGE);
4057                            }
4058
4059                            @Override
4060                            public void success(Message message) {
4061                                // TODO the following two call can be made before the callback
4062                                getActivity().runOnUiThread(() -> messageSent());
4063                            }
4064
4065                            @Override
4066                            public void error(final int error, Message message) {
4067                                getActivity()
4068                                        .runOnUiThread(
4069                                                () -> {
4070                                                    doneSendingPgpMessage();
4071                                                    Toast.makeText(
4072                                                                    getActivity(),
4073                                                                    error == 0
4074                                                                            ? R.string
4075                                                                                    .unable_to_connect_to_keychain
4076                                                                            : error,
4077                                                                    Toast.LENGTH_SHORT)
4078                                                            .show();
4079                                                });
4080                            }
4081                        });
4082    }
4083
4084    public void showNoPGPKeyDialog(final boolean plural, final DialogInterface.OnClickListener listener) {
4085        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
4086        if (plural) {
4087            builder.setTitle(getString(R.string.no_pgp_keys));
4088            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
4089        } else {
4090            builder.setTitle(getString(R.string.no_pgp_key));
4091            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
4092        }
4093        builder.setNegativeButton(getString(R.string.cancel), null);
4094        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
4095        builder.create().show();
4096    }
4097
4098    public void appendText(String text, final boolean doNotAppend) {
4099        if (text == null) {
4100            return;
4101        }
4102        final Editable editable = this.binding.textinput.getText();
4103        String previous = editable == null ? "" : editable.toString();
4104        if (doNotAppend && !TextUtils.isEmpty(previous)) {
4105            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
4106                    .show();
4107            return;
4108        }
4109        if (UIHelper.isLastLineQuote(previous)) {
4110            text = '\n' + text;
4111        } else if (previous.length() != 0
4112                && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4113            text = " " + text;
4114        }
4115        this.binding.textinput.append(text);
4116    }
4117
4118    @Override
4119    public boolean onEnterPressed(final boolean isCtrlPressed) {
4120        if (isCtrlPressed || enterIsSend()) {
4121            sendMessage();
4122            return true;
4123        }
4124        return false;
4125    }
4126
4127    private boolean enterIsSend() {
4128        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4129        return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4130    }
4131
4132    public boolean onArrowUpCtrlPressed() {
4133        final Message lastEditableMessage =
4134                conversation == null ? null : conversation.getLastEditableMessage();
4135        if (lastEditableMessage != null) {
4136            correctMessage(lastEditableMessage);
4137            return true;
4138        } else {
4139            Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4140                    .show();
4141            return false;
4142        }
4143    }
4144
4145    @Override
4146    public void onTypingStarted() {
4147        final XmppConnectionService service =
4148                activity == null ? null : activity.xmppConnectionService;
4149        if (service == null) {
4150            return;
4151        }
4152        final Account.State status = conversation.getAccount().getStatus();
4153        if (status == Account.State.ONLINE
4154                && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4155            service.sendChatState(conversation);
4156        }
4157        runOnUiThread(this::updateSendButton);
4158    }
4159
4160    @Override
4161    public void onTypingStopped() {
4162        final XmppConnectionService service =
4163                activity == null ? null : activity.xmppConnectionService;
4164        if (service == null) {
4165            return;
4166        }
4167        final Account.State status = conversation.getAccount().getStatus();
4168        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4169            service.sendChatState(conversation);
4170        }
4171    }
4172
4173    @Override
4174    public void onTextDeleted() {
4175        final XmppConnectionService service =
4176                activity == null ? null : activity.xmppConnectionService;
4177        if (service == null) {
4178            return;
4179        }
4180        final Account.State status = conversation.getAccount().getStatus();
4181        if (status == Account.State.ONLINE
4182                && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4183            service.sendChatState(conversation);
4184        }
4185        if (storeNextMessage()) {
4186            runOnUiThread(
4187                    () -> {
4188                        if (activity == null) {
4189                            return;
4190                        }
4191                        activity.onConversationsListItemUpdated();
4192                    });
4193        }
4194        runOnUiThread(this::updateSendButton);
4195    }
4196
4197    @Override
4198    public void onTextChanged() {
4199        if (conversation != null && conversation.getCorrectingMessage() != null) {
4200            runOnUiThread(this::updateSendButton);
4201        }
4202    }
4203
4204    @Override
4205    public boolean onTabPressed(boolean repeated) {
4206        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4207            return false;
4208        }
4209        if (repeated) {
4210            completionIndex++;
4211        } else {
4212            lastCompletionLength = 0;
4213            completionIndex = 0;
4214            final String content = this.binding.textinput.getText().toString();
4215            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4216            int start =
4217                    lastCompletionCursor > 0
4218                            ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4219                            : 0;
4220            firstWord = start == 0;
4221            incomplete = content.substring(start, lastCompletionCursor);
4222        }
4223        List<String> completions = new ArrayList<>();
4224        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4225            String name = user.getNick();
4226            if (name != null && name.startsWith(incomplete)) {
4227                completions.add(name + (firstWord ? ": " : " "));
4228            }
4229        }
4230        Collections.sort(completions);
4231        if (completions.size() > completionIndex) {
4232            String completion = completions.get(completionIndex).substring(incomplete.length());
4233            this.binding
4234                    .textinput
4235                    .getEditableText()
4236                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4237            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4238            lastCompletionLength = completion.length();
4239        } else {
4240            completionIndex = -1;
4241            this.binding
4242                    .textinput
4243                    .getEditableText()
4244                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4245            lastCompletionLength = 0;
4246        }
4247        return true;
4248    }
4249
4250    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4251        try {
4252            getActivity()
4253                    .startIntentSenderForResult(
4254                            pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
4255        } catch (final SendIntentException ignored) {
4256        }
4257    }
4258
4259    @Override
4260    public void onBackendConnected() {
4261        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4262        setupEmojiSearch();
4263        String uuid = pendingConversationsUuid.pop();
4264        if (uuid != null) {
4265            if (!findAndReInitByUuidOrArchive(uuid)) {
4266                return;
4267            }
4268        } else {
4269            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4270                clearPending();
4271                activity.onConversationArchived(conversation);
4272                return;
4273            }
4274        }
4275        ActivityResult activityResult = postponedActivityResult.pop();
4276        if (activityResult != null) {
4277            handleActivityResult(activityResult);
4278        }
4279        clearPending();
4280    }
4281
4282    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4283        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4284        if (conversation == null) {
4285            clearPending();
4286            activity.onConversationArchived(null);
4287            return false;
4288        }
4289        reInit(conversation);
4290        ScrollState scrollState = pendingScrollState.pop();
4291        String lastMessageUuid = pendingLastMessageUuid.pop();
4292        List<Attachment> attachments = pendingMediaPreviews.pop();
4293        if (scrollState != null) {
4294            setScrollPosition(scrollState, lastMessageUuid);
4295        }
4296        if (attachments != null && attachments.size() > 0) {
4297            Log.d(Config.LOGTAG, "had attachments on restore");
4298            mediaPreviewAdapter.addMediaPreviews(attachments);
4299            toggleInputMethod();
4300        }
4301        return true;
4302    }
4303
4304    private void clearPending() {
4305        if (postponedActivityResult.clear()) {
4306            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4307            if (pendingTakePhotoUri.clear()) {
4308                Log.e(Config.LOGTAG, "cleared pending photo uri");
4309            }
4310        }
4311        if (pendingScrollState.clear()) {
4312            Log.e(Config.LOGTAG, "cleared scroll state");
4313        }
4314        if (pendingConversationsUuid.clear()) {
4315            Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4316        }
4317        if (pendingMediaPreviews.clear()) {
4318            Log.e(Config.LOGTAG, "cleared pending media previews");
4319        }
4320    }
4321
4322    public Conversation getConversation() {
4323        return conversation;
4324    }
4325
4326    @Override
4327    public void onContactPictureLongClicked(View v, final Message message) {
4328        final String fingerprint;
4329        if (message.getEncryption() == Message.ENCRYPTION_PGP
4330                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4331            fingerprint = "pgp";
4332        } else {
4333            fingerprint = message.getFingerprint();
4334        }
4335        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4336        final Contact contact = message.getContact();
4337        if (message.getStatus() <= Message.STATUS_RECEIVED
4338                && (contact == null || !contact.isSelf())) {
4339            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4340                final Jid cp = message.getCounterpart();
4341                if (cp == null || cp.isBareJid()) {
4342                    return;
4343                }
4344                final Jid tcp = message.getTrueCounterpart();
4345                final User userByRealJid =
4346                        tcp != null
4347                                ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
4348                                : null;
4349                final String occupantId = message.getOccupantId();
4350                final User userByOccupantId =
4351                        occupantId != null
4352                                ? conversation.getMucOptions().findUserByOccupantId(occupantId)
4353                                : null;
4354                final User user =
4355                        userByRealJid != null
4356                                ? userByRealJid
4357                                : (userByOccupantId != null ? userByOccupantId : conversation.getMucOptions().findUserByFullJid(cp));
4358                if (user == null) return;
4359                popupMenu.inflate(R.menu.muc_details_context);
4360                final Menu menu = popupMenu.getMenu();
4361                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4362                        activity, menu, conversation, user);
4363                popupMenu.setOnMenuItemClickListener(
4364                        menuItem ->
4365                                MucDetailsContextMenuHelper.onContextItemSelected(
4366                                        menuItem, user, activity, fingerprint));
4367            } else {
4368                popupMenu.inflate(R.menu.one_on_one_context);
4369                popupMenu.setOnMenuItemClickListener(
4370                        item -> {
4371                            switch (item.getItemId()) {
4372                                case R.id.action_contact_details:
4373                                    activity.switchToContactDetails(
4374                                            message.getContact(), fingerprint);
4375                                    break;
4376                                case R.id.action_show_qr_code:
4377                                    activity.showQrCode(
4378                                            "xmpp:"
4379                                                    + message.getContact()
4380                                                            .getJid()
4381                                                            .asBareJid()
4382                                                            .toEscapedString());
4383                                    break;
4384                            }
4385                            return true;
4386                        });
4387            }
4388        } else {
4389            popupMenu.inflate(R.menu.account_context);
4390            final Menu menu = popupMenu.getMenu();
4391            menu.findItem(R.id.action_manage_accounts)
4392                    .setVisible(QuickConversationsService.isConversations());
4393            popupMenu.setOnMenuItemClickListener(
4394                    item -> {
4395                        final XmppActivity activity = this.activity;
4396                        if (activity == null) {
4397                            Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4398                            return true;
4399                        }
4400                        switch (item.getItemId()) {
4401                            case R.id.action_show_qr_code:
4402                                activity.showQrCode(conversation.getAccount().getShareableUri());
4403                                break;
4404                            case R.id.action_account_details:
4405                                activity.switchToAccount(
4406                                        message.getConversation().getAccount(), fingerprint);
4407                                break;
4408                            case R.id.action_manage_accounts:
4409                                AccountUtils.launchManageAccounts(activity);
4410                                break;
4411                        }
4412                        return true;
4413                    });
4414        }
4415        popupMenu.show();
4416    }
4417
4418    @Override
4419    public void onContactPictureClicked(Message message) {
4420        setThread(message.getThread());
4421        if (message.isPrivateMessage()) {
4422            privateMessageWith(message.getCounterpart());
4423            return;
4424        }
4425        forkNullThread(message);
4426        conversation.setUserSelectedThread(true);
4427
4428        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4429        if (received) {
4430            if (message.getConversation() instanceof Conversation
4431                    && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4432                Jid tcp = message.getTrueCounterpart();
4433                Jid user = message.getCounterpart();
4434                if (user != null && !user.isBareJid()) {
4435                    final MucOptions mucOptions =
4436                            ((Conversation) message.getConversation()).getMucOptions();
4437                    if (mucOptions.participating()
4438                            || ((Conversation) message.getConversation()).getNextCounterpart()
4439                                    != null) {
4440                        MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4441                        MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4442                        if (mucUser == null && tcpMucUser == null) {
4443                            Toast.makeText(
4444                                            getActivity(),
4445                                            activity.getString(
4446                                                    R.string.user_has_left_conference,
4447                                                    user.getResource()),
4448                                            Toast.LENGTH_SHORT)
4449                                    .show();
4450                        }
4451                        highlightInConference(mucUser == null || mucUser.getNick() == null ? (tcpMucUser == null || tcpMucUser.getNick() == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4452                    } else {
4453                        Toast.makeText(
4454                                        getActivity(),
4455                                        R.string.you_are_not_participating,
4456                                        Toast.LENGTH_SHORT)
4457                                .show();
4458                    }
4459                }
4460            }
4461        }
4462    }
4463
4464    private Activity requireActivity() {
4465        Activity activity = getActivity();
4466        if (activity == null) activity = this.activity;
4467        if (activity == null) {
4468            throw new IllegalStateException("Activity not attached");
4469        }
4470        return activity;
4471    }
4472}