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            conversation.setUserSelectedThread(false);
1342            setupReply(null);
1343        });
1344        binding.requestVoice.setOnClickListener((v) -> {
1345            activity.xmppConnectionService.requestVoice(conversation.getAccount(), conversation.getJid());
1346            binding.requestVoice.setVisibility(View.GONE);
1347        });
1348
1349        binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
1350        binding.messagesView.setOnScrollListener(mOnScrollListener);
1351        binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
1352        mediaPreviewAdapter = new MediaPreviewAdapter(this);
1353        binding.mediaPreview.setAdapter(mediaPreviewAdapter);
1354        messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1355        messageListAdapter.setOnContactPictureClicked(this);
1356        messageListAdapter.setOnContactPictureLongClicked(this);
1357        messageListAdapter.setOnInlineImageLongClicked(this);
1358        binding.messagesView.setAdapter(messageListAdapter);
1359
1360        registerForContextMenu(binding.messagesView);
1361
1362        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1363            this.binding.textinput.setCustomInsertionActionModeCallback(
1364                    new EditMessageActionModeCallback(this.binding.textinput));
1365        }
1366
1367        messageListAdapter.setOnMessageBoxClicked(message -> {
1368            if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1369            setThread(message.getThread());
1370            conversation.setUserSelectedThread(true);
1371        });
1372
1373        messageListAdapter.setOnMessageBoxSwiped(message -> {
1374            quoteMessage(message);
1375        });
1376
1377        binding.threadIdenticonLayout.setOnClickListener(v -> {
1378            boolean wasLocked = conversation.getLockThread();
1379            conversation.setLockThread(false);
1380            backPressedLeaveSingleThread.setEnabled(false);
1381            if (wasLocked) {
1382                conversation.setUserSelectedThread(false);
1383                refresh();
1384                updateThreadFromLastMessage();
1385            } else {
1386                newThread();
1387                conversation.setUserSelectedThread(true);
1388                newThreadTutorialToast("Switched to new thread");
1389            }
1390        });
1391
1392        binding.threadIdenticonLayout.setOnLongClickListener(v -> {
1393            boolean wasLocked = conversation.getLockThread();
1394            conversation.setLockThread(false);
1395            backPressedLeaveSingleThread.setEnabled(false);
1396            setThread(null);
1397            conversation.setUserSelectedThread(true);
1398            if (wasLocked) refresh();
1399            newThreadTutorialToast("Cleared thread");
1400            return true;
1401        });
1402
1403        final Pattern lastColonPattern = Pattern.compile("(?<!\\w):");
1404        emojiSearchBinding = DataBindingUtil.inflate(inflater, R.layout.emoji_search, null, false);
1405        emojiSearchBinding.emoji.setOnItemClickListener((parent, view, position, id) -> {
1406            EmojiSearch.EmojiSearchAdapter adapter = ((EmojiSearch.EmojiSearchAdapter) emojiSearchBinding.emoji.getAdapter());
1407            Editable toInsert = adapter.getItem(position).toInsert();
1408            toInsert.append(" ");
1409            Editable s = binding.textinput.getText();
1410
1411            Matcher lastColonMatcher = lastColonPattern.matcher(s);
1412            int lastColon = -1;
1413            while(lastColonMatcher.find()) lastColon = lastColonMatcher.end();
1414            if (lastColon > 0) s.replace(lastColon - 1, s.length(), toInsert, 0, toInsert.length());
1415        });
1416        setupEmojiSearch();
1417        int popupHeight = (int) displayMetrics.density * 200;
1418        emojiPopup = new PopupWindow(emojiSearchBinding.getRoot(), WindowManager.LayoutParams.MATCH_PARENT, Math.min(popupHeight, displayMetrics.heightPixels > 0 ? displayMetrics.heightPixels / 5 : popupHeight));
1419        Handler emojiDebounce = new Handler(Looper.getMainLooper());
1420        final Pattern notEmojiSearch = Pattern.compile("[^\\w\\(\\)\\+'\\-]");
1421        binding.textinput.addTextChangedListener(new TextWatcher() {
1422            @Override
1423            public void afterTextChanged(Editable s) {
1424                emojiDebounce.removeCallbacksAndMessages(null);
1425                emojiDebounce.postDelayed(() -> {
1426                    Matcher lastColonMatcher = lastColonPattern.matcher(s);
1427                    int lastColon = -1;
1428                    while(lastColonMatcher.find()) lastColon = lastColonMatcher.end();
1429                    if (lastColon < 0) {
1430                        emojiPopup.dismiss();
1431                        return;
1432                    }
1433                    final String q = s.toString().substring(lastColon);
1434                    if (notEmojiSearch.matcher(q).find()) {
1435                        emojiPopup.dismiss();
1436                    } else {
1437                        EmojiSearch.EmojiSearchAdapter adapter = ((EmojiSearch.EmojiSearchAdapter) emojiSearchBinding.emoji.getAdapter());
1438                        if (adapter != null) {
1439                            adapter.search(q);
1440                            emojiPopup.showAsDropDown(binding.textinput);
1441                        }
1442                    }
1443                }, 400L);
1444            }
1445
1446            @Override
1447            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
1448
1449            @Override
1450            public void onTextChanged(CharSequence s, int start, int count, int after) { }
1451        });
1452
1453        return binding.getRoot();
1454    }
1455
1456    protected void setupEmojiSearch() {
1457        if (emojiSearch == null && activity != null && activity.xmppConnectionService != null) {
1458            emojiSearch = activity.xmppConnectionService.emojiSearch();
1459        }
1460        if (emojiSearch == null || emojiSearchBinding == null) return;
1461
1462        emojiSearchBinding.emoji.setAdapter(emojiSearch.makeAdapter(activity));
1463    }
1464
1465    protected void newThreadTutorialToast(String s) {
1466        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1467        final int tutorialCount = p.getInt("thread_tutorial", 0);
1468        if (tutorialCount < 5) {
1469            Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
1470            p.edit().putInt("thread_tutorial", tutorialCount + 1).apply();
1471        }
1472    }
1473
1474    @Override
1475    public void onDestroyView() {
1476        super.onDestroyView();
1477        Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1478        messageListAdapter.setOnContactPictureClicked(null);
1479        messageListAdapter.setOnContactPictureLongClicked(null);
1480        messageListAdapter.setOnInlineImageLongClicked(null);
1481        binding.conversationViewPager.setAdapter(null);
1482        if (conversation != null) conversation.setupViewPager(null, null, false, null);
1483    }
1484
1485    private void quoteText(String text) {
1486        if (binding.textinput.isEnabled()) {
1487            binding.textinput.insertAsQuote(text);
1488            binding.textinput.requestFocus();
1489            InputMethodManager inputMethodManager =
1490                    (InputMethodManager)
1491                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1492            if (inputMethodManager != null) {
1493                inputMethodManager.showSoftInput(
1494                        binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1495            }
1496        }
1497    }
1498
1499    private void quoteMessage(Message message) {
1500        if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1501        setThread(message.getThread());
1502        conversation.setUserSelectedThread(true);
1503        if (!forkNullThread(message)) newThread();
1504        setupReply(message);
1505    }
1506
1507    private boolean forkNullThread(Message message) {
1508        if (message.getThread() != null || conversation.getMode() != Conversation.MODE_MULTI) return true;
1509        for (final Message m : conversation.findReplies(message.getServerMsgId())) {
1510            final Element thread = m.getThread();
1511            if (thread != null) {
1512                setThread(thread);
1513                return true;
1514            }
1515        }
1516
1517        return false;
1518    }
1519
1520    private void setupReply(Message message) {
1521        conversation.setReplyTo(message);
1522        if (message == null) {
1523            binding.contextPreview.setVisibility(View.GONE);
1524            return;
1525        }
1526
1527        SpannableStringBuilder body = message.getSpannableBody(null, null);
1528        if (message.isFileOrImage() || message.isOOb()) body.append(" 🖼️");
1529        messageListAdapter.handleTextQuotes(body, activity.isDarkTheme());
1530        binding.contextPreviewText.setText(body);
1531        binding.contextPreview.setVisibility(View.VISIBLE);
1532    }
1533
1534    private void setThread(Element thread) {
1535        this.conversation.setThread(thread);
1536        binding.threadIdenticon.setAlpha(0f);
1537        binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1538        if (thread != null) {
1539            final String threadId = thread.getContent();
1540            if (threadId != null) {
1541                binding.threadIdenticon.setAlpha(1f);
1542                binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1543                binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1544            }
1545        }
1546        updateSendButton();
1547    }
1548
1549    @Override
1550    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1551        // This should cancel any remaining click events that would otherwise trigger links
1552        v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1553        synchronized (this.messageList) {
1554            super.onCreateContextMenu(menu, v, menuInfo);
1555            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1556            this.selectedMessage = this.messageList.get(acmi.position);
1557            populateContextMenu(menu);
1558        }
1559    }
1560
1561    private void populateContextMenu(ContextMenu menu) {
1562        final Message m = this.selectedMessage;
1563        final Transferable t = m.getTransferable();
1564        Message relevantForCorrection = m;
1565        while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1566            relevantForCorrection = relevantForCorrection.next();
1567        }
1568        if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1569
1570            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1571                    || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1572                return;
1573            }
1574
1575            if (m.getStatus() == Message.STATUS_RECEIVED
1576                    && t != null
1577                    && (t.getStatus() == Transferable.STATUS_CANCELLED
1578                            || t.getStatus() == Transferable.STATUS_FAILED)) {
1579                return;
1580            }
1581
1582            final boolean deleted = m.isDeleted();
1583            final boolean encrypted =
1584                    m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1585                            || m.getEncryption() == Message.ENCRYPTION_PGP;
1586            final boolean receiving =
1587                    m.getStatus() == Message.STATUS_RECEIVED
1588                            && (t instanceof JingleFileTransferConnection
1589                                    || t instanceof HttpDownloadConnection);
1590            activity.getMenuInflater().inflate(R.menu.message_context, menu);
1591            MenuItem openWith = menu.findItem(R.id.open_with);
1592            MenuItem copyMessage = menu.findItem(R.id.copy_message);
1593            MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1594            MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1595            MenuItem correctMessage = menu.findItem(R.id.correct_message);
1596            MenuItem retractMessage = menu.findItem(R.id.retract_message);
1597            MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
1598            MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1599            MenuItem shareWith = menu.findItem(R.id.share_with);
1600            MenuItem sendAgain = menu.findItem(R.id.send_again);
1601            MenuItem copyUrl = menu.findItem(R.id.copy_url);
1602            MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
1603            MenuItem downloadFile = menu.findItem(R.id.download_file);
1604            MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1605            MenuItem blockMedia = menu.findItem(R.id.block_media);
1606            MenuItem deleteFile = menu.findItem(R.id.delete_file);
1607            MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1608            onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1609            final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1610            final boolean showError =
1611                    m.getStatus() == Message.STATUS_SEND_FAILED
1612                            && m.getErrorMessage() != null
1613                            && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1614            if (!encrypted && !m.getBody().equals("")) {
1615                copyMessage.setVisible(true);
1616            }
1617            quoteMessage.setVisible(!encrypted && !showError);
1618            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1619                retryDecryption.setVisible(true);
1620            }
1621            if (!showError
1622                    && relevantForCorrection.getType() == Message.TYPE_TEXT
1623                    && !m.isGeoUri()
1624                    && relevantForCorrection.isLastCorrectableMessage()
1625                    && m.getConversation() instanceof Conversation) {
1626                correctMessage.setVisible(true);
1627                if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1628            }
1629            if (relevantForCorrection.getReactions() != null) {
1630                correctMessage.setVisible(false);
1631                retractMessage.setVisible(true);
1632            }
1633            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")) {
1634                moderateMessage.setVisible(true);
1635            }
1636            if ((m.isFileOrImage() && !deleted && !receiving)
1637                    || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1638                            && !unInitiatedButKnownSize
1639                            && t == null) {
1640                shareWith.setVisible(true);
1641            }
1642            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1643                sendAgain.setVisible(true);
1644            }
1645            if (m.hasFileOnRemoteHost()
1646                    || m.isGeoUri()
1647                    || m.treatAsDownloadable()
1648                    || unInitiatedButKnownSize
1649                    || t instanceof HttpDownloadConnection) {
1650                copyUrl.setVisible(true);
1651            }
1652            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1653                downloadFile.setVisible(true);
1654                downloadFile.setTitle(
1655                        activity.getString(
1656                                R.string.download_x_file,
1657                                UIHelper.getFileDescriptionString(activity, m)));
1658            }
1659            final boolean waitingOfferedSending =
1660                    m.getStatus() == Message.STATUS_WAITING
1661                            || m.getStatus() == Message.STATUS_UNSEND
1662                            || m.getStatus() == Message.STATUS_OFFERED;
1663            final boolean cancelable =
1664                    (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1665            if (cancelable) {
1666                cancelTransmission.setVisible(true);
1667            }
1668            if (m.isFileOrImage() && !deleted && !cancelable) {
1669                final String path = m.getRelativeFilePath();
1670                if (path == null
1671                        || !path.startsWith("/")
1672                        || FileBackend.inConversationsDirectory(requireActivity(), path)) {
1673                    saveAsSticker.setVisible(true);
1674                    blockMedia.setVisible(true);
1675                    deleteFile.setVisible(true);
1676                    deleteFile.setTitle(
1677                            activity.getString(
1678                                    R.string.delete_x_file,
1679                                    UIHelper.getFileDescriptionString(activity, m)));
1680                }
1681            }
1682
1683            if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
1684                // We might be showing a thumbnail worth blocking
1685                blockMedia.setVisible(true);
1686            }
1687            if (showError) {
1688                showErrorMessage.setVisible(true);
1689            }
1690            final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1691            if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1692                    || (mime != null && mime.startsWith("audio/"))) {
1693                openWith.setVisible(true);
1694            }
1695        }
1696    }
1697
1698    @Override
1699    public boolean onContextItemSelected(MenuItem item) {
1700        switch (item.getItemId()) {
1701            case R.id.share_with:
1702                ShareUtil.share(activity, selectedMessage);
1703                return true;
1704            case R.id.correct_message:
1705                correctMessage(selectedMessage);
1706                return true;
1707            case R.id.retract_message:
1708                new AlertDialog.Builder(activity)
1709                    .setTitle(R.string.retract_message)
1710                    .setMessage("Do you really want to retract this message?")
1711                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1712                        Message message = selectedMessage;
1713                        while (message.mergeable(message.next())) {
1714                            message = message.next();
1715                        }
1716                        Element reactions = message.getReactions();
1717                        if (reactions != null) {
1718                            final Message previousReaction = conversation.findMessageReactingTo(reactions.getAttribute("id"), null);
1719                            if (previousReaction != null) reactions = previousReaction.getReactions();
1720                            for (Element el : reactions.getChildren()) {
1721                                if (message.getQuoteableBody().endsWith(el.getContent())) {
1722                                    reactions.removeChild(el);
1723                                }
1724                            }
1725                            message.setReactions(reactions);
1726                            if (previousReaction != null) {
1727                                previousReaction.setReactions(reactions);
1728                                activity.xmppConnectionService.updateMessage(previousReaction);
1729                            }
1730                        }
1731                        message.setBody(" ");
1732                        message.putEdited(message.getUuid(), message.getServerMsgId());
1733                        message.setServerMsgId(null);
1734                        message.setUuid(UUID.randomUUID().toString());
1735                        sendMessage(message);
1736                    })
1737                    .setNegativeButton(R.string.no, null).show();
1738                return true;
1739            case R.id.moderate_message:
1740                activity.quickEdit("Spam", (reason) -> {
1741                    activity.xmppConnectionService.moderateMessage(conversation.getAccount(), selectedMessage, reason);
1742                    return null;
1743                }, R.string.moderate_reason, false, false, true);
1744                return true;
1745            case R.id.copy_message:
1746                ShareUtil.copyToClipboard(activity, selectedMessage);
1747                return true;
1748            case R.id.quote_message:
1749                quoteMessage(selectedMessage);
1750                return true;
1751            case R.id.send_again:
1752                resendMessage(selectedMessage);
1753                return true;
1754            case R.id.copy_url:
1755                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1756                return true;
1757            case R.id.save_as_sticker:
1758                saveAsSticker(selectedMessage);
1759                return true;
1760            case R.id.download_file:
1761                startDownloadable(selectedMessage);
1762                return true;
1763            case R.id.cancel_transmission:
1764                cancelTransmission(selectedMessage);
1765                return true;
1766            case R.id.retry_decryption:
1767                retryDecryption(selectedMessage);
1768                return true;
1769            case R.id.block_media:
1770                new AlertDialog.Builder(activity)
1771                    .setTitle(R.string.block_media)
1772                    .setMessage("Do you really want to block this media in all messages?")
1773                    .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1774                        List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
1775                        if (thumbs != null && !thumbs.isEmpty()) {
1776                            for (Element thumb : thumbs) {
1777                                Uri uri = Uri.parse(thumb.getAttribute("uri"));
1778                                if (uri.getScheme().equals("cid")) {
1779                                    Cid cid = BobTransfer.cid(uri);
1780                                    if (cid == null) continue;
1781                                    DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
1782                                    activity.xmppConnectionService.blockMedia(f);
1783                                    activity.xmppConnectionService.evictPreview(f);
1784                                    f.delete();
1785                                }
1786                            }
1787                        }
1788                        File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
1789                        activity.xmppConnectionService.blockMedia(f);
1790                        activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
1791                        selectedMessage.setDeleted(true);
1792                        activity.xmppConnectionService.evictPreview(f);
1793                        activity.xmppConnectionService.updateMessage(selectedMessage, false);
1794                        activity.onConversationsListItemUpdated();
1795                        refresh();
1796                    })
1797                    .setNegativeButton(R.string.no, null).show();
1798                return true;
1799            case R.id.delete_file:
1800                deleteFile(selectedMessage);
1801                return true;
1802            case R.id.show_error_message:
1803                showErrorMessage(selectedMessage);
1804                return true;
1805            case R.id.open_with:
1806                openWith(selectedMessage);
1807                return true;
1808            case R.id.only_this_thread:
1809                conversation.setLockThread(true);
1810                backPressedLeaveSingleThread.setEnabled(true);
1811                setThread(selectedMessage.getThread());
1812                refresh();
1813                return true;
1814            default:
1815                return super.onContextItemSelected(item);
1816        }
1817    }
1818
1819    @Override
1820    public boolean onOptionsItemSelected(final MenuItem item) {
1821        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1822            return false;
1823        } else if (conversation == null) {
1824            return super.onOptionsItemSelected(item);
1825        }
1826        switch (item.getItemId()) {
1827            case R.id.encryption_choice_axolotl:
1828            case R.id.encryption_choice_pgp:
1829            case R.id.encryption_choice_none:
1830                handleEncryptionSelection(item);
1831                break;
1832            case R.id.attach_choose_picture:
1833            case R.id.attach_take_picture:
1834            case R.id.attach_record_video:
1835            case R.id.attach_choose_file:
1836            case R.id.attach_record_voice:
1837            case R.id.attach_location:
1838                handleAttachmentSelection(item);
1839                break;
1840            case R.id.action_search:
1841                startSearch();
1842                break;
1843            case R.id.action_archive:
1844                activity.xmppConnectionService.archiveConversation(conversation);
1845                break;
1846            case R.id.action_contact_details:
1847                activity.switchToContactDetails(conversation.getContact());
1848                break;
1849            case R.id.action_muc_details:
1850                ConferenceDetailsActivity.open(activity, conversation);
1851                break;
1852            case R.id.action_invite:
1853                startActivityForResult(
1854                        ChooseContactActivity.create(activity, conversation),
1855                        REQUEST_INVITE_TO_CONVERSATION);
1856                break;
1857            case R.id.action_clear_history:
1858                clearHistoryDialog(conversation);
1859                break;
1860            case R.id.action_mute:
1861                muteConversationDialog(conversation);
1862                break;
1863            case R.id.action_unmute:
1864                unMuteConversation(conversation);
1865                break;
1866            case R.id.action_block:
1867            case R.id.action_unblock:
1868                final Activity activity = getActivity();
1869                if (activity instanceof XmppActivity) {
1870                    BlockContactDialog.show((XmppActivity) activity, conversation);
1871                }
1872                break;
1873            case R.id.action_audio_call:
1874                checkPermissionAndTriggerAudioCall();
1875                break;
1876            case R.id.action_video_call:
1877                checkPermissionAndTriggerVideoCall();
1878                break;
1879            case R.id.action_ongoing_call:
1880                returnToOngoingCall();
1881                break;
1882            case R.id.action_toggle_pinned:
1883                togglePinned();
1884                break;
1885            case R.id.action_add_shortcut:
1886                addShortcut();
1887                break;
1888            case R.id.action_refresh_feature_discovery:
1889                refreshFeatureDiscovery();
1890                break;
1891            default:
1892                break;
1893        }
1894        return super.onOptionsItemSelected(item);
1895    }
1896
1897    public boolean onBackPressed() {
1898        boolean wasLocked = conversation.getLockThread();
1899        conversation.setLockThread(false);
1900        backPressedLeaveSingleThread.setEnabled(false);
1901        if (wasLocked) {
1902            conversation.setUserSelectedThread(false);
1903            refresh();
1904            updateThreadFromLastMessage();
1905            return true;
1906        }
1907        return false;
1908    }
1909
1910    private void startSearch() {
1911        final Intent intent = new Intent(getActivity(), SearchActivity.class);
1912        intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
1913        startActivity(intent);
1914    }
1915
1916    private void returnToOngoingCall() {
1917        final Optional<OngoingRtpSession> ongoingRtpSession =
1918                activity.xmppConnectionService
1919                        .getJingleConnectionManager()
1920                        .getOngoingRtpConnection(conversation.getContact());
1921        if (ongoingRtpSession.isPresent()) {
1922            final OngoingRtpSession id = ongoingRtpSession.get();
1923            final Intent intent = new Intent(activity, RtpSessionActivity.class);
1924            intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.getAccount().getJid().asBareJid().toEscapedString());
1925            intent.putExtra(
1926                    RtpSessionActivity.EXTRA_ACCOUNT,
1927                    id.getAccount().getJid().asBareJid().toEscapedString());
1928            intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
1929            if (id instanceof AbstractJingleConnection.Id) {
1930                intent.setAction(Intent.ACTION_VIEW);
1931                intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
1932            } else if (id instanceof JingleConnectionManager.RtpSessionProposal) {
1933                if (((JingleConnectionManager.RtpSessionProposal) id).media.contains(Media.VIDEO)) {
1934                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1935                } else {
1936                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1937                }
1938            }
1939            activity.startActivity(intent);
1940        }
1941    }
1942
1943    private void refreshFeatureDiscovery() {
1944        Set<Map.Entry<String, Presence>> presences = conversation.getContact().getPresences().getPresencesMap().entrySet();
1945        if (presences.isEmpty()) {
1946            presences = new HashSet<>();
1947            presences.add(new AbstractMap.SimpleEntry("", null));
1948        }
1949        for (Map.Entry<String, Presence> entry : presences) {
1950            Jid jid = conversation.getContact().getJid();
1951            if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
1952            activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
1953                if (activity == null) return;
1954                activity.runOnUiThread(() -> {
1955                    refresh();
1956                    refreshCommands(true);
1957                });
1958            });
1959        }
1960    }
1961
1962    private void addShortcut() {
1963        ShortcutInfoCompat info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getContact());
1964        ShortcutManagerCompat.requestPinShortcut(activity, info, null);
1965    }
1966
1967    private void togglePinned() {
1968        final boolean pinned =
1969                conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
1970        conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
1971        activity.xmppConnectionService.updateConversation(conversation);
1972        activity.invalidateOptionsMenu();
1973    }
1974
1975    private void checkPermissionAndTriggerAudioCall() {
1976        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1977            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1978            return;
1979        }
1980        final List<String> permissions;
1981        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1982            permissions =
1983                    Arrays.asList(
1984                            Manifest.permission.RECORD_AUDIO,
1985                            Manifest.permission.BLUETOOTH_CONNECT);
1986        } else {
1987            permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
1988        }
1989        if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
1990            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1991        }
1992    }
1993
1994    private void checkPermissionAndTriggerVideoCall() {
1995        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1996            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1997            return;
1998        }
1999        final List<String> permissions;
2000        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2001            permissions =
2002                    Arrays.asList(
2003                            Manifest.permission.RECORD_AUDIO,
2004                            Manifest.permission.CAMERA,
2005                            Manifest.permission.BLUETOOTH_CONNECT);
2006        } else {
2007            permissions =
2008                    Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2009        }
2010        if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2011            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2012        }
2013    }
2014
2015    private void triggerRtpSession(final String action) {
2016        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy() != null) {
2017            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2018                    .show();
2019            return;
2020        }
2021        final Contact contact = conversation.getContact();
2022        if (contact.getPresences().anySupport(Namespace.JINGLE_MESSAGE)) {
2023            triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2024        } else {
2025            final RtpCapability.Capability capability;
2026            if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2027                capability = RtpCapability.Capability.VIDEO;
2028            } else {
2029                capability = RtpCapability.Capability.AUDIO;
2030            }
2031            PresenceSelector.selectFullJidForDirectRtpConnection(
2032                    activity,
2033                    contact,
2034                    capability,
2035                    fullJid -> {
2036                        triggerRtpSession(contact.getAccount(), fullJid, action);
2037                    });
2038        }
2039    }
2040
2041    private void triggerRtpSession(final Account account, final Jid with, final String action) {
2042        final Intent intent = new Intent(activity, RtpSessionActivity.class);
2043        intent.setAction(action);
2044        intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, account.getJid().toEscapedString());
2045        intent.putExtra(RtpSessionActivity.EXTRA_WITH, with.toEscapedString());
2046        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2047        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
2048        startActivity(intent);
2049    }
2050
2051    private void handleAttachmentSelection(MenuItem item) {
2052        switch (item.getItemId()) {
2053            case R.id.attach_choose_picture:
2054                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2055                break;
2056            case R.id.attach_take_picture:
2057                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2058                break;
2059            case R.id.attach_record_video:
2060                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2061                break;
2062            case R.id.attach_choose_file:
2063                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2064                break;
2065            case R.id.attach_record_voice:
2066                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2067                break;
2068            case R.id.attach_location:
2069                attachFile(ATTACHMENT_CHOICE_LOCATION);
2070                break;
2071        }
2072    }
2073
2074    private void handleEncryptionSelection(MenuItem item) {
2075        if (conversation == null) {
2076            return;
2077        }
2078        final boolean updated;
2079        switch (item.getItemId()) {
2080            case R.id.encryption_choice_none:
2081                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2082                item.setChecked(true);
2083                break;
2084            case R.id.encryption_choice_pgp:
2085                if (activity.hasPgp()) {
2086                    if (conversation.getAccount().getPgpSignature() != null) {
2087                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2088                        item.setChecked(true);
2089                    } else {
2090                        updated = false;
2091                        activity.announcePgp(
2092                                conversation.getAccount(),
2093                                conversation,
2094                                null,
2095                                activity.onOpenPGPKeyPublished);
2096                    }
2097                } else {
2098                    activity.showInstallPgpDialog();
2099                    updated = false;
2100                }
2101                break;
2102            case R.id.encryption_choice_axolotl:
2103                Log.d(
2104                        Config.LOGTAG,
2105                        AxolotlService.getLogprefix(conversation.getAccount())
2106                                + "Enabled axolotl for Contact "
2107                                + conversation.getContact().getJid());
2108                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2109                item.setChecked(true);
2110                break;
2111            default:
2112                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2113                break;
2114        }
2115        if (updated) {
2116            activity.xmppConnectionService.updateConversation(conversation);
2117        }
2118        updateChatMsgHint();
2119        getActivity().invalidateOptionsMenu();
2120        activity.refreshUi();
2121    }
2122
2123    public void attachFile(final int attachmentChoice) {
2124        attachFile(attachmentChoice, true);
2125    }
2126
2127    public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2128        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2129            if (!hasPermissions(
2130                    attachmentChoice,
2131                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2132                    Manifest.permission.RECORD_AUDIO)) {
2133                return;
2134            }
2135        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2136                || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
2137            if (!hasPermissions(
2138                    attachmentChoice,
2139                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
2140                    Manifest.permission.CAMERA)) {
2141                return;
2142            }
2143        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2144            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2145                return;
2146            }
2147        }
2148        if (updateRecentlyUsed) {
2149            storeRecentlyUsedQuickAction(attachmentChoice);
2150        }
2151        final int encryption = conversation.getNextEncryption();
2152        final int mode = conversation.getMode();
2153        if (encryption == Message.ENCRYPTION_PGP) {
2154            if (activity.hasPgp()) {
2155                if (mode == Conversation.MODE_SINGLE
2156                        && conversation.getContact().getPgpKeyId() != 0) {
2157                    activity.xmppConnectionService
2158                            .getPgpEngine()
2159                            .hasKey(
2160                                    conversation.getContact(),
2161                                    new UiCallback<Contact>() {
2162
2163                                        @Override
2164                                        public void userInputRequired(
2165                                                PendingIntent pi, Contact contact) {
2166                                            startPendingIntent(pi, attachmentChoice);
2167                                        }
2168
2169                                        @Override
2170                                        public void success(Contact contact) {
2171                                            invokeAttachFileIntent(attachmentChoice);
2172                                        }
2173
2174                                        @Override
2175                                        public void error(int error, Contact contact) {
2176                                            activity.replaceToast(getString(error));
2177                                        }
2178                                    });
2179                } else if (mode == Conversation.MODE_MULTI
2180                        && conversation.getMucOptions().pgpKeysInUse()) {
2181                    if (!conversation.getMucOptions().everybodyHasKeys()) {
2182                        Toast warning =
2183                                Toast.makeText(
2184                                        getActivity(),
2185                                        R.string.missing_public_keys,
2186                                        Toast.LENGTH_LONG);
2187                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2188                        warning.show();
2189                    }
2190                    invokeAttachFileIntent(attachmentChoice);
2191                } else {
2192                    showNoPGPKeyDialog(
2193                            false,
2194                            (dialog, which) -> {
2195                                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2196                                activity.xmppConnectionService.updateConversation(conversation);
2197                                invokeAttachFileIntent(attachmentChoice);
2198                            });
2199                }
2200            } else {
2201                activity.showInstallPgpDialog();
2202            }
2203        } else {
2204            invokeAttachFileIntent(attachmentChoice);
2205        }
2206    }
2207
2208    private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2209        try {
2210            activity.getPreferences()
2211                    .edit()
2212                    .putString(
2213                            RECENTLY_USED_QUICK_ACTION,
2214                            SendButtonAction.of(attachmentChoice).toString())
2215                    .apply();
2216        } catch (IllegalArgumentException e) {
2217            // just do not save
2218        }
2219    }
2220
2221    @Override
2222    public void onRequestPermissionsResult(
2223            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2224        final PermissionUtils.PermissionResult permissionResult =
2225                PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2226        if (grantResults.length > 0) {
2227            if (allGranted(permissionResult.grantResults)) {
2228                switch (requestCode) {
2229                    case REQUEST_START_DOWNLOAD:
2230                        if (this.mPendingDownloadableMessage != null) {
2231                            startDownloadable(this.mPendingDownloadableMessage);
2232                        }
2233                        break;
2234                    case REQUEST_ADD_EDITOR_CONTENT:
2235                        if (this.mPendingEditorContent != null) {
2236                            attachEditorContentToConversation(this.mPendingEditorContent);
2237                        }
2238                        break;
2239                    case REQUEST_COMMIT_ATTACHMENTS:
2240                        commitAttachments();
2241                        break;
2242                    case REQUEST_START_AUDIO_CALL:
2243                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2244                        break;
2245                    case REQUEST_START_VIDEO_CALL:
2246                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2247                        break;
2248                    default:
2249                        attachFile(requestCode);
2250                        break;
2251                }
2252            } else {
2253                @StringRes int res;
2254                String firstDenied =
2255                        getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2256                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2257                    res = R.string.no_microphone_permission;
2258                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2259                    res = R.string.no_camera_permission;
2260                } else {
2261                    res = R.string.no_storage_permission;
2262                }
2263                Toast.makeText(
2264                                getActivity(),
2265                                getString(res, getString(R.string.app_name)),
2266                                Toast.LENGTH_SHORT)
2267                        .show();
2268            }
2269        }
2270        if (writeGranted(grantResults, permissions)) {
2271            if (activity != null && activity.xmppConnectionService != null) {
2272                activity.xmppConnectionService.getDrawableCache().evictAll();
2273                activity.xmppConnectionService.restartFileObserver();
2274            }
2275            refresh();
2276        }
2277    }
2278
2279    public void startDownloadable(Message message) {
2280        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2281            this.mPendingDownloadableMessage = message;
2282            return;
2283        }
2284        Transferable transferable = message.getTransferable();
2285        if (transferable != null) {
2286            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2287                createNewConnection(message);
2288                return;
2289            }
2290            if (!transferable.start()) {
2291                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2292                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2293                        .show();
2294            }
2295        } else if (message.treatAsDownloadable()
2296                || message.hasFileOnRemoteHost()
2297                || MessageUtils.unInitiatedButKnownSize(message)) {
2298            createNewConnection(message);
2299        } else {
2300            Log.d(
2301                    Config.LOGTAG,
2302                    message.getConversation().getAccount() + ": unable to start downloadable");
2303        }
2304    }
2305
2306    private void createNewConnection(final Message message) {
2307        if (!activity.xmppConnectionService.hasInternetConnection()) {
2308            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2309                    .show();
2310            return;
2311        }
2312        if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2313            try {
2314                BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2315                message.setTransferable(transfer);
2316                transfer.start();
2317            } catch (URISyntaxException e) {
2318                Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2319            }
2320        } else {
2321            activity.xmppConnectionService
2322                    .getHttpConnectionManager()
2323                    .createNewDownloadConnection(message, true);
2324        }
2325    }
2326
2327    @SuppressLint("InflateParams")
2328    protected void clearHistoryDialog(final Conversation conversation) {
2329        final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2330        builder.setTitle(getString(R.string.clear_conversation_history));
2331        final View dialogView =
2332                requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2333        final CheckBox endConversationCheckBox =
2334                dialogView.findViewById(R.id.end_conversation_checkbox);
2335        builder.setView(dialogView);
2336        builder.setNegativeButton(getString(R.string.cancel), null);
2337        builder.setPositiveButton(
2338                getString(R.string.confirm),
2339                (dialog, which) -> {
2340                    this.activity.xmppConnectionService.clearConversationHistory(conversation);
2341                    if (endConversationCheckBox.isChecked()) {
2342                        this.activity.xmppConnectionService.archiveConversation(conversation);
2343                        this.activity.onConversationArchived(conversation);
2344                    } else {
2345                        activity.onConversationsListItemUpdated();
2346                        refresh();
2347                    }
2348                });
2349        builder.create().show();
2350    }
2351
2352    protected void muteConversationDialog(final Conversation conversation) {
2353        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
2354        builder.setTitle(R.string.disable_notifications);
2355        final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2356        final CharSequence[] labels = new CharSequence[durations.length];
2357        for (int i = 0; i < durations.length; ++i) {
2358            if (durations[i] == -1) {
2359                labels[i] = activity.getString(R.string.until_further_notice);
2360            } else {
2361                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2362            }
2363        }
2364        builder.setItems(
2365                labels,
2366                (dialog, which) -> {
2367                    final long till;
2368                    if (durations[which] == -1) {
2369                        till = Long.MAX_VALUE;
2370                    } else {
2371                        till = System.currentTimeMillis() + (durations[which] * 1000L);
2372                    }
2373                    conversation.setMutedTill(till);
2374                    activity.xmppConnectionService.updateConversation(conversation);
2375                    activity.onConversationsListItemUpdated();
2376                    refresh();
2377                    activity.invalidateOptionsMenu();
2378                });
2379        builder.create().show();
2380    }
2381
2382    private boolean hasPermissions(int requestCode, List<String> permissions) {
2383        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
2384            final List<String> missingPermissions = new ArrayList<>();
2385            for (String permission : permissions) {
2386                if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU || Config.ONLY_INTERNAL_STORAGE) && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2387                    continue;
2388                }
2389                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2390                    missingPermissions.add(permission);
2391                }
2392            }
2393            if (missingPermissions.size() == 0) {
2394                return true;
2395            } else {
2396                requestPermissions(
2397                        missingPermissions.toArray(new String[0]),
2398                        requestCode);
2399                return false;
2400            }
2401        } else {
2402            return true;
2403        }
2404    }
2405
2406    private boolean hasPermissions(int requestCode, String... permissions) {
2407        return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2408    }
2409
2410    public void unMuteConversation(final Conversation conversation) {
2411        conversation.setMutedTill(0);
2412        this.activity.xmppConnectionService.updateConversation(conversation);
2413        this.activity.onConversationsListItemUpdated();
2414        refresh();
2415        this.activity.invalidateOptionsMenu();
2416    }
2417
2418    protected void invokeAttachFileIntent(final int attachmentChoice) {
2419        Intent intent = new Intent();
2420        boolean chooser = false;
2421        switch (attachmentChoice) {
2422            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2423                intent.setAction(Intent.ACTION_GET_CONTENT);
2424                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2425                intent.setType("image/*");
2426                chooser = true;
2427                break;
2428            case ATTACHMENT_CHOICE_RECORD_VIDEO:
2429                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2430                break;
2431            case ATTACHMENT_CHOICE_TAKE_PHOTO:
2432                final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2433                pendingTakePhotoUri.push(uri);
2434                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2435                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2436                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2437                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2438                break;
2439            case ATTACHMENT_CHOICE_CHOOSE_FILE:
2440                chooser = true;
2441                intent.setType("*/*");
2442                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2443                intent.addCategory(Intent.CATEGORY_OPENABLE);
2444                intent.setAction(Intent.ACTION_GET_CONTENT);
2445                break;
2446            case ATTACHMENT_CHOICE_RECORD_VOICE:
2447                intent = new Intent(getActivity(), RecordingActivity.class);
2448                break;
2449            case ATTACHMENT_CHOICE_LOCATION:
2450                intent = GeoHelper.getFetchIntent(activity);
2451                break;
2452        }
2453        final Context context = getActivity();
2454        if (context == null) {
2455            return;
2456        }
2457        try {
2458            if (chooser) {
2459                startActivityForResult(
2460                        Intent.createChooser(intent, getString(R.string.perform_action_with)),
2461                        attachmentChoice);
2462            } else {
2463                startActivityForResult(intent, attachmentChoice);
2464            }
2465        } catch (final ActivityNotFoundException e) {
2466            Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2467        }
2468    }
2469
2470    @Override
2471    public void onResume() {
2472        super.onResume();
2473        binding.messagesView.post(this::fireReadEvent);
2474    }
2475
2476    private void fireReadEvent() {
2477        if (activity != null && this.conversation != null) {
2478            String uuid = getLastVisibleMessageUuid();
2479            if (uuid != null) {
2480                activity.onConversationRead(this.conversation, uuid);
2481            }
2482        }
2483    }
2484
2485    private void newSubThread() {
2486        Element oldThread = conversation.getThread();
2487        Element thread = new Element("thread", "jabber:client");
2488        thread.setContent(UUID.randomUUID().toString());
2489        if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2490        setThread(thread);
2491    }
2492
2493    private void newThread() {
2494        Element thread = new Element("thread", "jabber:client");
2495        thread.setContent(UUID.randomUUID().toString());
2496        setThread(thread);
2497    }
2498
2499    private void updateThreadFromLastMessage() {
2500        if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2501            Message message = getLastVisibleMessage();
2502            if (message == null) {
2503                newThread();
2504            } else {
2505                setThread(message.getThread());
2506            }
2507        }
2508    }
2509
2510    private String getLastVisibleMessageUuid() {
2511        Message message =  getLastVisibleMessage();
2512        return message == null ? null : message.getUuid();
2513    }
2514
2515    private Message getLastVisibleMessage() {
2516        if (binding == null) {
2517            return null;
2518        }
2519        synchronized (this.messageList) {
2520            int pos = binding.messagesView.getLastVisiblePosition();
2521            if (pos >= 0) {
2522                Message message = null;
2523                for (int i = pos; i >= 0; --i) {
2524                    try {
2525                        message = (Message) binding.messagesView.getItemAtPosition(i);
2526                    } catch (IndexOutOfBoundsException e) {
2527                        // should not happen if we synchronize properly. however if that fails we
2528                        // just gonna try item -1
2529                        continue;
2530                    }
2531                    if (message.getType() != Message.TYPE_STATUS) {
2532                        break;
2533                    }
2534                }
2535                if (message != null) {
2536                    while (message.next() != null && message.next().wasMergedIntoPrevious()) {
2537                        message = message.next();
2538                    }
2539                    return message;
2540                }
2541            }
2542        }
2543        return null;
2544    }
2545
2546    private void openWith(final Message message) {
2547        if (message.isGeoUri()) {
2548            GeoHelper.view(getActivity(), message);
2549        } else {
2550            final DownloadableFile file =
2551                    activity.xmppConnectionService.getFileBackend().getFile(message);
2552            ViewUtil.view(activity, file);
2553        }
2554    }
2555
2556    private void showErrorMessage(final Message message) {
2557        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2558        builder.setTitle(R.string.error_message);
2559        final String errorMessage = message.getErrorMessage();
2560        final String[] errorMessageParts =
2561                errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2562        final String displayError;
2563        if (errorMessageParts.length == 2) {
2564            displayError = errorMessageParts[1];
2565        } else {
2566            displayError = errorMessage;
2567        }
2568        builder.setMessage(displayError);
2569        builder.setNegativeButton(
2570                R.string.copy_to_clipboard,
2571                (dialog, which) -> {
2572                    activity.copyTextToClipboard(displayError, R.string.error_message);
2573                    Toast.makeText(
2574                                    activity,
2575                                    R.string.error_message_copied_to_clipboard,
2576                                    Toast.LENGTH_SHORT)
2577                            .show();
2578                });
2579        builder.setPositiveButton(R.string.confirm, null);
2580        builder.create().show();
2581    }
2582
2583    public boolean onInlineImageLongClicked(Cid cid) {
2584        DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2585        if (f == null) return false;
2586
2587        saveAsSticker(f, null);
2588        return true;
2589    }
2590
2591    private void saveAsSticker(final Message m) {
2592        String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
2593        existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
2594        saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
2595    }
2596
2597    private void saveAsSticker(final File file, final String name) {
2598        savingAsSticker = file;
2599
2600        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
2601        intent.addCategory(Intent.CATEGORY_OPENABLE);
2602        intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file)));
2603        intent.putExtra(Intent.EXTRA_TITLE, name);
2604
2605        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2606        final String dir = p.getString("sticker_directory", "Stickers");
2607        if (dir.startsWith("content://")) {
2608            intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
2609        } else {
2610            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
2611            Uri uri;
2612            if (Build.VERSION.SDK_INT >= 29) {
2613                Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
2614                uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
2615                uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
2616            } else {
2617                uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
2618            }
2619            intent.putExtra("android.provider.extra.INITIAL_URI", uri);
2620            intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
2621        }
2622
2623        Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
2624        startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
2625    }
2626
2627    private void deleteFile(final Message message) {
2628        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2629        builder.setNegativeButton(R.string.cancel, null);
2630        builder.setTitle(R.string.delete_file_dialog);
2631        builder.setMessage(R.string.delete_file_dialog_msg);
2632        builder.setPositiveButton(
2633                R.string.confirm,
2634                (dialog, which) -> {
2635                    List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2636                    if (thumbs != null && !thumbs.isEmpty()) {
2637                        for (Element thumb : thumbs) {
2638                            Uri uri = Uri.parse(thumb.getAttribute("uri"));
2639                            if (uri.getScheme().equals("cid")) {
2640                                Cid cid = BobTransfer.cid(uri);
2641                                if (cid == null) continue;
2642                                DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2643                                activity.xmppConnectionService.evictPreview(f);
2644                                f.delete();
2645                            }
2646                        }
2647                    }
2648                    if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2649                        message.setDeleted(true);
2650                        activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
2651                        activity.xmppConnectionService.updateMessage(message, false);
2652                        activity.onConversationsListItemUpdated();
2653                        refresh();
2654                    }
2655                });
2656        builder.create().show();
2657    }
2658
2659    private void resendMessage(final Message message) {
2660        if (message.isFileOrImage()) {
2661            if (!(message.getConversation() instanceof Conversation)) {
2662                return;
2663            }
2664            final Conversation conversation = (Conversation) message.getConversation();
2665            final DownloadableFile file =
2666                    activity.xmppConnectionService.getFileBackend().getFile(message);
2667            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2668                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2669                if (!message.hasFileOnRemoteHost()
2670                        && xmppConnection != null
2671                        && conversation.getMode() == Conversational.MODE_SINGLE
2672                        && !xmppConnection
2673                                .getFeatures()
2674                                .httpUpload(message.getFileParams().getSize())) {
2675                    activity.selectPresence(
2676                            conversation,
2677                            () -> {
2678                                message.setCounterpart(conversation.getNextCounterpart());
2679                                activity.xmppConnectionService.resendFailedMessages(message);
2680                                new Handler()
2681                                        .post(
2682                                                () -> {
2683                                                    int size = messageList.size();
2684                                                    this.binding.messagesView.setSelection(
2685                                                            size - 1);
2686                                                });
2687                            });
2688                    return;
2689                }
2690            } else if (!Compatibility.hasStoragePermission(getActivity())) {
2691                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2692                return;
2693            } else {
2694                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2695                message.setDeleted(true);
2696                activity.xmppConnectionService.updateMessage(message, false);
2697                activity.onConversationsListItemUpdated();
2698                refresh();
2699                return;
2700            }
2701        }
2702        activity.xmppConnectionService.resendFailedMessages(message);
2703        new Handler()
2704                .post(
2705                        () -> {
2706                            int size = messageList.size();
2707                            this.binding.messagesView.setSelection(size - 1);
2708                        });
2709    }
2710
2711    private void cancelTransmission(Message message) {
2712        Transferable transferable = message.getTransferable();
2713        if (transferable != null) {
2714            transferable.cancel();
2715        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2716            activity.xmppConnectionService.markMessage(
2717                    message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2718        }
2719    }
2720
2721    private void retryDecryption(Message message) {
2722        message.setEncryption(Message.ENCRYPTION_PGP);
2723        activity.onConversationsListItemUpdated();
2724        refresh();
2725        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2726    }
2727
2728    public void privateMessageWith(final Jid counterpart) {
2729        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2730            activity.xmppConnectionService.sendChatState(conversation);
2731        }
2732        this.binding.textinput.setText("");
2733        this.conversation.setNextCounterpart(counterpart);
2734        updateChatMsgHint();
2735        updateSendButton();
2736        updateEditablity();
2737    }
2738
2739    private void correctMessage(Message message) {
2740        while (message.mergeable(message.next())) {
2741            message = message.next();
2742        }
2743        setThread(message.getThread());
2744        conversation.setUserSelectedThread(true);
2745        this.conversation.setCorrectingMessage(message);
2746        final Editable editable = binding.textinput.getText();
2747        this.conversation.setDraftMessage(editable.toString());
2748        this.binding.textinput.setText("");
2749        this.binding.textinput.append(message.getBody());
2750    }
2751
2752    private void highlightInConference(String nick) {
2753        final Editable editable = this.binding.textinput.getText();
2754        String oldString = editable.toString().trim();
2755        final int pos = this.binding.textinput.getSelectionStart();
2756        if (oldString.isEmpty() || pos == 0) {
2757            editable.insert(0, nick + ": ");
2758        } else {
2759            final char before = editable.charAt(pos - 1);
2760            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2761            if (before == '\n') {
2762                editable.insert(pos, nick + ": ");
2763            } else {
2764                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2765                    if (NickValidityChecker.check(
2766                            conversation,
2767                            Arrays.asList(
2768                                    editable.subSequence(0, pos - 2).toString().split(", ")))) {
2769                        editable.insert(pos - 2, ", " + nick);
2770                        return;
2771                    }
2772                }
2773                editable.insert(
2774                        pos,
2775                        (Character.isWhitespace(before) ? "" : " ")
2776                                + nick
2777                                + (Character.isWhitespace(after) ? "" : " "));
2778                if (Character.isWhitespace(after)) {
2779                    this.binding.textinput.setSelection(
2780                            this.binding.textinput.getSelectionStart() + 1);
2781                }
2782            }
2783        }
2784    }
2785
2786    @Override
2787    public void startActivityForResult(Intent intent, int requestCode) {
2788        final Activity activity = getActivity();
2789        if (activity instanceof ConversationsActivity) {
2790            ((ConversationsActivity) activity).clearPendingViewIntent();
2791        }
2792        super.startActivityForResult(intent, requestCode);
2793    }
2794
2795    @Override
2796    public void onSaveInstanceState(@NotNull Bundle outState) {
2797        super.onSaveInstanceState(outState);
2798        if (conversation != null) {
2799            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2800            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2801            final Uri uri = pendingTakePhotoUri.peek();
2802            if (uri != null) {
2803                outState.putString(STATE_PHOTO_URI, uri.toString());
2804            }
2805            final ScrollState scrollState = getScrollPosition();
2806            if (scrollState != null) {
2807                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2808            }
2809            final ArrayList<Attachment> attachments =
2810                    mediaPreviewAdapter == null
2811                            ? new ArrayList<>()
2812                            : mediaPreviewAdapter.getAttachments();
2813            if (attachments.size() > 0) {
2814                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2815            }
2816        }
2817    }
2818
2819    @Override
2820    public void onActivityCreated(Bundle savedInstanceState) {
2821        super.onActivityCreated(savedInstanceState);
2822        if (savedInstanceState == null) {
2823            return;
2824        }
2825        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2826        ArrayList<Attachment> attachments =
2827                savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2828        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2829        if (uuid != null) {
2830            QuickLoader.set(uuid);
2831            this.pendingConversationsUuid.push(uuid);
2832            if (attachments != null && attachments.size() > 0) {
2833                this.pendingMediaPreviews.push(attachments);
2834            }
2835            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2836            if (takePhotoUri != null) {
2837                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2838            }
2839            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2840        }
2841    }
2842
2843    @Override
2844    public void onStart() {
2845        super.onStart();
2846        if (this.reInitRequiredOnStart && this.conversation != null) {
2847            final Bundle extras = pendingExtras.pop();
2848            reInit(this.conversation, extras != null);
2849            if (extras != null) {
2850                processExtras(extras);
2851            }
2852        } else if (conversation == null
2853                && activity != null
2854                && activity.xmppConnectionService != null) {
2855            final String uuid = pendingConversationsUuid.pop();
2856            Log.d(
2857                    Config.LOGTAG,
2858                    "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
2859                            + uuid);
2860            if (uuid != null) {
2861                findAndReInitByUuidOrArchive(uuid);
2862            }
2863        }
2864    }
2865
2866    @Override
2867    public void onStop() {
2868        super.onStop();
2869        final Activity activity = getActivity();
2870        messageListAdapter.unregisterListenerInAudioPlayer();
2871        if (activity == null || !activity.isChangingConfigurations()) {
2872            hideSoftKeyboard(activity);
2873            messageListAdapter.stopAudioPlayer();
2874        }
2875        if (this.conversation != null) {
2876            final String msg = this.binding.textinput.getText().toString();
2877            storeNextMessage(msg);
2878            updateChatState(this.conversation, msg);
2879            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2880        }
2881        this.reInitRequiredOnStart = true;
2882        if (emojiPopup != null) emojiPopup.dismiss();
2883    }
2884
2885    private void updateChatState(final Conversation conversation, final String msg) {
2886        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2887        Account.State status = conversation.getAccount().getStatus();
2888        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2889            activity.xmppConnectionService.sendChatState(conversation);
2890        }
2891    }
2892
2893    private void saveMessageDraftStopAudioPlayer() {
2894        final Conversation previousConversation = this.conversation;
2895        if (this.activity == null || this.binding == null || previousConversation == null) {
2896            return;
2897        }
2898        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2899        final String msg = this.binding.textinput.getText().toString();
2900        storeNextMessage(msg);
2901        updateChatState(this.conversation, msg);
2902        messageListAdapter.stopAudioPlayer();
2903        mediaPreviewAdapter.clearPreviews();
2904        toggleInputMethod();
2905    }
2906
2907    public void reInit(final Conversation conversation, final Bundle extras) {
2908        QuickLoader.set(conversation.getUuid());
2909        final boolean changedConversation = this.conversation != conversation;
2910        if (changedConversation) {
2911            this.saveMessageDraftStopAudioPlayer();
2912        }
2913        this.clearPending();
2914        if (this.reInit(conversation, extras != null)) {
2915            if (extras != null) {
2916                processExtras(extras);
2917            }
2918            this.reInitRequiredOnStart = false;
2919        } else {
2920            this.reInitRequiredOnStart = true;
2921            pendingExtras.push(extras);
2922        }
2923        resetUnreadMessagesCount();
2924    }
2925
2926    private void reInit(Conversation conversation) {
2927        reInit(conversation, false);
2928    }
2929
2930    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2931        if (conversation == null) {
2932            return false;
2933        }
2934        final Conversation originalConversation = this.conversation;
2935        this.conversation = conversation;
2936        // once we set the conversation all is good and it will automatically do the right thing in
2937        // onStart()
2938        if (this.activity == null || this.binding == null) {
2939            return false;
2940        }
2941
2942        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2943            activity.onConversationArchived(this.conversation);
2944            return false;
2945        }
2946
2947        setThread(conversation.getThread());
2948        setupReply(conversation.getReplyTo());
2949
2950        stopScrolling();
2951        Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
2952
2953        if (this.conversation.isRead() && hasExtras) {
2954            Log.d(Config.LOGTAG, "trimming conversation");
2955            this.conversation.trim();
2956        }
2957
2958        setupIme();
2959
2960        final boolean scrolledToBottomAndNoPending =
2961                this.scrolledToBottom() && pendingScrollState.peek() == null;
2962
2963        this.binding.textSendButton.setContentDescription(
2964                activity.getString(R.string.send_message_to_x, conversation.getName()));
2965        this.binding.textinput.setKeyboardListener(null);
2966        final boolean participating =
2967                conversation.getMode() == Conversational.MODE_SINGLE
2968                        || conversation.getMucOptions().participating();
2969        if (participating) {
2970            this.binding.textinput.setText(this.conversation.getNextMessage());
2971            this.binding.textinput.setSelection(this.binding.textinput.length());
2972        } else {
2973            this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
2974        }
2975        this.binding.textinput.setKeyboardListener(this);
2976        messageListAdapter.updatePreferences();
2977        refresh(false);
2978        activity.invalidateOptionsMenu();
2979        this.conversation.messagesLoaded.set(true);
2980        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
2981
2982        if (hasExtras || scrolledToBottomAndNoPending) {
2983            resetUnreadMessagesCount();
2984            synchronized (this.messageList) {
2985                Log.d(Config.LOGTAG, "jump to first unread message");
2986                final Message first = conversation.getFirstUnreadMessage();
2987                final int bottom = Math.max(0, this.messageList.size() - 1);
2988                final int pos;
2989                final boolean jumpToBottom;
2990                if (first == null) {
2991                    pos = bottom;
2992                    jumpToBottom = true;
2993                } else {
2994                    int i = getIndexOf(first.getUuid(), this.messageList);
2995                    pos = i < 0 ? bottom : i;
2996                    jumpToBottom = false;
2997                }
2998                setSelection(pos, jumpToBottom);
2999            }
3000        }
3001
3002        this.binding.messagesView.post(this::fireReadEvent);
3003        // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3004        // layout which might be unnecessary since we can *see* it
3005        activity.xmppConnectionService
3006                .getNotificationService()
3007                .setOpenConversation(this.conversation);
3008
3009        if (commandAdapter != null && conversation != originalConversation) {
3010            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3011            refreshCommands(false);
3012        }
3013        if (commandAdapter == null && conversation != null) {
3014            conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3015            commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3016            binding.commandsView.setAdapter(commandAdapter);
3017            binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3018                if (activity == null) return;
3019
3020                final Element command = commandAdapter.getItem(position);
3021                activity.startCommand(conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
3022            });
3023            refreshCommands(false);
3024        }
3025
3026        return true;
3027    }
3028
3029    public void refreshForNewCaps() {
3030        refreshCommands(true);
3031    }
3032
3033    protected void refreshCommands(boolean delayShow) {
3034        if (commandAdapter == null) return;
3035
3036        Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3037        if (commandJid == null && conversation.getJid().isDomainJid()) {
3038            commandJid = conversation.getJid();
3039        }
3040        if (commandJid == null) {
3041            conversation.hideViewPager();
3042        } else {
3043            if (!delayShow) conversation.showViewPager();
3044            activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
3045                if (activity == null) return;
3046
3047                activity.runOnUiThread(() -> {
3048                    if (iq.getType() == IqPacket.TYPE.RESULT) {
3049                        binding.commandsViewProgressbar.setVisibility(View.GONE);
3050                        commandAdapter.clear();
3051                        for (Element child : iq.query().getChildren()) {
3052                            if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3053                            commandAdapter.add(child);
3054                        }
3055                    }
3056
3057                    if (commandAdapter.getCount() < 1) {
3058                        conversation.hideViewPager();
3059                    } else if (delayShow) {
3060                        conversation.showViewPager();
3061                    }
3062                });
3063            });
3064        }
3065    }
3066
3067    private void resetUnreadMessagesCount() {
3068        lastMessageUuid = null;
3069        hideUnreadMessagesCount();
3070    }
3071
3072    private void hideUnreadMessagesCount() {
3073        if (this.binding == null) {
3074            return;
3075        }
3076        this.binding.scrollToBottomButton.setEnabled(false);
3077        this.binding.scrollToBottomButton.hide();
3078        this.binding.unreadCountCustomView.setVisibility(View.GONE);
3079    }
3080
3081    private void setSelection(int pos, boolean jumpToBottom) {
3082        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3083        this.binding.messagesView.post(
3084                () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3085        this.binding.messagesView.post(this::fireReadEvent);
3086    }
3087
3088    private boolean scrolledToBottom() {
3089        return this.binding != null && scrolledToBottom(this.binding.messagesView);
3090    }
3091
3092    private void processExtras(final Bundle extras) {
3093        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3094        final String text = extras.getString(Intent.EXTRA_TEXT);
3095        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3096        final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3097        final String postInitAction =
3098                extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3099        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3100        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3101        final boolean doNotAppend =
3102                extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3103        final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3104        final List<Uri> uris = extractUris(extras);
3105        if (uris != null && uris.size() > 0) {
3106            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3107                mediaPreviewAdapter.addMediaPreviews(
3108                        Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3109            } else {
3110                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3111                mediaPreviewAdapter.addMediaPreviews(
3112                        Attachment.of(getActivity(), cleanedUris, type));
3113            }
3114            toggleInputMethod();
3115            return;
3116        }
3117        if (nick != null) {
3118            if (pm) {
3119                Jid jid = conversation.getJid();
3120                try {
3121                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3122                    privateMessageWith(next);
3123                } catch (final IllegalArgumentException ignored) {
3124                    // do nothing
3125                }
3126            } else {
3127                final MucOptions mucOptions = conversation.getMucOptions();
3128                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3129                    highlightInConference(nick);
3130                }
3131            }
3132        } else {
3133            if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3134                mediaPreviewAdapter.addMediaPreviews(
3135                        Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3136                toggleInputMethod();
3137                return;
3138            } else if (text != null && asQuote) {
3139                quoteText(text);
3140            } else {
3141                appendText(text, doNotAppend);
3142            }
3143        }
3144        if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3145            attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3146            return;
3147        }
3148        if ("call".equals(postInitAction)) {
3149            checkPermissionAndTriggerAudioCall();
3150        }
3151        if ("message".equals(postInitAction)) {
3152            binding.conversationViewPager.post(() -> {
3153                binding.conversationViewPager.setCurrentItem(0);
3154            });
3155        }
3156        if ("command".equals(postInitAction)) {
3157            binding.conversationViewPager.post(() -> {
3158                PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3159                if (adapter != null && adapter.getCount() > 1) {
3160                    binding.conversationViewPager.setCurrentItem(1);
3161                }
3162                final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3163                Jid commandJid = null;
3164                if (jid != null) {
3165                    try {
3166                        commandJid = Jid.of(jid);
3167                    } catch (final IllegalArgumentException e) { }
3168                }
3169                if (commandJid == null || !commandJid.isFullJid()) {
3170                    final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3171                    if (discoJid != null) commandJid = discoJid;
3172                }
3173                if (node != null && commandJid != null) {
3174                    conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3175                }
3176            });
3177            return;
3178        }
3179        final Message message =
3180                downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3181        if ("webxdc".equals(postInitAction)) {
3182            if (message == null) return;
3183
3184            Cid webxdcCid = message.getFileParams().getCids().get(0);
3185            WebxdcPage webxdc = new WebxdcPage(webxdcCid, message, activity.xmppConnectionService);
3186            Conversation conversation = (Conversation) message.getConversation();
3187            if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3188                conversation.startWebxdc(webxdc);
3189            }
3190        }
3191        if (message != null) {
3192            startDownloadable(message);
3193        }
3194        if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3195            if (!conversation.switchToSession("jabber:iq:register")) {
3196                conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3197            }
3198        }
3199    }
3200
3201    private Element commandFor(final Jid jid, final String node) {
3202        if (commandAdapter != null) {
3203            for (int i = 0; i < commandAdapter.getCount(); i++) {
3204                Element command = commandAdapter.getItem(i);
3205                final String commandNode = command.getAttribute("node");
3206                if (commandNode == null || !commandNode.equals(node)) continue;
3207
3208                final Jid commandJid = command.getAttributeAsJid("jid");
3209                if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3210
3211                return command;
3212            }
3213        }
3214
3215        return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3216    }
3217
3218    private List<Uri> extractUris(final Bundle extras) {
3219        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3220        if (uris != null) {
3221            return uris;
3222        }
3223        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3224        if (uri != null) {
3225            return Collections.singletonList(uri);
3226        } else {
3227            return null;
3228        }
3229    }
3230
3231    private List<Uri> cleanUris(final List<Uri> uris) {
3232        final Iterator<Uri> iterator = uris.iterator();
3233        while (iterator.hasNext()) {
3234            final Uri uri = iterator.next();
3235            if (FileBackend.weOwnFile(uri)) {
3236                iterator.remove();
3237                Toast.makeText(
3238                                getActivity(),
3239                                R.string.security_violation_not_attaching_file,
3240                                Toast.LENGTH_SHORT)
3241                        .show();
3242            }
3243        }
3244        return uris;
3245    }
3246
3247    private boolean showBlockSubmenu(View view) {
3248        final Jid jid = conversation.getJid();
3249        final boolean showReject =
3250                !conversation.isWithStranger()
3251                        && conversation
3252                                .getContact()
3253                                .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3254        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3255        popupMenu.inflate(R.menu.block);
3256        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3257        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3258        popupMenu.setOnMenuItemClickListener(
3259                menuItem -> {
3260                    Blockable blockable;
3261                    switch (menuItem.getItemId()) {
3262                        case R.id.reject:
3263                            activity.xmppConnectionService.stopPresenceUpdatesTo(
3264                                    conversation.getContact());
3265                            updateSnackBar(conversation);
3266                            return true;
3267                        case R.id.block_domain:
3268                            blockable =
3269                                    conversation
3270                                            .getAccount()
3271                                            .getRoster()
3272                                            .getContact(jid.getDomain());
3273                            break;
3274                        default:
3275                            blockable = conversation;
3276                    }
3277                    BlockContactDialog.show(activity, blockable);
3278                    return true;
3279                });
3280        popupMenu.show();
3281        return true;
3282    }
3283
3284    private void updateSnackBar(final Conversation conversation) {
3285        final Account account = conversation.getAccount();
3286        final XmppConnection connection = account.getXmppConnection();
3287        final int mode = conversation.getMode();
3288        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3289        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3290            return;
3291        }
3292        if (account.getStatus() == Account.State.DISABLED) {
3293            showSnackbar(
3294                    R.string.this_account_is_disabled,
3295                    R.string.enable,
3296                    this.mEnableAccountListener);
3297        } else if (conversation.isBlocked()) {
3298            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3299        } else if (contact != null
3300                && !contact.showInRoster()
3301                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3302            showSnackbar(
3303                    R.string.contact_added_you,
3304                    R.string.add_back,
3305                    this.mAddBackClickListener,
3306                    this.mLongPressBlockListener);
3307        } else if (contact != null
3308                && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3309            showSnackbar(
3310                    R.string.contact_asks_for_presence_subscription,
3311                    R.string.allow,
3312                    this.mAllowPresenceSubscription,
3313                    this.mLongPressBlockListener);
3314        } else if (mode == Conversation.MODE_MULTI
3315                && !conversation.getMucOptions().online()
3316                && account.getStatus() == Account.State.ONLINE) {
3317            switch (conversation.getMucOptions().getError()) {
3318                case NICK_IN_USE:
3319                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3320                    break;
3321                case NO_RESPONSE:
3322                    showSnackbar(R.string.joining_conference, 0, null);
3323                    break;
3324                case SERVER_NOT_FOUND:
3325                    if (conversation.receivedMessagesCount() > 0) {
3326                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3327                    } else {
3328                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3329                    }
3330                    break;
3331                case REMOTE_SERVER_TIMEOUT:
3332                    if (conversation.receivedMessagesCount() > 0) {
3333                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3334                    } else {
3335                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3336                    }
3337                    break;
3338                case PASSWORD_REQUIRED:
3339                    showSnackbar(
3340                            R.string.conference_requires_password,
3341                            R.string.enter_password,
3342                            enterPassword);
3343                    break;
3344                case BANNED:
3345                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3346                    break;
3347                case MEMBERS_ONLY:
3348                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3349                    break;
3350                case RESOURCE_CONSTRAINT:
3351                    showSnackbar(
3352                            R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3353                    break;
3354                case KICKED:
3355                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3356                    break;
3357                case TECHNICAL_PROBLEMS:
3358                    showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3359                    break;
3360                case UNKNOWN:
3361                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3362                    break;
3363                case INVALID_NICK:
3364                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3365                case SHUTDOWN:
3366                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3367                    break;
3368                case DESTROYED:
3369                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3370                    break;
3371                case NON_ANONYMOUS:
3372                    showSnackbar(
3373                            R.string.group_chat_will_make_your_jabber_id_public,
3374                            R.string.join,
3375                            acceptJoin);
3376                    break;
3377                default:
3378                    hideSnackbar();
3379                    break;
3380            }
3381        } else if (account.hasPendingPgpIntent(conversation)) {
3382            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3383        } else if (connection != null
3384                && connection.getFeatures().blocking()
3385                && conversation.countMessages() != 0
3386                && !conversation.isBlocked()
3387                && conversation.isWithStranger()) {
3388            showSnackbar(
3389                    R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
3390        } else {
3391            hideSnackbar();
3392        }
3393    }
3394
3395    @Override
3396    public void refresh() {
3397        if (this.binding == null) {
3398            Log.d(
3399                    Config.LOGTAG,
3400                    "ConversationFragment.refresh() skipped updated because view binding was null");
3401            return;
3402        }
3403        if (this.conversation != null
3404                && this.activity != null
3405                && this.activity.xmppConnectionService != null) {
3406            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3407                activity.onConversationArchived(this.conversation);
3408                return;
3409            }
3410        }
3411        this.refresh(true);
3412    }
3413
3414    private void refresh(boolean notifyConversationRead) {
3415        synchronized (this.messageList) {
3416            if (this.conversation != null) {
3417                conversation.populateWithMessages(this.messageList);
3418                updateSnackBar(conversation);
3419                updateStatusMessages();
3420                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3421                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3422                    binding.unreadCountCustomView.setUnreadCount(
3423                            conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3424                }
3425                this.messageListAdapter.notifyDataSetChanged();
3426                updateChatMsgHint();
3427                if (notifyConversationRead && activity != null) {
3428                    binding.messagesView.post(this::fireReadEvent);
3429                }
3430                updateSendButton();
3431                updateEditablity();
3432                conversation.refreshSessions();
3433            }
3434        }
3435    }
3436
3437    protected void messageSent() {
3438        conversation.setUserSelectedThread(false);
3439        mSendingPgpMessage.set(false);
3440        this.binding.textinput.setText("");
3441        if (conversation.setCorrectingMessage(null)) {
3442            this.binding.textinput.append(conversation.getDraftMessage());
3443            conversation.setDraftMessage(null);
3444        }
3445        storeNextMessage();
3446        updateChatMsgHint();
3447        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3448        final boolean prefScrollToBottom =
3449                p.getBoolean(
3450                        "scroll_to_bottom",
3451                        activity.getResources().getBoolean(R.bool.scroll_to_bottom));
3452        if (prefScrollToBottom || scrolledToBottom()) {
3453            new Handler()
3454                    .post(
3455                            () -> {
3456                                int size = messageList.size();
3457                                this.binding.messagesView.setSelection(size - 1);
3458                            });
3459        }
3460    }
3461
3462    private boolean storeNextMessage() {
3463        return storeNextMessage(this.binding.textinput.getText().toString());
3464    }
3465
3466    private boolean storeNextMessage(String msg) {
3467        final boolean participating =
3468                conversation.getMode() == Conversational.MODE_SINGLE
3469                        || conversation.getMucOptions().participating();
3470        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3471                && participating
3472                && this.conversation.setNextMessage(msg)) {
3473            this.activity.xmppConnectionService.updateConversation(this.conversation);
3474            return true;
3475        }
3476        return false;
3477    }
3478
3479    public void doneSendingPgpMessage() {
3480        mSendingPgpMessage.set(false);
3481    }
3482
3483    public long getMaxHttpUploadSize(Conversation conversation) {
3484        final XmppConnection connection = conversation.getAccount().getXmppConnection();
3485        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3486    }
3487
3488    private boolean canWrite() {
3489        return
3490                this.conversation.getMode() == Conversation.MODE_SINGLE
3491                        || this.conversation.getMucOptions().participating()
3492                        || this.conversation.getNextCounterpart() != null;
3493    }
3494
3495    private void updateEditablity() {
3496        boolean canWrite = canWrite();
3497        this.binding.textinput.setFocusable(canWrite);
3498        this.binding.textinput.setFocusableInTouchMode(canWrite);
3499        this.binding.textSendButton.setEnabled(canWrite);
3500        this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
3501        this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
3502        this.binding.textinput.setCursorVisible(canWrite);
3503        this.binding.textinput.setEnabled(canWrite);
3504    }
3505
3506    public void updateSendButton() {
3507        boolean hasAttachments =
3508                mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3509        final Conversation c = this.conversation;
3510        final Presence.Status status;
3511        final String text =
3512                this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3513        final SendButtonAction action;
3514        if (hasAttachments) {
3515            action = SendButtonAction.TEXT;
3516        } else {
3517            action = SendButtonTool.getAction(getActivity(), c, text);
3518        }
3519        if (c.getAccount().getStatus() == Account.State.ONLINE) {
3520            if (activity != null
3521                    && activity.xmppConnectionService != null
3522                    && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3523                status = Presence.Status.OFFLINE;
3524            } else if (c.getMode() == Conversation.MODE_SINGLE) {
3525                status = c.getContact().getShownStatus();
3526            } else {
3527                status =
3528                        c.getMucOptions().online()
3529                                ? Presence.Status.ONLINE
3530                                : Presence.Status.OFFLINE;
3531            }
3532        } else {
3533            status = Presence.Status.OFFLINE;
3534        }
3535        this.binding.textSendButton.setTag(action);
3536        final Activity activity = getActivity();
3537        if (activity != null) {
3538            this.binding.textSendButton.setImageResource(
3539                    SendButtonTool.getSendButtonImageResource(activity, action, status));
3540        }
3541
3542        ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
3543        if (identiconWidth < 0) identiconWidth = params.width;
3544        if (hasAttachments || binding.textinput.getText().length() > 0) {
3545            binding.conversationViewPager.setCurrentItem(0);
3546            params.width = conversation.getThread() == null ? 0 : identiconWidth;
3547        } else {
3548            params.width = identiconWidth;
3549        }
3550        if (!canWrite()) params.width = 0;
3551        binding.threadIdenticonLayout.setLayoutParams(params);
3552    }
3553
3554    protected void updateStatusMessages() {
3555        DateSeparator.addAll(this.messageList);
3556        if (showLoadMoreMessages(conversation)) {
3557            this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3558        }
3559        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3560            ChatState state = conversation.getIncomingChatState();
3561            if (state == ChatState.COMPOSING) {
3562                this.messageList.add(
3563                        Message.createStatusMessage(
3564                                conversation,
3565                                getString(R.string.contact_is_typing, conversation.getName())));
3566            } else if (state == ChatState.PAUSED) {
3567                this.messageList.add(
3568                        Message.createStatusMessage(
3569                                conversation,
3570                                getString(
3571                                        R.string.contact_has_stopped_typing,
3572                                        conversation.getName())));
3573            } else {
3574                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3575                    final Message message = this.messageList.get(i);
3576                    if (message.getType() != Message.TYPE_STATUS) {
3577                        if (message.getStatus() == Message.STATUS_RECEIVED) {
3578                            return;
3579                        } else {
3580                            if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3581                                this.messageList.add(
3582                                        i + 1,
3583                                        Message.createStatusMessage(
3584                                                conversation,
3585                                                getString(
3586                                                        R.string.contact_has_read_up_to_this_point,
3587                                                        conversation.getName())));
3588                                return;
3589                            }
3590                        }
3591                    }
3592                }
3593            }
3594        } else {
3595            final MucOptions mucOptions = conversation.getMucOptions();
3596            final List<MucOptions.User> allUsers = mucOptions.getUsers();
3597            final Set<ReadByMarker> addedMarkers = new HashSet<>();
3598            ChatState state = ChatState.COMPOSING;
3599            List<MucOptions.User> users =
3600                    conversation.getMucOptions().getUsersWithChatState(state, 5);
3601            if (users.size() == 0) {
3602                state = ChatState.PAUSED;
3603                users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3604            }
3605            if (mucOptions.isPrivateAndNonAnonymous()) {
3606                for (int i = this.messageList.size() - 1; i >= 0; --i) {
3607                    final Set<ReadByMarker> markersForMessage =
3608                            messageList.get(i).getReadByMarkers();
3609                    final List<MucOptions.User> shownMarkers = new ArrayList<>();
3610                    for (ReadByMarker marker : markersForMessage) {
3611                        if (!ReadByMarker.contains(marker, addedMarkers)) {
3612                            addedMarkers.add(
3613                                    marker); // may be put outside this condition. set should do
3614                                             // dedup anyway
3615                            MucOptions.User user = mucOptions.findUser(marker);
3616                            if (user != null && !users.contains(user)) {
3617                                shownMarkers.add(user);
3618                            }
3619                        }
3620                    }
3621                    final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3622                    final Message statusMessage;
3623                    final int size = shownMarkers.size();
3624                    if (size > 1) {
3625                        final String body;
3626                        if (size <= 4) {
3627                            body =
3628                                    getString(
3629                                            R.string.contacts_have_read_up_to_this_point,
3630                                            UIHelper.concatNames(shownMarkers));
3631                        } else if (ReadByMarker.allUsersRepresented(
3632                                allUsers, markersForMessage, markerForSender)) {
3633                            body = getString(R.string.everyone_has_read_up_to_this_point);
3634                        } else {
3635                            body =
3636                                    getString(
3637                                            R.string.contacts_and_n_more_have_read_up_to_this_point,
3638                                            UIHelper.concatNames(shownMarkers, 3),
3639                                            size - 3);
3640                        }
3641                        statusMessage = Message.createStatusMessage(conversation, body);
3642                        statusMessage.setCounterparts(shownMarkers);
3643                    } else if (size == 1) {
3644                        statusMessage =
3645                                Message.createStatusMessage(
3646                                        conversation,
3647                                        getString(
3648                                                R.string.contact_has_read_up_to_this_point,
3649                                                UIHelper.getDisplayName(shownMarkers.get(0))));
3650                        statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3651                        statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3652                    } else {
3653                        statusMessage = null;
3654                    }
3655                    if (statusMessage != null) {
3656                        this.messageList.add(i + 1, statusMessage);
3657                    }
3658                    addedMarkers.add(markerForSender);
3659                    if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3660                        break;
3661                    }
3662                }
3663            }
3664            if (users.size() > 0) {
3665                Message statusMessage;
3666                if (users.size() == 1) {
3667                    MucOptions.User user = users.get(0);
3668                    int id =
3669                            state == ChatState.COMPOSING
3670                                    ? R.string.contact_is_typing
3671                                    : R.string.contact_has_stopped_typing;
3672                    statusMessage =
3673                            Message.createStatusMessage(
3674                                    conversation, getString(id, UIHelper.getDisplayName(user)));
3675                    statusMessage.setTrueCounterpart(user.getRealJid());
3676                    statusMessage.setCounterpart(user.getFullJid());
3677                } else {
3678                    int id =
3679                            state == ChatState.COMPOSING
3680                                    ? R.string.contacts_are_typing
3681                                    : R.string.contacts_have_stopped_typing;
3682                    statusMessage =
3683                            Message.createStatusMessage(
3684                                    conversation, getString(id, UIHelper.concatNames(users)));
3685                    statusMessage.setCounterparts(users);
3686                }
3687                this.messageList.add(statusMessage);
3688            }
3689        }
3690    }
3691
3692    private void stopScrolling() {
3693        long now = SystemClock.uptimeMillis();
3694        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3695        binding.messagesView.dispatchTouchEvent(cancel);
3696    }
3697
3698    private boolean showLoadMoreMessages(final Conversation c) {
3699        if (activity == null || activity.xmppConnectionService == null) {
3700            return false;
3701        }
3702        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3703        final MessageArchiveService service =
3704                activity.xmppConnectionService.getMessageArchiveService();
3705        return mam
3706                && (c.getLastClearHistory().getTimestamp() != 0
3707                        || (c.countMessages() == 0
3708                                && c.messagesLoaded.get()
3709                                && c.hasMessagesLeftOnServer()
3710                                && !service.queryInProgress(c)));
3711    }
3712
3713    private boolean hasMamSupport(final Conversation c) {
3714        if (c.getMode() == Conversation.MODE_SINGLE) {
3715            final XmppConnection connection = c.getAccount().getXmppConnection();
3716            return connection != null && connection.getFeatures().mam();
3717        } else {
3718            return c.getMucOptions().mamSupport();
3719        }
3720    }
3721
3722    protected void showSnackbar(
3723            final int message, final int action, final OnClickListener clickListener) {
3724        showSnackbar(message, action, clickListener, null);
3725    }
3726
3727    protected void showSnackbar(
3728            final int message,
3729            final int action,
3730            final OnClickListener clickListener,
3731            final View.OnLongClickListener longClickListener) {
3732        this.binding.snackbar.setVisibility(View.VISIBLE);
3733        this.binding.snackbar.setOnClickListener(null);
3734        this.binding.snackbarMessage.setText(message);
3735        this.binding.snackbarMessage.setOnClickListener(null);
3736        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3737        if (action != 0) {
3738            this.binding.snackbarAction.setText(action);
3739        }
3740        this.binding.snackbarAction.setOnClickListener(clickListener);
3741        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3742    }
3743
3744    protected void hideSnackbar() {
3745        this.binding.snackbar.setVisibility(View.GONE);
3746    }
3747
3748    protected void sendMessage(Message message) {
3749        new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
3750        messageSent();
3751    }
3752
3753    protected void sendPgpMessage(final Message message) {
3754        final XmppConnectionService xmppService = activity.xmppConnectionService;
3755        final Contact contact = message.getConversation().getContact();
3756        if (!activity.hasPgp()) {
3757            activity.showInstallPgpDialog();
3758            return;
3759        }
3760        if (conversation.getAccount().getPgpSignature() == null) {
3761            activity.announcePgp(
3762                    conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3763            return;
3764        }
3765        if (!mSendingPgpMessage.compareAndSet(false, true)) {
3766            Log.d(Config.LOGTAG, "sending pgp message already in progress");
3767        }
3768        if (conversation.getMode() == Conversation.MODE_SINGLE) {
3769            if (contact.getPgpKeyId() != 0) {
3770                xmppService
3771                        .getPgpEngine()
3772                        .hasKey(
3773                                contact,
3774                                new UiCallback<Contact>() {
3775
3776                                    @Override
3777                                    public void userInputRequired(
3778                                            PendingIntent pi, Contact contact) {
3779                                        startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3780                                    }
3781
3782                                    @Override
3783                                    public void success(Contact contact) {
3784                                        encryptTextMessage(message);
3785                                    }
3786
3787                                    @Override
3788                                    public void error(int error, Contact contact) {
3789                                        activity.runOnUiThread(
3790                                                () ->
3791                                                        Toast.makeText(
3792                                                                        activity,
3793                                                                        R.string
3794                                                                                .unable_to_connect_to_keychain,
3795                                                                        Toast.LENGTH_SHORT)
3796                                                                .show());
3797                                        mSendingPgpMessage.set(false);
3798                                    }
3799                                });
3800
3801            } else {
3802                showNoPGPKeyDialog(
3803                        false,
3804                        (dialog, which) -> {
3805                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3806                            xmppService.updateConversation(conversation);
3807                            message.setEncryption(Message.ENCRYPTION_NONE);
3808                            xmppService.sendMessage(message);
3809                            messageSent();
3810                        });
3811            }
3812        } else {
3813            if (conversation.getMucOptions().pgpKeysInUse()) {
3814                if (!conversation.getMucOptions().everybodyHasKeys()) {
3815                    Toast warning =
3816                            Toast.makeText(
3817                                    getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3818                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3819                    warning.show();
3820                }
3821                encryptTextMessage(message);
3822            } else {
3823                showNoPGPKeyDialog(
3824                        true,
3825                        (dialog, which) -> {
3826                            conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3827                            message.setEncryption(Message.ENCRYPTION_NONE);
3828                            xmppService.updateConversation(conversation);
3829                            xmppService.sendMessage(message);
3830                            messageSent();
3831                        });
3832            }
3833        }
3834    }
3835
3836    public void encryptTextMessage(Message message) {
3837        activity.xmppConnectionService
3838                .getPgpEngine()
3839                .encrypt(
3840                        message,
3841                        new UiCallback<Message>() {
3842
3843                            @Override
3844                            public void userInputRequired(PendingIntent pi, Message message) {
3845                                startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3846                            }
3847
3848                            @Override
3849                            public void success(Message message) {
3850                                // TODO the following two call can be made before the callback
3851                                getActivity().runOnUiThread(() -> messageSent());
3852                            }
3853
3854                            @Override
3855                            public void error(final int error, Message message) {
3856                                getActivity()
3857                                        .runOnUiThread(
3858                                                () -> {
3859                                                    doneSendingPgpMessage();
3860                                                    Toast.makeText(
3861                                                                    getActivity(),
3862                                                                    error == 0
3863                                                                            ? R.string
3864                                                                                    .unable_to_connect_to_keychain
3865                                                                            : error,
3866                                                                    Toast.LENGTH_SHORT)
3867                                                            .show();
3868                                                });
3869                            }
3870                        });
3871    }
3872
3873    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3874        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3875        builder.setIconAttribute(android.R.attr.alertDialogIcon);
3876        if (plural) {
3877            builder.setTitle(getString(R.string.no_pgp_keys));
3878            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3879        } else {
3880            builder.setTitle(getString(R.string.no_pgp_key));
3881            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3882        }
3883        builder.setNegativeButton(getString(R.string.cancel), null);
3884        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3885        builder.create().show();
3886    }
3887
3888    public void appendText(String text, final boolean doNotAppend) {
3889        if (text == null) {
3890            return;
3891        }
3892        final Editable editable = this.binding.textinput.getText();
3893        String previous = editable == null ? "" : editable.toString();
3894        if (doNotAppend && !TextUtils.isEmpty(previous)) {
3895            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3896                    .show();
3897            return;
3898        }
3899        if (UIHelper.isLastLineQuote(previous)) {
3900            text = '\n' + text;
3901        } else if (previous.length() != 0
3902                && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3903            text = " " + text;
3904        }
3905        this.binding.textinput.append(text);
3906    }
3907
3908    @Override
3909    public boolean onEnterPressed(final boolean isCtrlPressed) {
3910        if (isCtrlPressed || enterIsSend()) {
3911            sendMessage();
3912            return true;
3913        }
3914        return false;
3915    }
3916
3917    private boolean enterIsSend() {
3918        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3919        return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3920    }
3921
3922    public boolean onArrowUpCtrlPressed() {
3923        final Message lastEditableMessage =
3924                conversation == null ? null : conversation.getLastEditableMessage();
3925        if (lastEditableMessage != null) {
3926            correctMessage(lastEditableMessage);
3927            return true;
3928        } else {
3929            Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3930                    .show();
3931            return false;
3932        }
3933    }
3934
3935    @Override
3936    public void onTypingStarted() {
3937        final XmppConnectionService service =
3938                activity == null ? null : activity.xmppConnectionService;
3939        if (service == null) {
3940            return;
3941        }
3942        final Account.State status = conversation.getAccount().getStatus();
3943        if (status == Account.State.ONLINE
3944                && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3945            service.sendChatState(conversation);
3946        }
3947        runOnUiThread(this::updateSendButton);
3948    }
3949
3950    @Override
3951    public void onTypingStopped() {
3952        final XmppConnectionService service =
3953                activity == null ? null : activity.xmppConnectionService;
3954        if (service == null) {
3955            return;
3956        }
3957        final Account.State status = conversation.getAccount().getStatus();
3958        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3959            service.sendChatState(conversation);
3960        }
3961    }
3962
3963    @Override
3964    public void onTextDeleted() {
3965        final XmppConnectionService service =
3966                activity == null ? null : activity.xmppConnectionService;
3967        if (service == null) {
3968            return;
3969        }
3970        final Account.State status = conversation.getAccount().getStatus();
3971        if (status == Account.State.ONLINE
3972                && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3973            service.sendChatState(conversation);
3974        }
3975        if (storeNextMessage()) {
3976            runOnUiThread(
3977                    () -> {
3978                        if (activity == null) {
3979                            return;
3980                        }
3981                        activity.onConversationsListItemUpdated();
3982                    });
3983        }
3984        runOnUiThread(this::updateSendButton);
3985    }
3986
3987    @Override
3988    public void onTextChanged() {
3989        if (conversation != null && conversation.getCorrectingMessage() != null) {
3990            runOnUiThread(this::updateSendButton);
3991        }
3992    }
3993
3994    @Override
3995    public boolean onTabPressed(boolean repeated) {
3996        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3997            return false;
3998        }
3999        if (repeated) {
4000            completionIndex++;
4001        } else {
4002            lastCompletionLength = 0;
4003            completionIndex = 0;
4004            final String content = this.binding.textinput.getText().toString();
4005            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4006            int start =
4007                    lastCompletionCursor > 0
4008                            ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4009                            : 0;
4010            firstWord = start == 0;
4011            incomplete = content.substring(start, lastCompletionCursor);
4012        }
4013        List<String> completions = new ArrayList<>();
4014        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4015            String name = user.getNick();
4016            if (name != null && name.startsWith(incomplete)) {
4017                completions.add(name + (firstWord ? ": " : " "));
4018            }
4019        }
4020        Collections.sort(completions);
4021        if (completions.size() > completionIndex) {
4022            String completion = completions.get(completionIndex).substring(incomplete.length());
4023            this.binding
4024                    .textinput
4025                    .getEditableText()
4026                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4027            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4028            lastCompletionLength = completion.length();
4029        } else {
4030            completionIndex = -1;
4031            this.binding
4032                    .textinput
4033                    .getEditableText()
4034                    .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4035            lastCompletionLength = 0;
4036        }
4037        return true;
4038    }
4039
4040    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4041        try {
4042            getActivity()
4043                    .startIntentSenderForResult(
4044                            pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
4045        } catch (final SendIntentException ignored) {
4046        }
4047    }
4048
4049    @Override
4050    public void onBackendConnected() {
4051        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4052        setupEmojiSearch();
4053        String uuid = pendingConversationsUuid.pop();
4054        if (uuid != null) {
4055            if (!findAndReInitByUuidOrArchive(uuid)) {
4056                return;
4057            }
4058        } else {
4059            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4060                clearPending();
4061                activity.onConversationArchived(conversation);
4062                return;
4063            }
4064        }
4065        ActivityResult activityResult = postponedActivityResult.pop();
4066        if (activityResult != null) {
4067            handleActivityResult(activityResult);
4068        }
4069        clearPending();
4070    }
4071
4072    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4073        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4074        if (conversation == null) {
4075            clearPending();
4076            activity.onConversationArchived(null);
4077            return false;
4078        }
4079        reInit(conversation);
4080        ScrollState scrollState = pendingScrollState.pop();
4081        String lastMessageUuid = pendingLastMessageUuid.pop();
4082        List<Attachment> attachments = pendingMediaPreviews.pop();
4083        if (scrollState != null) {
4084            setScrollPosition(scrollState, lastMessageUuid);
4085        }
4086        if (attachments != null && attachments.size() > 0) {
4087            Log.d(Config.LOGTAG, "had attachments on restore");
4088            mediaPreviewAdapter.addMediaPreviews(attachments);
4089            toggleInputMethod();
4090        }
4091        return true;
4092    }
4093
4094    private void clearPending() {
4095        if (postponedActivityResult.clear()) {
4096            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4097            if (pendingTakePhotoUri.clear()) {
4098                Log.e(Config.LOGTAG, "cleared pending photo uri");
4099            }
4100        }
4101        if (pendingScrollState.clear()) {
4102            Log.e(Config.LOGTAG, "cleared scroll state");
4103        }
4104        if (pendingConversationsUuid.clear()) {
4105            Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4106        }
4107        if (pendingMediaPreviews.clear()) {
4108            Log.e(Config.LOGTAG, "cleared pending media previews");
4109        }
4110    }
4111
4112    public Conversation getConversation() {
4113        return conversation;
4114    }
4115
4116    @Override
4117    public void onContactPictureLongClicked(View v, final Message message) {
4118        final String fingerprint;
4119        if (message.getEncryption() == Message.ENCRYPTION_PGP
4120                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4121            fingerprint = "pgp";
4122        } else {
4123            fingerprint = message.getFingerprint();
4124        }
4125        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4126        final Contact contact = message.getContact();
4127        if (message.getStatus() <= Message.STATUS_RECEIVED
4128                && (contact == null || !contact.isSelf())) {
4129            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4130                final Jid cp = message.getCounterpart();
4131                if (cp == null || cp.isBareJid()) {
4132                    return;
4133                }
4134                final Jid tcp = message.getTrueCounterpart();
4135                final User userByRealJid =
4136                        tcp != null
4137                                ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
4138                                : null;
4139                final User user =
4140                        userByRealJid != null
4141                                ? userByRealJid
4142                                : conversation.getMucOptions().findUserByFullJid(cp);
4143                popupMenu.inflate(R.menu.muc_details_context);
4144                final Menu menu = popupMenu.getMenu();
4145                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4146                        activity, menu, conversation, user);
4147                popupMenu.setOnMenuItemClickListener(
4148                        menuItem ->
4149                                MucDetailsContextMenuHelper.onContextItemSelected(
4150                                        menuItem, user, activity, fingerprint));
4151            } else {
4152                popupMenu.inflate(R.menu.one_on_one_context);
4153                popupMenu.setOnMenuItemClickListener(
4154                        item -> {
4155                            switch (item.getItemId()) {
4156                                case R.id.action_contact_details:
4157                                    activity.switchToContactDetails(
4158                                            message.getContact(), fingerprint);
4159                                    break;
4160                                case R.id.action_show_qr_code:
4161                                    activity.showQrCode(
4162                                            "xmpp:"
4163                                                    + message.getContact()
4164                                                            .getJid()
4165                                                            .asBareJid()
4166                                                            .toEscapedString());
4167                                    break;
4168                            }
4169                            return true;
4170                        });
4171            }
4172        } else {
4173            popupMenu.inflate(R.menu.account_context);
4174            final Menu menu = popupMenu.getMenu();
4175            menu.findItem(R.id.action_manage_accounts)
4176                    .setVisible(QuickConversationsService.isConversations());
4177            popupMenu.setOnMenuItemClickListener(
4178                    item -> {
4179                        final XmppActivity activity = this.activity;
4180                        if (activity == null) {
4181                            Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4182                            return true;
4183                        }
4184                        switch (item.getItemId()) {
4185                            case R.id.action_show_qr_code:
4186                                activity.showQrCode(conversation.getAccount().getShareableUri());
4187                                break;
4188                            case R.id.action_account_details:
4189                                activity.switchToAccount(
4190                                        message.getConversation().getAccount(), fingerprint);
4191                                break;
4192                            case R.id.action_manage_accounts:
4193                                AccountUtils.launchManageAccounts(activity);
4194                                break;
4195                        }
4196                        return true;
4197                    });
4198        }
4199        popupMenu.show();
4200    }
4201
4202    @Override
4203    public void onContactPictureClicked(Message message) {
4204        setThread(message.getThread());
4205        if (message.isPrivateMessage()) {
4206            privateMessageWith(message.getCounterpart());
4207            return;
4208        }
4209        forkNullThread(message);
4210        conversation.setUserSelectedThread(true);
4211
4212        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4213        if (received) {
4214            if (message.getConversation() instanceof Conversation
4215                    && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4216                Jid tcp = message.getTrueCounterpart();
4217                Jid user = message.getCounterpart();
4218                if (user != null && !user.isBareJid()) {
4219                    final MucOptions mucOptions =
4220                            ((Conversation) message.getConversation()).getMucOptions();
4221                    if (mucOptions.participating()
4222                            || ((Conversation) message.getConversation()).getNextCounterpart()
4223                                    != null) {
4224                        MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4225                        MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4226                        if (mucUser == null && tcpMucUser == null) {
4227                            Toast.makeText(
4228                                            getActivity(),
4229                                            activity.getString(
4230                                                    R.string.user_has_left_conference,
4231                                                    user.getResource()),
4232                                            Toast.LENGTH_SHORT)
4233                                    .show();
4234                        }
4235                        highlightInConference(mucUser == null ? (tcpMucUser == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4236                    } else {
4237                        Toast.makeText(
4238                                        getActivity(),
4239                                        R.string.you_are_not_participating,
4240                                        Toast.LENGTH_SHORT)
4241                                .show();
4242                    }
4243                }
4244            }
4245        }
4246    }
4247
4248    private Activity requireActivity() {
4249        final Activity activity = getActivity();
4250        if (activity == null) {
4251            throw new IllegalStateException("Activity not attached");
4252        }
4253        return activity;
4254    }
4255}