16c807cfb0aaf813fbd26f91ee6d6d439bdbfed2
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / AuthenticatorActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.net.MalformedURLException;
22 import java.net.URL;
23
24 import com.owncloud.android.AccountUtils;
25 import com.owncloud.android.authenticator.AccountAuthenticator;
26 import com.owncloud.android.authenticator.AuthenticationRunnable;
27 import com.owncloud.android.authenticator.ConnectionCheckOperation;
28 import com.owncloud.android.authenticator.OnAuthenticationResultListener;
29 import com.owncloud.android.authenticator.OnConnectCheckListener;
30 import com.owncloud.android.ui.dialog.SslValidatorDialog;
31 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
32 import com.owncloud.android.network.OwnCloudClientUtils;
33 import com.owncloud.android.operations.OnRemoteOperationListener;
34 import com.owncloud.android.operations.RemoteOperation;
35 import com.owncloud.android.operations.RemoteOperationResult;
36
37 import android.accounts.Account;
38 import android.accounts.AccountAuthenticatorActivity;
39 import android.accounts.AccountManager;
40 import android.app.AlertDialog;
41 import android.app.Dialog;
42 import android.app.ProgressDialog;
43 import android.content.ContentResolver;
44 import android.content.DialogInterface;
45 import android.content.Intent;
46 import android.content.SharedPreferences;
47 import android.net.Uri;
48 import android.os.Bundle;
49 import android.os.Handler;
50 import android.preference.PreferenceManager;
51 import android.text.InputType;
52 import android.util.Log;
53 import android.view.View;
54 import android.view.View.OnClickListener;
55 import android.view.View.OnFocusChangeListener;
56 import android.view.Window;
57 import android.widget.ImageView;
58 import android.widget.TextView;
59 import com.owncloud.android.R;
60
61 import eu.alefzero.webdav.WebdavClient;
62
63 /**
64 * This Activity is used to add an ownCloud account to the App
65 *
66 * @author Bartek Przybylski
67 *
68 */
69 public class AuthenticatorActivity extends AccountAuthenticatorActivity
70 implements OnAuthenticationResultListener, OnConnectCheckListener, OnRemoteOperationListener, OnSslValidatorListener,
71 OnFocusChangeListener, OnClickListener {
72
73 private static final int DIALOG_LOGIN_PROGRESS = 0;
74 private static final int DIALOG_SSL_VALIDATOR = 1;
75 private static final int DIALOG_CERT_NOT_SAVED = 2;
76
77 private static final String TAG = "AuthActivity";
78
79 private Thread mAuthThread;
80 private AuthenticationRunnable mAuthRunnable;
81 //private ConnectionCheckerRunnable mConnChkRunnable = null;
82 private ConnectionCheckOperation mConnChkRunnable;
83 private final Handler mHandler = new Handler();
84 private String mBaseUrl;
85
86 private static final String STATUS_TEXT = "STATUS_TEXT";
87 private static final String STATUS_ICON = "STATUS_ICON";
88 private static final String STATUS_CORRECT = "STATUS_CORRECT";
89 private static final String IS_SSL_CONN = "IS_SSL_CONN";
90 private int mStatusText, mStatusIcon;
91 private boolean mStatusCorrect, mIsSslConn;
92 private RemoteOperationResult mLastSslUntrustedServerResult;
93
94 public static final String PARAM_USERNAME = "param_Username";
95 public static final String PARAM_HOSTNAME = "param_Hostname";
96
97 @Override
98 protected void onCreate(Bundle savedInstanceState) {
99 super.onCreate(savedInstanceState);
100 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
101 setContentView(R.layout.account_setup);
102 ImageView iv = (ImageView) findViewById(R.id.refreshButton);
103 ImageView iv2 = (ImageView) findViewById(R.id.viewPassword);
104 TextView tv = (TextView) findViewById(R.id.host_URL);
105 TextView tv2 = (TextView) findViewById(R.id.account_password);
106
107 if (savedInstanceState != null) {
108 mStatusIcon = savedInstanceState.getInt(STATUS_ICON);
109 mStatusText = savedInstanceState.getInt(STATUS_TEXT);
110 mStatusCorrect = savedInstanceState.getBoolean(STATUS_CORRECT);
111 mIsSslConn = savedInstanceState.getBoolean(IS_SSL_CONN);
112 setResultIconAndText(mStatusIcon, mStatusText);
113 findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
114 if (!mStatusCorrect)
115 iv.setVisibility(View.VISIBLE);
116 else
117 iv.setVisibility(View.INVISIBLE);
118
119 } else {
120 mStatusText = mStatusIcon = 0;
121 mStatusCorrect = false;
122 mIsSslConn = false;
123 }
124 iv.setOnClickListener(this);
125 iv2.setOnClickListener(this);
126 tv.setOnFocusChangeListener(this);
127 tv2.setOnFocusChangeListener(this);
128 }
129
130 @Override
131 protected void onSaveInstanceState(Bundle outState) {
132 outState.putInt(STATUS_ICON, mStatusIcon);
133 outState.putInt(STATUS_TEXT, mStatusText);
134 outState.putBoolean(STATUS_CORRECT, mStatusCorrect);
135 super.onSaveInstanceState(outState);
136 }
137
138 @Override
139 protected Dialog onCreateDialog(int id) {
140 Dialog dialog = null;
141 switch (id) {
142 case DIALOG_LOGIN_PROGRESS: {
143 ProgressDialog working_dialog = new ProgressDialog(this);
144 working_dialog.setMessage(getResources().getString(
145 R.string.auth_trying_to_login));
146 working_dialog.setIndeterminate(true);
147 working_dialog.setCancelable(true);
148 working_dialog
149 .setOnCancelListener(new DialogInterface.OnCancelListener() {
150 @Override
151 public void onCancel(DialogInterface dialog) {
152 Log.i(TAG, "Login canceled");
153 if (mAuthThread != null) {
154 mAuthThread.interrupt();
155 finish();
156 }
157 }
158 });
159 dialog = working_dialog;
160 break;
161 }
162 case DIALOG_SSL_VALIDATOR: {
163 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
164 break;
165 }
166 case DIALOG_CERT_NOT_SAVED: {
167 AlertDialog.Builder builder = new AlertDialog.Builder(this);
168 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
169 builder.setCancelable(false);
170 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
171 @Override
172 public void onClick(DialogInterface dialog, int which) {
173 dialog.dismiss();
174 };
175 });
176 dialog = builder.create();
177 break;
178 }
179 default:
180 Log.e(TAG, "Incorrect dialog called with id = " + id);
181 }
182 return dialog;
183 }
184
185 @Override
186 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
187 switch (id) {
188 case DIALOG_LOGIN_PROGRESS:
189 case DIALOG_CERT_NOT_SAVED:
190 break;
191 case DIALOG_SSL_VALIDATOR: {
192 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
193 break;
194 }
195 default:
196 Log.e(TAG, "Incorrect dialog called with id = " + id);
197 }
198 }
199
200 public void onAuthenticationResult(boolean success, String message) {
201 if (success) {
202 TextView username_text = (TextView) findViewById(R.id.account_username), password_text = (TextView) findViewById(R.id.account_password);
203
204 URL url;
205 try {
206 url = new URL(message);
207 } catch (MalformedURLException e) {
208 // should never happen
209 Log.e(getClass().getName(), "Malformed URL: " + message);
210 return;
211 }
212
213 String username = username_text.getText().toString().trim();
214 String accountName = username + "@" + url.getHost();
215 if (url.getPort() >= 0) {
216 accountName += ":" + url.getPort();
217 }
218 Account account = new Account(accountName,
219 AccountAuthenticator.ACCOUNT_TYPE);
220 AccountManager accManager = AccountManager.get(this);
221 accManager.addAccountExplicitly(account, password_text.getText()
222 .toString(), null);
223
224 // Add this account as default in the preferences, if there is none
225 // already
226 Account defaultAccount = AccountUtils
227 .getCurrentOwnCloudAccount(this);
228 if (defaultAccount == null) {
229 SharedPreferences.Editor editor = PreferenceManager
230 .getDefaultSharedPreferences(this).edit();
231 editor.putString("select_oc_account", accountName);
232 editor.commit();
233 }
234
235 final Intent intent = new Intent();
236 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,
237 AccountAuthenticator.ACCOUNT_TYPE);
238 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
239 intent.putExtra(AccountManager.KEY_AUTHTOKEN,
240 AccountAuthenticator.ACCOUNT_TYPE);
241 intent.putExtra(AccountManager.KEY_USERDATA, username);
242
243 accManager.setUserData(account, AccountAuthenticator.KEY_OC_URL,
244 url.toString());
245 accManager.setUserData(account,
246 AccountAuthenticator.KEY_OC_VERSION, mConnChkRunnable
247 .getDiscoveredVersion().toString());
248
249 accManager.setUserData(account,
250 AccountAuthenticator.KEY_OC_BASE_URL, mBaseUrl);
251
252 setAccountAuthenticatorResult(intent.getExtras());
253 setResult(RESULT_OK, intent);
254 Bundle bundle = new Bundle();
255 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
256 //getContentResolver().startSync(ProviderTableMeta.CONTENT_URI,
257 // bundle);
258 ContentResolver.requestSync(account, "org.owncloud", bundle);
259
260 /*
261 * if
262 * (mConnChkRunnable.getDiscoveredVersion().compareTo(OwnCloudVersion
263 * .owncloud_v2) >= 0) { Intent i = new Intent(this,
264 * ExtensionsAvailableActivity.class); startActivity(i); }
265 */
266
267 finish();
268 } else {
269 try {
270 dismissDialog(DIALOG_LOGIN_PROGRESS);
271 } catch (IllegalArgumentException e) {
272 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
273 }
274 TextView tv = (TextView) findViewById(R.id.account_username);
275 tv.setError(message);
276 }
277 }
278 public void onCancelClick(View view) {
279 setResult(RESULT_CANCELED);
280 finish();
281 }
282
283 public void onOkClick(View view) {
284 String prefix = "";
285 String url = ((TextView) findViewById(R.id.host_URL)).getText()
286 .toString().trim();
287 if (mIsSslConn) {
288 prefix = "https://";
289 } else {
290 prefix = "http://";
291 }
292 if (url.toLowerCase().startsWith("http://")
293 || url.toLowerCase().startsWith("https://")) {
294 prefix = "";
295 }
296 continueConnection(prefix);
297 }
298
299 public void onRegisterClick(View view) {
300 Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse("https://owncloud.com/mobile/new"));
301 setResult(RESULT_CANCELED);
302 startActivity(register);
303 }
304
305 private void continueConnection(String prefix) {
306 String url = ((TextView) findViewById(R.id.host_URL)).getText()
307 .toString().trim();
308 String username = ((TextView) findViewById(R.id.account_username))
309 .getText().toString();
310 String password = ((TextView) findViewById(R.id.account_password))
311 .getText().toString();
312 if (url.endsWith("/"))
313 url = url.substring(0, url.length() - 1);
314
315 URL uri = null;
316 String webdav_path = AccountUtils.getWebdavPath(mConnChkRunnable
317 .getDiscoveredVersion());
318
319 if (webdav_path == null) {
320 onAuthenticationResult(false, getString(R.string.auth_bad_oc_version_title));
321 return;
322 }
323
324 try {
325 mBaseUrl = prefix + url;
326 String url_str = prefix + url + webdav_path;
327 uri = new URL(url_str);
328 } catch (MalformedURLException e) {
329 // should never happen
330 onAuthenticationResult(false, getString(R.string.auth_incorrect_address_title));
331 return;
332 }
333
334 showDialog(DIALOG_LOGIN_PROGRESS);
335 mAuthRunnable = new AuthenticationRunnable(uri, username, password, this);
336 mAuthRunnable.setOnAuthenticationResultListener(this, mHandler);
337 mAuthThread = new Thread(mAuthRunnable);
338 mAuthThread.start();
339 }
340
341 @Override
342 public void onConnectionCheckResult(ResultType type) {
343 mStatusText = mStatusIcon = 0;
344 mStatusCorrect = false;
345 String t_url = ((TextView) findViewById(R.id.host_URL)).getText()
346 .toString().trim().toLowerCase();
347
348 switch (type) {
349 case OK_SSL:
350 mIsSslConn = true;
351 mStatusIcon = android.R.drawable.ic_secure;
352 mStatusText = R.string.auth_secure_connection;
353 mStatusCorrect = true;
354 break;
355 case OK_NO_SSL:
356 mIsSslConn = false;
357 mStatusCorrect = true;
358 if (t_url.startsWith("http://") ) {
359 mStatusText = R.string.auth_connection_established;
360 mStatusIcon = R.drawable.ic_ok;
361 } else {
362 mStatusText = R.string.auth_nossl_plain_ok_title;
363 mStatusIcon = android.R.drawable.ic_partial_secure;
364 }
365 break;
366 case BAD_OC_VERSION:
367 mStatusIcon = R.drawable.common_error;
368 mStatusText = R.string.auth_bad_oc_version_title;
369 break;
370 case WRONG_CONNECTION:
371 mStatusIcon = R.drawable.common_error;
372 mStatusText = R.string.auth_wrong_connection_title;
373 break;
374 case TIMEOUT:
375 mStatusIcon = R.drawable.common_error;
376 mStatusText = R.string.auth_timeout_title;
377 break;
378 case INCORRECT_ADDRESS:
379 mStatusIcon = R.drawable.common_error;
380 mStatusText = R.string.auth_incorrect_address_title;
381 break;
382 case SSL_UNVERIFIED_SERVER:
383 mStatusIcon = R.drawable.common_error;
384 mStatusText = R.string.auth_ssl_unverified_server_title;
385 break;
386 case SSL_INIT_ERROR:
387 mStatusIcon = R.drawable.common_error;
388 mStatusText = R.string.auth_ssl_general_error_title;
389 break;
390 case HOST_NOT_AVAILABLE:
391 mStatusIcon = R.drawable.common_error;
392 mStatusText = R.string.auth_unknown_host_title;
393 break;
394 case NO_NETWORK_CONNECTION:
395 mStatusIcon = R.drawable.no_network;
396 mStatusText = R.string.auth_no_net_conn_title;
397 break;
398 case INSTANCE_NOT_CONFIGURED:
399 mStatusIcon = R.drawable.common_error;
400 mStatusText = R.string.auth_not_configured_title;
401 break;
402 case UNKNOWN_ERROR:
403 mStatusIcon = R.drawable.common_error;
404 mStatusText = R.string.auth_unknown_error_title;
405 break;
406 case FILE_NOT_FOUND:
407 mStatusIcon = R.drawable.common_error;
408 mStatusText = R.string.auth_incorrect_path_title;
409 break;
410 default:
411 Log.e(TAG, "Incorrect connection checker result type: " + type);
412 }
413 setResultIconAndText(mStatusIcon, mStatusText);
414 if (!mStatusCorrect)
415 findViewById(R.id.refreshButton).setVisibility(View.VISIBLE);
416 else
417 findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);
418 findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
419 }
420
421 @Override
422 public void onFocusChange(View view, boolean hasFocus) {
423 if (view.getId() == R.id.host_URL) {
424 if (!hasFocus) {
425 TextView tv = ((TextView) findViewById(R.id.host_URL));
426 String uri = tv.getText().toString().trim();
427 if (uri.length() != 0) {
428 setResultIconAndText(R.drawable.progress_small,
429 R.string.auth_testing_connection);
430 //mConnChkRunnable = new ConnectionCheckerRunnable(uri, this);
431 mConnChkRunnable = new ConnectionCheckOperation(uri, this);
432 //mConnChkRunnable.setListener(this, mHandler);
433 //mAuthThread = new Thread(mConnChkRunnable);
434 //mAuthThread.start();
435 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this);
436 mAuthThread = mConnChkRunnable.execute(client, this, mHandler);
437 } else {
438 findViewById(R.id.refreshButton).setVisibility(
439 View.INVISIBLE);
440 setResultIconAndText(0, 0);
441 }
442 } else {
443 // avoids that the 'connect' button can be clicked if the test was previously passed
444 findViewById(R.id.buttonOK).setEnabled(false);
445 }
446 } else if (view.getId() == R.id.account_password) {
447 ImageView iv = (ImageView) findViewById(R.id.viewPassword);
448 if (hasFocus) {
449 iv.setVisibility(View.VISIBLE);
450 } else {
451 TextView v = (TextView) findViewById(R.id.account_password);
452 int input_type = InputType.TYPE_CLASS_TEXT
453 | InputType.TYPE_TEXT_VARIATION_PASSWORD;
454 v.setInputType(input_type);
455 iv.setVisibility(View.INVISIBLE);
456 }
457 }
458 }
459
460 private void setResultIconAndText(int drawable_id, int text_id) {
461 ImageView iv = (ImageView) findViewById(R.id.action_indicator);
462 TextView tv = (TextView) findViewById(R.id.status_text);
463
464 if (drawable_id == 0 && text_id == 0) {
465 iv.setVisibility(View.INVISIBLE);
466 tv.setVisibility(View.INVISIBLE);
467 } else {
468 iv.setImageResource(drawable_id);
469 tv.setText(text_id);
470 iv.setVisibility(View.VISIBLE);
471 tv.setVisibility(View.VISIBLE);
472 }
473 }
474
475 @Override
476 public void onClick(View v) {
477 if (v.getId() == R.id.refreshButton) {
478 onFocusChange(findViewById(R.id.host_URL), false);
479 } else if (v.getId() == R.id.viewPassword) {
480 TextView view = (TextView) findViewById(R.id.account_password);
481 int input_type = InputType.TYPE_CLASS_TEXT
482 | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
483 view.setInputType(input_type);
484 }
485 }
486
487 @Override
488 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
489 if (operation.equals(mConnChkRunnable)) {
490
491 mStatusText = mStatusIcon = 0;
492 mStatusCorrect = false;
493 String t_url = ((TextView) findViewById(R.id.host_URL)).getText()
494 .toString().trim().toLowerCase();
495
496 switch (result.getCode()) {
497 case OK_SSL:
498 mIsSslConn = true;
499 mStatusIcon = android.R.drawable.ic_secure;
500 mStatusText = R.string.auth_secure_connection;
501 mStatusCorrect = true;
502 break;
503
504 case OK_NO_SSL:
505 case OK:
506 mIsSslConn = false;
507 mStatusCorrect = true;
508 if (t_url.startsWith("http://") ) {
509 mStatusText = R.string.auth_connection_established;
510 mStatusIcon = R.drawable.ic_ok;
511 } else {
512 mStatusText = R.string.auth_nossl_plain_ok_title;
513 mStatusIcon = android.R.drawable.ic_partial_secure;
514 }
515 break;
516
517
518 case BAD_OC_VERSION:
519 mStatusIcon = R.drawable.common_error;
520 mStatusText = R.string.auth_bad_oc_version_title;
521 break;
522 case WRONG_CONNECTION:
523 mStatusIcon = R.drawable.common_error;
524 mStatusText = R.string.auth_wrong_connection_title;
525 break;
526 case TIMEOUT:
527 mStatusIcon = R.drawable.common_error;
528 mStatusText = R.string.auth_timeout_title;
529 break;
530 case INCORRECT_ADDRESS:
531 mStatusIcon = R.drawable.common_error;
532 mStatusText = R.string.auth_incorrect_address_title;
533 break;
534
535 case SSL_RECOVERABLE_PEER_UNVERIFIED:
536 mStatusIcon = R.drawable.common_error;
537 mStatusText = R.string.auth_ssl_unverified_server_title;
538 mLastSslUntrustedServerResult = result;
539 showDialog(DIALOG_SSL_VALIDATOR);
540 break;
541
542 case SSL_ERROR:
543 mStatusIcon = R.drawable.common_error;
544 mStatusText = R.string.auth_ssl_general_error_title;
545 break;
546
547 case HOST_NOT_AVAILABLE:
548 mStatusIcon = R.drawable.common_error;
549 mStatusText = R.string.auth_unknown_host_title;
550 break;
551 case NO_NETWORK_CONNECTION:
552 mStatusIcon = R.drawable.no_network;
553 mStatusText = R.string.auth_no_net_conn_title;
554 break;
555 case INSTANCE_NOT_CONFIGURED:
556 mStatusIcon = R.drawable.common_error;
557 mStatusText = R.string.auth_not_configured_title;
558 break;
559 case FILE_NOT_FOUND:
560 mStatusIcon = R.drawable.common_error;
561 mStatusText = R.string.auth_incorrect_path_title;
562 break;
563 case UNHANDLED_HTTP_CODE:
564 case UNKNOWN_ERROR:
565 mStatusIcon = R.drawable.common_error;
566 mStatusText = R.string.auth_unknown_error_title;
567 break;
568 default:
569 Log.e(TAG, "Incorrect connection checker result type: " + result.getHttpCode());
570 }
571 setResultIconAndText(mStatusIcon, mStatusText);
572 if (!mStatusCorrect)
573 findViewById(R.id.refreshButton).setVisibility(View.VISIBLE);
574 else
575 findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);
576 findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
577 }
578 }
579
580
581 public void onSavedCertificate() {
582 mAuthThread = mConnChkRunnable.retry(this, mHandler);
583 }
584
585 @Override
586 public void onFailedSavingCertificate() {
587 showDialog(DIALOG_CERT_NOT_SAVED);
588 }
589
590 }