ConversationActivity.java

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