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