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