ConversationFragment.java

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