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