1package eu.siacs.conversations.ui;
2
3import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
4import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION;
5import static eu.siacs.conversations.ui.util.SoftKeyboardUtils.hideSoftKeyboard;
6import static eu.siacs.conversations.utils.PermissionUtils.allGranted;
7import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
8import static eu.siacs.conversations.utils.PermissionUtils.writeGranted;
9
10import android.Manifest;
11import android.annotation.SuppressLint;
12import android.app.Activity;
13import android.app.Fragment;
14import android.app.FragmentManager;
15import android.app.PendingIntent;
16import android.content.ActivityNotFoundException;
17import android.content.Context;
18import android.content.DialogInterface;
19import android.content.Intent;
20import android.content.IntentSender.SendIntentException;
21import android.content.SharedPreferences;
22import android.content.pm.PackageManager;
23import android.net.Uri;
24import android.os.Build;
25import android.os.Bundle;
26import android.os.Handler;
27import android.os.SystemClock;
28import android.preference.PreferenceManager;
29import android.provider.MediaStore;
30import android.text.Editable;
31import android.text.TextUtils;
32import android.util.Log;
33import android.view.ContextMenu;
34import android.view.ContextMenu.ContextMenuInfo;
35import android.view.Gravity;
36import android.view.LayoutInflater;
37import android.view.Menu;
38import android.view.MenuInflater;
39import android.view.MenuItem;
40import android.view.MotionEvent;
41import android.view.View;
42import android.view.View.OnClickListener;
43import android.view.ViewGroup;
44import android.view.inputmethod.EditorInfo;
45import android.view.inputmethod.InputMethodManager;
46import android.widget.AbsListView;
47import android.widget.AbsListView.OnScrollListener;
48import android.widget.AdapterView;
49import android.widget.AdapterView.AdapterContextMenuInfo;
50import android.widget.CheckBox;
51import android.widget.ListView;
52import android.widget.PopupMenu;
53import android.widget.TextView.OnEditorActionListener;
54import android.widget.Toast;
55
56import androidx.annotation.IdRes;
57import androidx.annotation.NonNull;
58import androidx.annotation.Nullable;
59import androidx.annotation.StringRes;
60import androidx.appcompat.app.AlertDialog;
61import androidx.core.view.inputmethod.InputConnectionCompat;
62import androidx.core.view.inputmethod.InputContentInfoCompat;
63import androidx.databinding.DataBindingUtil;
64import androidx.viewpager.widget.PagerAdapter;
65import androidx.viewpager.widget.ViewPager;
66
67import com.cheogram.android.BobTransfer;
68
69import com.google.common.base.Optional;
70import com.google.common.collect.ImmutableList;
71
72import org.jetbrains.annotations.NotNull;
73
74import java.net.URISyntaxException;
75import java.util.ArrayList;
76import java.util.Arrays;
77import java.util.Collection;
78import java.util.Collections;
79import java.util.HashSet;
80import java.util.Iterator;
81import java.util.List;
82import java.util.Map;
83import java.util.Set;
84import java.util.UUID;
85import java.util.concurrent.atomic.AtomicBoolean;
86
87import eu.siacs.conversations.Config;
88import eu.siacs.conversations.R;
89import eu.siacs.conversations.crypto.axolotl.AxolotlService;
90import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
91import eu.siacs.conversations.databinding.FragmentConversationBinding;
92import eu.siacs.conversations.entities.Account;
93import eu.siacs.conversations.entities.Blockable;
94import eu.siacs.conversations.entities.Contact;
95import eu.siacs.conversations.entities.Conversation;
96import eu.siacs.conversations.entities.Conversational;
97import eu.siacs.conversations.entities.DownloadableFile;
98import eu.siacs.conversations.entities.Message;
99import eu.siacs.conversations.entities.MucOptions;
100import eu.siacs.conversations.entities.MucOptions.User;
101import eu.siacs.conversations.entities.Presence;
102import eu.siacs.conversations.entities.Presences;
103import eu.siacs.conversations.entities.ReadByMarker;
104import eu.siacs.conversations.entities.Transferable;
105import eu.siacs.conversations.entities.TransferablePlaceholder;
106import eu.siacs.conversations.http.HttpDownloadConnection;
107import eu.siacs.conversations.persistance.FileBackend;
108import eu.siacs.conversations.services.MessageArchiveService;
109import eu.siacs.conversations.services.QuickConversationsService;
110import eu.siacs.conversations.services.XmppConnectionService;
111import eu.siacs.conversations.ui.adapter.CommandAdapter;
112import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
113import eu.siacs.conversations.ui.adapter.MessageAdapter;
114import eu.siacs.conversations.ui.util.ActivityResult;
115import eu.siacs.conversations.ui.util.Attachment;
116import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
117import eu.siacs.conversations.ui.util.DateSeparator;
118import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
119import eu.siacs.conversations.ui.util.ListViewUtils;
120import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
121import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
122import eu.siacs.conversations.ui.util.PendingItem;
123import eu.siacs.conversations.ui.util.PresenceSelector;
124import eu.siacs.conversations.ui.util.ScrollState;
125import eu.siacs.conversations.ui.util.SendButtonAction;
126import eu.siacs.conversations.ui.util.SendButtonTool;
127import eu.siacs.conversations.ui.util.ShareUtil;
128import eu.siacs.conversations.ui.util.ViewUtil;
129import eu.siacs.conversations.ui.widget.EditMessage;
130import eu.siacs.conversations.utils.AccountUtils;
131import eu.siacs.conversations.utils.Compatibility;
132import eu.siacs.conversations.utils.GeoHelper;
133import eu.siacs.conversations.utils.MessageUtils;
134import eu.siacs.conversations.utils.NickValidityChecker;
135import eu.siacs.conversations.utils.Patterns;
136import eu.siacs.conversations.utils.PermissionUtils;
137import eu.siacs.conversations.utils.QuickLoader;
138import eu.siacs.conversations.utils.StylingHelper;
139import eu.siacs.conversations.utils.TimeFrameUtils;
140import eu.siacs.conversations.utils.UIHelper;
141import eu.siacs.conversations.xml.Element;
142import eu.siacs.conversations.xml.Namespace;
143import eu.siacs.conversations.xmpp.Jid;
144import eu.siacs.conversations.xmpp.XmppConnection;
145import eu.siacs.conversations.xmpp.chatstate.ChatState;
146import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
147import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
148import eu.siacs.conversations.xmpp.jingle.JingleFileTransferConnection;
149import eu.siacs.conversations.xmpp.jingle.Media;
150import eu.siacs.conversations.xmpp.jingle.OngoingRtpSession;
151import eu.siacs.conversations.xmpp.jingle.RtpCapability;
152import eu.siacs.conversations.xmpp.stanzas.IqPacket;
153
154public class ConversationFragment extends XmppFragment
155 implements EditMessage.KeyboardListener,
156 MessageAdapter.OnContactPictureLongClicked,
157 MessageAdapter.OnContactPictureClicked {
158
159 public static final int REQUEST_SEND_MESSAGE = 0x0201;
160 public static final int REQUEST_DECRYPT_PGP = 0x0202;
161 public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
162 public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
163 public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209;
164 public static final int REQUEST_START_DOWNLOAD = 0x0210;
165 public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
166 public static final int REQUEST_COMMIT_ATTACHMENTS = 0x0212;
167 public static final int REQUEST_START_AUDIO_CALL = 0x213;
168 public static final int REQUEST_START_VIDEO_CALL = 0x214;
169 public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
170 public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
171 public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
172 public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
173 public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
174 public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
175 public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
176
177 public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
178 public static final String STATE_CONVERSATION_UUID =
179 ConversationFragment.class.getName() + ".uuid";
180 public static final String STATE_SCROLL_POSITION =
181 ConversationFragment.class.getName() + ".scroll_position";
182 public static final String STATE_PHOTO_URI =
183 ConversationFragment.class.getName() + ".media_previews";
184 public static final String STATE_MEDIA_PREVIEWS =
185 ConversationFragment.class.getName() + ".take_photo_uri";
186 private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid";
187
188 private final List<Message> messageList = new ArrayList<>();
189 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
190 private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
191 private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>();
192 private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
193 private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
194 private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
195 private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>();
196 private final PendingItem<Message> pendingMessage = new PendingItem<>();
197 public Uri mPendingEditorContent = null;
198 protected MessageAdapter messageListAdapter;
199 protected CommandAdapter commandAdapter;
200 private MediaPreviewAdapter mediaPreviewAdapter;
201 private String lastMessageUuid = null;
202 private Conversation conversation;
203 private FragmentConversationBinding binding;
204 private Toast messageLoaderToast;
205 private ConversationsActivity activity;
206 private boolean reInitRequiredOnStart = true;
207 private final OnClickListener clickToMuc =
208 new OnClickListener() {
209
210 @Override
211 public void onClick(View v) {
212 ConferenceDetailsActivity.open(getActivity(), conversation);
213 }
214 };
215 private final OnClickListener leaveMuc =
216 new OnClickListener() {
217
218 @Override
219 public void onClick(View v) {
220 activity.xmppConnectionService.archiveConversation(conversation);
221 }
222 };
223 private final OnClickListener joinMuc =
224 new OnClickListener() {
225
226 @Override
227 public void onClick(View v) {
228 activity.xmppConnectionService.joinMuc(conversation);
229 }
230 };
231
232 private final OnClickListener acceptJoin =
233 new OnClickListener() {
234 @Override
235 public void onClick(View v) {
236 conversation.setAttribute("accept_non_anonymous", true);
237 activity.xmppConnectionService.updateConversation(conversation);
238 activity.xmppConnectionService.joinMuc(conversation);
239 }
240 };
241
242 private final OnClickListener enterPassword =
243 new OnClickListener() {
244
245 @Override
246 public void onClick(View v) {
247 MucOptions muc = conversation.getMucOptions();
248 String password = muc.getPassword();
249 if (password == null) {
250 password = "";
251 }
252 activity.quickPasswordEdit(
253 password,
254 value -> {
255 activity.xmppConnectionService.providePasswordForMuc(
256 conversation, value);
257 return null;
258 });
259 }
260 };
261 private final OnScrollListener mOnScrollListener =
262 new OnScrollListener() {
263
264 @Override
265 public void onScrollStateChanged(AbsListView view, int scrollState) {
266 if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
267 fireReadEvent();
268 }
269 }
270
271 @Override
272 public void onScroll(
273 final AbsListView view,
274 int firstVisibleItem,
275 int visibleItemCount,
276 int totalItemCount) {
277 toggleScrollDownButton(view);
278 synchronized (ConversationFragment.this.messageList) {
279 if (firstVisibleItem < 5
280 && conversation != null
281 && conversation.messagesLoaded.compareAndSet(true, false)
282 && messageList.size() > 0) {
283 long timestamp;
284 if (messageList.get(0).getType() == Message.TYPE_STATUS
285 && messageList.size() >= 2) {
286 timestamp = messageList.get(1).getTimeSent();
287 } else {
288 timestamp = messageList.get(0).getTimeSent();
289 }
290 activity.xmppConnectionService.loadMoreMessages(
291 conversation,
292 timestamp,
293 new XmppConnectionService.OnMoreMessagesLoaded() {
294 @Override
295 public void onMoreMessagesLoaded(
296 final int c, final Conversation conversation) {
297 if (ConversationFragment.this.conversation
298 != conversation) {
299 conversation.messagesLoaded.set(true);
300 return;
301 }
302 runOnUiThread(
303 () -> {
304 synchronized (messageList) {
305 final int oldPosition =
306 binding.messagesView
307 .getFirstVisiblePosition();
308 Message message = null;
309 int childPos;
310 for (childPos = 0;
311 childPos + oldPosition
312 < messageList.size();
313 ++childPos) {
314 message =
315 messageList.get(
316 oldPosition
317 + childPos);
318 if (message.getType()
319 != Message.TYPE_STATUS) {
320 break;
321 }
322 }
323 final String uuid =
324 message != null
325 ? message.getUuid()
326 : null;
327 View v =
328 binding.messagesView.getChildAt(
329 childPos);
330 final int pxOffset =
331 (v == null) ? 0 : v.getTop();
332 ConversationFragment.this.conversation
333 .populateWithMessages(
334 ConversationFragment
335 .this
336 .messageList);
337 try {
338 updateStatusMessages();
339 } catch (IllegalStateException e) {
340 Log.d(
341 Config.LOGTAG,
342 "caught illegal state exception while updating status messages");
343 }
344 messageListAdapter
345 .notifyDataSetChanged();
346 int pos =
347 Math.max(
348 getIndexOf(
349 uuid,
350 messageList),
351 0);
352 binding.messagesView
353 .setSelectionFromTop(
354 pos, pxOffset);
355 if (messageLoaderToast != null) {
356 messageLoaderToast.cancel();
357 }
358 conversation.messagesLoaded.set(true);
359 }
360 });
361 }
362
363 @Override
364 public void informUser(final int resId) {
365
366 runOnUiThread(
367 () -> {
368 if (messageLoaderToast != null) {
369 messageLoaderToast.cancel();
370 }
371 if (ConversationFragment.this.conversation
372 != conversation) {
373 return;
374 }
375 messageLoaderToast =
376 Toast.makeText(
377 view.getContext(),
378 resId,
379 Toast.LENGTH_LONG);
380 messageLoaderToast.show();
381 });
382 }
383 });
384 }
385 }
386 }
387 };
388 private final EditMessage.OnCommitContentListener mEditorContentListener =
389 new EditMessage.OnCommitContentListener() {
390 @Override
391 public boolean onCommitContent(
392 InputContentInfoCompat inputContentInfo,
393 int flags,
394 Bundle opts,
395 String[] contentMimeTypes) {
396 // try to get permission to read the image, if applicable
397 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION)
398 != 0) {
399 try {
400 inputContentInfo.requestPermission();
401 } catch (Exception e) {
402 Log.e(
403 Config.LOGTAG,
404 "InputContentInfoCompat#requestPermission() failed.",
405 e);
406 Toast.makeText(
407 getActivity(),
408 activity.getString(
409 R.string.no_permission_to_access_x,
410 inputContentInfo.getDescription()),
411 Toast.LENGTH_LONG)
412 .show();
413 return false;
414 }
415 }
416 if (hasPermissions(
417 REQUEST_ADD_EDITOR_CONTENT,
418 Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
419 attachEditorContentToConversation(inputContentInfo.getContentUri());
420 } else {
421 mPendingEditorContent = inputContentInfo.getContentUri();
422 }
423 return true;
424 }
425 };
426 private Message selectedMessage;
427 private final OnClickListener mEnableAccountListener =
428 new OnClickListener() {
429 @Override
430 public void onClick(View v) {
431 final Account account = conversation == null ? null : conversation.getAccount();
432 if (account != null) {
433 account.setOption(Account.OPTION_DISABLED, false);
434 activity.xmppConnectionService.updateAccount(account);
435 }
436 }
437 };
438 private final OnClickListener mUnblockClickListener =
439 new OnClickListener() {
440 @Override
441 public void onClick(final View v) {
442 v.post(() -> v.setVisibility(View.INVISIBLE));
443 if (conversation.isDomainBlocked()) {
444 BlockContactDialog.show(activity, conversation);
445 } else {
446 unblockConversation(conversation);
447 }
448 }
449 };
450 private final OnClickListener mBlockClickListener = this::showBlockSubmenu;
451 private final OnClickListener mAddBackClickListener =
452 new OnClickListener() {
453
454 @Override
455 public void onClick(View v) {
456 final Contact contact = conversation == null ? null : conversation.getContact();
457 if (contact != null) {
458 activity.xmppConnectionService.createContact(contact, true);
459 activity.switchToContactDetails(contact);
460 }
461 }
462 };
463 private final View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
464 private final OnClickListener mAllowPresenceSubscription =
465 new OnClickListener() {
466 @Override
467 public void onClick(View v) {
468 final Contact contact = conversation == null ? null : conversation.getContact();
469 if (contact != null) {
470 activity.xmppConnectionService.sendPresencePacket(
471 contact.getAccount(),
472 activity.xmppConnectionService
473 .getPresenceGenerator()
474 .sendPresenceUpdatesTo(contact));
475 hideSnackbar();
476 }
477 }
478 };
479 protected OnClickListener clickToDecryptListener =
480 new OnClickListener() {
481
482 @Override
483 public void onClick(View v) {
484 PendingIntent pendingIntent =
485 conversation.getAccount().getPgpDecryptionService().getPendingIntent();
486 if (pendingIntent != null) {
487 try {
488 getActivity()
489 .startIntentSenderForResult(
490 pendingIntent.getIntentSender(),
491 REQUEST_DECRYPT_PGP,
492 null,
493 0,
494 0,
495 0);
496 } catch (SendIntentException e) {
497 Toast.makeText(
498 getActivity(),
499 R.string.unable_to_connect_to_keychain,
500 Toast.LENGTH_SHORT)
501 .show();
502 conversation
503 .getAccount()
504 .getPgpDecryptionService()
505 .continueDecryption(true);
506 }
507 }
508 updateSnackBar(conversation);
509 }
510 };
511 private final AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
512 private final OnEditorActionListener mEditorActionListener =
513 (v, actionId, event) -> {
514 if (actionId == EditorInfo.IME_ACTION_SEND) {
515 InputMethodManager imm =
516 (InputMethodManager)
517 activity.getSystemService(Context.INPUT_METHOD_SERVICE);
518 if (imm != null && imm.isFullscreenMode()) {
519 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
520 }
521 sendMessage();
522 return true;
523 } else {
524 return false;
525 }
526 };
527 private final OnClickListener mScrollButtonListener =
528 new OnClickListener() {
529
530 @Override
531 public void onClick(View v) {
532 stopScrolling();
533 setSelection(binding.messagesView.getCount() - 1, true);
534 }
535 };
536 private final OnClickListener mSendButtonListener =
537 new OnClickListener() {
538
539 @Override
540 public void onClick(View v) {
541 Object tag = v.getTag();
542 if (tag instanceof SendButtonAction) {
543 SendButtonAction action = (SendButtonAction) tag;
544 switch (action) {
545 case TAKE_PHOTO:
546 case RECORD_VIDEO:
547 case SEND_LOCATION:
548 case RECORD_VOICE:
549 case CHOOSE_PICTURE:
550 attachFile(action.toChoice());
551 break;
552 case CANCEL:
553 if (conversation != null) {
554 if (conversation.setCorrectingMessage(null)) {
555 binding.textinput.setText("");
556 binding.textinput.append(conversation.getDraftMessage());
557 conversation.setDraftMessage(null);
558 } else if (conversation.getMode() == Conversation.MODE_MULTI) {
559 conversation.setNextCounterpart(null);
560 binding.textinput.setText("");
561 } else {
562 binding.textinput.setText("");
563 }
564 updateChatMsgHint();
565 updateSendButton();
566 updateEditablity();
567 }
568 break;
569 default:
570 sendMessage();
571 }
572 } else {
573 sendMessage();
574 }
575 }
576 };
577 private int completionIndex = 0;
578 private int lastCompletionLength = 0;
579 private String incomplete;
580 private int lastCompletionCursor;
581 private boolean firstWord = false;
582 private Message mPendingDownloadableMessage;
583
584 private static ConversationFragment findConversationFragment(Activity activity) {
585 Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
586 if (fragment instanceof ConversationFragment) {
587 return (ConversationFragment) fragment;
588 }
589 fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
590 if (fragment instanceof ConversationFragment) {
591 return (ConversationFragment) fragment;
592 }
593 return null;
594 }
595
596 public static void startStopPending(Activity activity) {
597 ConversationFragment fragment = findConversationFragment(activity);
598 if (fragment != null) {
599 fragment.messageListAdapter.startStopPending();
600 }
601 }
602
603 public static void downloadFile(Activity activity, Message message) {
604 ConversationFragment fragment = findConversationFragment(activity);
605 if (fragment != null) {
606 fragment.startDownloadable(message);
607 }
608 }
609
610 public static void registerPendingMessage(Activity activity, Message message) {
611 ConversationFragment fragment = findConversationFragment(activity);
612 if (fragment != null) {
613 fragment.pendingMessage.push(message);
614 }
615 }
616
617 public static void openPendingMessage(Activity activity) {
618 ConversationFragment fragment = findConversationFragment(activity);
619 if (fragment != null) {
620 Message message = fragment.pendingMessage.pop();
621 if (message != null) {
622 fragment.messageListAdapter.openDownloadable(message);
623 }
624 }
625 }
626
627 public static Conversation getConversation(Activity activity) {
628 return getConversation(activity, R.id.secondary_fragment);
629 }
630
631 private static Conversation getConversation(Activity activity, @IdRes int res) {
632 final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
633 if (fragment instanceof ConversationFragment) {
634 return ((ConversationFragment) fragment).getConversation();
635 } else {
636 return null;
637 }
638 }
639
640 public static ConversationFragment get(Activity activity) {
641 FragmentManager fragmentManager = activity.getFragmentManager();
642 Fragment fragment = fragmentManager.findFragmentById(R.id.main_fragment);
643 if (fragment instanceof ConversationFragment) {
644 return (ConversationFragment) fragment;
645 } else {
646 fragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
647 return fragment instanceof ConversationFragment
648 ? (ConversationFragment) fragment
649 : null;
650 }
651 }
652
653 public static Conversation getConversationReliable(Activity activity) {
654 final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
655 if (conversation != null) {
656 return conversation;
657 }
658 return getConversation(activity, R.id.main_fragment);
659 }
660
661 private static boolean scrolledToBottom(AbsListView listView) {
662 final int count = listView.getCount();
663 if (count == 0) {
664 return true;
665 } else if (listView.getLastVisiblePosition() == count - 1) {
666 final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
667 return lastChild != null && lastChild.getBottom() <= listView.getHeight();
668 } else {
669 return false;
670 }
671 }
672
673 private void toggleScrollDownButton() {
674 toggleScrollDownButton(binding.messagesView);
675 }
676
677 private void toggleScrollDownButton(AbsListView listView) {
678 if (conversation == null) {
679 return;
680 }
681 if (scrolledToBottom(listView)) {
682 lastMessageUuid = null;
683 hideUnreadMessagesCount();
684 } else {
685 binding.scrollToBottomButton.setEnabled(true);
686 binding.scrollToBottomButton.show();
687 if (lastMessageUuid == null) {
688 lastMessageUuid = conversation.getLatestMessage().getUuid();
689 }
690 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) > 0) {
691 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
692 }
693 }
694 }
695
696 private int getIndexOf(String uuid, List<Message> messages) {
697 if (uuid == null) {
698 return messages.size() - 1;
699 }
700 for (int i = 0; i < messages.size(); ++i) {
701 if (uuid.equals(messages.get(i).getUuid())) {
702 return i;
703 } else {
704 Message next = messages.get(i);
705 while (next != null && next.wasMergedIntoPrevious()) {
706 if (uuid.equals(next.getUuid())) {
707 return i;
708 }
709 next = next.next();
710 }
711 }
712 }
713 return -1;
714 }
715
716 private ScrollState getScrollPosition() {
717 final ListView listView = this.binding == null ? null : this.binding.messagesView;
718 if (listView == null
719 || listView.getCount() == 0
720 || listView.getLastVisiblePosition() == listView.getCount() - 1) {
721 return null;
722 } else {
723 final int pos = listView.getFirstVisiblePosition();
724 final View view = listView.getChildAt(0);
725 if (view == null) {
726 return null;
727 } else {
728 return new ScrollState(pos, view.getTop());
729 }
730 }
731 }
732
733 private void setScrollPosition(ScrollState scrollPosition, String lastMessageUuid) {
734 if (scrollPosition != null) {
735
736 this.lastMessageUuid = lastMessageUuid;
737 if (lastMessageUuid != null) {
738 binding.unreadCountCustomView.setUnreadCount(
739 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
740 }
741 // TODO maybe this needs a 'post'
742 this.binding.messagesView.setSelectionFromTop(
743 scrollPosition.position, scrollPosition.offset);
744 toggleScrollDownButton();
745 }
746 }
747
748 private void attachLocationToConversation(Conversation conversation, Uri uri) {
749 if (conversation == null) {
750 return;
751 }
752 activity.xmppConnectionService.attachLocationToConversation(
753 conversation,
754 uri,
755 new UiCallback<Message>() {
756
757 @Override
758 public void success(Message message) {}
759
760 @Override
761 public void error(int errorCode, Message object) {
762 // TODO show possible pgp error
763 }
764
765 @Override
766 public void userInputRequired(PendingIntent pi, Message object) {}
767 });
768 }
769
770 private void attachFileToConversation(Conversation conversation, Uri uri, String type) {
771 if (conversation == null) {
772 return;
773 }
774 final Toast prepareFileToast =
775 Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
776 prepareFileToast.show();
777 activity.delegateUriPermissionsToService(uri);
778 activity.xmppConnectionService.attachFileToConversation(
779 conversation,
780 uri,
781 type,
782 new UiInformableCallback<Message>() {
783 @Override
784 public void inform(final String text) {
785 hidePrepareFileToast(prepareFileToast);
786 runOnUiThread(() -> activity.replaceToast(text));
787 }
788
789 @Override
790 public void success(Message message) {
791 runOnUiThread(() -> activity.hideToast());
792 hidePrepareFileToast(prepareFileToast);
793 }
794
795 @Override
796 public void error(final int errorCode, Message message) {
797 hidePrepareFileToast(prepareFileToast);
798 runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
799 }
800
801 @Override
802 public void userInputRequired(PendingIntent pi, Message message) {
803 hidePrepareFileToast(prepareFileToast);
804 }
805 });
806 }
807
808 public void attachEditorContentToConversation(Uri uri) {
809 mediaPreviewAdapter.addMediaPreviews(
810 Attachment.of(getActivity(), uri, Attachment.Type.FILE));
811 toggleInputMethod();
812 }
813
814 private void attachImageToConversation(Conversation conversation, Uri uri, String type) {
815 if (conversation == null) {
816 return;
817 }
818 final Toast prepareFileToast =
819 Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
820 prepareFileToast.show();
821 activity.delegateUriPermissionsToService(uri);
822 activity.xmppConnectionService.attachImageToConversation(
823 conversation,
824 uri,
825 type,
826 new UiCallback<Message>() {
827
828 @Override
829 public void userInputRequired(PendingIntent pi, Message object) {
830 hidePrepareFileToast(prepareFileToast);
831 }
832
833 @Override
834 public void success(Message message) {
835 hidePrepareFileToast(prepareFileToast);
836 }
837
838 @Override
839 public void error(final int error, final Message message) {
840 hidePrepareFileToast(prepareFileToast);
841 final ConversationsActivity activity = ConversationFragment.this.activity;
842 if (activity == null) {
843 return;
844 }
845 activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
846 }
847 });
848 }
849
850 private void hidePrepareFileToast(final Toast prepareFileToast) {
851 if (prepareFileToast != null && activity != null) {
852 activity.runOnUiThread(prepareFileToast::cancel);
853 }
854 }
855
856 private void sendMessage() {
857 if (mediaPreviewAdapter.hasAttachments()) {
858 commitAttachments();
859 return;
860 }
861 final Editable text = this.binding.textinput.getText();
862 final String body = text == null ? "" : text.toString();
863 final Conversation conversation = this.conversation;
864 if (body.length() == 0 || conversation == null) {
865 return;
866 }
867 if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_TEXT)) {
868 return;
869 }
870 final Message message;
871 if (conversation.getCorrectingMessage() == null) {
872 message = new Message(conversation, body, conversation.getNextEncryption());
873 message.setThread(conversation.getThread());
874 Message.configurePrivateMessage(message);
875 } else {
876 message = conversation.getCorrectingMessage();
877 message.setBody(body);
878 message.putEdited(message.getUuid(), message.getServerMsgId());
879 message.setServerMsgId(null);
880 message.setUuid(UUID.randomUUID().toString());
881 }
882 switch (conversation.getNextEncryption()) {
883 case Message.ENCRYPTION_PGP:
884 sendPgpMessage(message);
885 break;
886 default:
887 sendMessage(message);
888 }
889 }
890
891 private boolean trustKeysIfNeeded(final Conversation conversation, final int requestCode) {
892 return conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL
893 && trustKeysIfNeeded(requestCode);
894 }
895
896 protected boolean trustKeysIfNeeded(int requestCode) {
897 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
898 final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
899 boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
900 boolean hasUndecidedOwn =
901 !axolotlService
902 .getKeysWithTrust(FingerprintStatus.createActiveUndecided())
903 .isEmpty();
904 boolean hasUndecidedContacts =
905 !axolotlService
906 .getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets)
907 .isEmpty();
908 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
909 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
910 boolean downloadInProgress = axolotlService.hasPendingKeyFetches(targets);
911 if (hasUndecidedOwn
912 || hasUndecidedContacts
913 || hasPendingKeys
914 || hasNoTrustedKeys
915 || hasUnaccepted
916 || downloadInProgress) {
917 axolotlService.createSessionsIfNeeded(conversation);
918 Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
919 String[] contacts = new String[targets.size()];
920 for (int i = 0; i < contacts.length; ++i) {
921 contacts[i] = targets.get(i).toString();
922 }
923 intent.putExtra("contacts", contacts);
924 intent.putExtra(
925 EXTRA_ACCOUNT,
926 conversation.getAccount().getJid().asBareJid().toEscapedString());
927 intent.putExtra("conversation", conversation.getUuid());
928 startActivityForResult(intent, requestCode);
929 return true;
930 } else {
931 return false;
932 }
933 }
934
935 public void updateChatMsgHint() {
936 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
937 if (conversation.getCorrectingMessage() != null) {
938 this.binding.textInputHint.setVisibility(View.GONE);
939 this.binding.textinput.setHint(R.string.send_corrected_message);
940 binding.conversationViewPager.setCurrentItem(0);
941 } else if (multi && conversation.getNextCounterpart() != null) {
942 this.binding.textinput.setHint(R.string.send_message);
943 this.binding.textInputHint.setVisibility(View.VISIBLE);
944 this.binding.textInputHint.setText(
945 getString(
946 R.string.send_private_message_to,
947 conversation.getNextCounterpart().getResource()));
948 binding.conversationViewPager.setCurrentItem(0);
949 } else if (multi && !conversation.getMucOptions().participating()) {
950 this.binding.textInputHint.setVisibility(View.GONE);
951 this.binding.textinput.setHint(R.string.you_are_not_participating);
952 } else {
953 this.binding.textInputHint.setVisibility(View.GONE);
954 this.binding.textinput.setHint(UIHelper.getMessageHint(getActivity(), conversation));
955 getActivity().invalidateOptionsMenu();
956 }
957
958 binding.messagesView.post(this::updateThreadFromLastMessage);
959 }
960
961 public void setupIme() {
962 this.binding.textinput.refreshIme();
963 }
964
965 private void handleActivityResult(ActivityResult activityResult) {
966 if (activityResult.resultCode == Activity.RESULT_OK) {
967 handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
968 } else {
969 handleNegativeActivityResult(activityResult.requestCode);
970 }
971 }
972
973 private void handlePositiveActivityResult(int requestCode, final Intent data) {
974 switch (requestCode) {
975 case REQUEST_TRUST_KEYS_TEXT:
976 sendMessage();
977 break;
978 case REQUEST_TRUST_KEYS_ATTACHMENTS:
979 commitAttachments();
980 break;
981 case REQUEST_START_AUDIO_CALL:
982 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
983 break;
984 case REQUEST_START_VIDEO_CALL:
985 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
986 break;
987 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
988 final List<Attachment> imageUris =
989 Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE);
990 mediaPreviewAdapter.addMediaPreviews(imageUris);
991 toggleInputMethod();
992 break;
993 case ATTACHMENT_CHOICE_TAKE_PHOTO:
994 final Uri takePhotoUri = pendingTakePhotoUri.pop();
995 if (takePhotoUri != null) {
996 mediaPreviewAdapter.addMediaPreviews(
997 Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
998 toggleInputMethod();
999 } else {
1000 Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
1001 }
1002 break;
1003 case ATTACHMENT_CHOICE_CHOOSE_FILE:
1004 case ATTACHMENT_CHOICE_RECORD_VIDEO:
1005 case ATTACHMENT_CHOICE_RECORD_VOICE:
1006 final Attachment.Type type =
1007 requestCode == ATTACHMENT_CHOICE_RECORD_VOICE
1008 ? Attachment.Type.RECORDING
1009 : Attachment.Type.FILE;
1010 final List<Attachment> fileUris =
1011 Attachment.extractAttachments(getActivity(), data, type);
1012 mediaPreviewAdapter.addMediaPreviews(fileUris);
1013 toggleInputMethod();
1014 break;
1015 case ATTACHMENT_CHOICE_LOCATION:
1016 final double latitude = data.getDoubleExtra("latitude", 0);
1017 final double longitude = data.getDoubleExtra("longitude", 0);
1018 final int accuracy = data.getIntExtra("accuracy", 0);
1019 final Uri geo;
1020 if (accuracy > 0) {
1021 geo = Uri.parse(String.format("geo:%s,%s;u=%s", latitude, longitude, accuracy));
1022 } else {
1023 geo = Uri.parse(String.format("geo:%s,%s", latitude, longitude));
1024 }
1025 mediaPreviewAdapter.addMediaPreviews(
1026 Attachment.of(getActivity(), geo, Attachment.Type.LOCATION));
1027 toggleInputMethod();
1028 break;
1029 case REQUEST_INVITE_TO_CONVERSATION:
1030 XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data);
1031 if (invite != null) {
1032 if (invite.execute(activity)) {
1033 activity.mToast =
1034 Toast.makeText(
1035 activity, R.string.creating_conference, Toast.LENGTH_LONG);
1036 activity.mToast.show();
1037 }
1038 }
1039 break;
1040 }
1041 }
1042
1043 private void commitAttachments() {
1044 final List<Attachment> attachments = mediaPreviewAdapter.getAttachments();
1045 if (anyNeedsExternalStoragePermission(attachments)
1046 && !hasPermissions(
1047 REQUEST_COMMIT_ATTACHMENTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1048 return;
1049 }
1050 if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_ATTACHMENTS)) {
1051 return;
1052 }
1053 final PresenceSelector.OnPresenceSelected callback =
1054 () -> {
1055 for (Iterator<Attachment> i = attachments.iterator(); i.hasNext(); i.remove()) {
1056 final Attachment attachment = i.next();
1057 if (attachment.getType() == Attachment.Type.LOCATION) {
1058 attachLocationToConversation(conversation, attachment.getUri());
1059 } else if (attachment.getType() == Attachment.Type.IMAGE) {
1060 Log.d(
1061 Config.LOGTAG,
1062 "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE");
1063 attachImageToConversation(
1064 conversation, attachment.getUri(), attachment.getMime());
1065 } else {
1066 Log.d(
1067 Config.LOGTAG,
1068 "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1069 attachFileToConversation(
1070 conversation, attachment.getUri(), attachment.getMime());
1071 }
1072 }
1073 mediaPreviewAdapter.notifyDataSetChanged();
1074 toggleInputMethod();
1075 };
1076 if (conversation == null
1077 || conversation.getMode() == Conversation.MODE_MULTI
1078 || Attachment.canBeSendInband(attachments)
1079 || (conversation.getAccount().httpUploadAvailable()
1080 && FileBackend.allFilesUnderSize(
1081 getActivity(), attachments, getMaxHttpUploadSize(conversation)))) {
1082 callback.onPresenceSelected();
1083 } else {
1084 activity.selectPresence(conversation, callback);
1085 }
1086 }
1087
1088 private static boolean anyNeedsExternalStoragePermission(
1089 final Collection<Attachment> attachments) {
1090 for (final Attachment attachment : attachments) {
1091 if (attachment.getType() != Attachment.Type.LOCATION) {
1092 return true;
1093 }
1094 }
1095 return false;
1096 }
1097
1098 public void toggleInputMethod() {
1099 boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
1100 binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
1101 binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
1102 updateSendButton();
1103 }
1104
1105 private void handleNegativeActivityResult(int requestCode) {
1106 switch (requestCode) {
1107 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1108 if (pendingTakePhotoUri.clear()) {
1109 Log.d(
1110 Config.LOGTAG,
1111 "cleared pending photo uri after negative activity result");
1112 }
1113 break;
1114 }
1115 }
1116
1117 @Override
1118 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
1119 super.onActivityResult(requestCode, resultCode, data);
1120 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
1121 if (activity != null && activity.xmppConnectionService != null) {
1122 handleActivityResult(activityResult);
1123 } else {
1124 this.postponedActivityResult.push(activityResult);
1125 }
1126 }
1127
1128 public void unblockConversation(final Blockable conversation) {
1129 activity.xmppConnectionService.sendUnblockRequest(conversation);
1130 }
1131
1132 @Override
1133 public void onAttach(Activity activity) {
1134 super.onAttach(activity);
1135 Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
1136 if (activity instanceof ConversationsActivity) {
1137 this.activity = (ConversationsActivity) activity;
1138 } else {
1139 throw new IllegalStateException(
1140 "Trying to attach fragment to activity that is not the ConversationsActivity");
1141 }
1142 }
1143
1144 @Override
1145 public void onDetach() {
1146 super.onDetach();
1147 this.activity = null; // TODO maybe not a good idea since some callbacks really need it
1148 }
1149
1150 @Override
1151 public void onCreate(Bundle savedInstanceState) {
1152 super.onCreate(savedInstanceState);
1153 setHasOptionsMenu(true);
1154 }
1155
1156 @Override
1157 public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
1158 menuInflater.inflate(R.menu.fragment_conversation, menu);
1159 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
1160 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
1161 final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
1162 final MenuItem menuMute = menu.findItem(R.id.action_mute);
1163 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
1164 final MenuItem menuCall = menu.findItem(R.id.action_call);
1165 final MenuItem menuOngoingCall = menu.findItem(R.id.action_ongoing_call);
1166 final MenuItem menuVideoCall = menu.findItem(R.id.action_video_call);
1167 final MenuItem menuTogglePinned = menu.findItem(R.id.action_toggle_pinned);
1168
1169 if (conversation != null) {
1170 if (conversation.getMode() == Conversation.MODE_MULTI) {
1171 menuContactDetails.setVisible(false);
1172 menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
1173 menuMucDetails.setTitle(
1174 conversation.getMucOptions().isPrivateAndNonAnonymous()
1175 ? R.string.action_muc_details
1176 : R.string.channel_details);
1177 menuCall.setVisible(false);
1178 menuOngoingCall.setVisible(false);
1179 } else {
1180 final XmppConnectionService service =
1181 activity == null ? null : activity.xmppConnectionService;
1182 final Optional<OngoingRtpSession> ongoingRtpSession =
1183 service == null
1184 ? Optional.absent()
1185 : service.getJingleConnectionManager()
1186 .getOngoingRtpConnection(conversation.getContact());
1187 if (ongoingRtpSession.isPresent()) {
1188 menuOngoingCall.setVisible(true);
1189 menuCall.setVisible(false);
1190 } else {
1191 menuOngoingCall.setVisible(false);
1192 final RtpCapability.Capability rtpCapability =
1193 RtpCapability.check(conversation.getContact());
1194 final boolean cameraAvailable =
1195 activity != null && activity.isCameraFeatureAvailable();
1196 menuCall.setVisible(rtpCapability != RtpCapability.Capability.NONE);
1197 menuVideoCall.setVisible(
1198 rtpCapability == RtpCapability.Capability.VIDEO && cameraAvailable);
1199 }
1200 menuContactDetails.setVisible(!this.conversation.withSelf());
1201 menuMucDetails.setVisible(false);
1202 menuInviteContact.setVisible(
1203 service != null
1204 && service.findConferenceServer(conversation.getAccount()) != null);
1205 }
1206 if (conversation.isMuted()) {
1207 menuMute.setVisible(false);
1208 } else {
1209 menuUnmute.setVisible(false);
1210 }
1211 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
1212 ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
1213 if (conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false)) {
1214 menuTogglePinned.setTitle(R.string.remove_from_favorites);
1215 } else {
1216 menuTogglePinned.setTitle(R.string.add_to_favorites);
1217 }
1218 }
1219 super.onCreateOptionsMenu(menu, menuInflater);
1220 }
1221
1222 @Override
1223 public View onCreateView(
1224 final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
1225 this.binding =
1226 DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
1227 binding.getRoot().setOnClickListener(null); // TODO why the fuck did we do this?
1228
1229 binding.textinput.addTextChangedListener(
1230 new StylingHelper.MessageEditorStyler(binding.textinput));
1231
1232 binding.textinput.setOnEditorActionListener(mEditorActionListener);
1233 binding.textinput.setRichContentListener(new String[] {"image/*"}, mEditorContentListener);
1234
1235 binding.textSendButton.setOnClickListener(this.mSendButtonListener);
1236
1237 binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
1238 binding.messagesView.setOnScrollListener(mOnScrollListener);
1239 binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
1240 mediaPreviewAdapter = new MediaPreviewAdapter(this);
1241 binding.mediaPreview.setAdapter(mediaPreviewAdapter);
1242 messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1243 messageListAdapter.setOnContactPictureClicked(this);
1244 messageListAdapter.setOnContactPictureLongClicked(this);
1245 binding.messagesView.setAdapter(messageListAdapter);
1246
1247 registerForContextMenu(binding.messagesView);
1248
1249 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1250 this.binding.textinput.setCustomInsertionActionModeCallback(
1251 new EditMessageActionModeCallback(this.binding.textinput));
1252 }
1253
1254 binding.threadIdenticon.setOnClickListener(v -> newThread());
1255
1256 return binding.getRoot();
1257 }
1258
1259 @Override
1260 public void onDestroyView() {
1261 super.onDestroyView();
1262 Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1263 messageListAdapter.setOnContactPictureClicked(null);
1264 messageListAdapter.setOnContactPictureLongClicked(null);
1265 if (conversation != null) conversation.setupViewPager(null, null);
1266 }
1267
1268 private void quoteText(String text) {
1269 if (binding.textinput.isEnabled()) {
1270 binding.textinput.insertAsQuote(text);
1271 binding.textinput.requestFocus();
1272 InputMethodManager inputMethodManager =
1273 (InputMethodManager)
1274 getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1275 if (inputMethodManager != null) {
1276 inputMethodManager.showSoftInput(
1277 binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1278 }
1279 }
1280 }
1281
1282 private void quoteMessage(Message message) {
1283 setThread(message.getThread());
1284 quoteText(MessageUtils.prepareQuote(message));
1285 }
1286
1287 private void setThread(Element thread) {
1288 this.conversation.setThread(thread);
1289 binding.threadIdenticon.setAlpha(0f);
1290 if (thread != null) {
1291 final String threadId = thread.getContent();
1292 if (threadId != null) {
1293 binding.threadIdenticon.setAlpha(1f);
1294 binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1295 binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1296 }
1297 }
1298 }
1299
1300 @Override
1301 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1302 // This should cancel any remaining click events that would otherwise trigger links
1303 v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1304 synchronized (this.messageList) {
1305 super.onCreateContextMenu(menu, v, menuInfo);
1306 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1307 this.selectedMessage = this.messageList.get(acmi.position);
1308 populateContextMenu(menu);
1309 }
1310 }
1311
1312 private void populateContextMenu(ContextMenu menu) {
1313 final Message m = this.selectedMessage;
1314 final Transferable t = m.getTransferable();
1315 Message relevantForCorrection = m;
1316 while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1317 relevantForCorrection = relevantForCorrection.next();
1318 }
1319 if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1320
1321 if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1322 || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1323 return;
1324 }
1325
1326 if (m.getStatus() == Message.STATUS_RECEIVED
1327 && t != null
1328 && (t.getStatus() == Transferable.STATUS_CANCELLED
1329 || t.getStatus() == Transferable.STATUS_FAILED)) {
1330 return;
1331 }
1332
1333 final boolean deleted = m.isDeleted();
1334 final boolean encrypted =
1335 m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1336 || m.getEncryption() == Message.ENCRYPTION_PGP;
1337 final boolean receiving =
1338 m.getStatus() == Message.STATUS_RECEIVED
1339 && (t instanceof JingleFileTransferConnection
1340 || t instanceof HttpDownloadConnection);
1341 activity.getMenuInflater().inflate(R.menu.message_context, menu);
1342 menu.setHeaderTitle(R.string.message_options);
1343 MenuItem openWith = menu.findItem(R.id.open_with);
1344 MenuItem copyMessage = menu.findItem(R.id.copy_message);
1345 MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1346 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1347 MenuItem correctMessage = menu.findItem(R.id.correct_message);
1348 MenuItem retractMessage = menu.findItem(R.id.retract_message);
1349 MenuItem shareWith = menu.findItem(R.id.share_with);
1350 MenuItem sendAgain = menu.findItem(R.id.send_again);
1351 MenuItem copyUrl = menu.findItem(R.id.copy_url);
1352 MenuItem downloadFile = menu.findItem(R.id.download_file);
1353 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1354 MenuItem deleteFile = menu.findItem(R.id.delete_file);
1355 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1356 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1357 final boolean showError =
1358 m.getStatus() == Message.STATUS_SEND_FAILED
1359 && m.getErrorMessage() != null
1360 && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1361 if (!m.isFileOrImage()
1362 && !encrypted
1363 && !m.isGeoUri()
1364 && !m.treatAsDownloadable()
1365 && !unInitiatedButKnownSize
1366 && t == null) {
1367 copyMessage.setVisible(true);
1368 quoteMessage.setVisible(!showError && MessageUtils.prepareQuote(m).length() > 0);
1369 }
1370 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1371 retryDecryption.setVisible(true);
1372 }
1373 if (!showError
1374 && relevantForCorrection.getType() == Message.TYPE_TEXT
1375 && !m.isGeoUri()
1376 && relevantForCorrection.isLastCorrectableMessage()
1377 && m.getConversation() instanceof Conversation) {
1378 correctMessage.setVisible(true);
1379 if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1380 }
1381 if ((m.isFileOrImage() && !deleted && !receiving)
1382 || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1383 && !unInitiatedButKnownSize
1384 && t == null) {
1385 shareWith.setVisible(true);
1386 }
1387 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1388 sendAgain.setVisible(true);
1389 }
1390 if (m.hasFileOnRemoteHost()
1391 || m.isGeoUri()
1392 || m.treatAsDownloadable()
1393 || unInitiatedButKnownSize
1394 || t instanceof HttpDownloadConnection) {
1395 copyUrl.setVisible(true);
1396 }
1397 if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1398 downloadFile.setVisible(true);
1399 downloadFile.setTitle(
1400 activity.getString(
1401 R.string.download_x_file,
1402 UIHelper.getFileDescriptionString(activity, m)));
1403 }
1404 final boolean waitingOfferedSending =
1405 m.getStatus() == Message.STATUS_WAITING
1406 || m.getStatus() == Message.STATUS_UNSEND
1407 || m.getStatus() == Message.STATUS_OFFERED;
1408 final boolean cancelable =
1409 (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1410 if (cancelable) {
1411 cancelTransmission.setVisible(true);
1412 }
1413 if (m.isFileOrImage() && !deleted && !cancelable) {
1414 final String path = m.getRelativeFilePath();
1415 if (path == null
1416 || !path.startsWith("/")
1417 || FileBackend.inConversationsDirectory(requireActivity(), path)) {
1418 deleteFile.setVisible(true);
1419 deleteFile.setTitle(
1420 activity.getString(
1421 R.string.delete_x_file,
1422 UIHelper.getFileDescriptionString(activity, m)));
1423 }
1424 }
1425 if (showError) {
1426 showErrorMessage.setVisible(true);
1427 }
1428 final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1429 if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1430 || (mime != null && mime.startsWith("audio/"))) {
1431 openWith.setVisible(true);
1432 }
1433 }
1434 }
1435
1436 @Override
1437 public boolean onContextItemSelected(MenuItem item) {
1438 switch (item.getItemId()) {
1439 case R.id.share_with:
1440 ShareUtil.share(activity, selectedMessage);
1441 return true;
1442 case R.id.correct_message:
1443 correctMessage(selectedMessage);
1444 return true;
1445 case R.id.retract_message:
1446 new AlertDialog.Builder(activity)
1447 .setTitle(R.string.retract_message)
1448 .setMessage("Do you really want to retract this message?")
1449 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
1450 Message message = selectedMessage;
1451 while (message.mergeable(message.next())) {
1452 message = message.next();
1453 }
1454 message.setBody(" ");
1455 message.putEdited(message.getUuid(), message.getServerMsgId());
1456 message.setServerMsgId(null);
1457 message.setUuid(UUID.randomUUID().toString());
1458 sendMessage(message);
1459 })
1460 .setNegativeButton(R.string.no, null).show();
1461 return true;
1462 case R.id.copy_message:
1463 ShareUtil.copyToClipboard(activity, selectedMessage);
1464 return true;
1465 case R.id.quote_message:
1466 quoteMessage(selectedMessage);
1467 return true;
1468 case R.id.send_again:
1469 resendMessage(selectedMessage);
1470 return true;
1471 case R.id.copy_url:
1472 ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1473 return true;
1474 case R.id.download_file:
1475 startDownloadable(selectedMessage);
1476 return true;
1477 case R.id.cancel_transmission:
1478 cancelTransmission(selectedMessage);
1479 return true;
1480 case R.id.retry_decryption:
1481 retryDecryption(selectedMessage);
1482 return true;
1483 case R.id.delete_file:
1484 deleteFile(selectedMessage);
1485 return true;
1486 case R.id.show_error_message:
1487 showErrorMessage(selectedMessage);
1488 return true;
1489 case R.id.open_with:
1490 openWith(selectedMessage);
1491 return true;
1492 default:
1493 return super.onContextItemSelected(item);
1494 }
1495 }
1496
1497 @Override
1498 public boolean onOptionsItemSelected(final MenuItem item) {
1499 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1500 return false;
1501 } else if (conversation == null) {
1502 return super.onOptionsItemSelected(item);
1503 }
1504 switch (item.getItemId()) {
1505 case R.id.encryption_choice_axolotl:
1506 case R.id.encryption_choice_pgp:
1507 case R.id.encryption_choice_none:
1508 handleEncryptionSelection(item);
1509 break;
1510 case R.id.attach_choose_picture:
1511 case R.id.attach_take_picture:
1512 case R.id.attach_record_video:
1513 case R.id.attach_choose_file:
1514 case R.id.attach_record_voice:
1515 case R.id.attach_location:
1516 handleAttachmentSelection(item);
1517 break;
1518 case R.id.action_search:
1519 startSearch();
1520 break;
1521 case R.id.action_archive:
1522 activity.xmppConnectionService.archiveConversation(conversation);
1523 break;
1524 case R.id.action_contact_details:
1525 activity.switchToContactDetails(conversation.getContact());
1526 break;
1527 case R.id.action_muc_details:
1528 ConferenceDetailsActivity.open(activity, conversation);
1529 break;
1530 case R.id.action_invite:
1531 startActivityForResult(
1532 ChooseContactActivity.create(activity, conversation),
1533 REQUEST_INVITE_TO_CONVERSATION);
1534 break;
1535 case R.id.action_clear_history:
1536 clearHistoryDialog(conversation);
1537 break;
1538 case R.id.action_mute:
1539 muteConversationDialog(conversation);
1540 break;
1541 case R.id.action_unmute:
1542 unMuteConversation(conversation);
1543 break;
1544 case R.id.action_block:
1545 case R.id.action_unblock:
1546 final Activity activity = getActivity();
1547 if (activity instanceof XmppActivity) {
1548 BlockContactDialog.show((XmppActivity) activity, conversation);
1549 }
1550 break;
1551 case R.id.action_audio_call:
1552 checkPermissionAndTriggerAudioCall();
1553 break;
1554 case R.id.action_video_call:
1555 checkPermissionAndTriggerVideoCall();
1556 break;
1557 case R.id.action_ongoing_call:
1558 returnToOngoingCall();
1559 break;
1560 case R.id.action_toggle_pinned:
1561 togglePinned();
1562 break;
1563 case R.id.action_refresh_feature_discovery:
1564 refreshFeatureDiscovery();
1565 break;
1566 default:
1567 break;
1568 }
1569 return super.onOptionsItemSelected(item);
1570 }
1571
1572 private void startSearch() {
1573 final Intent intent = new Intent(getActivity(), SearchActivity.class);
1574 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
1575 startActivity(intent);
1576 }
1577
1578 private void returnToOngoingCall() {
1579 final Optional<OngoingRtpSession> ongoingRtpSession =
1580 activity.xmppConnectionService
1581 .getJingleConnectionManager()
1582 .getOngoingRtpConnection(conversation.getContact());
1583 if (ongoingRtpSession.isPresent()) {
1584 final OngoingRtpSession id = ongoingRtpSession.get();
1585 final Intent intent = new Intent(activity, RtpSessionActivity.class);
1586 intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.getAccount().getJid().asBareJid().toEscapedString());
1587 intent.putExtra(
1588 RtpSessionActivity.EXTRA_ACCOUNT,
1589 id.getAccount().getJid().asBareJid().toEscapedString());
1590 intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
1591 if (id instanceof AbstractJingleConnection.Id) {
1592 intent.setAction(Intent.ACTION_VIEW);
1593 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
1594 } else if (id instanceof JingleConnectionManager.RtpSessionProposal) {
1595 if (((JingleConnectionManager.RtpSessionProposal) id).media.contains(Media.VIDEO)) {
1596 intent.setAction(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1597 } else {
1598 intent.setAction(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1599 }
1600 }
1601 activity.startActivity(intent);
1602 }
1603 }
1604
1605 private void refreshFeatureDiscovery() {
1606 for (Map.Entry<String, Presence> entry : conversation.getContact().getPresences().getPresencesMap().entrySet()) {
1607 Jid jid = conversation.getContact().getJid();
1608 if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
1609 activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
1610 if (activity == null) return;
1611 activity.runOnUiThread(() -> {
1612 refresh();
1613 refreshCommands();
1614 });
1615 });
1616 }
1617 }
1618
1619 private void togglePinned() {
1620 final boolean pinned =
1621 conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
1622 conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
1623 activity.xmppConnectionService.updateConversation(conversation);
1624 activity.invalidateOptionsMenu();
1625 }
1626
1627 private void checkPermissionAndTriggerAudioCall() {
1628 if (activity.mUseTor || conversation.getAccount().isOnion()) {
1629 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1630 return;
1631 }
1632 final List<String> permissions;
1633 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1634 permissions =
1635 Arrays.asList(
1636 Manifest.permission.RECORD_AUDIO,
1637 Manifest.permission.BLUETOOTH_CONNECT);
1638 } else {
1639 permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
1640 }
1641 if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
1642 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1643 }
1644 }
1645
1646 private void checkPermissionAndTriggerVideoCall() {
1647 if (activity.mUseTor || conversation.getAccount().isOnion()) {
1648 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1649 return;
1650 }
1651 final List<String> permissions;
1652 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1653 permissions =
1654 Arrays.asList(
1655 Manifest.permission.RECORD_AUDIO,
1656 Manifest.permission.CAMERA,
1657 Manifest.permission.BLUETOOTH_CONNECT);
1658 } else {
1659 permissions =
1660 Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
1661 }
1662 if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
1663 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1664 }
1665 }
1666
1667 private void triggerRtpSession(final String action) {
1668 if (activity.xmppConnectionService.getJingleConnectionManager().isBusy() != null) {
1669 Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
1670 .show();
1671 return;
1672 }
1673 final Contact contact = conversation.getContact();
1674 if (contact.getPresences().anySupport(Namespace.JINGLE_MESSAGE)) {
1675 triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
1676 } else {
1677 final RtpCapability.Capability capability;
1678 if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
1679 capability = RtpCapability.Capability.VIDEO;
1680 } else {
1681 capability = RtpCapability.Capability.AUDIO;
1682 }
1683 PresenceSelector.selectFullJidForDirectRtpConnection(
1684 activity,
1685 contact,
1686 capability,
1687 fullJid -> {
1688 triggerRtpSession(contact.getAccount(), fullJid, action);
1689 });
1690 }
1691 }
1692
1693 private void triggerRtpSession(final Account account, final Jid with, final String action) {
1694 final Intent intent = new Intent(activity, RtpSessionActivity.class);
1695 intent.setAction(action);
1696 intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, account.getJid().toEscapedString());
1697 intent.putExtra(RtpSessionActivity.EXTRA_WITH, with.toEscapedString());
1698 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1699 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
1700 startActivity(intent);
1701 }
1702
1703 private void handleAttachmentSelection(MenuItem item) {
1704 switch (item.getItemId()) {
1705 case R.id.attach_choose_picture:
1706 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1707 break;
1708 case R.id.attach_take_picture:
1709 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1710 break;
1711 case R.id.attach_record_video:
1712 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1713 break;
1714 case R.id.attach_choose_file:
1715 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1716 break;
1717 case R.id.attach_record_voice:
1718 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1719 break;
1720 case R.id.attach_location:
1721 attachFile(ATTACHMENT_CHOICE_LOCATION);
1722 break;
1723 }
1724 }
1725
1726 private void handleEncryptionSelection(MenuItem item) {
1727 if (conversation == null) {
1728 return;
1729 }
1730 final boolean updated;
1731 switch (item.getItemId()) {
1732 case R.id.encryption_choice_none:
1733 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1734 item.setChecked(true);
1735 break;
1736 case R.id.encryption_choice_pgp:
1737 if (activity.hasPgp()) {
1738 if (conversation.getAccount().getPgpSignature() != null) {
1739 updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1740 item.setChecked(true);
1741 } else {
1742 updated = false;
1743 activity.announcePgp(
1744 conversation.getAccount(),
1745 conversation,
1746 null,
1747 activity.onOpenPGPKeyPublished);
1748 }
1749 } else {
1750 activity.showInstallPgpDialog();
1751 updated = false;
1752 }
1753 break;
1754 case R.id.encryption_choice_axolotl:
1755 Log.d(
1756 Config.LOGTAG,
1757 AxolotlService.getLogprefix(conversation.getAccount())
1758 + "Enabled axolotl for Contact "
1759 + conversation.getContact().getJid());
1760 updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1761 item.setChecked(true);
1762 break;
1763 default:
1764 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1765 break;
1766 }
1767 if (updated) {
1768 activity.xmppConnectionService.updateConversation(conversation);
1769 }
1770 updateChatMsgHint();
1771 getActivity().invalidateOptionsMenu();
1772 activity.refreshUi();
1773 }
1774
1775 public void attachFile(final int attachmentChoice) {
1776 attachFile(attachmentChoice, true);
1777 }
1778
1779 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
1780 if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1781 if (!hasPermissions(
1782 attachmentChoice,
1783 Manifest.permission.WRITE_EXTERNAL_STORAGE,
1784 Manifest.permission.RECORD_AUDIO)) {
1785 return;
1786 }
1787 } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
1788 || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1789 if (!hasPermissions(
1790 attachmentChoice,
1791 Manifest.permission.WRITE_EXTERNAL_STORAGE,
1792 Manifest.permission.CAMERA)) {
1793 return;
1794 }
1795 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1796 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1797 return;
1798 }
1799 }
1800 if (updateRecentlyUsed) {
1801 storeRecentlyUsedQuickAction(attachmentChoice);
1802 }
1803 final int encryption = conversation.getNextEncryption();
1804 final int mode = conversation.getMode();
1805 if (encryption == Message.ENCRYPTION_PGP) {
1806 if (activity.hasPgp()) {
1807 if (mode == Conversation.MODE_SINGLE
1808 && conversation.getContact().getPgpKeyId() != 0) {
1809 activity.xmppConnectionService
1810 .getPgpEngine()
1811 .hasKey(
1812 conversation.getContact(),
1813 new UiCallback<Contact>() {
1814
1815 @Override
1816 public void userInputRequired(
1817 PendingIntent pi, Contact contact) {
1818 startPendingIntent(pi, attachmentChoice);
1819 }
1820
1821 @Override
1822 public void success(Contact contact) {
1823 invokeAttachFileIntent(attachmentChoice);
1824 }
1825
1826 @Override
1827 public void error(int error, Contact contact) {
1828 activity.replaceToast(getString(error));
1829 }
1830 });
1831 } else if (mode == Conversation.MODE_MULTI
1832 && conversation.getMucOptions().pgpKeysInUse()) {
1833 if (!conversation.getMucOptions().everybodyHasKeys()) {
1834 Toast warning =
1835 Toast.makeText(
1836 getActivity(),
1837 R.string.missing_public_keys,
1838 Toast.LENGTH_LONG);
1839 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1840 warning.show();
1841 }
1842 invokeAttachFileIntent(attachmentChoice);
1843 } else {
1844 showNoPGPKeyDialog(
1845 false,
1846 (dialog, which) -> {
1847 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1848 activity.xmppConnectionService.updateConversation(conversation);
1849 invokeAttachFileIntent(attachmentChoice);
1850 });
1851 }
1852 } else {
1853 activity.showInstallPgpDialog();
1854 }
1855 } else {
1856 invokeAttachFileIntent(attachmentChoice);
1857 }
1858 }
1859
1860 private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
1861 try {
1862 activity.getPreferences()
1863 .edit()
1864 .putString(
1865 RECENTLY_USED_QUICK_ACTION,
1866 SendButtonAction.of(attachmentChoice).toString())
1867 .apply();
1868 } catch (IllegalArgumentException e) {
1869 // just do not save
1870 }
1871 }
1872
1873 @Override
1874 public void onRequestPermissionsResult(
1875 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
1876 final PermissionUtils.PermissionResult permissionResult =
1877 PermissionUtils.removeBluetoothConnect(permissions, grantResults);
1878 if (grantResults.length > 0) {
1879 if (allGranted(permissionResult.grantResults)) {
1880 switch (requestCode) {
1881 case REQUEST_START_DOWNLOAD:
1882 if (this.mPendingDownloadableMessage != null) {
1883 startDownloadable(this.mPendingDownloadableMessage);
1884 }
1885 break;
1886 case REQUEST_ADD_EDITOR_CONTENT:
1887 if (this.mPendingEditorContent != null) {
1888 attachEditorContentToConversation(this.mPendingEditorContent);
1889 }
1890 break;
1891 case REQUEST_COMMIT_ATTACHMENTS:
1892 commitAttachments();
1893 break;
1894 case REQUEST_START_AUDIO_CALL:
1895 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1896 break;
1897 case REQUEST_START_VIDEO_CALL:
1898 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1899 break;
1900 default:
1901 attachFile(requestCode);
1902 break;
1903 }
1904 } else {
1905 @StringRes int res;
1906 String firstDenied =
1907 getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
1908 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1909 res = R.string.no_microphone_permission;
1910 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1911 res = R.string.no_camera_permission;
1912 } else {
1913 res = R.string.no_storage_permission;
1914 }
1915 Toast.makeText(
1916 getActivity(),
1917 getString(res, getString(R.string.app_name)),
1918 Toast.LENGTH_SHORT)
1919 .show();
1920 }
1921 }
1922 if (writeGranted(grantResults, permissions)) {
1923 if (activity != null && activity.xmppConnectionService != null) {
1924 activity.xmppConnectionService.getBitmapCache().evictAll();
1925 activity.xmppConnectionService.restartFileObserver();
1926 }
1927 refresh();
1928 }
1929 }
1930
1931 public void startDownloadable(Message message) {
1932 if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1933 this.mPendingDownloadableMessage = message;
1934 return;
1935 }
1936 Transferable transferable = message.getTransferable();
1937 if (transferable != null) {
1938 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1939 createNewConnection(message);
1940 return;
1941 }
1942 if (!transferable.start()) {
1943 Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1944 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
1945 .show();
1946 }
1947 } else if (message.treatAsDownloadable()
1948 || message.hasFileOnRemoteHost()
1949 || MessageUtils.unInitiatedButKnownSize(message)) {
1950 createNewConnection(message);
1951 } else {
1952 Log.d(
1953 Config.LOGTAG,
1954 message.getConversation().getAccount() + ": unable to start downloadable");
1955 }
1956 }
1957
1958 private void createNewConnection(final Message message) {
1959 if (!activity.xmppConnectionService.hasInternetConnection()) {
1960 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
1961 .show();
1962 return;
1963 }
1964 if (message.getOob() != null && message.getOob().getScheme().equalsIgnoreCase("cid")) {
1965 try {
1966 BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
1967 message.setTransferable(transfer);
1968 transfer.start();
1969 } catch (URISyntaxException e) {
1970 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
1971 }
1972 } else {
1973 activity.xmppConnectionService
1974 .getHttpConnectionManager()
1975 .createNewDownloadConnection(message, true);
1976 }
1977 }
1978
1979 @SuppressLint("InflateParams")
1980 protected void clearHistoryDialog(final Conversation conversation) {
1981 final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
1982 builder.setTitle(getString(R.string.clear_conversation_history));
1983 final View dialogView =
1984 requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1985 final CheckBox endConversationCheckBox =
1986 dialogView.findViewById(R.id.end_conversation_checkbox);
1987 builder.setView(dialogView);
1988 builder.setNegativeButton(getString(R.string.cancel), null);
1989 builder.setPositiveButton(
1990 getString(R.string.confirm),
1991 (dialog, which) -> {
1992 this.activity.xmppConnectionService.clearConversationHistory(conversation);
1993 if (endConversationCheckBox.isChecked()) {
1994 this.activity.xmppConnectionService.archiveConversation(conversation);
1995 this.activity.onConversationArchived(conversation);
1996 } else {
1997 activity.onConversationsListItemUpdated();
1998 refresh();
1999 }
2000 });
2001 builder.create().show();
2002 }
2003
2004 protected void muteConversationDialog(final Conversation conversation) {
2005 final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
2006 builder.setTitle(R.string.disable_notifications);
2007 final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2008 final CharSequence[] labels = new CharSequence[durations.length];
2009 for (int i = 0; i < durations.length; ++i) {
2010 if (durations[i] == -1) {
2011 labels[i] = activity.getString(R.string.until_further_notice);
2012 } else {
2013 labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2014 }
2015 }
2016 builder.setItems(
2017 labels,
2018 (dialog, which) -> {
2019 final long till;
2020 if (durations[which] == -1) {
2021 till = Long.MAX_VALUE;
2022 } else {
2023 till = System.currentTimeMillis() + (durations[which] * 1000L);
2024 }
2025 conversation.setMutedTill(till);
2026 activity.xmppConnectionService.updateConversation(conversation);
2027 activity.onConversationsListItemUpdated();
2028 refresh();
2029 activity.invalidateOptionsMenu();
2030 });
2031 builder.create().show();
2032 }
2033
2034 private boolean hasPermissions(int requestCode, List<String> permissions) {
2035 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
2036 final List<String> missingPermissions = new ArrayList<>();
2037 for (String permission : permissions) {
2038 if (Config.ONLY_INTERNAL_STORAGE
2039 && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2040 continue;
2041 }
2042 if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2043 missingPermissions.add(permission);
2044 }
2045 }
2046 if (missingPermissions.size() == 0) {
2047 return true;
2048 } else {
2049 requestPermissions(
2050 missingPermissions.toArray(new String[0]),
2051 requestCode);
2052 return false;
2053 }
2054 } else {
2055 return true;
2056 }
2057 }
2058
2059 private boolean hasPermissions(int requestCode, String... permissions) {
2060 return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2061 }
2062
2063 public void unMuteConversation(final Conversation conversation) {
2064 conversation.setMutedTill(0);
2065 this.activity.xmppConnectionService.updateConversation(conversation);
2066 this.activity.onConversationsListItemUpdated();
2067 refresh();
2068 this.activity.invalidateOptionsMenu();
2069 }
2070
2071 protected void invokeAttachFileIntent(final int attachmentChoice) {
2072 Intent intent = new Intent();
2073 boolean chooser = false;
2074 switch (attachmentChoice) {
2075 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2076 intent.setAction(Intent.ACTION_GET_CONTENT);
2077 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2078 intent.setType("image/*");
2079 chooser = true;
2080 break;
2081 case ATTACHMENT_CHOICE_RECORD_VIDEO:
2082 intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2083 break;
2084 case ATTACHMENT_CHOICE_TAKE_PHOTO:
2085 final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2086 pendingTakePhotoUri.push(uri);
2087 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
2088 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2089 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2090 intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2091 break;
2092 case ATTACHMENT_CHOICE_CHOOSE_FILE:
2093 chooser = true;
2094 intent.setType("*/*");
2095 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2096 intent.addCategory(Intent.CATEGORY_OPENABLE);
2097 intent.setAction(Intent.ACTION_GET_CONTENT);
2098 break;
2099 case ATTACHMENT_CHOICE_RECORD_VOICE:
2100 intent = new Intent(getActivity(), RecordingActivity.class);
2101 break;
2102 case ATTACHMENT_CHOICE_LOCATION:
2103 intent = GeoHelper.getFetchIntent(activity);
2104 break;
2105 }
2106 final Context context = getActivity();
2107 if (context == null) {
2108 return;
2109 }
2110 try {
2111 if (chooser) {
2112 startActivityForResult(
2113 Intent.createChooser(intent, getString(R.string.perform_action_with)),
2114 attachmentChoice);
2115 } else {
2116 startActivityForResult(intent, attachmentChoice);
2117 }
2118 } catch (final ActivityNotFoundException e) {
2119 Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2120 }
2121 }
2122
2123 @Override
2124 public void onResume() {
2125 super.onResume();
2126 binding.messagesView.post(this::fireReadEvent);
2127 }
2128
2129 private void fireReadEvent() {
2130 if (activity != null && this.conversation != null) {
2131 String uuid = getLastVisibleMessageUuid();
2132 if (uuid != null) {
2133 activity.onConversationRead(this.conversation, uuid);
2134 }
2135 }
2136 }
2137
2138 private void newThread() {
2139 Element thread = new Element("thread", "jabber:client");
2140 thread.setContent(UUID.randomUUID().toString());
2141 setThread(thread);
2142 }
2143
2144 private void updateThreadFromLastMessage() {
2145 if (activity != null && this.conversation != null && TextUtils.isEmpty(binding.textinput.getText())) {
2146 Message message = getLastVisibleMessage();
2147 if (message == null) {
2148 newThread();
2149 } else {
2150 setThread(message.getThread());
2151 }
2152 }
2153 }
2154
2155 private String getLastVisibleMessageUuid() {
2156 Message message = getLastVisibleMessage();
2157 return message == null ? null : message.getUuid();
2158 }
2159
2160 private Message getLastVisibleMessage() {
2161 if (binding == null) {
2162 return null;
2163 }
2164 synchronized (this.messageList) {
2165 int pos = binding.messagesView.getLastVisiblePosition();
2166 if (pos >= 0) {
2167 Message message = null;
2168 for (int i = pos; i >= 0; --i) {
2169 try {
2170 message = (Message) binding.messagesView.getItemAtPosition(i);
2171 } catch (IndexOutOfBoundsException e) {
2172 // should not happen if we synchronize properly. however if that fails we
2173 // just gonna try item -1
2174 continue;
2175 }
2176 if (message.getType() != Message.TYPE_STATUS) {
2177 break;
2178 }
2179 }
2180 if (message != null) {
2181 while (message.next() != null && message.next().wasMergedIntoPrevious()) {
2182 message = message.next();
2183 }
2184 return message;
2185 }
2186 }
2187 }
2188 return null;
2189 }
2190
2191 private void openWith(final Message message) {
2192 if (message.isGeoUri()) {
2193 GeoHelper.view(getActivity(), message);
2194 } else {
2195 final DownloadableFile file =
2196 activity.xmppConnectionService.getFileBackend().getFile(message);
2197 ViewUtil.view(activity, file);
2198 }
2199 }
2200
2201 private void showErrorMessage(final Message message) {
2202 AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2203 builder.setTitle(R.string.error_message);
2204 final String errorMessage = message.getErrorMessage();
2205 final String[] errorMessageParts =
2206 errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2207 final String displayError;
2208 if (errorMessageParts.length == 2) {
2209 displayError = errorMessageParts[1];
2210 } else {
2211 displayError = errorMessage;
2212 }
2213 builder.setMessage(displayError);
2214 builder.setNegativeButton(
2215 R.string.copy_to_clipboard,
2216 (dialog, which) -> {
2217 activity.copyTextToClipboard(displayError, R.string.error_message);
2218 Toast.makeText(
2219 activity,
2220 R.string.error_message_copied_to_clipboard,
2221 Toast.LENGTH_SHORT)
2222 .show();
2223 });
2224 builder.setPositiveButton(R.string.confirm, null);
2225 builder.create().show();
2226 }
2227
2228 private void deleteFile(final Message message) {
2229 AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
2230 builder.setNegativeButton(R.string.cancel, null);
2231 builder.setTitle(R.string.delete_file_dialog);
2232 builder.setMessage(R.string.delete_file_dialog_msg);
2233 builder.setPositiveButton(
2234 R.string.confirm,
2235 (dialog, which) -> {
2236 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
2237 message.setDeleted(true);
2238 activity.xmppConnectionService.evictPreview(message.getUuid());
2239 activity.xmppConnectionService.updateMessage(message, false);
2240 activity.onConversationsListItemUpdated();
2241 refresh();
2242 }
2243 });
2244 builder.create().show();
2245 }
2246
2247 private void resendMessage(final Message message) {
2248 if (message.isFileOrImage()) {
2249 if (!(message.getConversation() instanceof Conversation)) {
2250 return;
2251 }
2252 final Conversation conversation = (Conversation) message.getConversation();
2253 final DownloadableFile file =
2254 activity.xmppConnectionService.getFileBackend().getFile(message);
2255 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
2256 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
2257 if (!message.hasFileOnRemoteHost()
2258 && xmppConnection != null
2259 && conversation.getMode() == Conversational.MODE_SINGLE
2260 && !xmppConnection
2261 .getFeatures()
2262 .httpUpload(message.getFileParams().getSize())) {
2263 activity.selectPresence(
2264 conversation,
2265 () -> {
2266 message.setCounterpart(conversation.getNextCounterpart());
2267 activity.xmppConnectionService.resendFailedMessages(message);
2268 new Handler()
2269 .post(
2270 () -> {
2271 int size = messageList.size();
2272 this.binding.messagesView.setSelection(
2273 size - 1);
2274 });
2275 });
2276 return;
2277 }
2278 } else if (!Compatibility.hasStoragePermission(getActivity())) {
2279 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
2280 return;
2281 } else {
2282 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
2283 message.setDeleted(true);
2284 activity.xmppConnectionService.updateMessage(message, false);
2285 activity.onConversationsListItemUpdated();
2286 refresh();
2287 return;
2288 }
2289 }
2290 activity.xmppConnectionService.resendFailedMessages(message);
2291 new Handler()
2292 .post(
2293 () -> {
2294 int size = messageList.size();
2295 this.binding.messagesView.setSelection(size - 1);
2296 });
2297 }
2298
2299 private void cancelTransmission(Message message) {
2300 Transferable transferable = message.getTransferable();
2301 if (transferable != null) {
2302 transferable.cancel();
2303 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
2304 activity.xmppConnectionService.markMessage(
2305 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
2306 }
2307 }
2308
2309 private void retryDecryption(Message message) {
2310 message.setEncryption(Message.ENCRYPTION_PGP);
2311 activity.onConversationsListItemUpdated();
2312 refresh();
2313 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
2314 }
2315
2316 public void privateMessageWith(final Jid counterpart) {
2317 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2318 activity.xmppConnectionService.sendChatState(conversation);
2319 }
2320 this.binding.textinput.setText("");
2321 this.conversation.setNextCounterpart(counterpart);
2322 updateChatMsgHint();
2323 updateSendButton();
2324 updateEditablity();
2325 }
2326
2327 private void correctMessage(Message message) {
2328 while (message.mergeable(message.next())) {
2329 message = message.next();
2330 }
2331 this.conversation.setCorrectingMessage(message);
2332 final Editable editable = binding.textinput.getText();
2333 this.conversation.setDraftMessage(editable.toString());
2334 this.binding.textinput.setText("");
2335 this.binding.textinput.append(message.getBody());
2336 }
2337
2338 private void highlightInConference(String nick) {
2339 final Editable editable = this.binding.textinput.getText();
2340 String oldString = editable.toString().trim();
2341 final int pos = this.binding.textinput.getSelectionStart();
2342 if (oldString.isEmpty() || pos == 0) {
2343 editable.insert(0, nick + ": ");
2344 } else {
2345 final char before = editable.charAt(pos - 1);
2346 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
2347 if (before == '\n') {
2348 editable.insert(pos, nick + ": ");
2349 } else {
2350 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
2351 if (NickValidityChecker.check(
2352 conversation,
2353 Arrays.asList(
2354 editable.subSequence(0, pos - 2).toString().split(", ")))) {
2355 editable.insert(pos - 2, ", " + nick);
2356 return;
2357 }
2358 }
2359 editable.insert(
2360 pos,
2361 (Character.isWhitespace(before) ? "" : " ")
2362 + nick
2363 + (Character.isWhitespace(after) ? "" : " "));
2364 if (Character.isWhitespace(after)) {
2365 this.binding.textinput.setSelection(
2366 this.binding.textinput.getSelectionStart() + 1);
2367 }
2368 }
2369 }
2370 }
2371
2372 @Override
2373 public void startActivityForResult(Intent intent, int requestCode) {
2374 final Activity activity = getActivity();
2375 if (activity instanceof ConversationsActivity) {
2376 ((ConversationsActivity) activity).clearPendingViewIntent();
2377 }
2378 super.startActivityForResult(intent, requestCode);
2379 }
2380
2381 @Override
2382 public void onSaveInstanceState(@NotNull Bundle outState) {
2383 super.onSaveInstanceState(outState);
2384 if (conversation != null) {
2385 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
2386 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
2387 final Uri uri = pendingTakePhotoUri.peek();
2388 if (uri != null) {
2389 outState.putString(STATE_PHOTO_URI, uri.toString());
2390 }
2391 final ScrollState scrollState = getScrollPosition();
2392 if (scrollState != null) {
2393 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
2394 }
2395 final ArrayList<Attachment> attachments =
2396 mediaPreviewAdapter == null
2397 ? new ArrayList<>()
2398 : mediaPreviewAdapter.getAttachments();
2399 if (attachments.size() > 0) {
2400 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
2401 }
2402 }
2403 }
2404
2405 @Override
2406 public void onActivityCreated(Bundle savedInstanceState) {
2407 super.onActivityCreated(savedInstanceState);
2408 if (savedInstanceState == null) {
2409 return;
2410 }
2411 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
2412 ArrayList<Attachment> attachments =
2413 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
2414 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
2415 if (uuid != null) {
2416 QuickLoader.set(uuid);
2417 this.pendingConversationsUuid.push(uuid);
2418 if (attachments != null && attachments.size() > 0) {
2419 this.pendingMediaPreviews.push(attachments);
2420 }
2421 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
2422 if (takePhotoUri != null) {
2423 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
2424 }
2425 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
2426 }
2427 }
2428
2429 @Override
2430 public void onStart() {
2431 super.onStart();
2432 if (this.reInitRequiredOnStart && this.conversation != null) {
2433 final Bundle extras = pendingExtras.pop();
2434 reInit(this.conversation, extras != null);
2435 if (extras != null) {
2436 processExtras(extras);
2437 }
2438 } else if (conversation == null
2439 && activity != null
2440 && activity.xmppConnectionService != null) {
2441 final String uuid = pendingConversationsUuid.pop();
2442 Log.d(
2443 Config.LOGTAG,
2444 "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
2445 + uuid);
2446 if (uuid != null) {
2447 findAndReInitByUuidOrArchive(uuid);
2448 }
2449 }
2450 }
2451
2452 @Override
2453 public void onStop() {
2454 super.onStop();
2455 final Activity activity = getActivity();
2456 messageListAdapter.unregisterListenerInAudioPlayer();
2457 if (activity == null || !activity.isChangingConfigurations()) {
2458 hideSoftKeyboard(activity);
2459 messageListAdapter.stopAudioPlayer();
2460 }
2461 if (this.conversation != null) {
2462 final String msg = this.binding.textinput.getText().toString();
2463 storeNextMessage(msg);
2464 updateChatState(this.conversation, msg);
2465 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
2466 }
2467 this.reInitRequiredOnStart = true;
2468 }
2469
2470 private void updateChatState(final Conversation conversation, final String msg) {
2471 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
2472 Account.State status = conversation.getAccount().getStatus();
2473 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
2474 activity.xmppConnectionService.sendChatState(conversation);
2475 }
2476 }
2477
2478 private void saveMessageDraftStopAudioPlayer() {
2479 final Conversation previousConversation = this.conversation;
2480 if (this.activity == null || this.binding == null || previousConversation == null) {
2481 return;
2482 }
2483 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
2484 final String msg = this.binding.textinput.getText().toString();
2485 storeNextMessage(msg);
2486 updateChatState(this.conversation, msg);
2487 messageListAdapter.stopAudioPlayer();
2488 mediaPreviewAdapter.clearPreviews();
2489 toggleInputMethod();
2490 }
2491
2492 public void reInit(final Conversation conversation, final Bundle extras) {
2493 QuickLoader.set(conversation.getUuid());
2494 final boolean changedConversation = this.conversation != conversation;
2495 if (changedConversation) {
2496 this.saveMessageDraftStopAudioPlayer();
2497 }
2498 this.clearPending();
2499 if (this.reInit(conversation, extras != null)) {
2500 if (extras != null) {
2501 processExtras(extras);
2502 }
2503 this.reInitRequiredOnStart = false;
2504 } else {
2505 this.reInitRequiredOnStart = true;
2506 pendingExtras.push(extras);
2507 }
2508 resetUnreadMessagesCount();
2509 }
2510
2511 private void reInit(Conversation conversation) {
2512 reInit(conversation, false);
2513 }
2514
2515 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2516 if (conversation == null) {
2517 return false;
2518 }
2519 final Conversation originalConversation = this.conversation;
2520 this.conversation = conversation;
2521 // once we set the conversation all is good and it will automatically do the right thing in
2522 // onStart()
2523 if (this.activity == null || this.binding == null) {
2524 return false;
2525 }
2526
2527 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2528 activity.onConversationArchived(this.conversation);
2529 return false;
2530 }
2531
2532 stopScrolling();
2533 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
2534
2535 if (this.conversation.isRead() && hasExtras) {
2536 Log.d(Config.LOGTAG, "trimming conversation");
2537 this.conversation.trim();
2538 }
2539
2540 setupIme();
2541
2542 final boolean scrolledToBottomAndNoPending =
2543 this.scrolledToBottom() && pendingScrollState.peek() == null;
2544
2545 this.binding.textSendButton.setContentDescription(
2546 activity.getString(R.string.send_message_to_x, conversation.getName()));
2547 this.binding.textinput.setKeyboardListener(null);
2548 this.binding.textinput.setText("");
2549 final boolean participating =
2550 conversation.getMode() == Conversational.MODE_SINGLE
2551 || conversation.getMucOptions().participating();
2552 if (participating) {
2553 this.binding.textinput.append(this.conversation.getNextMessage());
2554 }
2555 this.binding.textinput.setKeyboardListener(this);
2556 messageListAdapter.updatePreferences();
2557 refresh(false);
2558 activity.invalidateOptionsMenu();
2559 this.conversation.messagesLoaded.set(true);
2560 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
2561
2562 if (hasExtras || scrolledToBottomAndNoPending) {
2563 resetUnreadMessagesCount();
2564 synchronized (this.messageList) {
2565 Log.d(Config.LOGTAG, "jump to first unread message");
2566 final Message first = conversation.getFirstUnreadMessage();
2567 final int bottom = Math.max(0, this.messageList.size() - 1);
2568 final int pos;
2569 final boolean jumpToBottom;
2570 if (first == null) {
2571 pos = bottom;
2572 jumpToBottom = true;
2573 } else {
2574 int i = getIndexOf(first.getUuid(), this.messageList);
2575 pos = i < 0 ? bottom : i;
2576 jumpToBottom = false;
2577 }
2578 setSelection(pos, jumpToBottom);
2579 }
2580 }
2581
2582 this.binding.messagesView.post(this::fireReadEvent);
2583 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
2584 // layout which might be unnecessary since we can *see* it
2585 activity.xmppConnectionService
2586 .getNotificationService()
2587 .setOpenConversation(this.conversation);
2588
2589 if (commandAdapter != null && conversation != originalConversation) {
2590 originalConversation.setupViewPager(null, null);
2591 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout);
2592 refreshCommands();
2593 }
2594 if (commandAdapter == null && conversation != null) {
2595 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout);
2596 commandAdapter = new CommandAdapter((XmppActivity) getActivity());
2597 binding.commandsView.setAdapter(commandAdapter);
2598 binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
2599 final Element command = commandAdapter.getItem(position);
2600 activity.startCommand(conversation.getAccount(), command.getAttributeAsJid("jid"), command.getAttribute("node"));
2601 });
2602 refreshCommands();
2603 }
2604
2605 return true;
2606 }
2607
2608 protected void refreshCommands() {
2609 if (commandAdapter == null) return;
2610
2611 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
2612 if (commandJid == null) {
2613 conversation.hideViewPager();
2614 } else {
2615 conversation.showViewPager();
2616 activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (a, iq) -> {
2617 if (activity == null) return;
2618
2619 activity.runOnUiThread(() -> {
2620 if (iq.getType() == IqPacket.TYPE.RESULT) {
2621 binding.commandsViewProgressbar.setVisibility(View.GONE);
2622 commandAdapter.clear();
2623 for (Element child : iq.query().getChildren()) {
2624 if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
2625 commandAdapter.add(child);
2626 }
2627 }
2628
2629 if (commandAdapter.getCount() < 1) conversation.hideViewPager();
2630 });
2631 });
2632 }
2633 }
2634
2635 private void resetUnreadMessagesCount() {
2636 lastMessageUuid = null;
2637 hideUnreadMessagesCount();
2638 }
2639
2640 private void hideUnreadMessagesCount() {
2641 if (this.binding == null) {
2642 return;
2643 }
2644 this.binding.scrollToBottomButton.setEnabled(false);
2645 this.binding.scrollToBottomButton.hide();
2646 this.binding.unreadCountCustomView.setVisibility(View.GONE);
2647 }
2648
2649 private void setSelection(int pos, boolean jumpToBottom) {
2650 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2651 this.binding.messagesView.post(
2652 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2653 this.binding.messagesView.post(this::fireReadEvent);
2654 }
2655
2656 private boolean scrolledToBottom() {
2657 return this.binding != null && scrolledToBottom(this.binding.messagesView);
2658 }
2659
2660 private void processExtras(final Bundle extras) {
2661 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2662 final String text = extras.getString(Intent.EXTRA_TEXT);
2663 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2664 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
2665 final String postInitAction =
2666 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
2667 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2668 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2669 final boolean doNotAppend =
2670 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2671 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
2672 final List<Uri> uris = extractUris(extras);
2673 if (uris != null && uris.size() > 0) {
2674 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2675 mediaPreviewAdapter.addMediaPreviews(
2676 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2677 } else {
2678 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2679 mediaPreviewAdapter.addMediaPreviews(
2680 Attachment.of(getActivity(), cleanedUris, type));
2681 }
2682 toggleInputMethod();
2683 return;
2684 }
2685 if (nick != null) {
2686 if (pm) {
2687 Jid jid = conversation.getJid();
2688 try {
2689 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2690 privateMessageWith(next);
2691 } catch (final IllegalArgumentException ignored) {
2692 // do nothing
2693 }
2694 } else {
2695 final MucOptions mucOptions = conversation.getMucOptions();
2696 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2697 highlightInConference(nick);
2698 }
2699 }
2700 } else {
2701 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
2702 mediaPreviewAdapter.addMediaPreviews(
2703 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
2704 toggleInputMethod();
2705 return;
2706 } else if (text != null && asQuote) {
2707 quoteText(text);
2708 } else {
2709 appendText(text, doNotAppend);
2710 }
2711 }
2712 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
2713 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
2714 return;
2715 }
2716 if ("message".equals(postInitAction)) {
2717 binding.conversationViewPager.post(() -> {
2718 binding.conversationViewPager.setCurrentItem(0);
2719 });
2720 }
2721 if ("command".equals(postInitAction)) {
2722 binding.conversationViewPager.post(() -> {
2723 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
2724 if (adapter != null && adapter.getCount() > 1) {
2725 binding.conversationViewPager.setCurrentItem(1);
2726 }
2727 final Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
2728 if (node != null && commandJid != null) {
2729 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
2730 }
2731 });
2732 return;
2733 }
2734 final Message message =
2735 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2736 if (message != null) {
2737 startDownloadable(message);
2738 }
2739 }
2740
2741 private Element commandFor(final Jid jid, final String node) {
2742 if (commandAdapter != null) {
2743 for (int i = 0; i < commandAdapter.getCount(); i++) {
2744 Element command = commandAdapter.getItem(i);
2745 final String commandNode = command.getAttribute("node");
2746 if (commandNode == null || !commandNode.equals(node)) continue;
2747
2748 final Jid commandJid = command.getAttributeAsJid("jid");
2749 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
2750
2751 return command;
2752 }
2753 }
2754
2755 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
2756 }
2757
2758 private List<Uri> extractUris(final Bundle extras) {
2759 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2760 if (uris != null) {
2761 return uris;
2762 }
2763 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2764 if (uri != null) {
2765 return Collections.singletonList(uri);
2766 } else {
2767 return null;
2768 }
2769 }
2770
2771 private List<Uri> cleanUris(final List<Uri> uris) {
2772 final Iterator<Uri> iterator = uris.iterator();
2773 while (iterator.hasNext()) {
2774 final Uri uri = iterator.next();
2775 if (FileBackend.weOwnFile(uri)) {
2776 iterator.remove();
2777 Toast.makeText(
2778 getActivity(),
2779 R.string.security_violation_not_attaching_file,
2780 Toast.LENGTH_SHORT)
2781 .show();
2782 }
2783 }
2784 return uris;
2785 }
2786
2787 private boolean showBlockSubmenu(View view) {
2788 final Jid jid = conversation.getJid();
2789 final boolean showReject =
2790 !conversation.isWithStranger()
2791 && conversation
2792 .getContact()
2793 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2794 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2795 popupMenu.inflate(R.menu.block);
2796 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2797 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2798 popupMenu.setOnMenuItemClickListener(
2799 menuItem -> {
2800 Blockable blockable;
2801 switch (menuItem.getItemId()) {
2802 case R.id.reject:
2803 activity.xmppConnectionService.stopPresenceUpdatesTo(
2804 conversation.getContact());
2805 updateSnackBar(conversation);
2806 return true;
2807 case R.id.block_domain:
2808 blockable =
2809 conversation
2810 .getAccount()
2811 .getRoster()
2812 .getContact(jid.getDomain());
2813 break;
2814 default:
2815 blockable = conversation;
2816 }
2817 BlockContactDialog.show(activity, blockable);
2818 return true;
2819 });
2820 popupMenu.show();
2821 return true;
2822 }
2823
2824 private void updateSnackBar(final Conversation conversation) {
2825 final Account account = conversation.getAccount();
2826 final XmppConnection connection = account.getXmppConnection();
2827 final int mode = conversation.getMode();
2828 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2829 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2830 return;
2831 }
2832 if (account.getStatus() == Account.State.DISABLED) {
2833 showSnackbar(
2834 R.string.this_account_is_disabled,
2835 R.string.enable,
2836 this.mEnableAccountListener);
2837 } else if (conversation.isBlocked()) {
2838 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2839 } else if (contact != null
2840 && !contact.showInRoster()
2841 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2842 showSnackbar(
2843 R.string.contact_added_you,
2844 R.string.add_back,
2845 this.mAddBackClickListener,
2846 this.mLongPressBlockListener);
2847 } else if (contact != null
2848 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2849 showSnackbar(
2850 R.string.contact_asks_for_presence_subscription,
2851 R.string.allow,
2852 this.mAllowPresenceSubscription,
2853 this.mLongPressBlockListener);
2854 } else if (mode == Conversation.MODE_MULTI
2855 && !conversation.getMucOptions().online()
2856 && account.getStatus() == Account.State.ONLINE) {
2857 switch (conversation.getMucOptions().getError()) {
2858 case NICK_IN_USE:
2859 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2860 break;
2861 case NO_RESPONSE:
2862 showSnackbar(R.string.joining_conference, 0, null);
2863 break;
2864 case SERVER_NOT_FOUND:
2865 if (conversation.receivedMessagesCount() > 0) {
2866 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2867 } else {
2868 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2869 }
2870 break;
2871 case REMOTE_SERVER_TIMEOUT:
2872 if (conversation.receivedMessagesCount() > 0) {
2873 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2874 } else {
2875 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2876 }
2877 break;
2878 case PASSWORD_REQUIRED:
2879 showSnackbar(
2880 R.string.conference_requires_password,
2881 R.string.enter_password,
2882 enterPassword);
2883 break;
2884 case BANNED:
2885 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2886 break;
2887 case MEMBERS_ONLY:
2888 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2889 break;
2890 case RESOURCE_CONSTRAINT:
2891 showSnackbar(
2892 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2893 break;
2894 case KICKED:
2895 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2896 break;
2897 case TECHNICAL_PROBLEMS:
2898 showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
2899 break;
2900 case UNKNOWN:
2901 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2902 break;
2903 case INVALID_NICK:
2904 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2905 case SHUTDOWN:
2906 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2907 break;
2908 case DESTROYED:
2909 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2910 break;
2911 case NON_ANONYMOUS:
2912 showSnackbar(
2913 R.string.group_chat_will_make_your_jabber_id_public,
2914 R.string.join,
2915 acceptJoin);
2916 break;
2917 default:
2918 hideSnackbar();
2919 break;
2920 }
2921 } else if (account.hasPendingPgpIntent(conversation)) {
2922 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2923 } else if (connection != null
2924 && connection.getFeatures().blocking()
2925 && conversation.countMessages() != 0
2926 && !conversation.isBlocked()
2927 && conversation.isWithStranger()) {
2928 showSnackbar(
2929 R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2930 } else {
2931 hideSnackbar();
2932 }
2933 }
2934
2935 @Override
2936 public void refresh() {
2937 if (this.binding == null) {
2938 Log.d(
2939 Config.LOGTAG,
2940 "ConversationFragment.refresh() skipped updated because view binding was null");
2941 return;
2942 }
2943 if (this.conversation != null
2944 && this.activity != null
2945 && this.activity.xmppConnectionService != null) {
2946 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2947 activity.onConversationArchived(this.conversation);
2948 return;
2949 }
2950 }
2951 this.refresh(true);
2952 }
2953
2954 private void refresh(boolean notifyConversationRead) {
2955 synchronized (this.messageList) {
2956 if (this.conversation != null) {
2957 conversation.populateWithMessages(this.messageList);
2958 updateSnackBar(conversation);
2959 updateStatusMessages();
2960 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2961 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2962 binding.unreadCountCustomView.setUnreadCount(
2963 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2964 }
2965 this.messageListAdapter.notifyDataSetChanged();
2966 updateChatMsgHint();
2967 if (notifyConversationRead && activity != null) {
2968 binding.messagesView.post(this::fireReadEvent);
2969 }
2970 updateSendButton();
2971 updateEditablity();
2972 }
2973 }
2974 }
2975
2976 protected void messageSent() {
2977 mSendingPgpMessage.set(false);
2978 this.binding.textinput.setText("");
2979 if (conversation.setCorrectingMessage(null)) {
2980 this.binding.textinput.append(conversation.getDraftMessage());
2981 conversation.setDraftMessage(null);
2982 }
2983 storeNextMessage();
2984 updateChatMsgHint();
2985 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2986 final boolean prefScrollToBottom =
2987 p.getBoolean(
2988 "scroll_to_bottom",
2989 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2990 if (prefScrollToBottom || scrolledToBottom()) {
2991 new Handler()
2992 .post(
2993 () -> {
2994 int size = messageList.size();
2995 this.binding.messagesView.setSelection(size - 1);
2996 });
2997 }
2998 }
2999
3000 private boolean storeNextMessage() {
3001 return storeNextMessage(this.binding.textinput.getText().toString());
3002 }
3003
3004 private boolean storeNextMessage(String msg) {
3005 final boolean participating =
3006 conversation.getMode() == Conversational.MODE_SINGLE
3007 || conversation.getMucOptions().participating();
3008 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
3009 && participating
3010 && this.conversation.setNextMessage(msg)) {
3011 this.activity.xmppConnectionService.updateConversation(this.conversation);
3012 return true;
3013 }
3014 return false;
3015 }
3016
3017 public void doneSendingPgpMessage() {
3018 mSendingPgpMessage.set(false);
3019 }
3020
3021 public long getMaxHttpUploadSize(Conversation conversation) {
3022 final XmppConnection connection = conversation.getAccount().getXmppConnection();
3023 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
3024 }
3025
3026 private void updateEditablity() {
3027 boolean canWrite =
3028 this.conversation.getMode() == Conversation.MODE_SINGLE
3029 || this.conversation.getMucOptions().participating()
3030 || this.conversation.getNextCounterpart() != null;
3031 this.binding.textinput.setFocusable(canWrite);
3032 this.binding.textinput.setFocusableInTouchMode(canWrite);
3033 this.binding.textSendButton.setEnabled(canWrite);
3034 this.binding.textinput.setCursorVisible(canWrite);
3035 this.binding.textinput.setEnabled(canWrite);
3036 }
3037
3038 public void updateSendButton() {
3039 boolean hasAttachments =
3040 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
3041 final Conversation c = this.conversation;
3042 final Presence.Status status;
3043 final String text =
3044 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
3045 final SendButtonAction action;
3046 if (hasAttachments) {
3047 action = SendButtonAction.TEXT;
3048 } else {
3049 action = SendButtonTool.getAction(getActivity(), c, text);
3050 }
3051 if (c.getAccount().getStatus() == Account.State.ONLINE) {
3052 if (activity != null
3053 && activity.xmppConnectionService != null
3054 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
3055 status = Presence.Status.OFFLINE;
3056 } else if (c.getMode() == Conversation.MODE_SINGLE) {
3057 status = c.getContact().getShownStatus();
3058 } else {
3059 status =
3060 c.getMucOptions().online()
3061 ? Presence.Status.ONLINE
3062 : Presence.Status.OFFLINE;
3063 }
3064 } else {
3065 status = Presence.Status.OFFLINE;
3066 }
3067 this.binding.textSendButton.setTag(action);
3068 final Activity activity = getActivity();
3069 if (activity != null) {
3070 this.binding.textSendButton.setImageResource(
3071 SendButtonTool.getSendButtonImageResource(activity, action, status));
3072 }
3073
3074 if (hasAttachments || binding.textinput.getText().length() > 0) {
3075 binding.conversationViewPager.setCurrentItem(0);
3076 }
3077 }
3078
3079 protected void updateStatusMessages() {
3080 DateSeparator.addAll(this.messageList);
3081 if (showLoadMoreMessages(conversation)) {
3082 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
3083 }
3084 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3085 ChatState state = conversation.getIncomingChatState();
3086 if (state == ChatState.COMPOSING) {
3087 this.messageList.add(
3088 Message.createStatusMessage(
3089 conversation,
3090 getString(R.string.contact_is_typing, conversation.getName())));
3091 } else if (state == ChatState.PAUSED) {
3092 this.messageList.add(
3093 Message.createStatusMessage(
3094 conversation,
3095 getString(
3096 R.string.contact_has_stopped_typing,
3097 conversation.getName())));
3098 } else {
3099 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3100 final Message message = this.messageList.get(i);
3101 if (message.getType() != Message.TYPE_STATUS) {
3102 if (message.getStatus() == Message.STATUS_RECEIVED) {
3103 return;
3104 } else {
3105 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
3106 this.messageList.add(
3107 i + 1,
3108 Message.createStatusMessage(
3109 conversation,
3110 getString(
3111 R.string.contact_has_read_up_to_this_point,
3112 conversation.getName())));
3113 return;
3114 }
3115 }
3116 }
3117 }
3118 }
3119 } else {
3120 final MucOptions mucOptions = conversation.getMucOptions();
3121 final List<MucOptions.User> allUsers = mucOptions.getUsers();
3122 final Set<ReadByMarker> addedMarkers = new HashSet<>();
3123 ChatState state = ChatState.COMPOSING;
3124 List<MucOptions.User> users =
3125 conversation.getMucOptions().getUsersWithChatState(state, 5);
3126 if (users.size() == 0) {
3127 state = ChatState.PAUSED;
3128 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
3129 }
3130 if (mucOptions.isPrivateAndNonAnonymous()) {
3131 for (int i = this.messageList.size() - 1; i >= 0; --i) {
3132 final Set<ReadByMarker> markersForMessage =
3133 messageList.get(i).getReadByMarkers();
3134 final List<MucOptions.User> shownMarkers = new ArrayList<>();
3135 for (ReadByMarker marker : markersForMessage) {
3136 if (!ReadByMarker.contains(marker, addedMarkers)) {
3137 addedMarkers.add(
3138 marker); // may be put outside this condition. set should do
3139 // dedup anyway
3140 MucOptions.User user = mucOptions.findUser(marker);
3141 if (user != null && !users.contains(user)) {
3142 shownMarkers.add(user);
3143 }
3144 }
3145 }
3146 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
3147 final Message statusMessage;
3148 final int size = shownMarkers.size();
3149 if (size > 1) {
3150 final String body;
3151 if (size <= 4) {
3152 body =
3153 getString(
3154 R.string.contacts_have_read_up_to_this_point,
3155 UIHelper.concatNames(shownMarkers));
3156 } else if (ReadByMarker.allUsersRepresented(
3157 allUsers, markersForMessage, markerForSender)) {
3158 body = getString(R.string.everyone_has_read_up_to_this_point);
3159 } else {
3160 body =
3161 getString(
3162 R.string.contacts_and_n_more_have_read_up_to_this_point,
3163 UIHelper.concatNames(shownMarkers, 3),
3164 size - 3);
3165 }
3166 statusMessage = Message.createStatusMessage(conversation, body);
3167 statusMessage.setCounterparts(shownMarkers);
3168 } else if (size == 1) {
3169 statusMessage =
3170 Message.createStatusMessage(
3171 conversation,
3172 getString(
3173 R.string.contact_has_read_up_to_this_point,
3174 UIHelper.getDisplayName(shownMarkers.get(0))));
3175 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
3176 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
3177 } else {
3178 statusMessage = null;
3179 }
3180 if (statusMessage != null) {
3181 this.messageList.add(i + 1, statusMessage);
3182 }
3183 addedMarkers.add(markerForSender);
3184 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
3185 break;
3186 }
3187 }
3188 }
3189 if (users.size() > 0) {
3190 Message statusMessage;
3191 if (users.size() == 1) {
3192 MucOptions.User user = users.get(0);
3193 int id =
3194 state == ChatState.COMPOSING
3195 ? R.string.contact_is_typing
3196 : R.string.contact_has_stopped_typing;
3197 statusMessage =
3198 Message.createStatusMessage(
3199 conversation, getString(id, UIHelper.getDisplayName(user)));
3200 statusMessage.setTrueCounterpart(user.getRealJid());
3201 statusMessage.setCounterpart(user.getFullJid());
3202 } else {
3203 int id =
3204 state == ChatState.COMPOSING
3205 ? R.string.contacts_are_typing
3206 : R.string.contacts_have_stopped_typing;
3207 statusMessage =
3208 Message.createStatusMessage(
3209 conversation, getString(id, UIHelper.concatNames(users)));
3210 statusMessage.setCounterparts(users);
3211 }
3212 this.messageList.add(statusMessage);
3213 }
3214 }
3215 }
3216
3217 private void stopScrolling() {
3218 long now = SystemClock.uptimeMillis();
3219 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
3220 binding.messagesView.dispatchTouchEvent(cancel);
3221 }
3222
3223 private boolean showLoadMoreMessages(final Conversation c) {
3224 if (activity == null || activity.xmppConnectionService == null) {
3225 return false;
3226 }
3227 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
3228 final MessageArchiveService service =
3229 activity.xmppConnectionService.getMessageArchiveService();
3230 return mam
3231 && (c.getLastClearHistory().getTimestamp() != 0
3232 || (c.countMessages() == 0
3233 && c.messagesLoaded.get()
3234 && c.hasMessagesLeftOnServer()
3235 && !service.queryInProgress(c)));
3236 }
3237
3238 private boolean hasMamSupport(final Conversation c) {
3239 if (c.getMode() == Conversation.MODE_SINGLE) {
3240 final XmppConnection connection = c.getAccount().getXmppConnection();
3241 return connection != null && connection.getFeatures().mam();
3242 } else {
3243 return c.getMucOptions().mamSupport();
3244 }
3245 }
3246
3247 protected void showSnackbar(
3248 final int message, final int action, final OnClickListener clickListener) {
3249 showSnackbar(message, action, clickListener, null);
3250 }
3251
3252 protected void showSnackbar(
3253 final int message,
3254 final int action,
3255 final OnClickListener clickListener,
3256 final View.OnLongClickListener longClickListener) {
3257 this.binding.snackbar.setVisibility(View.VISIBLE);
3258 this.binding.snackbar.setOnClickListener(null);
3259 this.binding.snackbarMessage.setText(message);
3260 this.binding.snackbarMessage.setOnClickListener(null);
3261 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
3262 if (action != 0) {
3263 this.binding.snackbarAction.setText(action);
3264 }
3265 this.binding.snackbarAction.setOnClickListener(clickListener);
3266 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
3267 }
3268
3269 protected void hideSnackbar() {
3270 this.binding.snackbar.setVisibility(View.GONE);
3271 }
3272
3273 protected void sendMessage(Message message) {
3274 activity.xmppConnectionService.sendMessage(message);
3275 messageSent();
3276 }
3277
3278 protected void sendPgpMessage(final Message message) {
3279 final XmppConnectionService xmppService = activity.xmppConnectionService;
3280 final Contact contact = message.getConversation().getContact();
3281 if (!activity.hasPgp()) {
3282 activity.showInstallPgpDialog();
3283 return;
3284 }
3285 if (conversation.getAccount().getPgpSignature() == null) {
3286 activity.announcePgp(
3287 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
3288 return;
3289 }
3290 if (!mSendingPgpMessage.compareAndSet(false, true)) {
3291 Log.d(Config.LOGTAG, "sending pgp message already in progress");
3292 }
3293 if (conversation.getMode() == Conversation.MODE_SINGLE) {
3294 if (contact.getPgpKeyId() != 0) {
3295 xmppService
3296 .getPgpEngine()
3297 .hasKey(
3298 contact,
3299 new UiCallback<Contact>() {
3300
3301 @Override
3302 public void userInputRequired(
3303 PendingIntent pi, Contact contact) {
3304 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
3305 }
3306
3307 @Override
3308 public void success(Contact contact) {
3309 encryptTextMessage(message);
3310 }
3311
3312 @Override
3313 public void error(int error, Contact contact) {
3314 activity.runOnUiThread(
3315 () ->
3316 Toast.makeText(
3317 activity,
3318 R.string
3319 .unable_to_connect_to_keychain,
3320 Toast.LENGTH_SHORT)
3321 .show());
3322 mSendingPgpMessage.set(false);
3323 }
3324 });
3325
3326 } else {
3327 showNoPGPKeyDialog(
3328 false,
3329 (dialog, which) -> {
3330 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3331 xmppService.updateConversation(conversation);
3332 message.setEncryption(Message.ENCRYPTION_NONE);
3333 xmppService.sendMessage(message);
3334 messageSent();
3335 });
3336 }
3337 } else {
3338 if (conversation.getMucOptions().pgpKeysInUse()) {
3339 if (!conversation.getMucOptions().everybodyHasKeys()) {
3340 Toast warning =
3341 Toast.makeText(
3342 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
3343 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
3344 warning.show();
3345 }
3346 encryptTextMessage(message);
3347 } else {
3348 showNoPGPKeyDialog(
3349 true,
3350 (dialog, which) -> {
3351 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
3352 message.setEncryption(Message.ENCRYPTION_NONE);
3353 xmppService.updateConversation(conversation);
3354 xmppService.sendMessage(message);
3355 messageSent();
3356 });
3357 }
3358 }
3359 }
3360
3361 public void encryptTextMessage(Message message) {
3362 activity.xmppConnectionService
3363 .getPgpEngine()
3364 .encrypt(
3365 message,
3366 new UiCallback<Message>() {
3367
3368 @Override
3369 public void userInputRequired(PendingIntent pi, Message message) {
3370 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
3371 }
3372
3373 @Override
3374 public void success(Message message) {
3375 // TODO the following two call can be made before the callback
3376 getActivity().runOnUiThread(() -> messageSent());
3377 }
3378
3379 @Override
3380 public void error(final int error, Message message) {
3381 getActivity()
3382 .runOnUiThread(
3383 () -> {
3384 doneSendingPgpMessage();
3385 Toast.makeText(
3386 getActivity(),
3387 error == 0
3388 ? R.string
3389 .unable_to_connect_to_keychain
3390 : error,
3391 Toast.LENGTH_SHORT)
3392 .show();
3393 });
3394 }
3395 });
3396 }
3397
3398 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
3399 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
3400 builder.setIconAttribute(android.R.attr.alertDialogIcon);
3401 if (plural) {
3402 builder.setTitle(getString(R.string.no_pgp_keys));
3403 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
3404 } else {
3405 builder.setTitle(getString(R.string.no_pgp_key));
3406 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
3407 }
3408 builder.setNegativeButton(getString(R.string.cancel), null);
3409 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
3410 builder.create().show();
3411 }
3412
3413 public void appendText(String text, final boolean doNotAppend) {
3414 if (text == null) {
3415 return;
3416 }
3417 final Editable editable = this.binding.textinput.getText();
3418 String previous = editable == null ? "" : editable.toString();
3419 if (doNotAppend && !TextUtils.isEmpty(previous)) {
3420 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
3421 .show();
3422 return;
3423 }
3424 if (UIHelper.isLastLineQuote(previous)) {
3425 text = '\n' + text;
3426 } else if (previous.length() != 0
3427 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
3428 text = " " + text;
3429 }
3430 this.binding.textinput.append(text);
3431 }
3432
3433 @Override
3434 public boolean onEnterPressed(final boolean isCtrlPressed) {
3435 if (isCtrlPressed || enterIsSend()) {
3436 sendMessage();
3437 return true;
3438 }
3439 return false;
3440 }
3441
3442 private boolean enterIsSend() {
3443 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
3444 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
3445 }
3446
3447 public boolean onArrowUpCtrlPressed() {
3448 final Message lastEditableMessage =
3449 conversation == null ? null : conversation.getLastEditableMessage();
3450 if (lastEditableMessage != null) {
3451 correctMessage(lastEditableMessage);
3452 return true;
3453 } else {
3454 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
3455 .show();
3456 return false;
3457 }
3458 }
3459
3460 @Override
3461 public void onTypingStarted() {
3462 final XmppConnectionService service =
3463 activity == null ? null : activity.xmppConnectionService;
3464 if (service == null) {
3465 return;
3466 }
3467 final Account.State status = conversation.getAccount().getStatus();
3468 if (status == Account.State.ONLINE
3469 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
3470 service.sendChatState(conversation);
3471 }
3472 runOnUiThread(this::updateSendButton);
3473 }
3474
3475 @Override
3476 public void onTypingStopped() {
3477 final XmppConnectionService service =
3478 activity == null ? null : activity.xmppConnectionService;
3479 if (service == null) {
3480 return;
3481 }
3482 final Account.State status = conversation.getAccount().getStatus();
3483 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
3484 service.sendChatState(conversation);
3485 }
3486 }
3487
3488 @Override
3489 public void onTextDeleted() {
3490 final XmppConnectionService service =
3491 activity == null ? null : activity.xmppConnectionService;
3492 if (service == null) {
3493 return;
3494 }
3495 final Account.State status = conversation.getAccount().getStatus();
3496 if (status == Account.State.ONLINE
3497 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3498 service.sendChatState(conversation);
3499 }
3500 if (storeNextMessage()) {
3501 runOnUiThread(
3502 () -> {
3503 if (activity == null) {
3504 return;
3505 }
3506 activity.onConversationsListItemUpdated();
3507 });
3508 }
3509 runOnUiThread(this::updateSendButton);
3510 }
3511
3512 @Override
3513 public void onTextChanged() {
3514 if (conversation != null && conversation.getCorrectingMessage() != null) {
3515 runOnUiThread(this::updateSendButton);
3516 }
3517 }
3518
3519 @Override
3520 public boolean onTabPressed(boolean repeated) {
3521 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
3522 return false;
3523 }
3524 if (repeated) {
3525 completionIndex++;
3526 } else {
3527 lastCompletionLength = 0;
3528 completionIndex = 0;
3529 final String content = this.binding.textinput.getText().toString();
3530 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
3531 int start =
3532 lastCompletionCursor > 0
3533 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
3534 : 0;
3535 firstWord = start == 0;
3536 incomplete = content.substring(start, lastCompletionCursor);
3537 }
3538 List<String> completions = new ArrayList<>();
3539 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
3540 String name = user.getName();
3541 if (name != null && name.startsWith(incomplete)) {
3542 completions.add(name + (firstWord ? ": " : " "));
3543 }
3544 }
3545 Collections.sort(completions);
3546 if (completions.size() > completionIndex) {
3547 String completion = completions.get(completionIndex).substring(incomplete.length());
3548 this.binding
3549 .textinput
3550 .getEditableText()
3551 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3552 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
3553 lastCompletionLength = completion.length();
3554 } else {
3555 completionIndex = -1;
3556 this.binding
3557 .textinput
3558 .getEditableText()
3559 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
3560 lastCompletionLength = 0;
3561 }
3562 return true;
3563 }
3564
3565 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
3566 try {
3567 getActivity()
3568 .startIntentSenderForResult(
3569 pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
3570 } catch (final SendIntentException ignored) {
3571 }
3572 }
3573
3574 @Override
3575 public void onBackendConnected() {
3576 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
3577 String uuid = pendingConversationsUuid.pop();
3578 if (uuid != null) {
3579 if (!findAndReInitByUuidOrArchive(uuid)) {
3580 return;
3581 }
3582 } else {
3583 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
3584 clearPending();
3585 activity.onConversationArchived(conversation);
3586 return;
3587 }
3588 }
3589 ActivityResult activityResult = postponedActivityResult.pop();
3590 if (activityResult != null) {
3591 handleActivityResult(activityResult);
3592 }
3593 clearPending();
3594 }
3595
3596 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
3597 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
3598 if (conversation == null) {
3599 clearPending();
3600 activity.onConversationArchived(null);
3601 return false;
3602 }
3603 reInit(conversation);
3604 ScrollState scrollState = pendingScrollState.pop();
3605 String lastMessageUuid = pendingLastMessageUuid.pop();
3606 List<Attachment> attachments = pendingMediaPreviews.pop();
3607 if (scrollState != null) {
3608 setScrollPosition(scrollState, lastMessageUuid);
3609 }
3610 if (attachments != null && attachments.size() > 0) {
3611 Log.d(Config.LOGTAG, "had attachments on restore");
3612 mediaPreviewAdapter.addMediaPreviews(attachments);
3613 toggleInputMethod();
3614 }
3615 return true;
3616 }
3617
3618 private void clearPending() {
3619 if (postponedActivityResult.clear()) {
3620 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
3621 if (pendingTakePhotoUri.clear()) {
3622 Log.e(Config.LOGTAG, "cleared pending photo uri");
3623 }
3624 }
3625 if (pendingScrollState.clear()) {
3626 Log.e(Config.LOGTAG, "cleared scroll state");
3627 }
3628 if (pendingConversationsUuid.clear()) {
3629 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
3630 }
3631 if (pendingMediaPreviews.clear()) {
3632 Log.e(Config.LOGTAG, "cleared pending media previews");
3633 }
3634 }
3635
3636 public Conversation getConversation() {
3637 return conversation;
3638 }
3639
3640 @Override
3641 public void onContactPictureLongClicked(View v, final Message message) {
3642 final String fingerprint;
3643 if (message.getEncryption() == Message.ENCRYPTION_PGP
3644 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
3645 fingerprint = "pgp";
3646 } else {
3647 fingerprint = message.getFingerprint();
3648 }
3649 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
3650 final Contact contact = message.getContact();
3651 if (message.getStatus() <= Message.STATUS_RECEIVED
3652 && (contact == null || !contact.isSelf())) {
3653 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
3654 final Jid cp = message.getCounterpart();
3655 if (cp == null || cp.isBareJid()) {
3656 return;
3657 }
3658 final Jid tcp = message.getTrueCounterpart();
3659 final User userByRealJid =
3660 tcp != null
3661 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp)
3662 : null;
3663 final User user =
3664 userByRealJid != null
3665 ? userByRealJid
3666 : conversation.getMucOptions().findUserByFullJid(cp);
3667 popupMenu.inflate(R.menu.muc_details_context);
3668 final Menu menu = popupMenu.getMenu();
3669 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
3670 activity, menu, conversation, user);
3671 popupMenu.setOnMenuItemClickListener(
3672 menuItem ->
3673 MucDetailsContextMenuHelper.onContextItemSelected(
3674 menuItem, user, activity, fingerprint));
3675 } else {
3676 popupMenu.inflate(R.menu.one_on_one_context);
3677 popupMenu.setOnMenuItemClickListener(
3678 item -> {
3679 switch (item.getItemId()) {
3680 case R.id.action_contact_details:
3681 activity.switchToContactDetails(
3682 message.getContact(), fingerprint);
3683 break;
3684 case R.id.action_show_qr_code:
3685 activity.showQrCode(
3686 "xmpp:"
3687 + message.getContact()
3688 .getJid()
3689 .asBareJid()
3690 .toEscapedString());
3691 break;
3692 }
3693 return true;
3694 });
3695 }
3696 } else {
3697 popupMenu.inflate(R.menu.account_context);
3698 final Menu menu = popupMenu.getMenu();
3699 menu.findItem(R.id.action_manage_accounts)
3700 .setVisible(QuickConversationsService.isConversations());
3701 popupMenu.setOnMenuItemClickListener(
3702 item -> {
3703 final XmppActivity activity = this.activity;
3704 if (activity == null) {
3705 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
3706 return true;
3707 }
3708 switch (item.getItemId()) {
3709 case R.id.action_show_qr_code:
3710 activity.showQrCode(conversation.getAccount().getShareableUri());
3711 break;
3712 case R.id.action_account_details:
3713 activity.switchToAccount(
3714 message.getConversation().getAccount(), fingerprint);
3715 break;
3716 case R.id.action_manage_accounts:
3717 AccountUtils.launchManageAccounts(activity);
3718 break;
3719 }
3720 return true;
3721 });
3722 }
3723 popupMenu.show();
3724 }
3725
3726 @Override
3727 public void onContactPictureClicked(Message message) {
3728 setThread(message.getThread());
3729 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
3730 if (received) {
3731 if (message.getConversation() instanceof Conversation
3732 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
3733 Jid tcp = message.getTrueCounterpart();
3734 Jid user = message.getCounterpart();
3735 if (user != null && !user.isBareJid()) {
3736 final MucOptions mucOptions =
3737 ((Conversation) message.getConversation()).getMucOptions();
3738 if (mucOptions.participating()
3739 || ((Conversation) message.getConversation()).getNextCounterpart()
3740 != null) {
3741 if (!mucOptions.isUserInRoom(user)
3742 && mucOptions.findUserByRealJid(
3743 tcp == null ? null : tcp.asBareJid())
3744 == null) {
3745 Toast.makeText(
3746 getActivity(),
3747 activity.getString(
3748 R.string.user_has_left_conference,
3749 user.getResource()),
3750 Toast.LENGTH_SHORT)
3751 .show();
3752 }
3753 highlightInConference(user.getResource());
3754 } else {
3755 Toast.makeText(
3756 getActivity(),
3757 R.string.you_are_not_participating,
3758 Toast.LENGTH_SHORT)
3759 .show();
3760 }
3761 }
3762 }
3763 }
3764 }
3765
3766 private Activity requireActivity() {
3767 final Activity activity = getActivity();
3768 if (activity == null) {
3769 throw new IllegalStateException("Activity not attached");
3770 }
3771 return activity;
3772 }
3773}