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