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