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