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 && conversation.getMode() == Conversational.MODE_SINGLE
1698 && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1699 activity.selectPresence(conversation, () -> {
1700 message.setCounterpart(conversation.getNextCounterpart());
1701 activity.xmppConnectionService.resendFailedMessages(message);
1702 new Handler().post(() -> {
1703 int size = messageList.size();
1704 this.binding.messagesView.setSelection(size - 1);
1705 });
1706 });
1707 return;
1708 }
1709 } else {
1710 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1711 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1712 activity.onConversationsListItemUpdated();
1713 refresh();
1714 return;
1715 }
1716 }
1717 activity.xmppConnectionService.resendFailedMessages(message);
1718 new Handler().post(() -> {
1719 int size = messageList.size();
1720 this.binding.messagesView.setSelection(size - 1);
1721 });
1722 }
1723
1724 private void cancelTransmission(Message message) {
1725 Transferable transferable = message.getTransferable();
1726 if (transferable != null) {
1727 transferable.cancel();
1728 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1729 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
1730 }
1731 }
1732
1733 private void retryDecryption(Message message) {
1734 message.setEncryption(Message.ENCRYPTION_PGP);
1735 activity.onConversationsListItemUpdated();
1736 refresh();
1737 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1738 }
1739
1740 public void privateMessageWith(final Jid counterpart) {
1741 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1742 activity.xmppConnectionService.sendChatState(conversation);
1743 }
1744 this.binding.textinput.setText("");
1745 this.conversation.setNextCounterpart(counterpart);
1746 updateChatMsgHint();
1747 updateSendButton();
1748 updateEditablity();
1749 }
1750
1751 private void correctMessage(Message message) {
1752 while (message.mergeable(message.next())) {
1753 message = message.next();
1754 }
1755 this.conversation.setCorrectingMessage(message);
1756 final Editable editable = binding.textinput.getText();
1757 this.conversation.setDraftMessage(editable.toString());
1758 this.binding.textinput.setText("");
1759 this.binding.textinput.append(message.getBody());
1760
1761 }
1762
1763 private void highlightInConference(String nick) {
1764 final Editable editable = this.binding.textinput.getText();
1765 String oldString = editable.toString().trim();
1766 final int pos = this.binding.textinput.getSelectionStart();
1767 if (oldString.isEmpty() || pos == 0) {
1768 editable.insert(0, nick + ": ");
1769 } else {
1770 final char before = editable.charAt(pos - 1);
1771 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1772 if (before == '\n') {
1773 editable.insert(pos, nick + ": ");
1774 } else {
1775 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1776 if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1777 editable.insert(pos - 2, ", " + nick);
1778 return;
1779 }
1780 }
1781 editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1782 if (Character.isWhitespace(after)) {
1783 this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1784 }
1785 }
1786 }
1787 }
1788
1789 @Override
1790 public void startActivityForResult(Intent intent, int requestCode) {
1791 final Activity activity = getActivity();
1792 if (activity instanceof ConversationsActivity) {
1793 ((ConversationsActivity) activity).clearPendingViewIntent();
1794 }
1795 super.startActivityForResult(intent, requestCode);
1796 }
1797
1798 @Override
1799 public void onSaveInstanceState(Bundle outState) {
1800 super.onSaveInstanceState(outState);
1801 if (conversation != null) {
1802 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1803 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1804 final Uri uri = pendingTakePhotoUri.peek();
1805 if (uri != null) {
1806 outState.putString(STATE_PHOTO_URI, uri.toString());
1807 }
1808 final ScrollState scrollState = getScrollPosition();
1809 if (scrollState != null) {
1810 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1811 }
1812 final ArrayList<Attachment> attachments = mediaPreviewAdapter.getAttachments();
1813 if (attachments.size() > 0) {
1814 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
1815 }
1816 }
1817 }
1818
1819 @Override
1820 public void onActivityCreated(Bundle savedInstanceState) {
1821 super.onActivityCreated(savedInstanceState);
1822 if (savedInstanceState == null) {
1823 return;
1824 }
1825 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1826 ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
1827 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1828 if (uuid != null) {
1829 QuickLoader.set(uuid);
1830 this.pendingConversationsUuid.push(uuid);
1831 if (attachments != null && attachments.size() > 0) {
1832 this.pendingMediaPreviews.push(attachments);
1833 }
1834 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1835 if (takePhotoUri != null) {
1836 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1837 }
1838 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1839 }
1840 }
1841
1842 @Override
1843 public void onStart() {
1844 super.onStart();
1845 if (this.reInitRequiredOnStart && this.conversation != null) {
1846 final Bundle extras = pendingExtras.pop();
1847 reInit(this.conversation, extras != null);
1848 if (extras != null) {
1849 processExtras(extras);
1850 }
1851 } else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1852 final String uuid = pendingConversationsUuid.pop();
1853 Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
1854 if (uuid != null) {
1855 findAndReInitByUuidOrArchive(uuid);
1856 }
1857 }
1858 }
1859
1860 @Override
1861 public void onStop() {
1862 super.onStop();
1863 final Activity activity = getActivity();
1864 messageListAdapter.unregisterListenerInAudioPlayer();
1865 if (activity == null || !activity.isChangingConfigurations()) {
1866 hideSoftKeyboard(activity);
1867 messageListAdapter.stopAudioPlayer();
1868 }
1869 if (this.conversation != null) {
1870 final String msg = this.binding.textinput.getText().toString();
1871 storeNextMessage(msg);
1872 updateChatState(this.conversation, msg);
1873 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1874 }
1875 this.reInitRequiredOnStart = true;
1876 }
1877
1878 private void updateChatState(final Conversation conversation, final String msg) {
1879 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1880 Account.State status = conversation.getAccount().getStatus();
1881 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1882 activity.xmppConnectionService.sendChatState(conversation);
1883 }
1884 }
1885
1886 private void saveMessageDraftStopAudioPlayer() {
1887 final Conversation previousConversation = this.conversation;
1888 if (this.activity == null || this.binding == null || previousConversation == null) {
1889 return;
1890 }
1891 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1892 final String msg = this.binding.textinput.getText().toString();
1893 storeNextMessage(msg);
1894 updateChatState(this.conversation, msg);
1895 messageListAdapter.stopAudioPlayer();
1896 mediaPreviewAdapter.clearPreviews();
1897 toggleInputMethod();
1898 }
1899
1900 public void reInit(Conversation conversation, Bundle extras) {
1901 QuickLoader.set(conversation.getUuid());
1902 this.saveMessageDraftStopAudioPlayer();
1903 this.clearPending();
1904 if (this.reInit(conversation, extras != null)) {
1905 if (extras != null) {
1906 processExtras(extras);
1907 }
1908 this.reInitRequiredOnStart = false;
1909 } else {
1910 this.reInitRequiredOnStart = true;
1911 pendingExtras.push(extras);
1912 }
1913 resetUnreadMessagesCount();
1914 }
1915
1916 private void reInit(Conversation conversation) {
1917 reInit(conversation, false);
1918 }
1919
1920 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1921 if (conversation == null) {
1922 return false;
1923 }
1924 this.conversation = conversation;
1925 //once we set the conversation all is good and it will automatically do the right thing in onStart()
1926 if (this.activity == null || this.binding == null) {
1927 return false;
1928 }
1929
1930 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1931 activity.onConversationArchived(this.conversation);
1932 return false;
1933 }
1934
1935 stopScrolling();
1936 Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1937
1938 if (this.conversation.isRead() && hasExtras) {
1939 Log.d(Config.LOGTAG, "trimming conversation");
1940 this.conversation.trim();
1941 }
1942
1943 setupIme();
1944
1945 final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1946
1947 this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1948 this.binding.textinput.setKeyboardListener(null);
1949 this.binding.textinput.setText("");
1950 final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
1951 if (participating) {
1952 this.binding.textinput.append(this.conversation.getNextMessage());
1953 }
1954 this.binding.textinput.setKeyboardListener(this);
1955 messageListAdapter.updatePreferences();
1956 refresh(false);
1957 this.conversation.messagesLoaded.set(true);
1958 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1959
1960 if (hasExtras || scrolledToBottomAndNoPending) {
1961 resetUnreadMessagesCount();
1962 synchronized (this.messageList) {
1963 Log.d(Config.LOGTAG, "jump to first unread message");
1964 final Message first = conversation.getFirstUnreadMessage();
1965 final int bottom = Math.max(0, this.messageList.size() - 1);
1966 final int pos;
1967 final boolean jumpToBottom;
1968 if (first == null) {
1969 pos = bottom;
1970 jumpToBottom = true;
1971 } else {
1972 int i = getIndexOf(first.getUuid(), this.messageList);
1973 pos = i < 0 ? bottom : i;
1974 jumpToBottom = false;
1975 }
1976 setSelection(pos, jumpToBottom);
1977 }
1978 }
1979
1980
1981 this.binding.messagesView.post(this::fireReadEvent);
1982 //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
1983 activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1984 return true;
1985 }
1986
1987 private void resetUnreadMessagesCount() {
1988 lastMessageUuid = null;
1989 hideUnreadMessagesCount();
1990 }
1991
1992 private void hideUnreadMessagesCount() {
1993 if (this.binding == null) {
1994 return;
1995 }
1996 this.binding.scrollToBottomButton.setEnabled(false);
1997 this.binding.scrollToBottomButton.hide();
1998 this.binding.unreadCountCustomView.setVisibility(View.GONE);
1999 }
2000
2001 private void setSelection(int pos, boolean jumpToBottom) {
2002 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2003 this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2004 this.binding.messagesView.post(this::fireReadEvent);
2005 }
2006
2007
2008 private boolean scrolledToBottom() {
2009 return this.binding != null && scrolledToBottom(this.binding.messagesView);
2010 }
2011
2012 private void processExtras(Bundle extras) {
2013 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2014 final String text = extras.getString(Intent.EXTRA_TEXT);
2015 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2016 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2017 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2018 final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2019 final List<Uri> uris = extractUris(extras);
2020 if (uris != null && uris.size() > 0) {
2021 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2022 mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));
2023 toggleInputMethod();
2024 return;
2025 }
2026 if (nick != null) {
2027 if (pm) {
2028 Jid jid = conversation.getJid();
2029 try {
2030 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2031 privateMessageWith(next);
2032 } catch (final IllegalArgumentException ignored) {
2033 //do nothing
2034 }
2035 } else {
2036 final MucOptions mucOptions = conversation.getMucOptions();
2037 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2038 highlightInConference(nick);
2039 }
2040 }
2041 } else {
2042 if (text != null && asQuote) {
2043 quoteText(text);
2044 } else {
2045 appendText(text, doNotAppend);
2046 }
2047 }
2048 final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2049 if (message != null) {
2050 startDownloadable(message);
2051 }
2052 }
2053
2054 private List<Uri> extractUris(Bundle extras) {
2055 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2056 if (uris != null) {
2057 return uris;
2058 }
2059 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2060 if (uri != null) {
2061 return Collections.singletonList(uri);
2062 } else {
2063 return null;
2064 }
2065 }
2066
2067 private List<Uri> cleanUris(List<Uri> uris) {
2068 Iterator<Uri> iterator = uris.iterator();
2069 while (iterator.hasNext()) {
2070 final Uri uri = iterator.next();
2071 if (FileBackend.weOwnFile(getActivity(), uri)) {
2072 iterator.remove();
2073 Toast.makeText(getActivity(), R.string.security_violation_not_attaching_file, Toast.LENGTH_SHORT).show();
2074 }
2075 }
2076 return uris;
2077 }
2078
2079 private boolean showBlockSubmenu(View view) {
2080 final Jid jid = conversation.getJid();
2081 final boolean showReject = !conversation.isWithStranger() && conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2082 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2083 popupMenu.inflate(R.menu.block);
2084 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2085 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2086 popupMenu.setOnMenuItemClickListener(menuItem -> {
2087 Blockable blockable;
2088 switch (menuItem.getItemId()) {
2089 case R.id.reject:
2090 activity.xmppConnectionService.stopPresenceUpdatesTo(conversation.getContact());
2091 updateSnackBar(conversation);
2092 return true;
2093 case R.id.block_domain:
2094 blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
2095 break;
2096 default:
2097 blockable = conversation;
2098 }
2099 BlockContactDialog.show(activity, blockable);
2100 return true;
2101 });
2102 popupMenu.show();
2103 return true;
2104 }
2105
2106 private void updateSnackBar(final Conversation conversation) {
2107 final Account account = conversation.getAccount();
2108 final XmppConnection connection = account.getXmppConnection();
2109 final int mode = conversation.getMode();
2110 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2111 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2112 return;
2113 }
2114 if (account.getStatus() == Account.State.DISABLED) {
2115 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
2116 } else if (conversation.isBlocked()) {
2117 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2118 } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2119 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
2120 } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2121 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
2122 } else if (mode == Conversation.MODE_MULTI
2123 && !conversation.getMucOptions().online()
2124 && account.getStatus() == Account.State.ONLINE) {
2125 switch (conversation.getMucOptions().getError()) {
2126 case NICK_IN_USE:
2127 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2128 break;
2129 case NO_RESPONSE:
2130 showSnackbar(R.string.joining_conference, 0, null);
2131 break;
2132 case SERVER_NOT_FOUND:
2133 if (conversation.receivedMessagesCount() > 0) {
2134 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2135 } else {
2136 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2137 }
2138 break;
2139 case REMOTE_SERVER_TIMEOUT:
2140 if (conversation.receivedMessagesCount() > 0) {
2141 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2142 } else {
2143 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2144 }
2145 break;
2146 case PASSWORD_REQUIRED:
2147 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2148 break;
2149 case BANNED:
2150 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2151 break;
2152 case MEMBERS_ONLY:
2153 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2154 break;
2155 case RESOURCE_CONSTRAINT:
2156 showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2157 break;
2158 case KICKED:
2159 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2160 break;
2161 case UNKNOWN:
2162 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2163 break;
2164 case INVALID_NICK:
2165 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2166 case SHUTDOWN:
2167 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2168 break;
2169 case DESTROYED:
2170 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2171 break;
2172 default:
2173 hideSnackbar();
2174 break;
2175 }
2176 } else if (account.hasPendingPgpIntent(conversation)) {
2177 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2178 } else if (connection != null
2179 && connection.getFeatures().blocking()
2180 && conversation.countMessages() != 0
2181 && !conversation.isBlocked()
2182 && conversation.isWithStranger()) {
2183 showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2184 } else {
2185 hideSnackbar();
2186 }
2187 }
2188
2189 @Override
2190 public void refresh() {
2191 if (this.binding == null) {
2192 Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2193 return;
2194 }
2195 if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2196 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2197 activity.onConversationArchived(this.conversation);
2198 return;
2199 }
2200 }
2201 this.refresh(true);
2202 }
2203
2204 private void refresh(boolean notifyConversationRead) {
2205 synchronized (this.messageList) {
2206 if (this.conversation != null) {
2207 conversation.populateWithMessages(this.messageList);
2208 updateSnackBar(conversation);
2209 updateStatusMessages();
2210 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2211 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2212 binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2213 }
2214 this.messageListAdapter.notifyDataSetChanged();
2215 updateChatMsgHint();
2216 if (notifyConversationRead && activity != null) {
2217 binding.messagesView.post(this::fireReadEvent);
2218 }
2219 updateSendButton();
2220 updateEditablity();
2221 activity.invalidateOptionsMenu();
2222 }
2223 }
2224 }
2225
2226 protected void messageSent() {
2227 mSendingPgpMessage.set(false);
2228 this.binding.textinput.setText("");
2229 if (conversation.setCorrectingMessage(null)) {
2230 this.binding.textinput.append(conversation.getDraftMessage());
2231 conversation.setDraftMessage(null);
2232 }
2233 storeNextMessage();
2234 updateChatMsgHint();
2235 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2236 final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2237 if (prefScrollToBottom || scrolledToBottom()) {
2238 new Handler().post(() -> {
2239 int size = messageList.size();
2240 this.binding.messagesView.setSelection(size - 1);
2241 });
2242 }
2243 }
2244
2245 private boolean storeNextMessage() {
2246 return storeNextMessage(this.binding.textinput.getText().toString());
2247 }
2248
2249 private boolean storeNextMessage(String msg) {
2250 final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2251 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) {
2252 this.activity.xmppConnectionService.updateConversation(this.conversation);
2253 return true;
2254 }
2255 return false;
2256 }
2257
2258 public void doneSendingPgpMessage() {
2259 mSendingPgpMessage.set(false);
2260 }
2261
2262 public long getMaxHttpUploadSize(Conversation conversation) {
2263 final XmppConnection connection = conversation.getAccount().getXmppConnection();
2264 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2265 }
2266
2267 private void updateEditablity() {
2268 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2269 this.binding.textinput.setFocusable(canWrite);
2270 this.binding.textinput.setFocusableInTouchMode(canWrite);
2271 this.binding.textSendButton.setEnabled(canWrite);
2272 this.binding.textinput.setCursorVisible(canWrite);
2273 this.binding.textinput.setEnabled(canWrite);
2274 }
2275
2276 public void updateSendButton() {
2277 boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2278 boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2279 final Conversation c = this.conversation;
2280 final Presence.Status status;
2281 final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2282 final SendButtonAction action;
2283 if (hasAttachments) {
2284 action = SendButtonAction.TEXT;
2285 } else {
2286 action = SendButtonTool.getAction(getActivity(), c, text);
2287 }
2288 if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2289 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2290 status = Presence.Status.OFFLINE;
2291 } else if (c.getMode() == Conversation.MODE_SINGLE) {
2292 status = c.getContact().getShownStatus();
2293 } else {
2294 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2295 }
2296 } else {
2297 status = Presence.Status.OFFLINE;
2298 }
2299 this.binding.textSendButton.setTag(action);
2300 this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2301 }
2302
2303 protected void updateDateSeparators() {
2304 synchronized (this.messageList) {
2305 DateSeparator.addAll(this.messageList);
2306 }
2307 }
2308
2309 protected void updateStatusMessages() {
2310 updateDateSeparators();
2311 synchronized (this.messageList) {
2312 if (showLoadMoreMessages(conversation)) {
2313 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2314 }
2315 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2316 ChatState state = conversation.getIncomingChatState();
2317 if (state == ChatState.COMPOSING) {
2318 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2319 } else if (state == ChatState.PAUSED) {
2320 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2321 } else {
2322 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2323 final Message message = this.messageList.get(i);
2324 if (message.getType() != Message.TYPE_STATUS) {
2325 if (message.getStatus() == Message.STATUS_RECEIVED) {
2326 return;
2327 } else {
2328 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
2329 this.messageList.add(i + 1,
2330 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2331 return;
2332 }
2333 }
2334 }
2335 }
2336 }
2337 } else {
2338 final MucOptions mucOptions = conversation.getMucOptions();
2339 final List<MucOptions.User> allUsers = mucOptions.getUsers();
2340 final Set<ReadByMarker> addedMarkers = new HashSet<>();
2341 ChatState state = ChatState.COMPOSING;
2342 List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2343 if (users.size() == 0) {
2344 state = ChatState.PAUSED;
2345 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2346 }
2347 if (mucOptions.isPrivateAndNonAnonymous()) {
2348 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2349 final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2350 final List<MucOptions.User> shownMarkers = new ArrayList<>();
2351 for (ReadByMarker marker : markersForMessage) {
2352 if (!ReadByMarker.contains(marker, addedMarkers)) {
2353 addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2354 MucOptions.User user = mucOptions.findUser(marker);
2355 if (user != null && !users.contains(user)) {
2356 shownMarkers.add(user);
2357 }
2358 }
2359 }
2360 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2361 final Message statusMessage;
2362 final int size = shownMarkers.size();
2363 if (size > 1) {
2364 final String body;
2365 if (size <= 4) {
2366 body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2367 } else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) {
2368 body = getString(R.string.everyone_has_read_up_to_this_point);
2369 } else {
2370 body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2371 }
2372 statusMessage = Message.createStatusMessage(conversation, body);
2373 statusMessage.setCounterparts(shownMarkers);
2374 } else if (size == 1) {
2375 statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2376 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2377 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2378 } else {
2379 statusMessage = null;
2380 }
2381 if (statusMessage != null) {
2382 this.messageList.add(i + 1, statusMessage);
2383 }
2384 addedMarkers.add(markerForSender);
2385 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2386 break;
2387 }
2388 }
2389 }
2390 if (users.size() > 0) {
2391 Message statusMessage;
2392 if (users.size() == 1) {
2393 MucOptions.User user = users.get(0);
2394 int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2395 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2396 statusMessage.setTrueCounterpart(user.getRealJid());
2397 statusMessage.setCounterpart(user.getFullJid());
2398 } else {
2399 int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2400 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2401 statusMessage.setCounterparts(users);
2402 }
2403 this.messageList.add(statusMessage);
2404 }
2405
2406 }
2407 }
2408 }
2409
2410 private void stopScrolling() {
2411 long now = SystemClock.uptimeMillis();
2412 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2413 binding.messagesView.dispatchTouchEvent(cancel);
2414 }
2415
2416 private boolean showLoadMoreMessages(final Conversation c) {
2417 if (activity == null || activity.xmppConnectionService == null) {
2418 return false;
2419 }
2420 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2421 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2422 return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2423 }
2424
2425 private boolean hasMamSupport(final Conversation c) {
2426 if (c.getMode() == Conversation.MODE_SINGLE) {
2427 final XmppConnection connection = c.getAccount().getXmppConnection();
2428 return connection != null && connection.getFeatures().mam();
2429 } else {
2430 return c.getMucOptions().mamSupport();
2431 }
2432 }
2433
2434 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2435 showSnackbar(message, action, clickListener, null);
2436 }
2437
2438 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2439 this.binding.snackbar.setVisibility(View.VISIBLE);
2440 this.binding.snackbar.setOnClickListener(null);
2441 this.binding.snackbarMessage.setText(message);
2442 this.binding.snackbarMessage.setOnClickListener(null);
2443 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2444 if (action != 0) {
2445 this.binding.snackbarAction.setText(action);
2446 }
2447 this.binding.snackbarAction.setOnClickListener(clickListener);
2448 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2449 }
2450
2451 protected void hideSnackbar() {
2452 this.binding.snackbar.setVisibility(View.GONE);
2453 }
2454
2455 protected void sendMessage(Message message) {
2456 activity.xmppConnectionService.sendMessage(message);
2457 messageSent();
2458 }
2459
2460 protected void sendPgpMessage(final Message message) {
2461 final XmppConnectionService xmppService = activity.xmppConnectionService;
2462 final Contact contact = message.getConversation().getContact();
2463 if (!activity.hasPgp()) {
2464 activity.showInstallPgpDialog();
2465 return;
2466 }
2467 if (conversation.getAccount().getPgpSignature() == null) {
2468 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2469 return;
2470 }
2471 if (!mSendingPgpMessage.compareAndSet(false, true)) {
2472 Log.d(Config.LOGTAG, "sending pgp message already in progress");
2473 }
2474 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2475 if (contact.getPgpKeyId() != 0) {
2476 xmppService.getPgpEngine().hasKey(contact,
2477 new UiCallback<Contact>() {
2478
2479 @Override
2480 public void userInputRequried(PendingIntent pi, Contact contact) {
2481 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2482 }
2483
2484 @Override
2485 public void success(Contact contact) {
2486 encryptTextMessage(message);
2487 }
2488
2489 @Override
2490 public void error(int error, Contact contact) {
2491 activity.runOnUiThread(() -> Toast.makeText(activity,
2492 R.string.unable_to_connect_to_keychain,
2493 Toast.LENGTH_SHORT
2494 ).show());
2495 mSendingPgpMessage.set(false);
2496 }
2497 });
2498
2499 } else {
2500 showNoPGPKeyDialog(false, (dialog, which) -> {
2501 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2502 xmppService.updateConversation(conversation);
2503 message.setEncryption(Message.ENCRYPTION_NONE);
2504 xmppService.sendMessage(message);
2505 messageSent();
2506 });
2507 }
2508 } else {
2509 if (conversation.getMucOptions().pgpKeysInUse()) {
2510 if (!conversation.getMucOptions().everybodyHasKeys()) {
2511 Toast warning = Toast
2512 .makeText(getActivity(),
2513 R.string.missing_public_keys,
2514 Toast.LENGTH_LONG);
2515 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2516 warning.show();
2517 }
2518 encryptTextMessage(message);
2519 } else {
2520 showNoPGPKeyDialog(true, (dialog, which) -> {
2521 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2522 message.setEncryption(Message.ENCRYPTION_NONE);
2523 xmppService.updateConversation(conversation);
2524 xmppService.sendMessage(message);
2525 messageSent();
2526 });
2527 }
2528 }
2529 }
2530
2531 public void encryptTextMessage(Message message) {
2532 activity.xmppConnectionService.getPgpEngine().encrypt(message,
2533 new UiCallback<Message>() {
2534
2535 @Override
2536 public void userInputRequried(PendingIntent pi, Message message) {
2537 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2538 }
2539
2540 @Override
2541 public void success(Message message) {
2542 //TODO the following two call can be made before the callback
2543 getActivity().runOnUiThread(() -> messageSent());
2544 }
2545
2546 @Override
2547 public void error(final int error, Message message) {
2548 getActivity().runOnUiThread(() -> {
2549 doneSendingPgpMessage();
2550 Toast.makeText(getActivity(), error == 0 ? R.string.unable_to_connect_to_keychain : error, Toast.LENGTH_SHORT).show();
2551 });
2552
2553 }
2554 });
2555 }
2556
2557 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2558 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2559 builder.setIconAttribute(android.R.attr.alertDialogIcon);
2560 if (plural) {
2561 builder.setTitle(getString(R.string.no_pgp_keys));
2562 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2563 } else {
2564 builder.setTitle(getString(R.string.no_pgp_key));
2565 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2566 }
2567 builder.setNegativeButton(getString(R.string.cancel), null);
2568 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2569 builder.create().show();
2570 }
2571
2572 public void appendText(String text, final boolean doNotAppend) {
2573 if (text == null) {
2574 return;
2575 }
2576 final Editable editable = this.binding.textinput.getText();
2577 String previous = editable == null ? "" : editable.toString();
2578 if (doNotAppend && !TextUtils.isEmpty(previous)) {
2579 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG).show();
2580 return;
2581 }
2582 if (UIHelper.isLastLineQuote(previous)) {
2583 text = '\n' + text;
2584 } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
2585 text = " " + text;
2586 }
2587 this.binding.textinput.append(text);
2588 }
2589
2590 @Override
2591 public boolean onEnterPressed() {
2592 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2593 final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2594 if (enterIsSend) {
2595 sendMessage();
2596 return true;
2597 } else {
2598 return false;
2599 }
2600 }
2601
2602 @Override
2603 public void onTypingStarted() {
2604 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2605 if (service == null) {
2606 return;
2607 }
2608 Account.State status = conversation.getAccount().getStatus();
2609 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2610 service.sendChatState(conversation);
2611 }
2612 updateSendButton();
2613 }
2614
2615 @Override
2616 public void onTypingStopped() {
2617 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2618 if (service == null) {
2619 return;
2620 }
2621 Account.State status = conversation.getAccount().getStatus();
2622 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2623 service.sendChatState(conversation);
2624 }
2625 }
2626
2627 @Override
2628 public void onTextDeleted() {
2629 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2630 if (service == null) {
2631 return;
2632 }
2633 Account.State status = conversation.getAccount().getStatus();
2634 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2635 service.sendChatState(conversation);
2636 }
2637 if (storeNextMessage()) {
2638 activity.onConversationsListItemUpdated();
2639 }
2640 updateSendButton();
2641 }
2642
2643 @Override
2644 public void onTextChanged() {
2645 if (conversation != null && conversation.getCorrectingMessage() != null) {
2646 updateSendButton();
2647 }
2648 }
2649
2650 @Override
2651 public boolean onTabPressed(boolean repeated) {
2652 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2653 return false;
2654 }
2655 if (repeated) {
2656 completionIndex++;
2657 } else {
2658 lastCompletionLength = 0;
2659 completionIndex = 0;
2660 final String content = this.binding.textinput.getText().toString();
2661 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2662 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2663 firstWord = start == 0;
2664 incomplete = content.substring(start, lastCompletionCursor);
2665 }
2666 List<String> completions = new ArrayList<>();
2667 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2668 String name = user.getName();
2669 if (name != null && name.startsWith(incomplete)) {
2670 completions.add(name + (firstWord ? ": " : " "));
2671 }
2672 }
2673 Collections.sort(completions);
2674 if (completions.size() > completionIndex) {
2675 String completion = completions.get(completionIndex).substring(incomplete.length());
2676 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2677 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2678 lastCompletionLength = completion.length();
2679 } else {
2680 completionIndex = -1;
2681 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2682 lastCompletionLength = 0;
2683 }
2684 return true;
2685 }
2686
2687 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2688 try {
2689 getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2690 } catch (final SendIntentException ignored) {
2691 }
2692 }
2693
2694 @Override
2695 public void onBackendConnected() {
2696 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2697 String uuid = pendingConversationsUuid.pop();
2698 if (uuid != null) {
2699 if (!findAndReInitByUuidOrArchive(uuid)) {
2700 return;
2701 }
2702 } else {
2703 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2704 clearPending();
2705 activity.onConversationArchived(conversation);
2706 return;
2707 }
2708 }
2709 ActivityResult activityResult = postponedActivityResult.pop();
2710 if (activityResult != null) {
2711 handleActivityResult(activityResult);
2712 }
2713 clearPending();
2714 }
2715
2716 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2717 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2718 if (conversation == null) {
2719 clearPending();
2720 activity.onConversationArchived(null);
2721 return false;
2722 }
2723 reInit(conversation);
2724 ScrollState scrollState = pendingScrollState.pop();
2725 String lastMessageUuid = pendingLastMessageUuid.pop();
2726 List<Attachment> attachments = pendingMediaPreviews.pop();
2727 if (scrollState != null) {
2728 setScrollPosition(scrollState, lastMessageUuid);
2729 }
2730 if (attachments != null && attachments.size() > 0) {
2731 Log.d(Config.LOGTAG, "had attachments on restore");
2732 mediaPreviewAdapter.addMediaPreviews(attachments);
2733 toggleInputMethod();
2734 }
2735 return true;
2736 }
2737
2738 private void clearPending() {
2739 if (postponedActivityResult.clear()) {
2740 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2741 }
2742 if (pendingScrollState.clear()) {
2743 Log.e(Config.LOGTAG, "cleared scroll state");
2744 }
2745 if (pendingTakePhotoUri.clear()) {
2746 Log.e(Config.LOGTAG, "cleared pending photo uri");
2747 }
2748 }
2749
2750 public Conversation getConversation() {
2751 return conversation;
2752 }
2753}