ConversationActivity.java

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