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