ConversationFragment.java

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