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