ConversationFragment.java

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