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