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