1package eu.siacs.conversations.ui;
2
3import android.app.Activity;
4import android.app.AlertDialog;
5import android.app.Fragment;
6import android.app.PendingIntent;
7import android.content.ActivityNotFoundException;
8import android.content.Context;
9import android.content.DialogInterface;
10import android.content.Intent;
11import android.content.IntentSender.SendIntentException;
12import android.os.Bundle;
13import android.os.Handler;
14import android.support.v13.view.inputmethod.InputConnectionCompat;
15import android.support.v13.view.inputmethod.InputContentInfoCompat;
16import android.text.Editable;
17import android.text.InputType;
18import android.util.Log;
19import android.util.Pair;
20import android.view.ContextMenu;
21import android.view.ContextMenu.ContextMenuInfo;
22import android.view.Gravity;
23import android.view.KeyEvent;
24import android.view.LayoutInflater;
25import android.view.MenuItem;
26import android.view.View;
27import android.view.View.OnClickListener;
28import android.view.ViewGroup;
29import android.view.inputmethod.EditorInfo;
30import android.view.inputmethod.InputMethodManager;
31import android.widget.AbsListView;
32import android.widget.AbsListView.OnScrollListener;
33import android.widget.AdapterView;
34import android.widget.AdapterView.AdapterContextMenuInfo;
35import android.widget.ImageButton;
36import android.widget.ListView;
37import android.widget.PopupMenu;
38import android.widget.RelativeLayout;
39import android.widget.TextView;
40import android.widget.TextView.OnEditorActionListener;
41import android.widget.Toast;
42
43import net.java.otr4j.session.SessionStatus;
44
45import java.util.ArrayList;
46import java.util.Arrays;
47import java.util.Collections;
48import java.util.List;
49import java.util.UUID;
50import java.util.concurrent.atomic.AtomicBoolean;
51
52import eu.siacs.conversations.Config;
53import eu.siacs.conversations.R;
54import eu.siacs.conversations.entities.Account;
55import eu.siacs.conversations.entities.Blockable;
56import eu.siacs.conversations.entities.Contact;
57import eu.siacs.conversations.entities.Conversation;
58import eu.siacs.conversations.entities.DownloadableFile;
59import eu.siacs.conversations.entities.Message;
60import eu.siacs.conversations.entities.MucOptions;
61import eu.siacs.conversations.entities.Presence;
62import eu.siacs.conversations.entities.Transferable;
63import eu.siacs.conversations.entities.TransferablePlaceholder;
64import eu.siacs.conversations.http.HttpDownloadConnection;
65import eu.siacs.conversations.persistance.FileBackend;
66import eu.siacs.conversations.services.MessageArchiveService;
67import eu.siacs.conversations.services.XmppConnectionService;
68import eu.siacs.conversations.ui.XmppActivity.OnPresenceSelected;
69import eu.siacs.conversations.ui.XmppActivity.OnValueEdited;
70import eu.siacs.conversations.ui.adapter.MessageAdapter;
71import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureClicked;
72import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureLongClicked;
73import eu.siacs.conversations.ui.widget.ListSelectionManager;
74import eu.siacs.conversations.utils.GeoHelper;
75import eu.siacs.conversations.utils.NickValidityChecker;
76import eu.siacs.conversations.utils.UIHelper;
77import eu.siacs.conversations.xmpp.XmppConnection;
78import eu.siacs.conversations.xmpp.chatstate.ChatState;
79import eu.siacs.conversations.xmpp.jid.Jid;
80
81public class ConversationFragment extends Fragment implements EditMessage.KeyboardListener {
82
83 protected Conversation conversation;
84 private OnClickListener leaveMuc = new OnClickListener() {
85
86 @Override
87 public void onClick(View v) {
88 activity.endConversation(conversation);
89 }
90 };
91 private OnClickListener joinMuc = new OnClickListener() {
92
93 @Override
94 public void onClick(View v) {
95 activity.xmppConnectionService.joinMuc(conversation);
96 }
97 };
98 private OnClickListener enterPassword = new OnClickListener() {
99
100 @Override
101 public void onClick(View v) {
102 MucOptions muc = conversation.getMucOptions();
103 String password = muc.getPassword();
104 if (password == null) {
105 password = "";
106 }
107 activity.quickPasswordEdit(password, new OnValueEdited() {
108
109 @Override
110 public void onValueEdited(String value) {
111 activity.xmppConnectionService.providePasswordForMuc(
112 conversation, value);
113 }
114 });
115 }
116 };
117 protected ListView messagesView;
118 final protected List<Message> messageList = new ArrayList<>();
119 protected MessageAdapter messageListAdapter;
120 private EditMessage mEditMessage;
121 private ImageButton mSendButton;
122 private RelativeLayout snackbar;
123 private TextView snackbarMessage;
124 private TextView snackbarAction;
125 private Toast messageLoaderToast;
126
127 private OnScrollListener mOnScrollListener = new OnScrollListener() {
128
129 @Override
130 public void onScrollStateChanged(AbsListView view, int scrollState) {
131 // TODO Auto-generated method stub
132
133 }
134
135 @Override
136 public void onScroll(AbsListView view, int firstVisibleItem,
137 int visibleItemCount, int totalItemCount) {
138 synchronized (ConversationFragment.this.messageList) {
139 if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true,false) && messageList.size() > 0) {
140 long timestamp;
141 if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
142 timestamp = messageList.get(1).getTimeSent();
143 } else {
144 timestamp = messageList.get(0).getTimeSent();
145 }
146 activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
147 @Override
148 public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
149 if (ConversationFragment.this.conversation != conversation) {
150 conversation.messagesLoaded.set(true);
151 return;
152 }
153 activity.runOnUiThread(new Runnable() {
154 @Override
155 public void run() {
156 final int oldPosition = messagesView.getFirstVisiblePosition();
157 final Message message;
158 if (oldPosition < messageList.size()) {
159 message = messageList.get(oldPosition);
160 } else {
161 message = null;
162 }
163 String uuid = message != null ? message.getUuid() : null;
164 View v = messagesView.getChildAt(0);
165 final int pxOffset = (v == null) ? 0 : v.getTop();
166 ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
167 try {
168 updateStatusMessages();
169 } catch (IllegalStateException e) {
170 Log.d(Config.LOGTAG,"caught illegal state exception while updating status messages");
171 }
172 messageListAdapter.notifyDataSetChanged();
173 int pos = Math.max(getIndexOf(uuid,messageList),0);
174 messagesView.setSelectionFromTop(pos, pxOffset);
175 if (messageLoaderToast != null) {
176 messageLoaderToast.cancel();
177 }
178 conversation.messagesLoaded.set(true);
179 }
180 });
181 }
182
183 @Override
184 public void informUser(final int resId) {
185
186 activity.runOnUiThread(new Runnable() {
187 @Override
188 public void run() {
189 if (messageLoaderToast != null) {
190 messageLoaderToast.cancel();
191 }
192 if (ConversationFragment.this.conversation != conversation) {
193 return;
194 }
195 messageLoaderToast = Toast.makeText(activity, resId, Toast.LENGTH_LONG);
196 messageLoaderToast.show();
197 }
198 });
199
200 }
201 });
202
203 }
204 }
205 }
206 };
207
208 private int getIndexOf(String uuid, List<Message> messages) {
209 if (uuid == null) {
210 return messages.size() - 1;
211 }
212 for(int i = 0; i < messages.size(); ++i) {
213 if (uuid.equals(messages.get(i).getUuid())) {
214 return i;
215 } else {
216 Message next = messages.get(i);
217 while(next != null && next.wasMergedIntoPrevious()) {
218 if (uuid.equals(next.getUuid())) {
219 return i;
220 }
221 next = next.next();
222 }
223
224 }
225 }
226 return -1;
227 }
228
229 public Pair<Integer,Integer> getScrollPosition() {
230 if (this.messagesView.getCount() == 0 ||
231 this.messagesView.getLastVisiblePosition() == this.messagesView.getCount() - 1) {
232 return null;
233 } else {
234 final int pos = messagesView.getFirstVisiblePosition();
235 final View view = messagesView.getChildAt(0);
236 if (view == null) {
237 return null;
238 } else {
239 return new Pair<>(pos, view.getTop());
240 }
241 }
242 }
243
244 public void setScrollPosition(Pair<Integer,Integer> scrollPosition) {
245 if (scrollPosition != null) {
246 this.messagesView.setSelectionFromTop(scrollPosition.first, scrollPosition.second);
247 }
248 }
249
250 protected OnClickListener clickToDecryptListener = new OnClickListener() {
251
252 @Override
253 public void onClick(View v) {
254 PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
255 if (pendingIntent != null) {
256 try {
257 activity.startIntentSenderForResult(pendingIntent.getIntentSender(),
258 ConversationActivity.REQUEST_DECRYPT_PGP,
259 null,
260 0,
261 0,
262 0);
263 } catch (SendIntentException e) {
264 Toast.makeText(activity,R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
265 conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
266 }
267 }
268 updateSnackBar(conversation);
269 }
270 };
271 protected OnClickListener clickToVerify = new OnClickListener() {
272
273 @Override
274 public void onClick(View v) {
275 activity.verifyOtrSessionDialog(conversation, v);
276 }
277 };
278 private OnEditorActionListener mEditorActionListener = new OnEditorActionListener() {
279
280 @Override
281 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
282 if (actionId == EditorInfo.IME_ACTION_SEND) {
283 InputMethodManager imm = (InputMethodManager) v.getContext()
284 .getSystemService(Context.INPUT_METHOD_SERVICE);
285 if (imm.isFullscreenMode()) {
286 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
287 }
288 sendMessage();
289 return true;
290 } else {
291 return false;
292 }
293 }
294 };
295 private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
296 @Override
297 public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
298 // try to get permission to read the image, if applicable
299 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
300 try {
301 inputContentInfo.requestPermission();
302 } catch (Exception e) {
303 Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
304 Toast.makeText(
305 activity,
306 activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()),
307 Toast.LENGTH_LONG
308 ).show();
309 return false;
310 }
311 }
312
313 // send the image
314 activity.attachImageToConversation(inputContentInfo.getContentUri());
315
316 // TODO: revoke permissions?
317 // since uploading an image is async its tough to wire a callback to when
318 // the image has finished uploading.
319 // According to the docs: "calling IC#releasePermission() is just to be a
320 // good citizen. Even if we failed to call that method, the system would eventually revoke
321 // the permission sometime after inputContentInfo object gets garbage-collected."
322 // See: https://developer.android.com/samples/CommitContentSampleApp/src/com.example.android.commitcontent.app/MainActivity.html#l164
323 return true;
324 }
325 };
326 private OnClickListener mSendButtonListener = new OnClickListener() {
327
328 @Override
329 public void onClick(View v) {
330 Object tag = v.getTag();
331 if (tag instanceof SendButtonAction) {
332 SendButtonAction action = (SendButtonAction) tag;
333 switch (action) {
334 case TAKE_PHOTO:
335 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_TAKE_PHOTO);
336 break;
337 case SEND_LOCATION:
338 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_LOCATION);
339 break;
340 case RECORD_VOICE:
341 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
342 break;
343 case CHOOSE_PICTURE:
344 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_CHOOSE_IMAGE);
345 break;
346 case CANCEL:
347 if (conversation != null) {
348 if(conversation.setCorrectingMessage(null)) {
349 mEditMessage.setText("");
350 mEditMessage.append(conversation.getDraftMessage());
351 conversation.setDraftMessage(null);
352 } else if (conversation.getMode() == Conversation.MODE_MULTI) {
353 conversation.setNextCounterpart(null);
354 }
355 updateChatMsgHint();
356 updateSendButton();
357 }
358 break;
359 default:
360 sendMessage();
361 }
362 } else {
363 sendMessage();
364 }
365 }
366 };
367 private OnClickListener clickToMuc = new OnClickListener() {
368
369 @Override
370 public void onClick(View v) {
371 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
372 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
373 intent.putExtra("uuid", conversation.getUuid());
374 startActivity(intent);
375 }
376 };
377 private ConversationActivity activity;
378 private Message selectedMessage;
379
380 private void sendMessage() {
381 final String body = mEditMessage.getText().toString();
382 final Conversation conversation = this.conversation;
383 if (body.length() == 0 || conversation == null) {
384 return;
385 }
386 final Message message;
387 if (conversation.getCorrectingMessage() == null) {
388 message = new Message(conversation, body, conversation.getNextEncryption());
389 if (conversation.getMode() == Conversation.MODE_MULTI) {
390 if (conversation.getNextCounterpart() != null) {
391 message.setCounterpart(conversation.getNextCounterpart());
392 message.setType(Message.TYPE_PRIVATE);
393 }
394 }
395 } else {
396 message = conversation.getCorrectingMessage();
397 message.setBody(body);
398 message.setEdited(message.getUuid());
399 message.setUuid(UUID.randomUUID().toString());
400 }
401 switch (message.getConversation().getNextEncryption()) {
402 case Message.ENCRYPTION_OTR:
403 sendOtrMessage(message);
404 break;
405 case Message.ENCRYPTION_PGP:
406 sendPgpMessage(message);
407 break;
408 case Message.ENCRYPTION_AXOLOTL:
409 if(!activity.trustKeysIfNeeded(ConversationActivity.REQUEST_TRUST_KEYS_TEXT)) {
410 sendAxolotlMessage(message);
411 }
412 break;
413 default:
414 sendPlainTextMessage(message);
415 }
416 }
417
418 public void updateChatMsgHint() {
419 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
420 if (conversation.getCorrectingMessage() != null) {
421 this.mEditMessage.setHint(R.string.send_corrected_message);
422 } else if (multi && conversation.getNextCounterpart() != null) {
423 this.mEditMessage.setHint(getString(
424 R.string.send_private_message_to,
425 conversation.getNextCounterpart().getResourcepart()));
426 } else if (multi && !conversation.getMucOptions().participating()) {
427 this.mEditMessage.setHint(R.string.you_are_not_participating);
428 } else {
429 this.mEditMessage.setHint(UIHelper.getMessageHint(activity,conversation));
430 getActivity().invalidateOptionsMenu();
431 }
432 }
433
434 public void setupIme() {
435 if (activity != null) {
436 if (activity.usingEnterKey() && activity.enterIsSend()) {
437 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_FLAG_MULTI_LINE));
438 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
439 } else if (activity.usingEnterKey()) {
440 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
441 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
442 } else {
443 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
444 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
445 }
446 }
447 }
448
449 @Override
450 public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
451 final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
452 view.setOnClickListener(null);
453
454 String[] allImagesMimeType = {"image/*"};
455 mEditMessage = (EditMessage) view.findViewById(R.id.textinput);
456 mEditMessage.setOnClickListener(new OnClickListener() {
457
458 @Override
459 public void onClick(View v) {
460 if (activity != null) {
461 activity.hideConversationsOverview();
462 }
463 }
464 });
465 mEditMessage.setOnEditorActionListener(mEditorActionListener);
466 mEditMessage.setRichContentListener(allImagesMimeType, mEditorContentListener);
467
468 mSendButton = (ImageButton) view.findViewById(R.id.textSendButton);
469 mSendButton.setOnClickListener(this.mSendButtonListener);
470
471 snackbar = (RelativeLayout) view.findViewById(R.id.snackbar);
472 snackbarMessage = (TextView) view.findViewById(R.id.snackbar_message);
473 snackbarAction = (TextView) view.findViewById(R.id.snackbar_action);
474
475 messagesView = (ListView) view.findViewById(R.id.messages_view);
476 messagesView.setOnScrollListener(mOnScrollListener);
477 messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
478 messageListAdapter = new MessageAdapter((ConversationActivity) getActivity(), this.messageList);
479 messageListAdapter.setOnContactPictureClicked(new OnContactPictureClicked() {
480
481 @Override
482 public void onContactPictureClicked(Message message) {
483 if (message.getStatus() <= Message.STATUS_RECEIVED) {
484 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
485 Jid user = message.getCounterpart();
486 if (user != null && !user.isBareJid()) {
487 if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
488 Toast.makeText(activity,activity.getString(R.string.user_has_left_conference,user.getResourcepart()),Toast.LENGTH_SHORT).show();
489 }
490 highlightInConference(user.getResourcepart());
491 }
492 } else {
493 if (!message.getContact().isSelf()) {
494 String fingerprint;
495 if (message.getEncryption() == Message.ENCRYPTION_PGP
496 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
497 fingerprint = "pgp";
498 } else {
499 fingerprint = message.getFingerprint();
500 }
501 activity.switchToContactDetails(message.getContact(), fingerprint);
502 }
503 }
504 } else {
505 Account account = message.getConversation().getAccount();
506 Intent intent;
507 if (activity.manuallyChangePresence()) {
508 intent = new Intent(activity, SetPresenceActivity.class);
509 intent.putExtra(SetPresenceActivity.EXTRA_ACCOUNT, account.getJid().toBareJid().toString());
510 } else {
511 intent = new Intent(activity, EditAccountActivity.class);
512 intent.putExtra("jid", account.getJid().toBareJid().toString());
513 String fingerprint;
514 if (message.getEncryption() == Message.ENCRYPTION_PGP
515 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
516 fingerprint = "pgp";
517 } else {
518 fingerprint = message.getFingerprint();
519 }
520 intent.putExtra("fingerprint", fingerprint);
521 }
522 startActivity(intent);
523 }
524 }
525 });
526 messageListAdapter
527 .setOnContactPictureLongClicked(new OnContactPictureLongClicked() {
528
529 @Override
530 public void onContactPictureLongClicked(Message message) {
531 if (message.getStatus() <= Message.STATUS_RECEIVED) {
532 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
533 Jid user = message.getCounterpart();
534 if (user != null && !user.isBareJid()) {
535 if (message.getConversation().getMucOptions().isUserInRoom(user)) {
536 privateMessageWith(user);
537 } else {
538 Toast.makeText(activity, activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
539 }
540 }
541 }
542 } else {
543 activity.showQrCode();
544 }
545 }
546 });
547 messageListAdapter.setOnQuoteListener(new MessageAdapter.OnQuoteListener() {
548
549 @Override
550 public void onQuote(String text) {
551 if (mEditMessage.isEnabled()) {
552 text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
553 Editable editable = mEditMessage.getEditableText();
554 int position = mEditMessage.getSelectionEnd();
555 if (position == -1) position = editable.length();
556 if (position > 0 && editable.charAt(position - 1) != '\n') {
557 editable.insert(position++, "\n");
558 }
559 editable.insert(position, text);
560 position += text.length();
561 editable.insert(position++, "\n");
562 if (position < editable.length() && editable.charAt(position) != '\n') {
563 editable.insert(position, "\n");
564 }
565 mEditMessage.setSelection(position);
566 mEditMessage.requestFocus();
567 InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
568 .getSystemService(Context.INPUT_METHOD_SERVICE);
569 if (inputMethodManager != null) {
570 inputMethodManager.showSoftInput(mEditMessage, InputMethodManager.SHOW_IMPLICIT);
571 }
572 }
573 }
574 });
575 messagesView.setAdapter(messageListAdapter);
576
577 registerForContextMenu(messagesView);
578
579 return view;
580 }
581
582 @Override
583 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
584 synchronized (this.messageList) {
585 super.onCreateContextMenu(menu, v, menuInfo);
586 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
587 this.selectedMessage = this.messageList.get(acmi.position);
588 populateContextMenu(menu);
589 }
590 }
591
592 private void populateContextMenu(ContextMenu menu) {
593 final Message m = this.selectedMessage;
594 final Transferable t = m.getTransferable();
595 Message relevantForCorrection = m;
596 while(relevantForCorrection.mergeable(relevantForCorrection.next())) {
597 relevantForCorrection = relevantForCorrection.next();
598 }
599 if (m.getType() != Message.TYPE_STATUS) {
600 final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
601 && m.getType() != Message.TYPE_PRIVATE
602 && t == null;
603 activity.getMenuInflater().inflate(R.menu.message_context, menu);
604 menu.setHeaderTitle(R.string.message_options);
605 MenuItem selectText = menu.findItem(R.id.select_text);
606 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
607 MenuItem correctMessage = menu.findItem(R.id.correct_message);
608 MenuItem shareWith = menu.findItem(R.id.share_with);
609 MenuItem sendAgain = menu.findItem(R.id.send_again);
610 MenuItem copyUrl = menu.findItem(R.id.copy_url);
611 MenuItem downloadFile = menu.findItem(R.id.download_file);
612 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
613 MenuItem deleteFile = menu.findItem(R.id.delete_file);
614 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
615 if (!treatAsFile && !GeoHelper.isGeoUri(m.getBody()) && !m.treatAsDownloadable()) {
616 selectText.setVisible(ListSelectionManager.isSupported());
617 }
618 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
619 retryDecryption.setVisible(true);
620 }
621 if (relevantForCorrection.getType() == Message.TYPE_TEXT
622 && relevantForCorrection.isLastCorrectableMessage()
623 && (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
624 correctMessage.setVisible(true);
625 }
626 if (treatAsFile || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
627 shareWith.setVisible(true);
628 }
629 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
630 sendAgain.setVisible(true);
631 }
632 if (m.hasFileOnRemoteHost()
633 || GeoHelper.isGeoUri(m.getBody())
634 || m.treatAsDownloadable()
635 || (t != null && t instanceof HttpDownloadConnection)) {
636 copyUrl.setVisible(true);
637 }
638 if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
639 downloadFile.setVisible(true);
640 downloadFile.setTitle(activity.getString(R.string.download_x_file,UIHelper.getFileDescriptionString(activity, m)));
641 }
642 boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
643 || m.getStatus() == Message.STATUS_UNSEND
644 || m.getStatus() == Message.STATUS_OFFERED;
645 if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
646 cancelTransmission.setVisible(true);
647 }
648 if (treatAsFile) {
649 String path = m.getRelativeFilePath();
650 if (path == null || !path.startsWith("/")) {
651 deleteFile.setVisible(true);
652 deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
653 }
654 }
655 if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
656 showErrorMessage.setVisible(true);
657 }
658 }
659 }
660
661 @Override
662 public boolean onContextItemSelected(MenuItem item) {
663 switch (item.getItemId()) {
664 case R.id.share_with:
665 shareWith(selectedMessage);
666 return true;
667 case R.id.select_text:
668 selectText(selectedMessage);
669 return true;
670 case R.id.correct_message:
671 correctMessage(selectedMessage);
672 return true;
673 case R.id.send_again:
674 resendMessage(selectedMessage);
675 return true;
676 case R.id.copy_url:
677 copyUrl(selectedMessage);
678 return true;
679 case R.id.download_file:
680 downloadFile(selectedMessage);
681 return true;
682 case R.id.cancel_transmission:
683 cancelTransmission(selectedMessage);
684 return true;
685 case R.id.retry_decryption:
686 retryDecryption(selectedMessage);
687 return true;
688 case R.id.delete_file:
689 deleteFile(selectedMessage);
690 return true;
691 case R.id.show_error_message:
692 showErrorMessage(selectedMessage);
693 return true;
694 default:
695 return super.onContextItemSelected(item);
696 }
697 }
698
699 private void showErrorMessage(final Message message) {
700 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
701 builder.setTitle(R.string.error_message);
702 builder.setMessage(message.getErrorMessage());
703 builder.setPositiveButton(R.string.confirm,null);
704 builder.create().show();
705 }
706
707 private void shareWith(Message message) {
708 Intent shareIntent = new Intent();
709 shareIntent.setAction(Intent.ACTION_SEND);
710 if (GeoHelper.isGeoUri(message.getBody())) {
711 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
712 shareIntent.setType("text/plain");
713 } else if (!message.isFileOrImage()) {
714 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
715 shareIntent.setType("text/plain");
716 } else {
717 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
718 try {
719 shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(activity, file));
720 } catch (SecurityException e) {
721 Toast.makeText(activity, activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
722 return;
723 }
724 shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
725 String mime = message.getMimeType();
726 if (mime == null) {
727 mime = "*/*";
728 }
729 shareIntent.setType(mime);
730 }
731 try {
732 activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
733 } catch (ActivityNotFoundException e) {
734 //This should happen only on faulty androids because normally chooser is always available
735 Toast.makeText(activity,R.string.no_application_found_to_open_file,Toast.LENGTH_SHORT).show();
736 }
737 }
738
739 private void selectText(Message message) {
740 final int index;
741 synchronized (this.messageList) {
742 index = this.messageList.indexOf(message);
743 }
744 if (index >= 0) {
745 final int first = this.messagesView.getFirstVisiblePosition();
746 final int last = first + this.messagesView.getChildCount();
747 if (index >= first && index < last) {
748 final View view = this.messagesView.getChildAt(index - first);
749 final TextView messageBody = this.messageListAdapter.getMessageBody(view);
750 if (messageBody != null) {
751 ListSelectionManager.startSelection(messageBody);
752 }
753 }
754 }
755 }
756
757 private void deleteFile(Message message) {
758 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
759 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
760 activity.updateConversationList();
761 updateMessages();
762 }
763 }
764
765 private void resendMessage(Message message) {
766 if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
767 DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
768 if (!file.exists()) {
769 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
770 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
771 activity.updateConversationList();
772 updateMessages();
773 return;
774 }
775 }
776 activity.xmppConnectionService.resendFailedMessages(message);
777 }
778
779 private void copyUrl(Message message) {
780 final String url;
781 final int resId;
782 if (GeoHelper.isGeoUri(message.getBody())) {
783 resId = R.string.location;
784 url = message.getBody();
785 } else if (message.hasFileOnRemoteHost()) {
786 resId = R.string.file_url;
787 url = message.getFileParams().url.toString();
788 } else {
789 url = message.getBody().trim();
790 resId = R.string.file_url;
791 }
792 if (activity.copyTextToClipboard(url, resId)) {
793 Toast.makeText(activity, R.string.url_copied_to_clipboard,
794 Toast.LENGTH_SHORT).show();
795 }
796 }
797
798 private void downloadFile(Message message) {
799 activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message,true);
800 }
801
802 private void cancelTransmission(Message message) {
803 Transferable transferable = message.getTransferable();
804 if (transferable != null) {
805 transferable.cancel();
806 }
807 }
808
809 private void retryDecryption(Message message) {
810 message.setEncryption(Message.ENCRYPTION_PGP);
811 activity.updateConversationList();
812 updateMessages();
813 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
814 }
815
816 protected void privateMessageWith(final Jid counterpart) {
817 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
818 activity.xmppConnectionService.sendChatState(conversation);
819 }
820 this.mEditMessage.setText("");
821 this.conversation.setNextCounterpart(counterpart);
822 updateChatMsgHint();
823 updateSendButton();
824 }
825
826 private void correctMessage(Message message) {
827 while(message.mergeable(message.next())) {
828 message = message.next();
829 }
830 this.conversation.setCorrectingMessage(message);
831 final Editable editable = mEditMessage.getText();
832 this.conversation.setDraftMessage(editable.toString());
833 this.mEditMessage.setText("");
834 this.mEditMessage.append(message.getBody());
835
836 }
837
838 protected void highlightInConference(String nick) {
839 final Editable editable = mEditMessage.getText();
840 String oldString = editable.toString().trim();
841 final int pos = mEditMessage.getSelectionStart();
842 if (oldString.isEmpty() || pos == 0) {
843 editable.insert(0, nick + ": ");
844 } else {
845 final char before = editable.charAt(pos - 1);
846 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
847 if (before == '\n') {
848 editable.insert(pos, nick + ": ");
849 } else {
850 if (pos > 2 && editable.subSequence(pos-2,pos).toString().equals(": ")) {
851 if (NickValidityChecker.check(conversation,Arrays.asList(editable.subSequence(0,pos-2).toString().split(", ")))) {
852 editable.insert(pos - 2, ", " + nick);
853 return;
854 }
855 }
856 editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
857 if (Character.isWhitespace(after)) {
858 mEditMessage.setSelection(mEditMessage.getSelectionStart() + 1);
859 }
860 }
861 }
862 }
863
864 @Override
865 public void onStop() {
866 super.onStop();
867 if (this.conversation != null) {
868 final String msg = mEditMessage.getText().toString();
869 this.conversation.setNextMessage(msg);
870 updateChatState(this.conversation, msg);
871 }
872 }
873
874 private void updateChatState(final Conversation conversation, final String msg) {
875 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
876 Account.State status = conversation.getAccount().getStatus();
877 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
878 activity.xmppConnectionService.sendChatState(conversation);
879 }
880 }
881
882 public boolean reInit(Conversation conversation) {
883 if (conversation == null) {
884 return false;
885 }
886 this.activity = (ConversationActivity) getActivity();
887 setupIme();
888 if (this.conversation != null) {
889 final String msg = mEditMessage.getText().toString();
890 this.conversation.setNextMessage(msg);
891 if (this.conversation != conversation) {
892 updateChatState(this.conversation, msg);
893 }
894 this.conversation.trim();
895
896 }
897
898 if (activity != null) {
899 this.mSendButton.setContentDescription(activity.getString(R.string.send_message_to_x,conversation.getName()));
900 }
901
902 this.conversation = conversation;
903 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating();
904 this.mEditMessage.setEnabled(canWrite);
905 this.mSendButton.setEnabled(canWrite);
906 this.mEditMessage.setKeyboardListener(null);
907 this.mEditMessage.setText("");
908 this.mEditMessage.append(this.conversation.getNextMessage());
909 this.mEditMessage.setKeyboardListener(this);
910 messageListAdapter.updatePreferences();
911 this.messagesView.setAdapter(messageListAdapter);
912 updateMessages();
913 this.conversation.messagesLoaded.set(true);
914 synchronized (this.messageList) {
915 final Message first = conversation.getFirstUnreadMessage();
916 final int bottom = Math.max(0, this.messageList.size() - 1);
917 final int pos;
918 if (first == null) {
919 pos = bottom;
920 } else {
921 int i = getIndexOf(first.getUuid(), this.messageList);
922 pos = i < 0 ? bottom : i;
923 }
924 messagesView.setSelection(pos);
925 return pos == bottom;
926 }
927 }
928
929 private OnClickListener mEnableAccountListener = new OnClickListener() {
930 @Override
931 public void onClick(View v) {
932 final Account account = conversation == null ? null : conversation.getAccount();
933 if (account != null) {
934 account.setOption(Account.OPTION_DISABLED, false);
935 activity.xmppConnectionService.updateAccount(account);
936 }
937 }
938 };
939
940 private OnClickListener mUnblockClickListener = new OnClickListener() {
941 @Override
942 public void onClick(final View v) {
943 v.post(new Runnable() {
944 @Override
945 public void run() {
946 v.setVisibility(View.INVISIBLE);
947 }
948 });
949 if (conversation.isDomainBlocked()) {
950 BlockContactDialog.show(activity, conversation);
951 } else {
952 activity.unblockConversation(conversation);
953 }
954 }
955 };
956
957 private OnClickListener mBlockClickListener = new OnClickListener() {
958 @Override
959 public void onClick(final View view) {
960 final Jid jid = conversation.getJid();
961 if (jid.isDomainJid()) {
962 BlockContactDialog.show(activity, conversation);
963 } else {
964 PopupMenu popupMenu = new PopupMenu(activity, view);
965 popupMenu.inflate(R.menu.block);
966 popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
967 @Override
968 public boolean onMenuItemClick(MenuItem menuItem) {
969 Blockable blockable;
970 switch (menuItem.getItemId()) {
971 case R.id.block_domain:
972 blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
973 break;
974 default:
975 blockable = conversation;
976 }
977 BlockContactDialog.show(activity, blockable);
978 return true;
979 }
980 });
981 popupMenu.show();
982 }
983 }
984 };
985
986 private OnClickListener mAddBackClickListener = new OnClickListener() {
987
988 @Override
989 public void onClick(View v) {
990 final Contact contact = conversation == null ? null : conversation.getContact();
991 if (contact != null) {
992 activity.xmppConnectionService.createContact(contact);
993 activity.switchToContactDetails(contact);
994 }
995 }
996 };
997
998 private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
999 @Override
1000 public void onClick(View v) {
1001 final Contact contact = conversation == null ? null : conversation.getContact();
1002 if (contact != null) {
1003 activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
1004 activity.xmppConnectionService.getPresenceGenerator()
1005 .sendPresenceUpdatesTo(contact));
1006 hideSnackbar();
1007 }
1008 }
1009 };
1010
1011 private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
1012 @Override
1013 public void onClick(View view) {
1014 Intent intent = new Intent(activity, VerifyOTRActivity.class);
1015 intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
1016 intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
1017 intent.putExtra(VerifyOTRActivity.EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
1018 intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
1019 startActivity(intent);
1020 }
1021 };
1022
1023 private void updateSnackBar(final Conversation conversation) {
1024 final Account account = conversation.getAccount();
1025 final XmppConnection connection = account.getXmppConnection();
1026 final int mode = conversation.getMode();
1027 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1028 if (account.getStatus() == Account.State.DISABLED) {
1029 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1030 } else if (conversation.isBlocked()) {
1031 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1032 } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1033 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
1034 } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1035 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription);
1036 } else if (mode == Conversation.MODE_MULTI
1037 && !conversation.getMucOptions().online()
1038 && account.getStatus() == Account.State.ONLINE) {
1039 switch (conversation.getMucOptions().getError()) {
1040 case NICK_IN_USE:
1041 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1042 break;
1043 case NO_RESPONSE:
1044 showSnackbar(R.string.joining_conference, 0, null);
1045 break;
1046 case SERVER_NOT_FOUND:
1047 if (conversation.receivedMessagesCount() > 0) {
1048 showSnackbar(R.string.remote_server_not_found,R.string.try_again, joinMuc);
1049 } else {
1050 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1051 }
1052 break;
1053 case PASSWORD_REQUIRED:
1054 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1055 break;
1056 case BANNED:
1057 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1058 break;
1059 case MEMBERS_ONLY:
1060 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1061 break;
1062 case KICKED:
1063 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1064 break;
1065 case UNKNOWN:
1066 showSnackbar(R.string.conference_unknown_error, R.string.join, joinMuc);
1067 break;
1068 case SHUTDOWN:
1069 showSnackbar(R.string.conference_shutdown, R.string.join, joinMuc);
1070 break;
1071 default:
1072 hideSnackbar();
1073 break;
1074 }
1075 } else if (account.hasPendingPgpIntent(conversation)) {
1076 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1077 } else if (mode == Conversation.MODE_SINGLE
1078 && conversation.smpRequested()) {
1079 showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
1080 } else if (mode == Conversation.MODE_SINGLE
1081 && conversation.hasValidOtrSession()
1082 && (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
1083 && (!conversation.isOtrFingerprintVerified())) {
1084 showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
1085 } else if (connection != null
1086 && connection.getFeatures().blocking()
1087 && conversation.countMessages() != 0
1088 && !conversation.isBlocked()
1089 && conversation.isWithStranger()) {
1090 showSnackbar(R.string.received_message_from_stranger,R.string.block, mBlockClickListener);
1091 } else {
1092 hideSnackbar();
1093 }
1094 }
1095
1096 public void updateMessages() {
1097 synchronized (this.messageList) {
1098 if (getView() == null) {
1099 return;
1100 }
1101 final ConversationActivity activity = (ConversationActivity) getActivity();
1102 if (this.conversation != null) {
1103 conversation.populateWithMessages(ConversationFragment.this.messageList);
1104 updateSnackBar(conversation);
1105 updateStatusMessages();
1106 this.messageListAdapter.notifyDataSetChanged();
1107 updateChatMsgHint();
1108 if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
1109 activity.sendReadMarkerIfNecessary(conversation);
1110 }
1111 this.updateSendButton();
1112 }
1113 }
1114 }
1115
1116 protected void messageSent() {
1117 mSendingPgpMessage.set(false);
1118 mEditMessage.setText("");
1119 if (conversation.setCorrectingMessage(null)) {
1120 mEditMessage.append(conversation.getDraftMessage());
1121 conversation.setDraftMessage(null);
1122 }
1123 conversation.setNextMessage(mEditMessage.getText().toString());
1124 updateChatMsgHint();
1125 new Handler().post(new Runnable() {
1126 @Override
1127 public void run() {
1128 int size = messageList.size();
1129 messagesView.setSelection(size - 1);
1130 }
1131 });
1132 }
1133
1134 public void setFocusOnInputField() {
1135 mEditMessage.requestFocus();
1136 }
1137
1138 public void doneSendingPgpMessage() {
1139 mSendingPgpMessage.set(false);
1140 }
1141
1142 enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE}
1143
1144 private int getSendButtonImageResource(SendButtonAction action, Presence.Status status) {
1145 switch (action) {
1146 case TEXT:
1147 switch (status) {
1148 case CHAT:
1149 case ONLINE:
1150 return R.drawable.ic_send_text_online;
1151 case AWAY:
1152 return R.drawable.ic_send_text_away;
1153 case XA:
1154 case DND:
1155 return R.drawable.ic_send_text_dnd;
1156 default:
1157 return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1158 }
1159 case TAKE_PHOTO:
1160 switch (status) {
1161 case CHAT:
1162 case ONLINE:
1163 return R.drawable.ic_send_photo_online;
1164 case AWAY:
1165 return R.drawable.ic_send_photo_away;
1166 case XA:
1167 case DND:
1168 return R.drawable.ic_send_photo_dnd;
1169 default:
1170 return activity.getThemeResource(R.attr.ic_send_photo_offline, R.drawable.ic_send_photo_offline);
1171 }
1172 case RECORD_VOICE:
1173 switch (status) {
1174 case CHAT:
1175 case ONLINE:
1176 return R.drawable.ic_send_voice_online;
1177 case AWAY:
1178 return R.drawable.ic_send_voice_away;
1179 case XA:
1180 case DND:
1181 return R.drawable.ic_send_voice_dnd;
1182 default:
1183 return activity.getThemeResource(R.attr.ic_send_voice_offline, R.drawable.ic_send_voice_offline);
1184 }
1185 case SEND_LOCATION:
1186 switch (status) {
1187 case CHAT:
1188 case ONLINE:
1189 return R.drawable.ic_send_location_online;
1190 case AWAY:
1191 return R.drawable.ic_send_location_away;
1192 case XA:
1193 case DND:
1194 return R.drawable.ic_send_location_dnd;
1195 default:
1196 return activity.getThemeResource(R.attr.ic_send_location_offline, R.drawable.ic_send_location_offline);
1197 }
1198 case CANCEL:
1199 switch (status) {
1200 case CHAT:
1201 case ONLINE:
1202 return R.drawable.ic_send_cancel_online;
1203 case AWAY:
1204 return R.drawable.ic_send_cancel_away;
1205 case XA:
1206 case DND:
1207 return R.drawable.ic_send_cancel_dnd;
1208 default:
1209 return activity.getThemeResource(R.attr.ic_send_cancel_offline, R.drawable.ic_send_cancel_offline);
1210 }
1211 case CHOOSE_PICTURE:
1212 switch (status) {
1213 case CHAT:
1214 case ONLINE:
1215 return R.drawable.ic_send_picture_online;
1216 case AWAY:
1217 return R.drawable.ic_send_picture_away;
1218 case XA:
1219 case DND:
1220 return R.drawable.ic_send_picture_dnd;
1221 default:
1222 return activity.getThemeResource(R.attr.ic_send_picture_offline, R.drawable.ic_send_picture_offline);
1223 }
1224 }
1225 return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1226 }
1227
1228 public void updateSendButton() {
1229 final Conversation c = this.conversation;
1230 final SendButtonAction action;
1231 final Presence.Status status;
1232 final String text = this.mEditMessage == null ? "" : this.mEditMessage.getText().toString();
1233 final boolean empty = text.length() == 0;
1234 final boolean conference = c.getMode() == Conversation.MODE_MULTI;
1235 if (c.getCorrectingMessage() != null && (empty || text.equals(c.getCorrectingMessage().getBody()))) {
1236 action = SendButtonAction.CANCEL;
1237 } else if (conference && !c.getAccount().httpUploadAvailable()) {
1238 if (empty && c.getNextCounterpart() != null) {
1239 action = SendButtonAction.CANCEL;
1240 } else {
1241 action = SendButtonAction.TEXT;
1242 }
1243 } else {
1244 if (empty) {
1245 if (conference && c.getNextCounterpart() != null) {
1246 action = SendButtonAction.CANCEL;
1247 } else {
1248 String setting = activity.getPreferences().getString("quick_action", "recent");
1249 if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
1250 setting = "location";
1251 } else if (setting.equals("recent")) {
1252 setting = activity.getPreferences().getString("recently_used_quick_action", "text");
1253 }
1254 switch (setting) {
1255 case "photo":
1256 action = SendButtonAction.TAKE_PHOTO;
1257 break;
1258 case "location":
1259 action = SendButtonAction.SEND_LOCATION;
1260 break;
1261 case "voice":
1262 action = SendButtonAction.RECORD_VOICE;
1263 break;
1264 case "picture":
1265 action = SendButtonAction.CHOOSE_PICTURE;
1266 break;
1267 default:
1268 action = SendButtonAction.TEXT;
1269 break;
1270 }
1271 }
1272 } else {
1273 action = SendButtonAction.TEXT;
1274 }
1275 }
1276 if (activity.useSendButtonToIndicateStatus() && c != null
1277 && c.getAccount().getStatus() == Account.State.ONLINE) {
1278 if (c.getMode() == Conversation.MODE_SINGLE) {
1279 status = c.getContact().getShownStatus();
1280 } else {
1281 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1282 }
1283 } else {
1284 status = Presence.Status.OFFLINE;
1285 }
1286 this.mSendButton.setTag(action);
1287 this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
1288 }
1289
1290 protected void updateStatusMessages() {
1291 synchronized (this.messageList) {
1292 if (showLoadMoreMessages(conversation)) {
1293 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1294 }
1295 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1296 ChatState state = conversation.getIncomingChatState();
1297 if (state == ChatState.COMPOSING) {
1298 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1299 } else if (state == ChatState.PAUSED) {
1300 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1301 } else {
1302 for (int i = this.messageList.size() - 1; i >= 0; --i) {
1303 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1304 return;
1305 } else {
1306 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1307 this.messageList.add(i + 1,
1308 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1309 return;
1310 }
1311 }
1312 }
1313 }
1314 } else {
1315 ChatState state = ChatState.COMPOSING;
1316 List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state,5);
1317 if (users.size() == 0) {
1318 state = ChatState.PAUSED;
1319 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
1320
1321 }
1322 if (users.size() > 0) {
1323 Message statusMessage;
1324 if (users.size() == 1) {
1325 MucOptions.User user = users.get(0);
1326 int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
1327 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
1328 statusMessage.setTrueCounterpart(user.getRealJid());
1329 statusMessage.setCounterpart(user.getFullJid());
1330 } else {
1331 StringBuilder builder = new StringBuilder();
1332 for(MucOptions.User user : users) {
1333 if (builder.length() != 0) {
1334 builder.append(", ");
1335 }
1336 builder.append(UIHelper.getDisplayName(user));
1337 }
1338 int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
1339 statusMessage = Message.createStatusMessage(conversation, getString(id, builder.toString()));
1340 }
1341 this.messageList.add(statusMessage);
1342 }
1343
1344 }
1345 }
1346 }
1347
1348 private boolean showLoadMoreMessages(final Conversation c) {
1349 final boolean mam = hasMamSupport(c);
1350 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
1351 return mam && (c.getLastClearHistory() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
1352 }
1353
1354 private boolean hasMamSupport(final Conversation c) {
1355 if (c.getMode() == Conversation.MODE_SINGLE) {
1356 final XmppConnection connection = c.getAccount().getXmppConnection();
1357 return connection != null && connection.getFeatures().mam();
1358 } else {
1359 return c.getMucOptions().mamSupport();
1360 }
1361 }
1362
1363 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
1364 snackbar.setVisibility(View.VISIBLE);
1365 snackbar.setOnClickListener(null);
1366 snackbarMessage.setText(message);
1367 snackbarMessage.setOnClickListener(null);
1368 snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
1369 if (action != 0) {
1370 snackbarAction.setText(action);
1371 }
1372 snackbarAction.setOnClickListener(clickListener);
1373 }
1374
1375 protected void hideSnackbar() {
1376 snackbar.setVisibility(View.GONE);
1377 }
1378
1379 protected void sendPlainTextMessage(Message message) {
1380 ConversationActivity activity = (ConversationActivity) getActivity();
1381 activity.xmppConnectionService.sendMessage(message);
1382 messageSent();
1383 }
1384
1385 private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
1386
1387 protected void sendPgpMessage(final Message message) {
1388 final ConversationActivity activity = (ConversationActivity) getActivity();
1389 final XmppConnectionService xmppService = activity.xmppConnectionService;
1390 final Contact contact = message.getConversation().getContact();
1391 if (!activity.hasPgp()) {
1392 activity.showInstallPgpDialog();
1393 return;
1394 }
1395 if (conversation.getAccount().getPgpSignature() == null) {
1396 activity.announcePgp(conversation.getAccount(), conversation, activity.onOpenPGPKeyPublished);
1397 return;
1398 }
1399 if (!mSendingPgpMessage.compareAndSet(false,true)) {
1400 Log.d(Config.LOGTAG,"sending pgp message already in progress");
1401 }
1402 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1403 if (contact.getPgpKeyId() != 0) {
1404 xmppService.getPgpEngine().hasKey(contact,
1405 new UiCallback<Contact>() {
1406
1407 @Override
1408 public void userInputRequried(PendingIntent pi,
1409 Contact contact) {
1410 activity.runIntent(
1411 pi,
1412 ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1413 }
1414
1415 @Override
1416 public void success(Contact contact) {
1417 activity.encryptTextMessage(message);
1418 }
1419
1420 @Override
1421 public void error(int error, Contact contact) {
1422 activity.runOnUiThread(new Runnable() {
1423 @Override
1424 public void run() {
1425 Toast.makeText(activity,
1426 R.string.unable_to_connect_to_keychain,
1427 Toast.LENGTH_SHORT
1428 ).show();
1429 }
1430 });
1431 mSendingPgpMessage.set(false);
1432 }
1433 });
1434
1435 } else {
1436 showNoPGPKeyDialog(false,
1437 new DialogInterface.OnClickListener() {
1438
1439 @Override
1440 public void onClick(DialogInterface dialog,
1441 int which) {
1442 conversation
1443 .setNextEncryption(Message.ENCRYPTION_NONE);
1444 xmppService.updateConversation(conversation);
1445 message.setEncryption(Message.ENCRYPTION_NONE);
1446 xmppService.sendMessage(message);
1447 messageSent();
1448 }
1449 });
1450 }
1451 } else {
1452 if (conversation.getMucOptions().pgpKeysInUse()) {
1453 if (!conversation.getMucOptions().everybodyHasKeys()) {
1454 Toast warning = Toast
1455 .makeText(getActivity(),
1456 R.string.missing_public_keys,
1457 Toast.LENGTH_LONG);
1458 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1459 warning.show();
1460 }
1461 activity.encryptTextMessage(message);
1462 } else {
1463 showNoPGPKeyDialog(true,
1464 new DialogInterface.OnClickListener() {
1465
1466 @Override
1467 public void onClick(DialogInterface dialog,
1468 int which) {
1469 conversation
1470 .setNextEncryption(Message.ENCRYPTION_NONE);
1471 message.setEncryption(Message.ENCRYPTION_NONE);
1472 xmppService.updateConversation(conversation);
1473 xmppService.sendMessage(message);
1474 messageSent();
1475 }
1476 });
1477 }
1478 }
1479 }
1480
1481 public void showNoPGPKeyDialog(boolean plural,
1482 DialogInterface.OnClickListener listener) {
1483 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1484 builder.setIconAttribute(android.R.attr.alertDialogIcon);
1485 if (plural) {
1486 builder.setTitle(getString(R.string.no_pgp_keys));
1487 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1488 } else {
1489 builder.setTitle(getString(R.string.no_pgp_key));
1490 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1491 }
1492 builder.setNegativeButton(getString(R.string.cancel), null);
1493 builder.setPositiveButton(getString(R.string.send_unencrypted),
1494 listener);
1495 builder.create().show();
1496 }
1497
1498 protected void sendAxolotlMessage(final Message message) {
1499 final ConversationActivity activity = (ConversationActivity) getActivity();
1500 final XmppConnectionService xmppService = activity.xmppConnectionService;
1501 xmppService.sendMessage(message);
1502 messageSent();
1503 }
1504
1505 protected void sendOtrMessage(final Message message) {
1506 final ConversationActivity activity = (ConversationActivity) getActivity();
1507 final XmppConnectionService xmppService = activity.xmppConnectionService;
1508 activity.selectPresence(message.getConversation(),
1509 new OnPresenceSelected() {
1510
1511 @Override
1512 public void onPresenceSelected() {
1513 message.setCounterpart(conversation.getNextCounterpart());
1514 xmppService.sendMessage(message);
1515 messageSent();
1516 }
1517 });
1518 }
1519
1520 public void appendText(String text) {
1521 if (text == null) {
1522 return;
1523 }
1524 String previous = this.mEditMessage.getText().toString();
1525 if (previous.length() != 0 && !previous.endsWith(" ")) {
1526 text = " " + text;
1527 }
1528 this.mEditMessage.append(text);
1529 }
1530
1531 @Override
1532 public boolean onEnterPressed() {
1533 if (activity.enterIsSend()) {
1534 sendMessage();
1535 return true;
1536 } else {
1537 return false;
1538 }
1539 }
1540
1541 @Override
1542 public void onTypingStarted() {
1543 Account.State status = conversation.getAccount().getStatus();
1544 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1545 activity.xmppConnectionService.sendChatState(conversation);
1546 }
1547 activity.hideConversationsOverview();
1548 updateSendButton();
1549 }
1550
1551 @Override
1552 public void onTypingStopped() {
1553 Account.State status = conversation.getAccount().getStatus();
1554 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1555 activity.xmppConnectionService.sendChatState(conversation);
1556 }
1557 }
1558
1559 @Override
1560 public void onTextDeleted() {
1561 Account.State status = conversation.getAccount().getStatus();
1562 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1563 activity.xmppConnectionService.sendChatState(conversation);
1564 }
1565 updateSendButton();
1566 }
1567
1568 @Override
1569 public void onTextChanged() {
1570 if (conversation != null && conversation.getCorrectingMessage() != null) {
1571 updateSendButton();
1572 }
1573 }
1574
1575 private int completionIndex = 0;
1576 private int lastCompletionLength = 0;
1577 private String incomplete;
1578 private int lastCompletionCursor;
1579 private boolean firstWord = false;
1580
1581 @Override
1582 public boolean onTabPressed(boolean repeated) {
1583 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
1584 return false;
1585 }
1586 if (repeated) {
1587 completionIndex++;
1588 } else {
1589 lastCompletionLength = 0;
1590 completionIndex = 0;
1591 final String content = mEditMessage.getText().toString();
1592 lastCompletionCursor = mEditMessage.getSelectionEnd();
1593 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ",lastCompletionCursor-1) + 1 : 0;
1594 firstWord = start == 0;
1595 incomplete = content.substring(start,lastCompletionCursor);
1596 }
1597 List<String> completions = new ArrayList<>();
1598 for(MucOptions.User user : conversation.getMucOptions().getUsers()) {
1599 String name = user.getName();
1600 if (name != null && name.startsWith(incomplete)) {
1601 completions.add(name+(firstWord ? ": " : " "));
1602 }
1603 }
1604 Collections.sort(completions);
1605 if (completions.size() > completionIndex) {
1606 String completion = completions.get(completionIndex).substring(incomplete.length());
1607 mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1608 mEditMessage.getEditableText().insert(lastCompletionCursor, completion);
1609 lastCompletionLength = completion.length();
1610 } else {
1611 completionIndex = -1;
1612 mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1613 lastCompletionLength = 0;
1614 }
1615 return true;
1616 }
1617
1618 @Override
1619 public void onActivityResult(int requestCode, int resultCode,
1620 final Intent data) {
1621 if (resultCode == Activity.RESULT_OK) {
1622 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1623 activity.getSelectedConversation().getAccount().getPgpDecryptionService().continueDecryption(true);
1624 } else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_TEXT) {
1625 final String body = mEditMessage.getText().toString();
1626 Message message = new Message(conversation, body, conversation.getNextEncryption());
1627 sendAxolotlMessage(message);
1628 } else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_MENU) {
1629 int choice = data.getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID);
1630 activity.selectPresenceToAttachFile(choice, conversation.getNextEncryption());
1631 }
1632 }
1633 }
1634
1635}