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