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