1package eu.siacs.conversations.ui;
2
3import android.app.AlertDialog;
4import android.app.Fragment;
5import android.app.PendingIntent;
6import android.content.Context;
7import android.content.DialogInterface;
8import android.content.Intent;
9import android.content.IntentSender;
10import android.content.IntentSender.SendIntentException;
11import android.os.Bundle;
12import android.text.InputType;
13import android.view.ContextMenu;
14import android.view.ContextMenu.ContextMenuInfo;
15import android.view.Gravity;
16import android.view.KeyEvent;
17import android.view.LayoutInflater;
18import android.view.MenuItem;
19import android.view.View;
20import android.view.View.OnClickListener;
21import android.view.ViewGroup;
22import android.view.inputmethod.EditorInfo;
23import android.view.inputmethod.InputMethodManager;
24import android.widget.AbsListView;
25import android.widget.AbsListView.OnScrollListener;
26import android.widget.AdapterView;
27import android.widget.AdapterView.AdapterContextMenuInfo;
28import android.widget.ImageButton;
29import android.widget.ListView;
30import android.widget.RelativeLayout;
31import android.widget.TextView;
32import android.widget.TextView.OnEditorActionListener;
33import android.widget.Toast;
34
35import net.java.otr4j.session.SessionStatus;
36
37import java.net.URLConnection;
38import java.util.ArrayList;
39import java.util.List;
40import java.util.NoSuchElementException;
41import java.util.concurrent.ConcurrentLinkedQueue;
42
43import eu.siacs.conversations.Config;
44import eu.siacs.conversations.R;
45import eu.siacs.conversations.crypto.PgpEngine;
46import eu.siacs.conversations.entities.Account;
47import eu.siacs.conversations.entities.Contact;
48import eu.siacs.conversations.entities.Conversation;
49import eu.siacs.conversations.entities.Downloadable;
50import eu.siacs.conversations.entities.DownloadableFile;
51import eu.siacs.conversations.entities.DownloadablePlaceholder;
52import eu.siacs.conversations.entities.Message;
53import eu.siacs.conversations.entities.MucOptions;
54import eu.siacs.conversations.entities.Presences;
55import eu.siacs.conversations.services.XmppConnectionService;
56import eu.siacs.conversations.ui.XmppActivity.OnPresenceSelected;
57import eu.siacs.conversations.ui.XmppActivity.OnValueEdited;
58import eu.siacs.conversations.ui.adapter.MessageAdapter;
59import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureClicked;
60import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureLongClicked;
61import eu.siacs.conversations.utils.GeoHelper;
62import eu.siacs.conversations.utils.UIHelper;
63import eu.siacs.conversations.xmpp.chatstate.ChatState;
64import eu.siacs.conversations.xmpp.jid.Jid;
65
66public class ConversationFragment extends Fragment implements EditMessage.KeyboardListener {
67
68 protected Conversation conversation;
69 private OnClickListener leaveMuc = new OnClickListener() {
70
71 @Override
72 public void onClick(View v) {
73 activity.endConversation(conversation);
74 }
75 };
76 private OnClickListener joinMuc = new OnClickListener() {
77
78 @Override
79 public void onClick(View v) {
80 activity.xmppConnectionService.joinMuc(conversation);
81 }
82 };
83 private OnClickListener enterPassword = new OnClickListener() {
84
85 @Override
86 public void onClick(View v) {
87 MucOptions muc = conversation.getMucOptions();
88 String password = muc.getPassword();
89 if (password == null) {
90 password = "";
91 }
92 activity.quickPasswordEdit(password, new OnValueEdited() {
93
94 @Override
95 public void onValueEdited(String value) {
96 activity.xmppConnectionService.providePasswordForMuc(
97 conversation, value);
98 }
99 });
100 }
101 };
102 protected ListView messagesView;
103 final protected List<Message> messageList = new ArrayList<>();
104 protected MessageAdapter messageListAdapter;
105 private EditMessage mEditMessage;
106 private ImageButton mSendButton;
107 private RelativeLayout snackbar;
108 private TextView snackbarMessage;
109 private TextView snackbarAction;
110 private boolean messagesLoaded = true;
111 private Toast messageLoaderToast;
112
113 private OnScrollListener mOnScrollListener = new OnScrollListener() {
114
115 @Override
116 public void onScrollStateChanged(AbsListView view, int scrollState) {
117 // TODO Auto-generated method stub
118
119 }
120
121 private int getIndexOf(String uuid, List<Message> messages) {
122 if (uuid == null) {
123 return 0;
124 }
125 for(int i = 0; i < messages.size(); ++i) {
126 if (uuid.equals(messages.get(i).getUuid())) {
127 return i;
128 } else {
129 Message next = messages.get(i);
130 while(next != null && next.wasMergedIntoPrevious()) {
131 if (uuid.equals(next.getUuid())) {
132 return i;
133 }
134 next = next.next();
135 }
136
137 }
138 }
139 return 0;
140 }
141
142 @Override
143 public void onScroll(AbsListView view, int firstVisibleItem,
144 int visibleItemCount, int totalItemCount) {
145 synchronized (ConversationFragment.this.messageList) {
146 if (firstVisibleItem < 5 && messagesLoaded && messageList.size() > 0) {
147 long timestamp = ConversationFragment.this.messageList.get(0).getTimeSent();
148 messagesLoaded = false;
149 activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
150 @Override
151 public void onMoreMessagesLoaded(final int c, Conversation conversation) {
152 if (ConversationFragment.this.conversation != conversation) {
153 return;
154 }
155 activity.runOnUiThread(new Runnable() {
156 @Override
157 public void run() {
158 final int oldPosition = messagesView.getFirstVisiblePosition();
159 Message message = messageList.get(oldPosition);
160 String uuid = message != null ? message.getUuid() : null;
161 View v = messagesView.getChildAt(0);
162 final int pxOffset = (v == null) ? 0 : v.getTop();
163 ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
164 updateStatusMessages();
165 messageListAdapter.notifyDataSetChanged();
166 int pos = getIndexOf(uuid,messageList);
167 messagesView.setSelectionFromTop(pos, pxOffset);
168 messagesLoaded = true;
169 if (messageLoaderToast != null) {
170 messageLoaderToast.cancel();
171 }
172 }
173 });
174 }
175
176 @Override
177 public void informUser(final int resId) {
178
179 activity.runOnUiThread(new Runnable() {
180 @Override
181 public void run() {
182 if (messageLoaderToast != null) {
183 messageLoaderToast.cancel();
184 }
185 if (ConversationFragment.this.conversation != conversation) {
186 return;
187 }
188 messageLoaderToast = Toast.makeText(activity, resId, Toast.LENGTH_LONG);
189 messageLoaderToast.show();
190 }
191 });
192
193 }
194 });
195
196 }
197 }
198 }
199 };
200 private IntentSender askForPassphraseIntent = null;
201 protected OnClickListener clickToDecryptListener = new OnClickListener() {
202
203 @Override
204 public void onClick(View v) {
205 if (activity.hasPgp() && askForPassphraseIntent != null) {
206 try {
207 getActivity().startIntentSenderForResult(
208 askForPassphraseIntent,
209 ConversationActivity.REQUEST_DECRYPT_PGP, null, 0,
210 0, 0);
211 askForPassphraseIntent = null;
212 } catch (SendIntentException e) {
213 //
214 }
215 }
216 }
217 };
218 protected OnClickListener clickToVerify = new OnClickListener() {
219
220 @Override
221 public void onClick(View v) {
222 activity.verifyOtrSessionDialog(conversation, v);
223 }
224 };
225 private ConcurrentLinkedQueue<Message> mEncryptedMessages = new ConcurrentLinkedQueue<>();
226 private boolean mDecryptJobRunning = false;
227 private OnEditorActionListener mEditorActionListener = new OnEditorActionListener() {
228
229 @Override
230 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
231 if (actionId == EditorInfo.IME_ACTION_SEND) {
232 InputMethodManager imm = (InputMethodManager) v.getContext()
233 .getSystemService(Context.INPUT_METHOD_SERVICE);
234 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
235 sendMessage();
236 return true;
237 } else {
238 return false;
239 }
240 }
241 };
242 private OnClickListener mSendButtonListener = new OnClickListener() {
243
244 @Override
245 public void onClick(View v) {
246 Object tag = v.getTag();
247 if (tag instanceof SendButtonAction) {
248 SendButtonAction action = (SendButtonAction) tag;
249 switch (action) {
250 case TAKE_PHOTO:
251 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_TAKE_PHOTO);
252 break;
253 case SEND_LOCATION:
254 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_LOCATION);
255 break;
256 case RECORD_VOICE:
257 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
258 break;
259 case CHOOSE_PICTURE:
260 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_CHOOSE_IMAGE);
261 break;
262 case CANCEL:
263 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
264 conversation.setNextCounterpart(null);
265 updateChatMsgHint();
266 updateSendButton();
267 }
268 break;
269 default:
270 sendMessage();
271 }
272 } else {
273 sendMessage();
274 }
275 }
276 };
277 private OnClickListener clickToMuc = new OnClickListener() {
278
279 @Override
280 public void onClick(View v) {
281 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
282 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
283 intent.putExtra("uuid", conversation.getUuid());
284 startActivity(intent);
285 }
286 };
287 private ConversationActivity activity;
288 private Message selectedMessage;
289
290 private void sendMessage() {
291 final String body = mEditMessage.getText().toString();
292 if (body.length() == 0 || this.conversation == null) {
293 return;
294 }
295 Message message = new Message(conversation, body, conversation.getNextEncryption(activity.forceEncryption()));
296 if (conversation.getMode() == Conversation.MODE_MULTI) {
297 if (conversation.getNextCounterpart() != null) {
298 message.setCounterpart(conversation.getNextCounterpart());
299 message.setType(Message.TYPE_PRIVATE);
300 }
301 }
302 if (conversation.getNextEncryption(activity.forceEncryption()) == Message.ENCRYPTION_OTR) {
303 sendOtrMessage(message);
304 } else if (conversation.getNextEncryption(activity.forceEncryption()) == Message.ENCRYPTION_PGP) {
305 sendPgpMessage(message);
306 } else {
307 sendPlainTextMessage(message);
308 }
309 }
310
311 public void updateChatMsgHint() {
312 if (conversation.getMode() == Conversation.MODE_MULTI
313 && conversation.getNextCounterpart() != null) {
314 this.mEditMessage.setHint(getString(
315 R.string.send_private_message_to,
316 conversation.getNextCounterpart().getResourcepart()));
317 } else {
318 switch (conversation.getNextEncryption(activity.forceEncryption())) {
319 case Message.ENCRYPTION_NONE:
320 mEditMessage
321 .setHint(getString(R.string.send_plain_text_message));
322 break;
323 case Message.ENCRYPTION_OTR:
324 mEditMessage.setHint(getString(R.string.send_otr_message));
325 break;
326 case Message.ENCRYPTION_PGP:
327 mEditMessage.setHint(getString(R.string.send_pgp_message));
328 break;
329 default:
330 break;
331 }
332 getActivity().invalidateOptionsMenu();
333 }
334 }
335
336 private void setupIme() {
337 if (((ConversationActivity) getActivity()).usingEnterKey()) {
338 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
339 } else {
340 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
341 }
342 }
343
344 @Override
345 public View onCreateView(final LayoutInflater inflater,
346 ViewGroup container, Bundle savedInstanceState) {
347 final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
348 view.setOnClickListener(null);
349 mEditMessage = (EditMessage) view.findViewById(R.id.textinput);
350 setupIme();
351 mEditMessage.setOnClickListener(new OnClickListener() {
352
353 @Override
354 public void onClick(View v) {
355 if (activity != null) {
356 activity.hideConversationsOverview();
357 }
358 }
359 });
360 mEditMessage.setOnEditorActionListener(mEditorActionListener);
361
362 mSendButton = (ImageButton) view.findViewById(R.id.textSendButton);
363 mSendButton.setOnClickListener(this.mSendButtonListener);
364
365 snackbar = (RelativeLayout) view.findViewById(R.id.snackbar);
366 snackbarMessage = (TextView) view.findViewById(R.id.snackbar_message);
367 snackbarAction = (TextView) view.findViewById(R.id.snackbar_action);
368
369 messagesView = (ListView) view.findViewById(R.id.messages_view);
370 messagesView.setOnScrollListener(mOnScrollListener);
371 messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
372 messageListAdapter = new MessageAdapter((ConversationActivity) getActivity(), this.messageList);
373 messageListAdapter.setOnContactPictureClicked(new OnContactPictureClicked() {
374
375 @Override
376 public void onContactPictureClicked(Message message) {
377 if (message.getStatus() <= Message.STATUS_RECEIVED) {
378 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
379 if (message.getCounterpart() != null) {
380 if (!message.getCounterpart().isBareJid()) {
381 highlightInConference(message.getCounterpart().getResourcepart());
382 } else {
383 highlightInConference(message.getCounterpart().toString());
384 }
385 }
386 } else {
387 activity.switchToContactDetails(message.getContact());
388 }
389 } else {
390 Account account = message.getConversation().getAccount();
391 Intent intent = new Intent(activity, EditAccountActivity.class);
392 intent.putExtra("jid", account.getJid().toBareJid().toString());
393 startActivity(intent);
394 }
395 }
396 });
397 messageListAdapter
398 .setOnContactPictureLongClicked(new OnContactPictureLongClicked() {
399
400 @Override
401 public void onContactPictureLongClicked(Message message) {
402 if (message.getStatus() <= Message.STATUS_RECEIVED) {
403 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
404 if (message.getCounterpart() != null) {
405 privateMessageWith(message.getCounterpart());
406 }
407 }
408 } else {
409 activity.showQrCode();
410 }
411 }
412 });
413 messagesView.setAdapter(messageListAdapter);
414
415 registerForContextMenu(messagesView);
416
417 return view;
418 }
419
420 @Override
421 public void onCreateContextMenu(ContextMenu menu, View v,
422 ContextMenuInfo menuInfo) {
423 synchronized (this.messageList) {
424 super.onCreateContextMenu(menu, v, menuInfo);
425 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
426 this.selectedMessage = this.messageList.get(acmi.position);
427 populateContextMenu(menu);
428 }
429 }
430
431 private void populateContextMenu(ContextMenu menu) {
432 final Message m = this.selectedMessage;
433 if (m.getType() != Message.TYPE_STATUS) {
434 activity.getMenuInflater().inflate(R.menu.message_context, menu);
435 menu.setHeaderTitle(R.string.message_options);
436 MenuItem copyText = menu.findItem(R.id.copy_text);
437 MenuItem shareWith = menu.findItem(R.id.share_with);
438 MenuItem sendAgain = menu.findItem(R.id.send_again);
439 MenuItem copyUrl = menu.findItem(R.id.copy_url);
440 MenuItem downloadImage = menu.findItem(R.id.download_image);
441 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
442 if ((m.getType() != Message.TYPE_TEXT && m.getType() != Message.TYPE_PRIVATE)
443 || m.getDownloadable() != null || GeoHelper.isGeoUri(m.getBody())) {
444 copyText.setVisible(false);
445 }
446 if ((m.getType() == Message.TYPE_TEXT
447 || m.getType() == Message.TYPE_PRIVATE
448 || m.getDownloadable() != null)
449 && (!GeoHelper.isGeoUri(m.getBody()))) {
450 shareWith.setVisible(false);
451 }
452 if (m.getStatus() != Message.STATUS_SEND_FAILED) {
453 sendAgain.setVisible(false);
454 }
455 if (((m.getType() != Message.TYPE_IMAGE && m.getDownloadable() == null)
456 || m.getImageParams().url == null) && !GeoHelper.isGeoUri(m.getBody())) {
457 copyUrl.setVisible(false);
458 }
459 if (m.getType() != Message.TYPE_TEXT
460 || m.getDownloadable() != null
461 || !m.bodyContainsDownloadable()) {
462 downloadImage.setVisible(false);
463 }
464 if (!((m.getDownloadable() != null && !(m.getDownloadable() instanceof DownloadablePlaceholder))
465 || (m.isFileOrImage() && (m.getStatus() == Message.STATUS_WAITING
466 || m.getStatus() == Message.STATUS_OFFERED)))) {
467 cancelTransmission.setVisible(false);
468 }
469 }
470 }
471
472 @Override
473 public boolean onContextItemSelected(MenuItem item) {
474 switch (item.getItemId()) {
475 case R.id.share_with:
476 shareWith(selectedMessage);
477 return true;
478 case R.id.copy_text:
479 copyText(selectedMessage);
480 return true;
481 case R.id.send_again:
482 resendMessage(selectedMessage);
483 return true;
484 case R.id.copy_url:
485 copyUrl(selectedMessage);
486 return true;
487 case R.id.download_image:
488 downloadImage(selectedMessage);
489 return true;
490 case R.id.cancel_transmission:
491 cancelTransmission(selectedMessage);
492 return true;
493 default:
494 return super.onContextItemSelected(item);
495 }
496 }
497
498 private void shareWith(Message message) {
499 Intent shareIntent = new Intent();
500 shareIntent.setAction(Intent.ACTION_SEND);
501 if (GeoHelper.isGeoUri(message.getBody())) {
502 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
503 shareIntent.setType("text/plain");
504 } else {
505 shareIntent.putExtra(Intent.EXTRA_STREAM,
506 activity.xmppConnectionService.getFileBackend()
507 .getJingleFileUri(message));
508 shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
509 String path = message.getRelativeFilePath();
510 String mime = path == null ? null : URLConnection.guessContentTypeFromName(path);
511 if (mime == null) {
512 mime = "image/webp";
513 }
514 shareIntent.setType(mime);
515 }
516 activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
517 }
518
519 private void copyText(Message message) {
520 if (activity.copyTextToClipboard(message.getMergedBody(),
521 R.string.message_text)) {
522 Toast.makeText(activity, R.string.message_copied_to_clipboard,
523 Toast.LENGTH_SHORT).show();
524 }
525 }
526
527 private void resendMessage(Message message) {
528 if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
529 DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
530 if (!file.exists()) {
531 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
532 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
533 return;
534 }
535 }
536 activity.xmppConnectionService.resendFailedMessages(message);
537 }
538
539 private void copyUrl(Message message) {
540 final String url;
541 final int resId;
542 if (GeoHelper.isGeoUri(message.getBody())) {
543 resId = R.string.location;
544 url = message.getBody();
545 } else {
546 resId = R.string.image_url;
547 url = message.getImageParams().url.toString();
548 }
549 if (activity.copyTextToClipboard(url, resId)) {
550 Toast.makeText(activity, R.string.url_copied_to_clipboard,
551 Toast.LENGTH_SHORT).show();
552 }
553 }
554
555 private void downloadImage(Message message) {
556 activity.xmppConnectionService.getHttpConnectionManager()
557 .createNewConnection(message);
558 }
559
560 private void cancelTransmission(Message message) {
561 Downloadable downloadable = message.getDownloadable();
562 if (downloadable != null) {
563 downloadable.cancel();
564 } else {
565 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
566 }
567 }
568
569 protected void privateMessageWith(final Jid counterpart) {
570 this.mEditMessage.setText("");
571 this.conversation.setNextCounterpart(counterpart);
572 updateChatMsgHint();
573 updateSendButton();
574 }
575
576 protected void highlightInConference(String nick) {
577 String oldString = mEditMessage.getText().toString().trim();
578 if (oldString.isEmpty() || mEditMessage.getSelectionStart() == 0) {
579 mEditMessage.getText().insert(0, nick + ": ");
580 } else {
581 if (mEditMessage.getText().charAt(
582 mEditMessage.getSelectionStart() - 1) != ' ') {
583 nick = " " + nick;
584 }
585 mEditMessage.getText().insert(mEditMessage.getSelectionStart(),
586 nick + " ");
587 }
588 }
589
590 @Override
591 public void onStop() {
592 mDecryptJobRunning = false;
593 super.onStop();
594 if (this.conversation != null) {
595 final String msg = mEditMessage.getText().toString();
596 this.conversation.setNextMessage(msg);
597 updateChatState(this.conversation, msg);
598 }
599 }
600
601 private void updateChatState(final Conversation conversation, final String msg) {
602 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
603 Account.State status = conversation.getAccount().getStatus();
604 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
605 activity.xmppConnectionService.sendChatState(conversation);
606 }
607 }
608
609 public void reInit(Conversation conversation) {
610 if (conversation == null) {
611 return;
612 }
613
614 this.activity = (ConversationActivity) getActivity();
615
616 if (this.conversation != null) {
617 final String msg = mEditMessage.getText().toString();
618 this.conversation.setNextMessage(msg);
619 if (this.conversation != conversation) {
620 updateChatState(this.conversation, msg);
621 }
622 this.conversation.trim();
623 }
624
625 this.askForPassphraseIntent = null;
626 this.conversation = conversation;
627 this.mDecryptJobRunning = false;
628 this.mEncryptedMessages.clear();
629 if (this.conversation.getMode() == Conversation.MODE_MULTI) {
630 this.conversation.setNextCounterpart(null);
631 }
632 this.mEditMessage.setKeyboardListener(null);
633 this.mEditMessage.setText("");
634 this.mEditMessage.append(this.conversation.getNextMessage());
635 this.mEditMessage.setKeyboardListener(this);
636 this.messagesView.setAdapter(messageListAdapter);
637 updateMessages();
638 this.messagesLoaded = true;
639 int size = this.messageList.size();
640 if (size > 0) {
641 messagesView.setSelection(size - 1);
642 }
643 }
644
645 private OnClickListener mUnblockClickListener = new OnClickListener() {
646 @Override
647 public void onClick(final View v) {
648 v.post(new Runnable() {
649 @Override
650 public void run() {
651 v.setVisibility(View.INVISIBLE);
652 }
653 });
654 if (conversation.isDomainBlocked()) {
655 BlockContactDialog.show(activity, activity.xmppConnectionService, conversation);
656 } else {
657 activity.unblockConversation(conversation);
658 }
659 }
660 };
661
662 private OnClickListener mAddBackClickListener = new OnClickListener() {
663
664 @Override
665 public void onClick(View v) {
666 final Contact contact = conversation == null ? null : conversation.getContact();
667 if (contact != null) {
668 activity.xmppConnectionService.createContact(contact);
669 activity.switchToContactDetails(contact);
670 }
671 }
672 };
673
674 private OnClickListener mUnmuteClickListener = new OnClickListener() {
675
676 @Override
677 public void onClick(final View v) {
678 activity.unmuteConversation(conversation);
679 }
680 };
681
682 private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
683 @Override
684 public void onClick(View view) {
685 Intent intent = new Intent(activity, VerifyOTRActivity.class);
686 intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
687 intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
688 intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
689 intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
690 startActivity(intent);
691 }
692 };
693
694 private void updateSnackBar(final Conversation conversation) {
695 final Account account = conversation.getAccount();
696 final Contact contact = conversation.getContact();
697 final int mode = conversation.getMode();
698 if (conversation.isBlocked()) {
699 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
700 } else if (!contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
701 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
702 } else if (mode == Conversation.MODE_MULTI
703 && !conversation.getMucOptions().online()
704 && account.getStatus() == Account.State.ONLINE) {
705 switch (conversation.getMucOptions().getError()) {
706 case MucOptions.ERROR_NICK_IN_USE:
707 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
708 break;
709 case MucOptions.ERROR_UNKNOWN:
710 showSnackbar(R.string.conference_not_found, R.string.leave, leaveMuc);
711 break;
712 case MucOptions.ERROR_PASSWORD_REQUIRED:
713 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
714 break;
715 case MucOptions.ERROR_BANNED:
716 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
717 break;
718 case MucOptions.ERROR_MEMBERS_ONLY:
719 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
720 break;
721 case MucOptions.KICKED_FROM_ROOM:
722 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
723 break;
724 default:
725 break;
726 }
727 } else if (askForPassphraseIntent != null) {
728 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
729 } else if (mode == Conversation.MODE_SINGLE
730 && conversation.smpRequested()) {
731 showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
732 } else if (mode == Conversation.MODE_SINGLE
733 && conversation.hasValidOtrSession()
734 && (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
735 && (!conversation.isOtrFingerprintVerified())) {
736 showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
737 } else if (conversation.isMuted()) {
738 showSnackbar(R.string.notifications_disabled, R.string.enable, this.mUnmuteClickListener);
739 } else {
740 hideSnackbar();
741 }
742 }
743
744 public void updateMessages() {
745 synchronized (this.messageList) {
746 if (getView() == null) {
747 return;
748 }
749 final ConversationActivity activity = (ConversationActivity) getActivity();
750 if (this.conversation != null) {
751 updateSnackBar(this.conversation);
752 conversation.populateWithMessages(ConversationFragment.this.messageList);
753 for (final Message message : this.messageList) {
754 if (message.getEncryption() == Message.ENCRYPTION_PGP
755 && (message.getStatus() == Message.STATUS_RECEIVED || message
756 .getStatus() >= Message.STATUS_SEND)
757 && message.getDownloadable() == null) {
758 if (!mEncryptedMessages.contains(message)) {
759 mEncryptedMessages.add(message);
760 }
761 }
762 }
763 decryptNext();
764 updateStatusMessages();
765 this.messageListAdapter.notifyDataSetChanged();
766 updateChatMsgHint();
767 if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
768 activity.sendReadMarkerIfNecessary(conversation);
769 }
770 this.updateSendButton();
771 }
772 }
773 }
774
775 private void decryptNext() {
776 Message next = this.mEncryptedMessages.peek();
777 PgpEngine engine = activity.xmppConnectionService.getPgpEngine();
778
779 if (next != null && engine != null && !mDecryptJobRunning) {
780 mDecryptJobRunning = true;
781 engine.decrypt(next, new UiCallback<Message>() {
782
783 @Override
784 public void userInputRequried(PendingIntent pi, Message message) {
785 mDecryptJobRunning = false;
786 askForPassphraseIntent = pi.getIntentSender();
787 updateSnackBar(conversation);
788 }
789
790 @Override
791 public void success(Message message) {
792 mDecryptJobRunning = false;
793 try {
794 mEncryptedMessages.remove();
795 } catch (final NoSuchElementException ignored) {
796
797 }
798 askForPassphraseIntent = null;
799 activity.xmppConnectionService.updateMessage(message);
800 }
801
802 @Override
803 public void error(int error, Message message) {
804 message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
805 mDecryptJobRunning = false;
806 try {
807 mEncryptedMessages.remove();
808 } catch (final NoSuchElementException ignored) {
809
810 }
811 activity.xmppConnectionService.updateConversationUi();
812 }
813 });
814 }
815 }
816
817 private void messageSent() {
818 int size = this.messageList.size();
819 messagesView.setSelection(size - 1);
820 mEditMessage.setText("");
821 updateChatMsgHint();
822 }
823
824 enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE}
825
826 private int getSendButtonImageResource(SendButtonAction action, int status) {
827 switch (action) {
828 case TEXT:
829 switch (status) {
830 case Presences.CHAT:
831 case Presences.ONLINE:
832 return R.drawable.ic_send_text_online;
833 case Presences.AWAY:
834 return R.drawable.ic_send_text_away;
835 case Presences.XA:
836 case Presences.DND:
837 return R.drawable.ic_send_text_dnd;
838 default:
839 return R.drawable.ic_send_text_offline;
840 }
841 case TAKE_PHOTO:
842 switch (status) {
843 case Presences.CHAT:
844 case Presences.ONLINE:
845 return R.drawable.ic_send_photo_online;
846 case Presences.AWAY:
847 return R.drawable.ic_send_photo_away;
848 case Presences.XA:
849 case Presences.DND:
850 return R.drawable.ic_send_photo_dnd;
851 default:
852 return R.drawable.ic_send_photo_offline;
853 }
854 case RECORD_VOICE:
855 switch (status) {
856 case Presences.CHAT:
857 case Presences.ONLINE:
858 return R.drawable.ic_send_voice_online;
859 case Presences.AWAY:
860 return R.drawable.ic_send_voice_away;
861 case Presences.XA:
862 case Presences.DND:
863 return R.drawable.ic_send_voice_dnd;
864 default:
865 return R.drawable.ic_send_voice_offline;
866 }
867 case SEND_LOCATION:
868 switch (status) {
869 case Presences.CHAT:
870 case Presences.ONLINE:
871 return R.drawable.ic_send_location_online;
872 case Presences.AWAY:
873 return R.drawable.ic_send_location_away;
874 case Presences.XA:
875 case Presences.DND:
876 return R.drawable.ic_send_location_dnd;
877 default:
878 return R.drawable.ic_send_location_offline;
879 }
880 case CANCEL:
881 switch (status) {
882 case Presences.CHAT:
883 case Presences.ONLINE:
884 return R.drawable.ic_send_cancel_online;
885 case Presences.AWAY:
886 return R.drawable.ic_send_cancel_away;
887 case Presences.XA:
888 case Presences.DND:
889 return R.drawable.ic_send_cancel_dnd;
890 default:
891 return R.drawable.ic_send_cancel_offline;
892 }
893 case CHOOSE_PICTURE:
894 switch (status) {
895 case Presences.CHAT:
896 case Presences.ONLINE:
897 return R.drawable.ic_send_picture_online;
898 case Presences.AWAY:
899 return R.drawable.ic_send_picture_away;
900 case Presences.XA:
901 case Presences.DND:
902 return R.drawable.ic_send_picture_dnd;
903 default:
904 return R.drawable.ic_send_picture_offline;
905 }
906 }
907 return R.drawable.ic_send_text_offline;
908 }
909
910 public void updateSendButton() {
911 final Conversation c = this.conversation;
912 final SendButtonAction action;
913 final int status;
914 final boolean empty = this.mEditMessage == null || this.mEditMessage.getText().length() == 0;
915 if (c.getMode() == Conversation.MODE_MULTI) {
916 if (empty && c.getNextCounterpart() != null) {
917 action = SendButtonAction.CANCEL;
918 } else {
919 action = SendButtonAction.TEXT;
920 }
921 } else {
922 if (empty) {
923 String setting = activity.getPreferences().getString("quick_action","recent");
924 if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
925 setting = "location";
926 } else if (setting.equals("recent")) {
927 setting = activity.getPreferences().getString("recently_used_quick_action","text");
928 }
929 switch (setting) {
930 case "photo":
931 action = SendButtonAction.TAKE_PHOTO;
932 break;
933 case "location":
934 action = SendButtonAction.SEND_LOCATION;
935 break;
936 case "voice":
937 action = SendButtonAction.RECORD_VOICE;
938 break;
939 case "picture":
940 action = SendButtonAction.CHOOSE_PICTURE;
941 break;
942 default:
943 action = SendButtonAction.TEXT;
944 break;
945 }
946 } else {
947 action = SendButtonAction.TEXT;
948 }
949 }
950 if (activity.useSendButtonToIndicateStatus() && c != null
951 && c.getAccount().getStatus() == Account.State.ONLINE) {
952 if (c.getMode() == Conversation.MODE_SINGLE) {
953 status = c.getContact().getMostAvailableStatus();
954 } else {
955 status = c.getMucOptions().online() ? Presences.ONLINE : Presences.OFFLINE;
956 }
957 } else {
958 status = Presences.OFFLINE;
959 }
960 this.mSendButton.setTag(action);
961 this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
962 }
963
964 protected void updateStatusMessages() {
965 synchronized (this.messageList) {
966 if (conversation.getMode() == Conversation.MODE_SINGLE) {
967 ChatState state = conversation.getIncomingChatState();
968 if (state == ChatState.COMPOSING) {
969 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
970 } else if (state == ChatState.PAUSED) {
971 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
972 } else {
973 for (int i = this.messageList.size() - 1; i >= 0; --i) {
974 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
975 return;
976 } else {
977 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
978 this.messageList.add(i + 1,
979 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
980 return;
981 }
982 }
983 }
984 }
985 }
986 }
987 }
988
989 protected void showSnackbar(final int message, final int action,
990 final OnClickListener clickListener) {
991 snackbar.setVisibility(View.VISIBLE);
992 snackbar.setOnClickListener(null);
993 snackbarMessage.setText(message);
994 snackbarMessage.setOnClickListener(null);
995 snackbarAction.setVisibility(View.VISIBLE);
996 snackbarAction.setText(action);
997 snackbarAction.setOnClickListener(clickListener);
998 }
999
1000 protected void hideSnackbar() {
1001 snackbar.setVisibility(View.GONE);
1002 }
1003
1004 protected void sendPlainTextMessage(Message message) {
1005 ConversationActivity activity = (ConversationActivity) getActivity();
1006 activity.xmppConnectionService.sendMessage(message);
1007 messageSent();
1008 }
1009
1010 protected void sendPgpMessage(final Message message) {
1011 final ConversationActivity activity = (ConversationActivity) getActivity();
1012 final XmppConnectionService xmppService = activity.xmppConnectionService;
1013 final Contact contact = message.getConversation().getContact();
1014 if (activity.hasPgp()) {
1015 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1016 if (contact.getPgpKeyId() != 0) {
1017 xmppService.getPgpEngine().hasKey(contact,
1018 new UiCallback<Contact>() {
1019
1020 @Override
1021 public void userInputRequried(PendingIntent pi,
1022 Contact contact) {
1023 activity.runIntent(
1024 pi,
1025 ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1026 }
1027
1028 @Override
1029 public void success(Contact contact) {
1030 messageSent();
1031 activity.encryptTextMessage(message);
1032 }
1033
1034 @Override
1035 public void error(int error, Contact contact) {
1036
1037 }
1038 });
1039
1040 } else {
1041 showNoPGPKeyDialog(false,
1042 new DialogInterface.OnClickListener() {
1043
1044 @Override
1045 public void onClick(DialogInterface dialog,
1046 int which) {
1047 conversation
1048 .setNextEncryption(Message.ENCRYPTION_NONE);
1049 xmppService.databaseBackend
1050 .updateConversation(conversation);
1051 message.setEncryption(Message.ENCRYPTION_NONE);
1052 xmppService.sendMessage(message);
1053 messageSent();
1054 }
1055 });
1056 }
1057 } else {
1058 if (conversation.getMucOptions().pgpKeysInUse()) {
1059 if (!conversation.getMucOptions().everybodyHasKeys()) {
1060 Toast warning = Toast
1061 .makeText(getActivity(),
1062 R.string.missing_public_keys,
1063 Toast.LENGTH_LONG);
1064 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1065 warning.show();
1066 }
1067 activity.encryptTextMessage(message);
1068 messageSent();
1069 } else {
1070 showNoPGPKeyDialog(true,
1071 new DialogInterface.OnClickListener() {
1072
1073 @Override
1074 public void onClick(DialogInterface dialog,
1075 int which) {
1076 conversation
1077 .setNextEncryption(Message.ENCRYPTION_NONE);
1078 message.setEncryption(Message.ENCRYPTION_NONE);
1079 xmppService.databaseBackend
1080 .updateConversation(conversation);
1081 xmppService.sendMessage(message);
1082 messageSent();
1083 }
1084 });
1085 }
1086 }
1087 } else {
1088 activity.showInstallPgpDialog();
1089 }
1090 }
1091
1092 public void showNoPGPKeyDialog(boolean plural,
1093 DialogInterface.OnClickListener listener) {
1094 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1095 builder.setIconAttribute(android.R.attr.alertDialogIcon);
1096 if (plural) {
1097 builder.setTitle(getString(R.string.no_pgp_keys));
1098 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1099 } else {
1100 builder.setTitle(getString(R.string.no_pgp_key));
1101 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1102 }
1103 builder.setNegativeButton(getString(R.string.cancel), null);
1104 builder.setPositiveButton(getString(R.string.send_unencrypted),
1105 listener);
1106 builder.create().show();
1107 }
1108
1109 protected void sendOtrMessage(final Message message) {
1110 final ConversationActivity activity = (ConversationActivity) getActivity();
1111 final XmppConnectionService xmppService = activity.xmppConnectionService;
1112 activity.selectPresence(message.getConversation(),
1113 new OnPresenceSelected() {
1114
1115 @Override
1116 public void onPresenceSelected() {
1117 message.setCounterpart(conversation.getNextCounterpart());
1118 xmppService.sendMessage(message);
1119 messageSent();
1120 }
1121 });
1122 }
1123
1124 public void appendText(String text) {
1125 if (text == null) {
1126 return;
1127 }
1128 String previous = this.mEditMessage.getText().toString();
1129 if (previous.length() != 0 && !previous.endsWith(" ")) {
1130 text = " " + text;
1131 }
1132 this.mEditMessage.append(text);
1133 }
1134
1135 @Override
1136 public boolean onEnterPressed() {
1137 if (activity.enterIsSend()) {
1138 sendMessage();
1139 return true;
1140 } else {
1141 return false;
1142 }
1143 }
1144
1145 @Override
1146 public void onTypingStarted() {
1147 Account.State status = conversation.getAccount().getStatus();
1148 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1149 activity.xmppConnectionService.sendChatState(conversation);
1150 }
1151 updateSendButton();
1152 }
1153
1154 @Override
1155 public void onTypingStopped() {
1156 Account.State status = conversation.getAccount().getStatus();
1157 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1158 activity.xmppConnectionService.sendChatState(conversation);
1159 }
1160 }
1161
1162 @Override
1163 public void onTextDeleted() {
1164 Account.State status = conversation.getAccount().getStatus();
1165 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1166 activity.xmppConnectionService.sendChatState(conversation);
1167 }
1168 updateSendButton();
1169 }
1170
1171}