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