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