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