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