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