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.audioGranted;
8import static eu.siacs.conversations.utils.PermissionUtils.cameraGranted;
9import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
10import static eu.siacs.conversations.utils.PermissionUtils.writeGranted;
11
12import android.Manifest;
13import android.annotation.SuppressLint;
14import android.app.Activity;
15import android.app.DatePickerDialog;
16import android.app.Fragment;
17import android.app.FragmentManager;
18import android.app.PendingIntent;
19import android.app.TimePickerDialog;
20import android.content.ActivityNotFoundException;
21import android.content.Context;
22import android.content.DialogInterface;
23import android.content.Intent;
24import android.content.IntentSender.SendIntentException;
25import android.content.SharedPreferences;
26import android.content.pm.PackageManager;
27import android.content.res.ColorStateList;
28import android.graphics.Color;
29import android.icu.util.Calendar;
30import android.icu.util.TimeZone;
31import android.net.Uri;
32import android.os.Build;
33import android.os.Bundle;
34import android.os.Environment;
35import android.os.Handler;
36import android.os.Looper;
37import android.os.storage.StorageManager;
38import android.os.SystemClock;
39import android.preference.PreferenceManager;
40import android.provider.MediaStore;
41import android.text.Editable;
42import android.text.SpannableStringBuilder;
43import android.text.TextUtils;
44import android.text.TextWatcher;
45import android.text.style.ImageSpan;
46import android.util.DisplayMetrics;
47import android.util.Log;
48import android.view.ContextMenu;
49import android.view.ContextMenu.ContextMenuInfo;
50import android.view.Gravity;
51import android.view.LayoutInflater;
52import android.view.Menu;
53import android.view.MenuInflater;
54import android.view.MenuItem;
55import android.view.MotionEvent;
56import android.view.View;
57import android.view.View.OnClickListener;
58import android.view.ViewGroup;
59import android.view.inputmethod.EditorInfo;
60import android.view.inputmethod.InputMethodManager;
61import android.view.WindowManager;
62import android.widget.AbsListView;
63import android.widget.AbsListView.OnScrollListener;
64import android.widget.AdapterView;
65import android.widget.AdapterView.AdapterContextMenuInfo;
66import android.widget.CheckBox;
67import android.widget.ListView;
68import android.widget.PopupMenu;
69import android.widget.PopupWindow;
70import android.widget.TextView.OnEditorActionListener;
71import android.widget.Toast;
72
73import androidx.activity.OnBackPressedCallback;
74import androidx.annotation.IdRes;
75import androidx.annotation.NonNull;
76import androidx.annotation.Nullable;
77import androidx.annotation.StringRes;
78import androidx.appcompat.app.AlertDialog;
79import androidx.core.content.pm.ShortcutInfoCompat;
80import androidx.core.content.pm.ShortcutManagerCompat;
81import androidx.core.graphics.ColorUtils;
82import androidx.core.view.inputmethod.InputConnectionCompat;
83import androidx.core.view.inputmethod.InputContentInfoCompat;
84import androidx.databinding.DataBindingUtil;
85import androidx.documentfile.provider.DocumentFile;
86import androidx.recyclerview.widget.RecyclerView.Adapter;
87import androidx.viewpager.widget.PagerAdapter;
88import androidx.viewpager.widget.ViewPager;
89
90import com.cheogram.android.BobTransfer;
91import com.cheogram.android.EmojiSearch;
92import com.cheogram.android.EditMessageSelectionActionModeCallback;
93import com.cheogram.android.WebxdcPage;
94import com.cheogram.android.WebxdcStore;
95
96import com.google.android.material.color.MaterialColors;
97import com.google.android.material.dialog.MaterialAlertDialogBuilder;
98import com.google.common.base.Optional;
99import com.google.common.collect.Collections2;
100import com.google.common.collect.ImmutableList;
101import com.google.common.collect.ImmutableSet;
102import com.google.common.collect.Lists;
103import com.google.common.collect.Ordering;
104import com.google.common.io.Files;
105
106import com.otaliastudios.autocomplete.Autocomplete;
107import com.otaliastudios.autocomplete.AutocompleteCallback;
108import com.otaliastudios.autocomplete.AutocompletePresenter;
109import com.otaliastudios.autocomplete.CharPolicy;
110import com.otaliastudios.autocomplete.RecyclerViewPresenter;
111
112import org.jetbrains.annotations.NotNull;
113
114import io.ipfs.cid.Cid;
115
116import java.io.File;
117import java.net.URISyntaxException;
118import java.util.AbstractMap;
119import java.util.ArrayList;
120import java.util.Arrays;
121import java.util.Collection;
122import java.util.Collections;
123import java.util.HashSet;
124import java.util.Iterator;
125import java.util.List;
126import java.util.Locale;
127import java.util.Map;
128import java.util.Set;
129import java.util.UUID;
130import java.util.concurrent.atomic.AtomicBoolean;
131import java.util.regex.Matcher;
132import java.util.regex.Pattern;
133import java.util.stream.Collectors;
134
135import eu.siacs.conversations.Config;
136import eu.siacs.conversations.R;
137import eu.siacs.conversations.crypto.axolotl.AxolotlService;
138import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
139import eu.siacs.conversations.databinding.FragmentConversationBinding;
140import eu.siacs.conversations.entities.Account;
141import eu.siacs.conversations.entities.Blockable;
142import eu.siacs.conversations.entities.Contact;
143import eu.siacs.conversations.entities.Conversation;
144import eu.siacs.conversations.entities.Conversational;
145import eu.siacs.conversations.entities.DownloadableFile;
146import eu.siacs.conversations.entities.Message;
147import eu.siacs.conversations.entities.MucOptions;
148import eu.siacs.conversations.entities.MucOptions.User;
149import eu.siacs.conversations.entities.Presence;
150import eu.siacs.conversations.entities.Presences;
151import eu.siacs.conversations.entities.ReadByMarker;
152import eu.siacs.conversations.entities.Transferable;
153import eu.siacs.conversations.entities.TransferablePlaceholder;
154import eu.siacs.conversations.http.HttpDownloadConnection;
155import eu.siacs.conversations.persistance.FileBackend;
156import eu.siacs.conversations.services.CallIntegrationConnectionService;
157import eu.siacs.conversations.services.MessageArchiveService;
158import eu.siacs.conversations.services.QuickConversationsService;
159import eu.siacs.conversations.services.XmppConnectionService;
160import eu.siacs.conversations.ui.adapter.CommandAdapter;
161import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
162import eu.siacs.conversations.ui.adapter.MessageAdapter;
163import eu.siacs.conversations.ui.adapter.UserAdapter;
164import eu.siacs.conversations.ui.util.ActivityResult;
165import eu.siacs.conversations.ui.util.Attachment;
166import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
167import eu.siacs.conversations.ui.util.DateSeparator;
168import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
169import eu.siacs.conversations.ui.util.ListViewUtils;
170import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
171import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
172import eu.siacs.conversations.ui.util.PendingItem;
173import eu.siacs.conversations.ui.util.PresenceSelector;
174import eu.siacs.conversations.ui.util.ScrollState;
175import eu.siacs.conversations.ui.util.SendButtonAction;
176import eu.siacs.conversations.ui.util.SendButtonTool;
177import eu.siacs.conversations.ui.util.ShareUtil;
178import eu.siacs.conversations.ui.util.ViewUtil;
179import eu.siacs.conversations.ui.widget.EditMessage;
180import eu.siacs.conversations.utils.AccountUtils;
181import eu.siacs.conversations.utils.Compatibility;
182import eu.siacs.conversations.utils.Emoticons;
183import eu.siacs.conversations.utils.GeoHelper;
184import eu.siacs.conversations.utils.MessageUtils;
185import eu.siacs.conversations.utils.MimeUtils;
186import eu.siacs.conversations.utils.NickValidityChecker;
187import eu.siacs.conversations.utils.PermissionUtils;
188import eu.siacs.conversations.utils.QuickLoader;
189import eu.siacs.conversations.utils.StylingHelper;
190import eu.siacs.conversations.utils.TimeFrameUtils;
191import eu.siacs.conversations.utils.UIHelper;
192import eu.siacs.conversations.xml.Element;
193import eu.siacs.conversations.xml.Namespace;
194import eu.siacs.conversations.xmpp.Jid;
195import eu.siacs.conversations.xmpp.XmppConnection;
196import eu.siacs.conversations.xmpp.chatstate.ChatState;
197import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
198import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
199import eu.siacs.conversations.xmpp.jingle.JingleFileTransferConnection;
200import eu.siacs.conversations.xmpp.jingle.Media;
201import eu.siacs.conversations.xmpp.jingle.OngoingRtpSession;
202import eu.siacs.conversations.xmpp.jingle.RtpCapability;
203
204import im.conversations.android.xmpp.model.stanza.Iq;
205
206import org.jetbrains.annotations.NotNull;
207
208import java.util.ArrayList;
209import java.util.Arrays;
210import java.util.Collection;
211import java.util.Collections;
212import java.util.HashSet;
213import java.util.Iterator;
214import java.util.List;
215import java.util.Set;
216import java.util.UUID;
217import java.util.concurrent.atomic.AtomicBoolean;
218import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
219
220public class ConversationFragment extends XmppFragment
221 implements EditMessage.KeyboardListener,
222 MessageAdapter.OnContactPictureLongClicked,
223 MessageAdapter.OnContactPictureClicked,
224 MessageAdapter.OnInlineImageLongClicked {
225
226 public static final int REQUEST_SEND_MESSAGE = 0x0201;
227 public static final int REQUEST_DECRYPT_PGP = 0x0202;
228 public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
229 public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
230 public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209;
231 public static final int REQUEST_START_DOWNLOAD = 0x0210;
232 public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
233 public static final int REQUEST_COMMIT_ATTACHMENTS = 0x0212;
234 public static final int REQUEST_START_AUDIO_CALL = 0x213;
235 public static final int REQUEST_START_VIDEO_CALL = 0x214;
236 public static final int REQUEST_SAVE_STICKER = 0x215;
237 public static final int REQUEST_WEBXDC_STORE = 0x216;
238 public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
239 public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
240 public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
241 public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
242 public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
243 public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
244 public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
245
246 public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
247 public static final String STATE_CONVERSATION_UUID =
248 ConversationFragment.class.getName() + ".uuid";
249 public static final String STATE_SCROLL_POSITION =
250 ConversationFragment.class.getName() + ".scroll_position";
251 public static final String STATE_PHOTO_URI =
252 ConversationFragment.class.getName() + ".media_previews";
253 public static final String STATE_MEDIA_PREVIEWS =
254 ConversationFragment.class.getName() + ".take_photo_uri";
255 private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid";
256
257 private final List<Message> messageList = new ArrayList<>();
258 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
259 private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
260 private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>();
261 private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
262 private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
263 private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
264 private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>();
265 private final PendingItem<Message> pendingMessage = new PendingItem<>();
266 public Uri mPendingEditorContent = null;
267 protected ArrayList<WebxdcPage> extensions = new ArrayList<>();
268 protected MessageAdapter messageListAdapter;
269 protected CommandAdapter commandAdapter;
270 private MediaPreviewAdapter mediaPreviewAdapter;
271 private String lastMessageUuid = null;
272 private Conversation conversation;
273 private FragmentConversationBinding binding;
274 private Toast messageLoaderToast;
275 private ConversationsActivity activity;
276 private boolean reInitRequiredOnStart = true;
277 private int identiconWidth = -1;
278 private File savingAsSticker = null;
279 private EmojiSearch emojiSearch = null;
280 private final OnClickListener clickToMuc =
281 new OnClickListener() {
282
283 @Override
284 public void onClick(View v) {
285 ConferenceDetailsActivity.open(getActivity(), conversation);
286 }
287 };
288 private final OnClickListener leaveMuc =
289 new OnClickListener() {
290
291 @Override
292 public void onClick(View v) {
293 activity.xmppConnectionService.archiveConversation(conversation);
294 }
295 };
296 private final OnClickListener joinMuc =
297 new OnClickListener() {
298
299 @Override
300 public void onClick(View v) {
301 activity.xmppConnectionService.joinMuc(conversation);
302 }
303 };
304
305 private final OnClickListener acceptJoin =
306 new OnClickListener() {
307 @Override
308 public void onClick(View v) {
309 conversation.setAttribute("accept_non_anonymous", true);
310 activity.xmppConnectionService.updateConversation(conversation);
311 activity.xmppConnectionService.joinMuc(conversation);
312 }
313 };
314
315 private final OnClickListener enterPassword =
316 new OnClickListener() {
317
318 @Override
319 public void onClick(View v) {
320 MucOptions muc = conversation.getMucOptions();
321 String password = muc.getPassword();
322 if (password == null) {
323 password = "";
324 }
325 activity.quickPasswordEdit(
326 password,
327 value -> {
328 activity.xmppConnectionService.providePasswordForMuc(
329 conversation, value);
330 return null;
331 });
332 }
333 };
334 private final OnScrollListener mOnScrollListener =
335 new OnScrollListener() {
336
337 @Override
338 public void onScrollStateChanged(AbsListView view, int scrollState) {
339 if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
340 updateThreadFromLastMessage();
341 fireReadEvent();
342 }
343 }
344
345 @Override
346 public void onScroll(
347 final AbsListView view,
348 int firstVisibleItem,
349 int visibleItemCount,
350 int totalItemCount) {
351 toggleScrollDownButton(view);
352 synchronized (ConversationFragment.this.messageList) {
353 if (firstVisibleItem < 5
354 && conversation != null
355 && conversation.messagesLoaded.compareAndSet(true, false)
356 && messageList.size() > 0) {
357 long timestamp = conversation.loadMoreTimestamp();
358 activity.xmppConnectionService.loadMoreMessages(
359 conversation,
360 timestamp,
361 new XmppConnectionService.OnMoreMessagesLoaded() {
362 @Override
363 public void onMoreMessagesLoaded(
364 final int c, final Conversation conversation) {
365 if (ConversationFragment.this.conversation
366 != conversation) {
367 conversation.messagesLoaded.set(true);
368 return;
369 }
370 runOnUiThread(
371 () -> {
372 synchronized (messageList) {
373 final int oldPosition =
374 binding.messagesView
375 .getFirstVisiblePosition();
376 Message message = null;
377 int childPos;
378 for (childPos = 0;
379 childPos + oldPosition
380 < messageList.size();
381 ++childPos) {
382 message =
383 messageList.get(
384 oldPosition
385 + childPos);
386 if (message.getType()
387 != Message.TYPE_STATUS) {
388 break;
389 }
390 }
391 final String uuid =
392 message != null
393 ? message.getUuid()
394 : null;
395 View v =
396 binding.messagesView.getChildAt(
397 childPos);
398 final int pxOffset =
399 (v == null) ? 0 : v.getTop();
400 ConversationFragment.this.conversation
401 .populateWithMessages(
402 ConversationFragment
403 .this
404 .messageList, activity == null ? null : activity.xmppConnectionService);
405 try {
406 updateStatusMessages();
407 } catch (IllegalStateException e) {
408 Log.d(
409 Config.LOGTAG,
410 "caught illegal state exception while updating status messages");
411 }
412 messageListAdapter
413 .notifyDataSetChanged();
414 int pos =
415 Math.max(
416 getIndexOf(
417 uuid,
418 messageList),
419 0);
420 binding.messagesView
421 .setSelectionFromTop(
422 pos, pxOffset);
423 if (messageLoaderToast != null) {
424 messageLoaderToast.cancel();
425 }
426 conversation.messagesLoaded.set(true);
427 }
428 });
429 }
430
431 @Override
432 public void informUser(final int resId) {
433
434 runOnUiThread(
435 () -> {
436 if (messageLoaderToast != null) {
437 messageLoaderToast.cancel();
438 }
439 if (ConversationFragment.this.conversation
440 != conversation) {
441 return;
442 }
443 messageLoaderToast =
444 Toast.makeText(
445 view.getContext(),
446 resId,
447 Toast.LENGTH_LONG);
448 messageLoaderToast.show();
449 });
450 }
451 });
452 }
453 }
454 }
455 };
456 private final EditMessage.OnCommitContentListener mEditorContentListener =
457 new EditMessage.OnCommitContentListener() {
458 @Override
459 public boolean onCommitContent(
460 InputContentInfoCompat inputContentInfo,
461 int flags,
462 Bundle opts,
463 String[] contentMimeTypes) {
464 // try to get permission to read the image, if applicable
465 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION)
466 != 0) {
467 try {
468 inputContentInfo.requestPermission();
469 } catch (Exception e) {
470 Log.e(
471 Config.LOGTAG,
472 "InputContentInfoCompat#requestPermission() failed.",
473 e);
474 Toast.makeText(
475 getActivity(),
476 activity.getString(
477 R.string.no_permission_to_access_x,
478 inputContentInfo.getDescription()),
479 Toast.LENGTH_LONG)
480 .show();
481 return false;
482 }
483 }
484 if (hasPermissions(
485 REQUEST_ADD_EDITOR_CONTENT,
486 Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
487 attachEditorContentToConversation(inputContentInfo.getContentUri());
488 } else {
489 mPendingEditorContent = inputContentInfo.getContentUri();
490 }
491 return true;
492 }
493 };
494 private Message selectedMessage;
495 private final OnClickListener mEnableAccountListener =
496 new OnClickListener() {
497 @Override
498 public void onClick(View v) {
499 final Account account = conversation == null ? null : conversation.getAccount();
500 if (account != null) {
501 account.setOption(Account.OPTION_SOFT_DISABLED, false);
502 account.setOption(Account.OPTION_DISABLED, false);
503 activity.xmppConnectionService.updateAccount(account);
504 }
505 }
506 };
507 private final OnClickListener mUnblockClickListener =
508 new OnClickListener() {
509 @Override
510 public void onClick(final View v) {
511 v.post(() -> v.setVisibility(View.INVISIBLE));
512 if (conversation.isDomainBlocked()) {
513 BlockContactDialog.show(activity, conversation);
514 } else {
515 unblockConversation(conversation);
516 }
517 }
518 };
519 private final OnClickListener mBlockClickListener = this::showBlockSubmenu;
520 private final OnClickListener mAddBackClickListener =
521 new OnClickListener() {
522
523 @Override
524 public void onClick(View v) {
525 final Contact contact = conversation == null ? null : conversation.getContact();
526 if (contact != null) {
527 activity.xmppConnectionService.createContact(contact, true);
528 activity.switchToContactDetails(contact);
529 }
530 }
531 };
532 private final View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
533 private final OnClickListener mAllowPresenceSubscription =
534 new OnClickListener() {
535 @Override
536 public void onClick(View v) {
537 final Contact contact = conversation == null ? null : conversation.getContact();
538 if (contact != null) {
539 activity.xmppConnectionService.sendPresencePacket(
540 contact.getAccount(),
541 activity.xmppConnectionService
542 .getPresenceGenerator()
543 .sendPresenceUpdatesTo(contact));
544 hideSnackbar();
545 }
546 }
547 };
548 protected OnClickListener clickToDecryptListener =
549 new OnClickListener() {
550
551 @Override
552 public void onClick(View v) {
553 PendingIntent pendingIntent =
554 conversation.getAccount().getPgpDecryptionService().getPendingIntent();
555 if (pendingIntent != null) {
556 try {
557 getActivity()
558 .startIntentSenderForResult(
559 pendingIntent.getIntentSender(),
560 REQUEST_DECRYPT_PGP,
561 null,
562 0,
563 0,
564 0,
565 Compatibility.pgpStartIntentSenderOptions());
566 } catch (SendIntentException e) {
567 Toast.makeText(
568 getActivity(),
569 R.string.unable_to_connect_to_keychain,
570 Toast.LENGTH_SHORT)
571 .show();
572 conversation
573 .getAccount()
574 .getPgpDecryptionService()
575 .continueDecryption(true);
576 }
577 }
578 updateSnackBar(conversation);
579 }
580 };
581 private final AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
582 private final OnEditorActionListener mEditorActionListener =
583 (v, actionId, event) -> {
584 if (actionId == EditorInfo.IME_ACTION_SEND) {
585 InputMethodManager imm =
586 (InputMethodManager)
587 activity.getSystemService(Context.INPUT_METHOD_SERVICE);
588 if (imm != null && imm.isFullscreenMode()) {
589 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
590 }
591 sendMessage();
592 return true;
593 } else {
594 return false;
595 }
596 };
597 private final OnClickListener mScrollButtonListener =
598 new OnClickListener() {
599
600 @Override
601 public void onClick(View v) {
602 stopScrolling();
603 setSelection(binding.messagesView.getCount() - 1, true);
604 }
605 };
606 private final OnClickListener mSendButtonListener =
607 new OnClickListener() {
608
609 @Override
610 public void onClick(View v) {
611 Object tag = v.getTag();
612 if (tag instanceof SendButtonAction) {
613 SendButtonAction action = (SendButtonAction) tag;
614 switch (action) {
615 case TAKE_PHOTO:
616 case RECORD_VIDEO:
617 case SEND_LOCATION:
618 case RECORD_VOICE:
619 case CHOOSE_PICTURE:
620 attachFile(action.toChoice());
621 break;
622 case CANCEL:
623 if (conversation != null) {
624 conversation.setUserSelectedThread(false);
625 if (conversation.setCorrectingMessage(null)) {
626 binding.textinput.setText("");
627 binding.textinput.append(conversation.getDraftMessage());
628 conversation.setDraftMessage(null);
629 } else if (conversation.getMode() == Conversation.MODE_MULTI) {
630 conversation.setNextCounterpart(null);
631 binding.textinput.setText("");
632 } else {
633 binding.textinput.setText("");
634 }
635 binding.textinputSubject.setText("");
636 binding.textinputSubject.setVisibility(View.GONE);
637 updateChatMsgHint();
638 updateSendButton();
639 updateEditablity();
640 }
641 break;
642 default:
643 sendMessage();
644 }
645 } else {
646 sendMessage();
647 }
648 }
649 };
650 private OnBackPressedCallback backPressedLeaveSingleThread = new OnBackPressedCallback(false) {
651 @Override
652 public void handleOnBackPressed() {
653 conversation.setLockThread(false);
654 this.setEnabled(false);
655 conversation.setUserSelectedThread(false);
656 setThread(null);
657 refresh();
658 updateThreadFromLastMessage();
659 }
660 };
661 private int completionIndex = 0;
662 private int lastCompletionLength = 0;
663 private String incomplete;
664 private int lastCompletionCursor;
665 private boolean firstWord = false;
666 private Message mPendingDownloadableMessage;
667
668 private static ConversationFragment findConversationFragment(Activity activity) {
669 Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
670 if (fragment instanceof ConversationFragment) {
671 return (ConversationFragment) fragment;
672 }
673 fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
674 if (fragment instanceof ConversationFragment) {
675 return (ConversationFragment) fragment;
676 }
677 return null;
678 }
679
680 public static void startStopPending(Activity activity) {
681 ConversationFragment fragment = findConversationFragment(activity);
682 if (fragment != null) {
683 fragment.messageListAdapter.startStopPending();
684 }
685 }
686
687 public static void downloadFile(Activity activity, Message message) {
688 ConversationFragment fragment = findConversationFragment(activity);
689 if (fragment != null) {
690 fragment.startDownloadable(message);
691 }
692 }
693
694 public static void registerPendingMessage(Activity activity, Message message) {
695 ConversationFragment fragment = findConversationFragment(activity);
696 if (fragment != null) {
697 fragment.pendingMessage.push(message);
698 }
699 }
700
701 public static void openPendingMessage(Activity activity) {
702 ConversationFragment fragment = findConversationFragment(activity);
703 if (fragment != null) {
704 Message message = fragment.pendingMessage.pop();
705 if (message != null) {
706 fragment.messageListAdapter.openDownloadable(message);
707 }
708 }
709 }
710
711 public static Conversation getConversation(Activity activity) {
712 return getConversation(activity, R.id.secondary_fragment);
713 }
714
715 private static Conversation getConversation(Activity activity, @IdRes int res) {
716 final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
717 if (fragment instanceof ConversationFragment) {
718 return ((ConversationFragment) fragment).getConversation();
719 } else {
720 return null;
721 }
722 }
723
724 public static ConversationFragment get(Activity activity) {
725 FragmentManager fragmentManager = activity.getFragmentManager();
726 Fragment fragment = fragmentManager.findFragmentById(R.id.main_fragment);
727 if (fragment instanceof ConversationFragment) {
728 return (ConversationFragment) fragment;
729 } else {
730 fragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
731 return fragment instanceof ConversationFragment
732 ? (ConversationFragment) fragment
733 : null;
734 }
735 }
736
737 public static Conversation getConversationReliable(Activity activity) {
738 final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
739 if (conversation != null) {
740 return conversation;
741 }
742 return getConversation(activity, R.id.main_fragment);
743 }
744
745 private static boolean scrolledToBottom(AbsListView listView) {
746 final int count = listView.getCount();
747 if (count == 0) {
748 return true;
749 } else if (listView.getLastVisiblePosition() == count - 1) {
750 final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
751 return lastChild != null && lastChild.getBottom() <= listView.getHeight();
752 } else {
753 return false;
754 }
755 }
756
757 private void toggleScrollDownButton() {
758 toggleScrollDownButton(binding.messagesView);
759 }
760
761 private void toggleScrollDownButton(AbsListView listView) {
762 if (conversation == null) {
763 return;
764 }
765 if (scrolledToBottom(listView)) {
766 lastMessageUuid = null;
767 hideUnreadMessagesCount();
768 } else {
769 binding.scrollToBottomButton.setEnabled(true);
770 binding.scrollToBottomButton.show();
771 if (lastMessageUuid == null) {
772 lastMessageUuid = conversation.getLatestMessage().getUuid();
773 }
774 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) > 0) {
775 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
776 }
777 }
778 }
779
780 private int getIndexOf(String uuid, List<Message> messages) {
781 if (uuid == null) {
782 return messages.size() - 1;
783 }
784 for (int i = 0; i < messages.size(); ++i) {
785 if (uuid.equals(messages.get(i).getUuid())) {
786 return i;
787 } else {
788 Message next = messages.get(i);
789 while (next != null && next.wasMergedIntoPrevious(activity == null ? null : activity.xmppConnectionService)) {
790 if (uuid.equals(next.getUuid())) {
791 return i;
792 }
793 next = next.next();
794 }
795 }
796 }
797 return -1;
798 }
799
800 private ScrollState getScrollPosition() {
801 final ListView listView = this.binding == null ? null : this.binding.messagesView;
802 if (listView == null
803 || listView.getCount() == 0
804 || listView.getLastVisiblePosition() == listView.getCount() - 1) {
805 return null;
806 } else {
807 final int pos = listView.getFirstVisiblePosition();
808 final View view = listView.getChildAt(0);
809 if (view == null) {
810 return null;
811 } else {
812 return new ScrollState(pos, view.getTop());
813 }
814 }
815 }
816
817 private void setScrollPosition(ScrollState scrollPosition, String lastMessageUuid) {
818 if (scrollPosition != null) {
819
820 this.lastMessageUuid = lastMessageUuid;
821 if (lastMessageUuid != null) {
822 binding.unreadCountCustomView.setUnreadCount(
823 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
824 }
825 // TODO maybe this needs a 'post'
826 this.binding.messagesView.setSelectionFromTop(
827 scrollPosition.position, scrollPosition.offset);
828 toggleScrollDownButton();
829 }
830 }
831
832 private void attachLocationToConversation(Conversation conversation, Uri uri) {
833 if (conversation == null) {
834 return;
835 }
836 final String subject = binding.textinputSubject.getText().toString();
837 activity.xmppConnectionService.attachLocationToConversation(
838 conversation,
839 uri,
840 subject,
841 new UiCallback<Message>() {
842
843 @Override
844 public void success(Message message) {
845 messageSent();
846 }
847
848 @Override
849 public void error(int errorCode, Message object) {
850 // TODO show possible pgp error
851 }
852
853 @Override
854 public void userInputRequired(PendingIntent pi, Message object) {}
855 });
856 }
857
858 private void attachFileToConversation(Conversation conversation, Uri uri, String type, Runnable next) {
859 if (conversation == null) {
860 return;
861 }
862 final String subject = binding.textinputSubject.getText().toString();
863 if ("application/webxdc+zip".equals(type)) newSubThread();
864 final Toast prepareFileToast =
865 Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
866 prepareFileToast.show();
867 activity.delegateUriPermissionsToService(uri);
868 activity.xmppConnectionService.attachFileToConversation(
869 conversation,
870 uri,
871 type,
872 subject,
873 new UiInformableCallback<Message>() {
874 @Override
875 public void inform(final String text) {
876 hidePrepareFileToast(prepareFileToast);
877 runOnUiThread(() -> activity.replaceToast(text));
878 }
879
880 @Override
881 public void success(Message message) {
882 if (next == null) {
883 runOnUiThread(() -> {
884 activity.hideToast();
885 messageSent();
886 });
887 } else {
888 runOnUiThread(next);
889 }
890 hidePrepareFileToast(prepareFileToast);
891 }
892
893 @Override
894 public void error(final int errorCode, Message message) {
895 hidePrepareFileToast(prepareFileToast);
896 runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
897 }
898
899 @Override
900 public void userInputRequired(PendingIntent pi, Message message) {
901 hidePrepareFileToast(prepareFileToast);
902 }
903 });
904 }
905
906 public void attachEditorContentToConversation(Uri uri) {
907 mediaPreviewAdapter.addMediaPreviews(
908 Attachment.of(getActivity(), uri, Attachment.Type.FILE));
909 toggleInputMethod();
910 }
911
912 private void attachImageToConversation(Conversation conversation, Uri uri, String type, Runnable next) {
913 if (conversation == null) {
914 return;
915 }
916 final String subject = binding.textinputSubject.getText().toString();
917 final Toast prepareFileToast =
918 Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
919 prepareFileToast.show();
920 activity.delegateUriPermissionsToService(uri);
921 activity.xmppConnectionService.attachImageToConversation(
922 conversation,
923 uri,
924 type,
925 subject,
926 new UiCallback<Message>() {
927
928 @Override
929 public void userInputRequired(PendingIntent pi, Message object) {
930 hidePrepareFileToast(prepareFileToast);
931 }
932
933 @Override
934 public void success(Message message) {
935 hidePrepareFileToast(prepareFileToast);
936 if (next == null) {
937 runOnUiThread(() -> messageSent());
938 } else {
939 runOnUiThread(next);
940 }
941 }
942
943 @Override
944 public void error(final int error, final Message message) {
945 hidePrepareFileToast(prepareFileToast);
946 final ConversationsActivity activity = ConversationFragment.this.activity;
947 if (activity == null) {
948 return;
949 }
950 activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
951 }
952 });
953 }
954
955 private void hidePrepareFileToast(final Toast prepareFileToast) {
956 if (prepareFileToast != null && activity != null) {
957 activity.runOnUiThread(prepareFileToast::cancel);
958 }
959 }
960
961 private void sendMessage() {
962 sendMessage((Long) null);
963 }
964
965 private void sendMessage(Long sendAt) {
966 if (sendAt != null && sendAt < System.currentTimeMillis()) sendAt = null; // No sending in past plz
967 if (mediaPreviewAdapter.hasAttachments()) {
968 commitAttachments();
969 return;
970 }
971 Editable body = this.binding.textinput.getText();
972 if (body == null) body = new SpannableStringBuilder("");
973 if (body.length() > Config.MAX_DISPLAY_MESSAGE_CHARS) {
974 Toast.makeText(activity, "Message is too long", Toast.LENGTH_SHORT).show();
975 return;
976 }
977 final Conversation conversation = this.conversation;
978 final boolean hasSubject = binding.textinputSubject.getText().length() > 0;
979 if (conversation == null || (body.length() == 0 && (conversation.getThread() == null || !hasSubject))) {
980 if (Build.VERSION.SDK_INT >= 24) {
981 binding.textSendButton.showContextMenu(0, 0);
982 } else {
983 binding.textSendButton.showContextMenu();
984 }
985 return;
986 }
987 if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_TEXT)) {
988 return;
989 }
990 final Message message;
991 if (conversation.getCorrectingMessage() == null) {
992 boolean attention = false;
993 if (Pattern.compile("\\A@here\\s.*").matcher(body).find()) {
994 attention = true;
995 body.delete(0, 6);
996 while (body.length() > 0 && Character.isWhitespace(body.charAt(0))) body.delete(0, 1);
997 }
998 if (conversation.getReplyTo() != null) {
999 if (Emoticons.isEmoji(body.toString().replaceAll("\\s", ""))) {
1000 final var aggregated = conversation.getReplyTo().getAggregatedReactions();
1001 final ImmutableSet.Builder<String> reactionBuilder = new ImmutableSet.Builder<>();
1002 reactionBuilder.addAll(aggregated.ourReactions);
1003 reactionBuilder.add(body.toString().replaceAll("\\s", ""));
1004 activity.xmppConnectionService.sendReactions(conversation.getReplyTo(), reactionBuilder.build());
1005 messageSent();
1006 return;
1007 } else {
1008 message = conversation.getReplyTo().reply();
1009 message.appendBody(body);
1010 }
1011 message.setEncryption(conversation.getNextEncryption());
1012 } else {
1013 message = new Message(conversation, body.toString(), conversation.getNextEncryption());
1014 message.setBody(hasSubject && body.length() == 0 ? null : body);
1015 if (message.bodyIsOnlyEmojis()) {
1016 SpannableStringBuilder spannable = message.getSpannableBody(null, null);
1017 ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
1018 for (ImageSpan span : imageSpans) {
1019 final int start = spannable.getSpanStart(span);
1020 final int end = spannable.getSpanEnd(span);
1021 spannable.delete(start, end);
1022 }
1023 if (imageSpans.length == 1 && spannable.toString().replaceAll("\\s", "").length() < 1) {
1024 // Only one inline image, so it's a sticker
1025 String source = imageSpans[0].getSource();
1026 if (source != null && source.length() > 0 && source.substring(0, 4).equals("cid:")) {
1027 try {
1028 final Cid cid = BobTransfer.cid(Uri.parse(source));
1029 final String url = activity.xmppConnectionService.getUrlForCid(cid);
1030 final File f = activity.xmppConnectionService.getFileForCid(cid);
1031 if (url != null) {
1032 message.setBody("");
1033 message.setRelativeFilePath(f.getAbsolutePath());
1034 activity.xmppConnectionService.getFileBackend().updateFileParams(message);
1035 }
1036 } catch (final Exception e) { }
1037 }
1038 }
1039 }
1040 }
1041 if (hasSubject) message.setSubject(binding.textinputSubject.getText().toString());
1042 message.setThread(conversation.getThread());
1043 if (attention) {
1044 message.addPayload(new Element("attention", "urn:xmpp:attention:0"));
1045 }
1046 Message.configurePrivateMessage(message);
1047 } else {
1048 message = conversation.getCorrectingMessage();
1049 if (hasSubject) message.setSubject(binding.textinputSubject.getText().toString());
1050 message.setThread(conversation.getThread());
1051 if (conversation.getReplyTo() != null) {
1052 if (Emoticons.isEmoji(body.toString().replaceAll("\\s", ""))) {
1053 message.updateReaction(conversation.getReplyTo(), body.toString().replaceAll("\\s", ""));
1054 } else {
1055 message.updateReplyTo(conversation.getReplyTo(), body);
1056 }
1057 } else {
1058 message.clearReplyReact();
1059 message.setBody(hasSubject && body.length() == 0 ? null : body);
1060 }
1061 if (message.getStatus() == Message.STATUS_WAITING) {
1062 if (sendAt != null) message.setTime(sendAt);
1063 activity.xmppConnectionService.updateMessage(message);
1064 messageSent();
1065 return;
1066 } else {
1067 message.putEdited(message.getUuid(), message.getServerMsgId());
1068 message.setServerMsgId(null);
1069 message.setUuid(UUID.randomUUID().toString());
1070 }
1071 }
1072 if (sendAt != null) message.setTime(sendAt);
1073 switch (conversation.getNextEncryption()) {
1074 case Message.ENCRYPTION_PGP:
1075 sendPgpMessage(message);
1076 break;
1077 default:
1078 sendMessage(message);
1079 }
1080 setupReply(null);
1081 }
1082
1083 private boolean trustKeysIfNeeded(final Conversation conversation, final int requestCode) {
1084 return conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL
1085 && trustKeysIfNeeded(requestCode);
1086 }
1087
1088 protected boolean trustKeysIfNeeded(int requestCode) {
1089 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
1090 if (axolotlService == null) return false;
1091 final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
1092 boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
1093 boolean hasUndecidedOwn =
1094 !axolotlService
1095 .getKeysWithTrust(FingerprintStatus.createActiveUndecided())
1096 .isEmpty();
1097 boolean hasUndecidedContacts =
1098 !axolotlService
1099 .getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets)
1100 .isEmpty();
1101 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
1102 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1103 boolean downloadInProgress = axolotlService.hasPendingKeyFetches(targets);
1104 if (hasUndecidedOwn
1105 || hasUndecidedContacts
1106 || hasPendingKeys
1107 || hasNoTrustedKeys
1108 || hasUnaccepted
1109 || downloadInProgress) {
1110 axolotlService.createSessionsIfNeeded(conversation);
1111 Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
1112 String[] contacts = new String[targets.size()];
1113 for (int i = 0; i < contacts.length; ++i) {
1114 contacts[i] = targets.get(i).toString();
1115 }
1116 intent.putExtra("contacts", contacts);
1117 intent.putExtra(
1118 EXTRA_ACCOUNT,
1119 conversation.getAccount().getJid().asBareJid().toEscapedString());
1120 intent.putExtra("conversation", conversation.getUuid());
1121 startActivityForResult(intent, requestCode);
1122 return true;
1123 } else {
1124 return false;
1125 }
1126 }
1127
1128 public void updateChatMsgHint() {
1129 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
1130 if (conversation.getCorrectingMessage() != null) {
1131 this.binding.textInputHint.setVisibility(View.GONE);
1132 this.binding.textinput.setHint(R.string.send_corrected_message);
1133 binding.conversationViewPager.setCurrentItem(0);
1134 } else if (multi && conversation.getNextCounterpart() != null) {
1135 this.binding.textinput.setHint(R.string.send_message);
1136 this.binding.textInputHint.setVisibility(View.VISIBLE);
1137 final MucOptions.User user = conversation.getMucOptions().findUserByName(conversation.getNextCounterpart().getResource());
1138 String nick = user == null ? null : user.getNick();
1139 if (nick == null) nick = conversation.getNextCounterpart().getResource();
1140 this.binding.textInputHint.setText(
1141 getString(
1142 R.string.send_private_message_to,
1143 nick));
1144 binding.conversationViewPager.setCurrentItem(0);
1145 } else if (multi && !conversation.getMucOptions().participating()) {
1146 this.binding.textInputHint.setVisibility(View.GONE);
1147 this.binding.textinput.setHint(R.string.you_are_not_participating);
1148 this.binding.inputLayout.setBackgroundColor(android.R.color.transparent);
1149 } else {
1150 this.binding.textInputHint.setVisibility(View.GONE);
1151 if (activity == null) return;
1152 this.binding.textinput.setHint(UIHelper.getMessageHint(activity, conversation));
1153 this.binding.inputLayout.setBackground(activity.getDrawable(R.drawable.background_message_bubble));
1154 activity.invalidateOptionsMenu();
1155 }
1156
1157 binding.messagesView.post(this::updateThreadFromLastMessage);
1158 }
1159
1160 public void setupIme() {
1161 this.binding.textinput.refreshIme();
1162 }
1163
1164 private void handleActivityResult(ActivityResult activityResult) {
1165 if (activityResult.resultCode == Activity.RESULT_OK) {
1166 handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
1167 } else {
1168 handleNegativeActivityResult(activityResult.requestCode);
1169 }
1170 }
1171
1172 private void handlePositiveActivityResult(int requestCode, final Intent data) {
1173 switch (requestCode) {
1174 case REQUEST_WEBXDC_STORE:
1175 mediaPreviewAdapter.addMediaPreviews(Attachment.of(activity, data.getData(), Attachment.Type.FILE));
1176 toggleInputMethod();
1177 break;
1178 case REQUEST_SAVE_STICKER:
1179 final DocumentFile df = DocumentFile.fromSingleUri(activity, data.getData());
1180 final File f = savingAsSticker;
1181 savingAsSticker = null;
1182 try {
1183 activity.xmppConnectionService.getFileBackend().copyFileToDocumentFile(activity, f, df);
1184 Toast.makeText(activity, "Sticker saved", Toast.LENGTH_SHORT).show();
1185 } catch (final FileBackend.FileCopyException e) {
1186 Toast.makeText(activity, e.getResId(), Toast.LENGTH_SHORT).show();
1187 }
1188 break;
1189 case REQUEST_TRUST_KEYS_TEXT:
1190 sendMessage();
1191 break;
1192 case REQUEST_TRUST_KEYS_ATTACHMENTS:
1193 commitAttachments();
1194 break;
1195 case REQUEST_START_AUDIO_CALL:
1196 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1197 break;
1198 case REQUEST_START_VIDEO_CALL:
1199 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1200 break;
1201 case ATTACHMENT_CHOICE_CHOOSE_IMAGE: {
1202 final Uri takePhotoUri = pendingTakePhotoUri.pop();
1203 if (takePhotoUri != null && (data == null || (data.getData() == null && data.getClipData() == null))) {
1204 mediaPreviewAdapter.addMediaPreviews(
1205 Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
1206 }
1207 final List<Attachment> imageUris =
1208 Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE);
1209 mediaPreviewAdapter.addMediaPreviews(imageUris);
1210 toggleInputMethod();
1211 break;
1212 }
1213 case ATTACHMENT_CHOICE_TAKE_PHOTO: {
1214 final Uri takePhotoUri = pendingTakePhotoUri.pop();
1215 if (takePhotoUri != null) {
1216 mediaPreviewAdapter.addMediaPreviews(
1217 Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
1218 toggleInputMethod();
1219 } else {
1220 Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
1221 }
1222 break;
1223 }
1224 case ATTACHMENT_CHOICE_CHOOSE_FILE:
1225 case ATTACHMENT_CHOICE_RECORD_VIDEO:
1226 case ATTACHMENT_CHOICE_RECORD_VOICE:
1227 final Attachment.Type type =
1228 requestCode == ATTACHMENT_CHOICE_RECORD_VOICE
1229 ? Attachment.Type.RECORDING
1230 : Attachment.Type.FILE;
1231 final List<Attachment> fileUris =
1232 Attachment.extractAttachments(getActivity(), data, type);
1233 mediaPreviewAdapter.addMediaPreviews(fileUris);
1234 toggleInputMethod();
1235 break;
1236 case ATTACHMENT_CHOICE_LOCATION:
1237 final double latitude = data.getDoubleExtra("latitude", 0);
1238 final double longitude = data.getDoubleExtra("longitude", 0);
1239 final int accuracy = data.getIntExtra("accuracy", 0);
1240 final Uri geo;
1241 if (accuracy > 0) {
1242 geo = Uri.parse(String.format("geo:%s,%s;u=%s", latitude, longitude, accuracy));
1243 } else {
1244 geo = Uri.parse(String.format("geo:%s,%s", latitude, longitude));
1245 }
1246 mediaPreviewAdapter.addMediaPreviews(
1247 Attachment.of(getActivity(), geo, Attachment.Type.LOCATION));
1248 toggleInputMethod();
1249 break;
1250 case REQUEST_INVITE_TO_CONVERSATION:
1251 XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data);
1252 if (invite != null) {
1253 if (invite.execute(activity)) {
1254 activity.mToast =
1255 Toast.makeText(
1256 activity, R.string.creating_conference, Toast.LENGTH_LONG);
1257 activity.mToast.show();
1258 }
1259 }
1260 break;
1261 }
1262 }
1263
1264 private void commitAttachments() {
1265 final List<Attachment> attachments = mediaPreviewAdapter.getAttachments();
1266 if (anyNeedsExternalStoragePermission(attachments)
1267 && !hasPermissions(
1268 REQUEST_COMMIT_ATTACHMENTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1269 return;
1270 }
1271 if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_ATTACHMENTS)) {
1272 return;
1273 }
1274 final PresenceSelector.OnPresenceSelected callback =
1275 () -> {
1276 final Iterator<Attachment> i = attachments.iterator();
1277 final Runnable next = new Runnable() {
1278 @Override
1279 public void run() {
1280 try {
1281 final Attachment attachment = i.next();
1282 if (attachment.getType() == Attachment.Type.LOCATION) {
1283 attachLocationToConversation(conversation, attachment.getUri());
1284 if (i.hasNext()) runOnUiThread(this);
1285 } else if (attachment.getType() == Attachment.Type.IMAGE) {
1286 Log.d(
1287 Config.LOGTAG,
1288 "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE");
1289 attachImageToConversation(conversation, attachment.getUri(), attachment.getMime(), i.hasNext() ? this : null);
1290 } else {
1291 Log.d(
1292 Config.LOGTAG,
1293 "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1294 attachFileToConversation(conversation, attachment.getUri(), attachment.getMime(), i.hasNext() ? this : null);
1295 }
1296 i.remove();
1297 } catch (final java.util.ConcurrentModificationException e) {
1298 // Abort, leave any unsent attachments alone for the user to try again
1299 Toast.makeText(activity, "Sometimes went wrong with some attachments. Try again?", Toast.LENGTH_SHORT).show();
1300 }
1301 mediaPreviewAdapter.notifyDataSetChanged();
1302 toggleInputMethod();
1303 }
1304 };
1305 next.run();
1306 };
1307 if (conversation == null
1308 || conversation.getMode() == Conversation.MODE_MULTI
1309 || Attachment.canBeSendInBand(attachments)
1310 || (conversation.getAccount().httpUploadAvailable()
1311 && FileBackend.allFilesUnderSize(
1312 getActivity(), attachments, getMaxHttpUploadSize(conversation)))) {
1313 callback.onPresenceSelected();
1314 } else {
1315 activity.selectPresence(conversation, callback);
1316 }
1317 }
1318
1319 private static boolean anyNeedsExternalStoragePermission(
1320 final Collection<Attachment> attachments) {
1321 for (final Attachment attachment : attachments) {
1322 if (attachment.getType() != Attachment.Type.LOCATION) {
1323 return true;
1324 }
1325 }
1326 return false;
1327 }
1328
1329 public void toggleInputMethod() {
1330 boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
1331 binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
1332 binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
1333 updateSendButton();
1334 }
1335
1336 private void handleNegativeActivityResult(int requestCode) {
1337 switch (requestCode) {
1338 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1339 if (pendingTakePhotoUri.clear()) {
1340 Log.d(
1341 Config.LOGTAG,
1342 "cleared pending photo uri after negative activity result");
1343 }
1344 break;
1345 }
1346 }
1347
1348 @Override
1349 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
1350 super.onActivityResult(requestCode, resultCode, data);
1351 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
1352 if (activity != null && activity.xmppConnectionService != null) {
1353 handleActivityResult(activityResult);
1354 } else {
1355 this.postponedActivityResult.push(activityResult);
1356 }
1357 }
1358
1359 public void unblockConversation(final Blockable conversation) {
1360 activity.xmppConnectionService.sendUnblockRequest(conversation);
1361 }
1362
1363 @Override
1364 public void onAttach(Activity activity) {
1365 super.onAttach(activity);
1366 Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
1367 if (activity instanceof ConversationsActivity) {
1368 this.activity = (ConversationsActivity) activity;
1369 } else {
1370 throw new IllegalStateException(
1371 "Trying to attach fragment to activity that is not the ConversationsActivity");
1372 }
1373 }
1374
1375 @Override
1376 public void onDetach() {
1377 super.onDetach();
1378 this.activity = null; // TODO maybe not a good idea since some callbacks really need it
1379 }
1380
1381 @Override
1382 public void onCreate(Bundle savedInstanceState) {
1383 super.onCreate(savedInstanceState);
1384 setHasOptionsMenu(true);
1385 activity.getOnBackPressedDispatcher().addCallback(this, backPressedLeaveSingleThread);
1386 }
1387
1388 @Override
1389 public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
1390 if (activity != null && activity.xmppConnectionService != null && activity.xmppConnectionService.isOnboarding()) return;
1391
1392 menuInflater.inflate(R.menu.fragment_conversation, menu);
1393 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
1394 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
1395 final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
1396 final MenuItem menuMute = menu.findItem(R.id.action_mute);
1397 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
1398 final MenuItem menuCall = menu.findItem(R.id.action_call);
1399 final MenuItem menuOngoingCall = menu.findItem(R.id.action_ongoing_call);
1400 final MenuItem menuVideoCall = menu.findItem(R.id.action_video_call);
1401 final MenuItem menuTogglePinned = menu.findItem(R.id.action_toggle_pinned);
1402 final MenuItem menuArchiveChat = menu.findItem(R.id.action_archive);
1403
1404 if (conversation != null) {
1405 if (conversation.getMode() == Conversation.MODE_MULTI) {
1406 menuContactDetails.setVisible(false);
1407 menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
1408 menuMucDetails.setTitle(
1409 conversation.getMucOptions().isPrivateAndNonAnonymous()
1410 ? R.string.action_muc_details
1411 : R.string.channel_details);
1412 menuCall.setVisible(false);
1413 menuOngoingCall.setVisible(false);
1414 menuArchiveChat.setTitle("Leave " + (conversation.getMucOptions().isPrivateAndNonAnonymous() ? "group chat" : "Channel"));
1415 } else {
1416 final XmppConnectionService service =
1417 activity == null ? null : activity.xmppConnectionService;
1418 final Optional<OngoingRtpSession> ongoingRtpSession =
1419 service == null
1420 ? Optional.absent()
1421 : service.getJingleConnectionManager()
1422 .getOngoingRtpConnection(conversation.getContact());
1423 if (ongoingRtpSession.isPresent()) {
1424 menuOngoingCall.setVisible(true);
1425 menuCall.setVisible(false);
1426 } else {
1427 menuOngoingCall.setVisible(false);
1428 final RtpCapability.Capability rtpCapability =
1429 RtpCapability.check(conversation.getContact());
1430 final boolean cameraAvailable =
1431 activity != null && activity.isCameraFeatureAvailable();
1432 menuCall.setVisible(rtpCapability != RtpCapability.Capability.NONE);
1433 menuVideoCall.setVisible(
1434 rtpCapability == RtpCapability.Capability.VIDEO && cameraAvailable);
1435 }
1436 menuContactDetails.setVisible(!this.conversation.withSelf());
1437 menuMucDetails.setVisible(false);
1438 menuInviteContact.setVisible(
1439 service != null
1440 && service.findConferenceServer(conversation.getAccount()) != null);
1441 menuArchiveChat.setTitle(R.string.action_archive_chat);
1442 }
1443 if (conversation.isMuted()) {
1444 menuMute.setVisible(false);
1445 } else {
1446 menuUnmute.setVisible(false);
1447 }
1448 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
1449 ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
1450 if (conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false)) {
1451 menuTogglePinned.setTitle(R.string.remove_from_favorites);
1452 } else {
1453 menuTogglePinned.setTitle(R.string.add_to_favorites);
1454 }
1455 }
1456 super.onCreateOptionsMenu(menu, menuInflater);
1457 }
1458
1459 @Override
1460 public View onCreateView(
1461 final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
1462 this.binding =
1463 DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
1464 binding.getRoot().setOnClickListener(null); // TODO why the fuck did we do this?
1465
1466 binding.textinput.setOnEditorActionListener(mEditorActionListener);
1467 binding.textinput.setRichContentListener(new String[] {"image/*"}, mEditorContentListener);
1468 DisplayMetrics displayMetrics = new DisplayMetrics();
1469 activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
1470 if (displayMetrics.heightPixels > 0) binding.textinput.setMaxHeight(displayMetrics.heightPixels / 4);
1471
1472 binding.textSendButton.setOnClickListener(this.mSendButtonListener);
1473 binding.contextPreviewCancel.setOnClickListener((v) -> {
1474 setThread(null);
1475 conversation.setUserSelectedThread(false);
1476 setupReply(null);
1477 });
1478 binding.requestVoice.setOnClickListener((v) -> {
1479 activity.xmppConnectionService.requestVoice(conversation.getAccount(), conversation.getJid());
1480 binding.requestVoice.setVisibility(View.GONE);
1481 Toast.makeText(activity, "Your request has been sent to the moderators", Toast.LENGTH_SHORT).show();
1482 });
1483
1484 binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
1485 binding.messagesView.setOnScrollListener(mOnScrollListener);
1486 binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
1487 mediaPreviewAdapter = new MediaPreviewAdapter(this);
1488 binding.mediaPreview.setAdapter(mediaPreviewAdapter);
1489 messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1490 messageListAdapter.setOnContactPictureClicked(this);
1491 messageListAdapter.setOnContactPictureLongClicked(this);
1492 messageListAdapter.setOnInlineImageLongClicked(this);
1493 messageListAdapter.setConversationFragment(this);
1494 binding.messagesView.setAdapter(messageListAdapter);
1495
1496 binding.textinput.addTextChangedListener(
1497 new StylingHelper.MessageEditorStyler(binding.textinput, messageListAdapter));
1498
1499 registerForContextMenu(binding.messagesView);
1500 registerForContextMenu(binding.textSendButton);
1501
1502 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1503 this.binding.textinput.setCustomInsertionActionModeCallback(
1504 new EditMessageActionModeCallback(this.binding.textinput));
1505 this.binding.textinput.setCustomSelectionActionModeCallback(
1506 new EditMessageSelectionActionModeCallback(this.binding.textinput));
1507 }
1508
1509 messageListAdapter.setOnMessageBoxClicked(message -> {
1510 if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1511 setThread(message.getThread());
1512 conversation.setUserSelectedThread(true);
1513 });
1514
1515 messageListAdapter.setOnMessageBoxSwiped(message -> {
1516 quoteMessage(message);
1517 });
1518
1519 binding.threadIdenticonLayout.setOnClickListener(v -> {
1520 boolean wasLocked = conversation.getLockThread();
1521 conversation.setLockThread(false);
1522 backPressedLeaveSingleThread.setEnabled(false);
1523 if (wasLocked) {
1524 setThread(null);
1525 conversation.setUserSelectedThread(false);
1526 refresh();
1527 updateThreadFromLastMessage();
1528 } else {
1529 newThread();
1530 conversation.setUserSelectedThread(true);
1531 newThreadTutorialToast("Switched to new thread");
1532 }
1533 });
1534
1535 binding.threadIdenticonLayout.setOnLongClickListener(v -> {
1536 boolean wasLocked = conversation.getLockThread();
1537 conversation.setLockThread(false);
1538 backPressedLeaveSingleThread.setEnabled(false);
1539 setThread(null);
1540 conversation.setUserSelectedThread(true);
1541 if (wasLocked) refresh();
1542 newThreadTutorialToast("Cleared thread");
1543 return true;
1544 });
1545
1546 Autocomplete.<MucOptions.User>on(binding.textinput)
1547 .with(activity.getDrawable(R.drawable.background_message_bubble))
1548 .with(new CharPolicy('@'))
1549 .with(new RecyclerViewPresenter<MucOptions.User>(activity) {
1550 protected UserAdapter adapter;
1551
1552 @Override
1553 protected Adapter instantiateAdapter() {
1554 adapter = new UserAdapter(false) {
1555 @Override
1556 public void onBindViewHolder(UserAdapter.ViewHolder viewHolder, int position) {
1557 super.onBindViewHolder(viewHolder, position);
1558 final var item = getItem(position);
1559 viewHolder.binding.getRoot().setOnClickListener(v -> {
1560 dispatchClick(item);
1561 });
1562 }
1563 };
1564 return adapter;
1565 }
1566
1567 @Override
1568 protected void onQuery(@Nullable CharSequence query) {
1569 if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1570
1571 final var allUsers = conversation.getMucOptions().getUsers();
1572 if (!conversation.getMucOptions().getUsersByRole(MucOptions.Role.MODERATOR).isEmpty()) {
1573 final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0role:moderator", "Notify active moderators", new HashSet<>());
1574 u.setRole("participant");
1575 allUsers.add(u);
1576 }
1577 if (!allUsers.isEmpty() && conversation.getMucOptions().getSelf() != null && conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
1578 final var u = new MucOptions.User(conversation.getMucOptions(), null, "\0attention", "Notify active participants", new HashSet<>());
1579 u.setRole("participant");
1580 allUsers.add(u);
1581 }
1582 final String needle = query.toString().toLowerCase(Locale.getDefault());
1583 if (getRecyclerView() != null) getRecyclerView().setItemAnimator(null);
1584 adapter.submitList(
1585 Ordering.natural().immutableSortedCopy(Collections2.filter(
1586 allUsers,
1587 user -> {
1588 if ("mods".contains(needle) && "\0role:moderator".equals(user.getOccupantId())) return true;
1589 if ("here".contains(needle) && "\0attention".equals(user.getOccupantId())) return true;
1590 final String name = user.getNick();
1591 if (name == null) return false;
1592 for (final var hat : user.getHats()) {
1593 if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1594 }
1595 for (final var hat : user.getPseudoHats(activity)) {
1596 if (hat.toString().toLowerCase(Locale.getDefault()).contains(needle)) return true;
1597 }
1598 final Contact contact = user.getContact();
1599 return name.toLowerCase(Locale.getDefault()).contains(needle)
1600 || contact != null
1601 && contact.getDisplayName().toLowerCase(Locale.getDefault()).contains(needle);
1602 })));
1603 }
1604
1605 @Override
1606 protected AutocompletePresenter.PopupDimensions getPopupDimensions() {
1607 final var dim = new AutocompletePresenter.PopupDimensions();
1608 dim.width = displayMetrics.widthPixels * 4/5;
1609 return dim;
1610 }
1611 })
1612 .with(new AutocompleteCallback<MucOptions.User>() {
1613 @Override
1614 public boolean onPopupItemClicked(Editable editable, MucOptions.User user) {
1615 int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1616 if (range == null) return false;
1617 range[0] -= 1;
1618 if ("\0attention".equals(user.getOccupantId())) {
1619 editable.delete(Math.max(0, range[0]), Math.min(editable.length(), range[1]));
1620 editable.insert(0, "@here ");
1621 return true;
1622 }
1623 int colon = editable.toString().indexOf(':');
1624 final var beforeColon = range[0] < colon;
1625 String prefix = "";
1626 String suffix = " ";
1627 if (beforeColon) suffix = ", ";
1628 if (colon < 0 && range[0] == 0) suffix = ": ";
1629 if (colon > 0 && colon == range[0] - 2) {
1630 prefix = ", ";
1631 suffix = ": ";
1632 range[0] -= 2;
1633 }
1634 var insert = user.getNick();
1635 if ("\0role:moderator".equals(user.getOccupantId())) {
1636 insert = conversation.getMucOptions().getUsersByRole(MucOptions.Role.MODERATOR).stream().map(MucOptions.User::getNick).collect(Collectors.joining(", "));
1637 }
1638 editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), prefix + insert + suffix);
1639 return true;
1640 }
1641
1642 @Override
1643 public void onPopupVisibilityChanged(boolean shown) {}
1644 }).build();
1645
1646 Handler emojiDebounce = new Handler(Looper.getMainLooper());
1647 setupEmojiSearch();
1648 Autocomplete.<EmojiSearch.Emoji>on(binding.textinput)
1649 .with(activity.getDrawable(R.drawable.background_message_bubble))
1650 .with(new CharPolicy(':'))
1651 .with(new RecyclerViewPresenter<EmojiSearch.Emoji>(activity) {
1652 protected EmojiSearch.EmojiSearchAdapter adapter;
1653
1654 @Override
1655 protected Adapter instantiateAdapter() {
1656 setupEmojiSearch();
1657 adapter = emojiSearch.makeAdapter(item -> dispatchClick(item));
1658 return adapter;
1659 }
1660
1661 @Override
1662 protected void onViewHidden() {
1663 if (getRecyclerView() == null) return;
1664 super.onViewHidden();
1665 }
1666
1667 @Override
1668 protected void onQuery(@Nullable CharSequence query) {
1669 if (!activity.xmppConnectionService.getBooleanPreference("message_autocomplete", R.bool.message_autocomplete)) return;
1670
1671 emojiDebounce.removeCallbacksAndMessages(null);
1672 emojiDebounce.postDelayed(() -> {
1673 if (getRecyclerView() == null) return;
1674 getRecyclerView().setItemAnimator(null);
1675 adapter.search(activity, getRecyclerView(), query.toString());
1676 }, 100L);
1677 }
1678 })
1679 .with(new AutocompleteCallback<EmojiSearch.Emoji>() {
1680 @Override
1681 public boolean onPopupItemClicked(Editable editable, EmojiSearch.Emoji emoji) {
1682 int[] range = com.otaliastudios.autocomplete.CharPolicy.getQueryRange(editable);
1683 if (range == null) return false;
1684 range[0] -= 1;
1685 final var toInsert = emoji.toInsert();
1686 toInsert.append(" ");
1687 editable.replace(Math.max(0, range[0]), Math.min(editable.length(), range[1]), toInsert);
1688 return true;
1689 }
1690
1691 @Override
1692 public void onPopupVisibilityChanged(boolean shown) {}
1693 }).build();
1694
1695 return binding.getRoot();
1696 }
1697
1698 protected void setupEmojiSearch() {
1699 if (activity != null && activity.xmppConnectionService != null) {
1700 if (emojiSearch == null) {
1701 emojiSearch = activity.xmppConnectionService.emojiSearch();
1702 }
1703 }
1704 }
1705
1706 protected void newThreadTutorialToast(String s) {
1707 if (activity == null) return;
1708 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1709 final int tutorialCount = p.getInt("thread_tutorial", 0);
1710 if (tutorialCount < 5) {
1711 Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
1712 p.edit().putInt("thread_tutorial", tutorialCount + 1).apply();
1713 }
1714 }
1715
1716 @Override
1717 public void onDestroyView() {
1718 super.onDestroyView();
1719 Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
1720 messageListAdapter.setOnContactPictureClicked(null);
1721 messageListAdapter.setOnContactPictureLongClicked(null);
1722 messageListAdapter.setOnInlineImageLongClicked(null);
1723 messageListAdapter.setConversationFragment(null);
1724 messageListAdapter.setOnMessageBoxClicked(null);
1725 messageListAdapter.setOnMessageBoxSwiped(null);
1726 binding.conversationViewPager.setAdapter(null);
1727 if (conversation != null) conversation.setupViewPager(null, null, false, null);
1728 }
1729
1730 public void quoteText(String text) {
1731 if (binding.textinput.isEnabled()) {
1732 binding.textinput.insertAsQuote(text);
1733 binding.textinput.requestFocus();
1734 InputMethodManager inputMethodManager =
1735 (InputMethodManager)
1736 getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1737 if (inputMethodManager != null) {
1738 inputMethodManager.showSoftInput(
1739 binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1740 }
1741 }
1742 }
1743
1744 private void quoteMessage(Message message) {
1745 if (message.isPrivateMessage()) privateMessageWith(message.getCounterpart());
1746 setThread(message.getThread());
1747 conversation.setUserSelectedThread(true);
1748 if (!forkNullThread(message)) newThread();
1749 setupReply(message);
1750 }
1751
1752 private boolean forkNullThread(Message message) {
1753 if (message.getThread() != null || conversation.getMode() != Conversation.MODE_MULTI) return true;
1754 for (final Message m : conversation.findReplies(message.getServerMsgId())) {
1755 final Element thread = m.getThread();
1756 if (thread != null) {
1757 setThread(thread);
1758 return true;
1759 }
1760 }
1761
1762 return false;
1763 }
1764
1765 private void setupReply(Message message) {
1766 conversation.setReplyTo(message);
1767 if (message == null) {
1768 binding.contextPreview.setVisibility(View.GONE);
1769 binding.textsend.setBackgroundResource(R.drawable.textsend);
1770 return;
1771 }
1772
1773 SpannableStringBuilder body = message.getSpannableBody(null, null);
1774 if (message.isFileOrImage() || message.isOOb()) body.append(" 🖼️");
1775 messageListAdapter.handleTextQuotes(binding.contextPreviewText, body);
1776 binding.contextPreviewText.setText(body);
1777 binding.contextPreview.setVisibility(View.VISIBLE);
1778 }
1779
1780 private void setThread(Element thread) {
1781 this.conversation.setThread(thread);
1782 binding.threadIdenticon.setAlpha(0f);
1783 binding.threadIdenticonLock.setVisibility(this.conversation.getLockThread() ? View.VISIBLE : View.GONE);
1784 if (thread != null) {
1785 final String threadId = thread.getContent();
1786 if (threadId != null) {
1787 binding.threadIdenticon.setAlpha(1f);
1788 binding.threadIdenticon.setColor(UIHelper.getColorForName(threadId));
1789 binding.threadIdenticon.setHash(UIHelper.identiconHash(threadId));
1790 }
1791 }
1792 updateSendButton();
1793 }
1794
1795 @Override
1796 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1797 // This should cancel any remaining click events that would otherwise trigger links
1798 v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
1799
1800 if (v == binding.textSendButton) {
1801 super.onCreateContextMenu(menu, v, menuInfo);
1802 try {
1803 java.lang.reflect.Method m = menu.getClass().getSuperclass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
1804 m.setAccessible(true);
1805 m.invoke(menu, true);
1806 } catch (Exception e) {
1807 e.printStackTrace();
1808 }
1809 Menu tmpMenu = new PopupMenu(activity, null).getMenu();
1810 activity.getMenuInflater().inflate(R.menu.fragment_conversation, tmpMenu);
1811 MenuItem attachMenu = tmpMenu.findItem(R.id.action_attach_file);
1812 for (int i = 0; i < attachMenu.getSubMenu().size(); i++) {
1813 MenuItem item = attachMenu.getSubMenu().getItem(i);
1814 MenuItem newItem = menu.add(item.getGroupId(), item.getItemId(), item.getOrder(), item.getTitle());
1815 newItem.setIcon(item.getIcon());
1816 }
1817
1818 extensions.clear();
1819 final var xmppConnectionService = activity.xmppConnectionService;
1820 final var dir = new File(xmppConnectionService.getExternalFilesDir(null), "extensions");
1821 for (File file : Files.fileTraverser().breadthFirst(dir)) {
1822 if (file.isFile() && file.canRead()) {
1823 final var dummy = new Message(conversation, null, conversation.getNextEncryption());
1824 dummy.setStatus(Message.STATUS_DUMMY);
1825 dummy.setThread(conversation.getThread());
1826 dummy.setUuid(file.getName());
1827 final var xdc = new WebxdcPage(activity, file, dummy);
1828 extensions.add(xdc);
1829 final var item = menu.add(0x1, extensions.size() - 1, 0, xdc.getName());
1830 item.setIcon(xdc.getIcon(24));
1831 }
1832 }
1833 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu, TextUtils.isEmpty(binding.textinput.getText()));
1834 return;
1835 }
1836
1837 synchronized (this.messageList) {
1838 super.onCreateContextMenu(menu, v, menuInfo);
1839 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1840 this.selectedMessage = this.messageList.get(acmi.position);
1841 populateContextMenu(menu);
1842 }
1843 }
1844
1845 private void populateContextMenu(ContextMenu menu) {
1846 final Message m = this.selectedMessage;
1847 final Transferable t = m.getTransferable();
1848 Message relevantForCorrection = m;
1849 while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1850 relevantForCorrection = relevantForCorrection.next();
1851 }
1852 if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1853
1854 if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1855 || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1856 return;
1857 }
1858
1859 if (m.getStatus() == Message.STATUS_RECEIVED
1860 && t != null
1861 && (t.getStatus() == Transferable.STATUS_CANCELLED
1862 || t.getStatus() == Transferable.STATUS_FAILED)) {
1863 return;
1864 }
1865
1866 final boolean deleted = m.isDeleted();
1867 final boolean encrypted =
1868 m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1869 || m.getEncryption() == Message.ENCRYPTION_PGP;
1870 final boolean receiving =
1871 m.getStatus() == Message.STATUS_RECEIVED
1872 && (t instanceof JingleFileTransferConnection
1873 || t instanceof HttpDownloadConnection);
1874 activity.getMenuInflater().inflate(R.menu.message_context, menu);
1875 final MenuItem reportAndBlock = menu.findItem(R.id.action_report_and_block);
1876 final MenuItem addReaction = menu.findItem(R.id.action_add_reaction);
1877 MenuItem openWith = menu.findItem(R.id.open_with);
1878 MenuItem copyMessage = menu.findItem(R.id.copy_message);
1879 MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1880 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1881 MenuItem correctMessage = menu.findItem(R.id.correct_message);
1882 MenuItem retractMessage = menu.findItem(R.id.retract_message);
1883 MenuItem moderateMessage = menu.findItem(R.id.moderate_message);
1884 MenuItem onlyThisThread = menu.findItem(R.id.only_this_thread);
1885 MenuItem shareWith = menu.findItem(R.id.share_with);
1886 MenuItem sendAgain = menu.findItem(R.id.send_again);
1887 MenuItem copyUrl = menu.findItem(R.id.copy_url);
1888 MenuItem saveAsSticker = menu.findItem(R.id.save_as_sticker);
1889 MenuItem downloadFile = menu.findItem(R.id.download_file);
1890 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1891 MenuItem blockMedia = menu.findItem(R.id.block_media);
1892 MenuItem deleteFile = menu.findItem(R.id.delete_file);
1893 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1894 onlyThisThread.setVisible(!conversation.getLockThread() && m.getThread() != null);
1895 final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(m);
1896 final boolean showError =
1897 m.getStatus() == Message.STATUS_SEND_FAILED
1898 && m.getErrorMessage() != null
1899 && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1900 final Conversational conversational = m.getConversation();
1901 if (m.getStatus() == Message.STATUS_RECEIVED && conversational instanceof Conversation c) {
1902 final XmppConnection connection = c.getAccount().getXmppConnection();
1903 if (c.isWithStranger()
1904 && m.getServerMsgId() != null
1905 && !c.isBlocked()
1906 && connection != null
1907 && connection.getFeatures().spamReporting()) {
1908 reportAndBlock.setVisible(true);
1909 }
1910 }
1911 if (!encrypted) {
1912 addReaction.setVisible(!showError && !m.isDeleted());
1913 }
1914 if (!m.isFileOrImage()
1915 && !encrypted
1916 && !m.isGeoUri()
1917 && !m.treatAsDownloadable()
1918 && !unInitiatedButKnownSize
1919 && t == null) {
1920 copyMessage.setVisible(true);
1921 }
1922 quoteMessage.setVisible(!encrypted && !showError);
1923 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1924 retryDecryption.setVisible(true);
1925 }
1926 if (!showError
1927 && relevantForCorrection.getType() == Message.TYPE_TEXT
1928 && relevantForCorrection.isEditable()
1929 && !m.isGeoUri()
1930 && m.getConversation() instanceof Conversation) {
1931 correctMessage.setVisible(true);
1932 if (!relevantForCorrection.getBody().equals("") && !relevantForCorrection.getBody().equals(" ")) retractMessage.setVisible(true);
1933 }
1934 if (relevantForCorrection.getStatus() == Message.STATUS_WAITING) {
1935 correctMessage.setVisible(true);
1936 retractMessage.setVisible(true);
1937 }
1938 if (conversation.getMode() == Conversation.MODE_MULTI && m.getServerMsgId() != null && m.getModerated() == null && conversation.getMucOptions().getSelf().getRole().ranks(MucOptions.Role.MODERATOR) && conversation.getMucOptions().hasFeature("urn:xmpp:message-moderate:0")) {
1939 moderateMessage.setVisible(true);
1940 }
1941 if ((m.isFileOrImage() && !deleted && !receiving)
1942 || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())
1943 && !unInitiatedButKnownSize
1944 && t == null) {
1945 shareWith.setVisible(true);
1946 }
1947 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1948 sendAgain.setVisible(true);
1949 }
1950 if (m.hasFileOnRemoteHost()
1951 || m.isGeoUri()
1952 || m.treatAsDownloadable()
1953 || unInitiatedButKnownSize
1954 || t instanceof HttpDownloadConnection) {
1955 copyUrl.setVisible(true);
1956 }
1957 if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1958 downloadFile.setVisible(true);
1959 downloadFile.setTitle(
1960 activity.getString(
1961 R.string.download_x_file,
1962 UIHelper.getFileDescriptionString(activity, m)));
1963 }
1964 final boolean waitingOfferedSending =
1965 m.getStatus() == Message.STATUS_WAITING
1966 || m.getStatus() == Message.STATUS_UNSEND
1967 || m.getStatus() == Message.STATUS_OFFERED;
1968 final boolean cancelable =
1969 (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1970 if (cancelable) {
1971 cancelTransmission.setVisible(true);
1972 }
1973 if (m.isFileOrImage() && !deleted && !cancelable) {
1974 final String path = m.getRelativeFilePath();
1975 if (path != null) {
1976 final var file = new File(path);
1977 if (file.canRead()) saveAsSticker.setVisible(true);
1978 blockMedia.setVisible(true);
1979 if (file.canWrite()) deleteFile.setVisible(true);
1980 deleteFile.setTitle(
1981 activity.getString(
1982 R.string.delete_x_file,
1983 UIHelper.getFileDescriptionString(activity, m)));
1984 }
1985 }
1986
1987 if (m.getFileParams() != null && !m.getFileParams().getThumbnails().isEmpty()) {
1988 // We might be showing a thumbnail worth blocking
1989 blockMedia.setVisible(true);
1990 }
1991 if (showError) {
1992 showErrorMessage.setVisible(true);
1993 }
1994 final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1995 if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m))
1996 || (mime != null && mime.startsWith("audio/"))) {
1997 openWith.setVisible(true);
1998 }
1999 }
2000 }
2001
2002 @Override
2003 public boolean onContextItemSelected(MenuItem item) {
2004 switch (item.getItemId()) {
2005 case R.id.share_with:
2006 ShareUtil.share(activity, selectedMessage);
2007 return true;
2008 case R.id.correct_message:
2009 correctMessage(selectedMessage);
2010 return true;
2011 case R.id.retract_message:
2012 new AlertDialog.Builder(activity)
2013 .setTitle(R.string.retract_message)
2014 .setMessage("Do you really want to retract this message?")
2015 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2016 Message message = selectedMessage;
2017 while (message.mergeable(message.next())) {
2018 message = message.next();
2019 }
2020 if (message.getStatus() == Message.STATUS_WAITING || message.getStatus() == Message.STATUS_OFFERED) {
2021 activity.xmppConnectionService.deleteMessage(message);
2022 return;
2023 }
2024 Element reactions = message.getReactionsEl();
2025 if (reactions != null) {
2026 final Message previousReaction = conversation.findMessageReactingTo(reactions.getAttribute("id"), null);
2027 if (previousReaction != null) reactions = previousReaction.getReactionsEl();
2028 for (Element el : reactions.getChildren()) {
2029 if (message.getRawBody().endsWith(el.getContent())) {
2030 reactions.removeChild(el);
2031 }
2032 }
2033 message.setReactions(reactions);
2034 if (previousReaction != null) {
2035 previousReaction.setReactions(reactions);
2036 activity.xmppConnectionService.updateMessage(previousReaction);
2037 }
2038 } else {
2039 message.setInReplyTo(null);
2040 message.clearPayloads();
2041 }
2042 message.setBody(" ");
2043 message.setSubject(null);
2044 message.putEdited(message.getUuid(), message.getServerMsgId());
2045 message.setServerMsgId(null);
2046 message.setUuid(UUID.randomUUID().toString());
2047 sendMessage(message);
2048 })
2049 .setNegativeButton(R.string.no, null).show();
2050 return true;
2051 case R.id.moderate_message:
2052 activity.quickEdit("Spam", (reason) -> {
2053 Message message = selectedMessage;
2054 do {
2055 activity.xmppConnectionService.moderateMessage(conversation.getAccount(), message, reason);
2056 message = message.mergeable(message.next()) ? message.next() : null;
2057 } while (message != null);
2058 return null;
2059 }, R.string.moderate_reason, false, false, true, true);
2060 return true;
2061 case R.id.copy_message:
2062 ShareUtil.copyToClipboard(activity, selectedMessage);
2063 return true;
2064 case R.id.quote_message:
2065 quoteMessage(selectedMessage);
2066 return true;
2067 case R.id.send_again:
2068 resendMessage(selectedMessage);
2069 return true;
2070 case R.id.copy_url:
2071 ShareUtil.copyUrlToClipboard(activity, selectedMessage);
2072 return true;
2073 case R.id.save_as_sticker:
2074 saveAsSticker(selectedMessage);
2075 return true;
2076 case R.id.download_file:
2077 startDownloadable(selectedMessage);
2078 return true;
2079 case R.id.cancel_transmission:
2080 cancelTransmission(selectedMessage);
2081 return true;
2082 case R.id.retry_decryption:
2083 retryDecryption(selectedMessage);
2084 return true;
2085 case R.id.block_media:
2086 new AlertDialog.Builder(activity)
2087 .setTitle(R.string.block_media)
2088 .setMessage("Do you really want to block this media in all messages?")
2089 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2090 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
2091 if (thumbs != null && !thumbs.isEmpty()) {
2092 for (Element thumb : thumbs) {
2093 Uri uri = Uri.parse(thumb.getAttribute("uri"));
2094 if (uri.getScheme().equals("cid")) {
2095 Cid cid = BobTransfer.cid(uri);
2096 if (cid == null) continue;
2097 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
2098 activity.xmppConnectionService.blockMedia(f);
2099 activity.xmppConnectionService.evictPreview(f);
2100 f.delete();
2101 }
2102 }
2103 }
2104 File f = activity.xmppConnectionService.getFileBackend().getFile(selectedMessage);
2105 activity.xmppConnectionService.blockMedia(f);
2106 activity.xmppConnectionService.getFileBackend().deleteFile(selectedMessage);
2107 activity.xmppConnectionService.evictPreview(f);
2108 activity.xmppConnectionService.updateMessage(selectedMessage, false);
2109 activity.onConversationsListItemUpdated();
2110 refresh();
2111 })
2112 .setNegativeButton(R.string.no, null).show();
2113 return true;
2114 case R.id.delete_file:
2115 deleteFile(selectedMessage);
2116 return true;
2117 case R.id.show_error_message:
2118 showErrorMessage(selectedMessage);
2119 return true;
2120 case R.id.open_with:
2121 openWith(selectedMessage);
2122 return true;
2123 case R.id.only_this_thread:
2124 conversation.setLockThread(true);
2125 backPressedLeaveSingleThread.setEnabled(true);
2126 setThread(selectedMessage.getThread());
2127 refresh();
2128 return true;
2129 case R.id.action_report_and_block:
2130 reportMessage(selectedMessage);
2131 return true;
2132 case R.id.action_add_reaction:
2133 addReaction(selectedMessage);
2134 return true;
2135 default:
2136 return onOptionsItemSelected(item);
2137 }
2138 }
2139
2140 @Override
2141 public boolean onOptionsItemSelected(final MenuItem item) {
2142 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
2143 return false;
2144 } else if (conversation == null) {
2145 return super.onOptionsItemSelected(item);
2146 }
2147 if (item.getGroupId() == 0x1) {
2148 conversation.startWebxdc(extensions.get(item.getItemId()));
2149 return true;
2150 }
2151 switch (item.getItemId()) {
2152 case R.id.encryption_choice_axolotl:
2153 case R.id.encryption_choice_pgp:
2154 case R.id.encryption_choice_none:
2155 handleEncryptionSelection(item);
2156 break;
2157 case R.id.attach_choose_picture:
2158 //case R.id.attach_take_picture:
2159 //case R.id.attach_record_video:
2160 case R.id.attach_choose_file:
2161 case R.id.attach_record_voice:
2162 case R.id.attach_location:
2163 handleAttachmentSelection(item);
2164 break;
2165 case R.id.attach_webxdc:
2166 final Intent intent = new Intent(getActivity(), WebxdcStore.class);
2167 startActivityForResult(intent, REQUEST_WEBXDC_STORE);
2168 break;
2169 case R.id.attach_subject:
2170 binding.textinputSubject.setVisibility(binding.textinputSubject.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
2171 break;
2172 case R.id.attach_schedule:
2173 scheduleMessage();
2174 break;
2175 case R.id.action_search:
2176 startSearch();
2177 break;
2178 case R.id.action_archive:
2179 activity.xmppConnectionService.archiveConversation(conversation);
2180 break;
2181 case R.id.action_contact_details:
2182 activity.switchToContactDetails(conversation.getContact());
2183 break;
2184 case R.id.action_muc_details:
2185 ConferenceDetailsActivity.open(activity, conversation);
2186 break;
2187 case R.id.action_invite:
2188 startActivityForResult(
2189 ChooseContactActivity.create(activity, conversation),
2190 REQUEST_INVITE_TO_CONVERSATION);
2191 break;
2192 case R.id.action_clear_history:
2193 clearHistoryDialog(conversation);
2194 break;
2195 case R.id.action_mute:
2196 muteConversationDialog(conversation);
2197 break;
2198 case R.id.action_unmute:
2199 unMuteConversation(conversation);
2200 break;
2201 case R.id.action_block:
2202 case R.id.action_unblock:
2203 BlockContactDialog.show(activity, conversation);
2204 break;
2205 case R.id.action_audio_call:
2206 checkPermissionAndTriggerAudioCall();
2207 break;
2208 case R.id.action_video_call:
2209 checkPermissionAndTriggerVideoCall();
2210 break;
2211 case R.id.action_ongoing_call:
2212 returnToOngoingCall();
2213 break;
2214 case R.id.action_toggle_pinned:
2215 togglePinned();
2216 break;
2217 case R.id.action_add_shortcut:
2218 addShortcut();
2219 break;
2220 case R.id.action_block_avatar:
2221 new AlertDialog.Builder(activity)
2222 .setTitle(R.string.block_media)
2223 .setMessage("Do you really want to block this avatar?")
2224 .setPositiveButton(R.string.yes, (dialog, whichButton) -> {
2225 activity.xmppConnectionService.blockMedia(activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatarFilename()));
2226 activity.xmppConnectionService.getFileBackend().getAvatarFile(conversation.getContact().getAvatarFilename()).delete();
2227 activity.avatarService().clear(conversation);
2228 conversation.getContact().setAvatar(null);
2229 activity.xmppConnectionService.updateConversationUi();
2230 })
2231 .setNegativeButton(R.string.no, null).show();
2232 case R.id.action_refresh_feature_discovery:
2233 refreshFeatureDiscovery();
2234 break;
2235 default:
2236 break;
2237 }
2238 return super.onOptionsItemSelected(item);
2239 }
2240
2241 public boolean onBackPressed() {
2242 boolean wasLocked = conversation.getLockThread();
2243 conversation.setLockThread(false);
2244 backPressedLeaveSingleThread.setEnabled(false);
2245 if (wasLocked) {
2246 setThread(null);
2247 conversation.setUserSelectedThread(false);
2248 refresh();
2249 updateThreadFromLastMessage();
2250 return true;
2251 }
2252 return false;
2253 }
2254
2255 private void startSearch() {
2256 final Intent intent = new Intent(getActivity(), SearchActivity.class);
2257 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
2258 startActivity(intent);
2259 }
2260
2261 private void scheduleMessage() {
2262 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
2263 final var datePicker = com.google.android.material.datepicker.MaterialDatePicker.Builder.datePicker()
2264 .setTitleText("Schedule Message")
2265 .setSelection(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2266 .setCalendarConstraints(
2267 new com.google.android.material.datepicker.CalendarConstraints.Builder()
2268 .setStart(com.google.android.material.datepicker.MaterialDatePicker.todayInUtcMilliseconds())
2269 .build()
2270 )
2271 .build();
2272 datePicker.addOnPositiveButtonClickListener((date) -> {
2273 final Calendar now = Calendar.getInstance();
2274 final var timePicker = new com.google.android.material.timepicker.MaterialTimePicker.Builder()
2275 .setTitleText("Schedule Message")
2276 .setHour(now.get(Calendar.HOUR_OF_DAY))
2277 .setMinute(now.get(Calendar.MINUTE))
2278 .setTimeFormat(android.text.format.DateFormat.is24HourFormat(activity) ? com.google.android.material.timepicker.TimeFormat.CLOCK_24H : com.google.android.material.timepicker.TimeFormat.CLOCK_12H)
2279 .build();
2280 timePicker.addOnPositiveButtonClickListener((v2) -> {
2281 final var dateCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
2282 dateCal.setTimeInMillis(date);
2283 final var time = Calendar.getInstance();
2284 time.set(dateCal.get(Calendar.YEAR), dateCal.get(Calendar.MONTH), dateCal.get(Calendar.DAY_OF_MONTH), timePicker.getHour(), timePicker.getMinute(), 0);
2285 final long timestamp = time.getTimeInMillis();
2286 sendMessage(timestamp);
2287 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": scheduled message for " + timestamp);
2288 });
2289 timePicker.show(activity.getSupportFragmentManager(), "schedulMessageTime");
2290 });
2291 datePicker.show(activity.getSupportFragmentManager(), "schedulMessageDate");
2292 }
2293 }
2294
2295 private void returnToOngoingCall() {
2296 final Optional<OngoingRtpSession> ongoingRtpSession =
2297 activity.xmppConnectionService
2298 .getJingleConnectionManager()
2299 .getOngoingRtpConnection(conversation.getContact());
2300 if (ongoingRtpSession.isPresent()) {
2301 final OngoingRtpSession id = ongoingRtpSession.get();
2302 final Intent intent = new Intent(getActivity(), RtpSessionActivity.class);
2303 intent.setAction(Intent.ACTION_VIEW);
2304 intent.putExtra(
2305 RtpSessionActivity.EXTRA_ACCOUNT,
2306 id.getAccount().getJid().asBareJid().toEscapedString());
2307 intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
2308 if (id instanceof AbstractJingleConnection) {
2309 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
2310 startActivity(intent);
2311 } else if (id instanceof JingleConnectionManager.RtpSessionProposal proposal) {
2312 if (Media.audioOnly(proposal.media)) {
2313 intent.putExtra(
2314 RtpSessionActivity.EXTRA_LAST_ACTION,
2315 RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2316 } else {
2317 intent.putExtra(
2318 RtpSessionActivity.EXTRA_LAST_ACTION,
2319 RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2320 }
2321 intent.putExtra(RtpSessionActivity.EXTRA_PROPOSED_SESSION_ID, proposal.sessionId);
2322 startActivity(intent);
2323 }
2324 }
2325 }
2326
2327 private void refreshFeatureDiscovery() {
2328 Set<Map.Entry<String, Presence>> presences = conversation.getContact().getPresences().getPresencesMap().entrySet();
2329 if (presences.isEmpty()) {
2330 presences = new HashSet<>();
2331 presences.add(new AbstractMap.SimpleEntry("", null));
2332 }
2333 for (Map.Entry<String, Presence> entry : presences) {
2334 Jid jid = conversation.getContact().getJid();
2335 if (!entry.getKey().equals("")) jid = jid.withResource(entry.getKey());
2336 activity.xmppConnectionService.fetchCaps(conversation.getAccount(), jid, entry.getValue(), () -> {
2337 if (activity == null) return;
2338 activity.runOnUiThread(() -> {
2339 refresh();
2340 refreshCommands(true);
2341 });
2342 });
2343 }
2344 }
2345
2346 private void addShortcut() {
2347 ShortcutInfoCompat info;
2348 if (conversation.getMode() == Conversation.MODE_MULTI) {
2349 info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getMucOptions());
2350 } else {
2351 info = activity.xmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getContact());
2352 }
2353 ShortcutManagerCompat.requestPinShortcut(activity, info, null);
2354 }
2355
2356 private void togglePinned() {
2357 final boolean pinned =
2358 conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
2359 conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
2360 activity.xmppConnectionService.updateConversation(conversation);
2361 activity.invalidateOptionsMenu();
2362 }
2363
2364 private void checkPermissionAndTriggerAudioCall() {
2365 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2366 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2367 return;
2368 }
2369 final List<String> permissions;
2370 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2371 permissions =
2372 Arrays.asList(
2373 Manifest.permission.RECORD_AUDIO,
2374 Manifest.permission.BLUETOOTH_CONNECT);
2375 } else {
2376 permissions = Collections.singletonList(Manifest.permission.RECORD_AUDIO);
2377 }
2378 if (hasPermissions(REQUEST_START_AUDIO_CALL, permissions)) {
2379 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2380 }
2381 }
2382
2383 private void checkPermissionAndTriggerVideoCall() {
2384 if (activity.mUseTor || conversation.getAccount().isOnion()) {
2385 Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
2386 return;
2387 }
2388 final List<String> permissions;
2389 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
2390 permissions =
2391 Arrays.asList(
2392 Manifest.permission.RECORD_AUDIO,
2393 Manifest.permission.CAMERA,
2394 Manifest.permission.BLUETOOTH_CONNECT);
2395 } else {
2396 permissions =
2397 Arrays.asList(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA);
2398 }
2399 if (hasPermissions(REQUEST_START_VIDEO_CALL, permissions)) {
2400 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2401 }
2402 }
2403
2404 private void triggerRtpSession(final String action) {
2405 if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
2406 Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG)
2407 .show();
2408 return;
2409 }
2410 final Account account = conversation.getAccount();
2411 if (account.setOption(Account.OPTION_SOFT_DISABLED, false)) {
2412 activity.xmppConnectionService.updateAccount(account);
2413 }
2414 final Contact contact = conversation.getContact();
2415 if (Config.USE_JINGLE_MESSAGE_INIT && RtpCapability.jmiSupport(contact)) {
2416 triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
2417 } else {
2418 final RtpCapability.Capability capability;
2419 if (action.equals(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL)) {
2420 capability = RtpCapability.Capability.VIDEO;
2421 } else {
2422 capability = RtpCapability.Capability.AUDIO;
2423 }
2424 PresenceSelector.selectFullJidForDirectRtpConnection(
2425 activity,
2426 contact,
2427 capability,
2428 fullJid -> {
2429 triggerRtpSession(contact.getAccount(), fullJid, action);
2430 });
2431 }
2432 }
2433
2434 private void triggerRtpSession(final Account account, final Jid with, final String action) {
2435 CallIntegrationConnectionService.placeCall(activity.xmppConnectionService, account,with,RtpSessionActivity.actionToMedia(action));
2436 }
2437
2438 private void handleAttachmentSelection(MenuItem item) {
2439 switch (item.getItemId()) {
2440 case R.id.attach_choose_picture:
2441 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
2442 break;
2443 /*case R.id.attach_take_picture:
2444 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
2445 break;
2446 case R.id.attach_record_video:
2447 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
2448 break;*/
2449 case R.id.attach_choose_file:
2450 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
2451 break;
2452 case R.id.attach_record_voice:
2453 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
2454 break;
2455 case R.id.attach_location:
2456 attachFile(ATTACHMENT_CHOICE_LOCATION);
2457 break;
2458 }
2459 }
2460
2461 private void handleEncryptionSelection(MenuItem item) {
2462 if (conversation == null) {
2463 return;
2464 }
2465 final boolean updated;
2466 switch (item.getItemId()) {
2467 case R.id.encryption_choice_none:
2468 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2469 item.setChecked(true);
2470 break;
2471 case R.id.encryption_choice_pgp:
2472 if (activity.hasPgp()) {
2473 if (conversation.getAccount().getPgpSignature() != null) {
2474 updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
2475 item.setChecked(true);
2476 } else {
2477 updated = false;
2478 activity.announcePgp(
2479 conversation.getAccount(),
2480 conversation,
2481 null,
2482 activity.onOpenPGPKeyPublished);
2483 }
2484 } else {
2485 activity.showInstallPgpDialog();
2486 updated = false;
2487 }
2488 break;
2489 case R.id.encryption_choice_axolotl:
2490 Log.d(
2491 Config.LOGTAG,
2492 AxolotlService.getLogprefix(conversation.getAccount())
2493 + "Enabled axolotl for Contact "
2494 + conversation.getContact().getJid());
2495 updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
2496 item.setChecked(true);
2497 break;
2498 default:
2499 updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2500 break;
2501 }
2502 if (updated) {
2503 activity.xmppConnectionService.updateConversation(conversation);
2504 }
2505 updateChatMsgHint();
2506 getActivity().invalidateOptionsMenu();
2507 activity.refreshUi();
2508 }
2509
2510 public void attachFile(final int attachmentChoice) {
2511 attachFile(attachmentChoice, true);
2512 }
2513
2514 public void attachFile(final int attachmentChoice, final boolean updateRecentlyUsed) {
2515 if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
2516 if (!hasPermissions(
2517 attachmentChoice,
2518 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2519 Manifest.permission.RECORD_AUDIO)) {
2520 return;
2521 }
2522 } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO
2523 || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
2524 if (!hasPermissions(
2525 attachmentChoice,
2526 Manifest.permission.WRITE_EXTERNAL_STORAGE,
2527 Manifest.permission.CAMERA)) {
2528 return;
2529 }
2530 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
2531 if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2532 return;
2533 }
2534 }
2535 if (updateRecentlyUsed) {
2536 storeRecentlyUsedQuickAction(attachmentChoice);
2537 }
2538 final int encryption = conversation.getNextEncryption();
2539 final int mode = conversation.getMode();
2540 if (encryption == Message.ENCRYPTION_PGP) {
2541 if (activity.hasPgp()) {
2542 if (mode == Conversation.MODE_SINGLE
2543 && conversation.getContact().getPgpKeyId() != 0) {
2544 activity.xmppConnectionService
2545 .getPgpEngine()
2546 .hasKey(
2547 conversation.getContact(),
2548 new UiCallback<Contact>() {
2549
2550 @Override
2551 public void userInputRequired(
2552 PendingIntent pi, Contact contact) {
2553 startPendingIntent(pi, attachmentChoice);
2554 }
2555
2556 @Override
2557 public void success(Contact contact) {
2558 invokeAttachFileIntent(attachmentChoice);
2559 }
2560
2561 @Override
2562 public void error(int error, Contact contact) {
2563 activity.replaceToast(getString(error));
2564 }
2565 });
2566 } else if (mode == Conversation.MODE_MULTI
2567 && conversation.getMucOptions().pgpKeysInUse()) {
2568 if (!conversation.getMucOptions().everybodyHasKeys()) {
2569 Toast warning =
2570 Toast.makeText(
2571 getActivity(),
2572 R.string.missing_public_keys,
2573 Toast.LENGTH_LONG);
2574 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2575 warning.show();
2576 }
2577 invokeAttachFileIntent(attachmentChoice);
2578 } else {
2579 showNoPGPKeyDialog(
2580 false,
2581 (dialog, which) -> {
2582 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2583 activity.xmppConnectionService.updateConversation(conversation);
2584 invokeAttachFileIntent(attachmentChoice);
2585 });
2586 }
2587 } else {
2588 activity.showInstallPgpDialog();
2589 }
2590 } else {
2591 invokeAttachFileIntent(attachmentChoice);
2592 }
2593 }
2594
2595 private void storeRecentlyUsedQuickAction(final int attachmentChoice) {
2596 try {
2597 activity.getPreferences()
2598 .edit()
2599 .putString(
2600 RECENTLY_USED_QUICK_ACTION,
2601 SendButtonAction.of(attachmentChoice).toString())
2602 .apply();
2603 } catch (IllegalArgumentException e) {
2604 // just do not save
2605 }
2606 }
2607
2608 @Override
2609 public void onRequestPermissionsResult(
2610 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2611 final PermissionUtils.PermissionResult permissionResult =
2612 PermissionUtils.removeBluetoothConnect(permissions, grantResults);
2613 if (grantResults.length > 0) {
2614 if (allGranted(permissionResult.grantResults)) {
2615 switch (requestCode) {
2616 case REQUEST_START_DOWNLOAD:
2617 if (this.mPendingDownloadableMessage != null) {
2618 startDownloadable(this.mPendingDownloadableMessage);
2619 }
2620 break;
2621 case REQUEST_ADD_EDITOR_CONTENT:
2622 if (this.mPendingEditorContent != null) {
2623 attachEditorContentToConversation(this.mPendingEditorContent);
2624 }
2625 break;
2626 case REQUEST_COMMIT_ATTACHMENTS:
2627 commitAttachments();
2628 break;
2629 case REQUEST_START_AUDIO_CALL:
2630 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
2631 break;
2632 case REQUEST_START_VIDEO_CALL:
2633 triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
2634 break;
2635 default:
2636 attachFile(requestCode);
2637 break;
2638 }
2639 } else {
2640 @StringRes int res;
2641 String firstDenied =
2642 getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
2643 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
2644 res = R.string.no_microphone_permission;
2645 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
2646 res = R.string.no_camera_permission;
2647 } else {
2648 res = R.string.no_storage_permission;
2649 }
2650 Toast.makeText(
2651 getActivity(),
2652 getString(res, getString(R.string.app_name)),
2653 Toast.LENGTH_SHORT)
2654 .show();
2655 }
2656 }
2657 if (writeGranted(grantResults, permissions)) {
2658 if (activity != null && activity.xmppConnectionService != null) {
2659 activity.xmppConnectionService.getDrawableCache().evictAll();
2660 activity.xmppConnectionService.restartFileObserver();
2661 }
2662 refresh();
2663 }
2664 if (cameraGranted(grantResults, permissions) || audioGranted(grantResults, permissions)) {
2665 XmppConnectionService.toggleForegroundService(activity);
2666 }
2667 }
2668
2669 public void startDownloadable(Message message) {
2670 if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2671 this.mPendingDownloadableMessage = message;
2672 return;
2673 }
2674 Transferable transferable = message.getTransferable();
2675 if (transferable != null) {
2676 if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
2677 createNewConnection(message);
2678 return;
2679 }
2680 if (!transferable.start()) {
2681 Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
2682 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2683 .show();
2684 }
2685 } else if (message.treatAsDownloadable()
2686 || message.hasFileOnRemoteHost()
2687 || MessageUtils.unInitiatedButKnownSize(message)) {
2688 createNewConnection(message);
2689 } else {
2690 Log.d(
2691 Config.LOGTAG,
2692 message.getConversation().getAccount() + ": unable to start downloadable");
2693 }
2694 }
2695
2696 private void createNewConnection(final Message message) {
2697 if (!activity.xmppConnectionService.hasInternetConnection()) {
2698 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT)
2699 .show();
2700 return;
2701 }
2702 if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
2703 try {
2704 BobTransfer transfer = new BobTransfer.ForMessage(message, activity.xmppConnectionService);
2705 message.setTransferable(transfer);
2706 transfer.start();
2707 } catch (URISyntaxException e) {
2708 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
2709 }
2710 } else {
2711 activity.xmppConnectionService
2712 .getHttpConnectionManager()
2713 .createNewDownloadConnection(message, true);
2714 }
2715 }
2716
2717 @SuppressLint("InflateParams")
2718 protected void clearHistoryDialog(final Conversation conversation) {
2719 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2720 builder.setTitle(R.string.clear_conversation_history);
2721 final View dialogView =
2722 requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
2723 final CheckBox endConversationCheckBox =
2724 dialogView.findViewById(R.id.end_conversation_checkbox);
2725 builder.setView(dialogView);
2726 builder.setNegativeButton(getString(R.string.cancel), null);
2727 builder.setPositiveButton(
2728 getString(R.string.confirm),
2729 (dialog, which) -> {
2730 this.activity.xmppConnectionService.clearConversationHistory(conversation);
2731 if (endConversationCheckBox.isChecked()) {
2732 this.activity.xmppConnectionService.archiveConversation(conversation);
2733 this.activity.onConversationArchived(conversation);
2734 } else {
2735 activity.onConversationsListItemUpdated();
2736 refresh();
2737 }
2738 });
2739 builder.create().show();
2740 }
2741
2742 protected void muteConversationDialog(final Conversation conversation) {
2743 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2744 builder.setTitle(R.string.disable_notifications);
2745 final int[] durations = activity.getResources().getIntArray(R.array.mute_options_durations);
2746 final CharSequence[] labels = new CharSequence[durations.length];
2747 for (int i = 0; i < durations.length; ++i) {
2748 if (durations[i] == -1) {
2749 labels[i] = activity.getString(R.string.until_further_notice);
2750 } else {
2751 labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
2752 }
2753 }
2754 builder.setItems(
2755 labels,
2756 (dialog, which) -> {
2757 final long till;
2758 if (durations[which] == -1) {
2759 till = Long.MAX_VALUE;
2760 } else {
2761 till = System.currentTimeMillis() + (durations[which] * 1000L);
2762 }
2763 conversation.setMutedTill(till);
2764 activity.xmppConnectionService.updateConversation(conversation);
2765 activity.onConversationsListItemUpdated();
2766 refresh();
2767 activity.invalidateOptionsMenu();
2768 });
2769 builder.create().show();
2770 }
2771
2772 private boolean hasPermissions(int requestCode, List<String> permissions) {
2773 final List<String> missingPermissions = new ArrayList<>();
2774 for (String permission : permissions) {
2775 if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU || Config.ONLY_INTERNAL_STORAGE) && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
2776 continue;
2777 }
2778 if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
2779 missingPermissions.add(permission);
2780 }
2781 }
2782 if (missingPermissions.size() == 0) {
2783 return true;
2784 } else {
2785 requestPermissions(
2786 missingPermissions.toArray(new String[0]),
2787 requestCode);
2788 return false;
2789 }
2790 }
2791
2792 private boolean hasPermissions(int requestCode, String... permissions) {
2793 return hasPermissions(requestCode, ImmutableList.copyOf(permissions));
2794 }
2795
2796 public void unMuteConversation(final Conversation conversation) {
2797 conversation.setMutedTill(0);
2798 this.activity.xmppConnectionService.updateConversation(conversation);
2799 this.activity.onConversationsListItemUpdated();
2800 refresh();
2801 this.activity.invalidateOptionsMenu();
2802 }
2803
2804 protected void invokeAttachFileIntent(final int attachmentChoice) {
2805 Intent intent = new Intent();
2806
2807 final var takePhotoIntent = new Intent();
2808 final Uri takePhotoUri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
2809 pendingTakePhotoUri.push(takePhotoUri);
2810 takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePhotoUri);
2811 takePhotoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
2812 takePhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2813 takePhotoIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
2814
2815 final var takeVideoIntent = new Intent();
2816 takeVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
2817
2818 switch (attachmentChoice) {
2819 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
2820 intent.setAction(Intent.ACTION_GET_CONTENT);
2821 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2822 intent.setType("*/*");
2823 intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"image/*", "video/*"});
2824 intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
2825 intent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent, takeVideoIntent });
2826 break;
2827 case ATTACHMENT_CHOICE_RECORD_VIDEO:
2828 intent = takeVideoIntent;
2829 break;
2830 case ATTACHMENT_CHOICE_TAKE_PHOTO:
2831 intent = takePhotoIntent;
2832 break;
2833 case ATTACHMENT_CHOICE_CHOOSE_FILE:
2834 intent.setAction(Intent.ACTION_GET_CONTENT);
2835 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
2836 intent.setType("*/*");
2837 intent.addCategory(Intent.CATEGORY_OPENABLE);
2838 intent = Intent.createChooser(intent, getString(R.string.perform_action_with));
2839 break;
2840 case ATTACHMENT_CHOICE_RECORD_VOICE:
2841 intent = new Intent(getActivity(), RecordingActivity.class);
2842 break;
2843 case ATTACHMENT_CHOICE_LOCATION:
2844 intent = GeoHelper.getFetchIntent(activity);
2845 break;
2846 }
2847 final Context context = getActivity();
2848 if (context == null) {
2849 return;
2850 }
2851 try {
2852 startActivityForResult(intent, attachmentChoice);
2853 } catch (final ActivityNotFoundException e) {
2854 Toast.makeText(context, R.string.no_application_found, Toast.LENGTH_LONG).show();
2855 }
2856 }
2857
2858 @Override
2859 public void onResume() {
2860 super.onResume();
2861 binding.messagesView.post(this::fireReadEvent);
2862 }
2863
2864 private void fireReadEvent() {
2865 if (activity != null && this.conversation != null) {
2866 String uuid = getLastVisibleMessageUuid();
2867 if (uuid != null) {
2868 activity.onConversationRead(this.conversation, uuid);
2869 }
2870 }
2871 }
2872
2873 private void newSubThread() {
2874 Element oldThread = conversation.getThread();
2875 Element thread = new Element("thread", "jabber:client");
2876 thread.setContent(UUID.randomUUID().toString());
2877 if (oldThread != null) thread.setAttribute("parent", oldThread.getContent());
2878 setThread(thread);
2879 }
2880
2881 private void newThread() {
2882 Element thread = new Element("thread", "jabber:client");
2883 thread.setContent(UUID.randomUUID().toString());
2884 setThread(thread);
2885 }
2886
2887 private void updateThreadFromLastMessage() {
2888 if (this.conversation != null && !this.conversation.getUserSelectedThread() && TextUtils.isEmpty(binding.textinput.getText())) {
2889 Message message = getLastVisibleMessage();
2890 if (message == null) {
2891 newThread();
2892 } else {
2893 if (conversation.getMode() == Conversation.MODE_MULTI) {
2894 if (activity == null || activity.xmppConnectionService == null) return;
2895 if (message.getStatus() < Message.STATUS_SEND) {
2896 if (!activity.xmppConnectionService.getBooleanPreference("follow_thread_in_channel", R.bool.follow_thread_in_channel)) return;
2897 }
2898 }
2899
2900 setThread(message.getThread());
2901 }
2902 }
2903 }
2904
2905 private String getLastVisibleMessageUuid() {
2906 Message message = getLastVisibleMessage();
2907 return message == null ? null : message.getUuid();
2908 }
2909
2910 private Message getLastVisibleMessage() {
2911 if (binding == null) {
2912 return null;
2913 }
2914 synchronized (this.messageList) {
2915 int pos = binding.messagesView.getLastVisiblePosition();
2916 if (pos >= 0) {
2917 Message message = null;
2918 for (int i = pos; i >= 0; --i) {
2919 try {
2920 message = (Message) binding.messagesView.getItemAtPosition(i);
2921 } catch (IndexOutOfBoundsException e) {
2922 // should not happen if we synchronize properly. however if that fails we
2923 // just gonna try item -1
2924 continue;
2925 }
2926 if (message.getType() != Message.TYPE_STATUS) {
2927 break;
2928 }
2929 }
2930 if (message != null) {
2931 while (message.next() != null && message.next().wasMergedIntoPrevious(activity == null ? null : activity.xmppConnectionService)) {
2932 message = message.next();
2933 }
2934 return message;
2935 }
2936 }
2937 }
2938 return null;
2939 }
2940
2941 public void jumpTo(final Message message) {
2942 if (message.getUuid() == null) return;
2943 for (int i = 0; i < messageList.size(); i++) {
2944 final var m = messageList.get(i);
2945 if (m == null) continue;
2946 if (message.getUuid().equals(m.getUuid())) {
2947 binding.messagesView.setSelection(i);
2948 return;
2949 }
2950 }
2951 }
2952
2953 private void openWith(final Message message) {
2954 if (message.isGeoUri()) {
2955 GeoHelper.view(getActivity(), message);
2956 } else {
2957 final DownloadableFile file =
2958 activity.xmppConnectionService.getFileBackend().getFile(message);
2959 ViewUtil.view(activity, file);
2960 }
2961 }
2962
2963 private void addReaction(final Message message) {
2964 activity.addReaction(message, reactions -> activity.xmppConnectionService.sendReactions(message, reactions));
2965 }
2966
2967 private void reportMessage(final Message message) {
2968 BlockContactDialog.show(activity, conversation.getContact(), message.getServerMsgId());
2969 }
2970
2971 private void showErrorMessage(final Message message) {
2972 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
2973 builder.setTitle(R.string.error_message);
2974 final String errorMessage = message.getErrorMessage();
2975 final String[] errorMessageParts =
2976 errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
2977 final String displayError;
2978 if (errorMessageParts.length == 2) {
2979 displayError = errorMessageParts[1];
2980 } else {
2981 displayError = errorMessage;
2982 }
2983 builder.setMessage(displayError);
2984 builder.setNegativeButton(
2985 R.string.copy_to_clipboard,
2986 (dialog, which) -> {
2987 activity.copyTextToClipboard(displayError, R.string.error_message);
2988 Toast.makeText(
2989 activity,
2990 R.string.error_message_copied_to_clipboard,
2991 Toast.LENGTH_SHORT)
2992 .show();
2993 });
2994 builder.setPositiveButton(R.string.confirm, null);
2995 builder.create().show();
2996 }
2997
2998 public boolean onInlineImageLongClicked(Cid cid) {
2999 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3000 if (f == null) return false;
3001
3002 saveAsSticker(f, null);
3003 return true;
3004 }
3005
3006 private void saveAsSticker(final Message m) {
3007 String existingName = m.getFileParams() != null && m.getFileParams().getName() != null ? m.getFileParams().getName() : "";
3008 existingName = existingName.lastIndexOf(".") == -1 ? existingName : existingName.substring(0, existingName.lastIndexOf("."));
3009 saveAsSticker(activity.xmppConnectionService.getFileBackend().getFile(m), existingName);
3010 }
3011
3012 private void saveAsSticker(final File file, final String name) {
3013 savingAsSticker = file;
3014
3015 Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
3016 intent.addCategory(Intent.CATEGORY_OPENABLE);
3017 intent.setType(MimeUtils.guessMimeTypeFromUri(activity, activity.xmppConnectionService.getFileBackend().getUriForFile(activity, file)));
3018 intent.putExtra(Intent.EXTRA_TITLE, name);
3019
3020 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3021 final String dir = p.getString("sticker_directory", "Stickers");
3022 if (dir.startsWith("content://")) {
3023 intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(dir));
3024 } else {
3025 new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + dir + "/User Pack").mkdirs();
3026 Uri uri;
3027 if (Build.VERSION.SDK_INT >= 29) {
3028 Intent tmp = ((StorageManager) activity.getSystemService(Context.STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
3029 uri = tmp.getParcelableExtra("android.provider.extra.INITIAL_URI");
3030 uri = Uri.parse(uri.toString().replace("/root/", "/document/") + "%3APictures%2F" + dir);
3031 } else {
3032 uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3APictures%2F" + dir);
3033 }
3034 intent.putExtra("android.provider.extra.INITIAL_URI", uri);
3035 intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
3036 }
3037
3038 Toast.makeText(activity, "Choose a sticker pack to add this sticker to", Toast.LENGTH_SHORT).show();
3039 startActivityForResult(Intent.createChooser(intent, "Choose sticker pack"), REQUEST_SAVE_STICKER);
3040 }
3041
3042 private void deleteFile(final Message message) {
3043 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
3044 builder.setNegativeButton(R.string.cancel, null);
3045 builder.setTitle(R.string.delete_file_dialog);
3046 builder.setMessage(R.string.delete_file_dialog_msg);
3047 builder.setPositiveButton(
3048 R.string.confirm,
3049 (dialog, which) -> {
3050 List<Element> thumbs = selectedMessage.getFileParams() != null ? selectedMessage.getFileParams().getThumbnails() : null;
3051 if (thumbs != null && !thumbs.isEmpty()) {
3052 for (Element thumb : thumbs) {
3053 Uri uri = Uri.parse(thumb.getAttribute("uri"));
3054 if (uri.getScheme().equals("cid")) {
3055 Cid cid = BobTransfer.cid(uri);
3056 if (cid == null) continue;
3057 DownloadableFile f = activity.xmppConnectionService.getFileForCid(cid);
3058 activity.xmppConnectionService.evictPreview(f);
3059 f.delete();
3060 }
3061 }
3062 }
3063 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
3064 activity.xmppConnectionService.evictPreview(activity.xmppConnectionService.getFileBackend().getFile(message));
3065 activity.xmppConnectionService.updateMessage(message, false);
3066 activity.onConversationsListItemUpdated();
3067 refresh();
3068 }
3069 });
3070 builder.create().show();
3071 }
3072
3073 private void resendMessage(final Message message) {
3074 if (message.isFileOrImage()) {
3075 if (!(message.getConversation() instanceof Conversation)) {
3076 return;
3077 }
3078 final Conversation conversation = (Conversation) message.getConversation();
3079 final DownloadableFile file =
3080 activity.xmppConnectionService.getFileBackend().getFile(message);
3081 if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
3082 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
3083 if (!message.hasFileOnRemoteHost()
3084 && xmppConnection != null
3085 && conversation.getMode() == Conversational.MODE_SINGLE
3086 && !xmppConnection
3087 .getFeatures()
3088 .httpUpload(message.getFileParams().getSize())) {
3089 activity.selectPresence(
3090 conversation,
3091 () -> {
3092 message.setCounterpart(conversation.getNextCounterpart());
3093 activity.xmppConnectionService.resendFailedMessages(message);
3094 new Handler()
3095 .post(
3096 () -> {
3097 int size = messageList.size();
3098 this.binding.messagesView.setSelection(
3099 size - 1);
3100 });
3101 });
3102 return;
3103 }
3104 } else if (!Compatibility.hasStoragePermission(getActivity())) {
3105 Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
3106 return;
3107 } else {
3108 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
3109 message.setDeleted(true);
3110 activity.xmppConnectionService.updateMessage(message, false);
3111 activity.onConversationsListItemUpdated();
3112 refresh();
3113 return;
3114 }
3115 }
3116 activity.xmppConnectionService.resendFailedMessages(message);
3117 new Handler()
3118 .post(
3119 () -> {
3120 int size = messageList.size();
3121 this.binding.messagesView.setSelection(size - 1);
3122 });
3123 }
3124
3125 private void cancelTransmission(Message message) {
3126 Transferable transferable = message.getTransferable();
3127 if (transferable != null) {
3128 transferable.cancel();
3129 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
3130 activity.xmppConnectionService.markMessage(
3131 message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
3132 }
3133 }
3134
3135 private void retryDecryption(Message message) {
3136 message.setEncryption(Message.ENCRYPTION_PGP);
3137 activity.onConversationsListItemUpdated();
3138 refresh();
3139 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
3140 }
3141
3142 public void privateMessageWith(final Jid counterpart) {
3143 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
3144 activity.xmppConnectionService.sendChatState(conversation);
3145 }
3146 this.binding.textinput.setText("");
3147 this.conversation.setNextCounterpart(counterpart);
3148 updateChatMsgHint();
3149 updateSendButton();
3150 updateEditablity();
3151 }
3152
3153 private void correctMessage(Message message) {
3154 while (message.mergeable(message.next())) {
3155 message = message.next();
3156 }
3157 setThread(message.getThread());
3158 conversation.setUserSelectedThread(true);
3159 this.conversation.setCorrectingMessage(message);
3160 final Editable editable = binding.textinput.getText();
3161 this.conversation.setDraftMessage(editable.toString());
3162 this.binding.textinput.setText("");
3163 this.binding.textinput.append(message.getBody(true));
3164 if (message.getSubject() != null && message.getSubject().length() > 0) {
3165 this.binding.textinputSubject.setText(message.getSubject());
3166 this.binding.textinputSubject.setVisibility(View.VISIBLE);
3167 }
3168 setupReply(message.getInReplyTo());
3169 }
3170
3171 private void highlightInConference(String nick) {
3172 final Editable editable = this.binding.textinput.getText();
3173 String oldString = editable.toString().trim();
3174 final int pos = this.binding.textinput.getSelectionStart();
3175 if (oldString.isEmpty() || pos == 0) {
3176 editable.insert(0, nick + ": ");
3177 } else {
3178 final char before = editable.charAt(pos - 1);
3179 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
3180 if (before == '\n') {
3181 editable.insert(pos, nick + ": ");
3182 } else {
3183 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
3184 if (NickValidityChecker.check(
3185 conversation,
3186 Arrays.asList(
3187 editable.subSequence(0, pos - 2).toString().split(", ")))) {
3188 editable.insert(pos - 2, ", " + nick);
3189 return;
3190 }
3191 }
3192 editable.insert(
3193 pos,
3194 (Character.isWhitespace(before) ? "" : " ")
3195 + nick
3196 + (Character.isWhitespace(after) ? "" : " "));
3197 if (Character.isWhitespace(after)) {
3198 this.binding.textinput.setSelection(
3199 this.binding.textinput.getSelectionStart() + 1);
3200 }
3201 }
3202 }
3203 }
3204
3205 @Override
3206 public void startActivityForResult(Intent intent, int requestCode) {
3207 final Activity activity = getActivity();
3208 if (activity instanceof ConversationsActivity) {
3209 ((ConversationsActivity) activity).clearPendingViewIntent();
3210 }
3211 super.startActivityForResult(intent, requestCode);
3212 }
3213
3214 @Override
3215 public void onSaveInstanceState(@NonNull Bundle outState) {
3216 super.onSaveInstanceState(outState);
3217 if (conversation != null) {
3218 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
3219 outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
3220 final Uri uri = pendingTakePhotoUri.peek();
3221 if (uri != null) {
3222 outState.putString(STATE_PHOTO_URI, uri.toString());
3223 }
3224 final ScrollState scrollState = getScrollPosition();
3225 if (scrollState != null) {
3226 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
3227 }
3228 final ArrayList<Attachment> attachments =
3229 mediaPreviewAdapter == null
3230 ? new ArrayList<>()
3231 : mediaPreviewAdapter.getAttachments();
3232 if (attachments.size() > 0) {
3233 outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
3234 }
3235 }
3236 }
3237
3238 @Override
3239 public void onActivityCreated(Bundle savedInstanceState) {
3240 super.onActivityCreated(savedInstanceState);
3241 if (savedInstanceState == null) {
3242 return;
3243 }
3244 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
3245 ArrayList<Attachment> attachments =
3246 savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
3247 pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
3248 if (uuid != null) {
3249 QuickLoader.set(uuid);
3250 this.pendingConversationsUuid.push(uuid);
3251 if (attachments != null && attachments.size() > 0) {
3252 this.pendingMediaPreviews.push(attachments);
3253 }
3254 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
3255 if (takePhotoUri != null) {
3256 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
3257 }
3258 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
3259 }
3260 }
3261
3262 @Override
3263 public void onStart() {
3264 super.onStart();
3265 if (this.reInitRequiredOnStart && this.conversation != null) {
3266 final Bundle extras = pendingExtras.pop();
3267 reInit(this.conversation, extras != null);
3268 if (extras != null) {
3269 processExtras(extras);
3270 }
3271 } else if (conversation == null
3272 && activity != null
3273 && activity.xmppConnectionService != null) {
3274 final String uuid = pendingConversationsUuid.pop();
3275 Log.d(
3276 Config.LOGTAG,
3277 "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid="
3278 + uuid);
3279 if (uuid != null) {
3280 findAndReInitByUuidOrArchive(uuid);
3281 }
3282 }
3283 }
3284
3285 @Override
3286 public void onStop() {
3287 super.onStop();
3288 final Activity activity = getActivity();
3289 messageListAdapter.unregisterListenerInAudioPlayer();
3290 if (activity == null || !activity.isChangingConfigurations()) {
3291 hideSoftKeyboard(activity);
3292 messageListAdapter.stopAudioPlayer();
3293 }
3294 if (this.conversation != null) {
3295 final String msg = this.binding.textinput.getText().toString();
3296 storeNextMessage(msg);
3297 updateChatState(this.conversation, msg);
3298 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
3299 }
3300 this.reInitRequiredOnStart = true;
3301 }
3302
3303 private void updateChatState(final Conversation conversation, final String msg) {
3304 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
3305 Account.State status = conversation.getAccount().getStatus();
3306 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
3307 activity.xmppConnectionService.sendChatState(conversation);
3308 }
3309 }
3310
3311 private void saveMessageDraftStopAudioPlayer() {
3312 final Conversation previousConversation = this.conversation;
3313 if (this.activity == null || this.binding == null || previousConversation == null) {
3314 return;
3315 }
3316 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
3317 final String msg = this.binding.textinput.getText().toString();
3318 storeNextMessage(msg);
3319 updateChatState(this.conversation, msg);
3320 messageListAdapter.stopAudioPlayer();
3321 mediaPreviewAdapter.clearPreviews();
3322 toggleInputMethod();
3323 }
3324
3325 public void reInit(final Conversation conversation, final Bundle extras) {
3326 QuickLoader.set(conversation.getUuid());
3327 final boolean changedConversation = this.conversation != conversation;
3328 if (changedConversation) {
3329 this.saveMessageDraftStopAudioPlayer();
3330 }
3331 this.clearPending();
3332 if (this.reInit(conversation, extras != null)) {
3333 if (extras != null) {
3334 processExtras(extras);
3335 }
3336 this.reInitRequiredOnStart = false;
3337 } else {
3338 this.reInitRequiredOnStart = true;
3339 pendingExtras.push(extras);
3340 }
3341 resetUnreadMessagesCount();
3342 }
3343
3344 private void reInit(Conversation conversation) {
3345 reInit(conversation, false);
3346 }
3347
3348 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
3349 if (conversation == null) {
3350 return false;
3351 }
3352 final Conversation originalConversation = this.conversation;
3353 this.conversation = conversation;
3354 // once we set the conversation all is good and it will automatically do the right thing in
3355 // onStart()
3356 if (this.activity == null || this.binding == null) {
3357 return false;
3358 }
3359
3360 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3361 activity.onConversationArchived(this.conversation);
3362 return false;
3363 }
3364
3365 final var cursord = activity.getDrawable(R.drawable.cursor_on_tertiary_container);
3366 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getAccounts().size() > 1) {
3367 final var bg = MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorSurface);
3368 final var accountColor = conversation.getAccount().getColor(activity.isDark());
3369 final var colors = MaterialColors.getColorRoles(activity, accountColor);
3370 final var accent = activity.isDark() ? ColorUtils.blendARGB(colors.getAccentContainer(), bg, 1.0f - Math.max(0.25f, Color.alpha(accountColor) / 255.0f)) : colors.getAccentContainer();
3371 cursord.setTintList(ColorStateList.valueOf(colors.getOnAccentContainer()));
3372 binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(accent));
3373 binding.textinputSubject.setTextColor(colors.getOnAccentContainer());
3374 binding.textinput.setTextColor(colors.getOnAccentContainer());
3375 binding.textinputSubject.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3376 binding.textinput.setHintTextColor(ColorStateList.valueOf(colors.getOnAccentContainer()).withAlpha(115));
3377 binding.textInputHint.setTextColor(colors.getOnAccentContainer());
3378 } else {
3379 cursord.setTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer)));
3380 binding.inputLayout.setBackgroundTintList(ColorStateList.valueOf(MaterialColors.getColor(binding.inputLayout, com.google.android.material.R.attr.colorTertiaryContainer)));
3381 binding.textinputSubject.setTextColor(MaterialColors.getColor(binding.textinputSubject, com.google.android.material.R.attr.colorOnTertiaryContainer));
3382 binding.textinput.setTextColor(MaterialColors.getColor(binding.textinput, com.google.android.material.R.attr.colorOnTertiaryContainer));
3383 binding.textinputSubject.setHintTextColor(R.color.hint_on_tertiary_container);
3384 binding.textinput.setHintTextColor(R.color.hint_on_tertiary_container);
3385 binding.textInputHint.setTextColor(MaterialColors.getColor(binding.textInputHint, com.google.android.material.R.attr.colorOnTertiaryContainer));
3386 }
3387 if (Build.VERSION.SDK_INT >= 29) {
3388 binding.textinputSubject.setTextCursorDrawable(cursord);
3389 binding.textinput.setTextCursorDrawable(cursord);
3390 }
3391
3392 setThread(conversation.getThread());
3393 setupReply(conversation.getReplyTo());
3394
3395 stopScrolling();
3396 Log.d(Config.LOGTAG, "reInit(hasExtras=" + hasExtras + ")");
3397
3398 if (this.conversation.isRead(activity == null ? null : activity.xmppConnectionService) && hasExtras) {
3399 Log.d(Config.LOGTAG, "trimming conversation");
3400 this.conversation.trim();
3401 }
3402
3403 setupIme();
3404
3405 final boolean scrolledToBottomAndNoPending =
3406 this.scrolledToBottom() && pendingScrollState.peek() == null;
3407
3408 this.binding.textSendButton.setContentDescription(
3409 activity.getString(R.string.send_message_to_x, conversation.getName()));
3410 this.binding.textinput.setKeyboardListener(null);
3411 this.binding.textinputSubject.setKeyboardListener(null);
3412 final boolean participating =
3413 conversation.getMode() == Conversational.MODE_SINGLE
3414 || conversation.getMucOptions().participating();
3415 if (participating) {
3416 this.binding.textinput.setText(this.conversation.getNextMessage());
3417 this.binding.textinput.setSelection(this.binding.textinput.length());
3418 } else {
3419 this.binding.textinput.setText(MessageUtils.EMPTY_STRING);
3420 }
3421 this.binding.textinput.setKeyboardListener(this);
3422 this.binding.textinputSubject.setKeyboardListener(this);
3423 messageListAdapter.updatePreferences();
3424 refresh(false);
3425 activity.invalidateOptionsMenu();
3426 this.conversation.messagesLoaded.set(true);
3427 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + scrolledToBottomAndNoPending);
3428
3429 if (hasExtras || scrolledToBottomAndNoPending) {
3430 resetUnreadMessagesCount();
3431 synchronized (this.messageList) {
3432 Log.d(Config.LOGTAG, "jump to first unread message");
3433 final Message first = conversation.getFirstUnreadMessage();
3434 final int bottom = Math.max(0, this.messageList.size() - 1);
3435 final int pos;
3436 final boolean jumpToBottom;
3437 if (first == null) {
3438 pos = bottom;
3439 jumpToBottom = true;
3440 } else {
3441 int i = getIndexOf(first.getUuid(), this.messageList);
3442 pos = i < 0 ? bottom : i;
3443 jumpToBottom = false;
3444 }
3445 setSelection(pos, jumpToBottom);
3446 }
3447 }
3448
3449 this.binding.messagesView.post(this::fireReadEvent);
3450 // TODO if we only do this when this fragment is running on main it won't *bing* in tablet
3451 // layout which might be unnecessary since we can *see* it
3452 activity.xmppConnectionService
3453 .getNotificationService()
3454 .setOpenConversation(this.conversation);
3455
3456 if (commandAdapter != null && conversation != originalConversation) {
3457 commandAdapter.clear();
3458 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), originalConversation);
3459 refreshCommands(false);
3460 }
3461 if (commandAdapter == null && conversation != null) {
3462 conversation.setupViewPager(binding.conversationViewPager, binding.tabLayout, activity.xmppConnectionService.isOnboarding(), null);
3463 commandAdapter = new CommandAdapter((XmppActivity) getActivity());
3464 binding.commandsView.setAdapter(commandAdapter);
3465 binding.commandsView.setOnItemClickListener((parent, view, position, id) -> {
3466 if (activity == null) return;
3467
3468 commandAdapter.getItem(position).start(activity, ConversationFragment.this.conversation);
3469 });
3470 refreshCommands(false);
3471 }
3472
3473 binding.commandsNote.setVisibility(activity.xmppConnectionService.isOnboarding() ? View.VISIBLE : View.GONE);
3474
3475 return true;
3476 }
3477
3478 @Override
3479 public void refreshForNewCaps(final Set<Jid> newCapsJids) {
3480 if (newCapsJids.isEmpty() || (conversation != null && newCapsJids.contains(conversation.getJid().asBareJid()))) {
3481 refreshCommands(true);
3482 }
3483 }
3484
3485 protected void refreshCommands(boolean delayShow) {
3486 if (commandAdapter == null) return;
3487
3488 final CommandAdapter.MucConfig mucConfig =
3489 conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER) ?
3490 new CommandAdapter.MucConfig() :
3491 null;
3492
3493 Jid commandJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3494 if (commandJid == null && conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().hasFeature(Namespace.COMMANDS)) {
3495 commandJid = conversation.getJid().asBareJid();
3496 }
3497 if (commandJid == null && conversation.getJid().isDomainJid()) {
3498 commandJid = conversation.getJid();
3499 }
3500 if (commandJid == null) {
3501 binding.commandsViewProgressbar.setVisibility(View.GONE);
3502 if (mucConfig == null) {
3503 conversation.hideViewPager();
3504 } else {
3505 commandAdapter.clear();
3506 commandAdapter.add(mucConfig);
3507 conversation.showViewPager();
3508 }
3509 } else {
3510 if (!delayShow) conversation.showViewPager();
3511 binding.commandsViewProgressbar.setVisibility(View.VISIBLE);
3512 activity.xmppConnectionService.fetchCommands(conversation.getAccount(), commandJid, (iq) -> {
3513 if (activity == null) return;
3514
3515 activity.runOnUiThread(() -> {
3516 binding.commandsViewProgressbar.setVisibility(View.GONE);
3517 commandAdapter.clear();
3518 if (iq.getType() == Iq.Type.RESULT) {
3519 for (Element child : iq.query().getChildren()) {
3520 if (!"item".equals(child.getName()) || !Namespace.DISCO_ITEMS.equals(child.getNamespace())) continue;
3521 commandAdapter.add(new CommandAdapter.Command0050(child));
3522 }
3523 }
3524
3525 if (mucConfig != null) commandAdapter.add(mucConfig);
3526
3527 if (commandAdapter.getCount() < 1) {
3528 conversation.hideViewPager();
3529 } else if (delayShow) {
3530 conversation.showViewPager();
3531 }
3532 });
3533 });
3534 }
3535 }
3536
3537 private void resetUnreadMessagesCount() {
3538 lastMessageUuid = null;
3539 hideUnreadMessagesCount();
3540 }
3541
3542 private void hideUnreadMessagesCount() {
3543 if (this.binding == null) {
3544 return;
3545 }
3546 this.binding.scrollToBottomButton.setEnabled(false);
3547 this.binding.scrollToBottomButton.hide();
3548 this.binding.unreadCountCustomView.setVisibility(View.GONE);
3549 }
3550
3551 private void setSelection(int pos, boolean jumpToBottom) {
3552 ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
3553 this.binding.messagesView.post(
3554 () -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
3555 this.binding.messagesView.post(this::fireReadEvent);
3556 }
3557
3558 private boolean scrolledToBottom() {
3559 return this.binding != null && scrolledToBottom(this.binding.messagesView);
3560 }
3561
3562 private void processExtras(final Bundle extras) {
3563 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
3564 final String text = extras.getString(Intent.EXTRA_TEXT);
3565 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
3566 final String node = extras.getString(ConversationsActivity.EXTRA_NODE);
3567 final String postInitAction =
3568 extras.getString(ConversationsActivity.EXTRA_POST_INIT_ACTION);
3569 final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
3570 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
3571 final boolean doNotAppend =
3572 extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
3573 final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
3574
3575 final String thread = extras.getString(ConversationsActivity.EXTRA_THREAD);
3576 if (thread != null) {
3577 conversation.setLockThread(true);
3578 backPressedLeaveSingleThread.setEnabled(true);
3579 setThread(new Element("thread").setContent(thread));
3580 refresh();
3581 }
3582
3583 final List<Uri> uris = extractUris(extras);
3584 if (uris != null && uris.size() > 0) {
3585 if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
3586 mediaPreviewAdapter.addMediaPreviews(
3587 Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
3588 } else {
3589 final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
3590 mediaPreviewAdapter.addMediaPreviews(
3591 Attachment.of(getActivity(), cleanedUris, type));
3592 }
3593 toggleInputMethod();
3594 return;
3595 }
3596 if (nick != null) {
3597 if (pm) {
3598 Jid jid = conversation.getJid();
3599 try {
3600 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
3601 privateMessageWith(next);
3602 } catch (final IllegalArgumentException ignored) {
3603 // do nothing
3604 }
3605 } else {
3606 final MucOptions mucOptions = conversation.getMucOptions();
3607 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
3608 highlightInConference(nick);
3609 }
3610 }
3611 } else {
3612 if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
3613 mediaPreviewAdapter.addMediaPreviews(
3614 Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
3615 toggleInputMethod();
3616 return;
3617 } else if (text != null && asQuote) {
3618 quoteText(text);
3619 } else {
3620 appendText(text, doNotAppend);
3621 }
3622 }
3623 if (ConversationsActivity.POST_ACTION_RECORD_VOICE.equals(postInitAction)) {
3624 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE, false);
3625 return;
3626 }
3627 if ("call".equals(postInitAction)) {
3628 checkPermissionAndTriggerAudioCall();
3629 }
3630 if ("message".equals(postInitAction)) {
3631 binding.conversationViewPager.post(() -> {
3632 binding.conversationViewPager.setCurrentItem(0);
3633 });
3634 }
3635 if ("command".equals(postInitAction)) {
3636 binding.conversationViewPager.post(() -> {
3637 PagerAdapter adapter = binding.conversationViewPager.getAdapter();
3638 if (adapter != null && adapter.getCount() > 1) {
3639 binding.conversationViewPager.setCurrentItem(1);
3640 }
3641 final String jid = extras.getString(ConversationsActivity.EXTRA_JID);
3642 Jid commandJid = null;
3643 if (jid != null) {
3644 try {
3645 commandJid = Jid.of(jid);
3646 } catch (final IllegalArgumentException e) { }
3647 }
3648 if (commandJid == null || !commandJid.isFullJid()) {
3649 final Jid discoJid = conversation.getContact().resourceWhichSupport(Namespace.COMMANDS);
3650 if (discoJid != null) commandJid = discoJid;
3651 }
3652 if (node != null && commandJid != null && activity != null) {
3653 conversation.startCommand(commandFor(commandJid, node), activity.xmppConnectionService);
3654 }
3655 });
3656 return;
3657 }
3658 Message message =
3659 downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
3660 if ("webxdc".equals(postInitAction)) {
3661 if (message == null) {
3662 message = activity.xmppConnectionService.getMessage(conversation, downloadUuid);
3663 }
3664 if (message == null) return;
3665
3666 Cid webxdcCid = message.getFileParams().getCids().get(0);
3667 WebxdcPage webxdc = new WebxdcPage(activity, webxdcCid, message);
3668 Conversation conversation = (Conversation) message.getConversation();
3669 if (!conversation.switchToSession("webxdc\0" + message.getUuid())) {
3670 conversation.startWebxdc(webxdc);
3671 }
3672 }
3673 if (message != null) {
3674 startDownloadable(message);
3675 }
3676 if (activity.xmppConnectionService.isOnboarding() && conversation.getJid().equals(Jid.of("cheogram.com"))) {
3677 if (!conversation.switchToSession("jabber:iq:register")) {
3678 conversation.startCommand(commandFor(Jid.of("cheogram.com/CHEOGRAM%jabber:iq:register"), "jabber:iq:register"), activity.xmppConnectionService);
3679 }
3680 }
3681 }
3682
3683 private Element commandFor(final Jid jid, final String node) {
3684 if (commandAdapter != null) {
3685 for (int i = 0; i < commandAdapter.getCount(); i++) {
3686 final CommandAdapter.Command c = commandAdapter.getItem(i);
3687 if (!(c instanceof CommandAdapter.Command0050)) continue;
3688
3689 final Element command = ((CommandAdapter.Command0050) c).el;
3690 final String commandNode = command.getAttribute("node");
3691 if (commandNode == null || !commandNode.equals(node)) continue;
3692
3693 final Jid commandJid = command.getAttributeAsJid("jid");
3694 if (commandJid != null && !commandJid.asBareJid().equals(jid.asBareJid())) continue;
3695
3696 return command;
3697 }
3698 }
3699
3700 return new Element("command", Namespace.COMMANDS).setAttribute("name", node).setAttribute("node", node).setAttribute("jid", jid);
3701 }
3702
3703 private List<Uri> extractUris(final Bundle extras) {
3704 final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3705 if (uris != null) {
3706 return uris;
3707 }
3708 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
3709 if (uri != null) {
3710 return Collections.singletonList(uri);
3711 } else {
3712 return null;
3713 }
3714 }
3715
3716 private List<Uri> cleanUris(final List<Uri> uris) {
3717 final Iterator<Uri> iterator = uris.iterator();
3718 while (iterator.hasNext()) {
3719 final Uri uri = iterator.next();
3720 if (FileBackend.dangerousFile(uri)) {
3721 iterator.remove();
3722 Toast.makeText(
3723 requireActivity(),
3724 R.string.security_violation_not_attaching_file,
3725 Toast.LENGTH_SHORT)
3726 .show();
3727 }
3728 }
3729 return uris;
3730 }
3731
3732 private boolean showBlockSubmenu(View view) {
3733 final Jid jid = conversation.getJid();
3734 final int mode = conversation.getMode();
3735 final var contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3736 final boolean showReject = contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3737 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
3738 popupMenu.inflate(R.menu.block);
3739 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3740 popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
3741 popupMenu.getMenu().findItem(R.id.add_contact).setVisible(!contact.showInRoster());
3742 popupMenu.setOnMenuItemClickListener(
3743 menuItem -> {
3744 Blockable blockable;
3745 switch (menuItem.getItemId()) {
3746 case R.id.reject:
3747 activity.xmppConnectionService.stopPresenceUpdatesTo(
3748 conversation.getContact());
3749 updateSnackBar(conversation);
3750 return true;
3751 case R.id.add_contact:
3752 mAddBackClickListener.onClick(view);
3753 return true;
3754 case R.id.block_domain:
3755 blockable =
3756 conversation
3757 .getAccount()
3758 .getRoster()
3759 .getContact(jid.getDomain());
3760 break;
3761 default:
3762 blockable = conversation;
3763 }
3764 BlockContactDialog.show(activity, blockable);
3765 return true;
3766 });
3767 popupMenu.show();
3768 return true;
3769 }
3770
3771 private boolean showBlockMucSubmenu(View view) {
3772 final var jid = conversation.getJid();
3773 final var popupMenu = new PopupMenu(getActivity(), view);
3774 popupMenu.inflate(R.menu.block_muc);
3775 popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
3776 popupMenu.setOnMenuItemClickListener(
3777 menuItem -> {
3778 Blockable blockable;
3779 switch (menuItem.getItemId()) {
3780 case R.id.reject:
3781 activity.xmppConnectionService.clearConversationHistory(conversation);
3782 activity.xmppConnectionService.archiveConversation(conversation);
3783 return true;
3784 case R.id.add_bookmark:
3785 activity.xmppConnectionService.saveConversationAsBookmark(conversation, "");
3786 updateSnackBar(conversation);
3787 return true;
3788 case R.id.block_contact:
3789 blockable =
3790 conversation
3791 .getAccount()
3792 .getRoster()
3793 .getContact(Jid.of(conversation.getAttribute("inviter")));
3794 break;
3795 default:
3796 blockable = conversation;
3797 }
3798 BlockContactDialog.show(activity, blockable);
3799 activity.xmppConnectionService.archiveConversation(conversation);
3800 return true;
3801 });
3802 popupMenu.show();
3803 return true;
3804 }
3805
3806 private void updateSnackBar(final Conversation conversation) {
3807 final Account account = conversation.getAccount();
3808 final XmppConnection connection = account.getXmppConnection();
3809 final int mode = conversation.getMode();
3810 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
3811 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3812 return;
3813 }
3814 if (account.getStatus() == Account.State.DISABLED) {
3815 showSnackbar(
3816 R.string.this_account_is_disabled,
3817 R.string.enable,
3818 this.mEnableAccountListener);
3819 } else if (account.getStatus() == Account.State.LOGGED_OUT) {
3820 showSnackbar(R.string.this_account_is_logged_out,R.string.log_in,this.mEnableAccountListener);
3821 } else if (conversation.isBlocked()) {
3822 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
3823 } else if (account.getStatus() == Account.State.CONNECTING) {
3824 showSnackbar(R.string.this_account_is_connecting, 0, null);
3825 } else if (account.getStatus() != Account.State.ONLINE) {
3826 showSnackbar(R.string.this_account_is_offline, 0, null);
3827 } else if (contact != null
3828 && !contact.showInRoster()
3829 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3830 showSnackbar(
3831 R.string.contact_added_you,
3832 R.string.options,
3833 this.mBlockClickListener,
3834 this.mLongPressBlockListener);
3835 } else if (contact != null
3836 && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3837 showSnackbar(
3838 R.string.contact_asks_for_presence_subscription,
3839 R.string.allow,
3840 this.mAllowPresenceSubscription,
3841 this.mLongPressBlockListener);
3842 } else if (mode == Conversation.MODE_MULTI
3843 && !conversation.getMucOptions().online()
3844 && account.getStatus() == Account.State.ONLINE) {
3845 switch (conversation.getMucOptions().getError()) {
3846 case NICK_IN_USE:
3847 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
3848 break;
3849 case NO_RESPONSE:
3850 showSnackbar(R.string.joining_conference, 0, null);
3851 break;
3852 case SERVER_NOT_FOUND:
3853 if (conversation.receivedMessagesCount() > 0) {
3854 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
3855 } else {
3856 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
3857 }
3858 break;
3859 case REMOTE_SERVER_TIMEOUT:
3860 if (conversation.receivedMessagesCount() > 0) {
3861 showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
3862 } else {
3863 showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
3864 }
3865 break;
3866 case PASSWORD_REQUIRED:
3867 showSnackbar(
3868 R.string.conference_requires_password,
3869 R.string.enter_password,
3870 enterPassword);
3871 break;
3872 case BANNED:
3873 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
3874 break;
3875 case MEMBERS_ONLY:
3876 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
3877 break;
3878 case RESOURCE_CONSTRAINT:
3879 showSnackbar(
3880 R.string.conference_resource_constraint, R.string.try_again, joinMuc);
3881 break;
3882 case KICKED:
3883 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
3884 break;
3885 case TECHNICAL_PROBLEMS:
3886 showSnackbar(R.string.conference_technical_problems, R.string.try_again, joinMuc);
3887 break;
3888 case UNKNOWN:
3889 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
3890 break;
3891 case INVALID_NICK:
3892 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
3893 case SHUTDOWN:
3894 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
3895 break;
3896 case DESTROYED:
3897 showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
3898 break;
3899 case NON_ANONYMOUS:
3900 showSnackbar(
3901 R.string.group_chat_will_make_your_jabber_id_public,
3902 R.string.join,
3903 acceptJoin);
3904 break;
3905 default:
3906 hideSnackbar();
3907 break;
3908 }
3909 } else if (account.hasPendingPgpIntent(conversation)) {
3910 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
3911 } else if (connection != null
3912 && connection.getFeatures().blocking()
3913 && conversation.strangerInvited()) {
3914 showSnackbar(
3915 R.string.received_invite_from_stranger,
3916 R.string.options,
3917 (v) -> showBlockMucSubmenu(v),
3918 (v) -> showBlockMucSubmenu(v));
3919 } else if (connection != null
3920 && connection.getFeatures().blocking()
3921 && conversation.countMessages() != 0
3922 && !conversation.isBlocked()
3923 && conversation.isWithStranger()) {
3924 showSnackbar(
3925 R.string.received_message_from_stranger,
3926 R.string.options,
3927 this.mBlockClickListener,
3928 this.mLongPressBlockListener);
3929 } else {
3930 hideSnackbar();
3931 }
3932 }
3933
3934 @Override
3935 public void refresh() {
3936 if (this.binding == null) {
3937 Log.d(
3938 Config.LOGTAG,
3939 "ConversationFragment.refresh() skipped updated because view binding was null");
3940 return;
3941 }
3942 if (this.conversation != null
3943 && this.activity != null
3944 && this.activity.xmppConnectionService != null) {
3945 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
3946 activity.onConversationArchived(this.conversation);
3947 return;
3948 }
3949 }
3950 this.refresh(true);
3951 }
3952
3953 private void refresh(boolean notifyConversationRead) {
3954 synchronized (this.messageList) {
3955 if (this.conversation != null) {
3956 if (messageListAdapter.hasSelection()) {
3957 if (notifyConversationRead) binding.messagesView.postDelayed(this::refresh, 1000L);
3958 } else {
3959 conversation.populateWithMessages(this.messageList, activity == null ? null : activity.xmppConnectionService);
3960 updateStatusMessages();
3961 this.messageListAdapter.notifyDataSetChanged();
3962 }
3963 if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
3964 binding.unreadCountCustomView.setVisibility(View.VISIBLE);
3965 binding.unreadCountCustomView.setUnreadCount(
3966 conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
3967 }
3968 updateSnackBar(conversation);
3969 if (activity != null) updateChatMsgHint();
3970 if (notifyConversationRead && activity != null) {
3971 binding.messagesView.post(this::fireReadEvent);
3972 }
3973 updateSendButton();
3974 updateEditablity();
3975 conversation.refreshSessions();
3976 }
3977 }
3978 }
3979
3980 protected void messageSent() {
3981 binding.textinputSubject.setText("");
3982 binding.textinputSubject.setVisibility(View.GONE);
3983 setThread(null);
3984 setupReply(null);
3985 conversation.setUserSelectedThread(false);
3986 mSendingPgpMessage.set(false);
3987 this.binding.textinput.setText("");
3988 if (conversation.setCorrectingMessage(null)) {
3989 this.binding.textinput.append(conversation.getDraftMessage());
3990 conversation.setDraftMessage(null);
3991 }
3992 storeNextMessage();
3993 updateChatMsgHint();
3994 if (activity == null) return;
3995 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
3996 final boolean prefScrollToBottom =
3997 p.getBoolean(
3998 "scroll_to_bottom",
3999 activity.getResources().getBoolean(R.bool.scroll_to_bottom));
4000 if (prefScrollToBottom || scrolledToBottom()) {
4001 new Handler()
4002 .post(
4003 () -> {
4004 int size = messageList.size();
4005 this.binding.messagesView.setSelection(size - 1);
4006 });
4007 }
4008 }
4009
4010 private boolean storeNextMessage() {
4011 return storeNextMessage(this.binding.textinput.getText().toString());
4012 }
4013
4014 private boolean storeNextMessage(String msg) {
4015 final boolean participating =
4016 conversation.getMode() == Conversational.MODE_SINGLE
4017 || conversation.getMucOptions().participating();
4018 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED
4019 && participating
4020 && this.conversation.setNextMessage(msg) && activity != null) {
4021 activity.xmppConnectionService.updateConversation(this.conversation);
4022 return true;
4023 }
4024 return false;
4025 }
4026
4027 public void doneSendingPgpMessage() {
4028 mSendingPgpMessage.set(false);
4029 }
4030
4031 public long getMaxHttpUploadSize(Conversation conversation) {
4032 final XmppConnection connection = conversation.getAccount().getXmppConnection();
4033 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
4034 }
4035
4036 private boolean canWrite() {
4037 return
4038 this.conversation.getMode() == Conversation.MODE_SINGLE
4039 || this.conversation.getMucOptions().participating()
4040 || this.conversation.getNextCounterpart() != null;
4041 }
4042
4043 private void updateEditablity() {
4044 boolean canWrite = canWrite();
4045 this.binding.textinput.setFocusable(canWrite);
4046 this.binding.textinput.setFocusableInTouchMode(canWrite);
4047 this.binding.textSendButton.setEnabled(canWrite);
4048 this.binding.textSendButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
4049 this.binding.requestVoice.setVisibility(canWrite ? View.GONE : View.VISIBLE);
4050 this.binding.textinput.setCursorVisible(canWrite);
4051 this.binding.textinput.setEnabled(canWrite);
4052 }
4053
4054 public void updateSendButton() {
4055 boolean hasAttachments =
4056 mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
4057 final Conversation c = this.conversation;
4058 final Presence.Status status;
4059 final String text =
4060 this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
4061 final SendButtonAction action;
4062 if (hasAttachments) {
4063 action = SendButtonAction.TEXT;
4064 } else {
4065 action = SendButtonTool.getAction(getActivity(), c, text, binding.textinputSubject.getText().toString());
4066 }
4067 if (c.getAccount().getStatus() == Account.State.ONLINE) {
4068 if (activity != null
4069 && activity.xmppConnectionService != null
4070 && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
4071 status = Presence.Status.OFFLINE;
4072 } else if (c.getMode() == Conversation.MODE_SINGLE) {
4073 status = c.getContact().getShownStatus();
4074 } else {
4075 status =
4076 c.getMucOptions().online()
4077 ? Presence.Status.ONLINE
4078 : Presence.Status.OFFLINE;
4079 }
4080 } else {
4081 status = Presence.Status.OFFLINE;
4082 }
4083 this.binding.textSendButton.setTag(action);
4084 this.binding.textSendButton.setIconTint(ColorStateList.valueOf(SendButtonTool.getSendButtonColor(this.binding.textSendButton, status)));
4085 // TODO send button color
4086 final Activity activity = getActivity();
4087 if (activity != null) {
4088 this.binding.textSendButton.setIconResource(
4089 SendButtonTool.getSendButtonImageResource(action, text.length() > 0 || hasAttachments || (c.getThread() != null && binding.textinputSubject.getText().length() > 0)));
4090 }
4091
4092 ViewGroup.LayoutParams params = binding.threadIdenticonLayout.getLayoutParams();
4093 if (identiconWidth < 0) identiconWidth = params.width;
4094 if (hasAttachments || binding.textinput.getText().toString().replaceFirst("^(\\w|[, ])+:\\s*", "").length() > 0) {
4095 binding.conversationViewPager.setCurrentItem(0);
4096 params.width = conversation.getThread() == null ? 0 : identiconWidth;
4097 } else {
4098 params.width = identiconWidth;
4099 }
4100 if (!canWrite()) params.width = 0;
4101 binding.threadIdenticonLayout.setLayoutParams(params);
4102 }
4103
4104 protected void updateStatusMessages() {
4105 DateSeparator.addAll(this.messageList);
4106 if (showLoadMoreMessages(conversation)) {
4107 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
4108 }
4109 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4110 ChatState state = conversation.getIncomingChatState();
4111 if (state == ChatState.COMPOSING) {
4112 this.messageList.add(
4113 Message.createStatusMessage(
4114 conversation,
4115 getString(R.string.contact_is_typing, conversation.getName())));
4116 } else if (state == ChatState.PAUSED) {
4117 this.messageList.add(
4118 Message.createStatusMessage(
4119 conversation,
4120 getString(
4121 R.string.contact_has_stopped_typing,
4122 conversation.getName())));
4123 } else {
4124 for (int i = this.messageList.size() - 1; i >= 0; --i) {
4125 final Message message = this.messageList.get(i);
4126 if (message.getType() != Message.TYPE_STATUS) {
4127 if (message.getStatus() == Message.STATUS_RECEIVED) {
4128 return;
4129 } else {
4130 if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
4131 this.messageList.add(
4132 i + 1,
4133 Message.createStatusMessage(
4134 conversation,
4135 getString(
4136 R.string.contact_has_read_up_to_this_point,
4137 conversation.getName())));
4138 return;
4139 }
4140 }
4141 }
4142 }
4143 }
4144 } else {
4145 final MucOptions mucOptions = conversation.getMucOptions();
4146 final List<MucOptions.User> allUsers = mucOptions.getUsers();
4147 final Set<ReadByMarker> addedMarkers = new HashSet<>();
4148 ChatState state = ChatState.COMPOSING;
4149 List<MucOptions.User> users =
4150 conversation.getMucOptions().getUsersWithChatState(state, 5);
4151 if (users.size() == 0) {
4152 state = ChatState.PAUSED;
4153 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
4154 }
4155 if (mucOptions.isPrivateAndNonAnonymous()) {
4156 for (int i = this.messageList.size() - 1; i >= 0; --i) {
4157 final Set<ReadByMarker> markersForMessage =
4158 messageList.get(i).getReadByMarkers();
4159 final List<MucOptions.User> shownMarkers = new ArrayList<>();
4160 for (ReadByMarker marker : markersForMessage) {
4161 if (!ReadByMarker.contains(marker, addedMarkers)) {
4162 addedMarkers.add(
4163 marker); // may be put outside this condition. set should do
4164 // dedup anyway
4165 MucOptions.User user = mucOptions.findUser(marker);
4166 if (user != null && !users.contains(user)) {
4167 shownMarkers.add(user);
4168 }
4169 }
4170 }
4171 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
4172 final Message statusMessage;
4173 final int size = shownMarkers.size();
4174 if (size > 1) {
4175 final String body;
4176 if (size <= 4) {
4177 body =
4178 getString(
4179 R.string.contacts_have_read_up_to_this_point,
4180 UIHelper.concatNames(shownMarkers));
4181 } else if (ReadByMarker.allUsersRepresented(
4182 allUsers, markersForMessage, markerForSender)) {
4183 body = getString(R.string.everyone_has_read_up_to_this_point);
4184 } else {
4185 body =
4186 getString(
4187 R.string.contacts_and_n_more_have_read_up_to_this_point,
4188 UIHelper.concatNames(shownMarkers, 3),
4189 size - 3);
4190 }
4191 statusMessage = Message.createStatusMessage(conversation, body);
4192 statusMessage.setCounterparts(shownMarkers);
4193 } else if (size == 1) {
4194 statusMessage =
4195 Message.createStatusMessage(
4196 conversation,
4197 getString(
4198 R.string.contact_has_read_up_to_this_point,
4199 UIHelper.getDisplayName(shownMarkers.get(0))));
4200 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
4201 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
4202 } else {
4203 statusMessage = null;
4204 }
4205 if (statusMessage != null) {
4206 this.messageList.add(i + 1, statusMessage);
4207 }
4208 addedMarkers.add(markerForSender);
4209 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
4210 break;
4211 }
4212 }
4213 }
4214 if (users.size() > 0) {
4215 Message statusMessage;
4216 if (users.size() == 1) {
4217 MucOptions.User user = users.get(0);
4218 int id =
4219 state == ChatState.COMPOSING
4220 ? R.string.contact_is_typing
4221 : R.string.contact_has_stopped_typing;
4222 statusMessage =
4223 Message.createStatusMessage(
4224 conversation, getString(id, UIHelper.getDisplayName(user)));
4225 statusMessage.setTrueCounterpart(user.getRealJid());
4226 statusMessage.setCounterpart(user.getFullJid());
4227 } else {
4228 int id =
4229 state == ChatState.COMPOSING
4230 ? R.string.contacts_are_typing
4231 : R.string.contacts_have_stopped_typing;
4232 statusMessage =
4233 Message.createStatusMessage(
4234 conversation, getString(id, UIHelper.concatNames(users)));
4235 statusMessage.setCounterparts(users);
4236 }
4237 this.messageList.add(statusMessage);
4238 }
4239 }
4240 }
4241
4242 private void stopScrolling() {
4243 long now = SystemClock.uptimeMillis();
4244 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
4245 binding.messagesView.dispatchTouchEvent(cancel);
4246 }
4247
4248 private boolean showLoadMoreMessages(final Conversation c) {
4249 if (activity == null || activity.xmppConnectionService == null) {
4250 return false;
4251 }
4252 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
4253 final MessageArchiveService service =
4254 activity.xmppConnectionService.getMessageArchiveService();
4255 return mam
4256 && (c.getLastClearHistory().getTimestamp() != 0
4257 || (c.countMessages() == 0
4258 && c.messagesLoaded.get()
4259 && c.hasMessagesLeftOnServer()
4260 && !service.queryInProgress(c)));
4261 }
4262
4263 private boolean hasMamSupport(final Conversation c) {
4264 if (c.getMode() == Conversation.MODE_SINGLE) {
4265 final XmppConnection connection = c.getAccount().getXmppConnection();
4266 return connection != null && connection.getFeatures().mam();
4267 } else {
4268 return c.getMucOptions().mamSupport();
4269 }
4270 }
4271
4272 protected void showSnackbar(
4273 final int message, final int action, final OnClickListener clickListener) {
4274 showSnackbar(message, action, clickListener, null);
4275 }
4276
4277 protected void showSnackbar(
4278 final int message,
4279 final int action,
4280 final OnClickListener clickListener,
4281 final View.OnLongClickListener longClickListener) {
4282 this.binding.snackbar.setVisibility(View.VISIBLE);
4283 this.binding.snackbar.setOnClickListener(null);
4284 this.binding.snackbarMessage.setText(message);
4285 this.binding.snackbarMessage.setOnClickListener(null);
4286 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
4287 if (action != 0) {
4288 this.binding.snackbarAction.setText(action);
4289 }
4290 this.binding.snackbarAction.setOnClickListener(clickListener);
4291 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
4292 }
4293
4294 protected void hideSnackbar() {
4295 this.binding.snackbar.setVisibility(View.GONE);
4296 }
4297
4298 protected void sendMessage(Message message) {
4299 new Thread(() -> activity.xmppConnectionService.sendMessage(message)).start();
4300 messageSent();
4301 }
4302
4303 protected void sendPgpMessage(final Message message) {
4304 final XmppConnectionService xmppService = activity.xmppConnectionService;
4305 final Contact contact = message.getConversation().getContact();
4306 if (!activity.hasPgp()) {
4307 activity.showInstallPgpDialog();
4308 return;
4309 }
4310 if (conversation.getAccount().getPgpSignature() == null) {
4311 activity.announcePgp(
4312 conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
4313 return;
4314 }
4315 if (!mSendingPgpMessage.compareAndSet(false, true)) {
4316 Log.d(Config.LOGTAG, "sending pgp message already in progress");
4317 }
4318 if (conversation.getMode() == Conversation.MODE_SINGLE) {
4319 if (contact.getPgpKeyId() != 0) {
4320 xmppService
4321 .getPgpEngine()
4322 .hasKey(
4323 contact,
4324 new UiCallback<Contact>() {
4325
4326 @Override
4327 public void userInputRequired(
4328 PendingIntent pi, Contact contact) {
4329 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
4330 }
4331
4332 @Override
4333 public void success(Contact contact) {
4334 encryptTextMessage(message);
4335 }
4336
4337 @Override
4338 public void error(int error, Contact contact) {
4339 activity.runOnUiThread(
4340 () ->
4341 Toast.makeText(
4342 activity,
4343 R.string
4344 .unable_to_connect_to_keychain,
4345 Toast.LENGTH_SHORT)
4346 .show());
4347 mSendingPgpMessage.set(false);
4348 }
4349 });
4350
4351 } else {
4352 showNoPGPKeyDialog(
4353 false,
4354 (dialog, which) -> {
4355 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4356 xmppService.updateConversation(conversation);
4357 message.setEncryption(Message.ENCRYPTION_NONE);
4358 xmppService.sendMessage(message);
4359 messageSent();
4360 });
4361 }
4362 } else {
4363 if (conversation.getMucOptions().pgpKeysInUse()) {
4364 if (!conversation.getMucOptions().everybodyHasKeys()) {
4365 Toast warning =
4366 Toast.makeText(
4367 getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
4368 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
4369 warning.show();
4370 }
4371 encryptTextMessage(message);
4372 } else {
4373 showNoPGPKeyDialog(
4374 true,
4375 (dialog, which) -> {
4376 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
4377 message.setEncryption(Message.ENCRYPTION_NONE);
4378 xmppService.updateConversation(conversation);
4379 xmppService.sendMessage(message);
4380 messageSent();
4381 });
4382 }
4383 }
4384 }
4385
4386 public void encryptTextMessage(Message message) {
4387 activity.xmppConnectionService
4388 .getPgpEngine()
4389 .encrypt(
4390 message,
4391 new UiCallback<Message>() {
4392
4393 @Override
4394 public void userInputRequired(PendingIntent pi, Message message) {
4395 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
4396 }
4397
4398 @Override
4399 public void success(Message message) {
4400 // TODO the following two call can be made before the callback
4401 getActivity().runOnUiThread(() -> messageSent());
4402 }
4403
4404 @Override
4405 public void error(final int error, Message message) {
4406 getActivity()
4407 .runOnUiThread(
4408 () -> {
4409 doneSendingPgpMessage();
4410 Toast.makeText(
4411 getActivity(),
4412 error == 0
4413 ? R.string
4414 .unable_to_connect_to_keychain
4415 : error,
4416 Toast.LENGTH_SHORT)
4417 .show();
4418 });
4419 }
4420 });
4421 }
4422
4423 public void showNoPGPKeyDialog(final boolean plural, final DialogInterface.OnClickListener listener) {
4424 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity());
4425 if (plural) {
4426 builder.setTitle(getString(R.string.no_pgp_keys));
4427 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
4428 } else {
4429 builder.setTitle(getString(R.string.no_pgp_key));
4430 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
4431 }
4432 builder.setNegativeButton(getString(R.string.cancel), null);
4433 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
4434 builder.create().show();
4435 }
4436
4437 public void appendText(String text, final boolean doNotAppend) {
4438 if (text == null) {
4439 return;
4440 }
4441 final Editable editable = this.binding.textinput.getText();
4442 String previous = editable == null ? "" : editable.toString();
4443 if (doNotAppend && !TextUtils.isEmpty(previous)) {
4444 Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG)
4445 .show();
4446 return;
4447 }
4448 if (UIHelper.isLastLineQuote(previous)) {
4449 text = '\n' + text;
4450 } else if (previous.length() != 0
4451 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
4452 text = " " + text;
4453 }
4454 this.binding.textinput.append(text);
4455 }
4456
4457 @Override
4458 public boolean onEnterPressed(final boolean isCtrlPressed) {
4459 if (isCtrlPressed || enterIsSend()) {
4460 sendMessage();
4461 return true;
4462 }
4463 return false;
4464 }
4465
4466 private boolean enterIsSend() {
4467 final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
4468 return p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
4469 }
4470
4471 public boolean onArrowUpCtrlPressed() {
4472 final Message lastEditableMessage =
4473 conversation == null ? null : conversation.getLastEditableMessage();
4474 if (lastEditableMessage != null) {
4475 correctMessage(lastEditableMessage);
4476 return true;
4477 } else {
4478 Toast.makeText(getActivity(), R.string.could_not_correct_message, Toast.LENGTH_LONG)
4479 .show();
4480 return false;
4481 }
4482 }
4483
4484 @Override
4485 public void onTypingStarted() {
4486 final XmppConnectionService service =
4487 activity == null ? null : activity.xmppConnectionService;
4488 if (service == null) {
4489 return;
4490 }
4491 final Account.State status = conversation.getAccount().getStatus();
4492 if (status == Account.State.ONLINE
4493 && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
4494 service.sendChatState(conversation);
4495 }
4496 runOnUiThread(this::updateSendButton);
4497 }
4498
4499 @Override
4500 public void onTypingStopped() {
4501 final XmppConnectionService service =
4502 activity == null ? null : activity.xmppConnectionService;
4503 if (service == null) {
4504 return;
4505 }
4506 final Account.State status = conversation.getAccount().getStatus();
4507 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
4508 service.sendChatState(conversation);
4509 }
4510 }
4511
4512 @Override
4513 public void onTextDeleted() {
4514 final XmppConnectionService service =
4515 activity == null ? null : activity.xmppConnectionService;
4516 if (service == null) {
4517 return;
4518 }
4519 final Account.State status = conversation.getAccount().getStatus();
4520 if (status == Account.State.ONLINE
4521 && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
4522 service.sendChatState(conversation);
4523 }
4524 if (storeNextMessage()) {
4525 runOnUiThread(
4526 () -> {
4527 if (activity == null) {
4528 return;
4529 }
4530 activity.onConversationsListItemUpdated();
4531 });
4532 }
4533 runOnUiThread(this::updateSendButton);
4534 }
4535
4536 @Override
4537 public void onTextChanged() {
4538 if (conversation != null && conversation.getCorrectingMessage() != null) {
4539 runOnUiThread(this::updateSendButton);
4540 }
4541 }
4542
4543 @Override
4544 public boolean onTabPressed(boolean repeated) {
4545 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
4546 return false;
4547 }
4548 if (repeated) {
4549 completionIndex++;
4550 } else {
4551 lastCompletionLength = 0;
4552 completionIndex = 0;
4553 final String content = this.binding.textinput.getText().toString();
4554 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
4555 int start =
4556 lastCompletionCursor > 0
4557 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1
4558 : 0;
4559 firstWord = start == 0;
4560 incomplete = content.substring(start, lastCompletionCursor);
4561 }
4562 List<String> completions = new ArrayList<>();
4563 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
4564 String name = user.getNick();
4565 if (name != null && name.startsWith(incomplete)) {
4566 completions.add(name + (firstWord ? ": " : " "));
4567 }
4568 }
4569 Collections.sort(completions);
4570 if (completions.size() > completionIndex) {
4571 String completion = completions.get(completionIndex).substring(incomplete.length());
4572 this.binding
4573 .textinput
4574 .getEditableText()
4575 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4576 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
4577 lastCompletionLength = completion.length();
4578 } else {
4579 completionIndex = -1;
4580 this.binding
4581 .textinput
4582 .getEditableText()
4583 .delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
4584 lastCompletionLength = 0;
4585 }
4586 return true;
4587 }
4588
4589 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
4590 try {
4591 getActivity()
4592 .startIntentSenderForResult(
4593 pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0, Compatibility.pgpStartIntentSenderOptions());
4594 } catch (final SendIntentException ignored) {
4595 }
4596 }
4597
4598 @Override
4599 public void onBackendConnected() {
4600 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
4601 setupEmojiSearch();
4602 String uuid = pendingConversationsUuid.pop();
4603 if (uuid != null) {
4604 if (!findAndReInitByUuidOrArchive(uuid)) {
4605 return;
4606 }
4607 } else {
4608 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
4609 clearPending();
4610 activity.onConversationArchived(conversation);
4611 return;
4612 }
4613 }
4614 ActivityResult activityResult = postponedActivityResult.pop();
4615 if (activityResult != null) {
4616 handleActivityResult(activityResult);
4617 }
4618 clearPending();
4619 }
4620
4621 private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
4622 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
4623 if (conversation == null) {
4624 clearPending();
4625 activity.onConversationArchived(null);
4626 return false;
4627 }
4628 reInit(conversation);
4629 ScrollState scrollState = pendingScrollState.pop();
4630 String lastMessageUuid = pendingLastMessageUuid.pop();
4631 List<Attachment> attachments = pendingMediaPreviews.pop();
4632 if (scrollState != null) {
4633 setScrollPosition(scrollState, lastMessageUuid);
4634 }
4635 if (attachments != null && attachments.size() > 0) {
4636 Log.d(Config.LOGTAG, "had attachments on restore");
4637 mediaPreviewAdapter.addMediaPreviews(attachments);
4638 toggleInputMethod();
4639 }
4640 return true;
4641 }
4642
4643 private void clearPending() {
4644 if (postponedActivityResult.clear()) {
4645 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
4646 if (pendingTakePhotoUri.clear()) {
4647 Log.e(Config.LOGTAG, "cleared pending photo uri");
4648 }
4649 }
4650 if (pendingScrollState.clear()) {
4651 Log.e(Config.LOGTAG, "cleared scroll state");
4652 }
4653 if (pendingConversationsUuid.clear()) {
4654 Log.e(Config.LOGTAG, "cleared pending conversations uuid");
4655 }
4656 if (pendingMediaPreviews.clear()) {
4657 Log.e(Config.LOGTAG, "cleared pending media previews");
4658 }
4659 }
4660
4661 public Conversation getConversation() {
4662 return conversation;
4663 }
4664
4665 @Override
4666 public void onContactPictureLongClicked(View v, final Message message) {
4667 final String fingerprint;
4668 if (message.getEncryption() == Message.ENCRYPTION_PGP
4669 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
4670 fingerprint = "pgp";
4671 } else {
4672 fingerprint = message.getFingerprint();
4673 }
4674 final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
4675 final Contact contact = message.getContact();
4676 if (message.getStatus() <= Message.STATUS_RECEIVED
4677 && (contact == null || !contact.isSelf())) {
4678 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
4679 final Jid cp = message.getCounterpart();
4680 if (cp == null || cp.isBareJid()) {
4681 return;
4682 }
4683 final Jid tcp = message.getTrueCounterpart();
4684 final String occupantId = message.getOccupantId();
4685 final User userByRealJid =
4686 tcp != null
4687 ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp, occupantId)
4688 : null;
4689 final User userByOccupantId =
4690 occupantId != null
4691 ? conversation.getMucOptions().findUserByOccupantId(occupantId, cp)
4692 : null;
4693 final User user =
4694 userByRealJid != null
4695 ? userByRealJid
4696 : (userByOccupantId != null ? userByOccupantId : conversation.getMucOptions().findUserByFullJid(cp));
4697 if (user == null) return;
4698 popupMenu.inflate(R.menu.muc_details_context);
4699 final Menu menu = popupMenu.getMenu();
4700 MucDetailsContextMenuHelper.configureMucDetailsContextMenu(
4701 activity, menu, conversation, user);
4702 popupMenu.setOnMenuItemClickListener(
4703 menuItem ->
4704 MucDetailsContextMenuHelper.onContextItemSelected(
4705 menuItem, user, activity, fingerprint));
4706 } else {
4707 popupMenu.inflate(R.menu.one_on_one_context);
4708 popupMenu.setOnMenuItemClickListener(
4709 item -> {
4710 switch (item.getItemId()) {
4711 case R.id.action_contact_details:
4712 activity.switchToContactDetails(
4713 message.getContact(), fingerprint);
4714 break;
4715 case R.id.action_show_qr_code:
4716 activity.showQrCode(
4717 "xmpp:"
4718 + message.getContact()
4719 .getJid()
4720 .asBareJid()
4721 .toEscapedString());
4722 break;
4723 }
4724 return true;
4725 });
4726 }
4727 } else {
4728 popupMenu.inflate(R.menu.account_context);
4729 final Menu menu = popupMenu.getMenu();
4730 menu.findItem(R.id.action_manage_accounts)
4731 .setVisible(QuickConversationsService.isConversations());
4732 popupMenu.setOnMenuItemClickListener(
4733 item -> {
4734 final XmppActivity activity = this.activity;
4735 if (activity == null) {
4736 Log.e(Config.LOGTAG, "Unable to perform action. no context provided");
4737 return true;
4738 }
4739 switch (item.getItemId()) {
4740 case R.id.action_show_qr_code:
4741 activity.showQrCode(conversation.getAccount().getShareableUri());
4742 break;
4743 case R.id.action_account_details:
4744 activity.switchToAccount(
4745 message.getConversation().getAccount(), fingerprint);
4746 break;
4747 case R.id.action_manage_accounts:
4748 AccountUtils.launchManageAccounts(activity);
4749 break;
4750 }
4751 return true;
4752 });
4753 }
4754 popupMenu.show();
4755 }
4756
4757 @Override
4758 public void onContactPictureClicked(Message message) {
4759 setThread(message.getThread());
4760 if (message.isPrivateMessage()) {
4761 privateMessageWith(message.getCounterpart());
4762 return;
4763 }
4764 forkNullThread(message);
4765 conversation.setUserSelectedThread(true);
4766
4767 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
4768 if (received) {
4769 if (message.getConversation() instanceof Conversation
4770 && message.getConversation().getMode() == Conversation.MODE_MULTI) {
4771 Jid tcp = message.getTrueCounterpart();
4772 Jid user = message.getCounterpart();
4773 if (user != null && !user.isBareJid()) {
4774 final MucOptions mucOptions =
4775 ((Conversation) message.getConversation()).getMucOptions();
4776 if (mucOptions.participating()
4777 || ((Conversation) message.getConversation()).getNextCounterpart()
4778 != null) {
4779 MucOptions.User mucUser = mucOptions.findUserByFullJid(user);
4780 MucOptions.User tcpMucUser = mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid());
4781 if (mucUser == null && tcpMucUser == null) {
4782 Toast.makeText(
4783 getActivity(),
4784 activity.getString(
4785 R.string.user_has_left_conference,
4786 user.getResource()),
4787 Toast.LENGTH_SHORT)
4788 .show();
4789 }
4790 highlightInConference(mucUser == null || mucUser.getNick() == null ? (tcpMucUser == null || tcpMucUser.getNick() == null ? user.getResource() : tcpMucUser.getNick()) : mucUser.getNick());
4791 } else {
4792 Toast.makeText(
4793 getActivity(),
4794 R.string.you_are_not_participating,
4795 Toast.LENGTH_SHORT)
4796 .show();
4797 }
4798 }
4799 }
4800 }
4801 }
4802
4803 private Activity requireActivity() {
4804 Activity activity = getActivity();
4805 if (activity == null) activity = this.activity;
4806 if (activity == null) {
4807 throw new IllegalStateException("Activity not attached");
4808 }
4809 return activity;
4810 }
4811}