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