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 menuManageAccounts = (MenuItem) menu.findItem(R.id.action_accounts);
313 MenuItem menuSettings = (MenuItem) menu.findItem(R.id.action_settings);
314 MenuItem menuAdd = (MenuItem) menu.findItem(R.id.action_add);
315 MenuItem menuInviteContact = (MenuItem) menu.findItem(R.id.action_invite);
316
317 if ((spl.isOpen() && (spl.isSlideable()))) {
318 menuArchive.setVisible(false);
319 menuMucDetails.setVisible(false);
320 menuContactDetails.setVisible(false);
321 menuSecure.setVisible(false);
322 menuInviteContact.setVisible(false);
323 menuAttach.setVisible(false);
324 menuClearHistory.setVisible(false);
325 } else {
326 menuAdd.setVisible(!spl.isSlideable());
327 menuSettings.setVisible(!spl.isSlideable());
328 menuManageAccounts.setVisible(!spl.isSlideable());
329 if (this.getSelectedConversation() != null) {
330 if (this.getSelectedConversation().getLatestMessage()
331 .getEncryption() != Message.ENCRYPTION_NONE) {
332 menuSecure.setIcon(R.drawable.ic_action_secure);
333 }
334 if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
335 menuContactDetails.setVisible(false);
336 menuAttach.setVisible(false);
337 } else {
338 menuMucDetails.setVisible(false);
339 menuInviteContact.setVisible(false);
340 }
341 }
342 }
343 return true;
344 }
345
346 private void selectPresenceToAttachFile(final int attachmentChoice) {
347 selectPresence(getSelectedConversation(), new OnPresenceSelected() {
348
349 @Override
350 public void onPresenceSelected() {
351 if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO) {
352 Intent takePictureIntent = new Intent(
353 MediaStore.ACTION_IMAGE_CAPTURE);
354 takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
355 ImageProvider.getIncomingContentUri());
356 if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
357 startActivityForResult(takePictureIntent,
358 REQUEST_IMAGE_CAPTURE);
359 }
360 } else if (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
361 Intent attachFileIntent = new Intent();
362 attachFileIntent.setType("image/*");
363 attachFileIntent.setAction(Intent.ACTION_GET_CONTENT);
364 Intent chooser = Intent.createChooser(attachFileIntent,
365 getString(R.string.attach_file));
366 startActivityForResult(chooser, REQUEST_ATTACH_FILE_DIALOG);
367 } else if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
368 Intent intent = new Intent(
369 MediaStore.Audio.Media.RECORD_SOUND_ACTION);
370 startActivityForResult(intent, REQUEST_RECORD_AUDIO);
371 }
372 }
373 });
374 }
375
376 private void attachFile(final int attachmentChoice) {
377 final Conversation conversation = getSelectedConversation();
378 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
379 if (hasPgp()) {
380 if (conversation.getContact().getPgpKeyId() != 0) {
381 xmppConnectionService.getPgpEngine().hasKey(
382 conversation.getContact(),
383 new UiCallback<Contact>() {
384
385 @Override
386 public void userInputRequried(PendingIntent pi,
387 Contact contact) {
388 ConversationActivity.this.runIntent(pi,
389 attachmentChoice);
390 }
391
392 @Override
393 public void success(Contact contact) {
394 selectPresenceToAttachFile(attachmentChoice);
395 }
396
397 @Override
398 public void error(int error, Contact contact) {
399 displayErrorDialog(error);
400 }
401 });
402 } else {
403 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
404 .findFragmentByTag("conversation");
405 if (fragment != null) {
406 fragment.showNoPGPKeyDialog(false,
407 new OnClickListener() {
408
409 @Override
410 public void onClick(DialogInterface dialog,
411 int which) {
412 conversation
413 .setNextEncryption(Message.ENCRYPTION_NONE);
414 selectPresenceToAttachFile(attachmentChoice);
415 }
416 });
417 }
418 }
419 } else {
420 showInstallPgpDialog();
421 }
422 } else if (getSelectedConversation().getNextEncryption() == Message.ENCRYPTION_NONE) {
423 selectPresenceToAttachFile(attachmentChoice);
424 } else {
425 selectPresenceToAttachFile(attachmentChoice);
426 }
427 }
428
429 @Override
430 public boolean onOptionsItemSelected(MenuItem item) {
431 switch (item.getItemId()) {
432 case android.R.id.home:
433 spl.openPane();
434 break;
435 case R.id.action_attach_file:
436 View menuAttachFile = findViewById(R.id.action_attach_file);
437 if (menuAttachFile==null) {
438 break;
439 }
440 PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
441 attachFilePopup.inflate(R.menu.attachment_choices);
442 attachFilePopup
443 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
444
445 @Override
446 public boolean onMenuItemClick(MenuItem item) {
447 switch (item.getItemId()) {
448 case R.id.attach_choose_picture:
449 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
450 break;
451 case R.id.attach_take_picture:
452 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
453 break;
454 case R.id.attach_record_voice:
455 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
456 break;
457 }
458 return false;
459 }
460 });
461 attachFilePopup.show();
462 break;
463 case R.id.action_add:
464 startActivity(new Intent(this, StartConversationActivity.class));
465 break;
466 case R.id.action_archive:
467 this.endConversation(getSelectedConversation());
468 break;
469 case R.id.action_contact_details:
470 Contact contact = this.getSelectedConversation().getContact();
471 if (contact.showInRoster()) {
472 switchToContactDetails(contact);
473 } else {
474 showAddToRosterDialog(getSelectedConversation());
475 }
476 break;
477 case R.id.action_muc_details:
478 Intent intent = new Intent(this, ConferenceDetailsActivity.class);
479 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
480 intent.putExtra("uuid", getSelectedConversation().getUuid());
481 startActivity(intent);
482 break;
483 case R.id.action_invite:
484 inviteToConversation(getSelectedConversation());
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.onConversationUpdate();
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, StartConversationActivity.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 xmppConnectionService.populateWithOrderedConversations(conversationList);
809 listView.invalidateViews();
810 }
811
812 public boolean showLastseen() {
813 if (getSelectedConversation() == null) {
814 return false;
815 } else {
816 return this.showLastseen
817 && getSelectedConversation().getMode() == Conversation.MODE_SINGLE;
818 }
819 }
820
821 public void runIntent(PendingIntent pi, int requestCode) {
822 try {
823 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
824 null, 0, 0, 0);
825 } catch (SendIntentException e1) {
826 Log.d("xmppService", "failed to start intent to send message");
827 }
828 }
829
830 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
831 private final WeakReference<ImageView> imageViewReference;
832 private Message message = null;
833
834 public BitmapWorkerTask(ImageView imageView) {
835 imageViewReference = new WeakReference<ImageView>(imageView);
836 }
837
838 @Override
839 protected Bitmap doInBackground(Message... params) {
840 message = params[0];
841 try {
842 return xmppConnectionService.getFileBackend().getThumbnail(
843 message, (int) (metrics.density * 288), false);
844 } catch (FileNotFoundException e) {
845 Log.d("xmppService", "file not found!");
846 return null;
847 }
848 }
849
850 @Override
851 protected void onPostExecute(Bitmap bitmap) {
852 if (imageViewReference != null && bitmap != null) {
853 final ImageView imageView = imageViewReference.get();
854 if (imageView != null) {
855 imageView.setImageBitmap(bitmap);
856 imageView.setBackgroundColor(0x00000000);
857 }
858 }
859 }
860 }
861
862 public void loadBitmap(Message message, ImageView imageView) {
863 Bitmap bm;
864 try {
865 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
866 (int) (metrics.density * 288), true);
867 } catch (FileNotFoundException e) {
868 bm = null;
869 }
870 if (bm != null) {
871 imageView.setImageBitmap(bm);
872 imageView.setBackgroundColor(0x00000000);
873 } else {
874 if (cancelPotentialWork(message, imageView)) {
875 imageView.setBackgroundColor(0xff333333);
876 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
877 final AsyncDrawable asyncDrawable = new AsyncDrawable(
878 getResources(), null, task);
879 imageView.setImageDrawable(asyncDrawable);
880 task.execute(message);
881 }
882 }
883 }
884
885 public static boolean cancelPotentialWork(Message message,
886 ImageView imageView) {
887 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
888
889 if (bitmapWorkerTask != null) {
890 final Message oldMessage = bitmapWorkerTask.message;
891 if (oldMessage == null || message != oldMessage) {
892 bitmapWorkerTask.cancel(true);
893 } else {
894 return false;
895 }
896 }
897 return true;
898 }
899
900 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
901 if (imageView != null) {
902 final Drawable drawable = imageView.getDrawable();
903 if (drawable instanceof AsyncDrawable) {
904 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
905 return asyncDrawable.getBitmapWorkerTask();
906 }
907 }
908 return null;
909 }
910
911 static class AsyncDrawable extends BitmapDrawable {
912 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
913
914 public AsyncDrawable(Resources res, Bitmap bitmap,
915 BitmapWorkerTask bitmapWorkerTask) {
916 super(res, bitmap);
917 bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
918 bitmapWorkerTask);
919 }
920
921 public BitmapWorkerTask getBitmapWorkerTask() {
922 return bitmapWorkerTaskReference.get();
923 }
924 }
925
926 public void encryptTextMessage(Message message) {
927 xmppConnectionService.getPgpEngine().encrypt(message,
928 new UiCallback<Message>() {
929
930 @Override
931 public void userInputRequried(PendingIntent pi,
932 Message message) {
933 activity.runIntent(pi,
934 ConversationActivity.REQUEST_SEND_MESSAGE);
935 }
936
937 @Override
938 public void success(Message message) {
939 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
940 xmppConnectionService.sendMessage(message);
941 }
942
943 @Override
944 public void error(int error, Message message) {
945
946 }
947 });
948 }
949}