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