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