ConversationFragment.java

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