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