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        messageListAdapter.setOnMessageBoxSwiped(message -> {
1307            setupReply(message);
1308        });
1309
1310        binding.threadIdenticonLayout.setOnClickListener(v -> {
1311            boolean wasLocked = conversation.getLockThread();
1312            conversation.setLockThread(false);
1313            backPressedLeaveSingleThread.setEnabled(false);
1314            if (wasLocked) {
1315                conversation.setUserSelectedThread(false);
1316                refresh();
1317                updateThreadFromLastMessage();
1318            } else {
1319                newThread();
1320                conversation.setUserSelectedThread(true);
1321                newThreadTutorialToast("Switched to new thread");
1322            }
1323        });
1324
1325        binding.threadIdenticonLayout.setOnLongClickListener(v -> {
1326            boolean wasLocked = conversation.getLockThread();
1327            conversation.setLockThread(false);
1328            backPressedLeaveSingleThread.setEnabled(false);
1329            setThread(null);
1330            conversation.setUserSelectedThread(true);
1331            if (wasLocked) refresh();
1332            newThreadTutorialToast("Cleared thread");
1333            return true;
1334        });
1335
1336        return binding.getRoot();
1337    }
1338
1339    protected void newThreadTutorialToast(String s) {
1340        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1341        final int tutorialCount = p.getInt("thread_tutorial", 0);
1342        if (tutorialCount < 5) {
1343            Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
1344            p.edit().putInt("thread_tutorial", tutorialCount + 1).apply();
1345        }
1346    }
1347
1348    @Override
1349    public void onDestroyView() {
1350        super.onDestroyView();
1351        Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1352        messageListAdapter.setOnContactPictureClicked(null);
1353        messageListAdapter.setOnContactPictureLongClicked(null);
1354        messageListAdapter.setOnInlineImageLongClicked(null);
1355        if (conversation != null) conversation.setupViewPager(null, null);
1356    }
1357
1358    private void quoteText(String text) {
1359        if (binding.textinput.isEnabled()) {
1360            binding.textinput.insertAsQuote(text);
1361            binding.textinput.requestFocus();
1362            InputMethodManager inputMethodManager =
1363                    (InputMethodManager)
1364                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1365            if (inputMethodManager != null) {
1366                inputMethodManager.showSoftInput(
1367                        binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1368            }
1369        }
1370    }
1371
1372    private void quoteMessage(Message message) {
1373        setThread(message.getThread());
1374        conversation.setUserSelectedThread(true);
1375        if (message.getThread() == null) newThread();
1376        setupReply(message);
1377    }
1378
1379    private void setupReply(Message message) {
1380        conversation.setReplyTo(message);
1381        if (message == null) {
1382            binding.contextPreview.setVisibility(View.GONE);
1383            return;
1384        }
1385
1386        SpannableStringBuilder body = message.getSpannableBody(null, null);
1387        if (message.isFileOrImage() || message.isOOb()) body.append(" 🖼️");
1388        messageListAdapter.handleTextQuotes(body, activity.isDarkTheme());
1389        binding.contextPreviewText.setText(body);
1390        binding.contextPreview.setVisibility(View.VISIBLE);
1391    }
1392
1393    private void setThread(Element thread) {
1394        this.conversation.setThread(thread);
1395        binding.threadIdenticon.setAlpha(0f);
1396        binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1397        if (thread != null) {
1398            final String threadId = thread.getContent();
1399            if (threadId != null) {
1400                binding.threadIdenticon.setAlpha(1f);
1401                binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1402                binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1403            }
1404        }
1405        updateSendButton();
1406    }
1407
1408    @Override
1409    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1410        // This should cancel any remaining click events that would otherwise trigger links
1411        v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1412        synchronized (this.messageList) {
1413            super.onCreateContextMenu(menu, v, menuInfo);
1414            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1415            this.selectedMessage = this.messageList.get(acmi.position);
1416            populateContextMenu(menu);
1417        }
1418    }
1419
1420    private void populateContextMenu(ContextMenu menu) {
1421        final Message m = this.selectedMessage;
1422        final Transferable t = m.getTransferable();
1423        Message relevantForCorrection = m;
1424        while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1425            relevantForCorrection = relevantForCorrection.next();
1426        }
1427        if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1428
1429            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1430                    || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1431                return;
1432            }
1433
1434            if (m.getStatus() == Message.STATUS_RECEIVED
1435                    && t != null
1436                    && (t.getStatus() == Transferable.STATUS_CANCELLED
1437                            || t.getStatus() == Transferable.STATUS_FAILED)) {
1438                return;
1439            }
1440
1441            final boolean deleted = m.isDeleted();
1442            final boolean encrypted =
1443                    m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1444                            || m.getEncryption() == Message.ENCRYPTION_PGP;
1445            final boolean receiving =
1446                    m.getStatus() == Message.STATUS_RECEIVED
1447                            && (t instanceof JingleFileTransferConnection
1448                                    || t instanceof HttpDownloadConnection);
1449            activity.getMenuInflater().inflate(R.menu.message_context, menu);
1450            MenuItem openWith = menu.findItem(R.id.open_with);
1451            MenuItem copyMessage = menu.findItem(R.id.copy_message);
1452            MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1453            MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1454            MenuItem correctMessage = menu.findItem(R.id.correct_message);
1455            MenuItem retractMessage = menu.findItem(R.id.retract_message);
1456            MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
1457            MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1458            MenuItem shareWith = menu.findItem(R.id.share_with);
1459            MenuItem sendAgain = menu.findItem(R.id.send_again);
1460            MenuItem copyUrl = menu.findItem(R.id.copy_url);
1461            MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
1462            MenuItem downloadFile = menu.findItem(R.id.download_file);
1463            MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1464            MenuItem blockMedia = menu.findItem(R.id.block_media);
1465            MenuItem deleteFile = menu.findItem(R.id.delete_file);
1466            MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1467            onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1468            final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1469            final boolean showError =
1470                    m.getStatus() == Message.STATUS_SEND_FAILED
1471                            && m.getErrorMessage() != null
1472                            && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1473            if (!encrypted && !m.getBody().equals("")) {
1474                copyMessage.setVisible(true);
1475            }
1476            quoteMessage.setVisible(!encrypted && !showError);
1477            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1478                retryDecryption.setVisible(true);
1479            }
1480            if (!showError
1481                    && relevantForCorrection.getType() == Message.TYPE_TEXT
1482                    && !m.isGeoUri()
1483                    && relevantForCorrection.isLastCorrectableMessage()
1484                    && m.getConversation() instanceof Conversation) {
1485                correctMessage.setVisible(true);
1486                if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1487            }
1488            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")) {
1489                moderateMessage.setVisible(true);
1490            }
1491            if ((m.isFileOrImage() && !deleted && !receiving)
1492                    || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1493                            && !unInitiatedButKnownSize
1494                            && t == null) {
1495                shareWith.setVisible(true);
1496            }
1497            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1498                sendAgain.setVisible(true);
1499            }
1500            if (m.hasFileOnRemoteHost()
1501                    || m.isGeoUri()
1502                    || m.treatAsDownloadable()
1503                    || unInitiatedButKnownSize
1504                    || t instanceof HttpDownloadConnection) {
1505                copyUrl.setVisible(true);
1506            }
1507            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1508                downloadFile.setVisible(true);
1509                downloadFile.setTitle(
1510                        activity.getString(
1511                                R.string.download_x_file,
1512                                UIHelper.getFileDescriptionString(activity, m)));
1513            }
1514            final boolean waitingOfferedSending =
1515                    m.getStatus() == Message.STATUS_WAITING
1516                            || m.getStatus() == Message.STATUS_UNSEND
1517                            || m.getStatus() == Message.STATUS_OFFERED;
1518            final boolean cancelable =
1519                    (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1520            if (cancelable) {
1521                cancelTransmission.setVisible(true);
1522            }
1523            if (m.isFileOrImage() && !deleted && !cancelable) {
1524                final String path = m.getRelativeFilePath();
1525                if (path == null
1526                        || !path.startsWith("/")
1527                        || FileBackend.inConversationsDirectory(requireActivity(), path)) {
1528                    saveAsSticker.setVisible(true);
1529                    blockMedia.setVisible(true);
1530                    deleteFile.setVisible(true);
1531                    deleteFile.setTitle(
1532                            activity.getString(
1533                                    R.string.delete_x_file,
1534                                    UIHelper.getFileDescriptionString(activity, m)));
1535                }
1536            }
1537
1538            if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
1539                // We might be showing a thumbnail worth blocking
1540                blockMedia.setVisible(true);
1541            }
1542            if (showError) {
1543                showErrorMessage.setVisible(true);
1544            }
1545            final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1546            if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1547                    || (mime != null && mime.startsWith("audio/"))) {
1548                openWith.setVisible(true);
1549            }
1550        }
1551    }
1552
1553    @Override
1554    public boolean onContextItemSelected(MenuItem item) {
1555        switch (item.getItemId()) {
1556            case R.id.share_with:
1557                ShareUtil.share(activity, selectedMessage);
1558                return true;
1559            case R.id.correct_message:
1560                correctMessage(selectedMessage);
1561                return true;
1562            case R.id.retract_message:
1563                new AlertDialog.Builder(activity)
1564                    .setTitle(R.string.retract_message)
1565                    .setMessage("Do you really want to retract this message?")
1566                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1567                        Message message = selectedMessage;
1568                        while (message.mergeable(message.next())) {
1569                            message = message.next();
1570                        }
1571                        message.setBody(" ");
1572                        message.putEdited(message.getUuid(), message.getServerMsgId());
1573                        message.setServerMsgId(null);
1574                        message.setUuid(UUID.randomUUID().toString());
1575                        sendMessage(message);
1576                    })
1577                    .setNegativeButton(R.string.no, null).show();
1578                return true;
1579            case R.id.moderate_message:
1580                activity.quickEdit("Spam", (reason) -> {
1581                    activity.xmppConnectionService.moderateMessage(conversation.getAccount(), selectedMessage, reason);
1582                    return null;
1583                }, R.string.moderate_reason, false, false, true);
1584                return true;
1585            case R.id.copy_message:
1586                ShareUtil.copyToClipboard(activity, selectedMessage);
1587                return true;
1588            case R.id.quote_message:
1589                quoteMessage(selectedMessage);
1590                return true;
1591            case R.id.send_again:
1592                resendMessage(selectedMessage);
1593                return true;
1594            case R.id.copy_url:
1595                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1596                return true;
1597            case R.id.save_as_sticker:
1598                saveAsSticker(selectedMessage);
1599                return true;
1600            case R.id.download_file:
1601                startDownloadable(selectedMessage);
1602                return true;
1603            case R.id.cancel_transmission:
1604                cancelTransmission(selectedMessage);
1605                return true;
1606            case R.id.retry_decryption:
1607                retryDecryption(selectedMessage);
1608                return true;
1609            case R.id.block_media:
1610                new AlertDialog.Builder(activity)
1611                    .setTitle(R.string.block_media)
1612                    .setMessage("Do you really want to block this media in all messages?")
1613                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1614                        List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
1615                        if (thumbs != null && !thumbs.isEmpty()) {
1616                            for (Element thumb : thumbs) {
1617                                Uri uri = Uri.parse(thumb.getAttribute("uri"));
1618                                if (uri.getScheme().equals("cid")) {
1619                                    Cid cid = BobTransfer.cid(uri);
1620                                    if (cid == null) continue;
1621                                    DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
1622                                    activity.xmppConnectionService.blockMedia(f);
1623                                    activity.xmppConnectionService.evictPreview(f);
1624                                    f.delete();
1625                                }
1626                            }
1627                        }
1628                        File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
1629                        activity.xmppConnectionService.blockMedia(f);
1630                        activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
1631                        selectedMessage.setDeleted(true);
1632                        activity.xmppConnectionService.evictPreview(f);
1633                        activity.xmppConnectionService.updateMessage(selectedMessage, false);
1634                        activity.onConversationsListItemUpdated();
1635                        refresh();
1636                    })
1637                    .setNegativeButton(R.string.no, null).show();
1638                return true;
1639            case R.id.delete_file:
1640                deleteFile(selectedMessage);
1641                return true;
1642            case R.id.show_error_message:
1643                showErrorMessage(selectedMessage);
1644                return true;
1645            case R.id.open_with:
1646                openWith(selectedMessage);
1647                return true;
1648            case R.id.only_this_thread:
1649                conversation.setLockThread(true);
1650                backPressedLeaveSingleThread.setEnabled(true);
1651                setThread(selectedMessage.getThread());
1652                refresh();
1653                return true;
1654            default:
1655                return super.onContextItemSelected(item);
1656        }
1657    }
1658
1659    @Override
1660    public boolean onOptionsItemSelected(final MenuItem item) {
1661        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1662            return false;
1663        } else if (conversation == null) {
1664            return super.onOptionsItemSelected(item);
1665        }
1666        switch (item.getItemId()) {
1667            case R.id.encryption_choice_axolotl:
1668            case R.id.encryption_choice_pgp:
1669            case R.id.encryption_choice_none:
1670                handleEncryptionSelection(item);
1671                break;
1672            case R.id.attach_choose_picture:
1673            case R.id.attach_take_picture:
1674            case R.id.attach_record_video:
1675            case R.id.attach_choose_file:
1676            case R.id.attach_record_voice:
1677            case R.id.attach_location:
1678                handleAttachmentSelection(item);
1679                break;
1680            case R.id.action_search:
1681                startSearch();
1682                break;
1683            case R.id.action_archive:
1684                activity.xmppConnectionService.archiveConversation(conversation);
1685                break;
1686            case R.id.action_contact_details:
1687                activity.switchToContactDetails(conversation.getContact());
1688                break;
1689            case R.id.action_muc_details:
1690                ConferenceDetailsActivity.open(activity, conversation);
1691                break;
1692            case R.id.action_invite:
1693                startActivityForResult(
1694                        ChooseContactActivity.create(activity, conversation),
1695                        REQUEST_INVITE_TO_CONVERSATION);
1696                break;
1697            case R.id.action_clear_history:
1698                clearHistoryDialog(conversation);
1699                break;
1700            case R.id.action_mute:
1701                muteConversationDialog(conversation);
1702                break;
1703            case R.id.action_unmute:
1704                unMuteConversation(conversation);
1705                break;
1706            case R.id.action_block:
1707            case R.id.action_unblock:
1708                final Activity activity = getActivity();
1709                if (activity instanceof XmppActivity) {
1710                    BlockContactDialog.show((XmppActivity) activity, conversation);
1711                }
1712                break;
1713            case R.id.action_audio_call:
1714                checkPermissionAndTriggerAudioCall();
1715                break;
1716            case R.id.action_video_call:
1717                checkPermissionAndTriggerVideoCall();
1718                break;
1719            case R.id.action_ongoing_call:
1720                returnToOngoingCall();
1721                break;
1722            case R.id.action_toggle_pinned:
1723                togglePinned();
1724                break;
1725            case R.id.action_refresh_feature_discovery:
1726                refreshFeatureDiscovery();
1727                break;
1728            default:
1729                break;
1730        }
1731        return super.onOptionsItemSelected(item);
1732    }
1733
1734    public boolean onBackPressed() {
1735        boolean wasLocked = conversation.getLockThread();
1736        conversation.setLockThread(false);
1737        backPressedLeaveSingleThread.setEnabled(false);
1738        if (wasLocked) {
1739            conversation.setUserSelectedThread(false);
1740            refresh();
1741            updateThreadFromLastMessage();
1742            return true;
1743        }
1744        return false;
1745    }
1746
1747    private void startSearch() {
1748        final Intent intent = new Intent(getActivity(), SearchActivity.class);
1749        intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
1750        startActivity(intent);
1751    }
1752
1753    private void returnToOngoingCall() {
1754        final Optional<OngoingRtpSession> ongoingRtpSession =
1755                activity.xmppConnectionService
1756                        .getJingleConnectionManager()
1757                        .getOngoingRtpConnection(conversation.getContact());
1758        if (ongoingRtpSession.isPresent()) {
1759            final OngoingRtpSession id = ongoingRtpSession.get();
1760            final Intent intent = new Intent(activity, RtpSessionActivity.class);
1761            intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.getAccount().getJid().asBareJid().toEscapedString());
1762            intent.putExtra(
1763                    RtpSessionActivity.EXTRA_ACCOUNT,
1764                    id.getAccount().getJid().asBareJid().toEscapedString());
1765            intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
1766            if (id instanceof AbstractJingleConnection.Id) {
1767                intent.setAction(Intent.ACTION_VIEW);
1768                intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
1769            } else if (id instanceof JingleConnectionManager.RtpSessionProposal) {
1770                if (((JingleConnectionManager.RtpSessionProposal) id).media.contains(Media.VIDEO)) {
1771                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1772                } else {
1773                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1774                }
1775            }
1776            activity.startActivity(intent);
1777        }
1778    }
1779
1780    private void refreshFeatureDiscovery() {
1781        for (Map.Entry<String, Presence> entry : conversation.getContact().getPresences().getPresencesMap().entrySet()) {
1782            Jid jid = conversation.getContact().getJid();
1783            if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
1784            activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
1785                if (activity == null) return;
1786                activity.runOnUiThread(() -> {
1787                    refresh();
1788                    refreshCommands();
1789                });
1790            });
1791        }
1792    }
1793
1794    private void togglePinned() {
1795        final boolean pinned =
1796                conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
1797        conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
1798        activity.xmppConnectionService.updateConversation(conversation);
1799        activity.invalidateOptionsMenu();
1800    }
1801
1802    private void checkPermissionAndTriggerAudioCall() {
1803        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1804            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1805            return;
1806        }
1807        final List<String> permissions;
1808        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1809            permissions =
1810                    Arrays.asList(
1811                            Manifest.permission.RECORD_AUDIO,
1812                            Manifest.permission.BLUETOOTH_CONNECT);
1813        } else {
1814            permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
1815        }
1816        if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
1817            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1818        }
1819    }
1820
1821    private void checkPermissionAndTriggerVideoCall() {
1822        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1823            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1824            return;
1825        }
1826        final List<String> permissions;
1827        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1828            permissions =
1829                    Arrays.asList(
1830                            Manifest.permission.RECORD_AUDIO,
1831                            Manifest.permission.CAMERA,
1832                            Manifest.permission.BLUETOOTH_CONNECT);
1833        } else {
1834            permissions =
1835                    Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
1836        }
1837        if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
1838            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1839        }
1840    }
1841
1842    private void triggerRtpSession(final String action) {
1843        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy() != null) {
1844            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
1845                    .show();
1846            return;
1847        }
1848        final Contact contact = conversation.getContact();
1849        if (contact.getPresences().anySupport(Namespace.JINGLE_MESSAGE)) {
1850            triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
1851        } else {
1852            final RtpCapability.Capability capability;
1853            if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
1854                capability = RtpCapability.Capability.VIDEO;
1855            } else {
1856                capability = RtpCapability.Capability.AUDIO;
1857            }
1858            PresenceSelector.selectFullJidForDirectRtpConnection(
1859                    activity,
1860                    contact,
1861                    capability,
1862                    fullJid -> {
1863                        triggerRtpSession(contact.getAccount(), fullJid, action);
1864                    });
1865        }
1866    }
1867
1868    private void triggerRtpSession(final Account account, final Jid with, final String action) {
1869        final Intent intent = new Intent(activity, RtpSessionActivity.class);
1870        intent.setAction(action);
1871        intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, account.getJid().toEscapedString());
1872        intent.putExtra(RtpSessionActivity.EXTRA_WITH, with.toEscapedString());
1873        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1874        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
1875        startActivity(intent);
1876    }
1877
1878    private void handleAttachmentSelection(MenuItem item) {
1879        switch (item.getItemId()) {
1880            case R.id.attach_choose_picture:
1881                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1882                break;
1883            case R.id.attach_take_picture:
1884                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1885                break;
1886            case R.id.attach_record_video:
1887                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1888                break;
1889            case R.id.attach_choose_file:
1890                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1891                break;
1892            case R.id.attach_record_voice:
1893                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1894                break;
1895            case R.id.attach_location:
1896                attachFile(ATTACHMENT_CHOICE_LOCATION);
1897                break;
1898        }
1899    }
1900
1901    private void handleEncryptionSelection(MenuItem item) {
1902        if (conversation == null) {
1903            return;
1904        }
1905        final boolean updated;
1906        switch (item.getItemId()) {
1907            case R.id.encryption_choice_none:
1908                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1909                item.setChecked(true);
1910                break;
1911            case R.id.encryption_choice_pgp:
1912                if (activity.hasPgp()) {
1913                    if (conversation.getAccount().getPgpSignature() != null) {
1914                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1915                        item.setChecked(true);
1916                    } else {
1917                        updated = false;
1918                        activity.announcePgp(
1919                                conversation.getAccount(),
1920                                conversation,
1921                                null,
1922                                activity.onOpenPGPKeyPublished);
1923                    }
1924                } else {
1925                    activity.showInstallPgpDialog();
1926                    updated = false;
1927                }
1928                break;
1929            case R.id.encryption_choice_axolotl:
1930                Log.d(
1931                        Config.LOGTAG,
1932                        AxolotlService.getLogprefix(conversation.getAccount())
1933                                + "Enabled axolotl for Contact "
1934                                + conversation.getContact().getJid());
1935                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1936                item.setChecked(true);
1937                break;
1938            default:
1939                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1940                break;
1941        }
1942        if (updated) {
1943            activity.xmppConnectionService.updateConversation(conversation);
1944        }
1945        updateChatMsgHint();
1946        getActivity().invalidateOptionsMenu();
1947        activity.refreshUi();
1948    }
1949
1950    public void attachFile(final int attachmentChoice) {
1951        attachFile(attachmentChoice, true);
1952    }
1953
1954    public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
1955        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1956            if (!hasPermissions(
1957                    attachmentChoice,
1958                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
1959                    Manifest.permission.RECORD_AUDIO)) {
1960                return;
1961            }
1962        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
1963                || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1964            if (!hasPermissions(
1965                    attachmentChoice,
1966                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
1967                    Manifest.permission.CAMERA)) {
1968                return;
1969            }
1970        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1971            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1972                return;
1973            }
1974        }
1975        if (updateRecentlyUsed) {
1976            storeRecentlyUsedQuickAction(attachmentChoice);
1977        }
1978        final int encryption = conversation.getNextEncryption();
1979        final int mode = conversation.getMode();
1980        if (encryption == Message.ENCRYPTION_PGP) {
1981            if (activity.hasPgp()) {
1982                if (mode == Conversation.MODE_SINGLE
1983                        && conversation.getContact().getPgpKeyId() != 0) {
1984                    activity.xmppConnectionService
1985                            .getPgpEngine()
1986                            .hasKey(
1987                                    conversation.getContact(),
1988                                    new UiCallback<Contact>() {
1989
1990                                        @Override
1991                                        public void userInputRequired(
1992                                                PendingIntent pi, Contact contact) {
1993                                            startPendingIntent(pi, attachmentChoice);
1994                                        }
1995
1996                                        @Override
1997                                        public void success(Contact contact) {
1998                                            invokeAttachFileIntent(attachmentChoice);
1999                                        }
2000
2001                                        @Override
2002                                        public void error(int error, Contact contact) {
2003                                            activity.replaceToast(getString(error));
2004                                        }
2005                                    });
2006                } else if (mode == Conversation.MODE_MULTI
2007                        && conversation.getMucOptions().pgpKeysInUse()) {
2008                    if (!conversation.getMucOptions().everybodyHasKeys()) {
2009                        Toast warning =
2010                                Toast.makeText(
2011                                        getActivity(),
2012                                        R.string.missing_public_keys,
2013                                        Toast.LENGTH_LONG);
2014                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2015                        warning.show();
2016                    }
2017                    invokeAttachFileIntent(attachmentChoice);
2018                } else {
2019                    showNoPGPKeyDialog(
2020                            false,
2021                            (dialog, which) -> {
2022                                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2023                                activity.xmppConnectionService.updateConversation(conversation);
2024                                invokeAttachFileIntent(attachmentChoice);
2025                            });
2026                }
2027            } else {
2028                activity.showInstallPgpDialog();
2029            }
2030        } else {
2031            invokeAttachFileIntent(attachmentChoice);
2032        }
2033    }
2034
2035    private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2036        try {
2037            activity.getPreferences()
2038                    .edit()
2039                    .putString(
2040                            RECENTLY_USED_QUICK_ACTION,
2041                            SendButtonAction.of(attachmentChoice).toString())
2042                    .apply();
2043        } catch (IllegalArgumentException e) {
2044            // just do not save
2045        }
2046    }
2047
2048    @Override
2049    public void onRequestPermissionsResult(
2050            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2051        final PermissionUtils.PermissionResult permissionResult =
2052                PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2053        if (grantResults.length > 0) {
2054            if (allGranted(permissionResult.grantResults)) {
2055                switch (requestCode) {
2056                    case REQUEST_START_DOWNLOAD:
2057                        if (this.mPendingDownloadableMessage != null) {
2058                            startDownloadable(this.mPendingDownloadableMessage);
2059                        }
2060                        break;
2061                    case REQUEST_ADD_EDITOR_CONTENT:
2062                        if (this.mPendingEditorContent != null) {
2063                            attachEditorContentToConversation(this.mPendingEditorContent);
2064                        }
2065                        break;
2066                    case REQUEST_COMMIT_ATTACHMENTS:
2067                        commitAttachments();
2068                        break;
2069                    case REQUEST_START_AUDIO_CALL:
2070                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2071                        break;
2072                    case REQUEST_START_VIDEO_CALL:
2073                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2074                        break;
2075                    default:
2076                        attachFile(requestCode);
2077                        break;
2078                }
2079            } else {
2080                @StringRes int res;
2081                String firstDenied =
2082                        getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2083                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2084                    res = R.string.no_microphone_permission;
2085                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2086                    res = R.string.no_camera_permission;
2087                } else {
2088                    res = R.string.no_storage_permission;
2089                }
2090                Toast.makeText(
2091                                getActivity(),
2092                                getString(res, getString(R.string.app_name)),
2093                                Toast.LENGTH_SHORT)
2094                        .show();
2095            }
2096        }
2097        if (writeGranted(grantResults, permissions)) {
2098            if (activity != null && activity.xmppConnectionService != null) {
2099                activity.xmppConnectionService.getBitmapCache().evictAll();
2100                activity.xmppConnectionService.getDrawableCache().evictAll();
2101                activity.xmppConnectionService.restartFileObserver();
2102            }
2103            refresh();
2104        }
2105    }
2106
2107    public void startDownloadable(Message message) {
2108        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2109            this.mPendingDownloadableMessage = message;
2110            return;
2111        }
2112        Transferable transferable = message.getTransferable();
2113        if (transferable != null) {
2114            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2115                createNewConnection(message);
2116                return;
2117            }
2118            if (!transferable.start()) {
2119                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2120                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2121                        .show();
2122            }
2123        } else if (message.treatAsDownloadable()
2124                || message.hasFileOnRemoteHost()
2125                || MessageUtils.unInitiatedButKnownSize(message)) {
2126            createNewConnection(message);
2127        } else {
2128            Log.d(
2129                    Config.LOGTAG,
2130                    message.getConversation().getAccount() + ": unable to start downloadable");
2131        }
2132    }
2133
2134    private void createNewConnection(final Message message) {
2135        if (!activity.xmppConnectionService.hasInternetConnection()) {
2136            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2137                    .show();
2138            return;
2139        }
2140        if (message.getOob() != null && message.getOob().getScheme().equalsIgnoreCase("cid")) {
2141            try {
2142                BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2143                message.setTransferable(transfer);
2144                transfer.start();
2145            } catch (URISyntaxException e) {
2146                Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2147            }
2148        } else {
2149            activity.xmppConnectionService
2150                    .getHttpConnectionManager()
2151                    .createNewDownloadConnection(message, true);
2152        }
2153    }
2154
2155    @SuppressLint("InflateParams")
2156    protected void clearHistoryDialog(final Conversation conversation) {
2157        final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2158        builder.setTitle(getString(R.string.clear_conversation_history));
2159        final View dialogView =
2160                requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2161        final CheckBox endConversationCheckBox =
2162                dialogView.findViewById(R.id.end_conversation_checkbox);
2163        builder.setView(dialogView);
2164        builder.setNegativeButton(getString(R.string.cancel), null);
2165        builder.setPositiveButton(
2166                getString(R.string.confirm),
2167                (dialog, which) -> {
2168                    this.activity.xmppConnectionService.clearConversationHistory(conversation);
2169                    if (endConversationCheckBox.isChecked()) {
2170                        this.activity.xmppConnectionService.archiveConversation(conversation);
2171                        this.activity.onConversationArchived(conversation);
2172                    } else {
2173                        activity.onConversationsListItemUpdated();
2174                        refresh();
2175                    }
2176                });
2177        builder.create().show();
2178    }
2179
2180    protected void muteConversationDialog(final Conversation conversation) {
2181        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
2182        builder.setTitle(R.string.disable_notifications);
2183        final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2184        final CharSequence[] labels = new CharSequence[durations.length];
2185        for (int i = 0; i < durations.length; ++i) {
2186            if (durations[i] == -1) {
2187                labels[i] = activity.getString(R.string.until_further_notice);
2188            } else {
2189                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2190            }
2191        }
2192        builder.setItems(
2193                labels,
2194                (dialog, which) -> {
2195                    final long till;
2196                    if (durations[which] == -1) {
2197                        till = Long.MAX_VALUE;
2198                    } else {
2199                        till = System.currentTimeMillis() + (durations[which] * 1000L);
2200                    }
2201                    conversation.setMutedTill(till);
2202                    activity.xmppConnectionService.updateConversation(conversation);
2203                    activity.onConversationsListItemUpdated();
2204                    refresh();
2205                    activity.invalidateOptionsMenu();
2206                });
2207        builder.create().show();
2208    }
2209
2210    private boolean hasPermissions(int requestCode, List<String> permissions) {
2211        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
2212            final List<String> missingPermissions = new ArrayList<>();
2213            for (String permission : permissions) {
2214                if (Config.ONLY_INTERNAL_STORAGE
2215                        && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2216                    continue;
2217                }
2218                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2219                    missingPermissions.add(permission);
2220                }
2221            }
2222            if (missingPermissions.size() == 0) {
2223                return true;
2224            } else {
2225                requestPermissions(
2226                        missingPermissions.toArray(new String[0]),
2227                        requestCode);
2228                return false;
2229            }
2230        } else {
2231            return true;
2232        }
2233    }
2234
2235    private boolean hasPermissions(int requestCode, String... permissions) {
2236        return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2237    }
2238
2239    public void unMuteConversation(final Conversation conversation) {
2240        conversation.setMutedTill(0);
2241        this.activity.xmppConnectionService.updateConversation(conversation);
2242        this.activity.onConversationsListItemUpdated();
2243        refresh();
2244        this.activity.invalidateOptionsMenu();
2245    }
2246
2247    protected void invokeAttachFileIntent(final int attachmentChoice) {
2248        Intent intent = new Intent();
2249        boolean chooser = false;
2250        switch (attachmentChoice) {
2251            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2252                intent.setAction(Intent.ACTION_GET_CONTENT);
2253                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2254                intent.setType("image/*");
2255                chooser = true;
2256                break;
2257            case ATTACHMENT_CHOICE_RECORD_VIDEO:
2258                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2259                break;
2260            case ATTACHMENT_CHOICE_TAKE_PHOTO:
2261                final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2262                pendingTakePhotoUri.push(uri);
2263                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2264                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2265                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2266                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2267                break;
2268            case ATTACHMENT_CHOICE_CHOOSE_FILE:
2269                chooser = true;
2270                intent.setType("*/*");
2271                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2272                intent.addCategory(Intent.CATEGORY_OPENABLE);
2273                intent.setAction(Intent.ACTION_GET_CONTENT);
2274                break;
2275            case ATTACHMENT_CHOICE_RECORD_VOICE:
2276                intent = new Intent(getActivity(), RecordingActivity.class);
2277                break;
2278            case ATTACHMENT_CHOICE_LOCATION:
2279                intent = GeoHelper.getFetchIntent(activity);
2280                break;
2281        }
2282        final Context context = getActivity();
2283        if (context == null) {
2284            return;
2285        }
2286        try {
2287            if (chooser) {
2288                startActivityForResult(
2289                        Intent.createChooser(intent, getString(R.string.perform_action_with)),
2290                        attachmentChoice);
2291            } else {
2292                startActivityForResult(intent, attachmentChoice);
2293            }
2294        } catch (final ActivityNotFoundException e) {
2295            Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2296        }
2297    }
2298
2299    @Override
2300    public void onResume() {
2301        super.onResume();
2302        binding.messagesView.post(this::fireReadEvent);
2303    }
2304
2305    private void fireReadEvent() {
2306        if (activity != null && this.conversation != null) {
2307            String uuid = getLastVisibleMessageUuid();
2308            if (uuid != null) {
2309                activity.onConversationRead(this.conversation, uuid);
2310            }
2311        }
2312    }
2313
2314    private void newThread() {
2315        Element thread = new Element("thread", "jabber:client");
2316        thread.setContent(UUID.randomUUID().toString());
2317        setThread(thread);
2318    }
2319
2320    private void updateThreadFromLastMessage() {
2321        if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2322            Message message = getLastVisibleMessage();
2323            if (message == null) {
2324                newThread();
2325            } else {
2326                setThread(message.getThread());
2327            }
2328        }
2329    }
2330
2331    private String getLastVisibleMessageUuid() {
2332        Message message =  getLastVisibleMessage();
2333        return message == null ? null : message.getUuid();
2334    }
2335
2336    private Message getLastVisibleMessage() {
2337        if (binding == null) {
2338            return null;
2339        }
2340        synchronized (this.messageList) {
2341            int pos = binding.messagesView.getLastVisiblePosition();
2342            if (pos >= 0) {
2343                Message message = null;
2344                for (int i = pos; i >= 0; --i) {
2345                    try {
2346                        message = (Message) binding.messagesView.getItemAtPosition(i);
2347                    } catch (IndexOutOfBoundsException e) {
2348                        // should not happen if we synchronize properly. however if that fails we
2349                        // just gonna try item -1
2350                        continue;
2351                    }
2352                    if (message.getType() != Message.TYPE_STATUS) {
2353                        break;
2354                    }
2355                }
2356                if (message != null) {
2357                    while (message.next() != null && message.next().wasMergedIntoPrevious()) {
2358                        message = message.next();
2359                    }
2360                    return message;
2361                }
2362            }
2363        }
2364        return null;
2365    }
2366
2367    private void openWith(final Message message) {
2368        if (message.isGeoUri()) {
2369            GeoHelper.view(getActivity(), message);
2370        } else {
2371            final DownloadableFile file =
2372                    activity.xmppConnectionService.getFileBackend().getFile(message);
2373            ViewUtil.view(activity, file);
2374        }
2375    }
2376
2377    private void showErrorMessage(final Message message) {
2378        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2379        builder.setTitle(R.string.error_message);
2380        final String errorMessage = message.getErrorMessage();
2381        final String[] errorMessageParts =
2382                errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2383        final String displayError;
2384        if (errorMessageParts.length == 2) {
2385            displayError = errorMessageParts[1];
2386        } else {
2387            displayError = errorMessage;
2388        }
2389        builder.setMessage(displayError);
2390        builder.setNegativeButton(
2391                R.string.copy_to_clipboard,
2392                (dialog, which) -> {
2393                    activity.copyTextToClipboard(displayError, R.string.error_message);
2394                    Toast.makeText(
2395                                    activity,
2396                                    R.string.error_message_copied_to_clipboard,
2397                                    Toast.LENGTH_SHORT)
2398                            .show();
2399                });
2400        builder.setPositiveButton(R.string.confirm, null);
2401        builder.create().show();
2402    }
2403
2404    public boolean onInlineImageLongClicked(Cid cid) {
2405        DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2406        if (f == null) return false;
2407
2408        saveAsSticker(f, null);
2409        return true;
2410    }
2411
2412    private void saveAsSticker(final Message m) {
2413        String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
2414        existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
2415        saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
2416    }
2417
2418    private void saveAsSticker(final File file, final String name) {
2419        savingAsSticker = file;
2420
2421        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
2422        intent.addCategory(Intent.CATEGORY_OPENABLE);
2423        intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file)));
2424        intent.putExtra(Intent.EXTRA_TITLE, name);
2425
2426        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2427        final String dir = p.getString("sticker_directory", "Stickers");
2428        if (dir.startsWith("content://")) {
2429            intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
2430        } else {
2431            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
2432            Uri uri;
2433            if (Build.VERSION.SDK_INT >= 24) {
2434                Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
2435                uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
2436                uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
2437            } else {
2438                uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
2439            }
2440            intent.putExtra("android.provider.extra.INITIAL_URI", uri);
2441            intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
2442        }
2443
2444        Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
2445        startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
2446    }
2447
2448    private void deleteFile(final Message message) {
2449        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2450        builder.setNegativeButton(R.string.cancel, null);
2451        builder.setTitle(R.string.delete_file_dialog);
2452        builder.setMessage(R.string.delete_file_dialog_msg);
2453        builder.setPositiveButton(
2454                R.string.confirm,
2455                (dialog, which) -> {
2456                    if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2457                        message.setDeleted(true);
2458                        activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
2459                        activity.xmppConnectionService.updateMessage(message, false);
2460                        activity.onConversationsListItemUpdated();
2461                        refresh();
2462                    }
2463                });
2464        builder.create().show();
2465    }
2466
2467    private void resendMessage(final Message message) {
2468        if (message.isFileOrImage()) {
2469            if (!(message.getConversation() instanceof Conversation)) {
2470                return;
2471            }
2472            final Conversation conversation = (Conversation) message.getConversation();
2473            final DownloadableFile file =
2474                    activity.xmppConnectionService.getFileBackend().getFile(message);
2475            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2476                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2477                if (!message.hasFileOnRemoteHost()
2478                        && xmppConnection != null
2479                        && conversation.getMode() == Conversational.MODE_SINGLE
2480                        && !xmppConnection
2481                                .getFeatures()
2482                                .httpUpload(message.getFileParams().getSize())) {
2483                    activity.selectPresence(
2484                            conversation,
2485                            () -> {
2486                                message.setCounterpart(conversation.getNextCounterpart());
2487                                activity.xmppConnectionService.resendFailedMessages(message);
2488                                new Handler()
2489                                        .post(
2490                                                () -> {
2491                                                    int size = messageList.size();
2492                                                    this.binding.messagesView.setSelection(
2493                                                            size - 1);
2494                                                });
2495                            });
2496                    return;
2497                }
2498            } else if (!Compatibility.hasStoragePermission(getActivity())) {
2499                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2500                return;
2501            } else {
2502                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2503                message.setDeleted(true);
2504                activity.xmppConnectionService.updateMessage(message, false);
2505                activity.onConversationsListItemUpdated();
2506                refresh();
2507                return;
2508            }
2509        }
2510        activity.xmppConnectionService.resendFailedMessages(message);
2511        new Handler()
2512                .post(
2513                        () -> {
2514                            int size = messageList.size();
2515                            this.binding.messagesView.setSelection(size - 1);
2516                        });
2517    }
2518
2519    private void cancelTransmission(Message message) {
2520        Transferable transferable = message.getTransferable();
2521        if (transferable != null) {
2522            transferable.cancel();
2523        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2524            activity.xmppConnectionService.markMessage(
2525                    message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2526        }
2527    }
2528
2529    private void retryDecryption(Message message) {
2530        message.setEncryption(Message.ENCRYPTION_PGP);
2531        activity.onConversationsListItemUpdated();
2532        refresh();
2533        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2534    }
2535
2536    public void privateMessageWith(final Jid counterpart) {
2537        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2538            activity.xmppConnectionService.sendChatState(conversation);
2539        }
2540        this.binding.textinput.setText("");
2541        this.conversation.setNextCounterpart(counterpart);
2542        updateChatMsgHint();
2543        updateSendButton();
2544        updateEditablity();
2545    }
2546
2547    private void correctMessage(Message message) {
2548        while (message.mergeable(message.next())) {
2549            message = message.next();
2550        }
2551        this.conversation.setCorrectingMessage(message);
2552        final Editable editable = binding.textinput.getText();
2553        this.conversation.setDraftMessage(editable.toString());
2554        this.binding.textinput.setText("");
2555        this.binding.textinput.append(message.getBody());
2556    }
2557
2558    private void highlightInConference(String nick) {
2559        final Editable editable = this.binding.textinput.getText();
2560        String oldString = editable.toString().trim();
2561        final int pos = this.binding.textinput.getSelectionStart();
2562        if (oldString.isEmpty() || pos == 0) {
2563            editable.insert(0, nick + ": ");
2564        } else {
2565            final char before = editable.charAt(pos - 1);
2566            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2567            if (before == '\n') {
2568                editable.insert(pos, nick + ": ");
2569            } else {
2570                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2571                    if (NickValidityChecker.check(
2572                            conversation,
2573                            Arrays.asList(
2574                                    editable.subSequence(0, pos - 2).toString().split(", ")))) {
2575                        editable.insert(pos - 2, ", " + nick);
2576                        return;
2577                    }
2578                }
2579                editable.insert(
2580                        pos,
2581                        (Character.isWhitespace(before) ? "" : " ")
2582                                + nick
2583                                + (Character.isWhitespace(after) ? "" : " "));
2584                if (Character.isWhitespace(after)) {
2585                    this.binding.textinput.setSelection(
2586                            this.binding.textinput.getSelectionStart() + 1);
2587                }
2588            }
2589        }
2590    }
2591
2592    @Override
2593    public void startActivityForResult(Intent intent, int requestCode) {
2594        final Activity activity = getActivity();
2595        if (activity instanceof ConversationsActivity) {
2596            ((ConversationsActivity) activity).clearPendingViewIntent();
2597        }
2598        super.startActivityForResult(intent, requestCode);
2599    }
2600
2601    @Override
2602    public void onSaveInstanceState(@NotNull Bundle outState) {
2603        super.onSaveInstanceState(outState);
2604        if (conversation != null) {
2605            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2606            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2607            final Uri uri = pendingTakePhotoUri.peek();
2608            if (uri != null) {
2609                outState.putString(STATE_PHOTO_URI, uri.toString());
2610            }
2611            final ScrollState scrollState = getScrollPosition();
2612            if (scrollState != null) {
2613                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2614            }
2615            final ArrayList<Attachment> attachments =
2616                    mediaPreviewAdapter == null
2617                            ? new ArrayList<>()
2618                            : mediaPreviewAdapter.getAttachments();
2619            if (attachments.size() > 0) {
2620                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2621            }
2622        }
2623    }
2624
2625    @Override
2626    public void onActivityCreated(Bundle savedInstanceState) {
2627        super.onActivityCreated(savedInstanceState);
2628        if (savedInstanceState == null) {
2629            return;
2630        }
2631        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2632        ArrayList<Attachment> attachments =
2633                savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2634        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2635        if (uuid != null) {
2636            QuickLoader.set(uuid);
2637            this.pendingConversationsUuid.push(uuid);
2638            if (attachments != null && attachments.size() > 0) {
2639                this.pendingMediaPreviews.push(attachments);
2640            }
2641            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2642            if (takePhotoUri != null) {
2643                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2644            }
2645            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2646        }
2647    }
2648
2649    @Override
2650    public void onStart() {
2651        super.onStart();
2652        if (this.reInitRequiredOnStart && this.conversation != null) {
2653            final Bundle extras = pendingExtras.pop();
2654            reInit(this.conversation, extras != null);
2655            if (extras != null) {
2656                processExtras(extras);
2657            }
2658        } else if (conversation == null
2659                && activity != null
2660                && activity.xmppConnectionService != null) {
2661            final String uuid = pendingConversationsUuid.pop();
2662            Log.d(
2663                    Config.LOGTAG,
2664                    "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
2665                            + uuid);
2666            if (uuid != null) {
2667                findAndReInitByUuidOrArchive(uuid);
2668            }
2669        }
2670    }
2671
2672    @Override
2673    public void onStop() {
2674        super.onStop();
2675        final Activity activity = getActivity();
2676        messageListAdapter.unregisterListenerInAudioPlayer();
2677        if (activity == null || !activity.isChangingConfigurations()) {
2678            hideSoftKeyboard(activity);
2679            messageListAdapter.stopAudioPlayer();
2680        }
2681        if (this.conversation != null) {
2682            final String msg = this.binding.textinput.getText().toString();
2683            storeNextMessage(msg);
2684            updateChatState(this.conversation, msg);
2685            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2686        }
2687        this.reInitRequiredOnStart = true;
2688    }
2689
2690    private void updateChatState(final Conversation conversation, final String msg) {
2691        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2692        Account.State status = conversation.getAccount().getStatus();
2693        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2694            activity.xmppConnectionService.sendChatState(conversation);
2695        }
2696    }
2697
2698    private void saveMessageDraftStopAudioPlayer() {
2699        final Conversation previousConversation = this.conversation;
2700        if (this.activity == null || this.binding == null || previousConversation == null) {
2701            return;
2702        }
2703        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2704        final String msg = this.binding.textinput.getText().toString();
2705        storeNextMessage(msg);
2706        updateChatState(this.conversation, msg);
2707        messageListAdapter.stopAudioPlayer();
2708        mediaPreviewAdapter.clearPreviews();
2709        toggleInputMethod();
2710    }
2711
2712    public void reInit(final Conversation conversation, final Bundle extras) {
2713        QuickLoader.set(conversation.getUuid());
2714        final boolean changedConversation = this.conversation != conversation;
2715        if (changedConversation) {
2716            this.saveMessageDraftStopAudioPlayer();
2717        }
2718        this.clearPending();
2719        if (this.reInit(conversation, extras != null)) {
2720            if (extras != null) {
2721                processExtras(extras);
2722            }
2723            this.reInitRequiredOnStart = false;
2724        } else {
2725            this.reInitRequiredOnStart = true;
2726            pendingExtras.push(extras);
2727        }
2728        resetUnreadMessagesCount();
2729    }
2730
2731    private void reInit(Conversation conversation) {
2732        reInit(conversation, false);
2733    }
2734
2735    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2736        if (conversation == null) {
2737            return false;
2738        }
2739        final Conversation originalConversation = this.conversation;
2740        this.conversation = conversation;
2741        // once we set the conversation all is good and it will automatically do the right thing in
2742        // onStart()
2743        if (this.activity == null || this.binding == null) {
2744            return false;
2745        }
2746
2747        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2748            activity.onConversationArchived(this.conversation);
2749            return false;
2750        }
2751
2752        setThread(conversation.getThread());
2753        setupReply(conversation.getReplyTo());
2754
2755        stopScrolling();
2756        Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
2757
2758        if (this.conversation.isRead() && hasExtras) {
2759            Log.d(Config.LOGTAG, "trimming conversation");
2760            this.conversation.trim();
2761        }
2762
2763        setupIme();
2764
2765        final boolean scrolledToBottomAndNoPending =
2766                this.scrolledToBottom() && pendingScrollState.peek() == null;
2767
2768        this.binding.textSendButton.setContentDescription(
2769                activity.getString(R.string.send_message_to_x, conversation.getName()));
2770        this.binding.textinput.setKeyboardListener(null);
2771        this.binding.textinput.setText("");
2772        final boolean participating =
2773                conversation.getMode() == Conversational.MODE_SINGLE
2774                        || conversation.getMucOptions().participating();
2775        if (participating) {
2776            this.binding.textinput.append(this.conversation.getNextMessage());
2777        }
2778        this.binding.textinput.setKeyboardListener(this);
2779        messageListAdapter.updatePreferences();
2780        refresh(false);
2781        activity.invalidateOptionsMenu();
2782        this.conversation.messagesLoaded.set(true);
2783        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
2784
2785        if (hasExtras || scrolledToBottomAndNoPending) {
2786            resetUnreadMessagesCount();
2787            synchronized (this.messageList) {
2788                Log.d(Config.LOGTAG, "jump to first unread message");
2789                final Message first = conversation.getFirstUnreadMessage();
2790                final int bottom = Math.max(0, this.messageList.size() - 1);
2791                final int pos;
2792                final boolean jumpToBottom;
2793                if (first == null) {
2794                    pos = bottom;
2795                    jumpToBottom = true;
2796                } else {
2797                    int i = getIndexOf(first.getUuid(), this.messageList);
2798                    pos = i < 0 ? bottom : i;
2799                    jumpToBottom = false;
2800                }
2801                setSelection(pos, jumpToBottom);
2802            }
2803        }
2804
2805        this.binding.messagesView.post(this::fireReadEvent);
2806        // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
2807        // layout which might be unnecessary since we can *see* it
2808        activity.xmppConnectionService
2809                .getNotificationService()
2810                .setOpenConversation(this.conversation);
2811
2812        if (commandAdapter != null && conversation != originalConversation) {
2813            originalConversation.setupViewPager(null, null);
2814            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout);
2815            refreshCommands();
2816        }
2817        if (commandAdapter == null && conversation != null) {
2818            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout);
2819            commandAdapter = new CommandAdapter((XmppActivity) getActivity());
2820            binding.commandsView.setAdapter(commandAdapter);
2821            binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
2822                final Element command = commandAdapter.getItem(position);
2823                activity.startCommand(conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
2824            });
2825            refreshCommands();
2826        }
2827
2828        return true;
2829    }
2830
2831    public void refreshForNewCaps() {
2832        refreshCommands();
2833    }
2834
2835    protected void refreshCommands() {
2836        if (commandAdapter == null) return;
2837
2838        Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
2839        if (commandJid == null) {
2840            conversation.hideViewPager();
2841        } else {
2842            conversation.showViewPager();
2843            activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
2844                if (activity == null) return;
2845
2846                activity.runOnUiThread(() -> {
2847                    if (iq.getType() == IqPacket.TYPE.RESULT) {
2848                        binding.commandsViewProgressbar.setVisibility(View.GONE);
2849                        commandAdapter.clear();
2850                        for (Element child : iq.query().getChildren()) {
2851                            if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
2852                            commandAdapter.add(child);
2853                        }
2854                    }
2855
2856                    if (commandAdapter.getCount() < 1) conversation.hideViewPager();
2857                });
2858            });
2859        }
2860    }
2861
2862    private void resetUnreadMessagesCount() {
2863        lastMessageUuid = null;
2864        hideUnreadMessagesCount();
2865    }
2866
2867    private void hideUnreadMessagesCount() {
2868        if (this.binding == null) {
2869            return;
2870        }
2871        this.binding.scrollToBottomButton.setEnabled(false);
2872        this.binding.scrollToBottomButton.hide();
2873        this.binding.unreadCountCustomView.setVisibility(View.GONE);
2874    }
2875
2876    private void setSelection(int pos, boolean jumpToBottom) {
2877        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2878        this.binding.messagesView.post(
2879                () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2880        this.binding.messagesView.post(this::fireReadEvent);
2881    }
2882
2883    private boolean scrolledToBottom() {
2884        return this.binding != null && scrolledToBottom(this.binding.messagesView);
2885    }
2886
2887    private void processExtras(final Bundle extras) {
2888        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2889        final String text = extras.getString(Intent.EXTRA_TEXT);
2890        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2891        final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
2892        final String postInitAction =
2893                extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
2894        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2895        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2896        final boolean doNotAppend =
2897                extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2898        final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
2899        final List<Uri> uris = extractUris(extras);
2900        if (uris != null && uris.size() > 0) {
2901            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2902                mediaPreviewAdapter.addMediaPreviews(
2903                        Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2904            } else {
2905                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2906                mediaPreviewAdapter.addMediaPreviews(
2907                        Attachment.of(getActivity(), cleanedUris, type));
2908            }
2909            toggleInputMethod();
2910            return;
2911        }
2912        if (nick != null) {
2913            if (pm) {
2914                Jid jid = conversation.getJid();
2915                try {
2916                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2917                    privateMessageWith(next);
2918                } catch (final IllegalArgumentException ignored) {
2919                    // do nothing
2920                }
2921            } else {
2922                final MucOptions mucOptions = conversation.getMucOptions();
2923                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2924                    highlightInConference(nick);
2925                }
2926            }
2927        } else {
2928            if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
2929                mediaPreviewAdapter.addMediaPreviews(
2930                        Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
2931                toggleInputMethod();
2932                return;
2933            } else if (text != null && asQuote) {
2934                quoteText(text);
2935            } else {
2936                appendText(text, doNotAppend);
2937            }
2938        }
2939        if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
2940            attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
2941            return;
2942        }
2943        if ("call".equals(postInitAction)) {
2944            checkPermissionAndTriggerAudioCall();
2945        }
2946        if ("message".equals(postInitAction)) {
2947            binding.conversationViewPager.post(() -> {
2948                binding.conversationViewPager.setCurrentItem(0);
2949            });
2950        }
2951        if ("command".equals(postInitAction)) {
2952            binding.conversationViewPager.post(() -> {
2953                PagerAdapter adapter = binding.conversationViewPager.getAdapter();
2954                if (adapter != null && adapter.getCount() > 1) {
2955                    binding.conversationViewPager.setCurrentItem(1);
2956                }
2957                final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
2958                Jid commandJid = null;
2959                if (jid != null) {
2960                    try {
2961                        commandJid = Jid.of(jid);
2962                    } catch (final IllegalArgumentException e) { }
2963                }
2964                if (commandJid == null || !commandJid.isFullJid()) {
2965                    final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
2966                    if (discoJid != null) commandJid = discoJid;
2967                }
2968                if (node != null && commandJid != null) {
2969                    conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
2970                }
2971            });
2972            return;
2973        }
2974        final Message message =
2975                downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2976        if (message != null) {
2977            startDownloadable(message);
2978        }
2979    }
2980
2981    private Element commandFor(final Jid jid, final String node) {
2982        if (commandAdapter != null) {
2983            for (int i = 0; i < commandAdapter.getCount(); i++) {
2984                Element command = commandAdapter.getItem(i);
2985                final String commandNode = command.getAttribute("node");
2986                if (commandNode == null || !commandNode.equals(node)) continue;
2987
2988                final Jid commandJid = command.getAttributeAsJid("jid");
2989                if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
2990
2991                return command;
2992            }
2993        }
2994
2995        return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
2996    }
2997
2998    private List<Uri> extractUris(final Bundle extras) {
2999        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3000        if (uris != null) {
3001            return uris;
3002        }
3003        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3004        if (uri != null) {
3005            return Collections.singletonList(uri);
3006        } else {
3007            return null;
3008        }
3009    }
3010
3011    private List<Uri> cleanUris(final List<Uri> uris) {
3012        final Iterator<Uri> iterator = uris.iterator();
3013        while (iterator.hasNext()) {
3014            final Uri uri = iterator.next();
3015            if (FileBackend.weOwnFile(uri)) {
3016                iterator.remove();
3017                Toast.makeText(
3018                                getActivity(),
3019                                R.string.security_violation_not_attaching_file,
3020                                Toast.LENGTH_SHORT)
3021                        .show();
3022            }
3023        }
3024        return uris;
3025    }
3026
3027    private boolean showBlockSubmenu(View view) {
3028        final Jid jid = conversation.getJid();
3029        final boolean showReject =
3030                !conversation.isWithStranger()
3031                        && conversation
3032                                .getContact()
3033                                .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3034        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3035        popupMenu.inflate(R.menu.block);
3036        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3037        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3038        popupMenu.setOnMenuItemClickListener(
3039                menuItem -> {
3040                    Blockable blockable;
3041                    switch (menuItem.getItemId()) {
3042                        case R.id.reject:
3043                            activity.xmppConnectionService.stopPresenceUpdatesTo(
3044                                    conversation.getContact());
3045                            updateSnackBar(conversation);
3046                            return true;
3047                        case R.id.block_domain:
3048                            blockable =
3049                                    conversation
3050                                            .getAccount()
3051                                            .getRoster()
3052                                            .getContact(jid.getDomain());
3053                            break;
3054                        default:
3055                            blockable = conversation;
3056                    }
3057                    BlockContactDialog.show(activity, blockable);
3058                    return true;
3059                });
3060        popupMenu.show();
3061        return true;
3062    }
3063
3064    private void updateSnackBar(final Conversation conversation) {
3065        final Account account = conversation.getAccount();
3066        final XmppConnection connection = account.getXmppConnection();
3067        final int mode = conversation.getMode();
3068        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3069        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3070            return;
3071        }
3072        if (account.getStatus() == Account.State.DISABLED) {
3073            showSnackbar(
3074                    R.string.this_account_is_disabled,
3075                    R.string.enable,
3076                    this.mEnableAccountListener);
3077        } else if (conversation.isBlocked()) {
3078            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3079        } else if (contact != null
3080                && !contact.showInRoster()
3081                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3082            showSnackbar(
3083                    R.string.contact_added_you,
3084                    R.string.add_back,
3085                    this.mAddBackClickListener,
3086                    this.mLongPressBlockListener);
3087        } else if (contact != null
3088                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3089            showSnackbar(
3090                    R.string.contact_asks_for_presence_subscription,
3091                    R.string.allow,
3092                    this.mAllowPresenceSubscription,
3093                    this.mLongPressBlockListener);
3094        } else if (mode == Conversation.MODE_MULTI
3095                && !conversation.getMucOptions().online()
3096                && account.getStatus() == Account.State.ONLINE) {
3097            switch (conversation.getMucOptions().getError()) {
3098                case NICK_IN_USE:
3099                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3100                    break;
3101                case NO_RESPONSE:
3102                    showSnackbar(R.string.joining_conference, 0, null);
3103                    break;
3104                case SERVER_NOT_FOUND:
3105                    if (conversation.receivedMessagesCount() > 0) {
3106                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3107                    } else {
3108                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3109                    }
3110                    break;
3111                case REMOTE_SERVER_TIMEOUT:
3112                    if (conversation.receivedMessagesCount() > 0) {
3113                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3114                    } else {
3115                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3116                    }
3117                    break;
3118                case PASSWORD_REQUIRED:
3119                    showSnackbar(
3120                            R.string.conference_requires_password,
3121                            R.string.enter_password,
3122                            enterPassword);
3123                    break;
3124                case BANNED:
3125                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3126                    break;
3127                case MEMBERS_ONLY:
3128                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3129                    break;
3130                case RESOURCE_CONSTRAINT:
3131                    showSnackbar(
3132                            R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3133                    break;
3134                case KICKED:
3135                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3136                    break;
3137                case TECHNICAL_PROBLEMS:
3138                    showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3139                    break;
3140                case UNKNOWN:
3141                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3142                    break;
3143                case INVALID_NICK:
3144                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3145                case SHUTDOWN:
3146                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3147                    break;
3148                case DESTROYED:
3149                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3150                    break;
3151                case NON_ANONYMOUS:
3152                    showSnackbar(
3153                            R.string.group_chat_will_make_your_jabber_id_public,
3154                            R.string.join,
3155                            acceptJoin);
3156                    break;
3157                default:
3158                    hideSnackbar();
3159                    break;
3160            }
3161        } else if (account.hasPendingPgpIntent(conversation)) {
3162            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3163        } else if (connection != null
3164                && connection.getFeatures().blocking()
3165                && conversation.countMessages() != 0
3166                && !conversation.isBlocked()
3167                && conversation.isWithStranger()) {
3168            showSnackbar(
3169                    R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
3170        } else {
3171            hideSnackbar();
3172        }
3173    }
3174
3175    @Override
3176    public void refresh() {
3177        if (this.binding == null) {
3178            Log.d(
3179                    Config.LOGTAG,
3180                    "ConversationFragment.refresh() skipped updated because view binding was null");
3181            return;
3182        }
3183        if (this.conversation != null
3184                && this.activity != null
3185                && this.activity.xmppConnectionService != null) {
3186            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3187                activity.onConversationArchived(this.conversation);
3188                return;
3189            }
3190        }
3191        this.refresh(true);
3192    }
3193
3194    private void refresh(boolean notifyConversationRead) {
3195        synchronized (this.messageList) {
3196            if (this.conversation != null) {
3197                conversation.populateWithMessages(this.messageList);
3198                updateSnackBar(conversation);
3199                updateStatusMessages();
3200                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3201                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3202                    binding.unreadCountCustomView.setUnreadCount(
3203                            conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3204                }
3205                this.messageListAdapter.notifyDataSetChanged();
3206                updateChatMsgHint();
3207                if (notifyConversationRead && activity != null) {
3208                    binding.messagesView.post(this::fireReadEvent);
3209                }
3210                updateSendButton();
3211                updateEditablity();
3212            }
3213        }
3214    }
3215
3216    protected void messageSent() {
3217        mSendingPgpMessage.set(false);
3218        this.binding.textinput.setText("");
3219        if (conversation.setCorrectingMessage(null)) {
3220            this.binding.textinput.append(conversation.getDraftMessage());
3221            conversation.setDraftMessage(null);
3222        }
3223        storeNextMessage();
3224        updateChatMsgHint();
3225        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3226        final boolean prefScrollToBottom =
3227                p.getBoolean(
3228                        "scroll_to_bottom",
3229                        activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3230        if (prefScrollToBottom || scrolledToBottom()) {
3231            new Handler()
3232                    .post(
3233                            () -> {
3234                                int size = messageList.size();
3235                                this.binding.messagesView.setSelection(size - 1);
3236                            });
3237        }
3238    }
3239
3240    private boolean storeNextMessage() {
3241        return storeNextMessage(this.binding.textinput.getText().toString());
3242    }
3243
3244    private boolean storeNextMessage(String msg) {
3245        final boolean participating =
3246                conversation.getMode() == Conversational.MODE_SINGLE
3247                        || conversation.getMucOptions().participating();
3248        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3249                && participating
3250                && this.conversation.setNextMessage(msg)) {
3251            this.activity.xmppConnectionService.updateConversation(this.conversation);
3252            return true;
3253        }
3254        return false;
3255    }
3256
3257    public void doneSendingPgpMessage() {
3258        mSendingPgpMessage.set(false);
3259    }
3260
3261    public long getMaxHttpUploadSize(Conversation conversation) {
3262        final XmppConnection connection = conversation.getAccount().getXmppConnection();
3263        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3264    }
3265
3266    private void updateEditablity() {
3267        boolean canWrite =
3268                this.conversation.getMode() == Conversation.MODE_SINGLE
3269                        || this.conversation.getMucOptions().participating()
3270                        || this.conversation.getNextCounterpart() != null;
3271        this.binding.textinput.setFocusable(canWrite);
3272        this.binding.textinput.setFocusableInTouchMode(canWrite);
3273        this.binding.textSendButton.setEnabled(canWrite);
3274        this.binding.textinput.setCursorVisible(canWrite);
3275        this.binding.textinput.setEnabled(canWrite);
3276    }
3277
3278    public void updateSendButton() {
3279        boolean hasAttachments =
3280                mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3281        final Conversation c = this.conversation;
3282        final Presence.Status status;
3283        final String text =
3284                this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3285        final SendButtonAction action;
3286        if (hasAttachments) {
3287            action = SendButtonAction.TEXT;
3288        } else {
3289            action = SendButtonTool.getAction(getActivity(), c, text);
3290        }
3291        if (c.getAccount().getStatus() == Account.State.ONLINE) {
3292            if (activity != null
3293                    && activity.xmppConnectionService != null
3294                    && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3295                status = Presence.Status.OFFLINE;
3296            } else if (c.getMode() == Conversation.MODE_SINGLE) {
3297                status = c.getContact().getShownStatus();
3298            } else {
3299                status =
3300                        c.getMucOptions().online()
3301                                ? Presence.Status.ONLINE
3302                                : Presence.Status.OFFLINE;
3303            }
3304        } else {
3305            status = Presence.Status.OFFLINE;
3306        }
3307        this.binding.textSendButton.setTag(action);
3308        final Activity activity = getActivity();
3309        if (activity != null) {
3310            this.binding.textSendButton.setImageResource(
3311                    SendButtonTool.getSendButtonImageResource(activity, action, status));
3312        }
3313
3314        ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3315        if (identiconWidth < 0) identiconWidth = params.width;
3316        if (hasAttachments || binding.textinput.getText().length() > 0) {
3317            binding.conversationViewPager.setCurrentItem(0);
3318            params.width = conversation.getThread() == null ? 0 : identiconWidth;
3319        } else {
3320            params.width = identiconWidth;
3321        }
3322        binding.threadIdenticonLayout.setLayoutParams(params);
3323    }
3324
3325    protected void updateStatusMessages() {
3326        DateSeparator.addAll(this.messageList);
3327        if (showLoadMoreMessages(conversation)) {
3328            this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3329        }
3330        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3331            ChatState state = conversation.getIncomingChatState();
3332            if (state == ChatState.COMPOSING) {
3333                this.messageList.add(
3334                        Message.createStatusMessage(
3335                                conversation,
3336                                getString(R.string.contact_is_typing, conversation.getName())));
3337            } else if (state == ChatState.PAUSED) {
3338                this.messageList.add(
3339                        Message.createStatusMessage(
3340                                conversation,
3341                                getString(
3342                                        R.string.contact_has_stopped_typing,
3343                                        conversation.getName())));
3344            } else {
3345                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3346                    final Message message = this.messageList.get(i);
3347                    if (message.getType() != Message.TYPE_STATUS) {
3348                        if (message.getStatus() == Message.STATUS_RECEIVED) {
3349                            return;
3350                        } else {
3351                            if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3352                                this.messageList.add(
3353                                        i + 1,
3354                                        Message.createStatusMessage(
3355                                                conversation,
3356                                                getString(
3357                                                        R.string.contact_has_read_up_to_this_point,
3358                                                        conversation.getName())));
3359                                return;
3360                            }
3361                        }
3362                    }
3363                }
3364            }
3365        } else {
3366            final MucOptions mucOptions = conversation.getMucOptions();
3367            final List<MucOptions.User> allUsers = mucOptions.getUsers();
3368            final Set<ReadByMarker> addedMarkers = new HashSet<>();
3369            ChatState state = ChatState.COMPOSING;
3370            List<MucOptions.User> users =
3371                    conversation.getMucOptions().getUsersWithChatState(state, 5);
3372            if (users.size() == 0) {
3373                state = ChatState.PAUSED;
3374                users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3375            }
3376            if (mucOptions.isPrivateAndNonAnonymous()) {
3377                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3378                    final Set<ReadByMarker> markersForMessage =
3379                            messageList.get(i).getReadByMarkers();
3380                    final List<MucOptions.User> shownMarkers = new ArrayList<>();
3381                    for (ReadByMarker marker : markersForMessage) {
3382                        if (!ReadByMarker.contains(marker, addedMarkers)) {
3383                            addedMarkers.add(
3384                                    marker); // may be put outside this condition. set should do
3385                                             // dedup anyway
3386                            MucOptions.User user = mucOptions.findUser(marker);
3387                            if (user != null && !users.contains(user)) {
3388                                shownMarkers.add(user);
3389                            }
3390                        }
3391                    }
3392                    final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3393                    final Message statusMessage;
3394                    final int size = shownMarkers.size();
3395                    if (size > 1) {
3396                        final String body;
3397                        if (size <= 4) {
3398                            body =
3399                                    getString(
3400                                            R.string.contacts_have_read_up_to_this_point,
3401                                            UIHelper.concatNames(shownMarkers));
3402                        } else if (ReadByMarker.allUsersRepresented(
3403                                allUsers, markersForMessage, markerForSender)) {
3404                            body = getString(R.string.everyone_has_read_up_to_this_point);
3405                        } else {
3406                            body =
3407                                    getString(
3408                                            R.string.contacts_and_n_more_have_read_up_to_this_point,
3409                                            UIHelper.concatNames(shownMarkers, 3),
3410                                            size - 3);
3411                        }
3412                        statusMessage = Message.createStatusMessage(conversation, body);
3413                        statusMessage.setCounterparts(shownMarkers);
3414                    } else if (size == 1) {
3415                        statusMessage =
3416                                Message.createStatusMessage(
3417                                        conversation,
3418                                        getString(
3419                                                R.string.contact_has_read_up_to_this_point,
3420                                                UIHelper.getDisplayName(shownMarkers.get(0))));
3421                        statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3422                        statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3423                    } else {
3424                        statusMessage = null;
3425                    }
3426                    if (statusMessage != null) {
3427                        this.messageList.add(i + 1, statusMessage);
3428                    }
3429                    addedMarkers.add(markerForSender);
3430                    if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3431                        break;
3432                    }
3433                }
3434            }
3435            if (users.size() > 0) {
3436                Message statusMessage;
3437                if (users.size() == 1) {
3438                    MucOptions.User user = users.get(0);
3439                    int id =
3440                            state == ChatState.COMPOSING
3441                                    ? R.string.contact_is_typing
3442                                    : R.string.contact_has_stopped_typing;
3443                    statusMessage =
3444                            Message.createStatusMessage(
3445                                    conversation, getString(id, UIHelper.getDisplayName(user)));
3446                    statusMessage.setTrueCounterpart(user.getRealJid());
3447                    statusMessage.setCounterpart(user.getFullJid());
3448                } else {
3449                    int id =
3450                            state == ChatState.COMPOSING
3451                                    ? R.string.contacts_are_typing
3452                                    : R.string.contacts_have_stopped_typing;
3453                    statusMessage =
3454                            Message.createStatusMessage(
3455                                    conversation, getString(id, UIHelper.concatNames(users)));
3456                    statusMessage.setCounterparts(users);
3457                }
3458                this.messageList.add(statusMessage);
3459            }
3460        }
3461    }
3462
3463    private void stopScrolling() {
3464        long now = SystemClock.uptimeMillis();
3465        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3466        binding.messagesView.dispatchTouchEvent(cancel);
3467    }
3468
3469    private boolean showLoadMoreMessages(final Conversation c) {
3470        if (activity == null || activity.xmppConnectionService == null) {
3471            return false;
3472        }
3473        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3474        final MessageArchiveService service =
3475                activity.xmppConnectionService.getMessageArchiveService();
3476        return mam
3477                && (c.getLastClearHistory().getTimestamp() != 0
3478                        || (c.countMessages() == 0
3479                                && c.messagesLoaded.get()
3480                                && c.hasMessagesLeftOnServer()
3481                                && !service.queryInProgress(c)));
3482    }
3483
3484    private boolean hasMamSupport(final Conversation c) {
3485        if (c.getMode() == Conversation.MODE_SINGLE) {
3486            final XmppConnection connection = c.getAccount().getXmppConnection();
3487            return connection != null && connection.getFeatures().mam();
3488        } else {
3489            return c.getMucOptions().mamSupport();
3490        }
3491    }
3492
3493    protected void showSnackbar(
3494            final int message, final int action, final OnClickListener clickListener) {
3495        showSnackbar(message, action, clickListener, null);
3496    }
3497
3498    protected void showSnackbar(
3499            final int message,
3500            final int action,
3501            final OnClickListener clickListener,
3502            final View.OnLongClickListener longClickListener) {
3503        this.binding.snackbar.setVisibility(View.VISIBLE);
3504        this.binding.snackbar.setOnClickListener(null);
3505        this.binding.snackbarMessage.setText(message);
3506        this.binding.snackbarMessage.setOnClickListener(null);
3507        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3508        if (action != 0) {
3509            this.binding.snackbarAction.setText(action);
3510        }
3511        this.binding.snackbarAction.setOnClickListener(clickListener);
3512        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3513    }
3514
3515    protected void hideSnackbar() {
3516        this.binding.snackbar.setVisibility(View.GONE);
3517    }
3518
3519    protected void sendMessage(Message message) {
3520        activity.xmppConnectionService.sendMessage(message);
3521        messageSent();
3522    }
3523
3524    protected void sendPgpMessage(final Message message) {
3525        final XmppConnectionService xmppService = activity.xmppConnectionService;
3526        final Contact contact = message.getConversation().getContact();
3527        if (!activity.hasPgp()) {
3528            activity.showInstallPgpDialog();
3529            return;
3530        }
3531        if (conversation.getAccount().getPgpSignature() == null) {
3532            activity.announcePgp(
3533                    conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3534            return;
3535        }
3536        if (!mSendingPgpMessage.compareAndSet(false, true)) {
3537            Log.d(Config.LOGTAG, "sending pgp message already in progress");
3538        }
3539        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3540            if (contact.getPgpKeyId() != 0) {
3541                xmppService
3542                        .getPgpEngine()
3543                        .hasKey(
3544                                contact,
3545                                new UiCallback<Contact>() {
3546
3547                                    @Override
3548                                    public void userInputRequired(
3549                                            PendingIntent pi, Contact contact) {
3550                                        startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3551                                    }
3552
3553                                    @Override
3554                                    public void success(Contact contact) {
3555                                        encryptTextMessage(message);
3556                                    }
3557
3558                                    @Override
3559                                    public void error(int error, Contact contact) {
3560                                        activity.runOnUiThread(
3561                                                () ->
3562                                                        Toast.makeText(
3563                                                                        activity,
3564                                                                        R.string
3565                                                                                .unable_to_connect_to_keychain,
3566                                                                        Toast.LENGTH_SHORT)
3567                                                                .show());
3568                                        mSendingPgpMessage.set(false);
3569                                    }
3570                                });
3571
3572            } else {
3573                showNoPGPKeyDialog(
3574                        false,
3575                        (dialog, which) -> {
3576                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3577                            xmppService.updateConversation(conversation);
3578                            message.setEncryption(Message.ENCRYPTION_NONE);
3579                            xmppService.sendMessage(message);
3580                            messageSent();
3581                        });
3582            }
3583        } else {
3584            if (conversation.getMucOptions().pgpKeysInUse()) {
3585                if (!conversation.getMucOptions().everybodyHasKeys()) {
3586                    Toast warning =
3587                            Toast.makeText(
3588                                    getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3589                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3590                    warning.show();
3591                }
3592                encryptTextMessage(message);
3593            } else {
3594                showNoPGPKeyDialog(
3595                        true,
3596                        (dialog, which) -> {
3597                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3598                            message.setEncryption(Message.ENCRYPTION_NONE);
3599                            xmppService.updateConversation(conversation);
3600                            xmppService.sendMessage(message);
3601                            messageSent();
3602                        });
3603            }
3604        }
3605    }
3606
3607    public void encryptTextMessage(Message message) {
3608        activity.xmppConnectionService
3609                .getPgpEngine()
3610                .encrypt(
3611                        message,
3612                        new UiCallback<Message>() {
3613
3614                            @Override
3615                            public void userInputRequired(PendingIntent pi, Message message) {
3616                                startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3617                            }
3618
3619                            @Override
3620                            public void success(Message message) {
3621                                // TODO the following two call can be made before the callback
3622                                getActivity().runOnUiThread(() -> messageSent());
3623                            }
3624
3625                            @Override
3626                            public void error(final int error, Message message) {
3627                                getActivity()
3628                                        .runOnUiThread(
3629                                                () -> {
3630                                                    doneSendingPgpMessage();
3631                                                    Toast.makeText(
3632                                                                    getActivity(),
3633                                                                    error == 0
3634                                                                            ? R.string
3635                                                                                    .unable_to_connect_to_keychain
3636                                                                            : error,
3637                                                                    Toast.LENGTH_SHORT)
3638                                                            .show();
3639                                                });
3640                            }
3641                        });
3642    }
3643
3644    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3645        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3646        builder.setIconAttribute(android.R.attr.alertDialogIcon);
3647        if (plural) {
3648            builder.setTitle(getString(R.string.no_pgp_keys));
3649            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3650        } else {
3651            builder.setTitle(getString(R.string.no_pgp_key));
3652            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3653        }
3654        builder.setNegativeButton(getString(R.string.cancel), null);
3655        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3656        builder.create().show();
3657    }
3658
3659    public void appendText(String text, final boolean doNotAppend) {
3660        if (text == null) {
3661            return;
3662        }
3663        final Editable editable = this.binding.textinput.getText();
3664        String previous = editable == null ? "" : editable.toString();
3665        if (doNotAppend && !TextUtils.isEmpty(previous)) {
3666            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3667                    .show();
3668            return;
3669        }
3670        if (UIHelper.isLastLineQuote(previous)) {
3671            text = '\n' + text;
3672        } else if (previous.length() != 0
3673                && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3674            text = " " + text;
3675        }
3676        this.binding.textinput.append(text);
3677    }
3678
3679    @Override
3680    public boolean onEnterPressed(final boolean isCtrlPressed) {
3681        if (isCtrlPressed || enterIsSend()) {
3682            sendMessage();
3683            return true;
3684        }
3685        return false;
3686    }
3687
3688    private boolean enterIsSend() {
3689        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3690        return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3691    }
3692
3693    public boolean onArrowUpCtrlPressed() {
3694        final Message lastEditableMessage =
3695                conversation == null ? null : conversation.getLastEditableMessage();
3696        if (lastEditableMessage != null) {
3697            correctMessage(lastEditableMessage);
3698            return true;
3699        } else {
3700            Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3701                    .show();
3702            return false;
3703        }
3704    }
3705
3706    @Override
3707    public void onTypingStarted() {
3708        final XmppConnectionService service =
3709                activity == null ? null : activity.xmppConnectionService;
3710        if (service == null) {
3711            return;
3712        }
3713        final Account.State status = conversation.getAccount().getStatus();
3714        if (status == Account.State.ONLINE
3715                && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3716            service.sendChatState(conversation);
3717        }
3718        runOnUiThread(this::updateSendButton);
3719    }
3720
3721    @Override
3722    public void onTypingStopped() {
3723        final XmppConnectionService service =
3724                activity == null ? null : activity.xmppConnectionService;
3725        if (service == null) {
3726            return;
3727        }
3728        final Account.State status = conversation.getAccount().getStatus();
3729        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3730            service.sendChatState(conversation);
3731        }
3732    }
3733
3734    @Override
3735    public void onTextDeleted() {
3736        final XmppConnectionService service =
3737                activity == null ? null : activity.xmppConnectionService;
3738        if (service == null) {
3739            return;
3740        }
3741        final Account.State status = conversation.getAccount().getStatus();
3742        if (status == Account.State.ONLINE
3743                && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3744            service.sendChatState(conversation);
3745        }
3746        if (storeNextMessage()) {
3747            runOnUiThread(
3748                    () -> {
3749                        if (activity == null) {
3750                            return;
3751                        }
3752                        activity.onConversationsListItemUpdated();
3753                    });
3754        }
3755        runOnUiThread(this::updateSendButton);
3756    }
3757
3758    @Override
3759    public void onTextChanged() {
3760        if (conversation != null && conversation.getCorrectingMessage() != null) {
3761            runOnUiThread(this::updateSendButton);
3762        }
3763    }
3764
3765    @Override
3766    public boolean onTabPressed(boolean repeated) {
3767        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3768            return false;
3769        }
3770        if (repeated) {
3771            completionIndex++;
3772        } else {
3773            lastCompletionLength = 0;
3774            completionIndex = 0;
3775            final String content = this.binding.textinput.getText().toString();
3776            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
3777            int start =
3778                    lastCompletionCursor > 0
3779                            ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
3780                            : 0;
3781            firstWord = start == 0;
3782            incomplete = content.substring(start, lastCompletionCursor);
3783        }
3784        List<String> completions = new ArrayList<>();
3785        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
3786            String name = user.getName();
3787            if (name != null && name.startsWith(incomplete)) {
3788                completions.add(name + (firstWord ? ": " : " "));
3789            }
3790        }
3791        Collections.sort(completions);
3792        if (completions.size() > completionIndex) {
3793            String completion = completions.get(completionIndex).substring(incomplete.length());
3794            this.binding
3795                    .textinput
3796                    .getEditableText()
3797                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3798            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
3799            lastCompletionLength = completion.length();
3800        } else {
3801            completionIndex = -1;
3802            this.binding
3803                    .textinput
3804                    .getEditableText()
3805                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3806            lastCompletionLength = 0;
3807        }
3808        return true;
3809    }
3810
3811    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
3812        try {
3813            getActivity()
3814                    .startIntentSenderForResult(
3815                            pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
3816        } catch (final SendIntentException ignored) {
3817        }
3818    }
3819
3820    @Override
3821    public void onBackendConnected() {
3822        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
3823        String uuid = pendingConversationsUuid.pop();
3824        if (uuid != null) {
3825            if (!findAndReInitByUuidOrArchive(uuid)) {
3826                return;
3827            }
3828        } else {
3829            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
3830                clearPending();
3831                activity.onConversationArchived(conversation);
3832                return;
3833            }
3834        }
3835        ActivityResult activityResult = postponedActivityResult.pop();
3836        if (activityResult != null) {
3837            handleActivityResult(activityResult);
3838        }
3839        clearPending();
3840    }
3841
3842    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
3843        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
3844        if (conversation == null) {
3845            clearPending();
3846            activity.onConversationArchived(null);
3847            return false;
3848        }
3849        reInit(conversation);
3850        ScrollState scrollState = pendingScrollState.pop();
3851        String lastMessageUuid = pendingLastMessageUuid.pop();
3852        List<Attachment> attachments = pendingMediaPreviews.pop();
3853        if (scrollState != null) {
3854            setScrollPosition(scrollState, lastMessageUuid);
3855        }
3856        if (attachments != null && attachments.size() > 0) {
3857            Log.d(Config.LOGTAG, "had attachments on restore");
3858            mediaPreviewAdapter.addMediaPreviews(attachments);
3859            toggleInputMethod();
3860        }
3861        return true;
3862    }
3863
3864    private void clearPending() {
3865        if (postponedActivityResult.clear()) {
3866            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
3867            if (pendingTakePhotoUri.clear()) {
3868                Log.e(Config.LOGTAG, "cleared pending photo uri");
3869            }
3870        }
3871        if (pendingScrollState.clear()) {
3872            Log.e(Config.LOGTAG, "cleared scroll state");
3873        }
3874        if (pendingConversationsUuid.clear()) {
3875            Log.e(Config.LOGTAG, "cleared pending conversations uuid");
3876        }
3877        if (pendingMediaPreviews.clear()) {
3878            Log.e(Config.LOGTAG, "cleared pending media previews");
3879        }
3880    }
3881
3882    public Conversation getConversation() {
3883        return conversation;
3884    }
3885
3886    @Override
3887    public void onContactPictureLongClicked(View v, final Message message) {
3888        final String fingerprint;
3889        if (message.getEncryption() == Message.ENCRYPTION_PGP
3890                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3891            fingerprint = "pgp";
3892        } else {
3893            fingerprint = message.getFingerprint();
3894        }
3895        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
3896        final Contact contact = message.getContact();
3897        if (message.getStatus() <= Message.STATUS_RECEIVED
3898                && (contact == null || !contact.isSelf())) {
3899            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
3900                final Jid cp = message.getCounterpart();
3901                if (cp == null || cp.isBareJid()) {
3902                    return;
3903                }
3904                final Jid tcp = message.getTrueCounterpart();
3905                final User userByRealJid =
3906                        tcp != null
3907                                ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
3908                                : null;
3909                final User user =
3910                        userByRealJid != null
3911                                ? userByRealJid
3912                                : conversation.getMucOptions().findUserByFullJid(cp);
3913                popupMenu.inflate(R.menu.muc_details_context);
3914                final Menu menu = popupMenu.getMenu();
3915                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
3916                        activity, menu, conversation, user);
3917                popupMenu.setOnMenuItemClickListener(
3918                        menuItem ->
3919                                MucDetailsContextMenuHelper.onContextItemSelected(
3920                                        menuItem, user, activity, fingerprint));
3921            } else {
3922                popupMenu.inflate(R.menu.one_on_one_context);
3923                popupMenu.setOnMenuItemClickListener(
3924                        item -> {
3925                            switch (item.getItemId()) {
3926                                case R.id.action_contact_details:
3927                                    activity.switchToContactDetails(
3928                                            message.getContact(), fingerprint);
3929                                    break;
3930                                case R.id.action_show_qr_code:
3931                                    activity.showQrCode(
3932                                            "xmpp:"
3933                                                    + message.getContact()
3934                                                            .getJid()
3935                                                            .asBareJid()
3936                                                            .toEscapedString());
3937                                    break;
3938                            }
3939                            return true;
3940                        });
3941            }
3942        } else {
3943            popupMenu.inflate(R.menu.account_context);
3944            final Menu menu = popupMenu.getMenu();
3945            menu.findItem(R.id.action_manage_accounts)
3946                    .setVisible(QuickConversationsService.isConversations());
3947            popupMenu.setOnMenuItemClickListener(
3948                    item -> {
3949                        final XmppActivity activity = this.activity;
3950                        if (activity == null) {
3951                            Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
3952                            return true;
3953                        }
3954                        switch (item.getItemId()) {
3955                            case R.id.action_show_qr_code:
3956                                activity.showQrCode(conversation.getAccount().getShareableUri());
3957                                break;
3958                            case R.id.action_account_details:
3959                                activity.switchToAccount(
3960                                        message.getConversation().getAccount(), fingerprint);
3961                                break;
3962                            case R.id.action_manage_accounts:
3963                                AccountUtils.launchManageAccounts(activity);
3964                                break;
3965                        }
3966                        return true;
3967                    });
3968        }
3969        popupMenu.show();
3970    }
3971
3972    @Override
3973    public void onContactPictureClicked(Message message) {
3974        setThread(message.getThread());
3975        conversation.setUserSelectedThread(true);
3976
3977        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
3978        if (received) {
3979            if (message.getConversation() instanceof Conversation
3980                    && message.getConversation().getMode() == Conversation.MODE_MULTI) {
3981                Jid tcp = message.getTrueCounterpart();
3982                Jid user = message.getCounterpart();
3983                if (user != null && !user.isBareJid()) {
3984                    final MucOptions mucOptions =
3985                            ((Conversation) message.getConversation()).getMucOptions();
3986                    if (mucOptions.participating()
3987                            || ((Conversation) message.getConversation()).getNextCounterpart()
3988                                    != null) {
3989                        if (!mucOptions.isUserInRoom(user)
3990                                && mucOptions.findUserByRealJid(
3991                                                tcp == null ? null : tcp.asBareJid())
3992                                        == null) {
3993                            Toast.makeText(
3994                                            getActivity(),
3995                                            activity.getString(
3996                                                    R.string.user_has_left_conference,
3997                                                    user.getResource()),
3998                                            Toast.LENGTH_SHORT)
3999                                    .show();
4000                        }
4001                        highlightInConference(user.getResource());
4002                    } else {
4003                        Toast.makeText(
4004                                        getActivity(),
4005                                        R.string.you_are_not_participating,
4006                                        Toast.LENGTH_SHORT)
4007                                .show();
4008                    }
4009                }
4010            }
4011        }
4012    }
4013
4014    private Activity requireActivity() {
4015        final Activity activity = getActivity();
4016        if (activity == null) {
4017            throw new IllegalStateException("Activity not attached");
4018        }
4019        return activity;
4020    }
4021}