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