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