ConversationFragment.java

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