ConversationFragment.java

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