Tue, 10 Feb 2015 22:48:00 +0100
Merge https://github.com/gggard/AndroidCaldavSyncAdapater/pull/211/
1 /**
2 * Copyright (c) 2012-2013, Gerald Garcia
3 *
4 * This file is part of Andoid Caldav Sync Adapter Free.
5 *
6 * Andoid Caldav Sync Adapter Free is free software: you can redistribute
7 * it and/or modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation, either version 3 of the
9 * License, or at your option any later version.
10 *
11 * Andoid Caldav Sync Adapter Free is distributed in the hope that
12 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied
13 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with Andoid Caldav Sync Adapter Free.
18 * If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
22 package org.gege.caldavsyncadapter.authenticator;
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.animation.Animator;
27 import android.animation.AnimatorListenerAdapter;
28 import android.annotation.TargetApi;
29 import android.app.Activity;
30 import android.content.Context;
31 import android.content.pm.PackageManager.NameNotFoundException;
32 import android.os.AsyncTask;
33 import android.os.Build;
34 import android.os.Bundle;
35 import android.text.Editable;
36 import android.text.InputType;
37 import android.text.TextUtils;
38 import android.text.TextWatcher;
39 import android.util.Log;
40 import android.view.KeyEvent;
41 import android.view.Menu;
42 import android.view.View;
43 import android.view.inputmethod.EditorInfo;
44 import android.widget.CheckBox;
45 import android.widget.CompoundButton;
46 import android.widget.EditText;
47 import android.widget.TextView;
48 import android.widget.Toast;
50 import org.apache.http.conn.HttpHostConnectException;
51 import org.gege.caldavsyncadapter.Constants;
52 import org.gege.caldavsyncadapter.R;
53 import org.gege.caldavsyncadapter.caldav.CaldavFacade;
54 import org.gege.caldavsyncadapter.caldav.CaldavFacade.TestConnectionResult;
55 import org.xml.sax.SAXException;
57 import java.io.IOException;
58 import java.io.UnsupportedEncodingException;
59 import java.net.MalformedURLException;
60 import java.net.URISyntaxException;
61 import java.util.Locale;
63 import javax.xml.parsers.ParserConfigurationException;
65 /**
66 * Activity which displays a login screen to the user, offering registration as
67 * well.
68 */
69 public class AuthenticatorActivity extends Activity {
71 private static final String TAG = "AuthenticatorActivity";
73 private static final String ACCOUNT_TYPE = "org.gege.caldavsyncadapter.account";
75 public static final String USER_DATA_URL_KEY = "USER_DATA_URL_KEY";
76 public static final String USER_DATA_USERNAME = "USER_DATA_USERNAME";
77 public static final String USER_DATA_VERSION = "USER_DATA_VERSION";
78 public static final String CURRENT_USER_DATA_VERSION = "1";
80 public static final String ACCOUNT_NAME_SPLITTER = "@";
82 /**
83 * The default email to populate the email field with.
84 */
85 public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
87 /**
88 * Keep track of the login task to ensure we can cancel it if requested.
89 */
90 private UserLoginTask mAuthTask = null;
92 // Values for email and password at the time of the login attempt.
93 private String mUser;
94 private String mPassword;
95 private String mTrustAll;
96 private Context mContext;
98 // UI references.
99 private EditText mUserView;
100 private EditText mPasswordView;
101 private View mLoginFormView;
102 private View mLoginStatusView;
103 private TextView mLoginStatusMessageView;
104 private CheckBox mTrustCheckBox;
106 private AccountManager mAccountManager;
108 private String mURL;
109 private EditText mURLView;
111 private String mAccountname;
112 private EditText mAccountnameView;
114 private CheckBox showPassword;
116 public AuthenticatorActivity() {
117 super();
119 }
121 @Override
122 protected void onCreate(Bundle savedInstanceState) {
123 super.onCreate(savedInstanceState);
125 mAccountManager = AccountManager.get(this);
127 setContentView(R.layout.activity_authenticator);
129 // Set up the login form.
130 mUser = getIntent().getStringExtra(EXTRA_EMAIL);
131 mUserView = (EditText) findViewById(R.id.user);
132 mUserView.setText(mUser);
133 mUserView.requestFocus();
135 mContext = getBaseContext();
137 mPasswordView = (EditText) findViewById(R.id.password);
138 mPasswordView
139 .setOnEditorActionListener(new TextView.OnEditorActionListener() {
140 @Override
141 public boolean onEditorAction(TextView textView, int id,
142 KeyEvent keyEvent) {
143 if (id == R.id.login || id == EditorInfo.IME_NULL) {
144 attemptLogin();
145 return true;
146 }
147 return false;
148 }
149 });
151 showPassword = (CheckBox) findViewById(R.id.showPassword);
152 showPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
153 @Override
154 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
155 if(isChecked) {
156 mPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
157 } else {
158 mPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
159 }
160 }
161 });
163 mURLView = (EditText) findViewById(R.id.url);
164 // if the URL start with "https" show the option to disable SSL host verification
165 mURLView.addTextChangedListener(new TextWatcher() {
166 @Override
167 public void onTextChanged(CharSequence s, int start, int before, int count) {
168 String url = ((EditText) findViewById(R.id.url)).getText().toString();
169 int visible = url.toLowerCase(Locale.getDefault())
170 .startsWith("https") ? View.VISIBLE : View.GONE;
171 ((CheckBox) findViewById(R.id.trustall)).setVisibility(visible);
172 }
174 @Override
175 public void beforeTextChanged(CharSequence s, int start, int count,
176 int after) {
177 }
179 @Override
180 public void afterTextChanged(Editable s) {
181 }
182 });
184 mAccountnameView = (EditText) findViewById(R.id.accountname);
186 mLoginFormView = findViewById(R.id.login_form);
187 mLoginStatusView = findViewById(R.id.login_status);
188 mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
190 findViewById(R.id.sign_in_button).setOnClickListener(
191 new View.OnClickListener() {
192 @Override
193 public void onClick(View view) {
194 attemptLogin();
195 }
196 }
197 );
199 mTrustCheckBox = (CheckBox) findViewById(R.id.trustall);
202 }
204 @Override
205 public boolean onCreateOptionsMenu(Menu menu) {
206 super.onCreateOptionsMenu(menu);
207 return true;
208 }
210 /**
211 * Attempts to sign in or register the account specified by the login form.
212 * If there are form errors (invalid email, missing fields, etc.), the
213 * errors are presented and no actual login attempt is made.
214 */
215 public void attemptLogin() {
216 if (mAuthTask != null) {
217 return;
218 }
220 // Reset errors.
221 mUserView.setError(null);
222 mPasswordView.setError(null);
224 // Store values at the time of the login attempt.
225 mUser = mUserView.getText().toString();
226 mPassword = mPasswordView.getText().toString();
227 mURL = mURLView.getText().toString();
228 mAccountname = mAccountnameView.getText().toString();
229 mTrustAll = (mTrustCheckBox.isChecked() ? "false" : "true");
230 boolean cancel = false;
231 View focusView = null;
233 if (!mAccountname.equals("")) {
234 Account TestAccount = new Account(mAccountname, ACCOUNT_TYPE);
235 String TestUrl = mAccountManager.getUserData(TestAccount, AuthenticatorActivity.USER_DATA_URL_KEY);
236 if (TestUrl != null) {
237 mAccountnameView.setError(getString(R.string.error_account_already_in_use));
238 focusView = mAccountnameView;
239 cancel = true;
240 }
241 }
243 // Check for a valid password.
244 if (TextUtils.isEmpty(mPassword)) {
245 mPasswordView.setError(getString(R.string.error_field_required));
246 focusView = mPasswordView;
247 cancel = true;
248 }
250 // Check for a valid email address.
251 if (TextUtils.isEmpty(mUser)) {
252 mUserView.setError(getString(R.string.error_field_required));
253 focusView = mUserView;
254 cancel = true;
255 }
256 //else if (!mUser.contains("@")) {
257 // mUserView.setError(getString(R.string.error_invalid_email));
258 // focusView = mUserView;
259 // cancel = true;
260 //}
262 if (cancel) {
263 // There was an error; don't attempt login and focus the first
264 // form field with an error.
265 focusView.requestFocus();
266 } else {
267 // Show a progress spinner, and kick off a background task to
268 // perform the user login attempt.
269 mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
270 showProgress(true);
271 mAuthTask = new UserLoginTask();
272 mAuthTask.execute((Void) null);
273 }
274 }
276 /**
277 * Shows the progress UI and hides the login form.
278 */
279 @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
280 private void showProgress(final boolean show) {
281 // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
282 // for very easy animations. If available, use these APIs to fade-in
283 // the progress spinner.
284 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
285 int shortAnimTime = getResources().getInteger(
286 android.R.integer.config_shortAnimTime);
288 mLoginStatusView.setVisibility(View.VISIBLE);
289 mLoginStatusView.animate().setDuration(shortAnimTime)
290 .alpha(show ? 1 : 0)
291 .setListener(new AnimatorListenerAdapter() {
292 @Override
293 public void onAnimationEnd(Animator animation) {
294 mLoginStatusView.setVisibility(show ? View.VISIBLE
295 : View.GONE);
296 }
297 });
299 mLoginFormView.setVisibility(View.VISIBLE);
300 mLoginFormView.animate().setDuration(shortAnimTime)
301 .alpha(show ? 0 : 1)
302 .setListener(new AnimatorListenerAdapter() {
303 @Override
304 public void onAnimationEnd(Animator animation) {
305 mLoginFormView.setVisibility(show ? View.GONE
306 : View.VISIBLE);
307 }
308 });
309 } else {
310 // The ViewPropertyAnimator APIs are not available, so simply show
311 // and hide the relevant UI components.
312 mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
313 mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
314 }
315 }
318 protected enum LoginResult {
319 MalformedURLException,
320 GeneralSecurityException,
321 UnkonwnException,
322 WrongCredentials,
323 InvalidResponse,
324 WrongUrl,
325 ConnectionRefused,
326 Success_Calendar,
327 Success_Collection,
328 UNTRUSTED_CERT,
329 Account_Already_In_Use
330 }
333 /**
334 * Represents an asynchronous login/registration task used to authenticate
335 * the user.
336 */
337 public class UserLoginTask extends AsyncTask<Void, Void, LoginResult> {
339 @Override
340 protected LoginResult doInBackground(Void... params) {
342 TestConnectionResult result = null;
344 try {
345 CaldavFacade facade = new CaldavFacade(mUser, mPassword, mURL, mTrustAll);
346 String version = "";
347 try {
348 version = mContext.getPackageManager()
349 .getPackageInfo(mContext.getPackageName(), 0).versionName;
350 } catch (NameNotFoundException e) {
351 version = "unknown";
352 e.printStackTrace();
353 }
354 facade.setVersion(version);
355 result = facade.testConnection();
356 Log.i(TAG, "testConnection status=" + result);
357 } catch (HttpHostConnectException e) {
358 Log.w(TAG, "testConnection", e);
359 return LoginResult.ConnectionRefused;
360 } catch (MalformedURLException e) {
361 Log.w(TAG, "testConnection", e);
362 return LoginResult.MalformedURLException;
363 } catch (UnsupportedEncodingException e) {
364 Log.w(TAG, "testConnection", e);
365 return LoginResult.UnkonwnException;
366 } catch (ParserConfigurationException e) {
367 Log.w(TAG, "testConnection", e);
368 return LoginResult.UnkonwnException;
369 } catch (SAXException e) {
370 Log.w(TAG, "testConnection", e);
371 return LoginResult.InvalidResponse;
372 } catch (IOException e) {
373 Log.w(TAG, "testConnection", e);
374 return LoginResult.UnkonwnException;
375 } catch (URISyntaxException e) {
376 Log.w(TAG, "testConnection", e);
377 return LoginResult.MalformedURLException;
378 }
380 if (result == null) {
381 return LoginResult.UnkonwnException;
382 }
384 switch (result) {
386 case SSL_ERROR:
387 return LoginResult.UNTRUSTED_CERT;
388 case SUCCESS:
389 boolean OldAccount = false;
390 LoginResult Result = LoginResult.Success_Calendar;
392 if (OldAccount) {
393 final Account account = new Account(mUser, ACCOUNT_TYPE);
394 if (mAccountManager.addAccountExplicitly(account, mPassword, null)) {
395 Log.v(TAG, "new account created");
396 mAccountManager.setUserData(account, USER_DATA_URL_KEY, mURL);
397 } else {
398 Log.v(TAG, "no new account created");
399 Result = LoginResult.Account_Already_In_Use;
400 }
401 } else {
402 final Account account;
403 if (mAccountname.equals("")) {
404 account = new Account(mUser + ACCOUNT_NAME_SPLITTER + mURL, ACCOUNT_TYPE);
405 } else {
406 account = new Account(mAccountname, ACCOUNT_TYPE);
407 }
408 if (mAccountManager.addAccountExplicitly(account, mPassword, null)) {
409 Log.v(TAG, "new account created");
410 mAccountManager.setUserData(account, USER_DATA_URL_KEY, mURL);
411 mAccountManager.setUserData(account, USER_DATA_USERNAME, mUser);
412 mAccountManager.setUserData(account, USER_DATA_VERSION, CURRENT_USER_DATA_VERSION);
413 mAccountManager.setUserData(account, Constants.USER_DATA_TRUST_ALL_KEY, mTrustAll);
414 } else {
415 Log.v(TAG, "no new account created");
416 Result = LoginResult.Account_Already_In_Use;
417 }
418 }
420 return Result;
422 case WRONG_CREDENTIAL:
423 return LoginResult.WrongCredentials;
425 case WRONG_SERVER_STATUS:
426 return LoginResult.InvalidResponse;
428 case WRONG_URL:
429 return LoginResult.WrongUrl;
431 case WRONG_ANSWER:
432 return LoginResult.InvalidResponse;
434 default:
435 return LoginResult.UnkonwnException;
437 }
439 }
442 @Override
443 protected void onPostExecute(final LoginResult result) {
444 mAuthTask = null;
445 showProgress(false);
447 int duration = Toast.LENGTH_SHORT;
448 Toast toast = null;
450 switch (result) {
451 case Success_Calendar:
452 toast = Toast.makeText(getApplicationContext(), R.string.success_calendar, duration);
453 toast.show();
454 finish();
455 break;
457 case Success_Collection:
458 toast = Toast.makeText(getApplicationContext(), R.string.success_collection, duration);
459 toast.show();
460 finish();
461 break;
463 case MalformedURLException:
465 toast = Toast.makeText(getApplicationContext(), R.string.error_incorrect_url_format, duration);
466 toast.show();
467 mURLView.setError(getString(R.string.error_incorrect_url_format));
468 mURLView.requestFocus();
469 break;
470 case InvalidResponse:
471 toast = Toast.makeText(getApplicationContext(), R.string.error_invalid_server_answer, duration);
472 toast.show();
473 mURLView.setError(getString(R.string.error_invalid_server_answer));
474 mURLView.requestFocus();
475 break;
476 case WrongUrl:
477 toast = Toast.makeText(getApplicationContext(), R.string.error_wrong_url, duration);
478 toast.show();
479 mURLView.setError(getString(R.string.error_wrong_url));
480 mURLView.requestFocus();
481 break;
483 case GeneralSecurityException:
484 break;
485 case UnkonwnException:
486 break;
487 case WrongCredentials:
488 mPasswordView.setError(getString(R.string.error_incorrect_password));
489 mPasswordView.requestFocus();
490 break;
492 case ConnectionRefused:
493 toast = Toast.makeText(getApplicationContext(), R.string.error_connection_refused, duration);
494 toast.show();
495 mURLView.setError(getString(R.string.error_connection_refused));
496 mURLView.requestFocus();
497 break;
498 case UNTRUSTED_CERT:
499 toast = Toast.makeText(getApplicationContext(), getString(R.string.error_untrusted_certificate), duration);
500 toast.show();
501 mURLView.setError(getString(R.string.error_ssl));
502 mURLView.requestFocus();
503 break;
504 case Account_Already_In_Use:
505 toast = Toast.makeText(getApplicationContext(), R.string.error_account_already_in_use, duration);
506 toast.show();
507 mURLView.setError(getString(R.string.error_account_already_in_use));
508 mURLView.requestFocus();
509 break;
510 default:
511 toast = Toast.makeText(getApplicationContext(), R.string.error_unkown_error, duration);
512 toast.show();
513 mURLView.setError(getString(R.string.error_unkown_error));
514 mURLView.requestFocus();
515 break;
516 }
519 }
521 @Override
522 protected void onCancelled() {
523 mAuthTask = null;
524 showProgress(false);
525 }
526 }
527 }