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