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