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