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