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