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            newThread();
1265            conversation.setUserSelectedThread(true);
1266            if (wasLocked) refresh();
1267        });
1268
1269        binding.threadIdenticonLayout.setOnLongClickListener(v -> {
1270            boolean wasLocked = conversation.getLockThread();
1271            conversation.setLockThread(false);
1272            setThread(null);
1273            conversation.setUserSelectedThread(true);
1274            if (wasLocked) refresh();
1275            return true;
1276        });
1277
1278        return binding.getRoot();
1279    }
1280
1281    @Override
1282    public void onDestroyView() {
1283        super.onDestroyView();
1284        Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1285        messageListAdapter.setOnContactPictureClicked(null);
1286        messageListAdapter.setOnContactPictureLongClicked(null);
1287        if (conversation != null) conversation.setupViewPager(null, null);
1288    }
1289
1290    private void quoteText(String text) {
1291        if (binding.textinput.isEnabled()) {
1292            binding.textinput.insertAsQuote(text);
1293            binding.textinput.requestFocus();
1294            InputMethodManager inputMethodManager =
1295                    (InputMethodManager)
1296                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1297            if (inputMethodManager != null) {
1298                inputMethodManager.showSoftInput(
1299                        binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1300            }
1301        }
1302    }
1303
1304    private void quoteMessage(Message message) {
1305        setThread(message.getThread());
1306        conversation.setUserSelectedThread(true);
1307        quoteText(MessageUtils.prepareQuote(message));
1308    }
1309
1310    private void setThread(Element thread) {
1311        this.conversation.setThread(thread);
1312        binding.threadIdenticon.setAlpha(0f);
1313        binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1314        if (thread != null) {
1315            final String threadId = thread.getContent();
1316            if (threadId != null) {
1317                binding.threadIdenticon.setAlpha(1f);
1318                binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1319                binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1320            }
1321        }
1322    }
1323
1324    @Override
1325    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1326        // This should cancel any remaining click events that would otherwise trigger links
1327        v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1328        synchronized (this.messageList) {
1329            super.onCreateContextMenu(menu, v, menuInfo);
1330            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1331            this.selectedMessage = this.messageList.get(acmi.position);
1332            populateContextMenu(menu);
1333        }
1334    }
1335
1336    private void populateContextMenu(ContextMenu menu) {
1337        final Message m = this.selectedMessage;
1338        final Transferable t = m.getTransferable();
1339        Message relevantForCorrection = m;
1340        while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1341            relevantForCorrection = relevantForCorrection.next();
1342        }
1343        if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1344
1345            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1346                    || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1347                return;
1348            }
1349
1350            if (m.getStatus() == Message.STATUS_RECEIVED
1351                    && t != null
1352                    && (t.getStatus() == Transferable.STATUS_CANCELLED
1353                            || t.getStatus() == Transferable.STATUS_FAILED)) {
1354                return;
1355            }
1356
1357            final boolean deleted = m.isDeleted();
1358            final boolean encrypted =
1359                    m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1360                            || m.getEncryption() == Message.ENCRYPTION_PGP;
1361            final boolean receiving =
1362                    m.getStatus() == Message.STATUS_RECEIVED
1363                            && (t instanceof JingleFileTransferConnection
1364                                    || t instanceof HttpDownloadConnection);
1365            activity.getMenuInflater().inflate(R.menu.message_context, menu);
1366            menu.setHeaderTitle(R.string.message_options);
1367            MenuItem openWith = menu.findItem(R.id.open_with);
1368            MenuItem copyMessage = menu.findItem(R.id.copy_message);
1369            MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1370            MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1371            MenuItem correctMessage = menu.findItem(R.id.correct_message);
1372            MenuItem retractMessage = menu.findItem(R.id.retract_message);
1373            MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1374            MenuItem shareWith = menu.findItem(R.id.share_with);
1375            MenuItem sendAgain = menu.findItem(R.id.send_again);
1376            MenuItem copyUrl = menu.findItem(R.id.copy_url);
1377            MenuItem downloadFile = menu.findItem(R.id.download_file);
1378            MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1379            MenuItem deleteFile = menu.findItem(R.id.delete_file);
1380            MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1381            onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1382            final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1383            final boolean showError =
1384                    m.getStatus() == Message.STATUS_SEND_FAILED
1385                            && m.getErrorMessage() != null
1386                            && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1387            if (!m.isFileOrImage()
1388                    && !encrypted
1389                    && !m.isGeoUri()
1390                    && !m.treatAsDownloadable()
1391                    && !unInitiatedButKnownSize
1392                    && t == null) {
1393                copyMessage.setVisible(true);
1394                quoteMessage.setVisible(!showError && MessageUtils.prepareQuote(m).length() > 0);
1395            }
1396            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1397                retryDecryption.setVisible(true);
1398            }
1399            if (!showError
1400                    && relevantForCorrection.getType() == Message.TYPE_TEXT
1401                    && !m.isGeoUri()
1402                    && relevantForCorrection.isLastCorrectableMessage()
1403                    && m.getConversation() instanceof Conversation) {
1404                correctMessage.setVisible(true);
1405                if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1406            }
1407            if ((m.isFileOrImage() && !deleted && !receiving)
1408                    || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1409                            && !unInitiatedButKnownSize
1410                            && t == null) {
1411                shareWith.setVisible(true);
1412            }
1413            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1414                sendAgain.setVisible(true);
1415            }
1416            if (m.hasFileOnRemoteHost()
1417                    || m.isGeoUri()
1418                    || m.treatAsDownloadable()
1419                    || unInitiatedButKnownSize
1420                    || t instanceof HttpDownloadConnection) {
1421                copyUrl.setVisible(true);
1422            }
1423            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1424                downloadFile.setVisible(true);
1425                downloadFile.setTitle(
1426                        activity.getString(
1427                                R.string.download_x_file,
1428                                UIHelper.getFileDescriptionString(activity, m)));
1429            }
1430            final boolean waitingOfferedSending =
1431                    m.getStatus() == Message.STATUS_WAITING
1432                            || m.getStatus() == Message.STATUS_UNSEND
1433                            || m.getStatus() == Message.STATUS_OFFERED;
1434            final boolean cancelable =
1435                    (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1436            if (cancelable) {
1437                cancelTransmission.setVisible(true);
1438            }
1439            if (m.isFileOrImage() && !deleted && !cancelable) {
1440                final String path = m.getRelativeFilePath();
1441                if (path == null
1442                        || !path.startsWith("/")
1443                        || FileBackend.inConversationsDirectory(requireActivity(), path)) {
1444                    deleteFile.setVisible(true);
1445                    deleteFile.setTitle(
1446                            activity.getString(
1447                                    R.string.delete_x_file,
1448                                    UIHelper.getFileDescriptionString(activity, m)));
1449                }
1450            }
1451            if (showError) {
1452                showErrorMessage.setVisible(true);
1453            }
1454            final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1455            if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1456                    || (mime != null && mime.startsWith("audio/"))) {
1457                openWith.setVisible(true);
1458            }
1459        }
1460    }
1461
1462    @Override
1463    public boolean onContextItemSelected(MenuItem item) {
1464        switch (item.getItemId()) {
1465            case R.id.share_with:
1466                ShareUtil.share(activity, selectedMessage);
1467                return true;
1468            case R.id.correct_message:
1469                correctMessage(selectedMessage);
1470                return true;
1471            case R.id.retract_message:
1472                new AlertDialog.Builder(activity)
1473                    .setTitle(R.string.retract_message)
1474                    .setMessage("Do you really want to retract this message?")
1475                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1476                        Message message = selectedMessage;
1477                        while (message.mergeable(message.next())) {
1478                            message = message.next();
1479                        }
1480                        message.setBody(" ");
1481                        message.putEdited(message.getUuid(), message.getServerMsgId());
1482                        message.setServerMsgId(null);
1483                        message.setUuid(UUID.randomUUID().toString());
1484                        sendMessage(message);
1485                    })
1486                    .setNegativeButton(R.string.no, null).show();
1487                return true;
1488            case R.id.copy_message:
1489                ShareUtil.copyToClipboard(activity, selectedMessage);
1490                return true;
1491            case R.id.quote_message:
1492                quoteMessage(selectedMessage);
1493                return true;
1494            case R.id.send_again:
1495                resendMessage(selectedMessage);
1496                return true;
1497            case R.id.copy_url:
1498                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1499                return true;
1500            case R.id.download_file:
1501                startDownloadable(selectedMessage);
1502                return true;
1503            case R.id.cancel_transmission:
1504                cancelTransmission(selectedMessage);
1505                return true;
1506            case R.id.retry_decryption:
1507                retryDecryption(selectedMessage);
1508                return true;
1509            case R.id.delete_file:
1510                deleteFile(selectedMessage);
1511                return true;
1512            case R.id.show_error_message:
1513                showErrorMessage(selectedMessage);
1514                return true;
1515            case R.id.open_with:
1516                openWith(selectedMessage);
1517                return true;
1518            case R.id.only_this_thread:
1519                conversation.setLockThread(true);
1520                setThread(selectedMessage.getThread());
1521                refresh();
1522                setThread(selectedMessage.getThread());
1523                return true;
1524            default:
1525                return super.onContextItemSelected(item);
1526        }
1527    }
1528
1529    @Override
1530    public boolean onOptionsItemSelected(final MenuItem item) {
1531        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1532            return false;
1533        } else if (conversation == null) {
1534            return super.onOptionsItemSelected(item);
1535        }
1536        switch (item.getItemId()) {
1537            case R.id.encryption_choice_axolotl:
1538            case R.id.encryption_choice_pgp:
1539            case R.id.encryption_choice_none:
1540                handleEncryptionSelection(item);
1541                break;
1542            case R.id.attach_choose_picture:
1543            case R.id.attach_take_picture:
1544            case R.id.attach_record_video:
1545            case R.id.attach_choose_file:
1546            case R.id.attach_record_voice:
1547            case R.id.attach_location:
1548                handleAttachmentSelection(item);
1549                break;
1550            case R.id.action_search:
1551                startSearch();
1552                break;
1553            case R.id.action_archive:
1554                activity.xmppConnectionService.archiveConversation(conversation);
1555                break;
1556            case R.id.action_contact_details:
1557                activity.switchToContactDetails(conversation.getContact());
1558                break;
1559            case R.id.action_muc_details:
1560                ConferenceDetailsActivity.open(activity, conversation);
1561                break;
1562            case R.id.action_invite:
1563                startActivityForResult(
1564                        ChooseContactActivity.create(activity, conversation),
1565                        REQUEST_INVITE_TO_CONVERSATION);
1566                break;
1567            case R.id.action_clear_history:
1568                clearHistoryDialog(conversation);
1569                break;
1570            case R.id.action_mute:
1571                muteConversationDialog(conversation);
1572                break;
1573            case R.id.action_unmute:
1574                unMuteConversation(conversation);
1575                break;
1576            case R.id.action_block:
1577            case R.id.action_unblock:
1578                final Activity activity = getActivity();
1579                if (activity instanceof XmppActivity) {
1580                    BlockContactDialog.show((XmppActivity) activity, conversation);
1581                }
1582                break;
1583            case R.id.action_audio_call:
1584                checkPermissionAndTriggerAudioCall();
1585                break;
1586            case R.id.action_video_call:
1587                checkPermissionAndTriggerVideoCall();
1588                break;
1589            case R.id.action_ongoing_call:
1590                returnToOngoingCall();
1591                break;
1592            case R.id.action_toggle_pinned:
1593                togglePinned();
1594                break;
1595            case R.id.action_refresh_feature_discovery:
1596                refreshFeatureDiscovery();
1597                break;
1598            default:
1599                break;
1600        }
1601        return super.onOptionsItemSelected(item);
1602    }
1603
1604    private void startSearch() {
1605        final Intent intent = new Intent(getActivity(), SearchActivity.class);
1606        intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
1607        startActivity(intent);
1608    }
1609
1610    private void returnToOngoingCall() {
1611        final Optional<OngoingRtpSession> ongoingRtpSession =
1612                activity.xmppConnectionService
1613                        .getJingleConnectionManager()
1614                        .getOngoingRtpConnection(conversation.getContact());
1615        if (ongoingRtpSession.isPresent()) {
1616            final OngoingRtpSession id = ongoingRtpSession.get();
1617            final Intent intent = new Intent(activity, RtpSessionActivity.class);
1618            intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.getAccount().getJid().asBareJid().toEscapedString());
1619            intent.putExtra(
1620                    RtpSessionActivity.EXTRA_ACCOUNT,
1621                    id.getAccount().getJid().asBareJid().toEscapedString());
1622            intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
1623            if (id instanceof AbstractJingleConnection.Id) {
1624                intent.setAction(Intent.ACTION_VIEW);
1625                intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
1626            } else if (id instanceof JingleConnectionManager.RtpSessionProposal) {
1627                if (((JingleConnectionManager.RtpSessionProposal) id).media.contains(Media.VIDEO)) {
1628                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1629                } else {
1630                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1631                }
1632            }
1633            activity.startActivity(intent);
1634        }
1635    }
1636
1637    private void refreshFeatureDiscovery() {
1638        for (Map.Entry<String, Presence> entry : conversation.getContact().getPresences().getPresencesMap().entrySet()) {
1639            Jid jid = conversation.getContact().getJid();
1640            if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
1641            activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
1642                if (activity == null) return;
1643                activity.runOnUiThread(() -> {
1644                    refresh();
1645                    refreshCommands();
1646                });
1647            });
1648        }
1649    }
1650
1651    private void togglePinned() {
1652        final boolean pinned =
1653                conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
1654        conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
1655        activity.xmppConnectionService.updateConversation(conversation);
1656        activity.invalidateOptionsMenu();
1657    }
1658
1659    private void checkPermissionAndTriggerAudioCall() {
1660        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1661            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1662            return;
1663        }
1664        final List<String> permissions;
1665        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1666            permissions =
1667                    Arrays.asList(
1668                            Manifest.permission.RECORD_AUDIO,
1669                            Manifest.permission.BLUETOOTH_CONNECT);
1670        } else {
1671            permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
1672        }
1673        if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
1674            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1675        }
1676    }
1677
1678    private void checkPermissionAndTriggerVideoCall() {
1679        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1680            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1681            return;
1682        }
1683        final List<String> permissions;
1684        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1685            permissions =
1686                    Arrays.asList(
1687                            Manifest.permission.RECORD_AUDIO,
1688                            Manifest.permission.CAMERA,
1689                            Manifest.permission.BLUETOOTH_CONNECT);
1690        } else {
1691            permissions =
1692                    Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
1693        }
1694        if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
1695            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1696        }
1697    }
1698
1699    private void triggerRtpSession(final String action) {
1700        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy() != null) {
1701            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
1702                    .show();
1703            return;
1704        }
1705        final Contact contact = conversation.getContact();
1706        if (contact.getPresences().anySupport(Namespace.JINGLE_MESSAGE)) {
1707            triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
1708        } else {
1709            final RtpCapability.Capability capability;
1710            if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
1711                capability = RtpCapability.Capability.VIDEO;
1712            } else {
1713                capability = RtpCapability.Capability.AUDIO;
1714            }
1715            PresenceSelector.selectFullJidForDirectRtpConnection(
1716                    activity,
1717                    contact,
1718                    capability,
1719                    fullJid -> {
1720                        triggerRtpSession(contact.getAccount(), fullJid, action);
1721                    });
1722        }
1723    }
1724
1725    private void triggerRtpSession(final Account account, final Jid with, final String action) {
1726        final Intent intent = new Intent(activity, RtpSessionActivity.class);
1727        intent.setAction(action);
1728        intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, account.getJid().toEscapedString());
1729        intent.putExtra(RtpSessionActivity.EXTRA_WITH, with.toEscapedString());
1730        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1731        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
1732        startActivity(intent);
1733    }
1734
1735    private void handleAttachmentSelection(MenuItem item) {
1736        switch (item.getItemId()) {
1737            case R.id.attach_choose_picture:
1738                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1739                break;
1740            case R.id.attach_take_picture:
1741                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1742                break;
1743            case R.id.attach_record_video:
1744                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1745                break;
1746            case R.id.attach_choose_file:
1747                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1748                break;
1749            case R.id.attach_record_voice:
1750                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1751                break;
1752            case R.id.attach_location:
1753                attachFile(ATTACHMENT_CHOICE_LOCATION);
1754                break;
1755        }
1756    }
1757
1758    private void handleEncryptionSelection(MenuItem item) {
1759        if (conversation == null) {
1760            return;
1761        }
1762        final boolean updated;
1763        switch (item.getItemId()) {
1764            case R.id.encryption_choice_none:
1765                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1766                item.setChecked(true);
1767                break;
1768            case R.id.encryption_choice_pgp:
1769                if (activity.hasPgp()) {
1770                    if (conversation.getAccount().getPgpSignature() != null) {
1771                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1772                        item.setChecked(true);
1773                    } else {
1774                        updated = false;
1775                        activity.announcePgp(
1776                                conversation.getAccount(),
1777                                conversation,
1778                                null,
1779                                activity.onOpenPGPKeyPublished);
1780                    }
1781                } else {
1782                    activity.showInstallPgpDialog();
1783                    updated = false;
1784                }
1785                break;
1786            case R.id.encryption_choice_axolotl:
1787                Log.d(
1788                        Config.LOGTAG,
1789                        AxolotlService.getLogprefix(conversation.getAccount())
1790                                + "Enabled axolotl for Contact "
1791                                + conversation.getContact().getJid());
1792                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1793                item.setChecked(true);
1794                break;
1795            default:
1796                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1797                break;
1798        }
1799        if (updated) {
1800            activity.xmppConnectionService.updateConversation(conversation);
1801        }
1802        updateChatMsgHint();
1803        getActivity().invalidateOptionsMenu();
1804        activity.refreshUi();
1805    }
1806
1807    public void attachFile(final int attachmentChoice) {
1808        attachFile(attachmentChoice, true);
1809    }
1810
1811    public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
1812        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1813            if (!hasPermissions(
1814                    attachmentChoice,
1815                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
1816                    Manifest.permission.RECORD_AUDIO)) {
1817                return;
1818            }
1819        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
1820                || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1821            if (!hasPermissions(
1822                    attachmentChoice,
1823                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
1824                    Manifest.permission.CAMERA)) {
1825                return;
1826            }
1827        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1828            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1829                return;
1830            }
1831        }
1832        if (updateRecentlyUsed) {
1833            storeRecentlyUsedQuickAction(attachmentChoice);
1834        }
1835        final int encryption = conversation.getNextEncryption();
1836        final int mode = conversation.getMode();
1837        if (encryption == Message.ENCRYPTION_PGP) {
1838            if (activity.hasPgp()) {
1839                if (mode == Conversation.MODE_SINGLE
1840                        && conversation.getContact().getPgpKeyId() != 0) {
1841                    activity.xmppConnectionService
1842                            .getPgpEngine()
1843                            .hasKey(
1844                                    conversation.getContact(),
1845                                    new UiCallback<Contact>() {
1846
1847                                        @Override
1848                                        public void userInputRequired(
1849                                                PendingIntent pi, Contact contact) {
1850                                            startPendingIntent(pi, attachmentChoice);
1851                                        }
1852
1853                                        @Override
1854                                        public void success(Contact contact) {
1855                                            invokeAttachFileIntent(attachmentChoice);
1856                                        }
1857
1858                                        @Override
1859                                        public void error(int error, Contact contact) {
1860                                            activity.replaceToast(getString(error));
1861                                        }
1862                                    });
1863                } else if (mode == Conversation.MODE_MULTI
1864                        && conversation.getMucOptions().pgpKeysInUse()) {
1865                    if (!conversation.getMucOptions().everybodyHasKeys()) {
1866                        Toast warning =
1867                                Toast.makeText(
1868                                        getActivity(),
1869                                        R.string.missing_public_keys,
1870                                        Toast.LENGTH_LONG);
1871                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1872                        warning.show();
1873                    }
1874                    invokeAttachFileIntent(attachmentChoice);
1875                } else {
1876                    showNoPGPKeyDialog(
1877                            false,
1878                            (dialog, which) -> {
1879                                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1880                                activity.xmppConnectionService.updateConversation(conversation);
1881                                invokeAttachFileIntent(attachmentChoice);
1882                            });
1883                }
1884            } else {
1885                activity.showInstallPgpDialog();
1886            }
1887        } else {
1888            invokeAttachFileIntent(attachmentChoice);
1889        }
1890    }
1891
1892    private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
1893        try {
1894            activity.getPreferences()
1895                    .edit()
1896                    .putString(
1897                            RECENTLY_USED_QUICK_ACTION,
1898                            SendButtonAction.of(attachmentChoice).toString())
1899                    .apply();
1900        } catch (IllegalArgumentException e) {
1901            // just do not save
1902        }
1903    }
1904
1905    @Override
1906    public void onRequestPermissionsResult(
1907            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
1908        final PermissionUtils.PermissionResult permissionResult =
1909                PermissionUtils.removeBluetoothConnect(permissions, grantResults);
1910        if (grantResults.length > 0) {
1911            if (allGranted(permissionResult.grantResults)) {
1912                switch (requestCode) {
1913                    case REQUEST_START_DOWNLOAD:
1914                        if (this.mPendingDownloadableMessage != null) {
1915                            startDownloadable(this.mPendingDownloadableMessage);
1916                        }
1917                        break;
1918                    case REQUEST_ADD_EDITOR_CONTENT:
1919                        if (this.mPendingEditorContent != null) {
1920                            attachEditorContentToConversation(this.mPendingEditorContent);
1921                        }
1922                        break;
1923                    case REQUEST_COMMIT_ATTACHMENTS:
1924                        commitAttachments();
1925                        break;
1926                    case REQUEST_START_AUDIO_CALL:
1927                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1928                        break;
1929                    case REQUEST_START_VIDEO_CALL:
1930                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1931                        break;
1932                    default:
1933                        attachFile(requestCode);
1934                        break;
1935                }
1936            } else {
1937                @StringRes int res;
1938                String firstDenied =
1939                        getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
1940                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1941                    res = R.string.no_microphone_permission;
1942                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1943                    res = R.string.no_camera_permission;
1944                } else {
1945                    res = R.string.no_storage_permission;
1946                }
1947                Toast.makeText(
1948                                getActivity(),
1949                                getString(res, getString(R.string.app_name)),
1950                                Toast.LENGTH_SHORT)
1951                        .show();
1952            }
1953        }
1954        if (writeGranted(grantResults, permissions)) {
1955            if (activity != null && activity.xmppConnectionService != null) {
1956                activity.xmppConnectionService.getBitmapCache().evictAll();
1957                activity.xmppConnectionService.restartFileObserver();
1958            }
1959            refresh();
1960        }
1961    }
1962
1963    public void startDownloadable(Message message) {
1964        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1965            this.mPendingDownloadableMessage = message;
1966            return;
1967        }
1968        Transferable transferable = message.getTransferable();
1969        if (transferable != null) {
1970            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1971                createNewConnection(message);
1972                return;
1973            }
1974            if (!transferable.start()) {
1975                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1976                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
1977                        .show();
1978            }
1979        } else if (message.treatAsDownloadable()
1980                || message.hasFileOnRemoteHost()
1981                || MessageUtils.unInitiatedButKnownSize(message)) {
1982            createNewConnection(message);
1983        } else {
1984            Log.d(
1985                    Config.LOGTAG,
1986                    message.getConversation().getAccount() + ": unable to start downloadable");
1987        }
1988    }
1989
1990    private void createNewConnection(final Message message) {
1991        if (!activity.xmppConnectionService.hasInternetConnection()) {
1992            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
1993                    .show();
1994            return;
1995        }
1996        if (message.getOob() != null && message.getOob().getScheme().equalsIgnoreCase("cid")) {
1997            try {
1998                BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
1999                message.setTransferable(transfer);
2000                transfer.start();
2001            } catch (URISyntaxException e) {
2002                Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2003            }
2004        } else {
2005            activity.xmppConnectionService
2006                    .getHttpConnectionManager()
2007                    .createNewDownloadConnection(message, true);
2008        }
2009    }
2010
2011    @SuppressLint("InflateParams")
2012    protected void clearHistoryDialog(final Conversation conversation) {
2013        final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2014        builder.setTitle(getString(R.string.clear_conversation_history));
2015        final View dialogView =
2016                requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2017        final CheckBox endConversationCheckBox =
2018                dialogView.findViewById(R.id.end_conversation_checkbox);
2019        builder.setView(dialogView);
2020        builder.setNegativeButton(getString(R.string.cancel), null);
2021        builder.setPositiveButton(
2022                getString(R.string.confirm),
2023                (dialog, which) -> {
2024                    this.activity.xmppConnectionService.clearConversationHistory(conversation);
2025                    if (endConversationCheckBox.isChecked()) {
2026                        this.activity.xmppConnectionService.archiveConversation(conversation);
2027                        this.activity.onConversationArchived(conversation);
2028                    } else {
2029                        activity.onConversationsListItemUpdated();
2030                        refresh();
2031                    }
2032                });
2033        builder.create().show();
2034    }
2035
2036    protected void muteConversationDialog(final Conversation conversation) {
2037        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
2038        builder.setTitle(R.string.disable_notifications);
2039        final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2040        final CharSequence[] labels = new CharSequence[durations.length];
2041        for (int i = 0; i < durations.length; ++i) {
2042            if (durations[i] == -1) {
2043                labels[i] = activity.getString(R.string.until_further_notice);
2044            } else {
2045                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2046            }
2047        }
2048        builder.setItems(
2049                labels,
2050                (dialog, which) -> {
2051                    final long till;
2052                    if (durations[which] == -1) {
2053                        till = Long.MAX_VALUE;
2054                    } else {
2055                        till = System.currentTimeMillis() + (durations[which] * 1000L);
2056                    }
2057                    conversation.setMutedTill(till);
2058                    activity.xmppConnectionService.updateConversation(conversation);
2059                    activity.onConversationsListItemUpdated();
2060                    refresh();
2061                    activity.invalidateOptionsMenu();
2062                });
2063        builder.create().show();
2064    }
2065
2066    private boolean hasPermissions(int requestCode, List<String> permissions) {
2067        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
2068            final List<String> missingPermissions = new ArrayList<>();
2069            for (String permission : permissions) {
2070                if (Config.ONLY_INTERNAL_STORAGE
2071                        && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2072                    continue;
2073                }
2074                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2075                    missingPermissions.add(permission);
2076                }
2077            }
2078            if (missingPermissions.size() == 0) {
2079                return true;
2080            } else {
2081                requestPermissions(
2082                        missingPermissions.toArray(new String[0]),
2083                        requestCode);
2084                return false;
2085            }
2086        } else {
2087            return true;
2088        }
2089    }
2090
2091    private boolean hasPermissions(int requestCode, String... permissions) {
2092        return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2093    }
2094
2095    public void unMuteConversation(final Conversation conversation) {
2096        conversation.setMutedTill(0);
2097        this.activity.xmppConnectionService.updateConversation(conversation);
2098        this.activity.onConversationsListItemUpdated();
2099        refresh();
2100        this.activity.invalidateOptionsMenu();
2101    }
2102
2103    protected void invokeAttachFileIntent(final int attachmentChoice) {
2104        Intent intent = new Intent();
2105        boolean chooser = false;
2106        switch (attachmentChoice) {
2107            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2108                intent.setAction(Intent.ACTION_GET_CONTENT);
2109                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2110                intent.setType("image/*");
2111                chooser = true;
2112                break;
2113            case ATTACHMENT_CHOICE_RECORD_VIDEO:
2114                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2115                break;
2116            case ATTACHMENT_CHOICE_TAKE_PHOTO:
2117                final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2118                pendingTakePhotoUri.push(uri);
2119                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2120                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2121                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2122                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2123                break;
2124            case ATTACHMENT_CHOICE_CHOOSE_FILE:
2125                chooser = true;
2126                intent.setType("*/*");
2127                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2128                intent.addCategory(Intent.CATEGORY_OPENABLE);
2129                intent.setAction(Intent.ACTION_GET_CONTENT);
2130                break;
2131            case ATTACHMENT_CHOICE_RECORD_VOICE:
2132                intent = new Intent(getActivity(), RecordingActivity.class);
2133                break;
2134            case ATTACHMENT_CHOICE_LOCATION:
2135                intent = GeoHelper.getFetchIntent(activity);
2136                break;
2137        }
2138        final Context context = getActivity();
2139        if (context == null) {
2140            return;
2141        }
2142        try {
2143            if (chooser) {
2144                startActivityForResult(
2145                        Intent.createChooser(intent, getString(R.string.perform_action_with)),
2146                        attachmentChoice);
2147            } else {
2148                startActivityForResult(intent, attachmentChoice);
2149            }
2150        } catch (final ActivityNotFoundException e) {
2151            Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2152        }
2153    }
2154
2155    @Override
2156    public void onResume() {
2157        super.onResume();
2158        binding.messagesView.post(this::fireReadEvent);
2159    }
2160
2161    private void fireReadEvent() {
2162        if (activity != null && this.conversation != null) {
2163            String uuid = getLastVisibleMessageUuid();
2164            if (uuid != null) {
2165                activity.onConversationRead(this.conversation, uuid);
2166            }
2167        }
2168    }
2169
2170    private void newThread() {
2171        Element thread = new Element("thread", "jabber:client");
2172        thread.setContent(UUID.randomUUID().toString());
2173        setThread(thread);
2174    }
2175
2176    private void updateThreadFromLastMessage() {
2177        if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2178            Message message = getLastVisibleMessage();
2179            if (message == null) {
2180                newThread();
2181            } else {
2182                setThread(message.getThread());
2183            }
2184        }
2185    }
2186
2187    private String getLastVisibleMessageUuid() {
2188        Message message =  getLastVisibleMessage();
2189        return message == null ? null : message.getUuid();
2190    }
2191
2192    private Message getLastVisibleMessage() {
2193        if (binding == null) {
2194            return null;
2195        }
2196        synchronized (this.messageList) {
2197            int pos = binding.messagesView.getLastVisiblePosition();
2198            if (pos >= 0) {
2199                Message message = null;
2200                for (int i = pos; i >= 0; --i) {
2201                    try {
2202                        message = (Message) binding.messagesView.getItemAtPosition(i);
2203                    } catch (IndexOutOfBoundsException e) {
2204                        // should not happen if we synchronize properly. however if that fails we
2205                        // just gonna try item -1
2206                        continue;
2207                    }
2208                    if (message.getType() != Message.TYPE_STATUS) {
2209                        break;
2210                    }
2211                }
2212                if (message != null) {
2213                    while (message.next() != null && message.next().wasMergedIntoPrevious()) {
2214                        message = message.next();
2215                    }
2216                    return message;
2217                }
2218            }
2219        }
2220        return null;
2221    }
2222
2223    private void openWith(final Message message) {
2224        if (message.isGeoUri()) {
2225            GeoHelper.view(getActivity(), message);
2226        } else {
2227            final DownloadableFile file =
2228                    activity.xmppConnectionService.getFileBackend().getFile(message);
2229            ViewUtil.view(activity, file);
2230        }
2231    }
2232
2233    private void showErrorMessage(final Message message) {
2234        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2235        builder.setTitle(R.string.error_message);
2236        final String errorMessage = message.getErrorMessage();
2237        final String[] errorMessageParts =
2238                errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2239        final String displayError;
2240        if (errorMessageParts.length == 2) {
2241            displayError = errorMessageParts[1];
2242        } else {
2243            displayError = errorMessage;
2244        }
2245        builder.setMessage(displayError);
2246        builder.setNegativeButton(
2247                R.string.copy_to_clipboard,
2248                (dialog, which) -> {
2249                    activity.copyTextToClipboard(displayError, R.string.error_message);
2250                    Toast.makeText(
2251                                    activity,
2252                                    R.string.error_message_copied_to_clipboard,
2253                                    Toast.LENGTH_SHORT)
2254                            .show();
2255                });
2256        builder.setPositiveButton(R.string.confirm, null);
2257        builder.create().show();
2258    }
2259
2260    private void deleteFile(final Message message) {
2261        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2262        builder.setNegativeButton(R.string.cancel, null);
2263        builder.setTitle(R.string.delete_file_dialog);
2264        builder.setMessage(R.string.delete_file_dialog_msg);
2265        builder.setPositiveButton(
2266                R.string.confirm,
2267                (dialog, which) -> {
2268                    if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2269                        message.setDeleted(true);
2270                        activity.xmppConnectionService.evictPreview(message.getUuid());
2271                        activity.xmppConnectionService.updateMessage(message, false);
2272                        activity.onConversationsListItemUpdated();
2273                        refresh();
2274                    }
2275                });
2276        builder.create().show();
2277    }
2278
2279    private void resendMessage(final Message message) {
2280        if (message.isFileOrImage()) {
2281            if (!(message.getConversation() instanceof Conversation)) {
2282                return;
2283            }
2284            final Conversation conversation = (Conversation) message.getConversation();
2285            final DownloadableFile file =
2286                    activity.xmppConnectionService.getFileBackend().getFile(message);
2287            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2288                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2289                if (!message.hasFileOnRemoteHost()
2290                        && xmppConnection != null
2291                        && conversation.getMode() == Conversational.MODE_SINGLE
2292                        && !xmppConnection
2293                                .getFeatures()
2294                                .httpUpload(message.getFileParams().getSize())) {
2295                    activity.selectPresence(
2296                            conversation,
2297                            () -> {
2298                                message.setCounterpart(conversation.getNextCounterpart());
2299                                activity.xmppConnectionService.resendFailedMessages(message);
2300                                new Handler()
2301                                        .post(
2302                                                () -> {
2303                                                    int size = messageList.size();
2304                                                    this.binding.messagesView.setSelection(
2305                                                            size - 1);
2306                                                });
2307                            });
2308                    return;
2309                }
2310            } else if (!Compatibility.hasStoragePermission(getActivity())) {
2311                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2312                return;
2313            } else {
2314                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2315                message.setDeleted(true);
2316                activity.xmppConnectionService.updateMessage(message, false);
2317                activity.onConversationsListItemUpdated();
2318                refresh();
2319                return;
2320            }
2321        }
2322        activity.xmppConnectionService.resendFailedMessages(message);
2323        new Handler()
2324                .post(
2325                        () -> {
2326                            int size = messageList.size();
2327                            this.binding.messagesView.setSelection(size - 1);
2328                        });
2329    }
2330
2331    private void cancelTransmission(Message message) {
2332        Transferable transferable = message.getTransferable();
2333        if (transferable != null) {
2334            transferable.cancel();
2335        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2336            activity.xmppConnectionService.markMessage(
2337                    message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2338        }
2339    }
2340
2341    private void retryDecryption(Message message) {
2342        message.setEncryption(Message.ENCRYPTION_PGP);
2343        activity.onConversationsListItemUpdated();
2344        refresh();
2345        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2346    }
2347
2348    public void privateMessageWith(final Jid counterpart) {
2349        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2350            activity.xmppConnectionService.sendChatState(conversation);
2351        }
2352        this.binding.textinput.setText("");
2353        this.conversation.setNextCounterpart(counterpart);
2354        updateChatMsgHint();
2355        updateSendButton();
2356        updateEditablity();
2357    }
2358
2359    private void correctMessage(Message message) {
2360        while (message.mergeable(message.next())) {
2361            message = message.next();
2362        }
2363        this.conversation.setCorrectingMessage(message);
2364        final Editable editable = binding.textinput.getText();
2365        this.conversation.setDraftMessage(editable.toString());
2366        this.binding.textinput.setText("");
2367        this.binding.textinput.append(message.getBody());
2368    }
2369
2370    private void highlightInConference(String nick) {
2371        final Editable editable = this.binding.textinput.getText();
2372        String oldString = editable.toString().trim();
2373        final int pos = this.binding.textinput.getSelectionStart();
2374        if (oldString.isEmpty() || pos == 0) {
2375            editable.insert(0, nick + ": ");
2376        } else {
2377            final char before = editable.charAt(pos - 1);
2378            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2379            if (before == '\n') {
2380                editable.insert(pos, nick + ": ");
2381            } else {
2382                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2383                    if (NickValidityChecker.check(
2384                            conversation,
2385                            Arrays.asList(
2386                                    editable.subSequence(0, pos - 2).toString().split(", ")))) {
2387                        editable.insert(pos - 2, ", " + nick);
2388                        return;
2389                    }
2390                }
2391                editable.insert(
2392                        pos,
2393                        (Character.isWhitespace(before) ? "" : " ")
2394                                + nick
2395                                + (Character.isWhitespace(after) ? "" : " "));
2396                if (Character.isWhitespace(after)) {
2397                    this.binding.textinput.setSelection(
2398                            this.binding.textinput.getSelectionStart() + 1);
2399                }
2400            }
2401        }
2402    }
2403
2404    @Override
2405    public void startActivityForResult(Intent intent, int requestCode) {
2406        final Activity activity = getActivity();
2407        if (activity instanceof ConversationsActivity) {
2408            ((ConversationsActivity) activity).clearPendingViewIntent();
2409        }
2410        super.startActivityForResult(intent, requestCode);
2411    }
2412
2413    @Override
2414    public void onSaveInstanceState(@NotNull Bundle outState) {
2415        super.onSaveInstanceState(outState);
2416        if (conversation != null) {
2417            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2418            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2419            final Uri uri = pendingTakePhotoUri.peek();
2420            if (uri != null) {
2421                outState.putString(STATE_PHOTO_URI, uri.toString());
2422            }
2423            final ScrollState scrollState = getScrollPosition();
2424            if (scrollState != null) {
2425                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2426            }
2427            final ArrayList<Attachment> attachments =
2428                    mediaPreviewAdapter == null
2429                            ? new ArrayList<>()
2430                            : mediaPreviewAdapter.getAttachments();
2431            if (attachments.size() > 0) {
2432                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2433            }
2434        }
2435    }
2436
2437    @Override
2438    public void onActivityCreated(Bundle savedInstanceState) {
2439        super.onActivityCreated(savedInstanceState);
2440        if (savedInstanceState == null) {
2441            return;
2442        }
2443        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2444        ArrayList<Attachment> attachments =
2445                savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2446        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2447        if (uuid != null) {
2448            QuickLoader.set(uuid);
2449            this.pendingConversationsUuid.push(uuid);
2450            if (attachments != null && attachments.size() > 0) {
2451                this.pendingMediaPreviews.push(attachments);
2452            }
2453            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2454            if (takePhotoUri != null) {
2455                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2456            }
2457            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2458        }
2459    }
2460
2461    @Override
2462    public void onStart() {
2463        super.onStart();
2464        if (this.reInitRequiredOnStart && this.conversation != null) {
2465            final Bundle extras = pendingExtras.pop();
2466            reInit(this.conversation, extras != null);
2467            if (extras != null) {
2468                processExtras(extras);
2469            }
2470        } else if (conversation == null
2471                && activity != null
2472                && activity.xmppConnectionService != null) {
2473            final String uuid = pendingConversationsUuid.pop();
2474            Log.d(
2475                    Config.LOGTAG,
2476                    "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
2477                            + uuid);
2478            if (uuid != null) {
2479                findAndReInitByUuidOrArchive(uuid);
2480            }
2481        }
2482    }
2483
2484    @Override
2485    public void onStop() {
2486        super.onStop();
2487        final Activity activity = getActivity();
2488        messageListAdapter.unregisterListenerInAudioPlayer();
2489        if (activity == null || !activity.isChangingConfigurations()) {
2490            hideSoftKeyboard(activity);
2491            messageListAdapter.stopAudioPlayer();
2492        }
2493        if (this.conversation != null) {
2494            final String msg = this.binding.textinput.getText().toString();
2495            storeNextMessage(msg);
2496            updateChatState(this.conversation, msg);
2497            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2498        }
2499        this.reInitRequiredOnStart = true;
2500    }
2501
2502    private void updateChatState(final Conversation conversation, final String msg) {
2503        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2504        Account.State status = conversation.getAccount().getStatus();
2505        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2506            activity.xmppConnectionService.sendChatState(conversation);
2507        }
2508    }
2509
2510    private void saveMessageDraftStopAudioPlayer() {
2511        final Conversation previousConversation = this.conversation;
2512        if (this.activity == null || this.binding == null || previousConversation == null) {
2513            return;
2514        }
2515        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2516        final String msg = this.binding.textinput.getText().toString();
2517        storeNextMessage(msg);
2518        updateChatState(this.conversation, msg);
2519        messageListAdapter.stopAudioPlayer();
2520        mediaPreviewAdapter.clearPreviews();
2521        toggleInputMethod();
2522    }
2523
2524    public void reInit(final Conversation conversation, final Bundle extras) {
2525        QuickLoader.set(conversation.getUuid());
2526        final boolean changedConversation = this.conversation != conversation;
2527        if (changedConversation) {
2528            this.saveMessageDraftStopAudioPlayer();
2529        }
2530        this.clearPending();
2531        if (this.reInit(conversation, extras != null)) {
2532            if (extras != null) {
2533                processExtras(extras);
2534            }
2535            this.reInitRequiredOnStart = false;
2536        } else {
2537            this.reInitRequiredOnStart = true;
2538            pendingExtras.push(extras);
2539        }
2540        resetUnreadMessagesCount();
2541    }
2542
2543    private void reInit(Conversation conversation) {
2544        reInit(conversation, false);
2545    }
2546
2547    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2548        if (conversation == null) {
2549            return false;
2550        }
2551        final Conversation originalConversation = this.conversation;
2552        this.conversation = conversation;
2553        // once we set the conversation all is good and it will automatically do the right thing in
2554        // onStart()
2555        if (this.activity == null || this.binding == null) {
2556            return false;
2557        }
2558
2559        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2560            activity.onConversationArchived(this.conversation);
2561            return false;
2562        }
2563
2564        stopScrolling();
2565        Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
2566
2567        if (this.conversation.isRead() && hasExtras) {
2568            Log.d(Config.LOGTAG, "trimming conversation");
2569            this.conversation.trim();
2570        }
2571
2572        setupIme();
2573
2574        final boolean scrolledToBottomAndNoPending =
2575                this.scrolledToBottom() && pendingScrollState.peek() == null;
2576
2577        this.binding.textSendButton.setContentDescription(
2578                activity.getString(R.string.send_message_to_x, conversation.getName()));
2579        this.binding.textinput.setKeyboardListener(null);
2580        this.binding.textinput.setText("");
2581        final boolean participating =
2582                conversation.getMode() == Conversational.MODE_SINGLE
2583                        || conversation.getMucOptions().participating();
2584        if (participating) {
2585            this.binding.textinput.append(this.conversation.getNextMessage());
2586        }
2587        this.binding.textinput.setKeyboardListener(this);
2588        messageListAdapter.updatePreferences();
2589        refresh(false);
2590        activity.invalidateOptionsMenu();
2591        this.conversation.messagesLoaded.set(true);
2592        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
2593
2594        if (hasExtras || scrolledToBottomAndNoPending) {
2595            resetUnreadMessagesCount();
2596            synchronized (this.messageList) {
2597                Log.d(Config.LOGTAG, "jump to first unread message");
2598                final Message first = conversation.getFirstUnreadMessage();
2599                final int bottom = Math.max(0, this.messageList.size() - 1);
2600                final int pos;
2601                final boolean jumpToBottom;
2602                if (first == null) {
2603                    pos = bottom;
2604                    jumpToBottom = true;
2605                } else {
2606                    int i = getIndexOf(first.getUuid(), this.messageList);
2607                    pos = i < 0 ? bottom : i;
2608                    jumpToBottom = false;
2609                }
2610                setSelection(pos, jumpToBottom);
2611            }
2612        }
2613
2614        this.binding.messagesView.post(this::fireReadEvent);
2615        // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
2616        // layout which might be unnecessary since we can *see* it
2617        activity.xmppConnectionService
2618                .getNotificationService()
2619                .setOpenConversation(this.conversation);
2620
2621        if (commandAdapter != null && conversation != originalConversation) {
2622            originalConversation.setupViewPager(null, null);
2623            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout);
2624            refreshCommands();
2625        }
2626        if (commandAdapter == null && conversation != null) {
2627            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout);
2628            commandAdapter = new CommandAdapter((XmppActivity) getActivity());
2629            binding.commandsView.setAdapter(commandAdapter);
2630            binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
2631                final Element command = commandAdapter.getItem(position);
2632                activity.startCommand(conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
2633            });
2634            refreshCommands();
2635        }
2636
2637        return true;
2638    }
2639
2640    protected void refreshCommands() {
2641        if (commandAdapter == null) return;
2642
2643        Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
2644        if (commandJid == null) {
2645            conversation.hideViewPager();
2646        } else {
2647            conversation.showViewPager();
2648            activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
2649                if (activity == null) return;
2650
2651                activity.runOnUiThread(() -> {
2652                    if (iq.getType() == IqPacket.TYPE.RESULT) {
2653                        binding.commandsViewProgressbar.setVisibility(View.GONE);
2654                        commandAdapter.clear();
2655                        for (Element child : iq.query().getChildren()) {
2656                            if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
2657                            commandAdapter.add(child);
2658                        }
2659                    }
2660
2661                    if (commandAdapter.getCount() < 1) conversation.hideViewPager();
2662                });
2663            });
2664        }
2665    }
2666
2667    private void resetUnreadMessagesCount() {
2668        lastMessageUuid = null;
2669        hideUnreadMessagesCount();
2670    }
2671
2672    private void hideUnreadMessagesCount() {
2673        if (this.binding == null) {
2674            return;
2675        }
2676        this.binding.scrollToBottomButton.setEnabled(false);
2677        this.binding.scrollToBottomButton.hide();
2678        this.binding.unreadCountCustomView.setVisibility(View.GONE);
2679    }
2680
2681    private void setSelection(int pos, boolean jumpToBottom) {
2682        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2683        this.binding.messagesView.post(
2684                () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2685        this.binding.messagesView.post(this::fireReadEvent);
2686    }
2687
2688    private boolean scrolledToBottom() {
2689        return this.binding != null && scrolledToBottom(this.binding.messagesView);
2690    }
2691
2692    private void processExtras(final Bundle extras) {
2693        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2694        final String text = extras.getString(Intent.EXTRA_TEXT);
2695        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2696        final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
2697        final String postInitAction =
2698                extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
2699        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2700        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2701        final boolean doNotAppend =
2702                extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2703        final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
2704        final List<Uri> uris = extractUris(extras);
2705        if (uris != null && uris.size() > 0) {
2706            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2707                mediaPreviewAdapter.addMediaPreviews(
2708                        Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2709            } else {
2710                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2711                mediaPreviewAdapter.addMediaPreviews(
2712                        Attachment.of(getActivity(), cleanedUris, type));
2713            }
2714            toggleInputMethod();
2715            return;
2716        }
2717        if (nick != null) {
2718            if (pm) {
2719                Jid jid = conversation.getJid();
2720                try {
2721                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2722                    privateMessageWith(next);
2723                } catch (final IllegalArgumentException ignored) {
2724                    // do nothing
2725                }
2726            } else {
2727                final MucOptions mucOptions = conversation.getMucOptions();
2728                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2729                    highlightInConference(nick);
2730                }
2731            }
2732        } else {
2733            if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
2734                mediaPreviewAdapter.addMediaPreviews(
2735                        Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
2736                toggleInputMethod();
2737                return;
2738            } else if (text != null && asQuote) {
2739                quoteText(text);
2740            } else {
2741                appendText(text, doNotAppend);
2742            }
2743        }
2744        if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
2745            attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
2746            return;
2747        }
2748        if ("message".equals(postInitAction)) {
2749            binding.conversationViewPager.post(() -> {
2750                binding.conversationViewPager.setCurrentItem(0);
2751            });
2752        }
2753        if ("command".equals(postInitAction)) {
2754            binding.conversationViewPager.post(() -> {
2755                PagerAdapter adapter = binding.conversationViewPager.getAdapter();
2756                if (adapter != null && adapter.getCount() > 1) {
2757                    binding.conversationViewPager.setCurrentItem(1);
2758                }
2759                final Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
2760                if (node != null && commandJid != null) {
2761                    conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
2762                }
2763            });
2764            return;
2765        }
2766        final Message message =
2767                downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2768        if (message != null) {
2769            startDownloadable(message);
2770        }
2771    }
2772
2773    private Element commandFor(final Jid jid, final String node) {
2774        if (commandAdapter != null) {
2775            for (int i = 0; i < commandAdapter.getCount(); i++) {
2776                Element command = commandAdapter.getItem(i);
2777                final String commandNode = command.getAttribute("node");
2778                if (commandNode == null || !commandNode.equals(node)) continue;
2779
2780                final Jid commandJid = command.getAttributeAsJid("jid");
2781                if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
2782
2783                return command;
2784            }
2785        }
2786
2787        return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
2788    }
2789
2790    private List<Uri> extractUris(final Bundle extras) {
2791        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2792        if (uris != null) {
2793            return uris;
2794        }
2795        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2796        if (uri != null) {
2797            return Collections.singletonList(uri);
2798        } else {
2799            return null;
2800        }
2801    }
2802
2803    private List<Uri> cleanUris(final List<Uri> uris) {
2804        final Iterator<Uri> iterator = uris.iterator();
2805        while (iterator.hasNext()) {
2806            final Uri uri = iterator.next();
2807            if (FileBackend.weOwnFile(uri)) {
2808                iterator.remove();
2809                Toast.makeText(
2810                                getActivity(),
2811                                R.string.security_violation_not_attaching_file,
2812                                Toast.LENGTH_SHORT)
2813                        .show();
2814            }
2815        }
2816        return uris;
2817    }
2818
2819    private boolean showBlockSubmenu(View view) {
2820        final Jid jid = conversation.getJid();
2821        final boolean showReject =
2822                !conversation.isWithStranger()
2823                        && conversation
2824                                .getContact()
2825                                .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2826        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2827        popupMenu.inflate(R.menu.block);
2828        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2829        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2830        popupMenu.setOnMenuItemClickListener(
2831                menuItem -> {
2832                    Blockable blockable;
2833                    switch (menuItem.getItemId()) {
2834                        case R.id.reject:
2835                            activity.xmppConnectionService.stopPresenceUpdatesTo(
2836                                    conversation.getContact());
2837                            updateSnackBar(conversation);
2838                            return true;
2839                        case R.id.block_domain:
2840                            blockable =
2841                                    conversation
2842                                            .getAccount()
2843                                            .getRoster()
2844                                            .getContact(jid.getDomain());
2845                            break;
2846                        default:
2847                            blockable = conversation;
2848                    }
2849                    BlockContactDialog.show(activity, blockable);
2850                    return true;
2851                });
2852        popupMenu.show();
2853        return true;
2854    }
2855
2856    private void updateSnackBar(final Conversation conversation) {
2857        final Account account = conversation.getAccount();
2858        final XmppConnection connection = account.getXmppConnection();
2859        final int mode = conversation.getMode();
2860        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2861        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2862            return;
2863        }
2864        if (account.getStatus() == Account.State.DISABLED) {
2865            showSnackbar(
2866                    R.string.this_account_is_disabled,
2867                    R.string.enable,
2868                    this.mEnableAccountListener);
2869        } else if (conversation.isBlocked()) {
2870            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2871        } else if (contact != null
2872                && !contact.showInRoster()
2873                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2874            showSnackbar(
2875                    R.string.contact_added_you,
2876                    R.string.add_back,
2877                    this.mAddBackClickListener,
2878                    this.mLongPressBlockListener);
2879        } else if (contact != null
2880                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2881            showSnackbar(
2882                    R.string.contact_asks_for_presence_subscription,
2883                    R.string.allow,
2884                    this.mAllowPresenceSubscription,
2885                    this.mLongPressBlockListener);
2886        } else if (mode == Conversation.MODE_MULTI
2887                && !conversation.getMucOptions().online()
2888                && account.getStatus() == Account.State.ONLINE) {
2889            switch (conversation.getMucOptions().getError()) {
2890                case NICK_IN_USE:
2891                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2892                    break;
2893                case NO_RESPONSE:
2894                    showSnackbar(R.string.joining_conference, 0, null);
2895                    break;
2896                case SERVER_NOT_FOUND:
2897                    if (conversation.receivedMessagesCount() > 0) {
2898                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2899                    } else {
2900                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2901                    }
2902                    break;
2903                case REMOTE_SERVER_TIMEOUT:
2904                    if (conversation.receivedMessagesCount() > 0) {
2905                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2906                    } else {
2907                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2908                    }
2909                    break;
2910                case PASSWORD_REQUIRED:
2911                    showSnackbar(
2912                            R.string.conference_requires_password,
2913                            R.string.enter_password,
2914                            enterPassword);
2915                    break;
2916                case BANNED:
2917                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2918                    break;
2919                case MEMBERS_ONLY:
2920                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2921                    break;
2922                case RESOURCE_CONSTRAINT:
2923                    showSnackbar(
2924                            R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2925                    break;
2926                case KICKED:
2927                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2928                    break;
2929                case TECHNICAL_PROBLEMS:
2930                    showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
2931                    break;
2932                case UNKNOWN:
2933                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2934                    break;
2935                case INVALID_NICK:
2936                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2937                case SHUTDOWN:
2938                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2939                    break;
2940                case DESTROYED:
2941                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2942                    break;
2943                case NON_ANONYMOUS:
2944                    showSnackbar(
2945                            R.string.group_chat_will_make_your_jabber_id_public,
2946                            R.string.join,
2947                            acceptJoin);
2948                    break;
2949                default:
2950                    hideSnackbar();
2951                    break;
2952            }
2953        } else if (account.hasPendingPgpIntent(conversation)) {
2954            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2955        } else if (connection != null
2956                && connection.getFeatures().blocking()
2957                && conversation.countMessages() != 0
2958                && !conversation.isBlocked()
2959                && conversation.isWithStranger()) {
2960            showSnackbar(
2961                    R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2962        } else {
2963            hideSnackbar();
2964        }
2965    }
2966
2967    @Override
2968    public void refresh() {
2969        if (this.binding == null) {
2970            Log.d(
2971                    Config.LOGTAG,
2972                    "ConversationFragment.refresh() skipped updated because view binding was null");
2973            return;
2974        }
2975        if (this.conversation != null
2976                && this.activity != null
2977                && this.activity.xmppConnectionService != null) {
2978            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2979                activity.onConversationArchived(this.conversation);
2980                return;
2981            }
2982        }
2983        this.refresh(true);
2984    }
2985
2986    private void refresh(boolean notifyConversationRead) {
2987        synchronized (this.messageList) {
2988            if (this.conversation != null) {
2989                conversation.populateWithMessages(this.messageList);
2990                updateSnackBar(conversation);
2991                updateStatusMessages();
2992                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2993                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2994                    binding.unreadCountCustomView.setUnreadCount(
2995                            conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2996                }
2997                this.messageListAdapter.notifyDataSetChanged();
2998                updateChatMsgHint();
2999                if (notifyConversationRead && activity != null) {
3000                    binding.messagesView.post(this::fireReadEvent);
3001                }
3002                updateSendButton();
3003                updateEditablity();
3004            }
3005        }
3006    }
3007
3008    protected void messageSent() {
3009        mSendingPgpMessage.set(false);
3010        this.binding.textinput.setText("");
3011        if (conversation.setCorrectingMessage(null)) {
3012            this.binding.textinput.append(conversation.getDraftMessage());
3013            conversation.setDraftMessage(null);
3014        }
3015        storeNextMessage();
3016        updateChatMsgHint();
3017        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3018        final boolean prefScrollToBottom =
3019                p.getBoolean(
3020                        "scroll_to_bottom",
3021                        activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3022        if (prefScrollToBottom || scrolledToBottom()) {
3023            new Handler()
3024                    .post(
3025                            () -> {
3026                                int size = messageList.size();
3027                                this.binding.messagesView.setSelection(size - 1);
3028                            });
3029        }
3030    }
3031
3032    private boolean storeNextMessage() {
3033        return storeNextMessage(this.binding.textinput.getText().toString());
3034    }
3035
3036    private boolean storeNextMessage(String msg) {
3037        final boolean participating =
3038                conversation.getMode() == Conversational.MODE_SINGLE
3039                        || conversation.getMucOptions().participating();
3040        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3041                && participating
3042                && this.conversation.setNextMessage(msg)) {
3043            this.activity.xmppConnectionService.updateConversation(this.conversation);
3044            return true;
3045        }
3046        return false;
3047    }
3048
3049    public void doneSendingPgpMessage() {
3050        mSendingPgpMessage.set(false);
3051    }
3052
3053    public long getMaxHttpUploadSize(Conversation conversation) {
3054        final XmppConnection connection = conversation.getAccount().getXmppConnection();
3055        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3056    }
3057
3058    private void updateEditablity() {
3059        boolean canWrite =
3060                this.conversation.getMode() == Conversation.MODE_SINGLE
3061                        || this.conversation.getMucOptions().participating()
3062                        || this.conversation.getNextCounterpart() != null;
3063        this.binding.textinput.setFocusable(canWrite);
3064        this.binding.textinput.setFocusableInTouchMode(canWrite);
3065        this.binding.textSendButton.setEnabled(canWrite);
3066        this.binding.textinput.setCursorVisible(canWrite);
3067        this.binding.textinput.setEnabled(canWrite);
3068    }
3069
3070    public void updateSendButton() {
3071        boolean hasAttachments =
3072                mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3073        final Conversation c = this.conversation;
3074        final Presence.Status status;
3075        final String text =
3076                this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3077        final SendButtonAction action;
3078        if (hasAttachments) {
3079            action = SendButtonAction.TEXT;
3080        } else {
3081            action = SendButtonTool.getAction(getActivity(), c, text);
3082        }
3083        if (c.getAccount().getStatus() == Account.State.ONLINE) {
3084            if (activity != null
3085                    && activity.xmppConnectionService != null
3086                    && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3087                status = Presence.Status.OFFLINE;
3088            } else if (c.getMode() == Conversation.MODE_SINGLE) {
3089                status = c.getContact().getShownStatus();
3090            } else {
3091                status =
3092                        c.getMucOptions().online()
3093                                ? Presence.Status.ONLINE
3094                                : Presence.Status.OFFLINE;
3095            }
3096        } else {
3097            status = Presence.Status.OFFLINE;
3098        }
3099        this.binding.textSendButton.setTag(action);
3100        final Activity activity = getActivity();
3101        if (activity != null) {
3102            this.binding.textSendButton.setImageResource(
3103                    SendButtonTool.getSendButtonImageResource(activity, action, status));
3104        }
3105
3106        if (hasAttachments || binding.textinput.getText().length() > 0) {
3107            binding.conversationViewPager.setCurrentItem(0);
3108        }
3109    }
3110
3111    protected void updateStatusMessages() {
3112        DateSeparator.addAll(this.messageList);
3113        if (showLoadMoreMessages(conversation)) {
3114            this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3115        }
3116        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3117            ChatState state = conversation.getIncomingChatState();
3118            if (state == ChatState.COMPOSING) {
3119                this.messageList.add(
3120                        Message.createStatusMessage(
3121                                conversation,
3122                                getString(R.string.contact_is_typing, conversation.getName())));
3123            } else if (state == ChatState.PAUSED) {
3124                this.messageList.add(
3125                        Message.createStatusMessage(
3126                                conversation,
3127                                getString(
3128                                        R.string.contact_has_stopped_typing,
3129                                        conversation.getName())));
3130            } else {
3131                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3132                    final Message message = this.messageList.get(i);
3133                    if (message.getType() != Message.TYPE_STATUS) {
3134                        if (message.getStatus() == Message.STATUS_RECEIVED) {
3135                            return;
3136                        } else {
3137                            if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3138                                this.messageList.add(
3139                                        i + 1,
3140                                        Message.createStatusMessage(
3141                                                conversation,
3142                                                getString(
3143                                                        R.string.contact_has_read_up_to_this_point,
3144                                                        conversation.getName())));
3145                                return;
3146                            }
3147                        }
3148                    }
3149                }
3150            }
3151        } else {
3152            final MucOptions mucOptions = conversation.getMucOptions();
3153            final List<MucOptions.User> allUsers = mucOptions.getUsers();
3154            final Set<ReadByMarker> addedMarkers = new HashSet<>();
3155            ChatState state = ChatState.COMPOSING;
3156            List<MucOptions.User> users =
3157                    conversation.getMucOptions().getUsersWithChatState(state, 5);
3158            if (users.size() == 0) {
3159                state = ChatState.PAUSED;
3160                users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3161            }
3162            if (mucOptions.isPrivateAndNonAnonymous()) {
3163                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3164                    final Set<ReadByMarker> markersForMessage =
3165                            messageList.get(i).getReadByMarkers();
3166                    final List<MucOptions.User> shownMarkers = new ArrayList<>();
3167                    for (ReadByMarker marker : markersForMessage) {
3168                        if (!ReadByMarker.contains(marker, addedMarkers)) {
3169                            addedMarkers.add(
3170                                    marker); // may be put outside this condition. set should do
3171                                             // dedup anyway
3172                            MucOptions.User user = mucOptions.findUser(marker);
3173                            if (user != null && !users.contains(user)) {
3174                                shownMarkers.add(user);
3175                            }
3176                        }
3177                    }
3178                    final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3179                    final Message statusMessage;
3180                    final int size = shownMarkers.size();
3181                    if (size > 1) {
3182                        final String body;
3183                        if (size <= 4) {
3184                            body =
3185                                    getString(
3186                                            R.string.contacts_have_read_up_to_this_point,
3187                                            UIHelper.concatNames(shownMarkers));
3188                        } else if (ReadByMarker.allUsersRepresented(
3189                                allUsers, markersForMessage, markerForSender)) {
3190                            body = getString(R.string.everyone_has_read_up_to_this_point);
3191                        } else {
3192                            body =
3193                                    getString(
3194                                            R.string.contacts_and_n_more_have_read_up_to_this_point,
3195                                            UIHelper.concatNames(shownMarkers, 3),
3196                                            size - 3);
3197                        }
3198                        statusMessage = Message.createStatusMessage(conversation, body);
3199                        statusMessage.setCounterparts(shownMarkers);
3200                    } else if (size == 1) {
3201                        statusMessage =
3202                                Message.createStatusMessage(
3203                                        conversation,
3204                                        getString(
3205                                                R.string.contact_has_read_up_to_this_point,
3206                                                UIHelper.getDisplayName(shownMarkers.get(0))));
3207                        statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3208                        statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3209                    } else {
3210                        statusMessage = null;
3211                    }
3212                    if (statusMessage != null) {
3213                        this.messageList.add(i + 1, statusMessage);
3214                    }
3215                    addedMarkers.add(markerForSender);
3216                    if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3217                        break;
3218                    }
3219                }
3220            }
3221            if (users.size() > 0) {
3222                Message statusMessage;
3223                if (users.size() == 1) {
3224                    MucOptions.User user = users.get(0);
3225                    int id =
3226                            state == ChatState.COMPOSING
3227                                    ? R.string.contact_is_typing
3228                                    : R.string.contact_has_stopped_typing;
3229                    statusMessage =
3230                            Message.createStatusMessage(
3231                                    conversation, getString(id, UIHelper.getDisplayName(user)));
3232                    statusMessage.setTrueCounterpart(user.getRealJid());
3233                    statusMessage.setCounterpart(user.getFullJid());
3234                } else {
3235                    int id =
3236                            state == ChatState.COMPOSING
3237                                    ? R.string.contacts_are_typing
3238                                    : R.string.contacts_have_stopped_typing;
3239                    statusMessage =
3240                            Message.createStatusMessage(
3241                                    conversation, getString(id, UIHelper.concatNames(users)));
3242                    statusMessage.setCounterparts(users);
3243                }
3244                this.messageList.add(statusMessage);
3245            }
3246        }
3247    }
3248
3249    private void stopScrolling() {
3250        long now = SystemClock.uptimeMillis();
3251        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3252        binding.messagesView.dispatchTouchEvent(cancel);
3253    }
3254
3255    private boolean showLoadMoreMessages(final Conversation c) {
3256        if (activity == null || activity.xmppConnectionService == null) {
3257            return false;
3258        }
3259        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3260        final MessageArchiveService service =
3261                activity.xmppConnectionService.getMessageArchiveService();
3262        return mam
3263                && (c.getLastClearHistory().getTimestamp() != 0
3264                        || (c.countMessages() == 0
3265                                && c.messagesLoaded.get()
3266                                && c.hasMessagesLeftOnServer()
3267                                && !service.queryInProgress(c)));
3268    }
3269
3270    private boolean hasMamSupport(final Conversation c) {
3271        if (c.getMode() == Conversation.MODE_SINGLE) {
3272            final XmppConnection connection = c.getAccount().getXmppConnection();
3273            return connection != null && connection.getFeatures().mam();
3274        } else {
3275            return c.getMucOptions().mamSupport();
3276        }
3277    }
3278
3279    protected void showSnackbar(
3280            final int message, final int action, final OnClickListener clickListener) {
3281        showSnackbar(message, action, clickListener, null);
3282    }
3283
3284    protected void showSnackbar(
3285            final int message,
3286            final int action,
3287            final OnClickListener clickListener,
3288            final View.OnLongClickListener longClickListener) {
3289        this.binding.snackbar.setVisibility(View.VISIBLE);
3290        this.binding.snackbar.setOnClickListener(null);
3291        this.binding.snackbarMessage.setText(message);
3292        this.binding.snackbarMessage.setOnClickListener(null);
3293        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3294        if (action != 0) {
3295            this.binding.snackbarAction.setText(action);
3296        }
3297        this.binding.snackbarAction.setOnClickListener(clickListener);
3298        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3299    }
3300
3301    protected void hideSnackbar() {
3302        this.binding.snackbar.setVisibility(View.GONE);
3303    }
3304
3305    protected void sendMessage(Message message) {
3306        activity.xmppConnectionService.sendMessage(message);
3307        messageSent();
3308    }
3309
3310    protected void sendPgpMessage(final Message message) {
3311        final XmppConnectionService xmppService = activity.xmppConnectionService;
3312        final Contact contact = message.getConversation().getContact();
3313        if (!activity.hasPgp()) {
3314            activity.showInstallPgpDialog();
3315            return;
3316        }
3317        if (conversation.getAccount().getPgpSignature() == null) {
3318            activity.announcePgp(
3319                    conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3320            return;
3321        }
3322        if (!mSendingPgpMessage.compareAndSet(false, true)) {
3323            Log.d(Config.LOGTAG, "sending pgp message already in progress");
3324        }
3325        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3326            if (contact.getPgpKeyId() != 0) {
3327                xmppService
3328                        .getPgpEngine()
3329                        .hasKey(
3330                                contact,
3331                                new UiCallback<Contact>() {
3332
3333                                    @Override
3334                                    public void userInputRequired(
3335                                            PendingIntent pi, Contact contact) {
3336                                        startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3337                                    }
3338
3339                                    @Override
3340                                    public void success(Contact contact) {
3341                                        encryptTextMessage(message);
3342                                    }
3343
3344                                    @Override
3345                                    public void error(int error, Contact contact) {
3346                                        activity.runOnUiThread(
3347                                                () ->
3348                                                        Toast.makeText(
3349                                                                        activity,
3350                                                                        R.string
3351                                                                                .unable_to_connect_to_keychain,
3352                                                                        Toast.LENGTH_SHORT)
3353                                                                .show());
3354                                        mSendingPgpMessage.set(false);
3355                                    }
3356                                });
3357
3358            } else {
3359                showNoPGPKeyDialog(
3360                        false,
3361                        (dialog, which) -> {
3362                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3363                            xmppService.updateConversation(conversation);
3364                            message.setEncryption(Message.ENCRYPTION_NONE);
3365                            xmppService.sendMessage(message);
3366                            messageSent();
3367                        });
3368            }
3369        } else {
3370            if (conversation.getMucOptions().pgpKeysInUse()) {
3371                if (!conversation.getMucOptions().everybodyHasKeys()) {
3372                    Toast warning =
3373                            Toast.makeText(
3374                                    getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3375                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3376                    warning.show();
3377                }
3378                encryptTextMessage(message);
3379            } else {
3380                showNoPGPKeyDialog(
3381                        true,
3382                        (dialog, which) -> {
3383                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3384                            message.setEncryption(Message.ENCRYPTION_NONE);
3385                            xmppService.updateConversation(conversation);
3386                            xmppService.sendMessage(message);
3387                            messageSent();
3388                        });
3389            }
3390        }
3391    }
3392
3393    public void encryptTextMessage(Message message) {
3394        activity.xmppConnectionService
3395                .getPgpEngine()
3396                .encrypt(
3397                        message,
3398                        new UiCallback<Message>() {
3399
3400                            @Override
3401                            public void userInputRequired(PendingIntent pi, Message message) {
3402                                startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3403                            }
3404
3405                            @Override
3406                            public void success(Message message) {
3407                                // TODO the following two call can be made before the callback
3408                                getActivity().runOnUiThread(() -> messageSent());
3409                            }
3410
3411                            @Override
3412                            public void error(final int error, Message message) {
3413                                getActivity()
3414                                        .runOnUiThread(
3415                                                () -> {
3416                                                    doneSendingPgpMessage();
3417                                                    Toast.makeText(
3418                                                                    getActivity(),
3419                                                                    error == 0
3420                                                                            ? R.string
3421                                                                                    .unable_to_connect_to_keychain
3422                                                                            : error,
3423                                                                    Toast.LENGTH_SHORT)
3424                                                            .show();
3425                                                });
3426                            }
3427                        });
3428    }
3429
3430    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3431        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3432        builder.setIconAttribute(android.R.attr.alertDialogIcon);
3433        if (plural) {
3434            builder.setTitle(getString(R.string.no_pgp_keys));
3435            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3436        } else {
3437            builder.setTitle(getString(R.string.no_pgp_key));
3438            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3439        }
3440        builder.setNegativeButton(getString(R.string.cancel), null);
3441        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3442        builder.create().show();
3443    }
3444
3445    public void appendText(String text, final boolean doNotAppend) {
3446        if (text == null) {
3447            return;
3448        }
3449        final Editable editable = this.binding.textinput.getText();
3450        String previous = editable == null ? "" : editable.toString();
3451        if (doNotAppend && !TextUtils.isEmpty(previous)) {
3452            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3453                    .show();
3454            return;
3455        }
3456        if (UIHelper.isLastLineQuote(previous)) {
3457            text = '\n' + text;
3458        } else if (previous.length() != 0
3459                && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3460            text = " " + text;
3461        }
3462        this.binding.textinput.append(text);
3463    }
3464
3465    @Override
3466    public boolean onEnterPressed(final boolean isCtrlPressed) {
3467        if (isCtrlPressed || enterIsSend()) {
3468            sendMessage();
3469            return true;
3470        }
3471        return false;
3472    }
3473
3474    private boolean enterIsSend() {
3475        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3476        return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3477    }
3478
3479    public boolean onArrowUpCtrlPressed() {
3480        final Message lastEditableMessage =
3481                conversation == null ? null : conversation.getLastEditableMessage();
3482        if (lastEditableMessage != null) {
3483            correctMessage(lastEditableMessage);
3484            return true;
3485        } else {
3486            Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3487                    .show();
3488            return false;
3489        }
3490    }
3491
3492    @Override
3493    public void onTypingStarted() {
3494        final XmppConnectionService service =
3495                activity == null ? null : activity.xmppConnectionService;
3496        if (service == null) {
3497            return;
3498        }
3499        final Account.State status = conversation.getAccount().getStatus();
3500        if (status == Account.State.ONLINE
3501                && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3502            service.sendChatState(conversation);
3503        }
3504        runOnUiThread(this::updateSendButton);
3505    }
3506
3507    @Override
3508    public void onTypingStopped() {
3509        final XmppConnectionService service =
3510                activity == null ? null : activity.xmppConnectionService;
3511        if (service == null) {
3512            return;
3513        }
3514        final Account.State status = conversation.getAccount().getStatus();
3515        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3516            service.sendChatState(conversation);
3517        }
3518    }
3519
3520    @Override
3521    public void onTextDeleted() {
3522        final XmppConnectionService service =
3523                activity == null ? null : activity.xmppConnectionService;
3524        if (service == null) {
3525            return;
3526        }
3527        final Account.State status = conversation.getAccount().getStatus();
3528        if (status == Account.State.ONLINE
3529                && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3530            service.sendChatState(conversation);
3531        }
3532        if (storeNextMessage()) {
3533            runOnUiThread(
3534                    () -> {
3535                        if (activity == null) {
3536                            return;
3537                        }
3538                        activity.onConversationsListItemUpdated();
3539                    });
3540        }
3541        runOnUiThread(this::updateSendButton);
3542    }
3543
3544    @Override
3545    public void onTextChanged() {
3546        if (conversation != null && conversation.getCorrectingMessage() != null) {
3547            runOnUiThread(this::updateSendButton);
3548        }
3549    }
3550
3551    @Override
3552    public boolean onTabPressed(boolean repeated) {
3553        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3554            return false;
3555        }
3556        if (repeated) {
3557            completionIndex++;
3558        } else {
3559            lastCompletionLength = 0;
3560            completionIndex = 0;
3561            final String content = this.binding.textinput.getText().toString();
3562            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
3563            int start =
3564                    lastCompletionCursor > 0
3565                            ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
3566                            : 0;
3567            firstWord = start == 0;
3568            incomplete = content.substring(start, lastCompletionCursor);
3569        }
3570        List<String> completions = new ArrayList<>();
3571        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
3572            String name = user.getName();
3573            if (name != null && name.startsWith(incomplete)) {
3574                completions.add(name + (firstWord ? ": " : " "));
3575            }
3576        }
3577        Collections.sort(completions);
3578        if (completions.size() > completionIndex) {
3579            String completion = completions.get(completionIndex).substring(incomplete.length());
3580            this.binding
3581                    .textinput
3582                    .getEditableText()
3583                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3584            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
3585            lastCompletionLength = completion.length();
3586        } else {
3587            completionIndex = -1;
3588            this.binding
3589                    .textinput
3590                    .getEditableText()
3591                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3592            lastCompletionLength = 0;
3593        }
3594        return true;
3595    }
3596
3597    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
3598        try {
3599            getActivity()
3600                    .startIntentSenderForResult(
3601                            pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
3602        } catch (final SendIntentException ignored) {
3603        }
3604    }
3605
3606    @Override
3607    public void onBackendConnected() {
3608        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
3609        String uuid = pendingConversationsUuid.pop();
3610        if (uuid != null) {
3611            if (!findAndReInitByUuidOrArchive(uuid)) {
3612                return;
3613            }
3614        } else {
3615            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
3616                clearPending();
3617                activity.onConversationArchived(conversation);
3618                return;
3619            }
3620        }
3621        ActivityResult activityResult = postponedActivityResult.pop();
3622        if (activityResult != null) {
3623            handleActivityResult(activityResult);
3624        }
3625        clearPending();
3626    }
3627
3628    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
3629        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
3630        if (conversation == null) {
3631            clearPending();
3632            activity.onConversationArchived(null);
3633            return false;
3634        }
3635        reInit(conversation);
3636        ScrollState scrollState = pendingScrollState.pop();
3637        String lastMessageUuid = pendingLastMessageUuid.pop();
3638        List<Attachment> attachments = pendingMediaPreviews.pop();
3639        if (scrollState != null) {
3640            setScrollPosition(scrollState, lastMessageUuid);
3641        }
3642        if (attachments != null && attachments.size() > 0) {
3643            Log.d(Config.LOGTAG, "had attachments on restore");
3644            mediaPreviewAdapter.addMediaPreviews(attachments);
3645            toggleInputMethod();
3646        }
3647        return true;
3648    }
3649
3650    private void clearPending() {
3651        if (postponedActivityResult.clear()) {
3652            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
3653            if (pendingTakePhotoUri.clear()) {
3654                Log.e(Config.LOGTAG, "cleared pending photo uri");
3655            }
3656        }
3657        if (pendingScrollState.clear()) {
3658            Log.e(Config.LOGTAG, "cleared scroll state");
3659        }
3660        if (pendingConversationsUuid.clear()) {
3661            Log.e(Config.LOGTAG, "cleared pending conversations uuid");
3662        }
3663        if (pendingMediaPreviews.clear()) {
3664            Log.e(Config.LOGTAG, "cleared pending media previews");
3665        }
3666    }
3667
3668    public Conversation getConversation() {
3669        return conversation;
3670    }
3671
3672    @Override
3673    public void onContactPictureLongClicked(View v, final Message message) {
3674        final String fingerprint;
3675        if (message.getEncryption() == Message.ENCRYPTION_PGP
3676                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3677            fingerprint = "pgp";
3678        } else {
3679            fingerprint = message.getFingerprint();
3680        }
3681        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
3682        final Contact contact = message.getContact();
3683        if (message.getStatus() <= Message.STATUS_RECEIVED
3684                && (contact == null || !contact.isSelf())) {
3685            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
3686                final Jid cp = message.getCounterpart();
3687                if (cp == null || cp.isBareJid()) {
3688                    return;
3689                }
3690                final Jid tcp = message.getTrueCounterpart();
3691                final User userByRealJid =
3692                        tcp != null
3693                                ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
3694                                : null;
3695                final User user =
3696                        userByRealJid != null
3697                                ? userByRealJid
3698                                : conversation.getMucOptions().findUserByFullJid(cp);
3699                popupMenu.inflate(R.menu.muc_details_context);
3700                final Menu menu = popupMenu.getMenu();
3701                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
3702                        activity, menu, conversation, user);
3703                popupMenu.setOnMenuItemClickListener(
3704                        menuItem ->
3705                                MucDetailsContextMenuHelper.onContextItemSelected(
3706                                        menuItem, user, activity, fingerprint));
3707            } else {
3708                popupMenu.inflate(R.menu.one_on_one_context);
3709                popupMenu.setOnMenuItemClickListener(
3710                        item -> {
3711                            switch (item.getItemId()) {
3712                                case R.id.action_contact_details:
3713                                    activity.switchToContactDetails(
3714                                            message.getContact(), fingerprint);
3715                                    break;
3716                                case R.id.action_show_qr_code:
3717                                    activity.showQrCode(
3718                                            "xmpp:"
3719                                                    + message.getContact()
3720                                                            .getJid()
3721                                                            .asBareJid()
3722                                                            .toEscapedString());
3723                                    break;
3724                            }
3725                            return true;
3726                        });
3727            }
3728        } else {
3729            popupMenu.inflate(R.menu.account_context);
3730            final Menu menu = popupMenu.getMenu();
3731            menu.findItem(R.id.action_manage_accounts)
3732                    .setVisible(QuickConversationsService.isConversations());
3733            popupMenu.setOnMenuItemClickListener(
3734                    item -> {
3735                        final XmppActivity activity = this.activity;
3736                        if (activity == null) {
3737                            Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
3738                            return true;
3739                        }
3740                        switch (item.getItemId()) {
3741                            case R.id.action_show_qr_code:
3742                                activity.showQrCode(conversation.getAccount().getShareableUri());
3743                                break;
3744                            case R.id.action_account_details:
3745                                activity.switchToAccount(
3746                                        message.getConversation().getAccount(), fingerprint);
3747                                break;
3748                            case R.id.action_manage_accounts:
3749                                AccountUtils.launchManageAccounts(activity);
3750                                break;
3751                        }
3752                        return true;
3753                    });
3754        }
3755        popupMenu.show();
3756    }
3757
3758    @Override
3759    public void onContactPictureClicked(Message message) {
3760        setThread(message.getThread());
3761        conversation.setUserSelectedThread(true);
3762
3763        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
3764        if (received) {
3765            if (message.getConversation() instanceof Conversation
3766                    && message.getConversation().getMode() == Conversation.MODE_MULTI) {
3767                Jid tcp = message.getTrueCounterpart();
3768                Jid user = message.getCounterpart();
3769                if (user != null && !user.isBareJid()) {
3770                    final MucOptions mucOptions =
3771                            ((Conversation) message.getConversation()).getMucOptions();
3772                    if (mucOptions.participating()
3773                            || ((Conversation) message.getConversation()).getNextCounterpart()
3774                                    != null) {
3775                        if (!mucOptions.isUserInRoom(user)
3776                                && mucOptions.findUserByRealJid(
3777                                                tcp == null ? null : tcp.asBareJid())
3778                                        == null) {
3779                            Toast.makeText(
3780                                            getActivity(),
3781                                            activity.getString(
3782                                                    R.string.user_has_left_conference,
3783                                                    user.getResource()),
3784                                            Toast.LENGTH_SHORT)
3785                                    .show();
3786                        }
3787                        highlightInConference(user.getResource());
3788                    } else {
3789                        Toast.makeText(
3790                                        getActivity(),
3791                                        R.string.you_are_not_participating,
3792                                        Toast.LENGTH_SHORT)
3793                                .show();
3794                    }
3795                }
3796            }
3797        }
3798    }
3799
3800    private Activity requireActivity() {
3801        final Activity activity = getActivity();
3802        if (activity == null) {
3803            throw new IllegalStateException("Activity not attached");
3804        }
3805        return activity;
3806    }
3807}