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