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