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