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 public Message pendingMessage = null;
89
90 private OnConversationListChangedListener onConvChanged = new OnConversationListChangedListener() {
91
92 @Override
93 public void onConversationListChanged() {
94 runOnUiThread(new Runnable() {
95
96 @Override
97 public void run() {
98 updateConversationList();
99 if (paneShouldBeOpen) {
100 if (conversationList.size() >= 1) {
101 swapConversationFragment();
102 } else {
103 startActivity(new Intent(getApplicationContext(),
104 ContactsActivity.class));
105 finish();
106 }
107 }
108 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
109 .findFragmentByTag("conversation");
110 if (selectedFragment != null) {
111 selectedFragment.updateMessages();
112 }
113 }
114 });
115 }
116 };
117
118 protected ConversationActivity activity = this;
119 private DisplayMetrics metrics;
120 private Toast prepareImageToast;
121
122 public List<Conversation> getConversationList() {
123 return this.conversationList;
124 }
125
126 public Conversation getSelectedConversation() {
127 return this.selectedConversation;
128 }
129
130 public void setSelectedConversation(Conversation conversation) {
131 this.selectedConversation = conversation;
132 }
133
134 public ListView getConversationListView() {
135 return this.listView;
136 }
137
138 public SlidingPaneLayout getSlidingPaneLayout() {
139 return this.spl;
140 }
141
142 public boolean shouldPaneBeOpen() {
143 return paneShouldBeOpen;
144 }
145
146 @Override
147 protected void onCreate(Bundle savedInstanceState) {
148
149 metrics = getResources().getDisplayMetrics();
150
151 super.onCreate(savedInstanceState);
152
153 setContentView(R.layout.fragment_conversations_overview);
154
155 listView = (ListView) findViewById(R.id.list);
156
157 this.listAdapter = new ArrayAdapter<Conversation>(this,
158 R.layout.conversation_list_row, conversationList) {
159 @Override
160 public View getView(int position, View view, ViewGroup parent) {
161 if (view == null) {
162 LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
163 view = (View) inflater.inflate(
164 R.layout.conversation_list_row, null);
165 }
166 Conversation conv;
167 if (conversationList.size() > position) {
168 conv = getItem(position);
169 } else {
170 return view;
171 }
172 if (!spl.isSlideable()) {
173 if (conv == getSelectedConversation()) {
174 view.setBackgroundColor(0xffdddddd);
175 } else {
176 view.setBackgroundColor(Color.TRANSPARENT);
177 }
178 } else {
179 view.setBackgroundColor(Color.TRANSPARENT);
180 }
181 TextView convName = (TextView) view
182 .findViewById(R.id.conversation_name);
183 convName.setText(conv.getName(useSubject));
184 TextView convLastMsg = (TextView) view
185 .findViewById(R.id.conversation_lastmsg);
186 ImageView imagePreview = (ImageView) view
187 .findViewById(R.id.conversation_lastimage);
188
189 Message latestMessage = conv.getLatestMessage();
190
191 if (latestMessage.getType() == Message.TYPE_TEXT) {
192 if ((latestMessage.getEncryption() != Message.ENCRYPTION_PGP)
193 && (latestMessage.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED)) {
194 convLastMsg.setText(conv.getLatestMessage().getBody());
195 } else {
196 convLastMsg
197 .setText(getText(R.string.encrypted_message_received));
198 }
199 convLastMsg.setVisibility(View.VISIBLE);
200 imagePreview.setVisibility(View.GONE);
201 } else if (latestMessage.getType() == Message.TYPE_IMAGE) {
202 if (latestMessage.getStatus() >= Message.STATUS_RECIEVED) {
203 convLastMsg.setVisibility(View.GONE);
204 imagePreview.setVisibility(View.VISIBLE);
205 loadBitmap(latestMessage, imagePreview);
206 } else {
207 convLastMsg.setVisibility(View.VISIBLE);
208 imagePreview.setVisibility(View.GONE);
209 if (latestMessage.getStatus() == Message.STATUS_RECEIVED_OFFER) {
210 convLastMsg
211 .setText(getText(R.string.image_offered_for_download));
212 } else if (latestMessage.getStatus() == Message.STATUS_RECIEVING) {
213 convLastMsg
214 .setText(getText(R.string.receiving_image));
215 } else {
216 convLastMsg.setText("");
217 }
218 }
219 }
220
221 if (!conv.isRead()) {
222 convName.setTypeface(null, Typeface.BOLD);
223 convLastMsg.setTypeface(null, Typeface.BOLD);
224 } else {
225 convName.setTypeface(null, Typeface.NORMAL);
226 convLastMsg.setTypeface(null, Typeface.NORMAL);
227 }
228
229 ((TextView) view.findViewById(R.id.conversation_lastupdate))
230 .setText(UIHelper.readableTimeDifference(getContext(),
231 conv.getLatestMessage().getTimeSent()));
232
233 ImageView profilePicture = (ImageView) view
234 .findViewById(R.id.conversation_image);
235 profilePicture.setImageBitmap(UIHelper.getContactPicture(conv,
236 56, activity.getApplicationContext(), false));
237
238 return view;
239 }
240
241 };
242
243 listView.setAdapter(this.listAdapter);
244
245 listView.setOnItemClickListener(new OnItemClickListener() {
246
247 @Override
248 public void onItemClick(AdapterView<?> arg0, View clickedView,
249 int position, long arg3) {
250 paneShouldBeOpen = false;
251 if (getSelectedConversation() != conversationList.get(position)) {
252 setSelectedConversation(conversationList.get(position));
253 swapConversationFragment(); // .onBackendConnected(conversationList.get(position));
254 } else {
255 spl.closePane();
256 }
257 }
258 });
259 spl = (SlidingPaneLayout) findViewById(R.id.slidingpanelayout);
260 spl.setParallaxDistance(150);
261 spl.setShadowResource(R.drawable.es_slidingpane_shadow);
262 spl.setSliderFadeColor(0);
263 spl.setPanelSlideListener(new PanelSlideListener() {
264
265 @Override
266 public void onPanelOpened(View arg0) {
267 paneShouldBeOpen = true;
268 getActionBar().setDisplayHomeAsUpEnabled(false);
269 getActionBar().setHomeButtonEnabled(false);
270 getActionBar().setTitle(R.string.app_name);
271 invalidateOptionsMenu();
272 hideKeyboard();
273 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
274 .findFragmentByTag("conversation");
275 if (selectedFragment != null) {
276 selectedFragment.lastSeen.setVisibility(View.GONE);
277 }
278 }
279
280 @Override
281 public void onPanelClosed(View arg0) {
282 paneShouldBeOpen = false;
283 if ((conversationList.size() > 0)
284 && (getSelectedConversation() != null)) {
285 getActionBar().setDisplayHomeAsUpEnabled(true);
286 getActionBar().setHomeButtonEnabled(true);
287 getActionBar().setTitle(
288 getSelectedConversation().getName(useSubject));
289 invalidateOptionsMenu();
290 if (!getSelectedConversation().isRead()) {
291 xmppConnectionService
292 .markRead(getSelectedConversation());
293 UIHelper.updateNotification(getApplicationContext(),
294 getConversationList(), null, false);
295 listView.invalidateViews();
296 }
297 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
298 .findFragmentByTag("conversation");
299 if ((selectedFragment != null) && (showLastseen())) {
300 selectedFragment.lastSeen.setVisibility(View.VISIBLE);
301 }
302 }
303 }
304
305 @Override
306 public void onPanelSlide(View arg0, float arg1) {
307 // TODO Auto-generated method stub
308
309 }
310 });
311 }
312
313 @Override
314 public boolean onCreateOptionsMenu(Menu menu) {
315 getMenuInflater().inflate(R.menu.conversations, menu);
316 MenuItem menuSecure = (MenuItem) menu.findItem(R.id.action_security);
317 MenuItem menuArchive = (MenuItem) menu.findItem(R.id.action_archive);
318 MenuItem menuMucDetails = (MenuItem) menu
319 .findItem(R.id.action_muc_details);
320 MenuItem menuContactDetails = (MenuItem) menu
321 .findItem(R.id.action_contact_details);
322 MenuItem menuInviteContacts = (MenuItem) menu
323 .findItem(R.id.action_invite);
324 MenuItem menuAttach = (MenuItem) menu.findItem(R.id.action_attach_file);
325 MenuItem menuClearHistory = (MenuItem) menu
326 .findItem(R.id.action_clear_history);
327
328 if ((spl.isOpen() && (spl.isSlideable()))) {
329 menuArchive.setVisible(false);
330 menuMucDetails.setVisible(false);
331 menuContactDetails.setVisible(false);
332 menuSecure.setVisible(false);
333 menuInviteContacts.setVisible(false);
334 menuAttach.setVisible(false);
335 menuClearHistory.setVisible(false);
336 } else {
337 ((MenuItem) menu.findItem(R.id.action_add)).setVisible(!spl
338 .isSlideable());
339 if (this.getSelectedConversation() != null) {
340 if (this.getSelectedConversation().getLatestMessage()
341 .getEncryption() != Message.ENCRYPTION_NONE) {
342 menuSecure.setIcon(R.drawable.ic_action_secure);
343 }
344 if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
345 menuContactDetails.setVisible(false);
346 menuAttach.setVisible(false);
347 } else {
348 menuMucDetails.setVisible(false);
349 menuInviteContacts.setVisible(false);
350 }
351 }
352 }
353 return true;
354 }
355
356 private void selectPresenceToAttachFile(final int attachmentChoice) {
357 selectPresence(getSelectedConversation(), new OnPresenceSelected() {
358
359 @Override
360 public void onPresenceSelected(boolean success, String presence) {
361 if (success) {
362 if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO) {
363 Intent takePictureIntent = new Intent(
364 MediaStore.ACTION_IMAGE_CAPTURE);
365 takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
366 ImageProvider.getIncomingContentUri());
367 if (takePictureIntent
368 .resolveActivity(getPackageManager()) != null) {
369 startActivityForResult(takePictureIntent,
370 REQUEST_IMAGE_CAPTURE);
371 }
372 } else if (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
373 Intent attachFileIntent = new Intent();
374 attachFileIntent.setType("image/*");
375 attachFileIntent.setAction(Intent.ACTION_GET_CONTENT);
376 Intent chooser = Intent.createChooser(attachFileIntent,
377 getString(R.string.attach_file));
378 startActivityForResult(chooser,
379 REQUEST_ATTACH_FILE_DIALOG);
380 } else if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
381 Intent intent = new Intent(
382 MediaStore.Audio.Media.RECORD_SOUND_ACTION);
383 startActivityForResult(intent, REQUEST_RECORD_AUDIO);
384 }
385 }
386 }
387
388 @Override
389 public void onSendPlainTextInstead() {
390 // TODO Auto-generated method stub
391
392 }
393 }, "file");
394 }
395
396 private void attachFile(final int attachmentChoice) {
397 final Conversation conversation = getSelectedConversation();
398 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
399 if (hasPgp()) {
400 if (conversation.getContact().getPgpKeyId() != 0) {
401 xmppConnectionService.getPgpEngine().hasKey(
402 conversation.getContact(), new UiCallback() {
403
404 @Override
405 public void userInputRequried(PendingIntent pi) {
406 ConversationActivity.this.runIntent(pi,
407 attachmentChoice);
408 }
409
410 @Override
411 public void success() {
412 selectPresenceToAttachFile(attachmentChoice);
413 }
414
415 @Override
416 public void error(int error) {
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 pendingMessage = xmppConnectionService.attachImageToConversation(
819 conversation, uri, new UiCallback() {
820
821 @Override
822 public void userInputRequried(PendingIntent pi) {
823 hidePrepareImageToast();
824 ConversationActivity.this.runIntent(pi,
825 ConversationActivity.REQUEST_SEND_PGP_IMAGE);
826 }
827
828 @Override
829 public void success() {
830 sendPendingImageMessage();
831 hidePrepareImageToast();
832 }
833
834 @Override
835 public void error(int error) {
836 hidePrepareImageToast();
837 pendingMessage = null;
838 displayErrorDialog(error);
839 }
840 });
841 }
842
843 private void hidePrepareImageToast() {
844 if (prepareImageToast != null) {
845 runOnUiThread(new Runnable() {
846
847 @Override
848 public void run() {
849 prepareImageToast.cancel();
850 }
851 });
852 }
853 }
854
855 private void sendPendingImageMessage() {
856 pendingMessage.getConversation().getMessages().add(pendingMessage);
857 xmppConnectionService.databaseBackend.createMessage(pendingMessage);
858 xmppConnectionService.sendMessage(pendingMessage, null);
859 xmppConnectionService.updateUi(pendingMessage.getConversation(), false);
860 pendingMessage = null;
861 }
862
863 public void updateConversationList() {
864 conversationList.clear();
865 conversationList.addAll(xmppConnectionService.getConversations());
866 listView.invalidateViews();
867 }
868
869 public void selectPresence(final Conversation conversation,
870 final OnPresenceSelected listener, String reason) {
871 Account account = conversation.getAccount();
872 if (account.getStatus() != Account.STATUS_ONLINE) {
873 AlertDialog.Builder builder = new AlertDialog.Builder(this);
874 builder.setTitle(getString(R.string.not_connected));
875 builder.setIconAttribute(android.R.attr.alertDialogIcon);
876 if ("otr".equals(reason)) {
877 builder.setMessage(getString(R.string.you_are_offline,
878 getString(R.string.otr_messages)));
879 } else if ("file".equals(reason)) {
880 builder.setMessage(getString(R.string.you_are_offline,
881 getString(R.string.files)));
882 } else {
883 builder.setMessage(getString(R.string.you_are_offline_blank));
884 }
885 builder.setNegativeButton(getString(R.string.cancel), null);
886 builder.setPositiveButton(getString(R.string.manage_account),
887 new OnClickListener() {
888
889 @Override
890 public void onClick(DialogInterface dialog, int which) {
891 startActivity(new Intent(activity,
892 ManageAccountActivity.class));
893 }
894 });
895 builder.create().show();
896 listener.onPresenceSelected(false, null);
897 } else {
898 Contact contact = conversation.getContact();
899 if (contact == null) {
900 showAddToRosterDialog(conversation);
901 listener.onPresenceSelected(false, null);
902 } else {
903 Hashtable<String, Integer> presences = contact.getPresences();
904 if (presences.size() == 0) {
905 AlertDialog.Builder builder = new AlertDialog.Builder(this);
906 builder.setTitle(getString(R.string.contact_offline));
907 if ("otr".equals(reason)) {
908 builder.setMessage(getString(R.string.contact_offline_otr));
909 builder.setPositiveButton(
910 getString(R.string.send_unencrypted),
911 new OnClickListener() {
912
913 @Override
914 public void onClick(DialogInterface dialog,
915 int which) {
916 listener.onSendPlainTextInstead();
917 }
918 });
919 } else if ("file".equals(reason)) {
920 builder.setMessage(getString(R.string.contact_offline_file));
921 }
922 builder.setIconAttribute(android.R.attr.alertDialogIcon);
923 builder.setNegativeButton(getString(R.string.cancel), null);
924 builder.create().show();
925 listener.onPresenceSelected(false, null);
926 } else if (presences.size() == 1) {
927 String presence = (String) presences.keySet().toArray()[0];
928 conversation.setNextPresence(presence);
929 listener.onPresenceSelected(true, presence);
930 } else {
931 AlertDialog.Builder builder = new AlertDialog.Builder(this);
932 builder.setTitle(getString(R.string.choose_presence));
933 final String[] presencesArray = new String[presences.size()];
934 presences.keySet().toArray(presencesArray);
935 builder.setItems(presencesArray,
936 new DialogInterface.OnClickListener() {
937
938 @Override
939 public void onClick(DialogInterface dialog,
940 int which) {
941 String presence = presencesArray[which];
942 conversation.setNextPresence(presence);
943 listener.onPresenceSelected(true, presence);
944 }
945 });
946 builder.create().show();
947 }
948 }
949 }
950 }
951
952 public boolean showLastseen() {
953 if (getSelectedConversation() == null) {
954 return false;
955 } else {
956 return this.showLastseen
957 && getSelectedConversation().getMode() == Conversation.MODE_SINGLE;
958 }
959 }
960
961 private void showAddToRosterDialog(final Conversation conversation) {
962 String jid = conversation.getContactJid();
963 AlertDialog.Builder builder = new AlertDialog.Builder(this);
964 builder.setTitle(jid);
965 builder.setMessage(getString(R.string.not_in_roster));
966 builder.setNegativeButton(getString(R.string.cancel), null);
967 builder.setPositiveButton(getString(R.string.add_contact),
968 new DialogInterface.OnClickListener() {
969
970 @Override
971 public void onClick(DialogInterface dialog, int which) {
972 String jid = conversation.getContactJid();
973 Account account = getSelectedConversation()
974 .getAccount();
975 Contact contact = account.getRoster().getContact(jid);
976 xmppConnectionService.createContact(contact);
977 }
978 });
979 builder.create().show();
980 }
981
982 public void runIntent(PendingIntent pi, int requestCode) {
983 try {
984 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
985 null, 0, 0, 0);
986 } catch (SendIntentException e1) {
987 Log.d("xmppService", "failed to start intent to send message");
988 }
989 }
990
991 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
992 private final WeakReference<ImageView> imageViewReference;
993 private Message message = null;
994
995 public BitmapWorkerTask(ImageView imageView) {
996 imageViewReference = new WeakReference<ImageView>(imageView);
997 }
998
999 @Override
1000 protected Bitmap doInBackground(Message... params) {
1001 message = params[0];
1002 try {
1003 return xmppConnectionService.getFileBackend().getThumbnail(
1004 message, (int) (metrics.density * 288), false);
1005 } catch (FileNotFoundException e) {
1006 Log.d("xmppService", "file not found!");
1007 return null;
1008 }
1009 }
1010
1011 @Override
1012 protected void onPostExecute(Bitmap bitmap) {
1013 if (imageViewReference != null && bitmap != null) {
1014 final ImageView imageView = imageViewReference.get();
1015 if (imageView != null) {
1016 imageView.setImageBitmap(bitmap);
1017 imageView.setBackgroundColor(0x00000000);
1018 }
1019 }
1020 }
1021 }
1022
1023 public void loadBitmap(Message message, ImageView imageView) {
1024 Bitmap bm;
1025 try {
1026 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1027 (int) (metrics.density * 288), true);
1028 } catch (FileNotFoundException e) {
1029 bm = null;
1030 }
1031 if (bm != null) {
1032 imageView.setImageBitmap(bm);
1033 imageView.setBackgroundColor(0x00000000);
1034 } else {
1035 if (cancelPotentialWork(message, imageView)) {
1036 imageView.setBackgroundColor(0xff333333);
1037 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1038 final AsyncDrawable asyncDrawable = new AsyncDrawable(
1039 getResources(), null, task);
1040 imageView.setImageDrawable(asyncDrawable);
1041 task.execute(message);
1042 }
1043 }
1044 }
1045
1046 public static boolean cancelPotentialWork(Message message,
1047 ImageView imageView) {
1048 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1049
1050 if (bitmapWorkerTask != null) {
1051 final Message oldMessage = bitmapWorkerTask.message;
1052 if (oldMessage == null || message != oldMessage) {
1053 bitmapWorkerTask.cancel(true);
1054 } else {
1055 return false;
1056 }
1057 }
1058 return true;
1059 }
1060
1061 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1062 if (imageView != null) {
1063 final Drawable drawable = imageView.getDrawable();
1064 if (drawable instanceof AsyncDrawable) {
1065 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1066 return asyncDrawable.getBitmapWorkerTask();
1067 }
1068 }
1069 return null;
1070 }
1071
1072 static class AsyncDrawable extends BitmapDrawable {
1073 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1074
1075 public AsyncDrawable(Resources res, Bitmap bitmap,
1076 BitmapWorkerTask bitmapWorkerTask) {
1077 super(res, bitmap);
1078 bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
1079 bitmapWorkerTask);
1080 }
1081
1082 public BitmapWorkerTask getBitmapWorkerTask() {
1083 return bitmapWorkerTaskReference.get();
1084 }
1085 }
1086
1087 public void encryptTextMessage() {
1088 xmppConnectionService.getPgpEngine().encrypt(this.pendingMessage,
1089 new UiCallback() {
1090
1091 @Override
1092 public void userInputRequried(PendingIntent pi) {
1093 activity.runIntent(pi,
1094 ConversationActivity.REQUEST_SEND_MESSAGE);
1095 }
1096
1097 @Override
1098 public void success() {
1099 xmppConnectionService.sendMessage(pendingMessage, null);
1100 pendingMessage = null;
1101 ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
1102 .findFragmentByTag("conversation");
1103 if (selectedFragment != null) {
1104 selectedFragment.clearInputField();
1105 }
1106 }
1107
1108 @Override
1109 public void error(int error) {
1110
1111 }
1112 });
1113 }
1114}