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