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