ConversationFragment.java

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