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