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