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 });
1532 return;
1533 }
1534 } else {
1535 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1536 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1537 activity.onConversationsListItemUpdated();
1538 refresh();
1539 return;
1540 }
1541 }
1542 activity.xmppConnectionService.resendFailedMessages(message);
1543 }
1544
1545 private void copyUrl(Message message) {
1546 final String url;
1547 final int resId;
1548 if (message.isGeoUri()) {
1549 resId = R.string.location;
1550 url = message.getBody();
1551 } else if (message.hasFileOnRemoteHost()) {
1552 resId = R.string.file_url;
1553 url = message.getFileParams().url.toString();
1554 } else {
1555 url = message.getBody().trim();
1556 resId = R.string.file_url;
1557 }
1558 if (activity.copyTextToClipboard(url, resId)) {
1559 Toast.makeText(getActivity(), R.string.url_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1560 }
1561 }
1562
1563 private void cancelTransmission(Message message) {
1564 Transferable transferable = message.getTransferable();
1565 if (transferable != null) {
1566 transferable.cancel();
1567 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1568 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1569 }
1570 }
1571
1572 private void retryDecryption(Message message) {
1573 message.setEncryption(Message.ENCRYPTION_PGP);
1574 activity.onConversationsListItemUpdated();
1575 refresh();
1576 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1577 }
1578
1579 private void privateMessageWith(final Jid counterpart) {
1580 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1581 activity.xmppConnectionService.sendChatState(conversation);
1582 }
1583 this.binding.textinput.setText("");
1584 this.conversation.setNextCounterpart(counterpart);
1585 updateChatMsgHint();
1586 updateSendButton();
1587 updateEditablity();
1588 }
1589
1590 private void correctMessage(Message message) {
1591 while (message.mergeable(message.next())) {
1592 message = message.next();
1593 }
1594 this.conversation.setCorrectingMessage(message);
1595 final Editable editable = binding.textinput.getText();
1596 this.conversation.setDraftMessage(editable.toString());
1597 this.binding.textinput.setText("");
1598 this.binding.textinput.append(message.getBody());
1599
1600 }
1601
1602 private void highlightInConference(String nick) {
1603 final Editable editable = this.binding.textinput.getText();
1604 String oldString = editable.toString().trim();
1605 final int pos = this.binding.textinput.getSelectionStart();
1606 if (oldString.isEmpty() || pos == 0) {
1607 editable.insert(0, nick + ": ");
1608 } else {
1609 final char before = editable.charAt(pos - 1);
1610 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1611 if (before == '\n') {
1612 editable.insert(pos, nick + ": ");
1613 } else {
1614 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1615 if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1616 editable.insert(pos - 2, ", " + nick);
1617 return;
1618 }
1619 }
1620 editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1621 if (Character.isWhitespace(after)) {
1622 this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1623 }
1624 }
1625 }
1626 }
1627
1628 @Override
1629 public void onSaveInstanceState(Bundle outState) {
1630 super.onSaveInstanceState(outState);
1631 if (conversation != null) {
1632 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1633 final Uri uri = pendingTakePhotoUri.peek();
1634 if (uri != null) {
1635 outState.putString(STATE_PHOTO_URI, uri.toString());
1636 }
1637 final ScrollState scrollState = getScrollPosition();
1638 if (scrollState != null) {
1639 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1640 }
1641 }
1642 }
1643
1644 @Override
1645 public void onActivityCreated(Bundle savedInstanceState) {
1646 super.onActivityCreated(savedInstanceState);
1647 if (savedInstanceState == null) {
1648 return;
1649 }
1650 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1651 if (uuid != null) {
1652 this.pendingConversationsUuid.push(uuid);
1653 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1654 if (takePhotoUri != null) {
1655 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1656 }
1657 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1658 }
1659 }
1660
1661 @Override
1662 public void onStart() {
1663 super.onStart();
1664 if (this.reInitRequiredOnStart) {
1665 final Bundle extras = pendingExtras.pop();
1666 reInit(conversation, extras != null);
1667 if (extras != null) {
1668 processExtras(extras);
1669 }
1670 } else {
1671 Log.d(Config.LOGTAG, "skipped reinit on start");
1672 }
1673 }
1674
1675 @Override
1676 public void onStop() {
1677 super.onStop();
1678 final Activity activity = getActivity();
1679 if (activity == null || !activity.isChangingConfigurations()) {
1680 messageListAdapter.stopAudioPlayer();
1681 }
1682 if (this.conversation != null) {
1683 final String msg = this.binding.textinput.getText().toString();
1684 if (this.conversation.setNextMessage(msg)) {
1685 this.activity.xmppConnectionService.updateConversation(this.conversation);
1686 }
1687 updateChatState(this.conversation, msg);
1688 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1689 }
1690 this.reInitRequiredOnStart = true;
1691 }
1692
1693 private void updateChatState(final Conversation conversation, final String msg) {
1694 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1695 Account.State status = conversation.getAccount().getStatus();
1696 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1697 activity.xmppConnectionService.sendChatState(conversation);
1698 }
1699 }
1700
1701 private void saveMessageDraftStopAudioPlayer() {
1702 final Conversation previousConversation = this.conversation;
1703 if (this.activity == null || this.binding == null || previousConversation == null) {
1704 return;
1705 }
1706 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1707 final String msg = this.binding.textinput.getText().toString();
1708 if (previousConversation.setNextMessage(msg)) {
1709 activity.xmppConnectionService.updateConversation(previousConversation);
1710 }
1711 updateChatState(this.conversation, msg);
1712 messageListAdapter.stopAudioPlayer();
1713 }
1714
1715 public void reInit(Conversation conversation, Bundle extras) {
1716 this.saveMessageDraftStopAudioPlayer();
1717 if (this.reInit(conversation, extras != null)) {
1718 if (extras != null) {
1719 processExtras(extras);
1720 }
1721 this.reInitRequiredOnStart = false;
1722 } else {
1723 this.reInitRequiredOnStart = true;
1724 pendingExtras.push(extras);
1725 }
1726 }
1727
1728 private void reInit(Conversation conversation) {
1729 reInit(conversation, false);
1730 }
1731
1732 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1733 if (conversation == null) {
1734 return false;
1735 }
1736 this.conversation = conversation;
1737 //once we set the conversation all is good and it will automatically do the right thing in onStart()
1738 if (this.activity == null || this.binding == null) {
1739 return false;
1740 }
1741 Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1742
1743 if (this.conversation.isRead() && hasExtras) {
1744 Log.d(Config.LOGTAG, "trimming conversation");
1745 this.conversation.trim();
1746 }
1747
1748 setupIme();
1749
1750 final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1751
1752 this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1753 this.binding.textinput.setKeyboardListener(null);
1754 this.binding.textinput.setText("");
1755 this.binding.textinput.append(this.conversation.getNextMessage());
1756 this.binding.textinput.setKeyboardListener(this);
1757 messageListAdapter.updatePreferences();
1758 refresh(false);
1759 this.conversation.messagesLoaded.set(true);
1760
1761 Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1762
1763 if (hasExtras || scrolledToBottomAndNoPending) {
1764 synchronized (this.messageList) {
1765 Log.d(Config.LOGTAG, "jump to first unread message");
1766 final Message first = conversation.getFirstUnreadMessage();
1767 final int bottom = Math.max(0, this.messageList.size() - 1);
1768 final int pos;
1769 if (first == null) {
1770 pos = bottom;
1771 } else {
1772 int i = getIndexOf(first.getUuid(), this.messageList);
1773 pos = i < 0 ? bottom : i;
1774 }
1775 this.binding.messagesView.post(() -> this.binding.messagesView.setSelection(pos));
1776 }
1777 }
1778
1779 activity.onConversationRead(this.conversation);
1780 //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
1781 activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1782 return true;
1783 }
1784
1785 private boolean scrolledToBottom() {
1786 if (this.binding == null) {
1787 return false;
1788 }
1789 final ListView listView = this.binding.messagesView;
1790 if (listView.getLastVisiblePosition() == listView.getAdapter().getCount() - 1) {
1791 final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
1792 return lastChild != null && lastChild.getBottom() <= listView.getHeight();
1793 } else {
1794 return false;
1795 }
1796 }
1797
1798 private void processExtras(Bundle extras) {
1799 final String downloadUuid = extras.getString(ConversationActivity.EXTRA_DOWNLOAD_UUID);
1800 final String text = extras.getString(ConversationActivity.EXTRA_TEXT);
1801 final String nick = extras.getString(ConversationActivity.EXTRA_NICK);
1802 final boolean pm = extras.getBoolean(ConversationActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1803 if (nick != null) {
1804 if (pm) {
1805 Jid jid = conversation.getJid();
1806 try {
1807 Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1808 privateMessageWith(next);
1809 } catch (final InvalidJidException ignored) {
1810 //do nothing
1811 }
1812 } else {
1813 highlightInConference(nick);
1814 }
1815 } else {
1816 appendText(text);
1817 }
1818 final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
1819 if (message != null) {
1820 startDownloadable(message);
1821 }
1822 }
1823
1824 private boolean showBlockSubmenu(View view) {
1825 final Jid jid = conversation.getJid();
1826 if (jid.isDomainJid()) {
1827 BlockContactDialog.show(activity, conversation);
1828 } else {
1829 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
1830 popupMenu.inflate(R.menu.block);
1831 popupMenu.setOnMenuItemClickListener(menuItem -> {
1832 Blockable blockable;
1833 switch (menuItem.getItemId()) {
1834 case R.id.block_domain:
1835 blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
1836 break;
1837 default:
1838 blockable = conversation;
1839 }
1840 BlockContactDialog.show(activity, blockable);
1841 return true;
1842 });
1843 popupMenu.show();
1844 }
1845 return true;
1846 }
1847
1848 private void updateSnackBar(final Conversation conversation) {
1849 final Account account = conversation.getAccount();
1850 final XmppConnection connection = account.getXmppConnection();
1851 final int mode = conversation.getMode();
1852 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1853 if (account.getStatus() == Account.State.DISABLED) {
1854 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1855 } else if (conversation.isBlocked()) {
1856 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1857 } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1858 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1859 } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1860 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1861 } else if (mode == Conversation.MODE_MULTI
1862 && !conversation.getMucOptions().online()
1863 && account.getStatus() == Account.State.ONLINE) {
1864 switch (conversation.getMucOptions().getError()) {
1865 case NICK_IN_USE:
1866 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1867 break;
1868 case NO_RESPONSE:
1869 showSnackbar(R.string.joining_conference, 0, null);
1870 break;
1871 case SERVER_NOT_FOUND:
1872 if (conversation.receivedMessagesCount() > 0) {
1873 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
1874 } else {
1875 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1876 }
1877 break;
1878 case PASSWORD_REQUIRED:
1879 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1880 break;
1881 case BANNED:
1882 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1883 break;
1884 case MEMBERS_ONLY:
1885 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1886 break;
1887 case KICKED:
1888 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1889 break;
1890 case UNKNOWN:
1891 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
1892 break;
1893 case INVALID_NICK:
1894 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
1895 case SHUTDOWN:
1896 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
1897 break;
1898 default:
1899 hideSnackbar();
1900 break;
1901 }
1902 } else if (account.hasPendingPgpIntent(conversation)) {
1903 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1904 } else if (connection != null
1905 && connection.getFeatures().blocking()
1906 && conversation.countMessages() != 0
1907 && !conversation.isBlocked()
1908 && conversation.isWithStranger()) {
1909 showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
1910 } else {
1911 hideSnackbar();
1912 }
1913 }
1914
1915 @Override
1916 public void refresh() {
1917 if (this.binding == null) {
1918 Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
1919 return;
1920 }
1921 this.refresh(true);
1922 }
1923
1924 private void refresh(boolean notifyConversationRead) {
1925 synchronized (this.messageList) {
1926 if (this.conversation != null) {
1927 conversation.populateWithMessages(this.messageList);
1928 updateSnackBar(conversation);
1929 updateStatusMessages();
1930 this.messageListAdapter.notifyDataSetChanged();
1931 updateChatMsgHint();
1932 if (notifyConversationRead && activity != null) {
1933 activity.onConversationRead(this.conversation);
1934 }
1935 updateSendButton();
1936 updateEditablity();
1937 }
1938 }
1939 }
1940
1941 protected void messageSent() {
1942 mSendingPgpMessage.set(false);
1943 this.binding.textinput.setText("");
1944 if (conversation.setCorrectingMessage(null)) {
1945 this.binding.textinput.append(conversation.getDraftMessage());
1946 conversation.setDraftMessage(null);
1947 }
1948 if (conversation.setNextMessage(this.binding.textinput.getText().toString())) {
1949 activity.xmppConnectionService.updateConversation(conversation);
1950 }
1951 updateChatMsgHint();
1952 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
1953 final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
1954 if (prefScrollToBottom || scrolledToBottom()) {
1955 new Handler().post(() -> {
1956 int size = messageList.size();
1957 this.binding.messagesView.setSelection(size - 1);
1958 });
1959 }
1960 }
1961
1962 public void setFocusOnInputField() {
1963 this.binding.textinput.requestFocus();
1964 }
1965
1966 public void doneSendingPgpMessage() {
1967 mSendingPgpMessage.set(false);
1968 }
1969
1970 public long getMaxHttpUploadSize(Conversation conversation) {
1971 final XmppConnection connection = conversation.getAccount().getXmppConnection();
1972 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1973 }
1974
1975 private void updateEditablity() {
1976 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
1977 this.binding.textinput.setFocusable(canWrite);
1978 this.binding.textinput.setFocusableInTouchMode(canWrite);
1979 this.binding.textSendButton.setEnabled(canWrite);
1980 this.binding.textinput.setCursorVisible(canWrite);
1981 }
1982
1983 public void updateSendButton() {
1984 boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
1985 final Conversation c = this.conversation;
1986 final Presence.Status status;
1987 final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
1988 final SendButtonAction action = SendButtonTool.getAction(getActivity(), c, text);
1989 if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
1990 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
1991 status = Presence.Status.OFFLINE;
1992 } else if (c.getMode() == Conversation.MODE_SINGLE) {
1993 status = c.getContact().getShownStatus();
1994 } else {
1995 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1996 }
1997 } else {
1998 status = Presence.Status.OFFLINE;
1999 }
2000 this.binding.textSendButton.setTag(action);
2001 this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2002 }
2003
2004 protected void updateDateSeparators() {
2005 synchronized (this.messageList) {
2006 for (int i = 0; i < this.messageList.size(); ++i) {
2007 final Message current = this.messageList.get(i);
2008 if (i == 0 || !UIHelper.sameDay(this.messageList.get(i - 1).getTimeSent(), current.getTimeSent())) {
2009 this.messageList.add(i, Message.createDateSeparator(current));
2010 i++;
2011 }
2012 }
2013 }
2014 }
2015
2016 protected void updateStatusMessages() {
2017 updateDateSeparators();
2018 synchronized (this.messageList) {
2019 if (showLoadMoreMessages(conversation)) {
2020 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2021 }
2022 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2023 ChatState state = conversation.getIncomingChatState();
2024 if (state == ChatState.COMPOSING) {
2025 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2026 } else if (state == ChatState.PAUSED) {
2027 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2028 } else {
2029 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2030 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
2031 return;
2032 } else {
2033 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
2034 this.messageList.add(i + 1,
2035 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2036 return;
2037 }
2038 }
2039 }
2040 }
2041 } else {
2042 final MucOptions mucOptions = conversation.getMucOptions();
2043 final List<MucOptions.User> allUsers = mucOptions.getUsers();
2044 final Set<ReadByMarker> addedMarkers = new HashSet<>();
2045 ChatState state = ChatState.COMPOSING;
2046 List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2047 if (users.size() == 0) {
2048 state = ChatState.PAUSED;
2049 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2050 }
2051 if (mucOptions.isPrivateAndNonAnonymous()) {
2052 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2053 final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2054 final List<MucOptions.User> shownMarkers = new ArrayList<>();
2055 for (ReadByMarker marker : markersForMessage) {
2056 if (!ReadByMarker.contains(marker, addedMarkers)) {
2057 addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2058 MucOptions.User user = mucOptions.findUser(marker);
2059 if (user != null && !users.contains(user)) {
2060 shownMarkers.add(user);
2061 }
2062 }
2063 }
2064 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2065 final Message statusMessage;
2066 final int size = shownMarkers.size();
2067 if (size > 1) {
2068 final String body;
2069 if (size <= 4) {
2070 body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2071 } else {
2072 body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2073 }
2074 statusMessage = Message.createStatusMessage(conversation, body);
2075 statusMessage.setCounterparts(shownMarkers);
2076 } else if (size == 1) {
2077 statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2078 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2079 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2080 } else {
2081 statusMessage = null;
2082 }
2083 if (statusMessage != null) {
2084 this.messageList.add(i + 1, statusMessage);
2085 }
2086 addedMarkers.add(markerForSender);
2087 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2088 break;
2089 }
2090 }
2091 }
2092 if (users.size() > 0) {
2093 Message statusMessage;
2094 if (users.size() == 1) {
2095 MucOptions.User user = users.get(0);
2096 int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2097 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2098 statusMessage.setTrueCounterpart(user.getRealJid());
2099 statusMessage.setCounterpart(user.getFullJid());
2100 } else {
2101 int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2102 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2103 statusMessage.setCounterparts(users);
2104 }
2105 this.messageList.add(statusMessage);
2106 }
2107
2108 }
2109 }
2110 }
2111
2112 public void stopScrolling() {
2113 long now = SystemClock.uptimeMillis();
2114 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2115 binding.messagesView.dispatchTouchEvent(cancel);
2116 }
2117
2118 private boolean showLoadMoreMessages(final Conversation c) {
2119 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2120 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2121 return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2122 }
2123
2124 private boolean hasMamSupport(final Conversation c) {
2125 if (c.getMode() == Conversation.MODE_SINGLE) {
2126 final XmppConnection connection = c.getAccount().getXmppConnection();
2127 return connection != null && connection.getFeatures().mam();
2128 } else {
2129 return c.getMucOptions().mamSupport();
2130 }
2131 }
2132
2133 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2134 showSnackbar(message, action, clickListener, null);
2135 }
2136
2137 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2138 this.binding.snackbar.setVisibility(View.VISIBLE);
2139 this.binding.snackbar.setOnClickListener(null);
2140 this.binding.snackbarMessage.setText(message);
2141 this.binding.snackbarMessage.setOnClickListener(null);
2142 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2143 if (action != 0) {
2144 this.binding.snackbarAction.setText(action);
2145 }
2146 this.binding.snackbarAction.setOnClickListener(clickListener);
2147 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2148 }
2149
2150 protected void hideSnackbar() {
2151 this.binding.snackbar.setVisibility(View.GONE);
2152 }
2153
2154 protected void sendPlainTextMessage(Message message) {
2155 activity.xmppConnectionService.sendMessage(message);
2156 messageSent();
2157 }
2158
2159 protected void sendPgpMessage(final Message message) {
2160 final XmppConnectionService xmppService = activity.xmppConnectionService;
2161 final Contact contact = message.getConversation().getContact();
2162 if (!activity.hasPgp()) {
2163 activity.showInstallPgpDialog();
2164 return;
2165 }
2166 if (conversation.getAccount().getPgpSignature() == null) {
2167 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2168 return;
2169 }
2170 if (!mSendingPgpMessage.compareAndSet(false, true)) {
2171 Log.d(Config.LOGTAG, "sending pgp message already in progress");
2172 }
2173 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2174 if (contact.getPgpKeyId() != 0) {
2175 xmppService.getPgpEngine().hasKey(contact,
2176 new UiCallback<Contact>() {
2177
2178 @Override
2179 public void userInputRequried(PendingIntent pi, Contact contact) {
2180 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2181 }
2182
2183 @Override
2184 public void success(Contact contact) {
2185 encryptTextMessage(message);
2186 }
2187
2188 @Override
2189 public void error(int error, Contact contact) {
2190 activity.runOnUiThread(() -> Toast.makeText(activity,
2191 R.string.unable_to_connect_to_keychain,
2192 Toast.LENGTH_SHORT
2193 ).show());
2194 mSendingPgpMessage.set(false);
2195 }
2196 });
2197
2198 } else {
2199 showNoPGPKeyDialog(false, (dialog, which) -> {
2200 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2201 xmppService.updateConversation(conversation);
2202 message.setEncryption(Message.ENCRYPTION_NONE);
2203 xmppService.sendMessage(message);
2204 messageSent();
2205 });
2206 }
2207 } else {
2208 if (conversation.getMucOptions().pgpKeysInUse()) {
2209 if (!conversation.getMucOptions().everybodyHasKeys()) {
2210 Toast warning = Toast
2211 .makeText(getActivity(),
2212 R.string.missing_public_keys,
2213 Toast.LENGTH_LONG);
2214 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2215 warning.show();
2216 }
2217 encryptTextMessage(message);
2218 } else {
2219 showNoPGPKeyDialog(true, (dialog, which) -> {
2220 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2221 message.setEncryption(Message.ENCRYPTION_NONE);
2222 xmppService.updateConversation(conversation);
2223 xmppService.sendMessage(message);
2224 messageSent();
2225 });
2226 }
2227 }
2228 }
2229
2230 public void encryptTextMessage(Message message) {
2231 activity.xmppConnectionService.getPgpEngine().encrypt(message,
2232 new UiCallback<Message>() {
2233
2234 @Override
2235 public void userInputRequried(PendingIntent pi, Message message) {
2236 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2237 }
2238
2239 @Override
2240 public void success(Message message) {
2241 //TODO the following two call can be made before the callback
2242 getActivity().runOnUiThread(() -> messageSent());
2243 }
2244
2245 @Override
2246 public void error(final int error, Message message) {
2247 getActivity().runOnUiThread(() -> {
2248 doneSendingPgpMessage();
2249 Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2250 });
2251
2252 }
2253 });
2254 }
2255
2256 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2257 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2258 builder.setIconAttribute(android.R.attr.alertDialogIcon);
2259 if (plural) {
2260 builder.setTitle(getString(R.string.no_pgp_keys));
2261 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2262 } else {
2263 builder.setTitle(getString(R.string.no_pgp_key));
2264 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2265 }
2266 builder.setNegativeButton(getString(R.string.cancel), null);
2267 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2268 builder.create().show();
2269 }
2270
2271 protected void sendAxolotlMessage(final Message message) {
2272 activity.xmppConnectionService.sendMessage(message);
2273 messageSent();
2274 }
2275
2276 public void appendText(String text) {
2277 if (text == null) {
2278 return;
2279 }
2280 String previous = this.binding.textinput.getText().toString();
2281 if (previous.length() != 0 && !previous.endsWith(" ")) {
2282 text = " " + text;
2283 }
2284 this.binding.textinput.append(text);
2285 }
2286
2287 @Override
2288 public boolean onEnterPressed() {
2289 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2290 final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2291 if (enterIsSend) {
2292 sendMessage();
2293 return true;
2294 } else {
2295 return false;
2296 }
2297 }
2298
2299 @Override
2300 public void onTypingStarted() {
2301 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2302 if (service == null) {
2303 return;
2304 }
2305 Account.State status = conversation.getAccount().getStatus();
2306 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2307 service.sendChatState(conversation);
2308 }
2309 updateSendButton();
2310 }
2311
2312 @Override
2313 public void onTypingStopped() {
2314 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2315 if (service == null) {
2316 return;
2317 }
2318 Account.State status = conversation.getAccount().getStatus();
2319 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2320 service.sendChatState(conversation);
2321 }
2322 }
2323
2324 @Override
2325 public void onTextDeleted() {
2326 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2327 if (service == null) {
2328 return;
2329 }
2330 Account.State status = conversation.getAccount().getStatus();
2331 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2332 service.sendChatState(conversation);
2333 }
2334 updateSendButton();
2335 }
2336
2337 @Override
2338 public void onTextChanged() {
2339 if (conversation != null && conversation.getCorrectingMessage() != null) {
2340 updateSendButton();
2341 }
2342 }
2343
2344 @Override
2345 public boolean onTabPressed(boolean repeated) {
2346 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2347 return false;
2348 }
2349 if (repeated) {
2350 completionIndex++;
2351 } else {
2352 lastCompletionLength = 0;
2353 completionIndex = 0;
2354 final String content = this.binding.textinput.getText().toString();
2355 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2356 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2357 firstWord = start == 0;
2358 incomplete = content.substring(start, lastCompletionCursor);
2359 }
2360 List<String> completions = new ArrayList<>();
2361 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2362 String name = user.getName();
2363 if (name != null && name.startsWith(incomplete)) {
2364 completions.add(name + (firstWord ? ": " : " "));
2365 }
2366 }
2367 Collections.sort(completions);
2368 if (completions.size() > completionIndex) {
2369 String completion = completions.get(completionIndex).substring(incomplete.length());
2370 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2371 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2372 lastCompletionLength = completion.length();
2373 } else {
2374 completionIndex = -1;
2375 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2376 lastCompletionLength = 0;
2377 }
2378 return true;
2379 }
2380
2381 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2382 try {
2383 getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2384 } catch (final SendIntentException ignored) {
2385 }
2386 }
2387
2388 @Override
2389 public void onBackendConnected() {
2390 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2391 String uuid = pendingConversationsUuid.pop();
2392 if (uuid != null) {
2393 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2394 if (conversation == null) {
2395 Log.d(Config.LOGTAG, "unable to restore activity");
2396 clearPending();
2397 return;
2398 }
2399 reInit(conversation);
2400 ScrollState scrollState = pendingScrollState.pop();
2401 if (scrollState != null) {
2402 setScrollPosition(scrollState);
2403 }
2404 }
2405 ActivityResult activityResult = postponedActivityResult.pop();
2406 if (activityResult != null) {
2407 handleActivityResult(activityResult);
2408 }
2409 clearPending();
2410 }
2411
2412 private void clearPending() {
2413 if (postponedActivityResult.pop() != null) {
2414 Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2415 }
2416 pendingScrollState.pop();
2417 if (pendingTakePhotoUri.pop() != null) {
2418 Log.e(Config.LOGTAG, "cleared pending photo uri");
2419 }
2420 }
2421
2422 public Conversation getConversation() {
2423 return conversation;
2424 }
2425}