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