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