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