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