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