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