ConversationFragment.java

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