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