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