ConversationFragment.java

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