ConversationFragment.java

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