1package eu.siacs.conversations.ui;
2
3import java.util.ArrayList;
4import java.util.HashMap;
5import java.util.Hashtable;
6import java.util.LinkedList;
7import java.util.List;
8import java.util.Set;
9
10import net.java.otr4j.session.SessionStatus;
11
12import eu.siacs.conversations.R;
13import eu.siacs.conversations.crypto.PgpEngine.OpenPgpException;
14import eu.siacs.conversations.crypto.PgpEngine.UserInputRequiredException;
15import eu.siacs.conversations.entities.Contact;
16import eu.siacs.conversations.entities.Conversation;
17import eu.siacs.conversations.entities.Message;
18import eu.siacs.conversations.entities.MucOptions;
19import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
20import eu.siacs.conversations.services.XmppConnectionService;
21import eu.siacs.conversations.utils.UIHelper;
22import android.app.AlertDialog;
23import android.app.Fragment;
24import android.content.Context;
25import android.content.DialogInterface;
26import android.content.Intent;
27import android.content.IntentSender;
28import android.content.SharedPreferences;
29import android.content.IntentSender.SendIntentException;
30import android.graphics.Bitmap;
31import android.graphics.Typeface;
32import android.os.AsyncTask;
33import android.os.Bundle;
34import android.preference.PreferenceManager;
35import android.util.Log;
36import android.view.LayoutInflater;
37import android.view.View;
38import android.view.View.OnClickListener;
39import android.view.ViewGroup;
40import android.widget.ArrayAdapter;
41import android.widget.EditText;
42import android.widget.LinearLayout;
43import android.widget.ListView;
44import android.widget.ImageButton;
45import android.widget.ImageView;
46import android.widget.TextView;
47import android.widget.Toast;
48
49public class ConversationFragment extends Fragment {
50
51 protected Conversation conversation;
52 protected ListView messagesView;
53 protected LayoutInflater inflater;
54 protected List<Message> messageList = new ArrayList<Message>();
55 protected ArrayAdapter<Message> messageListAdapter;
56 protected Contact contact;
57 protected BitmapCache mBitmapCache = new BitmapCache();
58
59 protected String queuedPqpMessage = null;
60
61 private EditText chatMsg;
62 private String pastedText = null;
63
64 protected Bitmap selfBitmap;
65
66 private boolean useSubject = true;
67
68 private IntentSender askForPassphraseIntent = null;
69
70 private OnClickListener sendMsgListener = new OnClickListener() {
71
72 @Override
73 public void onClick(View v) {
74 if (chatMsg.getText().length() < 1)
75 return;
76 Message message = new Message(conversation, chatMsg.getText()
77 .toString(), conversation.nextMessageEncryption);
78 if (conversation.nextMessageEncryption == Message.ENCRYPTION_OTR) {
79 sendOtrMessage(message);
80 } else if (conversation.nextMessageEncryption == Message.ENCRYPTION_PGP) {
81 sendPgpMessage(message);
82 } else {
83 sendPlainTextMessage(message);
84 }
85 }
86 };
87 protected OnClickListener clickToDecryptListener = new OnClickListener() {
88
89 @Override
90 public void onClick(View v) {
91 Log.d("gultsch", "clicked to decrypt");
92 if (askForPassphraseIntent != null) {
93 try {
94 getActivity().startIntentSenderForResult(
95 askForPassphraseIntent,
96 ConversationActivity.REQUEST_DECRYPT_PGP, null, 0,
97 0, 0);
98 } catch (SendIntentException e) {
99 Log.d("gultsch", "couldnt fire intent");
100 }
101 }
102 }
103 };
104
105 private LinearLayout pgpInfo;
106 private LinearLayout mucError;
107 private TextView mucErrorText;
108 private OnClickListener clickToMuc = new OnClickListener() {
109
110 @Override
111 public void onClick(View v) {
112 Intent intent = new Intent(getActivity(), MucDetailsActivity.class);
113 intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC);
114 intent.putExtra("uuid", conversation.getUuid());
115 startActivity(intent);
116 }
117 };
118
119 public void hidePgpPassphraseBox() {
120 pgpInfo.setVisibility(View.GONE);
121 }
122
123 public void updateChatMsgHint() {
124 if (conversation.getMode() == Conversation.MODE_MULTI) {
125 chatMsg.setHint("Send message to conference");
126 } else {
127 switch (conversation.nextMessageEncryption) {
128 case Message.ENCRYPTION_NONE:
129 chatMsg.setHint("Send plain text message");
130 break;
131 case Message.ENCRYPTION_OTR:
132 chatMsg.setHint("Send OTR encrypted message");
133 break;
134 case Message.ENCRYPTION_PGP:
135 chatMsg.setHint("Send openPGP encryted messeage");
136 break;
137 case Message.ENCRYPTION_DECRYPTED:
138 chatMsg.setHint("Send openPGP encryted messeage");
139 break;
140 default:
141 break;
142 }
143 }
144 }
145
146 @Override
147 public View onCreateView(final LayoutInflater inflater,
148 ViewGroup container, Bundle savedInstanceState) {
149
150 this.inflater = inflater;
151
152 final View view = inflater.inflate(R.layout.fragment_conversation,
153 container, false);
154 chatMsg = (EditText) view.findViewById(R.id.textinput);
155
156 if (pastedText!=null) {
157 chatMsg.setText(pastedText);
158 }
159
160 ImageButton sendButton = (ImageButton) view
161 .findViewById(R.id.textSendButton);
162 sendButton.setOnClickListener(this.sendMsgListener);
163
164 pgpInfo = (LinearLayout) view.findViewById(R.id.pgp_keyentry);
165 pgpInfo.setOnClickListener(clickToDecryptListener);
166 mucError = (LinearLayout) view.findViewById(R.id.muc_error);
167 mucError.setOnClickListener(clickToMuc);
168 mucErrorText = (TextView) view.findViewById(R.id.muc_error_msg);
169
170 messagesView = (ListView) view.findViewById(R.id.messages_view);
171
172 messageListAdapter = new ArrayAdapter<Message>(this.getActivity()
173 .getApplicationContext(), R.layout.message_sent,
174 this.messageList) {
175
176 private static final int SENT = 0;
177 private static final int RECIEVED = 1;
178 private static final int ERROR = 2;
179
180 @Override
181 public int getViewTypeCount() {
182 return 3;
183 }
184
185 @Override
186 public int getItemViewType(int position) {
187 if (getItem(position).getStatus() == Message.STATUS_RECIEVED) {
188 return RECIEVED;
189 } else if (getItem(position).getStatus() == Message.STATUS_ERROR) {
190 return ERROR;
191 } else {
192 return SENT;
193 }
194 }
195
196 @Override
197 public View getView(int position, View view, ViewGroup parent) {
198 Message item = getItem(position);
199 int type = getItemViewType(position);
200 ViewHolder viewHolder;
201 if (view == null) {
202 viewHolder = new ViewHolder();
203 switch (type) {
204 case SENT:
205 view = (View) inflater.inflate(R.layout.message_sent,
206 null);
207 viewHolder.imageView = (ImageView) view
208 .findViewById(R.id.message_photo);
209 viewHolder.imageView.setImageBitmap(selfBitmap);
210 viewHolder.indicator = (ImageView) view.findViewById(R.id.security_indicator);
211 break;
212 case RECIEVED:
213 view = (View) inflater.inflate(
214 R.layout.message_recieved, null);
215 viewHolder.imageView = (ImageView) view
216 .findViewById(R.id.message_photo);
217 viewHolder.indicator = (ImageView) view.findViewById(R.id.security_indicator);
218 if (item.getConversation().getMode() == Conversation.MODE_SINGLE) {
219
220 viewHolder.imageView.setImageBitmap(mBitmapCache
221 .get(item.getConversation().getName(useSubject), item
222 .getConversation().getContact(),
223 getActivity()
224 .getApplicationContext()));
225
226 }
227 break;
228 case ERROR:
229 view = (View) inflater.inflate(R.layout.message_error,
230 null);
231 viewHolder.imageView = (ImageView) view
232 .findViewById(R.id.message_photo);
233 viewHolder.imageView.setImageBitmap(mBitmapCache
234 .getError());
235 break;
236 default:
237 viewHolder = null;
238 break;
239 }
240 viewHolder.messageBody = (TextView) view
241 .findViewById(R.id.message_body);
242 viewHolder.time = (TextView) view
243 .findViewById(R.id.message_time);
244 view.setTag(viewHolder);
245 } else {
246 viewHolder = (ViewHolder) view.getTag();
247 }
248 if (type == RECIEVED) {
249 if (item.getConversation().getMode() == Conversation.MODE_MULTI) {
250 if (item.getCounterpart() != null) {
251 viewHolder.imageView.setImageBitmap(mBitmapCache
252 .get(item.getCounterpart(), null,
253 getActivity()
254 .getApplicationContext()));
255 } else {
256 viewHolder.imageView.setImageBitmap(mBitmapCache
257 .get(item.getConversation().getName(useSubject),
258 null, getActivity()
259 .getApplicationContext()));
260 }
261 }
262 }
263 String body = item.getBody();
264 if (body != null) {
265 if (item.getEncryption() == Message.ENCRYPTION_PGP) {
266 viewHolder.messageBody
267 .setText(getString(R.string.encrypted_message));
268 viewHolder.messageBody.setTextColor(0xff33B5E5);
269 viewHolder.messageBody.setTypeface(null,
270 Typeface.ITALIC);
271 viewHolder.indicator.setVisibility(View.VISIBLE);
272 } else if ((item.getEncryption() == Message.ENCRYPTION_OTR)||(item.getEncryption() == Message.ENCRYPTION_DECRYPTED)) {
273 viewHolder.messageBody.setText(body.trim());
274 viewHolder.messageBody.setTextColor(0xff000000);
275 viewHolder.messageBody.setTypeface(null,
276 Typeface.NORMAL);
277 viewHolder.indicator.setVisibility(View.VISIBLE);
278 } else {
279 viewHolder.messageBody.setText(body.trim());
280 viewHolder.messageBody.setTextColor(0xff000000);
281 viewHolder.messageBody.setTypeface(null,
282 Typeface.NORMAL);
283 if (item.getStatus() != Message.STATUS_ERROR) {
284 viewHolder.indicator.setVisibility(View.GONE);
285 }
286 }
287 } else {
288 viewHolder.indicator.setVisibility(View.GONE);
289 }
290 if (item.getStatus() == Message.STATUS_UNSEND) {
291 viewHolder.time.setTypeface(null, Typeface.ITALIC);
292 viewHolder.time.setText("sending\u2026");
293 } else {
294 viewHolder.time.setTypeface(null, Typeface.NORMAL);
295 if ((item.getConversation().getMode() == Conversation.MODE_SINGLE)
296 || (type != RECIEVED)) {
297 viewHolder.time.setText(UIHelper
298 .readableTimeDifference(item.getTimeSent()));
299 } else {
300 viewHolder.time.setText(item.getCounterpart()
301 + " \u00B7 "
302 + UIHelper.readableTimeDifference(item
303 .getTimeSent()));
304 }
305 }
306 return view;
307 }
308 };
309 messagesView.setAdapter(messageListAdapter);
310
311 return view;
312 }
313
314 protected Bitmap findSelfPicture() {
315 SharedPreferences sharedPref = PreferenceManager
316 .getDefaultSharedPreferences(getActivity()
317 .getApplicationContext());
318 boolean showPhoneSelfContactPicture = sharedPref.getBoolean(
319 "show_phone_selfcontact_picture", true);
320
321 return UIHelper.getSelfContactPicture(conversation.getAccount(), 200,
322 showPhoneSelfContactPicture, getActivity());
323 }
324
325 @Override
326 public void onStart() {
327 super.onStart();
328 ConversationActivity activity = (ConversationActivity) getActivity();
329 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
330 this.useSubject = preferences.getBoolean("use_subject_in_muc", true);
331 if (activity.xmppConnectionServiceBound) {
332 this.onBackendConnected();
333 }
334 }
335
336 public void onBackendConnected() {
337 final ConversationActivity activity = (ConversationActivity) getActivity();
338 activity.registerListener();
339 this.conversation = activity.getSelectedConversation();
340 if (this.conversation == null) {
341 return;
342 }
343 this.selfBitmap = findSelfPicture();
344 updateMessages();
345 // rendering complete. now go tell activity to close pane
346 if (activity.getSlidingPaneLayout().isSlideable()) {
347 if (!activity.shouldPaneBeOpen()) {
348 activity.getSlidingPaneLayout().closePane();
349 activity.getActionBar().setDisplayHomeAsUpEnabled(true);
350 activity.getActionBar().setTitle(conversation.getName(useSubject));
351 activity.invalidateOptionsMenu();
352
353 }
354 }
355 if (queuedPqpMessage != null) {
356 this.conversation.nextMessageEncryption = Message.ENCRYPTION_PGP;
357 Message message = new Message(conversation, queuedPqpMessage,
358 Message.ENCRYPTION_PGP);
359 sendPgpMessage(message);
360 }
361 if (conversation.getMode() == Conversation.MODE_MULTI) {
362 activity.xmppConnectionService
363 .setOnRenameListener(new OnRenameListener() {
364
365 @Override
366 public void onRename(final boolean success) {
367 activity.xmppConnectionService.updateConversation(conversation);
368 getActivity().runOnUiThread(new Runnable() {
369
370 @Override
371 public void run() {
372 if (success) {
373 Toast.makeText(
374 getActivity(),
375 "Your nickname has been changed",
376 Toast.LENGTH_SHORT).show();
377 } else {
378 Toast.makeText(getActivity(),
379 "Nichname is already in use",
380 Toast.LENGTH_SHORT).show();
381 }
382 }
383 });
384 }
385 });
386 }
387 }
388
389 public void updateMessages() {
390 ConversationActivity activity = (ConversationActivity) getActivity();
391 List<Message> encryptedMessages = new LinkedList<Message>();
392 for (Message message : this.conversation.getMessages()) {
393 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
394 encryptedMessages.add(message);
395 }
396 }
397 if (encryptedMessages.size() > 0) {
398 DecryptMessage task = new DecryptMessage();
399 Message[] msgs = new Message[encryptedMessages.size()];
400 task.execute(encryptedMessages.toArray(msgs));
401 }
402 this.messageList.clear();
403 this.messageList.addAll(this.conversation.getMessages());
404 this.messageListAdapter.notifyDataSetChanged();
405 if (conversation.getMode() == Conversation.MODE_SINGLE) {
406 if (messageList.size() >= 1) {
407 int latestEncryption = this.conversation.getLatestMessage()
408 .getEncryption();
409 if (latestEncryption == Message.ENCRYPTION_DECRYPTED) {
410 conversation.nextMessageEncryption = Message.ENCRYPTION_PGP;
411 } else {
412 conversation.nextMessageEncryption = latestEncryption;
413 }
414 makeFingerprintWarning(latestEncryption);
415 }
416 } else {
417 if (conversation.getMucOptions().getError() != 0) {
418 mucError.setVisibility(View.VISIBLE);
419 if (conversation.getMucOptions().getError() == MucOptions.ERROR_NICK_IN_USE) {
420 mucErrorText.setText(getString(R.string.nick_in_use));
421 }
422 } else {
423 mucError.setVisibility(View.GONE);
424 }
425 }
426 getActivity().invalidateOptionsMenu();
427 updateChatMsgHint();
428 int size = this.messageList.size();
429 if (size >= 1)
430 messagesView.setSelection(size - 1);
431 if (!activity.shouldPaneBeOpen()) {
432 conversation.markRead();
433 // TODO update notifications
434 UIHelper.updateNotification(getActivity(),
435 activity.getConversationList(), null, false);
436 activity.updateConversationList();
437 }
438 }
439
440 protected void makeFingerprintWarning(int latestEncryption) {
441 final LinearLayout fingerprintWarning = (LinearLayout) getView()
442 .findViewById(R.id.new_fingerprint);
443 if (conversation.getContact() != null) {
444 Set<String> knownFingerprints = conversation.getContact()
445 .getOtrFingerprints();
446 if ((latestEncryption == Message.ENCRYPTION_OTR)
447 && (conversation.hasValidOtrSession()
448 && (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) && (!knownFingerprints
449 .contains(conversation.getOtrFingerprint())))) {
450 fingerprintWarning.setVisibility(View.VISIBLE);
451 TextView fingerprint = (TextView) getView().findViewById(
452 R.id.otr_fingerprint);
453 fingerprint.setText(conversation.getOtrFingerprint());
454 fingerprintWarning.setOnClickListener(new OnClickListener() {
455
456 @Override
457 public void onClick(View v) {
458 AlertDialog dialog = UIHelper
459 .getVerifyFingerprintDialog(
460 (ConversationActivity) getActivity(),
461 conversation, fingerprintWarning);
462 dialog.show();
463 }
464 });
465 } else {
466 fingerprintWarning.setVisibility(View.GONE);
467 }
468 } else {
469 fingerprintWarning.setVisibility(View.GONE);
470 }
471 }
472
473 protected void sendPlainTextMessage(Message message) {
474 ConversationActivity activity = (ConversationActivity) getActivity();
475 activity.xmppConnectionService.sendMessage(message, null);
476 chatMsg.setText("");
477 }
478
479 protected void sendPgpMessage(final Message message) {
480 ConversationActivity activity = (ConversationActivity) getActivity();
481 final XmppConnectionService xmppService = activity.xmppConnectionService;
482 Contact contact = message.getConversation().getContact();
483 if (activity.hasPgp()) {
484 if (contact.getPgpKeyId() != 0) {
485 xmppService.sendMessage(message, null);
486 chatMsg.setText("");
487 } else {
488 AlertDialog.Builder builder = new AlertDialog.Builder(
489 getActivity());
490 builder.setTitle("No openPGP key found");
491 builder.setIconAttribute(android.R.attr.alertDialogIcon);
492 builder.setMessage("There is no openPGP key assoziated with this contact");
493 builder.setNegativeButton("Cancel", null);
494 builder.setPositiveButton("Send plain text",
495 new DialogInterface.OnClickListener() {
496
497 @Override
498 public void onClick(DialogInterface dialog,
499 int which) {
500 conversation.nextMessageEncryption = Message.ENCRYPTION_NONE;
501 message.setEncryption(Message.ENCRYPTION_NONE);
502 xmppService.sendMessage(message, null);
503 chatMsg.setText("");
504 }
505 });
506 builder.create().show();
507 }
508 }
509 }
510
511 protected void sendOtrMessage(final Message message) {
512 ConversationActivity activity = (ConversationActivity) getActivity();
513 final XmppConnectionService xmppService = activity.xmppConnectionService;
514 if (conversation.hasValidOtrSession()) {
515 activity.xmppConnectionService.sendMessage(message, null);
516 chatMsg.setText("");
517 } else {
518 Hashtable<String, Integer> presences;
519 if (conversation.getContact() != null) {
520 presences = conversation.getContact().getPresences();
521 } else {
522 presences = null;
523 }
524 if ((presences == null) || (presences.size() == 0)) {
525 AlertDialog.Builder builder = new AlertDialog.Builder(
526 getActivity());
527 builder.setTitle("Contact is offline");
528 builder.setIconAttribute(android.R.attr.alertDialogIcon);
529 builder.setMessage("Sending OTR encrypted messages to an offline contact is impossible.");
530 builder.setPositiveButton("Send plain text",
531 new DialogInterface.OnClickListener() {
532
533 @Override
534 public void onClick(DialogInterface dialog,
535 int which) {
536 conversation.nextMessageEncryption = Message.ENCRYPTION_NONE;
537 message.setEncryption(Message.ENCRYPTION_NONE);
538 xmppService.sendMessage(message, null);
539 chatMsg.setText("");
540 }
541 });
542 builder.setNegativeButton("Cancel", null);
543 builder.create().show();
544 } else if (presences.size() == 1) {
545 xmppService.sendMessage(message, (String) presences.keySet()
546 .toArray()[0]);
547 chatMsg.setText("");
548 } else {
549 AlertDialog.Builder builder = new AlertDialog.Builder(
550 getActivity());
551 builder.setTitle("Choose Presence");
552 final String[] presencesArray = new String[presences.size()];
553 presences.keySet().toArray(presencesArray);
554 builder.setItems(presencesArray,
555 new DialogInterface.OnClickListener() {
556
557 @Override
558 public void onClick(DialogInterface dialog,
559 int which) {
560 xmppService.sendMessage(message,
561 presencesArray[which]);
562 chatMsg.setText("");
563 }
564 });
565 builder.create().show();
566 }
567 }
568 }
569
570 private static class ViewHolder {
571
572 protected ImageView indicator;
573 protected TextView time;
574 protected TextView messageBody;
575 protected ImageView imageView;
576
577 }
578
579 private class BitmapCache {
580 private HashMap<String, Bitmap> bitmaps = new HashMap<String, Bitmap>();
581 private Bitmap error = null;
582
583 public Bitmap get(String name, Contact contact, Context context) {
584 if (bitmaps.containsKey(name)) {
585 return bitmaps.get(name);
586 } else {
587 Bitmap bm = UIHelper.getContactPicture(contact, name, 200, context);
588 bitmaps.put(name, bm);
589 return bm;
590 }
591 }
592
593 public Bitmap getError() {
594 if (error == null) {
595 error = UIHelper.getErrorPicture(200);
596 }
597 return error;
598 }
599 }
600
601 class DecryptMessage extends AsyncTask<Message, Void, Boolean> {
602
603 @Override
604 protected Boolean doInBackground(Message... params) {
605 final ConversationActivity activity = (ConversationActivity) getActivity();
606 askForPassphraseIntent = null;
607 for (int i = 0; i < params.length; ++i) {
608 if (params[i].getEncryption() == Message.ENCRYPTION_PGP) {
609 String body = params[i].getBody();
610 String decrypted = null;
611 if (activity == null) {
612 return false;
613 } else if (!activity.xmppConnectionServiceBound) {
614 return false;
615 }
616 try {
617 decrypted = activity.xmppConnectionService
618 .getPgpEngine().decrypt(body);
619 } catch (UserInputRequiredException e) {
620 askForPassphraseIntent = e.getPendingIntent()
621 .getIntentSender();
622 activity.runOnUiThread(new Runnable() {
623
624 @Override
625 public void run() {
626 pgpInfo.setVisibility(View.VISIBLE);
627 }
628 });
629
630 return false;
631
632 } catch (OpenPgpException e) {
633 Log.d("gultsch", "error decrypting pgp");
634 }
635 if (decrypted != null) {
636 params[i].setBody(decrypted);
637 params[i].setEncryption(Message.ENCRYPTION_DECRYPTED);
638 activity.xmppConnectionService.updateMessage(params[i]);
639 }
640 if (activity != null) {
641 activity.runOnUiThread(new Runnable() {
642
643 @Override
644 public void run() {
645 messageListAdapter.notifyDataSetChanged();
646 }
647 });
648 }
649 }
650 if (activity != null) {
651 activity.runOnUiThread(new Runnable() {
652
653 @Override
654 public void run() {
655 activity.updateConversationList();
656 }
657 });
658 }
659 }
660 return true;
661 }
662
663 }
664
665 public void setText(String text) {
666 this.pastedText = text;
667 }
668}