ConversationFragment.java

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