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