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