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