ConversationActivity.java

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