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