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