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