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 (hasPermissions(REQUEST_START_AUDIO_CALL, Manifest.permission.RECORD_AUDIO)) {
1248 triggerRtpSession();
1249 }
1250 }
1251
1252 private void triggerRtpSession() {
1253 final Contact contact = conversation.getContact();
1254 final Intent intent = new Intent(activity, RtpSessionActivity.class);
1255 intent.setAction(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1256 intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, contact.getAccount().getJid().toEscapedString());
1257 intent.putExtra(RtpSessionActivity.EXTRA_WITH, contact.getJid().asBareJid().toEscapedString());
1258 startActivity(intent);
1259 }
1260
1261 private void handleAttachmentSelection(MenuItem item) {
1262 switch (item.getItemId()) {
1263 case R.id.attach_choose_picture:
1264 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1265 break;
1266 case R.id.attach_take_picture:
1267 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1268 break;
1269 case R.id.attach_record_video:
1270 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1271 break;
1272 case R.id.attach_choose_file:
1273 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1274 break;
1275 case R.id.attach_record_voice:
1276 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1277 break;
1278 case R.id.attach_location:
1279 attachFile(ATTACHMENT_CHOICE_LOCATION);
1280 break;
1281 }
1282 }
1283
1284 private void handleEncryptionSelection(MenuItem item) {
1285 if (conversation == null) {
1286 return;
1287 }
1288 final boolean updated;
1289 switch (item.getItemId()) {
1290 case R.id.encryption_choice_none:
1291 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1292 item.setChecked(true);
1293 break;
1294 case R.id.encryption_choice_pgp:
1295 if (activity.hasPgp()) {
1296 if (conversation.getAccount().getPgpSignature() != null) {
1297 updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1298 item.setChecked(true);
1299 } else {
1300 updated = false;
1301 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1302 }
1303 } else {
1304 activity.showInstallPgpDialog();
1305 updated = false;
1306 }
1307 break;
1308 case R.id.encryption_choice_axolotl:
1309 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1310 + "Enabled axolotl for Contact " + conversation.getContact().getJid());
1311 updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1312 item.setChecked(true);
1313 break;
1314 default:
1315 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1316 break;
1317 }
1318 if (updated) {
1319 activity.xmppConnectionService.updateConversation(conversation);
1320 }
1321 updateChatMsgHint();
1322 getActivity().invalidateOptionsMenu();
1323 activity.refreshUi();
1324 }
1325
1326 public void attachFile(final int attachmentChoice) {
1327 if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1328 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)) {
1329 return;
1330 }
1331 } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1332 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
1333 return;
1334 }
1335 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1336 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1337 return;
1338 }
1339 }
1340 try {
1341 activity.getPreferences().edit()
1342 .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1343 .apply();
1344 } catch (IllegalArgumentException e) {
1345 //just do not save
1346 }
1347 final int encryption = conversation.getNextEncryption();
1348 final int mode = conversation.getMode();
1349 if (encryption == Message.ENCRYPTION_PGP) {
1350 if (activity.hasPgp()) {
1351 if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1352 activity.xmppConnectionService.getPgpEngine().hasKey(
1353 conversation.getContact(),
1354 new UiCallback<Contact>() {
1355
1356 @Override
1357 public void userInputRequired(PendingIntent pi, Contact contact) {
1358 startPendingIntent(pi, attachmentChoice);
1359 }
1360
1361 @Override
1362 public void success(Contact contact) {
1363 invokeAttachFileIntent(attachmentChoice);
1364 }
1365
1366 @Override
1367 public void error(int error, Contact contact) {
1368 activity.replaceToast(getString(error));
1369 }
1370 });
1371 } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1372 if (!conversation.getMucOptions().everybodyHasKeys()) {
1373 Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1374 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1375 warning.show();
1376 }
1377 invokeAttachFileIntent(attachmentChoice);
1378 } else {
1379 showNoPGPKeyDialog(false, (dialog, which) -> {
1380 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1381 activity.xmppConnectionService.updateConversation(conversation);
1382 invokeAttachFileIntent(attachmentChoice);
1383 });
1384 }
1385 } else {
1386 activity.showInstallPgpDialog();
1387 }
1388 } else {
1389 invokeAttachFileIntent(attachmentChoice);
1390 }
1391 }
1392
1393 @Override
1394 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
1395 if (grantResults.length > 0) {
1396 if (allGranted(grantResults)) {
1397 switch (requestCode) {
1398 case REQUEST_START_DOWNLOAD:
1399 if (this.mPendingDownloadableMessage != null) {
1400 startDownloadable(this.mPendingDownloadableMessage);
1401 }
1402 break;
1403 case REQUEST_ADD_EDITOR_CONTENT:
1404 if (this.mPendingEditorContent != null) {
1405 attachEditorContentToConversation(this.mPendingEditorContent);
1406 }
1407 break;
1408 case REQUEST_COMMIT_ATTACHMENTS:
1409 commitAttachments();
1410 break;
1411 case REQUEST_START_AUDIO_CALL:
1412 triggerRtpSession();
1413 break;
1414 default:
1415 attachFile(requestCode);
1416 break;
1417 }
1418 } else {
1419 @StringRes int res;
1420 String firstDenied = getFirstDenied(grantResults, permissions);
1421 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1422 res = R.string.no_microphone_permission;
1423 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1424 res = R.string.no_camera_permission;
1425 } else {
1426 res = R.string.no_storage_permission;
1427 }
1428 Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1429 }
1430 }
1431 if (writeGranted(grantResults, permissions)) {
1432 if (activity != null && activity.xmppConnectionService != null) {
1433 activity.xmppConnectionService.restartFileObserver();
1434 }
1435 refresh();
1436 }
1437 }
1438
1439 public void startDownloadable(Message message) {
1440 if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1441 this.mPendingDownloadableMessage = message;
1442 return;
1443 }
1444 Transferable transferable = message.getTransferable();
1445 if (transferable != null) {
1446 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1447 createNewConnection(message);
1448 return;
1449 }
1450 if (!transferable.start()) {
1451 Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1452 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1453 }
1454 } else if (message.treatAsDownloadable() || message.hasFileOnRemoteHost() || MessageUtils.unInitiatedButKnownSize(message)) {
1455 createNewConnection(message);
1456 } else {
1457 Log.d(Config.LOGTAG, message.getConversation().getAccount() + ": unable to start downloadable");
1458 }
1459 }
1460
1461 private void createNewConnection(final Message message) {
1462 if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) {
1463 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1464 return;
1465 }
1466 activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1467 }
1468
1469 @SuppressLint("InflateParams")
1470 protected void clearHistoryDialog(final Conversation conversation) {
1471 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1472 builder.setTitle(getString(R.string.clear_conversation_history));
1473 final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1474 final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1475 builder.setView(dialogView);
1476 builder.setNegativeButton(getString(R.string.cancel), null);
1477 builder.setPositiveButton(getString(R.string.confirm), (dialog, which) -> {
1478 this.activity.xmppConnectionService.clearConversationHistory(conversation);
1479 if (endConversationCheckBox.isChecked()) {
1480 this.activity.xmppConnectionService.archiveConversation(conversation);
1481 this.activity.onConversationArchived(conversation);
1482 } else {
1483 activity.onConversationsListItemUpdated();
1484 refresh();
1485 }
1486 });
1487 builder.create().show();
1488 }
1489
1490 protected void muteConversationDialog(final Conversation conversation) {
1491 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1492 builder.setTitle(R.string.disable_notifications);
1493 final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1494 final CharSequence[] labels = new CharSequence[durations.length];
1495 for (int i = 0; i < durations.length; ++i) {
1496 if (durations[i] == -1) {
1497 labels[i] = getString(R.string.until_further_notice);
1498 } else {
1499 labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
1500 }
1501 }
1502 builder.setItems(labels, (dialog, which) -> {
1503 final long till;
1504 if (durations[which] == -1) {
1505 till = Long.MAX_VALUE;
1506 } else {
1507 till = System.currentTimeMillis() + (durations[which] * 1000);
1508 }
1509 conversation.setMutedTill(till);
1510 activity.xmppConnectionService.updateConversation(conversation);
1511 activity.onConversationsListItemUpdated();
1512 refresh();
1513 getActivity().invalidateOptionsMenu();
1514 });
1515 builder.create().show();
1516 }
1517
1518 private boolean hasPermissions(int requestCode, String... permissions) {
1519 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1520 final List<String> missingPermissions = new ArrayList<>();
1521 for (String permission : permissions) {
1522 if (Config.ONLY_INTERNAL_STORAGE && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1523 continue;
1524 }
1525 if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
1526 missingPermissions.add(permission);
1527 }
1528 }
1529 if (missingPermissions.size() == 0) {
1530 return true;
1531 } else {
1532 requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1533 return false;
1534 }
1535 } else {
1536 return true;
1537 }
1538 }
1539
1540 public void unmuteConversation(final Conversation conversation) {
1541 conversation.setMutedTill(0);
1542 this.activity.xmppConnectionService.updateConversation(conversation);
1543 this.activity.onConversationsListItemUpdated();
1544 refresh();
1545 getActivity().invalidateOptionsMenu();
1546 }
1547
1548
1549 protected void invokeAttachFileIntent(final int attachmentChoice) {
1550 Intent intent = new Intent();
1551 boolean chooser = false;
1552 switch (attachmentChoice) {
1553 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1554 intent.setAction(Intent.ACTION_GET_CONTENT);
1555 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1556 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1557 }
1558 intent.setType("image/*");
1559 chooser = true;
1560 break;
1561 case ATTACHMENT_CHOICE_RECORD_VIDEO:
1562 intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1563 break;
1564 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1565 final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1566 pendingTakePhotoUri.push(uri);
1567 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1568 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1569 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1570 intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1571 break;
1572 case ATTACHMENT_CHOICE_CHOOSE_FILE:
1573 chooser = true;
1574 intent.setType("*/*");
1575 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1576 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1577 }
1578 intent.addCategory(Intent.CATEGORY_OPENABLE);
1579 intent.setAction(Intent.ACTION_GET_CONTENT);
1580 break;
1581 case ATTACHMENT_CHOICE_RECORD_VOICE:
1582 intent = new Intent(getActivity(), RecordingActivity.class);
1583 break;
1584 case ATTACHMENT_CHOICE_LOCATION:
1585 intent = GeoHelper.getFetchIntent(activity);
1586 break;
1587 }
1588 final Context context = getActivity();
1589 if (context != null && intent.resolveActivity(context.getPackageManager()) != null) {
1590 if (chooser) {
1591 startActivityForResult(
1592 Intent.createChooser(intent, getString(R.string.perform_action_with)),
1593 attachmentChoice);
1594 } else {
1595 startActivityForResult(intent, attachmentChoice);
1596 }
1597 }
1598 }
1599
1600 @Override
1601 public void onResume() {
1602 super.onResume();
1603 binding.messagesView.post(this::fireReadEvent);
1604 }
1605
1606 private void fireReadEvent() {
1607 if (activity != null && this.conversation != null) {
1608 String uuid = getLastVisibleMessageUuid();
1609 if (uuid != null) {
1610 activity.onConversationRead(this.conversation, uuid);
1611 }
1612 }
1613 }
1614
1615 private String getLastVisibleMessageUuid() {
1616 if (binding == null) {
1617 return null;
1618 }
1619 synchronized (this.messageList) {
1620 int pos = binding.messagesView.getLastVisiblePosition();
1621 if (pos >= 0) {
1622 Message message = null;
1623 for (int i = pos; i >= 0; --i) {
1624 try {
1625 message = (Message) binding.messagesView.getItemAtPosition(i);
1626 } catch (IndexOutOfBoundsException e) {
1627 //should not happen if we synchronize properly. however if that fails we just gonna try item -1
1628 continue;
1629 }
1630 if (message.getType() != Message.TYPE_STATUS) {
1631 break;
1632 }
1633 }
1634 if (message != null) {
1635 while (message.next() != null && message.next().wasMergedIntoPrevious()) {
1636 message = message.next();
1637 }
1638 return message.getUuid();
1639 }
1640 }
1641 }
1642 return null;
1643 }
1644
1645 private void openWith(final Message message) {
1646 if (message.isGeoUri()) {
1647 GeoHelper.view(getActivity(), message);
1648 } else {
1649 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1650 ViewUtil.view(activity, file);
1651 }
1652 }
1653
1654 private void showErrorMessage(final Message message) {
1655 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1656 builder.setTitle(R.string.error_message);
1657 final String errorMessage = message.getErrorMessage();
1658 final String[] errorMessageParts = errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
1659 final String displayError;
1660 if (errorMessageParts.length == 2) {
1661 displayError = errorMessageParts[1];
1662 } else {
1663 displayError = errorMessage;
1664 }
1665 builder.setMessage(displayError);
1666 builder.setNegativeButton(R.string.copy_to_clipboard, (dialog, which) -> {
1667 activity.copyTextToClipboard(displayError, R.string.error_message);
1668 Toast.makeText(activity, R.string.error_message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1669 });
1670 builder.setPositiveButton(R.string.confirm, null);
1671 builder.create().show();
1672 }
1673
1674
1675 private void deleteFile(final Message message) {
1676 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1677 builder.setNegativeButton(R.string.cancel, null);
1678 builder.setTitle(R.string.delete_file_dialog);
1679 builder.setMessage(R.string.delete_file_dialog_msg);
1680 builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
1681 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1682 message.setDeleted(true);
1683 activity.xmppConnectionService.evictPreview(message.getUuid());
1684 activity.xmppConnectionService.updateMessage(message, false);
1685 activity.onConversationsListItemUpdated();
1686 refresh();
1687 }
1688 });
1689 builder.create().show();
1690
1691 }
1692
1693 private void resendMessage(final Message message) {
1694 if (message.isFileOrImage()) {
1695 if (!(message.getConversation() instanceof Conversation)) {
1696 return;
1697 }
1698 final Conversation conversation = (Conversation) message.getConversation();
1699 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1700 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
1701 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1702 if (!message.hasFileOnRemoteHost()
1703 && xmppConnection != null
1704 && conversation.getMode() == Conversational.MODE_SINGLE
1705 && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1706 activity.selectPresence(conversation, () -> {
1707 message.setCounterpart(conversation.getNextCounterpart());
1708 activity.xmppConnectionService.resendFailedMessages(message);
1709 new Handler().post(() -> {
1710 int size = messageList.size();
1711 this.binding.messagesView.setSelection(size - 1);
1712 });
1713 });
1714 return;
1715 }
1716 } else if (!Compatibility.hasStoragePermission(getActivity())) {
1717 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
1718 return;
1719 } else {
1720 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1721 message.setDeleted(true);
1722 activity.xmppConnectionService.updateMessage(message, false);
1723 activity.onConversationsListItemUpdated();
1724 refresh();
1725 return;
1726 }
1727 }
1728 activity.xmppConnectionService.resendFailedMessages(message);
1729 new Handler().post(() -> {
1730 int size = messageList.size();
1731 this.binding.messagesView.setSelection(size - 1);
1732 });
1733 }
1734
1735 private void cancelTransmission(Message message) {
1736 Transferable transferable = message.getTransferable();
1737 if (transferable != null) {
1738 transferable.cancel();
1739 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1740 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
1741 }
1742 }
1743
1744 private void retryDecryption(Message message) {
1745 message.setEncryption(Message.ENCRYPTION_PGP);
1746 activity.onConversationsListItemUpdated();
1747 refresh();
1748 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1749 }
1750
1751 public void privateMessageWith(final Jid counterpart) {
1752 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1753 activity.xmppConnectionService.sendChatState(conversation);
1754 }
1755 this.binding.textinput.setText("");
1756 this.conversation.setNextCounterpart(counterpart);
1757 updateChatMsgHint();
1758 updateSendButton();
1759 updateEditablity();
1760 }
1761
1762 private void correctMessage(Message message) {
1763 while (message.mergeable(message.next())) {
1764 message = message.next();
1765 }
1766 this.conversation.setCorrectingMessage(message);
1767 final Editable editable = binding.textinput.getText();
1768 this.conversation.setDraftMessage(editable.toString());
1769 this.binding.textinput.setText("");
1770 this.binding.textinput.append(message.getBody());
1771
1772 }
1773
1774 private void highlightInConference(String nick) {
1775 final Editable editable = this.binding.textinput.getText();
1776 String oldString = editable.toString().trim();
1777 final int pos = this.binding.textinput.getSelectionStart();
1778 if (oldString.isEmpty() || pos == 0) {
1779 editable.insert(0, nick + ": ");
1780 } else {
1781 final char before = editable.charAt(pos - 1);
1782 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1783 if (before == '\n') {
1784 editable.insert(pos, nick + ": ");
1785 } else {
1786 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1787 if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1788 editable.insert(pos - 2, ", " + nick);
1789 return;
1790 }
1791 }
1792 editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1793 if (Character.isWhitespace(after)) {
1794 this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1795 }
1796 }
1797 }
1798 }
1799
1800 @Override
1801 public void startActivityForResult(Intent intent, int requestCode) {
1802 final Activity activity = getActivity();
1803 if (activity instanceof ConversationsActivity) {
1804 ((ConversationsActivity) activity).clearPendingViewIntent();
1805 }
1806 super.startActivityForResult(intent, requestCode);
1807 }
1808
1809 @Override
1810 public void onSaveInstanceState(Bundle outState) {
1811 super.onSaveInstanceState(outState);
1812 if (conversation != null) {
1813 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1814 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1815 final Uri uri = pendingTakePhotoUri.peek();
1816 if (uri != null) {
1817 outState.putString(STATE_PHOTO_URI, uri.toString());
1818 }
1819 final ScrollState scrollState = getScrollPosition();
1820 if (scrollState != null) {
1821 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1822 }
1823 final ArrayList<Attachment> attachments = mediaPreviewAdapter == null ? new ArrayList<>() : mediaPreviewAdapter.getAttachments();
1824 if (attachments.size() > 0) {
1825 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
1826 }
1827 }
1828 }
1829
1830 @Override
1831 public void onActivityCreated(Bundle savedInstanceState) {
1832 super.onActivityCreated(savedInstanceState);
1833 if (savedInstanceState == null) {
1834 return;
1835 }
1836 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1837 ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
1838 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1839 if (uuid != null) {
1840 QuickLoader.set(uuid);
1841 this.pendingConversationsUuid.push(uuid);
1842 if (attachments != null && attachments.size() > 0) {
1843 this.pendingMediaPreviews.push(attachments);
1844 }
1845 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1846 if (takePhotoUri != null) {
1847 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1848 }
1849 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1850 }
1851 }
1852
1853 @Override
1854 public void onStart() {
1855 super.onStart();
1856 if (this.reInitRequiredOnStart && this.conversation != null) {
1857 final Bundle extras = pendingExtras.pop();
1858 reInit(this.conversation, extras != null);
1859 if (extras != null) {
1860 processExtras(extras);
1861 }
1862 } else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1863 final String uuid = pendingConversationsUuid.pop();
1864 Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
1865 if (uuid != null) {
1866 findAndReInitByUuidOrArchive(uuid);
1867 }
1868 }
1869 }
1870
1871 @Override
1872 public void onStop() {
1873 super.onStop();
1874 final Activity activity = getActivity();
1875 messageListAdapter.unregisterListenerInAudioPlayer();
1876 if (activity == null || !activity.isChangingConfigurations()) {
1877 hideSoftKeyboard(activity);
1878 messageListAdapter.stopAudioPlayer();
1879 }
1880 if (this.conversation != null) {
1881 final String msg = this.binding.textinput.getText().toString();
1882 storeNextMessage(msg);
1883 updateChatState(this.conversation, msg);
1884 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1885 }
1886 this.reInitRequiredOnStart = true;
1887 }
1888
1889 private void updateChatState(final Conversation conversation, final String msg) {
1890 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
1891 Account.State status = conversation.getAccount().getStatus();
1892 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1893 activity.xmppConnectionService.sendChatState(conversation);
1894 }
1895 }
1896
1897 private void saveMessageDraftStopAudioPlayer() {
1898 final Conversation previousConversation = this.conversation;
1899 if (this.activity == null || this.binding == null || previousConversation == null) {
1900 return;
1901 }
1902 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1903 final String msg = this.binding.textinput.getText().toString();
1904 storeNextMessage(msg);
1905 updateChatState(this.conversation, msg);
1906 messageListAdapter.stopAudioPlayer();
1907 mediaPreviewAdapter.clearPreviews();
1908 toggleInputMethod();
1909 }
1910
1911 public void reInit(Conversation conversation, Bundle extras) {
1912 QuickLoader.set(conversation.getUuid());
1913 this.saveMessageDraftStopAudioPlayer();
1914 this.clearPending();
1915 if (this.reInit(conversation, extras != null)) {
1916 if (extras != null) {
1917 processExtras(extras);
1918 }
1919 this.reInitRequiredOnStart = false;
1920 } else {
1921 this.reInitRequiredOnStart = true;
1922 pendingExtras.push(extras);
1923 }
1924 resetUnreadMessagesCount();
1925 }
1926
1927 private void reInit(Conversation conversation) {
1928 reInit(conversation, false);
1929 }
1930
1931 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1932 if (conversation == null) {
1933 return false;
1934 }
1935 this.conversation = conversation;
1936 //once we set the conversation all is good and it will automatically do the right thing in onStart()
1937 if (this.activity == null || this.binding == null) {
1938 return false;
1939 }
1940
1941 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1942 activity.onConversationArchived(this.conversation);
1943 return false;
1944 }
1945
1946 stopScrolling();
1947 Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1948
1949 if (this.conversation.isRead() && hasExtras) {
1950 Log.d(Config.LOGTAG, "trimming conversation");
1951 this.conversation.trim();
1952 }
1953
1954 setupIme();
1955
1956 final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1957
1958 this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1959 this.binding.textinput.setKeyboardListener(null);
1960 this.binding.textinput.setText("");
1961 final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
1962 if (participating) {
1963 this.binding.textinput.append(this.conversation.getNextMessage());
1964 }
1965 this.binding.textinput.setKeyboardListener(this);
1966 messageListAdapter.updatePreferences();
1967 refresh(false);
1968 this.conversation.messagesLoaded.set(true);
1969 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1970
1971 if (hasExtras || scrolledToBottomAndNoPending) {
1972 resetUnreadMessagesCount();
1973 synchronized (this.messageList) {
1974 Log.d(Config.LOGTAG, "jump to first unread message");
1975 final Message first = conversation.getFirstUnreadMessage();
1976 final int bottom = Math.max(0, this.messageList.size() - 1);
1977 final int pos;
1978 final boolean jumpToBottom;
1979 if (first == null) {
1980 pos = bottom;
1981 jumpToBottom = true;
1982 } else {
1983 int i = getIndexOf(first.getUuid(), this.messageList);
1984 pos = i < 0 ? bottom : i;
1985 jumpToBottom = false;
1986 }
1987 setSelection(pos, jumpToBottom);
1988 }
1989 }
1990
1991
1992 this.binding.messagesView.post(this::fireReadEvent);
1993 //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
1994 activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1995 return true;
1996 }
1997
1998 private void resetUnreadMessagesCount() {
1999 lastMessageUuid = null;
2000 hideUnreadMessagesCount();
2001 }
2002
2003 private void hideUnreadMessagesCount() {
2004 if (this.binding == null) {
2005 return;
2006 }
2007 this.binding.scrollToBottomButton.setEnabled(false);
2008 this.binding.scrollToBottomButton.hide();
2009 this.binding.unreadCountCustomView.setVisibility(View.GONE);
2010 }
2011
2012 private void setSelection(int pos, boolean jumpToBottom) {
2013 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2014 this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2015 this.binding.messagesView.post(this::fireReadEvent);
2016 }
2017
2018
2019 private boolean scrolledToBottom() {
2020 return this.binding != null && scrolledToBottom(this.binding.messagesView);
2021 }
2022
2023 private void processExtras(Bundle extras) {
2024 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2025 final String text = extras.getString(Intent.EXTRA_TEXT);
2026 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2027 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2028 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2029 final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2030 final List<Uri> uris = extractUris(extras);
2031 if (uris != null && uris.size() > 0) {
2032 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2033 mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2034 } else {
2035 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2036 mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));
2037 }
2038 toggleInputMethod();
2039 return;
2040 }
2041 if (nick != null) {
2042 if (pm) {
2043 Jid jid = conversation.getJid();
2044 try {
2045 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2046 privateMessageWith(next);
2047 } catch (final IllegalArgumentException ignored) {
2048 //do nothing
2049 }
2050 } else {
2051 final MucOptions mucOptions = conversation.getMucOptions();
2052 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2053 highlightInConference(nick);
2054 }
2055 }
2056 } else {
2057 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
2058 mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
2059 toggleInputMethod();
2060 return;
2061 } else if (text != null && asQuote) {
2062 quoteText(text);
2063 } else {
2064 appendText(text, doNotAppend);
2065 }
2066 }
2067 final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2068 if (message != null) {
2069 startDownloadable(message);
2070 }
2071 }
2072
2073 private List<Uri> extractUris(Bundle extras) {
2074 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2075 if (uris != null) {
2076 return uris;
2077 }
2078 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2079 if (uri != null) {
2080 return Collections.singletonList(uri);
2081 } else {
2082 return null;
2083 }
2084 }
2085
2086 private List<Uri> cleanUris(List<Uri> uris) {
2087 Iterator<Uri> iterator = uris.iterator();
2088 while (iterator.hasNext()) {
2089 final Uri uri = iterator.next();
2090 if (FileBackend.weOwnFile(getActivity(), uri)) {
2091 iterator.remove();
2092 Toast.makeText(getActivity(), R.string.security_violation_not_attaching_file, Toast.LENGTH_SHORT).show();
2093 }
2094 }
2095 return uris;
2096 }
2097
2098 private boolean showBlockSubmenu(View view) {
2099 final Jid jid = conversation.getJid();
2100 final boolean showReject = !conversation.isWithStranger() && conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2101 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2102 popupMenu.inflate(R.menu.block);
2103 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2104 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2105 popupMenu.setOnMenuItemClickListener(menuItem -> {
2106 Blockable blockable;
2107 switch (menuItem.getItemId()) {
2108 case R.id.reject:
2109 activity.xmppConnectionService.stopPresenceUpdatesTo(conversation.getContact());
2110 updateSnackBar(conversation);
2111 return true;
2112 case R.id.block_domain:
2113 blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
2114 break;
2115 default:
2116 blockable = conversation;
2117 }
2118 BlockContactDialog.show(activity, blockable);
2119 return true;
2120 });
2121 popupMenu.show();
2122 return true;
2123 }
2124
2125 private void updateSnackBar(final Conversation conversation) {
2126 final Account account = conversation.getAccount();
2127 final XmppConnection connection = account.getXmppConnection();
2128 final int mode = conversation.getMode();
2129 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2130 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2131 return;
2132 }
2133 if (account.getStatus() == Account.State.DISABLED) {
2134 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
2135 } else if (conversation.isBlocked()) {
2136 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2137 } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2138 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
2139 } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2140 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
2141 } else if (mode == Conversation.MODE_MULTI
2142 && !conversation.getMucOptions().online()
2143 && account.getStatus() == Account.State.ONLINE) {
2144 switch (conversation.getMucOptions().getError()) {
2145 case NICK_IN_USE:
2146 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2147 break;
2148 case NO_RESPONSE:
2149 showSnackbar(R.string.joining_conference, 0, null);
2150 break;
2151 case SERVER_NOT_FOUND:
2152 if (conversation.receivedMessagesCount() > 0) {
2153 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2154 } else {
2155 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2156 }
2157 break;
2158 case REMOTE_SERVER_TIMEOUT:
2159 if (conversation.receivedMessagesCount() > 0) {
2160 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2161 } else {
2162 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2163 }
2164 break;
2165 case PASSWORD_REQUIRED:
2166 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2167 break;
2168 case BANNED:
2169 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2170 break;
2171 case MEMBERS_ONLY:
2172 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2173 break;
2174 case RESOURCE_CONSTRAINT:
2175 showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2176 break;
2177 case KICKED:
2178 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2179 break;
2180 case UNKNOWN:
2181 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2182 break;
2183 case INVALID_NICK:
2184 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2185 case SHUTDOWN:
2186 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2187 break;
2188 case DESTROYED:
2189 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2190 break;
2191 case NON_ANONYMOUS:
2192 showSnackbar(R.string.group_chat_will_make_your_jabber_id_public, R.string.join, acceptJoin);
2193 break;
2194 default:
2195 hideSnackbar();
2196 break;
2197 }
2198 } else if (account.hasPendingPgpIntent(conversation)) {
2199 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2200 } else if (connection != null
2201 && connection.getFeatures().blocking()
2202 && conversation.countMessages() != 0
2203 && !conversation.isBlocked()
2204 && conversation.isWithStranger()) {
2205 showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2206 } else {
2207 hideSnackbar();
2208 }
2209 }
2210
2211 @Override
2212 public void refresh() {
2213 if (this.binding == null) {
2214 Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2215 return;
2216 }
2217 if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2218 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2219 activity.onConversationArchived(this.conversation);
2220 return;
2221 }
2222 }
2223 this.refresh(true);
2224 }
2225
2226 private void refresh(boolean notifyConversationRead) {
2227 synchronized (this.messageList) {
2228 if (this.conversation != null) {
2229 conversation.populateWithMessages(this.messageList);
2230 updateSnackBar(conversation);
2231 updateStatusMessages();
2232 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2233 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2234 binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2235 }
2236 this.messageListAdapter.notifyDataSetChanged();
2237 updateChatMsgHint();
2238 if (notifyConversationRead && activity != null) {
2239 binding.messagesView.post(this::fireReadEvent);
2240 }
2241 updateSendButton();
2242 updateEditablity();
2243 activity.invalidateOptionsMenu();
2244 }
2245 }
2246 }
2247
2248 protected void messageSent() {
2249 mSendingPgpMessage.set(false);
2250 this.binding.textinput.setText("");
2251 if (conversation.setCorrectingMessage(null)) {
2252 this.binding.textinput.append(conversation.getDraftMessage());
2253 conversation.setDraftMessage(null);
2254 }
2255 storeNextMessage();
2256 updateChatMsgHint();
2257 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2258 final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2259 if (prefScrollToBottom || scrolledToBottom()) {
2260 new Handler().post(() -> {
2261 int size = messageList.size();
2262 this.binding.messagesView.setSelection(size - 1);
2263 });
2264 }
2265 }
2266
2267 private boolean storeNextMessage() {
2268 return storeNextMessage(this.binding.textinput.getText().toString());
2269 }
2270
2271 private boolean storeNextMessage(String msg) {
2272 final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2273 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) {
2274 this.activity.xmppConnectionService.updateConversation(this.conversation);
2275 return true;
2276 }
2277 return false;
2278 }
2279
2280 public void doneSendingPgpMessage() {
2281 mSendingPgpMessage.set(false);
2282 }
2283
2284 public long getMaxHttpUploadSize(Conversation conversation) {
2285 final XmppConnection connection = conversation.getAccount().getXmppConnection();
2286 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2287 }
2288
2289 private void updateEditablity() {
2290 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2291 this.binding.textinput.setFocusable(canWrite);
2292 this.binding.textinput.setFocusableInTouchMode(canWrite);
2293 this.binding.textSendButton.setEnabled(canWrite);
2294 this.binding.textinput.setCursorVisible(canWrite);
2295 this.binding.textinput.setEnabled(canWrite);
2296 }
2297
2298 public void updateSendButton() {
2299 boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2300 final Conversation c = this.conversation;
2301 final Presence.Status status;
2302 final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2303 final SendButtonAction action;
2304 if (hasAttachments) {
2305 action = SendButtonAction.TEXT;
2306 } else {
2307 action = SendButtonTool.getAction(getActivity(), c, text);
2308 }
2309 if (c.getAccount().getStatus() == Account.State.ONLINE) {
2310 if (activity != null && activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2311 status = Presence.Status.OFFLINE;
2312 } else if (c.getMode() == Conversation.MODE_SINGLE) {
2313 status = c.getContact().getShownStatus();
2314 } else {
2315 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2316 }
2317 } else {
2318 status = Presence.Status.OFFLINE;
2319 }
2320 this.binding.textSendButton.setTag(action);
2321 final Activity activity = getActivity();
2322 if (activity != null) {
2323 this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(activity, action, status));
2324 }
2325 }
2326
2327 protected void updateStatusMessages() {
2328 DateSeparator.addAll(this.messageList);
2329 if (showLoadMoreMessages(conversation)) {
2330 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2331 }
2332 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2333 ChatState state = conversation.getIncomingChatState();
2334 if (state == ChatState.COMPOSING) {
2335 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2336 } else if (state == ChatState.PAUSED) {
2337 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2338 } else {
2339 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2340 final Message message = this.messageList.get(i);
2341 if (message.getType() != Message.TYPE_STATUS) {
2342 if (message.getStatus() == Message.STATUS_RECEIVED) {
2343 return;
2344 } else {
2345 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
2346 this.messageList.add(i + 1,
2347 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2348 return;
2349 }
2350 }
2351 }
2352 }
2353 }
2354 } else {
2355 final MucOptions mucOptions = conversation.getMucOptions();
2356 final List<MucOptions.User> allUsers = mucOptions.getUsers();
2357 final Set<ReadByMarker> addedMarkers = new HashSet<>();
2358 ChatState state = ChatState.COMPOSING;
2359 List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2360 if (users.size() == 0) {
2361 state = ChatState.PAUSED;
2362 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2363 }
2364 if (mucOptions.isPrivateAndNonAnonymous()) {
2365 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2366 final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2367 final List<MucOptions.User> shownMarkers = new ArrayList<>();
2368 for (ReadByMarker marker : markersForMessage) {
2369 if (!ReadByMarker.contains(marker, addedMarkers)) {
2370 addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2371 MucOptions.User user = mucOptions.findUser(marker);
2372 if (user != null && !users.contains(user)) {
2373 shownMarkers.add(user);
2374 }
2375 }
2376 }
2377 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2378 final Message statusMessage;
2379 final int size = shownMarkers.size();
2380 if (size > 1) {
2381 final String body;
2382 if (size <= 4) {
2383 body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2384 } else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) {
2385 body = getString(R.string.everyone_has_read_up_to_this_point);
2386 } else {
2387 body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2388 }
2389 statusMessage = Message.createStatusMessage(conversation, body);
2390 statusMessage.setCounterparts(shownMarkers);
2391 } else if (size == 1) {
2392 statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2393 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2394 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2395 } else {
2396 statusMessage = null;
2397 }
2398 if (statusMessage != null) {
2399 this.messageList.add(i + 1, statusMessage);
2400 }
2401 addedMarkers.add(markerForSender);
2402 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2403 break;
2404 }
2405 }
2406 }
2407 if (users.size() > 0) {
2408 Message statusMessage;
2409 if (users.size() == 1) {
2410 MucOptions.User user = users.get(0);
2411 int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2412 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2413 statusMessage.setTrueCounterpart(user.getRealJid());
2414 statusMessage.setCounterpart(user.getFullJid());
2415 } else {
2416 int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2417 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2418 statusMessage.setCounterparts(users);
2419 }
2420 this.messageList.add(statusMessage);
2421 }
2422
2423 }
2424 }
2425
2426 private void stopScrolling() {
2427 long now = SystemClock.uptimeMillis();
2428 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2429 binding.messagesView.dispatchTouchEvent(cancel);
2430 }
2431
2432 private boolean showLoadMoreMessages(final Conversation c) {
2433 if (activity == null || activity.xmppConnectionService == null) {
2434 return false;
2435 }
2436 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2437 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2438 return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2439 }
2440
2441 private boolean hasMamSupport(final Conversation c) {
2442 if (c.getMode() == Conversation.MODE_SINGLE) {
2443 final XmppConnection connection = c.getAccount().getXmppConnection();
2444 return connection != null && connection.getFeatures().mam();
2445 } else {
2446 return c.getMucOptions().mamSupport();
2447 }
2448 }
2449
2450 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2451 showSnackbar(message, action, clickListener, null);
2452 }
2453
2454 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2455 this.binding.snackbar.setVisibility(View.VISIBLE);
2456 this.binding.snackbar.setOnClickListener(null);
2457 this.binding.snackbarMessage.setText(message);
2458 this.binding.snackbarMessage.setOnClickListener(null);
2459 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2460 if (action != 0) {
2461 this.binding.snackbarAction.setText(action);
2462 }
2463 this.binding.snackbarAction.setOnClickListener(clickListener);
2464 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2465 }
2466
2467 protected void hideSnackbar() {
2468 this.binding.snackbar.setVisibility(View.GONE);
2469 }
2470
2471 protected void sendMessage(Message message) {
2472 activity.xmppConnectionService.sendMessage(message);
2473 messageSent();
2474 }
2475
2476 protected void sendPgpMessage(final Message message) {
2477 final XmppConnectionService xmppService = activity.xmppConnectionService;
2478 final Contact contact = message.getConversation().getContact();
2479 if (!activity.hasPgp()) {
2480 activity.showInstallPgpDialog();
2481 return;
2482 }
2483 if (conversation.getAccount().getPgpSignature() == null) {
2484 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2485 return;
2486 }
2487 if (!mSendingPgpMessage.compareAndSet(false, true)) {
2488 Log.d(Config.LOGTAG, "sending pgp message already in progress");
2489 }
2490 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2491 if (contact.getPgpKeyId() != 0) {
2492 xmppService.getPgpEngine().hasKey(contact,
2493 new UiCallback<Contact>() {
2494
2495 @Override
2496 public void userInputRequired(PendingIntent pi, Contact contact) {
2497 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2498 }
2499
2500 @Override
2501 public void success(Contact contact) {
2502 encryptTextMessage(message);
2503 }
2504
2505 @Override
2506 public void error(int error, Contact contact) {
2507 activity.runOnUiThread(() -> Toast.makeText(activity,
2508 R.string.unable_to_connect_to_keychain,
2509 Toast.LENGTH_SHORT
2510 ).show());
2511 mSendingPgpMessage.set(false);
2512 }
2513 });
2514
2515 } else {
2516 showNoPGPKeyDialog(false, (dialog, which) -> {
2517 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2518 xmppService.updateConversation(conversation);
2519 message.setEncryption(Message.ENCRYPTION_NONE);
2520 xmppService.sendMessage(message);
2521 messageSent();
2522 });
2523 }
2524 } else {
2525 if (conversation.getMucOptions().pgpKeysInUse()) {
2526 if (!conversation.getMucOptions().everybodyHasKeys()) {
2527 Toast warning = Toast
2528 .makeText(getActivity(),
2529 R.string.missing_public_keys,
2530 Toast.LENGTH_LONG);
2531 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2532 warning.show();
2533 }
2534 encryptTextMessage(message);
2535 } else {
2536 showNoPGPKeyDialog(true, (dialog, which) -> {
2537 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2538 message.setEncryption(Message.ENCRYPTION_NONE);
2539 xmppService.updateConversation(conversation);
2540 xmppService.sendMessage(message);
2541 messageSent();
2542 });
2543 }
2544 }
2545 }
2546
2547 public void encryptTextMessage(Message message) {
2548 activity.xmppConnectionService.getPgpEngine().encrypt(message,
2549 new UiCallback<Message>() {
2550
2551 @Override
2552 public void userInputRequired(PendingIntent pi, Message message) {
2553 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2554 }
2555
2556 @Override
2557 public void success(Message message) {
2558 //TODO the following two call can be made before the callback
2559 getActivity().runOnUiThread(() -> messageSent());
2560 }
2561
2562 @Override
2563 public void error(final int error, Message message) {
2564 getActivity().runOnUiThread(() -> {
2565 doneSendingPgpMessage();
2566 Toast.makeText(getActivity(), error == 0 ? R.string.unable_to_connect_to_keychain : error, Toast.LENGTH_SHORT).show();
2567 });
2568
2569 }
2570 });
2571 }
2572
2573 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2574 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2575 builder.setIconAttribute(android.R.attr.alertDialogIcon);
2576 if (plural) {
2577 builder.setTitle(getString(R.string.no_pgp_keys));
2578 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2579 } else {
2580 builder.setTitle(getString(R.string.no_pgp_key));
2581 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2582 }
2583 builder.setNegativeButton(getString(R.string.cancel), null);
2584 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2585 builder.create().show();
2586 }
2587
2588 public void appendText(String text, final boolean doNotAppend) {
2589 if (text == null) {
2590 return;
2591 }
2592 final Editable editable = this.binding.textinput.getText();
2593 String previous = editable == null ? "" : editable.toString();
2594 if (doNotAppend && !TextUtils.isEmpty(previous)) {
2595 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG).show();
2596 return;
2597 }
2598 if (UIHelper.isLastLineQuote(previous)) {
2599 text = '\n' + text;
2600 } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
2601 text = " " + text;
2602 }
2603 this.binding.textinput.append(text);
2604 }
2605
2606 @Override
2607 public boolean onEnterPressed() {
2608 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2609 final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2610 if (enterIsSend) {
2611 sendMessage();
2612 return true;
2613 } else {
2614 return false;
2615 }
2616 }
2617
2618 @Override
2619 public void onTypingStarted() {
2620 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2621 if (service == null) {
2622 return;
2623 }
2624 Account.State status = conversation.getAccount().getStatus();
2625 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2626 service.sendChatState(conversation);
2627 }
2628 runOnUiThread(this::updateSendButton);
2629 }
2630
2631 @Override
2632 public void onTypingStopped() {
2633 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2634 if (service == null) {
2635 return;
2636 }
2637 Account.State status = conversation.getAccount().getStatus();
2638 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2639 service.sendChatState(conversation);
2640 }
2641 }
2642
2643 @Override
2644 public void onTextDeleted() {
2645 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2646 if (service == null) {
2647 return;
2648 }
2649 Account.State status = conversation.getAccount().getStatus();
2650 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2651 service.sendChatState(conversation);
2652 }
2653 if (storeNextMessage()) {
2654 runOnUiThread(() -> {
2655 if (activity == null) {
2656 return;
2657 }
2658 activity.onConversationsListItemUpdated();
2659 });
2660 }
2661 runOnUiThread(this::updateSendButton);
2662 }
2663
2664 @Override
2665 public void onTextChanged() {
2666 if (conversation != null && conversation.getCorrectingMessage() != null) {
2667 runOnUiThread(this::updateSendButton);
2668 }
2669 }
2670
2671 @Override
2672 public boolean onTabPressed(boolean repeated) {
2673 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2674 return false;
2675 }
2676 if (repeated) {
2677 completionIndex++;
2678 } else {
2679 lastCompletionLength = 0;
2680 completionIndex = 0;
2681 final String content = this.binding.textinput.getText().toString();
2682 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2683 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2684 firstWord = start == 0;
2685 incomplete = content.substring(start, lastCompletionCursor);
2686 }
2687 List<String> completions = new ArrayList<>();
2688 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2689 String name = user.getName();
2690 if (name != null && name.startsWith(incomplete)) {
2691 completions.add(name + (firstWord ? ": " : " "));
2692 }
2693 }
2694 Collections.sort(completions);
2695 if (completions.size() > completionIndex) {
2696 String completion = completions.get(completionIndex).substring(incomplete.length());
2697 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2698 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2699 lastCompletionLength = completion.length();
2700 } else {
2701 completionIndex = -1;
2702 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2703 lastCompletionLength = 0;
2704 }
2705 return true;
2706 }
2707
2708 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2709 try {
2710 getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2711 } catch (final SendIntentException ignored) {
2712 }
2713 }
2714
2715 @Override
2716 public void onBackendConnected() {
2717 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2718 String uuid = pendingConversationsUuid.pop();
2719 if (uuid != null) {
2720 if (!findAndReInitByUuidOrArchive(uuid)) {
2721 return;
2722 }
2723 } else {
2724 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2725 clearPending();
2726 activity.onConversationArchived(conversation);
2727 return;
2728 }
2729 }
2730 ActivityResult activityResult = postponedActivityResult.pop();
2731 if (activityResult != null) {
2732 handleActivityResult(activityResult);
2733 }
2734 clearPending();
2735 }
2736
2737 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2738 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2739 if (conversation == null) {
2740 clearPending();
2741 activity.onConversationArchived(null);
2742 return false;
2743 }
2744 reInit(conversation);
2745 ScrollState scrollState = pendingScrollState.pop();
2746 String lastMessageUuid = pendingLastMessageUuid.pop();
2747 List<Attachment> attachments = pendingMediaPreviews.pop();
2748 if (scrollState != null) {
2749 setScrollPosition(scrollState, lastMessageUuid);
2750 }
2751 if (attachments != null && attachments.size() > 0) {
2752 Log.d(Config.LOGTAG, "had attachments on restore");
2753 mediaPreviewAdapter.addMediaPreviews(attachments);
2754 toggleInputMethod();
2755 }
2756 return true;
2757 }
2758
2759 private void clearPending() {
2760 if (postponedActivityResult.clear()) {
2761 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2762 }
2763 if (pendingScrollState.clear()) {
2764 Log.e(Config.LOGTAG, "cleared scroll state");
2765 }
2766 if (pendingTakePhotoUri.clear()) {
2767 Log.e(Config.LOGTAG, "cleared pending photo uri");
2768 }
2769 if (pendingConversationsUuid.clear()) {
2770 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
2771 }
2772 if (pendingMediaPreviews.clear()) {
2773 Log.e(Config.LOGTAG, "cleared pending media previews");
2774 }
2775 }
2776
2777 public Conversation getConversation() {
2778 return conversation;
2779 }
2780
2781 @Override
2782 public void onContactPictureLongClicked(View v, final Message message) {
2783 final String fingerprint;
2784 if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2785 fingerprint = "pgp";
2786 } else {
2787 fingerprint = message.getFingerprint();
2788 }
2789 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
2790 final Contact contact = message.getContact();
2791 if (message.getStatus() <= Message.STATUS_RECEIVED && (contact == null || !contact.isSelf())) {
2792 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
2793 final Jid cp = message.getCounterpart();
2794 if (cp == null || cp.isBareJid()) {
2795 return;
2796 }
2797 final Jid tcp = message.getTrueCounterpart();
2798 final User userByRealJid = tcp != null ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp) : null;
2799 final User user = userByRealJid != null ? userByRealJid : conversation.getMucOptions().findUserByFullJid(cp);
2800 popupMenu.inflate(R.menu.muc_details_context);
2801 final Menu menu = popupMenu.getMenu();
2802 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(activity, menu, conversation, user);
2803 popupMenu.setOnMenuItemClickListener(menuItem -> MucDetailsContextMenuHelper.onContextItemSelected(menuItem, user, activity, fingerprint));
2804 } else {
2805 popupMenu.inflate(R.menu.one_on_one_context);
2806 popupMenu.setOnMenuItemClickListener(item -> {
2807 switch (item.getItemId()) {
2808 case R.id.action_contact_details:
2809 activity.switchToContactDetails(message.getContact(), fingerprint);
2810 break;
2811 case R.id.action_show_qr_code:
2812 activity.showQrCode("xmpp:" + message.getContact().getJid().asBareJid().toEscapedString());
2813 break;
2814 }
2815 return true;
2816 });
2817 }
2818 } else {
2819 popupMenu.inflate(R.menu.account_context);
2820 final Menu menu = popupMenu.getMenu();
2821 menu.findItem(R.id.action_manage_accounts).setVisible(QuickConversationsService.isConversations());
2822 popupMenu.setOnMenuItemClickListener(item -> {
2823 switch (item.getItemId()) {
2824 case R.id.action_show_qr_code:
2825 activity.showQrCode(conversation.getAccount().getShareableUri());
2826 break;
2827 case R.id.action_account_details:
2828 activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2829 break;
2830 case R.id.action_manage_accounts:
2831 AccountUtils.launchManageAccounts(activity);
2832 break;
2833 }
2834 return true;
2835 });
2836 }
2837 popupMenu.show();
2838 }
2839
2840 @Override
2841 public void onContactPictureClicked(Message message) {
2842 String fingerprint;
2843 if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2844 fingerprint = "pgp";
2845 } else {
2846 fingerprint = message.getFingerprint();
2847 }
2848 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
2849 if (received) {
2850 if (message.getConversation() instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) {
2851 Jid tcp = message.getTrueCounterpart();
2852 Jid user = message.getCounterpart();
2853 if (user != null && !user.isBareJid()) {
2854 final MucOptions mucOptions = ((Conversation) message.getConversation()).getMucOptions();
2855 if (mucOptions.participating() || ((Conversation) message.getConversation()).getNextCounterpart() != null) {
2856 if (!mucOptions.isUserInRoom(user) && mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid()) == null) {
2857 Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
2858 }
2859 highlightInConference(user.getResource());
2860 } else {
2861 Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
2862 }
2863 }
2864 return;
2865 } else {
2866 if (!message.getContact().isSelf()) {
2867 activity.switchToContactDetails(message.getContact(), fingerprint);
2868 return;
2869 }
2870 }
2871 }
2872 activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2873 }
2874}