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