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 PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
465 attachFilePopup.inflate(R.menu.attachment_choices);
466 attachFilePopup
467 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
468
469 @Override
470 public boolean onMenuItemClick(MenuItem item) {
471 switch (item.getItemId()) {
472 case R.id.attach_choose_picture:
473 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
474 break;
475 case R.id.attach_take_picture:
476 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
477 break;
478 case R.id.attach_record_voice:
479 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
480 break;
481 }
482 return false;
483 }
484 });
485 attachFilePopup.show();
486 break;
487 case R.id.action_add:
488 startActivity(new Intent(this, ContactsActivity.class));
489 break;
490 case R.id.action_archive:
491 this.endConversation(getSelectedConversation());
492 break;
493 case R.id.action_contact_details:
494 Contact contact = this.getSelectedConversation().getContact();
495 if (contact.showInRoster()) {
496 Intent intent = new Intent(this, ContactDetailsActivity.class);
497 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
498 intent.putExtra("account", this.getSelectedConversation()
499 .getAccount().getJid());
500 intent.putExtra("contact", contact.getJid());
501 startActivity(intent);
502 } else {
503 showAddToRosterDialog(getSelectedConversation());
504 }
505 break;
506 case R.id.action_muc_details:
507 Intent intent = new Intent(this, MucDetailsActivity.class);
508 intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC);
509 intent.putExtra("uuid", getSelectedConversation().getUuid());
510 startActivity(intent);
511 break;
512 case R.id.action_invite:
513 Intent inviteIntent = new Intent(getApplicationContext(),
514 ContactsActivity.class);
515 inviteIntent.setAction("invite");
516 inviteIntent.putExtra("uuid", getSelectedConversation().getUuid());
517 startActivity(inviteIntent);
518 break;
519 case R.id.action_security:
520 final Conversation conversation = getSelectedConversation();
521 View menuItemView = findViewById(R.id.action_security);
522 PopupMenu popup = new PopupMenu(this, menuItemView);
523 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
524 .findFragmentByTag("conversation");
525 if (fragment != null) {
526 popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
527
528 @Override
529 public boolean onMenuItemClick(MenuItem item) {
530 switch (item.getItemId()) {
531 case R.id.encryption_choice_none:
532 conversation
533 .setNextEncryption(Message.ENCRYPTION_NONE);
534 item.setChecked(true);
535 break;
536 case R.id.encryption_choice_otr:
537 conversation
538 .setNextEncryption(Message.ENCRYPTION_OTR);
539 item.setChecked(true);
540 break;
541 case R.id.encryption_choice_pgp:
542 if (hasPgp()) {
543 if (conversation.getAccount().getKeys()
544 .has("pgp_signature")) {
545 conversation
546 .setNextEncryption(Message.ENCRYPTION_PGP);
547 item.setChecked(true);
548 } else {
549 announcePgp(conversation.getAccount(),
550 conversation);
551 }
552 } else {
553 showInstallPgpDialog();
554 }
555 break;
556 default:
557 conversation
558 .setNextEncryption(Message.ENCRYPTION_NONE);
559 break;
560 }
561 fragment.updateChatMsgHint();
562 return true;
563 }
564 });
565 popup.inflate(R.menu.encryption_choices);
566 MenuItem otr = popup.getMenu().findItem(
567 R.id.encryption_choice_otr);
568 if (conversation.getMode() == Conversation.MODE_MULTI) {
569 otr.setEnabled(false);
570 }
571 switch (conversation.getNextEncryption()) {
572 case Message.ENCRYPTION_NONE:
573 popup.getMenu().findItem(R.id.encryption_choice_none)
574 .setChecked(true);
575 break;
576 case Message.ENCRYPTION_OTR:
577 otr.setChecked(true);
578 break;
579 case Message.ENCRYPTION_PGP:
580 popup.getMenu().findItem(R.id.encryption_choice_pgp)
581 .setChecked(true);
582 break;
583 default:
584 popup.getMenu().findItem(R.id.encryption_choice_none)
585 .setChecked(true);
586 break;
587 }
588 popup.show();
589 }
590
591 break;
592 case R.id.action_clear_history:
593 clearHistoryDialog(getSelectedConversation());
594 break;
595 default:
596 break;
597 }
598 return super.onOptionsItemSelected(item);
599 }
600
601 private void endConversation(Conversation conversation) {
602 conversation.setStatus(Conversation.STATUS_ARCHIVED);
603 paneShouldBeOpen = true;
604 spl.openPane();
605 xmppConnectionService.archiveConversation(conversation);
606 if (conversationList.size() > 0) {
607 setSelectedConversation(conversationList.get(0));
608 } else {
609 setSelectedConversation(null);
610 }
611 }
612
613 protected void clearHistoryDialog(final Conversation conversation) {
614 AlertDialog.Builder builder = new AlertDialog.Builder(this);
615 builder.setTitle(getString(R.string.clear_conversation_history));
616 View dialogView = getLayoutInflater().inflate(
617 R.layout.dialog_clear_history, null);
618 final CheckBox endConversationCheckBox = (CheckBox) dialogView
619 .findViewById(R.id.end_conversation_checkbox);
620 builder.setView(dialogView);
621 builder.setNegativeButton(getString(R.string.cancel), null);
622 builder.setPositiveButton(getString(R.string.delete_messages),
623 new OnClickListener() {
624
625 @Override
626 public void onClick(DialogInterface dialog, int which) {
627 activity.xmppConnectionService
628 .clearConversationHistory(conversation);
629 if (endConversationCheckBox.isChecked()) {
630 endConversation(conversation);
631 }
632 }
633 });
634 builder.create().show();
635 }
636
637 protected ConversationFragment swapConversationFragment() {
638 ConversationFragment selectedFragment = new ConversationFragment();
639
640 FragmentTransaction transaction = getFragmentManager()
641 .beginTransaction();
642 transaction.replace(R.id.selected_conversation, selectedFragment,
643 "conversation");
644 transaction.commit();
645 return selectedFragment;
646 }
647
648 @Override
649 public boolean onKeyDown(int keyCode, KeyEvent event) {
650 if (keyCode == KeyEvent.KEYCODE_BACK) {
651 if (!spl.isOpen()) {
652 spl.openPane();
653 return false;
654 }
655 }
656 return super.onKeyDown(keyCode, event);
657 }
658
659 @Override
660 protected void onNewIntent(Intent intent) {
661 if ((Intent.ACTION_VIEW.equals(intent.getAction()) && (VIEW_CONVERSATION
662 .equals(intent.getType())))) {
663 String convToView = (String) intent.getExtras().get(CONVERSATION);
664 updateConversationList();
665 for (int i = 0; i < conversationList.size(); ++i) {
666 if (conversationList.get(i).getUuid().equals(convToView)) {
667 setSelectedConversation(conversationList.get(i));
668 break;
669 }
670 }
671 paneShouldBeOpen = false;
672 String text = intent.getExtras().getString(TEXT, null);
673 swapConversationFragment().setText(text);
674 }
675 }
676
677 @Override
678 public void onStart() {
679 super.onStart();
680 SharedPreferences preferences = PreferenceManager
681 .getDefaultSharedPreferences(this);
682 this.useSubject = preferences.getBoolean("use_subject_in_muc", true);
683 this.showLastseen = preferences.getBoolean("show_last_seen", false);
684 if (this.xmppConnectionServiceBound) {
685 this.onBackendConnected();
686 }
687 if (conversationList.size() >= 1) {
688 onConvChanged.onConversationListChanged();
689 }
690 }
691
692 @Override
693 protected void onStop() {
694 if (xmppConnectionServiceBound) {
695 xmppConnectionService.removeOnConversationListChangedListener();
696 }
697 super.onStop();
698 }
699
700 @Override
701 void onBackendConnected() {
702 this.registerListener();
703 if (conversationList.size() == 0) {
704 updateConversationList();
705 }
706
707 if ((getIntent().getAction() != null)
708 && (getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) {
709 if (getIntent().getType().equals(
710 ConversationActivity.VIEW_CONVERSATION)) {
711 handledViewIntent = true;
712
713 String convToView = (String) getIntent().getExtras().get(
714 CONVERSATION);
715
716 for (int i = 0; i < conversationList.size(); ++i) {
717 if (conversationList.get(i).getUuid().equals(convToView)) {
718 setSelectedConversation(conversationList.get(i));
719 }
720 }
721 paneShouldBeOpen = false;
722 String text = getIntent().getExtras().getString(TEXT, null);
723 swapConversationFragment().setText(text);
724 }
725 } else {
726 if (xmppConnectionService.getAccounts().size() == 0) {
727 startActivity(new Intent(this, ManageAccountActivity.class));
728 finish();
729 } else if (conversationList.size() <= 0) {
730 // add no history
731 startActivity(new Intent(this, ContactsActivity.class));
732 finish();
733 } else {
734 spl.openPane();
735 // find currently loaded fragment
736 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
737 .findFragmentByTag("conversation");
738 if (selectedFragment != null) {
739 selectedFragment.onBackendConnected();
740 } else {
741 setSelectedConversation(conversationList.get(0));
742 swapConversationFragment();
743 }
744 ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
745 }
746 }
747 }
748
749 public void registerListener() {
750 if (xmppConnectionServiceBound) {
751 xmppConnectionService
752 .setOnConversationListChangedListener(this.onConvChanged);
753 }
754 }
755
756 @Override
757 protected void onActivityResult(int requestCode, int resultCode,
758 final Intent data) {
759 super.onActivityResult(requestCode, resultCode, data);
760 if (resultCode == RESULT_OK) {
761 if (requestCode == REQUEST_DECRYPT_PGP) {
762 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
763 .findFragmentByTag("conversation");
764 if (selectedFragment != null) {
765 selectedFragment.hidePgpPassphraseBox();
766 }
767 } else if (requestCode == REQUEST_ATTACH_FILE_DIALOG) {
768 attachImageToConversation(getSelectedConversation(),
769 data.getData());
770 } else if (requestCode == REQUEST_SEND_PGP_IMAGE) {
771
772 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
773 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
774 } else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
775 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
776 } else if (requestCode == REQUEST_ANNOUNCE_PGP) {
777 announcePgp(getSelectedConversation().getAccount(),
778 getSelectedConversation());
779 } else if (requestCode == REQUEST_ENCRYPT_MESSAGE) {
780 // encryptTextMessage();
781 } else if (requestCode == REQUEST_IMAGE_CAPTURE) {
782 attachImageToConversation(getSelectedConversation(), null);
783 } else if (requestCode == REQUEST_RECORD_AUDIO) {
784 Log.d("xmppService", data.getData().toString());
785 attachAudioToConversation(getSelectedConversation(),
786 data.getData());
787 } else {
788 Log.d(LOGTAG, "unknown result code:" + requestCode);
789 }
790 }
791 }
792
793 private void attachAudioToConversation(Conversation conversation, Uri uri) {
794
795 }
796
797 private void attachImageToConversation(Conversation conversation, Uri uri) {
798 prepareImageToast = Toast.makeText(getApplicationContext(),
799 getText(R.string.preparing_image), Toast.LENGTH_LONG);
800 prepareImageToast.show();
801 xmppConnectionService.attachImageToConversation(conversation, uri,
802 new UiCallback<Message>() {
803
804 @Override
805 public void userInputRequried(PendingIntent pi,
806 Message object) {
807 hidePrepareImageToast();
808 ConversationActivity.this.runIntent(pi,
809 ConversationActivity.REQUEST_SEND_PGP_IMAGE);
810 }
811
812 @Override
813 public void success(Message message) {
814 xmppConnectionService.sendMessage(message);
815 }
816
817 @Override
818 public void error(int error, Message message) {
819 hidePrepareImageToast();
820 displayErrorDialog(error);
821 }
822 });
823 }
824
825 private void hidePrepareImageToast() {
826 if (prepareImageToast != null) {
827 runOnUiThread(new Runnable() {
828
829 @Override
830 public void run() {
831 prepareImageToast.cancel();
832 }
833 });
834 }
835 }
836
837 public void updateConversationList() {
838 conversationList.clear();
839 conversationList.addAll(xmppConnectionService.getConversations());
840 listView.invalidateViews();
841 }
842
843 public boolean showLastseen() {
844 if (getSelectedConversation() == null) {
845 return false;
846 } else {
847 return this.showLastseen
848 && getSelectedConversation().getMode() == Conversation.MODE_SINGLE;
849 }
850 }
851
852 public void runIntent(PendingIntent pi, int requestCode) {
853 try {
854 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
855 null, 0, 0, 0);
856 } catch (SendIntentException e1) {
857 Log.d("xmppService", "failed to start intent to send message");
858 }
859 }
860
861 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
862 private final WeakReference<ImageView> imageViewReference;
863 private Message message = null;
864
865 public BitmapWorkerTask(ImageView imageView) {
866 imageViewReference = new WeakReference<ImageView>(imageView);
867 }
868
869 @Override
870 protected Bitmap doInBackground(Message... params) {
871 message = params[0];
872 try {
873 return xmppConnectionService.getFileBackend().getThumbnail(
874 message, (int) (metrics.density * 288), false);
875 } catch (FileNotFoundException e) {
876 Log.d("xmppService", "file not found!");
877 return null;
878 }
879 }
880
881 @Override
882 protected void onPostExecute(Bitmap bitmap) {
883 if (imageViewReference != null && bitmap != null) {
884 final ImageView imageView = imageViewReference.get();
885 if (imageView != null) {
886 imageView.setImageBitmap(bitmap);
887 imageView.setBackgroundColor(0x00000000);
888 }
889 }
890 }
891 }
892
893 public void loadBitmap(Message message, ImageView imageView) {
894 Bitmap bm;
895 try {
896 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
897 (int) (metrics.density * 288), true);
898 } catch (FileNotFoundException e) {
899 bm = null;
900 }
901 if (bm != null) {
902 imageView.setImageBitmap(bm);
903 imageView.setBackgroundColor(0x00000000);
904 } else {
905 if (cancelPotentialWork(message, imageView)) {
906 imageView.setBackgroundColor(0xff333333);
907 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
908 final AsyncDrawable asyncDrawable = new AsyncDrawable(
909 getResources(), null, task);
910 imageView.setImageDrawable(asyncDrawable);
911 task.execute(message);
912 }
913 }
914 }
915
916 public static boolean cancelPotentialWork(Message message,
917 ImageView imageView) {
918 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
919
920 if (bitmapWorkerTask != null) {
921 final Message oldMessage = bitmapWorkerTask.message;
922 if (oldMessage == null || message != oldMessage) {
923 bitmapWorkerTask.cancel(true);
924 } else {
925 return false;
926 }
927 }
928 return true;
929 }
930
931 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
932 if (imageView != null) {
933 final Drawable drawable = imageView.getDrawable();
934 if (drawable instanceof AsyncDrawable) {
935 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
936 return asyncDrawable.getBitmapWorkerTask();
937 }
938 }
939 return null;
940 }
941
942 static class AsyncDrawable extends BitmapDrawable {
943 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
944
945 public AsyncDrawable(Resources res, Bitmap bitmap,
946 BitmapWorkerTask bitmapWorkerTask) {
947 super(res, bitmap);
948 bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
949 bitmapWorkerTask);
950 }
951
952 public BitmapWorkerTask getBitmapWorkerTask() {
953 return bitmapWorkerTaskReference.get();
954 }
955 }
956
957 public void encryptTextMessage(Message message) {
958 xmppConnectionService.getPgpEngine().encrypt(message,
959 new UiCallback<Message>() {
960
961 @Override
962 public void userInputRequried(PendingIntent pi,
963 Message message) {
964 activity.runIntent(pi,
965 ConversationActivity.REQUEST_SEND_MESSAGE);
966 }
967
968 @Override
969 public void success(Message message) {
970 xmppConnectionService.sendMessage(message);
971 }
972
973 @Override
974 public void error(int error, Message message) {
975
976 }
977 });
978 }
979}