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