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