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