1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.app.Activity;
6import android.content.SharedPreferences;
7import android.content.pm.PackageManager;
8import android.databinding.DataBindingUtil;
9import android.net.Uri;
10import android.os.Build;
11import android.preference.PreferenceManager;
12import android.provider.MediaStore;
13import android.support.annotation.IdRes;
14import android.support.annotation.NonNull;
15import android.support.annotation.StringRes;
16import android.support.v7.app.AlertDialog;
17import android.app.Fragment;
18import android.app.PendingIntent;
19import android.content.ActivityNotFoundException;
20import android.content.Context;
21import android.content.DialogInterface;
22import android.content.Intent;
23import android.content.IntentSender.SendIntentException;
24import android.os.Bundle;
25import android.os.Handler;
26import android.os.SystemClock;
27import android.support.v13.view.inputmethod.InputConnectionCompat;
28import android.support.v13.view.inputmethod.InputContentInfoCompat;
29import android.text.Editable;
30import android.util.Log;
31import android.view.ContextMenu;
32import android.view.ContextMenu.ContextMenuInfo;
33import android.view.Gravity;
34import android.view.LayoutInflater;
35import android.view.Menu;
36import android.view.MenuInflater;
37import android.view.MenuItem;
38import android.view.MotionEvent;
39import android.view.View;
40import android.view.View.OnClickListener;
41import android.view.ViewGroup;
42import android.view.inputmethod.EditorInfo;
43import android.view.inputmethod.InputMethodManager;
44import android.widget.AbsListView;
45import android.widget.AbsListView.OnScrollListener;
46import android.widget.AdapterView;
47import android.widget.AdapterView.AdapterContextMenuInfo;
48import android.widget.CheckBox;
49import android.widget.ListView;
50import android.widget.PopupMenu;
51import android.widget.TextView.OnEditorActionListener;
52import android.widget.Toast;
53
54import java.util.ArrayList;
55import java.util.Arrays;
56import java.util.Collections;
57import java.util.HashSet;
58import java.util.Iterator;
59import java.util.List;
60import java.util.Set;
61import java.util.UUID;
62import java.util.concurrent.atomic.AtomicBoolean;
63
64import eu.siacs.conversations.Config;
65import eu.siacs.conversations.R;
66import eu.siacs.conversations.crypto.axolotl.AxolotlService;
67import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
68import eu.siacs.conversations.databinding.FragmentConversationBinding;
69import eu.siacs.conversations.entities.Account;
70import eu.siacs.conversations.entities.Blockable;
71import eu.siacs.conversations.entities.Contact;
72import eu.siacs.conversations.entities.Conversation;
73import eu.siacs.conversations.entities.DownloadableFile;
74import eu.siacs.conversations.entities.Message;
75import eu.siacs.conversations.entities.MucOptions;
76import eu.siacs.conversations.entities.Presence;
77import eu.siacs.conversations.entities.ReadByMarker;
78import eu.siacs.conversations.entities.Transferable;
79import eu.siacs.conversations.entities.TransferablePlaceholder;
80import eu.siacs.conversations.http.HttpDownloadConnection;
81import eu.siacs.conversations.persistance.FileBackend;
82import eu.siacs.conversations.services.MessageArchiveService;
83import eu.siacs.conversations.services.XmppConnectionService;
84import eu.siacs.conversations.ui.adapter.MessageAdapter;
85import eu.siacs.conversations.ui.util.ActivityResult;
86import eu.siacs.conversations.ui.util.AttachmentTool;
87import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
88import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
89import eu.siacs.conversations.ui.util.PendingItem;
90import eu.siacs.conversations.ui.util.PresenceSelector;
91import eu.siacs.conversations.ui.util.ScrollState;
92import eu.siacs.conversations.ui.util.SendButtonAction;
93import eu.siacs.conversations.ui.util.SendButtonTool;
94import eu.siacs.conversations.ui.widget.EditMessage;
95import eu.siacs.conversations.utils.MessageUtils;
96import eu.siacs.conversations.utils.NickValidityChecker;
97import eu.siacs.conversations.utils.StylingHelper;
98import eu.siacs.conversations.utils.TimeframeUtils;
99import eu.siacs.conversations.utils.UIHelper;
100import eu.siacs.conversations.xmpp.XmppConnection;
101import eu.siacs.conversations.xmpp.chatstate.ChatState;
102import eu.siacs.conversations.xmpp.jingle.JingleConnection;
103import rocks.xmpp.addr.Jid;
104
105import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
106import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION;
107
108
109public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener {
110
111
112 public static final int REQUEST_SEND_MESSAGE = 0x0201;
113 public static final int REQUEST_DECRYPT_PGP = 0x0202;
114 public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
115 public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
116 public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
117 public static final int REQUEST_START_DOWNLOAD = 0x0210;
118 public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
119 public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
120 public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
121 public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
122 public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
123 public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
124 public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
125 public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
126
127 public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
128 public static final String STATE_CONVERSATION_UUID = ConversationFragment.class.getName() + ".uuid";
129 public static final String STATE_SCROLL_POSITION = ConversationFragment.class.getName() + ".scroll_position";
130 public static final String STATE_PHOTO_URI = ConversationFragment.class.getName() + ".take_photo_uri";
131
132
133 final protected List<Message> messageList = new ArrayList<>();
134 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
135 private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
136 private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
137 private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
138 private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
139 private final PendingItem<Message> pendingMessage = new PendingItem<>();
140 public Uri mPendingEditorContent = null;
141 protected MessageAdapter messageListAdapter;
142 private Conversation conversation;
143 private FragmentConversationBinding binding;
144 private Toast messageLoaderToast;
145 private ConversationsActivity activity;
146 private boolean reInitRequiredOnStart = true;
147 private OnClickListener clickToMuc = new OnClickListener() {
148
149 @Override
150 public void onClick(View v) {
151 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
152 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
153 intent.putExtra("uuid", conversation.getUuid());
154 startActivity(intent);
155 }
156 };
157 private OnClickListener leaveMuc = new OnClickListener() {
158
159 @Override
160 public void onClick(View v) {
161 activity.xmppConnectionService.archiveConversation(conversation);
162 }
163 };
164 private OnClickListener joinMuc = new OnClickListener() {
165
166 @Override
167 public void onClick(View v) {
168 activity.xmppConnectionService.joinMuc(conversation);
169 }
170 };
171 private OnClickListener enterPassword = new OnClickListener() {
172
173 @Override
174 public void onClick(View v) {
175 MucOptions muc = conversation.getMucOptions();
176 String password = muc.getPassword();
177 if (password == null) {
178 password = "";
179 }
180 activity.quickPasswordEdit(password, value -> {
181 activity.xmppConnectionService.providePasswordForMuc(conversation, value);
182 return null;
183 });
184 }
185 };
186 private OnScrollListener mOnScrollListener = new OnScrollListener() {
187
188 @Override
189 public void onScrollStateChanged(AbsListView view, int scrollState) {
190 // TODO Auto-generated method stub
191
192 }
193
194 @Override
195 public void onScroll(final AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
196 synchronized (ConversationFragment.this.messageList) {
197 if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true, false) && messageList.size() > 0) {
198 long timestamp;
199 if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
200 timestamp = messageList.get(1).getTimeSent();
201 } else {
202 timestamp = messageList.get(0).getTimeSent();
203 }
204 activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
205 @Override
206 public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
207 if (ConversationFragment.this.conversation != conversation) {
208 conversation.messagesLoaded.set(true);
209 return;
210 }
211 runOnUiThread(() -> {
212 final int oldPosition = binding.messagesView.getFirstVisiblePosition();
213 Message message = null;
214 int childPos;
215 for (childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
216 message = messageList.get(oldPosition + childPos);
217 if (message.getType() != Message.TYPE_STATUS) {
218 break;
219 }
220 }
221 final String uuid = message != null ? message.getUuid() : null;
222 View v = binding.messagesView.getChildAt(childPos);
223 final int pxOffset = (v == null) ? 0 : v.getTop();
224 ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
225 try {
226 updateStatusMessages();
227 } catch (IllegalStateException e) {
228 Log.d(Config.LOGTAG, "caught illegal state exception while updating status messages");
229 }
230 messageListAdapter.notifyDataSetChanged();
231 int pos = Math.max(getIndexOf(uuid, messageList), 0);
232 binding.messagesView.setSelectionFromTop(pos, pxOffset);
233 if (messageLoaderToast != null) {
234 messageLoaderToast.cancel();
235 }
236 conversation.messagesLoaded.set(true);
237 });
238 }
239
240 @Override
241 public void informUser(final int resId) {
242
243 runOnUiThread(() -> {
244 if (messageLoaderToast != null) {
245 messageLoaderToast.cancel();
246 }
247 if (ConversationFragment.this.conversation != conversation) {
248 return;
249 }
250 messageLoaderToast = Toast.makeText(view.getContext(), resId, Toast.LENGTH_LONG);
251 messageLoaderToast.show();
252 });
253
254 }
255 });
256
257 }
258 }
259 }
260 };
261 private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
262 @Override
263 public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
264 // try to get permission to read the image, if applicable
265 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
266 try {
267 inputContentInfo.requestPermission();
268 } catch (Exception e) {
269 Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
270 Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()), Toast.LENGTH_LONG
271 ).show();
272 return false;
273 }
274 }
275 if (hasStoragePermission(REQUEST_ADD_EDITOR_CONTENT)) {
276 attachImageToConversation(inputContentInfo.getContentUri());
277 } else {
278 mPendingEditorContent = inputContentInfo.getContentUri();
279 }
280 return true;
281 }
282 };
283 private Message selectedMessage;
284 private OnClickListener mEnableAccountListener = new OnClickListener() {
285 @Override
286 public void onClick(View v) {
287 final Account account = conversation == null ? null : conversation.getAccount();
288 if (account != null) {
289 account.setOption(Account.OPTION_DISABLED, false);
290 activity.xmppConnectionService.updateAccount(account);
291 }
292 }
293 };
294 private OnClickListener mUnblockClickListener = new OnClickListener() {
295 @Override
296 public void onClick(final View v) {
297 v.post(() -> v.setVisibility(View.INVISIBLE));
298 if (conversation.isDomainBlocked()) {
299 BlockContactDialog.show(activity, conversation);
300 } else {
301 unblockConversation(conversation);
302 }
303 }
304 };
305 private OnClickListener mBlockClickListener = this::showBlockSubmenu;
306 private OnClickListener mAddBackClickListener = new OnClickListener() {
307
308 @Override
309 public void onClick(View v) {
310 final Contact contact = conversation == null ? null : conversation.getContact();
311 if (contact != null) {
312 activity.xmppConnectionService.createContact(contact, true);
313 activity.switchToContactDetails(contact);
314 }
315 }
316 };
317 private View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
318 private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
319 @Override
320 public void onClick(View v) {
321 final Contact contact = conversation == null ? null : conversation.getContact();
322 if (contact != null) {
323 activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
324 activity.xmppConnectionService.getPresenceGenerator()
325 .sendPresenceUpdatesTo(contact));
326 hideSnackbar();
327 }
328 }
329 };
330 protected OnClickListener clickToDecryptListener = new OnClickListener() {
331
332 @Override
333 public void onClick(View v) {
334 PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
335 if (pendingIntent != null) {
336 try {
337 getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(),
338 REQUEST_DECRYPT_PGP,
339 null,
340 0,
341 0,
342 0);
343 } catch (SendIntentException e) {
344 Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
345 conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
346 }
347 }
348 updateSnackBar(conversation);
349 }
350 };
351 private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
352 private OnEditorActionListener mEditorActionListener = (v, actionId, event) -> {
353 if (actionId == EditorInfo.IME_ACTION_SEND) {
354 InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
355 if (imm != null && imm.isFullscreenMode()) {
356 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
357 }
358 sendMessage();
359 return true;
360 } else {
361 return false;
362 }
363 };
364 private OnClickListener mSendButtonListener = new OnClickListener() {
365
366 @Override
367 public void onClick(View v) {
368 Object tag = v.getTag();
369 if (tag instanceof SendButtonAction) {
370 SendButtonAction action = (SendButtonAction) tag;
371 switch (action) {
372 case TAKE_PHOTO:
373 case RECORD_VIDEO:
374 case SEND_LOCATION:
375 case RECORD_VOICE:
376 case CHOOSE_PICTURE:
377 attachFile(action.toChoice());
378 break;
379 case CANCEL:
380 if (conversation != null) {
381 if (conversation.setCorrectingMessage(null)) {
382 binding.textinput.setText("");
383 binding.textinput.append(conversation.getDraftMessage());
384 conversation.setDraftMessage(null);
385 } else if (conversation.getMode() == Conversation.MODE_MULTI) {
386 conversation.setNextCounterpart(null);
387 }
388 updateChatMsgHint();
389 updateSendButton();
390 updateEditablity();
391 }
392 break;
393 default:
394 sendMessage();
395 }
396 } else {
397 sendMessage();
398 }
399 }
400 };
401 private int completionIndex = 0;
402 private int lastCompletionLength = 0;
403 private String incomplete;
404 private int lastCompletionCursor;
405 private boolean firstWord = false;
406 private Message mPendingDownloadableMessage;
407
408 private static ConversationFragment findConversationFragment(Activity activity) {
409 Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
410 if (fragment != null && fragment instanceof ConversationFragment) {
411 return (ConversationFragment) fragment;
412 }
413 fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
414 if (fragment != null && fragment instanceof ConversationFragment) {
415 return (ConversationFragment) fragment;
416 }
417 return null;
418 }
419
420 public static void startStopPending(Activity activity) {
421 ConversationFragment fragment = findConversationFragment(activity);
422 if (fragment != null) {
423 fragment.messageListAdapter.startStopPending();
424 }
425 }
426
427 public static void downloadFile(Activity activity, Message message) {
428 ConversationFragment fragment = findConversationFragment(activity);
429 if (fragment != null) {
430 fragment.startDownloadable(message);
431 }
432 }
433
434 public static void registerPendingMessage(Activity activity, Message message) {
435 ConversationFragment fragment = findConversationFragment(activity);
436 if (fragment != null) {
437 fragment.pendingMessage.push(message);
438 }
439 }
440
441 public static void openPendingMessage(Activity activity) {
442 ConversationFragment fragment = findConversationFragment(activity);
443 if (fragment != null) {
444 Message message = fragment.pendingMessage.pop();
445 if (message != null) {
446 fragment.messageListAdapter.openDownloadable(message);
447 }
448 }
449 }
450
451 public static Conversation getConversation(Activity activity) {
452 return getConversation(activity, R.id.secondary_fragment);
453 }
454
455 private static Conversation getConversation(Activity activity, @IdRes int res) {
456 final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
457 if (fragment != null && fragment instanceof ConversationFragment) {
458 return ((ConversationFragment) fragment).getConversation();
459 } else {
460 return null;
461 }
462 }
463
464 public static Conversation getConversationReliable(Activity activity) {
465 final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
466 if (conversation != null) {
467 return conversation;
468 }
469 return getConversation(activity, R.id.main_fragment);
470 }
471
472 private static boolean allGranted(int[] grantResults) {
473 for (int grantResult : grantResults) {
474 if (grantResult != PackageManager.PERMISSION_GRANTED) {
475 return false;
476 }
477 }
478 return true;
479 }
480
481 private static String getFirstDenied(int[] grantResults, String[] permissions) {
482 for (int i = 0; i < grantResults.length; ++i) {
483 if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
484 return permissions[i];
485 }
486 }
487 return null;
488 }
489
490 private int getIndexOf(String uuid, List<Message> messages) {
491 if (uuid == null) {
492 return messages.size() - 1;
493 }
494 for (int i = 0; i < messages.size(); ++i) {
495 if (uuid.equals(messages.get(i).getUuid())) {
496 return i;
497 } else {
498 Message next = messages.get(i);
499 while (next != null && next.wasMergedIntoPrevious()) {
500 if (uuid.equals(next.getUuid())) {
501 return i;
502 }
503 next = next.next();
504 }
505
506 }
507 }
508 return -1;
509 }
510
511 private ScrollState getScrollPosition() {
512 final ListView listView = this.binding.messagesView;
513 if (listView.getCount() == 0 || listView.getLastVisiblePosition() == listView.getCount() - 1) {
514 return null;
515 } else {
516 final int pos = listView.getFirstVisiblePosition();
517 final View view = listView.getChildAt(0);
518 if (view == null) {
519 return null;
520 } else {
521 return new ScrollState(pos, view.getTop());
522 }
523 }
524 }
525
526 private void setScrollPosition(ScrollState scrollPosition) {
527 if (scrollPosition != null) {
528 //TODO maybe this needs a 'post'
529 this.binding.messagesView.setSelectionFromTop(scrollPosition.position, scrollPosition.offset);
530 }
531 }
532
533 private void attachLocationToConversation(Conversation conversation, Uri uri) {
534 if (conversation == null) {
535 return;
536 }
537 activity.xmppConnectionService.attachLocationToConversation(conversation, uri, new UiCallback<Message>() {
538
539 @Override
540 public void success(Message message) {
541
542 }
543
544 @Override
545 public void error(int errorCode, Message object) {
546 //TODO show possible pgp error
547 }
548
549 @Override
550 public void userInputRequried(PendingIntent pi, Message object) {
551
552 }
553 });
554 }
555
556 private void attachFileToConversation(Conversation conversation, Uri uri, String type) {
557 if (conversation == null) {
558 return;
559 }
560 final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
561 prepareFileToast.show();
562 activity.delegateUriPermissionsToService(uri);
563 activity.xmppConnectionService.attachFileToConversation(conversation, uri, type, new UiInformableCallback<Message>() {
564 @Override
565 public void inform(final String text) {
566 hidePrepareFileToast(prepareFileToast);
567 runOnUiThread(() -> activity.replaceToast(text));
568 }
569
570 @Override
571 public void success(Message message) {
572 runOnUiThread(() -> activity.hideToast());
573 hidePrepareFileToast(prepareFileToast);
574 }
575
576 @Override
577 public void error(final int errorCode, Message message) {
578 hidePrepareFileToast(prepareFileToast);
579 runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
580
581 }
582
583 @Override
584 public void userInputRequried(PendingIntent pi, Message message) {
585 hidePrepareFileToast(prepareFileToast);
586 }
587 });
588 }
589
590 public void attachImageToConversation(Uri uri) {
591 this.attachImageToConversation(conversation, uri);
592 }
593
594 private void attachImageToConversation(Conversation conversation, Uri uri) {
595 if (conversation == null) {
596 return;
597 }
598 final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
599 prepareFileToast.show();
600 activity.delegateUriPermissionsToService(uri);
601 activity.xmppConnectionService.attachImageToConversation(conversation, uri,
602 new UiCallback<Message>() {
603
604 @Override
605 public void userInputRequried(PendingIntent pi, Message object) {
606 hidePrepareFileToast(prepareFileToast);
607 }
608
609 @Override
610 public void success(Message message) {
611 hidePrepareFileToast(prepareFileToast);
612 }
613
614 @Override
615 public void error(final int error, Message message) {
616 hidePrepareFileToast(prepareFileToast);
617 activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
618 }
619 });
620 }
621
622 private void hidePrepareFileToast(final Toast prepareFileToast) {
623 if (prepareFileToast != null && activity != null) {
624 activity.runOnUiThread(prepareFileToast::cancel);
625 }
626 }
627
628 private void sendMessage() {
629 final String body = this.binding.textinput.getText().toString();
630 final Conversation conversation = this.conversation;
631 if (body.length() == 0 || conversation == null) {
632 return;
633 }
634 final Message message;
635 if (conversation.getCorrectingMessage() == null) {
636 message = new Message(conversation, body, conversation.getNextEncryption());
637 if (conversation.getMode() == Conversation.MODE_MULTI) {
638 final Jid nextCounterpart = conversation.getNextCounterpart();
639 if (nextCounterpart != null) {
640 message.setCounterpart(nextCounterpart);
641 message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(nextCounterpart));
642 message.setType(Message.TYPE_PRIVATE);
643 }
644 }
645 } else {
646 message = conversation.getCorrectingMessage();
647 message.setBody(body);
648 message.setEdited(message.getUuid());
649 message.setUuid(UUID.randomUUID().toString());
650 }
651 switch (message.getConversation().getNextEncryption()) {
652 case Message.ENCRYPTION_PGP:
653 sendPgpMessage(message);
654 break;
655 case Message.ENCRYPTION_AXOLOTL:
656 if (!trustKeysIfNeeded(REQUEST_TRUST_KEYS_TEXT)) {
657 sendMessage(message);
658 }
659 break;
660 default:
661 sendMessage(message);
662 }
663 }
664
665 protected boolean trustKeysIfNeeded(int requestCode) {
666 return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
667 }
668
669 protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
670 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
671 final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
672 boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
673 boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
674 boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
675 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
676 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
677 if (hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
678 axolotlService.createSessionsIfNeeded(conversation);
679 Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
680 String[] contacts = new String[targets.size()];
681 for (int i = 0; i < contacts.length; ++i) {
682 contacts[i] = targets.get(i).toString();
683 }
684 intent.putExtra("contacts", contacts);
685 intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString());
686 intent.putExtra("choice", attachmentChoice);
687 intent.putExtra("conversation", conversation.getUuid());
688 startActivityForResult(intent, requestCode);
689 return true;
690 } else {
691 return false;
692 }
693 }
694
695 public void updateChatMsgHint() {
696 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
697 if (conversation.getCorrectingMessage() != null) {
698 this.binding.textinput.setHint(R.string.send_corrected_message);
699 } else if (multi && conversation.getNextCounterpart() != null) {
700 this.binding.textinput.setHint(getString(
701 R.string.send_private_message_to,
702 conversation.getNextCounterpart().getResource()));
703 } else if (multi && !conversation.getMucOptions().participating()) {
704 this.binding.textinput.setHint(R.string.you_are_not_participating);
705 } else {
706 this.binding.textinput.setHint(UIHelper.getMessageHint(getActivity(), conversation));
707 getActivity().invalidateOptionsMenu();
708 }
709 }
710
711 public void setupIme() {
712 this.binding.textinput.refreshIme();
713 }
714
715 private void handleActivityResult(ActivityResult activityResult) {
716 if (activityResult.resultCode == Activity.RESULT_OK) {
717 handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
718 } else {
719 handleNegativeActivityResult(activityResult.requestCode);
720 }
721 }
722
723 private void handlePositiveActivityResult(int requestCode, final Intent data) {
724 switch (requestCode) {
725 case REQUEST_TRUST_KEYS_TEXT:
726 final String body = this.binding.textinput.getText().toString();
727 Message message = new Message(conversation, body, conversation.getNextEncryption());
728 sendMessage(message);
729 break;
730 case REQUEST_TRUST_KEYS_MENU:
731 int choice = data.getIntExtra("choice", ATTACHMENT_CHOICE_INVALID);
732 selectPresenceToAttachFile(choice);
733 break;
734 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
735 List<Uri> imageUris = AttachmentTool.extractUriFromIntent(data);
736 for (Iterator<Uri> i = imageUris.iterator(); i.hasNext(); i.remove()) {
737 Log.d(Config.LOGTAG, "ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
738 attachImageToConversation(conversation, i.next());
739 }
740 break;
741 case ATTACHMENT_CHOICE_TAKE_PHOTO:
742 Uri takePhotoUri = pendingTakePhotoUri.pop();
743 if (takePhotoUri != null) {
744 attachImageToConversation(conversation, takePhotoUri);
745 } else {
746 Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
747 }
748 break;
749 case ATTACHMENT_CHOICE_CHOOSE_FILE:
750 case ATTACHMENT_CHOICE_RECORD_VIDEO:
751 case ATTACHMENT_CHOICE_RECORD_VOICE:
752 final List<Uri> fileUris = AttachmentTool.extractUriFromIntent(data);
753 String type = data.getType();
754 final PresenceSelector.OnPresenceSelected callback = () -> {
755 for (Iterator<Uri> i = fileUris.iterator(); i.hasNext(); i.remove()) {
756 Log.d(Config.LOGTAG, "ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
757 attachFileToConversation(conversation, i.next(), type);
758 }
759 };
760 if (conversation == null || conversation.getMode() == Conversation.MODE_MULTI || FileBackend.allFilesUnderSize(getActivity(), fileUris, getMaxHttpUploadSize(conversation))) {
761 callback.onPresenceSelected();
762 } else {
763 activity.selectPresence(conversation, callback);
764 }
765 break;
766 case ATTACHMENT_CHOICE_LOCATION:
767 double latitude = data.getDoubleExtra("latitude", 0);
768 double longitude = data.getDoubleExtra("longitude", 0);
769 Uri geo = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
770 attachLocationToConversation(conversation, geo);
771 break;
772 case REQUEST_INVITE_TO_CONVERSATION:
773 XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data);
774 if (invite != null) {
775 if (invite.execute(activity)) {
776 activity.mToast = Toast.makeText(activity, R.string.creating_conference, Toast.LENGTH_LONG);
777 activity.mToast.show();
778 }
779 }
780 break;
781 }
782 }
783
784 private void handleNegativeActivityResult(int requestCode) {
785 switch (requestCode) {
786 //nothing to do for now
787 }
788 }
789
790 @Override
791 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
792 super.onActivityResult(requestCode, resultCode, data);
793 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
794 if (activity != null && activity.xmppConnectionService != null) {
795 handleActivityResult(activityResult);
796 } else {
797 this.postponedActivityResult.push(activityResult);
798 }
799 }
800
801 public void unblockConversation(final Blockable conversation) {
802 activity.xmppConnectionService.sendUnblockRequest(conversation);
803 }
804
805 @Override
806 public void onAttach(Activity activity) {
807 super.onAttach(activity);
808 Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
809 if (activity instanceof ConversationsActivity) {
810 this.activity = (ConversationsActivity) activity;
811 } else {
812 throw new IllegalStateException("Trying to attach fragment to activity that is not the ConversationsActivity");
813 }
814 }
815
816 @Override
817 public void onDetach() {
818 super.onDetach();
819 this.activity = null; //TODO maybe not a good idea since some callbacks really need it
820 }
821
822 @Override
823 public void onCreate(Bundle savedInstanceState) {
824 super.onCreate(savedInstanceState);
825 setHasOptionsMenu(true);
826 }
827
828 @Override
829 public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
830 menuInflater.inflate(R.menu.fragment_conversation, menu);
831 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
832 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
833 final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
834 final MenuItem menuMute = menu.findItem(R.id.action_mute);
835 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
836
837
838 if (conversation != null) {
839 if (conversation.getMode() == Conversation.MODE_MULTI) {
840 menuContactDetails.setVisible(false);
841 menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
842 } else {
843 menuContactDetails.setVisible(!this.conversation.withSelf());
844 menuMucDetails.setVisible(false);
845 final XmppConnectionService service = activity.xmppConnectionService;
846 menuInviteContact.setVisible(service != null && service.findConferenceServer(conversation.getAccount()) != null);
847 }
848 if (conversation.isMuted()) {
849 menuMute.setVisible(false);
850 } else {
851 menuUnmute.setVisible(false);
852 }
853 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
854 ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
855 }
856 super.onCreateOptionsMenu(menu, menuInflater);
857 }
858
859 @Override
860 public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
861 this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
862 binding.getRoot().setOnClickListener(null); //TODO why the fuck did we do this?
863
864 binding.textinput.addTextChangedListener(new StylingHelper.MessageEditorStyler(binding.textinput));
865
866 binding.textinput.setOnEditorActionListener(mEditorActionListener);
867 binding.textinput.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
868
869 binding.textSendButton.setOnClickListener(this.mSendButtonListener);
870
871 binding.messagesView.setOnScrollListener(mOnScrollListener);
872 binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
873 messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
874 messageListAdapter.setOnContactPictureClicked(message -> {
875 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
876 if (received) {
877 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
878 Jid user = message.getCounterpart();
879 if (user != null && !user.isBareJid()) {
880 final MucOptions mucOptions = message.getConversation().getMucOptions();
881 if (mucOptions.participating() || message.getConversation().getNextCounterpart() != null) {
882 if (!mucOptions.isUserInRoom(user)) {
883 Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
884 }
885 highlightInConference(user.getResource());
886 } else {
887 Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
888 }
889 }
890 return;
891 } else {
892 if (!message.getContact().isSelf()) {
893 String fingerprint;
894 if (message.getEncryption() == Message.ENCRYPTION_PGP
895 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
896 fingerprint = "pgp";
897 } else {
898 fingerprint = message.getFingerprint();
899 }
900 activity.switchToContactDetails(message.getContact(), fingerprint);
901 return;
902 }
903 }
904 }
905 Account account = message.getConversation().getAccount();
906 Intent intent = new Intent(activity, EditAccountActivity.class);
907 intent.putExtra("jid", account.getJid().asBareJid().toString());
908 String fingerprint;
909 if (message.getEncryption() == Message.ENCRYPTION_PGP
910 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
911 fingerprint = "pgp";
912 } else {
913 fingerprint = message.getFingerprint();
914 }
915 intent.putExtra("fingerprint", fingerprint);
916 startActivity(intent);
917 });
918 messageListAdapter.setOnContactPictureLongClicked(message -> {
919 if (message.getStatus() <= Message.STATUS_RECEIVED) {
920 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
921 final MucOptions mucOptions = conversation.getMucOptions();
922 if (!mucOptions.allowPm()) {
923 Toast.makeText(getActivity(), R.string.private_messages_are_disabled, Toast.LENGTH_SHORT).show();
924 return;
925 }
926 Jid user = message.getCounterpart();
927 if (user != null && !user.isBareJid()) {
928 if (mucOptions.isUserInRoom(user)) {
929 privateMessageWith(user);
930 } else {
931 Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
932 }
933 }
934 }
935 } else {
936 activity.showQrCode(conversation.getAccount().getShareableUri());
937 }
938 });
939 messageListAdapter.setOnQuoteListener(this::quoteText);
940 binding.messagesView.setAdapter(messageListAdapter);
941
942 registerForContextMenu(binding.messagesView);
943
944 return binding.getRoot();
945 }
946
947 private void quoteText(String text) {
948 if (binding.textinput.isEnabled()) {
949 text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
950 Editable editable = binding.textinput.getEditableText();
951 int position = binding.textinput.getSelectionEnd();
952 if (position == -1) position = editable.length();
953 if (position > 0 && editable.charAt(position - 1) != '\n') {
954 editable.insert(position++, "\n");
955 }
956 editable.insert(position, text);
957 position += text.length();
958 editable.insert(position++, "\n");
959 if (position < editable.length() && editable.charAt(position) != '\n') {
960 editable.insert(position, "\n");
961 }
962 binding.textinput.setSelection(position);
963 binding.textinput.requestFocus();
964 InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
965 if (inputMethodManager != null) {
966 inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
967 }
968 }
969 }
970
971 private static void hideSoftKeyboard(final Activity activity) {
972 InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
973 View view = activity.getCurrentFocus();
974 if (view != null && imm != null) {
975 imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
976 }
977 }
978
979 private void quoteMessage(Message message) {
980 quoteText(MessageUtils.prepareQuote(message));
981 }
982
983 @Override
984 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
985 synchronized (this.messageList) {
986 super.onCreateContextMenu(menu, v, menuInfo);
987 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
988 this.selectedMessage = this.messageList.get(acmi.position);
989 populateContextMenu(menu);
990 }
991 }
992
993 private void populateContextMenu(ContextMenu menu) {
994 final Message m = this.selectedMessage;
995 final Transferable t = m.getTransferable();
996 Message relevantForCorrection = m;
997 while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
998 relevantForCorrection = relevantForCorrection.next();
999 }
1000 if (m.getType() != Message.TYPE_STATUS) {
1001
1002 final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
1003 && m.getType() != Message.TYPE_PRIVATE
1004 && !(t instanceof TransferablePlaceholder);
1005 final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1006 || m.getEncryption() == Message.ENCRYPTION_PGP;
1007 final boolean receiving = m.getStatus() == Message.STATUS_RECEIVED && (t instanceof JingleConnection || t instanceof HttpDownloadConnection);
1008 activity.getMenuInflater().inflate(R.menu.message_context, menu);
1009 menu.setHeaderTitle(R.string.message_options);
1010 MenuItem copyMessage = menu.findItem(R.id.copy_message);
1011 MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1012 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1013 MenuItem correctMessage = menu.findItem(R.id.correct_message);
1014 MenuItem shareWith = menu.findItem(R.id.share_with);
1015 MenuItem sendAgain = menu.findItem(R.id.send_again);
1016 MenuItem copyUrl = menu.findItem(R.id.copy_url);
1017 MenuItem downloadFile = menu.findItem(R.id.download_file);
1018 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1019 MenuItem deleteFile = menu.findItem(R.id.delete_file);
1020 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1021 if (!treatAsFile && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
1022 copyMessage.setVisible(true);
1023 quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
1024 }
1025 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
1026 retryDecryption.setVisible(true);
1027 }
1028 if (relevantForCorrection.getType() == Message.TYPE_TEXT
1029 && relevantForCorrection.isLastCorrectableMessage()
1030 && (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
1031 correctMessage.setVisible(true);
1032 }
1033 if ((treatAsFile && !receiving) || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
1034 shareWith.setVisible(true);
1035 }
1036 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1037 sendAgain.setVisible(true);
1038 }
1039 if (m.hasFileOnRemoteHost()
1040 || m.isGeoUri()
1041 || m.treatAsDownloadable()
1042 || (t != null && t instanceof HttpDownloadConnection)) {
1043 copyUrl.setVisible(true);
1044 }
1045 if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
1046 downloadFile.setVisible(true);
1047 downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
1048 }
1049 boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1050 || m.getStatus() == Message.STATUS_UNSEND
1051 || m.getStatus() == Message.STATUS_OFFERED;
1052 if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
1053 cancelTransmission.setVisible(true);
1054 }
1055 if (treatAsFile) {
1056 String path = m.getRelativeFilePath();
1057 if (path == null || !path.startsWith("/")) {
1058 deleteFile.setVisible(true);
1059 deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1060 }
1061 }
1062 if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
1063 showErrorMessage.setVisible(true);
1064 }
1065 }
1066 }
1067
1068 @Override
1069 public boolean onContextItemSelected(MenuItem item) {
1070 switch (item.getItemId()) {
1071 case R.id.share_with:
1072 shareWith(selectedMessage);
1073 return true;
1074 case R.id.correct_message:
1075 correctMessage(selectedMessage);
1076 return true;
1077 case R.id.copy_message:
1078 copyMessage(selectedMessage);
1079 return true;
1080 case R.id.quote_message:
1081 quoteMessage(selectedMessage);
1082 return true;
1083 case R.id.send_again:
1084 resendMessage(selectedMessage);
1085 return true;
1086 case R.id.copy_url:
1087 copyUrl(selectedMessage);
1088 return true;
1089 case R.id.download_file:
1090 startDownloadable(selectedMessage);
1091 return true;
1092 case R.id.cancel_transmission:
1093 cancelTransmission(selectedMessage);
1094 return true;
1095 case R.id.retry_decryption:
1096 retryDecryption(selectedMessage);
1097 return true;
1098 case R.id.delete_file:
1099 deleteFile(selectedMessage);
1100 return true;
1101 case R.id.show_error_message:
1102 showErrorMessage(selectedMessage);
1103 return true;
1104 default:
1105 return super.onContextItemSelected(item);
1106 }
1107 }
1108
1109 @Override
1110 public boolean onOptionsItemSelected(final MenuItem item) {
1111 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1112 return false;
1113 } else if (conversation == null) {
1114 return super.onOptionsItemSelected(item);
1115 }
1116 switch (item.getItemId()) {
1117 case R.id.encryption_choice_axolotl:
1118 case R.id.encryption_choice_pgp:
1119 case R.id.encryption_choice_none:
1120 handleEncryptionSelection(item);
1121 break;
1122 case R.id.attach_choose_picture:
1123 case R.id.attach_take_picture:
1124 case R.id.attach_record_video:
1125 case R.id.attach_choose_file:
1126 case R.id.attach_record_voice:
1127 case R.id.attach_location:
1128 handleAttachmentSelection(item);
1129 break;
1130 case R.id.action_archive:
1131 activity.xmppConnectionService.archiveConversation(conversation);
1132 break;
1133 case R.id.action_contact_details:
1134 activity.switchToContactDetails(conversation.getContact());
1135 break;
1136 case R.id.action_muc_details:
1137 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1138 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1139 intent.putExtra("uuid", conversation.getUuid());
1140 startActivity(intent);
1141 break;
1142 case R.id.action_invite:
1143 startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
1144 break;
1145 case R.id.action_clear_history:
1146 clearHistoryDialog(conversation);
1147 break;
1148 case R.id.action_mute:
1149 muteConversationDialog(conversation);
1150 break;
1151 case R.id.action_unmute:
1152 unmuteConversation(conversation);
1153 break;
1154 case R.id.action_block:
1155 case R.id.action_unblock:
1156 final Activity activity = getActivity();
1157 if (activity instanceof XmppActivity) {
1158 BlockContactDialog.show((XmppActivity) activity, conversation);
1159 }
1160 break;
1161 default:
1162 break;
1163 }
1164 return super.onOptionsItemSelected(item);
1165 }
1166
1167 private void handleAttachmentSelection(MenuItem item) {
1168 switch (item.getItemId()) {
1169 case R.id.attach_choose_picture:
1170 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1171 break;
1172 case R.id.attach_take_picture:
1173 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1174 break;
1175 case R.id.attach_record_video:
1176 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1177 break;
1178 case R.id.attach_choose_file:
1179 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1180 break;
1181 case R.id.attach_record_voice:
1182 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1183 break;
1184 case R.id.attach_location:
1185 attachFile(ATTACHMENT_CHOICE_LOCATION);
1186 break;
1187 }
1188 }
1189
1190 private void handleEncryptionSelection(MenuItem item) {
1191 if (conversation == null) {
1192 return;
1193 }
1194 switch (item.getItemId()) {
1195 case R.id.encryption_choice_none:
1196 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1197 item.setChecked(true);
1198 break;
1199 case R.id.encryption_choice_pgp:
1200 if (activity.hasPgp()) {
1201 if (conversation.getAccount().getPgpSignature() != null) {
1202 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1203 item.setChecked(true);
1204 } else {
1205 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1206 }
1207 } else {
1208 activity.showInstallPgpDialog();
1209 }
1210 break;
1211 case R.id.encryption_choice_axolotl:
1212 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1213 + "Enabled axolotl for Contact " + conversation.getContact().getJid());
1214 conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1215 item.setChecked(true);
1216 break;
1217 default:
1218 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1219 break;
1220 }
1221 activity.xmppConnectionService.updateConversation(conversation);
1222 updateChatMsgHint();
1223 getActivity().invalidateOptionsMenu();
1224 activity.refreshUi();
1225 }
1226
1227 public void attachFile(final int attachmentChoice) {
1228 if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1229 if (!hasStorageAndCameraPermission(attachmentChoice)) {
1230 return;
1231 }
1232 } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1233 if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
1234 return;
1235 }
1236 }
1237 try {
1238 activity.getPreferences().edit()
1239 .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1240 .apply();
1241 } catch (IllegalArgumentException e) {
1242 //just do not save
1243 }
1244 final int encryption = conversation.getNextEncryption();
1245 final int mode = conversation.getMode();
1246 if (encryption == Message.ENCRYPTION_PGP) {
1247 if (activity.hasPgp()) {
1248 if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1249 activity.xmppConnectionService.getPgpEngine().hasKey(
1250 conversation.getContact(),
1251 new UiCallback<Contact>() {
1252
1253 @Override
1254 public void userInputRequried(PendingIntent pi, Contact contact) {
1255 startPendingIntent(pi, attachmentChoice);
1256 }
1257
1258 @Override
1259 public void success(Contact contact) {
1260 selectPresenceToAttachFile(attachmentChoice);
1261 }
1262
1263 @Override
1264 public void error(int error, Contact contact) {
1265 activity.replaceToast(getString(error));
1266 }
1267 });
1268 } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1269 if (!conversation.getMucOptions().everybodyHasKeys()) {
1270 Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1271 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1272 warning.show();
1273 }
1274 selectPresenceToAttachFile(attachmentChoice);
1275 } else {
1276 showNoPGPKeyDialog(false, (dialog, which) -> {
1277 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1278 activity.xmppConnectionService.updateConversation(conversation);
1279 selectPresenceToAttachFile(attachmentChoice);
1280 });
1281 }
1282 } else {
1283 activity.showInstallPgpDialog();
1284 }
1285 } else {
1286 if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
1287 selectPresenceToAttachFile(attachmentChoice);
1288 }
1289 }
1290 }
1291
1292 @Override
1293 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
1294 if (grantResults.length > 0)
1295 if (allGranted(grantResults)) {
1296 if (requestCode == REQUEST_START_DOWNLOAD) {
1297 if (this.mPendingDownloadableMessage != null) {
1298 startDownloadable(this.mPendingDownloadableMessage);
1299 }
1300 } else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
1301 if (this.mPendingEditorContent != null) {
1302 attachImageToConversation(this.mPendingEditorContent);
1303 }
1304 } else {
1305 attachFile(requestCode);
1306 }
1307 } else {
1308 @StringRes int res;
1309 if (Manifest.permission.CAMERA.equals(getFirstDenied(grantResults, permissions))) {
1310 res = R.string.no_camera_permission;
1311 } else {
1312 res = R.string.no_storage_permission;
1313 }
1314 Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1315 }
1316 }
1317
1318 public void startDownloadable(Message message) {
1319 if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(REQUEST_START_DOWNLOAD)) {
1320 this.mPendingDownloadableMessage = message;
1321 return;
1322 }
1323 Transferable transferable = message.getTransferable();
1324 if (transferable != null) {
1325 if (transferable instanceof TransferablePlaceholder && message.treatAsDownloadable()) {
1326 activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1327 return;
1328 }
1329 if (!transferable.start()) {
1330 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1331 }
1332 } else if (message.treatAsDownloadable()) {
1333 activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1334 }
1335 }
1336
1337 @SuppressLint("InflateParams")
1338 protected void clearHistoryDialog(final Conversation conversation) {
1339 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1340 builder.setTitle(getString(R.string.clear_conversation_history));
1341 final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1342 final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1343 builder.setView(dialogView);
1344 builder.setNegativeButton(getString(R.string.cancel), null);
1345 builder.setPositiveButton(getString(R.string.delete_messages), (dialog, which) -> {
1346 this.activity.xmppConnectionService.clearConversationHistory(conversation);
1347 if (endConversationCheckBox.isChecked()) {
1348 this.activity.xmppConnectionService.archiveConversation(conversation);
1349 this.activity.onConversationArchived(conversation);
1350 } else {
1351 activity.onConversationsListItemUpdated();
1352 refresh();
1353 }
1354 });
1355 builder.create().show();
1356 }
1357
1358 protected void muteConversationDialog(final Conversation conversation) {
1359 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1360 builder.setTitle(R.string.disable_notifications);
1361 final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1362 final CharSequence[] labels = new CharSequence[durations.length];
1363 for (int i = 0; i < durations.length; ++i) {
1364 if (durations[i] == -1) {
1365 labels[i] = getString(R.string.until_further_notice);
1366 } else {
1367 labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
1368 }
1369 }
1370 builder.setItems(labels, (dialog, which) -> {
1371 final long till;
1372 if (durations[which] == -1) {
1373 till = Long.MAX_VALUE;
1374 } else {
1375 till = System.currentTimeMillis() + (durations[which] * 1000);
1376 }
1377 conversation.setMutedTill(till);
1378 activity.xmppConnectionService.updateConversation(conversation);
1379 activity.onConversationsListItemUpdated();
1380 refresh();
1381 getActivity().invalidateOptionsMenu();
1382 });
1383 builder.create().show();
1384 }
1385
1386 private boolean hasStoragePermission(int requestCode) {
1387 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1388 if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1389 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
1390 return false;
1391 } else {
1392 return true;
1393 }
1394 } else {
1395 return true;
1396 }
1397 }
1398
1399 private boolean hasStorageAndCameraPermission(int requestCode) {
1400 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1401 List<String> missingPermissions = new ArrayList<>();
1402 if (!Config.ONLY_INTERNAL_STORAGE && activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1403 missingPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
1404 }
1405 if (activity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
1406 missingPermissions.add(Manifest.permission.CAMERA);
1407 }
1408 if (missingPermissions.size() == 0) {
1409 return true;
1410 } else {
1411 requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1412 return false;
1413 }
1414 } else {
1415 return true;
1416 }
1417 }
1418
1419 public void unmuteConversation(final Conversation conversation) {
1420 conversation.setMutedTill(0);
1421 this.activity.xmppConnectionService.updateConversation(conversation);
1422 this.activity.onConversationsListItemUpdated();
1423 refresh();
1424 getActivity().invalidateOptionsMenu();
1425 }
1426
1427 protected void selectPresenceToAttachFile(final int attachmentChoice) {
1428 final Account account = conversation.getAccount();
1429 final PresenceSelector.OnPresenceSelected callback = () -> {
1430 Intent intent = new Intent();
1431 boolean chooser = false;
1432 String fallbackPackageId = null;
1433 switch (attachmentChoice) {
1434 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1435 intent.setAction(Intent.ACTION_GET_CONTENT);
1436 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1437 intent.setType("image/*");
1438 chooser = true;
1439 break;
1440 case ATTACHMENT_CHOICE_RECORD_VIDEO:
1441 intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1442 break;
1443 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1444 final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1445 pendingTakePhotoUri.push(uri);
1446 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1447 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1448 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1449 intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1450 break;
1451 case ATTACHMENT_CHOICE_CHOOSE_FILE:
1452 chooser = true;
1453 intent.setType("*/*");
1454 intent.addCategory(Intent.CATEGORY_OPENABLE);
1455 intent.setAction(Intent.ACTION_GET_CONTENT);
1456 break;
1457 case ATTACHMENT_CHOICE_RECORD_VOICE:
1458 intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
1459 fallbackPackageId = "eu.siacs.conversations.voicerecorder";
1460 break;
1461 case ATTACHMENT_CHOICE_LOCATION:
1462 intent.setAction("eu.siacs.conversations.location.request");
1463 fallbackPackageId = "eu.siacs.conversations.sharelocation";
1464 break;
1465 }
1466 if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1467 if (chooser) {
1468 startActivityForResult(
1469 Intent.createChooser(intent, getString(R.string.perform_action_with)),
1470 attachmentChoice);
1471 } else {
1472 startActivityForResult(intent, attachmentChoice);
1473 }
1474 } else if (fallbackPackageId != null) {
1475 startActivity(getInstallApkIntent(fallbackPackageId));
1476 }
1477 };
1478 if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1479 conversation.setNextCounterpart(null);
1480 callback.onPresenceSelected();
1481 } else {
1482 activity.selectPresence(conversation, callback);
1483 }
1484 }
1485
1486 private Intent getInstallApkIntent(final String packageId) {
1487 Intent intent = new Intent(Intent.ACTION_VIEW);
1488 intent.setData(Uri.parse("market://details?id=" + packageId));
1489 if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1490 return intent;
1491 } else {
1492 intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
1493 return intent;
1494 }
1495 }
1496
1497 @Override
1498 public void onResume() {
1499 new Handler().post(() -> {
1500 final Activity activity = getActivity();
1501 if (activity == null) {
1502 return;
1503 }
1504 final PackageManager packageManager = activity.getPackageManager();
1505 ConversationMenuConfigurator.updateAttachmentAvailability(packageManager);
1506 getActivity().invalidateOptionsMenu();
1507 });
1508 super.onResume();
1509 if (activity != null && this.conversation != null) {
1510 activity.onConversationRead(this.conversation);
1511 }
1512 }
1513
1514 private void showErrorMessage(final Message message) {
1515 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1516 builder.setTitle(R.string.error_message);
1517 builder.setMessage(message.getErrorMessage());
1518 builder.setPositiveButton(R.string.confirm, null);
1519 builder.create().show();
1520 }
1521
1522 private void shareWith(Message message) {
1523 Intent shareIntent = new Intent();
1524 shareIntent.setAction(Intent.ACTION_SEND);
1525 if (message.isGeoUri()) {
1526 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
1527 shareIntent.setType("text/plain");
1528 } else if (!message.isFileOrImage()) {
1529 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
1530 shareIntent.setType("text/plain");
1531 } else {
1532 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1533 try {
1534 shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(getActivity(), file));
1535 } catch (SecurityException e) {
1536 Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
1537 return;
1538 }
1539 shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1540 String mime = message.getMimeType();
1541 if (mime == null) {
1542 mime = "*/*";
1543 }
1544 shareIntent.setType(mime);
1545 }
1546 try {
1547 startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
1548 } catch (ActivityNotFoundException e) {
1549 //This should happen only on faulty androids because normally chooser is always available
1550 Toast.makeText(getActivity(), R.string.no_application_found_to_open_file, Toast.LENGTH_SHORT).show();
1551 }
1552 }
1553
1554 private void copyMessage(Message message) {
1555 if (activity.copyTextToClipboard(message.getMergedBody().toString(), R.string.message)) {
1556 Toast.makeText(getActivity(), R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1557 }
1558 }
1559
1560 private void deleteFile(Message message) {
1561 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1562 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1563 activity.onConversationsListItemUpdated();
1564 refresh();
1565 }
1566 }
1567
1568 private void resendMessage(final Message message) {
1569 if (message.isFileOrImage()) {
1570 DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1571 if (file.exists()) {
1572 final Conversation conversation = message.getConversation();
1573 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1574 if (!message.hasFileOnRemoteHost()
1575 && xmppConnection != null
1576 && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1577 activity.selectPresence(conversation, () -> {
1578 message.setCounterpart(conversation.getNextCounterpart());
1579 activity.xmppConnectionService.resendFailedMessages(message);
1580 new Handler().post(() -> {
1581 int size = messageList.size();
1582 this.binding.messagesView.setSelection(size - 1);
1583 });
1584 });
1585 return;
1586 }
1587 } else {
1588 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1589 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1590 activity.onConversationsListItemUpdated();
1591 refresh();
1592 return;
1593 }
1594 }
1595 activity.xmppConnectionService.resendFailedMessages(message);
1596 new Handler().post(() -> {
1597 int size = messageList.size();
1598 this.binding.messagesView.setSelection(size - 1);
1599 });
1600 }
1601
1602 private void copyUrl(Message message) {
1603 final String url;
1604 final int resId;
1605 if (message.isGeoUri()) {
1606 resId = R.string.location;
1607 url = message.getBody();
1608 } else if (message.hasFileOnRemoteHost()) {
1609 resId = R.string.file_url;
1610 url = message.getFileParams().url.toString();
1611 } else {
1612 url = message.getBody().trim();
1613 resId = R.string.file_url;
1614 }
1615 if (activity.copyTextToClipboard(url, resId)) {
1616 Toast.makeText(getActivity(), R.string.url_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1617 }
1618 }
1619
1620 private void cancelTransmission(Message message) {
1621 Transferable transferable = message.getTransferable();
1622 if (transferable != null) {
1623 transferable.cancel();
1624 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1625 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1626 }
1627 }
1628
1629 private void retryDecryption(Message message) {
1630 message.setEncryption(Message.ENCRYPTION_PGP);
1631 activity.onConversationsListItemUpdated();
1632 refresh();
1633 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1634 }
1635
1636 private void privateMessageWith(final Jid counterpart) {
1637 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1638 activity.xmppConnectionService.sendChatState(conversation);
1639 }
1640 this.binding.textinput.setText("");
1641 this.conversation.setNextCounterpart(counterpart);
1642 updateChatMsgHint();
1643 updateSendButton();
1644 updateEditablity();
1645 }
1646
1647 private void correctMessage(Message message) {
1648 while (message.mergeable(message.next())) {
1649 message = message.next();
1650 }
1651 this.conversation.setCorrectingMessage(message);
1652 final Editable editable = binding.textinput.getText();
1653 this.conversation.setDraftMessage(editable.toString());
1654 this.binding.textinput.setText("");
1655 this.binding.textinput.append(message.getBody());
1656
1657 }
1658
1659 private void highlightInConference(String nick) {
1660 final Editable editable = this.binding.textinput.getText();
1661 String oldString = editable.toString().trim();
1662 final int pos = this.binding.textinput.getSelectionStart();
1663 if (oldString.isEmpty() || pos == 0) {
1664 editable.insert(0, nick + ": ");
1665 } else {
1666 final char before = editable.charAt(pos - 1);
1667 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1668 if (before == '\n') {
1669 editable.insert(pos, nick + ": ");
1670 } else {
1671 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1672 if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1673 editable.insert(pos - 2, ", " + nick);
1674 return;
1675 }
1676 }
1677 editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1678 if (Character.isWhitespace(after)) {
1679 this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1680 }
1681 }
1682 }
1683 }
1684
1685 @Override
1686 public void onSaveInstanceState(Bundle outState) {
1687 super.onSaveInstanceState(outState);
1688 if (conversation != null) {
1689 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1690 final Uri uri = pendingTakePhotoUri.peek();
1691 if (uri != null) {
1692 outState.putString(STATE_PHOTO_URI, uri.toString());
1693 }
1694 final ScrollState scrollState = getScrollPosition();
1695 if (scrollState != null) {
1696 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1697 }
1698 }
1699 }
1700
1701 @Override
1702 public void onActivityCreated(Bundle savedInstanceState) {
1703 super.onActivityCreated(savedInstanceState);
1704 if (savedInstanceState == null) {
1705 return;
1706 }
1707 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1708 if (uuid != null) {
1709 this.pendingConversationsUuid.push(uuid);
1710 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1711 if (takePhotoUri != null) {
1712 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1713 }
1714 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1715 }
1716 }
1717
1718 @Override
1719 public void onStart() {
1720 super.onStart();
1721 if (this.reInitRequiredOnStart) {
1722 final Bundle extras = pendingExtras.pop();
1723 reInit(conversation, extras != null);
1724 if (extras != null) {
1725 processExtras(extras);
1726 }
1727 } else {
1728 Log.d(Config.LOGTAG, "skipped reinit on start");
1729 }
1730 }
1731
1732 @Override
1733 public void onStop() {
1734 super.onStop();
1735 final Activity activity = getActivity();
1736 if (activity == null || !activity.isChangingConfigurations()) {
1737 hideSoftKeyboard(activity);
1738 messageListAdapter.stopAudioPlayer();
1739 }
1740 if (this.conversation != null) {
1741 final String msg = this.binding.textinput.getText().toString();
1742 if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && this.conversation.setNextMessage(msg)) {
1743 this.activity.xmppConnectionService.updateConversation(this.conversation);
1744 }
1745 updateChatState(this.conversation, msg);
1746 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1747 }
1748 this.reInitRequiredOnStart = true;
1749 }
1750
1751 private void updateChatState(final Conversation conversation, final String msg) {
1752 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1753 Account.State status = conversation.getAccount().getStatus();
1754 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1755 activity.xmppConnectionService.sendChatState(conversation);
1756 }
1757 }
1758
1759 private void saveMessageDraftStopAudioPlayer() {
1760 final Conversation previousConversation = this.conversation;
1761 if (this.activity == null || this.binding == null || previousConversation == null) {
1762 return;
1763 }
1764 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1765 final String msg = this.binding.textinput.getText().toString();
1766 if (previousConversation.setNextMessage(msg)) {
1767 activity.xmppConnectionService.updateConversation(previousConversation);
1768 }
1769 updateChatState(this.conversation, msg);
1770 messageListAdapter.stopAudioPlayer();
1771 }
1772
1773 public void reInit(Conversation conversation, Bundle extras) {
1774 this.saveMessageDraftStopAudioPlayer();
1775 if (this.reInit(conversation, extras != null)) {
1776 if (extras != null) {
1777 processExtras(extras);
1778 }
1779 this.reInitRequiredOnStart = false;
1780 } else {
1781 this.reInitRequiredOnStart = true;
1782 pendingExtras.push(extras);
1783 }
1784 }
1785
1786 private void reInit(Conversation conversation) {
1787 reInit(conversation, false);
1788 }
1789
1790 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1791 if (conversation == null) {
1792 return false;
1793 }
1794 this.conversation = conversation;
1795 //once we set the conversation all is good and it will automatically do the right thing in onStart()
1796 if (this.activity == null || this.binding == null) {
1797 return false;
1798 }
1799
1800 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1801 activity.onConversationArchived(this.conversation);
1802 return false;
1803 }
1804
1805 stopScrolling();
1806 Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1807
1808 if (this.conversation.isRead() && hasExtras) {
1809 Log.d(Config.LOGTAG, "trimming conversation");
1810 this.conversation.trim();
1811 }
1812
1813 setupIme();
1814
1815 final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1816
1817 this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1818 this.binding.textinput.setKeyboardListener(null);
1819 this.binding.textinput.setText("");
1820 this.binding.textinput.append(this.conversation.getNextMessage());
1821 this.binding.textinput.setKeyboardListener(this);
1822 messageListAdapter.updatePreferences();
1823 refresh(false);
1824 this.conversation.messagesLoaded.set(true);
1825
1826 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1827
1828 if (hasExtras || scrolledToBottomAndNoPending) {
1829 synchronized (this.messageList) {
1830 Log.d(Config.LOGTAG, "jump to first unread message");
1831 final Message first = conversation.getFirstUnreadMessage();
1832 final int bottom = Math.max(0, this.messageList.size() - 1);
1833 final int pos;
1834 if (first == null) {
1835 pos = bottom;
1836 } else {
1837 int i = getIndexOf(first.getUuid(), this.messageList);
1838 pos = i < 0 ? bottom : i;
1839 }
1840 setSelection(pos);
1841 }
1842 }
1843
1844 activity.onConversationRead(this.conversation);
1845 //TODO if we only do this when this fragment is running on main it won't *bing* in tablet layout which might be unnecessary since we can *see* it
1846 activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1847 return true;
1848 }
1849
1850 private void setSelection(int pos) {
1851 this.binding.messagesView.setSelection(pos);
1852 this.binding.messagesView.post(() -> this.binding.messagesView.setSelection(pos));
1853 }
1854
1855 private boolean scrolledToBottom() {
1856 if (this.binding == null) {
1857 return false;
1858 }
1859 final ListView listView = this.binding.messagesView;
1860 if (listView.getLastVisiblePosition() == listView.getAdapter().getCount() - 1) {
1861 final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
1862 return lastChild != null && lastChild.getBottom() <= listView.getHeight();
1863 } else {
1864 return false;
1865 }
1866 }
1867
1868 private void processExtras(Bundle extras) {
1869 final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
1870 final String text = extras.getString(ConversationsActivity.EXTRA_TEXT);
1871 final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
1872 final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1873 if (nick != null) {
1874 if (pm) {
1875 Jid jid = conversation.getJid();
1876 try {
1877 Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
1878 privateMessageWith(next);
1879 } catch (final IllegalArgumentException ignored) {
1880 //do nothing
1881 }
1882 } else {
1883 final MucOptions mucOptions = conversation.getMucOptions();
1884 if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
1885 highlightInConference(nick);
1886 }
1887 }
1888 } else {
1889 appendText(text);
1890 }
1891 final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
1892 if (message != null) {
1893 startDownloadable(message);
1894 }
1895 }
1896
1897 private boolean showBlockSubmenu(View view) {
1898 final Jid jid = conversation.getJid();
1899 if (jid.getLocal() == null) {
1900 BlockContactDialog.show(activity, conversation);
1901 } else {
1902 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
1903 popupMenu.inflate(R.menu.block);
1904 popupMenu.setOnMenuItemClickListener(menuItem -> {
1905 Blockable blockable;
1906 switch (menuItem.getItemId()) {
1907 case R.id.block_domain:
1908 blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
1909 break;
1910 default:
1911 blockable = conversation;
1912 }
1913 BlockContactDialog.show(activity, blockable);
1914 return true;
1915 });
1916 popupMenu.show();
1917 }
1918 return true;
1919 }
1920
1921 private void updateSnackBar(final Conversation conversation) {
1922 final Account account = conversation.getAccount();
1923 final XmppConnection connection = account.getXmppConnection();
1924 final int mode = conversation.getMode();
1925 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1926 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
1927 return;
1928 }
1929 if (account.getStatus() == Account.State.DISABLED) {
1930 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1931 } else if (conversation.isBlocked()) {
1932 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1933 } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1934 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1935 } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1936 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1937 } else if (mode == Conversation.MODE_MULTI
1938 && !conversation.getMucOptions().online()
1939 && account.getStatus() == Account.State.ONLINE) {
1940 switch (conversation.getMucOptions().getError()) {
1941 case NICK_IN_USE:
1942 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1943 break;
1944 case NO_RESPONSE:
1945 showSnackbar(R.string.joining_conference, 0, null);
1946 break;
1947 case SERVER_NOT_FOUND:
1948 if (conversation.receivedMessagesCount() > 0) {
1949 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
1950 } else {
1951 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1952 }
1953 break;
1954 case PASSWORD_REQUIRED:
1955 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1956 break;
1957 case BANNED:
1958 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1959 break;
1960 case MEMBERS_ONLY:
1961 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1962 break;
1963 case KICKED:
1964 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1965 break;
1966 case UNKNOWN:
1967 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
1968 break;
1969 case INVALID_NICK:
1970 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
1971 case SHUTDOWN:
1972 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
1973 break;
1974 default:
1975 hideSnackbar();
1976 break;
1977 }
1978 } else if (account.hasPendingPgpIntent(conversation)) {
1979 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1980 } else if (connection != null
1981 && connection.getFeatures().blocking()
1982 && conversation.countMessages() != 0
1983 && !conversation.isBlocked()
1984 && conversation.isWithStranger()) {
1985 showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
1986 } else {
1987 hideSnackbar();
1988 }
1989 }
1990
1991 @Override
1992 public void refresh() {
1993 if (this.binding == null) {
1994 Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
1995 return;
1996 }
1997 if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
1998 if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
1999 activity.onConversationArchived(this.conversation);
2000 return;
2001 }
2002 }
2003 this.refresh(true);
2004 }
2005
2006 private void refresh(boolean notifyConversationRead) {
2007 synchronized (this.messageList) {
2008 if (this.conversation != null) {
2009 conversation.populateWithMessages(this.messageList);
2010 updateSnackBar(conversation);
2011 updateStatusMessages();
2012 this.messageListAdapter.notifyDataSetChanged();
2013 updateChatMsgHint();
2014 if (notifyConversationRead && activity != null) {
2015 activity.onConversationRead(this.conversation);
2016 }
2017 updateSendButton();
2018 updateEditablity();
2019 }
2020 }
2021 }
2022
2023 protected void messageSent() {
2024 mSendingPgpMessage.set(false);
2025 this.binding.textinput.setText("");
2026 if (conversation.setCorrectingMessage(null)) {
2027 this.binding.textinput.append(conversation.getDraftMessage());
2028 conversation.setDraftMessage(null);
2029 }
2030 if (conversation.setNextMessage(this.binding.textinput.getText().toString())) {
2031 activity.xmppConnectionService.updateConversation(conversation);
2032 }
2033 updateChatMsgHint();
2034 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2035 final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2036 if (prefScrollToBottom || scrolledToBottom()) {
2037 new Handler().post(() -> {
2038 int size = messageList.size();
2039 this.binding.messagesView.setSelection(size - 1);
2040 });
2041 }
2042 }
2043
2044 public void doneSendingPgpMessage() {
2045 mSendingPgpMessage.set(false);
2046 }
2047
2048 public long getMaxHttpUploadSize(Conversation conversation) {
2049 final XmppConnection connection = conversation.getAccount().getXmppConnection();
2050 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2051 }
2052
2053 private void updateEditablity() {
2054 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2055 this.binding.textinput.setFocusable(canWrite);
2056 this.binding.textinput.setFocusableInTouchMode(canWrite);
2057 this.binding.textSendButton.setEnabled(canWrite);
2058 this.binding.textinput.setCursorVisible(canWrite);
2059 }
2060
2061 public void updateSendButton() {
2062 boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2063 final Conversation c = this.conversation;
2064 final Presence.Status status;
2065 final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2066 final SendButtonAction action = SendButtonTool.getAction(getActivity(), c, text);
2067 if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2068 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2069 status = Presence.Status.OFFLINE;
2070 } else if (c.getMode() == Conversation.MODE_SINGLE) {
2071 status = c.getContact().getShownStatus();
2072 } else {
2073 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2074 }
2075 } else {
2076 status = Presence.Status.OFFLINE;
2077 }
2078 this.binding.textSendButton.setTag(action);
2079 this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2080 }
2081
2082 protected void updateDateSeparators() {
2083 synchronized (this.messageList) {
2084 for (int i = 0; i < this.messageList.size(); ++i) {
2085 final Message current = this.messageList.get(i);
2086 if (i == 0 || !UIHelper.sameDay(this.messageList.get(i - 1).getTimeSent(), current.getTimeSent())) {
2087 this.messageList.add(i, Message.createDateSeparator(current));
2088 i++;
2089 }
2090 }
2091 }
2092 }
2093
2094 protected void updateStatusMessages() {
2095 updateDateSeparators();
2096 synchronized (this.messageList) {
2097 if (showLoadMoreMessages(conversation)) {
2098 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2099 }
2100 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2101 ChatState state = conversation.getIncomingChatState();
2102 if (state == ChatState.COMPOSING) {
2103 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2104 } else if (state == ChatState.PAUSED) {
2105 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2106 } else {
2107 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2108 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
2109 return;
2110 } else {
2111 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
2112 this.messageList.add(i + 1,
2113 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2114 return;
2115 }
2116 }
2117 }
2118 }
2119 } else {
2120 final MucOptions mucOptions = conversation.getMucOptions();
2121 final List<MucOptions.User> allUsers = mucOptions.getUsers();
2122 final Set<ReadByMarker> addedMarkers = new HashSet<>();
2123 ChatState state = ChatState.COMPOSING;
2124 List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2125 if (users.size() == 0) {
2126 state = ChatState.PAUSED;
2127 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2128 }
2129 if (mucOptions.isPrivateAndNonAnonymous()) {
2130 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2131 final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2132 final List<MucOptions.User> shownMarkers = new ArrayList<>();
2133 for (ReadByMarker marker : markersForMessage) {
2134 if (!ReadByMarker.contains(marker, addedMarkers)) {
2135 addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2136 MucOptions.User user = mucOptions.findUser(marker);
2137 if (user != null && !users.contains(user)) {
2138 shownMarkers.add(user);
2139 }
2140 }
2141 }
2142 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2143 final Message statusMessage;
2144 final int size = shownMarkers.size();
2145 if (size > 1) {
2146 final String body;
2147 if (size <= 4) {
2148 body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2149 } else {
2150 body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2151 }
2152 statusMessage = Message.createStatusMessage(conversation, body);
2153 statusMessage.setCounterparts(shownMarkers);
2154 } else if (size == 1) {
2155 statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2156 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2157 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2158 } else {
2159 statusMessage = null;
2160 }
2161 if (statusMessage != null) {
2162 this.messageList.add(i + 1, statusMessage);
2163 }
2164 addedMarkers.add(markerForSender);
2165 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2166 break;
2167 }
2168 }
2169 }
2170 if (users.size() > 0) {
2171 Message statusMessage;
2172 if (users.size() == 1) {
2173 MucOptions.User user = users.get(0);
2174 int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2175 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2176 statusMessage.setTrueCounterpart(user.getRealJid());
2177 statusMessage.setCounterpart(user.getFullJid());
2178 } else {
2179 int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2180 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2181 statusMessage.setCounterparts(users);
2182 }
2183 this.messageList.add(statusMessage);
2184 }
2185
2186 }
2187 }
2188 }
2189
2190 private void stopScrolling() {
2191 long now = SystemClock.uptimeMillis();
2192 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2193 binding.messagesView.dispatchTouchEvent(cancel);
2194 }
2195
2196 private boolean showLoadMoreMessages(final Conversation c) {
2197 if (activity == null || activity.xmppConnectionService == null) {
2198 return false;
2199 }
2200 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2201 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2202 return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2203 }
2204
2205 private boolean hasMamSupport(final Conversation c) {
2206 if (c.getMode() == Conversation.MODE_SINGLE) {
2207 final XmppConnection connection = c.getAccount().getXmppConnection();
2208 return connection != null && connection.getFeatures().mam();
2209 } else {
2210 return c.getMucOptions().mamSupport();
2211 }
2212 }
2213
2214 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2215 showSnackbar(message, action, clickListener, null);
2216 }
2217
2218 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2219 this.binding.snackbar.setVisibility(View.VISIBLE);
2220 this.binding.snackbar.setOnClickListener(null);
2221 this.binding.snackbarMessage.setText(message);
2222 this.binding.snackbarMessage.setOnClickListener(null);
2223 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2224 if (action != 0) {
2225 this.binding.snackbarAction.setText(action);
2226 }
2227 this.binding.snackbarAction.setOnClickListener(clickListener);
2228 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2229 }
2230
2231 protected void hideSnackbar() {
2232 this.binding.snackbar.setVisibility(View.GONE);
2233 }
2234
2235 protected void sendMessage(Message message) {
2236 activity.xmppConnectionService.sendMessage(message);
2237 messageSent();
2238 }
2239
2240 protected void sendPgpMessage(final Message message) {
2241 final XmppConnectionService xmppService = activity.xmppConnectionService;
2242 final Contact contact = message.getConversation().getContact();
2243 if (!activity.hasPgp()) {
2244 activity.showInstallPgpDialog();
2245 return;
2246 }
2247 if (conversation.getAccount().getPgpSignature() == null) {
2248 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2249 return;
2250 }
2251 if (!mSendingPgpMessage.compareAndSet(false, true)) {
2252 Log.d(Config.LOGTAG, "sending pgp message already in progress");
2253 }
2254 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2255 if (contact.getPgpKeyId() != 0) {
2256 xmppService.getPgpEngine().hasKey(contact,
2257 new UiCallback<Contact>() {
2258
2259 @Override
2260 public void userInputRequried(PendingIntent pi, Contact contact) {
2261 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2262 }
2263
2264 @Override
2265 public void success(Contact contact) {
2266 encryptTextMessage(message);
2267 }
2268
2269 @Override
2270 public void error(int error, Contact contact) {
2271 activity.runOnUiThread(() -> Toast.makeText(activity,
2272 R.string.unable_to_connect_to_keychain,
2273 Toast.LENGTH_SHORT
2274 ).show());
2275 mSendingPgpMessage.set(false);
2276 }
2277 });
2278
2279 } else {
2280 showNoPGPKeyDialog(false, (dialog, which) -> {
2281 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2282 xmppService.updateConversation(conversation);
2283 message.setEncryption(Message.ENCRYPTION_NONE);
2284 xmppService.sendMessage(message);
2285 messageSent();
2286 });
2287 }
2288 } else {
2289 if (conversation.getMucOptions().pgpKeysInUse()) {
2290 if (!conversation.getMucOptions().everybodyHasKeys()) {
2291 Toast warning = Toast
2292 .makeText(getActivity(),
2293 R.string.missing_public_keys,
2294 Toast.LENGTH_LONG);
2295 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2296 warning.show();
2297 }
2298 encryptTextMessage(message);
2299 } else {
2300 showNoPGPKeyDialog(true, (dialog, which) -> {
2301 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2302 message.setEncryption(Message.ENCRYPTION_NONE);
2303 xmppService.updateConversation(conversation);
2304 xmppService.sendMessage(message);
2305 messageSent();
2306 });
2307 }
2308 }
2309 }
2310
2311 public void encryptTextMessage(Message message) {
2312 activity.xmppConnectionService.getPgpEngine().encrypt(message,
2313 new UiCallback<Message>() {
2314
2315 @Override
2316 public void userInputRequried(PendingIntent pi, Message message) {
2317 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2318 }
2319
2320 @Override
2321 public void success(Message message) {
2322 //TODO the following two call can be made before the callback
2323 getActivity().runOnUiThread(() -> messageSent());
2324 }
2325
2326 @Override
2327 public void error(final int error, Message message) {
2328 getActivity().runOnUiThread(() -> {
2329 doneSendingPgpMessage();
2330 Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2331 });
2332
2333 }
2334 });
2335 }
2336
2337 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2338 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2339 builder.setIconAttribute(android.R.attr.alertDialogIcon);
2340 if (plural) {
2341 builder.setTitle(getString(R.string.no_pgp_keys));
2342 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2343 } else {
2344 builder.setTitle(getString(R.string.no_pgp_key));
2345 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2346 }
2347 builder.setNegativeButton(getString(R.string.cancel), null);
2348 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2349 builder.create().show();
2350 }
2351
2352 public void appendText(String text) {
2353 if (text == null) {
2354 return;
2355 }
2356 String previous = this.binding.textinput.getText().toString();
2357 if (previous.length() != 0 && !previous.endsWith(" ")) {
2358 text = " " + text;
2359 }
2360 this.binding.textinput.append(text);
2361 }
2362
2363 @Override
2364 public boolean onEnterPressed() {
2365 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2366 final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2367 if (enterIsSend) {
2368 sendMessage();
2369 return true;
2370 } else {
2371 return false;
2372 }
2373 }
2374
2375 @Override
2376 public void onTypingStarted() {
2377 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2378 if (service == null) {
2379 return;
2380 }
2381 Account.State status = conversation.getAccount().getStatus();
2382 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2383 service.sendChatState(conversation);
2384 }
2385 updateSendButton();
2386 }
2387
2388 @Override
2389 public void onTypingStopped() {
2390 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2391 if (service == null) {
2392 return;
2393 }
2394 Account.State status = conversation.getAccount().getStatus();
2395 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2396 service.sendChatState(conversation);
2397 }
2398 }
2399
2400 @Override
2401 public void onTextDeleted() {
2402 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2403 if (service == null) {
2404 return;
2405 }
2406 Account.State status = conversation.getAccount().getStatus();
2407 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2408 service.sendChatState(conversation);
2409 }
2410 updateSendButton();
2411 }
2412
2413 @Override
2414 public void onTextChanged() {
2415 if (conversation != null && conversation.getCorrectingMessage() != null) {
2416 updateSendButton();
2417 }
2418 }
2419
2420 @Override
2421 public boolean onTabPressed(boolean repeated) {
2422 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2423 return false;
2424 }
2425 if (repeated) {
2426 completionIndex++;
2427 } else {
2428 lastCompletionLength = 0;
2429 completionIndex = 0;
2430 final String content = this.binding.textinput.getText().toString();
2431 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2432 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2433 firstWord = start == 0;
2434 incomplete = content.substring(start, lastCompletionCursor);
2435 }
2436 List<String> completions = new ArrayList<>();
2437 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2438 String name = user.getName();
2439 if (name != null && name.startsWith(incomplete)) {
2440 completions.add(name + (firstWord ? ": " : " "));
2441 }
2442 }
2443 Collections.sort(completions);
2444 if (completions.size() > completionIndex) {
2445 String completion = completions.get(completionIndex).substring(incomplete.length());
2446 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2447 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2448 lastCompletionLength = completion.length();
2449 } else {
2450 completionIndex = -1;
2451 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2452 lastCompletionLength = 0;
2453 }
2454 return true;
2455 }
2456
2457 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2458 try {
2459 getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2460 } catch (final SendIntentException ignored) {
2461 }
2462 }
2463
2464 @Override
2465 public void onBackendConnected() {
2466 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2467 String uuid = pendingConversationsUuid.pop();
2468 if (uuid != null) {
2469 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2470 if (conversation == null) {
2471 clearPending();
2472 activity.onConversationArchived(null);
2473 return;
2474 }
2475 reInit(conversation);
2476 ScrollState scrollState = pendingScrollState.pop();
2477 if (scrollState != null) {
2478 setScrollPosition(scrollState);
2479 }
2480 } else {
2481 if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2482 clearPending();
2483 activity.onConversationArchived(conversation);
2484 return;
2485 }
2486 }
2487 ActivityResult activityResult = postponedActivityResult.pop();
2488 if (activityResult != null) {
2489 handleActivityResult(activityResult);
2490 }
2491 clearPending();
2492 }
2493
2494 private void clearPending() {
2495 if (postponedActivityResult.pop() != null) {
2496 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2497 }
2498 pendingScrollState.pop();
2499 if (pendingTakePhotoUri.pop() != null) {
2500 Log.e(Config.LOGTAG, "cleared pending photo uri");
2501 }
2502 }
2503
2504 public Conversation getConversation() {
2505 return conversation;
2506 }
2507}