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