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