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