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