ConversationFragment.java

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