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
330 if (activity.xmppConnectionServiceBound) {
331 this.onBackendConnected();
332 }
333 }
334
335 public void onBackendConnected() {
336 final ConversationActivity activity = (ConversationActivity) getActivity();
337 activity.registerListener();
338 this.conversation = activity.getSelectedConversation();
339 if (this.conversation == null) {
340 return;
341 }
342 this.selfBitmap = findSelfPicture();
343 updateMessages();
344 // rendering complete. now go tell activity to close pane
345 if (activity.getSlidingPaneLayout().isSlideable()) {
346 if (!activity.shouldPaneBeOpen()) {
347 activity.getSlidingPaneLayout().closePane();
348 activity.getActionBar().setDisplayHomeAsUpEnabled(true);
349 activity.getActionBar().setTitle(conversation.getName(useSubject));
350 activity.invalidateOptionsMenu();
351
352 }
353 }
354 if (queuedPqpMessage != null) {
355 this.conversation.nextMessageEncryption = Message.ENCRYPTION_PGP;
356 Message message = new Message(conversation, queuedPqpMessage,
357 Message.ENCRYPTION_PGP);
358 sendPgpMessage(message);
359 }
360 if (conversation.getMode() == Conversation.MODE_MULTI) {
361 activity.xmppConnectionService
362 .setOnRenameListener(new OnRenameListener() {
363
364 @Override
365 public void onRename(final boolean success) {
366 activity.xmppConnectionService.updateConversation(conversation);
367 getActivity().runOnUiThread(new Runnable() {
368
369 @Override
370 public void run() {
371 if (success) {
372 Toast.makeText(
373 getActivity(),
374 "Your nickname has been changed",
375 Toast.LENGTH_SHORT).show();
376 } else {
377 Toast.makeText(getActivity(),
378 "Nichname is already in use",
379 Toast.LENGTH_SHORT).show();
380 }
381 }
382 });
383 }
384 });
385 }
386 }
387
388 public void updateMessages() {
389 ConversationActivity activity = (ConversationActivity) getActivity();
390 List<Message> encryptedMessages = new LinkedList<Message>();
391 for (Message message : this.conversation.getMessages()) {
392 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
393 encryptedMessages.add(message);
394 }
395 }
396 if (encryptedMessages.size() > 0) {
397 DecryptMessage task = new DecryptMessage();
398 Message[] msgs = new Message[encryptedMessages.size()];
399 task.execute(encryptedMessages.toArray(msgs));
400 }
401 this.messageList.clear();
402 this.messageList.addAll(this.conversation.getMessages());
403 this.messageListAdapter.notifyDataSetChanged();
404 if (conversation.getMode() == Conversation.MODE_SINGLE) {
405 if (messageList.size() >= 1) {
406 int latestEncryption = this.conversation.getLatestMessage()
407 .getEncryption();
408 if (latestEncryption == Message.ENCRYPTION_DECRYPTED) {
409 conversation.nextMessageEncryption = Message.ENCRYPTION_PGP;
410 } else {
411 conversation.nextMessageEncryption = latestEncryption;
412 }
413 makeFingerprintWarning(latestEncryption);
414 }
415 } else {
416 if (conversation.getMucOptions().getError() != 0) {
417 mucError.setVisibility(View.VISIBLE);
418 if (conversation.getMucOptions().getError() == MucOptions.ERROR_NICK_IN_USE) {
419 mucErrorText.setText(getString(R.string.nick_in_use));
420 }
421 } else {
422 mucError.setVisibility(View.GONE);
423 }
424 }
425 getActivity().invalidateOptionsMenu();
426 updateChatMsgHint();
427 int size = this.messageList.size();
428 if (size >= 1)
429 messagesView.setSelection(size - 1);
430 if (!activity.shouldPaneBeOpen()) {
431 conversation.markRead();
432 // TODO update notifications
433 UIHelper.updateNotification(getActivity(),
434 activity.getConversationList(), null, false);
435 activity.updateConversationList();
436 }
437 }
438
439 protected void makeFingerprintWarning(int latestEncryption) {
440 final LinearLayout fingerprintWarning = (LinearLayout) getView()
441 .findViewById(R.id.new_fingerprint);
442 if (conversation.getContact() != null) {
443 Set<String> knownFingerprints = conversation.getContact()
444 .getOtrFingerprints();
445 if ((latestEncryption == Message.ENCRYPTION_OTR)
446 && (conversation.hasValidOtrSession()
447 && (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) && (!knownFingerprints
448 .contains(conversation.getOtrFingerprint())))) {
449 fingerprintWarning.setVisibility(View.VISIBLE);
450 TextView fingerprint = (TextView) getView().findViewById(
451 R.id.otr_fingerprint);
452 fingerprint.setText(conversation.getOtrFingerprint());
453 fingerprintWarning.setOnClickListener(new OnClickListener() {
454
455 @Override
456 public void onClick(View v) {
457 AlertDialog dialog = UIHelper
458 .getVerifyFingerprintDialog(
459 (ConversationActivity) getActivity(),
460 conversation, fingerprintWarning);
461 dialog.show();
462 }
463 });
464 } else {
465 fingerprintWarning.setVisibility(View.GONE);
466 }
467 } else {
468 fingerprintWarning.setVisibility(View.GONE);
469 }
470 }
471
472 protected void sendPlainTextMessage(Message message) {
473 ConversationActivity activity = (ConversationActivity) getActivity();
474 activity.xmppConnectionService.sendMessage(message, null);
475 chatMsg.setText("");
476 }
477
478 protected void sendPgpMessage(final Message message) {
479 ConversationActivity activity = (ConversationActivity) getActivity();
480 final XmppConnectionService xmppService = activity.xmppConnectionService;
481 Contact contact = message.getConversation().getContact();
482 if (activity.hasPgp()) {
483 if (contact.getPgpKeyId() != 0) {
484 xmppService.sendMessage(message, null);
485 chatMsg.setText("");
486 } else {
487 AlertDialog.Builder builder = new AlertDialog.Builder(
488 getActivity());
489 builder.setTitle("No openPGP key found");
490 builder.setIconAttribute(android.R.attr.alertDialogIcon);
491 builder.setMessage("There is no openPGP key assoziated with this contact");
492 builder.setNegativeButton("Cancel", null);
493 builder.setPositiveButton("Send plain text",
494 new DialogInterface.OnClickListener() {
495
496 @Override
497 public void onClick(DialogInterface dialog,
498 int which) {
499 conversation.nextMessageEncryption = Message.ENCRYPTION_NONE;
500 message.setEncryption(Message.ENCRYPTION_NONE);
501 xmppService.sendMessage(message, null);
502 chatMsg.setText("");
503 }
504 });
505 builder.create().show();
506 }
507 }
508 }
509
510 protected void sendOtrMessage(final Message message) {
511 ConversationActivity activity = (ConversationActivity) getActivity();
512 final XmppConnectionService xmppService = activity.xmppConnectionService;
513 if (conversation.hasValidOtrSession()) {
514 activity.xmppConnectionService.sendMessage(message, null);
515 chatMsg.setText("");
516 } else {
517 Hashtable<String, Integer> presences;
518 if (conversation.getContact() != null) {
519 presences = conversation.getContact().getPresences();
520 } else {
521 presences = null;
522 }
523 if ((presences == null) || (presences.size() == 0)) {
524 AlertDialog.Builder builder = new AlertDialog.Builder(
525 getActivity());
526 builder.setTitle("Contact is offline");
527 builder.setIconAttribute(android.R.attr.alertDialogIcon);
528 builder.setMessage("Sending OTR encrypted messages to an offline contact is impossible.");
529 builder.setPositiveButton("Send plain text",
530 new DialogInterface.OnClickListener() {
531
532 @Override
533 public void onClick(DialogInterface dialog,
534 int which) {
535 conversation.nextMessageEncryption = Message.ENCRYPTION_NONE;
536 message.setEncryption(Message.ENCRYPTION_NONE);
537 xmppService.sendMessage(message, null);
538 chatMsg.setText("");
539 }
540 });
541 builder.setNegativeButton("Cancel", null);
542 builder.create().show();
543 } else if (presences.size() == 1) {
544 xmppService.sendMessage(message, (String) presences.keySet()
545 .toArray()[0]);
546 chatMsg.setText("");
547 } else {
548 AlertDialog.Builder builder = new AlertDialog.Builder(
549 getActivity());
550 builder.setTitle("Choose Presence");
551 final String[] presencesArray = new String[presences.size()];
552 presences.keySet().toArray(presencesArray);
553 builder.setItems(presencesArray,
554 new DialogInterface.OnClickListener() {
555
556 @Override
557 public void onClick(DialogInterface dialog,
558 int which) {
559 xmppService.sendMessage(message,
560 presencesArray[which]);
561 chatMsg.setText("");
562 }
563 });
564 builder.create().show();
565 }
566 }
567 }
568
569 private static class ViewHolder {
570
571 protected ImageView indicator;
572 protected TextView time;
573 protected TextView messageBody;
574 protected ImageView imageView;
575
576 }
577
578 private class BitmapCache {
579 private HashMap<String, Bitmap> bitmaps = new HashMap<String, Bitmap>();
580 private Bitmap error = null;
581
582 public Bitmap get(String name, Contact contact, Context context) {
583 if (bitmaps.containsKey(name)) {
584 return bitmaps.get(name);
585 } else {
586 Bitmap bm = UIHelper.getContactPicture(contact, name, 200, context);
587 bitmaps.put(name, bm);
588 return bm;
589 }
590 }
591
592 public Bitmap getError() {
593 if (error == null) {
594 error = UIHelper.getErrorPicture(200);
595 }
596 return error;
597 }
598 }
599
600 class DecryptMessage extends AsyncTask<Message, Void, Boolean> {
601
602 @Override
603 protected Boolean doInBackground(Message... params) {
604 final ConversationActivity activity = (ConversationActivity) getActivity();
605 askForPassphraseIntent = null;
606 for (int i = 0; i < params.length; ++i) {
607 if (params[i].getEncryption() == Message.ENCRYPTION_PGP) {
608 String body = params[i].getBody();
609 String decrypted = null;
610 if (activity == null) {
611 return false;
612 } else if (!activity.xmppConnectionServiceBound) {
613 return false;
614 }
615 try {
616 decrypted = activity.xmppConnectionService
617 .getPgpEngine().decrypt(body);
618 } catch (UserInputRequiredException e) {
619 askForPassphraseIntent = e.getPendingIntent()
620 .getIntentSender();
621 activity.runOnUiThread(new Runnable() {
622
623 @Override
624 public void run() {
625 pgpInfo.setVisibility(View.VISIBLE);
626 }
627 });
628
629 return false;
630
631 } catch (OpenPgpException e) {
632 Log.d("gultsch", "error decrypting pgp");
633 }
634 if (decrypted != null) {
635 params[i].setBody(decrypted);
636 params[i].setEncryption(Message.ENCRYPTION_DECRYPTED);
637 activity.xmppConnectionService.updateMessage(params[i]);
638 }
639 if (activity != null) {
640 activity.runOnUiThread(new Runnable() {
641
642 @Override
643 public void run() {
644 messageListAdapter.notifyDataSetChanged();
645 }
646 });
647 }
648 }
649 if (activity != null) {
650 activity.runOnUiThread(new Runnable() {
651
652 @Override
653 public void run() {
654 activity.updateConversationList();
655 }
656 });
657 }
658 }
659 return true;
660 }
661
662 }
663
664 public void setText(String text) {
665 this.pastedText = text;
666 }
667}