Tue, 10 Feb 2015 22:40:00 +0100
Merge https://github.com/gggard/AndroidCaldavSyncAdapater/pull/206/
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.TextUtils;
37 import android.text.TextWatcher;
38 import android.util.Log;
39 import android.view.KeyEvent;
40 import android.view.Menu;
41 import android.view.View;
42 import android.view.inputmethod.EditorInfo;
43 import android.widget.CheckBox;
44 import android.widget.EditText;
45 import android.widget.TextView;
46 import android.widget.Toast;
48 import org.apache.http.conn.HttpHostConnectException;
49 import org.gege.caldavsyncadapter.Constants;
50 import org.gege.caldavsyncadapter.R;
51 import org.gege.caldavsyncadapter.caldav.CaldavFacade;
52 import org.gege.caldavsyncadapter.caldav.CaldavFacade.TestConnectionResult;
53 import org.xml.sax.SAXException;
55 import java.io.IOException;
56 import java.io.UnsupportedEncodingException;
57 import java.net.MalformedURLException;
58 import java.net.URISyntaxException;
59 import java.util.Locale;
61 import javax.xml.parsers.ParserConfigurationException;
63 /**
64 * Activity which displays a login screen to the user, offering registration as
65 * well.
66 */
67 public class AuthenticatorActivity extends Activity {
69 private static final String TAG = "AuthenticatorActivity";
71 private static final String ACCOUNT_TYPE = "org.gege.caldavsyncadapter.account";
73 public static final String USER_DATA_URL_KEY = "USER_DATA_URL_KEY";
74 public static final String USER_DATA_USERNAME = "USER_DATA_USERNAME";
75 public static final String USER_DATA_VERSION = "USER_DATA_VERSION";
76 public static final String CURRENT_USER_DATA_VERSION = "1";
78 public static final String ACCOUNT_NAME_SPLITTER = "@";
80 /**
81 * The default email to populate the email field with.
82 */
83 public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
85 /**
86 * Keep track of the login task to ensure we can cancel it if requested.
87 */
88 private UserLoginTask mAuthTask = null;
90 // Values for email and password at the time of the login attempt.
91 private String mUser;
92 private String mPassword;
93 private String mTrustAll;
94 private Context mContext;
96 // UI references.
97 private EditText mUserView;
98 private EditText mPasswordView;
99 private View mLoginFormView;
100 private View mLoginStatusView;
101 private TextView mLoginStatusMessageView;
102 private CheckBox mTrustCheckBox;
104 private AccountManager mAccountManager;
106 private String mURL;
107 private EditText mURLView;
109 private String mAccountname;
110 private EditText mAccountnameView;
112 public AuthenticatorActivity() {
113 super();
115 }
117 @Override
118 protected void onCreate(Bundle savedInstanceState) {
119 super.onCreate(savedInstanceState);
121 mAccountManager = AccountManager.get(this);
123 setContentView(R.layout.activity_authenticator);
125 // Set up the login form.
126 mUser = getIntent().getStringExtra(EXTRA_EMAIL);
127 mUserView = (EditText) findViewById(R.id.user);
128 mUserView.setText(mUser);
130 mContext = getBaseContext();
132 mPasswordView = (EditText) findViewById(R.id.password);
133 mPasswordView
134 .setOnEditorActionListener(new TextView.OnEditorActionListener() {
135 @Override
136 public boolean onEditorAction(TextView textView, int id,
137 KeyEvent keyEvent) {
138 if (id == R.id.login || id == EditorInfo.IME_NULL) {
139 attemptLogin();
140 return true;
141 }
142 return false;
143 }
144 });
147 mURLView = (EditText) findViewById(R.id.url);
148 // if the URL start with "https" show the option to disable SSL host verification
149 mURLView.addTextChangedListener(new TextWatcher() {
150 @Override
151 public void onTextChanged(CharSequence s, int start, int before, int count) {
152 String url = ((EditText) findViewById(R.id.url)).getText().toString();
153 int visible = url.toLowerCase(Locale.getDefault())
154 .startsWith("https") ? View.VISIBLE : View.GONE;
155 ((CheckBox) findViewById(R.id.trustall)).setVisibility(visible);
156 }
158 @Override
159 public void beforeTextChanged(CharSequence s, int start, int count,
160 int after) {
161 }
163 @Override
164 public void afterTextChanged(Editable s) {
165 }
166 });
168 mAccountnameView = (EditText) findViewById(R.id.accountname);
170 mLoginFormView = findViewById(R.id.login_form);
171 mLoginStatusView = findViewById(R.id.login_status);
172 mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
174 findViewById(R.id.sign_in_button).setOnClickListener(
175 new View.OnClickListener() {
176 @Override
177 public void onClick(View view) {
178 attemptLogin();
179 }
180 }
181 );
183 mTrustCheckBox = (CheckBox) findViewById(R.id.trustall);
186 }
188 @Override
189 public boolean onCreateOptionsMenu(Menu menu) {
190 super.onCreateOptionsMenu(menu);
191 return true;
192 }
194 /**
195 * Attempts to sign in or register the account specified by the login form.
196 * If there are form errors (invalid email, missing fields, etc.), the
197 * errors are presented and no actual login attempt is made.
198 */
199 public void attemptLogin() {
200 if (mAuthTask != null) {
201 return;
202 }
204 // Reset errors.
205 mUserView.setError(null);
206 mPasswordView.setError(null);
208 // Store values at the time of the login attempt.
209 mUser = mUserView.getText().toString();
210 mPassword = mPasswordView.getText().toString();
211 mURL = mURLView.getText().toString();
212 mAccountname = mAccountnameView.getText().toString();
213 mTrustAll = (mTrustCheckBox.isChecked() ? "false" : "true");
214 boolean cancel = false;
215 View focusView = null;
217 if (!mAccountname.equals("")) {
218 Account TestAccount = new Account(mAccountname, ACCOUNT_TYPE);
219 String TestUrl = mAccountManager.getUserData(TestAccount, AuthenticatorActivity.USER_DATA_URL_KEY);
220 if (TestUrl != null) {
221 mAccountnameView.setError(getString(R.string.error_account_already_in_use));
222 focusView = mAccountnameView;
223 cancel = true;
224 }
225 }
227 // Check for a valid password.
228 if (TextUtils.isEmpty(mPassword)) {
229 mPasswordView.setError(getString(R.string.error_field_required));
230 focusView = mPasswordView;
231 cancel = true;
232 }
234 // Check for a valid email address.
235 if (TextUtils.isEmpty(mUser)) {
236 mUserView.setError(getString(R.string.error_field_required));
237 focusView = mUserView;
238 cancel = true;
239 }
240 //else if (!mUser.contains("@")) {
241 // mUserView.setError(getString(R.string.error_invalid_email));
242 // focusView = mUserView;
243 // cancel = true;
244 //}
246 if (cancel) {
247 // There was an error; don't attempt login and focus the first
248 // form field with an error.
249 focusView.requestFocus();
250 } else {
251 // Show a progress spinner, and kick off a background task to
252 // perform the user login attempt.
253 mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
254 showProgress(true);
255 mAuthTask = new UserLoginTask();
256 mAuthTask.execute((Void) null);
257 }
258 }
260 /**
261 * Shows the progress UI and hides the login form.
262 */
263 @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
264 private void showProgress(final boolean show) {
265 // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
266 // for very easy animations. If available, use these APIs to fade-in
267 // the progress spinner.
268 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
269 int shortAnimTime = getResources().getInteger(
270 android.R.integer.config_shortAnimTime);
272 mLoginStatusView.setVisibility(View.VISIBLE);
273 mLoginStatusView.animate().setDuration(shortAnimTime)
274 .alpha(show ? 1 : 0)
275 .setListener(new AnimatorListenerAdapter() {
276 @Override
277 public void onAnimationEnd(Animator animation) {
278 mLoginStatusView.setVisibility(show ? View.VISIBLE
279 : View.GONE);
280 }
281 });
283 mLoginFormView.setVisibility(View.VISIBLE);
284 mLoginFormView.animate().setDuration(shortAnimTime)
285 .alpha(show ? 0 : 1)
286 .setListener(new AnimatorListenerAdapter() {
287 @Override
288 public void onAnimationEnd(Animator animation) {
289 mLoginFormView.setVisibility(show ? View.GONE
290 : View.VISIBLE);
291 }
292 });
293 } else {
294 // The ViewPropertyAnimator APIs are not available, so simply show
295 // and hide the relevant UI components.
296 mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
297 mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
298 }
299 }
302 protected enum LoginResult {
303 MalformedURLException,
304 GeneralSecurityException,
305 UnkonwnException,
306 WrongCredentials,
307 InvalidResponse,
308 WrongUrl,
309 ConnectionRefused,
310 Success_Calendar,
311 Success_Collection,
312 UNTRUSTED_CERT,
313 Account_Already_In_Use
314 }
317 /**
318 * Represents an asynchronous login/registration task used to authenticate
319 * the user.
320 */
321 public class UserLoginTask extends AsyncTask<Void, Void, LoginResult> {
323 @Override
324 protected LoginResult doInBackground(Void... params) {
326 TestConnectionResult result = null;
328 try {
329 CaldavFacade facade = new CaldavFacade(mUser, mPassword, mURL, mTrustAll);
330 String version = "";
331 try {
332 version = mContext.getPackageManager()
333 .getPackageInfo(mContext.getPackageName(), 0).versionName;
334 } catch (NameNotFoundException e) {
335 version = "unknown";
336 e.printStackTrace();
337 }
338 facade.setVersion(version);
339 result = facade.testConnection();
340 Log.i(TAG, "testConnection status=" + result);
341 } catch (HttpHostConnectException e) {
342 Log.w(TAG, "testConnection", e);
343 return LoginResult.ConnectionRefused;
344 } catch (MalformedURLException e) {
345 Log.w(TAG, "testConnection", e);
346 return LoginResult.MalformedURLException;
347 } catch (UnsupportedEncodingException e) {
348 Log.w(TAG, "testConnection", e);
349 return LoginResult.UnkonwnException;
350 } catch (ParserConfigurationException e) {
351 Log.w(TAG, "testConnection", e);
352 return LoginResult.UnkonwnException;
353 } catch (SAXException e) {
354 Log.w(TAG, "testConnection", e);
355 return LoginResult.InvalidResponse;
356 } catch (IOException e) {
357 Log.w(TAG, "testConnection", e);
358 return LoginResult.UnkonwnException;
359 } catch (URISyntaxException e) {
360 Log.w(TAG, "testConnection", e);
361 return LoginResult.MalformedURLException;
362 }
364 if (result == null) {
365 return LoginResult.UnkonwnException;
366 }
368 switch (result) {
370 case SSL_ERROR:
371 return LoginResult.UNTRUSTED_CERT;
372 case SUCCESS:
373 boolean OldAccount = false;
374 LoginResult Result = LoginResult.Success_Calendar;
376 if (OldAccount) {
377 final Account account = new Account(mUser, ACCOUNT_TYPE);
378 if (mAccountManager.addAccountExplicitly(account, mPassword, null)) {
379 Log.v(TAG, "new account created");
380 mAccountManager.setUserData(account, USER_DATA_URL_KEY, mURL);
381 } else {
382 Log.v(TAG, "no new account created");
383 Result = LoginResult.Account_Already_In_Use;
384 }
385 } else {
386 final Account account;
387 if (mAccountname.equals("")) {
388 account = new Account(mUser + ACCOUNT_NAME_SPLITTER + mURL, ACCOUNT_TYPE);
389 } else {
390 account = new Account(mAccountname, ACCOUNT_TYPE);
391 }
392 if (mAccountManager.addAccountExplicitly(account, mPassword, null)) {
393 Log.v(TAG, "new account created");
394 mAccountManager.setUserData(account, USER_DATA_URL_KEY, mURL);
395 mAccountManager.setUserData(account, USER_DATA_USERNAME, mUser);
396 mAccountManager.setUserData(account, USER_DATA_VERSION, CURRENT_USER_DATA_VERSION);
397 mAccountManager.setUserData(account, Constants.USER_DATA_TRUST_ALL_KEY, mTrustAll);
398 } else {
399 Log.v(TAG, "no new account created");
400 Result = LoginResult.Account_Already_In_Use;
401 }
402 }
404 return Result;
406 case WRONG_CREDENTIAL:
407 return LoginResult.WrongCredentials;
409 case WRONG_SERVER_STATUS:
410 return LoginResult.InvalidResponse;
412 case WRONG_URL:
413 return LoginResult.WrongUrl;
415 case WRONG_ANSWER:
416 return LoginResult.InvalidResponse;
418 default:
419 return LoginResult.UnkonwnException;
421 }
423 }
426 @Override
427 protected void onPostExecute(final LoginResult result) {
428 mAuthTask = null;
429 showProgress(false);
431 int duration = Toast.LENGTH_SHORT;
432 Toast toast = null;
434 switch (result) {
435 case Success_Calendar:
436 toast = Toast.makeText(getApplicationContext(), R.string.success_calendar, duration);
437 toast.show();
438 finish();
439 break;
441 case Success_Collection:
442 toast = Toast.makeText(getApplicationContext(), R.string.success_collection, duration);
443 toast.show();
444 finish();
445 break;
447 case MalformedURLException:
449 toast = Toast.makeText(getApplicationContext(), R.string.error_incorrect_url_format, duration);
450 toast.show();
451 mURLView.setError(getString(R.string.error_incorrect_url_format));
452 mURLView.requestFocus();
453 break;
454 case InvalidResponse:
455 toast = Toast.makeText(getApplicationContext(), R.string.error_invalid_server_answer, duration);
456 toast.show();
457 mURLView.setError(getString(R.string.error_invalid_server_answer));
458 mURLView.requestFocus();
459 break;
460 case WrongUrl:
461 toast = Toast.makeText(getApplicationContext(), R.string.error_wrong_url, duration);
462 toast.show();
463 mURLView.setError(getString(R.string.error_wrong_url));
464 mURLView.requestFocus();
465 break;
467 case GeneralSecurityException:
468 break;
469 case UnkonwnException:
470 break;
471 case WrongCredentials:
472 mPasswordView.setError(getString(R.string.error_incorrect_password));
473 mPasswordView.requestFocus();
474 break;
476 case ConnectionRefused:
477 toast = Toast.makeText(getApplicationContext(), R.string.error_connection_refused, duration);
478 toast.show();
479 mURLView.setError(getString(R.string.error_connection_refused));
480 mURLView.requestFocus();
481 break;
482 case UNTRUSTED_CERT:
483 toast = Toast.makeText(getApplicationContext(), getString(R.string.error_untrusted_certificate), duration);
484 toast.show();
485 mURLView.setError(getString(R.string.error_ssl));
486 mURLView.requestFocus();
487 break;
488 case Account_Already_In_Use:
489 toast = Toast.makeText(getApplicationContext(), R.string.error_account_already_in_use, duration);
490 toast.show();
491 mURLView.setError(getString(R.string.error_account_already_in_use));
492 mURLView.requestFocus();
493 break;
494 default:
495 toast = Toast.makeText(getApplicationContext(), R.string.error_unkown_error, duration);
496 toast.show();
497 mURLView.setError(getString(R.string.error_unkown_error));
498 mURLView.requestFocus();
499 break;
500 }
503 }
505 @Override
506 protected void onCancelled() {
507 mAuthTask = null;
508 showProgress(false);
509 }
510 }
511 }