1package eu.siacs.conversations.ui;
2
3import java.io.FileNotFoundException;
4import java.lang.ref.WeakReference;
5import java.util.ArrayList;
6import java.util.Hashtable;
7import java.util.List;
8
9import eu.siacs.conversations.R;
10import eu.siacs.conversations.entities.Account;
11import eu.siacs.conversations.entities.Contact;
12import eu.siacs.conversations.entities.Conversation;
13import eu.siacs.conversations.entities.Message;
14import eu.siacs.conversations.services.ImageProvider;
15import eu.siacs.conversations.utils.ExceptionHelper;
16import eu.siacs.conversations.utils.UIHelper;
17import android.net.Uri;
18import android.os.AsyncTask;
19import android.os.Bundle;
20import android.preference.PreferenceManager;
21import android.provider.MediaStore;
22import android.app.AlertDialog;
23import android.app.FragmentTransaction;
24import android.app.PendingIntent;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.DialogInterface.OnClickListener;
28import android.content.IntentSender.SendIntentException;
29import android.content.Intent;
30import android.content.SharedPreferences;
31import android.content.res.Resources;
32import android.graphics.Bitmap;
33import android.graphics.Color;
34import android.graphics.Typeface;
35import android.graphics.drawable.BitmapDrawable;
36import android.graphics.drawable.Drawable;
37import android.support.v4.widget.SlidingPaneLayout;
38import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
39import android.util.DisplayMetrics;
40import android.util.Log;
41import android.view.KeyEvent;
42import android.view.LayoutInflater;
43import android.view.Menu;
44import android.view.MenuItem;
45import android.view.View;
46import android.view.ViewGroup;
47import android.widget.AdapterView;
48import android.widget.AdapterView.OnItemClickListener;
49import android.widget.ArrayAdapter;
50import android.widget.CheckBox;
51import android.widget.ListView;
52import android.widget.PopupMenu;
53import android.widget.PopupMenu.OnMenuItemClickListener;
54import android.widget.TextView;
55import android.widget.ImageView;
56import android.widget.Toast;
57
58public class ConversationActivity extends XmppActivity {
59
60 public static final String VIEW_CONVERSATION = "viewConversation";
61 public static final String CONVERSATION = "conversationUuid";
62 public static final String TEXT = "text";
63 public static final String PRESENCE = "eu.siacs.conversations.presence";
64
65 public static final int REQUEST_SEND_MESSAGE = 0x75441;
66 public static final int REQUEST_DECRYPT_PGP = 0x76783;
67 private static final int REQUEST_ATTACH_FILE_DIALOG = 0x48502;
68 private static final int REQUEST_IMAGE_CAPTURE = 0x33788;
69 private static final int REQUEST_RECORD_AUDIO = 0x46189;
70 private static final int REQUEST_SEND_PGP_IMAGE = 0x53883;
71 public static final int REQUEST_ENCRYPT_MESSAGE = 0x378018;
72
73 private static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x92734;
74 private static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x84123;
75 private static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x75291;
76
77 protected SlidingPaneLayout spl;
78
79 private List<Conversation> conversationList = new ArrayList<Conversation>();
80 private Conversation selectedConversation = null;
81 private ListView listView;
82
83 private boolean paneShouldBeOpen = true;
84 private boolean useSubject = true;
85 private boolean showLastseen = false;
86 private ArrayAdapter<Conversation> listAdapter;
87
88 private OnConversationListChangedListener onConvChanged = new OnConversationListChangedListener() {
89
90 @Override
91 public void onConversationListChanged() {
92 runOnUiThread(new Runnable() {
93
94 @Override
95 public void run() {
96 updateConversationList();
97 if (paneShouldBeOpen) {
98 if (conversationList.size() >= 1) {
99 swapConversationFragment();
100 } else {
101 startActivity(new Intent(getApplicationContext(),
102 ContactsActivity.class));
103 finish();
104 }
105 }
106 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
107 .findFragmentByTag("conversation");
108 if (selectedFragment != null) {
109 selectedFragment.updateMessages();
110 }
111 }
112 });
113 }
114 };
115
116 protected ConversationActivity activity = this;
117 private DisplayMetrics metrics;
118 private Toast prepareImageToast;
119
120 public List<Conversation> getConversationList() {
121 return this.conversationList;
122 }
123
124 public Conversation getSelectedConversation() {
125 return this.selectedConversation;
126 }
127
128 public void setSelectedConversation(Conversation conversation) {
129 this.selectedConversation = conversation;
130 }
131
132 public ListView getConversationListView() {
133 return this.listView;
134 }
135
136 public SlidingPaneLayout getSlidingPaneLayout() {
137 return this.spl;
138 }
139
140 public boolean shouldPaneBeOpen() {
141 return paneShouldBeOpen;
142 }
143
144 @Override
145 protected void onCreate(Bundle savedInstanceState) {
146
147 metrics = getResources().getDisplayMetrics();
148
149 super.onCreate(savedInstanceState);
150
151 setContentView(R.layout.fragment_conversations_overview);
152
153 listView = (ListView) findViewById(R.id.list);
154
155 this.listAdapter = new ArrayAdapter<Conversation>(this,
156 R.layout.conversation_list_row, conversationList) {
157 @Override
158 public View getView(int position, View view, ViewGroup parent) {
159 if (view == null) {
160 LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
161 view = (View) inflater.inflate(
162 R.layout.conversation_list_row, null);
163 }
164 Conversation conv;
165 if (conversationList.size() > position) {
166 conv = getItem(position);
167 } else {
168 return view;
169 }
170 if (!spl.isSlideable()) {
171 if (conv == getSelectedConversation()) {
172 view.setBackgroundColor(0xffdddddd);
173 } else {
174 view.setBackgroundColor(Color.TRANSPARENT);
175 }
176 } else {
177 view.setBackgroundColor(Color.TRANSPARENT);
178 }
179 TextView convName = (TextView) view
180 .findViewById(R.id.conversation_name);
181 convName.setText(conv.getName(useSubject));
182 TextView convLastMsg = (TextView) view
183 .findViewById(R.id.conversation_lastmsg);
184 ImageView imagePreview = (ImageView) view
185 .findViewById(R.id.conversation_lastimage);
186
187 Message latestMessage = conv.getLatestMessage();
188
189 if (latestMessage.getType() == Message.TYPE_TEXT) {
190 if ((latestMessage.getEncryption() != Message.ENCRYPTION_PGP)
191 && (latestMessage.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED)) {
192 convLastMsg.setText(conv.getLatestMessage().getBody());
193 } else {
194 convLastMsg
195 .setText(getText(R.string.encrypted_message_received));
196 }
197 convLastMsg.setVisibility(View.VISIBLE);
198 imagePreview.setVisibility(View.GONE);
199 } else if (latestMessage.getType() == Message.TYPE_IMAGE) {
200 if (latestMessage.getStatus() >= Message.STATUS_RECIEVED) {
201 convLastMsg.setVisibility(View.GONE);
202 imagePreview.setVisibility(View.VISIBLE);
203 loadBitmap(latestMessage, imagePreview);
204 } else {
205 convLastMsg.setVisibility(View.VISIBLE);
206 imagePreview.setVisibility(View.GONE);
207 if (latestMessage.getStatus() == Message.STATUS_RECEIVED_OFFER) {
208 convLastMsg
209 .setText(getText(R.string.image_offered_for_download));
210 } else if (latestMessage.getStatus() == Message.STATUS_RECIEVING) {
211 convLastMsg
212 .setText(getText(R.string.receiving_image));
213 } else {
214 convLastMsg.setText("");
215 }
216 }
217 }
218
219 if (!conv.isRead()) {
220 convName.setTypeface(null, Typeface.BOLD);
221 convLastMsg.setTypeface(null, Typeface.BOLD);
222 } else {
223 convName.setTypeface(null, Typeface.NORMAL);
224 convLastMsg.setTypeface(null, Typeface.NORMAL);
225 }
226
227 ((TextView) view.findViewById(R.id.conversation_lastupdate))
228 .setText(UIHelper.readableTimeDifference(getContext(),
229 conv.getLatestMessage().getTimeSent()));
230
231 ImageView profilePicture = (ImageView) view
232 .findViewById(R.id.conversation_image);
233 profilePicture.setImageBitmap(UIHelper.getContactPicture(conv,
234 56, activity.getApplicationContext(), false));
235
236 return view;
237 }
238
239 };
240
241 listView.setAdapter(this.listAdapter);
242
243 listView.setOnItemClickListener(new OnItemClickListener() {
244
245 @Override
246 public void onItemClick(AdapterView<?> arg0, View clickedView,
247 int position, long arg3) {
248 paneShouldBeOpen = false;
249 if (getSelectedConversation() != conversationList.get(position)) {
250 setSelectedConversation(conversationList.get(position));
251 swapConversationFragment(); // .onBackendConnected(conversationList.get(position));
252 } else {
253 spl.closePane();
254 }
255 }
256 });
257 spl = (SlidingPaneLayout) findViewById(R.id.slidingpanelayout);
258 spl.setParallaxDistance(150);
259 spl.setShadowResource(R.drawable.es_slidingpane_shadow);
260 spl.setSliderFadeColor(0);
261 spl.setPanelSlideListener(new PanelSlideListener() {
262
263 @Override
264 public void onPanelOpened(View arg0) {
265 paneShouldBeOpen = true;
266 getActionBar().setDisplayHomeAsUpEnabled(false);
267 getActionBar().setHomeButtonEnabled(false);
268 getActionBar().setTitle(R.string.app_name);
269 invalidateOptionsMenu();
270 hideKeyboard();
271 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
272 .findFragmentByTag("conversation");
273 if (selectedFragment != null) {
274 selectedFragment.lastSeen.setVisibility(View.GONE);
275 }
276 }
277
278 @Override
279 public void onPanelClosed(View arg0) {
280 paneShouldBeOpen = false;
281 if ((conversationList.size() > 0)
282 && (getSelectedConversation() != null)) {
283 getActionBar().setDisplayHomeAsUpEnabled(true);
284 getActionBar().setHomeButtonEnabled(true);
285 getActionBar().setTitle(
286 getSelectedConversation().getName(useSubject));
287 invalidateOptionsMenu();
288 if (!getSelectedConversation().isRead()) {
289 xmppConnectionService
290 .markRead(getSelectedConversation());
291 UIHelper.updateNotification(getApplicationContext(),
292 getConversationList(), null, false);
293 listView.invalidateViews();
294 }
295 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
296 .findFragmentByTag("conversation");
297 if ((selectedFragment != null) && (showLastseen())) {
298 selectedFragment.lastSeen.setVisibility(View.VISIBLE);
299 }
300 }
301 }
302
303 @Override
304 public void onPanelSlide(View arg0, float arg1) {
305 // TODO Auto-generated method stub
306
307 }
308 });
309 }
310
311 @Override
312 public boolean onCreateOptionsMenu(Menu menu) {
313 getMenuInflater().inflate(R.menu.conversations, menu);
314 MenuItem menuSecure = (MenuItem) menu.findItem(R.id.action_security);
315 MenuItem menuArchive = (MenuItem) menu.findItem(R.id.action_archive);
316 MenuItem menuMucDetails = (MenuItem) menu
317 .findItem(R.id.action_muc_details);
318 MenuItem menuContactDetails = (MenuItem) menu
319 .findItem(R.id.action_contact_details);
320 MenuItem menuInviteContacts = (MenuItem) menu
321 .findItem(R.id.action_invite);
322 MenuItem menuAttach = (MenuItem) menu.findItem(R.id.action_attach_file);
323 MenuItem menuClearHistory = (MenuItem) menu
324 .findItem(R.id.action_clear_history);
325
326 if ((spl.isOpen() && (spl.isSlideable()))) {
327 menuArchive.setVisible(false);
328 menuMucDetails.setVisible(false);
329 menuContactDetails.setVisible(false);
330 menuSecure.setVisible(false);
331 menuInviteContacts.setVisible(false);
332 menuAttach.setVisible(false);
333 menuClearHistory.setVisible(false);
334 } else {
335 ((MenuItem) menu.findItem(R.id.action_add)).setVisible(!spl
336 .isSlideable());
337 if (this.getSelectedConversation() != null) {
338 if (this.getSelectedConversation().getLatestMessage()
339 .getEncryption() != Message.ENCRYPTION_NONE) {
340 menuSecure.setIcon(R.drawable.ic_action_secure);
341 }
342 if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
343 menuContactDetails.setVisible(false);
344 menuAttach.setVisible(false);
345 } else {
346 menuMucDetails.setVisible(false);
347 menuInviteContacts.setVisible(false);
348 }
349 }
350 }
351 return true;
352 }
353
354 private void selectPresenceToAttachFile(final int attachmentChoice) {
355 selectPresence(getSelectedConversation(), new OnPresenceSelected() {
356
357 @Override
358 public void onPresenceSelected(boolean success, String presence) {
359 if (success) {
360 if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO) {
361 Intent takePictureIntent = new Intent(
362 MediaStore.ACTION_IMAGE_CAPTURE);
363 takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
364 ImageProvider.getIncomingContentUri());
365 if (takePictureIntent
366 .resolveActivity(getPackageManager()) != null) {
367 startActivityForResult(takePictureIntent,
368 REQUEST_IMAGE_CAPTURE);
369 }
370 } else if (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
371 Intent attachFileIntent = new Intent();
372 attachFileIntent.setType("image/*");
373 attachFileIntent.setAction(Intent.ACTION_GET_CONTENT);
374 Intent chooser = Intent.createChooser(attachFileIntent,
375 getString(R.string.attach_file));
376 startActivityForResult(chooser,
377 REQUEST_ATTACH_FILE_DIALOG);
378 } else if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
379 Intent intent = new Intent(
380 MediaStore.Audio.Media.RECORD_SOUND_ACTION);
381 startActivityForResult(intent, REQUEST_RECORD_AUDIO);
382 }
383 }
384 }
385
386 @Override
387 public void onSendPlainTextInstead() {
388 // TODO Auto-generated method stub
389
390 }
391 }, "file");
392 }
393
394 private void attachFile(final int attachmentChoice) {
395 final Conversation conversation = getSelectedConversation();
396 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
397 if (hasPgp()) {
398 if (conversation.getContact().getPgpKeyId() != 0) {
399 xmppConnectionService.getPgpEngine().hasKey(
400 conversation.getContact(),
401 new UiCallback<Contact>() {
402
403 @Override
404 public void userInputRequried(PendingIntent pi,
405 Contact contact) {
406 ConversationActivity.this.runIntent(pi,
407 attachmentChoice);
408 }
409
410 @Override
411 public void success(Contact contact) {
412 selectPresenceToAttachFile(attachmentChoice);
413 }
414
415 @Override
416 public void error(int error, Contact contact) {
417 displayErrorDialog(error);
418 }
419 });
420 } else {
421 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
422 .findFragmentByTag("conversation");
423 if (fragment != null) {
424 fragment.showNoPGPKeyDialog(false,
425 new OnClickListener() {
426
427 @Override
428 public void onClick(DialogInterface dialog,
429 int which) {
430 conversation
431 .setNextEncryption(Message.ENCRYPTION_NONE);
432 selectPresenceToAttachFile(attachmentChoice);
433 }
434 });
435 }
436 }
437 }
438 } else if (getSelectedConversation().getNextEncryption() == Message.ENCRYPTION_NONE) {
439 selectPresenceToAttachFile(attachmentChoice);
440 } else {
441 AlertDialog.Builder builder = new AlertDialog.Builder(this);
442 builder.setTitle(getString(R.string.otr_file_transfer));
443 builder.setMessage(getString(R.string.otr_file_transfer_msg));
444 builder.setNegativeButton(getString(R.string.cancel), null);
445 if (conversation.getContact().getPgpKeyId() == 0) {
446 builder.setPositiveButton(getString(R.string.send_unencrypted),
447 new OnClickListener() {
448
449 @Override
450 public void onClick(DialogInterface dialog,
451 int which) {
452 conversation
453 .setNextEncryption(Message.ENCRYPTION_NONE);
454 attachFile(attachmentChoice);
455 }
456 });
457 } else {
458 builder.setPositiveButton(
459 getString(R.string.use_pgp_encryption),
460 new OnClickListener() {
461
462 @Override
463 public void onClick(DialogInterface dialog,
464 int which) {
465 conversation
466 .setNextEncryption(Message.ENCRYPTION_PGP);
467 attachFile(attachmentChoice);
468 }
469 });
470 }
471 builder.create().show();
472 }
473 }
474
475 @Override
476 public boolean onOptionsItemSelected(MenuItem item) {
477 switch (item.getItemId()) {
478 case android.R.id.home:
479 spl.openPane();
480 break;
481 case R.id.action_attach_file:
482 View menuAttachFile = findViewById(R.id.action_attach_file);
483 PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
484 attachFilePopup.inflate(R.menu.attachment_choices);
485 attachFilePopup
486 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
487
488 @Override
489 public boolean onMenuItemClick(MenuItem item) {
490 switch (item.getItemId()) {
491 case R.id.attach_choose_picture:
492 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
493 break;
494 case R.id.attach_take_picture:
495 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
496 break;
497 case R.id.attach_record_voice:
498 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
499 break;
500 }
501 return false;
502 }
503 });
504 attachFilePopup.show();
505 break;
506 case R.id.action_add:
507 startActivity(new Intent(this, ContactsActivity.class));
508 break;
509 case R.id.action_archive:
510 this.endConversation(getSelectedConversation());
511 break;
512 case R.id.action_contact_details:
513 Contact contact = this.getSelectedConversation().getContact();
514 if (contact.showInRoster()) {
515 Intent intent = new Intent(this, ContactDetailsActivity.class);
516 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
517 intent.putExtra("account", this.getSelectedConversation()
518 .getAccount().getJid());
519 intent.putExtra("contact", contact.getJid());
520 startActivity(intent);
521 } else {
522 showAddToRosterDialog(getSelectedConversation());
523 }
524 break;
525 case R.id.action_muc_details:
526 Intent intent = new Intent(this, MucDetailsActivity.class);
527 intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC);
528 intent.putExtra("uuid", getSelectedConversation().getUuid());
529 startActivity(intent);
530 break;
531 case R.id.action_invite:
532 Intent inviteIntent = new Intent(getApplicationContext(),
533 ContactsActivity.class);
534 inviteIntent.setAction("invite");
535 inviteIntent.putExtra("uuid", getSelectedConversation().getUuid());
536 startActivity(inviteIntent);
537 break;
538 case R.id.action_security:
539 final Conversation conversation = getSelectedConversation();
540 View menuItemView = findViewById(R.id.action_security);
541 PopupMenu popup = new PopupMenu(this, menuItemView);
542 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
543 .findFragmentByTag("conversation");
544 if (fragment != null) {
545 popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
546
547 @Override
548 public boolean onMenuItemClick(MenuItem item) {
549 switch (item.getItemId()) {
550 case R.id.encryption_choice_none:
551 conversation
552 .setNextEncryption(Message.ENCRYPTION_NONE);
553 item.setChecked(true);
554 break;
555 case R.id.encryption_choice_otr:
556 conversation
557 .setNextEncryption(Message.ENCRYPTION_OTR);
558 item.setChecked(true);
559 break;
560 case R.id.encryption_choice_pgp:
561 if (hasPgp()) {
562 if (conversation.getAccount().getKeys()
563 .has("pgp_signature")) {
564 conversation
565 .setNextEncryption(Message.ENCRYPTION_PGP);
566 item.setChecked(true);
567 } else {
568 announcePgp(conversation.getAccount(),
569 conversation);
570 }
571 }
572 break;
573 default:
574 conversation
575 .setNextEncryption(Message.ENCRYPTION_NONE);
576 break;
577 }
578 fragment.updateChatMsgHint();
579 return true;
580 }
581 });
582 popup.inflate(R.menu.encryption_choices);
583 MenuItem otr = popup.getMenu().findItem(
584 R.id.encryption_choice_otr);
585 if (conversation.getMode() == Conversation.MODE_MULTI) {
586 otr.setEnabled(false);
587 }
588 switch (conversation.getNextEncryption()) {
589 case Message.ENCRYPTION_NONE:
590 popup.getMenu().findItem(R.id.encryption_choice_none)
591 .setChecked(true);
592 break;
593 case Message.ENCRYPTION_OTR:
594 otr.setChecked(true);
595 break;
596 case Message.ENCRYPTION_PGP:
597 popup.getMenu().findItem(R.id.encryption_choice_pgp)
598 .setChecked(true);
599 break;
600 default:
601 popup.getMenu().findItem(R.id.encryption_choice_none)
602 .setChecked(true);
603 break;
604 }
605 popup.show();
606 }
607
608 break;
609 case R.id.action_clear_history:
610 clearHistoryDialog(getSelectedConversation());
611 break;
612 default:
613 break;
614 }
615 return super.onOptionsItemSelected(item);
616 }
617
618 private void endConversation(Conversation conversation) {
619 conversation.setStatus(Conversation.STATUS_ARCHIVED);
620 paneShouldBeOpen = true;
621 spl.openPane();
622 xmppConnectionService.archiveConversation(conversation);
623 if (conversationList.size() > 0) {
624 setSelectedConversation(conversationList.get(0));
625 } else {
626 setSelectedConversation(null);
627 }
628 }
629
630 protected void clearHistoryDialog(final Conversation conversation) {
631 AlertDialog.Builder builder = new AlertDialog.Builder(this);
632 builder.setTitle(getString(R.string.clear_conversation_history));
633 View dialogView = getLayoutInflater().inflate(
634 R.layout.dialog_clear_history, null);
635 final CheckBox endConversationCheckBox = (CheckBox) dialogView
636 .findViewById(R.id.end_conversation_checkbox);
637 builder.setView(dialogView);
638 builder.setNegativeButton(getString(R.string.cancel), null);
639 builder.setPositiveButton(getString(R.string.delete_messages),
640 new OnClickListener() {
641
642 @Override
643 public void onClick(DialogInterface dialog, int which) {
644 activity.xmppConnectionService
645 .clearConversationHistory(conversation);
646 if (endConversationCheckBox.isChecked()) {
647 endConversation(conversation);
648 }
649 }
650 });
651 builder.create().show();
652 }
653
654 protected ConversationFragment swapConversationFragment() {
655 ConversationFragment selectedFragment = new ConversationFragment();
656
657 FragmentTransaction transaction = getFragmentManager()
658 .beginTransaction();
659 transaction.replace(R.id.selected_conversation, selectedFragment,
660 "conversation");
661 transaction.commit();
662 return selectedFragment;
663 }
664
665 @Override
666 public boolean onKeyDown(int keyCode, KeyEvent event) {
667 if (keyCode == KeyEvent.KEYCODE_BACK) {
668 if (!spl.isOpen()) {
669 spl.openPane();
670 return false;
671 }
672 }
673 return super.onKeyDown(keyCode, event);
674 }
675
676 @Override
677 protected void onNewIntent(Intent intent) {
678 if ((Intent.ACTION_VIEW.equals(intent.getAction()) && (VIEW_CONVERSATION
679 .equals(intent.getType())))) {
680 String convToView = (String) intent.getExtras().get(CONVERSATION);
681 updateConversationList();
682 for (int i = 0; i < conversationList.size(); ++i) {
683 if (conversationList.get(i).getUuid().equals(convToView)) {
684 setSelectedConversation(conversationList.get(i));
685 break;
686 }
687 }
688 paneShouldBeOpen = false;
689 String text = intent.getExtras().getString(TEXT, null);
690 swapConversationFragment().setText(text);
691 }
692 }
693
694 @Override
695 public void onStart() {
696 super.onStart();
697 SharedPreferences preferences = PreferenceManager
698 .getDefaultSharedPreferences(this);
699 this.useSubject = preferences.getBoolean("use_subject_in_muc", true);
700 this.showLastseen = preferences.getBoolean("show_last_seen", false);
701 if (this.xmppConnectionServiceBound) {
702 this.onBackendConnected();
703 }
704 if (conversationList.size() >= 1) {
705 onConvChanged.onConversationListChanged();
706 }
707 }
708
709 @Override
710 protected void onStop() {
711 if (xmppConnectionServiceBound) {
712 xmppConnectionService.removeOnConversationListChangedListener();
713 }
714 super.onStop();
715 }
716
717 @Override
718 void onBackendConnected() {
719 this.registerListener();
720 if (conversationList.size() == 0) {
721 updateConversationList();
722 }
723
724 if ((getIntent().getAction() != null)
725 && (getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) {
726 if (getIntent().getType().equals(
727 ConversationActivity.VIEW_CONVERSATION)) {
728 handledViewIntent = true;
729
730 String convToView = (String) getIntent().getExtras().get(
731 CONVERSATION);
732
733 for (int i = 0; i < conversationList.size(); ++i) {
734 if (conversationList.get(i).getUuid().equals(convToView)) {
735 setSelectedConversation(conversationList.get(i));
736 }
737 }
738 paneShouldBeOpen = false;
739 String text = getIntent().getExtras().getString(TEXT, null);
740 swapConversationFragment().setText(text);
741 }
742 } else {
743 if (xmppConnectionService.getAccounts().size() == 0) {
744 startActivity(new Intent(this, ManageAccountActivity.class));
745 finish();
746 } else if (conversationList.size() <= 0) {
747 // add no history
748 startActivity(new Intent(this, ContactsActivity.class));
749 finish();
750 } else {
751 spl.openPane();
752 // find currently loaded fragment
753 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
754 .findFragmentByTag("conversation");
755 if (selectedFragment != null) {
756 selectedFragment.onBackendConnected();
757 } else {
758 setSelectedConversation(conversationList.get(0));
759 swapConversationFragment();
760 }
761 ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
762 }
763 }
764 }
765
766 public void registerListener() {
767 if (xmppConnectionServiceBound) {
768 xmppConnectionService
769 .setOnConversationListChangedListener(this.onConvChanged);
770 }
771 }
772
773 @Override
774 protected void onActivityResult(int requestCode, int resultCode,
775 final Intent data) {
776 super.onActivityResult(requestCode, resultCode, data);
777 if (resultCode == RESULT_OK) {
778 if (requestCode == REQUEST_DECRYPT_PGP) {
779 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
780 .findFragmentByTag("conversation");
781 if (selectedFragment != null) {
782 selectedFragment.hidePgpPassphraseBox();
783 }
784 } else if (requestCode == REQUEST_ATTACH_FILE_DIALOG) {
785 attachImageToConversation(getSelectedConversation(),
786 data.getData());
787 } else if (requestCode == REQUEST_SEND_PGP_IMAGE) {
788
789 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
790 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
791 } else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
792 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
793 } else if (requestCode == REQUEST_ANNOUNCE_PGP) {
794 announcePgp(getSelectedConversation().getAccount(),
795 getSelectedConversation());
796 } else if (requestCode == REQUEST_ENCRYPT_MESSAGE) {
797 // encryptTextMessage();
798 } else if (requestCode == REQUEST_IMAGE_CAPTURE) {
799 attachImageToConversation(getSelectedConversation(), null);
800 } else if (requestCode == REQUEST_RECORD_AUDIO) {
801 Log.d("xmppService", data.getData().toString());
802 attachAudioToConversation(getSelectedConversation(),
803 data.getData());
804 } else {
805 Log.d(LOGTAG, "unknown result code:" + requestCode);
806 }
807 }
808 }
809
810 private void attachAudioToConversation(Conversation conversation, Uri uri) {
811
812 }
813
814 private void attachImageToConversation(Conversation conversation, Uri uri) {
815 prepareImageToast = Toast.makeText(getApplicationContext(),
816 getText(R.string.preparing_image), Toast.LENGTH_LONG);
817 prepareImageToast.show();
818 xmppConnectionService.attachImageToConversation(conversation, uri,
819 new UiCallback<Message>() {
820
821 @Override
822 public void userInputRequried(PendingIntent pi,
823 Message object) {
824 hidePrepareImageToast();
825 ConversationActivity.this.runIntent(pi,
826 ConversationActivity.REQUEST_SEND_PGP_IMAGE);
827 }
828
829 @Override
830 public void success(Message message) {
831 message.getConversation().getMessages().add(message);
832 xmppConnectionService.databaseBackend
833 .createMessage(message);
834 xmppConnectionService.sendMessage(message, null);
835 xmppConnectionService.updateUi(
836 message.getConversation(), false);
837 }
838
839 @Override
840 public void error(int error, Message message) {
841 hidePrepareImageToast();
842 displayErrorDialog(error);
843 }
844 });
845 }
846
847 private void hidePrepareImageToast() {
848 if (prepareImageToast != null) {
849 runOnUiThread(new Runnable() {
850
851 @Override
852 public void run() {
853 prepareImageToast.cancel();
854 }
855 });
856 }
857 }
858
859 public void updateConversationList() {
860 conversationList.clear();
861 conversationList.addAll(xmppConnectionService.getConversations());
862 listView.invalidateViews();
863 }
864
865 public void selectPresence(final Conversation conversation,
866 final OnPresenceSelected listener, String reason) {
867 Account account = conversation.getAccount();
868 if (account.getStatus() != Account.STATUS_ONLINE) {
869 AlertDialog.Builder builder = new AlertDialog.Builder(this);
870 builder.setTitle(getString(R.string.not_connected));
871 builder.setIconAttribute(android.R.attr.alertDialogIcon);
872 if ("otr".equals(reason)) {
873 builder.setMessage(getString(R.string.you_are_offline,
874 getString(R.string.otr_messages)));
875 } else if ("file".equals(reason)) {
876 builder.setMessage(getString(R.string.you_are_offline,
877 getString(R.string.files)));
878 } else {
879 builder.setMessage(getString(R.string.you_are_offline_blank));
880 }
881 builder.setNegativeButton(getString(R.string.cancel), null);
882 builder.setPositiveButton(getString(R.string.manage_account),
883 new OnClickListener() {
884
885 @Override
886 public void onClick(DialogInterface dialog, int which) {
887 startActivity(new Intent(activity,
888 ManageAccountActivity.class));
889 }
890 });
891 builder.create().show();
892 listener.onPresenceSelected(false, null);
893 } else {
894 Contact contact = conversation.getContact();
895 if (contact == null) {
896 showAddToRosterDialog(conversation);
897 listener.onPresenceSelected(false, null);
898 } else {
899 Hashtable<String, Integer> presences = contact.getPresences();
900 if (presences.size() == 0) {
901 AlertDialog.Builder builder = new AlertDialog.Builder(this);
902 builder.setTitle(getString(R.string.contact_offline));
903 if ("otr".equals(reason)) {
904 builder.setMessage(getString(R.string.contact_offline_otr));
905 builder.setPositiveButton(
906 getString(R.string.send_unencrypted),
907 new OnClickListener() {
908
909 @Override
910 public void onClick(DialogInterface dialog,
911 int which) {
912 listener.onSendPlainTextInstead();
913 }
914 });
915 } else if ("file".equals(reason)) {
916 builder.setMessage(getString(R.string.contact_offline_file));
917 }
918 builder.setIconAttribute(android.R.attr.alertDialogIcon);
919 builder.setNegativeButton(getString(R.string.cancel), null);
920 builder.create().show();
921 listener.onPresenceSelected(false, null);
922 } else if (presences.size() == 1) {
923 String presence = (String) presences.keySet().toArray()[0];
924 conversation.setNextPresence(presence);
925 listener.onPresenceSelected(true, presence);
926 } else {
927 AlertDialog.Builder builder = new AlertDialog.Builder(this);
928 builder.setTitle(getString(R.string.choose_presence));
929 final String[] presencesArray = new String[presences.size()];
930 presences.keySet().toArray(presencesArray);
931 builder.setItems(presencesArray,
932 new DialogInterface.OnClickListener() {
933
934 @Override
935 public void onClick(DialogInterface dialog,
936 int which) {
937 String presence = presencesArray[which];
938 conversation.setNextPresence(presence);
939 listener.onPresenceSelected(true, presence);
940 }
941 });
942 builder.create().show();
943 }
944 }
945 }
946 }
947
948 public boolean showLastseen() {
949 if (getSelectedConversation() == null) {
950 return false;
951 } else {
952 return this.showLastseen
953 && getSelectedConversation().getMode() == Conversation.MODE_SINGLE;
954 }
955 }
956
957 private void showAddToRosterDialog(final Conversation conversation) {
958 String jid = conversation.getContactJid();
959 AlertDialog.Builder builder = new AlertDialog.Builder(this);
960 builder.setTitle(jid);
961 builder.setMessage(getString(R.string.not_in_roster));
962 builder.setNegativeButton(getString(R.string.cancel), null);
963 builder.setPositiveButton(getString(R.string.add_contact),
964 new DialogInterface.OnClickListener() {
965
966 @Override
967 public void onClick(DialogInterface dialog, int which) {
968 String jid = conversation.getContactJid();
969 Account account = getSelectedConversation()
970 .getAccount();
971 Contact contact = account.getRoster().getContact(jid);
972 xmppConnectionService.createContact(contact);
973 }
974 });
975 builder.create().show();
976 }
977
978 public void runIntent(PendingIntent pi, int requestCode) {
979 try {
980 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
981 null, 0, 0, 0);
982 } catch (SendIntentException e1) {
983 Log.d("xmppService", "failed to start intent to send message");
984 }
985 }
986
987 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
988 private final WeakReference<ImageView> imageViewReference;
989 private Message message = null;
990
991 public BitmapWorkerTask(ImageView imageView) {
992 imageViewReference = new WeakReference<ImageView>(imageView);
993 }
994
995 @Override
996 protected Bitmap doInBackground(Message... params) {
997 message = params[0];
998 try {
999 return xmppConnectionService.getFileBackend().getThumbnail(
1000 message, (int) (metrics.density * 288), false);
1001 } catch (FileNotFoundException e) {
1002 Log.d("xmppService", "file not found!");
1003 return null;
1004 }
1005 }
1006
1007 @Override
1008 protected void onPostExecute(Bitmap bitmap) {
1009 if (imageViewReference != null && bitmap != null) {
1010 final ImageView imageView = imageViewReference.get();
1011 if (imageView != null) {
1012 imageView.setImageBitmap(bitmap);
1013 imageView.setBackgroundColor(0x00000000);
1014 }
1015 }
1016 }
1017 }
1018
1019 public void loadBitmap(Message message, ImageView imageView) {
1020 Bitmap bm;
1021 try {
1022 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1023 (int) (metrics.density * 288), true);
1024 } catch (FileNotFoundException e) {
1025 bm = null;
1026 }
1027 if (bm != null) {
1028 imageView.setImageBitmap(bm);
1029 imageView.setBackgroundColor(0x00000000);
1030 } else {
1031 if (cancelPotentialWork(message, imageView)) {
1032 imageView.setBackgroundColor(0xff333333);
1033 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1034 final AsyncDrawable asyncDrawable = new AsyncDrawable(
1035 getResources(), null, task);
1036 imageView.setImageDrawable(asyncDrawable);
1037 task.execute(message);
1038 }
1039 }
1040 }
1041
1042 public static boolean cancelPotentialWork(Message message,
1043 ImageView imageView) {
1044 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1045
1046 if (bitmapWorkerTask != null) {
1047 final Message oldMessage = bitmapWorkerTask.message;
1048 if (oldMessage == null || message != oldMessage) {
1049 bitmapWorkerTask.cancel(true);
1050 } else {
1051 return false;
1052 }
1053 }
1054 return true;
1055 }
1056
1057 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1058 if (imageView != null) {
1059 final Drawable drawable = imageView.getDrawable();
1060 if (drawable instanceof AsyncDrawable) {
1061 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1062 return asyncDrawable.getBitmapWorkerTask();
1063 }
1064 }
1065 return null;
1066 }
1067
1068 static class AsyncDrawable extends BitmapDrawable {
1069 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1070
1071 public AsyncDrawable(Resources res, Bitmap bitmap,
1072 BitmapWorkerTask bitmapWorkerTask) {
1073 super(res, bitmap);
1074 bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
1075 bitmapWorkerTask);
1076 }
1077
1078 public BitmapWorkerTask getBitmapWorkerTask() {
1079 return bitmapWorkerTaskReference.get();
1080 }
1081 }
1082
1083 public void encryptTextMessage(Message message) {
1084 xmppConnectionService.getPgpEngine().encrypt(message,
1085 new UiCallback<Message>() {
1086
1087 @Override
1088 public void userInputRequried(PendingIntent pi,
1089 Message message) {
1090 activity.runIntent(pi,
1091 ConversationActivity.REQUEST_SEND_MESSAGE);
1092 }
1093
1094 @Override
1095 public void success(Message message) {
1096 xmppConnectionService.sendMessage(message, null);
1097 }
1098
1099 @Override
1100 public void error(int error, Message message) {
1101
1102 }
1103 });
1104 }
1105}