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