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