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