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