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