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