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            case ATTACHMENT_CHOICE_TAKE_PHOTO:
 906                if (pendingTakePhotoUri.clear()) {
 907                    Log.d(Config.LOGTAG,"cleared pending photo uri after negative activity result");
 908                }
 909                break;
 910        }
 911    }
 912
 913    @Override
 914    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
 915        super.onActivityResult(requestCode, resultCode, data);
 916        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
 917        if (activity != null && activity.xmppConnectionService != null) {
 918            handleActivityResult(activityResult);
 919        } else {
 920            this.postponedActivityResult.push(activityResult);
 921        }
 922    }
 923
 924    public void unblockConversation(final Blockable conversation) {
 925        activity.xmppConnectionService.sendUnblockRequest(conversation);
 926    }
 927
 928    @Override
 929    public void onAttach(Activity activity) {
 930        super.onAttach(activity);
 931        Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
 932        if (activity instanceof ConversationsActivity) {
 933            this.activity = (ConversationsActivity) activity;
 934        } else {
 935            throw new IllegalStateException("Trying to attach fragment to activity that is not the ConversationsActivity");
 936        }
 937    }
 938
 939    @Override
 940    public void onDetach() {
 941        super.onDetach();
 942        this.activity = null; //TODO maybe not a good idea since some callbacks really need it
 943    }
 944
 945    @Override
 946    public void onCreate(Bundle savedInstanceState) {
 947        super.onCreate(savedInstanceState);
 948        setHasOptionsMenu(true);
 949    }
 950
 951    @Override
 952    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
 953        menuInflater.inflate(R.menu.fragment_conversation, menu);
 954        final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 955        final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 956        final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 957        final MenuItem menuMute = menu.findItem(R.id.action_mute);
 958        final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 959
 960
 961        if (conversation != null) {
 962            if (conversation.getMode() == Conversation.MODE_MULTI) {
 963                menuContactDetails.setVisible(false);
 964                menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
 965            } else {
 966                menuContactDetails.setVisible(!this.conversation.withSelf());
 967                menuMucDetails.setVisible(false);
 968                final XmppConnectionService service = activity.xmppConnectionService;
 969                menuInviteContact.setVisible(service != null && service.findConferenceServer(conversation.getAccount()) != null);
 970            }
 971            if (conversation.isMuted()) {
 972                menuMute.setVisible(false);
 973            } else {
 974                menuUnmute.setVisible(false);
 975            }
 976            ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
 977            ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
 978        }
 979        super.onCreateOptionsMenu(menu, menuInflater);
 980    }
 981
 982    @Override
 983    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 984        this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
 985        binding.getRoot().setOnClickListener(null); //TODO why the fuck did we do this?
 986
 987        binding.textinput.addTextChangedListener(new StylingHelper.MessageEditorStyler(binding.textinput));
 988
 989        binding.textinput.setOnEditorActionListener(mEditorActionListener);
 990        binding.textinput.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
 991
 992        binding.textSendButton.setOnClickListener(this.mSendButtonListener);
 993
 994        binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
 995        binding.messagesView.setOnScrollListener(mOnScrollListener);
 996        binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
 997        mediaPreviewAdapter = new MediaPreviewAdapter(this);
 998        binding.mediaPreview.setAdapter(mediaPreviewAdapter);
 999        messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1000        messageListAdapter.setOnContactPictureClicked(message -> {
1001            String fingerprint;
1002            if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
1003                fingerprint = "pgp";
1004            } else {
1005                fingerprint = message.getFingerprint();
1006            }
1007            final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
1008            if (received) {
1009                if (message.getConversation() instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) {
1010                    Jid tcp = message.getTrueCounterpart();
1011                    Jid user = message.getCounterpart();
1012                    if (user != null && !user.isBareJid()) {
1013                        final MucOptions mucOptions = ((Conversation) message.getConversation()).getMucOptions();
1014                        if (mucOptions.participating() || ((Conversation) message.getConversation()).getNextCounterpart() != null) {
1015                            if (!mucOptions.isUserInRoom(user) && mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid()) == null) {
1016                                Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
1017                            }
1018                            highlightInConference(user.getResource());
1019                        } else {
1020                            Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
1021                        }
1022                    }
1023                    return;
1024                } else {
1025                    if (!message.getContact().isSelf()) {
1026                        activity.switchToContactDetails(message.getContact(), fingerprint);
1027                        return;
1028                    }
1029                }
1030            }
1031            activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
1032        });
1033        messageListAdapter.setOnContactPictureLongClicked((v, message) -> {
1034            if (message.getStatus() <= Message.STATUS_RECEIVED) {
1035                if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
1036                    Jid tcp = message.getTrueCounterpart();
1037                    Jid cp = message.getCounterpart();
1038                    if (cp != null && !cp.isBareJid()) {
1039                        User userByRealJid = tcp != null ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp) : null;
1040                        final User user = userByRealJid != null ? userByRealJid : conversation.getMucOptions().findUserByFullJid(cp);
1041                        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
1042                        popupMenu.inflate(R.menu.muc_details_context);
1043                        final Menu menu = popupMenu.getMenu();
1044                        MucDetailsContextMenuHelper.configureMucDetailsContextMenu(activity, menu, conversation, user);
1045                        popupMenu.setOnMenuItemClickListener(menuItem -> MucDetailsContextMenuHelper.onContextItemSelected(menuItem, user, conversation, activity));
1046                        popupMenu.show();
1047                    }
1048                }
1049            } else {
1050                activity.showQrCode(conversation.getAccount().getShareableUri());
1051            }
1052        });
1053        messageListAdapter.setOnQuoteListener(this::quoteText);
1054        binding.messagesView.setAdapter(messageListAdapter);
1055
1056        registerForContextMenu(binding.messagesView);
1057
1058        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1059            this.binding.textinput.setCustomInsertionActionModeCallback(new EditMessageActionModeCallback(this.binding.textinput));
1060        }
1061
1062        return binding.getRoot();
1063    }
1064
1065    private void quoteText(String text) {
1066        if (binding.textinput.isEnabled()) {
1067            binding.textinput.insertAsQuote(text);
1068            binding.textinput.requestFocus();
1069            InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1070            if (inputMethodManager != null) {
1071                inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1072            }
1073        }
1074    }
1075
1076    private void quoteMessage(Message message) {
1077        quoteText(MessageUtils.prepareQuote(message));
1078    }
1079
1080    @Override
1081    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1082        synchronized (this.messageList) {
1083            super.onCreateContextMenu(menu, v, menuInfo);
1084            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1085            this.selectedMessage = this.messageList.get(acmi.position);
1086            populateContextMenu(menu);
1087        }
1088    }
1089
1090    private void populateContextMenu(ContextMenu menu) {
1091        final Message m = this.selectedMessage;
1092        final Transferable t = m.getTransferable();
1093        Message relevantForCorrection = m;
1094        while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1095            relevantForCorrection = relevantForCorrection.next();
1096        }
1097        if (m.getType() != Message.TYPE_STATUS) {
1098
1099            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
1100                return;
1101            }
1102
1103            final boolean deleted = t != null && t instanceof TransferablePlaceholder;
1104            final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1105                    || m.getEncryption() == Message.ENCRYPTION_PGP;
1106            final boolean receiving = m.getStatus() == Message.STATUS_RECEIVED && (t instanceof JingleConnection || t instanceof HttpDownloadConnection);
1107            activity.getMenuInflater().inflate(R.menu.message_context, menu);
1108            menu.setHeaderTitle(R.string.message_options);
1109            MenuItem copyMessage = menu.findItem(R.id.copy_message);
1110            MenuItem copyLink = menu.findItem(R.id.copy_link);
1111            MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1112            MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1113            MenuItem correctMessage = menu.findItem(R.id.correct_message);
1114            MenuItem shareWith = menu.findItem(R.id.share_with);
1115            MenuItem sendAgain = menu.findItem(R.id.send_again);
1116            MenuItem copyUrl = menu.findItem(R.id.copy_url);
1117            MenuItem downloadFile = menu.findItem(R.id.download_file);
1118            MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1119            MenuItem deleteFile = menu.findItem(R.id.delete_file);
1120            MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1121            if (!m.isFileOrImage() && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
1122                copyMessage.setVisible(true);
1123                quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
1124                String body = m.getMergedBody().toString();
1125                if (ShareUtil.containsXmppUri(body)) {
1126                    copyLink.setTitle(R.string.copy_jabber_id);
1127                    copyLink.setVisible(true);
1128                } else if (Patterns.AUTOLINK_WEB_URL.matcher(body).find()) {
1129                    copyLink.setVisible(true);
1130                }
1131            }
1132            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
1133                retryDecryption.setVisible(true);
1134            }
1135            if (relevantForCorrection.getType() == Message.TYPE_TEXT
1136                    && relevantForCorrection.isLastCorrectableMessage()
1137                    && m.getConversation() instanceof Conversation
1138                    && (((Conversation) m.getConversation()).getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
1139                correctMessage.setVisible(true);
1140            }
1141            if ((m.isFileOrImage() && !deleted && !receiving) || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
1142                shareWith.setVisible(true);
1143            }
1144            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1145                sendAgain.setVisible(true);
1146            }
1147            if (m.hasFileOnRemoteHost()
1148                    || m.isGeoUri()
1149                    || m.treatAsDownloadable()
1150                    || (t != null && t instanceof HttpDownloadConnection)) {
1151                copyUrl.setVisible(true);
1152            }
1153            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1154                downloadFile.setVisible(true);
1155                downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
1156            }
1157            boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1158                    || m.getStatus() == Message.STATUS_UNSEND
1159                    || m.getStatus() == Message.STATUS_OFFERED;
1160            if ((t != null && !deleted) || waitingOfferedSending && m.needsUploading()) {
1161                cancelTransmission.setVisible(true);
1162            }
1163            if (m.isFileOrImage() && !deleted) {
1164                String path = m.getRelativeFilePath();
1165                if (path == null || !path.startsWith("/") || FileBackend.isInDirectoryThatShouldNotBeScanned(getActivity(), path)) {
1166                    deleteFile.setVisible(true);
1167                    deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1168                }
1169            }
1170            if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
1171                showErrorMessage.setVisible(true);
1172            }
1173        }
1174    }
1175
1176    @Override
1177    public boolean onContextItemSelected(MenuItem item) {
1178        switch (item.getItemId()) {
1179            case R.id.share_with:
1180                ShareUtil.share(activity, selectedMessage);
1181                return true;
1182            case R.id.correct_message:
1183                correctMessage(selectedMessage);
1184                return true;
1185            case R.id.copy_message:
1186                ShareUtil.copyToClipboard(activity, selectedMessage);
1187                return true;
1188            case R.id.copy_link:
1189                ShareUtil.copyLinkToClipboard(activity, selectedMessage);
1190                return true;
1191            case R.id.quote_message:
1192                quoteMessage(selectedMessage);
1193                return true;
1194            case R.id.send_again:
1195                resendMessage(selectedMessage);
1196                return true;
1197            case R.id.copy_url:
1198                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1199                return true;
1200            case R.id.download_file:
1201                startDownloadable(selectedMessage);
1202                return true;
1203            case R.id.cancel_transmission:
1204                cancelTransmission(selectedMessage);
1205                return true;
1206            case R.id.retry_decryption:
1207                retryDecryption(selectedMessage);
1208                return true;
1209            case R.id.delete_file:
1210                deleteFile(selectedMessage);
1211                return true;
1212            case R.id.show_error_message:
1213                showErrorMessage(selectedMessage);
1214                return true;
1215            default:
1216                return super.onContextItemSelected(item);
1217        }
1218    }
1219
1220    @Override
1221    public boolean onOptionsItemSelected(final MenuItem item) {
1222        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1223            return false;
1224        } else if (conversation == null) {
1225            return super.onOptionsItemSelected(item);
1226        }
1227        switch (item.getItemId()) {
1228            case R.id.encryption_choice_axolotl:
1229            case R.id.encryption_choice_pgp:
1230            case R.id.encryption_choice_none:
1231                handleEncryptionSelection(item);
1232                break;
1233            case R.id.attach_choose_picture:
1234            case R.id.attach_take_picture:
1235            case R.id.attach_record_video:
1236            case R.id.attach_choose_file:
1237            case R.id.attach_record_voice:
1238            case R.id.attach_location:
1239                handleAttachmentSelection(item);
1240                break;
1241            case R.id.action_archive:
1242                activity.xmppConnectionService.archiveConversation(conversation);
1243                break;
1244            case R.id.action_contact_details:
1245                activity.switchToContactDetails(conversation.getContact());
1246                break;
1247            case R.id.action_muc_details:
1248                Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1249                intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1250                intent.putExtra("uuid", conversation.getUuid());
1251                startActivity(intent);
1252                break;
1253            case R.id.action_invite:
1254                startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
1255                break;
1256            case R.id.action_clear_history:
1257                clearHistoryDialog(conversation);
1258                break;
1259            case R.id.action_mute:
1260                muteConversationDialog(conversation);
1261                break;
1262            case R.id.action_unmute:
1263                unmuteConversation(conversation);
1264                break;
1265            case R.id.action_block:
1266            case R.id.action_unblock:
1267                final Activity activity = getActivity();
1268                if (activity instanceof XmppActivity) {
1269                    BlockContactDialog.show((XmppActivity) activity, conversation);
1270                }
1271                break;
1272            default:
1273                break;
1274        }
1275        return super.onOptionsItemSelected(item);
1276    }
1277
1278    private void handleAttachmentSelection(MenuItem item) {
1279        switch (item.getItemId()) {
1280            case R.id.attach_choose_picture:
1281                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1282                break;
1283            case R.id.attach_take_picture:
1284                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1285                break;
1286            case R.id.attach_record_video:
1287                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1288                break;
1289            case R.id.attach_choose_file:
1290                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1291                break;
1292            case R.id.attach_record_voice:
1293                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1294                break;
1295            case R.id.attach_location:
1296                attachFile(ATTACHMENT_CHOICE_LOCATION);
1297                break;
1298        }
1299    }
1300
1301    private void handleEncryptionSelection(MenuItem item) {
1302        if (conversation == null) {
1303            return;
1304        }
1305        switch (item.getItemId()) {
1306            case R.id.encryption_choice_none:
1307                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1308                item.setChecked(true);
1309                break;
1310            case R.id.encryption_choice_pgp:
1311                if (activity.hasPgp()) {
1312                    if (conversation.getAccount().getPgpSignature() != null) {
1313                        conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1314                        item.setChecked(true);
1315                    } else {
1316                        activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1317                    }
1318                } else {
1319                    activity.showInstallPgpDialog();
1320                }
1321                break;
1322            case R.id.encryption_choice_axolotl:
1323                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1324                        + "Enabled axolotl for Contact " + conversation.getContact().getJid());
1325                conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1326                item.setChecked(true);
1327                break;
1328            default:
1329                conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1330                break;
1331        }
1332        activity.xmppConnectionService.updateConversation(conversation);
1333        updateChatMsgHint();
1334        getActivity().invalidateOptionsMenu();
1335        activity.refreshUi();
1336    }
1337
1338    public void attachFile(final int attachmentChoice) {
1339        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1340            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)) {
1341                return;
1342            }
1343        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1344            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
1345                return;
1346            }
1347        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1348            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1349                return;
1350            }
1351        }
1352        try {
1353            activity.getPreferences().edit()
1354                    .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1355                    .apply();
1356        } catch (IllegalArgumentException e) {
1357            //just do not save
1358        }
1359        final int encryption = conversation.getNextEncryption();
1360        final int mode = conversation.getMode();
1361        if (encryption == Message.ENCRYPTION_PGP) {
1362            if (activity.hasPgp()) {
1363                if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1364                    activity.xmppConnectionService.getPgpEngine().hasKey(
1365                            conversation.getContact(),
1366                            new UiCallback<Contact>() {
1367
1368                                @Override
1369                                public void userInputRequried(PendingIntent pi, Contact contact) {
1370                                    startPendingIntent(pi, attachmentChoice);
1371                                }
1372
1373                                @Override
1374                                public void success(Contact contact) {
1375                                    selectPresenceToAttachFile(attachmentChoice);
1376                                }
1377
1378                                @Override
1379                                public void error(int error, Contact contact) {
1380                                    activity.replaceToast(getString(error));
1381                                }
1382                            });
1383                } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1384                    if (!conversation.getMucOptions().everybodyHasKeys()) {
1385                        Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1386                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1387                        warning.show();
1388                    }
1389                    selectPresenceToAttachFile(attachmentChoice);
1390                } else {
1391                    showNoPGPKeyDialog(false, (dialog, which) -> {
1392                        conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1393                        activity.xmppConnectionService.updateConversation(conversation);
1394                        selectPresenceToAttachFile(attachmentChoice);
1395                    });
1396                }
1397            } else {
1398                activity.showInstallPgpDialog();
1399            }
1400        } else {
1401            if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
1402                selectPresenceToAttachFile(attachmentChoice);
1403            }
1404        }
1405    }
1406
1407    @Override
1408    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
1409        if (grantResults.length > 0) {
1410            if (allGranted(grantResults)) {
1411                if (requestCode == REQUEST_START_DOWNLOAD) {
1412                    if (this.mPendingDownloadableMessage != null) {
1413                        startDownloadable(this.mPendingDownloadableMessage);
1414                    }
1415                } else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
1416                    if (this.mPendingEditorContent != null) {
1417                        attachEditorContentToConversation(this.mPendingEditorContent);
1418                    }
1419                } else {
1420                    attachFile(requestCode);
1421                }
1422            } else {
1423                @StringRes int res;
1424                String firstDenied = getFirstDenied(grantResults, permissions);
1425                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1426                    res = R.string.no_microphone_permission;
1427                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1428                    res = R.string.no_camera_permission;
1429                } else {
1430                    res = R.string.no_storage_permission;
1431                }
1432                Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1433            }
1434        }
1435        if (writeGranted(grantResults, permissions)) {
1436            if (activity != null && activity.xmppConnectionService != null) {
1437                activity.xmppConnectionService.restartFileObserver();
1438            }
1439        }
1440    }
1441
1442    public void startDownloadable(Message message) {
1443        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1444            this.mPendingDownloadableMessage = message;
1445            return;
1446        }
1447        Transferable transferable = message.getTransferable();
1448        if (transferable != null) {
1449            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1450                createNewConnection(message);
1451                return;
1452            }
1453            if (!transferable.start()) {
1454                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1455                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1456            }
1457        } else if (message.treatAsDownloadable()) {
1458            createNewConnection(message);
1459        }
1460    }
1461
1462    private void createNewConnection(final Message message) {
1463        if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) {
1464            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1465            return;
1466        }
1467        activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1468    }
1469
1470    @SuppressLint("InflateParams")
1471    protected void clearHistoryDialog(final Conversation conversation) {
1472        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1473        builder.setTitle(getString(R.string.clear_conversation_history));
1474        final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1475        final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1476        builder.setView(dialogView);
1477        builder.setNegativeButton(getString(R.string.cancel), null);
1478        builder.setPositiveButton(getString(R.string.delete_messages), (dialog, which) -> {
1479            this.activity.xmppConnectionService.clearConversationHistory(conversation);
1480            if (endConversationCheckBox.isChecked()) {
1481                this.activity.xmppConnectionService.archiveConversation(conversation);
1482                this.activity.onConversationArchived(conversation);
1483            } else {
1484                activity.onConversationsListItemUpdated();
1485                refresh();
1486            }
1487        });
1488        builder.create().show();
1489    }
1490
1491    protected void muteConversationDialog(final Conversation conversation) {
1492        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1493        builder.setTitle(R.string.disable_notifications);
1494        final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1495        final CharSequence[] labels = new CharSequence[durations.length];
1496        for (int i = 0; i < durations.length; ++i) {
1497            if (durations[i] == -1) {
1498                labels[i] = getString(R.string.until_further_notice);
1499            } else {
1500                labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
1501            }
1502        }
1503        builder.setItems(labels, (dialog, which) -> {
1504            final long till;
1505            if (durations[which] == -1) {
1506                till = Long.MAX_VALUE;
1507            } else {
1508                till = System.currentTimeMillis() + (durations[which] * 1000);
1509            }
1510            conversation.setMutedTill(till);
1511            activity.xmppConnectionService.updateConversation(conversation);
1512            activity.onConversationsListItemUpdated();
1513            refresh();
1514            getActivity().invalidateOptionsMenu();
1515        });
1516        builder.create().show();
1517    }
1518
1519    private boolean hasPermissions(int requestCode, String... permissions) {
1520        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1521            final List<String> missingPermissions = new ArrayList<>();
1522            for (String permission : permissions) {
1523                if (Config.ONLY_INTERNAL_STORAGE && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1524                    continue;
1525                }
1526                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
1527                    missingPermissions.add(permission);
1528                }
1529            }
1530            if (missingPermissions.size() == 0) {
1531                return true;
1532            } else {
1533                requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1534                return false;
1535            }
1536        } else {
1537            return true;
1538        }
1539    }
1540
1541    public void unmuteConversation(final Conversation conversation) {
1542        conversation.setMutedTill(0);
1543        this.activity.xmppConnectionService.updateConversation(conversation);
1544        this.activity.onConversationsListItemUpdated();
1545        refresh();
1546        getActivity().invalidateOptionsMenu();
1547    }
1548
1549    protected void selectPresenceToAttachFile(final int attachmentChoice) {
1550        final Account account = conversation.getAccount();
1551        final PresenceSelector.OnPresenceSelected callback = () -> {
1552            Intent intent = new Intent();
1553            boolean chooser = false;
1554            switch (attachmentChoice) {
1555                case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1556                    intent.setAction(Intent.ACTION_GET_CONTENT);
1557                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1558                    intent.setType("image/*");
1559                    chooser = true;
1560                    break;
1561                case ATTACHMENT_CHOICE_RECORD_VIDEO:
1562                    intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1563                    break;
1564                case ATTACHMENT_CHOICE_TAKE_PHOTO:
1565                    final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1566                    pendingTakePhotoUri.push(uri);
1567                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1568                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1569                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1570                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1571                    break;
1572                case ATTACHMENT_CHOICE_CHOOSE_FILE:
1573                    chooser = true;
1574                    intent.setType("*/*");
1575                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1576                    intent.addCategory(Intent.CATEGORY_OPENABLE);
1577                    intent.setAction(Intent.ACTION_GET_CONTENT);
1578                    break;
1579                case ATTACHMENT_CHOICE_RECORD_VOICE:
1580                    intent = new Intent(getActivity(), RecordingActivity.class);
1581                    break;
1582                case ATTACHMENT_CHOICE_LOCATION:
1583                    intent = GeoHelper.getFetchIntent(activity);
1584                    break;
1585            }
1586            if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1587                if (chooser) {
1588                    startActivityForResult(
1589                            Intent.createChooser(intent, getString(R.string.perform_action_with)),
1590                            attachmentChoice);
1591                } else {
1592                    startActivityForResult(intent, attachmentChoice);
1593                }
1594            }
1595        };
1596        if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1597            conversation.setNextCounterpart(null);
1598            callback.onPresenceSelected();
1599        } else {
1600            activity.selectPresence(conversation, callback);
1601        }
1602    }
1603
1604    @Override
1605    public void onResume() {
1606        super.onResume();
1607        binding.messagesView.post(this::fireReadEvent);
1608    }
1609
1610    private void fireReadEvent() {
1611        if (activity != null && this.conversation != null) {
1612            String uuid = getLastVisibleMessageUuid();
1613            if (uuid != null) {
1614                activity.onConversationRead(this.conversation, uuid);
1615            }
1616        }
1617    }
1618
1619    private String getLastVisibleMessageUuid() {
1620        if (binding == null) {
1621            return null;
1622        }
1623        synchronized (this.messageList) {
1624            int pos = binding.messagesView.getLastVisiblePosition();
1625            if (pos >= 0) {
1626                Message message = null;
1627                for (int i = pos; i >= 0; --i) {
1628                    try {
1629                        message = (Message) binding.messagesView.getItemAtPosition(i);
1630                    } catch (IndexOutOfBoundsException e) {
1631                        //should not happen if we synchronize properly. however if that fails we just gonna try item -1
1632                        continue;
1633                    }
1634                    if (message.getType() != Message.TYPE_STATUS) {
1635                        break;
1636                    }
1637                }
1638                if (message != null) {
1639                    while (message.next() != null && message.next().wasMergedIntoPrevious()) {
1640                        message = message.next();
1641                    }
1642                    return message.getUuid();
1643                }
1644            }
1645        }
1646        return null;
1647    }
1648
1649    private void showErrorMessage(final Message message) {
1650        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1651        builder.setTitle(R.string.error_message);
1652        builder.setMessage(message.getErrorMessage());
1653        builder.setPositiveButton(R.string.confirm, null);
1654        builder.create().show();
1655    }
1656
1657
1658    private void deleteFile(Message message) {
1659        if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1660            message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1661            activity.onConversationsListItemUpdated();
1662            refresh();
1663        }
1664    }
1665
1666    private void resendMessage(final Message message) {
1667        if (message.isFileOrImage()) {
1668            if (!(message.getConversation() instanceof Conversation)) {
1669                return;
1670            }
1671            final Conversation conversation = (Conversation) message.getConversation();
1672            DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1673            if (file.exists()) {
1674                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1675                if (!message.hasFileOnRemoteHost()
1676                        && xmppConnection != null
1677                        && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1678                    activity.selectPresence(conversation, () -> {
1679                        message.setCounterpart(conversation.getNextCounterpart());
1680                        activity.xmppConnectionService.resendFailedMessages(message);
1681                        new Handler().post(() -> {
1682                            int size = messageList.size();
1683                            this.binding.messagesView.setSelection(size - 1);
1684                        });
1685                    });
1686                    return;
1687                }
1688            } else {
1689                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1690                message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1691                activity.onConversationsListItemUpdated();
1692                refresh();
1693                return;
1694            }
1695        }
1696        activity.xmppConnectionService.resendFailedMessages(message);
1697        new Handler().post(() -> {
1698            int size = messageList.size();
1699            this.binding.messagesView.setSelection(size - 1);
1700        });
1701    }
1702
1703    private void cancelTransmission(Message message) {
1704        Transferable transferable = message.getTransferable();
1705        if (transferable != null) {
1706            transferable.cancel();
1707        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1708            activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1709        }
1710    }
1711
1712    private void retryDecryption(Message message) {
1713        message.setEncryption(Message.ENCRYPTION_PGP);
1714        activity.onConversationsListItemUpdated();
1715        refresh();
1716        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1717    }
1718
1719    public void privateMessageWith(final Jid counterpart) {
1720        if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1721            activity.xmppConnectionService.sendChatState(conversation);
1722        }
1723        this.binding.textinput.setText("");
1724        this.conversation.setNextCounterpart(counterpart);
1725        updateChatMsgHint();
1726        updateSendButton();
1727        updateEditablity();
1728    }
1729
1730    private void correctMessage(Message message) {
1731        while (message.mergeable(message.next())) {
1732            message = message.next();
1733        }
1734        this.conversation.setCorrectingMessage(message);
1735        final Editable editable = binding.textinput.getText();
1736        this.conversation.setDraftMessage(editable.toString());
1737        this.binding.textinput.setText("");
1738        this.binding.textinput.append(message.getBody());
1739
1740    }
1741
1742    private void highlightInConference(String nick) {
1743        final Editable editable = this.binding.textinput.getText();
1744        String oldString = editable.toString().trim();
1745        final int pos = this.binding.textinput.getSelectionStart();
1746        if (oldString.isEmpty() || pos == 0) {
1747            editable.insert(0, nick + ": ");
1748        } else {
1749            final char before = editable.charAt(pos - 1);
1750            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1751            if (before == '\n') {
1752                editable.insert(pos, nick + ": ");
1753            } else {
1754                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1755                    if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1756                        editable.insert(pos - 2, ", " + nick);
1757                        return;
1758                    }
1759                }
1760                editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1761                if (Character.isWhitespace(after)) {
1762                    this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1763                }
1764            }
1765        }
1766    }
1767
1768    @Override
1769    public void startActivityForResult(Intent intent, int requestCode) {
1770        final Activity activity = getActivity();
1771        if (activity instanceof ConversationsActivity) {
1772            ((ConversationsActivity) activity).clearPendingViewIntent();
1773        }
1774        super.startActivityForResult(intent, requestCode);
1775    }
1776
1777    @Override
1778    public void onSaveInstanceState(Bundle outState) {
1779        super.onSaveInstanceState(outState);
1780        if (conversation != null) {
1781            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1782            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1783            final Uri uri = pendingTakePhotoUri.peek();
1784            if (uri != null) {
1785                outState.putString(STATE_PHOTO_URI, uri.toString());
1786            }
1787            final ScrollState scrollState = getScrollPosition();
1788            if (scrollState != null) {
1789                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1790            }
1791            final ArrayList<Attachment> attachments = mediaPreviewAdapter.getAttachments();
1792            if (attachments.size() > 0) {
1793                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
1794            }
1795        }
1796    }
1797
1798    @Override
1799    public void onActivityCreated(Bundle savedInstanceState) {
1800        super.onActivityCreated(savedInstanceState);
1801        if (savedInstanceState == null) {
1802            return;
1803        }
1804        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1805        ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
1806        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1807        if (uuid != null) {
1808            QuickLoader.set(uuid);
1809            this.pendingConversationsUuid.push(uuid);
1810            if (attachments != null && attachments.size() > 0) {
1811                this.pendingMediaPreviews.push(attachments);
1812            }
1813            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1814            if (takePhotoUri != null) {
1815                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1816            }
1817            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1818        }
1819    }
1820
1821    @Override
1822    public void onStart() {
1823        super.onStart();
1824        if (this.reInitRequiredOnStart && this.conversation != null) {
1825            final Bundle extras = pendingExtras.pop();
1826            reInit(this.conversation, extras != null);
1827            if (extras != null) {
1828                processExtras(extras);
1829            }
1830        } else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1831            final String uuid = pendingConversationsUuid.pop();
1832            Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
1833            if (uuid != null) {
1834                findAndReInitByUuidOrArchive(uuid);
1835            }
1836        }
1837    }
1838
1839    @Override
1840    public void onStop() {
1841        super.onStop();
1842        final Activity activity = getActivity();
1843        messageListAdapter.unregisterListenerInAudioPlayer();
1844        if (activity == null || !activity.isChangingConfigurations()) {
1845            hideSoftKeyboard(activity);
1846            messageListAdapter.stopAudioPlayer();
1847        }
1848        if (this.conversation != null) {
1849            final String msg = this.binding.textinput.getText().toString();
1850            final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
1851            if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) {
1852                this.activity.xmppConnectionService.updateConversation(this.conversation);
1853            }
1854            updateChatState(this.conversation, msg);
1855            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1856        }
1857        this.reInitRequiredOnStart = true;
1858    }
1859
1860    private void updateChatState(final Conversation conversation, final String msg) {
1861        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1862        Account.State status = conversation.getAccount().getStatus();
1863        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1864            activity.xmppConnectionService.sendChatState(conversation);
1865        }
1866    }
1867
1868    private void saveMessageDraftStopAudioPlayer() {
1869        final Conversation previousConversation = this.conversation;
1870        if (this.activity == null || this.binding == null || previousConversation == null) {
1871            return;
1872        }
1873        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1874        final String msg = this.binding.textinput.getText().toString();
1875        final boolean participating = previousConversation.getMode() == Conversational.MODE_SINGLE || previousConversation.getMucOptions().participating();
1876        if (participating && previousConversation.setNextMessage(msg)) {
1877            activity.xmppConnectionService.updateConversation(previousConversation);
1878        }
1879        updateChatState(this.conversation, msg);
1880        messageListAdapter.stopAudioPlayer();
1881        mediaPreviewAdapter.clearPreviews();
1882        toggleInputMethod();
1883    }
1884
1885    public void reInit(Conversation conversation, Bundle extras) {
1886        QuickLoader.set(conversation.getUuid());
1887        this.saveMessageDraftStopAudioPlayer();
1888        this.clearPending();
1889        if (this.reInit(conversation, extras != null)) {
1890            if (extras != null) {
1891                processExtras(extras);
1892            }
1893            this.reInitRequiredOnStart = false;
1894        } else {
1895            this.reInitRequiredOnStart = true;
1896            pendingExtras.push(extras);
1897        }
1898        resetUnreadMessagesCount();
1899    }
1900
1901    private void reInit(Conversation conversation) {
1902        reInit(conversation, false);
1903    }
1904
1905    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1906        if (conversation == null) {
1907            return false;
1908        }
1909        this.conversation = conversation;
1910        //once we set the conversation all is good and it will automatically do the right thing in onStart()
1911        if (this.activity == null || this.binding == null) {
1912            return false;
1913        }
1914
1915        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1916            activity.onConversationArchived(this.conversation);
1917            return false;
1918        }
1919
1920        stopScrolling();
1921        Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1922
1923        if (this.conversation.isRead() && hasExtras) {
1924            Log.d(Config.LOGTAG, "trimming conversation");
1925            this.conversation.trim();
1926        }
1927
1928        setupIme();
1929
1930        final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1931
1932        this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1933        this.binding.textinput.setKeyboardListener(null);
1934        this.binding.textinput.setText("");
1935        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
1936        if (participating) {
1937            this.binding.textinput.append(this.conversation.getNextMessage());
1938        }
1939        this.binding.textinput.setKeyboardListener(this);
1940        messageListAdapter.updatePreferences();
1941        refresh(false);
1942        this.conversation.messagesLoaded.set(true);
1943        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1944
1945        if (hasExtras || scrolledToBottomAndNoPending) {
1946            resetUnreadMessagesCount();
1947            synchronized (this.messageList) {
1948                Log.d(Config.LOGTAG, "jump to first unread message");
1949                final Message first = conversation.getFirstUnreadMessage();
1950                final int bottom = Math.max(0, this.messageList.size() - 1);
1951                final int pos;
1952                final boolean jumpToBottom;
1953                if (first == null) {
1954                    pos = bottom;
1955                    jumpToBottom = true;
1956                } else {
1957                    int i = getIndexOf(first.getUuid(), this.messageList);
1958                    pos = i < 0 ? bottom : i;
1959                    jumpToBottom = false;
1960                }
1961                setSelection(pos, jumpToBottom);
1962            }
1963        }
1964
1965
1966        this.binding.messagesView.post(this::fireReadEvent);
1967        //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
1968        activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1969        return true;
1970    }
1971
1972    private void resetUnreadMessagesCount() {
1973        lastMessageUuid = null;
1974        hideUnreadMessagesCount();
1975    }
1976
1977    private void hideUnreadMessagesCount() {
1978        if (this.binding == null) {
1979            return;
1980        }
1981        this.binding.scrollToBottomButton.setEnabled(false);
1982        this.binding.scrollToBottomButton.setVisibility(View.GONE);
1983        this.binding.unreadCountCustomView.setVisibility(View.GONE);
1984    }
1985
1986    private void setSelection(int pos, boolean jumpToBottom) {
1987        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
1988        this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
1989        this.binding.messagesView.post(this::fireReadEvent);
1990    }
1991
1992
1993    private boolean scrolledToBottom() {
1994        return this.binding != null && scrolledToBottom(this.binding.messagesView);
1995    }
1996
1997    private void processExtras(Bundle extras) {
1998        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
1999        final String text = extras.getString(ConversationsActivity.EXTRA_TEXT);
2000        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2001        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2002        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2003        final List<Uri> uris = extractUris(extras);
2004        if (uris != null && uris.size() > 0) {
2005            mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uris));
2006            toggleInputMethod();
2007            return;
2008        }
2009        if (nick != null) {
2010            if (pm) {
2011                Jid jid = conversation.getJid();
2012                try {
2013                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2014                    privateMessageWith(next);
2015                } catch (final IllegalArgumentException ignored) {
2016                    //do nothing
2017                }
2018            } else {
2019                final MucOptions mucOptions = conversation.getMucOptions();
2020                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2021                    highlightInConference(nick);
2022                }
2023            }
2024        } else {
2025            if (text != null && asQuote) {
2026                quoteText(text);
2027            } else {
2028                appendText(text);
2029            }
2030        }
2031        final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2032        if (message != null) {
2033            startDownloadable(message);
2034        }
2035    }
2036
2037    private List<Uri> extractUris(Bundle extras) {
2038        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2039        if (uris != null) {
2040            return uris;
2041        }
2042        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2043        if (uri != null) {
2044            return Collections.singletonList(uri);
2045        } else {
2046            return null;
2047        }
2048    }
2049
2050    private boolean showBlockSubmenu(View view) {
2051        final Jid jid = conversation.getJid();
2052        if (jid.getLocal() == null) {
2053            BlockContactDialog.show(activity, conversation);
2054        } else {
2055            PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2056            popupMenu.inflate(R.menu.block);
2057            popupMenu.setOnMenuItemClickListener(menuItem -> {
2058                Blockable blockable;
2059                switch (menuItem.getItemId()) {
2060                    case R.id.block_domain:
2061                        blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
2062                        break;
2063                    default:
2064                        blockable = conversation;
2065                }
2066                BlockContactDialog.show(activity, blockable);
2067                return true;
2068            });
2069            popupMenu.show();
2070        }
2071        return true;
2072    }
2073
2074    private void updateSnackBar(final Conversation conversation) {
2075        final Account account = conversation.getAccount();
2076        final XmppConnection connection = account.getXmppConnection();
2077        final int mode = conversation.getMode();
2078        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2079        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2080            return;
2081        }
2082        if (account.getStatus() == Account.State.DISABLED) {
2083            showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
2084        } else if (conversation.isBlocked()) {
2085            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2086        } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2087            showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
2088        } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2089            showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
2090        } else if (mode == Conversation.MODE_MULTI
2091                && !conversation.getMucOptions().online()
2092                && account.getStatus() == Account.State.ONLINE) {
2093            switch (conversation.getMucOptions().getError()) {
2094                case NICK_IN_USE:
2095                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2096                    break;
2097                case NO_RESPONSE:
2098                    showSnackbar(R.string.joining_conference, 0, null);
2099                    break;
2100                case SERVER_NOT_FOUND:
2101                    if (conversation.receivedMessagesCount() > 0) {
2102                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2103                    } else {
2104                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2105                    }
2106                    break;
2107                case PASSWORD_REQUIRED:
2108                    showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2109                    break;
2110                case BANNED:
2111                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2112                    break;
2113                case MEMBERS_ONLY:
2114                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2115                    break;
2116                case RESOURCE_CONSTRAINT:
2117                    showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2118                    break;
2119                case KICKED:
2120                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2121                    break;
2122                case UNKNOWN:
2123                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2124                    break;
2125                case INVALID_NICK:
2126                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2127                case SHUTDOWN:
2128                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2129                    break;
2130                case DESTROYED:
2131                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2132                    break;
2133                default:
2134                    hideSnackbar();
2135                    break;
2136            }
2137        } else if (account.hasPendingPgpIntent(conversation)) {
2138            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2139        } else if (connection != null
2140                && connection.getFeatures().blocking()
2141                && conversation.countMessages() != 0
2142                && !conversation.isBlocked()
2143                && conversation.isWithStranger()) {
2144            showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2145        } else {
2146            hideSnackbar();
2147        }
2148    }
2149
2150    @Override
2151    public void refresh() {
2152        if (this.binding == null) {
2153            Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2154            return;
2155        }
2156        if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2157            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2158                activity.onConversationArchived(this.conversation);
2159                return;
2160            }
2161        }
2162        this.refresh(true);
2163    }
2164
2165    private void refresh(boolean notifyConversationRead) {
2166        synchronized (this.messageList) {
2167            if (this.conversation != null) {
2168                conversation.populateWithMessages(this.messageList);
2169                updateSnackBar(conversation);
2170                updateStatusMessages();
2171                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2172                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2173                    binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2174                }
2175                this.messageListAdapter.notifyDataSetChanged();
2176                updateChatMsgHint();
2177                if (notifyConversationRead && activity != null) {
2178                    binding.messagesView.post(this::fireReadEvent);
2179                }
2180                updateSendButton();
2181                updateEditablity();
2182                activity.invalidateOptionsMenu();
2183            }
2184        }
2185    }
2186
2187    protected void messageSent() {
2188        mSendingPgpMessage.set(false);
2189        this.binding.textinput.setText("");
2190        if (conversation.setCorrectingMessage(null)) {
2191            this.binding.textinput.append(conversation.getDraftMessage());
2192            conversation.setDraftMessage(null);
2193        }
2194        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2195        if (participating && conversation.setNextMessage(this.binding.textinput.getText().toString())) {
2196            activity.xmppConnectionService.databaseBackend.updateConversation(conversation);
2197        }
2198        updateChatMsgHint();
2199        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2200        final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2201        if (prefScrollToBottom || scrolledToBottom()) {
2202            new Handler().post(() -> {
2203                int size = messageList.size();
2204                this.binding.messagesView.setSelection(size - 1);
2205            });
2206        }
2207    }
2208
2209    public void doneSendingPgpMessage() {
2210        mSendingPgpMessage.set(false);
2211    }
2212
2213    public long getMaxHttpUploadSize(Conversation conversation) {
2214        final XmppConnection connection = conversation.getAccount().getXmppConnection();
2215        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2216    }
2217
2218    private void updateEditablity() {
2219        boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2220        this.binding.textinput.setFocusable(canWrite);
2221        this.binding.textinput.setFocusableInTouchMode(canWrite);
2222        this.binding.textSendButton.setEnabled(canWrite);
2223        this.binding.textinput.setCursorVisible(canWrite);
2224        this.binding.textinput.setEnabled(canWrite);
2225    }
2226
2227    public void updateSendButton() {
2228        boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2229        boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2230        final Conversation c = this.conversation;
2231        final Presence.Status status;
2232        final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2233        final SendButtonAction action;
2234        if (hasAttachments) {
2235            action = SendButtonAction.TEXT;
2236        } else {
2237            action = SendButtonTool.getAction(getActivity(), c, text);
2238        }
2239        if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2240            if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2241                status = Presence.Status.OFFLINE;
2242            } else if (c.getMode() == Conversation.MODE_SINGLE) {
2243                status = c.getContact().getShownStatus();
2244            } else {
2245                status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2246            }
2247        } else {
2248            status = Presence.Status.OFFLINE;
2249        }
2250        this.binding.textSendButton.setTag(action);
2251        this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2252    }
2253
2254    protected void updateDateSeparators() {
2255        synchronized (this.messageList) {
2256            DateSeparator.addAll(this.messageList);
2257        }
2258    }
2259
2260    protected void updateStatusMessages() {
2261        updateDateSeparators();
2262        synchronized (this.messageList) {
2263            if (showLoadMoreMessages(conversation)) {
2264                this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2265            }
2266            if (conversation.getMode() == Conversation.MODE_SINGLE) {
2267                ChatState state = conversation.getIncomingChatState();
2268                if (state == ChatState.COMPOSING) {
2269                    this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2270                } else if (state == ChatState.PAUSED) {
2271                    this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2272                } else {
2273                    for (int i = this.messageList.size() - 1; i >= 0; --i) {
2274                        if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
2275                            return;
2276                        } else {
2277                            if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
2278                                this.messageList.add(i + 1,
2279                                        Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2280                                return;
2281                            }
2282                        }
2283                    }
2284                }
2285            } else {
2286                final MucOptions mucOptions = conversation.getMucOptions();
2287                final List<MucOptions.User> allUsers = mucOptions.getUsers();
2288                final Set<ReadByMarker> addedMarkers = new HashSet<>();
2289                ChatState state = ChatState.COMPOSING;
2290                List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2291                if (users.size() == 0) {
2292                    state = ChatState.PAUSED;
2293                    users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2294                }
2295                if (mucOptions.isPrivateAndNonAnonymous()) {
2296                    for (int i = this.messageList.size() - 1; i >= 0; --i) {
2297                        final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2298                        final List<MucOptions.User> shownMarkers = new ArrayList<>();
2299                        for (ReadByMarker marker : markersForMessage) {
2300                            if (!ReadByMarker.contains(marker, addedMarkers)) {
2301                                addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2302                                MucOptions.User user = mucOptions.findUser(marker);
2303                                if (user != null && !users.contains(user)) {
2304                                    shownMarkers.add(user);
2305                                }
2306                            }
2307                        }
2308                        final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2309                        final Message statusMessage;
2310                        final int size = shownMarkers.size();
2311                        if (size > 1) {
2312                            final String body;
2313                            if (size <= 4) {
2314                                body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2315                            } else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) {
2316                                body = getString(R.string.everyone_has_read_up_to_this_point);
2317                            } else {
2318                                body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2319                            }
2320                            statusMessage = Message.createStatusMessage(conversation, body);
2321                            statusMessage.setCounterparts(shownMarkers);
2322                        } else if (size == 1) {
2323                            statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2324                            statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2325                            statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2326                        } else {
2327                            statusMessage = null;
2328                        }
2329                        if (statusMessage != null) {
2330                            this.messageList.add(i + 1, statusMessage);
2331                        }
2332                        addedMarkers.add(markerForSender);
2333                        if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2334                            break;
2335                        }
2336                    }
2337                }
2338                if (users.size() > 0) {
2339                    Message statusMessage;
2340                    if (users.size() == 1) {
2341                        MucOptions.User user = users.get(0);
2342                        int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2343                        statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2344                        statusMessage.setTrueCounterpart(user.getRealJid());
2345                        statusMessage.setCounterpart(user.getFullJid());
2346                    } else {
2347                        int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2348                        statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2349                        statusMessage.setCounterparts(users);
2350                    }
2351                    this.messageList.add(statusMessage);
2352                }
2353
2354            }
2355        }
2356    }
2357
2358    private void stopScrolling() {
2359        long now = SystemClock.uptimeMillis();
2360        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2361        binding.messagesView.dispatchTouchEvent(cancel);
2362    }
2363
2364    private boolean showLoadMoreMessages(final Conversation c) {
2365        if (activity == null || activity.xmppConnectionService == null) {
2366            return false;
2367        }
2368        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2369        final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2370        return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2371    }
2372
2373    private boolean hasMamSupport(final Conversation c) {
2374        if (c.getMode() == Conversation.MODE_SINGLE) {
2375            final XmppConnection connection = c.getAccount().getXmppConnection();
2376            return connection != null && connection.getFeatures().mam();
2377        } else {
2378            return c.getMucOptions().mamSupport();
2379        }
2380    }
2381
2382    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2383        showSnackbar(message, action, clickListener, null);
2384    }
2385
2386    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2387        this.binding.snackbar.setVisibility(View.VISIBLE);
2388        this.binding.snackbar.setOnClickListener(null);
2389        this.binding.snackbarMessage.setText(message);
2390        this.binding.snackbarMessage.setOnClickListener(null);
2391        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2392        if (action != 0) {
2393            this.binding.snackbarAction.setText(action);
2394        }
2395        this.binding.snackbarAction.setOnClickListener(clickListener);
2396        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2397    }
2398
2399    protected void hideSnackbar() {
2400        this.binding.snackbar.setVisibility(View.GONE);
2401    }
2402
2403    protected void sendMessage(Message message) {
2404        activity.xmppConnectionService.sendMessage(message);
2405        messageSent();
2406    }
2407
2408    protected void sendPgpMessage(final Message message) {
2409        final XmppConnectionService xmppService = activity.xmppConnectionService;
2410        final Contact contact = message.getConversation().getContact();
2411        if (!activity.hasPgp()) {
2412            activity.showInstallPgpDialog();
2413            return;
2414        }
2415        if (conversation.getAccount().getPgpSignature() == null) {
2416            activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2417            return;
2418        }
2419        if (!mSendingPgpMessage.compareAndSet(false, true)) {
2420            Log.d(Config.LOGTAG, "sending pgp message already in progress");
2421        }
2422        if (conversation.getMode() == Conversation.MODE_SINGLE) {
2423            if (contact.getPgpKeyId() != 0) {
2424                xmppService.getPgpEngine().hasKey(contact,
2425                        new UiCallback<Contact>() {
2426
2427                            @Override
2428                            public void userInputRequried(PendingIntent pi, Contact contact) {
2429                                startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2430                            }
2431
2432                            @Override
2433                            public void success(Contact contact) {
2434                                encryptTextMessage(message);
2435                            }
2436
2437                            @Override
2438                            public void error(int error, Contact contact) {
2439                                activity.runOnUiThread(() -> Toast.makeText(activity,
2440                                        R.string.unable_to_connect_to_keychain,
2441                                        Toast.LENGTH_SHORT
2442                                ).show());
2443                                mSendingPgpMessage.set(false);
2444                            }
2445                        });
2446
2447            } else {
2448                showNoPGPKeyDialog(false, (dialog, which) -> {
2449                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2450                    xmppService.updateConversation(conversation);
2451                    message.setEncryption(Message.ENCRYPTION_NONE);
2452                    xmppService.sendMessage(message);
2453                    messageSent();
2454                });
2455            }
2456        } else {
2457            if (conversation.getMucOptions().pgpKeysInUse()) {
2458                if (!conversation.getMucOptions().everybodyHasKeys()) {
2459                    Toast warning = Toast
2460                            .makeText(getActivity(),
2461                                    R.string.missing_public_keys,
2462                                    Toast.LENGTH_LONG);
2463                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2464                    warning.show();
2465                }
2466                encryptTextMessage(message);
2467            } else {
2468                showNoPGPKeyDialog(true, (dialog, which) -> {
2469                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2470                    message.setEncryption(Message.ENCRYPTION_NONE);
2471                    xmppService.updateConversation(conversation);
2472                    xmppService.sendMessage(message);
2473                    messageSent();
2474                });
2475            }
2476        }
2477    }
2478
2479    public void encryptTextMessage(Message message) {
2480        activity.xmppConnectionService.getPgpEngine().encrypt(message,
2481                new UiCallback<Message>() {
2482
2483                    @Override
2484                    public void userInputRequried(PendingIntent pi, Message message) {
2485                        startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2486                    }
2487
2488                    @Override
2489                    public void success(Message message) {
2490                        //TODO the following two call can be made before the callback
2491                        getActivity().runOnUiThread(() -> messageSent());
2492                    }
2493
2494                    @Override
2495                    public void error(final int error, Message message) {
2496                        getActivity().runOnUiThread(() -> {
2497                            doneSendingPgpMessage();
2498                            Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2499                        });
2500
2501                    }
2502                });
2503    }
2504
2505    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2506        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2507        builder.setIconAttribute(android.R.attr.alertDialogIcon);
2508        if (plural) {
2509            builder.setTitle(getString(R.string.no_pgp_keys));
2510            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2511        } else {
2512            builder.setTitle(getString(R.string.no_pgp_key));
2513            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2514        }
2515        builder.setNegativeButton(getString(R.string.cancel), null);
2516        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2517        builder.create().show();
2518    }
2519
2520    public void appendText(String text) {
2521        if (text == null) {
2522            return;
2523        }
2524        String previous = this.binding.textinput.getText().toString();
2525        if (UIHelper.isLastLineQuote(previous)) {
2526            text = '\n' + text;
2527        } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
2528            text = " " + text;
2529        }
2530        this.binding.textinput.append(text);
2531    }
2532
2533    @Override
2534    public boolean onEnterPressed() {
2535        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2536        final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2537        if (enterIsSend) {
2538            sendMessage();
2539            return true;
2540        } else {
2541            return false;
2542        }
2543    }
2544
2545    @Override
2546    public void onTypingStarted() {
2547        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2548        if (service == null) {
2549            return;
2550        }
2551        Account.State status = conversation.getAccount().getStatus();
2552        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2553            service.sendChatState(conversation);
2554        }
2555        updateSendButton();
2556    }
2557
2558    @Override
2559    public void onTypingStopped() {
2560        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2561        if (service == null) {
2562            return;
2563        }
2564        Account.State status = conversation.getAccount().getStatus();
2565        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2566            service.sendChatState(conversation);
2567        }
2568    }
2569
2570    @Override
2571    public void onTextDeleted() {
2572        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2573        if (service == null) {
2574            return;
2575        }
2576        Account.State status = conversation.getAccount().getStatus();
2577        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2578            service.sendChatState(conversation);
2579        }
2580        updateSendButton();
2581    }
2582
2583    @Override
2584    public void onTextChanged() {
2585        if (conversation != null && conversation.getCorrectingMessage() != null) {
2586            updateSendButton();
2587        }
2588    }
2589
2590    @Override
2591    public boolean onTabPressed(boolean repeated) {
2592        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2593            return false;
2594        }
2595        if (repeated) {
2596            completionIndex++;
2597        } else {
2598            lastCompletionLength = 0;
2599            completionIndex = 0;
2600            final String content = this.binding.textinput.getText().toString();
2601            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2602            int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2603            firstWord = start == 0;
2604            incomplete = content.substring(start, lastCompletionCursor);
2605        }
2606        List<String> completions = new ArrayList<>();
2607        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2608            String name = user.getName();
2609            if (name != null && name.startsWith(incomplete)) {
2610                completions.add(name + (firstWord ? ": " : " "));
2611            }
2612        }
2613        Collections.sort(completions);
2614        if (completions.size() > completionIndex) {
2615            String completion = completions.get(completionIndex).substring(incomplete.length());
2616            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2617            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2618            lastCompletionLength = completion.length();
2619        } else {
2620            completionIndex = -1;
2621            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2622            lastCompletionLength = 0;
2623        }
2624        return true;
2625    }
2626
2627    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2628        try {
2629            getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2630        } catch (final SendIntentException ignored) {
2631        }
2632    }
2633
2634    @Override
2635    public void onBackendConnected() {
2636        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2637        String uuid = pendingConversationsUuid.pop();
2638        if (uuid != null) {
2639            if (!findAndReInitByUuidOrArchive(uuid)) {
2640                return;
2641            }
2642        } else {
2643            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2644                clearPending();
2645                activity.onConversationArchived(conversation);
2646                return;
2647            }
2648        }
2649        ActivityResult activityResult = postponedActivityResult.pop();
2650        if (activityResult != null) {
2651            handleActivityResult(activityResult);
2652        }
2653        clearPending();
2654    }
2655
2656    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2657        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2658        if (conversation == null) {
2659            clearPending();
2660            activity.onConversationArchived(null);
2661            return false;
2662        }
2663        reInit(conversation);
2664        ScrollState scrollState = pendingScrollState.pop();
2665        String lastMessageUuid = pendingLastMessageUuid.pop();
2666        List<Attachment> attachments = pendingMediaPreviews.pop();
2667        if (scrollState != null) {
2668            setScrollPosition(scrollState, lastMessageUuid);
2669        }
2670        if (attachments != null && attachments.size() > 0) {
2671            Log.d(Config.LOGTAG,"had attachments on restore");
2672            mediaPreviewAdapter.addMediaPreviews(attachments);
2673            toggleInputMethod();
2674        }
2675        return true;
2676    }
2677
2678    private void clearPending() {
2679        if (postponedActivityResult.clear()) {
2680            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2681        }
2682        if (pendingScrollState.clear()) {
2683            Log.e(Config.LOGTAG,"cleared scroll state");
2684        }
2685        if (pendingTakePhotoUri.clear()) {
2686            Log.e(Config.LOGTAG, "cleared pending photo uri");
2687        }
2688    }
2689
2690    public Conversation getConversation() {
2691        return conversation;
2692    }
2693}