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