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