1package eu.siacs.conversations.ui;
2
3import java.io.FileNotFoundException;
4import java.lang.ref.WeakReference;
5import java.util.ArrayList;
6import java.util.List;
7
8import eu.siacs.conversations.R;
9import eu.siacs.conversations.entities.Contact;
10import eu.siacs.conversations.entities.Conversation;
11import eu.siacs.conversations.entities.Message;
12import eu.siacs.conversations.services.ImageProvider;
13import eu.siacs.conversations.utils.ExceptionHelper;
14import eu.siacs.conversations.utils.UIHelper;
15import android.net.Uri;
16import android.os.AsyncTask;
17import android.os.Bundle;
18import android.preference.PreferenceManager;
19import android.provider.MediaStore;
20import android.app.AlertDialog;
21import android.app.FragmentTransaction;
22import android.app.PendingIntent;
23import android.content.Context;
24import android.content.DialogInterface;
25import android.content.DialogInterface.OnClickListener;
26import android.content.IntentSender.SendIntentException;
27import android.content.Intent;
28import android.content.SharedPreferences;
29import android.content.res.Resources;
30import android.graphics.Bitmap;
31import android.graphics.Color;
32import android.graphics.Typeface;
33import android.graphics.drawable.BitmapDrawable;
34import android.graphics.drawable.Drawable;
35import android.support.v4.widget.SlidingPaneLayout;
36import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
37import android.util.DisplayMetrics;
38import android.util.Log;
39import android.view.KeyEvent;
40import android.view.LayoutInflater;
41import android.view.Menu;
42import android.view.MenuItem;
43import android.view.View;
44import android.view.ViewGroup;
45import android.widget.AdapterView;
46import android.widget.AdapterView.OnItemClickListener;
47import android.widget.ArrayAdapter;
48import android.widget.CheckBox;
49import android.widget.ListView;
50import android.widget.PopupMenu;
51import android.widget.PopupMenu.OnMenuItemClickListener;
52import android.widget.TextView;
53import android.widget.ImageView;
54import android.widget.Toast;
55
56public class ConversationActivity extends XmppActivity {
57
58 public static final String VIEW_CONVERSATION = "viewConversation";
59 public static final String CONVERSATION = "conversationUuid";
60 public static final String TEXT = "text";
61 public static final String PRESENCE = "eu.siacs.conversations.presence";
62
63 public static final int REQUEST_SEND_MESSAGE = 0x75441;
64 public static final int REQUEST_DECRYPT_PGP = 0x76783;
65 private static final int REQUEST_ATTACH_FILE_DIALOG = 0x48502;
66 private static final int REQUEST_IMAGE_CAPTURE = 0x33788;
67 private static final int REQUEST_RECORD_AUDIO = 0x46189;
68 private static final int REQUEST_SEND_PGP_IMAGE = 0x53883;
69 public static final int REQUEST_ENCRYPT_MESSAGE = 0x378018;
70
71 private static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x92734;
72 private static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x84123;
73 private static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x75291;
74
75 protected SlidingPaneLayout spl;
76
77 private List<Conversation> conversationList = new ArrayList<Conversation>();
78 private Conversation selectedConversation = null;
79 private ListView listView;
80
81 private boolean paneShouldBeOpen = true;
82 private boolean useSubject = true;
83 private boolean showLastseen = false;
84 private ArrayAdapter<Conversation> listAdapter;
85
86 private OnConversationListChangedListener onConvChanged = new OnConversationListChangedListener() {
87
88 @Override
89 public void onConversationListChanged() {
90 runOnUiThread(new Runnable() {
91
92 @Override
93 public void run() {
94 updateConversationList();
95 if (paneShouldBeOpen) {
96 if (conversationList.size() >= 1) {
97 swapConversationFragment();
98 } else {
99 startActivity(new Intent(getApplicationContext(),
100 ContactsActivity.class));
101 finish();
102 }
103 }
104 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
105 .findFragmentByTag("conversation");
106 if (selectedFragment != null) {
107 selectedFragment.updateMessages();
108 }
109 }
110 });
111 }
112 };
113
114 protected ConversationActivity activity = this;
115 private DisplayMetrics metrics;
116 private Toast prepareImageToast;
117
118 public List<Conversation> getConversationList() {
119 return this.conversationList;
120 }
121
122 public Conversation getSelectedConversation() {
123 return this.selectedConversation;
124 }
125
126 public void setSelectedConversation(Conversation conversation) {
127 this.selectedConversation = conversation;
128 }
129
130 public ListView getConversationListView() {
131 return this.listView;
132 }
133
134 public SlidingPaneLayout getSlidingPaneLayout() {
135 return this.spl;
136 }
137
138 public boolean shouldPaneBeOpen() {
139 return paneShouldBeOpen;
140 }
141
142 @Override
143 protected void onCreate(Bundle savedInstanceState) {
144
145 metrics = getResources().getDisplayMetrics();
146
147 super.onCreate(savedInstanceState);
148
149 setContentView(R.layout.fragment_conversations_overview);
150
151 listView = (ListView) findViewById(R.id.list);
152
153 this.listAdapter = new ArrayAdapter<Conversation>(this,
154 R.layout.conversation_list_row, conversationList) {
155 @Override
156 public View getView(int position, View view, ViewGroup parent) {
157 if (view == null) {
158 LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
159 view = (View) inflater.inflate(
160 R.layout.conversation_list_row, null);
161 }
162 Conversation conv;
163 if (conversationList.size() > position) {
164 conv = getItem(position);
165 } else {
166 return view;
167 }
168 if (!spl.isSlideable()) {
169 if (conv == getSelectedConversation()) {
170 view.setBackgroundColor(0xffdddddd);
171 } else {
172 view.setBackgroundColor(Color.TRANSPARENT);
173 }
174 } else {
175 view.setBackgroundColor(Color.TRANSPARENT);
176 }
177 TextView convName = (TextView) view
178 .findViewById(R.id.conversation_name);
179 convName.setText(conv.getName(useSubject));
180 TextView convLastMsg = (TextView) view
181 .findViewById(R.id.conversation_lastmsg);
182 ImageView imagePreview = (ImageView) view
183 .findViewById(R.id.conversation_lastimage);
184
185 Message latestMessage = conv.getLatestMessage();
186
187 if (latestMessage.getType() == Message.TYPE_TEXT) {
188 if ((latestMessage.getEncryption() != Message.ENCRYPTION_PGP)
189 && (latestMessage.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED)) {
190 convLastMsg.setText(conv.getLatestMessage().getBody());
191 } else {
192 convLastMsg
193 .setText(getText(R.string.encrypted_message_received));
194 }
195 convLastMsg.setVisibility(View.VISIBLE);
196 imagePreview.setVisibility(View.GONE);
197 } else if (latestMessage.getType() == Message.TYPE_IMAGE) {
198 if (latestMessage.getStatus() >= Message.STATUS_RECIEVED) {
199 convLastMsg.setVisibility(View.GONE);
200 imagePreview.setVisibility(View.VISIBLE);
201 loadBitmap(latestMessage, imagePreview);
202 } else {
203 convLastMsg.setVisibility(View.VISIBLE);
204 imagePreview.setVisibility(View.GONE);
205 if (latestMessage.getStatus() == Message.STATUS_RECEIVED_OFFER) {
206 convLastMsg
207 .setText(getText(R.string.image_offered_for_download));
208 } else if (latestMessage.getStatus() == Message.STATUS_RECIEVING) {
209 convLastMsg
210 .setText(getText(R.string.receiving_image));
211 } else {
212 convLastMsg.setText("");
213 }
214 }
215 }
216
217 if (!conv.isRead()) {
218 convName.setTypeface(null, Typeface.BOLD);
219 convLastMsg.setTypeface(null, Typeface.BOLD);
220 } else {
221 convName.setTypeface(null, Typeface.NORMAL);
222 convLastMsg.setTypeface(null, Typeface.NORMAL);
223 }
224
225 ((TextView) view.findViewById(R.id.conversation_lastupdate))
226 .setText(UIHelper.readableTimeDifference(getContext(),
227 conv.getLatestMessage().getTimeSent()));
228
229 ImageView profilePicture = (ImageView) view
230 .findViewById(R.id.conversation_image);
231 profilePicture.setImageBitmap(UIHelper.getContactPicture(conv,
232 56, activity.getApplicationContext(), false));
233
234 return view;
235 }
236
237 };
238
239 listView.setAdapter(this.listAdapter);
240
241 listView.setOnItemClickListener(new OnItemClickListener() {
242
243 @Override
244 public void onItemClick(AdapterView<?> arg0, View clickedView,
245 int position, long arg3) {
246 paneShouldBeOpen = false;
247 if (getSelectedConversation() != conversationList.get(position)) {
248 setSelectedConversation(conversationList.get(position));
249 swapConversationFragment(); // .onBackendConnected(conversationList.get(position));
250 } else {
251 spl.closePane();
252 }
253 }
254 });
255 spl = (SlidingPaneLayout) findViewById(R.id.slidingpanelayout);
256 spl.setParallaxDistance(150);
257 spl.setShadowResource(R.drawable.es_slidingpane_shadow);
258 spl.setSliderFadeColor(0);
259 spl.setPanelSlideListener(new PanelSlideListener() {
260
261 @Override
262 public void onPanelOpened(View arg0) {
263 paneShouldBeOpen = true;
264 getActionBar().setDisplayHomeAsUpEnabled(false);
265 getActionBar().setHomeButtonEnabled(false);
266 getActionBar().setTitle(R.string.app_name);
267 invalidateOptionsMenu();
268 hideKeyboard();
269 }
270
271 @Override
272 public void onPanelClosed(View arg0) {
273 paneShouldBeOpen = false;
274 if ((conversationList.size() > 0)
275 && (getSelectedConversation() != null)) {
276 getActionBar().setDisplayHomeAsUpEnabled(true);
277 getActionBar().setHomeButtonEnabled(true);
278 getActionBar().setTitle(
279 getSelectedConversation().getName(useSubject));
280 invalidateOptionsMenu();
281 if (!getSelectedConversation().isRead()) {
282 xmppConnectionService
283 .markRead(getSelectedConversation());
284 UIHelper.updateNotification(getApplicationContext(),
285 getConversationList(), null, false);
286 listView.invalidateViews();
287 }
288 }
289 }
290
291 @Override
292 public void onPanelSlide(View arg0, float arg1) {
293 // TODO Auto-generated method stub
294
295 }
296 });
297 }
298
299 @Override
300 public boolean onCreateOptionsMenu(Menu menu) {
301 getMenuInflater().inflate(R.menu.conversations, menu);
302 MenuItem menuSecure = (MenuItem) menu.findItem(R.id.action_security);
303 MenuItem menuArchive = (MenuItem) menu.findItem(R.id.action_archive);
304 MenuItem menuMucDetails = (MenuItem) menu
305 .findItem(R.id.action_muc_details);
306 MenuItem menuContactDetails = (MenuItem) menu
307 .findItem(R.id.action_contact_details);
308 MenuItem menuInviteContacts = (MenuItem) menu
309 .findItem(R.id.action_invite);
310 MenuItem menuAttach = (MenuItem) menu.findItem(R.id.action_attach_file);
311 MenuItem menuClearHistory = (MenuItem) menu
312 .findItem(R.id.action_clear_history);
313
314 if ((spl.isOpen() && (spl.isSlideable()))) {
315 menuArchive.setVisible(false);
316 menuMucDetails.setVisible(false);
317 menuContactDetails.setVisible(false);
318 menuSecure.setVisible(false);
319 menuInviteContacts.setVisible(false);
320 menuAttach.setVisible(false);
321 menuClearHistory.setVisible(false);
322 } else {
323 ((MenuItem) menu.findItem(R.id.action_add)).setVisible(!spl
324 .isSlideable());
325 if (this.getSelectedConversation() != null) {
326 if (this.getSelectedConversation().getLatestMessage()
327 .getEncryption() != Message.ENCRYPTION_NONE) {
328 menuSecure.setIcon(R.drawable.ic_action_secure);
329 }
330 if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
331 menuContactDetails.setVisible(false);
332 menuAttach.setVisible(false);
333 } else {
334 menuMucDetails.setVisible(false);
335 menuInviteContacts.setVisible(false);
336 }
337 }
338 }
339 return true;
340 }
341
342 private void selectPresenceToAttachFile(final int attachmentChoice) {
343 selectPresence(getSelectedConversation(), new OnPresenceSelected() {
344
345 @Override
346 public void onPresenceSelected() {
347 if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO) {
348 Intent takePictureIntent = new Intent(
349 MediaStore.ACTION_IMAGE_CAPTURE);
350 takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
351 ImageProvider.getIncomingContentUri());
352 if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
353 startActivityForResult(takePictureIntent,
354 REQUEST_IMAGE_CAPTURE);
355 }
356 } else if (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
357 Intent attachFileIntent = new Intent();
358 attachFileIntent.setType("image/*");
359 attachFileIntent.setAction(Intent.ACTION_GET_CONTENT);
360 Intent chooser = Intent.createChooser(attachFileIntent,
361 getString(R.string.attach_file));
362 startActivityForResult(chooser, REQUEST_ATTACH_FILE_DIALOG);
363 } else if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
364 Intent intent = new Intent(
365 MediaStore.Audio.Media.RECORD_SOUND_ACTION);
366 startActivityForResult(intent, REQUEST_RECORD_AUDIO);
367 }
368 }
369 });
370 }
371
372 private void attachFile(final int attachmentChoice) {
373 final Conversation conversation = getSelectedConversation();
374 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
375 if (hasPgp()) {
376 if (conversation.getContact().getPgpKeyId() != 0) {
377 xmppConnectionService.getPgpEngine().hasKey(
378 conversation.getContact(),
379 new UiCallback<Contact>() {
380
381 @Override
382 public void userInputRequried(PendingIntent pi,
383 Contact contact) {
384 ConversationActivity.this.runIntent(pi,
385 attachmentChoice);
386 }
387
388 @Override
389 public void success(Contact contact) {
390 selectPresenceToAttachFile(attachmentChoice);
391 }
392
393 @Override
394 public void error(int error, Contact contact) {
395 displayErrorDialog(error);
396 }
397 });
398 } else {
399 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
400 .findFragmentByTag("conversation");
401 if (fragment != null) {
402 fragment.showNoPGPKeyDialog(false,
403 new OnClickListener() {
404
405 @Override
406 public void onClick(DialogInterface dialog,
407 int which) {
408 conversation
409 .setNextEncryption(Message.ENCRYPTION_NONE);
410 selectPresenceToAttachFile(attachmentChoice);
411 }
412 });
413 }
414 }
415 } else {
416 showInstallPgpDialog();
417 }
418 } else if (getSelectedConversation().getNextEncryption() == Message.ENCRYPTION_NONE) {
419 selectPresenceToAttachFile(attachmentChoice);
420 } else {
421 selectPresenceToAttachFile(attachmentChoice);
422 /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
423 builder.setTitle(getString(R.string.otr_file_transfer));
424 builder.setMessage(getString(R.string.otr_file_transfer_msg));
425 builder.setNegativeButton(getString(R.string.cancel), null);
426 if (conversation.getContact().getPgpKeyId() == 0) {
427 builder.setPositiveButton(getString(R.string.send_unencrypted),
428 new OnClickListener() {
429
430 @Override
431 public void onClick(DialogInterface dialog,
432 int which) {
433 conversation
434 .setNextEncryption(Message.ENCRYPTION_NONE);
435 attachFile(attachmentChoice);
436 }
437 });
438 } else {
439 builder.setPositiveButton(
440 getString(R.string.use_pgp_encryption),
441 new OnClickListener() {
442
443 @Override
444 public void onClick(DialogInterface dialog,
445 int which) {
446 conversation
447 .setNextEncryption(Message.ENCRYPTION_PGP);
448 attachFile(attachmentChoice);
449 }
450 });
451 }
452 builder.create().show();*/
453 }
454 }
455
456 @Override
457 public boolean onOptionsItemSelected(MenuItem item) {
458 switch (item.getItemId()) {
459 case android.R.id.home:
460 spl.openPane();
461 break;
462 case R.id.action_attach_file:
463 View menuAttachFile = findViewById(R.id.action_attach_file);
464 if (menuAttachFile==null) {
465 break;
466 }
467 PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
468 attachFilePopup.inflate(R.menu.attachment_choices);
469 attachFilePopup
470 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
471
472 @Override
473 public boolean onMenuItemClick(MenuItem item) {
474 switch (item.getItemId()) {
475 case R.id.attach_choose_picture:
476 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
477 break;
478 case R.id.attach_take_picture:
479 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
480 break;
481 case R.id.attach_record_voice:
482 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
483 break;
484 }
485 return false;
486 }
487 });
488 attachFilePopup.show();
489 break;
490 case R.id.action_add:
491 startActivity(new Intent(this, ContactsActivity.class));
492 break;
493 case R.id.action_archive:
494 this.endConversation(getSelectedConversation());
495 break;
496 case R.id.action_contact_details:
497 Contact contact = this.getSelectedConversation().getContact();
498 if (contact.showInRoster()) {
499 Intent intent = new Intent(this, ContactDetailsActivity.class);
500 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
501 intent.putExtra("account", this.getSelectedConversation()
502 .getAccount().getJid());
503 intent.putExtra("contact", contact.getJid());
504 startActivity(intent);
505 } else {
506 showAddToRosterDialog(getSelectedConversation());
507 }
508 break;
509 case R.id.action_muc_details:
510 Intent intent = new Intent(this, MucDetailsActivity.class);
511 intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC);
512 intent.putExtra("uuid", getSelectedConversation().getUuid());
513 startActivity(intent);
514 break;
515 case R.id.action_invite:
516 Intent inviteIntent = new Intent(getApplicationContext(),
517 ContactsActivity.class);
518 inviteIntent.setAction("invite");
519 inviteIntent.putExtra("uuid", getSelectedConversation().getUuid());
520 startActivity(inviteIntent);
521 break;
522 case R.id.action_security:
523 final Conversation conversation = getSelectedConversation();
524 View menuItemView = findViewById(R.id.action_security);
525 if (menuItemView==null) {
526 break;
527 }
528 PopupMenu popup = new PopupMenu(this, menuItemView);
529 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
530 .findFragmentByTag("conversation");
531 if (fragment != null) {
532 popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
533
534 @Override
535 public boolean onMenuItemClick(MenuItem item) {
536 switch (item.getItemId()) {
537 case R.id.encryption_choice_none:
538 conversation
539 .setNextEncryption(Message.ENCRYPTION_NONE);
540 item.setChecked(true);
541 break;
542 case R.id.encryption_choice_otr:
543 conversation
544 .setNextEncryption(Message.ENCRYPTION_OTR);
545 item.setChecked(true);
546 break;
547 case R.id.encryption_choice_pgp:
548 if (hasPgp()) {
549 if (conversation.getAccount().getKeys()
550 .has("pgp_signature")) {
551 conversation
552 .setNextEncryption(Message.ENCRYPTION_PGP);
553 item.setChecked(true);
554 } else {
555 announcePgp(conversation.getAccount(),
556 conversation);
557 }
558 } else {
559 showInstallPgpDialog();
560 }
561 break;
562 default:
563 conversation
564 .setNextEncryption(Message.ENCRYPTION_NONE);
565 break;
566 }
567 fragment.updateChatMsgHint();
568 return true;
569 }
570 });
571 popup.inflate(R.menu.encryption_choices);
572 MenuItem otr = popup.getMenu().findItem(
573 R.id.encryption_choice_otr);
574 if (conversation.getMode() == Conversation.MODE_MULTI) {
575 otr.setEnabled(false);
576 }
577 switch (conversation.getNextEncryption()) {
578 case Message.ENCRYPTION_NONE:
579 popup.getMenu().findItem(R.id.encryption_choice_none)
580 .setChecked(true);
581 break;
582 case Message.ENCRYPTION_OTR:
583 otr.setChecked(true);
584 break;
585 case Message.ENCRYPTION_PGP:
586 popup.getMenu().findItem(R.id.encryption_choice_pgp)
587 .setChecked(true);
588 break;
589 default:
590 popup.getMenu().findItem(R.id.encryption_choice_none)
591 .setChecked(true);
592 break;
593 }
594 popup.show();
595 }
596
597 break;
598 case R.id.action_clear_history:
599 clearHistoryDialog(getSelectedConversation());
600 break;
601 default:
602 break;
603 }
604 return super.onOptionsItemSelected(item);
605 }
606
607 private void endConversation(Conversation conversation) {
608 conversation.setStatus(Conversation.STATUS_ARCHIVED);
609 paneShouldBeOpen = true;
610 spl.openPane();
611 xmppConnectionService.archiveConversation(conversation);
612 if (conversationList.size() > 0) {
613 setSelectedConversation(conversationList.get(0));
614 } else {
615 setSelectedConversation(null);
616 }
617 }
618
619 protected void clearHistoryDialog(final Conversation conversation) {
620 AlertDialog.Builder builder = new AlertDialog.Builder(this);
621 builder.setTitle(getString(R.string.clear_conversation_history));
622 View dialogView = getLayoutInflater().inflate(
623 R.layout.dialog_clear_history, null);
624 final CheckBox endConversationCheckBox = (CheckBox) dialogView
625 .findViewById(R.id.end_conversation_checkbox);
626 builder.setView(dialogView);
627 builder.setNegativeButton(getString(R.string.cancel), null);
628 builder.setPositiveButton(getString(R.string.delete_messages),
629 new OnClickListener() {
630
631 @Override
632 public void onClick(DialogInterface dialog, int which) {
633 activity.xmppConnectionService
634 .clearConversationHistory(conversation);
635 if (endConversationCheckBox.isChecked()) {
636 endConversation(conversation);
637 }
638 }
639 });
640 builder.create().show();
641 }
642
643 protected ConversationFragment swapConversationFragment() {
644 ConversationFragment selectedFragment = new ConversationFragment();
645
646 FragmentTransaction transaction = getFragmentManager()
647 .beginTransaction();
648 transaction.replace(R.id.selected_conversation, selectedFragment,
649 "conversation");
650 transaction.commitAllowingStateLoss();
651 return selectedFragment;
652 }
653
654 @Override
655 public boolean onKeyDown(int keyCode, KeyEvent event) {
656 if (keyCode == KeyEvent.KEYCODE_BACK) {
657 if (!spl.isOpen()) {
658 spl.openPane();
659 return false;
660 }
661 }
662 return super.onKeyDown(keyCode, event);
663 }
664
665 @Override
666 protected void onNewIntent(Intent intent) {
667 if ((Intent.ACTION_VIEW.equals(intent.getAction()) && (VIEW_CONVERSATION
668 .equals(intent.getType())))) {
669 String convToView = (String) intent.getExtras().get(CONVERSATION);
670 updateConversationList();
671 for (int i = 0; i < conversationList.size(); ++i) {
672 if (conversationList.get(i).getUuid().equals(convToView)) {
673 setSelectedConversation(conversationList.get(i));
674 break;
675 }
676 }
677 paneShouldBeOpen = false;
678 String text = intent.getExtras().getString(TEXT, null);
679 swapConversationFragment().setText(text);
680 }
681 }
682
683 @Override
684 public void onStart() {
685 super.onStart();
686 SharedPreferences preferences = PreferenceManager
687 .getDefaultSharedPreferences(this);
688 this.useSubject = preferences.getBoolean("use_subject_in_muc", true);
689 this.showLastseen = preferences.getBoolean("show_last_seen", false);
690 if (this.xmppConnectionServiceBound) {
691 this.onBackendConnected();
692 }
693 if (conversationList.size() >= 1) {
694 onConvChanged.onConversationListChanged();
695 }
696 }
697
698 @Override
699 protected void onStop() {
700 if (xmppConnectionServiceBound) {
701 xmppConnectionService.removeOnConversationListChangedListener();
702 }
703 super.onStop();
704 }
705
706 @Override
707 void onBackendConnected() {
708 this.registerListener();
709 if (conversationList.size() == 0) {
710 updateConversationList();
711 }
712
713 if ((getIntent().getAction() != null)
714 && (getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) {
715 if (getIntent().getType().equals(
716 ConversationActivity.VIEW_CONVERSATION)) {
717 handledViewIntent = true;
718
719 String convToView = (String) getIntent().getExtras().get(
720 CONVERSATION);
721
722 for (int i = 0; i < conversationList.size(); ++i) {
723 if (conversationList.get(i).getUuid().equals(convToView)) {
724 setSelectedConversation(conversationList.get(i));
725 }
726 }
727 paneShouldBeOpen = false;
728 String text = getIntent().getExtras().getString(TEXT, null);
729 swapConversationFragment().setText(text);
730 }
731 } else {
732 if (xmppConnectionService.getAccounts().size() == 0) {
733 startActivity(new Intent(this, ManageAccountActivity.class));
734 finish();
735 } else if (conversationList.size() <= 0) {
736 // add no history
737 startActivity(new Intent(this, ContactsActivity.class));
738 finish();
739 } else {
740 spl.openPane();
741 // find currently loaded fragment
742 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
743 .findFragmentByTag("conversation");
744 if (selectedFragment != null) {
745 selectedFragment.onBackendConnected();
746 } else {
747 setSelectedConversation(conversationList.get(0));
748 swapConversationFragment();
749 }
750 ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
751 }
752 }
753 }
754
755 public void registerListener() {
756 if (xmppConnectionServiceBound) {
757 xmppConnectionService
758 .setOnConversationListChangedListener(this.onConvChanged);
759 }
760 }
761
762 @Override
763 protected void onActivityResult(int requestCode, int resultCode,
764 final Intent data) {
765 super.onActivityResult(requestCode, resultCode, data);
766 if (resultCode == RESULT_OK) {
767 if (requestCode == REQUEST_DECRYPT_PGP) {
768 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
769 .findFragmentByTag("conversation");
770 if (selectedFragment != null) {
771 selectedFragment.hidePgpPassphraseBox();
772 }
773 } else if (requestCode == REQUEST_ATTACH_FILE_DIALOG) {
774 attachImageToConversation(getSelectedConversation(),
775 data.getData());
776 } else if (requestCode == REQUEST_SEND_PGP_IMAGE) {
777
778 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
779 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
780 } else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
781 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
782 } else if (requestCode == REQUEST_ANNOUNCE_PGP) {
783 announcePgp(getSelectedConversation().getAccount(),
784 getSelectedConversation());
785 } else if (requestCode == REQUEST_ENCRYPT_MESSAGE) {
786 // encryptTextMessage();
787 } else if (requestCode == REQUEST_IMAGE_CAPTURE) {
788 attachImageToConversation(getSelectedConversation(), null);
789 } else if (requestCode == REQUEST_RECORD_AUDIO) {
790 Log.d("xmppService", data.getData().toString());
791 attachAudioToConversation(getSelectedConversation(),
792 data.getData());
793 } else {
794 Log.d(LOGTAG, "unknown result code:" + requestCode);
795 }
796 }
797 }
798
799 private void attachAudioToConversation(Conversation conversation, Uri uri) {
800
801 }
802
803 private void attachImageToConversation(Conversation conversation, Uri uri) {
804 prepareImageToast = Toast.makeText(getApplicationContext(),
805 getText(R.string.preparing_image), Toast.LENGTH_LONG);
806 prepareImageToast.show();
807 xmppConnectionService.attachImageToConversation(conversation, uri,
808 new UiCallback<Message>() {
809
810 @Override
811 public void userInputRequried(PendingIntent pi,
812 Message object) {
813 hidePrepareImageToast();
814 ConversationActivity.this.runIntent(pi,
815 ConversationActivity.REQUEST_SEND_PGP_IMAGE);
816 }
817
818 @Override
819 public void success(Message message) {
820 xmppConnectionService.sendMessage(message);
821 }
822
823 @Override
824 public void error(int error, Message message) {
825 hidePrepareImageToast();
826 displayErrorDialog(error);
827 }
828 });
829 }
830
831 private void hidePrepareImageToast() {
832 if (prepareImageToast != null) {
833 runOnUiThread(new Runnable() {
834
835 @Override
836 public void run() {
837 prepareImageToast.cancel();
838 }
839 });
840 }
841 }
842
843 public void updateConversationList() {
844 conversationList.clear();
845 conversationList.addAll(xmppConnectionService.getConversations());
846 listView.invalidateViews();
847 }
848
849 public boolean showLastseen() {
850 if (getSelectedConversation() == null) {
851 return false;
852 } else {
853 return this.showLastseen
854 && getSelectedConversation().getMode() == Conversation.MODE_SINGLE;
855 }
856 }
857
858 public void runIntent(PendingIntent pi, int requestCode) {
859 try {
860 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
861 null, 0, 0, 0);
862 } catch (SendIntentException e1) {
863 Log.d("xmppService", "failed to start intent to send message");
864 }
865 }
866
867 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
868 private final WeakReference<ImageView> imageViewReference;
869 private Message message = null;
870
871 public BitmapWorkerTask(ImageView imageView) {
872 imageViewReference = new WeakReference<ImageView>(imageView);
873 }
874
875 @Override
876 protected Bitmap doInBackground(Message... params) {
877 message = params[0];
878 try {
879 return xmppConnectionService.getFileBackend().getThumbnail(
880 message, (int) (metrics.density * 288), false);
881 } catch (FileNotFoundException e) {
882 Log.d("xmppService", "file not found!");
883 return null;
884 }
885 }
886
887 @Override
888 protected void onPostExecute(Bitmap bitmap) {
889 if (imageViewReference != null && bitmap != null) {
890 final ImageView imageView = imageViewReference.get();
891 if (imageView != null) {
892 imageView.setImageBitmap(bitmap);
893 imageView.setBackgroundColor(0x00000000);
894 }
895 }
896 }
897 }
898
899 public void loadBitmap(Message message, ImageView imageView) {
900 Bitmap bm;
901 try {
902 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
903 (int) (metrics.density * 288), true);
904 } catch (FileNotFoundException e) {
905 bm = null;
906 }
907 if (bm != null) {
908 imageView.setImageBitmap(bm);
909 imageView.setBackgroundColor(0x00000000);
910 } else {
911 if (cancelPotentialWork(message, imageView)) {
912 imageView.setBackgroundColor(0xff333333);
913 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
914 final AsyncDrawable asyncDrawable = new AsyncDrawable(
915 getResources(), null, task);
916 imageView.setImageDrawable(asyncDrawable);
917 task.execute(message);
918 }
919 }
920 }
921
922 public static boolean cancelPotentialWork(Message message,
923 ImageView imageView) {
924 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
925
926 if (bitmapWorkerTask != null) {
927 final Message oldMessage = bitmapWorkerTask.message;
928 if (oldMessage == null || message != oldMessage) {
929 bitmapWorkerTask.cancel(true);
930 } else {
931 return false;
932 }
933 }
934 return true;
935 }
936
937 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
938 if (imageView != null) {
939 final Drawable drawable = imageView.getDrawable();
940 if (drawable instanceof AsyncDrawable) {
941 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
942 return asyncDrawable.getBitmapWorkerTask();
943 }
944 }
945 return null;
946 }
947
948 static class AsyncDrawable extends BitmapDrawable {
949 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
950
951 public AsyncDrawable(Resources res, Bitmap bitmap,
952 BitmapWorkerTask bitmapWorkerTask) {
953 super(res, bitmap);
954 bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
955 bitmapWorkerTask);
956 }
957
958 public BitmapWorkerTask getBitmapWorkerTask() {
959 return bitmapWorkerTaskReference.get();
960 }
961 }
962
963 public void encryptTextMessage(Message message) {
964 xmppConnectionService.getPgpEngine().encrypt(message,
965 new UiCallback<Message>() {
966
967 @Override
968 public void userInputRequried(PendingIntent pi,
969 Message message) {
970 activity.runIntent(pi,
971 ConversationActivity.REQUEST_SEND_MESSAGE);
972 }
973
974 @Override
975 public void success(Message message) {
976 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
977 xmppConnectionService.sendMessage(message);
978 }
979
980 @Override
981 public void error(int error, Message message) {
982
983 }
984 });
985 }
986}