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 = m.isDeleted();
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 && !deleted) {
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() || message.hasFileOnRemoteHost()) {
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.setDeleted(true);
1642                activity.xmppConnectionService.updateMessage(message, false);
1643                activity.onConversationsListItemUpdated();
1644                refresh();
1645            }
1646        });
1647        builder.create().show();
1648
1649    }
1650
1651    private void resendMessage(final Message message) {
1652        if (message.isFileOrImage()) {
1653            if (!(message.getConversation() instanceof Conversation)) {
1654                return;
1655            }
1656            final Conversation conversation = (Conversation) message.getConversation();
1657            DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1658            if (file.exists()) {
1659                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1660                if (!message.hasFileOnRemoteHost()
1661                        && xmppConnection != null
1662                        && conversation.getMode() == Conversational.MODE_SINGLE
1663                        && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1664                    activity.selectPresence(conversation, () -> {
1665                        message.setCounterpart(conversation.getNextCounterpart());
1666                        activity.xmppConnectionService.resendFailedMessages(message);
1667                        new Handler().post(() -> {
1668                            int size = messageList.size();
1669                            this.binding.messagesView.setSelection(size - 1);
1670                        });
1671                    });
1672                    return;
1673                }
1674            } else {
1675                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1676                //TODO check if we have storage permission
1677                message.setDeleted(true);
1678                activity.xmppConnectionService.updateMessage(message, false);
1679                activity.onConversationsListItemUpdated();
1680                refresh();
1681                return;
1682            }
1683        }
1684        activity.xmppConnectionService.resendFailedMessages(message);
1685        new Handler().post(() -> {
1686            int size = messageList.size();
1687            this.binding.messagesView.setSelection(size - 1);
1688        });
1689    }
1690
1691    private void cancelTransmission(Message message) {
1692        Transferable transferable = message.getTransferable();
1693        if (transferable != null) {
1694            transferable.cancel();
1695        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1696            activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
1697        }
1698    }
1699
1700    private void retryDecryption(Message message) {
1701        message.setEncryption(Message.ENCRYPTION_PGP);
1702        activity.onConversationsListItemUpdated();
1703        refresh();
1704        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1705    }
1706
1707    public void privateMessageWith(final Jid counterpart) {
1708        if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1709            activity.xmppConnectionService.sendChatState(conversation);
1710        }
1711        this.binding.textinput.setText("");
1712        this.conversation.setNextCounterpart(counterpart);
1713        updateChatMsgHint();
1714        updateSendButton();
1715        updateEditablity();
1716    }
1717
1718    private void correctMessage(Message message) {
1719        while (message.mergeable(message.next())) {
1720            message = message.next();
1721        }
1722        this.conversation.setCorrectingMessage(message);
1723        final Editable editable = binding.textinput.getText();
1724        this.conversation.setDraftMessage(editable.toString());
1725        this.binding.textinput.setText("");
1726        this.binding.textinput.append(message.getBody());
1727
1728    }
1729
1730    private void highlightInConference(String nick) {
1731        final Editable editable = this.binding.textinput.getText();
1732        String oldString = editable.toString().trim();
1733        final int pos = this.binding.textinput.getSelectionStart();
1734        if (oldString.isEmpty() || pos == 0) {
1735            editable.insert(0, nick + ": ");
1736        } else {
1737            final char before = editable.charAt(pos - 1);
1738            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1739            if (before == '\n') {
1740                editable.insert(pos, nick + ": ");
1741            } else {
1742                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1743                    if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1744                        editable.insert(pos - 2, ", " + nick);
1745                        return;
1746                    }
1747                }
1748                editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1749                if (Character.isWhitespace(after)) {
1750                    this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1751                }
1752            }
1753        }
1754    }
1755
1756    @Override
1757    public void startActivityForResult(Intent intent, int requestCode) {
1758        final Activity activity = getActivity();
1759        if (activity instanceof ConversationsActivity) {
1760            ((ConversationsActivity) activity).clearPendingViewIntent();
1761        }
1762        super.startActivityForResult(intent, requestCode);
1763    }
1764
1765    @Override
1766    public void onSaveInstanceState(Bundle outState) {
1767        super.onSaveInstanceState(outState);
1768        if (conversation != null) {
1769            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1770            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1771            final Uri uri = pendingTakePhotoUri.peek();
1772            if (uri != null) {
1773                outState.putString(STATE_PHOTO_URI, uri.toString());
1774            }
1775            final ScrollState scrollState = getScrollPosition();
1776            if (scrollState != null) {
1777                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1778            }
1779            final ArrayList<Attachment> attachments = mediaPreviewAdapter == null ? new ArrayList<>() : mediaPreviewAdapter.getAttachments();
1780            if (attachments.size() > 0) {
1781                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
1782            }
1783        }
1784    }
1785
1786    @Override
1787    public void onActivityCreated(Bundle savedInstanceState) {
1788        super.onActivityCreated(savedInstanceState);
1789        if (savedInstanceState == null) {
1790            return;
1791        }
1792        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1793        ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
1794        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1795        if (uuid != null) {
1796            QuickLoader.set(uuid);
1797            this.pendingConversationsUuid.push(uuid);
1798            if (attachments != null && attachments.size() > 0) {
1799                this.pendingMediaPreviews.push(attachments);
1800            }
1801            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1802            if (takePhotoUri != null) {
1803                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1804            }
1805            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1806        }
1807    }
1808
1809    @Override
1810    public void onStart() {
1811        super.onStart();
1812        if (this.reInitRequiredOnStart && this.conversation != null) {
1813            final Bundle extras = pendingExtras.pop();
1814            reInit(this.conversation, extras != null);
1815            if (extras != null) {
1816                processExtras(extras);
1817            }
1818        } else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1819            final String uuid = pendingConversationsUuid.pop();
1820            Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
1821            if (uuid != null) {
1822                findAndReInitByUuidOrArchive(uuid);
1823            }
1824        }
1825    }
1826
1827    @Override
1828    public void onStop() {
1829        super.onStop();
1830        final Activity activity = getActivity();
1831        messageListAdapter.unregisterListenerInAudioPlayer();
1832        if (activity == null || !activity.isChangingConfigurations()) {
1833            hideSoftKeyboard(activity);
1834            messageListAdapter.stopAudioPlayer();
1835        }
1836        if (this.conversation != null) {
1837            final String msg = this.binding.textinput.getText().toString();
1838            storeNextMessage(msg);
1839            updateChatState(this.conversation, msg);
1840            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1841        }
1842        this.reInitRequiredOnStart = true;
1843    }
1844
1845    private void updateChatState(final Conversation conversation, final String msg) {
1846        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1847        Account.State status = conversation.getAccount().getStatus();
1848        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1849            activity.xmppConnectionService.sendChatState(conversation);
1850        }
1851    }
1852
1853    private void saveMessageDraftStopAudioPlayer() {
1854        final Conversation previousConversation = this.conversation;
1855        if (this.activity == null || this.binding == null || previousConversation == null) {
1856            return;
1857        }
1858        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1859        final String msg = this.binding.textinput.getText().toString();
1860        storeNextMessage(msg);
1861        updateChatState(this.conversation, msg);
1862        messageListAdapter.stopAudioPlayer();
1863        mediaPreviewAdapter.clearPreviews();
1864        toggleInputMethod();
1865    }
1866
1867    public void reInit(Conversation conversation, Bundle extras) {
1868        QuickLoader.set(conversation.getUuid());
1869        this.saveMessageDraftStopAudioPlayer();
1870        this.clearPending();
1871        if (this.reInit(conversation, extras != null)) {
1872            if (extras != null) {
1873                processExtras(extras);
1874            }
1875            this.reInitRequiredOnStart = false;
1876        } else {
1877            this.reInitRequiredOnStart = true;
1878            pendingExtras.push(extras);
1879        }
1880        resetUnreadMessagesCount();
1881    }
1882
1883    private void reInit(Conversation conversation) {
1884        reInit(conversation, false);
1885    }
1886
1887    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1888        if (conversation == null) {
1889            return false;
1890        }
1891        this.conversation = conversation;
1892        //once we set the conversation all is good and it will automatically do the right thing in onStart()
1893        if (this.activity == null || this.binding == null) {
1894            return false;
1895        }
1896
1897        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1898            activity.onConversationArchived(this.conversation);
1899            return false;
1900        }
1901
1902        stopScrolling();
1903        Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1904
1905        if (this.conversation.isRead() && hasExtras) {
1906            Log.d(Config.LOGTAG, "trimming conversation");
1907            this.conversation.trim();
1908        }
1909
1910        setupIme();
1911
1912        final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1913
1914        this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1915        this.binding.textinput.setKeyboardListener(null);
1916        this.binding.textinput.setText("");
1917        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
1918        if (participating) {
1919            this.binding.textinput.append(this.conversation.getNextMessage());
1920        }
1921        this.binding.textinput.setKeyboardListener(this);
1922        messageListAdapter.updatePreferences();
1923        refresh(false);
1924        this.conversation.messagesLoaded.set(true);
1925        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1926
1927        if (hasExtras || scrolledToBottomAndNoPending) {
1928            resetUnreadMessagesCount();
1929            synchronized (this.messageList) {
1930                Log.d(Config.LOGTAG, "jump to first unread message");
1931                final Message first = conversation.getFirstUnreadMessage();
1932                final int bottom = Math.max(0, this.messageList.size() - 1);
1933                final int pos;
1934                final boolean jumpToBottom;
1935                if (first == null) {
1936                    pos = bottom;
1937                    jumpToBottom = true;
1938                } else {
1939                    int i = getIndexOf(first.getUuid(), this.messageList);
1940                    pos = i < 0 ? bottom : i;
1941                    jumpToBottom = false;
1942                }
1943                setSelection(pos, jumpToBottom);
1944            }
1945        }
1946
1947
1948        this.binding.messagesView.post(this::fireReadEvent);
1949        //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
1950        activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1951        return true;
1952    }
1953
1954    private void resetUnreadMessagesCount() {
1955        lastMessageUuid = null;
1956        hideUnreadMessagesCount();
1957    }
1958
1959    private void hideUnreadMessagesCount() {
1960        if (this.binding == null) {
1961            return;
1962        }
1963        this.binding.scrollToBottomButton.setEnabled(false);
1964        this.binding.scrollToBottomButton.hide();
1965        this.binding.unreadCountCustomView.setVisibility(View.GONE);
1966    }
1967
1968    private void setSelection(int pos, boolean jumpToBottom) {
1969        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
1970        this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
1971        this.binding.messagesView.post(this::fireReadEvent);
1972    }
1973
1974
1975    private boolean scrolledToBottom() {
1976        return this.binding != null && scrolledToBottom(this.binding.messagesView);
1977    }
1978
1979    private void processExtras(Bundle extras) {
1980        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
1981        final String text = extras.getString(Intent.EXTRA_TEXT);
1982        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
1983        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
1984        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1985        final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
1986        final List<Uri> uris = extractUris(extras);
1987        if (uris != null && uris.size() > 0) {
1988            final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
1989            mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));
1990            toggleInputMethod();
1991            return;
1992        }
1993        if (nick != null) {
1994            if (pm) {
1995                Jid jid = conversation.getJid();
1996                try {
1997                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
1998                    privateMessageWith(next);
1999                } catch (final IllegalArgumentException ignored) {
2000                    //do nothing
2001                }
2002            } else {
2003                final MucOptions mucOptions = conversation.getMucOptions();
2004                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2005                    highlightInConference(nick);
2006                }
2007            }
2008        } else {
2009            if (text != null && asQuote) {
2010                quoteText(text);
2011            } else {
2012                appendText(text, doNotAppend);
2013            }
2014        }
2015        final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2016        if (message != null) {
2017            startDownloadable(message);
2018        }
2019    }
2020
2021    private List<Uri> extractUris(Bundle extras) {
2022        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2023        if (uris != null) {
2024            return uris;
2025        }
2026        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2027        if (uri != null) {
2028            return Collections.singletonList(uri);
2029        } else {
2030            return null;
2031        }
2032    }
2033
2034    private List<Uri> cleanUris(List<Uri> uris) {
2035        Iterator<Uri> iterator = uris.iterator();
2036        while (iterator.hasNext()) {
2037            final Uri uri = iterator.next();
2038            if (FileBackend.weOwnFile(getActivity(), uri)) {
2039                iterator.remove();
2040                Toast.makeText(getActivity(), R.string.security_violation_not_attaching_file, Toast.LENGTH_SHORT).show();
2041            }
2042        }
2043        return uris;
2044    }
2045
2046    private boolean showBlockSubmenu(View view) {
2047        final Jid jid = conversation.getJid();
2048        final boolean showReject = !conversation.isWithStranger() && conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2049        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2050        popupMenu.inflate(R.menu.block);
2051        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2052        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2053        popupMenu.setOnMenuItemClickListener(menuItem -> {
2054            Blockable blockable;
2055            switch (menuItem.getItemId()) {
2056                case R.id.reject:
2057                    activity.xmppConnectionService.stopPresenceUpdatesTo(conversation.getContact());
2058                    updateSnackBar(conversation);
2059                    return true;
2060                case R.id.block_domain:
2061                    blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
2062                    break;
2063                default:
2064                    blockable = conversation;
2065            }
2066            BlockContactDialog.show(activity, blockable);
2067            return true;
2068        });
2069        popupMenu.show();
2070        return true;
2071    }
2072
2073    private void updateSnackBar(final Conversation conversation) {
2074        final Account account = conversation.getAccount();
2075        final XmppConnection connection = account.getXmppConnection();
2076        final int mode = conversation.getMode();
2077        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2078        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2079            return;
2080        }
2081        if (account.getStatus() == Account.State.DISABLED) {
2082            showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
2083        } else if (conversation.isBlocked()) {
2084            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2085        } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2086            showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
2087        } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2088            showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
2089        } else if (mode == Conversation.MODE_MULTI
2090                && !conversation.getMucOptions().online()
2091                && account.getStatus() == Account.State.ONLINE) {
2092            switch (conversation.getMucOptions().getError()) {
2093                case NICK_IN_USE:
2094                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2095                    break;
2096                case NO_RESPONSE:
2097                    showSnackbar(R.string.joining_conference, 0, null);
2098                    break;
2099                case SERVER_NOT_FOUND:
2100                    if (conversation.receivedMessagesCount() > 0) {
2101                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2102                    } else {
2103                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2104                    }
2105                    break;
2106                case REMOTE_SERVER_TIMEOUT:
2107                    if (conversation.receivedMessagesCount() > 0) {
2108                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2109                    } else {
2110                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2111                    }
2112                    break;
2113                case PASSWORD_REQUIRED:
2114                    showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2115                    break;
2116                case BANNED:
2117                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2118                    break;
2119                case MEMBERS_ONLY:
2120                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2121                    break;
2122                case RESOURCE_CONSTRAINT:
2123                    showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2124                    break;
2125                case KICKED:
2126                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2127                    break;
2128                case UNKNOWN:
2129                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2130                    break;
2131                case INVALID_NICK:
2132                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2133                case SHUTDOWN:
2134                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2135                    break;
2136                case DESTROYED:
2137                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2138                    break;
2139                case NON_ANONYMOUS:
2140                    showSnackbar(R.string.group_chat_will_make_your_jabber_id_public, R.string.join, acceptJoin);
2141                    break;
2142                default:
2143                    hideSnackbar();
2144                    break;
2145            }
2146        } else if (account.hasPendingPgpIntent(conversation)) {
2147            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2148        } else if (connection != null
2149                && connection.getFeatures().blocking()
2150                && conversation.countMessages() != 0
2151                && !conversation.isBlocked()
2152                && conversation.isWithStranger()) {
2153            showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2154        } else {
2155            hideSnackbar();
2156        }
2157    }
2158
2159    @Override
2160    public void refresh() {
2161        if (this.binding == null) {
2162            Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2163            return;
2164        }
2165        if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2166            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2167                activity.onConversationArchived(this.conversation);
2168                return;
2169            }
2170        }
2171        this.refresh(true);
2172    }
2173
2174    private void refresh(boolean notifyConversationRead) {
2175        synchronized (this.messageList) {
2176            if (this.conversation != null) {
2177                conversation.populateWithMessages(this.messageList);
2178                updateSnackBar(conversation);
2179                updateStatusMessages();
2180                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2181                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2182                    binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2183                }
2184                this.messageListAdapter.notifyDataSetChanged();
2185                updateChatMsgHint();
2186                if (notifyConversationRead && activity != null) {
2187                    binding.messagesView.post(this::fireReadEvent);
2188                }
2189                updateSendButton();
2190                updateEditablity();
2191                activity.invalidateOptionsMenu();
2192            }
2193        }
2194    }
2195
2196    protected void messageSent() {
2197        mSendingPgpMessage.set(false);
2198        this.binding.textinput.setText("");
2199        if (conversation.setCorrectingMessage(null)) {
2200            this.binding.textinput.append(conversation.getDraftMessage());
2201            conversation.setDraftMessage(null);
2202        }
2203        storeNextMessage();
2204        updateChatMsgHint();
2205        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2206        final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2207        if (prefScrollToBottom || scrolledToBottom()) {
2208            new Handler().post(() -> {
2209                int size = messageList.size();
2210                this.binding.messagesView.setSelection(size - 1);
2211            });
2212        }
2213    }
2214
2215    private boolean storeNextMessage() {
2216        return storeNextMessage(this.binding.textinput.getText().toString());
2217    }
2218
2219    private boolean storeNextMessage(String msg) {
2220        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2221        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) {
2222            this.activity.xmppConnectionService.updateConversation(this.conversation);
2223            return true;
2224        }
2225        return false;
2226    }
2227
2228    public void doneSendingPgpMessage() {
2229        mSendingPgpMessage.set(false);
2230    }
2231
2232    public long getMaxHttpUploadSize(Conversation conversation) {
2233        final XmppConnection connection = conversation.getAccount().getXmppConnection();
2234        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2235    }
2236
2237    private void updateEditablity() {
2238        boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2239        this.binding.textinput.setFocusable(canWrite);
2240        this.binding.textinput.setFocusableInTouchMode(canWrite);
2241        this.binding.textSendButton.setEnabled(canWrite);
2242        this.binding.textinput.setCursorVisible(canWrite);
2243        this.binding.textinput.setEnabled(canWrite);
2244    }
2245
2246    public void updateSendButton() {
2247        boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2248        boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2249        final Conversation c = this.conversation;
2250        final Presence.Status status;
2251        final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2252        final SendButtonAction action;
2253        if (hasAttachments) {
2254            action = SendButtonAction.TEXT;
2255        } else {
2256            action = SendButtonTool.getAction(getActivity(), c, text);
2257        }
2258        if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2259            if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2260                status = Presence.Status.OFFLINE;
2261            } else if (c.getMode() == Conversation.MODE_SINGLE) {
2262                status = c.getContact().getShownStatus();
2263            } else {
2264                status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2265            }
2266        } else {
2267            status = Presence.Status.OFFLINE;
2268        }
2269        this.binding.textSendButton.setTag(action);
2270        this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2271    }
2272
2273    protected void updateDateSeparators() {
2274        synchronized (this.messageList) {
2275            DateSeparator.addAll(this.messageList);
2276        }
2277    }
2278
2279    protected void updateStatusMessages() {
2280        updateDateSeparators();
2281        synchronized (this.messageList) {
2282            if (showLoadMoreMessages(conversation)) {
2283                this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2284            }
2285            if (conversation.getMode() == Conversation.MODE_SINGLE) {
2286                ChatState state = conversation.getIncomingChatState();
2287                if (state == ChatState.COMPOSING) {
2288                    this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2289                } else if (state == ChatState.PAUSED) {
2290                    this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2291                } else {
2292                    for (int i = this.messageList.size() - 1; i >= 0; --i) {
2293                        final Message message = this.messageList.get(i);
2294                        if (message.getType() != Message.TYPE_STATUS) {
2295                            if (message.getStatus() == Message.STATUS_RECEIVED) {
2296                                return;
2297                            } else {
2298                                if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
2299                                    this.messageList.add(i + 1,
2300                                            Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2301                                    return;
2302                                }
2303                            }
2304                        }
2305                    }
2306                }
2307            } else {
2308                final MucOptions mucOptions = conversation.getMucOptions();
2309                final List<MucOptions.User> allUsers = mucOptions.getUsers();
2310                final Set<ReadByMarker> addedMarkers = new HashSet<>();
2311                ChatState state = ChatState.COMPOSING;
2312                List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2313                if (users.size() == 0) {
2314                    state = ChatState.PAUSED;
2315                    users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2316                }
2317                if (mucOptions.isPrivateAndNonAnonymous()) {
2318                    for (int i = this.messageList.size() - 1; i >= 0; --i) {
2319                        final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2320                        final List<MucOptions.User> shownMarkers = new ArrayList<>();
2321                        for (ReadByMarker marker : markersForMessage) {
2322                            if (!ReadByMarker.contains(marker, addedMarkers)) {
2323                                addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2324                                MucOptions.User user = mucOptions.findUser(marker);
2325                                if (user != null && !users.contains(user)) {
2326                                    shownMarkers.add(user);
2327                                }
2328                            }
2329                        }
2330                        final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2331                        final Message statusMessage;
2332                        final int size = shownMarkers.size();
2333                        if (size > 1) {
2334                            final String body;
2335                            if (size <= 4) {
2336                                body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2337                            } else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) {
2338                                body = getString(R.string.everyone_has_read_up_to_this_point);
2339                            } else {
2340                                body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2341                            }
2342                            statusMessage = Message.createStatusMessage(conversation, body);
2343                            statusMessage.setCounterparts(shownMarkers);
2344                        } else if (size == 1) {
2345                            statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2346                            statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2347                            statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2348                        } else {
2349                            statusMessage = null;
2350                        }
2351                        if (statusMessage != null) {
2352                            this.messageList.add(i + 1, statusMessage);
2353                        }
2354                        addedMarkers.add(markerForSender);
2355                        if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2356                            break;
2357                        }
2358                    }
2359                }
2360                if (users.size() > 0) {
2361                    Message statusMessage;
2362                    if (users.size() == 1) {
2363                        MucOptions.User user = users.get(0);
2364                        int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2365                        statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2366                        statusMessage.setTrueCounterpart(user.getRealJid());
2367                        statusMessage.setCounterpart(user.getFullJid());
2368                    } else {
2369                        int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2370                        statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2371                        statusMessage.setCounterparts(users);
2372                    }
2373                    this.messageList.add(statusMessage);
2374                }
2375
2376            }
2377        }
2378    }
2379
2380    private void stopScrolling() {
2381        long now = SystemClock.uptimeMillis();
2382        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2383        binding.messagesView.dispatchTouchEvent(cancel);
2384    }
2385
2386    private boolean showLoadMoreMessages(final Conversation c) {
2387        if (activity == null || activity.xmppConnectionService == null) {
2388            return false;
2389        }
2390        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2391        final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2392        return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2393    }
2394
2395    private boolean hasMamSupport(final Conversation c) {
2396        if (c.getMode() == Conversation.MODE_SINGLE) {
2397            final XmppConnection connection = c.getAccount().getXmppConnection();
2398            return connection != null && connection.getFeatures().mam();
2399        } else {
2400            return c.getMucOptions().mamSupport();
2401        }
2402    }
2403
2404    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2405        showSnackbar(message, action, clickListener, null);
2406    }
2407
2408    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2409        this.binding.snackbar.setVisibility(View.VISIBLE);
2410        this.binding.snackbar.setOnClickListener(null);
2411        this.binding.snackbarMessage.setText(message);
2412        this.binding.snackbarMessage.setOnClickListener(null);
2413        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2414        if (action != 0) {
2415            this.binding.snackbarAction.setText(action);
2416        }
2417        this.binding.snackbarAction.setOnClickListener(clickListener);
2418        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2419    }
2420
2421    protected void hideSnackbar() {
2422        this.binding.snackbar.setVisibility(View.GONE);
2423    }
2424
2425    protected void sendMessage(Message message) {
2426        activity.xmppConnectionService.sendMessage(message);
2427        messageSent();
2428    }
2429
2430    protected void sendPgpMessage(final Message message) {
2431        final XmppConnectionService xmppService = activity.xmppConnectionService;
2432        final Contact contact = message.getConversation().getContact();
2433        if (!activity.hasPgp()) {
2434            activity.showInstallPgpDialog();
2435            return;
2436        }
2437        if (conversation.getAccount().getPgpSignature() == null) {
2438            activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2439            return;
2440        }
2441        if (!mSendingPgpMessage.compareAndSet(false, true)) {
2442            Log.d(Config.LOGTAG, "sending pgp message already in progress");
2443        }
2444        if (conversation.getMode() == Conversation.MODE_SINGLE) {
2445            if (contact.getPgpKeyId() != 0) {
2446                xmppService.getPgpEngine().hasKey(contact,
2447                        new UiCallback<Contact>() {
2448
2449                            @Override
2450                            public void userInputRequried(PendingIntent pi, Contact contact) {
2451                                startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2452                            }
2453
2454                            @Override
2455                            public void success(Contact contact) {
2456                                encryptTextMessage(message);
2457                            }
2458
2459                            @Override
2460                            public void error(int error, Contact contact) {
2461                                activity.runOnUiThread(() -> Toast.makeText(activity,
2462                                        R.string.unable_to_connect_to_keychain,
2463                                        Toast.LENGTH_SHORT
2464                                ).show());
2465                                mSendingPgpMessage.set(false);
2466                            }
2467                        });
2468
2469            } else {
2470                showNoPGPKeyDialog(false, (dialog, which) -> {
2471                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2472                    xmppService.updateConversation(conversation);
2473                    message.setEncryption(Message.ENCRYPTION_NONE);
2474                    xmppService.sendMessage(message);
2475                    messageSent();
2476                });
2477            }
2478        } else {
2479            if (conversation.getMucOptions().pgpKeysInUse()) {
2480                if (!conversation.getMucOptions().everybodyHasKeys()) {
2481                    Toast warning = Toast
2482                            .makeText(getActivity(),
2483                                    R.string.missing_public_keys,
2484                                    Toast.LENGTH_LONG);
2485                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2486                    warning.show();
2487                }
2488                encryptTextMessage(message);
2489            } else {
2490                showNoPGPKeyDialog(true, (dialog, which) -> {
2491                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2492                    message.setEncryption(Message.ENCRYPTION_NONE);
2493                    xmppService.updateConversation(conversation);
2494                    xmppService.sendMessage(message);
2495                    messageSent();
2496                });
2497            }
2498        }
2499    }
2500
2501    public void encryptTextMessage(Message message) {
2502        activity.xmppConnectionService.getPgpEngine().encrypt(message,
2503                new UiCallback<Message>() {
2504
2505                    @Override
2506                    public void userInputRequried(PendingIntent pi, Message message) {
2507                        startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2508                    }
2509
2510                    @Override
2511                    public void success(Message message) {
2512                        //TODO the following two call can be made before the callback
2513                        getActivity().runOnUiThread(() -> messageSent());
2514                    }
2515
2516                    @Override
2517                    public void error(final int error, Message message) {
2518                        getActivity().runOnUiThread(() -> {
2519                            doneSendingPgpMessage();
2520                            Toast.makeText(getActivity(), error == 0 ? R.string.unable_to_connect_to_keychain : error, Toast.LENGTH_SHORT).show();
2521                        });
2522
2523                    }
2524                });
2525    }
2526
2527    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2528        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2529        builder.setIconAttribute(android.R.attr.alertDialogIcon);
2530        if (plural) {
2531            builder.setTitle(getString(R.string.no_pgp_keys));
2532            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2533        } else {
2534            builder.setTitle(getString(R.string.no_pgp_key));
2535            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2536        }
2537        builder.setNegativeButton(getString(R.string.cancel), null);
2538        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2539        builder.create().show();
2540    }
2541
2542    public void appendText(String text, final boolean doNotAppend) {
2543        if (text == null) {
2544            return;
2545        }
2546        final Editable editable = this.binding.textinput.getText();
2547        String previous = editable == null ? "" : editable.toString();
2548        if (doNotAppend && !TextUtils.isEmpty(previous)) {
2549            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG).show();
2550            return;
2551        }
2552        if (UIHelper.isLastLineQuote(previous)) {
2553            text = '\n' + text;
2554        } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
2555            text = " " + text;
2556        }
2557        this.binding.textinput.append(text);
2558    }
2559
2560    @Override
2561    public boolean onEnterPressed() {
2562        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2563        final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2564        if (enterIsSend) {
2565            sendMessage();
2566            return true;
2567        } else {
2568            return false;
2569        }
2570    }
2571
2572    @Override
2573    public void onTypingStarted() {
2574        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2575        if (service == null) {
2576            return;
2577        }
2578        Account.State status = conversation.getAccount().getStatus();
2579        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2580            service.sendChatState(conversation);
2581        }
2582        updateSendButton();
2583    }
2584
2585    @Override
2586    public void onTypingStopped() {
2587        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2588        if (service == null) {
2589            return;
2590        }
2591        Account.State status = conversation.getAccount().getStatus();
2592        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2593            service.sendChatState(conversation);
2594        }
2595    }
2596
2597    @Override
2598    public void onTextDeleted() {
2599        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2600        if (service == null) {
2601            return;
2602        }
2603        Account.State status = conversation.getAccount().getStatus();
2604        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2605            service.sendChatState(conversation);
2606        }
2607        if (storeNextMessage()) {
2608            activity.onConversationsListItemUpdated();
2609        }
2610        updateSendButton();
2611    }
2612
2613    @Override
2614    public void onTextChanged() {
2615        if (conversation != null && conversation.getCorrectingMessage() != null) {
2616            updateSendButton();
2617        }
2618    }
2619
2620    @Override
2621    public boolean onTabPressed(boolean repeated) {
2622        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2623            return false;
2624        }
2625        if (repeated) {
2626            completionIndex++;
2627        } else {
2628            lastCompletionLength = 0;
2629            completionIndex = 0;
2630            final String content = this.binding.textinput.getText().toString();
2631            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2632            int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2633            firstWord = start == 0;
2634            incomplete = content.substring(start, lastCompletionCursor);
2635        }
2636        List<String> completions = new ArrayList<>();
2637        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2638            String name = user.getName();
2639            if (name != null && name.startsWith(incomplete)) {
2640                completions.add(name + (firstWord ? ": " : " "));
2641            }
2642        }
2643        Collections.sort(completions);
2644        if (completions.size() > completionIndex) {
2645            String completion = completions.get(completionIndex).substring(incomplete.length());
2646            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2647            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2648            lastCompletionLength = completion.length();
2649        } else {
2650            completionIndex = -1;
2651            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2652            lastCompletionLength = 0;
2653        }
2654        return true;
2655    }
2656
2657    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2658        try {
2659            getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2660        } catch (final SendIntentException ignored) {
2661        }
2662    }
2663
2664    @Override
2665    public void onBackendConnected() {
2666        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2667        String uuid = pendingConversationsUuid.pop();
2668        if (uuid != null) {
2669            if (!findAndReInitByUuidOrArchive(uuid)) {
2670                return;
2671            }
2672        } else {
2673            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2674                clearPending();
2675                activity.onConversationArchived(conversation);
2676                return;
2677            }
2678        }
2679        ActivityResult activityResult = postponedActivityResult.pop();
2680        if (activityResult != null) {
2681            handleActivityResult(activityResult);
2682        }
2683        clearPending();
2684    }
2685
2686    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2687        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2688        if (conversation == null) {
2689            clearPending();
2690            activity.onConversationArchived(null);
2691            return false;
2692        }
2693        reInit(conversation);
2694        ScrollState scrollState = pendingScrollState.pop();
2695        String lastMessageUuid = pendingLastMessageUuid.pop();
2696        List<Attachment> attachments = pendingMediaPreviews.pop();
2697        if (scrollState != null) {
2698            setScrollPosition(scrollState, lastMessageUuid);
2699        }
2700        if (attachments != null && attachments.size() > 0) {
2701            Log.d(Config.LOGTAG, "had attachments on restore");
2702            mediaPreviewAdapter.addMediaPreviews(attachments);
2703            toggleInputMethod();
2704        }
2705        return true;
2706    }
2707
2708    private void clearPending() {
2709        if (postponedActivityResult.clear()) {
2710            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2711        }
2712        if (pendingScrollState.clear()) {
2713            Log.e(Config.LOGTAG, "cleared scroll state");
2714        }
2715        if (pendingTakePhotoUri.clear()) {
2716            Log.e(Config.LOGTAG, "cleared pending photo uri");
2717        }
2718        if (pendingConversationsUuid.clear()) {
2719            Log.e(Config.LOGTAG,"cleared pending conversations uuid");
2720        }
2721        if (pendingMediaPreviews.clear()) {
2722            Log.e(Config.LOGTAG,"cleared pending media previews");
2723        }
2724    }
2725
2726    public Conversation getConversation() {
2727        return conversation;
2728    }
2729
2730    @Override
2731    public void onContactPictureLongClicked(View v, final Message message) {
2732        if (message.getStatus() <= Message.STATUS_RECEIVED) {
2733            final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
2734            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
2735                final Jid cp = message.getCounterpart();
2736                if (cp == null || cp.isBareJid()) {
2737                    return;
2738                }
2739                Jid tcp = message.getTrueCounterpart();
2740                User userByRealJid = tcp != null ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp) : null;
2741                final User user = userByRealJid != null ? userByRealJid : conversation.getMucOptions().findUserByFullJid(cp);
2742                popupMenu.inflate(R.menu.muc_details_context);
2743                final Menu menu = popupMenu.getMenu();
2744                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(activity, menu, conversation, user);
2745                popupMenu.setOnMenuItemClickListener(menuItem -> MucDetailsContextMenuHelper.onContextItemSelected(menuItem, user, conversation, activity));
2746            } else {
2747                final Contact contact = message.getContact();
2748                if (contact.isSelf()) {
2749                    activity.showQrCode(conversation.getAccount().getShareableUri());
2750                    return;
2751                }
2752                popupMenu.inflate(R.menu.one_on_one_context);
2753                popupMenu.setOnMenuItemClickListener(item -> {
2754                    switch (item.getItemId()) {
2755                        case R.id.action_contact_details:
2756                            String fingerprint;
2757                            if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2758                                fingerprint = "pgp";
2759                            } else {
2760                                fingerprint = message.getFingerprint();
2761                            }
2762                            activity.switchToContactDetails(message.getContact(), fingerprint);
2763                            break;
2764                        case R.id.action_show_qr_code:
2765                            activity.showQrCode("xmpp:" + message.getContact().getJid().asBareJid().toEscapedString());
2766                            break;
2767                    }
2768                    return true;
2769                });
2770            }
2771            popupMenu.show();
2772        } else {
2773            activity.showQrCode(conversation.getAccount().getShareableUri());
2774        }
2775    }
2776
2777    @Override
2778    public void onContactPictureClicked(Message message) {
2779        String fingerprint;
2780        if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2781            fingerprint = "pgp";
2782        } else {
2783            fingerprint = message.getFingerprint();
2784        }
2785        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
2786        if (received) {
2787            if (message.getConversation() instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) {
2788                Jid tcp = message.getTrueCounterpart();
2789                Jid user = message.getCounterpart();
2790                if (user != null && !user.isBareJid()) {
2791                    final MucOptions mucOptions = ((Conversation) message.getConversation()).getMucOptions();
2792                    if (mucOptions.participating() || ((Conversation) message.getConversation()).getNextCounterpart() != null) {
2793                        if (!mucOptions.isUserInRoom(user) && mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid()) == null) {
2794                            Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
2795                        }
2796                        highlightInConference(user.getResource());
2797                    } else {
2798                        Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
2799                    }
2800                }
2801                return;
2802            } else {
2803                if (!message.getContact().isSelf()) {
2804                    activity.switchToContactDetails(message.getContact(), fingerprint);
2805                    return;
2806                }
2807            }
2808        }
2809        activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2810    }
2811}