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