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