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