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