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