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