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.hasFileOnRemoteHost() && !GeoHelper.isGeoUri(m.getBody())) {
456 copyUrl.setVisible(false);
457 }
458 if (m.getType() != Message.TYPE_TEXT
459 || m.getDownloadable() != null
460 || m.treatAsDownloadable() == Message.Decision.NEVER) {
461 downloadImage.setVisible(false);
462 }
463 if (!((m.getDownloadable() != null && !(m.getDownloadable() instanceof DownloadablePlaceholder))
464 || (m.isFileOrImage() && (m.getStatus() == Message.STATUS_WAITING
465 || m.getStatus() == Message.STATUS_OFFERED)))) {
466 cancelTransmission.setVisible(false);
467 }
468 }
469 }
470
471 @Override
472 public boolean onContextItemSelected(MenuItem item) {
473 switch (item.getItemId()) {
474 case R.id.share_with:
475 shareWith(selectedMessage);
476 return true;
477 case R.id.copy_text:
478 copyText(selectedMessage);
479 return true;
480 case R.id.send_again:
481 resendMessage(selectedMessage);
482 return true;
483 case R.id.copy_url:
484 copyUrl(selectedMessage);
485 return true;
486 case R.id.download_image:
487 downloadImage(selectedMessage);
488 return true;
489 case R.id.cancel_transmission:
490 cancelTransmission(selectedMessage);
491 return true;
492 default:
493 return super.onContextItemSelected(item);
494 }
495 }
496
497 private void shareWith(Message message) {
498 Intent shareIntent = new Intent();
499 shareIntent.setAction(Intent.ACTION_SEND);
500 if (GeoHelper.isGeoUri(message.getBody())) {
501 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
502 shareIntent.setType("text/plain");
503 } else {
504 shareIntent.putExtra(Intent.EXTRA_STREAM,
505 activity.xmppConnectionService.getFileBackend()
506 .getJingleFileUri(message));
507 shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
508 String mime = message.getMimeType();
509 if (mime == null) {
510 mime = "image/webp";
511 }
512 shareIntent.setType(mime);
513 }
514 activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
515 }
516
517 private void copyText(Message message) {
518 if (activity.copyTextToClipboard(message.getMergedBody(),
519 R.string.message_text)) {
520 Toast.makeText(activity, R.string.message_copied_to_clipboard,
521 Toast.LENGTH_SHORT).show();
522 }
523 }
524
525 private void resendMessage(Message message) {
526 if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
527 DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
528 if (!file.exists()) {
529 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
530 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
531 return;
532 }
533 }
534 activity.xmppConnectionService.resendFailedMessages(message);
535 }
536
537 private void copyUrl(Message message) {
538 final String url;
539 final int resId;
540 if (GeoHelper.isGeoUri(message.getBody())) {
541 resId = R.string.location;
542 url = message.getBody();
543 } else {
544 resId = R.string.image_url;
545 url = message.getFileParams().url.toString();
546 }
547 if (activity.copyTextToClipboard(url, resId)) {
548 Toast.makeText(activity, R.string.url_copied_to_clipboard,
549 Toast.LENGTH_SHORT).show();
550 }
551 }
552
553 private void downloadImage(Message message) {
554 activity.xmppConnectionService.getHttpConnectionManager()
555 .createNewConnection(message);
556 }
557
558 private void cancelTransmission(Message message) {
559 Downloadable downloadable = message.getDownloadable();
560 if (downloadable != null) {
561 downloadable.cancel();
562 } else {
563 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
564 }
565 }
566
567 protected void privateMessageWith(final Jid counterpart) {
568 this.mEditMessage.setText("");
569 this.conversation.setNextCounterpart(counterpart);
570 updateChatMsgHint();
571 updateSendButton();
572 }
573
574 protected void highlightInConference(String nick) {
575 String oldString = mEditMessage.getText().toString().trim();
576 if (oldString.isEmpty() || mEditMessage.getSelectionStart() == 0) {
577 mEditMessage.getText().insert(0, nick + ": ");
578 } else {
579 if (mEditMessage.getText().charAt(
580 mEditMessage.getSelectionStart() - 1) != ' ') {
581 nick = " " + nick;
582 }
583 mEditMessage.getText().insert(mEditMessage.getSelectionStart(),
584 nick + " ");
585 }
586 }
587
588 @Override
589 public void onStop() {
590 mDecryptJobRunning = false;
591 super.onStop();
592 if (this.conversation != null) {
593 final String msg = mEditMessage.getText().toString();
594 this.conversation.setNextMessage(msg);
595 updateChatState(this.conversation, msg);
596 }
597 }
598
599 private void updateChatState(final Conversation conversation, final String msg) {
600 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
601 Account.State status = conversation.getAccount().getStatus();
602 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
603 activity.xmppConnectionService.sendChatState(conversation);
604 }
605 }
606
607 public void reInit(Conversation conversation) {
608 if (conversation == null) {
609 return;
610 }
611
612 this.activity = (ConversationActivity) getActivity();
613
614 if (this.conversation != null) {
615 final String msg = mEditMessage.getText().toString();
616 this.conversation.setNextMessage(msg);
617 if (this.conversation != conversation) {
618 updateChatState(this.conversation, msg);
619 }
620 this.conversation.trim();
621 }
622
623 this.askForPassphraseIntent = null;
624 this.conversation = conversation;
625 this.mDecryptJobRunning = false;
626 this.mEncryptedMessages.clear();
627 if (this.conversation.getMode() == Conversation.MODE_MULTI) {
628 this.conversation.setNextCounterpart(null);
629 }
630 this.mEditMessage.setKeyboardListener(null);
631 this.mEditMessage.setText("");
632 this.mEditMessage.append(this.conversation.getNextMessage());
633 this.mEditMessage.setKeyboardListener(this);
634 this.messagesView.setAdapter(messageListAdapter);
635 updateMessages();
636 this.messagesLoaded = true;
637 int size = this.messageList.size();
638 if (size > 0) {
639 messagesView.setSelection(size - 1);
640 }
641 }
642
643 private OnClickListener mUnblockClickListener = new OnClickListener() {
644 @Override
645 public void onClick(final View v) {
646 v.post(new Runnable() {
647 @Override
648 public void run() {
649 v.setVisibility(View.INVISIBLE);
650 }
651 });
652 if (conversation.isDomainBlocked()) {
653 BlockContactDialog.show(activity, activity.xmppConnectionService, conversation);
654 } else {
655 activity.unblockConversation(conversation);
656 }
657 }
658 };
659
660 private OnClickListener mAddBackClickListener = new OnClickListener() {
661
662 @Override
663 public void onClick(View v) {
664 final Contact contact = conversation == null ? null : conversation.getContact();
665 if (contact != null) {
666 activity.xmppConnectionService.createContact(contact);
667 activity.switchToContactDetails(contact);
668 }
669 }
670 };
671
672 private OnClickListener mUnmuteClickListener = new OnClickListener() {
673
674 @Override
675 public void onClick(final View v) {
676 activity.unmuteConversation(conversation);
677 }
678 };
679
680 private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
681 @Override
682 public void onClick(View view) {
683 Intent intent = new Intent(activity, VerifyOTRActivity.class);
684 intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
685 intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
686 intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
687 intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
688 startActivity(intent);
689 }
690 };
691
692 private void updateSnackBar(final Conversation conversation) {
693 final Account account = conversation.getAccount();
694 final Contact contact = conversation.getContact();
695 final int mode = conversation.getMode();
696 if (conversation.isBlocked()) {
697 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
698 } else if (!contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
699 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
700 } else if (mode == Conversation.MODE_MULTI
701 && !conversation.getMucOptions().online()
702 && account.getStatus() == Account.State.ONLINE) {
703 switch (conversation.getMucOptions().getError()) {
704 case MucOptions.ERROR_NICK_IN_USE:
705 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
706 break;
707 case MucOptions.ERROR_UNKNOWN:
708 showSnackbar(R.string.conference_not_found, R.string.leave, leaveMuc);
709 break;
710 case MucOptions.ERROR_PASSWORD_REQUIRED:
711 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
712 break;
713 case MucOptions.ERROR_BANNED:
714 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
715 break;
716 case MucOptions.ERROR_MEMBERS_ONLY:
717 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
718 break;
719 case MucOptions.KICKED_FROM_ROOM:
720 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
721 break;
722 default:
723 break;
724 }
725 } else if (askForPassphraseIntent != null) {
726 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
727 } else if (mode == Conversation.MODE_SINGLE
728 && conversation.smpRequested()) {
729 showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
730 } else if (mode == Conversation.MODE_SINGLE
731 && conversation.hasValidOtrSession()
732 && (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
733 && (!conversation.isOtrFingerprintVerified())) {
734 showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
735 } else if (conversation.isMuted()) {
736 showSnackbar(R.string.notifications_disabled, R.string.enable, this.mUnmuteClickListener);
737 } else {
738 hideSnackbar();
739 }
740 }
741
742 public void updateMessages() {
743 synchronized (this.messageList) {
744 if (getView() == null) {
745 return;
746 }
747 final ConversationActivity activity = (ConversationActivity) getActivity();
748 if (this.conversation != null) {
749 updateSnackBar(this.conversation);
750 conversation.populateWithMessages(ConversationFragment.this.messageList);
751 for (final Message message : this.messageList) {
752 if (message.getEncryption() == Message.ENCRYPTION_PGP
753 && (message.getStatus() == Message.STATUS_RECEIVED || message
754 .getStatus() >= Message.STATUS_SEND)
755 && message.getDownloadable() == null) {
756 if (!mEncryptedMessages.contains(message)) {
757 mEncryptedMessages.add(message);
758 }
759 }
760 }
761 decryptNext();
762 updateStatusMessages();
763 this.messageListAdapter.notifyDataSetChanged();
764 updateChatMsgHint();
765 if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
766 activity.sendReadMarkerIfNecessary(conversation);
767 }
768 this.updateSendButton();
769 }
770 }
771 }
772
773 private void decryptNext() {
774 Message next = this.mEncryptedMessages.peek();
775 PgpEngine engine = activity.xmppConnectionService.getPgpEngine();
776
777 if (next != null && engine != null && !mDecryptJobRunning) {
778 mDecryptJobRunning = true;
779 engine.decrypt(next, new UiCallback<Message>() {
780
781 @Override
782 public void userInputRequried(PendingIntent pi, Message message) {
783 mDecryptJobRunning = false;
784 askForPassphraseIntent = pi.getIntentSender();
785 updateSnackBar(conversation);
786 }
787
788 @Override
789 public void success(Message message) {
790 mDecryptJobRunning = false;
791 try {
792 mEncryptedMessages.remove();
793 } catch (final NoSuchElementException ignored) {
794
795 }
796 askForPassphraseIntent = null;
797 activity.xmppConnectionService.updateMessage(message);
798 }
799
800 @Override
801 public void error(int error, Message message) {
802 message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
803 mDecryptJobRunning = false;
804 try {
805 mEncryptedMessages.remove();
806 } catch (final NoSuchElementException ignored) {
807
808 }
809 activity.xmppConnectionService.updateConversationUi();
810 }
811 });
812 }
813 }
814
815 private void messageSent() {
816 int size = this.messageList.size();
817 messagesView.setSelection(size - 1);
818 mEditMessage.setText("");
819 updateChatMsgHint();
820 }
821
822 enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE}
823
824 private int getSendButtonImageResource(SendButtonAction action, int status) {
825 switch (action) {
826 case TEXT:
827 switch (status) {
828 case Presences.CHAT:
829 case Presences.ONLINE:
830 return R.drawable.ic_send_text_online;
831 case Presences.AWAY:
832 return R.drawable.ic_send_text_away;
833 case Presences.XA:
834 case Presences.DND:
835 return R.drawable.ic_send_text_dnd;
836 default:
837 return R.drawable.ic_send_text_offline;
838 }
839 case TAKE_PHOTO:
840 switch (status) {
841 case Presences.CHAT:
842 case Presences.ONLINE:
843 return R.drawable.ic_send_photo_online;
844 case Presences.AWAY:
845 return R.drawable.ic_send_photo_away;
846 case Presences.XA:
847 case Presences.DND:
848 return R.drawable.ic_send_photo_dnd;
849 default:
850 return R.drawable.ic_send_photo_offline;
851 }
852 case RECORD_VOICE:
853 switch (status) {
854 case Presences.CHAT:
855 case Presences.ONLINE:
856 return R.drawable.ic_send_voice_online;
857 case Presences.AWAY:
858 return R.drawable.ic_send_voice_away;
859 case Presences.XA:
860 case Presences.DND:
861 return R.drawable.ic_send_voice_dnd;
862 default:
863 return R.drawable.ic_send_voice_offline;
864 }
865 case SEND_LOCATION:
866 switch (status) {
867 case Presences.CHAT:
868 case Presences.ONLINE:
869 return R.drawable.ic_send_location_online;
870 case Presences.AWAY:
871 return R.drawable.ic_send_location_away;
872 case Presences.XA:
873 case Presences.DND:
874 return R.drawable.ic_send_location_dnd;
875 default:
876 return R.drawable.ic_send_location_offline;
877 }
878 case CANCEL:
879 switch (status) {
880 case Presences.CHAT:
881 case Presences.ONLINE:
882 return R.drawable.ic_send_cancel_online;
883 case Presences.AWAY:
884 return R.drawable.ic_send_cancel_away;
885 case Presences.XA:
886 case Presences.DND:
887 return R.drawable.ic_send_cancel_dnd;
888 default:
889 return R.drawable.ic_send_cancel_offline;
890 }
891 case CHOOSE_PICTURE:
892 switch (status) {
893 case Presences.CHAT:
894 case Presences.ONLINE:
895 return R.drawable.ic_send_picture_online;
896 case Presences.AWAY:
897 return R.drawable.ic_send_picture_away;
898 case Presences.XA:
899 case Presences.DND:
900 return R.drawable.ic_send_picture_dnd;
901 default:
902 return R.drawable.ic_send_picture_offline;
903 }
904 }
905 return R.drawable.ic_send_text_offline;
906 }
907
908 public void updateSendButton() {
909 final Conversation c = this.conversation;
910 final SendButtonAction action;
911 final int status;
912 final boolean empty = this.mEditMessage == null || this.mEditMessage.getText().length() == 0;
913 final boolean conference = c.getMode() == Conversation.MODE_MULTI;
914 if (conference && !c.getAccount().httpUploadAvailable()) {
915 if (empty && c.getNextCounterpart() != null) {
916 action = SendButtonAction.CANCEL;
917 } else {
918 action = SendButtonAction.TEXT;
919 }
920 } else {
921 if (empty) {
922 if (conference && c.getNextCounterpart() != null) {
923 action = SendButtonAction.CANCEL;
924 } else {
925 String setting = activity.getPreferences().getString("quick_action", "recent");
926 if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
927 setting = "location";
928 } else if (setting.equals("recent")) {
929 setting = activity.getPreferences().getString("recently_used_quick_action", "text");
930 }
931 switch (setting) {
932 case "photo":
933 action = SendButtonAction.TAKE_PHOTO;
934 break;
935 case "location":
936 action = SendButtonAction.SEND_LOCATION;
937 break;
938 case "voice":
939 action = SendButtonAction.RECORD_VOICE;
940 break;
941 case "picture":
942 action = SendButtonAction.CHOOSE_PICTURE;
943 break;
944 default:
945 action = SendButtonAction.TEXT;
946 break;
947 }
948 }
949 } else {
950 action = SendButtonAction.TEXT;
951 }
952 }
953 if (activity.useSendButtonToIndicateStatus() && c != null
954 && c.getAccount().getStatus() == Account.State.ONLINE) {
955 if (c.getMode() == Conversation.MODE_SINGLE) {
956 status = c.getContact().getMostAvailableStatus();
957 } else {
958 status = c.getMucOptions().online() ? Presences.ONLINE : Presences.OFFLINE;
959 }
960 } else {
961 status = Presences.OFFLINE;
962 }
963 this.mSendButton.setTag(action);
964 this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
965 }
966
967 protected void updateStatusMessages() {
968 synchronized (this.messageList) {
969 if (conversation.getMode() == Conversation.MODE_SINGLE) {
970 ChatState state = conversation.getIncomingChatState();
971 if (state == ChatState.COMPOSING) {
972 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
973 } else if (state == ChatState.PAUSED) {
974 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
975 } else {
976 for (int i = this.messageList.size() - 1; i >= 0; --i) {
977 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
978 return;
979 } else {
980 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
981 this.messageList.add(i + 1,
982 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
983 return;
984 }
985 }
986 }
987 }
988 }
989 }
990 }
991
992 protected void showSnackbar(final int message, final int action,
993 final OnClickListener clickListener) {
994 snackbar.setVisibility(View.VISIBLE);
995 snackbar.setOnClickListener(null);
996 snackbarMessage.setText(message);
997 snackbarMessage.setOnClickListener(null);
998 snackbarAction.setVisibility(View.VISIBLE);
999 snackbarAction.setText(action);
1000 snackbarAction.setOnClickListener(clickListener);
1001 }
1002
1003 protected void hideSnackbar() {
1004 snackbar.setVisibility(View.GONE);
1005 }
1006
1007 protected void sendPlainTextMessage(Message message) {
1008 ConversationActivity activity = (ConversationActivity) getActivity();
1009 activity.xmppConnectionService.sendMessage(message);
1010 messageSent();
1011 }
1012
1013 protected void sendPgpMessage(final Message message) {
1014 final ConversationActivity activity = (ConversationActivity) getActivity();
1015 final XmppConnectionService xmppService = activity.xmppConnectionService;
1016 final Contact contact = message.getConversation().getContact();
1017 if (activity.hasPgp()) {
1018 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1019 if (contact.getPgpKeyId() != 0) {
1020 xmppService.getPgpEngine().hasKey(contact,
1021 new UiCallback<Contact>() {
1022
1023 @Override
1024 public void userInputRequried(PendingIntent pi,
1025 Contact contact) {
1026 activity.runIntent(
1027 pi,
1028 ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1029 }
1030
1031 @Override
1032 public void success(Contact contact) {
1033 messageSent();
1034 activity.encryptTextMessage(message);
1035 }
1036
1037 @Override
1038 public void error(int error, Contact contact) {
1039
1040 }
1041 });
1042
1043 } else {
1044 showNoPGPKeyDialog(false,
1045 new DialogInterface.OnClickListener() {
1046
1047 @Override
1048 public void onClick(DialogInterface dialog,
1049 int which) {
1050 conversation
1051 .setNextEncryption(Message.ENCRYPTION_NONE);
1052 xmppService.databaseBackend
1053 .updateConversation(conversation);
1054 message.setEncryption(Message.ENCRYPTION_NONE);
1055 xmppService.sendMessage(message);
1056 messageSent();
1057 }
1058 });
1059 }
1060 } else {
1061 if (conversation.getMucOptions().pgpKeysInUse()) {
1062 if (!conversation.getMucOptions().everybodyHasKeys()) {
1063 Toast warning = Toast
1064 .makeText(getActivity(),
1065 R.string.missing_public_keys,
1066 Toast.LENGTH_LONG);
1067 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1068 warning.show();
1069 }
1070 activity.encryptTextMessage(message);
1071 messageSent();
1072 } else {
1073 showNoPGPKeyDialog(true,
1074 new DialogInterface.OnClickListener() {
1075
1076 @Override
1077 public void onClick(DialogInterface dialog,
1078 int which) {
1079 conversation
1080 .setNextEncryption(Message.ENCRYPTION_NONE);
1081 message.setEncryption(Message.ENCRYPTION_NONE);
1082 xmppService.databaseBackend
1083 .updateConversation(conversation);
1084 xmppService.sendMessage(message);
1085 messageSent();
1086 }
1087 });
1088 }
1089 }
1090 } else {
1091 activity.showInstallPgpDialog();
1092 }
1093 }
1094
1095 public void showNoPGPKeyDialog(boolean plural,
1096 DialogInterface.OnClickListener listener) {
1097 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1098 builder.setIconAttribute(android.R.attr.alertDialogIcon);
1099 if (plural) {
1100 builder.setTitle(getString(R.string.no_pgp_keys));
1101 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1102 } else {
1103 builder.setTitle(getString(R.string.no_pgp_key));
1104 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1105 }
1106 builder.setNegativeButton(getString(R.string.cancel), null);
1107 builder.setPositiveButton(getString(R.string.send_unencrypted),
1108 listener);
1109 builder.create().show();
1110 }
1111
1112 protected void sendOtrMessage(final Message message) {
1113 final ConversationActivity activity = (ConversationActivity) getActivity();
1114 final XmppConnectionService xmppService = activity.xmppConnectionService;
1115 activity.selectPresence(message.getConversation(),
1116 new OnPresenceSelected() {
1117
1118 @Override
1119 public void onPresenceSelected() {
1120 message.setCounterpart(conversation.getNextCounterpart());
1121 xmppService.sendMessage(message);
1122 messageSent();
1123 }
1124 });
1125 }
1126
1127 public void appendText(String text) {
1128 if (text == null) {
1129 return;
1130 }
1131 String previous = this.mEditMessage.getText().toString();
1132 if (previous.length() != 0 && !previous.endsWith(" ")) {
1133 text = " " + text;
1134 }
1135 this.mEditMessage.append(text);
1136 }
1137
1138 @Override
1139 public boolean onEnterPressed() {
1140 if (activity.enterIsSend()) {
1141 sendMessage();
1142 return true;
1143 } else {
1144 return false;
1145 }
1146 }
1147
1148 @Override
1149 public void onTypingStarted() {
1150 Account.State status = conversation.getAccount().getStatus();
1151 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1152 activity.xmppConnectionService.sendChatState(conversation);
1153 }
1154 updateSendButton();
1155 }
1156
1157 @Override
1158 public void onTypingStopped() {
1159 Account.State status = conversation.getAccount().getStatus();
1160 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1161 activity.xmppConnectionService.sendChatState(conversation);
1162 }
1163 }
1164
1165 @Override
1166 public void onTextDeleted() {
1167 Account.State status = conversation.getAccount().getStatus();
1168 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1169 activity.xmppConnectionService.sendChatState(conversation);
1170 }
1171 updateSendButton();
1172 }
1173
1174}