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