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