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