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