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