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		if (getSelectedConversation().getNextEncryption() == Message.ENCRYPTION_PGP) {
345			if (hasPgp()) {
346				xmppConnectionService.getPgpEngine().hasKey(getSelectedConversation().getContact(), new OnPgpEngineResult() {
347					
348					@Override
349					public void userInputRequried(PendingIntent pi) {
350						ConversationActivity.this.runIntent(pi, REQUEST_SEND_PGP_IMAGE);
351					}
352					
353					@Override
354					public void success() {
355						attachFileDialog();
356					}
357					
358					@Override
359					public void error(OpenPgpError openPgpError) {
360						// TODO Auto-generated method stub
361						
362					}
363				});
364			}
365		} else if (getSelectedConversation().getNextEncryption() == Message.ENCRYPTION_NONE) {
366			attachFileDialog();
367		}
368	}
369	
370	@Override
371	public boolean onOptionsItemSelected(MenuItem item) {
372		switch (item.getItemId()) {
373		case android.R.id.home:
374			spl.openPane();
375			break;
376		case R.id.action_attach_file:
377			attachFile();
378			break;
379		case R.id.action_add:
380			startActivity(new Intent(this, ContactsActivity.class));
381			break;
382		case R.id.action_archive:
383			this.endConversation(getSelectedConversation());
384			break;
385		case R.id.action_contact_details:
386			Contact contact = this.getSelectedConversation().getContact();
387			if (contact != null) {
388				Intent intent = new Intent(this, ContactDetailsActivity.class);
389				intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
390				intent.putExtra("uuid", contact.getUuid());
391				startActivity(intent);
392			} else {
393				showAddToRosterDialog(getSelectedConversation());
394			}
395			break;
396		case R.id.action_muc_details:
397			Intent intent = new Intent(this, MucDetailsActivity.class);
398			intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC);
399			intent.putExtra("uuid", getSelectedConversation().getUuid());
400			startActivity(intent);
401			break;
402		case R.id.action_invite:
403			Intent inviteIntent = new Intent(getApplicationContext(),
404					ContactsActivity.class);
405			inviteIntent.setAction("invite");
406			inviteIntent.putExtra("uuid", selectedConversation.getUuid());
407			startActivity(inviteIntent);
408			break;
409		case R.id.action_security:
410			final Conversation selConv = getSelectedConversation();
411			View menuItemView = findViewById(R.id.action_security);
412			PopupMenu popup = new PopupMenu(this, menuItemView);
413			final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
414					.findFragmentByTag("conversation");
415			if (fragment != null) {
416				popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
417
418					@Override
419					public boolean onMenuItemClick(MenuItem item) {
420						switch (item.getItemId()) {
421						case R.id.encryption_choice_none:
422							selConv.setNextEncryption(Message.ENCRYPTION_NONE);
423							item.setChecked(true);
424							break;
425						case R.id.encryption_choice_otr:
426							selConv.setNextEncryption(Message.ENCRYPTION_OTR);
427							item.setChecked(true);
428							break;
429						case R.id.encryption_choice_pgp:
430							selConv.setNextEncryption(Message.ENCRYPTION_PGP);
431							item.setChecked(true);
432							break;
433						default:
434							selConv.setNextEncryption(Message.ENCRYPTION_NONE);
435							break;
436						}
437						fragment.updateChatMsgHint();
438						return true;
439					}
440				});
441				popup.inflate(R.menu.encryption_choices);
442				switch (selConv.getNextEncryption()) {
443				case Message.ENCRYPTION_NONE:
444					popup.getMenu().findItem(R.id.encryption_choice_none)
445							.setChecked(true);
446					break;
447				case Message.ENCRYPTION_OTR:
448					popup.getMenu().findItem(R.id.encryption_choice_otr)
449							.setChecked(true);
450					break;
451				case Message.ENCRYPTION_PGP:
452					popup.getMenu().findItem(R.id.encryption_choice_pgp)
453							.setChecked(true);
454					break;
455				case Message.ENCRYPTION_DECRYPTED:
456					popup.getMenu().findItem(R.id.encryption_choice_pgp)
457							.setChecked(true);
458					break;
459				default:
460					popup.getMenu().findItem(R.id.encryption_choice_none)
461							.setChecked(true);
462					break;
463				}
464				popup.show();
465			}
466
467			break;
468		case R.id.action_clear_history:
469			clearHistoryDialog(getSelectedConversation());
470			break;
471		default:
472			break;
473		}
474		return super.onOptionsItemSelected(item);
475	}
476	
477	private void endConversation(Conversation conversation) {
478		conversation.setStatus(Conversation.STATUS_ARCHIVED);
479		paneShouldBeOpen = true;
480		spl.openPane();
481		xmppConnectionService.archiveConversation(conversation);
482		if (conversationList.size() > 0) {
483			selectedConversation = conversationList.get(0);
484		} else {
485			selectedConversation = null;
486		}
487	}
488
489	protected void clearHistoryDialog(final Conversation conversation) {
490		AlertDialog.Builder builder = new AlertDialog.Builder(this);
491		builder.setTitle(getString(R.string.clear_conversation_history));
492		View dialogView = getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
493		final CheckBox endConversationCheckBox = (CheckBox) dialogView.findViewById(R.id.end_conversation_checkbox);
494		builder.setView(dialogView);
495		builder.setNegativeButton(getString(R.string.cancel), null);
496		builder.setPositiveButton(getString(R.string.delete_messages), new OnClickListener() {
497			
498			@Override
499			public void onClick(DialogInterface dialog, int which) {
500				activity.xmppConnectionService.clearConversationHistory(conversation);
501				if (endConversationCheckBox.isChecked()) {
502					endConversation(conversation);
503				}
504			}
505		});
506		builder.create().show();
507	}
508
509	protected ConversationFragment swapConversationFragment() {
510		ConversationFragment selectedFragment = new ConversationFragment();
511
512		FragmentTransaction transaction = getFragmentManager()
513				.beginTransaction();
514		transaction.replace(R.id.selected_conversation, selectedFragment,
515				"conversation");
516		transaction.commit();
517		return selectedFragment;
518	}
519
520	@Override
521	public boolean onKeyDown(int keyCode, KeyEvent event) {
522		if (keyCode == KeyEvent.KEYCODE_BACK) {
523			if (!spl.isOpen()) {
524				spl.openPane();
525				return false;
526			}
527		}
528		return super.onKeyDown(keyCode, event);
529	}
530
531	@Override
532	public void onStart() {
533		super.onStart();
534		SharedPreferences preferences = PreferenceManager
535				.getDefaultSharedPreferences(this);
536		this.useSubject = preferences.getBoolean("use_subject_in_muc", true);
537		if (this.xmppConnectionServiceBound) {
538			this.onBackendConnected();
539		}
540		if (conversationList.size() >= 1) {
541			onConvChanged.onConversationListChanged();
542		}
543	}
544
545	@Override
546	protected void onStop() {
547		if (xmppConnectionServiceBound) {
548			xmppConnectionService.removeOnConversationListChangedListener();
549		}
550		super.onStop();
551	}
552
553	@Override
554	void onBackendConnected() {
555		this.registerListener();
556		if (conversationList.size() == 0) {
557			updateConversationList();
558		}
559
560		if ((getIntent().getAction() != null)
561				&& (getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) {
562			if (getIntent().getType().equals(
563					ConversationActivity.VIEW_CONVERSATION)) {
564				handledViewIntent = true;
565
566				String convToView = (String) getIntent().getExtras().get(
567						CONVERSATION);
568
569				for (int i = 0; i < conversationList.size(); ++i) {
570					if (conversationList.get(i).getUuid().equals(convToView)) {
571						selectedConversation = conversationList.get(i);
572					}
573				}
574				paneShouldBeOpen = false;
575				String text = getIntent().getExtras().getString(TEXT, null);
576				swapConversationFragment().setText(text);
577			}
578		} else {
579			if (xmppConnectionService.getAccounts().size() == 0) {
580				startActivity(new Intent(this, ManageAccountActivity.class));
581				finish();
582			} else if (conversationList.size() <= 0) {
583				// add no history
584				startActivity(new Intent(this, ContactsActivity.class));
585				finish();
586			} else {
587				spl.openPane();
588				// find currently loaded fragment
589				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
590						.findFragmentByTag("conversation");
591				if (selectedFragment != null) {
592					selectedFragment.onBackendConnected();
593				} else {
594					selectedConversation = conversationList.get(0);
595					swapConversationFragment();
596				}
597				ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
598			}
599		}
600	}
601
602	public void registerListener() {
603		if (xmppConnectionServiceBound) {
604			xmppConnectionService
605					.setOnConversationListChangedListener(this.onConvChanged);
606		}
607	}
608
609	@Override
610	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
611		super.onActivityResult(requestCode, resultCode, data);
612		if (resultCode == RESULT_OK) {
613			if (requestCode == REQUEST_DECRYPT_PGP) {
614				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
615						.findFragmentByTag("conversation");
616				if (selectedFragment != null) {
617					selectedFragment.hidePgpPassphraseBox();
618				}
619			} else if (requestCode == ATTACH_FILE) {
620				final Conversation conversation = getSelectedConversation();
621				String presence = conversation.getNextPresence();
622				if (conversation.getNextEncryption() == Message.ENCRYPTION_NONE) {
623					xmppConnectionService.attachImageToConversation(conversation, presence, data.getData());
624				} else if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
625					pendingMessage = xmppConnectionService.attachEncryptedImageToConversation(conversation, presence, data.getData(), new OnPgpEngineResult() {
626						
627						@Override
628						public void userInputRequried(PendingIntent pi) {
629							ConversationActivity.this.runIntent(pi, ConversationActivity.REQUEST_SEND_PGP_IMAGE);
630						}
631						
632						@Override
633						public void success() {
634							conversation.getMessages().add(pendingMessage);
635							pendingMessage.setStatus(Message.STATUS_OFFERED);
636							xmppConnectionService.databaseBackend.createMessage(pendingMessage);
637							xmppConnectionService.sendMessage(pendingMessage, null);
638							xmppConnectionService.updateUi(conversation, false);
639							pendingMessage = null;
640						}
641						
642						@Override
643						public void error(OpenPgpError openPgpError) {
644							Log.d(LOGTAG,"pgp error"+openPgpError.getMessage());
645						}
646					});
647				} else {
648					Log.d(LOGTAG,"unknown next message encryption: "+conversation.getNextEncryption());
649				}
650			}
651		}
652	}
653
654	public void updateConversationList() {
655		conversationList.clear();
656		conversationList.addAll(xmppConnectionService.getConversations());
657		listView.invalidateViews();
658	}
659	
660	public void selectPresence(final Conversation conversation, final OnPresenceSelected listener, String reason) {
661		Account account = conversation.getAccount();
662		if (account.getStatus() != Account.STATUS_ONLINE) {
663			AlertDialog.Builder builder = new AlertDialog.Builder(this);
664			builder.setTitle(getString(R.string.not_connected));
665			builder.setIconAttribute(android.R.attr.alertDialogIcon);
666			if ("otr".equals(reason)) {
667				builder.setMessage(getString(R.string.you_are_offline,getString(R.string.otr_messages)));
668			} else if ("file".equals(reason)) {
669				builder.setMessage(getString(R.string.you_are_offline,getString(R.string.files)));
670			} else {
671				builder.setMessage(getString(R.string.you_are_offline_blank));
672			}
673			builder.setNegativeButton(getString(R.string.cancel), null);
674			builder.setPositiveButton(getString(R.string.manage_account), new OnClickListener() {
675				
676				@Override
677				public void onClick(DialogInterface dialog, int which) {
678					startActivity(new Intent(activity, ManageAccountActivity.class));
679				}
680			});
681			builder.create().show();
682			listener.onPresenceSelected(false, null);
683		} else {
684			Contact contact = conversation.getContact();
685			if (contact==null) {
686				showAddToRosterDialog(conversation);
687				listener.onPresenceSelected(false,null);
688			} else {
689				Hashtable<String, Integer> presences = contact.getPresences();
690				if (presences.size() == 0) {
691					AlertDialog.Builder builder = new AlertDialog.Builder(this);
692					builder.setTitle(getString(R.string.contact_offline));
693					if ("otr".equals(reason)) {
694						builder.setMessage(getString(R.string.contact_offline_otr));
695						builder.setPositiveButton(getString(R.string.send_unencrypted), new OnClickListener() {
696							
697							@Override
698							public void onClick(DialogInterface dialog, int which) {
699								listener.onSendPlainTextInstead();
700							}
701						});
702					} else if ("file".equals(reason)) {
703						builder.setMessage(getString(R.string.contact_offline_file));
704					}
705					builder.setIconAttribute(android.R.attr.alertDialogIcon);
706					builder.setNegativeButton(getString(R.string.cancel), null);
707					builder.create().show();
708					listener.onPresenceSelected(false, null);
709				} else if (presences.size() == 1) {
710					String presence = (String) presences.keySet().toArray()[0];
711					conversation.setNextPresence(presence);
712					listener.onPresenceSelected(true, presence);
713				} else {
714					AlertDialog.Builder builder = new AlertDialog.Builder(this);
715					builder.setTitle(getString(R.string.choose_presence));
716					final String[] presencesArray = new String[presences.size()];
717					presences.keySet().toArray(presencesArray);
718					builder.setItems(presencesArray,
719							new DialogInterface.OnClickListener() {
720	
721								@Override
722								public void onClick(DialogInterface dialog,
723										int which) {
724									String presence = presencesArray[which];
725									conversation.setNextPresence(presence);
726									listener.onPresenceSelected(true,presence);
727								}
728							});
729					builder.create().show();
730				}
731			}
732		}
733	}
734	
735	private void showAddToRosterDialog(final Conversation conversation) {
736		String jid = conversation.getContactJid();
737		AlertDialog.Builder builder = new AlertDialog.Builder(this);
738		builder.setTitle(jid);
739		builder.setMessage(getString(R.string.not_in_roster));
740		builder.setNegativeButton(getString(R.string.cancel), null);
741		builder.setPositiveButton(getString(R.string.add_contact), new DialogInterface.OnClickListener() {
742
743			@Override
744			public void onClick(DialogInterface dialog, int which) {
745				String jid = conversation.getContactJid();
746				Account account = getSelectedConversation().getAccount();
747				String name = jid.split("@")[0];
748				Contact contact = new Contact(account, name, jid, null);
749				xmppConnectionService.createContact(contact);
750			}
751		});
752		builder.create().show();
753	}
754	
755	public void runIntent(PendingIntent pi, int requestCode) {
756		try {
757			this.startIntentSenderForResult(pi.getIntentSender(),requestCode, null, 0,
758					0, 0);
759		} catch (SendIntentException e1) {
760			Log.d("xmppService","failed to start intent to send message");
761		}
762	}
763	
764	
765	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
766	    private final WeakReference<ImageView> imageViewReference;
767	    private Message message = null;
768
769	    public BitmapWorkerTask(ImageView imageView) {
770	        imageViewReference = new WeakReference<ImageView>(imageView);
771	    }
772
773	    @Override
774	    protected Bitmap doInBackground(Message... params) {
775	        message = params[0];
776	        try {
777				return xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288),false);
778			} catch (FileNotFoundException e) {
779				Log.d("xmppService","file not found!");
780				return null;
781			}
782	    }
783
784	    @Override
785	    protected void onPostExecute(Bitmap bitmap) {
786	        if (imageViewReference != null && bitmap != null) {
787	            final ImageView imageView = imageViewReference.get();
788	            if (imageView != null) {
789	                imageView.setImageBitmap(bitmap);
790	                imageView.setBackgroundColor(0x00000000);
791	            }
792	        }
793	    }
794	}
795	
796	public void loadBitmap(Message message, ImageView imageView) {
797		Bitmap bm;
798		try {
799			bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
800		} catch (FileNotFoundException e) {
801			bm = null;
802		}
803		if (bm!=null) {
804			imageView.setImageBitmap(bm);
805			imageView.setBackgroundColor(0x00000000);
806		} else {
807		    if (cancelPotentialWork(message, imageView)) {
808		    	imageView.setBackgroundColor(0xff333333);
809		        final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
810		        final AsyncDrawable asyncDrawable =
811		                new AsyncDrawable(getResources(), null, task);
812		        imageView.setImageDrawable(asyncDrawable);
813		        task.execute(message);
814		    }
815		}
816	}
817	
818	public static boolean cancelPotentialWork(Message message, ImageView imageView) {
819	    final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
820
821	    if (bitmapWorkerTask != null) {
822	        final Message oldMessage = bitmapWorkerTask.message;
823	        if (oldMessage == null || message != oldMessage) {
824	            bitmapWorkerTask.cancel(true);
825	        } else {
826	            return false;
827	        }
828	    }
829	    return true;
830	}
831	
832	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
833		   if (imageView != null) {
834		       final Drawable drawable = imageView.getDrawable();
835		       if (drawable instanceof AsyncDrawable) {
836		           final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
837		           return asyncDrawable.getBitmapWorkerTask();
838		       }
839		    }
840		    return null;
841	}
842	
843	static class AsyncDrawable extends BitmapDrawable {
844	    private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
845
846	    public AsyncDrawable(Resources res, Bitmap bitmap,
847	            BitmapWorkerTask bitmapWorkerTask) {
848	        super(res, bitmap);
849	        bitmapWorkerTaskReference =
850	            new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
851	    }
852
853	    public BitmapWorkerTask getBitmapWorkerTask() {
854	        return bitmapWorkerTaskReference.get();
855	    }
856	}
857}