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