ConversationFragment.java

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