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