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