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 protected void inviteToConversation(Conversation conversation) {
252 Intent intent = new Intent(getApplicationContext(),
253 ChooseContactActivity.class);
254 intent.putExtra("conversation", conversation.getUuid());
255 startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
256 }
257
258 protected void announcePgp(Account account, final Conversation conversation) {
259 xmppConnectionService.getPgpEngine().generateSignature(account,
260 "online", new UiCallback<Account>() {
261
262 @Override
263 public void userInputRequried(PendingIntent pi,
264 Account account) {
265 try {
266 startIntentSenderForResult(pi.getIntentSender(),
267 REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
268 } catch (SendIntentException e) {
269 }
270 }
271
272 @Override
273 public void success(Account account) {
274 xmppConnectionService.databaseBackend
275 .updateAccount(account);
276 xmppConnectionService.sendPresencePacket(account,
277 xmppConnectionService.getPresenceGenerator()
278 .sendPresence(account));
279 if (conversation != null) {
280 conversation
281 .setNextEncryption(Message.ENCRYPTION_PGP);
282 }
283 }
284
285 @Override
286 public void error(int error, Account account) {
287 displayErrorDialog(error);
288 }
289 });
290 }
291
292 protected void displayErrorDialog(final int errorCode) {
293 runOnUiThread(new Runnable() {
294
295 @Override
296 public void run() {
297 AlertDialog.Builder builder = new AlertDialog.Builder(
298 XmppActivity.this);
299 builder.setIconAttribute(android.R.attr.alertDialogIcon);
300 builder.setTitle(getString(R.string.error));
301 builder.setMessage(errorCode);
302 builder.setNeutralButton(R.string.accept, null);
303 builder.create().show();
304 }
305 });
306
307 }
308
309 protected void showAddToRosterDialog(final Conversation conversation) {
310 String jid = conversation.getContactJid();
311 AlertDialog.Builder builder = new AlertDialog.Builder(this);
312 builder.setTitle(jid);
313 builder.setMessage(getString(R.string.not_in_roster));
314 builder.setNegativeButton(getString(R.string.cancel), null);
315 builder.setPositiveButton(getString(R.string.add_contact),
316 new DialogInterface.OnClickListener() {
317
318 @Override
319 public void onClick(DialogInterface dialog, int which) {
320 String jid = conversation.getContactJid();
321 Account account = conversation.getAccount();
322 Contact contact = account.getRoster().getContact(jid);
323 xmppConnectionService.createContact(contact);
324 switchToContactDetails(contact);
325 }
326 });
327 builder.create().show();
328 }
329
330 private void showAskForPresenceDialog(final Contact contact) {
331 AlertDialog.Builder builder = new AlertDialog.Builder(this);
332 builder.setTitle(contact.getJid());
333 builder.setMessage(R.string.request_presence_updates);
334 builder.setNegativeButton(R.string.cancel, null);
335 builder.setPositiveButton(R.string.request_now,
336 new DialogInterface.OnClickListener() {
337
338 @Override
339 public void onClick(DialogInterface dialog, int which) {
340 if (xmppConnectionServiceBound) {
341 xmppConnectionService.sendPresencePacket(contact
342 .getAccount(), xmppConnectionService
343 .getPresenceGenerator()
344 .requestPresenceUpdatesFrom(contact));
345 }
346 }
347 });
348 builder.create().show();
349 }
350
351 private void warnMutalPresenceSubscription(final Conversation conversation,
352 final OnPresenceSelected listener) {
353 AlertDialog.Builder builder = new AlertDialog.Builder(this);
354 builder.setTitle(conversation.getContact().getJid());
355 builder.setMessage(R.string.without_mutual_presence_updates);
356 builder.setNegativeButton(R.string.cancel, null);
357 builder.setPositiveButton(R.string.ignore, new OnClickListener() {
358
359 @Override
360 public void onClick(DialogInterface dialog, int which) {
361 conversation.setNextPresence(null);
362 if (listener != null) {
363 listener.onPresenceSelected();
364 }
365 }
366 });
367 builder.create().show();
368 }
369
370 protected void quickEdit(String previousValue, OnValueEdited callback) {
371 quickEdit(previousValue, callback, false);
372 }
373
374 protected void quickPasswordEdit(String previousValue,
375 OnValueEdited callback) {
376 quickEdit(previousValue, callback, true);
377 }
378
379 private void quickEdit(final String previousValue,
380 final OnValueEdited callback, boolean password) {
381 AlertDialog.Builder builder = new AlertDialog.Builder(this);
382 View view = (View) getLayoutInflater()
383 .inflate(R.layout.quickedit, null);
384 final EditText editor = (EditText) view.findViewById(R.id.editor);
385 OnClickListener mClickListener = new OnClickListener() {
386
387 @Override
388 public void onClick(DialogInterface dialog, int which) {
389 String value = editor.getText().toString();
390 if (!previousValue.equals(value) && value.trim().length() > 0) {
391 callback.onValueEdited(value);
392 }
393 }
394 };
395 if (password) {
396 editor.setInputType(InputType.TYPE_CLASS_TEXT
397 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
398 editor.setHint(R.string.password);
399 builder.setPositiveButton(R.string.accept, mClickListener);
400 } else {
401 builder.setPositiveButton(R.string.edit, mClickListener);
402 }
403 editor.requestFocus();
404 editor.setText(previousValue);
405 builder.setView(view);
406 builder.setNegativeButton(R.string.cancel, null);
407 builder.create().show();
408 }
409
410 public void selectPresence(final Conversation conversation,
411 final OnPresenceSelected listener) {
412 Contact contact = conversation.getContact();
413 if (!contact.showInRoster()) {
414 showAddToRosterDialog(conversation);
415 } else {
416 Presences presences = contact.getPresences();
417 if (presences.size() == 0) {
418 if (!contact.getOption(Contact.Options.TO)
419 && !contact.getOption(Contact.Options.ASKING)
420 && contact.getAccount().getStatus() == Account.STATUS_ONLINE) {
421 showAskForPresenceDialog(contact);
422 } else if (!contact.getOption(Contact.Options.TO)
423 || !contact.getOption(Contact.Options.FROM)) {
424 warnMutalPresenceSubscription(conversation, listener);
425 } else {
426 conversation.setNextPresence(null);
427 listener.onPresenceSelected();
428 }
429 } else if (presences.size() == 1) {
430 String presence = (String) presences.asStringArray()[0];
431 conversation.setNextPresence(presence);
432 listener.onPresenceSelected();
433 } else {
434 final StringBuilder presence = new StringBuilder();
435 AlertDialog.Builder builder = new AlertDialog.Builder(this);
436 builder.setTitle(getString(R.string.choose_presence));
437 final String[] presencesArray = presences.asStringArray();
438 int preselectedPresence = 0;
439 for (int i = 0; i < presencesArray.length; ++i) {
440 if (presencesArray[i].equals(contact.lastseen.presence)) {
441 preselectedPresence = i;
442 break;
443 }
444 }
445 presence.append(presencesArray[preselectedPresence]);
446 builder.setSingleChoiceItems(presencesArray,
447 preselectedPresence,
448 new DialogInterface.OnClickListener() {
449
450 @Override
451 public void onClick(DialogInterface dialog,
452 int which) {
453 presence.delete(0, presence.length());
454 presence.append(presencesArray[which]);
455 }
456 });
457 builder.setNegativeButton(R.string.cancel, null);
458 builder.setPositiveButton(R.string.ok, new OnClickListener() {
459
460 @Override
461 public void onClick(DialogInterface dialog, int which) {
462 conversation.setNextPresence(presence.toString());
463 listener.onPresenceSelected();
464 }
465 });
466 builder.create().show();
467 }
468 }
469 }
470
471 protected void onActivityResult(int requestCode, int resultCode,
472 final Intent data) {
473 super.onActivityResult(requestCode, resultCode, data);
474 if (requestCode == REQUEST_INVITE_TO_CONVERSATION
475 && resultCode == RESULT_OK) {
476 String contactJid = data.getStringExtra("contact");
477 String conversationUuid = data.getStringExtra("conversation");
478 Conversation conversation = xmppConnectionService
479 .findConversationByUuid(conversationUuid);
480 if (conversation.getMode() == Conversation.MODE_MULTI) {
481 xmppConnectionService.invite(conversation, contactJid);
482 }
483 Log.d(Config.LOGTAG, "inviting " + contactJid + " to "
484 + conversation.getName());
485 }
486 }
487
488 public int getSecondaryTextColor() {
489 return this.mSecondaryTextColor;
490 }
491
492 public int getPrimaryTextColor() {
493 return this.mPrimaryTextColor;
494 }
495
496 public int getWarningTextColor() {
497 return this.mColorRed;
498 }
499
500 public int getPrimaryColor() {
501 return this.mPrimaryColor;
502 }
503
504 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
505 private final WeakReference<ImageView> imageViewReference;
506 private Message message = null;
507
508 public BitmapWorkerTask(ImageView imageView) {
509 imageViewReference = new WeakReference<ImageView>(imageView);
510 }
511
512 @Override
513 protected Bitmap doInBackground(Message... params) {
514 message = params[0];
515 try {
516 return xmppConnectionService.getFileBackend().getThumbnail(
517 message, (int) (metrics.density * 288), false);
518 } catch (FileNotFoundException e) {
519 return null;
520 }
521 }
522
523 @Override
524 protected void onPostExecute(Bitmap bitmap) {
525 if (imageViewReference != null && bitmap != null) {
526 final ImageView imageView = imageViewReference.get();
527 if (imageView != null) {
528 imageView.setImageBitmap(bitmap);
529 imageView.setBackgroundColor(0x00000000);
530 }
531 }
532 }
533 }
534
535 public void loadBitmap(Message message, ImageView imageView) {
536 Bitmap bm;
537 try {
538 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
539 (int) (metrics.density * 288), true);
540 } catch (FileNotFoundException e) {
541 bm = null;
542 }
543 if (bm != null) {
544 imageView.setImageBitmap(bm);
545 imageView.setBackgroundColor(0x00000000);
546 } else {
547 if (cancelPotentialWork(message, imageView)) {
548 imageView.setBackgroundColor(0xff333333);
549 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
550 final AsyncDrawable asyncDrawable = new AsyncDrawable(
551 getResources(), null, task);
552 imageView.setImageDrawable(asyncDrawable);
553 try {
554 task.execute(message);
555 } catch (RejectedExecutionException e) {
556 return;
557 }
558 }
559 }
560 }
561
562 public static boolean cancelPotentialWork(Message message,
563 ImageView imageView) {
564 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
565
566 if (bitmapWorkerTask != null) {
567 final Message oldMessage = bitmapWorkerTask.message;
568 if (oldMessage == null || message != oldMessage) {
569 bitmapWorkerTask.cancel(true);
570 } else {
571 return false;
572 }
573 }
574 return true;
575 }
576
577 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
578 if (imageView != null) {
579 final Drawable drawable = imageView.getDrawable();
580 if (drawable instanceof AsyncDrawable) {
581 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
582 return asyncDrawable.getBitmapWorkerTask();
583 }
584 }
585 return null;
586 }
587
588 static class AsyncDrawable extends BitmapDrawable {
589 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
590
591 public AsyncDrawable(Resources res, Bitmap bitmap,
592 BitmapWorkerTask bitmapWorkerTask) {
593 super(res, bitmap);
594 bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
595 bitmapWorkerTask);
596 }
597
598 public BitmapWorkerTask getBitmapWorkerTask() {
599 return bitmapWorkerTaskReference.get();
600 }
601 }
602}