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