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