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