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