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