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