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