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