ConversationFragment.java

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