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