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