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