XmppActivity.java

  1package eu.siacs.conversations.ui;
  2
  3import java.io.FileNotFoundException;
  4import java.lang.ref.WeakReference;
  5import java.util.List;
  6import java.util.concurrent.RejectedExecutionException;
  7
  8import eu.siacs.conversations.Config;
  9import eu.siacs.conversations.R;
 10import eu.siacs.conversations.entities.Account;
 11import eu.siacs.conversations.entities.Contact;
 12import eu.siacs.conversations.entities.Conversation;
 13import eu.siacs.conversations.entities.Message;
 14import eu.siacs.conversations.entities.Presences;
 15import eu.siacs.conversations.services.XmppConnectionService;
 16import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
 17import eu.siacs.conversations.utils.ExceptionHelper;
 18import android.app.Activity;
 19import android.app.AlertDialog;
 20import android.app.PendingIntent;
 21import android.app.AlertDialog.Builder;
 22import android.content.ComponentName;
 23import android.content.Context;
 24import android.content.DialogInterface;
 25import android.content.SharedPreferences;
 26import android.content.DialogInterface.OnClickListener;
 27import android.content.IntentSender.SendIntentException;
 28import android.content.pm.PackageManager;
 29import android.content.pm.ResolveInfo;
 30import android.content.res.Resources;
 31import android.content.Intent;
 32import android.content.ServiceConnection;
 33import android.graphics.Bitmap;
 34import android.graphics.drawable.BitmapDrawable;
 35import android.graphics.drawable.Drawable;
 36import android.net.Uri;
 37import android.os.AsyncTask;
 38import android.os.Bundle;
 39import android.os.IBinder;
 40import android.preference.PreferenceManager;
 41import android.text.InputType;
 42import android.util.DisplayMetrics;
 43import android.util.Log;
 44import android.view.MenuItem;
 45import android.view.View;
 46import android.view.inputmethod.InputMethodManager;
 47import android.widget.EditText;
 48import android.widget.ImageView;
 49
 50public abstract class XmppActivity extends Activity {
 51
 52	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
 53	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
 54
 55	public XmppConnectionService xmppConnectionService;
 56	public boolean xmppConnectionServiceBound = false;
 57	protected boolean handledViewIntent = false;
 58
 59	protected int mPrimaryTextColor;
 60	protected int mSecondaryTextColor;
 61	protected int mColorRed;
 62	protected int mColorOrange;
 63	protected int mColorGreen;
 64	protected int mPrimaryColor;
 65	
 66	protected boolean mUseSubject = true;
 67
 68	private DisplayMetrics metrics;
 69
 70	protected interface OnValueEdited {
 71		public void onValueEdited(String value);
 72	}
 73
 74	public interface OnPresenceSelected {
 75		public void onPresenceSelected();
 76	}
 77
 78	protected ServiceConnection mConnection = new ServiceConnection() {
 79
 80		@Override
 81		public void onServiceConnected(ComponentName className, IBinder service) {
 82			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 83			xmppConnectionService = binder.getService();
 84			xmppConnectionServiceBound = true;
 85			onBackendConnected();
 86		}
 87
 88		@Override
 89		public void onServiceDisconnected(ComponentName arg0) {
 90			xmppConnectionServiceBound = false;
 91		}
 92	};
 93
 94	@Override
 95	protected void onStart() {
 96		super.onStart();
 97		if (!xmppConnectionServiceBound) {
 98			connectToBackend();
 99		}
100	}
101
102	public void connectToBackend() {
103		Intent intent = new Intent(this, XmppConnectionService.class);
104		intent.setAction("ui");
105		startService(intent);
106		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
107	}
108
109	@Override
110	protected void onStop() {
111		super.onStop();
112		if (xmppConnectionServiceBound) {
113			unbindService(mConnection);
114			xmppConnectionServiceBound = false;
115		}
116	}
117
118	protected void hideKeyboard() {
119		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
120
121		View focus = getCurrentFocus();
122
123		if (focus != null) {
124
125			inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
126					InputMethodManager.HIDE_NOT_ALWAYS);
127		}
128	}
129
130	public boolean hasPgp() {
131		return xmppConnectionService.getPgpEngine() != null;
132	}
133
134	public void showInstallPgpDialog() {
135		Builder builder = new AlertDialog.Builder(this);
136		builder.setTitle(getString(R.string.openkeychain_required));
137		builder.setIconAttribute(android.R.attr.alertDialogIcon);
138		builder.setMessage(getText(R.string.openkeychain_required_long));
139		builder.setNegativeButton(getString(R.string.cancel), null);
140		builder.setNeutralButton(getString(R.string.restart),
141				new OnClickListener() {
142
143					@Override
144					public void onClick(DialogInterface dialog, int which) {
145						if (xmppConnectionServiceBound) {
146							unbindService(mConnection);
147							xmppConnectionServiceBound = false;
148						}
149						stopService(new Intent(XmppActivity.this,
150								XmppConnectionService.class));
151						finish();
152					}
153				});
154		builder.setPositiveButton(getString(R.string.install),
155				new OnClickListener() {
156
157					@Override
158					public void onClick(DialogInterface dialog, int which) {
159						Uri uri = Uri
160								.parse("market://details?id=org.sufficientlysecure.keychain");
161						Intent marketIntent = new Intent(Intent.ACTION_VIEW,
162								uri);
163						PackageManager manager = getApplicationContext()
164								.getPackageManager();
165						List<ResolveInfo> infos = manager
166								.queryIntentActivities(marketIntent, 0);
167						if (infos.size() > 0) {
168							startActivity(marketIntent);
169						} else {
170							uri = Uri.parse("http://www.openkeychain.org/");
171							Intent browserIntent = new Intent(
172									Intent.ACTION_VIEW, uri);
173							startActivity(browserIntent);
174						}
175						finish();
176					}
177				});
178		builder.create().show();
179	}
180
181	abstract void onBackendConnected();
182
183	public boolean onOptionsItemSelected(MenuItem item) {
184		switch (item.getItemId()) {
185		case R.id.action_settings:
186			startActivity(new Intent(this, SettingsActivity.class));
187			break;
188		case R.id.action_accounts:
189			startActivity(new Intent(this, ManageAccountActivity.class));
190			break;
191		case android.R.id.home:
192			finish();
193			break;
194		}
195		return super.onOptionsItemSelected(item);
196	}
197
198	@Override
199	protected void onCreate(Bundle savedInstanceState) {
200		super.onCreate(savedInstanceState);
201		metrics = getResources().getDisplayMetrics();
202		ExceptionHelper.init(getApplicationContext());
203		mPrimaryTextColor = getResources().getColor(R.color.primarytext);
204		mSecondaryTextColor = getResources().getColor(R.color.secondarytext);
205		mColorRed = getResources().getColor(R.color.red);
206		mColorOrange = getResources().getColor(R.color.orange);
207		mColorGreen = getResources().getColor(R.color.green);
208		mPrimaryColor = getResources().getColor(R.color.primary);
209		if (getPreferences().getBoolean("use_larger_font", false)) {
210			setTheme(R.style.ConversationsTheme_LargerText);
211		}
212		mUseSubject = getPreferences().getBoolean("use_subject", true);
213	}
214
215	protected SharedPreferences getPreferences() {
216		return PreferenceManager
217				.getDefaultSharedPreferences(getApplicationContext());
218	}
219	
220	public boolean useSubjectToIdentifyConference() {
221		return mUseSubject;
222	}
223
224	public void switchToConversation(Conversation conversation) {
225		switchToConversation(conversation, null, false);
226	}
227
228	public void switchToConversation(Conversation conversation, String text,
229			boolean newTask) {
230		Intent viewConversationIntent = new Intent(this,
231				ConversationActivity.class);
232		viewConversationIntent.setAction(Intent.ACTION_VIEW);
233		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
234				conversation.getUuid());
235		if (text != null) {
236			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
237		}
238		viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
239		if (newTask) {
240			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
241					| Intent.FLAG_ACTIVITY_NEW_TASK
242					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
243		} else {
244			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
245					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
246		}
247		startActivity(viewConversationIntent);
248	}
249
250	public void switchToContactDetails(Contact contact) {
251		Intent intent = new Intent(this, ContactDetailsActivity.class);
252		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
253		intent.putExtra("account", contact.getAccount().getJid());
254		intent.putExtra("contact", contact.getJid());
255		startActivity(intent);
256	}
257	
258	public void switchToAccount(Account account) {
259		Intent intent = new Intent(this, EditAccountActivity.class);
260		intent.putExtra("jid", account.getJid());
261		startActivity(intent);
262	}
263
264	protected void inviteToConversation(Conversation conversation) {
265		Intent intent = new Intent(getApplicationContext(),
266				ChooseContactActivity.class);
267		intent.putExtra("conversation", conversation.getUuid());
268		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
269	}
270
271	protected void announcePgp(Account account, final Conversation conversation) {
272		xmppConnectionService.getPgpEngine().generateSignature(account,
273				"online", new UiCallback<Account>() {
274
275					@Override
276					public void userInputRequried(PendingIntent pi,
277							Account account) {
278						try {
279							startIntentSenderForResult(pi.getIntentSender(),
280									REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
281						} catch (SendIntentException e) {
282						}
283					}
284
285					@Override
286					public void success(Account account) {
287						xmppConnectionService.databaseBackend
288								.updateAccount(account);
289						xmppConnectionService.sendPresencePacket(account,
290								xmppConnectionService.getPresenceGenerator()
291										.sendPresence(account));
292						if (conversation != null) {
293							conversation
294									.setNextEncryption(Message.ENCRYPTION_PGP);
295						}
296					}
297
298					@Override
299					public void error(int error, Account account) {
300						displayErrorDialog(error);
301					}
302				});
303	}
304
305	protected void displayErrorDialog(final int errorCode) {
306		runOnUiThread(new Runnable() {
307
308			@Override
309			public void run() {
310				AlertDialog.Builder builder = new AlertDialog.Builder(
311						XmppActivity.this);
312				builder.setIconAttribute(android.R.attr.alertDialogIcon);
313				builder.setTitle(getString(R.string.error));
314				builder.setMessage(errorCode);
315				builder.setNeutralButton(R.string.accept, null);
316				builder.create().show();
317			}
318		});
319
320	}
321
322	protected void showAddToRosterDialog(final Conversation conversation) {
323		String jid = conversation.getContactJid();
324		AlertDialog.Builder builder = new AlertDialog.Builder(this);
325		builder.setTitle(jid);
326		builder.setMessage(getString(R.string.not_in_roster));
327		builder.setNegativeButton(getString(R.string.cancel), null);
328		builder.setPositiveButton(getString(R.string.add_contact),
329				new DialogInterface.OnClickListener() {
330
331					@Override
332					public void onClick(DialogInterface dialog, int which) {
333						String jid = conversation.getContactJid();
334						Account account = conversation.getAccount();
335						Contact contact = account.getRoster().getContact(jid);
336						xmppConnectionService.createContact(contact);
337						switchToContactDetails(contact);
338					}
339				});
340		builder.create().show();
341	}
342
343	private void showAskForPresenceDialog(final Contact contact) {
344		AlertDialog.Builder builder = new AlertDialog.Builder(this);
345		builder.setTitle(contact.getJid());
346		builder.setMessage(R.string.request_presence_updates);
347		builder.setNegativeButton(R.string.cancel, null);
348		builder.setPositiveButton(R.string.request_now,
349				new DialogInterface.OnClickListener() {
350
351					@Override
352					public void onClick(DialogInterface dialog, int which) {
353						if (xmppConnectionServiceBound) {
354							xmppConnectionService.sendPresencePacket(contact
355									.getAccount(), xmppConnectionService
356									.getPresenceGenerator()
357									.requestPresenceUpdatesFrom(contact));
358						}
359					}
360				});
361		builder.create().show();
362	}
363
364	private void warnMutalPresenceSubscription(final Conversation conversation,
365			final OnPresenceSelected listener) {
366		AlertDialog.Builder builder = new AlertDialog.Builder(this);
367		builder.setTitle(conversation.getContact().getJid());
368		builder.setMessage(R.string.without_mutual_presence_updates);
369		builder.setNegativeButton(R.string.cancel, null);
370		builder.setPositiveButton(R.string.ignore, new OnClickListener() {
371
372			@Override
373			public void onClick(DialogInterface dialog, int which) {
374				conversation.setNextPresence(null);
375				if (listener != null) {
376					listener.onPresenceSelected();
377				}
378			}
379		});
380		builder.create().show();
381	}
382
383	protected void quickEdit(String previousValue, OnValueEdited callback) {
384		quickEdit(previousValue, callback, false);
385	}
386
387	protected void quickPasswordEdit(String previousValue,
388			OnValueEdited callback) {
389		quickEdit(previousValue, callback, true);
390	}
391
392	private void quickEdit(final String previousValue,
393			final OnValueEdited callback, boolean password) {
394		AlertDialog.Builder builder = new AlertDialog.Builder(this);
395		View view = (View) getLayoutInflater()
396				.inflate(R.layout.quickedit, null);
397		final EditText editor = (EditText) view.findViewById(R.id.editor);
398		OnClickListener mClickListener = new OnClickListener() {
399
400			@Override
401			public void onClick(DialogInterface dialog, int which) {
402				String value = editor.getText().toString();
403				if (!previousValue.equals(value) && value.trim().length() > 0) {
404					callback.onValueEdited(value);
405				}
406			}
407		};
408		if (password) {
409			editor.setInputType(InputType.TYPE_CLASS_TEXT
410					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
411			editor.setHint(R.string.password);
412			builder.setPositiveButton(R.string.accept, mClickListener);
413		} else {
414			builder.setPositiveButton(R.string.edit, mClickListener);
415		}
416		editor.requestFocus();
417		editor.setText(previousValue);
418		builder.setView(view);
419		builder.setNegativeButton(R.string.cancel, null);
420		builder.create().show();
421	}
422
423	public void selectPresence(final Conversation conversation,
424			final OnPresenceSelected listener) {
425		Contact contact = conversation.getContact();
426		if (!contact.showInRoster()) {
427			showAddToRosterDialog(conversation);
428		} else {
429			Presences presences = contact.getPresences();
430			if (presences.size() == 0) {
431				if (!contact.getOption(Contact.Options.TO)
432						&& !contact.getOption(Contact.Options.ASKING)
433						&& contact.getAccount().getStatus() == Account.STATUS_ONLINE) {
434					showAskForPresenceDialog(contact);
435				} else if (!contact.getOption(Contact.Options.TO)
436						|| !contact.getOption(Contact.Options.FROM)) {
437					warnMutalPresenceSubscription(conversation, listener);
438				} else {
439					conversation.setNextPresence(null);
440					listener.onPresenceSelected();
441				}
442			} else if (presences.size() == 1) {
443				String presence = (String) presences.asStringArray()[0];
444				conversation.setNextPresence(presence);
445				listener.onPresenceSelected();
446			} else {
447				final StringBuilder presence = new StringBuilder();
448				AlertDialog.Builder builder = new AlertDialog.Builder(this);
449				builder.setTitle(getString(R.string.choose_presence));
450				final String[] presencesArray = presences.asStringArray();
451				int preselectedPresence = 0;
452				for (int i = 0; i < presencesArray.length; ++i) {
453					if (presencesArray[i].equals(contact.lastseen.presence)) {
454						preselectedPresence = i;
455						break;
456					}
457				}
458				presence.append(presencesArray[preselectedPresence]);
459				builder.setSingleChoiceItems(presencesArray,
460						preselectedPresence,
461						new DialogInterface.OnClickListener() {
462
463							@Override
464							public void onClick(DialogInterface dialog,
465									int which) {
466								presence.delete(0, presence.length());
467								presence.append(presencesArray[which]);
468							}
469						});
470				builder.setNegativeButton(R.string.cancel, null);
471				builder.setPositiveButton(R.string.ok, new OnClickListener() {
472
473					@Override
474					public void onClick(DialogInterface dialog, int which) {
475						conversation.setNextPresence(presence.toString());
476						listener.onPresenceSelected();
477					}
478				});
479				builder.create().show();
480			}
481		}
482	}
483
484	protected void onActivityResult(int requestCode, int resultCode,
485			final Intent data) {
486		super.onActivityResult(requestCode, resultCode, data);
487		if (requestCode == REQUEST_INVITE_TO_CONVERSATION
488				&& resultCode == RESULT_OK) {
489			String contactJid = data.getStringExtra("contact");
490			String conversationUuid = data.getStringExtra("conversation");
491			Conversation conversation = xmppConnectionService
492					.findConversationByUuid(conversationUuid);
493			if (conversation.getMode() == Conversation.MODE_MULTI) {
494				xmppConnectionService.invite(conversation, contactJid);
495			}
496			Log.d(Config.LOGTAG, "inviting " + contactJid + " to "
497					+ conversation.getName());
498		}
499	}
500
501	public int getSecondaryTextColor() {
502		return this.mSecondaryTextColor;
503	}
504
505	public int getPrimaryTextColor() {
506		return this.mPrimaryTextColor;
507	}
508
509	public int getWarningTextColor() {
510		return this.mColorRed;
511	}
512
513	public int getPrimaryColor() {
514		return this.mPrimaryColor;
515	}
516
517	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
518		private final WeakReference<ImageView> imageViewReference;
519		private Message message = null;
520
521		public BitmapWorkerTask(ImageView imageView) {
522			imageViewReference = new WeakReference<ImageView>(imageView);
523		}
524
525		@Override
526		protected Bitmap doInBackground(Message... params) {
527			message = params[0];
528			try {
529				return xmppConnectionService.getFileBackend().getThumbnail(
530						message, (int) (metrics.density * 288), false);
531			} catch (FileNotFoundException e) {
532				return null;
533			}
534		}
535
536		@Override
537		protected void onPostExecute(Bitmap bitmap) {
538			if (imageViewReference != null && bitmap != null) {
539				final ImageView imageView = imageViewReference.get();
540				if (imageView != null) {
541					imageView.setImageBitmap(bitmap);
542					imageView.setBackgroundColor(0x00000000);
543				}
544			}
545		}
546	}
547
548	public void loadBitmap(Message message, ImageView imageView) {
549		Bitmap bm;
550		try {
551			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
552					(int) (metrics.density * 288), true);
553		} catch (FileNotFoundException e) {
554			bm = null;
555		}
556		if (bm != null) {
557			imageView.setImageBitmap(bm);
558			imageView.setBackgroundColor(0x00000000);
559		} else {
560			if (cancelPotentialWork(message, imageView)) {
561				imageView.setBackgroundColor(0xff333333);
562				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
563				final AsyncDrawable asyncDrawable = new AsyncDrawable(
564						getResources(), null, task);
565				imageView.setImageDrawable(asyncDrawable);
566				try {
567					task.execute(message);
568				} catch (RejectedExecutionException e) {
569					return;
570				}
571			}
572		}
573	}
574
575	public static boolean cancelPotentialWork(Message message,
576			ImageView imageView) {
577		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
578
579		if (bitmapWorkerTask != null) {
580			final Message oldMessage = bitmapWorkerTask.message;
581			if (oldMessage == null || message != oldMessage) {
582				bitmapWorkerTask.cancel(true);
583			} else {
584				return false;
585			}
586		}
587		return true;
588	}
589
590	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
591		if (imageView != null) {
592			final Drawable drawable = imageView.getDrawable();
593			if (drawable instanceof AsyncDrawable) {
594				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
595				return asyncDrawable.getBitmapWorkerTask();
596			}
597		}
598		return null;
599	}
600
601	static class AsyncDrawable extends BitmapDrawable {
602		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
603
604		public AsyncDrawable(Resources res, Bitmap bitmap,
605				BitmapWorkerTask bitmapWorkerTask) {
606			super(res, bitmap);
607			bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
608					bitmapWorkerTask);
609		}
610
611		public BitmapWorkerTask getBitmapWorkerTask() {
612			return bitmapWorkerTaskReference.get();
613		}
614	}
615}