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