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