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 deleted = t != null && t instanceof TransferablePlaceholder;
1064 final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1065 || m.getEncryption() == Message.ENCRYPTION_PGP;
1066 final boolean receiving = m.getStatus() == Message.STATUS_RECEIVED && (t instanceof JingleConnection || t instanceof HttpDownloadConnection);
1067 activity.getMenuInflater().inflate(R.menu.message_context, menu);
1068 menu.setHeaderTitle(R.string.message_options);
1069 MenuItem copyMessage = menu.findItem(R.id.copy_message);
1070 MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1071 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1072 MenuItem correctMessage = menu.findItem(R.id.correct_message);
1073 MenuItem shareWith = menu.findItem(R.id.share_with);
1074 MenuItem sendAgain = menu.findItem(R.id.send_again);
1075 MenuItem copyUrl = menu.findItem(R.id.copy_url);
1076 MenuItem downloadFile = menu.findItem(R.id.download_file);
1077 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1078 MenuItem deleteFile = menu.findItem(R.id.delete_file);
1079 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1080 if (!m.isFileOrImage() && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
1081 copyMessage.setVisible(true);
1082 quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
1083 }
1084 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
1085 retryDecryption.setVisible(true);
1086 }
1087 if (relevantForCorrection.getType() == Message.TYPE_TEXT
1088 && relevantForCorrection.isLastCorrectableMessage()
1089 && (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
1090 correctMessage.setVisible(true);
1091 }
1092 if ((m.isFileOrImage() && !deleted && !receiving) || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
1093 shareWith.setVisible(true);
1094 }
1095 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1096 sendAgain.setVisible(true);
1097 }
1098 if (m.hasFileOnRemoteHost()
1099 || m.isGeoUri()
1100 || m.treatAsDownloadable()
1101 || (t != null && t instanceof HttpDownloadConnection)) {
1102 copyUrl.setVisible(true);
1103 }
1104 if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1105 downloadFile.setVisible(true);
1106 downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
1107 }
1108 boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1109 || m.getStatus() == Message.STATUS_UNSEND
1110 || m.getStatus() == Message.STATUS_OFFERED;
1111 if ((t != null && !deleted) || waitingOfferedSending && m.needsUploading()) {
1112 cancelTransmission.setVisible(true);
1113 }
1114 if (m.isFileOrImage() && !deleted) {
1115 String path = m.getRelativeFilePath();
1116 if (path == null || !path.startsWith("/")) {
1117 deleteFile.setVisible(true);
1118 deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1119 }
1120 }
1121 if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
1122 showErrorMessage.setVisible(true);
1123 }
1124 }
1125 }
1126
1127 @Override
1128 public boolean onContextItemSelected(MenuItem item) {
1129 switch (item.getItemId()) {
1130 case R.id.share_with:
1131 shareWith(selectedMessage);
1132 return true;
1133 case R.id.correct_message:
1134 correctMessage(selectedMessage);
1135 return true;
1136 case R.id.copy_message:
1137 copyMessage(selectedMessage);
1138 return true;
1139 case R.id.quote_message:
1140 quoteMessage(selectedMessage);
1141 return true;
1142 case R.id.send_again:
1143 resendMessage(selectedMessage);
1144 return true;
1145 case R.id.copy_url:
1146 copyUrl(selectedMessage);
1147 return true;
1148 case R.id.download_file:
1149 startDownloadable(selectedMessage);
1150 return true;
1151 case R.id.cancel_transmission:
1152 cancelTransmission(selectedMessage);
1153 return true;
1154 case R.id.retry_decryption:
1155 retryDecryption(selectedMessage);
1156 return true;
1157 case R.id.delete_file:
1158 deleteFile(selectedMessage);
1159 return true;
1160 case R.id.show_error_message:
1161 showErrorMessage(selectedMessage);
1162 return true;
1163 default:
1164 return super.onContextItemSelected(item);
1165 }
1166 }
1167
1168 @Override
1169 public boolean onOptionsItemSelected(final MenuItem item) {
1170 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1171 return false;
1172 } else if (conversation == null) {
1173 return super.onOptionsItemSelected(item);
1174 }
1175 switch (item.getItemId()) {
1176 case R.id.encryption_choice_axolotl:
1177 case R.id.encryption_choice_pgp:
1178 case R.id.encryption_choice_none:
1179 handleEncryptionSelection(item);
1180 break;
1181 case R.id.attach_choose_picture:
1182 case R.id.attach_take_picture:
1183 case R.id.attach_record_video:
1184 case R.id.attach_choose_file:
1185 case R.id.attach_record_voice:
1186 case R.id.attach_location:
1187 handleAttachmentSelection(item);
1188 break;
1189 case R.id.action_archive:
1190 activity.xmppConnectionService.archiveConversation(conversation);
1191 break;
1192 case R.id.action_contact_details:
1193 activity.switchToContactDetails(conversation.getContact());
1194 break;
1195 case R.id.action_muc_details:
1196 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1197 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1198 intent.putExtra("uuid", conversation.getUuid());
1199 startActivity(intent);
1200 break;
1201 case R.id.action_invite:
1202 startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
1203 break;
1204 case R.id.action_clear_history:
1205 clearHistoryDialog(conversation);
1206 break;
1207 case R.id.action_mute:
1208 muteConversationDialog(conversation);
1209 break;
1210 case R.id.action_unmute:
1211 unmuteConversation(conversation);
1212 break;
1213 case R.id.action_block:
1214 case R.id.action_unblock:
1215 final Activity activity = getActivity();
1216 if (activity instanceof XmppActivity) {
1217 BlockContactDialog.show((XmppActivity) activity, conversation);
1218 }
1219 break;
1220 default:
1221 break;
1222 }
1223 return super.onOptionsItemSelected(item);
1224 }
1225
1226 private void handleAttachmentSelection(MenuItem item) {
1227 switch (item.getItemId()) {
1228 case R.id.attach_choose_picture:
1229 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1230 break;
1231 case R.id.attach_take_picture:
1232 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1233 break;
1234 case R.id.attach_record_video:
1235 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1236 break;
1237 case R.id.attach_choose_file:
1238 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1239 break;
1240 case R.id.attach_record_voice:
1241 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1242 break;
1243 case R.id.attach_location:
1244 attachFile(ATTACHMENT_CHOICE_LOCATION);
1245 break;
1246 }
1247 }
1248
1249 private void handleEncryptionSelection(MenuItem item) {
1250 if (conversation == null) {
1251 return;
1252 }
1253 switch (item.getItemId()) {
1254 case R.id.encryption_choice_none:
1255 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1256 item.setChecked(true);
1257 break;
1258 case R.id.encryption_choice_pgp:
1259 if (activity.hasPgp()) {
1260 if (conversation.getAccount().getPgpSignature() != null) {
1261 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1262 item.setChecked(true);
1263 } else {
1264 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1265 }
1266 } else {
1267 activity.showInstallPgpDialog();
1268 }
1269 break;
1270 case R.id.encryption_choice_axolotl:
1271 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1272 + "Enabled axolotl for Contact " + conversation.getContact().getJid());
1273 conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1274 item.setChecked(true);
1275 break;
1276 default:
1277 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1278 break;
1279 }
1280 activity.xmppConnectionService.updateConversation(conversation);
1281 updateChatMsgHint();
1282 getActivity().invalidateOptionsMenu();
1283 activity.refreshUi();
1284 }
1285
1286 public void attachFile(final int attachmentChoice) {
1287 if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1288 if (!hasStorageAndCameraPermission(attachmentChoice)) {
1289 return;
1290 }
1291 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1292 if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
1293 return;
1294 }
1295 }
1296 try {
1297 activity.getPreferences().edit()
1298 .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1299 .apply();
1300 } catch (IllegalArgumentException e) {
1301 //just do not save
1302 }
1303 final int encryption = conversation.getNextEncryption();
1304 final int mode = conversation.getMode();
1305 if (encryption == Message.ENCRYPTION_PGP) {
1306 if (activity.hasPgp()) {
1307 if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1308 activity.xmppConnectionService.getPgpEngine().hasKey(
1309 conversation.getContact(),
1310 new UiCallback<Contact>() {
1311
1312 @Override
1313 public void userInputRequried(PendingIntent pi, Contact contact) {
1314 startPendingIntent(pi, attachmentChoice);
1315 }
1316
1317 @Override
1318 public void success(Contact contact) {
1319 selectPresenceToAttachFile(attachmentChoice);
1320 }
1321
1322 @Override
1323 public void error(int error, Contact contact) {
1324 activity.replaceToast(getString(error));
1325 }
1326 });
1327 } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1328 if (!conversation.getMucOptions().everybodyHasKeys()) {
1329 Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1330 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1331 warning.show();
1332 }
1333 selectPresenceToAttachFile(attachmentChoice);
1334 } else {
1335 showNoPGPKeyDialog(false, (dialog, which) -> {
1336 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1337 activity.xmppConnectionService.updateConversation(conversation);
1338 selectPresenceToAttachFile(attachmentChoice);
1339 });
1340 }
1341 } else {
1342 activity.showInstallPgpDialog();
1343 }
1344 } else {
1345 if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
1346 selectPresenceToAttachFile(attachmentChoice);
1347 }
1348 }
1349 }
1350
1351 @Override
1352 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
1353 if (grantResults.length > 0)
1354 if (allGranted(grantResults)) {
1355 if (requestCode == REQUEST_START_DOWNLOAD) {
1356 if (this.mPendingDownloadableMessage != null) {
1357 startDownloadable(this.mPendingDownloadableMessage);
1358 }
1359 } else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
1360 if (this.mPendingEditorContent != null) {
1361 attachImageToConversation(this.mPendingEditorContent);
1362 }
1363 } else {
1364 attachFile(requestCode);
1365 }
1366 } else {
1367 @StringRes int res;
1368 if (Manifest.permission.CAMERA.equals(getFirstDenied(grantResults, permissions))) {
1369 res = R.string.no_camera_permission;
1370 } else {
1371 res = R.string.no_storage_permission;
1372 }
1373 Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1374 }
1375 }
1376
1377 public void startDownloadable(Message message) {
1378 if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(REQUEST_START_DOWNLOAD)) {
1379 this.mPendingDownloadableMessage = message;
1380 return;
1381 }
1382 Transferable transferable = message.getTransferable();
1383 if (transferable != null) {
1384 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1385 activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1386 return;
1387 }
1388 if (!transferable.start()) {
1389 Log.d(Config.LOGTAG,"type: "+transferable.getClass().getName());
1390 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1391 }
1392 } else if (message.treatAsDownloadable()) {
1393 activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1394 }
1395 }
1396
1397 @SuppressLint("InflateParams")
1398 protected void clearHistoryDialog(final Conversation conversation) {
1399 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1400 builder.setTitle(getString(R.string.clear_conversation_history));
1401 final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1402 final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1403 builder.setView(dialogView);
1404 builder.setNegativeButton(getString(R.string.cancel), null);
1405 builder.setPositiveButton(getString(R.string.delete_messages), (dialog, which) -> {
1406 this.activity.xmppConnectionService.clearConversationHistory(conversation);
1407 if (endConversationCheckBox.isChecked()) {
1408 this.activity.xmppConnectionService.archiveConversation(conversation);
1409 this.activity.onConversationArchived(conversation);
1410 } else {
1411 activity.onConversationsListItemUpdated();
1412 refresh();
1413 }
1414 });
1415 builder.create().show();
1416 }
1417
1418 protected void muteConversationDialog(final Conversation conversation) {
1419 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1420 builder.setTitle(R.string.disable_notifications);
1421 final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1422 final CharSequence[] labels = new CharSequence[durations.length];
1423 for (int i = 0; i < durations.length; ++i) {
1424 if (durations[i] == -1) {
1425 labels[i] = getString(R.string.until_further_notice);
1426 } else {
1427 labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
1428 }
1429 }
1430 builder.setItems(labels, (dialog, which) -> {
1431 final long till;
1432 if (durations[which] == -1) {
1433 till = Long.MAX_VALUE;
1434 } else {
1435 till = System.currentTimeMillis() + (durations[which] * 1000);
1436 }
1437 conversation.setMutedTill(till);
1438 activity.xmppConnectionService.updateConversation(conversation);
1439 activity.onConversationsListItemUpdated();
1440 refresh();
1441 getActivity().invalidateOptionsMenu();
1442 });
1443 builder.create().show();
1444 }
1445
1446 private boolean hasStoragePermission(int requestCode) {
1447 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1448 if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1449 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
1450 return false;
1451 } else {
1452 return true;
1453 }
1454 } else {
1455 return true;
1456 }
1457 }
1458
1459 private boolean hasStorageAndCameraPermission(int requestCode) {
1460 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1461 List<String> missingPermissions = new ArrayList<>();
1462 if (!Config.ONLY_INTERNAL_STORAGE && activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1463 missingPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
1464 }
1465 if (activity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
1466 missingPermissions.add(Manifest.permission.CAMERA);
1467 }
1468 if (missingPermissions.size() == 0) {
1469 return true;
1470 } else {
1471 requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1472 return false;
1473 }
1474 } else {
1475 return true;
1476 }
1477 }
1478
1479 public void unmuteConversation(final Conversation conversation) {
1480 conversation.setMutedTill(0);
1481 this.activity.xmppConnectionService.updateConversation(conversation);
1482 this.activity.onConversationsListItemUpdated();
1483 refresh();
1484 getActivity().invalidateOptionsMenu();
1485 }
1486
1487 protected void selectPresenceToAttachFile(final int attachmentChoice) {
1488 final Account account = conversation.getAccount();
1489 final PresenceSelector.OnPresenceSelected callback = () -> {
1490 Intent intent = new Intent();
1491 boolean chooser = false;
1492 String fallbackPackageId = null;
1493 switch (attachmentChoice) {
1494 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1495 intent.setAction(Intent.ACTION_GET_CONTENT);
1496 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1497 intent.setType("image/*");
1498 chooser = true;
1499 break;
1500 case ATTACHMENT_CHOICE_RECORD_VIDEO:
1501 intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1502 break;
1503 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1504 final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1505 pendingTakePhotoUri.push(uri);
1506 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1507 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1508 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1509 intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1510 break;
1511 case ATTACHMENT_CHOICE_CHOOSE_FILE:
1512 chooser = true;
1513 intent.setType("*/*");
1514 intent.addCategory(Intent.CATEGORY_OPENABLE);
1515 intent.setAction(Intent.ACTION_GET_CONTENT);
1516 break;
1517 case ATTACHMENT_CHOICE_RECORD_VOICE:
1518 intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
1519 fallbackPackageId = "eu.siacs.conversations.voicerecorder";
1520 break;
1521 case ATTACHMENT_CHOICE_LOCATION:
1522 intent.setAction("eu.siacs.conversations.location.request");
1523 fallbackPackageId = "eu.siacs.conversations.sharelocation";
1524 break;
1525 }
1526 if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1527 if (chooser) {
1528 startActivityForResult(
1529 Intent.createChooser(intent, getString(R.string.perform_action_with)),
1530 attachmentChoice);
1531 } else {
1532 startActivityForResult(intent, attachmentChoice);
1533 }
1534 } else if (fallbackPackageId != null) {
1535 startActivity(getInstallApkIntent(fallbackPackageId));
1536 }
1537 };
1538 if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1539 conversation.setNextCounterpart(null);
1540 callback.onPresenceSelected();
1541 } else {
1542 activity.selectPresence(conversation, callback);
1543 }
1544 }
1545
1546 private Intent getInstallApkIntent(final String packageId) {
1547 Intent intent = new Intent(Intent.ACTION_VIEW);
1548 intent.setData(Uri.parse("market://details?id=" + packageId));
1549 if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1550 return intent;
1551 } else {
1552 intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
1553 return intent;
1554 }
1555 }
1556
1557 @Override
1558 public void onResume() {
1559 new Handler().post(() -> {
1560 final Activity activity = getActivity();
1561 if (activity == null) {
1562 return;
1563 }
1564 final PackageManager packageManager = activity.getPackageManager();
1565 ConversationMenuConfigurator.updateAttachmentAvailability(packageManager);
1566 getActivity().invalidateOptionsMenu();
1567 });
1568 super.onResume();
1569 binding.messagesView.post(this::fireReadEvent);
1570 }
1571
1572 private void fireReadEvent() {
1573 if (activity != null && this.conversation != null) {
1574 String uuid = getLastVisibleMessageUuid();
1575 if (uuid != null) {
1576 activity.onConversationRead(this.conversation, uuid);
1577 }
1578 }
1579 }
1580
1581 private String getLastVisibleMessageUuid() {
1582 if (binding == null) {
1583 return null;
1584 }
1585 synchronized (this.messageList) {
1586 int pos = binding.messagesView.getLastVisiblePosition();
1587 if (pos >= 0) {
1588 Message message = null;
1589 for (int i = pos; i >= 0; --i) {
1590 try {
1591 message = (Message) binding.messagesView.getItemAtPosition(i);
1592 } catch (IndexOutOfBoundsException e) {
1593 //should not happen if we synchronize properly. however if that fails we just gonna try item -1
1594 continue;
1595 }
1596 if (message.getType() != Message.TYPE_STATUS) {
1597 break;
1598 }
1599 }
1600 if (message != null) {
1601 while (message.next() != null && message.next().wasMergedIntoPrevious()) {
1602 message = message.next();
1603 }
1604 return message.getUuid();
1605 }
1606 }
1607 }
1608 return null;
1609 }
1610
1611 private void showErrorMessage(final Message message) {
1612 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1613 builder.setTitle(R.string.error_message);
1614 builder.setMessage(message.getErrorMessage());
1615 builder.setPositiveButton(R.string.confirm, null);
1616 builder.create().show();
1617 }
1618
1619 private void shareWith(Message message) {
1620 Intent shareIntent = new Intent();
1621 shareIntent.setAction(Intent.ACTION_SEND);
1622 if (message.isGeoUri()) {
1623 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
1624 shareIntent.setType("text/plain");
1625 } else if (!message.isFileOrImage()) {
1626 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
1627 shareIntent.setType("text/plain");
1628 } else {
1629 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1630 try {
1631 shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(getActivity(), file));
1632 } catch (SecurityException e) {
1633 Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
1634 return;
1635 }
1636 shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1637 String mime = message.getMimeType();
1638 if (mime == null) {
1639 mime = "*/*";
1640 }
1641 shareIntent.setType(mime);
1642 }
1643 try {
1644 startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
1645 } catch (ActivityNotFoundException e) {
1646 //This should happen only on faulty androids because normally chooser is always available
1647 Toast.makeText(getActivity(), R.string.no_application_found_to_open_file, Toast.LENGTH_SHORT).show();
1648 }
1649 }
1650
1651 private void copyMessage(Message message) {
1652 if (activity.copyTextToClipboard(message.getMergedBody().toString(), R.string.message)) {
1653 Toast.makeText(getActivity(), R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1654 }
1655 }
1656
1657 private void deleteFile(Message message) {
1658 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1659 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1660 activity.onConversationsListItemUpdated();
1661 refresh();
1662 }
1663 }
1664
1665 private void resendMessage(final Message message) {
1666 if (message.isFileOrImage()) {
1667 DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1668 if (file.exists()) {
1669 final Conversation conversation = message.getConversation();
1670 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1671 if (!message.hasFileOnRemoteHost()
1672 && xmppConnection != null
1673 && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1674 activity.selectPresence(conversation, () -> {
1675 message.setCounterpart(conversation.getNextCounterpart());
1676 activity.xmppConnectionService.resendFailedMessages(message);
1677 new Handler().post(() -> {
1678 int size = messageList.size();
1679 this.binding.messagesView.setSelection(size - 1);
1680 });
1681 });
1682 return;
1683 }
1684 } else {
1685 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1686 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1687 activity.onConversationsListItemUpdated();
1688 refresh();
1689 return;
1690 }
1691 }
1692 activity.xmppConnectionService.resendFailedMessages(message);
1693 new Handler().post(() -> {
1694 int size = messageList.size();
1695 this.binding.messagesView.setSelection(size - 1);
1696 });
1697 }
1698
1699 private void copyUrl(Message message) {
1700 final String url;
1701 final int resId;
1702 if (message.isGeoUri()) {
1703 resId = R.string.location;
1704 url = message.getBody();
1705 } else if (message.hasFileOnRemoteHost()) {
1706 resId = R.string.file_url;
1707 url = message.getFileParams().url.toString();
1708 } else {
1709 url = message.getBody().trim();
1710 resId = R.string.file_url;
1711 }
1712 if (activity.copyTextToClipboard(url, resId)) {
1713 Toast.makeText(getActivity(), R.string.url_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1714 }
1715 }
1716
1717 private void cancelTransmission(Message message) {
1718 Transferable transferable = message.getTransferable();
1719 if (transferable != null) {
1720 transferable.cancel();
1721 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1722 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1723 }
1724 }
1725
1726 private void retryDecryption(Message message) {
1727 message.setEncryption(Message.ENCRYPTION_PGP);
1728 activity.onConversationsListItemUpdated();
1729 refresh();
1730 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1731 }
1732
1733 private void privateMessageWith(final Jid counterpart) {
1734 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1735 activity.xmppConnectionService.sendChatState(conversation);
1736 }
1737 this.binding.textinput.setText("");
1738 this.conversation.setNextCounterpart(counterpart);
1739 updateChatMsgHint();
1740 updateSendButton();
1741 updateEditablity();
1742 }
1743
1744 private void correctMessage(Message message) {
1745 while (message.mergeable(message.next())) {
1746 message = message.next();
1747 }
1748 this.conversation.setCorrectingMessage(message);
1749 final Editable editable = binding.textinput.getText();
1750 this.conversation.setDraftMessage(editable.toString());
1751 this.binding.textinput.setText("");
1752 this.binding.textinput.append(message.getBody());
1753
1754 }
1755
1756 private void highlightInConference(String nick) {
1757 final Editable editable = this.binding.textinput.getText();
1758 String oldString = editable.toString().trim();
1759 final int pos = this.binding.textinput.getSelectionStart();
1760 if (oldString.isEmpty() || pos == 0) {
1761 editable.insert(0, nick + ": ");
1762 } else {
1763 final char before = editable.charAt(pos - 1);
1764 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1765 if (before == '\n') {
1766 editable.insert(pos, nick + ": ");
1767 } else {
1768 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1769 if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1770 editable.insert(pos - 2, ", " + nick);
1771 return;
1772 }
1773 }
1774 editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1775 if (Character.isWhitespace(after)) {
1776 this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1777 }
1778 }
1779 }
1780 }
1781
1782 @Override
1783 public void onSaveInstanceState(Bundle outState) {
1784 super.onSaveInstanceState(outState);
1785 if (conversation != null) {
1786 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1787 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1788 final Uri uri = pendingTakePhotoUri.peek();
1789 if (uri != null) {
1790 outState.putString(STATE_PHOTO_URI, uri.toString());
1791 }
1792 final ScrollState scrollState = getScrollPosition();
1793 if (scrollState != null) {
1794 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1795 }
1796 }
1797 }
1798
1799 @Override
1800 public void onActivityCreated(Bundle savedInstanceState) {
1801 super.onActivityCreated(savedInstanceState);
1802 if (savedInstanceState == null) {
1803 return;
1804 }
1805 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1806 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1807 if (uuid != null) {
1808 this.pendingConversationsUuid.push(uuid);
1809 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1810 if (takePhotoUri != null) {
1811 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1812 }
1813 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1814 }
1815 }
1816
1817 @Override
1818 public void onStart() {
1819 super.onStart();
1820 if (this.reInitRequiredOnStart && this.conversation != null) {
1821 final Bundle extras = pendingExtras.pop();
1822 reInit(this.conversation, extras != null);
1823 if (extras != null) {
1824 processExtras(extras);
1825 }
1826 } else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1827 final String uuid = pendingConversationsUuid.pop();
1828 Log.d(Config.LOGTAG,"ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="+uuid);
1829 if (uuid != null) {
1830 findAndReInitByUuidOrArchive(uuid);
1831 }
1832 }
1833 }
1834
1835 @Override
1836 public void onStop() {
1837 super.onStop();
1838 final Activity activity = getActivity();
1839 if (activity == null || !activity.isChangingConfigurations()) {
1840 hideSoftKeyboard(activity);
1841 messageListAdapter.stopAudioPlayer();
1842 }
1843 if (this.conversation != null) {
1844 final String msg = this.binding.textinput.getText().toString();
1845 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && this.conversation.setNextMessage(msg)) {
1846 this.activity.xmppConnectionService.updateConversation(this.conversation);
1847 }
1848 updateChatState(this.conversation, msg);
1849 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1850 }
1851 this.reInitRequiredOnStart = true;
1852 }
1853
1854 private void updateChatState(final Conversation conversation, final String msg) {
1855 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1856 Account.State status = conversation.getAccount().getStatus();
1857 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1858 activity.xmppConnectionService.sendChatState(conversation);
1859 }
1860 }
1861
1862 private void saveMessageDraftStopAudioPlayer() {
1863 final Conversation previousConversation = this.conversation;
1864 if (this.activity == null || this.binding == null || previousConversation == null) {
1865 return;
1866 }
1867 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1868 final String msg = this.binding.textinput.getText().toString();
1869 if (previousConversation.setNextMessage(msg)) {
1870 activity.xmppConnectionService.updateConversation(previousConversation);
1871 }
1872 updateChatState(this.conversation, msg);
1873 messageListAdapter.stopAudioPlayer();
1874 }
1875
1876 public void reInit(Conversation conversation, Bundle extras) {
1877 this.saveMessageDraftStopAudioPlayer();
1878 if (this.reInit(conversation, extras != null)) {
1879 if (extras != null) {
1880 processExtras(extras);
1881 }
1882 this.reInitRequiredOnStart = false;
1883 } else {
1884 this.reInitRequiredOnStart = true;
1885 pendingExtras.push(extras);
1886 }
1887 resetUnreadMessagesCount();
1888 }
1889
1890 private void reInit(Conversation conversation) {
1891 reInit(conversation, false);
1892 }
1893
1894 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1895 if (conversation == null) {
1896 return false;
1897 }
1898 this.conversation = conversation;
1899 //once we set the conversation all is good and it will automatically do the right thing in onStart()
1900 if (this.activity == null || this.binding == null) {
1901 return false;
1902 }
1903
1904 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1905 activity.onConversationArchived(this.conversation);
1906 return false;
1907 }
1908
1909 stopScrolling();
1910 Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1911
1912 if (this.conversation.isRead() && hasExtras) {
1913 Log.d(Config.LOGTAG, "trimming conversation");
1914 this.conversation.trim();
1915 }
1916
1917 setupIme();
1918
1919 final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1920
1921 this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1922 this.binding.textinput.setKeyboardListener(null);
1923 this.binding.textinput.setText("");
1924 this.binding.textinput.append(this.conversation.getNextMessage());
1925 this.binding.textinput.setKeyboardListener(this);
1926 messageListAdapter.updatePreferences();
1927 refresh(false);
1928 this.conversation.messagesLoaded.set(true);
1929 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1930
1931 if (hasExtras || scrolledToBottomAndNoPending) {
1932 resetUnreadMessagesCount();
1933 synchronized (this.messageList) {
1934 Log.d(Config.LOGTAG, "jump to first unread message");
1935 final Message first = conversation.getFirstUnreadMessage();
1936 final int bottom = Math.max(0, this.messageList.size() - 1);
1937 final int pos;
1938 if (first == null) {
1939 pos = bottom;
1940 } else {
1941 int i = getIndexOf(first.getUuid(), this.messageList);
1942 pos = i < 0 ? bottom : i;
1943 }
1944 setSelection(pos);
1945 }
1946 }
1947
1948
1949 this.binding.messagesView.post(this::fireReadEvent);
1950 //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
1951 activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1952 return true;
1953 }
1954
1955 private void resetUnreadMessagesCount() {
1956 lastMessageUuid = null;
1957 hideUnreadMessagesCount();
1958 }
1959
1960 private void hideUnreadMessagesCount() {
1961 if (this.binding == null) {
1962 return;
1963 }
1964 this.binding.scrollToBottomButton.setEnabled(false);
1965 this.binding.scrollToBottomButton.setVisibility(View.GONE);
1966 this.binding.unreadCountCustomView.setVisibility(View.GONE);
1967 }
1968
1969 private void setSelection(int pos) {
1970 this.binding.messagesView.setSelection(pos);
1971 this.binding.messagesView.post(() -> this.binding.messagesView.setSelection(pos));
1972 this.binding.messagesView.post(this::fireReadEvent);
1973 }
1974
1975 private boolean scrolledToBottom() {
1976 if (this.binding == null) {
1977 return false;
1978 }
1979 return scrolledToBottom(this.binding.messagesView);
1980 }
1981
1982 private void processExtras(Bundle extras) {
1983 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
1984 final String text = extras.getString(ConversationsActivity.EXTRA_TEXT);
1985 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
1986 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1987 if (nick != null) {
1988 if (pm) {
1989 Jid jid = conversation.getJid();
1990 try {
1991 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
1992 privateMessageWith(next);
1993 } catch (final IllegalArgumentException ignored) {
1994 //do nothing
1995 }
1996 } else {
1997 final MucOptions mucOptions = conversation.getMucOptions();
1998 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
1999 highlightInConference(nick);
2000 }
2001 }
2002 } else {
2003 appendText(text);
2004 }
2005 final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2006 if (message != null) {
2007 startDownloadable(message);
2008 }
2009 }
2010
2011 private boolean showBlockSubmenu(View view) {
2012 final Jid jid = conversation.getJid();
2013 if (jid.getLocal() == null) {
2014 BlockContactDialog.show(activity, conversation);
2015 } else {
2016 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2017 popupMenu.inflate(R.menu.block);
2018 popupMenu.setOnMenuItemClickListener(menuItem -> {
2019 Blockable blockable;
2020 switch (menuItem.getItemId()) {
2021 case R.id.block_domain:
2022 blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
2023 break;
2024 default:
2025 blockable = conversation;
2026 }
2027 BlockContactDialog.show(activity, blockable);
2028 return true;
2029 });
2030 popupMenu.show();
2031 }
2032 return true;
2033 }
2034
2035 private void updateSnackBar(final Conversation conversation) {
2036 final Account account = conversation.getAccount();
2037 final XmppConnection connection = account.getXmppConnection();
2038 final int mode = conversation.getMode();
2039 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2040 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2041 return;
2042 }
2043 if (account.getStatus() == Account.State.DISABLED) {
2044 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
2045 } else if (conversation.isBlocked()) {
2046 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2047 } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2048 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
2049 } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2050 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
2051 } else if (mode == Conversation.MODE_MULTI
2052 && !conversation.getMucOptions().online()
2053 && account.getStatus() == Account.State.ONLINE) {
2054 switch (conversation.getMucOptions().getError()) {
2055 case NICK_IN_USE:
2056 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2057 break;
2058 case NO_RESPONSE:
2059 showSnackbar(R.string.joining_conference, 0, null);
2060 break;
2061 case SERVER_NOT_FOUND:
2062 if (conversation.receivedMessagesCount() > 0) {
2063 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2064 } else {
2065 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2066 }
2067 break;
2068 case PASSWORD_REQUIRED:
2069 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2070 break;
2071 case BANNED:
2072 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2073 break;
2074 case MEMBERS_ONLY:
2075 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2076 break;
2077 case KICKED:
2078 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2079 break;
2080 case UNKNOWN:
2081 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2082 break;
2083 case INVALID_NICK:
2084 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2085 case SHUTDOWN:
2086 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2087 break;
2088 default:
2089 hideSnackbar();
2090 break;
2091 }
2092 } else if (account.hasPendingPgpIntent(conversation)) {
2093 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2094 } else if (connection != null
2095 && connection.getFeatures().blocking()
2096 && conversation.countMessages() != 0
2097 && !conversation.isBlocked()
2098 && conversation.isWithStranger()) {
2099 showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2100 } else {
2101 hideSnackbar();
2102 }
2103 }
2104
2105 @Override
2106 public void refresh() {
2107 if (this.binding == null) {
2108 Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2109 return;
2110 }
2111 if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2112 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2113 activity.onConversationArchived(this.conversation);
2114 return;
2115 }
2116 }
2117 this.refresh(true);
2118 }
2119
2120 private void refresh(boolean notifyConversationRead) {
2121 synchronized (this.messageList) {
2122 if (this.conversation != null) {
2123 conversation.populateWithMessages(this.messageList);
2124 updateSnackBar(conversation);
2125 updateStatusMessages();
2126 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2127 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2128 binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2129 }
2130 this.messageListAdapter.notifyDataSetChanged();
2131 updateChatMsgHint();
2132 if (notifyConversationRead && activity != null) {
2133 binding.messagesView.post(this::fireReadEvent);
2134 }
2135 updateSendButton();
2136 updateEditablity();
2137 }
2138 }
2139 }
2140
2141 protected void messageSent() {
2142 mSendingPgpMessage.set(false);
2143 this.binding.textinput.setText("");
2144 if (conversation.setCorrectingMessage(null)) {
2145 this.binding.textinput.append(conversation.getDraftMessage());
2146 conversation.setDraftMessage(null);
2147 }
2148 if (conversation.setNextMessage(this.binding.textinput.getText().toString())) {
2149 activity.xmppConnectionService.updateConversation(conversation);
2150 }
2151 updateChatMsgHint();
2152 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2153 final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2154 if (prefScrollToBottom || scrolledToBottom()) {
2155 new Handler().post(() -> {
2156 int size = messageList.size();
2157 this.binding.messagesView.setSelection(size - 1);
2158 });
2159 }
2160 }
2161
2162 public void doneSendingPgpMessage() {
2163 mSendingPgpMessage.set(false);
2164 }
2165
2166 public long getMaxHttpUploadSize(Conversation conversation) {
2167 final XmppConnection connection = conversation.getAccount().getXmppConnection();
2168 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2169 }
2170
2171 private void updateEditablity() {
2172 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2173 this.binding.textinput.setFocusable(canWrite);
2174 this.binding.textinput.setFocusableInTouchMode(canWrite);
2175 this.binding.textSendButton.setEnabled(canWrite);
2176 this.binding.textinput.setCursorVisible(canWrite);
2177 }
2178
2179 public void updateSendButton() {
2180 boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2181 final Conversation c = this.conversation;
2182 final Presence.Status status;
2183 final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2184 final SendButtonAction action = SendButtonTool.getAction(getActivity(), c, text);
2185 if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2186 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2187 status = Presence.Status.OFFLINE;
2188 } else if (c.getMode() == Conversation.MODE_SINGLE) {
2189 status = c.getContact().getShownStatus();
2190 } else {
2191 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2192 }
2193 } else {
2194 status = Presence.Status.OFFLINE;
2195 }
2196 this.binding.textSendButton.setTag(action);
2197 this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2198 }
2199
2200 protected void updateDateSeparators() {
2201 synchronized (this.messageList) {
2202 for (int i = 0; i < this.messageList.size(); ++i) {
2203 final Message current = this.messageList.get(i);
2204 if (i == 0 || !UIHelper.sameDay(this.messageList.get(i - 1).getTimeSent(), current.getTimeSent())) {
2205 this.messageList.add(i, Message.createDateSeparator(current));
2206 i++;
2207 }
2208 }
2209 }
2210 }
2211
2212 protected void updateStatusMessages() {
2213 updateDateSeparators();
2214 synchronized (this.messageList) {
2215 if (showLoadMoreMessages(conversation)) {
2216 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2217 }
2218 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2219 ChatState state = conversation.getIncomingChatState();
2220 if (state == ChatState.COMPOSING) {
2221 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2222 } else if (state == ChatState.PAUSED) {
2223 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2224 } else {
2225 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2226 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
2227 return;
2228 } else {
2229 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
2230 this.messageList.add(i + 1,
2231 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2232 return;
2233 }
2234 }
2235 }
2236 }
2237 } else {
2238 final MucOptions mucOptions = conversation.getMucOptions();
2239 final List<MucOptions.User> allUsers = mucOptions.getUsers();
2240 final Set<ReadByMarker> addedMarkers = new HashSet<>();
2241 ChatState state = ChatState.COMPOSING;
2242 List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2243 if (users.size() == 0) {
2244 state = ChatState.PAUSED;
2245 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2246 }
2247 if (mucOptions.isPrivateAndNonAnonymous()) {
2248 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2249 final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2250 final List<MucOptions.User> shownMarkers = new ArrayList<>();
2251 for (ReadByMarker marker : markersForMessage) {
2252 if (!ReadByMarker.contains(marker, addedMarkers)) {
2253 addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2254 MucOptions.User user = mucOptions.findUser(marker);
2255 if (user != null && !users.contains(user)) {
2256 shownMarkers.add(user);
2257 }
2258 }
2259 }
2260 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2261 final Message statusMessage;
2262 final int size = shownMarkers.size();
2263 if (size > 1) {
2264 final String body;
2265 if (size <= 4) {
2266 body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2267 } else {
2268 body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2269 }
2270 statusMessage = Message.createStatusMessage(conversation, body);
2271 statusMessage.setCounterparts(shownMarkers);
2272 } else if (size == 1) {
2273 statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2274 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2275 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2276 } else {
2277 statusMessage = null;
2278 }
2279 if (statusMessage != null) {
2280 this.messageList.add(i + 1, statusMessage);
2281 }
2282 addedMarkers.add(markerForSender);
2283 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2284 break;
2285 }
2286 }
2287 }
2288 if (users.size() > 0) {
2289 Message statusMessage;
2290 if (users.size() == 1) {
2291 MucOptions.User user = users.get(0);
2292 int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2293 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2294 statusMessage.setTrueCounterpart(user.getRealJid());
2295 statusMessage.setCounterpart(user.getFullJid());
2296 } else {
2297 int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2298 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2299 statusMessage.setCounterparts(users);
2300 }
2301 this.messageList.add(statusMessage);
2302 }
2303
2304 }
2305 }
2306 }
2307
2308 private void stopScrolling() {
2309 long now = SystemClock.uptimeMillis();
2310 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2311 binding.messagesView.dispatchTouchEvent(cancel);
2312 }
2313
2314 private boolean showLoadMoreMessages(final Conversation c) {
2315 if (activity == null || activity.xmppConnectionService == null) {
2316 return false;
2317 }
2318 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2319 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2320 return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2321 }
2322
2323 private boolean hasMamSupport(final Conversation c) {
2324 if (c.getMode() == Conversation.MODE_SINGLE) {
2325 final XmppConnection connection = c.getAccount().getXmppConnection();
2326 return connection != null && connection.getFeatures().mam();
2327 } else {
2328 return c.getMucOptions().mamSupport();
2329 }
2330 }
2331
2332 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2333 showSnackbar(message, action, clickListener, null);
2334 }
2335
2336 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2337 this.binding.snackbar.setVisibility(View.VISIBLE);
2338 this.binding.snackbar.setOnClickListener(null);
2339 this.binding.snackbarMessage.setText(message);
2340 this.binding.snackbarMessage.setOnClickListener(null);
2341 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2342 if (action != 0) {
2343 this.binding.snackbarAction.setText(action);
2344 }
2345 this.binding.snackbarAction.setOnClickListener(clickListener);
2346 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2347 }
2348
2349 protected void hideSnackbar() {
2350 this.binding.snackbar.setVisibility(View.GONE);
2351 }
2352
2353 protected void sendMessage(Message message) {
2354 activity.xmppConnectionService.sendMessage(message);
2355 messageSent();
2356 }
2357
2358 protected void sendPgpMessage(final Message message) {
2359 final XmppConnectionService xmppService = activity.xmppConnectionService;
2360 final Contact contact = message.getConversation().getContact();
2361 if (!activity.hasPgp()) {
2362 activity.showInstallPgpDialog();
2363 return;
2364 }
2365 if (conversation.getAccount().getPgpSignature() == null) {
2366 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2367 return;
2368 }
2369 if (!mSendingPgpMessage.compareAndSet(false, true)) {
2370 Log.d(Config.LOGTAG, "sending pgp message already in progress");
2371 }
2372 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2373 if (contact.getPgpKeyId() != 0) {
2374 xmppService.getPgpEngine().hasKey(contact,
2375 new UiCallback<Contact>() {
2376
2377 @Override
2378 public void userInputRequried(PendingIntent pi, Contact contact) {
2379 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2380 }
2381
2382 @Override
2383 public void success(Contact contact) {
2384 encryptTextMessage(message);
2385 }
2386
2387 @Override
2388 public void error(int error, Contact contact) {
2389 activity.runOnUiThread(() -> Toast.makeText(activity,
2390 R.string.unable_to_connect_to_keychain,
2391 Toast.LENGTH_SHORT
2392 ).show());
2393 mSendingPgpMessage.set(false);
2394 }
2395 });
2396
2397 } else {
2398 showNoPGPKeyDialog(false, (dialog, which) -> {
2399 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2400 xmppService.updateConversation(conversation);
2401 message.setEncryption(Message.ENCRYPTION_NONE);
2402 xmppService.sendMessage(message);
2403 messageSent();
2404 });
2405 }
2406 } else {
2407 if (conversation.getMucOptions().pgpKeysInUse()) {
2408 if (!conversation.getMucOptions().everybodyHasKeys()) {
2409 Toast warning = Toast
2410 .makeText(getActivity(),
2411 R.string.missing_public_keys,
2412 Toast.LENGTH_LONG);
2413 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2414 warning.show();
2415 }
2416 encryptTextMessage(message);
2417 } else {
2418 showNoPGPKeyDialog(true, (dialog, which) -> {
2419 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2420 message.setEncryption(Message.ENCRYPTION_NONE);
2421 xmppService.updateConversation(conversation);
2422 xmppService.sendMessage(message);
2423 messageSent();
2424 });
2425 }
2426 }
2427 }
2428
2429 public void encryptTextMessage(Message message) {
2430 activity.xmppConnectionService.getPgpEngine().encrypt(message,
2431 new UiCallback<Message>() {
2432
2433 @Override
2434 public void userInputRequried(PendingIntent pi, Message message) {
2435 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2436 }
2437
2438 @Override
2439 public void success(Message message) {
2440 //TODO the following two call can be made before the callback
2441 getActivity().runOnUiThread(() -> messageSent());
2442 }
2443
2444 @Override
2445 public void error(final int error, Message message) {
2446 getActivity().runOnUiThread(() -> {
2447 doneSendingPgpMessage();
2448 Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2449 });
2450
2451 }
2452 });
2453 }
2454
2455 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2456 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2457 builder.setIconAttribute(android.R.attr.alertDialogIcon);
2458 if (plural) {
2459 builder.setTitle(getString(R.string.no_pgp_keys));
2460 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2461 } else {
2462 builder.setTitle(getString(R.string.no_pgp_key));
2463 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2464 }
2465 builder.setNegativeButton(getString(R.string.cancel), null);
2466 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2467 builder.create().show();
2468 }
2469
2470 public void appendText(String text) {
2471 if (text == null) {
2472 return;
2473 }
2474 String previous = this.binding.textinput.getText().toString();
2475 if (previous.length() != 0 && !previous.endsWith(" ")) {
2476 text = " " + text;
2477 }
2478 this.binding.textinput.append(text);
2479 }
2480
2481 @Override
2482 public boolean onEnterPressed() {
2483 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2484 final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2485 if (enterIsSend) {
2486 sendMessage();
2487 return true;
2488 } else {
2489 return false;
2490 }
2491 }
2492
2493 @Override
2494 public void onTypingStarted() {
2495 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2496 if (service == null) {
2497 return;
2498 }
2499 Account.State status = conversation.getAccount().getStatus();
2500 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2501 service.sendChatState(conversation);
2502 }
2503 updateSendButton();
2504 }
2505
2506 @Override
2507 public void onTypingStopped() {
2508 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2509 if (service == null) {
2510 return;
2511 }
2512 Account.State status = conversation.getAccount().getStatus();
2513 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2514 service.sendChatState(conversation);
2515 }
2516 }
2517
2518 @Override
2519 public void onTextDeleted() {
2520 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2521 if (service == null) {
2522 return;
2523 }
2524 Account.State status = conversation.getAccount().getStatus();
2525 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2526 service.sendChatState(conversation);
2527 }
2528 updateSendButton();
2529 }
2530
2531 @Override
2532 public void onTextChanged() {
2533 if (conversation != null && conversation.getCorrectingMessage() != null) {
2534 updateSendButton();
2535 }
2536 }
2537
2538 @Override
2539 public boolean onTabPressed(boolean repeated) {
2540 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2541 return false;
2542 }
2543 if (repeated) {
2544 completionIndex++;
2545 } else {
2546 lastCompletionLength = 0;
2547 completionIndex = 0;
2548 final String content = this.binding.textinput.getText().toString();
2549 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2550 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2551 firstWord = start == 0;
2552 incomplete = content.substring(start, lastCompletionCursor);
2553 }
2554 List<String> completions = new ArrayList<>();
2555 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2556 String name = user.getName();
2557 if (name != null && name.startsWith(incomplete)) {
2558 completions.add(name + (firstWord ? ": " : " "));
2559 }
2560 }
2561 Collections.sort(completions);
2562 if (completions.size() > completionIndex) {
2563 String completion = completions.get(completionIndex).substring(incomplete.length());
2564 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2565 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2566 lastCompletionLength = completion.length();
2567 } else {
2568 completionIndex = -1;
2569 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2570 lastCompletionLength = 0;
2571 }
2572 return true;
2573 }
2574
2575 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2576 try {
2577 getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2578 } catch (final SendIntentException ignored) {
2579 }
2580 }
2581
2582 @Override
2583 public void onBackendConnected() {
2584 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2585 String uuid = pendingConversationsUuid.pop();
2586 if (uuid != null) {
2587 if (!findAndReInitByUuidOrArchive(uuid)) {
2588 return;
2589 }
2590 } else {
2591 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2592 clearPending();
2593 activity.onConversationArchived(conversation);
2594 return;
2595 }
2596 }
2597 ActivityResult activityResult = postponedActivityResult.pop();
2598 if (activityResult != null) {
2599 handleActivityResult(activityResult);
2600 }
2601 clearPending();
2602 }
2603
2604 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2605 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2606 if (conversation == null) {
2607 clearPending();
2608 activity.onConversationArchived(null);
2609 return false;
2610 }
2611 reInit(conversation);
2612 ScrollState scrollState = pendingScrollState.pop();
2613 String lastMessageUuid = pendingLastMessageUuid.pop();
2614 if (scrollState != null) {
2615 setScrollPosition(scrollState, lastMessageUuid);
2616 }
2617 return true;
2618 }
2619
2620 private void clearPending() {
2621 if (postponedActivityResult.pop() != null) {
2622 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2623 }
2624 pendingScrollState.pop();
2625 if (pendingTakePhotoUri.pop() != null) {
2626 Log.e(Config.LOGTAG, "cleared pending photo uri");
2627 }
2628 }
2629
2630 public Conversation getConversation() {
2631 return conversation;
2632 }
2633}