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