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