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